@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
@@ -1,29 +1,8 @@
1
- // spec-check.mjs — the structural checker of the feature-spec layer (spec layer 2b), ADVISORY.
2
- //
3
- // It answers ONE question per document: given what the session says it changed, does the store on
4
- // disk say the same thing? The change source is EXPLICIT (parsed ops, never git), and "well-formed"
5
- // has no second definition here — every per-document verdict is RELAYED from the ONE reader
6
- // (references/scripts/spec-schema/index.mjs) and its 2a `structure` extraction. This module adds only what
7
- // text alone cannot decide: does the post-state on disk match the declared op, is the document
8
- // listed by its parent, does its scenario marker really occur once in the file it names, and — under
9
- // --all — the five invariants that span documents.
10
- //
11
- // Two lanes:
12
- // session the closure of the declared ops (targets + their listing parents), judged per document.
13
- // --all every document under the store, plus: unlisted child (DISTINCT from orphan),
14
- // acyclicity, store-wide slug uniqueness, module overlap. An ABSENT store root refuses.
15
- //
16
- // FAIL-CLOSED before every read. Containment is judged lexically AND by realpath over each
17
- // path-bearing field, and the parents of a leaf are judged BEFORE the leaf is opened. The LEAF read
18
- // itself is descriptor-bound and no-follow (the CLI half passes fs-read-nofollow.mjs in), so a
19
- // pathname swapped after the probe cannot change the bytes judged. A mid-run PARENT swap is a
20
- // STATED non-goal: this is an advisory checker, not a custody mechanism.
21
- //
22
- // No IO of its own: { read, probe, realpath, list } are injected. Dependency-free, Node >= 22.
1
+ // spec-check.mjs — see docs/ai/specs/kit/spec-layer/spec-check.md.
23
2
 
24
- import { dirname as pathDirname, isAbsolute, relative, sep } from 'node:path';
3
+ import { dirname as pathDirname, isAbsolute, join, relative, sep } from 'node:path';
25
4
  import { SPEC_SCHEMA, readSpecDocument, classifyPath } from '../references/scripts/spec-schema/index.mjs';
26
- import { SPEC_OPS_GRAMMAR, buildClosure, listingParentOf, slugOf } from './spec-check-ops.mjs';
5
+ import { SPEC_OPS_GRAMMAR, buildClosure, listingParentOf, slugOf, parsePendingModulePath, selectPendingModulePlans, hasPendingModuleCover } from './spec-check-ops.mjs';
27
6
 
28
7
  const STORE = SPEC_OPS_GRAMMAR.storePrefix;
29
8
  const NAV = SPEC_OPS_GRAMMAR.navigator;
@@ -35,11 +14,9 @@ const STORE_DIR = STORE.slice(0, -1);
35
14
  // as a regular file, so a state that has changed underneath since is a fact to state, never a
36
15
  // document to drop quietly from a store the run would otherwise call clean.
37
16
  const DECLARED_STATE = Object.freeze({ add: 'file', modify: 'file', 'rename-to': 'file', remove: 'absent', 'rename-from': 'absent', present: 'file' });
38
- const missing = () => {
39
- throw new Error('spec-check: an IO dependency was not injected — this module owns no filesystem of its own');
40
- };
17
+ const missing = () => { throw new Error('spec-check: an IO dependency was not injected — this module owns no filesystem of its own'); };
41
18
 
42
- const dirOf = (rel) => rel.slice(0, rel.lastIndexOf('/'));
19
+ const dirOf = (rel) => rel.slice(0, Math.max(rel.lastIndexOf('/'), 0));
43
20
  const leafOf = (rel) => rel.slice(rel.lastIndexOf('/') + 1);
44
21
  const bare = (rel) => (rel.endsWith('/') ? rel.slice(0, -1) : rel);
45
22
  const lineCount = (text) => text.replace(/\n$/, '').split('\n').length;
