create-agentic-workspace 0.18.5 → 0.23.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/README.md CHANGED
@@ -9,8 +9,8 @@ session exists**, in the operator's own terminal.
9
9
  npx create-agentic-workspace --dir my-workspace
10
10
  ```
11
11
 
12
- The CLI walks you through the target directory, greenfield-vs-existing, git/GitHub identity, and
13
- stage mode, **previews every file it will write and every capability it will declare**, writes
12
+ The CLI walks you through the target directory, greenfield-vs-existing, git/GitHub identity,
13
+ **previews every file it will write and every capability it will declare**, writes
14
14
  the workspace, and stops. `create-agentic-workspace` never runs `claude`, never accepts the
15
15
  workspace trust dialog, and never pre-grants anything — it *declares*, the platform's trust dialog
16
16
  is the consent ceremony.
@@ -35,7 +35,7 @@ it does invoke `claude` (bounded by a closed allowlist — see its own README).
35
35
  `drifted` and left byte-identical, never overwritten. Never-clobber is unconditional.
36
36
  - The permission-floor reconcile is additive with ONE narrow exception: a row shaped exactly like
37
37
  the floor's own root-glob rows (`Bash(<plugin-root-glob>/scripts/<name>[ <sub>]:*)`), whose
38
- `(name, sub)` PAIR — not the script name alone — the shipped floor no longer declares, is retired
38
+ `(name, sub)` PAIR — not the script name alone — the shipped floor does not declare, is dropped
39
39
  from `allow`/`ask` and printed `[retired] <row>`. The pair, not just the name, matters: retiring
40
40
  one subcommand of a script that still ships other subcommands (say `<name> --a:*` is dropped
41
41
  while `<name> --b:*` remains) removes only the stale `(name, sub)` row, never the whole family —
@@ -52,8 +52,8 @@ it does invoke `claude` (bounded by a closed allowlist — see its own README).
52
52
  - `.foundry/permissions.yaml` is a SEED, not a managed file: written once when absent (an empty,
53
53
  commented starter for standing grants — see the plugin's `docs/how-to/standing-grants.md`),
54
54
  then operator-owned — reported `[kept]`, never compared, never drifted, never written again.
55
- - The Amendments backfill: every `specs/**/*.md` (any basename, since v1.17.1) with a normative region and no
56
- `## Amendments` section after it gets the empty section `/foundry:amend` requires, reported as
55
+ - The Amendments backfill: every `specs/**/*.md` (any basename) with a normative region and no
56
+ `## Amendments` section after it gets an empty section, reported as
57
57
  one row (`[amendments] backfilled N of M specs (K already present, J skipped: no normative
58
58
  region)`). Outside the hashed region, so no `spec_sha256` moves; already-present, marker-less and
59
59
  symlinked specs are never written; `--dry-run` prints the same row.
@@ -63,6 +63,35 @@ it does invoke `claude` (bounded by a closed allowlist — see its own README).
63
63
  Run `npx create-agentic-workspace --help` for the full, single-sourced flag list (every flag has
64
64
  an interactive-prompt twin, and `--yes` never prompts).
65
65
 
66
+ ### The `foundry-infra` opt-in: `--with-infra` and `--no-infra`
67
+
68
+ The infrastructure-delivery verbs ship in a second plugin, `foundry-infra`. The installer asks one
69
+ question about it. `--with-infra` answers Yes. `--no-infra` answers No. Give only one of them: if you
70
+ give both, the run refuses, writes nothing and exits `1`. `--no-infra` takes no value, so
71
+ `--no-infra=false` is a refusal. `--with-infra=false` is the same as `--no-infra`.
72
+
73
+ The default rule:
74
+
75
+ - The default is **Yes** only when `<target>/.foundry/stack-profile.lock` is a regular file (not a
76
+ symlink) of at most 65,536 bytes, it parses as a JSON object, and its `profiles` list holds an entry
77
+ whose `id` is one of the ids in `foundry.infra_profile_ids` in this package's `package.json`.
78
+ - In every other case the default is **No**. This includes a missing lock, a lock that is too large,
79
+ a lock that does not parse, and a custom profile that is not in the list.
80
+ - The interactive prompt shows the resolved default as `[y]` or `[n]`. `--yes` applies it.
81
+
82
+ What a Yes does:
83
+
84
+ - When the run creates `.claude/settings.json`, it adds `foundry-infra@agentic-foundry` to
85
+ `enabledPlugins`, after `foundry`. Claude Code installs the plugin when you trust the folder. The
86
+ installer starts no `claude` process.
87
+ - When `.claude/settings.json` already exists and does not enable `foundry-infra`, the installer
88
+ leaves the file unchanged, prints
89
+ `claude plugin install foundry-infra@agentic-foundry --scope project`, and exits `2`. (A run that
90
+ also gives `--reconcile-floor` still applies the floor rules to that file, as it does without this
91
+ option. It never adds the plugin key.)
92
+ - If Claude Code reports that the install failed, the `/foundry-infra:*` verbs are not available. Run
93
+ `/foundry:doctor` and the install command above.
94
+
66
95
  ## No telemetry
67
96
 
68
97
  This CLI collects and transmits nothing — **no telemetry** of any kind, and no opt-out to offer
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-agentic-workspace",
3
- "version": "0.18.5",
3
+ "version": "0.23.0",
4
4
  "description": "The pre-session bootstrap wizard for an Agentic Foundry workspace: declares (never grants) the permission floor, absorbs foundry-bootstrap.sh's out-of-session identity wiring, and scaffolds a seven-file schema-valid workspace. Zero dependencies, no lifecycle scripts, no telemetry.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -36,7 +36,11 @@
36
36
  "marketplace_name": "agentic-foundry",
37
37
  "marketplace_repo": "lukasrepublic/agentic-foundry",
38
38
  "plugin_name": "foundry",
39
- "plugin_version": "1.18.5",
39
+ "infra_plugin_name": "foundry-infra",
40
+ "infra_profile_ids": [
41
+ "aws-eks-karpenter"
42
+ ],
43
+ "plugin_version": "1.23.0",
40
44
  "pins_researched": "2026-08-02"
41
45
  }
42
46
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema_version": 1,
3
3
  "plugin_root_glob": "~/.claude/plugins/cache/*/foundry/*",
4
- "generated_for_plugin_version": "1.18.5",
4
+ "generated_for_plugin_version": "1.23.0",
5
5
  "entries": [
6
6
  {
7
7
  "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-acceptance-contract-validate.py:*)",
@@ -23,11 +23,6 @@
23
23
  "tier": "allow",
24
24
  "rationale": "writes one schema-validated evidence row to .foundry/audit-ledger.jsonl at the end of /foundry:audit"
25
25
  },
26
- {
27
- "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-build-citation-graph.py:*)",
28
- "tier": "allow",
29
- "rationale": "builds the derived citation-graph cache from plain-text source-of-truth files"
30
- },
31
26
  {
32
27
  "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-coherence-check.py:*)",
33
28
  "tier": "allow",
@@ -44,7 +39,7 @@
44
39
  "rationale": "declarative content shape/leak checker the operator runs over docs/pack/skill content atoms"
45
40
  },
46
41
  {
47
- "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-dashboard-fidelity.py:*)",
42
+ "rule": "Bash(~/.claude/plugins/cache/*/foundry-infra/*/scripts/foundry-dashboard-fidelity.py:*)",
48
43
  "tier": "allow",
49
44
  "rationale": "N/N MATCH fidelity gate between golden dashboards and the code-generated renderer output"
50
45
  },
@@ -63,11 +58,6 @@
63
58
  "tier": "allow",
64
59
  "rationale": "bare invocation runs the thin 5-check health probe; read-only, fail-open; exact rule deliberately — flag-qualified forms fall through to a prompt so no allow-prefix can reach the --heal ceremony (security review 2026-08-02)."
65
60
  },
66
- {
67
- "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-done-when-backfill.py --dry-run:*)",
68
- "tier": "allow",
69
- "rationale": "read-only report of every acceptance-contract.yaml lacking a top-level done_when and its derivation; writes nothing (AC-SUB-3)"
70
- },
71
61
  {
72
62
  "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-env-hygiene.py:*)",
73
63
  "tier": "allow",
@@ -78,11 +68,6 @@
78
68
  "tier": "allow",
79
69
  "rationale": "read-only report of skill prose lines / shipped scripts / floor rows / hook commands / pytest count; prints only, writes nothing (AC-SUB-4)"
80
70
  },
81
- {
82
- "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-graph-mcp.py:*)",
83
- "tier": "allow",
84
- "rationale": "advisory citation-graph staleness surface / MCP server; run in CONTRIBUTING dev loop + CI"
85
- },
86
71
  {
87
72
  "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-index.py:*)",
88
73
  "tier": "allow",
@@ -118,11 +103,6 @@
118
103
  "tier": "allow",
119
104
  "rationale": "pre-visibility-flip leak scan; read-only denylist/term-matching over the tree"
120
105
  },
121
- {
122
- "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-project-rtm.py:*)",
123
- "tier": "allow",
124
- "rationale": "read-only requirements-traceability-matrix report over committed governance records"
125
- },
126
106
  {
127
107
  "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-release-acceptance.py:*)",
128
108
  "tier": "allow",
@@ -224,25 +204,15 @@
224
204
  "rationale": "Read-only registry-integrity report (feat-foundry-repo-registry-formalization): physical-confinement + gitignore-pairing + origin-match rows over .claude/foundry-project.json; single read-only git choke point, sanitizing emission sink, writes nothing. Tiered at merge-reconciliation when the script landed after the map (the closed-world tripwire firing as designed)."
225
205
  },
226
206
  {
227
- "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry_session_mode.py:*)",
207
+ "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry_fork_policy.py:*)",
228
208
  "tier": "allow",
229
- "rationale": "session-scoped mode/fork-policy set-and-resolve state-writer; not a release/repo ceremony"
209
+ "rationale": "reads the project fork_policy key and appends one line to .foundry/auto-answers.jsonl; sets nothing; not a release/repo ceremony"
230
210
  },
