feat: drop the kettle plugin; the binary writes its own skills
The plugin and the binary shipped on two release cadences and nothing on an operator's machine ever checked that the one they installed described the other. The generated flag block existed precisely so a renamed flag could not ship with documentation recommending the old one — and then shipped one version behind the registry it came from, which is the same bug one hop downstream. So the prose moved into the binary. `internal/scaffold` embeds every document; `kettle init` and `kettle gen scaffold` write them into a project's own `.claude/`. The two cannot disagree because there is one artefact. The namespace survived the move. A project's skills are flat, so the prefix is spelled into the directory name (`kettle-issue`); a project's *commands* take their namespace from a subdirectory, so `commands/kettle/init.md` is still `/kettle:init`. Four of the six command files are thin pointers at a skill, and that is what kept ~1,600 lines of `/kettle:…` cross-references true without a rewrite. `init` and `auth` lost `disable-model-invocation: true` — being a command is that property — and `auth` now restricts `allowed-tools` so a model cannot reach `kettle auth add` at all. `gen scaffold` writes files whole rather than splicing a region. The old refusal protected somebody's hand-written prose around the block; that prose is embedded now, so there is none to protect, and preserving local edits would freeze a project's documentation at whatever version first initialized it. `--check` warns before an upgrade discards one. The plugin's `agents-sync.sh` — 141 lines of Python behind a filename that said `.sh` — became `internal/mirror` and `kettle mirror`. Same seven branches, same refusal to merge two real files that differ, now with a table test per branch and a check that a repair converges in one pass. `--hook` is the PreToolUse form and exits 0 on every path including a panic. It is opt-in per project, which is strictly narrower than the plugin hook that was on for everybody who installed it. `kettle init --interactive` walks a person through the login, the token (read with the echo off, so it lands in no history and no file), the repository, the `.claude/` tree and the mirror hook. It refuses a stdin that is not a terminal and names the flags instead: every question it asks has one, and it performs nothing itself, so an interactive run and a flag run are one code path. Two rules that used to be prose are now the binary's: init refuses a linked worktree and names the main checkout, and writing into an existing `.claude/settings.json` is refused with the snippet printed rather than reformatting a file the operator commits. The scaffold version stamp went to its own `.kettle/scaffold.yaml` rather than into `config.yaml`, because unknown keys there are a hard error and that file may be committed and read by whatever build each machine has. golang.org/x/term becomes a direct dependency; it was already in the tree indirectly, so no module was added. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
+105
-28
@@ -11,9 +11,9 @@ and therefore cannot be tested.
|
||||
|
||||
Each command is one `register(&Command{…})` in an `init()`, carrying the metadata a
|
||||
human needs — `Short`, `Long`, `Examples`, `Args`, `Group` — **in the same struct
|
||||
that carries the code**. That is what lets the plugin's SKILL.md files be generated
|
||||
from this list: a command whose flags changed cannot ship with documentation that
|
||||
says otherwise.
|
||||
that carries the code**. That is what lets a project's skills be generated from
|
||||
this list: a command whose flags changed cannot ship with documentation that says
|
||||
otherwise.
|
||||
|
||||
```go
|
||||
func init() {
|
||||
@@ -47,20 +47,34 @@ token of every invocation, and the grouping that matters for reading is carried
|
||||
| `command.go` | `Command`, the registry, `Main`, help rendering, `SilentError`, `Fail`, and `permute` |
|
||||
| `flags.go` | `storeFlag`/`storeRoot`, `wasSet`, the repeatable `stringList` |
|
||||
| `sync.go` | `syncStart`/`syncStartExisting`, `commentsSidecarPath` — the shared opening of every tracker command |
|
||||
| `gen.go` | `kettle gen skills`: the generated region in the plugin's SKILL.md files |
|
||||
| `init.go` `auth.go` `config.go` `version.go` | group `project`. `version.go` also holds `Version`, the string a release build stamps in with `-ldflags -X` |
|
||||
| `gen.go` | `kettle gen scaffold`: rendering [`scaffold`](../scaffold/AGENTS.md)'s documents with the registry's flag tables spliced in |
|
||||
| `init.go` `auth.go` `config.go` `version.go` `mirror.go` | group `project`. `version.go` also holds `Version`, the string a release build stamps in with `-ldflags -X` |
|
||||
| `interactive.go` | `kettle init --interactive`: the only thing here that reads a terminal |
|
||||
| `settings.go` | registering `kettle mirror --hook` in `.claude/settings.json`, and refusing to reformat one it did not write |
|
||||
| `new.go` `check.go` `ac.go` `tree.go` `index.go` `evict.go` | group `issue` — no network in any of them |
|
||||
| `pull.go` `push.go` `remote.go` `comment.go` `close.go` `labels.go` `evict_sync.go` | group `sync` |
|
||||
| `api.go` | group `api`, alone in it: one request to an endpoint nothing here wraps |
|
||||
| `cli_test.go` | builds the binary in `TestMain`, runs it as a subprocess |
|
||||
| `sync_pull_test.go` `sync_write_test.go` `api_test.go` | the tracker halves, against fake servers |
|
||||
| `gen_test.go` | the generator: determinism, the region splice, the missing-marker refusal |
|
||||
| `gen_test.go` | the generator: the whole tree, determinism, and that a local edit does not survive |
|
||||
| `mirror_test.go` | the repair command, and the hook form's promise never to fail a Bash call |
|
||||
| `init_scaffold_test.go` | the `.claude/` tree, the settings refusal, the worktree refusal, the not-a-terminal refusal |
|
||||
| `scaffold_coverage_test.go` | the registry ⇄ documents seam, in the one package that can see both |
|
||||
|
||||
The fourth group is one command and was still worth naming, because a group is a
|
||||
skill directory over in the plugin: `api` is a subject somebody loads on its own —
|
||||
skill written into a project: `api` is a subject somebody loads on its own —
|
||||
which endpoint, and does it paginate — and folding it into `sync` would have put
|
||||
"how do I cut a release" behind a skill about the issue round trip.
|
||||
|
||||
**`mirror` is the one command in the tree that has nothing to do with issues**,
|
||||
and it is here rather than in a second binary for the reason this repository
|
||||
keeps repeating to itself: a binary holds what can be enforced. Repairing an
|
||||
`AGENTS.md`/`CLAUDE.md` pair is a seven-branch filesystem decision with one
|
||||
refusal in it, which is a thing a table test can hold down and a shell script
|
||||
cannot. It was 141 lines of Python behind a filename that said `.sh`, shipped in
|
||||
the plugin's hooks; when the plugin went, the shell had nowhere to live and Go
|
||||
did. The domain is untouched: [`mirror`](../mirror/AGENTS.md) imports nothing.
|
||||
|
||||
## Three conventions every command follows
|
||||
|
||||
**Flags may come after positionals.** The standard `flag` package stops parsing at
|
||||
@@ -114,7 +128,9 @@ because that is what the operator asked for.
|
||||
kettle help # the tree, grouped
|
||||
kettle help push # one command in full: flags, defaults, examples
|
||||
|
||||
kettle init --interactive # a person at a terminal, walked through it
|
||||
kettle init --login noodles --repo owner/name
|
||||
kettle mirror --check # AGENTS.md ⇄ CLAUDE.md, everywhere below here
|
||||
kettle new --type task --title "Wire sqlc into the appclick repo layer"
|
||||
kettle ac wire-sqlc-appclick --check 3
|
||||
kettle check --strict # exit 1 on any error; --strict counts warnings too
|
||||
@@ -125,9 +141,59 @@ kettle sync-evict --dry-run
|
||||
```
|
||||
|
||||
Every command's own `Long` text is the reference — it is what
|
||||
`kettle help <name>` prints and what the generator writes into the plugin. **Do not
|
||||
restate a flag table here**; it would be a third copy of something already in two
|
||||
places, one of them mechanically checked.
|
||||
`kettle help <name>` prints and what the generator splices into
|
||||
[`scaffold`](../scaffold/AGENTS.md)'s documents. **Do not restate a flag table
|
||||
here**; it would be a third copy of something already in two places, one of them
|
||||
mechanically checked.
|
||||
|
||||
## `--interactive`, and the two things it may never become
|
||||
|
||||
`interactive.go` is the only code in this binary that reads a terminal. Two rules
|
||||
hold it in place, and both are about what it must not turn into.
|
||||
|
||||
**It answers no question the flags cannot answer.** Every prompt has a field in
|
||||
`initOptions` and therefore a flag — `--login`, `--repo`, `--scaffold-out`,
|
||||
`--no-scaffold`, `--mirror-hook`. A capability reachable only by answering a
|
||||
prompt would be a capability no script, no CI run and no agent could ever use.
|
||||
|
||||
**It performs nothing.** It fills the struct in and hands it back, so `runInit`
|
||||
is one code path: the run that follows an interactive session is byte for byte
|
||||
the run somebody else gets from flags.
|
||||
|
||||
It **refuses a standard input that is not a terminal**, and that refusal is load
|
||||
bearing rather than fussy. A model that reached for `--interactive` would
|
||||
otherwise block forever on a prompt nobody is going to answer; the error names
|
||||
the flags instead. It is also what makes the one genuinely better thing here
|
||||
possible — `term.ReadPassword` puts a token in no history, no file and no
|
||||
scrollback, which every other route into this binary can only approximate.
|
||||
|
||||
`--repo` is offered with a guess read out of `.git/config`, parsed rather than
|
||||
shelled out to. `git` is one more thing that has to be installed and one more
|
||||
process to misread; a guess is worth what it costs, and anything unparseable is
|
||||
no guess at all.
|
||||
|
||||
## Writing into `.claude/settings.json`
|
||||
|
||||
`settings.go` registers `kettle mirror --hook` on `PreToolUse(Bash)`, and is the
|
||||
only place this binary touches a file the operator owns and commits. It has three
|
||||
outcomes and the third is the whole reason it is not ten lines long:
|
||||
|
||||
- **no file** — written, hook and all;
|
||||
- **a file already holding a `kettle mirror` hook** — nothing happens;
|
||||
- **a file holding something else** — **refused**, with the snippet printed to
|
||||
paste, unless `--force-settings`.
|
||||
|
||||
Go's `encoding/json` cannot preserve key order, so any merge reformats the whole
|
||||
document. An operator who asked for a documentation hook and got an unrelated
|
||||
diff across a file they share with their team has been badly served; a snippet
|
||||
they paste costs them ten seconds. The refusal is reported on stderr and the run
|
||||
still **succeeds** — everything before it already happened, and reporting a
|
||||
failure would send somebody looking for damage there is none of.
|
||||
|
||||
The registered command carries a `command -v kettle` guard. That line outlives
|
||||
this binary: an operator who uninstalls `kettle` would otherwise get
|
||||
`command not found` on every Bash call, from a hook they set up months ago and
|
||||
have long stopped thinking about.
|
||||
|
||||
## push and pull, the two halves of one rule
|
||||
|
||||
@@ -173,30 +239,40 @@ the body** — it is a fetch, not a merge — with checkbox state the one except
|
||||
|
||||
## The generator
|
||||
|
||||
`gen.go` writes the plugin's SKILL.md command reference from this registry.
|
||||
`gen.go` writes a project's `.claude/` tree: [`scaffold`](../scaffold/AGENTS.md)'s
|
||||
embedded documents, with this registry's flag tables spliced into the four that
|
||||
declare a region.
|
||||
|
||||
**It owns a region, not a file.** Everything between `<!-- kettle:gen -->` and
|
||||
`<!-- /kettle:gen -->` is replaced on every run; every byte outside comes back
|
||||
exactly as it was, which matters most for `description:`, the prose that decides
|
||||
whether an agent loads the skill at all and the one thing here no generator can
|
||||
write. A file with **no** markers is reported and left alone, never overwritten —
|
||||
clobbering somebody's prose because they forgot a marker is the failure this design
|
||||
exists to prevent.
|
||||
**It writes every file whole, and that is a deliberate reversal.** The old
|
||||
generator owned a region and left every byte outside it alone, because the prose
|
||||
around the block was somebody's hand-written file in this repository. It is not
|
||||
any more — it is embedded — so there is no hand-written half left to protect, and
|
||||
preserving local edits would freeze a project's documentation at whatever version
|
||||
first initialized it. The markers stay in the output so a reader can still see
|
||||
which half came from the registry.
|
||||
|
||||
The principle the old refusal protected did not go away; it moved. **Nobody's
|
||||
prose is clobbered because nobody's prose is there** — it lives in `assets/`, next
|
||||
to the code it describes, and `--check` warns before an upgrade replaces a local
|
||||
edit.
|
||||
|
||||
The output is deterministic to the byte — no timestamps, no map iteration — so
|
||||
regenerating something unchanged produces no diff. `--check` is that property made
|
||||
useful: it writes nothing and exits 1 when anything on disk differs, which is what a
|
||||
pre-commit hook or a CI step calls, and it wins over `--dry-run`.
|
||||
useful: it writes nothing and exits 1 when anything on disk differs, which is what
|
||||
a pre-commit hook or a CI step calls, and it wins over `--dry-run`.
|
||||
|
||||
One file per **group**, so adding a group here adds a skill directory over there;
|
||||
name one only when it is a subject somebody would load on its own. `api` was
|
||||
added exactly that way, and the first `gen skills` run after it wrote a stub whose
|
||||
`description:` said TODO — a stub is not shippable, and filling that line in by
|
||||
hand is the last step of adding a group, not an optional one. A command with no
|
||||
`Group` is in no skill and the run says so. A `Long` or `Example` that spells a
|
||||
region marker out in full is a hard error — the generated block would end inside
|
||||
One document per **group**, so adding a group here means adding one under
|
||||
`internal/scaffold/assets`; name a group only when it is a subject somebody would
|
||||
load on its own. `TestEveryGroupHasSomewhereToBeWritten` is what makes that a
|
||||
two-step change rather than a silent one-step mistake — the generator walks the
|
||||
documents, not the registry, so a group with no document would have its commands
|
||||
written nowhere and nothing would say so. A `Long` or `Example` that spells a
|
||||
region marker out in full is a hard error: the generated block would end inside
|
||||
itself.
|
||||
|
||||
`--out` defaults to `<project>/.claude`, resolved by the same walk everything else
|
||||
uses, and no marker is an answer rather than a fallback.
|
||||
|
||||
## Keeping this file true
|
||||
|
||||
- **Scope:** the shape of the command tree — the registry, the shared helpers, the
|
||||
@@ -204,7 +280,8 @@ itself.
|
||||
source file in this directory.
|
||||
- **Update it when** a command file is added or removed, a group is added, a shared
|
||||
helper in `flags.go`/`sync.go` changes, an exit code gains a meaning, a command
|
||||
gains a confirmation gate, or the push/pull ordering guarantees change.
|
||||
gains a confirmation gate, the push/pull ordering guarantees change, or the rules
|
||||
around writing into `.claude/` change.
|
||||
- **Do not** copy a flag list or a command's `Long` text here. `kettle help <name>`
|
||||
and the generated SKILL.md blocks are the two places that exist for it, and a
|
||||
third would be the one that drifts.
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
//
|
||||
// Commands are values, not init() side effects on a framework: each one carries
|
||||
// the metadata a human needs (what it does, what it takes, worked examples) in
|
||||
// the same struct that carries the code. That is deliberate — the plugin's
|
||||
// SKILL.md files are generated from this list, so a command whose flags changed
|
||||
// cannot ship with documentation that says otherwise.
|
||||
// the same struct that carries the code. That is deliberate — the skills kettle
|
||||
// writes into a project are generated from this list, so a command whose flags
|
||||
// changed cannot ship with documentation that says otherwise.
|
||||
//
|
||||
// The tree is flat. `kettle new`, not `kettle issue new`: an agent pays for
|
||||
// every token of every invocation, and the grouping that matters for reading is
|
||||
|
||||
@@ -37,6 +37,7 @@ This is the command to reach for when the store looks empty, when a push says
|
||||
fmt.Printf("payload %s\n", project.PayloadRoot(""))
|
||||
fmt.Printf("config %s\n", config.ProjectPath(""))
|
||||
fmt.Printf("logins %s\n", config.LoginsPath())
|
||||
printScaffold()
|
||||
|
||||
r, err := config.Resolve("")
|
||||
if err != nil {
|
||||
@@ -66,3 +67,30 @@ This is the command to reach for when the store looks empty, when a push says
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// printScaffold says where the agent-harness tree went and whether the build
|
||||
// that wrote it is the build that is running now.
|
||||
//
|
||||
// The mismatch is worth a line because these documents are generated whole:
|
||||
// there is nothing inside one that tells an operator how old it is, and a skill
|
||||
// four releases behind describes flags that have since been renamed. It is a
|
||||
// note, never a failure — `kettle gen scaffold` is the fix and the operator
|
||||
// decides when to run it.
|
||||
func printScaffold() {
|
||||
rec, existed, err := config.ReadScaffoldFile(config.ScaffoldPath(""))
|
||||
if err != nil || !existed {
|
||||
fmt.Printf("scaffold (none written — `kettle gen scaffold`)\n")
|
||||
return
|
||||
}
|
||||
out := rec.Out
|
||||
if out == "" {
|
||||
out = "(unrecorded)"
|
||||
}
|
||||
switch {
|
||||
case rec.Version == Version:
|
||||
fmt.Printf("scaffold %s (kettle %s)\n", out, rec.Version)
|
||||
default:
|
||||
fmt.Printf("scaffold %s (written by kettle %s; this is %s — run `kettle gen scaffold`)\n",
|
||||
out, rec.Version, Version)
|
||||
}
|
||||
}
|
||||
|
||||
+144
-125
@@ -9,21 +9,24 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.noodles.cam/claude-skills/marketplace/cli/internal/project"
|
||||
"git.noodles.cam/claude-skills/marketplace/cli/internal/scaffold"
|
||||
)
|
||||
|
||||
// The region markers. What sits between them belongs to the generator; the
|
||||
// rest of the file belongs to whoever wrote it.
|
||||
// The region markers. What sits between them comes from the registry; the rest
|
||||
// of the document is the embedded prose around it.
|
||||
const (
|
||||
genOpen = "<!-- kettle:gen -->"
|
||||
genClose = "<!-- /kettle:gen -->"
|
||||
)
|
||||
|
||||
// genBanner opens every generated region. The first thing anybody who finds
|
||||
// the block wants to do is edit it in place, so the block says who wrote it and
|
||||
// genBanner opens every generated region. The first thing anybody who finds the
|
||||
// block wants to do is edit it in place, so the block says who wrote it and
|
||||
// which command writes it again.
|
||||
const genBanner = "**Generated from the kettle command registry by `kettle gen skills`.** " +
|
||||
const genBanner = "**Generated from the kettle command registry by `kettle gen scaffold`.** " +
|
||||
"Everything between the two markers is replaced on the next run — " +
|
||||
"hand-written prose belongs outside them."
|
||||
"the prose around it is embedded in the binary and replaced with it."
|
||||
|
||||
// exampleAlign is the widest example command that still gets its `# what`
|
||||
// padded into a column. One long pipeline would otherwise push every other
|
||||
@@ -34,176 +37,199 @@ func init() {
|
||||
register(&Command{
|
||||
Name: "gen",
|
||||
Group: GroupProject,
|
||||
Args: "skills",
|
||||
Short: "write the plugin's SKILL.md files from the command registry",
|
||||
Long: `A SKILL.md tells an agent how to invoke this binary. Hand-written, it drifts: a
|
||||
flag is renamed here and the documentation goes on recommending the old one,
|
||||
and the agent that reads it fails in a way nobody traces back to a stale
|
||||
sentence. Everything those files say about a command — its usage line, its
|
||||
flags with their defaults, its worked examples — is already in the registry
|
||||
this binary is built from, so it is written from there and cannot disagree.
|
||||
Args: "scaffold",
|
||||
Short: "write this project's .claude/ commands, skills and subagent",
|
||||
Long: `A skill tells an agent how to invoke this binary, and a command is how an
|
||||
operator invokes one by hand. Both are written from here, whole, because both
|
||||
travel INSIDE the binary: the prose is embedded next to the code it describes
|
||||
and the flag tables are rendered from the command registry the binary is built
|
||||
from, so neither can be a version behind the other.
|
||||
|
||||
THE GENERATOR OWNS A REGION, NOT A FILE. Each SKILL.md carries a pair of HTML
|
||||
comment markers — ` + "`kettle:gen`" + ` to open and ` + "`/kettle:gen`" + ` to close, both written in
|
||||
the ` + "`<!-- … -->`" + ` form and visible at the top and bottom of the block below.
|
||||
Everything between them is replaced on every run; every byte outside them comes
|
||||
back exactly as it was, which matters most for ` + "`description:`" + `, the prose that
|
||||
decides whether an agent loads the skill at all, and the one thing here that no
|
||||
generator can write.
|
||||
That is the whole reason these documents are not a plugin any more. A plugin
|
||||
ships on its own cadence, and nothing on an operator's machine ever checked that
|
||||
the one they installed described the binary they installed — so a renamed flag
|
||||
could still arrive with documentation recommending the old one, which is exactly
|
||||
the failure the generated block was invented to prevent, one hop further
|
||||
downstream.
|
||||
|
||||
A file with no markers is REPORTED AND LEFT ALONE, never overwritten: clobbering
|
||||
somebody's prose because they forgot a marker is the failure this design exists
|
||||
to prevent. A file that does not exist yet is created with a frontmatter stub
|
||||
around a generated block, for a human to fill in.
|
||||
EVERY FILE IS WRITTEN WHOLE, and that is a deliberate reversal. The old
|
||||
generator owned a region and left every byte outside it alone, because the prose
|
||||
around the block was somebody's hand-written file. It is not any more: it is
|
||||
embedded, so there is no hand-written half left to protect, and preserving local
|
||||
edits would mean freezing a project's documentation at whatever version first
|
||||
initialized it. The markers stay in the output so a reader can see which half
|
||||
came from the registry.
|
||||
|
||||
WHAT THIS MEANS FOR A LOCAL EDIT: it does not survive. Run --check before an
|
||||
upgrade if you have made one; the fix for a sentence that is wrong is a newer
|
||||
kettle, not a patch that the next run silently discards.
|
||||
|
||||
The output is deterministic to the byte — no timestamps, no map iteration — so
|
||||
regenerating something that has not changed produces no diff. --check is that
|
||||
property made useful: it writes nothing and exits 1 when any file on disk
|
||||
differs from what would be generated, which is what a pre-commit hook or a CI
|
||||
step calls. It wins over --dry-run when both are given.`,
|
||||
differs from what would be written, which is what a pre-commit hook or a CI step
|
||||
calls. It wins over --dry-run when both are given.`,
|
||||
Examples: []Example{
|
||||
{"kettle gen skills --out ../plugins/kettle/skills", "write the region in every group's SKILL.md"},
|
||||
{"kettle gen skills --out ../plugins/kettle/skills --dry-run", "print what would change; write nothing"},
|
||||
{"kettle gen skills --out ../plugins/kettle/skills --check", "exit 1 if the docs are out of date"},
|
||||
{"kettle gen scaffold", "write .claude/ under this project"},
|
||||
{"kettle gen scaffold --out ~/code/x/.claude", "write it somewhere else"},
|
||||
{"kettle gen scaffold --dry-run", "print what would change; write nothing"},
|
||||
{"kettle gen scaffold --check", "exit 1 if the documents are out of date"},
|
||||
},
|
||||
Setup: func(fs *flag.FlagSet) func([]string) error {
|
||||
out := fs.String("out", "", "directory the skills live in; one <group>/SKILL.md under it")
|
||||
out := fs.String("out", "", "directory to write into (default: <project>/"+scaffold.Marker+")")
|
||||
dryRun := fs.Bool("dry-run", false, "print what would change; write nothing")
|
||||
check := fs.Bool("check", false, "write nothing, exit 1 if anything is out of date")
|
||||
|
||||
return func(args []string) error {
|
||||
target := "skills"
|
||||
target := "scaffold"
|
||||
if len(args) > 0 {
|
||||
target = args[0]
|
||||
}
|
||||
if len(args) > 1 || target != "skills" {
|
||||
return Fail("the only target is `skills` — try `kettle gen skills --out <dir>`")
|
||||
if len(args) > 1 || target != "scaffold" {
|
||||
return Fail("the only target is `scaffold` — try `kettle gen scaffold`")
|
||||
}
|
||||
if *out == "" {
|
||||
return Fail("--out is required — the directory the SKILL.md files live under")
|
||||
dir, err := scaffoldDir(*out)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return genSkills(*out, *dryRun, *check)
|
||||
return genScaffold(dir, *dryRun, *check)
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// errNoRegion is what a file that the generator may not touch reports.
|
||||
var errNoRegion = errors.New("no " + genOpen + " … " + genClose + " region")
|
||||
// scaffoldDir resolves where the tree goes.
|
||||
//
|
||||
// An explicit --out is used exactly as typed, relative and all, because that is
|
||||
// what the operator asked for. Without one the answer comes from the marker, the
|
||||
// same walk every other command uses — and no marker is an answer rather than a
|
||||
// fallback, because a `.claude/` written into a plausible-looking directory is
|
||||
// the failure the marker exists to replace.
|
||||
func scaffoldDir(out string) (string, error) {
|
||||
if out != "" {
|
||||
return out, nil
|
||||
}
|
||||
root := project.Root("")
|
||||
if root == "" {
|
||||
return "", project.NotFoundError("")
|
||||
}
|
||||
return filepath.Join(root, scaffold.Marker), nil
|
||||
}
|
||||
|
||||
func genSkills(dir string, dryRun, check bool) error {
|
||||
func genScaffold(dir string, dryRun, check bool) error {
|
||||
// --check is a read-only question about the working tree, so it overrules
|
||||
// --dry-run rather than combining with it.
|
||||
if check {
|
||||
dryRun = true
|
||||
}
|
||||
|
||||
groups := docGroups()
|
||||
var written, unchanged, outdated, kept int
|
||||
for _, group := range groups {
|
||||
path := filepath.Join(dir, group, "SKILL.md")
|
||||
block, err := renderGroup(commandsIn(group))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
files, err := renderAll()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var written, unchanged, outdated int
|
||||
for _, f := range files {
|
||||
path := filepath.Join(dir, filepath.FromSlash(f.Path))
|
||||
existing, err := os.ReadFile(path)
|
||||
switch {
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
outdated++
|
||||
if check {
|
||||
fmt.Printf("%-13s %s\n", "missing", path)
|
||||
continue
|
||||
}
|
||||
if dryRun {
|
||||
fmt.Printf("%-13s %s\n", "would create", path)
|
||||
continue
|
||||
}
|
||||
if err := writeFile(path, stubFile(group, block)); err != nil {
|
||||
if err := report(path, "missing", "would create", "created", dryRun, check, func() error {
|
||||
return writeFile(path, f.Body)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
written++
|
||||
fmt.Printf("%-13s %s\n", "created", path)
|
||||
if !dryRun {
|
||||
written++
|
||||
}
|
||||
|
||||
case err != nil:
|
||||
return err
|
||||
|
||||
case string(existing) == f.Body:
|
||||
unchanged++
|
||||
fmt.Printf("%-13s %s\n", "unchanged", path)
|
||||
|
||||
default:
|
||||
want, err := spliceRegion(string(existing), block)
|
||||
if err != nil {
|
||||
// Reported, never repaired: a missing marker is somebody's
|
||||
// prose sitting where the block used to be.
|
||||
kept++
|
||||
fmt.Fprintf(os.Stderr, "kettle gen: %s left alone — %v\n", path, err)
|
||||
continue
|
||||
}
|
||||
if want == string(existing) {
|
||||
unchanged++
|
||||
fmt.Printf("%-13s %s\n", "unchanged", path)
|
||||
continue
|
||||
}
|
||||
outdated++
|
||||
if check {
|
||||
fmt.Printf("%-13s %s\n", "stale", path)
|
||||
continue
|
||||
}
|
||||
if dryRun {
|
||||
fmt.Printf("%-13s %s\n", "would update", path)
|
||||
continue
|
||||
}
|
||||
if err := writeFile(path, want); err != nil {
|
||||
if err := report(path, "stale", "would update", "updated", dryRun, check, func() error {
|
||||
return writeFile(path, f.Body)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
written++
|
||||
fmt.Printf("%-13s %s\n", "updated", path)
|
||||
if !dryRun {
|
||||
written++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
switch {
|
||||
case check:
|
||||
fmt.Printf("%d file(s) checked, %d out of date, %d without a region\n",
|
||||
len(groups), outdated, kept)
|
||||
fmt.Printf("%d file(s) checked, %d out of date\n", len(files), outdated)
|
||||
if outdated > 0 {
|
||||
fmt.Printf("run `kettle gen skills --out %s`\n", dir)
|
||||
fmt.Printf("run `kettle gen scaffold --out %s`\n", dir)
|
||||
return SilentError{Code: 1}
|
||||
}
|
||||
case dryRun:
|
||||
fmt.Printf("%d file(s) would change, %d unchanged, %d without a region — nothing was written\n",
|
||||
outdated, unchanged, kept)
|
||||
fmt.Printf("%d file(s) would change, %d unchanged — nothing was written\n", outdated, unchanged)
|
||||
default:
|
||||
fmt.Printf("%d file(s) written, %d unchanged, %d without a region\n", written, unchanged, kept)
|
||||
fmt.Printf("%d file(s) written, %d unchanged\n", written, unchanged)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// docGroups lists the groups that have commands, in the order Commands()
|
||||
// returns them — the same order twice, so two runs cannot differ.
|
||||
func docGroups() []string {
|
||||
var out []string
|
||||
seen := map[string]bool{}
|
||||
for _, c := range Commands() {
|
||||
if c.Group == "" {
|
||||
fmt.Fprintf(os.Stderr, "kettle gen: command %q has no group and is in no skill\n", c.Name)
|
||||
continue
|
||||
}
|
||||
if !seen[c.Group] {
|
||||
seen[c.Group] = true
|
||||
out = append(out, c.Group)
|
||||
// report prints one line for one file and performs the write unless this run is
|
||||
// only answering a question.
|
||||
func report(path, checkWord, dryWord, doneWord string, dryRun, check bool, write func() error) error {
|
||||
switch {
|
||||
case check:
|
||||
fmt.Printf("%-13s %s\n", checkWord, path)
|
||||
case dryRun:
|
||||
fmt.Printf("%-13s %s\n", dryWord, path)
|
||||
default:
|
||||
if err := write(); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("%-13s %s\n", doneWord, path)
|
||||
}
|
||||
return out
|
||||
return nil
|
||||
}
|
||||
|
||||
func commandsIn(group string) []*Command {
|
||||
var out []*Command
|
||||
for _, c := range Commands() {
|
||||
if c.Group == group {
|
||||
out = append(out, c)
|
||||
// renderAll is every embedded document with its generated region filled in.
|
||||
//
|
||||
// Nothing here touches the disk: the result is what the tree SHOULD be, and
|
||||
// comparing it against what is there is a separate question asked by the caller.
|
||||
// That split is what lets --check be exact rather than a heuristic about
|
||||
// timestamps.
|
||||
func renderAll() ([]scaffold.File, error) {
|
||||
files := scaffold.Files()
|
||||
out := make([]scaffold.File, 0, len(files))
|
||||
for _, f := range files {
|
||||
if f.Group == "" {
|
||||
out = append(out, f)
|
||||
continue
|
||||
}
|
||||
block, err := renderGroup(commandsIn(f.Group))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body, err := spliceRegion(f.Body, block)
|
||||
if err != nil {
|
||||
// The embedded document is shipped inside this binary, so a missing
|
||||
// marker is a build-time mistake in this repository and not
|
||||
// something an operator can have caused.
|
||||
return nil, Fail("%s: %v — this is a bug in the embedded document, not in your project", f.Path, err)
|
||||
}
|
||||
f.Body = body
|
||||
out = append(out, f)
|
||||
}
|
||||
return out
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// errNoRegion is what a document that declares a region and has none reports.
|
||||
var errNoRegion = errors.New("no " + genOpen + " … " + genClose + " region")
|
||||
|
||||
// renderGroup is the generated block for one group, without the markers and
|
||||
// without a trailing newline.
|
||||
func renderGroup(cmds []*Command) (string, error) {
|
||||
@@ -295,23 +321,16 @@ func spliceRegion(existing, block string) (string, error) {
|
||||
return existing[:start] + region(block) + existing[rest+end+len(genClose):], nil
|
||||
}
|
||||
|
||||
// stubFile is a new SKILL.md: the least frontmatter that is still a skill,
|
||||
// and the region.
|
||||
//
|
||||
// The description is left as a TODO on purpose. It is the sentence that decides
|
||||
// whether an agent loads this skill at all — prose a human tunes against real
|
||||
// failures to trigger, and the one thing here a generator has no way to write.
|
||||
func stubFile(group, block string) string {
|
||||
title := "# kettle " + group + "\n"
|
||||
if blurb := groupBlurb[group]; blurb != "" {
|
||||
title += "\n" + blurb + "\n"
|
||||
// commandsIn lists a group's commands in the order Commands() returns them —
|
||||
// the same order twice, so two runs cannot differ.
|
||||
func commandsIn(group string) []*Command {
|
||||
var out []*Command
|
||||
for _, c := range Commands() {
|
||||
if c.Group == group {
|
||||
out = append(out, c)
|
||||
}
|
||||
}
|
||||
return "---\n" +
|
||||
"name: " + group + "\n" +
|
||||
"description: TODO — write this by hand. It is the only thing that decides whether an agent loads this skill at all, so it is prose a human tunes; kettle gen never reads or writes it.\n" +
|
||||
"---\n\n" +
|
||||
title + "\n" +
|
||||
region(block) + "\n"
|
||||
return out
|
||||
}
|
||||
|
||||
func writeFile(path, content string) error {
|
||||
|
||||
+118
-114
@@ -1,9 +1,9 @@
|
||||
package cmd_test
|
||||
|
||||
// `kettle gen` writes documentation an agent reads to invoke this binary, into
|
||||
// files a human also writes prose in. Both halves of that are tested here: what
|
||||
// it produces has to be the same twice over, and what it does NOT own has to
|
||||
// come back byte for byte.
|
||||
// `kettle gen scaffold` writes the documents an operator invokes and a model
|
||||
// loads. They are embedded in the binary, so this file tests the two properties
|
||||
// that follow from that: what it produces is the same twice over, and it is the
|
||||
// binary's answer rather than whatever happens to be on disk.
|
||||
|
||||
import (
|
||||
"os"
|
||||
@@ -17,39 +17,66 @@ const (
|
||||
genClose = "<!-- /kettle:gen -->"
|
||||
)
|
||||
|
||||
func TestGenWritesOneFilePerGroupAndIsIdempotent(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
out := filepath.Join(dir, "skills")
|
||||
// everything the tree is made of. Named here rather than derived, because a file
|
||||
// that silently stopped being written is exactly the failure this catches.
|
||||
var scaffoldFiles = []string{
|
||||
"agents/kettle-runner.md",
|
||||
"commands/kettle/api.md",
|
||||
"commands/kettle/auth.md",
|
||||
"commands/kettle/init.md",
|
||||
"commands/kettle/issue.md",
|
||||
"commands/kettle/project.md",
|
||||
"commands/kettle/sync.md",
|
||||
"skills/kettle-api/SKILL.md",
|
||||
"skills/kettle-issue/SKILL.md",
|
||||
"skills/kettle-issue/references/format.md",
|
||||
"skills/kettle-project/SKILL.md",
|
||||
"skills/kettle-sync/SKILL.md",
|
||||
}
|
||||
|
||||
first := mustRun(t, dir, "gen", "skills", "--out", out)
|
||||
for _, group := range []string{"project", "issue", "sync"} {
|
||||
path := filepath.Join(out, group, "SKILL.md")
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("%s was not created: %v\n%s", path, err, first.out())
|
||||
func TestGenWritesTheWholeTreeAndIsIdempotent(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
out := filepath.Join(dir, "out")
|
||||
|
||||
first := mustRun(t, dir, "gen", "scaffold", "--out", out)
|
||||
for _, rel := range scaffoldFiles {
|
||||
path := filepath.Join(out, filepath.FromSlash(rel))
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
t.Fatalf("%s was not created: %v\n%s", rel, err, first.out())
|
||||
}
|
||||
body := string(raw)
|
||||
// The frontmatter is what makes it a skill at all, and the description
|
||||
// is prose a human tunes — the stub says so and generates nothing.
|
||||
if !strings.HasPrefix(body, "---\nname: "+group+"\n") {
|
||||
t.Errorf("%s has no frontmatter naming the group:\n%s", path, firstLines(body, 5))
|
||||
}
|
||||
|
||||
// The four skills that carry a flag table carry the markers around it, so a
|
||||
// reader can see which half came from the registry.
|
||||
for _, group := range []string{"project", "issue", "sync", "api"} {
|
||||
path := filepath.Join(out, "skills", "kettle-"+group, "SKILL.md")
|
||||
body := readFile(t, path)
|
||||
if !strings.HasPrefix(body, "---\nname: kettle-"+group+"\n") {
|
||||
t.Errorf("%s does not name itself after its directory:\n%s", path, firstLines(body, 4))
|
||||
}
|
||||
if !strings.Contains(body, genOpen) || !strings.Contains(body, genClose) {
|
||||
t.Errorf("%s was created without the region markers:\n%s", path, body)
|
||||
t.Errorf("%s has no region markers", path)
|
||||
}
|
||||
// The block has to say what wrote it: the first thing anybody who finds
|
||||
// it will want to do is edit it in place.
|
||||
if !strings.Contains(body, "kettle gen skills") {
|
||||
t.Errorf("%s does not name the command that regenerates it:\n%s", path, body)
|
||||
if !strings.Contains(body, "kettle gen scaffold") {
|
||||
t.Errorf("%s does not name the command that regenerates it", path)
|
||||
}
|
||||
}
|
||||
|
||||
// A command is invoked by a person who typed it, and takes its name from its
|
||||
// filename — a `name:` here would be a second spelling free to drift.
|
||||
initBody := readFile(t, filepath.Join(out, "commands", "kettle", "init.md"))
|
||||
if strings.Contains(firstLines(initBody, 6), "\nname:") {
|
||||
t.Errorf("the init command carries a name: of its own:\n%s", firstLines(initBody, 6))
|
||||
}
|
||||
if !strings.Contains(initBody, "description:") {
|
||||
t.Errorf("the init command has no description for the command list:\n%s", firstLines(initBody, 6))
|
||||
}
|
||||
|
||||
// One command's documentation, end to end: usage line, short, a flag out of
|
||||
// the flag set, and a worked example with its explanation beside it.
|
||||
issues, err := os.ReadFile(filepath.Join(out, "issue", "SKILL.md"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
issues := readFile(t, filepath.Join(out, "skills", "kettle-issue", "SKILL.md"))
|
||||
for _, want := range []string{
|
||||
"## `kettle evict [<id>…]`",
|
||||
"remove closed issues from the local store",
|
||||
@@ -57,8 +84,8 @@ func TestGenWritesOneFilePerGroupAndIsIdempotent(t *testing.T) {
|
||||
"kettle evict --dry-run",
|
||||
"# print what would go; touch nothing",
|
||||
} {
|
||||
if !strings.Contains(string(issues), want) {
|
||||
t.Errorf("the issue group is missing %q:\n%s", want, issues)
|
||||
if !strings.Contains(issues, want) {
|
||||
t.Errorf("the issue skill is missing %q", want)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,7 +93,7 @@ func TestGenWritesOneFilePerGroupAndIsIdempotent(t *testing.T) {
|
||||
// changed must produce no diff at all, or every run of a CI step is a
|
||||
// spurious one.
|
||||
before := readAll(t, out)
|
||||
second := mustRun(t, dir, "gen", "skills", "--out", out)
|
||||
second := mustRun(t, dir, "gen", "scaffold", "--out", out)
|
||||
if strings.Contains(second.stdout, "updated") {
|
||||
t.Errorf("a second run rewrote a file:\n%s", second.out())
|
||||
}
|
||||
@@ -76,105 +103,56 @@ func TestGenWritesOneFilePerGroupAndIsIdempotent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
if r := run(t, dir, "gen", "skills", "--out", out, "--check"); r.code != 0 {
|
||||
if r := run(t, dir, "gen", "scaffold", "--out", out, "--check"); r.code != 0 {
|
||||
t.Errorf("--check exited %d on files that were just written:\n%s", r.code, r.out())
|
||||
}
|
||||
}
|
||||
|
||||
// The generator owns a region, not a file. Everything outside the markers is
|
||||
// somebody's prose and comes back exactly as it was.
|
||||
func TestGenLeavesHandWrittenProseAlone(t *testing.T) {
|
||||
// The reversal, and the one behaviour worth stating out loud: these files are
|
||||
// the binary's, whole. The old generator owned a region and left the prose
|
||||
// around it alone, because that prose was somebody's hand-written file. It is
|
||||
// embedded now — there is no hand-written half left to protect, and preserving
|
||||
// local edits would freeze a project's documentation at whatever version first
|
||||
// initialized it.
|
||||
func TestGenReplacesLocalEditsRatherThanPreservingThem(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
out := filepath.Join(dir, "skills")
|
||||
mustRun(t, dir, "gen", "skills", "--out", out)
|
||||
out := filepath.Join(dir, "out")
|
||||
mustRun(t, dir, "gen", "scaffold", "--out", out)
|
||||
|
||||
path := filepath.Join(out, "issue", "SKILL.md")
|
||||
raw := readFile(t, path)
|
||||
start := strings.Index(raw, genOpen)
|
||||
end := strings.Index(raw, genClose) + len(genClose)
|
||||
if start < 0 || end < len(genClose) {
|
||||
t.Fatalf("no region in the generated file:\n%s", raw)
|
||||
path := filepath.Join(out, "skills", "kettle-issue", "SKILL.md")
|
||||
pristine := readFile(t, path)
|
||||
edited := strings.Replace(pristine, "# /kettle:issue", "# my own heading", 1)
|
||||
edited = strings.Replace(edited, genClose, "hand-added line\n"+genClose, 1)
|
||||
if edited == pristine {
|
||||
t.Fatal("the fixture did not actually edit anything")
|
||||
}
|
||||
|
||||
const above = "\n## Identity: the slug\n\nThe file name is the id, and it never changes.\n\n"
|
||||
const below = "\n\n## Layering rule\n\nThis skill must keep working with the sync skill deleted.\n"
|
||||
// A description a human tuned, in the frontmatter the generator must not
|
||||
// touch: it is the only thing that decides whether the skill loads at all.
|
||||
edited := strings.Replace(raw[:start], "description: TODO", "description: Work with this project's issues as units of work", 1)
|
||||
edited += above + raw[start:end] + below
|
||||
if err := os.WriteFile(path, []byte(edited), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
mustRun(t, dir, "gen", "skills", "--out", out)
|
||||
after := readFile(t, path)
|
||||
if after != edited {
|
||||
t.Errorf("a no-op regeneration did not return the file byte for byte:\n--- want ---\n%s\n--- got ---\n%s", edited, after)
|
||||
// --check is the warning, and it comes before the loss rather than after.
|
||||
if r := run(t, dir, "gen", "scaffold", "--out", out, "--check"); r.code != 1 {
|
||||
t.Errorf("--check exited %d on an edited file, want 1:\n%s", r.code, r.out())
|
||||
}
|
||||
|
||||
// And the prose survives a regeneration that actually rewrites the block.
|
||||
shortened := strings.Replace(after, genClose, "the block was gutted by hand\n"+genClose, 1)
|
||||
if err := os.WriteFile(path, []byte(shortened), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mustRun(t, dir, "gen", "skills", "--out", out)
|
||||
restored := readFile(t, path)
|
||||
if restored != edited {
|
||||
t.Error("regenerating the block did not restore it, or did not preserve the prose around it")
|
||||
}
|
||||
if !strings.Contains(restored, "description: Work with this project's issues") {
|
||||
t.Errorf("the hand-tuned description was overwritten:\n%s", firstLines(restored, 5))
|
||||
}
|
||||
if !strings.Contains(restored, above) || !strings.Contains(restored, below) {
|
||||
t.Errorf("hand-written prose outside the markers was lost:\n%s", restored)
|
||||
}
|
||||
}
|
||||
|
||||
// Clobbering somebody's prose because they forgot a marker is the failure this
|
||||
// whole design exists to prevent.
|
||||
func TestGenNeverOverwritesAFileWithoutMarkers(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
out := filepath.Join(dir, "skills")
|
||||
path := filepath.Join(out, "issue", "SKILL.md")
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const prose = "---\nname: issue\ndescription: hand written, every word of it\n---\n\n# Everything here is somebody's work\n"
|
||||
if err := os.WriteFile(path, []byte(prose), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
r := mustRun(t, dir, "gen", "skills", "--out", out)
|
||||
if got := readFile(t, path); got != prose {
|
||||
t.Fatalf("a file with no markers was rewritten:\n%s", got)
|
||||
}
|
||||
// Left alone silently is how it drifts unnoticed, so it is reported — and
|
||||
// on stderr, where a warning belongs.
|
||||
if !strings.Contains(r.stderr, path) {
|
||||
t.Errorf("the skipped file was not named on stderr:\n%s", r.out())
|
||||
}
|
||||
if !strings.Contains(r.stdout, "without a region") {
|
||||
t.Errorf("the receipt did not account for it:\n%s", r.stdout)
|
||||
}
|
||||
// The other groups still got written — one unmanaged file stops nothing.
|
||||
if _, err := os.Stat(filepath.Join(out, "sync", "SKILL.md")); err != nil {
|
||||
t.Error("one file without markers stopped the whole run")
|
||||
mustRun(t, dir, "gen", "scaffold", "--out", out)
|
||||
if got := readFile(t, path); got != pristine {
|
||||
t.Errorf("regenerating did not restore the binary's own copy:\n%s", firstLines(got, 8))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenCheckFailsOnAStaleFileAndNamesIt(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
out := filepath.Join(dir, "skills")
|
||||
mustRun(t, dir, "gen", "skills", "--out", out)
|
||||
out := filepath.Join(dir, "out")
|
||||
mustRun(t, dir, "gen", "scaffold", "--out", out)
|
||||
|
||||
stale := filepath.Join(out, "sync", "SKILL.md")
|
||||
raw := readFile(t, stale)
|
||||
edited := strings.Replace(raw, genClose, "kettle push --thoroughly-renamed-flag\n"+genClose, 1)
|
||||
stale := filepath.Join(out, "skills", "kettle-sync", "SKILL.md")
|
||||
edited := strings.Replace(readFile(t, stale), genClose, "kettle push --thoroughly-renamed-flag\n"+genClose, 1)
|
||||
if err := os.WriteFile(stale, []byte(edited), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
r := run(t, dir, "gen", "skills", "--out", out, "--check")
|
||||
r := run(t, dir, "gen", "scaffold", "--out", out, "--check")
|
||||
if r.code != 1 {
|
||||
t.Fatalf("--check exited %d, want 1 — this is what a hook or a CI step calls:\n%s", r.code, r.out())
|
||||
}
|
||||
@@ -190,7 +168,7 @@ func TestGenCheckFailsOnAStaleFileAndNamesIt(t *testing.T) {
|
||||
if err := os.Remove(stale); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r := run(t, dir, "gen", "skills", "--out", out, "--check"); r.code != 1 {
|
||||
if r := run(t, dir, "gen", "scaffold", "--out", out, "--check"); r.code != 1 {
|
||||
t.Errorf("--check exited %d for a missing file, want 1:\n%s", r.code, r.out())
|
||||
}
|
||||
if _, err := os.Stat(stale); err == nil {
|
||||
@@ -200,9 +178,9 @@ func TestGenCheckFailsOnAStaleFileAndNamesIt(t *testing.T) {
|
||||
|
||||
func TestGenDryRunWritesNothingAtAll(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
out := filepath.Join(dir, "skills")
|
||||
out := filepath.Join(dir, "out")
|
||||
|
||||
fresh := mustRun(t, dir, "gen", "skills", "--out", out, "--dry-run")
|
||||
fresh := mustRun(t, dir, "gen", "scaffold", "--out", out, "--dry-run")
|
||||
if !strings.Contains(fresh.stdout, "would create") {
|
||||
t.Errorf("a dry run said nothing about what it would do:\n%s", fresh.out())
|
||||
}
|
||||
@@ -211,14 +189,14 @@ func TestGenDryRunWritesNothingAtAll(t *testing.T) {
|
||||
}
|
||||
|
||||
// And on an existing tree: the file is described, never touched.
|
||||
mustRun(t, dir, "gen", "skills", "--out", out)
|
||||
path := filepath.Join(out, "issue", "SKILL.md")
|
||||
mustRun(t, dir, "gen", "scaffold", "--out", out)
|
||||
path := filepath.Join(out, "skills", "kettle-issue", "SKILL.md")
|
||||
edited := strings.Replace(readFile(t, path), genClose, "gutted\n"+genClose, 1)
|
||||
if err := os.WriteFile(path, []byte(edited), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
r := mustRun(t, dir, "gen", "skills", "--out", out, "--dry-run")
|
||||
r := mustRun(t, dir, "gen", "scaffold", "--out", out, "--dry-run")
|
||||
if !strings.Contains(r.stdout, "would update") || !strings.Contains(r.stdout, "nothing was written") {
|
||||
t.Errorf("the dry run did not report the pending change:\n%s", r.out())
|
||||
}
|
||||
@@ -227,12 +205,38 @@ func TestGenDryRunWritesNothingAtAll(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenRefusesAnUnknownTargetAndAMissingOut(t *testing.T) {
|
||||
// Without --out the tree goes under the project marker, resolved by the same
|
||||
// walk every other command uses. No marker is an answer, not a fallback: a
|
||||
// `.claude/` written into a plausible-looking directory is the failure the
|
||||
// marker exists to replace.
|
||||
func TestGenWithoutOutResolvesTheProject(t *testing.T) {
|
||||
dir := newProject(t)
|
||||
sub := filepath.Join(dir, "cli", "internal")
|
||||
if err := os.MkdirAll(sub, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
mustRun(t, sub, "gen", "scaffold")
|
||||
if _, err := os.Stat(filepath.Join(dir, ".claude", "skills", "kettle-issue", "SKILL.md")); err != nil {
|
||||
t.Errorf("run from %s, the tree did not land at the project root: %v", sub, err)
|
||||
}
|
||||
|
||||
orphan := t.TempDir()
|
||||
r := run(t, orphan, "gen", "scaffold")
|
||||
if r.code == 0 {
|
||||
t.Fatalf("gen outside a project must stop:\n%s", r.out())
|
||||
}
|
||||
if !strings.Contains(r.stderr, ".kettle") {
|
||||
t.Errorf("the refusal does not name what is missing:\n%s", r.out())
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(orphan, ".claude")); err == nil {
|
||||
t.Error("the refused run created a tree anyway")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenRefusesAnUnknownTarget(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
|
||||
if r := run(t, dir, "gen", "skills"); r.code == 0 || !strings.Contains(r.stderr, "--out") {
|
||||
t.Errorf("gen without --out must stop and say so:\n%s", r.out())
|
||||
}
|
||||
if r := run(t, dir, "gen", "agents", "--out", filepath.Join(dir, "x")); r.code == 0 {
|
||||
t.Errorf("an unknown target must be refused:\n%s", r.out())
|
||||
}
|
||||
|
||||
+173
-42
@@ -1,6 +1,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
@@ -9,8 +10,27 @@ import (
|
||||
|
||||
"git.noodles.cam/claude-skills/marketplace/cli/internal/config"
|
||||
"git.noodles.cam/claude-skills/marketplace/cli/internal/project"
|
||||
"git.noodles.cam/claude-skills/marketplace/cli/internal/scaffold"
|
||||
)
|
||||
|
||||
// initOptions is everything init does, as data.
|
||||
//
|
||||
// It exists so that --interactive and the flags are two ways of filling in one
|
||||
// struct rather than two implementations of one command. Every question the
|
||||
// wizard asks has a field here and therefore a flag: a step that could only be
|
||||
// reached by answering a prompt would be a step no script, no CI run and no
|
||||
// agent could take.
|
||||
type initOptions struct {
|
||||
Root string
|
||||
Login string
|
||||
Repo string
|
||||
Scaffold bool
|
||||
ScaffoldOut string
|
||||
MirrorHook bool
|
||||
ForceSettings bool
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// writeConfig creates or updates .kettle/config.yaml, touching only the
|
||||
// settings it was given.
|
||||
//
|
||||
@@ -66,7 +86,8 @@ func init() {
|
||||
Short: "make this directory a project that tracks issues",
|
||||
Long: `Creates ` + "`.kettle/`" + ` — the marker every other command resolves the store from,
|
||||
and ` + "`.kettle/config.yaml`" + `, which says which tracker repository these issues
|
||||
belong to and which login to reach it under.
|
||||
belong to and which login to reach it under — and writes ` + "`.claude/`" + `: the slash
|
||||
commands an operator invokes, the skills a model loads, and the runner subagent.
|
||||
|
||||
The marker is deliberately something an operator makes, not something inferred
|
||||
from the tree: ` + "`.git`" + ` is in every clone, so anything that inferred a root from
|
||||
@@ -77,18 +98,26 @@ machine, outside every working tree, managed with ` + "`kettle auth`" + `.
|
||||
|
||||
All of it is idempotent: it creates .kettle/issues and .kettle/payload, migrates
|
||||
an older store in if it finds one (either layout the tea plugin used, oldest
|
||||
first), writes the config without disturbing settings it was not given, and adds
|
||||
.kettle/ to .gitignore. Each migration is a move, not a copy — two stores is the
|
||||
state the marker exists to prevent — and it refuses to pick a winner when both
|
||||
sides hold a file of the same name.
|
||||
first), writes the config without disturbing settings it was not given, writes
|
||||
the .claude/ tree, and adds .kettle/ to .gitignore. Each migration is a move,
|
||||
not a copy — two stores is the state the marker exists to prevent — and it
|
||||
refuses to pick a winner when both sides hold a file of the same name.
|
||||
|
||||
Do NOT run this inside a linked worktree. A worktree is the same project on
|
||||
another branch and reaches the store by a hop out to the main checkout; a marker
|
||||
here would give one project two stores, and the directory holding the second one
|
||||
disappears with the branch.`,
|
||||
IT REFUSES TO RUN IN A LINKED WORKTREE, and names the main checkout instead. A
|
||||
worktree is the same project on another branch and reaches the store by a hop
|
||||
out to the main checkout; a marker here would give one project two stores, and
|
||||
the directory holding the second one disappears with the branch.
|
||||
|
||||
--interactive walks a person through the whole thing — the login, the token with
|
||||
the echo turned off, the repository, the .claude/ tree and the AGENTS.md mirror
|
||||
hook. IT REQUIRES A TERMINAL and refuses a standard input that is not one, which
|
||||
is deliberate: every question it asks has a flag beside it, so nothing that is
|
||||
not a person ever needs to answer a prompt.`,
|
||||
Examples: []Example{
|
||||
{"kettle init", "initialize the current directory"},
|
||||
{"kettle init --interactive", "be walked through it, at a terminal"},
|
||||
{"kettle init --login noodles --repo claude-skills/marketplace", "and point it at a tracker"},
|
||||
{"kettle init --mirror-hook", "register the AGENTS.md mirror on PreToolUse(Bash)"},
|
||||
{"kettle init --at ~/code/x", "initialize somewhere else"},
|
||||
{"kettle init --dry-run", "say what it would do, touch nothing"},
|
||||
},
|
||||
@@ -96,6 +125,11 @@ disappears with the branch.`,
|
||||
at := fs.String("at", "", "directory to initialize (default: the working directory)")
|
||||
login := fs.String("login", "", "name of a login in the machine-wide file (see `kettle auth`)")
|
||||
repo := fs.String("repo", "", "tracker repository, as owner/name")
|
||||
interactive := fs.Bool("interactive", false, "ask, one question at a time; requires a terminal")
|
||||
noScaffold := fs.Bool("no-scaffold", false, "do not write the .claude/ commands, skills and subagent")
|
||||
scaffoldOut := fs.String("scaffold-out", "", "where the .claude/ tree goes (default: <project>/"+scaffold.Marker+")")
|
||||
mirrorHook := fs.Bool("mirror-hook", false, "register `kettle mirror --hook` on PreToolUse(Bash)")
|
||||
forceSettings := fs.Bool("force-settings", false, "let the hook be merged into an existing settings.json, reformatting it")
|
||||
dryRun := fs.Bool("dry-run", false, "report what would happen; change nothing")
|
||||
|
||||
return func(args []string) error {
|
||||
@@ -115,43 +149,140 @@ disappears with the branch.`,
|
||||
return Fail("%s is not a directory", root)
|
||||
}
|
||||
|
||||
// A second marker inside an existing project gives it a second
|
||||
// store, and the nearer one wins — which is a surprise worth
|
||||
// naming before it happens, not after.
|
||||
if existing := project.Root(root); existing != "" && existing != root {
|
||||
fmt.Fprintf(os.Stderr,
|
||||
"warning: %s already sits inside the project at %s — a second marker here gives it a second store, and the nearer one wins.\n",
|
||||
root, existing)
|
||||
opts := initOptions{
|
||||
Root: root,
|
||||
Login: *login,
|
||||
Repo: *repo,
|
||||
Scaffold: !*noScaffold,
|
||||
ScaffoldOut: *scaffoldOut,
|
||||
MirrorHook: *mirrorHook,
|
||||
ForceSettings: *forceSettings,
|
||||
DryRun: *dryRun,
|
||||
}
|
||||
|
||||
if *repo != "" {
|
||||
if owner, name, ok := strings.Cut(*repo, "/"); !ok || owner == "" || name == "" {
|
||||
return Fail("--repo %q is not owner/name", *repo)
|
||||
if *interactive {
|
||||
if err := askInit(&opts); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
done, err := project.Init(root, *dryRun)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
line, err := writeConfig(root, *login, *repo, *dryRun)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if line != "" {
|
||||
done = append(done, line)
|
||||
}
|
||||
|
||||
prefix := ""
|
||||
if *dryRun {
|
||||
prefix = "would: "
|
||||
}
|
||||
for _, l := range done {
|
||||
fmt.Println(prefix + l)
|
||||
}
|
||||
return nil
|
||||
return runInit(opts)
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func runInit(opts initOptions) error {
|
||||
// A worktree is the same project on another branch. The rule used to live in
|
||||
// a skill somebody had to read; it is here because the wizard is now the
|
||||
// front door and a front door cannot rely on the reader having read anything.
|
||||
if main := project.MainWorktree(opts.Root); main != "" {
|
||||
return Fail("%s is a linked worktree of the project at %s.\n"+
|
||||
"A worktree reaches that store on its own — the walk crosses to it through the `gitdir:` in the .git file — "+
|
||||
"and a marker here would give one project two stores, the second of which is deleted with the branch.\n"+
|
||||
"Initialize the main checkout instead: kettle init --at %s", opts.Root, main, main)
|
||||
}
|
||||
|
||||
// A second marker inside an existing project gives it a second store, and
|
||||
// the nearer one wins — which is a surprise worth naming before it happens,
|
||||
// not after.
|
||||
if existing := project.Root(opts.Root); existing != "" && existing != opts.Root {
|
||||
fmt.Fprintf(os.Stderr,
|
||||
"warning: %s already sits inside the project at %s — a second marker here gives it a second store, and the nearer one wins.\n",
|
||||
opts.Root, existing)
|
||||
}
|
||||
|
||||
if opts.Repo != "" {
|
||||
if owner, name, ok := strings.Cut(opts.Repo, "/"); !ok || owner == "" || name == "" {
|
||||
return Fail("--repo %q is not owner/name", opts.Repo)
|
||||
}
|
||||
}
|
||||
|
||||
done, err := project.Init(opts.Root, opts.DryRun)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
line, err := writeConfig(opts.Root, opts.Login, opts.Repo, opts.DryRun)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if line != "" {
|
||||
done = append(done, line)
|
||||
}
|
||||
|
||||
prefix := ""
|
||||
if opts.DryRun {
|
||||
prefix = "would: "
|
||||
}
|
||||
for _, l := range done {
|
||||
fmt.Println(prefix + l)
|
||||
}
|
||||
|
||||
if opts.Scaffold {
|
||||
if err := initScaffold(opts); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if opts.MirrorHook {
|
||||
if err := initMirrorHook(opts); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// scaffoldOut is where the .claude/ tree goes for this run. An explicit
|
||||
// --scaffold-out is used exactly as typed; without one it sits beside the
|
||||
// marker, which is the only place another command can find it again.
|
||||
func (o initOptions) scaffoldOut() string {
|
||||
if o.ScaffoldOut != "" {
|
||||
return o.ScaffoldOut
|
||||
}
|
||||
return filepath.Join(o.Root, scaffold.Marker)
|
||||
}
|
||||
|
||||
func initScaffold(opts initOptions) error {
|
||||
out := opts.scaffoldOut()
|
||||
if err := genScaffold(out, opts.DryRun, false); err != nil {
|
||||
return err
|
||||
}
|
||||
if opts.DryRun {
|
||||
return nil
|
||||
}
|
||||
|
||||
// The stamp is written last and is not load-bearing: nothing resolves from
|
||||
// it, and deleting it costs the warning in `kettle config` and nothing else.
|
||||
rec := &config.Scaffold{Version: Version, Out: relativeTo(opts.Root, out)}
|
||||
return config.SaveScaffoldFile(filepath.Join(opts.Root, project.Marker, "scaffold.yaml"), rec)
|
||||
}
|
||||
|
||||
func initMirrorHook(opts initOptions) error {
|
||||
line, err := writeMirrorHook(opts.scaffoldOut(), opts.ForceSettings, opts.DryRun)
|
||||
if err != nil {
|
||||
// An existing settings.json is a decision for the operator, not a
|
||||
// failure of the run: everything before this point already happened and
|
||||
// saying otherwise would send them looking for damage there is none of.
|
||||
if errors.Is(err, errSettingsExist) {
|
||||
fmt.Fprintf(os.Stderr, "kettle init: the mirror hook was not registered — %v\n", err)
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if line != "" {
|
||||
prefix := ""
|
||||
if opts.DryRun {
|
||||
prefix = "would: "
|
||||
}
|
||||
fmt.Println(prefix + line)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// relativeTo is path as written down in the scaffold record: relative when it
|
||||
// sits under the project, absolute when the operator sent it somewhere else.
|
||||
func relativeTo(root, path string) string {
|
||||
rel, err := filepath.Rel(root, path)
|
||||
if err != nil || strings.HasPrefix(rel, "..") {
|
||||
return path
|
||||
}
|
||||
return rel
|
||||
}
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
package cmd_test
|
||||
|
||||
// What `kettle init` writes beyond the marker: the .claude/ tree, the record of
|
||||
// which build wrote it, and the optional mirror hook. Plus the two refusals that
|
||||
// used to be prose in a skill and are now the binary's.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInitWritesTheClaudeTreeByDefault(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
r := mustRun(t, dir, "init")
|
||||
|
||||
for _, rel := range scaffoldFiles {
|
||||
if _, err := os.Stat(filepath.Join(dir, ".claude", filepath.FromSlash(rel))); err != nil {
|
||||
t.Errorf("%s was not written: %v\n%s", rel, err, r.out())
|
||||
}
|
||||
}
|
||||
|
||||
// And the record of what wrote it, which is the only way an operator can
|
||||
// tell a current tree from one four releases old.
|
||||
stamp := readFile(t, filepath.Join(dir, ".kettle", "scaffold.yaml"))
|
||||
for _, want := range []string{"version:", "out: .claude"} {
|
||||
if !strings.Contains(stamp, want) {
|
||||
t.Errorf("the scaffold record is missing %q:\n%s", want, stamp)
|
||||
}
|
||||
}
|
||||
if cfg := mustRun(t, dir, "config"); !strings.Contains(cfg.stdout, "scaffold .claude") {
|
||||
t.Errorf("`kettle config` does not report the tree:\n%s", cfg.stdout)
|
||||
}
|
||||
|
||||
// Idempotent all the way through: a second init rewrites nothing.
|
||||
second := mustRun(t, dir, "init")
|
||||
if strings.Contains(second.stdout, "updated") {
|
||||
t.Errorf("a second init rewrote a document:\n%s", second.out())
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitCanBeToldToWriteNoTreeAtAll(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
mustRun(t, dir, "init", "--no-scaffold")
|
||||
|
||||
if _, err := os.Stat(filepath.Join(dir, ".claude")); err == nil {
|
||||
t.Error("--no-scaffold still wrote the tree")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, ".kettle", "scaffold.yaml")); err == nil {
|
||||
t.Error("--no-scaffold recorded a tree it did not write")
|
||||
}
|
||||
// Nothing else is affected: this is still a project.
|
||||
if _, err := os.Stat(filepath.Join(dir, ".kettle", "issues")); err != nil {
|
||||
t.Errorf("--no-scaffold skipped the store as well: %v", err)
|
||||
}
|
||||
// And `kettle config` says so rather than saying nothing.
|
||||
if cfg := mustRun(t, dir, "config"); !strings.Contains(cfg.stdout, "scaffold (none written") {
|
||||
t.Errorf("`kettle config` is silent about the missing tree:\n%s", cfg.stdout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitScaffoldOutIsUsedAsTyped(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
elsewhere := filepath.Join(dir, "somewhere", "else")
|
||||
|
||||
mustRun(t, dir, "init", "--scaffold-out", elsewhere)
|
||||
if _, err := os.Stat(filepath.Join(elsewhere, "skills", "kettle-issue", "SKILL.md")); err != nil {
|
||||
t.Errorf("the tree did not go where it was told: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, ".claude")); err == nil {
|
||||
t.Error("it went to the default as well")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitDryRunWritesNoTreeAndNoRecord(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
|
||||
r := mustRun(t, dir, "init", "--dry-run", "--mirror-hook")
|
||||
if !strings.Contains(r.stdout, "would create") {
|
||||
t.Errorf("the dry run said nothing about the tree:\n%s", r.out())
|
||||
}
|
||||
for _, p := range []string{".claude", ".kettle"} {
|
||||
if _, err := os.Stat(filepath.Join(dir, p)); err == nil {
|
||||
t.Errorf("a dry run created %s", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The mirror hook: offered, never assumed. A project that keeps no AGENTS.md
|
||||
// files wants nothing to do with it.
|
||||
func TestInitRegistersTheMirrorHookOnlyWhenAsked(t *testing.T) {
|
||||
plain := t.TempDir()
|
||||
mustRun(t, plain, "init")
|
||||
if _, err := os.Stat(filepath.Join(plain, ".claude", "settings.json")); err == nil {
|
||||
t.Error("init registered a hook nobody asked for")
|
||||
}
|
||||
|
||||
asked := t.TempDir()
|
||||
mustRun(t, asked, "init", "--mirror-hook")
|
||||
body := readFile(t, filepath.Join(asked, ".claude", "settings.json"))
|
||||
|
||||
var settings struct {
|
||||
Hooks struct {
|
||||
PreToolUse []struct {
|
||||
Matcher string `json:"matcher"`
|
||||
Hooks []struct {
|
||||
Type string `json:"type"`
|
||||
Command string `json:"command"`
|
||||
} `json:"hooks"`
|
||||
} `json:"PreToolUse"`
|
||||
} `json:"hooks"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &settings); err != nil {
|
||||
t.Fatalf("the settings file is not valid JSON: %v\n%s", err, body)
|
||||
}
|
||||
if len(settings.Hooks.PreToolUse) != 1 || settings.Hooks.PreToolUse[0].Matcher != "Bash" {
|
||||
t.Fatalf("the hook is not registered on PreToolUse(Bash):\n%s", body)
|
||||
}
|
||||
command := settings.Hooks.PreToolUse[0].Hooks[0].Command
|
||||
if !strings.Contains(command, "kettle mirror --hook") {
|
||||
t.Errorf("the registered command is %q", command)
|
||||
}
|
||||
// The guard outlives the binary: an operator who uninstalls kettle must not
|
||||
// get "command not found" on every Bash call from a hook they set up months
|
||||
// ago and have stopped thinking about.
|
||||
if !strings.Contains(command, "command -v kettle") {
|
||||
t.Errorf("the registered command has no guard against kettle being gone: %q", command)
|
||||
}
|
||||
}
|
||||
|
||||
// settings.json is a file the operator owns and commits, and Go cannot preserve
|
||||
// its key order. So an existing one is never rewritten without being asked
|
||||
// twice: the run reports what it did not do, prints the snippet, and succeeds.
|
||||
func TestInitRefusesToRewriteAnExistingSettingsFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
settings := filepath.Join(dir, ".claude", "settings.json")
|
||||
if err := os.MkdirAll(filepath.Dir(settings), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const theirs = `{ "permissions": { "allow": ["Bash(ls:*)"] } }`
|
||||
if err := os.WriteFile(settings, []byte(theirs), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
r := mustRun(t, dir, "init", "--mirror-hook")
|
||||
if got := readFile(t, settings); got != theirs {
|
||||
t.Errorf("the operator's settings file was rewritten:\n%s", got)
|
||||
}
|
||||
if !strings.Contains(r.stderr, "kettle mirror") {
|
||||
t.Errorf("the refusal did not print the snippet to paste:\n%s", r.out())
|
||||
}
|
||||
if !strings.Contains(r.stderr, "--force-settings") {
|
||||
t.Errorf("the refusal did not name the way past it:\n%s", r.out())
|
||||
}
|
||||
// Everything before the hook still happened; this is a decision, not a
|
||||
// failure, and reporting it as one would send somebody looking for damage.
|
||||
if _, err := os.Stat(filepath.Join(dir, ".kettle", "issues")); err != nil {
|
||||
t.Error("the refusal rolled back the rest of the run")
|
||||
}
|
||||
|
||||
// Asked twice, it merges — and keeps what was already in the file.
|
||||
mustRun(t, dir, "init", "--mirror-hook", "--force-settings")
|
||||
merged := readFile(t, settings)
|
||||
if !strings.Contains(merged, "kettle mirror") {
|
||||
t.Errorf("--force-settings did not add the hook:\n%s", merged)
|
||||
}
|
||||
if !strings.Contains(merged, "Bash(ls:*)") {
|
||||
t.Errorf("--force-settings dropped what was already there:\n%s", merged)
|
||||
}
|
||||
|
||||
// And a third run adds nothing: the hook is already there.
|
||||
mustRun(t, dir, "init", "--mirror-hook")
|
||||
if again := readFile(t, settings); again != merged {
|
||||
t.Errorf("a re-run duplicated the hook:\n%s", again)
|
||||
}
|
||||
}
|
||||
|
||||
// The rule that used to be a paragraph in a skill an operator had to read. The
|
||||
// wizard is the front door now, and a front door cannot assume anybody read
|
||||
// anything.
|
||||
func TestInitRefusesALinkedWorktree(t *testing.T) {
|
||||
main := t.TempDir()
|
||||
worktree := filepath.Join(main, "wt")
|
||||
gitdir := filepath.Join(main, ".git", "worktrees", "wt")
|
||||
if err := os.MkdirAll(gitdir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(worktree, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(gitdir, "commondir"), []byte("../..\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(worktree, ".git"), []byte("gitdir: "+gitdir+"\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
r := run(t, worktree, "init")
|
||||
if r.code == 0 {
|
||||
t.Fatalf("init in a linked worktree must be refused:\n%s", r.out())
|
||||
}
|
||||
if !strings.Contains(r.stderr, main) {
|
||||
t.Errorf("the refusal does not name the main checkout to use instead:\n%s", r.out())
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(worktree, ".kettle")); err == nil {
|
||||
t.Error("the refused run created a second marker anyway")
|
||||
}
|
||||
}
|
||||
|
||||
// --interactive is for a person. Under a test harness, a script or an agent,
|
||||
// standard input is a pipe and the answer is an error that names the flags
|
||||
// rather than a prompt nobody will ever answer.
|
||||
func TestInteractiveRefusesWhatIsNotATerminal(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
|
||||
r := runWith(t, dir, nil, "\n\n\n", "init", "--interactive")
|
||||
if r.code == 0 {
|
||||
t.Fatalf("--interactive succeeded without a terminal:\n%s", r.out())
|
||||
}
|
||||
if !strings.Contains(r.stderr, "terminal") {
|
||||
t.Errorf("the refusal does not say what is missing:\n%s", r.out())
|
||||
}
|
||||
for _, flag := range []string{"--login", "--repo", "--mirror-hook"} {
|
||||
if !strings.Contains(r.stderr, flag) {
|
||||
t.Errorf("the refusal does not name %s, which is the way through:\n%s", flag, r.out())
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, ".kettle")); err == nil {
|
||||
t.Error("the refused run initialized the directory anyway")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/term"
|
||||
|
||||
"git.noodles.cam/claude-skills/marketplace/cli/internal/config"
|
||||
"git.noodles.cam/claude-skills/marketplace/cli/internal/project"
|
||||
)
|
||||
|
||||
// askInit fills in an initOptions by asking, and is the ONLY thing in this
|
||||
// binary that reads from a terminal.
|
||||
//
|
||||
// Two rules hold it in place, and both are about what it is not allowed to
|
||||
// become. It answers no question the flags cannot answer, so nothing here is a
|
||||
// capability that exists only behind a prompt; and it performs nothing itself —
|
||||
// it fills in the struct and hands it back, so the run that follows an
|
||||
// interactive session is byte for byte the run somebody else gets from flags.
|
||||
func askInit(opts *initOptions) error {
|
||||
if !term.IsTerminal(int(os.Stdin.Fd())) {
|
||||
return Fail("--interactive needs a terminal, and standard input is not one.\n" +
|
||||
"Every question it asks has a flag: --login, --repo, --scaffold-out, --no-scaffold, --mirror-hook.")
|
||||
}
|
||||
in := bufio.NewReader(os.Stdin)
|
||||
|
||||
fmt.Printf("kettle init — %s\n\n", opts.Root)
|
||||
if main := project.MainWorktree(opts.Root); main != "" {
|
||||
// Asked before anything else, because every answer after it would be
|
||||
// about a project that must not be created here.
|
||||
return Fail("%s is a linked worktree of the project at %s — initialize the main checkout instead", opts.Root, main)
|
||||
}
|
||||
|
||||
if err := askLogin(in, opts); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := askRepo(in, opts); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
opts.Scaffold = askYesNo(in, "Write the kettle commands and skills into "+
|
||||
relativeTo(opts.Root, opts.scaffoldOut())+"?", true)
|
||||
opts.MirrorHook = askYesNo(in, "Mirror AGENTS.md to CLAUDE.md in this project? "+
|
||||
"(registers `kettle mirror --hook` on PreToolUse)", false)
|
||||
|
||||
fmt.Println()
|
||||
return nil
|
||||
}
|
||||
|
||||
// askLogin offers what the machine already holds, and never invents one.
|
||||
//
|
||||
// Adding a login is offered here rather than left to `kettle auth add` for one
|
||||
// reason: this is a person at a terminal, so the token can be read with the echo
|
||||
// turned off — no shell history, no temp file, no scrollback. That is strictly
|
||||
// better than every other way of getting a secret into this program, and it is
|
||||
// the single strongest argument for the wizard existing at all.
|
||||
func askLogin(in *bufio.Reader, opts *initOptions) error {
|
||||
logins, err := config.LoadLogins()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if opts.Login != "" {
|
||||
fmt.Printf("login %s (given on the command line)\n", opts.Login)
|
||||
return nil
|
||||
}
|
||||
|
||||
names := logins.Names()
|
||||
fmt.Println("Logins on this machine:")
|
||||
if len(names) == 0 {
|
||||
fmt.Println(" (none)")
|
||||
}
|
||||
for i, l := range logins.Logins {
|
||||
fmt.Printf(" %d) %-16s %s\n", i+1, l.Name, l.URL)
|
||||
}
|
||||
fmt.Printf(" a) add one\n s) skip — pin a login later with `kettle init --login <name>`\n")
|
||||
|
||||
for {
|
||||
answer := strings.TrimSpace(ask(in, "Which login should this project run under?", "s"))
|
||||
switch strings.ToLower(answer) {
|
||||
case "s", "skip":
|
||||
return nil
|
||||
case "a", "add":
|
||||
name, err := addLogin(in, logins)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
opts.Login = name
|
||||
return nil
|
||||
}
|
||||
if n, err := strconv.Atoi(answer); err == nil && n >= 1 && n <= len(logins.Logins) {
|
||||
opts.Login = logins.Logins[n-1].Name
|
||||
return nil
|
||||
}
|
||||
// A name typed in full is the same answer as its number, and is what
|
||||
// somebody who already knows the login will reach for.
|
||||
if logins.Find(answer) != nil {
|
||||
opts.Login = answer
|
||||
return nil
|
||||
}
|
||||
fmt.Printf(" %q is not one of them.\n", answer)
|
||||
}
|
||||
}
|
||||
|
||||
// addLogin writes one entry into the machine-wide file, token and all.
|
||||
func addLogin(in *bufio.Reader, logins *config.Logins) (string, error) {
|
||||
name := required(in, " Name for this login (a label, not a username)")
|
||||
url := strings.TrimRight(required(in, " Instance URL, e.g. https://git.example.com"), "/")
|
||||
user := ask(in, " Account it belongs to (documentation only)", "")
|
||||
scopes := ask(in, " Scopes it was minted with (documentation only)", "write:issue,write:repository")
|
||||
|
||||
token, err := askSecret(" Token (not echoed)")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if token == "" {
|
||||
return "", Fail("no token given")
|
||||
}
|
||||
|
||||
entry := config.Login{
|
||||
Name: name,
|
||||
URL: url,
|
||||
User: user,
|
||||
Scopes: splitScopes(scopes),
|
||||
Token: token,
|
||||
}
|
||||
if existing := logins.Find(name); existing != nil {
|
||||
*existing = entry
|
||||
} else {
|
||||
logins.Logins = append(logins.Logins, entry)
|
||||
}
|
||||
if err := config.SaveLogins(logins); err != nil {
|
||||
return "", err
|
||||
}
|
||||
fmt.Printf(" %s -> %s %s\n\n", entry.Name, entry.URL, config.LoginsPath())
|
||||
return name, nil
|
||||
}
|
||||
|
||||
// askRepo offers what the git remote says, because that is right nearly every
|
||||
// time and wrong in a way the operator can see immediately.
|
||||
func askRepo(in *bufio.Reader, opts *initOptions) error {
|
||||
if opts.Repo != "" {
|
||||
fmt.Printf("repo %s (given on the command line)\n", opts.Repo)
|
||||
return nil
|
||||
}
|
||||
guess := repoFromGitConfig(opts.Root)
|
||||
answer := strings.TrimSpace(ask(in, "Tracker repository, as owner/name", guess))
|
||||
if answer == "" {
|
||||
return nil
|
||||
}
|
||||
if owner, name, ok := strings.Cut(answer, "/"); !ok || owner == "" || name == "" {
|
||||
return Fail("%q is not owner/name", answer)
|
||||
}
|
||||
opts.Repo = answer
|
||||
return nil
|
||||
}
|
||||
|
||||
// repoFromGitConfig reads owner/name out of `origin` in .git/config, or "".
|
||||
//
|
||||
// Parsed rather than shelled out to, because `git` is one more thing that has to
|
||||
// be installed and one more process to fail in a way this has to interpret. A
|
||||
// guess is worth exactly what it costs, and this costs a file read: anything it
|
||||
// cannot make sense of is no guess at all, and the operator types the answer.
|
||||
func repoFromGitConfig(root string) string {
|
||||
raw, err := os.ReadFile(filepath.Join(root, ".git", "config"))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
inOrigin := false
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if strings.HasPrefix(line, "[") {
|
||||
inOrigin = strings.HasPrefix(line, `[remote "origin"]`)
|
||||
continue
|
||||
}
|
||||
if !inOrigin {
|
||||
continue
|
||||
}
|
||||
value, ok := strings.CutPrefix(line, "url")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if _, v, found := strings.Cut(value, "="); found {
|
||||
return ownerName(strings.TrimSpace(v))
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ownerName is the last two path elements of a git URL, without any .git.
|
||||
// `git@host:owner/name.git` and `https://host/owner/name` both answer
|
||||
// `owner/name`; anything else answers "".
|
||||
func ownerName(url string) string {
|
||||
url = strings.TrimSuffix(strings.TrimSpace(url), ".git")
|
||||
if _, after, found := strings.Cut(url, "://"); found {
|
||||
url = after
|
||||
if _, path, ok := strings.Cut(url, "/"); ok {
|
||||
url = path
|
||||
} else {
|
||||
return ""
|
||||
}
|
||||
} else if _, after, found := strings.Cut(url, ":"); found {
|
||||
url = after
|
||||
}
|
||||
parts := strings.Split(strings.Trim(url, "/"), "/")
|
||||
if len(parts) < 2 {
|
||||
return ""
|
||||
}
|
||||
owner, name := parts[len(parts)-2], parts[len(parts)-1]
|
||||
if owner == "" || name == "" {
|
||||
return ""
|
||||
}
|
||||
return owner + "/" + name
|
||||
}
|
||||
|
||||
// ask prints a question and returns the answer, or def when the line is empty.
|
||||
func ask(in *bufio.Reader, question, def string) string {
|
||||
if def != "" {
|
||||
fmt.Printf("%s [%s]: ", question, def)
|
||||
} else {
|
||||
fmt.Printf("%s: ", question)
|
||||
}
|
||||
line, err := in.ReadString('\n')
|
||||
if err != nil && line == "" {
|
||||
return def
|
||||
}
|
||||
if answer := strings.TrimSpace(line); answer != "" {
|
||||
return answer
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func required(in *bufio.Reader, question string) string {
|
||||
for {
|
||||
if answer := ask(in, question, ""); answer != "" {
|
||||
return answer
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// askYesNo is deliberately biased: the default is what an operator gets by
|
||||
// holding down return, so every prompt whose wrong answer costs something
|
||||
// defaults to no.
|
||||
func askYesNo(in *bufio.Reader, question string, def bool) bool {
|
||||
hint := "y/N"
|
||||
if def {
|
||||
hint = "Y/n"
|
||||
}
|
||||
for {
|
||||
fmt.Printf("%s [%s]: ", question, hint)
|
||||
line, err := in.ReadString('\n')
|
||||
if err != nil && line == "" {
|
||||
return def
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(line)) {
|
||||
case "":
|
||||
return def
|
||||
case "y", "yes":
|
||||
return true
|
||||
case "n", "no":
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// askSecret reads a line with the terminal's echo turned off.
|
||||
//
|
||||
// This is the whole reason --interactive needs a terminal rather than merely
|
||||
// preferring one: a token typed at a prompt that echoes is a token in somebody's
|
||||
// scrollback, and a token passed as an argument is a token in their shell
|
||||
// history. Neither is recoverable after the fact.
|
||||
func askSecret(question string) (string, error) {
|
||||
fmt.Print(question + ": ")
|
||||
raw, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
fmt.Println()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(string(raw)), nil
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"git.noodles.cam/claude-skills/marketplace/cli/internal/mirror"
|
||||
)
|
||||
|
||||
// hookPayload is the part of a PreToolUse payload this command reads. Every
|
||||
// other field is somebody else's business and is ignored rather than rejected —
|
||||
// a payload that grows a key must not stop a Bash call.
|
||||
type hookPayload struct {
|
||||
CWD string `json:"cwd"`
|
||||
}
|
||||
|
||||
// hookOutput is what a PreToolUse hook says back. additionalContext is
|
||||
// advisory: it is shown, and it decides nothing.
|
||||
type hookOutput struct {
|
||||
HookSpecificOutput struct {
|
||||
HookEventName string `json:"hookEventName"`
|
||||
AdditionalContext string `json:"additionalContext"`
|
||||
} `json:"hookSpecificOutput"`
|
||||
}
|
||||
|
||||
func init() {
|
||||
register(&Command{
|
||||
Name: "mirror",
|
||||
Group: GroupProject,
|
||||
Args: "[<dir>]",
|
||||
Short: "keep CLAUDE.md a symlink to AGENTS.md in every directory below here",
|
||||
Long: `Two agent harnesses read two different filenames for the same document. A
|
||||
repository that keeps both as real files keeps TWO DOCUMENTS, and they drift —
|
||||
silently, until somebody reads the stale one and believes it. This walks a tree
|
||||
and leaves one arrangement behind everywhere:
|
||||
|
||||
AGENTS.md is the real file; CLAUDE.md is a symlink pointing at it.
|
||||
|
||||
The link is relative, so a tree that is moved, copied or cloned keeps working.
|
||||
AGENTS.md is the real one because the convention is not one vendor's: a
|
||||
repository that names its documents after a single tool has picked a side it did
|
||||
not need to pick.
|
||||
|
||||
NOTHING HERE DELETES CONTENT. Six of the seven states it can find are repaired
|
||||
losslessly — a missing link is created, a reversed layout is swapped round, a
|
||||
duplicate whose bytes match its original is replaced by the link. The seventh,
|
||||
two real files whose contents DIFFER, is reported and left exactly as it was:
|
||||
one of them is somebody's writing and no rule here knows which.
|
||||
|
||||
It walks the directory given, or the working directory. node_modules, vendor,
|
||||
venv, __pycache__ and every dot-directory are skipped, because somebody else's
|
||||
tree is somebody else's business.
|
||||
|
||||
--hook is the PreToolUse form: it reads the hook payload on standard input,
|
||||
writes any report back as additionalContext, and ALWAYS EXITS 0 — including when
|
||||
it fails. A tool that broke somebody's Bash call because its documentation
|
||||
helper crashed would be worse than no tool. --check is the opposite end: it
|
||||
writes nothing and exits 1 when the tree is not canonical, which is what a
|
||||
pre-commit hook or a make target calls.
|
||||
|
||||
` + "`kettle init --interactive`" + ` offers to register the --hook form in
|
||||
.claude/settings.json. It is offered rather than assumed: this is one
|
||||
repository's documentation convention, and a project that does not keep AGENTS.md
|
||||
files wants nothing to do with it.`,
|
||||
Examples: []Example{
|
||||
{"kettle mirror", "repair the working directory and everything below it"},
|
||||
{"kettle mirror ~/code/x", "repair somewhere else"},
|
||||
{"kettle mirror --check", "exit 1 if anything is out of place; write nothing"},
|
||||
{"kettle mirror --hook", "the PreToolUse form; reads a payload, always exits 0"},
|
||||
},
|
||||
Setup: func(fs *flag.FlagSet) func([]string) error {
|
||||
check := fs.Bool("check", false, "write nothing, exit 1 if the tree is not canonical")
|
||||
hook := fs.Bool("hook", false, "PreToolUse form: payload on stdin, report as additionalContext, always exit 0")
|
||||
quiet := fs.Bool("quiet", false, "repair without printing what was repaired")
|
||||
|
||||
return func(args []string) error {
|
||||
if len(args) > 1 {
|
||||
return Fail("give one directory, or none for the working directory")
|
||||
}
|
||||
explicit := ""
|
||||
if len(args) == 1 {
|
||||
explicit = args[0]
|
||||
}
|
||||
if *hook {
|
||||
runHook(explicit)
|
||||
return nil
|
||||
}
|
||||
|
||||
root, err := mirrorRoot(explicit, "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var res mirror.Result
|
||||
if *check {
|
||||
res = mirror.Check(root)
|
||||
} else {
|
||||
res = mirror.Sync(root)
|
||||
}
|
||||
|
||||
if !*quiet {
|
||||
printMirror(os.Stdout, res, *check)
|
||||
}
|
||||
// A conflict is a state a person has to resolve, so --check
|
||||
// reports it as a failure. A repair run says so and carries on:
|
||||
// the six branches it could fix, it fixed.
|
||||
if *check && !res.Clean() {
|
||||
return SilentError{Code: 1}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// mirrorRoot decides which tree to walk.
|
||||
//
|
||||
// An explicit argument wins, then the harness's own idea of the project, then
|
||||
// the working directory. project.Root is deliberately NOT consulted: this
|
||||
// command has nothing to do with issues and must be usable in a tree that has
|
||||
// never seen `kettle init`.
|
||||
func mirrorRoot(explicit, payloadCWD string) (string, error) {
|
||||
for _, candidate := range []string{explicit, os.Getenv("CLAUDE_PROJECT_DIR"), payloadCWD} {
|
||||
if candidate == "" {
|
||||
continue
|
||||
}
|
||||
abs, err := filepath.Abs(candidate)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if fi, err := os.Stat(abs); err == nil && fi.IsDir() {
|
||||
return abs, nil
|
||||
}
|
||||
if candidate == explicit {
|
||||
return "", Fail("%s is not a directory", explicit)
|
||||
}
|
||||
}
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return wd, nil
|
||||
}
|
||||
|
||||
func printMirror(w io.Writer, res mirror.Result, check bool) {
|
||||
prefix := ""
|
||||
if check {
|
||||
prefix = "would: "
|
||||
}
|
||||
for _, line := range res.Fixes {
|
||||
fmt.Fprintln(w, prefix+line)
|
||||
}
|
||||
for _, line := range res.Conflicts {
|
||||
fmt.Fprintln(w, "conflict: "+line)
|
||||
}
|
||||
if res.Clean() {
|
||||
fmt.Fprintln(w, "every AGENTS.md has its CLAUDE.md symlink — nothing to do")
|
||||
}
|
||||
}
|
||||
|
||||
// runHook is the PreToolUse form, and its whole contract is that it cannot fail.
|
||||
//
|
||||
// Every path here returns normally and the caller exits 0: an unreadable
|
||||
// payload, an unwritable tree, a bug in this function. Documentation maintenance
|
||||
// is not permitted to break somebody's build, so silence is the failure mode and
|
||||
// a report is the only output.
|
||||
func runHook(explicit string) {
|
||||
// The one recover in the tree, and it earns its place: this function runs
|
||||
// before every Bash call in every project the hook is registered in, and a
|
||||
// panic here would surface as a failed tool call rather than as a bug in a
|
||||
// documentation helper.
|
||||
defer func() { _ = recover() }()
|
||||
|
||||
var payload hookPayload
|
||||
if raw, err := io.ReadAll(os.Stdin); err == nil && len(raw) > 0 {
|
||||
_ = json.Unmarshal(raw, &payload)
|
||||
}
|
||||
|
||||
root, err := mirrorRoot(explicit, payload.CWD)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
res := mirror.Sync(root)
|
||||
if res.Clean() {
|
||||
return // silence means the tree was already canonical
|
||||
}
|
||||
|
||||
var parts []string
|
||||
if len(res.Fixes) > 0 {
|
||||
parts = append(parts, "kettle mirror fixed:\n "+strings.Join(res.Fixes, "\n "))
|
||||
}
|
||||
if len(res.Conflicts) > 0 {
|
||||
parts = append(parts, "kettle mirror needs manual resolution:\n "+strings.Join(res.Conflicts, "\n "))
|
||||
}
|
||||
|
||||
var out hookOutput
|
||||
out.HookSpecificOutput.HookEventName = "PreToolUse"
|
||||
out.HookSpecificOutput.AdditionalContext = strings.Join(parts, "\n")
|
||||
if encoded, err := json.Marshal(out); err == nil {
|
||||
fmt.Println(string(encoded))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package cmd_test
|
||||
|
||||
// `kettle mirror` is the one command in the tree that has nothing to do with
|
||||
// issues, and the one that must never fail a caller. Both are tested here.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func writeDoc(t *testing.T, dir, name, body string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func linkTarget(t *testing.T, path string) string {
|
||||
t.Helper()
|
||||
target, err := os.Readlink(path)
|
||||
if err != nil {
|
||||
t.Fatalf("%s is not a symlink: %v", path, err)
|
||||
}
|
||||
return target
|
||||
}
|
||||
|
||||
// The tree it walks is the working directory, not a project: this must work in
|
||||
// a directory that has never seen `kettle init`, because the convention it
|
||||
// maintains has nothing to do with issues.
|
||||
func TestMirrorNeedsNoProject(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeDoc(t, dir, "AGENTS.md", "root\n")
|
||||
writeDoc(t, filepath.Join(dir, "cli"), "AGENTS.md", "cli\n")
|
||||
|
||||
r := mustRun(t, dir, "mirror")
|
||||
if strings.Contains(r.out(), ".kettle") {
|
||||
t.Errorf("mirror asked for a project:\n%s", r.out())
|
||||
}
|
||||
for _, sub := range []string{".", "cli"} {
|
||||
if got := linkTarget(t, filepath.Join(dir, sub, "CLAUDE.md")); got != "AGENTS.md" {
|
||||
t.Errorf("%s/CLAUDE.md points at %q, want a relative AGENTS.md", sub, got)
|
||||
}
|
||||
}
|
||||
|
||||
// Idempotent, and it says so rather than printing nothing at all.
|
||||
again := mustRun(t, dir, "mirror")
|
||||
if !strings.Contains(again.stdout, "nothing to do") {
|
||||
t.Errorf("a canonical tree did not report itself clean:\n%s", again.out())
|
||||
}
|
||||
}
|
||||
|
||||
func TestMirrorTakesADirectoryArgument(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
elsewhere := filepath.Join(dir, "elsewhere")
|
||||
writeDoc(t, elsewhere, "AGENTS.md", "there\n")
|
||||
|
||||
mustRun(t, dir, "mirror", elsewhere)
|
||||
if _, err := os.Lstat(filepath.Join(elsewhere, "CLAUDE.md")); err != nil {
|
||||
t.Errorf("the named directory was not repaired: %v", err)
|
||||
}
|
||||
|
||||
if r := run(t, dir, "mirror", filepath.Join(dir, "nowhere")); r.code == 0 {
|
||||
t.Errorf("a directory that is not there must be refused:\n%s", r.out())
|
||||
}
|
||||
}
|
||||
|
||||
func TestMirrorCheckWritesNothingAndFailsLoudly(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeDoc(t, dir, "AGENTS.md", "root\n")
|
||||
|
||||
r := run(t, dir, "mirror", "--check")
|
||||
if r.code != 1 {
|
||||
t.Fatalf("--check exited %d on a tree with work to do, want 1:\n%s", r.code, r.out())
|
||||
}
|
||||
if !strings.Contains(r.stdout, "would: ") {
|
||||
t.Errorf("--check did not say what it would do:\n%s", r.out())
|
||||
}
|
||||
if _, err := os.Lstat(filepath.Join(dir, "CLAUDE.md")); err == nil {
|
||||
t.Error("--check wrote to the tree it was asked about")
|
||||
}
|
||||
|
||||
mustRun(t, dir, "mirror")
|
||||
if r := run(t, dir, "mirror", "--check"); r.code != 0 {
|
||||
t.Errorf("--check exited %d on a canonical tree:\n%s", r.code, r.out())
|
||||
}
|
||||
}
|
||||
|
||||
// The refusal, end to end. One of these two files is somebody's writing and no
|
||||
// rule in this binary knows which, so both survive and the operator is told.
|
||||
func TestMirrorRefusesTwoDifferentRealFiles(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeDoc(t, dir, "AGENTS.md", "mine\n")
|
||||
writeDoc(t, dir, "CLAUDE.md", "theirs\n")
|
||||
|
||||
r := mustRun(t, dir, "mirror")
|
||||
if !strings.Contains(r.stdout, "conflict:") || !strings.Contains(r.stdout, "merge manually") {
|
||||
t.Errorf("the conflict was not reported:\n%s", r.out())
|
||||
}
|
||||
if got := readFile(t, filepath.Join(dir, "AGENTS.md")); got != "mine\n" {
|
||||
t.Errorf("AGENTS.md was changed: %q", got)
|
||||
}
|
||||
if got := readFile(t, filepath.Join(dir, "CLAUDE.md")); got != "theirs\n" {
|
||||
t.Errorf("CLAUDE.md was changed: %q", got)
|
||||
}
|
||||
// A repair run reports the conflict and still exits 0 — the six branches it
|
||||
// could fix, it fixed. --check is the one that turns it into a failure.
|
||||
if r := run(t, dir, "mirror", "--check"); r.code != 1 {
|
||||
t.Errorf("--check exited %d on a conflict, want 1", r.code)
|
||||
}
|
||||
}
|
||||
|
||||
// The hook form's whole contract: it cannot fail a Bash call. Every one of these
|
||||
// is a payload or a state that could plausibly arrive, and every one exits 0.
|
||||
func TestMirrorHookAlwaysExitsZero(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
stdin string
|
||||
setup func(t *testing.T, dir string)
|
||||
}{
|
||||
{name: "no payload at all", stdin: ""},
|
||||
{name: "a payload that is not JSON", stdin: "not json at all"},
|
||||
{name: "an empty object", stdin: "{}"},
|
||||
{name: "a payload with keys it does not know", stdin: `{"cwd":".","tool_name":"Bash","future":{"x":1}}`},
|
||||
{
|
||||
name: "a tree it cannot resolve",
|
||||
stdin: `{"cwd":"/nowhere/at/all"}`,
|
||||
setup: func(t *testing.T, dir string) { writeDoc(t, dir, "AGENTS.md", "root\n") },
|
||||
},
|
||||
{
|
||||
name: "a conflict it must not resolve",
|
||||
stdin: `{}`,
|
||||
setup: func(t *testing.T, dir string) {
|
||||
writeDoc(t, dir, "AGENTS.md", "mine\n")
|
||||
writeDoc(t, dir, "CLAUDE.md", "theirs\n")
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if tc.setup != nil {
|
||||
tc.setup(t, dir)
|
||||
}
|
||||
r := runWith(t, dir, nil, tc.stdin, "mirror", "--hook")
|
||||
if r.code != 0 {
|
||||
t.Errorf("exited %d — a documentation helper may not break a Bash call:\n%s", r.code, r.out())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// What it says when it did something, and what it says when it did not.
|
||||
func TestMirrorHookReportsOnlyWhenThereIsSomethingToSay(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeDoc(t, dir, "AGENTS.md", "root\n")
|
||||
|
||||
r := runWith(t, dir, nil, "{}", "mirror", "--hook")
|
||||
var out struct {
|
||||
HookSpecificOutput struct {
|
||||
HookEventName string `json:"hookEventName"`
|
||||
AdditionalContext string `json:"additionalContext"`
|
||||
} `json:"hookSpecificOutput"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(r.stdout), &out); err != nil {
|
||||
t.Fatalf("the hook did not emit JSON: %v\n%s", err, r.out())
|
||||
}
|
||||
if out.HookSpecificOutput.HookEventName != "PreToolUse" {
|
||||
t.Errorf("hookEventName is %q", out.HookSpecificOutput.HookEventName)
|
||||
}
|
||||
if !strings.Contains(out.HookSpecificOutput.AdditionalContext, "CLAUDE.md") {
|
||||
t.Errorf("the report says nothing about what it did:\n%s", out.HookSpecificOutput.AdditionalContext)
|
||||
}
|
||||
|
||||
// Silence means the tree was already canonical. A hook that spoke on every
|
||||
// Bash call would be noise in every transcript.
|
||||
quiet := runWith(t, dir, nil, "{}", "mirror", "--hook")
|
||||
if strings.TrimSpace(quiet.stdout) != "" {
|
||||
t.Errorf("a canonical tree still produced output:\n%s", quiet.stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// CLAUDE_PROJECT_DIR is the harness's own answer to "which tree", and it wins
|
||||
// over the payload's cwd — a Bash call made from a subdirectory must still
|
||||
// repair the whole project rather than the corner it was made in.
|
||||
func TestMirrorHookPrefersTheProjectDirectory(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
sub := filepath.Join(dir, "deep", "inside")
|
||||
writeDoc(t, dir, "AGENTS.md", "root\n")
|
||||
writeDoc(t, sub, "AGENTS.md", "inside\n")
|
||||
|
||||
r := runWith(t, sub, []string{"CLAUDE_PROJECT_DIR=" + dir}, `{"cwd":"`+sub+`"}`, "mirror", "--hook")
|
||||
if r.code != 0 {
|
||||
t.Fatalf("exited %d:\n%s", r.code, r.out())
|
||||
}
|
||||
if _, err := os.Lstat(filepath.Join(dir, "CLAUDE.md")); err != nil {
|
||||
t.Errorf("the project root was not repaired: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package cmd
|
||||
|
||||
// The seam between the registry and the documents written from it. Both halves
|
||||
// are in this package's reach, so it is asserted here rather than inferred from
|
||||
// a generated file downstream.
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.noodles.cam/claude-skills/marketplace/cli/internal/scaffold"
|
||||
)
|
||||
|
||||
// A group with no document is a group whose flag table is written nowhere, and
|
||||
// nothing would say so: gen walks the documents, not the registry, so the
|
||||
// commands would simply be absent. This is the test that makes adding a group a
|
||||
// two-step change rather than a silent one-step mistake.
|
||||
func TestEveryGroupHasSomewhereToBeWritten(t *testing.T) {
|
||||
inRegistry := map[string]bool{}
|
||||
for _, c := range Commands() {
|
||||
if c.Group == "" {
|
||||
t.Errorf("command %q has no group, so it is in no document at all", c.Name)
|
||||
continue
|
||||
}
|
||||
inRegistry[c.Group] = true
|
||||
}
|
||||
|
||||
for _, g := range scaffold.Groups() {
|
||||
if !inRegistry[g] {
|
||||
t.Errorf("scaffold ships a document for group %q, which no command is in", g)
|
||||
}
|
||||
}
|
||||
for g := range inRegistry {
|
||||
if scaffold.PathFor(g) == "" {
|
||||
t.Errorf("group %q has commands and no document — add one to internal/scaffold/assets", g)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Every document renders, and the flag table inside it is this binary's. A
|
||||
// command whose Long text spelled a region marker out in full would end the
|
||||
// generated block inside itself, and renderAll is where that is caught.
|
||||
func TestEveryDocumentRendersWithItsOwnFlags(t *testing.T) {
|
||||
files, err := renderAll()
|
||||
if err != nil {
|
||||
t.Fatalf("rendering the tree failed: %v", err)
|
||||
}
|
||||
if len(files) != len(scaffold.Files()) {
|
||||
t.Fatalf("rendered %d of %d documents", len(files), len(scaffold.Files()))
|
||||
}
|
||||
|
||||
for _, f := range files {
|
||||
if f.Group == "" {
|
||||
continue
|
||||
}
|
||||
for _, c := range commandsIn(f.Group) {
|
||||
if !strings.Contains(f.Body, "## `"+c.Usage()+"`") {
|
||||
t.Errorf("%s does not document `%s`", f.Path, c.Usage())
|
||||
}
|
||||
for _, flag := range c.Flags() {
|
||||
if !strings.Contains(f.Body, "| `--"+flag.Name+"` |") {
|
||||
t.Errorf("%s documents `%s` without --%s", f.Path, c.Name, flag.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
if strings.Contains(f.Body, genOpen+"\n"+genOpen) {
|
||||
t.Errorf("%s has a doubled marker", f.Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Rendering twice produces the same bytes. Everything downstream — --check, the
|
||||
// idempotence of init, a diff in somebody's repository — is built on it.
|
||||
func TestRenderingIsDeterministic(t *testing.T) {
|
||||
a, err := renderAll()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := renderAll()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(a) != len(b) {
|
||||
t.Fatalf("two renders produced %d and %d documents", len(a), len(b))
|
||||
}
|
||||
for i := range a {
|
||||
if a[i].Path != b[i].Path {
|
||||
t.Fatalf("document %d is %s then %s", i, a[i].Path, b[i].Path)
|
||||
}
|
||||
if a[i].Body != b[i].Body {
|
||||
t.Errorf("%s differs between two renders", a[i].Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The guess the wizard offers for --repo. It is worth exactly what it costs —
|
||||
// a file read — so anything it cannot make sense of must answer "" and let the
|
||||
// operator type it, rather than proposing half an address.
|
||||
func TestOwnerNameReadsTheSpellingsGitActuallyWrites(t *testing.T) {
|
||||
cases := []struct{ url, want string }{
|
||||
{"git@git.example.com:claude-skills/marketplace.git", "claude-skills/marketplace"},
|
||||
{"git@git.example.com:claude-skills/marketplace", "claude-skills/marketplace"},
|
||||
{"https://git.example.com/claude-skills/marketplace.git", "claude-skills/marketplace"},
|
||||
{"https://git.example.com/claude-skills/marketplace", "claude-skills/marketplace"},
|
||||
{"ssh://git@git.example.com:2222/claude-skills/marketplace.git", "claude-skills/marketplace"},
|
||||
{" https://git.example.com/owner/name.git ", "owner/name"},
|
||||
// Deeper paths: a Gitea instance served under a prefix still ends in
|
||||
// owner/name, and the last two elements are the address.
|
||||
{"https://example.com/git/owner/name.git", "owner/name"},
|
||||
// Nothing that can be read as an address.
|
||||
{"", ""},
|
||||
{"https://git.example.com/", ""},
|
||||
{"https://git.example.com/lonely", ""},
|
||||
{"/a/local/path", "local/path"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
if got := ownerName(tc.url); got != tc.want {
|
||||
t.Errorf("ownerName(%q) = %q, want %q", tc.url, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The document list is stable and sorted, which is what makes a receipt from one
|
||||
// machine comparable with a receipt from another.
|
||||
func TestScaffoldFilesAreSorted(t *testing.T) {
|
||||
files := scaffold.Files()
|
||||
paths := make([]string, len(files))
|
||||
for i, f := range files {
|
||||
paths[i] = f.Path
|
||||
}
|
||||
if !sort.StringsAreSorted(paths) {
|
||||
t.Errorf("the document list is not sorted: %v", paths)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// mirrorHookCommand is what gets registered on PreToolUse(Bash).
|
||||
//
|
||||
// The `command -v` guard is not decoration. This line outlives the binary that
|
||||
// wrote it: an operator who uninstalls kettle, or moves it off PATH, would
|
||||
// otherwise get a "command not found" on every Bash call in this project, from a
|
||||
// hook they set up months ago and have long stopped thinking about. The guard
|
||||
// makes the failure mode silence.
|
||||
const mirrorHookCommand = `command -v kettle >/dev/null && kettle mirror --hook || true`
|
||||
|
||||
// mirrorHookSnippet is what an operator is shown when the merge is not this
|
||||
// command's to make.
|
||||
const mirrorHookSnippet = `{
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{ "type": "command", "command": "` + mirrorHookCommand + `" }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}`
|
||||
|
||||
// errSettingsExist means the file is there, does not hold the hook, and merging
|
||||
// it is a decision rather than a step.
|
||||
var errSettingsExist = errors.New("settings file already exists")
|
||||
|
||||
// settingsPath is `<out>/settings.json` — the shared file, not
|
||||
// settings.local.json. The convention this registers is a property of a
|
||||
// repository rather than of one developer's checkout, so it belongs in the file
|
||||
// that is committed.
|
||||
func settingsPath(out string) string { return filepath.Join(out, "settings.json") }
|
||||
|
||||
// writeMirrorHook registers the PreToolUse hook, and refuses to rewrite a file
|
||||
// it did not create.
|
||||
//
|
||||
// Three outcomes, and the third is the interesting one:
|
||||
//
|
||||
// - no file: it is written, hook and all.
|
||||
// - a file already holding a `kettle mirror` hook: nothing happens.
|
||||
// - a file holding something else: REFUSED unless force, and the snippet is
|
||||
// printed for the operator to paste.
|
||||
//
|
||||
// That refusal is deliberate and is the only reason this file is not a dozen
|
||||
// lines shorter. settings.json is a file the operator owns and commits, and Go's
|
||||
// encoding/json cannot preserve key order — so any merge reformats the whole
|
||||
// document, and an operator who asked for a documentation hook would find an
|
||||
// unrelated diff across a file they share with their team. A snippet they paste
|
||||
// costs them ten seconds; a reformat costs them a review.
|
||||
func writeMirrorHook(out string, force, dryRun bool) (string, error) {
|
||||
path := settingsPath(out)
|
||||
rel := filepath.Join(filepath.Base(out), "settings.json")
|
||||
|
||||
raw, err := os.ReadFile(path)
|
||||
switch {
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
if dryRun {
|
||||
return fmt.Sprintf("created %s (PreToolUse: kettle mirror --hook)", rel), nil
|
||||
}
|
||||
if err := writeFile(path, mirrorHookSnippet+"\n"); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("created %s (PreToolUse: kettle mirror --hook)", rel), nil
|
||||
|
||||
case err != nil:
|
||||
return "", err
|
||||
}
|
||||
|
||||
var settings map[string]any
|
||||
if err := json.Unmarshal(raw, &settings); err != nil {
|
||||
return "", Fail("%s is not readable as JSON (%v) — fix it, or add the hook by hand:\n\n%s", path, err, mirrorHookSnippet)
|
||||
}
|
||||
if strings.Contains(string(raw), "kettle mirror") {
|
||||
return "", nil // already registered; nothing to do and nothing to say
|
||||
}
|
||||
if !force {
|
||||
return "", fmt.Errorf("%w: %s. Add this to it, or re-run with --force-settings to have kettle merge it (which reformats the file):\n\n%s",
|
||||
errSettingsExist, path, mirrorHookSnippet)
|
||||
}
|
||||
|
||||
merged, err := mergeMirrorHook(settings)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if dryRun {
|
||||
return fmt.Sprintf("merged the hook into %s (reformatting it)", rel), nil
|
||||
}
|
||||
body, err := json.MarshalIndent(merged, "", " ")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := writeFile(path, string(body)+"\n"); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("merged the hook into %s (reformatting it)", rel), nil
|
||||
}
|
||||
|
||||
// mergeMirrorHook appends the hook to whatever PreToolUse already holds,
|
||||
// creating the path if it is not there. Nothing existing is removed or
|
||||
// reordered — what is lost is key order, which JSON does not carry, and that
|
||||
// is the whole reason this is behind a flag.
|
||||
func mergeMirrorHook(settings map[string]any) (map[string]any, error) {
|
||||
if settings == nil {
|
||||
settings = map[string]any{}
|
||||
}
|
||||
hooks, _ := settings["hooks"].(map[string]any)
|
||||
if hooks == nil {
|
||||
hooks = map[string]any{}
|
||||
}
|
||||
pre, _ := hooks["PreToolUse"].([]any)
|
||||
pre = append(pre, map[string]any{
|
||||
"matcher": "Bash",
|
||||
"hooks": []any{
|
||||
map[string]any{"type": "command", "command": mirrorHookCommand},
|
||||
},
|
||||
})
|
||||
hooks["PreToolUse"] = pre
|
||||
settings["hooks"] = hooks
|
||||
return settings, nil
|
||||
}
|
||||
Reference in New Issue
Block a user