@@ -156,15 +133,25 @@ const judgeEdges = (doc, ctx) => {
156
133
  }
157
134
  };
158
135
 
136
+ const canonicalGround = (path, ctx, ancestor = false, state = ctx.io.probe(ctx.at(path))) => {
137
+ const { io, at, rootReal } = ctx;
138
+ const absent = state === 'absent' && path !== '';
139
+ const real = absent ? canonicalGround(dirOf(path), ctx, true) : io.realpath(at(path));
140
+ if (real === null || !contained(rootReal, real)) return null;
141
+ if (absent) return join(real, leafOf(path));
142
+ const kind = state === 'symlink' ? io.probe(real) : state;
143
+ return kind === 'dir' || (!ancestor && kind === 'file') ? real : null;
144
+ };
145
+
159
146
  // The per-document judgement, identical in both lanes: the relayed reader rules, the kind's own
160
147
  // line cap, the listed edges, the D4 scenario bindings and the containment of every path it names.
161
- const judgeDocument = (doc, ctx) => {
148
+ const judgeDocument = (doc, ctx, groundOnly = false) => {
162
149
  const { io, at, rootReal, add } = ctx;
163
150
  const { path, verdict } = doc;
164
151
  if (verdict === null) return;
165
- for (const error of verdict.errors) add('reader', path, `${error.rule}: ${error.message}`, { readerRule: error.rule });
152
+ for (const error of verdict.errors) if (!groundOnly || verdict.structure === null || error.rule.startsWith('module-')) add('reader', path, `${error.rule}: ${error.message}`, { readerRule: error.rule });
166
153
  const cap = SPEC_SCHEMA.maxLines[verdict.kind];
167
- if (cap !== undefined && doc.lines > cap) {
154
+ if (!groundOnly && cap !== undefined && doc.lines > cap) {
168
155
  add('threshold', path, `${doc.lines} lines over the ${verdict.kind} cap of ${cap} — promote it to <slug>/index.md + parts`);
169
156
  }
170
157
  const structure = verdict.structure;
@@ -176,21 +163,28 @@ const judgeDocument = (doc, ctx) => {
176
163
  const wantDir = claimed.endsWith('/');
177
164
  const target = bare(claimed);
178
165
  const real = io.realpath(at(target));
179
- if (real === null) {
180
- add('module', path, `the module path ${claimed} names ground that is not there`);
181
- continue;
182
- }
183
- if (!contained(rootReal, real)) {
166
+ if (real !== null && !contained(rootReal, real)) {
184
167
  add('contained', path, `the module path ${claimed} resolves outside the root (${real})`);
185
168
  continue;
186
169
  }
187
170
  const state = io.probe(at(target));
171
+ if (real === null || state === 'absent') {
172
+ const canonical = state === 'absent' && parsePendingModulePath(claimed) && canonicalGround(target, ctx, false, state);
173
+ const { plan, refusedPlans } = selectPendingModulePlans(canonical ? ctx.plans : [], { path, status: verdict.status, home: ctx.home });
174
+ const covers = ({ creates }) => canonical && hasPendingModuleCover(canonical, wantDir ? 'dir' : 'file', creates
175
+ .filter((path) => classifyPath(path) === 'file' && parsePendingModulePath(path)).map((path) => canonicalGround(path, ctx)).filter(Boolean));
176
+ if (plan && covers(plan)) doc.ground.push(canonical);
177
+ else add('module', path, [`the module path ${claimed} names ground that is not there`,
178
+ ...refusedPlans.filter(covers).map(({ identity }) => `structurally refused plan: ${identity}`)].join('; '));
179
+ continue;
180
+ }
188
181
  if (state !== (wantDir ? 'dir' : 'file')) {
189
182
  add('module', path, `the module path ${claimed} is "${state}", not the ${wantDir ? 'directory' : 'file'} it declares`);
190
183
  continue;
191
184
  }
192
185
  doc.ground.push(real);
193
186
  }
187
+ if (groundOnly) return;
194
188
  judgeEdges(doc, ctx);
195
189
  for (const scenario of structure.scenarios) {
196
190
  if (scenario.binding === null) continue;
@@ -226,19 +220,22 @@ const judgeDocument = (doc, ctx) => {
226
220
  // The listing judgement — a SESSION-lane rule: the document the ops touched must be listed by its
227
221
  // parent exactly once after an add/modify/rename-to, and not at all after a remove/rename-from.
228
222
  // Under --all the reachability invariants below own this ground instead, so it never doubles up.
229
- const judgeListing = (doc, docs, add) => {
223
+ const judgeListing = (doc, docs, add, home) => {
230
224
  const declared = doc.roles.map((role) => DECLARED_STATE[role]).find(Boolean);
231
225
  if (!declared) return;
232
226
  const parent = listingParentOf(doc.path);
233
227
  if (parent === null) return;
234
228
  const holder = docs.get(parent);
229
+ const revised = home?.paths.includes(parent) && holder?.verdict?.kind === 'spec' && dirOf(parent) === dirOf(doc.path);
230
+ if (doc.roles.includes('present') && !revised) return;
235
231
  const link = expectedLink(doc.path, parent);
232
+ if (declared === 'absent' && holder?.roles.includes('remove') && holder.state === 'absent') return;
236
233
  if (!holder || holder.state !== 'file' || holder.verdict === null) {
237
234
  add('listed', doc.path, `its listing parent ${parent} cannot be read, so nothing states whether ${link} is listed`);
238
235
  return;
239
236
  }
240
237
  const found = linkTargetsOf(holder).filter((target) => target === link).length;
241
- if (declared === 'file' && found !== 1) add('listed', doc.path, `${parent} lists ${link} ${found} time(s) — a present document is listed exactly once`);
238
+ if (declared === 'file' && found !== 1) add(revised && found === 0 ? 'unlisted-child' : 'listed', doc.path, `${parent} lists ${link} ${found} time(s) — a present document is listed exactly once`);
242
239
  if (declared === 'absent' && found !== 0) add('listed', doc.path, `${parent} still lists ${link} — a removed document is listed by nobody`);
243
240
  };
244
241
 
@@ -327,6 +324,9 @@ const judgeStore = (docs, ctx) => {
327
324
  for (const [slug, paths] of bySlug) {
328
325
  if (paths.length > 1) for (const rel of paths) add('slug-unique', rel, `the slug "${slug}" is claimed by ${paths.length} documents (${paths.join(', ')}) — a slug is store-wide`);
329
326
  }
327
+ };
328
+
329
+ const judgeOverlap = (docs, add, targets) => {
330
330
  // PROVEN canonical ground only (judgeDocument) — a path that never resolved is not compared as if
331
331
  // it had. Nesting is asked with the platform's own path model — `dirname` walked upward, never a
332
332
  // hand-rolled separator rule — and it is asked ONCE PER PATH rather than once per pair: the store
@@ -346,7 +346,7 @@ const judgeStore = (docs, ctx) => {
346
346
  // Any separator those paths might themselves contain makes the key non-injective, and the pair
347
347
  // that collides would be dropped in silence.
348
348
  const note = (one, other, claimed) => {
349
- if (one === other) return;
349
+ if (one === other || (targets && !targets.has(one) && !targets.has(other))) return;
350
350
  const [a, b] = [one, other].sort();
351
351
  const key = JSON.stringify([a, b]);
352
352
  if (!pairs.has(key)) pairs.set(key, { a, b, claimed });
@@ -364,17 +364,19 @@ const judgeStore = (docs, ctx) => {
364
364
  }
365
365
  };
366
366
 
367
- // checkSpecs({ root, ops, all }, deps) -> { verdict, exit, findings, documents, lines }.
367
+ // checkSpecs({ root, ops, all, plans, home }, deps) -> { verdict, exit, findings, documents, lines }.
368
368
  // Exit 0 ACCEPT · 1 one or more findings · 2 a refusal about the RUN itself (an unresolvable root,
369
369
  // an absent store root under --all) — the CLI prints the lines and returns the code.
370
- export const checkSpecs = ({ root, ops = [], all = false } = {}, deps = {}) => {
370
+ export const checkSpecs = ({ root, ops = [], all = false, plans, home } = {}, deps = {}) => {
371
371
  const io = { read: missing, probe: missing, realpath: missing, list: missing, ...deps };
372
372
  const at = (rel) => (rel === '' ? root : `${root}/${rel}`);
373
373
  const rootReal = io.realpath(root);
374
374
  if (rootReal === null) return refusal(`--root "${root}" does not resolve to a directory — nothing can be judged against it`);
375
375
  const findings = [];
376
376
  const add = (rule, path, message, extra = {}) => findings.push({ rule, path, message, ...extra });
377
- const ctx = { io, at, rootReal, add };
377
+ const planCache = {};
378
+ const filterPlans = (predicate) => (planCache.plans ??= plans()).filter(predicate);
379
+ const ctx = { io, at, rootReal, add, plans: typeof plans === 'function' ? { filter: filterPlans } : plans, home: all ? undefined : home };
378
380
  if (all && io.probe(at(STORE_ROOT)) !== 'file') {
379
381
  return refusal(`the store root ${STORE_ROOT} is not a regular file — an --all run over no store would report an empty clean store, so it refuses instead`);
380
382
  }
@@ -383,9 +385,16 @@ export const checkSpecs = ({ root, ops = [], all = false } = {}, deps = {}) => {
383
385
  // the empty-closure usage error would throw away the only thing the run learned, so the usage
384
386
  // refusal is the SESSION lane's alone.
385
387
  if (closure.length === 0 && findings.length === 0) return refusal('no document to judge — the op closure is empty');
386
- const docs = readClosure(closure, ctx);
387
- for (const doc of docs.values()) judgeDocument(doc, ctx);
388
+ const targets = new Set(closure.map(({ path }) => path));
389
+ const removed = new Set(ctx.home ? ops.filter(({ verb }) => verb === 'remove').map(({ target }) => at(target)) : []);
390
+ const storePaths = ctx.home ? [...new Set([...walkStore(ctx), ...ctx.home.paths])] : [];
391
+ const entries = closure.concat(storePaths.filter((path) => !targets.has(path)).map((path) => ({ path, roles: ['present'] })));
392
+ if (removed.size > 0) ctx.io = { ...io, probe: (path, state = io.probe(path)) => removed.has(path) && state === 'file' ? 'absent' : state };
393
+ const docs = readClosure(entries, ctx);
394
+ for (const doc of docs.values()) judgeDocument(doc, ctx, !targets.has(doc.path));
388
395
  if (all) judgeStore(docs, ctx);
389
- else for (const doc of docs.values()) judgeListing(doc, docs, add);
396
+ else for (const doc of docs.values()) judgeListing(doc, docs, add, ctx.home);
397
+ if (all || (ctx.home && !findings.some(({ rule }) => rule === 'census') &&
398
+ entries.every(({ path, roles }) => roles.includes('remove') || docs.get(path)?.verdict?.structure))) judgeOverlap(docs, add, all ? undefined : targets);
390
399
  return verdictOf(findings, closure.length, all ? 'the whole store' : `${ops.length} op(s)`);
391
400
  };
@@ -7,11 +7,12 @@
7
7
 
8
8
  import { readFileSync, readdirSync, writeFileSync } from 'node:fs';
9
9
  import { join, relative, sep } from 'node:path';
10
+ import { SPEC_COVERAGE, SPEC_STORE } from '../references/scripts/shared/index.mjs';
10
11
  import { isDirectRun } from './direct-run.mjs';
11
12
  import { claimsOf, formatFindings, judgeCoverage, settleAfter } from './spec-coverage.mjs';
12
13
 
13
- export const SCOPE_PATH = join('docs', 'ai', 'spec-coverage.json');
14
- export const STORE_ROOT = join('docs', 'ai', 'specs');
14
+ export const SCOPE_PATH = join(SPEC_COVERAGE);
15
+ export const STORE_ROOT = join(SPEC_STORE);
15
16
  const REASON_MAX_BYTES = 300;
16
17
 
17
18
  const HELP = `spec-coverage — every shipped tool is governed by a contract, or the debt names it.
@@ -0,0 +1,231 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { homedir } from 'node:os';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { writeContainedFileAtomic } from '../atomic-write.mjs';
7
+ import { isDirectRun } from '../direct-run.mjs';
8
+ import { PROCEDURES_FRAGMENT_REL, readEngineFragment, resolveEngineDir } from '../engine-source.mjs';
9
+ import { readRegularFileNoFollow } from '../fs-read-nofollow.mjs';
10
+ import { resolveGitLocation, stripGitLocationEnv } from '../git-env.mjs';
11
+ import { OUTCOME_LINES as APPROVAL_LINES, getLocalDate, readApproval } from '../plan-approval/index.mjs';
12
+ import { escapeForDisplay, isRenderableLine, isSeedablePathToken, shellQuoteArg } from '../repo-lex.mjs';
13
+ import {
14
+ RECORD_GATED_STAGES, STAGES_REL, STAGE_RECORD_BASENAME, composeDispatchPart, composeRenderCommand, composeRenderLine,
15
+ composeSlotText, composeStageRecord, composeStartPrompt, loadStages, renderStage, validateSlots,
16
+ } from './index.mjs';
17
+
18
+ const CLI_PATH = fileURLToPath(import.meta.url);
19
+ const CLI_TOKEN = isSeedablePathToken(CLI_PATH) ? CLI_PATH : shellQuoteArg(CLI_PATH);
20
+ const STAGES_PATH = resolve(dirname(CLI_PATH), '../..', STAGES_REL);
21
+ const WRITE = '--write';
22
+ const DISPATCH = '--dispatch';
23
+ const STAGE_FLAG = '--stage';
24
+ const DECISIONS_FLAG = '--decisions';
25
+ const DECISION_SEPARATOR = '#';
26
+ const VALUE_FLAGS = Object.freeze(['plan', 'queue-row']);
27
+ const WAITING_STAGE = 'waiting-on-approval';
28
+ const UPGRADE = 'upgrade the kit and its engine (/agent-workflow-kit upgrade)';
29
+ const START_HEADER = 'the start prompt, shown to the user unchanged:';
30
+ const WRITES_AUTHORING = 'authoring';
31
+ const WRITES_ANY = 'any';
32
+ const LOCATED = 'work-tree';
33
+ const NO_REPOSITORY = 'not-a-repository';
34
+ const EXIT_OK = 0;
35
+ const EXIT_REFUSE = 1;
36
+ const EXIT_USAGE = 2;
37
+ const LINE_ENDING = '\n';
38
+ const display = escapeForDisplay;
39
+
40
+ export const OUTCOME_LINES = Object.freeze({
41
+ usage: (reason) => `Usage: node ${display(CLI_TOKEN)} <slot file> | ${WRITE} <slot file> ${STAGE_FLAG} <id> [--plan <path>] [--queue-row <id>] [${DECISIONS_FLAG} <path>#<heading>]... | ${DISPATCH} <plan> — ${display(reason)}`,
42
+ cannotRender: (subject, reason) => `stage-render: CANNOT RENDER — ${display(subject)}: ${display(reason)}; ${UPGRADE}`,
43
+ refused: (subject, reason) => `stage-render: REFUSE — ${display(subject)}: ${display(reason)}`,
44
+ unapproved: (stage, plan, reason) => `stage-render: REFUSE — ${display(stage)} for ${display(plan)} waits for its approval record, so the stage is ${WAITING_STAGE}; ${APPROVAL_LINES.refused(plan, reason)}`,
45
+ finding: (plan, finding) => APPROVAL_LINES.finding(plan, finding),
46
+ malformed: (recordPath, line) => APPROVAL_LINES.malformed(recordPath, line),
47
+ unlocated: (reason) => `stage-render: ERROR — cannot locate the git directory of ${STAGE_RECORD_BASENAME}: ${display(reason)}`,
48
+ recordFailed: (recordPath, reason) => `stage-render: ERROR — cannot record the stage at ${display(recordPath)}: ${display(reason)}`,
49
+ writeFailed: (slotFile, reason) => `stage-render: ERROR — cannot write ${display(slotFile)}: ${display(reason)}`,
50
+ written: (slotFile) => `stage-render: WRITTEN — ${display(slotFile)}; its render line and the command that runs it here:`,
51
+ startHeader: () => START_HEADER,
52
+ text: (line) => display(line),
53
+ });
54
+
55
+ const halt = (exitCode, lines) => Object.assign(new Error(lines[0]), { exitCode, lines });
56
+ const isOperand = (value) => typeof value === 'string' && value !== '' && !value.startsWith('-');
57
+
58
+ const parseWriteFlags = (pairs) => pairs.reduce((flags, value, index) => {
59
+ if (flags === null || index % 2 === 1) return flags;
60
+ const flag = value;
61
+ const operand = pairs[index + 1];
62
+ const kind = flag.startsWith('--') ? flag.slice(2) : null;
63
+ if (flag === DECISIONS_FLAG && operand.includes(DECISION_SEPARATOR)) {
64
+ const cut = operand.indexOf(DECISION_SEPARATOR);
65
+ return { ...flags, decisions: [...flags.decisions, { path: operand.slice(0, cut), heading: operand.slice(cut + 1) }] };
66
+ }
67
+ if (flag === STAGE_FLAG && flags.stage === undefined && isOperand(operand)) return { ...flags, stage: operand };
68
+ if (VALUE_FLAGS.includes(kind) && !Object.hasOwn(flags.values, kind) && operand !== '') {
69
+ return { ...flags, values: { ...flags.values, [kind]: operand } };
70
+ }
71
+ return null;
72
+ }, { values: {}, decisions: [] });
73
+
74
+ const parseArgs = (argv) => {
75
+ const broken = argv.find((value) => !isRenderableLine(value));
76
+ if (broken !== undefined) return { usage: `${broken} carries a control byte` };
77
+ const [first, second, ...rest] = argv;
78
+ if (first === DISPATCH) return argv.length === 2 && isOperand(second) ? { command: DISPATCH, plan: second } : { usage: `${DISPATCH} takes one plan` };
79
+ if (first === WRITE) {
80
+ const flags = isOperand(second) && rest.length % 2 === 0 ? parseWriteFlags(rest) : null;
81
+ return flags?.stage === undefined ? { usage: `${WRITE} takes one slot file, ${STAGE_FLAG} once and known flags` } : { command: WRITE, slotFile: second, ...flags };
82
+ }
83
+ return argv.length === 1 && isOperand(first) ? { command: 'render', slotFile: first } : { usage: 'one slot file, --write or --dispatch' };
84
+ };
85
+
86
+ const locateGitDir = ({ cwd, env }) => {
87
+ const location = resolveGitLocation(cwd, { env: stripGitLocationEnv(env) });
88
+ if (location.state === NO_REPOSITORY) return null;
89
+ if (location.state !== LOCATED) throw halt(EXIT_USAGE, [OUTCOME_LINES.unlocated(location.cause)]);
90
+ return location;
91
+ };
92
+
93
+ const isMainTree = (location) => location === null || location.gitDir === location.commonDir;
94
+
95
+ const recordStage = (location, slotFile, stage, writes) => {
96
+ if (location === null) return;
97
+ const recordPath = join(location.gitDir, STAGE_RECORD_BASENAME);
98
+ try {
99
+ writeContainedFileAtomic(location.gitDir, recordPath, composeStageRecord({ stage, slotFile, writes }), {}, { label: recordPath });
100
+ } catch (error) {
101
+ throw halt(EXIT_USAGE, [OUTCOME_LINES.recordFailed(recordPath, error.message)]);
102
+ }
103
+ };
104
+
105
+ const loadTable = ({ stagesPath }) => {
106
+ const read = readRegularFileNoFollow(stagesPath);
107
+ if (read.outcome !== 'ok' || read.closeFailure) {
108
+ throw halt(EXIT_USAGE, [OUTCOME_LINES.cannotRender(STAGES_REL, `cannot read ${stagesPath} (${read.closeFailure ?? read.code ?? read.outcome})`)]);
109
+ }
110
+ try {
111
+ return loadStages(read.content);
112
+ } catch (error) {
113
+ throw halt(EXIT_USAGE, [OUTCOME_LINES.cannotRender(STAGES_REL, error.message)]);
114
+ }
115
+ };
116
+
117
+ const requireApproval = ({ cwd, env, stderr }, plan, stage) => {
118
+ const approval = readApproval({ cwd, env, plan });
119
+ const malformed = (approval.malformedLines ?? []).map((line) => OUTCOME_LINES.malformed(approval.recordPath, line));
120
+ if (approval.exitCode === EXIT_OK) {
121
+ malformed.forEach(stderr);
122
+ return approval;
123
+ }
124
+ const findings = (approval.verdict?.result.findings ?? []).map((finding) => OUTCOME_LINES.finding(plan, finding));
125
+ throw halt(EXIT_REFUSE, [OUTCOME_LINES.unapproved(stage, plan, approval.reason), ...malformed, ...findings]);
126
+ };
127
+
128
+ const readCanon = (env) => {
129
+ try {
130
+ const { dir, source } = resolveEngineDir({ env, home: homedir() });
131
+ return readEngineFragment(dir, { source, rel: PROCEDURES_FRAGMENT_REL });
132
+ } catch (error) {
133
+ throw halt(EXIT_USAGE, [OUTCOME_LINES.cannotRender(PROCEDURES_FRAGMENT_REL, error.message)]);
134
+ }
135
+ };
136
+
137
+ const validate = (io, slotFile, table, text) => {
138
+ try {
139
+ return validateSlots({ root: io.cwd, slotFile, table, text });
140
+ } catch (error) {
141
+ throw halt(EXIT_REFUSE, [OUTCOME_LINES.refused(slotFile, error.message)]);
142
+ }
143
+ };
144
+
145
+ const runRender = (io, { slotFile }) => {
146
+ const location = locateGitDir(io);
147
+ recordStage(location, slotFile, null, WRITES_AUTHORING);
148
+ const table = loadTable(io);
149
+ const slots = validate(io, slotFile, table);
150
+ const gated = RECORD_GATED_STAGES.includes(slots.stage);
151
+ const match = gated ? requireApproval(io, slots.plan, slots.stage) : null;
152
+ const canon = readCanon(io.env);
153
+ const rendering = (() => {
154
+ try {
155
+ return renderStage({ root: io.cwd, slotFile, slots, table, canon, match });
156
+ } catch (error) {
157
+ throw error.stage === WAITING_STAGE
158
+ ? halt(EXIT_REFUSE, [OUTCOME_LINES.unapproved(slots.stage, slots.plan, error.message)])
159
+ : halt(EXIT_USAGE, [OUTCOME_LINES.cannotRender(PROCEDURES_FRAGMENT_REL, error.message)]);
160
+ }
161
+ })();
162
+ recordStage(location, slotFile, slots.stage, gated ? WRITES_ANY : WRITES_AUTHORING);
163
+ io.stdout(rendering);
164
+ };
165
+
166
+ const runDispatch = (io, { plan }) => {
167
+ const approval = requireApproval(io, plan, DISPATCH);
168
+ composeDispatchPart({ plan: approval.verdict.identity, match: approval }).split(LINE_ENDING).forEach((line) => io.out(OUTCOME_LINES.text(line)));
169
+ };
170
+
171
+ const refusing = (subject, compose) => {
172
+ try {
173
+ return compose();
174
+ } catch (error) {
175
+ throw halt(EXIT_REFUSE, [OUTCOME_LINES.refused(subject, error.message)]);
176
+ }
177
+ };
178
+
179
+ const composeText = (table, { stage, values, decisions }) => refusing(STAGE_FLAG,
180
+ () => composeSlotText({ stage, values: { ...values, decisions }, date: getLocalDate(), table }));
181
+
182
+ const composeWrittenLines = (slotFile, slots, table, location) => refusing(slotFile, () => {
183
+ const prompt = isMainTree(location)
184
+ ? [OUTCOME_LINES.startHeader(), ...composeStartPrompt({ slotFile, slots, table }).split(LINE_ENDING).map(OUTCOME_LINES.text)]
185
+ : [];
186
+ return [OUTCOME_LINES.written(slotFile), OUTCOME_LINES.text(composeRenderLine(slotFile)), OUTCOME_LINES.text(composeRenderCommand(slotFile)), ...prompt];
187
+ });
188
+
189
+ const runWrite = (io, flags) => {
190
+ const { slotFile, stage } = flags;
191
+ const table = loadTable(io);
192
+ const text = composeText(table, flags);
193
+ const slots = validate(io, slotFile, table, text);
194
+ const gated = RECORD_GATED_STAGES.includes(stage);
195
+ if (gated) requireApproval(io, slots.plan, stage);
196
+ const location = locateGitDir(io);
197
+ const lines = composeWrittenLines(slotFile, slots, table, location);
198
+ if (!gated) recordStage(location, slotFile, stage, WRITES_AUTHORING);
199
+ try {
200
+ writeContainedFileAtomic(io.cwd, join(io.cwd, slotFile), text, {}, { label: slotFile });
201
+ } catch (error) {
202
+ throw halt(EXIT_USAGE, [OUTCOME_LINES.writeFailed(slotFile, error.message)]);
203
+ }
204
+ lines.forEach(io.out);
205
+ };
206
+
207
+ const COMMANDS = Object.freeze({ render: runRender, [WRITE]: runWrite, [DISPATCH]: runDispatch });
208
+
209
+ export const main = (argv = process.argv.slice(2), io = {}) => {
210
+ const stdout = io.stdout ?? ((text) => process.stdout.write(text));
211
+ const stderr = io.stderr ?? ((text) => process.stderr.write(text));
212
+ const context = {
213
+ cwd: io.cwd ?? process.cwd(), env: io.env ?? process.env, stagesPath: io.stagesPath ?? STAGES_PATH, stdout,
214
+ out: (line) => stdout(`${line}${LINE_ENDING}`), stderr: (line) => stderr(`${line}${LINE_ENDING}`),
215
+ };
216
+ const args = parseArgs(argv);
217
+ if (args.usage !== undefined) {
218
+ context.stderr(OUTCOME_LINES.usage(args.usage));
219
+ return EXIT_USAGE;
220
+ }
221
+ try {
222
+ COMMANDS[args.command](context, args);
223
+ return EXIT_OK;
224
+ } catch (error) {
225
+ if (error.exitCode === undefined) throw error;
226
+ error.lines.forEach(context.stderr);
227
+ return error.exitCode;
228
+ }
229
+ };
230
+
231
+ if (isDirectRun(import.meta.url)) process.exitCode = main();