231
211
  {
232
212
  "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-routine-wake-prompt.py:*)",
233
213
  "tier": "allow",
234
214
  "rationale": "routine-wake (autonomy-continuation R3, AC-RWK-1): validates <programme>/--deck-name as [a-z0-9-]+ slugs and prints the self-contained Routine prompt plus the /schedule recipe and prerequisites; reads no corpus state and writes nothing"
235
215
  },
236
- {
237
- "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-authorize.py:*)",
238
- "tier": "ask",
239
- "rationale": "ceremony: front-authorization; --yes/--skip-audit-reason arrive after other args, not prefix-keyable, so the whole script is ask"
240
- },
241
- {
242
- "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-amend.py:*)",
243
- "tier": "ask",
244
- "rationale": "writes the frozen authorized: trailer (re-freeze after a non-widening amendment) — operator-prompted until permissions.yaml (R1) tiers it; a widening is refused by the verb itself"
245
- },
246
216
  {
247
217
  "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-bootstrap.sh:*)",
248
218
  "tier": "ask",
@@ -254,20 +224,15 @@
254
224
  "rationale": "ER class-C release-cut ceremony marker, taken at the coarser fail-safe tier; the script itself mutates no tree"
255
225
  },
256
226
  {
257
- "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-decommission.py gate-check:*)",
227
+ "rule": "Bash(~/.claude/plugins/cache/*/foundry-infra/*/scripts/foundry-decommission.py gate-check:*)",
258
228
  "tier": "ask",
259
229
  "rationale": "ceremony: leading subcommand, gate-checks a decommission"
260
230
  },
261
231
  {
262
- "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-decommission.py record:*)",
232
+ "rule": "Bash(~/.claude/plugins/cache/*/foundry-infra/*/scripts/foundry-decommission.py record:*)",
263
233
  "tier": "ask",
264
234
  "rationale": "ceremony: leading subcommand, writes a decommission record"
265
235
  },
266
- {
267
- "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-done-when-backfill.py --apply:*)",
268
- "tier": "ask",
269
- "rationale": "writes a derived done_when: block into every acceptance-contract.yaml it backfills across the workspace's whole spec corpus; the --dry-run flag above is the read-only tier (AC-SUB-3)"
270
- },
271
236
  {
272
237
  "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-doctor.py --heal:*)",
273
238
  "tier": "ask",
@@ -276,7 +241,7 @@
276
241
  {
277
242
  "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-merge-when-green.py:*)",
278
243
  "tier": "ask",
279
- "rationale": "issues gh pr merge <pr> --squash once every check is green — a merge is a repo-state mutation, ask like foundry-authorize.py/foundry-amend.py, never a self-grant"
244
+ "rationale": "issues gh pr merge <pr> --squash once every check is green — a merge is a repo-state mutation, ask, never a self-grant"
280
245
  },
281
246
  {
282
247
  "rule": "Bash(~/.claude/plugins/cache/*/foundry/*/scripts/foundry-project-sync.py:*)",
@@ -360,6 +325,14 @@
360
325
  }
361
326
  ],
362
327
  "not_invoked": [
328
+ {
329
+ "script": "foundry-authorize.py",
330
+ "rationale": "retired in 1.20.0: prints the retirement message and exits 0; writes nothing, so it needs no tier"
331
+ },
332
+ {
333
+ "script": "foundry-amend.py",
334
+ "rationale": "retired in 1.20.0: prints the retirement message and exits 0; writes nothing, so it needs no tier"
335
+ },
363
336
  {
364
337
  "script": "foundry_shell_scan.py",
365
338
  "rationale": "library: no argparse/__main__; the stdlib shell tokenizer imported by the two PreToolUse(Bash) guards (guard-structured-observations)"
@@ -402,15 +375,15 @@
402
375
  },
403
376
  {
404
377
  "script": "foundry_graph.py",
405
- "rationale": "library: no argparse/__main__; citation-graph primitives imported by the graph CLIs"
378
+ "rationale": "library: no argparse/__main__; citation graph primitives imported by the coherence check"
406
379
  },
407
380
  {
408
381
  "script": "foundry_id_alloc.py",
409
- "rationale": "library: no argparse/__main__; id-allocation helpers imported by id-* skills"
382
+ "rationale": "library: no argparse/__main__; id-allocation helpers imported by the core env-hygiene skill through foundry_env_isolation.py"
410
383
  },
411
384
  {
412
385
  "script": "foundry_id_apply.py",
413
- "rationale": "pure decision library: no argparse/main()/__main__; exposes classify_gitops/decide_apply as pure functions (R5)"
386
+ "rationale": "foundry-infra plugin: pure decision library: no argparse/main()/__main__; exposes classify_gitops/decide_apply as pure functions (R5)"
414
387
  },
415
388
  {
416
389
  "script": "foundry_main_catalogue.py",
@@ -422,7 +395,7 @@
422
395
  },
423
396
  {
424
397
  "script": "foundry_plan_model.py",
425
- "rationale": "the shipped __main__ is a convenience CLI (parse a plan JSON on stdin); the shipped workflow only imports its parsers"
398
+ "rationale": "foundry-infra plugin: the shipped __main__ is a convenience CLI (parse a plan JSON on stdin); the shipped workflow only imports its parsers"
426
399
  },
427
400
  {
428
401
  "script": "foundry_pr_review.py",
@@ -438,15 +411,11 @@
438
411
  },
439
412
  {
440
413
  "script": "foundry_realization.py",
441
- "rationale": "library: no argparse/__main__; loads foundry_plan_model.py dynamically for the empties-check"
442
- },
443
- {
444
- "script": "foundry_reconcile.py",
445
- "rationale": "library: no argparse/__main__; reconciliation helpers imported by other scripts"
414
+ "rationale": "foundry-infra plugin: library: no argparse/__main__; loads foundry_plan_model.py dynamically for the empties-check"
446
415
  },
447
416
  {
448
417
  "script": "foundry_sandbox_signature.py",
449
- "rationale": "library: no argparse/__main__; sandbox-apply signature helpers, dormant per skills/infra-sandboxed-apply"
418
+ "rationale": "library: no argparse/__main__; sandbox-apply signature helpers, dormant per plugins/foundry-infra/skills/sandboxed-apply"
450
419
  },
451
420
  {
452
421
  "script": "foundry_security_review.py",
@@ -11,6 +11,52 @@
11
11
  "max_bytes": 4194304,
12
12
  "max_total_bytes": 67108864
13
13
  },
14
+ "retired_verbs": {
15
+ "_comment": "context-diet-r1 D4: plugin skills removed from the shipped plugin. Never a removal candidate: the updater and the doctor only REPORT a workspace file (the reference_scan set) that still names `/foundry:<name>`, so the operator can repoint it. `.claude/skills` and operator files are never touched.",
16
+ "names": [
17
+ { "name": "index", "removed_in": "1.21.0", "use": "/foundry:help" },
18
+ { "name": "report-citation-graph", "removed_in": "1.21.0", "use": "/foundry:coherence-check" },
19
+ { "name": "learn-capture", "removed_in": "1.21.0", "use": "/foundry:retro-capture" },
20
+ { "name": "learn-distill", "removed_in": "1.21.0", "use": "/foundry:retro" },
21
+ { "name": "sd-debug", "removed_in": "1.21.0", "use": "/foundry:dev-debug" },
22
+ { "name": "sd-discover", "removed_in": "1.21.0", "use": "/foundry:dev-discover" },
23
+ { "name": "sd-document", "removed_in": "1.21.0", "use": "/foundry:dev-document" },
24
+ { "name": "sd-plan-tests", "removed_in": "1.21.0", "use": "/foundry:dev-plan-tests" },
25
+ { "name": "sd-review", "removed_in": "1.21.0", "use": "/foundry:dev-review" },
26
+ { "name": "sd-test", "removed_in": "1.21.0", "use": "/foundry:dev-test" },
27
+ { "name": "sd-verify", "removed_in": "1.21.0", "use": "/foundry:dev-verify" },
28
+ { "name": "authorize", "removed_in": "1.21.0", "use": "/foundry:spec-review" },
29
+ { "name": "authorize-release", "removed_in": "1.21.0", "use": "/foundry:spec-review" },
30
+ { "name": "amend", "removed_in": "1.21.0", "use": "a new spec" },
31
+ { "name": "drift-sweep", "removed_in": "1.21.0", "use": "nothing (code and tests are the source of truth after release)" },
32
+ { "name": "id-apply", "removed_in": "1.22.0", "use": "/foundry-infra:apply (plugin foundry-infra@agentic-foundry)" },
33
+ { "name": "id-architect", "removed_in": "1.22.0", "use": "/foundry-infra:architect (plugin foundry-infra@agentic-foundry)" },
34
+ { "name": "id-baseline", "removed_in": "1.22.0", "use": "/foundry-infra:baseline (plugin foundry-infra@agentic-foundry)" },
35
+ { "name": "id-discover", "removed_in": "1.22.0", "use": "/foundry-infra:discover (plugin foundry-infra@agentic-foundry)" },
36
+ { "name": "id-document", "removed_in": "1.22.0", "use": "/foundry-infra:document (plugin foundry-infra@agentic-foundry)" },
37
+ { "name": "id-drift", "removed_in": "1.22.0", "use": "/foundry-infra:drift (plugin foundry-infra@agentic-foundry)" },
38
+ { "name": "id-impact", "removed_in": "1.22.0", "use": "/foundry-infra:impact (plugin foundry-infra@agentic-foundry)" },
39
+ { "name": "id-implement", "removed_in": "1.22.0", "use": "/foundry-infra:implement (plugin foundry-infra@agentic-foundry)" },
40
+ { "name": "id-import", "removed_in": "1.22.0", "use": "/foundry-infra:import (plugin foundry-infra@agentic-foundry)" },
41
+ { "name": "id-plan", "removed_in": "1.22.0", "use": "/foundry-infra:plan (plugin foundry-infra@agentic-foundry)" },
42
+ { "name": "id-promote", "removed_in": "1.22.0", "use": "/foundry-infra:promote (plugin foundry-infra@agentic-foundry)" },
43
+ { "name": "id-review", "removed_in": "1.22.0", "use": "/foundry-infra:review (plugin foundry-infra@agentic-foundry)" },
44
+ { "name": "id-rollback", "removed_in": "1.22.0", "use": "/foundry-infra:rollback (plugin foundry-infra@agentic-foundry)" },
45
+ { "name": "id-simulate", "removed_in": "1.22.0", "use": "/foundry-infra:simulate (plugin foundry-infra@agentic-foundry)" },
46
+ { "name": "id-sync", "removed_in": "1.22.0", "use": "/foundry-infra:sync (plugin foundry-infra@agentic-foundry)" },
47
+ { "name": "id-test", "removed_in": "1.22.0", "use": "/foundry-infra:test (plugin foundry-infra@agentic-foundry)" },
48
+ { "name": "id-validate", "removed_in": "1.22.0", "use": "/foundry-infra:validate (plugin foundry-infra@agentic-foundry)" },
49
+ { "name": "id-verify", "removed_in": "1.22.0", "use": "/foundry-infra:verify (plugin foundry-infra@agentic-foundry)" },
50
+ { "name": "infra-sandboxed-apply", "removed_in": "1.22.0", "use": "/foundry-infra:sandboxed-apply (plugin foundry-infra@agentic-foundry)" },
51
+ { "name": "data-tier-cutover", "removed_in": "1.22.0", "use": "/foundry-infra:data-tier-cutover (plugin foundry-infra@agentic-foundry)" },
52
+ { "name": "dashboards-as-code", "removed_in": "1.22.0", "use": "/foundry-infra:dashboards-as-code (plugin foundry-infra@agentic-foundry)" },
53
+ { "name": "decommission-gate", "removed_in": "1.22.0", "use": "/foundry-infra:decommission-gate (plugin foundry-infra@agentic-foundry)" },
54
+ { "name": "mode", "removed_in": "1.23.0", "use": "the `fork_policy` key in `.claude/foundry-project.json` (values `park` | `two-way-auto`; the operator edits the file)" },
55
+ { "name": "mode-autonomous", "removed_in": "1.23.0", "use": "/foundry:command-deck <programme-id> (the deck drives a release unattended; the merge-authority record is in `skills/command-deck/SKILL.md`)" },
56
+ { "name": "citation-graph", "removed_in": "1.23.0", "use": "/foundry:coherence-check" },
57
+ { "name": "mode-interactive", "removed_in": "1.23.0", "use": "/foundry:dispatch (see `skills/dispatch/SKILL.md`, \"Implement in the main session\")" }
58
+ ]
59
+ },
14
60
  "entries": [
15
61
  { "path": ".foundry/wiring-hash.pin", "kind": "file", "retired_in": "0.24.0", "reason": "the wiring-hash auto-heal and its pin were removed with the live-seam merge gate" },
16
62
  { "path": ".foundry/active-workflow.json", "kind": "file", "retired_in": "0.5.0", "reason": "the macro-workflow engine's active-workflow pointer; the engine was retired" },
@@ -29,6 +75,7 @@
29
75
  { "path": ".claude/session-learnings", "kind": "dir", "retired_in": "1.0.0", "reason": "the old learnings location; the partition is .foundry/session-learnings" },
30
76
  { "path": ".claude/hooks/*-exec-guard.sh", "kind": "file", "exclude_prefix": "foundry-", "retired_in": "1.8.0", "reason": "the retired session-context framework's cloud-cli exec guard; a hook still named by a command in .claude/settings*.json is refused, never removed" },
31
77
  { "path": ".foundry/admission-ledger.jsonl", "kind": "file", "retired_in": "0.24.0", "reason": "the retired ADL admission gate's ledger; nothing reads it" },
32
- { "path": ".claude/hooks/foundry-subagent-statusline.sh", "kind": "file", "retired_in": "1.18.2", "reason": "the subagent status line is retired (the status line runs for the root session only); removed only once no settings file names it" }
78
+ { "path": ".claude/hooks/foundry-subagent-statusline.sh", "kind": "file", "retired_in": "1.18.2", "reason": "the subagent status line is retired (the status line runs for the root session only); removed only once no settings file names it" },
79
+ { "path": ".foundry/graph.json", "kind": "file", "retired_in": "1.23.0", "reason": "the citation-graph cache; no release builds or reads it" }
33
80
  ]
34
81
  }
