@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
@@ -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
 
@@ -15,6 +15,7 @@
15
15
  //
16
16
  // Dependency-free, Node >= 22. No writes, no side effects on import.
17
17
 
18
+ import { AGENT_RULES, RULES_EFFECTIVE } from '../references/scripts/shared/index.mjs';
18
19
  import { SOURCE_SIZE_CONFIG_REL, SOURCE_SIZE_WARNING_PREFIX, SOURCE_SIZE_WHY, configPathFor, escapeForLine, isLineUnsafe, jsonForLine } from './source-size-refusal.mjs';
19
20
  import { KIT_FOLDER_ROOT, SOURCE_SIZE_SCHEMA, practiceFacts } from './source-size-config.mjs';
20
21
  import { SOURCE_SIZE_TOOL_PATH, dqUnsafePath } from './source-size-gate-cmd.mjs';
@@ -32,9 +33,10 @@ const namedConfig = (cwd) => escapeForLine(configPathFor(cwd));
32
33
  // `_README` byte-equal to one of them with the text of the schema it writes and carries any other verbatim.
33
34
  export const SCHEMA1_TEMPLATE_README = 'Source-size practice: declared scope + thresholds + the recorded ratchet. Authored keys: schema, defaults, roots, exclude, extensions. Machine keys: baseline, aggregate — each recorded entry carries a reason, and a recorded size is debt, not permission. Strict JSON — unknown keys refused.';
34
35
  export const SCHEMA2_TEMPLATE_README = 'Source-size practice: declared scope + the recorded ratchet; the limits are the kit\'s, kept in its code. Authored keys: schema, roots, exclude, extensions, limits (a project\'s reasoned overrides of a kit limit). Machine keys: baseline, aggregate, layout — each recorded entry carries a reason, and a recorded size is debt, not permission. Strict JSON — unknown keys refused.';
35
- export const TEMPLATE_README = 'Source-size practice: declared scope + the recorded ratchet; the limits are the kit\'s, kept in its code. Authored keys: schema, roots, exclude, extensions, limits (a project\'s reasoned overrides of a kit limit). Machine keys: baseline, layout — each recorded entry carries a reason, and a recorded size is debt, not permission. Strict JSON — unknown keys refused.';
36
+ const REVISION_12_TEMPLATE_README = 'Source-size practice: declared scope + the recorded ratchet; the limits are the kit\'s, kept in its code. Authored keys: schema, roots, exclude, extensions, limits (a project\'s reasoned overrides of a kit limit). Machine keys: baseline, layout — each recorded entry carries a reason, and a recorded size is debt, not permission. Strict JSON — unknown keys refused.';
37
+ export const TEMPLATE_README = 'Source-size practice: declared scope + the recorded ratchet; the limits are the kit\'s, kept in its code. Authored keys: schema, roots, exclude, extensions, limits (a project\'s reasoned overrides of a kit limit). Machine keys: baseline, layout — each recorded entry is an exception with its own reason, never permission to grow. Strict JSON — unknown keys refused.';
36
38
  export const TEMPLATE_READMES = Object.freeze({ schema1: SCHEMA1_TEMPLATE_README, schema2: SCHEMA2_TEMPLATE_README });
37
- export const EARLIER_TEMPLATE_READMES = Object.freeze([SCHEMA1_TEMPLATE_README, SCHEMA2_TEMPLATE_README]);
39
+ export const EARLIER_TEMPLATE_READMES = Object.freeze([SCHEMA1_TEMPLATE_README, SCHEMA2_TEMPLATE_README, REVISION_12_TEMPLATE_README]);
38
40
 
39
41
  // The authoring template (D-5): GENERIC, and INERT by construction — its roots/extensions carry
40
42
  // placeholders the validator refuses, so it can never be pasted into an empty-green scope.
@@ -82,7 +84,9 @@ const WITHHELD_LINE = 'source-size: no paste-ready command is printed — this p
82
84
  // The withheld fallback is the reader's ONLY remaining instruction, so it has to be the instruction
