@sabaiway/agent-workflow-kit 7.1.0 → 7.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,59 @@ Semantically versioned ([semver](https://semver.org)), newest first. The `versio
4
4
  is the current release. `upgrade` mode reads a project's `docs/ai/.workflow-version` and applies
5
5
  every `migrations/<version>-<slug>.md` newer than it, in semver order.
6
6
 
7
+ ## 7.2.0 — `.mcp.json` joins the hidden-mode footprint, and a worktree never owns it (AD-111)
8
+
9
+ 7.0.0 taught the kit to register its MCP server. It did not teach hidden mode about the file that
10
+ registration writes — so a hidden deployment that ran `/agent-workflow-kit mcp` left `.mcp.json`
11
+ sitting in `git status`, one `git add -A` away from a commit. That is exactly the leak the footprint
12
+ registry exists to prevent, and it shipped anyway.
13
+
14
+ - **`/.mcp.json` is in `KIT_OWN_PATHS`.** It joins `/.claude/settings.json` as a SHARED container the
15
+ kit merges into rather than owns, on the same terms: the tracked→ASK arm means a project that
16
+ already commits its own registration is asked, never silently un-tracked. Candidacy is
17
+ unconditional on purpose — the path is CONSIDERED before a later `mcp --apply` writes the file
18
+ rather than only after it appears, and is then hidden, dropped as already covered by a tracked
19
+ `.gitignore`, or surfaced as an ASK. That is what removes the follow-up reconcile the bug depended
20
+ on. The `contracts.md` prose mirror names it.
21
+ - **A worktree is never HANDED one, and never owns one.** The scope is the untracked lanes this tool
22
+ drives — the registry copy set and `--include`; a TRACKED `.mcp.json` still arrives with
23
+ `git worktree add`, because that is the checkout, not a copy. One frozen never-provisioned set,
24
+ read at three sites because each needs it for a different reason: the copy set would hand a
25
+ satellite a launcher pinned to a path consented for the MAIN checkout; the containment sweep would
26
+ STOP the whole provision on an escaping symlink at that path (a device-node mask realpaths inside
27
+ the repo and reaches the later special-file refusal instead); and `registryRoots` decides what
28
+ `cleanup` may REMOVE. That third one was measured — without the guard, `cleanup` on a landed
29
+ worktree carrying a satellite's own `.mcp.json` exited 0 and took the file with it. `--include` is
30
+ refused pre-mutation for the same paths: it is the one door that bypasses the copy set, and it
31
+ would have recorded the launcher as ours.
32
+ - **A settings copy this tool wrote never enables a server the worktree cannot declare.** The
33
+ guarantee is exactly that narrow. `.claude/settings.json` rides `REBASE_TARGETS` into a worktree
34
+ carrying `enabledMcpjsonServers`, which `mcp.md` itself calls a client error on every startup. An
35
+ untracked copy still equal to MAIN loses our enable and our two derived allow rules — and ONLY
36
+ those; every foreign server, rule and key survives, as do the file's EOL and the order of its
37
+ non-index keys (`withoutRegistration`, the token-removal complement of `mergeSettings`, not its
38
+ exact inverse — a JSON round-trip still hoists integer-like keys, as JS object semantics require).
39
+ **Where a rewrite would LOSE something the kit does not own, it is refused whole and says why.**
40
+ Three ways, each detected before anything is written: a number past double precision comes back a
41
+ different value; a duplicate key at any depth collapses to the last one (both found on the source
42
+ TEXT, because after the parse the evidence is gone); and invalid UTF-8 would become U+FFFD, so both
43
+ rewriting lanes — the pin rebase and the token strip — decode with FATAL UTF-8 and refuse
44
+ separately. The MAIN-equality proof compares BYTES, with the BOM preserved through the decode, so
45
+ a BOM-carrying original and a BOM-less copy can never pass for the same file.
46
+ The rewrite is admitted by ONE positive conjunction — untracked, bytes still MAIN's or their
47
+ rebased form, and a launcher proven ABSENT — so a tracked or user-modified settings file keeps its
48
+ registration tokens on purpose, as does one standing beside a launcher that is present or that
49
+ cannot be read. Those states get a neutral line naming the tokens; orphanhood is only CLAIMED where
50
+ it is proven.
51
+ - **All three output arms name the reconcile.** Applied, masked hand-off, and already-registered —
52
+ the last one matters most, because a deployment registered under 7.0.0 learns about the reconcile
53
+ on its next run. A settings write that fails after the entry landed carries the note too: that
54
+ path never reaches the report, and it strands a standing registration.
55
+
56
+ **Known residual, stated:** a VISIBLE deployment still commits a launcher carrying an absolute
57
+ machine path. The fix is not symmetric with hidden mode — a visible `.mcp.json` may legitimately hold
58
+ a team's own committable servers — so it is its own queued decision, not a line in this release.
59
+
7
60
  ## 7.1.0 — `fold-scope`: the fold channel gets a checker that refuses a claim whose reference does not resolve (AD-110)
8
61
 
9
62
  The engine canon now asks every finding to NAME the invariant its fix enforces before the edit
package/SKILL.md CHANGED
@@ -3,7 +3,7 @@ name: agent-workflow-kit
3
3
  description: Deploy or upgrade a portable AI-agent memory-and-workflow system in any project. Use when the user wants to bootstrap `docs/ai/` + an entry-point `AGENTS.md` (+ `CLAUDE.md` alias) + cap/archive/index enforcement in a new or existing repo, set up the Memory Map and session protocols, install the docs-rotation pre-commit hook, or run `/agent-workflow-kit` / `/agent-workflow-kit upgrade`. Triggers on phrases like "set up the memory system", "deploy the AI workflow here", "bootstrap docs/ai", "upgrade the workflow".
4
4
  disable-model-invocation: true
5
5
  metadata:
6
- version: '7.1.0'
6
+ version: '7.2.0'
7
7
  ---
8
8
 
9
9
  # agent-workflow-kit
package/capability.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "schema": 1,
4
4
  "name": "agent-workflow-kit",
5
5
  "kind": "composition-root",
6
- "version": "7.1.0",
6
+ "version": "7.2.0",
7
7
  "provides": [],
8
8
  "roles": {},
9
9
  "detect": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sabaiway/agent-workflow-kit",
3
- "version": "7.1.0",
3
+ "version": "7.2.0",
4
4
  "description": "Portable, cross-agent memory & workflow for AI coding agents — Claude Code, Codex, Cursor, Devin Desktop. One command deploys an AGENTS.md entry point + docs/ai context with cap/archive/index enforcement into any repo.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -42,7 +42,7 @@ diverge:
42
42
  | `/.aider.input.history` | Aider | file | no | input history |
43
43
  | `/.continue/` | Continue | dir | no | project config dir |
44
44
 
45
- The kit's OWN footprint (`KIT_OWN_PATHS`) — `AGENTS.md`, `CLAUDE.md`, `docs/ai/` (subsumes the stamp), the added `scripts/*.mjs`, `docs/plans/`, `.claude/settings.local.json`, and `.claude/settings.json` (hidden-only — visible mode commits it) — is always a candidate in hidden mode.
45
+ The kit's OWN footprint (`KIT_OWN_PATHS`) — `AGENTS.md`, `CLAUDE.md`, `docs/ai/` (subsumes the stamp), the added `scripts/*.mjs`, `docs/plans/`, `.claude/settings.local.json`, `.claude/settings.json` (hidden-only — visible mode commits it), and `.mcp.json` (the `mcp` mode's registration; hidden-only for the same reason, and it carries an absolute machine path) — is always a candidate in hidden mode.
46
46
 
47
47
  Not in this version: a fully-external hidden mode (artifacts relocated outside the repo tree).
48
48
  Deferred to a later release + migration.
@@ -17,6 +17,8 @@ Run `node ${CLAUDE_SKILL_DIR}/tools/mcp.mjs [--dry-run | --apply] [--cwd <dir>]`
17
17
  2. **Ask consent** via **`AskUserQuestion` where supported**, the no-change option first: keep the shell lanes, or register the typed channel — presenting the trust posture above in plain language.
18
18
  3. **Only on an explicit yes**, re-run with `--apply`. It writes **`.mcp.json` FIRST, then `.claude/settings.json`** — settings that enable a server whose entry is not yet there is a client error on every startup. Both writes are merge-don't-clobber (foreign servers, foreign keys and existing allow rules preserved; a re-apply adds nothing twice) and keep each file's existing EOL. New MCP servers are picked up when the client next starts — unlike the `hook` mode, this is not a hot reload.
19
19
 
20
+ 4. **Hidden-mode deployments:** after apply, run the hide-footprint reconcile (`node ${CLAUDE_SKILL_DIR}/tools/hide-footprint.mjs --dir <project> --reconcile`) so the registration stays invisible to `git status` — `/.mcp.json` is in the known-footprint registry; every output arm reminds you.
21
+
20
22
  **The two arms that are not a write:**
21
23
 
22
24
  - **DIFFERING** — `.mcp.json` already carries an `"agent-workflow"` entry that **structurally differs** from ours (another kit copy, a hand-edited path, an added `env`, a `null`). The comparison is deliberately key-order-independent, so a re-serialized identical entry is the SAME registration, while any real difference in what would be launched is a difference. The run **STOPs unwritten, on both lanes**: silently changing what an MCP server launches is exactly what consent must not slide past. The recovery is named — review that entry, then remove or rename it and re-run. The kit never resolves this for you.
@@ -14,10 +14,25 @@ The ONE stored-metadata exception is the PREPARED OID recorded in the handoff: l
14
14
  Git ≥ 2.36 is required for NUL-terminated worktree porcelain; an older Git fails closed with its
15
15
  own verbatim error through the existing Git-error surface.
16
16
 
17
+ **The MCP registration is never HANDED to a worktree, and never owned by one.** The scope is the
18
+ untracked lanes this tool drives — the registry copy set and `--include` (refused pre-mutation, and
19
+ a recorded include from an older handoff is filtered out too); a TRACKED `.mcp.json` still arrives
20
+ with `git worktree add`, because that is the checkout, not a copy. `/.mcp.json` names an absolute
21
+ machine path and its consent is per checkout, so it is excluded from the copy set, from the provision
22
+ containment sweep, and from what `cleanup` may remove — a satellite's own `.mcp.json` therefore stays
23
+ classified as foreign work and blocks cleanup, rather than being deleted as ours. The settings half
24
+ is rewritten only under ONE conjunction of proven facts: untracked, bytes still MAIN's (or their
25
+ rebased form), and a launcher proven ABSENT — then the copy loses our `enabledMcpjsonServers`
26
+ membership and our two derived allow rules and nothing else. Every other state keeps its registration
27
+ TOKENS — not necessarily its bytes, since `rebasePins` may still rewrite absolute pins in that same
28
+ file on its own lane — and, where the settings file is readable, well-formed and actually carries
29
+ tokens, gets a neutral line naming them; orphanhood is claimed only where it is proven.
30
+
17
31
  - `provision <slug> --plan <path> [--as <name>.md] [--dir <path>] [--branch <name>] [--include <path>]... [--install] [--resume]`
