@sabaiway/agent-workflow-kit 23.11.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 (159) hide show
  1. package/CHANGELOG.md +87 -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/control-bytes.md +38 -32
  23. package/references/modes/flow-writer.md +10 -2
  24. package/references/modes/hook.md +4 -1
  25. package/references/modes/now.md +1 -1
  26. package/references/modes/procedures.md +49 -10
  27. package/references/modes/recipes.md +7 -7
  28. package/references/modes/recommendations.md +5 -4
  29. package/references/modes/robustness-brief.md +9 -8
  30. package/references/modes/set-recipe.md +1 -1
  31. package/references/modes/state-block-guard.md +4 -3
  32. package/references/modes/status.md +1 -1
  33. package/references/modes/upgrade.md +1 -1
  34. package/references/modes/worktrees.md +28 -5
  35. package/references/rules/story-sessions.md +2 -2
  36. package/references/scripts/archives/archive-caps.mjs +1 -1
  37. package/references/scripts/archives/archive-changelog.mjs +8 -8
  38. package/references/scripts/archives/archive-decisions.mjs +7 -7
  39. package/references/scripts/archives/archive-issues.mjs +5 -5
  40. package/references/scripts/archives/rotation-conservation.mjs +2 -1
  41. package/references/scripts/docs-size/check-docs-size.mjs +15 -15
  42. package/references/scripts/family.json +2 -0
  43. package/references/scripts/gates/kit-command-gates.mjs +7 -8
  44. package/references/scripts/gates/migrate-gates.mjs +10 -10
  45. package/references/scripts/git-hooks/install-git-hooks.mjs +13 -13
  46. package/references/scripts/run.mjs +1 -2
  47. package/references/scripts/shared/index.mjs +2 -0
  48. package/references/scripts/shared/locations.mjs +103 -0
  49. package/references/scripts/spec-schema/spec-schema.mjs +2 -1
  50. package/references/templates/orchestration.json +1 -1
  51. package/tools/ack-store.mjs +2 -1
  52. package/tools/advisor-matrix.mjs +2 -1
  53. package/tools/advisor-skip/index.mjs +73 -0
  54. package/tools/apply-danger-check.mjs +20 -6
  55. package/tools/atomic-write.mjs +3 -2
  56. package/tools/attribution.mjs +2 -1
  57. package/tools/autonomy-config.mjs +2 -1
  58. package/tools/bridge-wiring.mjs +13 -11
  59. package/tools/carriers.mjs +54 -14
  60. package/tools/cheap-agents-read.mjs +28 -7
  61. package/tools/cheap-agents.mjs +15 -10
  62. package/tools/checker-gates-read.mjs +6 -5
  63. package/tools/commands.mjs +2 -2
  64. package/tools/control-bytes.mjs +43 -20
  65. package/tools/coverage-declared/config.mjs +2 -1
  66. package/tools/coverage-producer.mjs +10 -9
  67. package/tools/delegation.mjs +7 -6
  68. package/tools/detect-backends.mjs +1 -1
  69. package/tools/dispatch-baseline.mjs +2 -1
  70. package/tools/distribution-files/scripts.mjs +4 -4
  71. package/tools/doc-parity/index.mjs +46 -0
  72. package/tools/doc-parity.mjs +27 -47
  73. package/tools/ensure-configs.mjs +2 -2
  74. package/tools/ensure-ops.mjs +24 -24
  75. package/tools/ensure-specs.mjs +7 -7
  76. package/tools/epic-shape-cli.mjs +2 -2
  77. package/tools/epic-shape-ledger.mjs +5 -5
  78. package/tools/epic-shape.mjs +5 -3
  79. package/tools/epic-store.mjs +2 -1
  80. package/tools/family-members.mjs +7 -5
  81. package/tools/family-registry.mjs +36 -30
  82. package/tools/feedback-record-cli.mjs +4 -5
  83. package/tools/flow-writer.mjs +26 -15
  84. package/tools/gate-hook.mjs +33 -28
  85. package/tools/gates-declaration.mjs +2 -1
  86. package/tools/gates-init.mjs +6 -5
  87. package/tools/git-hooks.mjs +64 -41
  88. package/tools/grounding.mjs +3 -2
  89. package/tools/hide-footprint.mjs +2 -1
  90. package/tools/hook-writer/index.mjs +147 -0
  91. package/tools/init-preflight.mjs +5 -4
  92. package/tools/init-project.mjs +12 -11
  93. package/tools/inject-methodology.mjs +3 -2
  94. package/tools/jev-guide.mjs +2 -2
  95. package/tools/known-footprint.mjs +27 -25
  96. package/tools/mcp-registration.mjs +6 -5
  97. package/tools/migration-blocks.mjs +2 -1
  98. package/tools/migration-notes.mjs +2 -2
  99. package/tools/node-evidence.mjs +4 -4
  100. package/tools/now-facts.mjs +5 -5
  101. package/tools/now-status.mjs +1 -5
  102. package/tools/orchestration-config.mjs +2 -1
  103. package/tools/orchestration-readme.mjs +7 -2
  104. package/tools/plan-approval/cli.mjs +45 -0
  105. package/tools/plan-approval/entries.mjs +109 -0
  106. package/tools/plan-approval/index.mjs +2 -0
  107. package/tools/plan-approval/record.mjs +198 -0
  108. package/tools/plan-files.mjs +6 -4
  109. package/tools/plan-shape-cli.mjs +10 -64
  110. package/tools/plan-shape-facts.mjs +240 -83
  111. package/tools/plan-shape.mjs +173 -160
  112. package/tools/plan-structure/cli.mjs +79 -0
  113. package/tools/plan-structure/index.mjs +67 -0
  114. package/tools/procedures.mjs +21 -17
  115. package/tools/profile-gaps.mjs +4 -6
  116. package/tools/project-rules/rules-priors.mjs +2 -0
  117. package/tools/project-rules/themes.mjs +6 -4
  118. package/tools/recipes.mjs +44 -29
  119. package/tools/recommendations.mjs +90 -39
  120. package/tools/reference-profile.mjs +2 -2
  121. package/tools/release-scan/index.mjs +30 -0
  122. package/tools/release-scan.mjs +46 -25
  123. package/tools/renderers.mjs +14 -8
  124. package/tools/repo-lex.mjs +84 -0
  125. package/tools/robustness-brief.mjs +14 -11
  126. package/tools/sandbox-masks.mjs +6 -4
  127. package/tools/satellite-locator.mjs +3 -2
  128. package/tools/script-priors.mjs +3 -2
  129. package/tools/session-close-check.mjs +71 -15
  130. package/tools/set-flow.mjs +2 -2
  131. package/tools/set-recipe.mjs +17 -9
  132. package/tools/source-size/help.mjs +4 -4
  133. package/tools/source-size/layout.mjs +2 -1
  134. package/tools/source-size/piles.mjs +2 -2
  135. package/tools/source-size-config.mjs +3 -3
  136. package/tools/source-size-refusal.mjs +4 -3
  137. package/tools/source-size-report.mjs +41 -13
  138. package/tools/spec-check-cli.mjs +159 -21
  139. package/tools/spec-check-ops.mjs +74 -5
  140. package/tools/spec-check.mjs +54 -45
  141. package/tools/spec-coverage-cli.mjs +3 -2
  142. package/tools/stage-render/cli.mjs +231 -0
  143. package/tools/stage-render/index.mjs +340 -0
  144. package/tools/stage-render/stages.json +115 -0
  145. package/tools/stage-write-guard/cli.mjs +64 -0
  146. package/tools/stage-write-guard/index.mjs +56 -0
  147. package/tools/state-block-hook.mjs +38 -163
  148. package/tools/task-brief.mjs +8 -13
  149. package/tools/task-thread.mjs +3 -1
  150. package/tools/tier-guide-facts.mjs +23 -9
  151. package/tools/tier-preview.mjs +15 -19
  152. package/tools/transition/index.mjs +10 -9
  153. package/tools/uninstall.mjs +26 -12
  154. package/tools/vehicle-settings.mjs +2 -1
  155. package/tools/velocity-profile.mjs +5 -6
  156. package/tools/view-model.mjs +7 -4
  157. package/tools/worktree-prompt.mjs +7 -3
  158. package/tools/worktrees.mjs +235 -159
  159. package/tools/write-lanes.mjs +20 -14
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { realpathSync } from 'node:fs';
4
4
  import { isAbsolute, resolve, sep } from 'node:path';