package/src/answers.mjs CHANGED
@@ -58,7 +58,7 @@ export function isYesMode(values, isTTY) {
58
58
  * (naming the flag) on an unanswered required record. Interactively: prompt only records marked
59
59
  * `interactive: true` and not already provided by a flag; a non-interactive record always takes
60
60
  * its provided value or its default. */
61
- export async function resolveAnswers(table, parsed, { yesMode, input, output }) {
61
+ export async function resolveAnswers(table, parsed, { yesMode, input, output, probe = null }) {
62
62
  const { values, provided } = parsed;
63
63
  const resolved = { ...values };
64
64
 
@@ -71,8 +71,13 @@ export async function resolveAnswers(table, parsed, { yesMode, input, output })
71
71
  rl = createInterface({ input, output });
72
72
  }
73
73
  try {
74
- for (const rec of table) {
75
- if (provided.has(rec.id)) continue;
74
+ for (const rawRec of table) {
75
+ if (provided.has(rawRec.id)) continue;
76
+ // `defaultFrom` (AC-IIO-2): a default that depends on an earlier answer is resolved here, once,
77
+ // and used by yes-mode, by the prompt's `[y]`/`[n]` token and by an empty answer alike.
78
+ const rec = rawRec.defaultFrom && probe
79
+ ? { ...rawRec, default: Boolean(rawRec.defaultFrom(resolved, probe)) }
80
+ : rawRec;
76
81
  if (yesMode || !rec.interactive) {
77
82
  if (rec.required) {
78
83
  throw new RefusalError(`missing required flag: --${rec.flag}`, rec.flag);
package/src/argv.mjs CHANGED
@@ -8,8 +8,12 @@ import { RefusalError } from './util.mjs';
8
8
  * function performs no I/O). */
9
9
  export function parseArgv(argv, table) {
10
10
  const byFlag = new Map(table.map((r) => [r.flag, r]));
11
+ // A negation flag is derived from the same record (AC-IIO-1): `--<negationFlag>` sets the value
12
+ // to false. It takes no value: A negation flag with an inline value is a refusal, because "not no" has two readings.
13
+ const byNegation = new Map(table.filter((r) => r.negationFlag).map((r) => [r.negationFlag, r]));
11
14
  const values = {};
12
15
  const provided = new Set();
16
+ const seenFlags = new Set();
13
17
 
14
18
  for (let i = 0; i < argv.length; i++) {
15
19
  const tok = argv[i];
@@ -23,7 +27,26 @@ export function parseArgv(argv, table) {
23
27
  inline = name.slice(eq + 1);
24
28
  name = name.slice(0, eq);
25
29
  }
30
+ const negRec = byNegation.get(name);
31
+ if (negRec) {
32
+ if (inline !== null) {
33
+ throw new RefusalError(`--${name} takes no value (got ${JSON.stringify(inline)})`, name);
34
+ }
35
+ seenFlags.add(name);
36
+ if (seenFlags.has(negRec.flag)) {
37
+ throw new RefusalError(`--${negRec.flag} and --${name} contradict each other; give only one`, name);
38
+ }
39
+ values[negRec.id] = false;
40
+ provided.add(negRec.id);
41
+ continue;
42
+ }
26
43
  const rec = byFlag.get(name);
44
+ if (rec && rec.negationFlag) {
45
+ seenFlags.add(name);
46
+ if (seenFlags.has(rec.negationFlag)) {
47
+ throw new RefusalError(`--${rec.flag} and --${rec.negationFlag} contradict each other; give only one`, name);
48
+ }
49
+ }
27
50
  if (!rec) {
28
51
  throw new RefusalError(`unknown flag: --${name}`, name);
29
52
  }
@@ -56,8 +79,12 @@ export function parseArgv(argv, table) {
56
79
  export function renderHelp(table, { programName = 'create-agentic-workspace' } = {}) {
57
80
  const lines = [`Usage: ${programName} [options]`, ''];
58
81
  for (const rec of table) {
59
- const flagCol = rec.type === 'boolean' ? `--${rec.flag}` : `--${rec.flag} <value>`;
60
- const req = rec.required ? ' (required)' : rec.default !== undefined && rec.default !== '' ? ` (default: ${rec.default})` : '';
82
+ const flagCol = rec.type === 'boolean'
83
+ ? (rec.negationFlag ? `--${rec.flag} | --${rec.negationFlag}` : `--${rec.flag}`)
84
+ : `--${rec.flag} <value>`;
85
+ // A record with `defaultFrom` states its default rule in the description, not a fixed value.
86
+ const req = rec.required ? ' (required)'
87
+ : rec.default !== undefined && rec.default !== '' && !rec.defaultFrom ? ` (default: ${rec.default})` : '';
61
88
  const choices = rec.choices ? ` [choices: ${rec.choices.join('|')}]` : '';
62
89
  lines.push(` ${flagCol.padEnd(24)} ${rec.prompt}${choices}${req}`);
63
90
  // The description renders as an indented continuation beneath its flag line (AC-WPD-10),
@@ -0,0 +1,55 @@
1
+ // infraOptIn.mjs — the `foundry-infra` opt-in (feat-foundry-onboarding-installer-infra-opt-in).
2
+ // Pure helpers: the plugin key, the default rule (AC-IIO-2) and the "already enabled" probe. The
3
+ // lock is UNTRUSTED input: capped in size, read through a no-follow descriptor, compared by string
4
+ // equality with a pinned id list, and never used to build a path (AC-IIO-2).
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+
8
+ export const LOCK_MAX_BYTES = 65536;
9
+
10
+ /** The `foundry-infra@<marketplace>` key, built from the pins and from no literal (AC-IIO-8). */
11
+ export function infraPluginKey(pins) {
12
+ return `${pins.infra_plugin_name}@${pins.marketplace_name}`;
13
+ }
14
+
15
+ /** AC-IIO-2: true only when `<targetRoot>/.foundry/stack-profile.lock` is a regular file (a symlink
16
+ * is not one) of at most LOCK_MAX_BYTES that parses as a JSON object whose `profiles` list holds an
17
+ * entry whose `id` string equals a member of `pins.infra_profile_ids`. Anything else is false. */
18
+ export function lockDeclaresInfraProfile(targetRoot, pins) {
19
+ const ids = Array.isArray(pins && pins.infra_profile_ids) ? pins.infra_profile_ids : [];
20
+ if (ids.length === 0) return false;
21
+ const lockPath = path.join(targetRoot, '.foundry', 'stack-profile.lock');
22
+ let fd = null;
23
+ try {
24
+ const l = fs.lstatSync(lockPath);
25
+ if (!l.isFile()) return false;
26
+ // O_NOFOLLOW closes the window between the lstat above and the open below.
27
+ fd = fs.openSync(lockPath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
28
+ const st = fs.fstatSync(fd);
29
+ if (!st.isFile() || st.size > LOCK_MAX_BYTES) return false;
30
+ const buf = Buffer.alloc(st.size);
31
+ const n = fs.readSync(fd, buf, 0, st.size, 0);
32
+ const doc = JSON.parse(buf.subarray(0, n).toString('utf-8'));
33
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)) return false;
34
+ if (!Array.isArray(doc.profiles)) return false;
35
+ return doc.profiles.some(
36
+ (e) => e && typeof e === 'object' && typeof e.id === 'string' && ids.includes(e.id),
37
+ );
38
+ } catch {
39
+ return false;
40
+ } finally {
41
+ if (fd !== null) {
42
+ try { fs.closeSync(fd); } catch { /* nothing to do */ }
43
+ }
44
+ }
45
+ }
46
+
47
+ /** True when the settings file at `settingsPath` parses and enables `key`. Unreadable = false. */
48
+ export function settingsEnablePlugin(settingsPath, key) {
49
+ try {
50
+ const doc = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
51
+ return Boolean(doc && typeof doc === 'object' && doc.enabledPlugins && doc.enabledPlugins[key] === true);
52
+ } catch {
53
+ return false;
54
+ }
55
+ }
@@ -217,7 +217,7 @@ export const DRIFT_CLASSES = Object.freeze([
217
217
  * closed-world REGISTRY of every script (AC-PFM-2), never projected. */
218
218
  export const PROJECTED_TIERS = Object.freeze(['deny']);
219
219
 
220
- export function buildSettings(map, pins) {
220
+ export function buildSettings(map, pins, { withInfra = false } = {}) {
221
221
  const byTier = { allow: [], ask: [], deny: [] };
222
222
  for (const e of map.entries) {
223
223
  if (PROJECTED_TIERS.includes(e.tier)) byTier[e.tier].push(e.rule);
@@ -273,7 +273,12 @@ export function buildSettings(map, pins) {
273
273
  return {
274
274
  permissions: { allow: byTier.allow, ask: byTier.ask, deny: byTier.deny },
275
275
  extraKnownMarketplaces: { [pins.marketplace_name]: marketplaceEntry },
276
- enabledPlugins: { [`${pins.plugin_name}@${pins.marketplace_name}`]: true },
276
+ // AC-IIO-3: `foundry-infra` is the SECOND key, only on an explicit opt-in. The default argument
277
+ // keeps every existing caller byte-identical.
278
+ enabledPlugins: {
279
+ [`${pins.plugin_name}@${pins.marketplace_name}`]: true,
280
+ ...(withInfra ? { [`${pins.infra_plugin_name}@${pins.marketplace_name}`]: true } : {}),
281
+ },
277
282
  // v1.18.3 (AC-BCL-4(c) amended, operator directive 2026-09-30): the status line ships with the
278
283
  // scaffold — a new workspace had none. The one value permitted, naming the framework wrapper the
279
284
  // create path writes beside it (statuslineWiring.mjs). Grants nothing; the trust dialog gates it.
package/src/preview.mjs CHANGED
@@ -2,12 +2,14 @@
2
2
  // write, and every capability the CLI will declare, before the first byte lands.
3
3
  import { renderCapabilityLines } from './permissionFloor.mjs';
4
4
 
5
- export function renderPreview({ plan, machineScopeWrites, map }) {
5
+ export function renderPreview({ plan, machineScopeWrites, map, infraRow = null }) {
6
6
  const lines = [];
7
7
  lines.push('The following paths will be written or reconciled under the target root:');
8
8
  for (const f of plan) {
9
9
  lines.push(` [${f.action}] ${f.relPath}`);
10
10
  }
11
+ // AC-IIO-4: one row for the foundry-infra opt-in, before the write-phase confirmation.
12
+ if (infraRow) lines.push(infraRow);
11
13
  lines.push('');
12
14
  if (machineScopeWrites.length > 0) {
13
15
  lines.push('The following machine-scope writes will be made (outside the target root):');
@@ -43,7 +45,7 @@ export function renderPreview({ plan, machineScopeWrites, map }) {
43
45
  // the only consent moment there will be. Saying otherwise points the operator at a review that will
44
46
  // not happen — the one claim this tool cannot afford to get wrong, since "declares, never grants" is
45
47
  // its whole posture. (bootstrap-cli R8, answered 2026-08-12.)
46
- export const TRUST_HANDOFF_TEXT = (dir, { isGitRepo = true, reconciledExisting = false } = {}) => `
48
+ export const TRUST_HANDOFF_TEXT = (dir, { isGitRepo = true, reconciledExisting = false, infraKey = null } = {}) => `
47
49
  ${reconciledExisting ? `The workspace has been written, and the permission-floor rules above were added to a workspace
48
50
  that is ALREADY TRUSTED. On that path there is no second consent ceremony: the preview and the
49
51
  confirmation you just gave were it, and the added \`allow\` rules are in effect from the next
@@ -63,4 +65,8 @@ you accept it — the dialog lists them.`}
63
65
 
64
66
  Once the session is open, run \`/foundry:doctor\` — it compares this written floor against the
65
67
  installed plugin's own copy of the map, the one independent check that did not travel through npm.
66
- `;
68
+ ${infraKey ? `
69
+ Claude Code installs foundry-infra when you trust the folder. If Claude Code reports that the
70
+ install failed, the /foundry-infra:* verbs are not available: run \`/foundry:doctor\` and
71
+ \`claude plugin install ${infraKey} --scope project\`.
72
+ ` : ''}`;
package/src/questions.mjs CHANGED
@@ -16,6 +16,13 @@
16
16
  // draft copy ("writes global git config, machine-wide") was read by the framework's own operator
17
17
  // as changing their global identity, which it does not do.
18
18
 
19
+ import path from 'node:path';
20
+ import { lockDeclaresInfraProfile } from './infraOptIn.mjs';
21
+
22
+ // `negationFlag` (AC-IIO-1): a boolean record may name a second flag that sets the value to false.
23
+ // `defaultFrom(resolvedSoFar, probe)` (AC-IIO-2): a record whose default depends on an earlier answer
24
+ // resolves it here; `probe` is { cwd, pins }. The static `default` is the fallback.
25
+
19
26
  export const QUESTION_TABLE = [
20
27
  {
21
28
  id: 'dir',
@@ -43,20 +50,23 @@ export const QUESTION_TABLE = [
43
50
  interactive: true,
44
51
  },
45
52
  {
46
- id: 'stageMode',
47
- flag: 'stage-mode',
48
- type: 'string',
49
- prompt: 'Stage mode',
53
+ id: 'withInfra',
54
+ flag: 'with-infra',
55
+ negationFlag: 'no-infra',
56
+ type: 'boolean',
57
+ prompt: 'Also enable the foundry-infra plugin (infrastructure verbs)?',
50
58
  description:
51
- 'How much process ceremony this workspace enforces.\n' +
52
- "Recorded in your workspace's CLAUDE.md; agents read it each session,\n" +
53
- 'and you can change it later by editing that line.',
54
- default: 'lean',
55
- choices: ['lean', 'scale'],
56
- choiceDescriptions: {
57
- lean: 'development loop with lighter ceremony — the solo/small-team norm',
58
- scale: 'higher ceremony loop enforced end to end',
59
- },
59
+ 'Adds foundry-infra@agentic-foundry to enabledPlugins in the new\n' +
60
+ '.claude/settings.json, after foundry. Claude Code installs it when you\n' +
61
+ 'trust the folder. --with-infra says yes; --no-infra says no.\n' +
62
+ 'The default is yes only when the target already holds\n' +
63
+ '.foundry/stack-profile.lock naming a stack profile that declares\n' +
64
+ 'infra_binding. Otherwise the default is no.\n' +
65
+ 'An existing .claude/settings.json is never merged: the run prints the\n' +
66
+ 'claude plugin install command instead and exits 2.\n' +
67
+ 'Enter alone takes the default. y, yes, true or 1 mean yes.',
68
+ default: false,
69
+ defaultFrom: (resolved, probe) => lockDeclaresInfraProfile(path.resolve(probe.cwd, resolved.dir), probe.pins),
60
70
  interactive: true,
61
71
  },
62
72
  {
@@ -38,9 +38,40 @@ export function loadRetiredCatalogue(pkgDir) {
38
38
  throw new Error(`retired-artifacts.json: only one '*' in the last segment is allowed (${e.path})`);
39
39
  }
40
40
  }
41
+ const rv = doc.retired_verbs;
42
+ if (rv !== undefined) {
43
+ if (!rv || !Array.isArray(rv.names) || !rv.names.every((v) => v && typeof v.name === 'string'
44
+ && /^[a-z0-9][a-z0-9-]*$/.test(v.name) && typeof v.removed_in === 'string' && typeof v.use === 'string')) {
45
+ throw new Error('retired-artifacts.json: retired_verbs malformed');
46
+ }
47
+ }
41
48
  return doc;
42
49
  }
43
50
 
51
+ /** context-diet-r1 D4: the removed plugin verbs a workspace file still names. Report-only — nothing is
52
+ * ever removed or rewritten. Returns `{ rows: [{ name, removed_in, use, refs }], incomplete }`;
53
+ * `incomplete` (the reference scan could not finish) means "unknown", never "none". */
54
+ export function planRetiredVerbs({ physicalRoot, catalogue }) {
55
+ const names = (catalogue.retired_verbs && catalogue.retired_verbs.names) || [];
56
+ if (names.length === 0) return { rows: [], incomplete: null };
57
+ const refs = scanReferenceTexts(physicalRoot, catalogue.reference_scan);
58
+ if (refs.incomplete) return { rows: [], incomplete: refs.incomplete };
59
+ const rows = [];
60
+ for (const v of names) {
61
+ const re = new RegExp(`/foundry:${v.name}(?![A-Za-z0-9_-])`);
62
+ const by = refs.texts.filter(([, text]) => re.test(text)).map(([rel]) => rel);
63
+ if (by.length > 0) rows.push({ name: v.name, removed_in: v.removed_in, use: v.use, refs: by });
64
+ }
65
+ return { rows, incomplete: null };
66
+ }
67
+
68
+ /** One `[retired verb]` row per removed verb a workspace file still names; one `[unknown]` row when
69
+ * the scan could not finish. Empty when nothing names a removed verb. */
70
+ export function renderRetiredVerbRows(plan) {
71
+ if (plan.incomplete) return [` [unknown] retired verbs — the reference scan could not finish (${plan.incomplete})`];
72
+ return plan.rows.map((r) => ` [retired verb] /foundry:${r.name} — removed in v${r.removed_in}; use ${r.use} — named by ${r.refs.slice(0, 3).join(', ')}${r.refs.length > 3 ? ' …' : ''}`);
73
+ }
74
+
44
75
  /** Expand an entry to concrete relative paths present on disk: the path itself, or, for a
45
76
  * basename glob, every directory entry that matches (names starting with `exclude_prefix` skipped). */
46
77
  function candidates(physicalRoot, entry) {
package/src/run.mjs CHANGED
@@ -13,12 +13,12 @@ import { PROJECTED_TIERS, loadMap, buildSettings, classifyDrift } from './permis
13
13
  import { buildManagedFiles, DECLARED_PATH_SET } from './scaffold.mjs';
14
14
  import { planManagedFiles, applyPlan, exitCodeForPlan } from './reconcile.mjs';
15
15
  import { renderPreview, TRUST_HANDOFF_TEXT } from './preview.mjs';
16
+ import { infraPluginKey, settingsEnablePlugin } from './infraOptIn.mjs';
16
17
  import { validateSlug, resolveIdentity, wireIdentity, plannedMachineScopeWrites } from './identity.mjs';
17
18
  import {
18
19
  resolveTarget, readTarget, applyAdditions, planReconcile, writeTargetAtomically, renderPlan,
19
20
  } from './floorReconcile.mjs';
20
21
  import { reconcileGitignorePlan, applyGitignorePlan, renderGitignoreRow } from './gitignoreReconcile.mjs';
21
- import { planAmendmentsBackfill, applyAmendmentsBackfill, renderAmendmentsRow } from './amendmentsBackfill.mjs';
22
22
  import { planStatuslineWiring, applyStatuslineWiring, renderStatuslineRows, wrapperIsOurs } from './statuslineWiring.mjs';
23
23
 
24
24
  export { DECLARED_PATH_SET };
@@ -128,7 +128,9 @@ export async function runCli(argv, { cwd, isTTY, input, output, homeDir, pkgDir
128
128
  }
129
129
 
130
130
  const yesMode = isYesMode(parsed.values, isTTY);
131
- const answers = await resolveAnswers(QUESTION_TABLE, parsed, { yesMode, input, output });
131
+ const answers = await resolveAnswers(QUESTION_TABLE, parsed, {
132
+ yesMode, input, output, probe: { cwd, pins: loadPins(pkgDir) },
133
+ });
132
134
 
133
135
  const targetRoot = path.resolve(cwd, answers.dir);
134
136
  const nonEmpty = isNonEmptyDir(targetRoot);
@@ -155,7 +157,8 @@ export async function runCli(argv, { cwd, isTTY, input, output, homeDir, pkgDir
155
157
  const physicalRoot = physicalResolve(targetRoot);
156
158
  const map = loadMap(path.join(pkgDir, 'permission-floor.json'));
157
159
  const pins = loadPins(pkgDir);
158
- const settingsObj = buildSettings(map, pins);
160
+ const withInfra = answers.withInfra === true;
161
+ const settingsObj = buildSettings(map, pins, { withInfra });
159
162
  if (!wrapperIsOurs(physicalRoot)) delete settingsObj.statusLine;
160
163
  const settingsBytes = Buffer.from(`${JSON.stringify(settingsObj, null, 2)}\n`, 'utf-8');
161
164
 
@@ -163,13 +166,27 @@ export async function runCli(argv, { cwd, isTTY, input, output, homeDir, pkgDir
163
166
  templatesDir: path.join(pkgDir, 'templates'),
164
167
  physicalRoot,
165
168
  projectName: path.basename(targetRoot),
166
- stageMode: answers.stageMode,
167
169
  settingsBytes,
168
170
  });
169
171
  const plan = planManagedFiles(managedFiles);
170
172
  const machineScopeWrites = slug ? plannedMachineScopeWrites({ slug, targetRoot, homeDir }) : [];
171
173
 
172
- print(renderPreview({ plan, machineScopeWrites, map }));
174
+ // AC-IIO-4/-5: what the run does with `foundry-infra`. The key is written only when this run
175
+ // CREATES .claude/settings.json; an existing file is never merged (AC-BCL-9), so the operator is
176
+ // told the install command instead (printed after the write phase, AC-IIO-5).
177
+ const settingsRow = plan.find((f) => f.relPath === '.claude/settings.json');
178
+ const infraKey = withInfra ? infraPluginKey(pins) : null;
179
+ const infraEnabledByRun = Boolean(withInfra && settingsRow && settingsRow.action === 'create');
180
+ const infraAlreadyEnabled = Boolean(
181
+ withInfra && !infraEnabledByRun && settingsEnablePlugin(path.join(physicalRoot, '.claude', 'settings.json'), infraKey),
182
+ );
183
+ const infraManual = Boolean(withInfra && !infraEnabledByRun && !infraAlreadyEnabled);
184
+ const infraRow = !withInfra ? null
185
+ : infraEnabledByRun ? ` [enable] ${infraKey} in .claude/settings.json (enabledPlugins, after ${pins.plugin_name})`
186
+ : infraAlreadyEnabled ? ` [present] ${infraKey} is already enabled in .claude/settings.json`
187
+ : ` [unchanged] ${infraKey} NOT added: .claude/settings.json already exists and is never merged`;
188
+
189
+ print(renderPreview({ plan, machineScopeWrites, map, infraRow }));
173
190
 
174
191
  // gitignore-block-reconcile (ER #177, AC-GBR-1/-2/-3): the generic managed-file row above
175
192
  // already covers `.gitignore` for the CREATE case (absent -> the full template lands verbatim,
@@ -187,16 +204,6 @@ export async function runCli(argv, { cwd, isTTY, input, output, homeDir, pkgDir
187
204
  print('');
188
205
  print(gitignoreRow);
189
206
  }
190
- // amendments-backfill (ER #214, AC-AMB-1): every `specs/**/feat-*.md` with a normative region
191
- // and no `## Amendments` section after it gets the empty section `/foundry:amend` requires.
192
- // Planned here for the same reason as the gitignore block — --dry-run reports the same row a
193
- // real run would act on — and `null` when the workspace has no specs at all (a fresh scaffold).
194
- const amendmentsPlan = planAmendmentsBackfill({ physicalRoot });
195
- const amendmentsRow = renderAmendmentsRow(amendmentsPlan);
196
- if (amendmentsRow) {
197
- if (!gitignoreRow) print('');
198
- print(amendmentsRow);
199
- }
200
207
  // statusline-wiring (v1.17.0, AC-SLW-1/-2): ONLY on --existing --reconcile-floor. A plain
201
208
  // --existing run never touches .claude/settings.json (AC-BCL-9: an existing settings file is
202
209
  // reported drifted, left byte-identical, never merged); --reconcile-floor is the one opt-in
@@ -286,9 +293,6 @@ export async function runCli(argv, { cwd, isTTY, input, output, homeDir, pkgDir
286
293
  // since it is a data-integrity issue local to one file, not the security-shaped case
287
294
  // --reconcile-floor's pre-write refusal exists for.
288
295
  applyGitignorePlan(gitignorePlan);
289
- // Same never-clobber posture as the gitignore block: only a spec classified `absent` is ever
290
- // written, and it is re-classified immediately before the atomic append (AC-AMB-2).
291
- applyAmendmentsBackfill(amendmentsPlan);
292
296
 
293
297
  if (floorHasWork) {
294
298
  // floorPlan.settingsObj is ALREADY post-retirement (planReconcile derived it that way) —
@@ -358,14 +362,17 @@ export async function runCli(argv, { cwd, isTTY, input, output, homeDir, pkgDir
358
362
  const gitignoreWrote = Boolean(
359
363
  gitignorePlan && (gitignorePlan.action === 'converged' || gitignorePlan.action === 'appended'),
360
364
  );
365
+ if (infraManual) {
366
+ print(`foundry-infra not enabled: run \`claude plugin install ${infraKey} --scope project\``);
367
+ }
361
368
  print(TRUST_HANDOFF_TEXT(targetRoot, {
362
369
  isGitRepo,
370
+ infraKey: infraEnabledByRun ? infraKey : null,
363
371
  // only when a reconcile actually wrote — a dry run, a no-op second run, or a plain scaffold
364
372
  // all keep the standard hand-off. The gitignore-block-reconcile counts too: it is the SAME
365
373
  // kind of write to an already-trusted workspace floorPlan's own comment describes, just to a
366
374
  // different file.
367
- reconciledExisting: Boolean(floorPlan && floorPlan.total > 0) || gitignoreWrote
368
- || Boolean(amendmentsPlan && amendmentsPlan.applied && amendmentsPlan.written > 0),
375
+ reconciledExisting: Boolean(floorPlan && floorPlan.total > 0) || gitignoreWrote,
369
376
  }));
370
377
 
371
378
  // A refused gitignore block joins the SAME non-zero bucket `drifted` files use (exit 2, "needs
@@ -374,7 +381,7 @@ export async function runCli(argv, { cwd, isTTY, input, output, homeDir, pkgDir
374
381
  // only ever returns 0 or 2, so a refusal simply forces 2 rather than deferring to it.
375
382
  const gitignoreRefused = Boolean(gitignorePlan && gitignorePlan.action === 'refused');
376
383
  return {
377
- exitCode: gitignoreRefused ? 2 : exitCodeForPlan(plan),
384
+ exitCode: gitignoreRefused || infraManual ? 2 : exitCodeForPlan(plan),
378
385
  output: lines.join('\n'),
379
386
  };
380
387
  } catch (e) {
package/src/scaffold.mjs CHANGED
@@ -21,9 +21,9 @@ export const TEMPLATE_ENTRIES = Object.freeze([
21
21
  ]);
22
22
 
23
23
  /** Render a template's raw text with the CLAUDE.md substitutions (the only templated file). */
24
- function renderTemplate(target, raw, { projectName, stageMode }) {
24
+ function renderTemplate(target, raw, { projectName }) {
25
25
  if (target === 'CLAUDE.md') {
26
- return raw.replaceAll('{{PROJECT_NAME}}', projectName).replaceAll('{{STAGE_MODE}}', stageMode);
26
+ return raw.replaceAll('{{PROJECT_NAME}}', projectName);
27
27
  }
28
28
  return raw;
29
29
  }
@@ -36,7 +36,6 @@ export function buildManagedFiles({
36
36
  templatesDir,
37
37
  physicalRoot,
38
38
  projectName,
39
- stageMode,
40
39
  settingsBytes,
41
40
  entries = TEMPLATE_ENTRIES,
42
41
  }) {
@@ -50,7 +49,7 @@ export function buildManagedFiles({
50
49
  );
51
50
  }
52
51
  const raw = fs.readFileSync(path.join(templatesDir, entry.template), 'utf-8');
53
- const rendered = renderTemplate(entry.target, raw, { projectName, stageMode });
52
+ const rendered = renderTemplate(entry.target, raw, { projectName });
54
53
  files.push({
55
54
  relPath: entry.target, absPath: joined, bytes: Buffer.from(rendered, 'utf-8'),
56
55
  ...(entry.seed ? { seed: true } : {}),
@@ -1,6 +1,6 @@
1
1
  // statuslineWiring.mjs — statusline-wiring (v1.17.0, AC-SLW-1/-2).
2
2
  //
3
- // The token-budget status line (`⌂ <repo>:<branch> · tok ██████░░░░ 69% · ⚙️ factory`) is rendered
3
+ // The token-budget status line (`⌂ <repo>:<branch> · tok ██████░░░░ 69%`) is rendered
4
4
  // by the plugin's shipped `scripts/foundry-statusline.sh`, reached through a thin wrapper at
5
5
  // `.claude/hooks/foundry-statusline.sh` and a `statusLine` key in `.claude/settings.json`. Until
6
6
  // v1.17.0 nothing shipped that wiring: /foundry:init only verified it, and the wrapper printed
package/src/update.mjs CHANGED
@@ -16,11 +16,10 @@ import {
16
16
  resolveTarget, readTarget, applyAdditions, planReconcile, writeTargetAtomically, renderPlan,
17
17
  } from './floorReconcile.mjs';
18
18
  import { reconcileGitignorePlan, applyGitignorePlan, renderGitignoreRow } from './gitignoreReconcile.mjs';
19
- import { planAmendmentsBackfill, applyAmendmentsBackfill, renderAmendmentsRow } from './amendmentsBackfill.mjs';
20
19
  import { planManifestTrueUp, applyManifestTrueUp, renderManifestTrueUpRows } from './manifestTrueUp.mjs';
21
20
  import { buildUpgradeReport, writeUpgradeReport, installedVersionBefore, versionOrNull, NEXT_LINE } from './upgradeReport.mjs';
22
21
  import { planStatuslineWiring, applyStatuslineWiring, renderStatuslineRows, statuslineChanged } from './statuslineWiring.mjs';
23
- import { loadRetiredCatalogue, planRetiredArtifacts, applyRetiredArtifacts, renderRetiredArtifactRows } from './retiredArtifacts.mjs';
22
+ import { loadRetiredCatalogue, planRetiredArtifacts, applyRetiredArtifacts, renderRetiredArtifactRows, planRetiredVerbs, renderRetiredVerbRows } from './retiredArtifacts.mjs';
24
23
  import { planRetirements, applyRetirements, askRootKeys } from './floorReconcile.mjs';
25
24
  import {
26
25
  ALLOWED_CLAUDE_SUBCOMMANDS, resolveClaudeOnPath, runClaude,
@@ -30,6 +29,7 @@ import {
30
29
  readInstalledPluginsRegistry, scopeRecordsFor,
31
30
  } from './pluginRefresh.mjs';
32
31
  import { runCleanupPhase } from './cleanup.mjs';
32
+ import { infraPluginKey } from './infraOptIn.mjs';
33
33
  import { loadPythonRequirements, ensurePythonDeps, renderPythonDepsRow } from './pythonDeps.mjs';
34
34
 
35
35
  export { ALLOWED_CLAUDE_SUBCOMMANDS };
@@ -79,10 +79,18 @@ function planLocalRetirement({ physicalRoot, map, trackedSettingsObj }) {
79
79
  }
80
80
  }
81
81
 
82
+ /** The first non-empty line of a failed child process's error output (stderr, then stdout, then the
83
+ * error message), stripped of control characters and capped at 200 characters (AC-IIO-12). */
84
+ export function firstErrorLine(e) {
85
+ const pick = (v) => String(v == null ? '' : v).split('\n').map((l) => l.trim()).find((l) => l) || '';
86
+ const line = pick(e && e.stderr) || pick(e && e.stdout) || pick(e && e.message) || 'no error output';
87
+ return line.replace(/[\u0000-\u001f\u007f]/g, ' ').slice(0, 200);
88
+ }
89
+
82
90
  export function renderSummary(phases) {
83
91
  const lines = ['Summary:'];
84
92
  for (const p of phases) {
85
- const verdict = p.verdict === 'skipped' ? `skipped: ${p.reason}` : p.verdict;
93
+ const verdict = (p.verdict === 'skipped' || p.verdict === 'failed') && p.reason ? `${p.verdict}: ${p.reason}` : p.verdict;
86
94
  lines.push(` [${p.name}] ${verdict}`);
87
95
  }
88
96
  return lines.join('\n');
@@ -159,6 +167,10 @@ export async function runUpdate(argv, { cwd, configDir, homeDir, pkgDir, output,
159
167
  const scopes = defaultScopes({ cwd, configDir });
160
168
  const snapshot = snapshotScopes(scopes);
161
169
  const enabledScopes = enabledScopeNames(snapshot, pluginKey);
170
+ // AC-IIO-10/-11: from the SAME pre-mutation snapshot. The updater only UPDATES foundry-infra
171
+ // where a scope already enables it; it never adds the key and never runs `plugin install`.
172
+ const infraKey = infraPluginKey(pins);
173
+ const infraScopes = enabledScopeNames(snapshot, infraKey);
162
174
 
163
175
  const registry = readInstalledPluginsRegistry(configDir);
164
176
  const isInstalled = isInstalledInScopeFactory(registry, pluginKey, cwd);
@@ -186,7 +198,6 @@ export async function runUpdate(argv, { cwd, configDir, homeDir, pkgDir, output,
186
198
  templatesDir: path.join(pkgDir, 'templates'),
187
199
  physicalRoot,
188
200
  projectName: path.basename(physicalRoot),
189
- stageMode: 'lean',
190
201
  settingsBytes,
191
202
  });
192
203
  const filePlan = planManagedFiles(managedFiles);
@@ -241,6 +252,9 @@ export async function runUpdate(argv, { cwd, configDir, homeDir, pkgDir, output,
241
252
  for (const scopeName of enabledScopes) {
242
253
  previewLines.push(` claude plugin update ${pluginKey} --scope ${scopeName}`);
243
254
  }
255
+ for (const scopeName of infraScopes) {
256
+ previewLines.push(` claude plugin update ${infraKey} --scope ${scopeName}`);
257
+ }
244
258
  // C3 / AC-UAW-7: the concrete cleanup candidate list cannot be known until Phases 1-2 have
245
259
  // refreshed the manifest, so it cannot be named here by path — but the SHAPE of what it may
246
260
  // do, and whether this run can act on it at all, is known up front and disclosed here rather
@@ -264,10 +278,6 @@ export async function runUpdate(argv, { cwd, configDir, homeDir, pkgDir, output,
264
278
  }
265
279
  const previewGitignoreRow = renderGitignoreRow(previewGitignorePlan);
266
280
  if (previewGitignoreRow) previewLines.push(previewGitignoreRow);
267
- // amendments-backfill (ER #214, AC-AMB-1): PREVIEW-ONLY like the two rows above; Phase 4
268
- // re-plans fresh from disk before it writes.
269
- const previewAmendmentsRow = renderAmendmentsRow(planAmendmentsBackfill({ physicalRoot }));
270
- if (previewAmendmentsRow) previewLines.push(previewAmendmentsRow);
271
281
  // v1.18.2: release manifests trued up to the current contract (preview only here)
272
282
  previewLines.push(...renderManifestTrueUpRows(planManifestTrueUp({ physicalRoot })));
273
283
  // statusline-wiring (AC-SLW-1/-2): PREVIEW-ONLY rows; Phase 4 re-plans fresh from disk.
@@ -334,6 +344,19 @@ export async function runUpdate(argv, { cwd, configDir, homeDir, pkgDir, output,
334
344
  for (const scopeName of enabledScopes) {
335
345
  runPluginUpdate({ scope: scopeName, pluginKey, env, cwd, claudeBin });
336
346
  }
347
+ // AC-IIO-11/-12: foundry-infra, after the foundry update. A failure is reported and the run
348
+ // continues (the foundry update and the reconcile are complete and useful without it); it ends
349
+ // as verdict `failed` and exit 2, the same precedent as `python-deps`.
350
+ const infraFailures = [];
351
+ for (const scopeName of infraScopes) {
352
+ try {
353
+ runPluginUpdate({ scope: scopeName, pluginKey: infraKey, env, cwd, claudeBin });
354
+ } catch (e) {
355
+ const reason = `claude plugin update ${infraKey} --scope ${scopeName} failed: ${firstErrorLine(e)}`;
356
+ infraFailures.push(reason);
357
+ print(reason);
358
+ }
359
+ }
337
360
  // v1.18.0 (AC-V118C-5): the verdict is what THIS workspace has installed, read back from the
338
361
  // platform's own registry — never whether the marketplace clone moved in this run (a machine's
339
362
  // second workspace read "already current" whatever it installed).
@@ -344,6 +367,13 @@ export async function runUpdate(argv, { cwd, configDir, homeDir, pkgDir, output,
344
367
  ...(installedAfter ? {} : { reason: 'installed version unreadable from installed_plugins.json' }),
345
368
  });
346
369
 
370
+ if (infraScopes.length > 0) {
371
+ phases.push(infraFailures.length > 0
372
+ ? { name: 'plugin-update-infra', verdict: 'failed', reason: infraFailures.join('; ') }
373
+ : { name: 'plugin-update-infra', verdict: 'ran' });
374
+ }
375
+ const infraFailed = infraFailures.length > 0;
376
+
347
377
  // ── Phase 2b (v1.18.2): the plugin's Python runtime deps — install only what is missing ──────
348
378
  // FOUNDRY_PYTHON names another interpreter (a venv's), and lets tests keep pip off the machine.
349
379
  const pythonDeps = ensurePythonDeps(pythonRequirements, { env: spawnEnv, python: spawnEnv.FOUNDRY_PYTHON || 'python3' });
@@ -403,13 +433,6 @@ export async function runUpdate(argv, { cwd, configDir, homeDir, pkgDir, output,
403
433
  if (gitignoreRow) print(gitignoreRow);
404
434
  }
405
435
 
406
- // amendments-backfill (ER #214, AC-AMB-1/-2): re-planned FRESH from disk like the two blocks
407
- // above, applied with the module's own re-classify-before-append guard.
408
- const amendmentsPlan = planAmendmentsBackfill({ physicalRoot });
409
- applyAmendmentsBackfill(amendmentsPlan);
410
- for (const rel of amendmentsPlan.writtenPaths || []) wrote(rel, 'amendments-backfill');
411
- const amendmentsRow = renderAmendmentsRow(amendmentsPlan);
412
- if (amendmentsRow) print(amendmentsRow);
413
436
  // v1.18.2: release manifests trued up to the current contract — re-planned fresh from disk
414
437
  const trueUpPlan = applyManifestTrueUp(planManifestTrueUp({ physicalRoot }));
415
438
  for (const rel of trueUpPlan.written || []) wrote(rel, 'manifest-true-up');
@@ -421,7 +444,6 @@ export async function runUpdate(argv, { cwd, configDir, homeDir, pkgDir, output,
421
444
  const anyGitignoreChanged = Boolean(
422
445
  freshGitignorePlan && (freshGitignorePlan.action === 'converged' || freshGitignorePlan.action === 'appended'),
423
446
  );
424
- const anyAmendmentsBackfilled = amendmentsPlan.written > 0;
425
447
  // statusline-wiring (v1.17.0, AC-SLW-1/-2): the updater is the post-trust writer of the
426
448
  // wrapper files and the two settings keys (added only when absent). Planned fresh from disk
427
449
  // here, after the floor write above, so the settings read is the current one.
@@ -438,6 +460,8 @@ export async function runUpdate(argv, { cwd, configDir, homeDir, pkgDir, output,
438
460
  if (flags.cleanup && retiredPlan.present > 0) retiredRemoved = applyRetiredArtifacts(retiredPlan, physicalRoot);
439
461
  for (const r of retiredPlan.rows) if (r.state === 'removed') removed.push(r.relPath);
440
462
  for (const row of renderRetiredArtifactRows(retiredPlan, { cleanup: flags.cleanup })) print(row);
463
+ // context-diet-r1 D4: removed plugin verbs a workspace file still names — reported, never rewritten.
464
+ for (const row of renderRetiredVerbRows(planRetiredVerbs({ physicalRoot, catalogue: retiredCatalogue }))) print(row);
441
465
 
442
466
  // settings.local.json (hotfix-v1.17.4): the tracked-file reconcile never reads it, so a
443
467
  // version-pinned floor row an old init left there survived every upgrade. Only RETIREMENT is
@@ -464,7 +488,7 @@ export async function runUpdate(argv, { cwd, configDir, homeDir, pkgDir, output,
464
488
 
465
489
  phases.push({
466
490
  name: 'reinitialization',
467
- verdict: anyCreated || anyFloorAdded || anyGitignoreChanged || anyAmendmentsBackfilled || (trueUpPlan.written || []).length > 0
491
+ verdict: anyCreated || anyFloorAdded || anyGitignoreChanged || (trueUpPlan.written || []).length > 0
468
492
  || statuslineChanged(statuslinePlan) || retiredRemoved > 0 || localRetired > 0 ? 'changed' : 'already current',
469
493
  });
470
494
 
@@ -475,7 +499,7 @@ export async function runUpdate(argv, { cwd, configDir, homeDir, pkgDir, output,
475
499
  // completed run (overwritten — a report, not a managed file; `.foundry/*` is gitignored), and
476
500
  // named in the LAST line so the operator's next step is never a guess.
477
501
  const report = buildUpgradeReport({
478
- installedBefore, installedAfter, afterEntry, toPluginVersion: pins.plugin_version, phases, filePlan, amendmentsPlan,
502
+ installedBefore, installedAfter, afterEntry, toPluginVersion: pins.plugin_version, phases, filePlan,
479
503
  written, removed, configDir, hostname: os.hostname(), pythonDeps,
480
504
  updaterVersion, coreVersion: corePkg.version, updaterPluginVersion: pins.plugin_version,
481
505
  retiredArtifacts: { present: retiredPlan.rows.filter((r) => r.state === 'stale').map((r) => r.relPath), removed: retiredRemoved, refused: retiredPlan.refused },
@@ -500,7 +524,7 @@ export async function runUpdate(argv, { cwd, configDir, homeDir, pkgDir, output,
500
524
  const gitignoreRefused = Boolean(freshGitignorePlan && freshGitignorePlan.action === 'refused');
501
525
  // v1.18.2: a python dep that could not be installed leaves the plugin's scripts broken — exit 2
502
526
  // (attention needed; the row above names what is missing and why), like a refused gitignore.
503
- return { exitCode: anyDrifted || gitignoreRefused || pythonDeps.verdict === 'failed' ? 2 : 0, output: lines.join('\n') };
527
+ return { exitCode: anyDrifted || gitignoreRefused || pythonDeps.verdict === 'failed' || infraFailed ? 2 : 0, output: lines.join('\n') };
504
528
  } catch (e) {
505
529
  if (e instanceof RefusalError) {
506
530
  print(`refused: ${e.message}`);
@@ -5,12 +5,6 @@ verbs are `/foundry:*`; run `/foundry:init` inside a trusted Claude Code session
5
5
  logical wiring (operator registry, project config), then `/foundry:doctor` to confirm
6
6
  `DOCTOR-GREEN`.
7
7
 
8
- ## Stage mode
9
-
10
- Stage mode: {{STAGE_MODE}}
11
-
12
- `lean` favors the direct loop with lighter ceremony; `scale` enforces the full gates.
13
-
14
8
  ## Conventions
15
9
 
16
10
  Specs are atomic: `specs/features/<domain>/<capability>/feat-<capability>.md`, each with stable AC-IDs, a delimited `<!-- normative -->` region, and a sibling `acceptance-contract.yaml`.
@@ -1,180 +0,0 @@
1
- // amendmentsBackfill.mjs — amendments-backfill (ER #214, AC-AMB-1..5).
2
- //
3
- // `/foundry:amend` (v1.11.0) refuses, by design and by test, when a spec has no `## Amendments`
4
- // heading after its LAST `<!-- /normative -->` marker (outside fenced code) — see
5
- // scripts/foundry-amend.py `amendments_section_ok`, whose rule this module mirrors byte for byte
6
- // (tests/test_amendments_backfill.py cross-checks the two over one fixture set). Nothing added that
7
- // section to a spec written before the verb existed, so on an upgraded corpus the verb never fires:
8
- // 0 of 204 specs on one adopter, 7 of 360 on the self-hosting workspace (2026-09-22/23).
9
- //
10
- // The section sits OUTSIDE the hashed normative region, so appending it moves no `spec_sha256`
11
- // and no authorization (AC-AMB-4 pins that with the real hashing function). This module therefore
12
- // runs on the `--existing` reconcile and the upgrader's Phase 4 like the gitignore block does:
13
- // idempotent, never-clobber in the only sense that matters (a spec that already has the section is
14
- // never written), atomic writes, and a plan/apply split so `--dry-run` prints the same row.
15
- import fs from 'node:fs';
16
- import path from 'node:path';
17
- import { confinedJoin } from './util.mjs';
18
-
19
- export const NORMATIVE_CLOSE = '<!-- /normative -->';
20
- export const AMENDMENTS_HEADING = '## Amendments';
21
- /** Exactly what is appended (AC-AMB-1); the leading blank line is added only when the file does
22
- * not already end with one, so a spec ending "...\n" gets "\n## Amendments..." and one ending
23
- * "...\n\n" gets the heading directly. Header columns are `foundry-amend.py`'s own row shape. */
24
- export const AMENDMENTS_BLOCK = `${AMENDMENTS_HEADING}\n\n| date | what changed | why reality required it | auth_seq |\n|---|---|---|---|\n`;
25
-
26
- // ER #223 (v1.17.1): EVERY `*.md` under specs/, not only `feat-*.md` — foundry-amend.py has no
27
- // filename rule (it classifies by the normative region), and an adopter's delivery atoms are named
28
- // `spec-*.md`. A README or template without a normative region lands in `skipped`, never written.
29
- const SPEC_BASENAME_RE = /\.md$/;
30
- const CODE_FENCE_RE = /```[\s\S]*?```/g;
31
- const HEADING_LINE_SRC = '^## Amendments[ \\t]*\\r?$';
32
-
33
- /** The verdict `foundry-amend.py`'s amendments_section_ok gives: `present` when a `## Amendments`
34
- * heading appears after the LAST normative close marker and outside any fenced code block;
35
- * `absent` when it does not; `no-marker` when the spec has no close marker at all (amend's own
36
- * whole-body fallback applies there, and this module never writes such a file). Fenced blocks are
37
- * masked with same-length filler so the heading's offset stays comparable to the marker's, exactly
38
- * as the Python does; CRLF is tolerated because neither search depends on line structure. */
39
- export function classifySpec(text) {
40
- const closeIdx = text.lastIndexOf(NORMATIVE_CLOSE);
41
- if (closeIdx === -1) return 'no-marker';
42
- const masked = text.replace(CODE_FENCE_RE, (m) => '\0'.repeat(m.length));
43
- // v1.18.1: the heading must be a LINE of its own, searched from the marker onward. The first
44
- // occurrence anywhere was used before, so a spec whose normative prose names "`## Amendments`"
45
- // read `absent` although its real section followed the marker — and got another section appended
46
- // on every updater run. Same line rule as the size ceiling's strip_amendments_section.
47
- const heading = new RegExp(HEADING_LINE_SRC, 'gm');
48
- heading.lastIndex = closeIdx;
49
- if (heading.exec(masked)) return 'present';
50
- // A heading BEFORE the marker does not count for amend either — the section must follow the
51
- // normative region — so it is `absent` and the block is appended at the end of the file.
52
- return 'absent';
53
- }
54
-
55
- /** Every regular `*.md` under `<root>/specs` (any basename — ER #223), depth-first, with symlinked FILES reported
56
- * separately (never followed, never written — AC-AMB-2) and symlinked DIRECTORIES not descended
57
- * (the same confinement instinct as the scaffold's confinedJoin: nothing outside the workspace
58
- * root is ever touched). Absent `specs/` yields an empty walk, not an error. */
59
- export function walkSpecs(physicalRoot) {
60
- const files = [];
61
- const symlinks = [];
62
- // v1.17.1 security review Risk 1: the ROOT is confined like every entry under it — a `specs`
63
- // that is itself a symlink (or resolves outside the workspace) is never descended, never written.
64
- const specsRoot = confinedJoin(physicalRoot, 'specs');
65
- if (!specsRoot) return { files, symlinks };
66
- const rootStat = fs.lstatSync(specsRoot, { throwIfNoEntry: false });
67
- if (!rootStat || rootStat.isSymbolicLink() || !rootStat.isDirectory()) return { files, symlinks };
68
- const stack = [specsRoot];
69
- while (stack.length > 0) {
70
- const dir = stack.pop();
71
- let entries;
72
- try {
73
- entries = fs.readdirSync(dir, { withFileTypes: true });
74
- } catch {
75
- continue;
76
- }
77
- for (const ent of entries) {
78
- const abs = path.join(dir, ent.name);
79
- if (ent.isSymbolicLink()) {
80
- if (SPEC_BASENAME_RE.test(ent.name)) symlinks.push(abs);
81
- continue; // never descend a symlinked directory, never write a symlinked file
82
- }
83
- if (ent.isDirectory()) stack.push(abs);
84
- else if (ent.isFile() && SPEC_BASENAME_RE.test(ent.name)) files.push(abs);
85
- }
86
- }
87
- files.sort();
88
- symlinks.sort();
89
- return { files, symlinks };
90
- }
91
-
92
- /** Plan only — no write. `{ toAppend: [abs...], present, skipped, symlinks, total }` where `total`
93
- * counts every regular spec seen (the "of <m>" in the row) and `skipped` is the no-marker count. */
94
- export function planAmendmentsBackfill({ physicalRoot }) {
95
- const { files, symlinks } = walkSpecs(physicalRoot);
96
- const toAppend = [];
97
- let present = 0;
98
- let skipped = 0;
99
- for (const abs of files) {
100
- let text;
101
- try {
102
- text = fs.readFileSync(abs, 'utf-8');
103
- } catch {
104
- skipped += 1;
105
- continue;
106
- }
107
- const verdict = classifySpec(text);
108
- if (verdict === 'present') present += 1;
109
- else if (verdict === 'no-marker') skipped += 1;
110
- else toAppend.push(abs);
111
- }
112
- return { physicalRoot, toAppend, present, skipped, symlinks, total: files.length, applied: false };
113
- }
114
-
115
- /** The bytes to append for a given current text: the block, preceded by one newline when the text
116
- * does not already end with a blank line, and by TWO when it does not end with a newline at all. */
117
- export function appendBytesFor(text) {
118
- if (text === '' || text.endsWith('\n\n') || text.endsWith('\r\n\r\n')) return AMENDMENTS_BLOCK;
119
- if (text.endsWith('\n')) return `\n${AMENDMENTS_BLOCK}`;
120
- return `\n\n${AMENDMENTS_BLOCK}`;
121
- }
122
-
123
- /** Atomic append: read, compose, write a sibling temp file, rename over the original (the same
124
- * discipline as gitignoreReconcile's writer). Re-classifies right before writing so a file that
125
- * gained the section between plan and apply is left alone. Returns the count actually written. */
126
- export function applyAmendmentsBackfill(plan) {
127
- let written = 0;
128
- // v1.18.0 (AC-V118C-8): every planned spec lands in exactly one bucket — written, gained the
129
- // section since the plan (present), or failed — so backfilled + present + skipped + failed ==
130
- // total and the post-upgrade arithmetic check can never refuse on an uncounted file.
131
- let failed = 0;
132
- const writtenPaths = [];
133
- for (const abs of plan.toAppend) {
134
- let text;
135
- try {
136
- text = fs.readFileSync(abs, 'utf-8');
137
- } catch {
138
- failed += 1;
139
- continue;
140
- }
141
- if (classifySpec(text) !== 'absent') { plan.present += 1; continue; }
142
- const tmp = `${abs}.amendments-backfill.tmp`;
143
- // v1.17.1 security review Risk 2: `wx` refuses to write through a planted sibling — a symlink
144
- // or a leftover file at the temp path means this spec is skipped, never written elsewhere.
145
- try {
146
- fs.writeFileSync(tmp, text + appendBytesFor(text), { encoding: 'utf-8', flag: 'wx' });
147
- } catch {
148
- failed += 1;
149
- continue;
150
- }
151
- try {
152
- fs.renameSync(tmp, abs);
153
- } catch {
154
- fs.rmSync(tmp, { force: true });
155
- failed += 1;
156
- continue;
157
- }
158
- written += 1;
159
- if (plan.physicalRoot) writtenPaths.push(path.relative(plan.physicalRoot, abs).split(path.sep).join('/'));
160
- }
161
- plan.applied = true;
162
- plan.written = written;
163
- plan.failed = failed;
164
- plan.writtenPaths = writtenPaths;
165
- return written;
166
- }
167
-
168
- /** The one row (AC-AMB-1). `null` when the workspace has no specs at all, so a fresh scaffold's
169
- * output is unchanged. Under dry-run the count is what WOULD be backfilled; after apply it is what
170
- * was. Symlinked spec files are named so the operator sees what was deliberately not touched. */
171
- export function renderAmendmentsRow(plan) {
172
- if (!plan || (plan.total === 0 && plan.symlinks.length === 0)) return null;
173
- const n = plan.applied ? plan.written : plan.toAppend.length;
174
- const verb = plan.applied ? 'backfilled' : 'would backfill';
175
- let row = ` [amendments] ${verb} ${n} of ${plan.total} specs (${plan.present} already present, ${plan.skipped} skipped: no normative region${plan.failed ? `, ${plan.failed} FAILED to write` : ''})`;
176
- if (plan.symlinks.length > 0) {
177
- row += `; ${plan.symlinks.length} symlinked spec file(s) not touched: ${plan.symlinks.map((p) => path.basename(p)).join(', ')}`;
178
- }
179
- return row;
180
- }