18
32
  — create a feature worktree (default: the visible sibling `<repoParent>/<repoName>--<slug>`,
19
33
  branch `aw/<slug>`) and populate it: the registry-derived footprint copy-if-missing (a tracked
20
- file is NEVER overwritten), EXACTLY ONE seeded feature plan, the `handoff-<slug>.md` stub
34
+ file is NEVER overwritten, and `/.mcp.json` is never copied or owned — see below), EXACTLY ONE seeded
35
+ feature plan, the `handoff-<slug>.md` stub
21
36
  (written at provision — the tool's own record; `list` and `cleanup` read it), a
22
37
  `node_modules` symlink when main has one and the link stays ignored — a SHARED MUTABLE cache:
23
38
  writes through it hit MAIN's node_modules; for isolation RUN the printed isolated-install
@@ -81,6 +81,7 @@ Apply these when authoring a plan, reviewing, folding a finding, or editing code
81
81
  - **No code-mechanics in the plan.** A ledger row carries its path and anchor, and Verification carries the exact commands (the plan-shape canon) — checked syntax: the plan's own Verification runs them against an explicit expected outcome or gate; the only other syntax a plan may carry is a literal fixture/schema fragment a named test copies or validates. Un-run, logic-bearing syntax — control-flow, a regex, a glob, a grammar, an algorithm body, a mini-DSL — never lives in plan prose, however plausible or shell-verified it looks: a fold or draft that wants one is the trigger to write the test instead.
82
82
  - **Test-as-spec.** Fold a code-touching finding into a red→green TEST, not a prose paragraph — the gate is the only deterministic checker; a paragraph cannot self-check.
83
83
  - **Characterize-first.** Before editing UNCOVERED code, pin its current behavior in a green test, then edit — any unintended change goes red. Never edit what has no checker; first give it one. Keep edits atomic/reversible; prefer SUBTRACTIVE folds.
84
+ - **State table BEFORE the guard — enumerate by PROOF, never by exclusion.** The subtraction rule above fires on a repeat finding, which is a LATE signal: by then the review has paid for each miss. The EARLY signal is structural — a decision whose input has **several independent state dimensions** (is it tracked? do the bytes still match the source? does the neighbouring file exist?). Write the table first, admit the write with **ONE conjunction of proven facts**, and funnel every other cell into a single refusal; the table is then the table-driven test. An exclusion list (`if (bad1) return; if (bad2) return;`) fails **OPEN** on the first state nobody enumerated — and "unreadable" is a state, distinct from "absent". A reviewer cannot save you here: it judges the patch in front of it and can only name the NEXT missing state, one round at a time.
84
85
  - **Fold minimally — prose has no checker.** An ephemeral, gitignored plan is prose with no executable checker; fold **minimally, in ONE place** and run a **self-consistency** read across the plan before every re-review — a fold that drifts several prose spots is what turns a 2-round review into churn.
85
86
  - **Heavy review at the diff.** Plan-review settles architecture only (≤2 rounds, stop at the pre-existing→fold-induced crossover); the exhaustive per-row review runs against real compiling code + the full suite, where a regression fails a gate immediately. **Backend divergence** (one backend grounded-ships while another keeps revising mechanics) IS that crossover — resolve at altitude, don't exhaust the strictest backend; route an all-mechanics/CI or prose-only artifact to a **thin plan + diff-review**.
86
87
  - **Convergence bar.** A review loop is CLEAN only when one round returns **0 blockers + 0 majors** from EVERY backend the recipe names (nits + a ship verdict is the stop). Folding ≠ convergence — re-review after folding.
@@ -33,7 +33,12 @@ export const stop = (message, fields = {}) =>
33
33
  // may have unrelated scripts). `/.claude/settings.json` is carried HIDDEN-ONLY: in hidden mode the
34
34
  // kit's own attribution file is a footprint; in visible mode the kit commits it and never runs this
35
35
  // tool. It passes the same tracked→ASK classifier, so a project that already commits it gets an ASK,
36
- // never a silent un-track. `/docs/plans/` + both `.claude/settings*.json` are listed because a pure
36
+ // never a silent un-track. `/.mcp.json` (the `mcp` mode's registration) is the second shared
37
+ // container carried on those terms — the kit merges into it and preserves foreign servers, so the
38
+ // same tracked→ASK arm is what protects a team that commits its own. It is seated here rather than
39
+ // in KNOWN_FOOTPRINT deliberately: KIT_OWN candidacy is unconditional, so the path is in the block
40
+ // BEFORE a later `mcp --apply` writes the file — present-only candidacy would re-open the very
41
+ // follow-up-reconcile gap this entry closes. Never provisioned into a worktree (worktrees.mjs). `/docs/plans/` + both `.claude/settings*.json` are listed because a pure
37
42
  // hidden deploy has no tracked `.gitignore`; the classifier drops any candidate a tracked `.gitignore`
38
43
  // already covers, so in a repo that DOES track those ignores they are never re-written.
39
44
  // The enumeration must cover EVERY file the deploy copies into `scripts/` (bootstrap step 8 copies
@@ -67,6 +72,7 @@ export const KIT_OWN_PATHS = [
67
72
  '/docs/plans/',
68
73
  '/.claude/settings.local.json',
69
74
  '/.claude/settings.json',
75
+ '/.mcp.json',
70
76
  ];
71
77
 
72
78
  // Every OTHER tool's footprint. `falsePositiveRisk` flags a name generic/ambiguous enough that a
@@ -183,6 +183,76 @@ export const decideSettingsText = (text, allowRules) => {
183
183
  };
184
184
  };
