@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
@@ -5,10 +5,9 @@
5
5
  // three cases of references/modes/state-block-guard.md: no `hooks` key, a `hooks` key without
6
6
  // `Stop`, and a `hooks.Stop` array, which gains one element.
7
7
  //
8
- // The symlink, target and settings-shape checks and the hook-file write (writeHookFile) are IMPORTED
9
- // from gate-hook.mjs, with the stamp reader and the settings formatter; the unsafe-mode and stamp
10
- // refusals, the place-then-wire order and the no-follow re-read of the placed file before the
11
- // settings write follow gate-hook's, with its error codes. What is the Stop hook's own:
8
+ // The place-then-wire flow runs on the kit's hook writer (hook-writer/index.mjs), which imports the
9
+ // hardened checks, the hook-file write and the unsafe-mode and stamp refusals from gate-hook.mjs,
10
+ // with its error codes. What is the Stop hook's own:
12
11
  // • preview by default; `--apply` writes;
13
12
  // • the runtime is created when absent, kept when byte-equal, replaced when it differs (the
14
13
  // preview says so; the danger check prints the replaced bytes' digest);
@@ -21,42 +20,17 @@
21
20
  // Exit codes: 0 done / preview; 1 precondition STOP; 2 usage. Dependency-free beyond the kit's
22
21
  // own internal exports, Node >= 22. No side effects on import.
23
22
 
24
- import { dirname, join, resolve } from 'node:path';
23
+ import { dirname, resolve } from 'node:path';
25
24
  import { fileURLToPath } from 'node:url';
26
- import {
27
- CLAUDE_DIR,
28
- EXPECTED_WORKFLOW_VERSION,
29
- SAFE_DEFAULT_MODES,
30
- SETTINGS_FILE,
31
- SETTINGS_LOCAL_FILE,
32
- UNSAFE_BYPASS_MODE,
33
- WORKFLOW_STAMP,
34
- readSettingsFile,
35
- resolveEffectiveMode,
36
- } from './velocity-profile.mjs';
37
- import {
38
- GATE_HOOK_DIVERGED,
39
- GATE_HOOK_STAMP,
40
- GATE_HOOK_UNSAFE_MODE,
41
- HOOKS_DIR,
42
- assertDirSafe,
43
- assertHooksShape,
44
- assertSettingsWritable,
45
- formatJson,
46
- fsDeps,
47
- makeGateHookError,
48
- planTarget,
49
- readBundledHook,
50
- readStamp,
51
- writeHookFile,
52
- } from './gate-hook.mjs';
25
+ import { STOP_HOOK } from '../references/scripts/shared/index.mjs';
26
+ import { SETTINGS_FILE, SETTINGS_LOCAL_FILE } from './velocity-profile.mjs';
27
+ import { formatKitHookResult, mergeHookEntryInto, writeKitHook } from './hook-writer/index.mjs';
53
28
  import { isDirectRun } from './direct-run.mjs';
54
- import { fileLine } from './distribution-files/index.mjs';
55
29
 
56
30
  const HERE = dirname(fileURLToPath(import.meta.url));
57
31
 
58
32
  export const STATE_BLOCK_HOOK_RUNTIME = 'state-block-guard.mjs';
59
- export const STATE_BLOCK_HOOK_FILE_REL = `${HOOKS_DIR}/${STATE_BLOCK_HOOK_RUNTIME}`;
33
+ export const STATE_BLOCK_HOOK_FILE_REL = STOP_HOOK;
60
34
  const BUNDLED_STATE_BLOCK_HOOK_PATH = resolve(HERE, '..', 'references', 'hooks', STATE_BLOCK_HOOK_RUNTIME);
61
35
  // NO `--require-block` in the offered command. That flag turns on the absent-block report, and this
62
36
  // kit does not mandate the three-part closing block — offering it to every project would hand them a
@@ -68,17 +42,13 @@ export const STOP_EVENT = 'Stop';
68
42
  const EXIT_OK = 0;
69
43
  const EXIT_PRECONDITION = 1;
70
44
  const EXIT_USAGE = 2;
71
- const UTF8 = 'utf8';
72
- const LF = '\n';
73
-
74
- const PLACEMENT_CREATE = 'create';
75
- const PLACEMENT_KEEP = 'keep';
76
- const PLACEMENT_REPLACE = 'replace';
77
- const PLACEMENT_OF = Object.freeze({ place: PLACEMENT_CREATE, 'already-current': PLACEMENT_KEEP, diverged: PLACEMENT_REPLACE });
78
45
 
79
46
  const MERGE_NO_HOOKS = 'no-hooks';
47
+ const MERGE_NO_EVENT = 'no-event';
80
48
  const MERGE_NO_STOP = 'no-stop';
81
49
  const MERGE_APPEND = 'append';
50
+ const STOP_CASE_OF = Object.freeze({ [MERGE_NO_EVENT]: MERGE_NO_STOP });
51
+ const KIT_CASE_OF = Object.freeze({ [MERGE_NO_STOP]: MERGE_NO_EVENT });
82
52
 
83
53
  const USAGE = `usage: state-block-hook [--apply] [--cwd <dir>] [--help]
84
54
 
@@ -91,7 +61,6 @@ The entry is merged only while no ${STOP_EVENT} entry of either settings file ru
91
61
  Never writes ${SETTINGS_LOCAL_FILE}; never commits.`;
92
62
 
93
63
  const usageError = (message) => Object.assign(new Error(message), { exitCode: EXIT_USAGE });
94
- const isJsonObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
95
64
 
96
65
  // ── the Stop entry ────────────────────────────────────────────────────────────────────
97
66
 
@@ -112,137 +81,43 @@ export const isStopHookWired = (data) => {
112
81
  : runsStateBlockGuard(entry)));
