@sabaiway/agent-workflow-kit 23.12.0 → 24.0.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.
Files changed (150) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +4 -4
  3. package/SKILL.md +1 -1
  4. package/bridges/codex-cli-bridge/SKILL.md +7 -2
  5. package/bridges/codex-cli-bridge/bin/codex-exec-jev.test.mjs +11 -6
  6. package/bridges/codex-cli-bridge/bin/codex-exec.sh +72 -33
  7. package/bridges/codex-cli-bridge/bin/codex-exec.test.mjs +111 -3
  8. package/bridges/codex-cli-bridge/bin/codex-fixtures-harness.test.mjs +16 -1
  9. package/bridges/codex-cli-bridge/bin/codex-model-posture.test.mjs +5 -3
  10. package/bridges/codex-cli-bridge/bin/codex-review.sh +1 -1
  11. package/bridges/codex-cli-bridge/capability.json +2 -2
  12. package/capability.json +1 -1
  13. package/package.json +1 -1
  14. package/references/advisor-writers.md +2 -0
  15. package/references/agents/author.md +21 -0
  16. package/references/agents/executor.md +12 -6
  17. package/references/contracts.md +4 -4
  18. package/references/hooks/gate-approve.mjs +7 -8
  19. package/references/hooks/stage-write-guard.mjs +314 -0
  20. package/references/modes/agents.md +6 -4
  21. package/references/modes/bootstrap.md +1 -1
  22. package/references/modes/flow-writer.md +10 -2
  23. package/references/modes/hook.md +4 -1
  24. package/references/modes/now.md +1 -1
  25. package/references/modes/procedures.md +49 -10
  26. package/references/modes/recipes.md +7 -7
  27. package/references/modes/recommendations.md +4 -3
  28. package/references/modes/robustness-brief.md +9 -8
  29. package/references/modes/set-recipe.md +1 -1
  30. package/references/modes/state-block-guard.md +4 -3
  31. package/references/modes/status.md +1 -1
  32. package/references/modes/upgrade.md +1 -1
  33. package/references/modes/worktrees.md +28 -5
  34. package/references/rules/story-sessions.md +2 -2
  35. package/references/scripts/archives/archive-caps.mjs +1 -1
  36. package/references/scripts/archives/archive-changelog.mjs +8 -8
  37. package/references/scripts/archives/archive-decisions.mjs +7 -7
  38. package/references/scripts/archives/archive-issues.mjs +5 -5
  39. package/references/scripts/archives/rotation-conservation.mjs +2 -1
  40. package/references/scripts/docs-size/check-docs-size.mjs +15 -15
  41. package/references/scripts/family.json +2 -0
  42. package/references/scripts/gates/kit-command-gates.mjs +7 -8
  43. package/references/scripts/gates/migrate-gates.mjs +10 -10
  44. package/references/scripts/git-hooks/install-git-hooks.mjs +13 -13
  45. package/references/scripts/run.mjs +1 -2
  46. package/references/scripts/shared/index.mjs +2 -0
  47. package/references/scripts/shared/locations.mjs +103 -0
  48. package/references/scripts/spec-schema/spec-schema.mjs +2 -1
  49. package/references/templates/orchestration.json +1 -1
  50. package/tools/ack-store.mjs +2 -1
  51. package/tools/apply-danger-check.mjs +20 -6
  52. package/tools/atomic-write.mjs +3 -2
  53. package/tools/attribution.mjs +2 -1
  54. package/tools/autonomy-config.mjs +2 -1
  55. package/tools/bridge-wiring.mjs +13 -11
  56. package/tools/carriers.mjs +54 -14
  57. package/tools/cheap-agents-read.mjs +28 -7
  58. package/tools/cheap-agents.mjs +15 -10
  59. package/tools/checker-gates-read.mjs +6 -5
  60. package/tools/commands.mjs +2 -2
  61. package/tools/coverage-declared/config.mjs +2 -1
  62. package/tools/coverage-producer.mjs +10 -9
  63. package/tools/delegation.mjs +7 -6
  64. package/tools/detect-backends.mjs +1 -1
  65. package/tools/dispatch-baseline.mjs +2 -1
  66. package/tools/distribution-files/scripts.mjs +4 -4
  67. package/tools/ensure-configs.mjs +2 -2
  68. package/tools/ensure-ops.mjs +24 -24
  69. package/tools/ensure-specs.mjs +7 -7
  70. package/tools/epic-shape-cli.mjs +2 -2
  71. package/tools/epic-shape-ledger.mjs +5 -5
  72. package/tools/epic-shape.mjs +5 -3
  73. package/tools/epic-store.mjs +2 -1
  74. package/tools/family-members.mjs +7 -5
  75. package/tools/family-registry.mjs +36 -30
  76. package/tools/feedback-record-cli.mjs +4 -5
  77. package/tools/flow-writer.mjs +26 -15
  78. package/tools/gate-hook.mjs +33 -28
  79. package/tools/gates-declaration.mjs +2 -1
  80. package/tools/gates-init.mjs +6 -5
  81. package/tools/git-hooks.mjs +64 -41
  82. package/tools/grounding.mjs +3 -2
  83. package/tools/hide-footprint.mjs +2 -1
  84. package/tools/hook-writer/index.mjs +147 -0
  85. package/tools/init-preflight.mjs +5 -4
  86. package/tools/init-project.mjs +12 -11
  87. package/tools/inject-methodology.mjs +3 -2
  88. package/tools/jev-guide.mjs +2 -2
  89. package/tools/known-footprint.mjs +27 -25
  90. package/tools/mcp-registration.mjs +6 -5
  91. package/tools/migration-blocks.mjs +2 -1
  92. package/tools/migration-notes.mjs +2 -2
  93. package/tools/node-evidence.mjs +4 -4
  94. package/tools/now-facts.mjs +5 -5
  95. package/tools/now-status.mjs +1 -5
  96. package/tools/orchestration-config.mjs +2 -1
  97. package/tools/orchestration-readme.mjs +7 -2
  98. package/tools/plan-approval/cli.mjs +45 -0
  99. package/tools/plan-approval/entries.mjs +109 -0
  100. package/tools/plan-approval/index.mjs +2 -0
  101. package/tools/plan-approval/record.mjs +198 -0
  102. package/tools/plan-files.mjs +6 -4
  103. package/tools/plan-shape-cli.mjs +10 -64
  104. package/tools/plan-shape-facts.mjs +240 -83
  105. package/tools/plan-shape.mjs +173 -160
  106. package/tools/plan-structure/cli.mjs +79 -0
  107. package/tools/plan-structure/index.mjs +67 -0
  108. package/tools/procedures.mjs +21 -17
  109. package/tools/profile-gaps.mjs +4 -6
  110. package/tools/project-rules/rules-priors.mjs +2 -0
  111. package/tools/project-rules/themes.mjs +6 -4
  112. package/tools/recipes.mjs +44 -29
  113. package/tools/recommendations.mjs +84 -33
  114. package/tools/reference-profile.mjs +2 -2
  115. package/tools/renderers.mjs +14 -8
  116. package/tools/repo-lex.mjs +84 -0
  117. package/tools/robustness-brief.mjs +14 -11
  118. package/tools/satellite-locator.mjs +3 -2
  119. package/tools/script-priors.mjs +3 -2
  120. package/tools/session-close-check.mjs +71 -15
  121. package/tools/set-flow.mjs +2 -2
  122. package/tools/set-recipe.mjs +17 -9
  123. package/tools/source-size/help.mjs +4 -4
  124. package/tools/source-size/layout.mjs +2 -1
  125. package/tools/source-size/piles.mjs +2 -2
  126. package/tools/source-size-config.mjs +3 -3
  127. package/tools/source-size-refusal.mjs +4 -3
  128. package/tools/source-size-report.mjs +41 -13
  129. package/tools/spec-check-cli.mjs +159 -21
  130. package/tools/spec-check-ops.mjs +74 -5
  131. package/tools/spec-check.mjs +54 -45
  132. package/tools/spec-coverage-cli.mjs +3 -2
  133. package/tools/stage-render/cli.mjs +231 -0
  134. package/tools/stage-render/index.mjs +340 -0
  135. package/tools/stage-render/stages.json +115 -0
  136. package/tools/stage-write-guard/cli.mjs +64 -0
  137. package/tools/stage-write-guard/index.mjs +56 -0
  138. package/tools/state-block-hook.mjs +38 -163
  139. package/tools/task-brief.mjs +8 -13
  140. package/tools/task-thread.mjs +3 -1
  141. package/tools/tier-guide-facts.mjs +23 -9
  142. package/tools/tier-preview.mjs +15 -19
  143. package/tools/transition/index.mjs +10 -9
  144. package/tools/uninstall.mjs +26 -12
  145. package/tools/vehicle-settings.mjs +2 -1
  146. package/tools/velocity-profile.mjs +5 -6
  147. package/tools/view-model.mjs +7 -4
  148. package/tools/worktree-prompt.mjs +7 -3
  149. package/tools/worktrees.mjs +235 -159
  150. package/tools/write-lanes.mjs +20 -14