185
185
 
186
+ // The token-removal COMPLEMENT of mergeSettings (not its exact inverse — merging into an empty file
187
+ // and removing again leaves the managed containers behind), for a settings copy moved away from its `.mcp.json`
188
+ // (a provisioned worktree: it gets no launcher, so a copied enable would be a client error on every
189
+ // client start). Removes ONLY our own tokens — our `SERVER_NAME` membership and our derived allow
190
+ // rules — and preserves every foreign server, foreign rule, foreign key and the file's EOL. Returns
191
+ // `{ text, changed, hasTokens, reason }` (the four outcomes are tabulated at the function); `text`
192
+ // is the input byte-for-byte whenever `changed` is false — this never repairs, and never edits what
193
+ // it did not understand.
194
+ // A JSON round-trip is not content-preserving for everything a file may legally carry, and this
195
+ // function rewrites a file it does NOT own — so each way the trip can lose data is detected and
196
+ // REFUSES the rewrite whole. Two are known and both are checked on the SOURCE TEXT, because after
197
+ // `JSON.parse` the evidence is already gone:
198
+ // • a number past double precision (9007199254740993 → …992) comes back a different value;
199
+ // • a duplicate key ({"a":1,"a":2}) collapses to the last one, dropping foreign data silently.
200
+ // String bodies are blanked to `""` first, so a digit run or a colon inside a string is never read
201
+ // as a number or a key. Deliberately strict on numbers: `1.0` and `1e2` are re-spellings rather
202
+ // than losses and are refused too — fail-closed is the correct direction here.
203
+ const blankStrings = (text) => text.replace(/"(?:[^"\\]|\\.)*"/g, '""');
204
+ const JSON_NUMBER = /-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][-+]?\d+)?/g;
205
+
206
+ const countKeys = (value) => (Array.isArray(value)
207
+ ? value.reduce((n, v) => n + countKeys(v), 0)
208
+ : isPlainObject(value)
209
+ ? Object.entries(value).reduce((n, [, v]) => n + 1 + countKeys(v), 0)
210
+ : 0);
211
+
212
+ // Why a COUNT: a duplicate at any depth makes the source carry more key tokens than the parsed
213
+ // value has keys. No second JSON parser, and nothing depends on where the duplicate sits.
214
+ const roundTripLoss = (text, parsed) => {
215
+ const blanked = blankStrings(text);
216
+ const numbers = blanked.match(JSON_NUMBER) ?? [];
217
+ if (!numbers.every((lit) => String(JSON.parse(lit)) === lit)) return 'a number would not survive the rewrite';
218
+ const keyTokens = (blanked.match(/""\s*:/g) ?? []).length;
219
+ if (keyTokens !== countKeys(parsed)) return 'a duplicate key would be collapsed by the rewrite';
220
+ return null;
221
+ };
222
+
223
+ // Four outcomes over `{ text, changed, hasTokens, reason }`, and a caller must be able to tell them
224
+ // apart — `changed:false` alone conflates
225
+ // "nothing of ours is here" with "ours is here and the rewrite was REFUSED", and the second one owes
226
+ // the operator a word:
227
+ // unreadable → {changed:false, hasTokens:false, reason:'…'} not JSON of the shape we write
228
+ // nothing of ours → {changed:false, hasTokens:false, reason:null}
229
+ // refused (lossy) → {changed:false, hasTokens:true, reason:'…'} tokens stay, say why
230
+ // rewritten → {changed:true, hasTokens:true, reason:null}
231
+ export const withoutRegistration = (text, allowRules = allowRulesFor()) => {
232
+ const keep = (hasTokens, reason) => ({ text, changed: false, hasTokens, reason });
233
+ const decided = decideSettingsText(text, allowRules);
234
+ if (decided.state !== STATE.PRESENT) return keep(false, 'not readable as settings JSON');
235
+ if (!decided.enabled && decided.allowPresent.length === 0) return keep(false, null);
236
+ const loss = roundTripLoss(text, decided.data);
237
+ if (loss !== null) return keep(true, loss);
238
+ const { [ENABLED_KEY]: enabledList, permissions } = decided.data;
239
+ const keptEnabled = (Array.isArray(enabledList) ? enabledList : []).filter((n) => n !== SERVER_NAME);
240
+ const keptAllow = (isPlainObject(permissions) && Array.isArray(permissions.allow) ? permissions.allow : [])
241
+ .filter((rule) => !allowRules.includes(rule));
242
+ // Only an allow array that ALREADY existed is rewritten — synthesising `allow: []` where the file
243
+ // had no such key would be adding foreign content under the name of removing ours.
244
+ const nextPermissions = isPlainObject(permissions) && Array.isArray(permissions.allow)
245
+ ? { ...permissions, allow: keptAllow }
246
+ : permissions;
247
+ // Rebuilt through the original order of the NON-INDEX keys — a settings file the user reads should
248
+ // not be reordered by a removal it did not ask for. Integer-like keys are the stated exception:
249
+ // any JSON round-trip hoists them to the front, because JS object semantics say so.
250
+ const next = Object.fromEntries(Object.entries(decided.data).map(([key, value]) => (
251
+ key === ENABLED_KEY ? [key, keptEnabled] : key === 'permissions' ? [key, nextPermissions] : [key, value]
252
+ )));
253
+ return { text: formatJson(next, decided.eol), changed: true, hasTokens: true, reason: null };
254
+ };
255
+
186
256
  // readRegistration(root, io?) → the full registration picture of ONE project. `io.serverPath`