83
85
  // for what they were actually doing. Sending an adoption to the regenerator would leave them with a
84
86
  // record and no gate — half an adoption, handed over as the way out — so the lane is per MODE.
85
- const WITHHELD_LANE = 'Run the regenerator yourself with the working directory set to this project (source-size-check.mjs --write-baseline, plus --reason "<text>" for any raise), or record each size by hand below, your reason in place of the placeholder.';
87
+ const regenerationMode = (layout) => (layout ? '--write-baseline --layout' : '--write-baseline');
88
+ const withheldLane = (layout = false) => `Run the regenerator yourself with the working directory set to this project (source-size-check.mjs ${regenerationMode(layout)}, plus --reason "<text>" for any raise).`;
89
+ const WITHHELD_LANE = withheldLane();
86
90
  const WITHHELD_ADOPT_LANE = `Run source-size-check.mjs --adopt --reason "${INITIAL_ADOPTION_REASON}" yourself, with the working directory set to this project — it mints the record and declares the gate in one step.`;
87
91
 
88
92
  // → { command, withheld }: exactly one of the two is non-null. ONE renderer for every mode this tool
@@ -93,9 +97,12 @@ const rendered = (cwd, mode, reason) => {
93
97
  if (paths.some(dqUnsafePath)) return { command: null, withheld: WITHHELD_SHELL };
94
98
  return { command: `node "${SOURCE_SIZE_TOOL_PATH}" ${mode} --cwd "${cwd}"${reason === undefined ? '' : ` --reason "${reason}"`}`, withheld: null };
95
99
  };
96
- const regenerator = (cwd, reason, layout = false) => rendered(cwd, layout ? '--write-baseline --layout' : '--write-baseline', reason);
100
+ const regenerator = (cwd, reason, layout = false) => rendered(cwd, regenerationMode(layout), reason);
97
101
 
98
102
  const SPLIT_QUALITY_FOCUS = 'source-size: REVIEW FOCUS — a recorded size went DOWN or disappeared: check that this is real decomposition and not the same coupling spread across more files (paste this line into the review dispatch focus).';
103
+ const RAISE_FOCUS_END = 'judge whether the project\'s code rules were kept for that file; a reason naming a debt row holds an old file grown outside its story\'s scope (paste this line into the review dispatch focus).';
104
+ const RAISE_REVIEW_FOCUS = `source-size: REVIEW FOCUS — this write RAISED a recorded size: read each raised entry's reason and ${RAISE_FOCUS_END}`;
105
+ const HAND_RECORD_FOCUS = `source-size: REVIEW FOCUS — the entries above RAISE a recorded size once recorded by hand: give the review each one's recorded and new value and its reason, read each reason and ${RAISE_FOCUS_END}`;
99
106
 
100
107
  // Rendered refusals close with WHY. Thrown stops and usage refusals carry no WHY line; the command
101
108
  // line composes them, each with the remedy of its exit class (usage carries only its help lines).
@@ -106,7 +113,7 @@ const refusal = (lines) => [...lines, WHY_LINE];
106
113
  // absent one records nothing to summarize.
107
114
  const practiceLine = (config) => {
108
115
  const facts = practiceFacts(config);
109
- return `source-size: practice — caps ${facts.maxLines} lines · ${facts.maxLineBytes} bytes per line over ${facts.roots} declared root(s) · ${facts.recordedFiles} file(s) carry a recorded size (debt, not permission): growth past a record takes a reasoned bump, and a record above the tree or gone warns until the regeneration lowers or removes it.`;
116
+ return `source-size: practice — caps ${facts.maxLines} lines · ${facts.maxLineBytes} bytes per line over ${facts.roots} declared root(s) · ${facts.recordedFiles} file(s) carry a recorded size, each an exception with its reason: growth the regeneration would raise stops and takes a reason, asking again whether the project's code rules were kept; a record above the tree or gone warns until the regeneration lowers or removes it.`;
110
117
  };