@@ -12,11 +12,12 @@ import {
12
12
  symlinkSync, realpathSync, unlinkSync, openSync, fstatSync, readSync, writeSync, fchmodSync,
13
13
  closeSync, constants as fsC,
14
14
  } from 'node:fs';
15
- import { join, dirname, basename, resolve, relative, isAbsolute, sep } from 'node:path';
15
+ import { join, dirname, basename, posix, resolve, relative, isAbsolute, sep } from 'node:path';
16
16
  import { fileURLToPath } from 'node:url';
17
17
  import { spawnSync } from 'node:child_process';
18
18
  import { randomBytes } from 'node:crypto';
19
19
 
20
+ import { BINDING_GYP, BUN_LOCK, BUN_LOCKB, CODEX_LAST_SESSION, DOCS_TREE, GATES, LERNA_JSON, NODE_MODULES, NPM_LOCK, PACKAGE_JSON, PNPM_LOCK, PNPM_WORKSPACE, PNPM_WORKSPACE_YML, QUEUE, SETTINGS_LOCAL, SYNC_MIRRORS, VSCODE_DIR, VSCODE_SETTINGS, WORKTREES, YARN_LOCK } from '../references/scripts/shared/index.mjs';
20
21
  import { MCP_JSON_REL, SERVER_NAME, SETTINGS_REL, withoutRegistration } from './mcp-registration.mjs';