187
257
  // overrides the running kit's server path (tests); every fs primitive in `io` is the fs-read-nofollow
188
258
  // injection contract. NEVER throws.
package/tools/mcp.mjs CHANGED
@@ -185,16 +185,35 @@ export const writeMcp = ({ cwd, dryRun = true } = {}, deps = {}) => {
185
185
  writeContainedFileAtomic(root, registration.mcpJson.abs, plan.mcpBody, deps, { stop, label: MCP_JSON_REL });
186
186
  }
187
187
  if (plan.writeSettings) {
188
- // The ONE write the preflight deliberately does not do: creating `.claude/` is a mutation, so it
189
- // belongs on the apply lane only a preview that made a directory would not be a preview.
190
- assertCreatableDirSafe(join(root, CLAUDE_DIR_REL), deps, { stop, noun: SETTINGS_REL });
191
- writeContainedFileAtomic(root, registration.settings.abs, plan.settingsBody, deps, { stop, label: SETTINGS_REL });
188
+ // A settings failure AFTER the entry landed leaves a STANDING registration on disk that never
189
+ // reaches formatResult so the reconcile note has to ride the failure too, or a hidden
190
+ // deployment is left with a visible `.mcp.json` and no mention of it anywhere.
191
+ // The catch is around the WRITE, not inside it: a raw fs error (a failing rename) never passes
192
+ // through the injected stop, and it is exactly the case that strands a standing registration.
193
+ try {
194
+ // The ONE write the preflight deliberately does not do: creating `.claude/` is a mutation, so
195
+ // it belongs on the apply lane only — a preview that made a directory would not be a preview.
196
+ assertCreatableDirSafe(join(root, CLAUDE_DIR_REL), deps, { stop, noun: SETTINGS_REL });
197
+ writeContainedFileAtomic(root, registration.settings.abs, plan.settingsBody, deps, { stop, label: SETTINGS_REL });
198
+ } catch (err) {
199
+ // Reaching here always leaves a STANDING registration on disk — either this run wrote the
200
+ // entry (`writeMcpJson`) or the preflight found it already current (`matches`), and those two
201
+ // are exhaustive, so the note is unconditional rather than guarded by a branch nothing can
202
+ // take. A differing entry never reaches the writer at all; it STOPs in the preflight.
203
+ throw Object.assign(err, { message: `${err.message}\n${HIDDEN_MODE_LINE}` });
204
+ }
192
205
  }