5
- import { readShippedRobustnessLiterals, parseRobustTag } from './robustness-literals.mjs';
5
+ import { classIds, readShippedRobustnessLiterals, parseRobustTag } from './robustness-literals.mjs';
6
6
  import { checkPlanStructure, formatFindings, isSweep } from './plan-shape.mjs';
7
7
  import { expandSweepPaths } from './plan-shape-facts.mjs';
8
8
  import { readFileBytesNoFollowCapped } from './fs-read-nofollow.mjs';
@@ -13,6 +13,7 @@ const PLAN_READ_CAP = 1_048_576;
13
13
  const ROW_ID = /^[A-Za-z0-9._-]+$/u;
14
14
  const SEARCHABLE_KINDS = new Set(['env', 'flag', 'ref', 'syscall', 'errno', 'argv']);
15
15
  const SHIPPED_LIST_PATH = 'agent-workflow-kit/references/robustness-literals.json';
16
+ export const ROBUST_CLASS_CODE = 'robust-class';
16
17
  const USAGE = 'Usage: node robustness-brief.mjs --plan <plan> [--row <id>] [--coverage]';
17
18
  const usage = (message) => Object.assign(new Error(message), { usage: true });
18
19
  const isInside = (root, path) => path === root || path.startsWith(`${root}${sep}`);
@@ -123,19 +124,19 @@ export const renderCoverage = (rows, displayPath) => [
123
124
  : `| ${row.id} | ${renderCell(row.path)} | ${row.tagged.join(',') || '—'} | ${row.present.join(',') || '—'} | ${row.uncovered.join(',') || '—'} |`),
124
125
  ];
125
126
 