21
22
  import {
22
23
  KIT_OWN_PATHS, KNOWN_FOOTPRINT, expandGlob, normalizeSlashes, isDirPattern, isGlobPattern,
@@ -24,7 +25,7 @@ import {
24
25
  } from './known-footprint.mjs';
25
26
  import { isDirectRun } from './direct-run.mjs';
26
27
  import { isScratchPlanName, plansInFlight, PLANS_REL } from './plan-files.mjs';
27
- import { shellQuoteArg } from './repo-lex.mjs';
28
+ import { escapeRegExp, parseStrictJson, shellQuoteArg } from './repo-lex.mjs';
28
29
  import { writeContainedFileAtomic } from './atomic-write.mjs';
29
30
  import { assertContainedRealPath } from './fs-safe.mjs';
30
31
  import { GIT_MAX_BUFFER } from './git-env.mjs';
@@ -41,6 +42,10 @@ import {
41
42
  import { composeSatellitePrompt, resolveSeededPlan } from './worktree-prompt.mjs';
42
43
  import { applySlot } from './write-lanes.mjs';
43
44
  import { dirCovers } from './declared-paths.mjs';
45
+ import { RECEIPTS_BASENAME } from './core-evidence-receipts.mjs';
46
+ import { readRegularFileNoFollow } from './fs-read-nofollow.mjs';
47
+ import { OUTCOME_LINES as APPROVAL_LINES, appendApproval, getLocalDate, readApproval } from './plan-approval/index.mjs';
48
+ import { RECORD_GATED_STAGES, STAGES_REL, composeRenderCommand, composeSlotText, loadStages, validateSlots } from './stage-render/index.mjs';
44
49
 
45
50
  // The record format and the satellite locator now live in leaves the dispatch side reads too — but
46
51
  // every name they took away is re-exported here, so no import site and no asserted error `code`
@@ -58,14 +63,14 @@ const errorText = (error) => String(error?.message ?? error).replace(/^\[agent-w
58
63
  const composeFailure = (primary, secondaryName, secondary) =>
59
64
  stop(`${errorText(primary)}; ${secondaryName} failed: ${errorText(secondary)}`);
60
65
 
61
- export const CONFIG_REL = 'docs/ai/worktrees.json';
66
+ export const CONFIG_REL = WORKTREES;
62
67
  export const SLUG_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
63
68
  const WORKTREES_TOOL_ABS = fileURLToPath(import.meta.url);
64
69
  const WORKTREES_TOOL_DIR = dirname(WORKTREES_TOOL_ABS);
65
70
 
66
71
  // Stores/sidecars a fresh worktree must NOT inherit (session state stays with its session).
67
72
  const EXCLUDED_BASENAMES = new Set([
68
- '.codex-last-session',
73
+ CODEX_LAST_SESSION,
69
74
  'agent-workflow-review-receipts.jsonl',
70
75
  'agent-workflow-core-evidence.jsonl',
71
76
  ]);
@@ -73,22 +78,30 @@ const EXCLUDED_BASENAMES = new Set([
73
78
  const SEEDED_SEPARATELY = new Set([`/${PLANS_REL}/`]);
74
79
  // Never copied AND never owned — unlike SEEDED_SEPARATELY, whose members cleanup may still remove.
75
80
  // A satellite's own `.mcp.json` must stay FOREIGN or an ordinary cleanup deletes what we never placed.
76
- const NEVER_PROVISIONED = new Set(['/.mcp.json']);
81
+ const NEVER_PROVISIONED = new Set([`/${MCP_JSON_REL}`]);
77
82
  // Copied files whose absolute main-root pins are rebased onto the worktree root.
78
- const REBASE_TARGETS = Object.freeze(['docs/ai/gates.json', '.claude/settings.json', '.claude/settings.local.json']);
83
+ const REBASE_TARGETS = Object.freeze([GATES, SETTINGS_REL, SETTINGS_LOCAL]);
79
84
  const TRACKED_PIN_DECLARATION =
80
85
  'tracked declaration is not worktree-portable — this worktree\'s council/final checks route through the MAIN runner via --cwd';
81
- const TRANSFER_EXCLUSIONS = Object.freeze([':!docs/ai', ':!docs/plans']);
86
+ const TRANSFER_EXCLUSIONS = Object.freeze([`:!${DOCS_TREE}`, `:!${PLANS_REL}`]);
82
87
  const PREPARE_LOCK_BASENAME = 'aw-prepare-lock';
88
+ const SLOT_FILE_REL = `${PLANS_REL}/next-session.json`;
89
+ const DEFAULT_STAGE = 'tests';
90
+ const STAGES_ABS = join(dirname(WORKTREES_TOOL_DIR), STAGES_REL);
91
+ const TOOL_EXIT_OK = 0;
92
+ const TOOL_EXIT_USAGE = 2;
83
93
 
84
94
  const USAGE = [
85
95
  'usage: worktrees.mjs <subcommand> [args]',
86
96
  '',
87
97
  ' provision <slug> --plan <path> [--as <name>.md] [--dir <path>] [--branch <name>]',
88
- ' [--include <path>]... [--install] [--resume]',
98
+ ' [--include <path>]... [--install] [--resume] [--stage <id>]',
89
99
  ' create + populate a feature worktree (sibling dir by default; the parent dir is',
90
100
  ` the ${CONFIG_REL} "parentDir" setting when present). --install only PRINTS the`,
91
101
  ' install command. --resume completes a half-done provision (identity-checked).',
102
+ ' Only a plan with a matching approval record is provisioned; its entry is carried',
103
+ ` into the worktree's record and ${SLOT_FILE_REL} is written for --stage`,
104
+ ` (${RECORD_GATED_STAGES.join(', ')}; ${DEFAULT_STAGE} when absent).`,
92
105
  ' list show every worktree of this repo: slug, path, branch, base OID, dirty, handoff.',
93
106
  ' prompt <slug>',
94
107
  ' re-print the satellite cold-start prompt for a provisioned worktree: where it is,',
@@ -400,95 +413,15 @@ export const validateSlug = (slug) => {
400
413
  return slug;
401
414
  };
402
415
 
403
- export const parseStrictJson = (text) => {
404
- const source = String(text);
405
- const cursor = { index: 0 };
406
- const skipWhitespace = () => {
407
- while (/\s/.test(source[cursor.index] ?? '')) cursor.index += 1;
408
- };
409
- const readString = () => {
410
- const start = cursor.index;
411
- cursor.index += 1;
412
- while (cursor.index < source.length) {
413
- if (source[cursor.index] === '\\') {
414
- cursor.index += 2;
415
- } else if (source[cursor.index] === '"') {
416
- cursor.index += 1;
417
- return JSON.parse(source.slice(start, cursor.index));
418
- } else {
419
- cursor.index += 1;
420
- }
421
- }
422
- return null;
423
- };
424
- const childPath = (path, key) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key)
425
- ? `${path}.${key}`
426
- : `${path}[${JSON.stringify(key)}]`;
427
- const scanValue = (path) => {
428
- skipWhitespace();
429
- if (source[cursor.index] === '{') {
430
- cursor.index += 1;
431
- skipWhitespace();
432
- const seen = new Set();
433
- if (source[cursor.index] === '}') {
434
- cursor.index += 1;
435
- return;
436
- }
437
- while (cursor.index < source.length) {
438
- const key = readString();
439
- if (seen.has(key)) throw new SyntaxError(`duplicate JSON key ${JSON.stringify(key)} at ${path}`);
440
- seen.add(key);
441
- skipWhitespace();
442
- cursor.index += 1;
443
- scanValue(childPath(path, key));
444
- skipWhitespace();
445
- if (source[cursor.index] === '}') {
446
- cursor.index += 1;
447
- return;
448
- }
449
- cursor.index += 1;
450
- skipWhitespace();
451
- }
452
- return;
453
- }
454
- if (source[cursor.index] === '[') {
455
- cursor.index += 1;
456
- skipWhitespace();
457
- if (source[cursor.index] === ']') {
458
- cursor.index += 1;
459
- return;
460
- }
461
- let item = 0;
462
- while (cursor.index < source.length) {
463
- scanValue(`${path}[${item}]`);
464
- item += 1;
465
- skipWhitespace();
466
- if (source[cursor.index] === ']') {
467
- cursor.index += 1;
468
- return;
469
- }
470
- cursor.index += 1;
471
- }
472
- return;
473
- }
474
- if (source[cursor.index] === '"') {
475
- readString();
476
- return;
477
- }
478
- while (cursor.index < source.length && !/[\s,}\]]/.test(source[cursor.index])) cursor.index += 1;
479
- };
480
- // the duplicate scan tolerates malformed tails (EOF-safe returns); JSON.parse then rejects them
481
- scanValue('$');
482
- return JSON.parse(source);
483
- };
416
+ export { parseStrictJson } from './repo-lex.mjs';
484
417
 
485
418
  export const loadWorktreesConfig = (root, deps = {}) => {
486
419
  const fs = fsOf(deps);
487
420
  // the ancestor chain is verified even when the leaf is absent — a symlinked docs/ or docs/ai
488
421
  // must never read as plain absence
489
422
  let dir = root;
490
- for (const seg of ['docs', 'ai']) {
491
- dir = join(dir, seg);
423
+ for (const segment of DOCS_TREE.split('/')) {
424
+ dir = join(dir, segment);
492
425
  let st;
493
426
  try {
494
427
  st = fs.lstat(dir);
@@ -628,6 +561,7 @@ const provisionFlagsTail = (flags, q) => {
628
561
  for (const inc of flags.include ?? []) parts.push('--include', q(inc));
629
562
  if (flags.install) parts.push('--install');
630
563
  if (flags.resume) parts.push('--resume');
564
+ if (flags.stage) parts.push('--stage', q(flags.stage));
631
565
  return parts;
632
566
  };
633
567
 
@@ -890,8 +824,6 @@ export const copyTreeIfMissing = ({ srcAbs, dstAbs, wtRoot, rel, deps = {} }) =>
890
824
 
891
825
  // ── absolute-pin rebase (pure; slash-normalized both ways) ─────────────────────────────
892
826
 
893
- const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
894
-
895
827
  export const rebaseAbsolutePins = (text, mainRoot, wtRoot) => {
896
828
  const mainFwd = normalizeSlashes(mainRoot);
897
829
  const wtFwd = normalizeSlashes(wtRoot);
@@ -902,9 +834,9 @@ export const rebaseAbsolutePins = (text, mainRoot, wtRoot) => {
902
834
  const mainBack2 = mainBack.replace(/\\/g, '\\\\');
903
835
  const wtBack2 = wtBack.replace(/\\/g, '\\\\');
904
836
  const boundary = '(?=[/\\\\"\'\\s]|$)';
905
- const fwdRe = () => new RegExp(escapeRe(mainFwd) + boundary, 'g');
906
- const backRe = () => new RegExp(escapeRe(mainBack) + boundary, 'g');
907
- const back2Re = () => new RegExp(escapeRe(mainBack2) + boundary, 'g');
837
+ const fwdRe = () => new RegExp(escapeRegExp(mainFwd) + boundary, 'g');
838
+ const backRe = () => new RegExp(escapeRegExp(mainBack) + boundary, 'g');
839
+ const back2Re = () => new RegExp(escapeRegExp(mainBack2) + boundary, 'g');
908
840
  // function replacements — a worktree path carrying $&/$$/$' must land byte-literal
909
841
  const rebased = text.replace(back2Re(), () => wtBack2).replace(fwdRe(), () => wtFwd).replace(backRe(), () => wtBack);
910
842
  const changes = [];
@@ -1079,7 +1011,7 @@ const listPlansIndexEntries = ({ git, cwd }) => {
1079
1011
  };
1080
1012
 
1081
1013
  const plansChainRels = ({ slug, seedName }) =>
1082
- [...new Set([`${PLANS_REL}/${handoffBasename(slug)}`, `${PLANS_REL}/${seedName}`])];
1014
+ [...new Set([`${PLANS_REL}/${handoffBasename(slug)}`, `${PLANS_REL}/${seedName}`, SLOT_FILE_REL])];
1083
1015
 
1084
1016
  // The finding kind is decided over EVERY entry of the path from BOTH sources; an unmerged
1085
1017
  // index state — several stages OR a single non-zero stage — is irregular outright, never a
@@ -1256,7 +1188,7 @@ const assertPlansChainCleanOnResume = ({ git, root, wtRoot, slug, branch, rels,
1256
1188
 
1257
1189
  // The orientation facts a fresh satellite session cannot derive from its own checkout. They are
1258
1190
  // CONSTANTS so the doc-parity registry can pin the mode doc to the exact strings the tool emits.
1259
- export const QUEUE_BASENAME = 'queue.md';
1191
+ export const QUEUE_BASENAME = posix.basename(QUEUE);
1260
1192
  // QUEUE_SHARED_RULE travels with the composer that emits it (worktrees-record.mjs) and is
1261
1193
  // re-exported above; LANDING_FROM_MAIN stays where its only user is.
1262
1194
  export const LANDING_FROM_MAIN = 'landing runs FROM MAIN, never from this worktree';
@@ -1281,6 +1213,7 @@ export const INCLUDE_IDENTITY_RULE = 'An --include source is copied only through
1281
1213
  export const PLACEMENT_REGISTRY = Object.freeze([
1282
1214
  'handoff-stub',
1283
1215
  'seed-plan',
1216
+ 'slot-file',
1284
1217
  'copy-set-leaf',
1285
1218
  'include-leaf',
1286
1219
  'node-modules-link',
@@ -1409,7 +1342,7 @@ const landingCommand = ({ root, slug }) =>
1409
1342
  `${composeOwnToolPrefix(root)} land ${shellQuoteArg(slug)} --prepare`;
1410
1343
 
1411
1344
  const orientationFields = ({ root, slug }) => ({
1412
- sharedQueue: join(root, PLANS_REL, QUEUE_BASENAME),
1345
+ sharedQueue: join(root, QUEUE),
1413
1346
  landing: composeLandingValue({ rule: LANDING_FROM_MAIN, command: landingCommand({ root, slug }) }),
1414
1347
  });
1415
1348
 
@@ -1449,7 +1382,7 @@ const assertIncludeNeverCopiesTheQueue = ({ rootReal, incReal, inc, fs, contract
1449
1382
  // `contract` marks the WALK-TIME (point-of-use) call: its failures are include-identity
1450
1383
  // refusals and carry the door contract; the pre-mutation preflight call keeps the plain form.
1451
1384
  const withContract = (message) => stop(contract ? `${message}\n${INCLUDE_IDENTITY_RULE}` : message);
1452
- const queueLexical = join(rootReal, PLANS_REL, QUEUE_BASENAME);
1385
+ const queueLexical = join(rootReal, QUEUE);
1453
1386
  const queuePaths = [queueLexical];
1454
1387
  try {
1455
1388
  queuePaths.push(fs.realpath(queueLexical));
@@ -1568,6 +1501,130 @@ const writeSeedPlan = ({ wtRoot, srcAbs, name, fs, report, journal = NO_JOURNAL
1568
1501
  report.push(` seeded plan: ${PLANS_REL}/${name}`);
1569
1502
  };
1570
1503
 
1504
+ // ── the plan approval and the stage slot file (specs kit/plan-approval and kit/stage-render) ─
1505
+
1506
+ // The record sits beside the review receipts, so pinning their resolver to the git dir the injected
1507
+ // git answers keeps provision's reads, its carry and the stage writer on one record file.
1508
+ const approvalEnv = (gitDir) => ({ ...process.env, AW_REVIEW_RECEIPTS: join(gitDir, RECEIPTS_BASENAME) });
1509
+
1510
+ const resolveGitDir = (git, cwd) => {
1511
+ const gitDir = gitLine(git, ['rev-parse', '--path-format=absolute', '--git-dir'], cwd);
1512
+ if (gitDir == null) throw stop(`cannot resolve the git dir of ${cwd}`);
1513
+ return gitDir;
1514
+ };
1515
+
1516
+ const approvalLines = (plan, result) => [
1517
+ ...(result.malformedLines ?? []).map((line) => APPROVAL_LINES.malformed(result.recordPath, line)),
1518
+ ...(result.verdict?.result.findings ?? []).map((finding) => APPROVAL_LINES.finding(plan, finding)),
1519
+ ];
1520
+
1521
+ const placedInstance = ({ root, wtRoot, planFlag, seedName, fs }) => {
1522
+ const placed = `${PLANS_REL}/${seedName}`;
1523
+ return lstatNoFollow(fs.lstat, join(wtRoot, placed)) === null ? { cwd: root, plan: planFlag } : { cwd: wtRoot, plan: placed };
1524
+ };
1525
+
1526
+ // The match is the work tree's own record first, then MAIN's, whose contracts are digested in MAIN; MAIN's
1527
+ // matching entry is returned to be carried, null when the work tree already holds one. An unreadable
1528
+ // work-tree record never falls back.
1529
+ const requireInstanceApproval = ({ instance, root, worktreeGitDir, mainGitDir, report }) => {
1530
+ if (process.env.AW_REVIEW_RECEIPTS) {
1531
+ throw stop('provision refuses: AW_REVIEW_RECEIPTS is set, so the worktree\'s plan approval record would be MAIN\'s own file — unset it, then re-run');
1532
+ }
1533
+ const read = (gitDir, contractsCwd) => readApproval({ cwd: instance.cwd, contractsCwd, env: approvalEnv(gitDir), plan: instance.plan });
1534
+ const accept = (result) => {
1535
+ report.push(...approvalLines(instance.plan, result).map((line) => ` ${line}`));
1536
+ return result.match;
1537
+ };
1538
+ const local = worktreeGitDir === null ? null : read(worktreeGitDir, instance.cwd);
1539
+ if (local?.exitCode === TOOL_EXIT_OK) {
1540
+ accept(local);
1541
+ return null;
1542
+ }
1543
+ const result = local?.exitCode === TOOL_EXIT_USAGE ? local : read(mainGitDir, root);
1544
+ if (result.exitCode === TOOL_EXIT_OK) return accept(result);
1545
+ throw stop([
1546
+ `provision refuses: the plan ${displayValue(instance.plan)} has no matching approval record in ${worktreeGitDir === null ? 'MAIN' : 'this worktree or in MAIN'} — a worktree is provisioned only for an approved plan`,
1547
+ APPROVAL_LINES.refused(instance.plan, result.reason),
1548
+ ...approvalLines(instance.plan, result),
1549
+ ].join('\n'));
1550
+ };
1551
+
1552
+ const carryApproval = ({ wtRoot, gitDir, match, report }) => {
1553
+ if (match === null) return;
1554
+ const result = appendApproval({ cwd: wtRoot, env: approvalEnv(gitDir), entry: { ...match, from: 'provision' } });
1555
+ if (result.exitCode !== TOOL_EXIT_OK) {
1556
+ throw stop([`provision could not carry the approval of ${displayValue(match.plan)} into the worktree's record`,
1557
+ APPROVAL_LINES.error(match.plan, result.reason), ...approvalLines(match.plan, result)].join('\n'));
1558
+ }
1559
+ report.push(` plan approval: ${result.written ? 'carried from MAIN' : 'already carried'} into ${result.recordPath}`,
1560
+ ...approvalLines(match.plan, result).map((line) => ` ${line}`));
1561
+ };
1562
+
1563
+ const loadStageTable = (stagesPath = STAGES_ABS) => {
1564
+ const read = readRegularFileNoFollow(stagesPath);
1565
+ if (read.outcome !== 'ok' || read.closeFailure) {
1566
+ throw stop(`the stage table ${stagesPath} is not readable (${read.closeFailure ?? read.code ?? read.outcome}) — upgrade the kit`);
1567
+ }
1568
+ try {
1569
+ return loadStages(read.content);
1570
+ } catch (err) {
1571
+ throw stop(`the stage table ${stagesPath} is refused: ${errorText(err)} — upgrade the kit`);
1572
+ }
1573
+ };
1574
+
1575
+ const REWRITE_SLOT = `re-run --resume with --stage <${RECORD_GATED_STAGES.join('|')}> to rewrite it, or remove it`;
1576
+ const REMOVE_SLOT = 'remove it, then finish with --resume';
1577
+ const slotRefusal = (detail, remedy) => stop(`provision refuses: the slot file ${SLOT_FILE_REL} in the worktree ${detail} — ${remedy}`);
1578
+ const refusingSlot = (detail, remedy, compose) => {
1579
+ try {
1580
+ return compose();
1581
+ } catch (err) {
1582
+ throw slotRefusal(`${detail} (${errorText(err)})`, remedy);
1583
+ }
1584
+ };
1585
+
1586
+ // Decided before the first provision write: a non-regular node refuses, and only a --resume without
1587
+ // --stage keeps a regular slot file, which keepSlotFile judges once the plan is seeded.
1588
+ const planSlotFile = ({ wtRoot, flags, fs }) => {
1589
+ const node = classifyNodeNoFollow(join(wtRoot, SLOT_FILE_REL), fs);
1590
+ if (node.kind !== 'absent' && node.kind !== 'regular-file') {
1591
+ throw slotRefusal(node.kind === 'error' ? `cannot be inspected (${node.error})` : `is a ${node.kind}, not a regular file`, REMOVE_SLOT);
1592
+ }
1593
+ const keep = node.kind === 'regular-file' && flags.resume && flags.stage === null;
1594
+ return { write: !keep, stage: flags.stage ?? DEFAULT_STAGE };
1595
+ };
1596
+
1597
+ const keepSlotFile = ({ wtRoot, seedName, stagesPath }) => {
1598
+ const table = loadStageTable(stagesPath);
1599
+ const slots = refusingSlot('does not validate', REWRITE_SLOT, () => validateSlots({ root: wtRoot, slotFile: SLOT_FILE_REL, table }));
1600
+ if (slots.plan !== `${PLANS_REL}/${seedName}`) {
1601
+ throw slotRefusal(`names the plan ${displayValue(JSON.stringify(slots.plan ?? null))}, not ${PLANS_REL}/${displayValue(seedName)}`, REWRITE_SLOT);
1602
+ }
1603
+ if (!RECORD_GATED_STAGES.includes(slots.stage)) {
1604
+ throw slotRefusal(`names the stage ${displayValue(JSON.stringify(slots.stage))}, outside ${RECORD_GATED_STAGES.join(', ')}`, REWRITE_SLOT);
1605
+ }
1606
+ return slots.stage;
1607
+ };
1608
+
1609
+ const composeSlotFile = ({ wtRoot, seedName, stage, stagesPath }) => {
1610
+ const table = loadStageTable(stagesPath);
1611
+ return refusingSlot(`cannot be composed for the stage ${displayValue(stage)}`, REMOVE_SLOT, () => {
1612
+ const text = composeSlotText({ stage, values: { plan: `${PLANS_REL}/${seedName}` }, date: getLocalDate(), table });
1613
+ validateSlots({ root: wtRoot, slotFile: SLOT_FILE_REL, table, text });
1614
+ return text;
1615
+ });
1616
+ };
1617
+
1618
+ const writeSlotFile = ({ wtRoot, seedName, slot, stagesPath, fs, report, journal }) => {
1619
+ const stage = slot.write ? slot.stage : keepSlotFile({ wtRoot, seedName, stagesPath });
1620
+ if (slot.write) {
1621
+ const text = composeSlotFile({ wtRoot, seedName, stage, stagesPath });
1622
+ writeContainedFileAtomic(wtRoot, join(wtRoot, SLOT_FILE_REL), text, fs, { stop: (m) => stop(m) });
1623
+ }
1624
+ journal.record({ rel: SLOT_FILE_REL, surface: 'slot-file', outcome: slot.write ? 'written' : 'kept' });
1625
+ report.push(` slot file: ${SLOT_FILE_REL} (${slot.write ? 'written' : 'kept'}, stage ${stage})`);
1626
+ };
1627
+
1571
1628
  // The include set is resolved and identity-checked in runProvision — BEFORE `git worktree add` —
1572
1629
  // against the queue-copy guard and the round-trip guard, and arrives here as {rel, real} pairs.
1573
1630
  // It is copied from that already-canonical `real`, NEVER re-resolved from the raw path: a fresh
@@ -1575,7 +1632,7 @@ const writeSeedPlan = ({ wtRoot, srcAbs, name, fs, report, journal = NO_JOURNAL
1575
1632
  // redirect an include at the shared series index between the check and the copy.
1576
1633
  const provisionIncludes = ({ rootReal, wtRoot, includeSources, resume, git, fs, report, copied, journal = NO_JOURNAL }) => {
1577
1634
  const recorded = [];
1578
- const queuePath = join(rootReal, PLANS_REL, QUEUE_BASENAME);
1635
+ const queuePath = join(rootReal, QUEUE);
1579
1636
  for (const { rel, real, identity } of includeSources) {
1580
1637
  // Defence in depth: re-assert the queue-copy prohibition on the canonical path at the POINT OF
1581
1638
  // USE, so it holds where the copy happens and not only where the path was first checked.
@@ -1618,11 +1675,11 @@ const provisionIncludes = ({ rootReal, wtRoot, includeSources, resume, git, fs,
1618
1675
  };
1619
1676
 
1620
1677
  const LOCKFILE_MANAGERS = Object.freeze([
1621
- ['package-lock.json', 'npm'],
1622
- ['pnpm-lock.yaml', 'pnpm'],
1623
- ['yarn.lock', 'yarn'],
1624
- ['bun.lockb', 'bun'],
1625
- ['bun.lock', 'bun'],
1678
+ [NPM_LOCK, 'npm'],
1679
+ [PNPM_LOCK, 'pnpm'],
1680
+ [YARN_LOCK, 'yarn'],
1681
+ [BUN_LOCKB, 'bun'],
1682
+ [BUN_LOCK, 'bun'],
1626
1683
  ]);
1627
1684
  const NEUTRAL_INSTALL_ADVICE =
1628
1685
  'install command not printed — package manager is ambiguous or unknown; install dependencies in the worktree by hand';
@@ -1630,7 +1687,7 @@ const NEUTRAL_INSTALL_ADVICE =
1630
1687
  // Advice evidence = the WORKTREE'S OWN LIVE checkout (manifest AND lockfiles): the printed
1631
1688
  // command runs in the satellite, so what main's working tree happens to hold must not steer it.
1632
1689
  const resolveInstallAdvice = ({ wtRoot, fs }) => {
1633
- const pkg = readFileNoFollow(fs, join(wtRoot, 'package.json'));
1690
+ const pkg = readFileNoFollow(fs, join(wtRoot, PACKAGE_JSON));
1634
1691
  let manager = null;
1635
1692
  let inspectLocks = false;
1636
1693
  if (pkg.absent) {
@@ -1681,7 +1738,7 @@ const resolveInstallAdvice = ({ wtRoot, fs }) => {
1681
1738
  export const DEPENDENCY_FIELDS = Object.freeze(['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']);
1682
1739
  // Workspace declarations this tool cannot read. Their presence makes the dependency inventory
1683
1740
  // unknowable from package.json alone, so it is never proof.
1684
- export const EXTERNAL_WORKSPACE_MANIFESTS = Object.freeze(['pnpm-workspace.yaml', 'pnpm-workspace.yml', 'lerna.json']);
1741
+ export const EXTERNAL_WORKSPACE_MANIFESTS = Object.freeze([PNPM_WORKSPACE, PNPM_WORKSPACE_YML, LERNA_JSON]);
1685
1742
 
1686
1743
  const readPackageJson = (fs, path) => {
1687
1744
  const file = readFileNoFollow(fs, path);
@@ -1732,7 +1789,7 @@ const installHookVerdict = (pkg) => {
1732
1789
  };
1733
1790
  // A native-addon manifest triggers an implicit `node-gyp rebuild` on install even with an empty
1734
1791
  // scripts block, so its presence — root or member — is a mandatory install, never proof of none.
1735
- const declaresNativeBuild = (fs, dir) => lstatNoFollow(fs.lstat, join(dir, 'binding.gyp')) !== null;
1792
+ const declaresNativeBuild = (fs, dir) => lstatNoFollow(fs.lstat, join(dir, BINDING_GYP)) !== null;
1736
1793
 
1737
1794
  // PROVABLY dependency-free, or nothing — read from the WORKTREE'S OWN LIVE CHECKOUT, never from
1738
1795
  // MAIN's mutable working tree: the evidence is what an install run in THIS worktree would actually
@@ -1748,7 +1805,7 @@ const declaresNativeBuild = (fs, dir) => lstatNoFollow(fs.lstat, join(dir, 'bind
1748
1805
  // manifest — leaves the posture UNKNOWN, and unknown keeps the existing install advice: a false
1749
1806
  // "nothing to install" is worse than a redundant hint.
1750
1807
  const declaresNoDependencies = ({ wtRoot, fs }) => {
1751
- const pkg = readPackageJson(fs, join(wtRoot, 'package.json'));
1808
+ const pkg = readPackageJson(fs, join(wtRoot, PACKAGE_JSON));
1752
1809
  if (pkg === null || dependencyFieldsVerdict(pkg) !== 'none' || installHookVerdict(pkg) !== 'none') return false;
1753
1810
  if (Object.hasOwn(pkg, 'workspaces')) return false;
1754
1811
  if (declaresNativeBuild(fs, wtRoot)) return false;
@@ -1830,10 +1887,10 @@ const decodeTargetStrictly = (buffer) => {
1830
1887
  const nodeModulesLinkOwnership = ({ fs, git, nmPath, wtRoot, mainRoot }) => {
1831
1888
  const read = readLinkTarget(fs, nmPath);
1832
1889
  if (read.error !== undefined) return { verdict: 'unreadable', error: read.error };
1833
- if (Buffer.compare(read.target, Buffer.from(join(mainRoot, NODE_MODULES_REL))) !== 0) {
1890
+ if (Buffer.compare(read.target, Buffer.from(join(mainRoot, NODE_MODULES))) !== 0) {
1834
1891
  return { verdict: 'foreign', target: read.target };
1835
1892
  }
1836
- const lane = probeOwnedLane({ git, wtRoot, rel: NODE_MODULES_REL });
1893
+ const lane = probeOwnedLane({ git, wtRoot, rel: NODE_MODULES });
1837
1894
  if (lane.lane === 'ignored') return { verdict: 'ours', target: read.target };
1838
1895
  if (lane.lane === 'tracked') return { verdict: 'tracked', target: read.target };
1839
1896
  // The target WAS read here — only the lane is unsettled — so this must not borrow the wording of a
@@ -1854,7 +1911,7 @@ const INSTALL_RUNNABLE_DESCRIPTION = 'this checkout installs its own dependencie
1854
1911
  // IS a command in the ordinary case, so rendering it as prose would offer an instruction nothing
1855
1912
  // attributes and no command parser can see.
1856
1913
  const resolveInstall = ({ wtRoot, mainRoot, dependencyFree, fs, git }) => {
1857
- const nmPath = join(wtRoot, 'node_modules');
1914
+ const nmPath = join(wtRoot, NODE_MODULES);
1858
1915
  const nm = lstatNoFollow(fs.lstat, nmPath);
1859
1916
  const removal = `rm ${shellQuoteArg(nmPath)}`;
1860
1917
  if (nm !== null && nm.isSymbolicLink()) {
@@ -1908,6 +1965,7 @@ const composeSatellitePromptFor = ({ root, wtRoot, slug, branch, record, plan, i
1908
1965
  branch,
1909
1966
  worktreePath: wtRoot,
1910
1967
  plan,
1968
+ renderCommand: composeRenderCommand(SLOT_FILE_REL),
1911
1969
  live: {
1912
1970
  sharedQueue: orientationFields({ root, slug }).sharedQueue,
1913
1971
  landingRule: LANDING_FROM_MAIN,
@@ -1922,10 +1980,10 @@ const composeSatellitePromptFor = ({ root, wtRoot, slug, branch, record, plan, i
1922
1980
  const provisionNodeModules = ({ root, rootReal, wtRoot, installFlag, dependencyFree, git, fs, report, journal = NO_JOURNAL }) => {
1923
1981
  // The lane places ONLY a symlink, so the kind gate admits only a symlink at this path: a
1924
1982
  // directory (a real install) is the user's, never provision's to prove or advise on.
1925
- const journalLink = (outcome) => journal.record({ rel: NODE_MODULES_REL, surface: 'node-modules-link', outcome, kind: 'symlink' });
1983
+ const journalLink = (outcome) => journal.record({ rel: NODE_MODULES, surface: 'node-modules-link', outcome, kind: 'symlink' });
1926
1984
  const install = resolveInstallAdvice({ wtRoot, fs });
1927
1985
  if (installFlag) {
1928
- const dst = join(wtRoot, NODE_MODULES_REL);
1986
+ const dst = join(wtRoot, NODE_MODULES);
1929
1987
  const existing = lstatNoFollow(fs.lstat, dst);
1930
1988
  if (existing !== null && existing.isSymbolicLink()) {
1931
1989
  // The unlink-first advice belongs to OUR link and to no other: for a link this tool never
@@ -1952,7 +2010,7 @@ const provisionNodeModules = ({ root, rootReal, wtRoot, installFlag, dependencyF
1952
2010
  // LIVE STATE WINS the whole default lane: a node already at the worktree — a directory, or a
1953
2011
  // symlink an earlier provision left, even dangling — is what the record states; reporting
1954
2012
  // MAIN's state (`absent`) beside an existing node would contradict record.install.
1955
- const dst = join(wtRoot, NODE_MODULES_REL);
2013
+ const dst = join(wtRoot, NODE_MODULES);
1956
2014
  if (lstatNoFollow(fs.lstat, dst) !== null) {
1957
2015
  journalLink('kept');
1958
2016
  report.push(' node_modules: already present in the worktree');
@@ -1966,7 +2024,7 @@ const provisionNodeModules = ({ root, rootReal, wtRoot, installFlag, dependencyF
1966
2024
  report.push(` node_modules: ${NO_DEPENDENCIES_POSTURE}`);
1967
2025
  return NODE_MODULES_NONE;
1968
2026
  }
1969
- const mainNm = join(root, 'node_modules');
2027
+ const mainNm = join(root, NODE_MODULES);
1970
2028
  const node = classifyNodeNoFollow(mainNm, fs);
1971
2029
  if (node.kind === 'absent') {
1972
2030
  report.push(` node_modules: main has none — after your own install there, re-run --resume, or: ${install.instruction}`);
@@ -1984,7 +2042,7 @@ const provisionNodeModules = ({ root, rootReal, wtRoot, installFlag, dependencyF
1984
2042
  // A directory-form ignore pattern (node_modules/) never covers a SYMLINK of that name — the
1985
2043
  // link would surface as an untracked leftover; the placed-paths-stay-ignored rule applies.
1986
2044
  // Deliberately slashless: this probes the SYMLINK form.
1987
- if (!checkIgnored(git, 'node_modules', wtRoot)) {
2045
+ if (!checkIgnored(git, NODE_MODULES, wtRoot)) {
1988
2046
  report.push(` node_modules: a symlink would not be ignored here (only the directory form is) — not symlinked; ${install.instruction}`);
1989
2047
  return 'not-ignored';
1990
2048
  }
@@ -2012,42 +2070,41 @@ const provisionNodeModules = ({ root, rootReal, wtRoot, installFlag, dependencyF
2012
2070
  };
2013
2071
 
2014
2072
  const provisionVscode = ({ root, wtRoot, slug, git, fs, report, journal = NO_JOURNAL }) => {
2015
- const relPath = '.vscode/settings.json';
2016
2073
  // An EXISTING satellite destination is journaled FIRST, before every source-side and gate-side
2017
2074
  // early return: the doors decide only what this run WRITES, while the journal decides what gets
2018
2075
  // PROVEN. Membership must not depend on MAIN's current state — a file an earlier run placed
2019
2076
  // would otherwise skip here (MAIN lost its .vscode dir, MAIN's copy became tracked, or the
2020
2077
  // ignore rule was lost) and ride a successful resume out as a land-blocking leftover.
2021
- const present = lstatNoFollow(fs.lstat, join(wtRoot, relPath)) !== null;
2022
- if (present) journal.record({ rel: relPath, surface: 'vscode-settings', outcome: 'kept' });
2023
- const vscodeDir = lstatNoFollow(fs.lstat, join(root, '.vscode'));
2078
+ const present = lstatNoFollow(fs.lstat, join(wtRoot, VSCODE_SETTINGS)) !== null;
2079
+ if (present) journal.record({ rel: VSCODE_SETTINGS, surface: 'vscode-settings', outcome: 'kept' });
2080
+ const vscodeDir = lstatNoFollow(fs.lstat, join(root, VSCODE_DIR));
2024
2081
  if (vscodeDir === null || !vscodeDir.isDirectory()) {
2025
2082
  report.push(' .vscode: main has no .vscode/ dir — window title not written');
2026
2083
  return 'absent';
2027
2084
  }
2028
- const tracked = git(['ls-files', '--', relPath], root);
2085
+ const tracked = git(['ls-files', '--', VSCODE_SETTINGS], root);
2029
2086
  if (tracked.status !== 0) {
2030
- throw stop(`git ls-files failed for ${relPath}: ${(tracked.stderr || tracked.stdout).trim()}`);
2087
+ throw stop(`git ls-files failed for ${VSCODE_SETTINGS}: ${(tracked.stderr || tracked.stdout).trim()}`);
2031
2088
  }
2032
2089
  if (tracked.stdout.trim() !== '') {
2033
- report.push(` .vscode: ${relPath} is tracked — left byte-unchanged (set the window title by hand if wanted)`);
2090
+ report.push(` .vscode: ${VSCODE_SETTINGS} is tracked — left byte-unchanged (set the window title by hand if wanted)`);
2034
2091
  return 'skipped-tracked';
2035
2092
  }
2036
- if (!checkIgnored(git, relPath, wtRoot)) {
2037
- report.push(` .vscode: ${relPath} is not ignored in the worktree — skipped (it would become a land leftover)`);
2093
+ if (!checkIgnored(git, VSCODE_SETTINGS, wtRoot)) {
2094
+ report.push(` .vscode: ${VSCODE_SETTINGS} is not ignored in the worktree — skipped (it would become a land leftover)`);
2038
2095
  return 'skipped-not-ignored';
2039
2096
  }
2040
2097
  if (present) {
2041
2098
  report.push(' .vscode: kept (already present)');
2042
2099
  return 'kept';
2043
2100
  }
2044
- const src = readFileNoFollow(fs, join(root, relPath));
2101
+ const src = readFileNoFollow(fs, join(root, VSCODE_SETTINGS));
2045
2102
  if (src.unsafe) {
2046
- report.push(` .vscode: main's ${relPath} is not a regular file — skipped`);
2103
+ report.push(` .vscode: main's ${VSCODE_SETTINGS} is not a regular file — skipped`);
2047
2104
  return 'skipped-unsafe';
2048
2105
  }
2049
2106
  if (src.error) {
2050
- report.push(` .vscode: main's ${relPath} is unreadable (${src.error}) — skipped`);
2107
+ report.push(` .vscode: main's ${VSCODE_SETTINGS} is unreadable (${src.error}) — skipped`);
2051
2108
  return 'skipped-unreadable';
2052
2109
  }
2053
2110
  const base = (() => {
@@ -2059,15 +2116,15 @@ const provisionVscode = ({ root, wtRoot, slug, git, fs, report, journal = NO_JOU
2059
2116
  }
2060
2117
  })();
2061
2118
  if (base === null || typeof base !== 'object' || Array.isArray(base)) {
2062
- report.push(` .vscode: main's ${relPath} is not a JSON object — skipped`);
2119
+ report.push(` .vscode: main's ${VSCODE_SETTINGS} is not a JSON object — skipped`);
2063
2120
  return 'skipped-unparsable';
2064
2121
  }
2065
2122
  const body = `${JSON.stringify({ ...base, 'window.title': slug }, null, 2)}\n`;
2066
- guardDst(fs, wtRoot, join(wtRoot, '.vscode'));
2067
- fs.mkdir(join(wtRoot, '.vscode'));
2068
- writeContainedFileAtomic(wtRoot, join(wtRoot, relPath), body, fs, { stop: (m) => stop(m) });
2069
- journal.record({ rel: relPath, surface: 'vscode-settings', outcome: 'written' });
2070
- report.push(` .vscode: ${relPath} written (window.title = ${slug})`);
2123
+ guardDst(fs, wtRoot, join(wtRoot, VSCODE_DIR));
2124
+ fs.mkdir(join(wtRoot, VSCODE_DIR));
2125
+ writeContainedFileAtomic(wtRoot, join(wtRoot, VSCODE_SETTINGS), body, fs, { stop: (m) => stop(m) });
2126
+ journal.record({ rel: VSCODE_SETTINGS, surface: 'vscode-settings', outcome: 'written' });
2127
+ report.push(` .vscode: ${VSCODE_SETTINGS} written (window.title = ${slug})`);
2071
2128
  return 'written';
2072
2129
  };
2073
2130
 
@@ -2110,7 +2167,7 @@ const rebasePins = ({ root, wtRoot, git, fs, report, journal = NO_JOURNAL }) =>
2110
2167
  report.push(` ${target}: carries main-root pins but is user-modified — left untouched; rebase it by hand if wanted`);
2111
2168
  }
2112
2169
  }
2113
- const gates = readFileNoFollow(fs, join(wtRoot, 'docs/ai/gates.json'));
2170
+ const gates = readFileNoFollow(fs, join(wtRoot, GATES));
2114
2171
  if (!gates.absent) {
2115
2172
  const capable = (() => {
2116
2173
  if (!gates.bytes) return null;
@@ -2131,7 +2188,7 @@ export const runProvision = ({ argvSlug, flags, cwd, git, deps, log }) => {
2131
2188
  const slug = validateSlug(argvSlug);
2132
2189
  const branch = flags.branch ?? `${DEFAULT_BRANCH_PREFIX}${slug}`;
2133
2190
  if (flags.plan == null) throw usageStop('provision requires --plan <path> (the ONE feature plan the worktree starts with)');
2134
- const { root, commonDir } = resolveRoots(cwd, git);
2191
+ const { root, gitDir, commonDir } = resolveRoots(cwd, git);
2135
2192
  // Composing the record is the LAST step of provision, so a refusal there would leave a created
2136
2193
  // worktree with no handoff — which neither --resume nor `cleanup --abandon` can recover, because
2137
2194
  // both bind on the handoff identity. Every value the record will carry is therefore checked HERE,
@@ -2169,6 +2226,7 @@ export const runProvision = ({ argvSlug, flags, cwd, git, deps, log }) => {
2169
2226
  ...provisionSetRels,
2170
2227
  `${PLANS_REL}/${seed.name}`,
2171
2228
  `${PLANS_REL}/${handoffBasename(slug)}`,
2229
+ SLOT_FILE_REL,
2172
2230
  ];
2173
2231
  const includeSources = [];
2174
2232
  for (const inc of flags.include) {
@@ -2207,7 +2265,7 @@ export const runProvision = ({ argvSlug, flags, cwd, git, deps, log }) => {
2207
2265
  }
2208
2266
  const reserved = reservedRels.find((r) => includeRelsOverlap(rel, r));
2209
2267
  if (reserved !== undefined) {
2210
- 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`);
2268
+ throw stop(`--include overlaps a path provision itself populates (${reserved}): ${inc} — the footprint, the seeded plan, the handoff and the slot file are placed by provision; drop the --include`);
2211
2269
  }
2212
2270
  const clashing = includeSources.find((prior) => includeRelsOverlap(rel, prior.rel));
2213
2271
  if (clashing !== undefined) {
@@ -2231,6 +2289,7 @@ export const runProvision = ({ argvSlug, flags, cwd, git, deps, log }) => {
2231
2289
  }
2232
2290
  };
2233
2291
 
2292
+ const approval = { match: null, worktreeGitDir: null };
2234
2293
  if (flags.resume) {
2235
2294
  const entry = listWorktrees(git, root).find((e) => resolve(e.path) === resolve(targetReal));
2236
2295
  if (!entry) throw stop(`--resume: no registered worktree at ${targetReal} — run provision without --resume`);
@@ -2242,9 +2301,18 @@ export const runProvision = ({ argvSlug, flags, cwd, git, deps, log }) => {
2242
2301
  assertPlansChainCleanOnResume({ git, root, wtRoot: targetReal, slug, branch, rels: plansChainRels({ slug, seedName: seed.name }), fs });
2243
2302
  assertResumeHandoffIdentity({ wtRoot: targetReal, slug, branch, fs });
2244
2303
  assertResumePlanCompatibility({ wtRoot: targetReal, seedName: seed.name, fs });
2304
+ approval.worktreeGitDir = resolveGitDir(git, targetReal);
2305
+ approval.match = requireInstanceApproval({
2306
+ instance: placedInstance({ root, wtRoot: targetReal, planFlag: flags.plan, seedName: seed.name, fs }),
2307
+ root,
2308
+ worktreeGitDir: approval.worktreeGitDir,
2309
+ mainGitDir: gitDir,
2310
+ report,
2311
+ });
2245
2312
  runWritabilityProbe();
2246
2313
  report.push(`resuming provision at ${targetReal} (branch ${branch})`);
2247
2314
  } else {
2315
+ approval.match = requireInstanceApproval({ instance: { cwd: root, plan: flags.plan }, root, worktreeGitDir: null, mainGitDir: gitDir, report });
2248
2316
  runWritabilityProbe();
2249
2317
  // ONE captured commit binds the plans-chain tree proof AND the branch cut: a clean
2250
2318
  // captured OID with a subsequently-moved HEAD still cuts from the captured OID.
@@ -2272,7 +2340,11 @@ export const runProvision = ({ argvSlug, flags, cwd, git, deps, log }) => {
2272
2340
  if (!flags.resume) {
2273
2341
  assertPlansChainCleanPostAdd({ git, wtRoot: targetReal, branch, rels: plansChainRels({ slug, seedName: seed.name }) });
2274
2342
  }
2275
- return finishProvision({ root, rootReal, targetPath: targetReal, slug, branch, flags, seed, includeSources, provisionSet, git, deps, fs, report, log });
2343
+ const worktreeGitDir = approval.worktreeGitDir ?? resolveGitDir(git, targetReal);
2344
+ return finishProvision({
2345
+ root, rootReal, targetPath: targetReal, slug, branch, flags, seed, includeSources, provisionSet,
2346
+ approvalMatch: approval.match, worktreeGitDir, git, deps, fs, report, log,
2347
+ });
2276
2348
  } catch (err) {
2277
2349
  if (!flags.resume && err?.message && !err.suppressKeptNote) {
2278
2350
  err.message += `\nNOTE: the worktree at ${targetReal} (branch ${branch}) was created and KEPT — finish with: ${composeProvisionArgv({ root, slug, flags: { ...flags, resume: true } })} (or reclaim it with the consented cleanup).`;
@@ -2344,7 +2416,8 @@ const dropMcpRegistration = ({ root, wtRoot, git, fs, report }) => {
2344
2416
  report.push(` ${SETTINGS_REL}: dropped our registration tokens (this worktree declares no ${MCP_JSON_REL})`);
2345
2417
  };
2346
2418
 
2347
- const finishProvision = ({ root, rootReal, targetPath, slug, branch, flags, seed, includeSources, provisionSet, git, deps, fs, report, log }) => {
2419
+ const finishProvision = ({ root, rootReal, targetPath, slug, branch, flags, seed, includeSources, provisionSet, approvalMatch, worktreeGitDir, git, deps, fs, report, log }) => {
2420
+ const slot = planSlotFile({ wtRoot: targetPath, flags, fs });
2348
2421
  // THIS run's proof set: every lane journals the leaf it placed or kept, and nothing else is ever
2349
2422
  // examined by the resume verify — the session's own work is out of scope by construction.
2350
2423
  const journal = createPlacementJournal({ wtRoot: targetPath, fs });
@@ -2358,6 +2431,8 @@ const finishProvision = ({ root, rootReal, targetPath, slug, branch, flags, seed
2358
2431
  }
2359
2432
 
2360
2433
  writeSeedPlan({ wtRoot: targetPath, srcAbs: seed.srcAbs, name: seed.name, fs, report, journal });
2434
+ carryApproval({ wtRoot: targetPath, gitDir: worktreeGitDir, match: approvalMatch, report });
2435
+ writeSlotFile({ wtRoot: targetPath, seedName: seed.name, slot, stagesPath: deps.stagesPath, fs, report, journal });
2361
2436
  const includesRecorded = provisionIncludes({ rootReal, wtRoot: targetPath, includeSources, resume: flags.resume, git, fs, report, copied, journal });
2362
2437
  // Computed ONCE, from the satellite's own checkout, and threaded to both consumers — the report
2363
2438
  // lane and the record must state the SAME verdict.
@@ -2651,7 +2726,7 @@ const assertSatelliteReady = ({ slug, mainHead, satelliteHead, worktree, git })
2651
2726
  if (divergence === 'behind') throw stop(driftRecipe({ slug, satelliteHead, mainHead }));
2652
2727
 
2653
2728
  const docsAi = nulFields(gitRead(
2654
- git, ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--', 'docs/ai'], worktree,
2729
+ git, ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--', DOCS_TREE], worktree,
2655
2730
  'git status failed for docs/ai',
2656
2731
  ).stdout).map((entry) => entry.length > 3 ? entry.slice(3) : entry);
2657
2732
  if (docsAi.length > 0) {
@@ -2661,7 +2736,7 @@ const assertSatelliteReady = ({ slug, mainHead, satelliteHead, worktree, git })
2661
2736
  }
2662
2737
 
2663
2738
  const stagedExcluded = nulFields(gitRead(
2664
- git, ['diff', '--cached', '--name-only', '--no-renames', '-z', '--', 'docs/ai', 'docs/plans'], worktree,
2739
+ git, ['diff', '--cached', '--name-only', '--no-renames', '-z', '--', DOCS_TREE, PLANS_REL], worktree,
2665
2740
  'git diff failed for excluded paths',
2666
2741
  ).stdout);
2667
2742
  if (stagedExcluded.length > 0) {
@@ -2754,7 +2829,7 @@ const applyTransfer = ({ root, commonDir, slug, patch, mainHead, git, fs }) => {
2754
2829
  };
2755
2830
 
2756
2831
  const runSyncAdapter = ({ root, mainHead, transferPaths, git, fs, deps, report }) => {
2757
- const adapter = join(root, 'scripts/sync-mirrors.mjs');
2832
+ const adapter = join(root, SYNC_MIRRORS);
2758
2833
  const node = classifyNodeNoFollow(adapter, fs);
2759
2834
  if (node.kind === 'absent') {
2760
2835
  report.push('sync adapter: absent — skipped');
@@ -2882,7 +2957,7 @@ export const runLand = ({ argvSlug, flags, cwd, git, deps, log }) => {
2882
2957
  const transferPaths = assertSatelliteReady({ slug, mainHead, satelliteHead, worktree: entry.path, git });
2883
2958
  runSatelliteReview({ worktree: entry.path, deps });
2884
2959
 
2885
- const gates = classifyNodeNoFollow(join(root, 'docs/ai/gates.json'), fs);
2960
+ const gates = classifyNodeNoFollow(join(root, GATES), fs);
2886
2961
  if (gates.kind === 'absent') throw stop('docs/ai/gates.json is absent — land cannot attest the prepared main tree');
2887
2962
  if (gates.kind !== 'regular-file') throw stop('docs/ai/gates.json is not a regular non-symlink file — land fails closed');
2888
2963
 
@@ -3016,7 +3091,7 @@ const provisionKnownRoots = (identity) => {
3016
3091
  ...identity.record.includes.map(safeRecordedPath).filter((rel) => !isNeverProvisionedRel(rel)),
3017
3092
  PLANS_REL,
3018
3093
  ];
3019
- if (identity.record.vscode === 'written') roots.push('.vscode/settings.json');
3094
+ if (identity.record.vscode === 'written') roots.push(VSCODE_SETTINGS);
3020
3095
  return [...new Set(roots)];
3021
3096
  };
3022
3097
 
@@ -3035,7 +3110,7 @@ const provisionKnownDirectoryRoots = ({ root, identity, fs }) => {
3035
3110
 
3036
3111
  const rootCoveringPath = (path, roots) => roots.find((root) => {
3037
3112
  if (root.includes('*')) {
3038
- const expression = new RegExp(`^${root.split('*').map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('[^/]*')}$`);
3113
+ const expression = new RegExp(`^${root.split('*').map(escapeRegExp).join('[^/]*')}$`);
3039
3114
  return expression.test(path);
3040
3115
  }
3041
3116
  return path === root || path.startsWith(`${root}/`);
@@ -3054,7 +3129,7 @@ const foreignIgnoredPaths = ({ root, git, identity, fs, exemptNodeModules = fals
3054
3129
  const path = normalized.replace(/\/$/, '');
3055
3130
  // The ONE ownership exemption (AD-069): the gate has already proven this exact node an
3056
3131
  // ignored-lane matching symlink; it is neither re-probed nor reported here.
3057
- if (exemptNodeModules && path === NODE_MODULES_REL) continue;
3132
+ if (exemptNodeModules && path === NODE_MODULES) continue;
3058
3133
  const kind = classifyNodeNoFollow(join(root, path), fs).kind;
3059
3134
  const rootType = kind === 'plain-directory' || kind === 'symlink-to-directory'
3060
3135
  ? 'directory'
@@ -3084,14 +3159,12 @@ const foreignIgnoredPaths = ({ root, git, identity, fs, exemptNodeModules = fals
3084
3159
  // command. The single exempt state — the ignored-lane matching link — is re-proven immediately
3085
3160
  // before the irreversible worktree remove.
3086
3161
 
3087
- const NODE_MODULES_REL = 'node_modules';
3088
-
3089
3162
  const nodeModulesInspectStop = (nmPath, detail) => stop(
3090
3163
  `cleanup stopped: cannot inspect ${nmPath} (${detail})\n${CLEANUP_OWNERSHIP_RULE}`,
3091
3164
  );
3092
3165
 
3093
3166
  const nodeModulesSnapshot = ({ wtRoot, mainRoot, git, fs }) => {
3094
- const nmPath = join(wtRoot, NODE_MODULES_REL);
3167
+ const nmPath = join(wtRoot, NODE_MODULES);
3095
3168
  const node = (() => {
3096
3169
  try {
3097
3170
  return { stat: fs.lstat(nmPath) };
@@ -3100,7 +3173,7 @@ const nodeModulesSnapshot = ({ wtRoot, mainRoot, git, fs }) => {
3100
3173
  }
3101
3174
  })();
3102
3175
  if (node.error) throw nodeModulesInspectStop(nmPath, node.error);
3103
- const trackedProbe = git(['ls-files', '--cached', '-z', '--', NODE_MODULES_REL], wtRoot);
3176
+ const trackedProbe = git(['ls-files', '--cached', '-z', '--', NODE_MODULES], wtRoot);
3104
3177
  if (trackedProbe.status !== 0) {
3105
3178
  throw nodeModulesInspectStop(nmPath, `git ls-files failed: ${(trackedProbe.stderr || trackedProbe.stdout).trim()}`);
3106
3179
  }
@@ -3109,7 +3182,7 @@ const nodeModulesSnapshot = ({ wtRoot, mainRoot, git, fs }) => {
3109
3182
  return { klass: 'absent', kind: 'absent', lane: tracked ? 'tracked' : null, nmPath };
3110
3183
  }
3111
3184
  const lane = tracked ? 'tracked' : (() => {
3112
- const probe = git(['check-ignore', '--', NODE_MODULES_REL], wtRoot);
3185
+ const probe = git(['check-ignore', '--', NODE_MODULES], wtRoot);
3113
3186
  if (probe.status === 0) return 'ignored';
3114
3187
  if (probe.status === 1) return 'untracked';
3115
3188
  throw nodeModulesInspectStop(nmPath, `git check-ignore failed: ${(probe.stderr || probe.stdout).trim()}`);
@@ -3129,7 +3202,7 @@ const nodeModulesSnapshot = ({ wtRoot, mainRoot, git, fs }) => {
3129
3202
  // Raw BYTES against MAIN's node_modules path — never decoded, never resolved: a relative or
3130
3203
  // re-encoded form that merely RESOLVES to main stays foreign, and the target's kind is
3131
3204
  // irrelevant (unlink touches only the link).
3132
- const matches = Buffer.compare(target.bytes, Buffer.from(join(mainRoot, NODE_MODULES_REL))) === 0;
3205
+ const matches = Buffer.compare(target.bytes, Buffer.from(join(mainRoot, NODE_MODULES))) === 0;
3133
3206
  return { klass: matches ? 'ephemeral' : 'foreign', kind: 'symlink', lane, nmPath };
3134
3207
  };
3135
3208
 
@@ -3224,11 +3297,11 @@ export const runCleanup = ({ argvSlug, flags, cwd, git, deps, log }) => {
3224
3297
  'git diff failed for landed verification',
3225
3298
  );
3226
3299
  const excludedStagedPaths = nulFields(gitRead(
3227
- git, ['diff', '--cached', '--name-only', '--no-renames', '-z', '--', 'docs/ai', 'docs/plans'], entry.path,
3300
+ git, ['diff', '--cached', '--name-only', '--no-renames', '-z', '--', DOCS_TREE, PLANS_REL], entry.path,
3228
3301
  'git diff failed for excluded tracked paths',
3229
3302
  ).stdout);
3230
3303
  const excludedUnstagedPaths = nulFields(gitRead(
3231
- git, ['diff', '--name-only', '--no-renames', '-z', '--', 'docs/ai', 'docs/plans'], entry.path,
3304
+ git, ['diff', '--name-only', '--no-renames', '-z', '--', DOCS_TREE, PLANS_REL], entry.path,
3232
3305
  'git diff failed for excluded tracked paths',
3233
3306
  ).stdout);
3234
3307
  const mismatches = new Set([...unstagedPaths, ...excludedStagedPaths, ...excludedUnstagedPaths]);
@@ -3328,13 +3401,13 @@ export const parseArgs = (argv) => {
3328
3401
  throw usageStop(`unknown subcommand ${JSON.stringify(sub)}\n${USAGE}`);
3329
3402
  }
3330
3403
  const SUB_FLAGS = {
3331
- provision: ['--plan', '--as', '--dir', '--branch', '--include', '--install', '--resume'],
3404
+ provision: ['--plan', '--as', '--dir', '--branch', '--include', '--install', '--resume', '--stage'],
3332
3405
  list: [],
3333
3406
  prompt: [],
3334
3407
  land: ['--prepare'],
3335
3408
  cleanup: ['--branch', '--abandon'],
3336
3409
  };
3337
- const flags = { plan: null, as: null, dir: null, branch: null, include: [], install: false, resume: false, prepare: false, abandon: false };
3410
+ const flags = { plan: null, as: null, dir: null, branch: null, include: [], install: false, resume: false, stage: null, prepare: false, abandon: false };
3338
3411
  let slug = null;
3339
3412
  for (let i = 0; i < rest.length; i += 1) {
3340
3413
  const a = rest[i];
@@ -3342,7 +3415,7 @@ export const parseArgs = (argv) => {
3342
3415
  if (!SUB_FLAGS[sub].includes(a)) {
3343
3416
  throw usageStop(`flag ${JSON.stringify(a)} is not valid for ${sub}\n${USAGE}`);
3344
3417
  }
3345
- const takesValue = ['--plan', '--as', '--dir', '--branch', '--include'].includes(a);
3418
+ const takesValue = ['--plan', '--as', '--dir', '--branch', '--include', '--stage'].includes(a);
3346
3419
  if (takesValue) {
3347
3420
  i += 1;
3348
3421
  if (rest[i] === undefined) throw usageStop(`${a} requires an argument`);
@@ -3355,6 +3428,9 @@ export const parseArgs = (argv) => {
3355
3428
  else throw usageStop(`unexpected argument ${JSON.stringify(a)}`);
3356
3429
  }
3357
3430
  if (sub !== 'list' && slug === null) throw usageStop(`${sub} requires the positional <slug>`);
3431
+ if (flags.stage !== null && !RECORD_GATED_STAGES.includes(flags.stage)) {
3432
+ throw usageStop(`--stage must be one of the record-gated stages (${RECORD_GATED_STAGES.join(', ')}), got ${displayValue(JSON.stringify(flags.stage))}`);
3433
+ }
3358
3434
  if (sub === 'list' && slug !== null) throw usageStop('list takes no positional argument');
3359
3435
  return { sub, slug, flags };
3360
3436
  };