193
206
  return { ...base, wrote: plan.writeMcpJson || plan.writeSettings };
194
207
  };
195
208
 
196
209
  // ── the report ─────────────────────────────────────────────────────────────────────────
197
210
 
211
+ // A registration is an AI-tool footprint: `/.mcp.json` is in the known-footprint registry, so a
212
+ // HIDDEN deployment needs the reconcile before `git status` is clean again. Stated conditionally —
213
+ // this mode never detects visibility, and detecting it would widen what it reads.
214
+ const HIDDEN_MODE_LINE =
215
+ 'hidden-mode note: if this deployment is hidden, run the hide-footprint reconcile so the registration stays out of `git status` (the registry carries /.mcp.json).';
216
+
198
217
  const POSTURE_LINE =
199
218
  'trust posture: the registered server is a READ-ONLY child of your MCP client (path/type/size/line facts and literal search over this project root) — it runs OUTSIDE the Bash sandbox, as the client itself does, and exposes no write or exec API. The two allow rules make its tool calls promptless; nothing else in this project changes.';
200
219
 
@@ -229,6 +248,7 @@ const maskedReport = (result) => {
229
248
  ` merge into ${SETTINGS_REL} (that file was observable — and read where present — so this body already carries what is in it):`,
230
249
  indented(result.fragments.settings),
231
250
  POSTURE_LINE,
251
+ HIDDEN_MODE_LINE,
232
252
  ].join(LF);
233
253
  };
234
254
 