127
+ const renderStructuralRefusal = (shape, displayPath) => ({
128
+ code: 1,
129
+ lines: formatFindings(shape, escapeForDisplay(displayPath)).split('\n').map(escapeForDisplay),
130
+ });
131
+
126
132
  export const renderBrief = (planText, list, { row, displayPath }) => {
127
- const shape = checkPlanStructure(planText, {});
128
- if (shape.findings.length > 0) return { code: 1, lines: formatFindings(shape, escapeForDisplay(displayPath)).split('\n').map(escapeForDisplay) };
133
+ const shape = checkPlanStructure(planText, { robustClasses: classIds(list) });
134
+ if (shape.findings.length > 0) return renderStructuralRefusal(shape, displayPath);
129
135
  const classes = new Map(list.classes.map((entry) => [entry.id, entry]));
130
136
  const rows = shape.parsed.rows.filter((entry) => entry.valid).map((entry) => ({
131
137
  ...entry,
132
138
  robust: parseRobustTag(entry.responsibility),
133
139
  }));
134
- const refused = rows.find((entry) => entry.robust.refusal || entry.robust.classes.some((classId) => !classes.has(classId)));
135
- if (refused) {
136
- const reason = refused.robust.refusal ?? `unknown class ${refused.robust.classes.find((classId) => !classes.has(classId))}`;
137
- return { code: 1, lines: [`robustness-brief: ${refused.id}: robust-class — ${reason}`] };
138
- }
139
140
  const selected = row === null ? rows.filter((entry) => entry.robust.classes.length > 0) : rows.filter((entry) => entry.id === row);
140
141
  if (row !== null && selected.length === 0) return { code: 1, lines: [`robustness-brief: ${row}: row is absent`] };
141
142
  if (row !== null && selected[0].robust.classes.length === 0) return { code: 1, lines: [`robustness-brief: ${row}: row is untagged`] };
@@ -181,8 +182,10 @@ export const main = (argv = process.argv.slice(2), deps = {}) => {
181
182
  throw usage(`malformed-utf8 --plan ${parsed.plan}`);
182
183
  }
183
184
  const list = (deps.readList ?? readShippedRobustnessLiterals)();
184
- const brief = renderBrief(planText, list, { row: parsed.row, displayPath: parsed.plan });
185
- if (!parsed.coverage || checkPlanStructure(planText, {}).findings.length > 0) return brief;
185
+ if (!parsed.coverage) return renderBrief(planText, list, { row: parsed.row, displayPath: parsed.plan });
186
+ const shape = checkPlanStructure(planText, { robustClasses: classIds(list) });
187
+ const findings = shape.findings.filter(({ code }) => code !== ROBUST_CLASS_CODE);
188
+ if (findings.length > 0) return renderStructuralRefusal({ ...shape, findings }, parsed.plan);
186
189
  const sweepPaths = checkPlanStructure(planText, {}).parsed.rows
187
190
  .filter((entry) => entry.valid && isSweep(entry.path) && !isCoverageDocument(entry.path))
188
191
  .map((entry) => entry.path);
@@ -193,7 +196,7 @@ export const main = (argv = process.argv.slice(2), deps = {}) => {
193
196
  });
194
197
  if (coverage.refusal) {
195
198
  const { id, path, outcome, reason } = coverage.refusal;
196
- throw usage(reason === undefined ? `${id}: ${escapeForDisplay(path)} — ${outcome}` : `${id}: robust-class — ${reason}`);
199
+ throw usage(reason === undefined ? `${id}: ${escapeForDisplay(path)} — ${outcome}` : `${id}: ${ROBUST_CLASS_CODE} — ${reason}`);
197
200
  }
198
201
  const lines = [...renderCoverage(coverage.rows, parsed.plan), ...coverage.evidence.map(({ id, classId, literal }) => `${id}:${classId}:${literal}`)];
199
202
  return { code: coverage.evidence.length > 0 ? 1 : 0, lines };
@@ -42,6 +42,7 @@ import { isNeverCommittableStat, shellQuoteArg } from './review-state.mjs';
42
42
  import { assertContainedRealPath } from './fs-safe.mjs';
43
43
  import { GIT_MAX_BUFFER } from './git-env.mjs';
44
44
  import { foreignMountTargets } from './mount-masks.mjs';
45
+ import { jsonForLine } from './source-size-refusal.mjs';
45
46
 
46
47
  export const MASKS_FENCE_START = '# >>> agent-workflow sandbox-masks — managed block, fully REPLACED by the kit sandbox-masks lane; do not hand-edit inside >>>';
47
48
  export const MASKS_FENCE_END = '# <<< agent-workflow sandbox-masks <<<';