113
82
  };
114
83
 
115
- const mergeCaseOf = (data) => {
116
- if (!isJsonObject(data) || data.hooks === undefined) return MERGE_NO_HOOKS;
117
- return data.hooks[STOP_EVENT] === undefined ? MERGE_NO_STOP : MERGE_APPEND;
118
- };
119
-
120
84
  // Append our ONE entry; every foreign hook, matcher and key is carried over untouched. Only called
121
85
  // when the entry is absent (idempotence lives in the caller's plan, not in dedup-on-write).
122
- export const mergeStopEntry = (base) => {
123
- const root = isJsonObject(base) ? base : {};
124
- const hooks = isJsonObject(root.hooks) ? root.hooks : {};
125
- const entries = Array.isArray(hooks[STOP_EVENT]) ? hooks[STOP_EVENT] : [];
126
- return { ...root, hooks: { ...hooks, [STOP_EVENT]: [...entries, buildStopHookEntry()] } };
127
- };
128
-
129
- // ── the writer ────────────────────────────────────────────────────────────────────────
130
-
131
- const preflight = (projectDir, deps) => {
132
- const fs = fsDeps(deps);
133
- const bundleContent = readBundledHook({ ...deps, bundlePath: deps.bundlePath ?? BUNDLED_STATE_BLOCK_HOOK_PATH });
134
- const stamp = readStamp(join(projectDir, WORKFLOW_STAMP), fs);
135
- assertDirSafe(join(projectDir, CLAUDE_DIR), CLAUDE_DIR, fs);
136
- assertDirSafe(join(projectDir, HOOKS_DIR), HOOKS_DIR, fs);
137
- const target = planTarget(join(projectDir, STATE_BLOCK_HOOK_FILE_REL), STATE_BLOCK_HOOK_FILE_REL, bundleContent, fs);
138
- assertSettingsWritable(join(projectDir, SETTINGS_FILE), fs);
139
- const projectSettings = readSettingsFile(join(projectDir, SETTINGS_FILE), { ...deps, cwd: projectDir });
140
- const localSettings = readSettingsFile(join(projectDir, SETTINGS_LOCAL_FILE), { ...deps, cwd: projectDir });
141
- const { bypassPermissionsPresent, unsafeModePresent } = resolveEffectiveMode(projectSettings.data, localSettings.data);
142
- if (bypassPermissionsPresent) {
143
- throw makeGateHookError(GATE_HOOK_UNSAFE_MODE, `${UNSAFE_BYPASS_MODE} appears in Claude settings - refusing to wire a hook beside it`);
144
- }
145
- if (unsafeModePresent) {
146
- throw makeGateHookError(
147
- GATE_HOOK_UNSAFE_MODE,
148
- `an unsafe or unknown permissions.defaultMode is present in Claude settings - accepted modes: ${SAFE_DEFAULT_MODES.join(', ')}`,
149
- );
150
- }
151
- assertHooksShape(projectSettings.data, SETTINGS_FILE, STOP_EVENT);
152
- return {
153
- projectDir,
154
- bundleContent,
155
- stamp,
156
- stampOk: stamp === EXPECTED_WORKFLOW_VERSION,
157
- placement: PLACEMENT_OF[target.action],
158
- projectSettings,
159
- localSettings,
160
- wiredInProject: isStopHookWired(projectSettings.data),
161
- wiredInLocal: isStopHookWired(localSettings.data),
162
- mergeCase: mergeCaseOf(projectSettings.data),
163
- };
164
- };
165
-
166
- export const writeStateBlockHook = ({ cwd, dryRun = true } = {}, deps = {}) => {
167
- const fs = fsDeps(deps);
168
- const plan = preflight(resolve(cwd ?? deps.cwd ?? process.cwd()), deps);
169
- const placePlanned = plan.placement !== PLACEMENT_KEEP;
170
- const mergePlanned = !plan.wiredInProject && !plan.wiredInLocal;
171
- const base = { placePlanned, mergePlanned, ...plan };
172
- if (dryRun) return { wrote: false, dryRun: true, ...base };
173
-
174
- if (!plan.stampOk) {
175
- throw makeGateHookError(
176
- GATE_HOOK_STAMP,
177
- `not a deployed agent-workflow project at lineage ${EXPECTED_WORKFLOW_VERSION} (found ${plan.stamp ?? 'none'}) — run init/upgrade first`,
178
- );
179
- }
180
- // Place FIRST, then wire — a wired-but-missing hook would error on every turn end.
181
- const hookAbs = join(plan.projectDir, STATE_BLOCK_HOOK_FILE_REL);
182
- if (plan.placement === PLACEMENT_CREATE) fs.mkdir(join(plan.projectDir, HOOKS_DIR), { recursive: true });
183
- if (placePlanned) writeHookFile(hookAbs, STATE_BLOCK_HOOK_FILE_REL, plan.bundleContent, plan.placement === PLACEMENT_CREATE, fs);
184
- if (mergePlanned) {
185
- // Re-judge the placed file no-follow immediately BEFORE wiring: a runtime swapped, or turned
186
- // into a link, between the placement and now must never be wired — zero settings mutation.
187
- const placed = planTarget(hookAbs, STATE_BLOCK_HOOK_FILE_REL, plan.bundleContent, fs);
188
- if (placed.action !== 'already-current') {
189
- throw makeGateHookError(
190
- GATE_HOOK_DIVERGED,
191
- `${STATE_BLOCK_HOOK_FILE_REL} changed after placement — refusing to wire an unknown script as a ${STOP_EVENT} hook (no settings change made); re-run`,
192
- );
193
- }
194
- fs.writeFile(
195
- join(plan.projectDir, SETTINGS_FILE),
196
- formatJson(mergeStopEntry(plan.projectSettings.data ?? {}), plan.projectSettings.eol ?? LF),
197
- UTF8,
198
- );
199
- }
200
- return { wrote: placePlanned || mergePlanned, dryRun: false, ...base };
201
- };
202
-
203
- // ── report ────────────────────────────────────────────────────────────────────────────
86
+ export const mergeStopEntry = (base) => mergeHookEntryInto(base, STOP_EVENT, buildStopHookEntry());
204
87
 