@@ -236,7 +256,7 @@ export const formatResult = (result) => {
236
256
  if (result.masked) return maskedReport(result);
237
257
  const nothingToDo = !result.plan.writeMcpJson && !result.plan.writeSettings;
238
258
  if (nothingToDo) {
239
- return [`agent-workflow MCP registration — already registered ("${SERVER_NAME}"); nothing to do.`, POSTURE_LINE].join(LF);
259
+ return [`agent-workflow MCP registration — already registered ("${SERVER_NAME}"); nothing to do.`, POSTURE_LINE, HIDDEN_MODE_LINE].join(LF);
240
260
  }
241
261
  const lines = [
242
262
  result.dryRun
@@ -247,6 +267,7 @@ export const formatResult = (result) => {
247
267
  ' the entry this registration declares (re-serialized here; the same structured value goes into the file):',
248
268
  indented(JSON.stringify(result.registration.entry, null, JSON_INDENT)),
249
269
  POSTURE_LINE,
270
+ HIDDEN_MODE_LINE,
250
271
  ];
251
272
  if (result.dryRun) lines.push(` to apply: ${applyMcpCommand(result.root)}`);
252
273
  return lines.join(LF);
@@ -16,6 +16,7 @@ import { join, dirname, basename, resolve, relative, isAbsolute, sep } from 'nod
16
16
  import { fileURLToPath } from 'node:url';
17
17
  import { spawnSync } from 'node:child_process';
18
18
  import { randomBytes } from 'node:crypto';
19
+ import { MCP_JSON_REL, SERVER_NAME, SETTINGS_REL, withoutRegistration } from './mcp-registration.mjs';
19
20
  import {
20
21
  KIT_OWN_PATHS, KNOWN_FOOTPRINT, expandGlob, normalizeSlashes, isDirPattern, isGlobPattern,
21
22
  patternToProbe,
@@ -65,6 +66,9 @@ const EXCLUDED_BASENAMES = new Set([
65
66
  ]);
66
67
  // Registry entries provision seeds by its own rules instead of copying wholesale.
67
68
  const SEEDED_SEPARATELY = new Set([`/${PLANS_REL}/`]);
69
+ // Never copied AND never owned — unlike SEEDED_SEPARATELY, whose members cleanup may still remove.
70
+ // A satellite's own `.mcp.json` must stay FOREIGN or an ordinary cleanup deletes what we never placed.
71
+ const NEVER_PROVISIONED = new Set(['/.mcp.json']);
68
72
  // Copied files whose absolute main-root pins are rebased onto the worktree root.
69
73
  const REBASE_TARGETS = Object.freeze(['docs/ai/gates.json', '.claude/settings.json', '.claude/settings.local.json']);
70
74
  const TRACKED_PIN_DECLARATION =
@@ -192,6 +196,12 @@ const readFileNoFollow = (fs, abs) => {
192
196
  }
193
197
  };
194
198
 
199
+ // Fatal UTF-8: a lossy decode would let invalid bytes become U+FFFD and pass for text we may rewrite.
200
+ // `ignoreBOM: true` KEEPS a leading BOM in the string — the default STRIPS it, which would make a
201
+ // BOM-carrying file and a BOM-less one decode identically and defeat a byte-faithful comparison.
202
+ const UTF8_STRICT = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
203
+ const decodeUtf8Strict = (buf) => { try { return UTF8_STRICT.decode(buf); } catch { return null; } };
204
+
195
205
  const NOFOLLOW_WRITE = fsC.O_WRONLY | fsC.O_CREAT | fsC.O_EXCL | (fsC.O_NOFOLLOW ?? 0);
196
206
  const COPY_BUFFER_BYTES = 64 * 1024;
197
207
 
@@ -650,7 +660,7 @@ export const provisionCopySet = (root, deps = {}) => {
650
660
  const fs = fsOf(deps);
651
661
  const out = [];
652
662
  for (const pattern of KIT_OWN_PATHS) {
653
- if (SEEDED_SEPARATELY.has(pattern)) continue;
663
+ if (SEEDED_SEPARATELY.has(pattern) || NEVER_PROVISIONED.has(pattern)) continue;
654
664
  if (isPresent(root, pattern, fs)) out.push(pattern);
655
665
  }
656
666
  for (const entry of KNOWN_FOOTPRINT) {
@@ -902,7 +912,7 @@ export const rebaseAbsolutePins = (text, mainRoot, wtRoot) => {
902
912
  const assertProvisionSourcesContained = ({ root, rootReal, fs, statFollow }) => {
903
913
  const rels = [];
904
914
  for (const pattern of [...KIT_OWN_PATHS, ...KNOWN_FOOTPRINT.map((e) => e.pattern)]) {
905
- if (SEEDED_SEPARATELY.has(pattern)) continue;
915
+ if (SEEDED_SEPARATELY.has(pattern) || NEVER_PROVISIONED.has(pattern)) continue;
906
916
  if (isGlobPattern(pattern)) {
907
917
  rels.push(...expandGlob(pattern, { dir: root, readdir: fs.readdir, stat: statFollow }).map((p) => patternToProbe(p)));
908
918
  continue;
@@ -2057,7 +2067,13 @@ const rebasePins = ({ root, wtRoot, git, fs, report, journal = NO_JOURNAL }) =>
2057
2067
  }
2058
2068
  const tracked = git(['ls-files', '--', target], wtRoot);
2059
2069
  if (tracked.status !== 0) throw stop(`git ls-files failed for ${target}: ${(tracked.stderr || tracked.stdout).trim()}`);
2060
- const text = String(cur.bytes);
2070
+ // Fatal decode BEFORE any rewrite: `String(buffer)` turns invalid bytes into U+FFFD, so a
2071
+ // rebase would silently destroy them in a file this lane only means to re-point.
2072
+ const text = decodeUtf8Strict(cur.bytes);
2073
+ if (text === null) {
2074
+ report.push(` ${target}: not valid UTF-8 — left untouched, pins not rebased`);
2075
+ continue;
2076
+ }
2061
2077
  const { text: rebased, changes } = rebaseAbsolutePins(text, root, wtRoot);
2062
2078
  if (tracked.stdout.trim() !== '') {
2063
2079
  if (changes.length > 0) report.push(` ${target}: ${TRACKED_PIN_DECLARATION}`);
@@ -2065,7 +2081,7 @@ const rebasePins = ({ root, wtRoot, git, fs, report, journal = NO_JOURNAL }) =>
2065
2081
  }
2066
2082
  if (changes.length === 0) continue;
2067
2083
  const main = readFileNoFollow(fs, join(root, target));
2068
- const mainText = main.bytes ? String(main.bytes) : null;
2084
+ const mainText = main.bytes ? decodeUtf8Strict(main.bytes) : null;
2069
2085
  const rebasedMain = mainText === null ? null : rebaseAbsolutePins(mainText, root, wtRoot).text;
2070
2086
  if (mainText !== null && (text === mainText || text === rebasedMain)) {
2071
2087
  writeContainedFileAtomic(wtRoot, wtAbs, rebasedMain, fs, { stop: (m) => stop(m) });
@@ -2163,6 +2179,13 @@ export const runProvision = ({ argvSlug, flags, cwd, git, deps, log }) => {
2163
2179
  // Overlap refusal (pre-mutation): an include rel that another provision lane also populates
2164
2180
  // (the frozen registry footprint, the seeded plan, the handoff) — or another include root —
2165
2181
  // would meet the copy-if-missing kept-exit and skip the identity door entirely.
2182
+ // A NEVER_PROVISIONED path is absent from reservedRels precisely because provision skips it, so
2183
+ // the overlap arm below cannot see it — and an --include would copy it AND record it as owned,
2184
+ // which is the never-owned half of the rule defeated through the one door that bypasses the set.
2185
+ const neverProvisioned = [...NEVER_PROVISIONED].find((p) => includeRelsOverlap(rel, patternToProbe(p).replace(/\/$/, '')));
2186
+ if (neverProvisioned !== undefined) {
2187
+ throw stop(`--include names a path a worktree never gets and never owns (${neverProvisioned}): ${inc} — an MCP registration is machine-local and its consent is per checkout; register the satellite itself instead`);
2188
+ }
2166
2189
  const reserved = reservedRels.find((r) => includeRelsOverlap(rel, r));
2167
2190
  if (reserved !== undefined) {
2168
2191
  throw stop(`--include overlaps a path provision itself populates (${reserved}): ${inc} — the footprint, the seeded plan, and the handoff are copied by provision; drop the --include`);
@@ -2239,6 +2262,69 @@ export const runProvision = ({ argvSlug, flags, cwd, git, deps, log }) => {
2239
2262
  }
2240
2263
  };
2241
2264
 
2265
+ // The worktree gets no `.mcp.json`, so a settings enable carried over would name a server it does
2266
+ // not declare. Eligibility is decided LIVE by the same two questions rebasePins asks — is the file
2267
+ // tracked, and is it still MAIN's bytes (before or after the pin rebase)? — never by a run-local
2268
+ // copy log, which a --resume turns into `kept` and silently skips. Anything else is user work: the
2269
+ // registration TOKENS stay — the bytes may still move, since rebasePins rewrites absolute pins on
2270
+ // its own lane — and the tokens are REPORTED rather than quietly left. Scope note: this is the
2271
+ // untracked provision lane; a TRACKED `.mcp.json` arrives with `git worktree add`, not with us.
2272
+ //
2273
+ // SCOPE, stated: this speaks only about a settings file that is readable, well-formed and actually
2274
+ // carries tokens of ours. An absent, unreadable or non-JSON one is not this lane's business and
2275
+ // returns silently — `rebasePins` above already reports the unreadable case in its own words.
2276
+ const dropMcpRegistration = ({ root, wtRoot, git, fs, report }) => {
2277
+ const wtAbs = join(wtRoot, SETTINGS_REL);
2278
+ const cur = readFileNoFollow(fs, wtAbs);
2279
+ if (!cur.bytes) return;
2280
+ // STRICT decode, and the MAIN comparison below is on BYTES: `String(buffer)` replaces invalid
2281
+ // UTF-8 with U+FFFD, so two DIFFERENT byte sequences can decode to the same string — which would
2282
+ // let a file that is not MAIN's satisfy the "matches MAIN" proof and be rewritten.
2283
+ const text = decodeUtf8Strict(cur.bytes);
2284
+ if (text === null) {
2285
+ report.push(` ${SETTINGS_REL}: not valid UTF-8 — left untouched, and no registration claim is made about it`);
2286
+ return;
2287
+ }
2288
+ const removal = withoutRegistration(text);
2289
+ if (!removal.hasTokens) return; // nothing of ours in it, or not readable as ours
2290
+ if (removal.reason !== null) {
2291
+ // Tokens ARE here and the rewrite was refused to protect foreign data — never a silent skip.
2292
+ report.push(` ${SETTINGS_REL}: carries registration tokens for "${SERVER_NAME}" but ${removal.reason}; left untouched`);
2293
+ return;
2294
+ }
2295
+ // ONE conjunction of PROVEN facts admits the write; every other state — including every state a
2296
+ // read cannot settle — takes the single report branch below. Stated as a positive proof rather
2297
+ // than a list of exclusions on purpose: three review rounds each found one more launcher/copy
2298
+ // sub-state an exclusion list had not enumerated, and an unenumerated state failed OPEN.
2299
+ const tracked = git(['ls-files', '--', SETTINGS_REL], wtRoot);
2300
+ if (tracked.status !== 0) throw stop(`git ls-files failed for ${SETTINGS_REL}: ${(tracked.stderr || tracked.stdout).trim()}`);
2301
+ const main = readFileNoFollow(fs, join(root, SETTINGS_REL));
2302
+ const mainText = main.bytes ? decodeUtf8Strict(main.bytes) : null;
2303
+ // Byte equality, and it is NOT interchangeable with string equality: a decoder that strips the BOM
2304
+ // maps a BOM-carrying file and a BOM-less one to the same string. Only the DIRECT branch is
2305
+ // independent of that policy — the rebased branch rebuilds the expected bytes FROM `mainText`, so
2306
+ // it holds only because `ignoreBOM: true` kept the BOM in the decode.
2307
+ const isMainCopy = mainText !== null
2308
+ && (cur.bytes.equals(main.bytes)
2309
+ || cur.bytes.equals(Buffer.from(rebaseAbsolutePins(mainText, root, wtRoot).text, 'utf8')));
2310
+ // ABSENT is the only launcher state that proves the tokens are orphaned. Unreadable, symlinked,
2311
+ // device-masked and present-with-an-entry all mean "a declaration may be live" — never strip.
2312
+ const launcherAbsent = readFileNoFollow(fs, join(wtRoot, MCP_JSON_REL)).absent === true;
2313
+ // The admission is ONE positive conjunction; the chain below only NAMES which proof was missing.
2314
+ const canStrip = tracked.stdout.trim() === '' && isMainCopy && launcherAbsent;
2315
+ const why = canStrip ? null
2316
+ : tracked.stdout.trim() !== '' ? 'tracked'
2317
+ // NOT "user-modified": the same arm covers a MAIN settings file that is absent or unreadable.
2318
+ : !isMainCopy ? 'not proven to match MAIN'
2319
+ : `a ${MCP_JSON_REL} is present or unreadable`;
2320
+ if (!canStrip) {
2321
+ report.push(` ${SETTINGS_REL}: ${why} — carries registration tokens for "${SERVER_NAME}"; left untouched, remove them by hand if this worktree declares no server`);
2322
+ return;
2323
+ }
2324
+ writeContainedFileAtomic(wtRoot, wtAbs, removal.text, fs, { stop: (m) => stop(m) });
2325
+ report.push(` ${SETTINGS_REL}: dropped our registration tokens (this worktree declares no ${MCP_JSON_REL})`);
2326
+ };
2327
+
2242
2328
  const finishProvision = ({ root, rootReal, targetPath, slug, branch, flags, seed, includeSources, provisionSet, git, deps, fs, report, log }) => {
2243
2329
  // THIS run's proof set: every lane journals the leaf it placed or kept, and nothing else is ever
2244
2330
  // examined by the resume verify — the session's own work is out of scope by construction.
@@ -2261,6 +2347,9 @@ const finishProvision = ({ root, rootReal, targetPath, slug, branch, flags, seed
2261
2347
  const vscodeMode = provisionVscode({ root, wtRoot: targetPath, slug, git, fs, report, journal });
2262
2348
 
2263
2349
  rebasePins({ root, wtRoot: targetPath, git, fs, report, journal });
2350
+ // AFTER the rebase: stripping first makes the copy differ from MAIN, and rebasePins would then
2351
+ // read it as user work and skip the pins it exists to fix.
2352
+ dropMcpRegistration({ root, wtRoot: targetPath, git, fs, report });
2264
2353
 
2265
2354
  const inFlight = plansInFlight(targetPath, fs.readdir);
2266
2355
  if (inFlight.length !== 1 || inFlight[0] !== seed.name) {
@@ -2877,6 +2966,7 @@ const headEntry = (git, cwd, head, path) => {
2877
2966
  const registryRoots = () => {
2878
2967
  const roots = [];
2879
2968
  for (const pattern of [...KIT_OWN_PATHS, ...KNOWN_FOOTPRINT.map((entry) => entry.pattern)]) {
2969
+ if (NEVER_PROVISIONED.has(pattern)) continue; // on the RAW pattern — normalizing first never matches
2880
2970
  const normalized = normalizeSlashes(pattern).replace(/^\//, '').replace(/\/$/, '');
2881
2971
  if (normalized) roots.push(normalized);
2882
2972
  }
@@ -2891,10 +2981,20 @@ const safeRecordedPath = (path) => {
2891
2981
  return normalized;
2892
2982
  };
2893
2983
 
2984
+ // Ownership has TWO sources — the registry and the record's own includes — and BOTH must honour
2985
+ // NEVER_PROVISIONED. A record written before the --include refusal existed still names the path, and
2986
+ // without this filter that legacy record hands cleanup a registration it may delete. The comparison
2987
+ // is includeRelsOverlap, the SAME predicate the refusal uses. Stated honestly: on POSIX that is
2988
+ // indistinguishable from an exact match here (a recorded DESCENDANT covers nothing at this path, and
2989
+ // case is significant); what it buys is the backslash-platform case fold, already pinned on the
2990
+ // predicate itself (worktrees-include-identity.test.mjs) rather than claimed by a test run here.
2991
+ const NEVER_PROVISIONED_RELS = [...NEVER_PROVISIONED].map((p) => patternToProbe(p).replace(/\/$/, ''));
2992
+ const isNeverProvisionedRel = (rel) => NEVER_PROVISIONED_RELS.some((p) => includeRelsOverlap(rel, p));
2993
+
2894
2994
  const provisionKnownRoots = (identity) => {
2895
2995
  const roots = [
2896
2996
  ...registryRoots(),
2897
- ...identity.record.includes.map(safeRecordedPath),
2997
+ ...identity.record.includes.map(safeRecordedPath).filter((rel) => !isNeverProvisionedRel(rel)),
2898
2998
  PLANS_REL,
2899
2999
  ];
2900
3000
  if (identity.record.vscode === 'written') roots.push('.vscode/settings.json');