@@ -225,7 +226,7 @@ export const probeSandboxMasks = ({ cwd = process.cwd(), lstat = lstatSync, list
225
226
  const fence = findMasksFence(lines);
226
227
  const staleReal = fence.state === 'ok' ? revalidateFence(fence.body, { root, lstat: lstatOnce, readMountinfo: once }) : [];
227
228
  const leftovers = clearOnly ? [] : staleReal.filter((rel) => isLeftoverStat(lstatOnce(join(root, rel))));
228
- if (leftovers.length > 0) throw fail(1, [...staleReal.filter((rel) => !leftovers.includes(rel)).map(staleRealLine), ...leftovers.map(leftoverLine)].join('\n'));
229
+ if (leftovers.length > 0) throw fail(1, [...formatGroup(staleRealHead, staleReal.filter((rel) => !leftovers.includes(rel))), ...formatGroup(leftoverHead, leftovers)].join('\n'));
229
230
  const applyCmd = `node ${shellQuoteArg(join(HERE, 'sandbox-masks.mjs'))} --cwd ${shellQuoteArg(root)} --apply`;
230
231
  return { root, excludeFile, gitCommonDir, content, lines, fence, masks, unrenderable, mountOnly, mountSignal, staleReal, applyCmd };
231
232
  };
@@ -281,8 +282,9 @@ export const planApply = (probe, { clear = false } = {}) => {
281
282
 
282
283
  // ── rendering ───────────────────────────────────────────────────────────────────────
283
284
 
284
- const staleRealLine = (rel) => ` ⚠ fenced entry became a REAL path: ${rel} — delete its line from the managed block BEFORE relying on git for this path: an excluded real file is silently skipped by bulk staging (git add -A / git add .), so it stays OUT of your commits, and an explicit git add refuses it without -f; .git/info/exclude never warns`;
285
- const leftoverLine = (rel) => ` ⚠ refusing: fenced entry ${rel} is an empty read-only file no arm calls a mask, so neither verdict is given — a running sandbox's mask: re-run once no other sandboxed command runs; litter a sandbox left: remove the file outside the sandbox and keep its line; a real file: delete its line`;
285
+ const staleRealHead = (n) => ` ⚠ ${n} fenced entr(ies) became REAL path(s) — delete each one's line from the managed block BEFORE relying on git for it: an excluded real file is silently skipped by bulk staging (git add -A / git add .), so it stays OUT of your commits, and an explicit git add refuses it without -f; .git/info/exclude never warns:`;
286
+ const leftoverHead = (n) => ` ⚠ refusing: ${n} fenced entr(ies) are empty read-only files no arm calls a mask, so neither verdict is given — a running sandbox's mask: re-run once no other sandboxed command runs; litter a sandbox left: remove the file outside the sandbox and keep its line; a real file: delete its line:`;
287
+ const formatGroup = (sentence, paths) => paths.length === 0 ? [] : [sentence(paths.length), ...paths.map((rel) => ' ' + jsonForLine(rel))];
286
288
 
287
289
  const formatProbe = (probe) => {
288
290
  const lines = [
@@ -294,7 +296,7 @@ const formatProbe = (probe) => {
294
296
  lines.push(` masks visible now: ${probe.masks.length === 0 ? '0 (outside the sandbox or clean)' : ''}`);
295
297
  for (const m of probe.masks) lines.push(` · ${m}${probe.mountOnly.includes(m) ? ' (mount-only: it rides git add -A and the review fingerprint while git does not ignore it)' : ''}`);
296
298
  if (probe.mountSignal === 'absent') lines.push(' mount signal: not read on this platform — only device/FIFO/socket masks are judged');
297
- lines.push(...probe.staleReal.map(staleRealLine));
299
+ lines.push(...formatGroup(staleRealHead, probe.staleReal));
298
300
  for (const rel of probe.unrenderable) {
299
301
  lines.push(` ⚠ mask name carries a newline or ends with a tab and cannot be expressed as ONE exclude rule — NOT written (the mask itself stays untracked): ${JSON.stringify(rel)}`);
300
302
  }
@@ -14,9 +14,10 @@
14
14
  // second body here would be exactly the duplication that pin exists to prevent. `fs` is the shape
15
15
  // worktrees.mjs builds: { lstat, readdir, realpath, readFileNoFollow }.
16
16
  //
17
- // Node built-ins plus two pure leaves. No side effects on import; no CLI. Dependency-free, Node >= 22.
17
+ // Node built-ins, shared locations and two pure leaves. No side effects on import; no CLI. Dependency-free, Node >= 22.
18
18
 
19
19
  import { join } from 'node:path';
20
+ import { DOCS } from '../references/scripts/shared/index.mjs';
20
21
  import { PLANS_REL } from './plan-files.mjs';
21
22
  import { stop, handoffBasename, parseProvisionRecord, displayValue } from './worktrees-record.mjs';
22
23
 
@@ -100,7 +101,7 @@ export const classifyNodeNoFollow = (path, fs) => {
100
101
  // ANY stat failure (not just readdir) renders honestly — list must never crash on a bad node.
101
102
  export const scanPlansDir = ({ wtRoot, fs }) => {
102
103
  if (classifyNodeNoFollow(wtRoot, fs).kind !== 'plain-directory') return { state: 'unreadable' };
103
- const docs = classifyNodeNoFollow(join(wtRoot, 'docs'), fs);
104
+ const docs = classifyNodeNoFollow(join(wtRoot, DOCS), fs);
104
105
  if (docs.kind === 'absent') return { state: 'absent' };
105
106
  if (docs.kind !== 'plain-directory') return { state: 'unreadable' };
106
107
  const plans = classifyNodeNoFollow(join(wtRoot, PLANS_REL), fs);
@@ -32,8 +32,8 @@ export const PRIOR_FILES = Object.freeze([
32
32
  export const READER_PAIR = Object.freeze(['spec-schema.mjs', 'spec-schema.test.mjs']);
33
33
  export const CHECKER_PAIR = Object.freeze(['check-docs-size.mjs', 'check-docs-size.test.mjs']);
34
34
 
35
- // The hook installer and the two suites that test it beside it — written first, installer first, so a
36
- // stop partway never leaves a bundled suite beside a prior installer.
35
+ // The hook installer and the two suites that test it beside it form one set because a bundled suite
36
+ // fails inside the hook when paired with a prior installer.
37
37
  export const INSTALLER_SET = Object.freeze(['install-git-hooks.mjs', 'install-git-hooks.test.mjs', 'install-git-hooks-repo-exec.test.mjs']);
38
38
 
39
39
  const prior = (file, firstShipped, lastShipped, digest) => Object.freeze({ file, firstShipped, lastShipped, digest });
@@ -89,6 +89,7 @@ export const SCRIPT_PRIORS = Object.freeze([
89
89
  prior('migrate-gates.test.mjs', '8.1.5', '9.0.0', '8f99a2f65f1f3db0eb3464a0382c208ca5076388b6df0596cf099d53ab2a1f86'),
90
90
  prior('spec-schema.test.mjs', '8.7.0', '9.0.0', '6a602a93e9f9f21f0bc10c50e356de693936d3e204987efbab1a1d7674030498'),
91
91
  prior('markdown-blocks.mjs', '4.0.0', '9.0.0', '5a9fb45d4248c53dee9694b2d95c1cf98fe08a55c41429cf72826aa218f0ad2d'),
92
+ prior('spec-schema.mjs', '8.7.0', '9.0.0', 'ddc14a4c79498913977d6494f84e4b48348d0d2d7a415d84bb24334e24d3538f'),
92
93
  ]);
93
94
 
94
95
  export const digestOf = (bytes) => createHash('sha256').update(bytes).digest('hex');
@@ -1,13 +1,11 @@
1
1
  #!/usr/bin/env node
2
- // session-close-check.mjs — the read-only checker of a session close: judges the `## For the user`
3
- // section of docs/ai/handover.md and its two labels. Governing contract:
4
- // docs/ai/specs/kit/tier/session-rules/ (part session-close-check). Not a gate: a session close is
5
- // not a commit boundary. main(argv, deps) returns, never exits, never asks; every read goes through deps.
6
2
  import { resolve } from 'node:path';
3
+ import { HANDOVER } from '../references/scripts/shared/index.mjs';
7
4
  import { safeLine } from './carriers.mjs';
8
5
  import { isDeployed } from './checker-gates-read.mjs';
9
6
  import { isDirectRun } from './direct-run.mjs';
10
- import { readRegularFileNoFollow } from './fs-read-nofollow.mjs';
7
+ import { lstatNoFollowRead, readRegularFileNoFollow } from './fs-read-nofollow.mjs';
8
+ import { composeRenderLine, loadStages, NEXT_SESSION_HEADING, STAGES_REL, validateSlots } from './stage-render/index.mjs';
11
9
 
12
10
  const LF = String.fromCharCode(10);
13
11
  const CR = String.fromCharCode(13);
@@ -19,12 +17,17 @@ const EXIT_CANNOT_JUDGE = 2;
19
17
  const CHECK_FLAG = '--check';
20
18
  const CWD_FLAG = '--cwd';
21
19
  const HELP_FLAG = '--help';
22
- const HANDOVER_REL = 'docs/ai/handover.md';
23
20
  const SECTION_HEADING = '## For the user';
24
21
  const SECTION_BOUNDARY = '## ';
25
22
  const LABELS = Object.freeze(['**What was done, and for what:**', '**What is next, and why:**']);
26
23
  const SINGLE = 1;
27
24
  const SYMLINK_CLASS = 'symlink';
25
+ const STAGES_PATH = resolve(import.meta.dirname, '..', STAGES_REL);
26
+ const SAMPLE_OPERAND = 'slot-file';
27
+ const RENDER_PREFIX = composeRenderLine(SAMPLE_OPERAND).slice(0, -SAMPLE_OPERAND.length);
28
+ const QUOTE = "'";
29
+ const ESCAPED_QUOTE = "'\\''";
30
+ const ABSENT_CODE = 'ENOENT';
28
31
 
29
32
  const STATES = Object.freeze({
30
33
  noDeployment: 'no-deployment',
@@ -38,16 +41,22 @@ const STATES = Object.freeze({
38
41
  labelTwice: 'label-twice',
39
42
  labelOrder: 'label-order',
40
43
  labelEmpty: 'label-empty',
44
+ nextAbsent: 'next-absent',
45
+ nextTwice: 'next-twice',
46
+ nextEmpty: 'next-empty',
47
+ nextMany: 'next-many',
48
+ nextForm: 'next-form',
49
+ nextFile: 'next-file',
41
50
  });
42
51
 
43
52
  export const OUTCOME_LINES = Object.freeze({
44
- accept: () => 'session-close-check: accept — the handover carries the For the user section with both labels and their text',
53
+ accept: () => 'session-close-check: accept — the handover carries the For the user section with both labels and their text, and the Next session block in its one form',
45
54
  state: (name) => safeLine(name),
46
55
  labelState: (name, label) => `${safeLine(name)}: ${safeLine(label)}`,
47
56
  usage: (problem) => `usage: session-close-check.mjs --check [--cwd DIR] — ${safeLine(problem)}`,
48
57
  help: () => [
49
58
  'session-close-check.mjs --check [--cwd DIR]',
50
- 'Judges the For the user section of docs/ai/handover.md in DIR (default: the current directory); writes nothing.',
59
+ 'Judges the For the user and Next session sections of docs/ai/handover.md in DIR (default: the current directory); writes nothing.',
51
60
  'Exit codes: 0 accept, 1 one refusal per line, 2 usage or cannot judge.',
52
61
  ].join(LF),
53
62
  });
@@ -81,11 +90,11 @@ const parseArgs = (argv) => {
81
90
  const stripCr = (line) => (line.endsWith(CR) ? line.slice(0, -1) : line);
82
91
  const isBlank = (text) => text.trim() === '';
83
92
 
84
- const sectionLines = (text) => {
93
+ const sectionLines = (text, heading, absent, twice) => {
85
94
  const lines = text.split(LF).map(stripCr);
86
95
  if (lines[0].startsWith(BOM_CHAR)) lines[0] = lines[0].slice(BOM_CHAR.length);
87
- const starts = lines.flatMap((line, index) => (line === SECTION_HEADING ? [index] : []));
88
- if (starts.length !== SINGLE) return { state: starts.length === 0 ? STATES.sectionAbsent : STATES.sectionTwice };
96
+ const starts = lines.flatMap((line, index) => (line === heading ? [index] : []));
97
+ if (starts.length !== SINGLE) return { state: starts.length === 0 ? absent : twice };
89
98
  const body = lines.slice(starts[0] + 1);
90
99
  const end = body.findIndex((line) => line.startsWith(SECTION_BOUNDARY));
91
100
  return { lines: end === -1 ? body : body.slice(0, end) };
@@ -117,22 +126,69 @@ const judgeLabels = (lines) => {
117
126
  return refusals;
118
127
  };
119
128
 
120
- const judgeHandover = (content) => {
121
- const section = sectionLines(content);
129
+ const judgeUserSection = (content) => {
130
+ const section = sectionLines(content, SECTION_HEADING, STATES.sectionAbsent, STATES.sectionTwice);
122
131
  if (section.state) return [OUTCOME_LINES.state(section.state)];
123
132
  return judgeLabels(section.lines);
124
133
  };
125
134
 
135
+ const readSlotOperand = (line) => {
136
+ if (!line.startsWith(RENDER_PREFIX)) return null;
137
+ const token = line.slice(RENDER_PREFIX.length);
138
+ const operand = token.startsWith(QUOTE) && token.endsWith(QUOTE)
139
+ ? token.slice(1, -1).replaceAll(ESCAPED_QUOTE, QUOTE) : token;
140
+ try {
141
+ return composeRenderLine(operand) === line ? operand : null;
142
+ } catch {
143
+ return null;
144
+ }
145
+ };
146
+
147
+ const readText = (path, deps) => {
148
+ const read = readRegularFileNoFollow(path, deps);
149
+ if (read.outcome !== 'ok' || read.closeFailure) {
150
+ throw new Error(`cannot read ${path} (${read.closeFailure ?? read.code ?? read.className ?? read.outcome})`);
151
+ }
152
+ return read.content;
153
+ };
154
+
155
+ const makeSlotReads = (deps) => Object.keys(deps).length === 0 ? undefined : ({
156
+ ...deps,
157
+ lstatSync: deps.lstatSync ?? deps.lstat ?? ((path) => {
158
+ const stat = lstatNoFollowRead(path);
159
+ if (stat === null) throw Object.assign(new Error(`${path} does not exist`), { code: ABSENT_CODE });
160
+ return stat;
161
+ }),
162
+ readFileSync: deps.readFileSync ?? ((path) => Buffer.from(readText(path, deps), 'utf8')),
163
+ });
164
+
165
+ const judgeNextSection = (content, root, deps) => {
166
+ const section = sectionLines(content, NEXT_SESSION_HEADING, STATES.nextAbsent, STATES.nextTwice);
167
+ if (section.state) return [OUTCOME_LINES.state(section.state)];
168
+ const lines = section.lines.filter((line) => !isBlank(line));
169
+ if (lines.length !== SINGLE) return [OUTCOME_LINES.state(lines.length === 0 ? STATES.nextEmpty : STATES.nextMany)];
170
+ const [line] = lines;
171
+ const slotFile = readSlotOperand(line);
172
+ if (slotFile === null) return [OUTCOME_LINES.labelState(STATES.nextForm, line)];
173
+ try {
174
+ const table = loadStages(readText(STAGES_PATH, deps));
175
+ validateSlots({ root, slotFile, table }, makeSlotReads(deps));
176
+ return [];
177
+ } catch (error) {
178
+ return [OUTCOME_LINES.labelState(STATES.nextFile, error.message)];
179
+ }
180
+ };
181
+
126
182
  const runCheck = (options, deps) => {
127
183
  const root = resolve(options.cwd);
128
184
  if (!isDeployed(root, deps)) return cannotJudge(STATES.noDeployment);
129
- const read = readRegularFileNoFollow(resolve(root, HANDOVER_REL), deps);
185
+ const read = readRegularFileNoFollow(resolve(root, HANDOVER), deps);
130
186
  if (read.outcome === 'absent') return result(EXIT_REFUSAL, '', OUTCOME_LINES.state(STATES.handoverAbsent));
131
187
  if (read.outcome === 'foreign') {
132
188
  return cannotJudge(read.className === SYMLINK_CLASS ? STATES.handoverSymlink : STATES.handoverNotRegular);
133
189
  }
134
190
  if (read.outcome !== 'ok') return cannotJudge(STATES.handoverUnreadable);
135
- const refusals = judgeHandover(read.content);
191
+ const refusals = [...judgeUserSection(read.content), ...judgeNextSection(read.content, root, deps)];
136
192
  if (refusals.length > 0) return result(EXIT_REFUSAL, '', refusals.join(LF));
137
193
  return result(EXIT_ACCEPT, OUTCOME_LINES.accept());
138
194
  };
@@ -32,6 +32,7 @@ import { readFileSync, lstatSync } from 'node:fs';
32
32
  import { join, dirname, resolve } from 'node:path';
33
33
  import { fileURLToPath } from 'node:url';
34
34
  import { spawnSync } from 'node:child_process';
35
+ import { DOCS_TREE } from '../references/scripts/shared/index.mjs';
35
36
  import {
36
37
  CONFIG_REL,
37
38
  fail,
@@ -53,7 +54,6 @@ import { readAuthoritativeVersion } from './manifest/validate.mjs';
53
54
  import { GIT_MAX_BUFFER } from './git-env.mjs';
54
55
 
55
56
  const KIT_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
56
- const GATES_REL = 'docs/ai/gates.json';
57
57
 
58
58
  // The honest boundary of the bookkeeping floors — printed on EVERY floor evaluation and
59
59
  // doc-parity-bound into the set-flow mode doc, so the admission can never be reworded away.
@@ -261,7 +261,7 @@ const bookkeepingFloorFailures = ({ key, rel, excluded, top, gates, lstat, runGi
261
261
  failures.push(`flow.${key} "${rel}": must be a plain forward-slash path without "." or ".." segments (#37)`);
262
262
  return { failures, notes };
263
263
  }
264
- if (rel === 'docs/ai' || rel.startsWith('docs/ai/')) {
264
+ if (rel === DOCS_TREE || rel.startsWith(`${DOCS_TREE}/`)) {
265
265
  failures.push(`flow.${key} "${rel}": a bookkeeping path never lives under docs/ai/ (#37)`);
266
266
  }
267
267
  for (const gate of gates) {
@@ -17,11 +17,11 @@
17
17
  // language when narrating. Exit codes: 0 success (an explicit recipe that gracefully degrades is still
18
18
  // 0); 2 usage (bad/duplicate op, --write with zero ops); 1 config error (malformed/unreadable config)
19
19
  // or a write STOP (no deployment / symlinked leaf). main(argv, ctx) → { code, stdout, stderr }; cwd /
20
- // env / home / detect / surveyVehicle / fs are injectable for host-independent tests.
20
+ // env / home / detect / surveyVehicle / surveyAuthorVehicle / fs are injectable for host-independent tests.
21
21
  //
22
22
  // It writes every slot of every activity in the registry (carriers.mjs, via recipes.mjs) — the
23
23
  // carrier slots and the `routine.parallel` switch included — and resolves each preview against the
24
- // SAME readiness the recipes advisor composes: detected backends plus the executor-vehicle survey.
24
+ // SAME readiness the recipes advisor composes: detected backends plus both vehicle surveys.
25
25
  //
26
26
  // Dependency-free, Node >= 22. No side effects on import (the isDirectRun idiom).
27
27
 
@@ -31,6 +31,7 @@ import { settingsSnapshot } from './bridge-settings-read.mjs';
31
31
  import { posturesByBackend } from './bridge-posture.mjs';
32
32
  import { surveyVehicle } from './cheap-agents-read.mjs';
33
33
  import { applyCheapAgentsCommand } from './cheap-agents.mjs';
34
+ import { AUTHOR_ROLE, CARRY_ROLE, slotRole } from './carriers.mjs';
34
35
  import {
35
36
  ACTIVITIES,
36
37
  SLOT_RECIPES,
@@ -105,15 +106,15 @@ const parseArgs = (argv) => {
105
106
 
106
107
  // ── effective-recipe resolution per op (degradation honesty) ────────────────────────
107
108
 
108
- // The readiness EVERY resolution here runs against: the detected bridges plus the executor-vehicle
109
- // survey, composed by the one helper the recipes CLI uses. Detection is a SECONDARY input — a bridge
109
+ // The readiness EVERY resolution here runs against: the detected bridges plus both vehicle
110
+ // surveys, composed by the one helper the recipes CLI uses. Detection is a SECONDARY input — a bridge
110
111
  // detector throw must NOT block the write (the config write is readiness-independent) and must not
111
- // cost the CARRIER either: the hook warns, the bridge half floors at not-ready, the vehicle survives.
112
+ // cost the CARRIER either: the hook warns, the bridge half floors at not-ready, the vehicles survive.
112
113
  const composeReadinessOrWarn = (cwd, deps, warnings) =>
113
114
  composeReadiness(cwd, {
114
115
  ...deps,
115
116
  onDetectError: (err) => warnings.push(
116
- `backend detection failed (${(err && err.message) || err}) — treating every bridge as not ready; recipes needing a bridge degrade to solo (the executor vehicle is unaffected).`,
117
+ `backend detection failed (${(err && err.message) || err}) — treating every bridge as not ready; recipes needing a bridge degrade to solo (the executor and author vehicles are unaffected).`,
117
118
  ),
118
119
  });
119
120
 
@@ -190,6 +191,12 @@ const QUALIFIED_SLOTS = Object.entries(ACTIVITIES)
190
191
  .flatMap(([activity, def]) => Object.keys(def.slots).map((slot) => `${activity}.${slot}`))
191
192
  .join(', ');
192
193
 
194
+ const listSlotsByRole = (role) => Object.entries(ACTIVITIES)
195
+ .flatMap(([activity, def]) => Object.keys(def.slots)
196
+ .filter((slot) => slotRole(activity, slot) === role)
197
+ .map((slot) => `${activity}.${slot}`))
198
+ .join(', ');
199
+
193
200
  const HELP = `set-recipe — write the per-project orchestration config (docs/ai/orchestration.json).
194
201
 
195
202
  Usage:
@@ -211,8 +218,9 @@ ${ACTIVITY_LINES}
211
218
  Accepted values per slot type:
212
219
  ${VALUE_LINES}
213
220
 
214
- A carrier slot set to subagent needs the executor vehicle placed in this project — ${EXECUTOR_APPLY};
215
- without it the slot resolves to solo with the reason stated. routine.parallel is a flag, not a
221
+ A slot set to subagent needs the author vehicle for ${listSlotsByRole(AUTHOR_ROLE)};
222
+ the executor vehicle for ${listSlotsByRole(CARRY_ROLE)}. Without its role's ready vehicle the slot
223
+ resolves to solo with the reason stated — ${EXECUTOR_APPLY}. routine.parallel is a flag, not a
216
224
  recipe: it never degrades.
217
225
 
218
226
  Previews by default; --write applies via an atomic, symlink/TOCTOU-safe write behind a deployment gate.
@@ -226,7 +234,7 @@ Exit codes: 0 success (an explicit recipe that gracefully degrades is still 0);
226
234
 
227
235
  export const main = (argv, ctx = {}) => {
228
236
  const cwd = ctx.cwd ?? process.cwd();
229
- const readinessDeps = { detect: ctx.detect, surveyVehicle: ctx.surveyVehicle };
237
+ const readinessDeps = { detect: ctx.detect, surveyVehicle: ctx.surveyVehicle, surveyAuthorVehicle: ctx.surveyAuthorVehicle };
230
238
  const readFile = ctx.readFileSync ?? readFileSync;
231
239
  const lstat = ctx.lstatSync ?? lstatSync;
232
240
  const writeConfig = ctx.writeConfig ?? writeConfigFs;
@@ -30,10 +30,10 @@ entries of each directory and its depth below its root, over every tracked entry
30
30
  root outside the kit's own folder ${KIT_FOLDER_ROOT} plus the spec store docs/ai/specs walked from
31
31
  disk, and the files of each declared root.
32
32
 
33
- A recorded entry is DEBT: a finding stops exactly when the regeneration would raise it, and a record
34
- above the tree or gone warns until the regeneration lowers or removes it. No line sum over a root is
35
- judged or recorded: an "aggregate" an earlier schema recorded warns on every check of a minted config and is dropped,
36
- with no reason, by the next regeneration.
33
+ A recorded entry is an exception with its reason: a finding stops exactly when the regeneration
34
+ would raise it, and a record above the tree or gone warns until the regeneration lowers or removes
35
+ it. No line sum over a root is judged or recorded: an "aggregate" an earlier schema recorded warns
36
+ on every check of a minted config and is dropped, with no reason, by the next regeneration.
37
37
 
38
38
  --write-baseline regenerates the machine keys (baseline, and layout where it is judged) from the
39
39
  tree and writes schema ${SOURCE_SIZE_SCHEMA}, on an absent config too. --layout starts the layout record on a
@@ -10,10 +10,11 @@
10
10
  // Dependency-free, Node >= 22. No side effects on import.
11
11
 
12
12
  import { join } from 'node:path';
13
+ import { SPEC_STORE } from '../../references/scripts/shared/index.mjs';
13
14
 
14
15
  // The spec store: one more judged root, at a fixed path, walked from disk because a deployment may
15
16
  // hide it from git.
16
- export const SPEC_STORE_ROOT = 'docs/ai/specs';
17
+ export const SPEC_STORE_ROOT = SPEC_STORE;
17
18
 
18
19
  // bandOf(value, tolerance) → ceil(value × tolerance / 100), in integers so no float rounds it.
19
20
  export const bandOf = (value, tolerance) => Math.floor((value * tolerance + 99) / 100);
@@ -7,14 +7,14 @@
7
7
 
8
8
  import { createHash } from 'node:crypto';
9
9
  import { join, resolve } from 'node:path';
10
- import { tokenizeMarkdown } from '../../references/scripts/shared/index.mjs';
10
+ import { QUEUE, tokenizeMarkdown } from '../../references/scripts/shared/index.mjs';
11
11
  import { auditQueue, canonicalHeading, checkQueue } from '../queue-audit.mjs';
12
12
  import { parseArgv } from '../queue-audit-cli.mjs';
13
13
  import { bandOf } from './layout.mjs';
14
14
 
15
15
  export const PILE_ANSWERS = Object.freeze(['none', 'held', 'write']);
16
16
  export const PILE_HELD = Object.freeze(['key', 'queue', 'bucket', 'check', 'refused']);
17
- export const PILE_QUEUE_REL = 'docs/plans/queue.md';
17
+ export const PILE_QUEUE_REL = QUEUE;
18
18
  export const PILE_QUEUE_MAX_BYTES = 8388608;
19
19
 
20
20
  const QUEUE_CLI = 'queue-audit-cli.mjs';
@@ -5,7 +5,7 @@
5
5
  // present). A malformed or unknown-keyed config is a loud STOP
6
6
  // (exit 2), never a guess, and the template placeholders are REFUSED until replaced, so a
7
7
  // printed authoring template can never be pasted into an empty-green scope.
8
- // • A RECORDED size is debt, not permission: every entry carries a reason, and the reason lands
8
+ // • A RECORDED size is an exception with its reason, which lands
9
9
  // verbatim in the JSON, the commit message and the release CHANGELOG — so it is validated as the
10
10
  // single line those three surfaces can carry.
11
11
  // • SCHEMAS — 3 is the shape: the kit's limits live in its code (tools/source-size/), the config
@@ -18,6 +18,7 @@
18
18
 
19
19
  import { readFileSync, lstatSync } from 'node:fs';
20
20
  import { isAbsolute } from 'node:path';
21
+ import { KIT_FOLDER } from '../references/scripts/shared/index.mjs';
21
22
  import { SOURCE_SIZE_CONFIG_REL, configFail, configPathFor, isLineUnsafe } from './source-size-refusal.mjs';
22
23
  import { KIT_LIMITS, SPEC_STORE_ROOT, layoutDefect, limitsDefect, migrateSchema1, resolveLimits } from './source-size/index.mjs';
23
24
 
@@ -32,7 +33,7 @@ export { INITIAL_ADOPTION_REASON } from './source-size/index.mjs';
32
33
  // The root an absent `roots` declares: every tracked path. Admitted only as the sole root.
33
34
  export const WHOLE_TREE_ROOT = '.';
34
35
  // The kit's own folder: taken away from every judgment by this fixed path, with no config key.
35
- export const KIT_FOLDER_ROOT = 'scripts/agent-workflow';
36
+ export const KIT_FOLDER_ROOT = KIT_FOLDER;
36
37
 
37
38
  export const AUTHORED_KEYS = Object.freeze(['_README', 'schema', 'roots', 'exclude', 'extensions', 'limits']);
38
39
  const SCHEMA1_AUTHORED_KEYS = Object.freeze(['_README', 'schema', 'defaults', 'roots', 'exclude', 'extensions']);
@@ -249,7 +250,6 @@ export const validateSourceSizeConfig = (parsed) => {
249
250
  if (defect) throw configFail(defect);
250
251
  assertNoStoreRoot(roots);
251
252
  }
252
- // `defaults` keeps the shape the judge, practiceFacts and the plan-time cap read, now resolved.
253
253
  const { limits, defaults } = resolveLimits(shape.limits);
254
254
  return {
255
255
  schema: parsed.schema,
@@ -20,19 +20,20 @@
20
20
  // Dependency-free, Node >= 22. No side effects on import.
21
21
 
22
22
  import { resolve } from 'node:path';
23
+ import { SOURCE_SIZE } from '../references/scripts/shared/index.mjs';
23
24
 
24
- export const SOURCE_SIZE_CONFIG_REL = 'docs/ai/source-size.json';
25
+ export const SOURCE_SIZE_CONFIG_REL = SOURCE_SIZE;
25
26
 
26
27
  // Quoted VERBATIM by every surface that explains the practice: the plan-time render, the checker's
27
28
  // rendered refusals, the constraints row a grounded review payload carries. The checker's GREEN line
28
29
  // states the practice's FACTS instead — caps, recorded count — and never this sentence.
29
- export const SOURCE_SIZE_WHY = 'A module you can hold whole is the unit of review, test pairing and safe edit; the caps turn size drift into recorded, reasoned debt instead of invisible growth.';
30
+ export const SOURCE_SIZE_WHY = 'A module you can hold whole is the unit of review, test pairing and safe edit; a limit is a signal, not a goal, and a justified size is a recorded exception with its reason instead of invisible growth.';
30
31
 
31
32
  // Every warning the check prints is one line under this anchored prefix, so the gate runner can echo
32
33
  // a green check's warnings and nothing else of its output.
33
34
  export const SOURCE_SIZE_WARNING_PREFIX = 'source-size: WARNING — ';
34
35
 
35
- export const configPathFor = (cwd) => resolve(cwd, 'docs', 'ai', 'source-size.json');
36
+ export const configPathFor = (cwd) => resolve(cwd, SOURCE_SIZE);
36
37
 
37
38
  export const SOURCE_SIZE_STOP = 'SOURCE_SIZE_STOP';
38
39