111
118
 
112
119
  export const absentRefusalLines = (cwd) => refusal([
@@ -160,15 +167,16 @@ const PREDATING_KIT_STOPS = (schema) => `a kit that predates schema ${schema} st
160
167
  const BAND = (f) => `over the limit ${f.allowed} but within its band (up to ${f.ceiling})`;
161
168
  const NAMED_PATHS = 3;
162
169
  const namedPaths = (paths) => `${paths.slice(0, NAMED_PATHS).map(escapeForLine).join(', ')}${paths.length > NAMED_PATHS ? ` and ${paths.length - NAMED_PATHS} more` : ''}`;
170
+ const RECORDED_EXCEPTION_ENDING = 'a recorded exception holds the size it was reasoned for, not growth past it';
163
171
 
164
172
  // A stop: the regeneration would raise.
165
173
  const FINDING_LINE = Object.freeze({
166
174
  'over-default': (f) => `${f.rel}: ${f.dimension} ${f.actual} exceeds the declared default ${f.allowed} beyond its band (up to ${f.ceiling})`,
167
- grew: (f) => `${f.rel}: ${f.dimension} ${f.actual} exceeds its recorded baseline ${f.recorded} — recorded debt is not permission to grow`,
175
+ grew: (f) => `${f.rel}: ${f.dimension} ${f.actual} exceeds its recorded baseline ${f.recorded} — ${RECORDED_EXCEPTION_ENDING}`,
168
176
  'root-unrecorded': (f) => `${f.root}: declared root carries NO recorded files count (${f.actual} files measured) — the layout record must mirror the declared roots exactly`,
169
177
  'root-grew': (f) => `${f.root}: files ${f.actual} exceeds its recorded ${f.recorded} beyond its band (up to ${f.ceiling})`,
170
178
  'dir-over': (f) => `${f.dir}: ${f.dimension} ${f.actual} exceeds the limit ${f.allowed} beyond its band (up to ${f.ceiling})`,
171
- 'dir-grew': (f) => `${f.dir}: ${f.dimension} ${f.actual} exceeds its recorded ${f.recorded} — recorded debt is not permission to grow`,
179
+ 'dir-grew': (f) => `${f.dir}: ${f.dimension} ${f.actual} exceeds its recorded ${f.recorded} — ${RECORDED_EXCEPTION_ENDING}`,
172
180
  });
173
181
 
174
182
  // A warning: printed on every run, exit 0, until the value or its record comes back within its limit.
@@ -219,20 +227,40 @@ const findingPart = (finding) => {
219
227
  const emptyRootLines = (verdict) => verdict.scope.emptyRoots.map((rel) =>
220
228
  `source-size: NOTE — the declared root "${escapeForLine(rel)}" matches no tracked file with a declared extension${verdict.scope.kitFolderRoots.includes(rel) ? ` outside the kit's own folder ${KIT_FOLDER_ROOT}` : ''}`);
221
229
 
230
+ const CODE_RULE_QUESTIONS = [
231
+ `for each place above, ask first whether the project's code rules were kept; consult ${AGENT_RULES} and ${RULES_EFFECTIVE} where present`,
232
+ 'a broken rule: fix the code along its own seam; the rules kept and the size justified: record it as an exception with its reason, written by whoever runs the write, never asked of the user',
233
+ 'never split or compress a file for the number',
234
+ 'an old file grown in work about something else, its rules not kept: write a debt row and record the raise with a reason that names the row, never reworking the file outside that work\'s scope',
235
+ ];
236
+ const HAND_RECORD_REMEDIES = [
237
+ 'record each raised file by hand under "baseline", with that file\'s own reason: the entries below',
238
+ 'only where one reason fits every raise of this run, regenerate instead:',
239
+ ];
240
+ const HAND_RECORD_LEAD = 'Each placeholder below is replaced by that file\'s own reason; the validator accepts the rest of these bytes as they are:';
241
+ const REGENERATION_RAISES = 'This regeneration RAISES a recorded value, so the reason is REQUIRED — it is recorded in the entry it raises, and it is what the commit message and the CHANGELOG restate.';
242
+
222
243
  export const checkStopBlock = ({ cwd, verdict, absent = false }) => {
223
244
  const stops = stopsOf(verdict.findings);
224
245
  const warnings = warningsOf(verdict.findings);
225
246
  const entries = suggestedEntryLines(verdict);
247
+ const hasRaisedFiles = entries.length > 0;
248
+ const limitFired = stops.some((finding) => finding.kind !== 'root-unrecorded');
226
249
  const { command, withheld } = regenerator(cwd, GROWTH_REASON_PLACEHOLDER);
227
250
  return {
228
251
  failed: escapeLeadingSpace(`${stops.length} finding(s) ${absent ? `under the kit's values (${namedConfig(cwd)} is absent)` : `against ${namedConfig(cwd)}`}`),
229
252
  findings: stops.map(findingPart),
230
- remedies: [command ?? WITHHELD_LANE],
253
+ remedies: [
254
+ ...(limitFired ? CODE_RULE_QUESTIONS : []),
255
+ ...(hasRaisedFiles ? HAND_RECORD_REMEDIES : []),
256
+ command ?? WITHHELD_LANE,
257
+ ],
231
258
  after: refusal([
232
259
  ...emptyRootLines(verdict), ...warningLines(warnings),
233
- ...(command === null ? [withheld] : ['This regeneration RAISES a recorded value, so the reason is REQUIRED — it is recorded in the entry it raises, and it is what the commit message and the CHANGELOG restate.']),
234
- ...(command !== null && entries.length > 0 ? ['Or record each size by hand under "baseline" — replace the placeholder with your reason; the validator accepts the rest of these bytes as they are:'] : []),
235
- ...entries, ...(hasLoweredRecord(warnings) ? [SPLIT_QUALITY_FOCUS] : []),
260
+ command === null ? withheld : REGENERATION_RAISES,
261
+ ...(hasRaisedFiles ? [HAND_RECORD_LEAD, ...entries] : []),
262
+ ...(hasLoweredRecord(warnings) ? [SPLIT_QUALITY_FOCUS] : []),
263
+ ...(hasRaisedFiles ? [HAND_RECORD_FOCUS] : []),
236
264
  ]),
237
265
  };
238
266
  };
@@ -268,7 +296,7 @@ export const deltaLines = (deltas) => deltas.map(
268
296
  // A run that starts the layout record says so in the command it prints, or pasting it would not.
269
297
  const regenerationRefusal = (lead, cwd, deltas, layout) => {
270
298
  const { command, withheld } = regenerator(cwd, GROWTH_REASON_PLACEHOLDER, layout);
271
- return refusal([lead, ...deltaLines(deltas), command === null ? `${withheld} ${WITHHELD_LANE}` : ` ${command}`]);
299
+ return refusal([lead, ...deltaLines(deltas), command === null ? `${withheld} ${withheldLane(layout)}` : ` ${command}`]);
272
300
  };
273
301
 
274
302
  export const reasonRequiredLines = (cwd, deltas, { layout = false } = {}) => regenerationRefusal(
@@ -375,7 +403,7 @@ export const writtenLines = ({ cwd, deltas, reason, changed }) => {
375
403
  return [
376
404
  `source-size: baseline regenerated — ${deltas.length} change(s) in ${namedConfig(cwd)}:`,
377
405
  ...deltaLines(deltas),
378
- ...(reason === undefined ? [] : [`reason: ${reason}`]),
406
+ ...(reason === undefined ? [] : [`reason: ${reason}`, RAISE_REVIEW_FOCUS]),
379
407
  ];
380
408
  };
381
409