205
- const STATE_BLOCK_CURRENT_LINE = 'nothing to change: the state-block hook is placed, current and wired';
88
+ // ── the writer and its report ─────────────────────────────────────────────────────────
206
89
 
207
90
  const TRUST_POSTURE_LINE =
208
91
  'trust posture: the guard reads the closing assistant message of each turn and writes one warning line; it runs a Node process on every turn end, reads nothing else, makes no network call and approves nothing.';
209
92
 
210
- const PLACEMENT_LINES = Object.freeze({ [PLACEMENT_CREATE]: ['would place', 'placed'], [PLACEMENT_KEEP]: ['already current', 'already current'] });
211
- const placementLine = ({ placement, dryRun }) => (placement === PLACEMENT_REPLACE
212
- ? fileLine({ rel: STATE_BLOCK_HOOK_FILE_REL, state: 'hook' }, dryRun ? undefined : 'written', dryRun)
213
- : `${STATE_BLOCK_HOOK_FILE_REL}: ${PLACEMENT_LINES[placement][dryRun ? 0 : 1]}`);
214
-
215
- const MERGE_LINES = Object.freeze({
216
- [MERGE_NO_HOOKS]: 'the hooks key with the Stop entry',
217
- [MERGE_NO_STOP]: 'the Stop key beside the existing hooks',
218
- [MERGE_APPEND]: 'one element to the existing hooks.Stop array',
93
+ const STATE_BLOCK_HOOK = Object.freeze({
94
+ fileRel: STATE_BLOCK_HOOK_FILE_REL,
95
+ bundlePath: BUNDLED_STATE_BLOCK_HOOK_PATH,
96
+ event: STOP_EVENT,
97
+ entry: buildStopHookEntry(),
98
+ isWired: isStopHookWired,
99
+ refusesUnsafeModes: true,
100
+ lines: Object.freeze({
101
+ title: 'state-block hook',
102
+ commandNote: `command: ${STATE_BLOCK_HOOK_COMMAND} (no --require-block; references/modes/state-block-guard.md says when to add it)`,
103
+ reload: 'the Stop hook runs from the next turn end',
104
+ merge: Object.freeze({
105
+ [MERGE_NO_HOOKS]: 'the hooks key with the Stop entry',
106
+ [MERGE_NO_EVENT]: 'the Stop key beside the existing hooks',
107
+ [MERGE_APPEND]: 'one element to the existing hooks.Stop array',
108
+ }),
109
+ bypassReason: 'refusing to wire a hook beside it',
110
+ trustPosture: TRUST_POSTURE_LINE,
111
+ nothingToChange: 'nothing to change: the state-block hook is placed, current and wired',
112
+ }),
219
113
  });
220
114
 
221
- const formatSettingsLine = (result) => {
222
- if (result.wiredInProject) return ` - ${SETTINGS_FILE}: already wired`;
223
- if (result.wiredInLocal) return ` - ${SETTINGS_FILE}: already wired via ${SETTINGS_LOCAL_FILE} — not duplicated`;
224
- return ` - ${SETTINGS_FILE}: ${result.dryRun ? 'would add' : 'added'} ${MERGE_LINES[result.mergeCase]}`;
225
- };
115
+ const withMergeCase = (result, caseOf) => ({ ...result, mergeCase: caseOf[result.mergeCase] ?? result.mergeCase });
226
116
 
227
- export const formatResult = (result) => {
228
- if (!result.placePlanned && !result.mergePlanned) return STATE_BLOCK_CURRENT_LINE;
229
- const lines = [
230
- result.dryRun
231
- ? 'agent-workflow state-block hook — DRY RUN (no changes; re-run with --apply)'
232
- : 'agent-workflow state-block hook — APPLY',
233
- ` - ${placementLine(result)}`,
234
- formatSettingsLine(result),
235
- ` command: ${STATE_BLOCK_HOOK_COMMAND} (no --require-block; references/modes/state-block-guard.md says when to add it)`,
236
- TRUST_POSTURE_LINE,
237
- ];
238
- if (!result.stampOk) {
239
- lines.push(`note: no current deployment stamp found (${result.stamp ?? 'none'}) — --apply will refuse until init/upgrade runs.`);
240
- }
241
- if (!result.dryRun && result.mergePlanned) {
242
- lines.push('settings hot-reload: the Stop hook runs from the next turn end — no session restart needed.');
243
- }
244
- return lines.join(LF);
245
- };
117
+ export const writeStateBlockHook = ({ cwd, dryRun = true } = {}, deps = {}) =>
118
+ withMergeCase(writeKitHook(STATE_BLOCK_HOOK, { cwd: cwd ?? deps.cwd ?? process.cwd(), dryRun }, deps), STOP_CASE_OF);
119
+
120
+ export const formatResult = (result) => formatKitHookResult(STATE_BLOCK_HOOK, withMergeCase(result, KIT_CASE_OF));
246
121
 
247
122
  // ── CLI ───────────────────────────────────────────────────────────────────────────────
248
123
 
@@ -2,6 +2,7 @@
2
2
  import { writeFileSync, realpathSync, constants as fsConstants } from 'node:fs';
3
3
  import { dirname, isAbsolute, relative, resolve, sep, posix } from 'node:path';
4
4
  import { createHash } from 'node:crypto';
5
+ import { PLANS } from '../references/scripts/shared/index.mjs';
5
6
  import { readFileBytesNoFollow } from './fs-read-nofollow.mjs';
6
7
  import { parseLedger, isSweep, PLAN_HEADINGS } from './plan-shape.mjs';
7
8
  import { expandSweepPaths } from './plan-shape-facts.mjs';
@@ -13,6 +14,7 @@ import { claimedPaths } from './task-thread.mjs';
13
14
  import { newestCheckpoint, verifyCheckpoint } from './checkpoint.mjs';
14
15
  import { withRepository, readGit } from './checkpoint-core.mjs';
15
16
  import { isDirectRun } from './direct-run.mjs';
17
+ import { escapeRegExp } from './repo-lex.mjs';
16
18
 
17
19
  export const BRIEF_BINDING_INFO_STRING = 'aw-task-binding';
18
20
  const ACCEPT = 0;
@@ -36,11 +38,10 @@ const FENCE_RE = /^(`{3,})(.*)$/;
36
38
  const TITLE_RE = /^# Task: (\S.*)$/;
37
39
  const HEADING_RE = /^#{1,2} /;
38
40
  const STORY_PREFIX = 'Story:';
39
- const HEADINGS = ['## Slice', '## Reads', '## Acceptance', '## Negative cases', '## Budget'];
40
- const SLICE_FIELDS = [/^Plan: (docs\/plans\/[^/]+\.md)$/, /^Row: (\S+)$/, /^Grouping: (.*)$/, /^Files:$/];
41
+ const HEADINGS = ['## Slice', '## Reads', '## Acceptance', '## Negative cases'];
42
+ const SLICE_FIELDS = [new RegExp(`^Plan: (${escapeRegExp(PLANS)}\\/[^/]+\\.md)$`), /^Row: (\S+)$/, /^Grouping: (.*)$/, /^Files:$/];
41
43
  const PAIR_RE = /^- (\S(?:.*\S)?) :: (\S(?:.*\S)?)$/;
42
44
  const BULLET_RE = /^- (\S.*)$/;
43
- const INTEGER_RE = /^[1-9]\d*$/;
44
45
  const TEST_RE = /(?:^|\/)[^/]+\.test(?:\.mjs$|\/[^/].*$)/;
45
46
  const EXTENSION_RE = /\.[^/.]+$/;
46
47
  const TEST_SUFFIX = '.test.mjs';
@@ -135,22 +136,16 @@ export const parseBrief = (text) => {
135
136
  checkMembers(found, HEADINGS, 'heading');
136
137
  if (HEADINGS.some((text, index) => found[index] !== text)) reject(NAMES.shape, `headings out of order: ${found.join(', ')}`);
137
138
  const sections = HEADINGS.map((heading, index) => lines.slice(headings[index + ONE].index + ONE, headings[index + BASIC_ARGS]?.index ?? lines.length));
138
- const [slice, reads, acceptance, negative, budget] = sections;
139
+ const [slice, reads, acceptance, negative] = sections;
139
140
  const [[planPath], [rowId], [grouping]] = SLICE_FIELDS.map((pattern, index) => checkSliceField(pattern, slice[index], index));
140
141
  const files = slice.slice(SLICE_FIELDS.length).map((line) => {
141
142
  const [path, tag] = matchLine(PAIR_RE, line, 'a Files: line is not "- <path> :: <tag>"');
142
143
  return { path, tag };
143
144
  });
144
- const budgets = budget.map((line) => {
145
- const [path, count] = matchLine(PAIR_RE, line, 'a ## Budget line is not "- <path> :: <lines>"');
146
- if (!INTEGER_RE.test(count) || !Number.isSafeInteger(Number(count))) reject(NAMES.shape, `a ## Budget count is not a positive integer: ${line}`);
147
- return { path, maxLines: Number(count) };
148
- });
149
145
  if (files.length === START) reject(NAMES.shape, 'Files: lists no path');
150
- checkMembers(budgets.map(({ path }) => path), [...new Set(files.map(({ path }) => path))], '## Budget path');
151
146
  if (acceptance.length === START) reject(NAMES.shape, '## Acceptance lists no line');
152
147
  if (negative.length === START) reject(NAMES.shape, '## Negative cases lists no line');
153
- return { ok: true, title, storyLines, planPath, rowId, grouping, files, budgets,
148
+ return { ok: true, title, storyLines, planPath, rowId, grouping, files,
154
149
  reads: reads.map((line) => matchLine(BULLET_RE, line, 'a ## Reads line is not a bullet')[START]),
155
150
  acceptance: acceptance.map((line) => matchLine(PAIR_RE, line, 'an ## Acceptance line is not "- <command> :: <outcome>"')),
156
151
  negative: negative.map((line) => matchLine(BULLET_RE, line, 'a ## Negative cases line is not a bullet')[START]),
@@ -177,12 +172,11 @@ const checkGrouping = (brief, row) => {
177
172
  const expected = TAGS.filter((tag) => brief.files.some((file) => file.tag === tag)).join(GROUP_SEPARATOR);
178
173
  if (brief.grouping !== expected) reject(NAMES.grouping, `Grouping: ${brief.grouping} differs from the Files tags ${expected}`);
179
174
  const pins = brief.files.filter(({ tag }) => tag === PIN);
180
- if (row && posix.basename(row.path) === PIN_FILE) {
175
+ if (posix.basename(row.path) === PIN_FILE) {
181
176
  if (pins.length !== ONE || pins[START].path !== row.path) reject(NAMES.grouping, `a pin row tags only its own path ${row.path} pin`);
182
177
  } else if (pins.length !== START) reject(NAMES.grouping, `the pin tag belongs to a ${PIN_FILE} row only`);
183
178
  };
184
179
  const checkRow = (context, brief, row) => {
185
- if (!row?.valid) reject(NAMES.row, brief.rowId);
186
180
  const files = brief.files.map((file) => {
187
181
  const path = posix.normalize(file.path);
188
182
  if (path !== file.path || path === CURRENT || path.startsWith(PARENT) || posix.isAbsolute(path)) reject(NAMES.row, file.path);
@@ -210,6 +204,7 @@ const readGrammar = (context, briefPath) => {
210
204
  const plan = readInside(context, brief.planPath);
211
205
  const ledger = parseLedger(plan.bytes.toString(UTF8));
212
206
  const row = ledger.rows.find(({ id }) => id === brief.rowId);
207
+ if (!row?.valid) reject(NAMES.row, brief.rowId);
213
208
  checkGrouping(brief, row);
214
209
  checkRow(context, brief, row);
215
210
  const goal = ledger.document.headings.find(({ text }) => text === PLAN_HEADINGS[START]);
@@ -1,6 +1,8 @@
1
+ import { PLANS } from '../references/scripts/shared/index.mjs';
1
2
  import { hasPathOverlap } from './claim-relation.mjs';
3
+ import { escapeRegExp } from './repo-lex.mjs';
2
4
 
3
- const TASK_BRIEF = /^docs\/plans\/TASK-[^/]+-T[1-9][0-9]*\.md$/u;
5
+ const TASK_BRIEF = new RegExp(`^${escapeRegExp(PLANS)}\\/TASK-[^/]+-T[1-9][0-9]*\\.md$`, 'u');
4
6
  const INVALID_SEGMENTS = Object.freeze(['', '.', '..', '.git']);
5
7
  const HEAD_BASELINE = Object.freeze({ kind: 'head', treeOid: null });
6
8
 
@@ -1,6 +1,7 @@
1
1
  // spec:tier-guide — docs/ai/specs/kit/tier/tier-guide/index.md and its part guide-stages.md
2
2
  import { lstatSync } from 'node:fs';
3
3
  import { posix, resolve } from 'node:path';
4
+ import { DOCS_TREE } from '../references/scripts/shared/index.mjs';
4
5
  import { readRegularFileNoFollow } from './fs-read-nofollow.mjs';
5
6
  import { resolveGitLocation } from './git-env.mjs';
6
7
  import { EPICS_REL, readEpicStore } from './epic-store.mjs';
@@ -8,7 +9,7 @@ import { checkEpic } from './epic-shape.mjs';
8
9
  import { QUEUE_PATH, checkClaims, judgeClose, sweepSiblings } from './epic-shape-ledger.mjs';
9
10
  import { PLANS_REL, isScratchPlanName, plansInFlight, readPlanEntries } from './plan-files.mjs';
10
11
  import { readStoryLine } from './plan-shape-ownership.mjs';
11
- import { PLAN_HEADINGS, isSweep, parseLedger } from './plan-shape.mjs';
12
+ import { PLAN_HEADINGS, RETIRED_FORM_CODES, checkPlanStructure, isSweep, parseLedger, unique } from './plan-shape.mjs';
12
13
  import { expandSweepPaths } from './plan-shape-facts.mjs';
13
14
  import { withRepository } from './checkpoint-core.mjs';
14
15
  import { escapeForDisplay, isRenderableLine, shellQuoteArg } from './repo-lex.mjs';
@@ -24,7 +25,7 @@ const CR_END = /\r$/;
24
25
  const SPAN = /\{\{([\s\S]*?)\}\}/g;
25
26
  const PLAN_STEM = /^[A-Za-z0-9_-]+$/;
26
27
  const PLAN_TITLE = /^# Plan: (.+)$/;
27
- const DOCS_AI = 'docs/ai/';
28
+ const DOCS_AI = `${DOCS_TREE}/`;
28
29
  const PROMPT_PREFIX = `${PLANS_REL}/EXECUTE-PROMPT-`;
29
30
  const OID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
30
31
  const HEADER_CODES = new Set(['sibling-header', 'sibling-read']);
@@ -109,7 +110,19 @@ const readStore = (cwd) => {
109
110
  states: [...states, ...siblingStates.map((finding) => ({ finding }))] };
110
111
  };
111
112
 
112
- const planShape = (row, epicId) => `The shape: the title # Plan: and a name; the five headings; under Goal and boundary the line Story: ${row.id} of ${epicId} and a governing spec path under docs/ai/specs or the words not adopted; one ledger row per file in six fields (id, verb, path, responsibility, budget, anchor) — a create or modify row an anchor that resolves to one place and, with no declared source-size cap, the budget n/a, a delete row a dash (—) in budget and anchor; the total line last, its before figure the current lines of every deleted file and of every modify row with a numeric budget, so total: 0 → 0 lines when every row is a create or modify with the budget n/a; at least one - bullet under Verification.`;
113
+ const planShape = (row, epicId) => `The shape: the title # Plan: and a name; the five headings; under Goal and boundary the line Story: ${row.id} of ${epicId} and a governing spec path under docs/ai/specs or the words not adopted; one ledger row per file in five fields (id, verb, path, responsibility, anchor) and no total line; a create or modify row an anchor that resolves to one place, a delete row a dash (—) in its anchor; at least one - bullet under Verification.`;
114
+
115
+ const checkPlanPrerequisite = (text, parsed, rows, tools, path) => {
116
+ const retiredCodes = new Set(Object.values(RETIRED_FORM_CODES));
117
+ const retired = unique(checkPlanStructure(text, {}).findings.map(({ code }) => code).filter((code) => retiredCodes.has(code)));
118
+ if (rows.length > 0 && retired.length === 0) return null;
119
+ if (retired.length > 0) return state(READERS.ledger, path, `the Module ledger carries the old form: ${retired.join(', ')}`, tools.planCheck(path));
120
+ const ledger = parsed.document.headings.find(({ text }) => text === PLAN_HEADINGS[1]);
121
+ const verification = parsed.document.headings.find(({ text }) => text === PLAN_HEADINGS[2]);
122
+ const empty = ledger && verification && ledger.index < verification.index && parsed.entries.every(({ raw }) => !raw.trim());
123
+ const next = empty ? tools.planCheck(path, `add a ledger row to ${path}, then check the plan`) : tools.planCheck(path);
124
+ return state(READERS.ledger, path, 'the plan has no valid row in its Module ledger', next);
125
+ };
113
126
 
114
127
  // The Story line is read under Goal and boundary alone, as plan-shape reads it.
115
128
  const storyOf = ({ document }) => {
@@ -131,7 +144,7 @@ const readPlan = (cwd, tools, path) => {
131
144
  const rows = parsed.rows.filter((row) => row.valid);
132
145
  const ledger = rows.filter((row) => !row.path.startsWith(DOCS_AI)).map((row) => ({ ...row, prompt: `${PROMPT_PREFIX}${stem}-${row.id}${MARKDOWN}` }));
133
146
  const title = linesOf(read.text).map((line) => PLAN_TITLE.exec(line)?.[1]).find(Boolean) ?? null;
134
- return { path, story, hasRow: rows.length > 0, ledger, title, failure: null };
147
+ return { path, story, prerequisite: checkPlanPrerequisite(read.text, parsed, rows, tools, path), ledger, title, failure: null };
135
148
  } catch (error) {
136
149
  return refused(READERS.ledger, error.message);
137
150
  }
@@ -170,8 +183,8 @@ const judgeStory = (context, epicPath, epicId, row) => {
170
183
  return stateOf('S1', [tools.review(epicPath), action('write', `author the plan by hand at ${standIn}. ${planShape(row, epicId)}`)]);
171
184
  }
172
185
  const [plan] = own;
186
+ if (plan.prerequisite) return { state: plan.prerequisite };
173
187
  if (plan.shared) return {};
174
- if (!plan.hasRow) return { state: state(READERS.ledger, plan.path, 'the plan has no valid row in its Module ledger', tools.planCheck(plan.path, `add a ledger row to ${plan.path}, then check the plan`)) };
175
188
  const prompts = plan.ledger.map((ledgerRow) => ({ row: ledgerRow, ...readText(cwd, ledgerRow.prompt) }));
176
189
  const refused = prompts.find((prompt) => prompt.text === undefined && !prompt.absent);
177
190
  if (refused) return { state: state(READERS.prompt, refused.row.prompt, refused.cause) };
@@ -222,7 +235,7 @@ const readIndex = (context, held) => {
222
235
  };
223
236
 
224
237
  const leftoverActions = (context, plans) => {
225
- if (!context.index.ok || plans.some((plan) => plan.shared)) return [];
238
+ if (!context.index.ok || plans.some((plan) => plan.shared || plan.prerequisite)) return [];
226
239
  const removals = plans.map((plan) => {
227
240
  const prompts = plan.ledger.map((row) => row.prompt).filter((prompt) => isPresent(context.cwd, prompt));
228
241
  return action('write', `remove the plan ${plan.path} and its prompts (${prompts.length ? prompts.join(', ') : 'none on disk'}): the Cleanup of a landed story`);
@@ -251,12 +264,13 @@ const judgeEntry = (context, judged) => {
251
264
  if (!judged.accepted) return { entry: base, states: [] };
252
265
  const accepted = { ...base, residual: findSpans(path, judged.entry.text) };
253
266
  const leftover = judged.leftover.length ? leftoverActions(context, judged.leftover) : null;
254
- if (epic.fields.state === LANDED) return { entry: { ...accepted, stage: 'E5', actions: leftover ?? [] }, states: [] };
267
+ const states = judged.leftover.map((plan) => plan.prerequisite).filter(Boolean);
268
+ if (epic.fields.state === LANDED) return { entry: { ...accepted, stage: 'E5', actions: leftover ?? [] }, states };
255
269
  const landed = new Set(epic.rows.filter((row) => row.state === LANDED).map((row) => row.id));
256
270
  const inHand = epic.rows.filter((row) => row.state !== LANDED && row.dependsOn.every((dependency) => landed.has(dependency)));
257
- if (inHand.length === 0) return { entry: { ...accepted, stage: 'E4', actions: leftover ?? (context.index === null ? closeActions(context, judged) : []) }, states: [] };
271
+ if (inHand.length === 0) return { entry: { ...accepted, stage: 'E4', actions: leftover ?? (context.index === null ? closeActions(context, judged) : []) }, states };
258
272
  const held = { ...accepted, stage: 'E3', fact: tools.epicCheck(path, 'fact'), actions: leftover ?? [] };
259
- if (context.index !== null) return { entry: held, states: [] };
273
+ if (context.index !== null) return { entry: held, states };
260
274
  const stories = inHand.map((row) => judgeStory(context, path, id, row));
261
275
  return { entry: { ...held, stories: stories.filter((story) => story.story).map((story) => story.story) },
262
276
  states: stories.filter((story) => story.state).map((story) => story.state) };
@@ -6,8 +6,9 @@
6
6
  // never asks; every read and write goes through deps.
7
7
  import { linkSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
8
8
  import { resolve } from 'node:path';
9
+ import { EPIC_STORE, EPIC_STORE_SEED, ORCHESTRATION, PLANS, PROFILE_DECLINES, QUEUE } from '../references/scripts/shared/index.mjs';
9
10
  import { assertDocsAiDeployment, writeDocsAiFileAtomic, writeProjectFileCreateOnly } from './atomic-write.mjs';
10
- import { safeLine } from './carriers.mjs';
11
+ import { safeLine, slotRole } from './carriers.mjs';
11
12
  import { isDirectRun } from './direct-run.mjs';
12
13
  import { tmpNote } from './ensure-ops.mjs';
13
14
  import { CANON_README, applySetOps, refreshReadme } from './orchestration-config.mjs';
@@ -28,14 +29,8 @@ const HELP_FLAGS = new Set(['--help', '-h']);
28
29
  const MODE_FLAGS = new Set([APPLY_FLAG, DECLINE_FLAG]);
29
30
  const SLOTS_ID = 'epic-task-slots';
30
31
  const STORE_ID = 'epic-store-seeded';
31
- const STORE_DIR = 'docs/ai/epics';
32
- const STORE_SEED = 'docs/ai/epics/.gitkeep';
33
32
  const QUEUE_ID = 'named-queue-row-seed';
34
- const PLANS_DIR = 'docs/plans';
35
- const QUEUE_SEED = 'docs/plans/queue.md';
36
33
  const MISSING_CODE = 'ENOENT';
37
- const CONFIG_WRITTEN = 'docs/ai/orchestration.json';
38
- const DECLINES_REL = 'docs/ai/profile-declines.json';
39
34
  const SCHEMA = 1;
40
35
  const INDENT = ' ';
41
36
  const WORDS = Object.freeze({
@@ -100,10 +95,11 @@ const withFs = (deps) => ({
100
95
  // The resolution walk: the first candidate planRecipe reports not degraded wins; every candidate
101
96
  // before it carries that plan's own first degrade reason.
102
97
  // solo, every target's last candidate, is always satisfiable, so the find always answers.
103
- const resolveTarget = ({ candidates }, readiness) => {
98
+ const resolveTarget = ({ activity, slot, candidates }, readiness) => {
104
99
  const skipped = [];
100
+ const role = slotRole(activity, slot);
105
101
  const value = candidates.find((candidate) => {
106
- const plan = planRecipe(candidate, readiness);
102
+ const plan = planRecipe(candidate, readiness, role);
107
103
  if (plan.degraded) skipped.push({ candidate, reason: plan.degradation[0].reason });
108
104
  return !plan.degraded;
109
105
  });
@@ -160,11 +156,11 @@ const missingAt = (root, rel, deps) => {
160
156
  };
161
157
 
162
158
  const writeQueueSeed = (root, deps, bytes, made) => {
163
- const plansMissing = missingAt(root, PLANS_DIR, deps);
159
+ const plansMissing = missingAt(root, PLANS, deps);
164
160
  try {
165
- return { seeded: writeProjectFileCreateOnly(root, QUEUE_SEED, bytes, deps, { noun: 'the queue seed' }) };
161
+ return { seeded: writeProjectFileCreateOnly(root, QUEUE, bytes, deps, { noun: 'the queue seed' }) };
166
162
  } catch (error) {
167
- if (plansMissing && directoryAt(root, PLANS_DIR, deps)) made.push(`${PLANS_DIR} created`);
163
+ if (plansMissing && directoryAt(root, PLANS, deps)) made.push(`${PLANS} created`);
168
164
  return { refusal: refuse('write-failed', [...made, causeOf(error)].join('; ')) };
169
165
  }
170
166
  };
@@ -181,21 +177,21 @@ const runApply = (root, deps, judged, slots, config) => {
181
177
  } catch (error) {
182
178
  return { refusal: refuse('write-failed', causeOf(error)) };
183
179
  }
184
- made.push(`${CONFIG_WRITTEN} written`);
180
+ made.push(`${ORCHESTRATION} written`);
185
181
  byId.set(SLOTS_ID, { ...byId.get(SLOTS_ID), word: WORDS.applied });
186
182
  }
187
183
  if (byId.get(STORE_ID)?.word === GAP_STATES.offered) {
188
184
  let seeded;
189
185
  try {
190
- seeded = writeProjectFileCreateOnly(root, STORE_SEED, '', deps, { noun: 'the epic store seed' });
186
+ seeded = writeProjectFileCreateOnly(root, EPIC_STORE_SEED, '', deps, { noun: 'the epic store seed' });
191
187
  } catch (error) {
192
- if (directoryAt(root, STORE_DIR, deps)) made.push(`${STORE_DIR} created`);
188
+ if (directoryAt(root, EPIC_STORE, deps)) made.push(`${EPIC_STORE} created`);
193
189
  return { refusal: refuse('write-failed', [...made, causeOf(error)].join('; ')) };
194
190
  }
195
191
  byId.set(STORE_ID, { ...byId.get(STORE_ID), word: seeded.created ? WORDS.applied : GAP_STATES.present });
196
- if (seeded.created) made.push(`${STORE_SEED} created`);
192
+ if (seeded.created) made.push(`${EPIC_STORE_SEED} created`);
197
193
  if (seeded.tmpLeftBehind) {
198
- extra.push(OUTCOME_LINES.tmpLeft(STORE_SEED, seeded.tmpLeftBehind));
194
+ extra.push(OUTCOME_LINES.tmpLeft(EPIC_STORE_SEED, seeded.tmpLeftBehind));
199
195
  made.push(`${seeded.tmpLeftBehind} left behind`);
200
196
  }
201
197
  }
@@ -203,7 +199,7 @@ const runApply = (root, deps, judged, slots, config) => {
203
199
  const written = writeQueueSeed(root, deps, seed.bytes, made);
204
200
  if (written.refusal) return written;
205
201
  byId.set(QUEUE_ID, { ...byId.get(QUEUE_ID), word: written.seeded.created ? WORDS.applied : GAP_STATES.present });
206
- if (written.seeded.tmpLeftBehind) extra.push(OUTCOME_LINES.tmpLeft(QUEUE_SEED, written.seeded.tmpLeftBehind));
202
+ if (written.seeded.tmpLeftBehind) extra.push(OUTCOME_LINES.tmpLeft(QUEUE, written.seeded.tmpLeftBehind));
207
203
  }
208
204
  return { judged: judged.map((item) => byId.get(item.entry.id)), extra };
209
205
  };
@@ -219,7 +215,7 @@ const runDecline = (root, deps, judged, profile, declined) => {
219
215
  const merged = { ...(declined ?? {}) };
220
216
  for (const { entry } of offered) merged[entry.id] = profile.lineage;
221
217
  try {
222
- writeDocsAiFileAtomic(root, DECLINES_REL, serializeDeclines(merged), deps, { noun: 'the decline record' });
218
+ writeDocsAiFileAtomic(root, PROFILE_DECLINES, serializeDeclines(merged), deps, { noun: 'the decline record' });
223
219
  } catch (error) {
224
220
  return { refusal: refuse('write-failed', causeOf(error)) };
225
221
  }
@@ -6,17 +6,17 @@
6
6
  // Contract: docs/ai/specs/kit/transition/.
7
7
 
8
8
  import { join, resolve } from 'node:path';
9
- import { tokenizeMarkdown } from '../../references/scripts/shared/index.mjs';
9
+ import { AGENTS_FILE, AGENT_RULES, RULES_EFFECTIVE, tokenizeMarkdown } from '../../references/scripts/shared/index.mjs';
10
10
  import { writeContainedFileAtomic } from '../atomic-write.mjs';
11
11
  import { isDirectRun } from '../direct-run.mjs';
12
12
  import { probeRegularFileNoFollow, readRegularFileNoFollow } from '../fs-read-nofollow.mjs';
13
13
  import { findKitBlock, SKIP_PREFIX } from '../inject-methodology.mjs';
14
+ import { themePaths } from '../project-rules/index.mjs';
15
+ import { escapeRegExp } from '../repo-lex.mjs';
14
16
 
15
17
  const LF = '\n';
16
18
  const BOM = '';
17
- const AGENTS_REL = 'AGENTS.md';
18
- const RULES_REL = 'docs/ai/agent_rules.md';
19
- const LENS_REL = 'docs/ai/rules/lens.md';
19
+ const LENS_REL = themePaths('lens').kit;
20
20
  const USAGE = 'usage: transition/index.mjs --cwd <project>';
21
21
  const UPGRADE_AGAIN = 'run the upgrade again: its step 3 writes the kit block or names its malformed lines';
22
22
  const ENGINE_REFRESH = 'run npx @sabaiway/agent-workflow-engine@latest init, then run the upgrade again';
@@ -25,7 +25,8 @@ const ENGINE_REFRESH = 'run npx @sabaiway/agent-workflow-engine@latest init, the
25
25
  // theme and the line-cap footer in AGENTS.md; the title words of three sections in the rules file.
26
26
  const POINTERS = ['methodology', 'orchestration', 'autonomy'];
27
27
  const MARKER_RE = new RegExp(`^<!-- workflow:(${POINTERS.join('|')}):(start|end) -->$`, 'u');
28
- const THEME_ROW_RE = /^\| \[`docs\/ai\/rules\/effective\/([^`/\s]+)\.md`\]\(\.\/docs\/ai\/rules\/effective\/\1\.md\) \|/u;
28
+ const EFFECTIVE_RULES_PATTERN = escapeRegExp(RULES_EFFECTIVE);
29
+ const THEME_ROW_RE = new RegExp(`^\\| \\[\`${EFFECTIVE_RULES_PATTERN}\\/([^\`/\\s]+)\\.md\`\\]\\(\\.\\/${EFFECTIVE_RULES_PATTERN}\\/\\1\\.md\\) \\|`, 'u');
29
30
  const FOOTER = '**Rule:** This file stays CONCISE (≤100 lines). Details go to `docs/ai/`. Never bloat this file.';
30
31
  const TITLES = ['Communication (user-facing messages)', 'Story sessions', 'Planning, review & process-fidelity'];
31
32
  const HEADING_RE = /^ {0,3}#{1,6}[ \t]+(.*)$/u;
@@ -178,14 +179,14 @@ export const main = async (argv, deps = {}) => {
178
179
  }
179
180
  const cwd = resolve(argv[1]);
180
181
  try {
181
- const agentsFile = readProjectFile(cwd, AGENTS_REL, deps);
182
- const rulesFile = readProjectFile(cwd, RULES_REL, deps);
182
+ const agentsFile = readProjectFile(cwd, AGENTS_FILE, deps);
183
+ const rulesFile = readProjectFile(cwd, AGENT_RULES, deps);
183
184
  const agents = agentsFile && parse(agentsFile);
184
185
  const rules = rulesFile && parse(rulesFile);
185
186
  const block = firstStep(agents, cwd, deps);
186
187
  const judged = [
187
- { rel: AGENTS_REL, doc: agents, spans: keepParseable(agents, agentsSpans(agents, block)) },
188
- { rel: RULES_REL, doc: rules, spans: rules === null ? [] : keepParseable(rules, rulesSpans(rules)) },
188
+ { rel: AGENTS_FILE, doc: agents, spans: keepParseable(agents, agentsSpans(agents, block)) },
189
+ { rel: AGENT_RULES, doc: rules, spans: rules === null ? [] : keepParseable(rules, rulesSpans(rules)) },
189
190
  ];
190
191
  const written = [];
191
192
  for (const { rel, doc, spans } of judged) {