@sabaiway/agent-workflow-kit 20.2.0 → 22.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 (98) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +7 -5
  3. package/SKILL.md +1 -1
  4. package/bin/install.mjs +10 -11
  5. package/capability.json +1 -1
  6. package/launchers/windsurf-workflow.md +3 -1
  7. package/migrations/3.0.0-hardened-core-loop.md +7 -6
  8. package/package.json +5 -2
  9. package/references/advisor-writers.md +1 -1
  10. package/references/contracts.md +11 -10
  11. package/references/modes/bootstrap.md +3 -3
  12. package/references/modes/commit-guard.md +1 -1
  13. package/references/modes/gates.md +2 -2
  14. package/references/modes/recommendations.md +3 -3
  15. package/references/modes/upgrade.md +6 -6
  16. package/references/scripts/{archive-caps.mjs → archives/archive-caps.mjs} +1 -1
  17. package/references/scripts/{archive-changelog.mjs → archives/archive-changelog.mjs} +7 -9
  18. package/references/scripts/{archive-decisions.mjs → archives/archive-decisions.mjs} +13 -10
  19. package/references/scripts/{archive-issues.mjs → archives/archive-issues.mjs} +7 -8
  20. package/references/scripts/{check-docs-size.mjs → docs-size/check-docs-size.mjs} +3 -4
  21. package/references/scripts/docs-size/index.mjs +2 -0
  22. package/references/scripts/family.json +45 -0
  23. package/references/scripts/family.mjs +90 -0
  24. package/references/scripts/gates/kit-command-gates.mjs +117 -0
  25. package/references/scripts/{migrate-gates.mjs → gates/migrate-gates.mjs} +263 -182
  26. package/references/scripts/{install-git-hooks.mjs → git-hooks/install-git-hooks.mjs} +50 -38
  27. package/references/scripts/run.mjs +90 -0
  28. package/references/scripts/shared/index.mjs +3 -0
  29. package/references/scripts/shared/project-root.mjs +11 -0
  30. package/references/scripts/spec-schema/index.mjs +2 -0
  31. package/references/scripts/test-reporter/reporter.mjs +130 -0
  32. package/references/shared/composition-handoff.md +1 -1
  33. package/references/shared/deploy-tail.md +2 -2
  34. package/references/templates/SPEC_TEMPLATE.md +1 -1
  35. package/references/templates/adr-record.md +3 -3
  36. package/tools/apply-danger-check.mjs +9 -5
  37. package/tools/atomic-write.mjs +3 -1
  38. package/tools/coverage-producer.mjs +76 -41
  39. package/tools/direct-run.mjs +2 -0
  40. package/tools/distribution-files/retired.mjs +99 -0
  41. package/tools/distribution-files/scripts.mjs +68 -52
  42. package/tools/ensure-configs.mjs +21 -21
  43. package/tools/ensure-ops.mjs +60 -18
  44. package/tools/ensure-specs.mjs +85 -47
  45. package/tools/ensure-vocabulary.mjs +4 -4
  46. package/tools/epic-shape-cli.mjs +1 -1
  47. package/tools/epic-shape-ledger.mjs +1 -1
  48. package/tools/epic-shape.mjs +1 -1
  49. package/tools/family-registry.mjs +3 -1
  50. package/tools/feedback-record-cli.mjs +1 -1
  51. package/tools/fold-scope.mjs +2 -2
  52. package/tools/gates-declaration.mjs +22 -14
  53. package/tools/gates-init.mjs +33 -17
  54. package/tools/git-hooks.mjs +90 -65
  55. package/tools/jev-connect.mjs +1 -1
  56. package/tools/jev-guide.mjs +1 -1
  57. package/tools/jev-skill.mjs +1 -1
  58. package/tools/known-footprint.mjs +7 -29
  59. package/tools/node-evidence.mjs +29 -15
  60. package/tools/now-cli.mjs +1 -1
  61. package/tools/payload-prune.mjs +53 -58
  62. package/tools/plan-shape-cli.mjs +1 -1
  63. package/tools/plan-shape.mjs +1 -1
  64. package/tools/project-rules/rules-record.mjs +1 -1
  65. package/tools/queue-audit-cli.mjs +1 -1
  66. package/tools/queue-audit.mjs +2 -2
  67. package/tools/queue-purge-archive.mjs +1 -1
  68. package/tools/queue-purge-cli.mjs +1 -1
  69. package/tools/queue-purge.mjs +1 -1
  70. package/tools/recommendations.mjs +37 -25
  71. package/tools/script-priors.mjs +31 -3
  72. package/tools/source-size/piles.mjs +1 -1
  73. package/tools/spec-adoption.mjs +1 -1
  74. package/tools/spec-check-ops.mjs +2 -2
  75. package/tools/spec-check.mjs +2 -2
  76. package/tools/spec-coverage.mjs +1 -1
  77. package/tools/tier-guide.mjs +1 -1
  78. package/tools/transition/index.mjs +1 -1
  79. package/tools/upgrade-runlist.mjs +3 -3
  80. package/tools/write-lanes.mjs +2 -2
  81. package/references/scripts/_expect-shim.mjs +0 -41
  82. package/references/scripts/archive-caps.test.mjs +0 -321
  83. package/references/scripts/archive-changelog.test.mjs +0 -560
  84. package/references/scripts/archive-conservation.test.mjs +0 -466
  85. package/references/scripts/archive-decisions.test.mjs +0 -1503
  86. package/references/scripts/archive-issues.test.mjs +0 -825
  87. package/references/scripts/archiver-structure.test.mjs +0 -84
  88. package/references/scripts/check-docs-size-cli.test.mjs +0 -325
  89. package/references/scripts/check-docs-size-ensure.test.mjs +0 -360
  90. package/references/scripts/check-docs-size.test.mjs +0 -395
  91. package/references/scripts/install-git-hooks-repo-exec.test.mjs +0 -185
  92. package/references/scripts/install-git-hooks.test.mjs +0 -241
  93. package/references/scripts/markdown-blocks.test.mjs +0 -310
  94. package/references/scripts/migrate-gates-branches.test.mjs +0 -302
  95. package/references/scripts/migrate-gates.test.mjs +0 -517
  96. package/references/scripts/spec-schema.test.mjs +0 -352
  97. /package/references/scripts/{markdown-blocks.mjs → shared/markdown-blocks.mjs} +0 -0
  98. /package/references/scripts/{spec-schema.mjs → spec-schema/spec-schema.mjs} +0 -0
@@ -31,7 +31,9 @@
31
31
  // executes project-controlled tooling (a node_modules/.bin PATH shim intercepts under every
32
32
  // form) — the documented residual, disclosed in the preview, bounded by the two consents;
33
33
  // • a `node --test` suite body — the ONE allowlist member that produces lcov unaided — is
34
- // emitted WITH the canonical coverage reporters, so the offered checker has a producer; every
34
+ // emitted as the stable kit command's unit-tests name (spec coverage-producer), which adds the
35
+ // lcov reporter, so the offered checker has a producer — only while the project's kit folder
36
+ // holds THIS kit's run.mjs and a reporter, else it is withheld naming the upgrade; every
35
37
  // other body is emitted verbatim. The coverage-check candidate is WITHHELD (loud note) when
36
38
  // neither the offer nor the existing declaration carries a producer, and --apply refuses to
37
39
  // WRITE a declaration whose checker has no producer, is not last, or has a canonical twin:
@@ -62,8 +64,8 @@ import { fileURLToPath } from 'node:url';
62
64
  import { isDirectRun } from './direct-run.mjs';
63
65
  import { discoverGateCandidates, EXPECTED_WORKFLOW_VERSION } from './velocity-profile.mjs';
64
66
  import { GATES_REL, validateDeclaration } from './run-gates.mjs';
65
- import { canonicalCheckerGates, coverageDeclarationDefects, isKitOwnedCheckerGate } from './gates-declaration.mjs';
66
- import { COVERAGE_PRODUCER_BODY, isCoverageProducerGate } from './coverage-producer.mjs';
67
+ import { canonicalCheckerGates, coverageDeclarationDefects, coverageProducerPrecedes, isKitOwnedCheckerGate, NO_PRODUCER_REMEDY } from './gates-declaration.mjs';
68
+ import { COVERAGE_PRODUCER_BODY, guardRemedy, matchesCoverageProducer, unitTestsGuardFailure } from './coverage-producer.mjs';
67
69
  import { loadConfig } from './orchestration-config.mjs';
68
70
  import { assertDocsAiDeployment, writeDocsAiFileAtomic, lstatNoFollow } from './atomic-write.mjs';
69
71
  // The source-size practice, through its PURE READ core only (D-18): this module asks whether the
@@ -117,8 +119,9 @@ never watch/serve, never a write-mode variant) whose BODY is a member of the lit
117
119
  allowlist is offered, as the hook-free \`COREPACK_ENABLE_NETWORK=0 <pm> exec -- <body>\` form for
118
120
  the detected package manager. A gate-class script whose body is NOT in the allowlist is screened
119
121
  out with a note naming it (a command you trust can still be declared by hand); non-gate-class
120
- names are excluded silently, as always. A \`node --test\` body carries the canonical coverage
121
- reporters; the coverage-check candidate is withheld when nothing would produce the lcov it reads,
122
+ names are excluded silently, as always. A \`node --test\` body runs as ${COVERAGE_PRODUCER_BODY}
123
+ while the kit folder holds this kit's command and reporter (else it is withheld, naming
124
+ /agent-workflow-kit upgrade); the coverage-check candidate is withheld when nothing would produce the lcov it reads,
122
125
  and --apply refuses to write a checker with no producer, a checker that is not last, or a second
123
126
  canonical checker.
124
127
  ${TRUST_CHAIN_DISCLOSURE}`;
@@ -222,11 +225,15 @@ export const execCmdFor = (pm, body) => {
222
225
 
223
226
  // The coverage PRODUCER wiring (Decision 1 — closed-world here too). `node --test` is the only
224
227
  // allowlist body that produces lcov with no extra dependency, so it is the only body the offer
225
- // extends with the reporter flags; every other body is emitted verbatim and produces none (an
226
- // optional-dependency coverage flag set would be speculation about the project's own tooling).
228
+ // rewrites — into the stable kit command's unit-tests name; every other body is emitted verbatim
229
+ // and produces none (an optional-dependency coverage flag set would be speculation about the
230
+ // project's own tooling).
227
231
  const COVERAGE_PRODUCING_BODY = 'node --test';
228
232
  const emittedBodyOf = (body) => (body === COVERAGE_PRODUCING_BODY ? COVERAGE_PRODUCER_BODY : body);
229
233
 
234
+ // The unit-tests guard reads the project's kit folder against THIS kit's bundled run.mjs.
235
+ const KIT_RUN = join(HERE, '..', 'references', 'scripts', 'run.mjs');
236
+
230
237
  export const kebabIdOf = (name) =>
231
238
  String(name)
232
239
  .toLowerCase()
@@ -276,6 +283,8 @@ const deriveScripts = (cwd, deps = {}) => {
276
283
  const entries = [];
277
284
  const screenedIds = [];
278
285
  const withheld = [];
286
+ const guardWithheld = [];
287
+ let guard;
279
288
  for (const c of named) {
280
289
  const id = kebabIdOf(c.scriptName);
281
290
  if (!id || seen.has(id)) continue; // an empty or duplicate derived id never enters the offer
@@ -286,12 +295,16 @@ const deriveScripts = (cwd, deps = {}) => {
286
295
  continue;
287
296
  }
288
297
  const emitted = emittedBodyOf(body);
298
+ if (emitted !== body && (guard === undefined ? (guard = unitTestsGuardFailure(cwd, KIT_RUN, { lstatSync, readFileSync })) : guard) !== null) {
299
+ guardWithheld.push({ id, ...guard });
300
+ continue;
301
+ }
289
302
  const { cmd, note } = execCmdFor(pm, emitted);
290
303
  if (cmd === null) {
291
304
  withheld.push({ id, note });
292
305
  continue;
293
306
  }
294
- const coverage = emitted === body ? '' : ' (+ the lcov reporters the coverage checker reads)';
307
+ const coverage = emitted === body ? '' : ' (through the stable kit command, + the lcov reporter the coverage checker reads)';
295
308
  entries.push({ id, title: `Project script ${c.scriptName}: ${body}${coverage}`, cmd });
296
309
  }
297
310
  const notes = [];
@@ -304,7 +317,10 @@ const deriveScripts = (cwd, deps = {}) => {
304
317
  if (withheld.length) {
305
318
  notes.push(`${withheld.length} script gate(s) withheld: ${withheld.map((w) => w.id).join(', ')} — ${withheld[0].note}`);
306
319
  }
307
- return { entries, notes };
320
+ for (const { id, path, kind } of guardWithheld) {
321
+ notes.push(`script gate ${id} withheld: its node --test body runs as ${COVERAGE_PRODUCER_BODY}, and ${path} ${guardRemedy(kind, '/agent-workflow-kit upgrade')}`);
322
+ }
323
+ return { entries, notes, guardWithheld: guardWithheld.map(({ id, path }) => ({ id, path })) };
308
324
  };
309
325
 
310
326
  export const deriveScriptEntries = (cwd, deps = {}) => deriveScripts(cwd, deps).entries;
@@ -533,17 +549,15 @@ export const buildOffer = (cwd, deps = {}) => {
533
549
  // a declaration the user already wrote by hand, so the rule reads the merged picture; a
534
550
  // declaration this preview cannot read degrades to a stated note, never to a silent withhold.
535
551
  const existing = declaredGatesBestEffort(cwd, deps);
536
- // Both sides ask the ONE gate-level predicate. The offer side can only ever be a recognized cmd
537
- // (this preview never EMITS the marker — it offers nothing it cannot verify), but a declaration
538
- // the user wrote by hand may carry it, and the two sides must not answer through two predicates.
552
+ // The offered entries carry no marker and no claim, so the closed cmd world screens them; every
553
+ // declared row is asked the ONE row question (readsAsCoverageProducer, through
554
+ // coverageProducerPrecedes over the whole list), so a row claiming the checker never produces.
539
555
  const producerPresent =
540
- scripts.entries.some((entry) => isCoverageProducerGate(entry)) ||
541
- existing.gates.some((gate) => isCoverageProducerGate(gate));
556
+ scripts.entries.some((entry) => matchesCoverageProducer(entry.cmd)) ||
557
+ coverageProducerPrecedes(existing.gates, existing.gates.length, cwd);
542
558
  const withholdCoverage = cc.candidate !== null && !producerPresent;
543
559
  const coverageNote = withholdCoverage
544
- ? `the coverage-check candidate was withheld: nothing would PRODUCE the lcov it reads — no offered or ` +
545
- `declared gate carries the canonical coverage reporters, and a checker with no producer passes while ` +
546
- `verifying nothing (declare a suite gate per references/modes/gates.md, then re-run)`
560
+ ? `the coverage-check candidate was withheld: no declared gate is a producer this kit reads, and none is offered — ${NO_PRODUCER_REMEDY}`
547
561
  : cc.note;
548
562
  // ALWAYS stated, not only when it changed the withhold: the preview would otherwise promise an
549
563
  // applicable offer over a declaration --apply is certain to refuse.
@@ -573,6 +587,8 @@ export const buildOffer = (cwd, deps = {}) => {
573
587
  return {
574
588
  entries: [...scripts.entries, ...candidates],
575
589
  notes: [...scripts.notes, noVerificationNote, unreadableNote, rs.note, fc.note, ss.note, coverageNote].filter(Boolean),
590
+ // The script gates the unit-tests guard withheld, { id, path }: the signal the advisor reads, never the note's text.
591
+ guardWithheld: scripts.guardWithheld,
576
592
  };
577
593
  };
578
594
 
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // git-hooks.mjs — the thin writer of the three git-hook items (`enforcement`, `commit-guard`,
3
- // `hook-checks`): it copies the bundled scripts create-only and spawns the project's own
4
- // scripts/install-git-hooks.mjs as it stands, which decides the hook at the write. The leaf
3
+ // `hook-checks`): it copies the deployed scripts create-only into the kit folder and spawns the project's
4
+ // own installer (INSTALLER_REL) as it stands, which decides the hook at the write. The leaf
5
5
  // decides nothing about the hook: the danger check binds the copies and the installer bytes this dry run
6
6
  // answers, never git's hooks dir. It is also the home of the one pre-commit reader, which the
7
7
  // commit-guard and hook-checks applies run after the installer to verify the arm.
@@ -11,18 +11,17 @@ import { spawnSync } from 'node:child_process';
11
11
  import { dirname, join, resolve } from 'node:path';
12
12
  import { fileURLToPath } from 'node:url';
13
13
  import { writeProjectFileCreateOnly } from './atomic-write.mjs';
14
- import { BUNDLED_SCRIPT_NAMES, INSTALLER_REL, NODE_EVIDENCE_SCRIPTS, SCRIPTS_DIR } from './node-evidence.mjs';
14
+ import { DEPLOYED_SCRIPTS, INSTALLER_REL, NODE_EVIDENCE_SCRIPTS, SCRIPTS_DIR } from './node-evidence.mjs';
15
15
  import { shellQuoteArg } from './repo-lex.mjs';
16
16
  import { GIT_MAX_BUFFER } from './git-env.mjs';
17
+ import { KIT_COMMAND_PATH, KIT_COMMANDS } from '../references/scripts/run.mjs';
17
18
  import { isDirectRun } from './direct-run.mjs';
18
19
  import { checkRules } from './project-rules/index.mjs';
19
20
  import { readLayoutSetup } from './source-size-core.mjs';
20
21
 
21
22
  const TOOLS = dirname(fileURLToPath(import.meta.url));
22
23
  export const SCRIPTS_REL = SCRIPTS_DIR;
23
- export { BUNDLED_SCRIPT_NAMES, INSTALLER_REL };
24
- const bundleDir = (toolsDir) => join(toolsDir, '..', 'references', 'scripts');
25
- const INSTALLER_NAME = 'install-git-hooks.mjs';
24
+ export { DEPLOYED_SCRIPTS, INSTALLER_REL };
26
25
 
27
26
  const EXIT_OK = 0;
28
27
  const EXIT_INCOMPLETE = 1;
@@ -44,8 +43,18 @@ const nodeAt = (path, lstat) => {
44
43
  throw error;
45
44
  }
46
45
  };
46
+ // The rollback's read: a path it cannot lstat is never one it removes.
47
+ const nodeOrNull = (path, lstat) => {
48
+ try {
49
+ return nodeAt(path, lstat);
50
+ } catch {
51
+ return null;
52
+ }
53
+ };
47
54
  const isPlainDir = (node) => node !== null && node.isDirectory() && !node.isSymbolicLink();
48
55
  const isFile = (node) => node !== null && node.isFile() && !node.isSymbolicLink();
56
+ // Each folder between the root and rel, shallowest first: scripts/, the kit folder, a module folder.
57
+ const foldersOf = (rel) => rel.split('/').slice(0, -1).map((_, at, parts) => parts.slice(0, at + 1).join('/'));
49
58
 
50
59
  // The absolute hooks dir git itself reports (a linked worktree's own, core.hooksPath), or null outside a git tree.
51
60
  export const resolveGitHooksPath = (projectDir, env = process.env) => {
@@ -54,8 +63,9 @@ export const resolveGitHooksPath = (projectDir, env = process.env) => {
54
63
  return resolve(projectDir, result.stdout.toString('utf8').replace(/\r?\n$/, ''));
55
64
  };
56
65
 
57
- export const INSTALLER_MARKER_RE = /:install-git-hooks\.mjs$/m;
66
+ export const INSTALLER_MARKER_RE = /:install-git-hooks\.mjs\r?$/m;
58
67
  const escapeRe = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
68
+ const COMMAND_LINE_RE = new RegExp(`^node ${escapeRe(KIT_COMMAND_PATH)} docs-size\\r?$`, 'm');
59
69
  // Armed means the exact line the installer writes on the kit's own guard path; a commented or lookalike line is not.
60
70
  export const canonicalGuardLineRe = (toolsDir = TOOLS) => new RegExp(`^node "${escapeRe(join(toolsDir, 'commit-guard.mjs'))}" --check$`, 'm');
61
71
 
@@ -88,7 +98,7 @@ const roleStates = (hook, toolsDir, platform) => Object.fromEntries(ROLES.flatMa
88
98
 
89
99
  // The one reader of git's pre-commit: whose hook it is, and which canonical lines arm it.
90
100
  export const readPreCommitState = (root, deps = {}) => {
91
- const unarmed = (fields) => ({ ...fields, armed: false, ...roleStates(null) });
101
+ const unarmed = (fields) => ({ ...fields, armed: false, command: false, ...roleStates(null) });
92
102
  const hooksPath = (deps.gitHooksPath ?? resolveGitHooksPath)(root, deps.env);
93
103
  if (hooksPath === null) return unarmed({ state: 'no-hooks-dir' });
94
104
  const path = join(hooksPath, 'pre-commit');
@@ -101,9 +111,13 @@ export const readPreCommitState = (root, deps = {}) => {
101
111
  return unarmed({ state: 'unreadable', code: error?.code ?? String(error?.message ?? error), path });
102
112
  }
103
113
  return { state: INSTALLER_MARKER_RE.test(hook) ? 'managed' : 'unmanaged', armed: canonicalGuardLineRe(deps.toolsDir).test(hook),
104
- ...roleStates(hook, deps.toolsDir ?? TOOLS, deps.platform) };
114
+ command: COMMAND_LINE_RE.test(hook), ...roleStates(hook, deps.toolsDir ?? TOOLS, deps.platform) };
105
115
  };
106
116
 
117
+ export const missingHookCommandFile = (root, deps = {}) => [INSTALLER_REL, KIT_COMMAND_PATH,
118
+ ...Object.values(KIT_COMMANDS).map((target) => join(dirname(KIT_COMMAND_PATH), target))]
119
+ .map((rel) => join(root, rel)).find((path) => !isFile(nodeAt(path, deps.lstat ?? lstatSync)));
120
+
107
121
  // The two read-only answers the hook-checks dry run and the advisor's probe ask, on the tree on disk.
108
122
  export const hookCheckAnswers = (root, deps = {}) => {
109
123
  const verdicts = (deps.checkRules ?? checkRules)(root, deps);
@@ -124,94 +138,102 @@ export const unsafeToolsPath = (toolsDir, platform) => (ROLES.some(({ tool }) =>
124
138
  ? `the kit's tools path ${toolsDir} carries ", $, a backtick, a backslash, CR or LF — a hook line would not run the file it names` : null);
125
139
 
126
140
  // hook-checks: the lines it arms, from the two answers and the hook; the installer runs as it stands.
127
- const planHookChecks = ({ root, toolsDir, installer, scriptsNode, kinds, readFile, deps }) => {
128
- if (!isPlainDir(scriptsNode) || kinds.get(INSTALLER_NAME) !== 'file') throw refusal(`${installer} is absent — nothing here places the hook installer`);
141
+ const planHookChecks = ({ root, toolsDir, installer, installerNode, lstat, readFile, deps }) => {
142
+ if (!isFile(installerNode)) throw refusal(`${installer} is absent — nothing here places the hook installer`);
129
143
  const unsafe = unsafeToolsPath(toolsDir, deps.platform);
130
144
  if (unsafe !== null) throw refusal(unsafe);
131
145
  const hook = readPreCommitState(root, { toolsDir, platform: deps.platform, gitHooksPath: deps.gitHooksPath });
132
146
  if (hook.state === 'unreadable') throw refusal(`${hook.path} is unreadable (${hook.code}) — the pre-commit hook cannot be judged`);
133
147
  if (hook.state === 'no-hooks-dir') throw refusal('nothing to plan — git reports no hooks dir here (not a git checkout), so there is no hook to arm');
148
+ const switchCommand = hook.state === 'managed' && !hook.command;
149
+ const missing = switchCommand ? missingHookCommandFile(root, { lstat }) : undefined;
150
+ if (missing) throw refusal(`${missing} is not a regular file — re-run /agent-workflow-kit upgrade, then apply this item again`);
134
151
  const answers = hookCheckAnswers(root, deps);
135
152
  const roles = plannedRoles(answers, hook);
136
- if (roles.length === 0) {
153
+ if (roles.length === 0 && !switchCommand) {
137
154
  throw refusal(`nothing to plan — ${ROLES.map(({ key, role }) => `the ${role} line: ${hook[`${key}Armed`] ? 'armed' : `not armable (${answers[key].why})`}`).join('; ')}`);
138
155
  }
139
156
  const flags = roles.flatMap(({ flag, tool }) => [flag, tool(toolsDir)]);
140
- return { root, variant: 'hook-checks', scriptsCreated: false, copies: [], roles: roles.map(({ key }) => key),
157
+ return { root, variant: 'hook-checks', folders: [], copies: [], switchCommand, roles: roles.map(({ key }) => key),
141
158
  runs: { argv: ['node', installer, ...flags], shown: ['node', INSTALLER_REL, ...flags], bytes: readFile(installer) } };
142
159
  };
143
160
 
144
161
  // The dry run: what the apply copies and the installer it runs, with the bytes of each.
145
162
  export const planGitHooks = ({ root, variant, toolsDir = TOOLS, lstat = lstatSync, readFile = readFileSync, ...deps }) => {
146
- const scripts = join(root, SCRIPTS_REL);
147
- const scriptsNode = nodeAt(scripts, lstat);
148
- if (scriptsNode !== null && !isPlainDir(scriptsNode)) throw refusal(`${scripts} is not a plain directory`);
149
- const kinds = new Map();
150
- const names = variant === 'enforcement' ? BUNDLED_SCRIPT_NAMES : [INSTALLER_REL.slice(SCRIPTS_REL.length + 1)];
151
- for (const name of scriptsNode === null ? [] : names) {
152
- const path = join(scripts, name);
153
- const node = nodeAt(path, lstat);
154
- if (node !== null && !isFile(node)) throw refusal(`${path} is not a regular file`);
155
- kinds.set(name, node === null ? 'absent' : 'file');
163
+ const enforcing = variant === 'enforcement';
164
+ const nodes = new Map();
165
+ const folders = [];
166
+ // Never beneath an absent folder: a folder on the way absent, every path under it is absent.
167
+ const probe = (rel, isKind, kind) => {
168
+ if (nodes.has(rel)) return nodes.get(rel);
169
+ const path = join(root, rel);
170
+ const node = foldersOf(rel).some((folder) => nodes.get(folder) === null) ? null : nodeAt(path, lstat);
171
+ if (node !== null && !isKind(node)) throw refusal(`${path} is not ${kind}`);
172
+ nodes.set(rel, node);
173
+ return node;
174
+ };
175
+ for (const rel of enforcing ? DEPLOYED_SCRIPTS.map(({ deployed }) => deployed) : [INSTALLER_REL]) {
176
+ for (const folder of foldersOf(rel)) if (!nodes.has(folder)) (folders.push(folder), probe(folder, isPlainDir, 'a plain directory'));
177
+ probe(rel, isFile, 'a regular file');
156
178
  }
157
179
  const installer = join(root, INSTALLER_REL);
158
- if (variant === 'hook-checks') return planHookChecks({ root, toolsDir, installer, scriptsNode, kinds, readFile, deps });
159
- const deployed = NODE_EVIDENCE_SCRIPTS.some((name) => kinds.get(name) === 'file');
160
- const copies = variant === 'enforcement' && !deployed ? BUNDLED_SCRIPT_NAMES.map((name) => {
161
- if (kinds.get(name) === 'file') return { name, path: join(scripts, name), action: 'kept' };
162
- return { name, path: join(scripts, name), action: 'created', bytes: readFile(join(bundleDir(toolsDir), name)) };
163
- }) : [];
164
- const placed = copies.find(({ path, action }) => path === installer && action === 'created');
165
- if (!placed && !isFile(nodeAt(installer, lstat))) throw refusal(`${installer} is absent — nothing here places the hook installer`);
180
+ if (variant === 'hook-checks') return planHookChecks({ root, toolsDir, installer, installerNode: nodes.get(INSTALLER_REL), lstat, readFile, deps });
181
+ // A flat evidence name is no copy path: another node kind there is not evidence, never a refusal.
182
+ const evidence = (rel) => (nodes.has(rel) ? isFile(nodes.get(rel)) : nodes.get(SCRIPTS_REL) !== null && isFile(nodeAt(join(root, rel), lstat)));
183
+ const deployed = enforcing && NODE_EVIDENCE_SCRIPTS.some((name) => evidence(`${SCRIPTS_REL}/${name}`));
184
+ const copies = enforcing && !deployed ? DEPLOYED_SCRIPTS.map(({ deployed: rel, bundled }) =>
185
+ ({ rel, path: join(root, rel), action: 'created', bytes: readFile(join(toolsDir, '..', bundled)) })) : [];
186
+ const placed = copies.find(({ rel }) => rel === INSTALLER_REL);
187
+ if (!placed && !isFile(nodes.get(INSTALLER_REL))) throw refusal(`${installer} is absent — nothing here places the hook installer`);
166
188
  const guard = variant === 'commit-guard' ? ['--commit-guard', join(toolsDir, 'commit-guard.mjs')] : [];
167
189
  return {
168
190
  root,
169
191
  variant,
170
- scriptsCreated: scriptsNode === null,
192
+ folders: copies.length === 0 ? [] : folders.filter((folder) => nodes.get(folder) === null),
171
193
  copies,
172
194
  runs: { argv: ['node', installer, ...guard], shown: ['node', INSTALLER_REL, ...guard], bytes: placed ? placed.bytes : readFile(installer) },
173
195
  };
174
196
  };
175
197
 
176
198
  export const formatPlan = (plan) => [
177
- ...plan.copies.map(({ name, action, bytes }) => `copy: ${SCRIPTS_REL}/${name} ${action}${action === 'created' ? ` sha256:${sha(bytes)}` : ''}`),
199
+ ...plan.copies.map(({ rel, action, bytes }) => `copy: ${rel} ${action}${action === 'created' ? ` sha256:${sha(bytes)}` : ''}`),
178
200
  `runs: ${plan.runs.shown.map(shellQuoteArg).join(' ')} sha256:${sha(plan.runs.bytes)}`,
179
201
  ];
180
202
 
181
- // Removes exactly the files this run created, then scripts/ when this run created it and it is empty;
182
- // every path it cannot remove is answered for the caller to name.
203
+ // Removes exactly the files this run created, then each folder this run created, deepest first, when it is
204
+ // empty; a path is removed only while every folder above it is the plain directory this apply observed,
205
+ // and every path it cannot remove is answered for the caller to name.
183
206
  const rollBack = (plan, created, io) => {
184
- const scripts = join(plan.root, SCRIPTS_REL);
185
207
  const left = [];
186
- const dirNow = () => nodeAt(scripts, io.lstat);
187
- for (const path of created) {
188
- const dir = dirNow();
189
- const node = nodeAt(path, io.lstat);
190
- if (!isPlainDir(dir) || dir.ino !== created.dirIno || !isFile(node)) {
191
- left.push(path);
192
- continue;
193
- }
208
+ const observed = (folder) => {
209
+ const node = nodeOrNull(join(plan.root, folder), io.lstat);
210
+ return isPlainDir(node) && node.ino === created.inos.get(folder);
211
+ };
212
+ const intact = (rel) => foldersOf(rel).every(observed);
213
+ const remove = (path, act) => {
194
214
  try {
195
- io.unlink(path);
215
+ act(path);
196
216
  } catch {
197
217
  left.push(path);
198
218
  }
219
+ };
220
+ for (const { rel, path } of created.files) {
221
+ if (intact(rel) && isFile(nodeOrNull(path, io.lstat))) remove(path, io.unlink);
222
+ else left.push(path);
199
223
  }
200
- if (plan.scriptsCreated && created.dirIno !== undefined) {
201
- const dir = dirNow();
224
+ for (const folder of created.folders.filter((rel) => created.inos.has(rel)).reverse()) {
225
+ const path = join(plan.root, folder);
226
+ if (!intact(folder) || !observed(folder)) {
227
+ left.push(path);
228
+ continue;
229
+ }
202
230
  let empty = false;
203
231
  try {
204
- empty = isPlainDir(dir) && dir.ino === created.dirIno && io.readdir(scripts).length === 0;
232
+ empty = io.readdir(path).length === 0;
205
233
  } catch {
206
234
  empty = false;
207
235
  }
208
- if (empty) {
209
- try {
210
- io.rmdir(scripts);
211
- } catch {
212
- left.push(scripts);
213
- }
214
- } else if (!isPlainDir(dir) || dir.ino !== created.dirIno) left.push(scripts);
236
+ if (empty) remove(path, io.rmdir);
215
237
  }
216
238
  return left;
217
239
  };
@@ -225,6 +247,7 @@ const applyHookChecks = (plan, resolved) => {
225
247
  const failure = child.status !== 0 ? `installer exited ${child.status ?? child.signal ?? child.error?.code}`
226
248
  : hook.state === 'no-hooks-dir' ? null
227
249
  : hook.state === 'unreadable' ? `${preCommit} is unreadable (${hook.code}) after the installer exited 0`
250
+ : plan.switchCommand && !hook.command ? `${preCommit} carries no kit-command line after the installer exited 0 — ${UPGRADE_ROUTE}`
228
251
  : ROLES.filter(({ key }) => plan.roles.includes(key)).map(({ key, role }) => (!hook[`${key}Armed`]
229
252
  ? `${preCommit} carries no ${role} line after the installer exited 0 — ${UPGRADE_ROUTE}`
230
253
  : hook[`${key}Foreign`] ? `${preCommit} still carries a ${role} line on a path other than this kit's after the installer exited 0` : null)).find(Boolean) ?? null;
@@ -238,30 +261,32 @@ export const applyGitHooks = (plan, io = {}) => {
238
261
  log: console.log, error: console.error, writeFile: writeProjectFileCreateOnly, toolsDir: TOOLS, platform: process.platform,
239
262
  spawn: (argv, options) => spawnSync(argv[0], argv.slice(1), options), ...io };
240
263
  if (plan.variant === 'hook-checks') return applyHookChecks(plan, resolved);
241
- const created = [];
264
+ // A folder the dry run found absent and that still is absent here is one this run creates; a plan with no copies names none.
265
+ const created = { files: [], inos: new Map(), folders: (plan.folders ?? []).filter((rel) => nodeOrNull(join(plan.root, rel), resolved.lstat) === null) };
242
266
  const leftovers = [];
243
267
  const fail = (lines) => {
244
268
  for (const line of lines) resolved.error(line);
245
269
  for (const path of [...rollBack(plan, created, resolved), ...leftovers]) resolved.error(`not removed: ${path}`);
246
270
  return EXIT_INCOMPLETE;
247
271
  };
248
- const scripts = join(plan.root, SCRIPTS_REL);
249
- const noteDir = () => {
250
- const dir = nodeAt(scripts, resolved.lstat);
251
- if (created.dirIno === undefined && isPlainDir(dir)) created.dirIno = dir.ino;
272
+ const noteFolders = (rel) => {
273
+ for (const folder of foldersOf(rel).filter((at) => !created.inos.has(at))) {
274
+ const node = nodeOrNull(join(plan.root, folder), resolved.lstat);
275
+ if (isPlainDir(node)) created.inos.set(folder, node.ino);
276
+ }
252
277
  };
253
278
  for (const copy of plan.copies.filter(({ action }) => action === 'created')) {
254
279
  let result;
255
280
  try {
256
- result = resolved.writeFile(plan.root, `${SCRIPTS_REL}/${copy.name}`, copy.bytes);
281
+ result = resolved.writeFile(plan.root, copy.rel, copy.bytes);
257
282
  } catch (error) {
258
- noteDir();
259
- return fail([error?.message ?? String(error)]);
283
+ noteFolders(copy.rel);
284
+ return fail([`${copy.path}: ${error?.message ?? String(error)}`]);
260
285
  }
261
- noteDir();
286
+ noteFolders(copy.rel);
262
287
  if (result.tmpLeftBehind) leftovers.push(result.tmpLeftBehind);
263
288
  if (!result.created) return fail([`${copy.path} appeared after the check — the file found there stands`]);
264
- created.push(copy.path);
289
+ created.files.push(copy);
265
290
  }
266
291
  const child = resolved.spawn(plan.runs.argv, { cwd: plan.root, env: resolved.env, stdio: 'inherit' });
267
292
  if (child.status !== 0) return fail([`installer exited ${child.status ?? child.signal ?? child.error?.code}`]);
@@ -10,7 +10,7 @@ import { spawnSync } from 'node:child_process';
10
10
  import { lstatSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
11
11
  import { homedir } from 'node:os';
12
12
  import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
13
- import { fail } from '../references/scripts/markdown-blocks.mjs';
13
+ import { fail } from '../references/scripts/shared/index.mjs';
14
14
  import { isDirectRun } from './direct-run.mjs';
15
15
  import { JEV_ENDPOINT, JEV_ERROR_MEANINGS, JEV_SAMPLE_BODY, KEY_VARIABLE, RESTART_STEP } from './jev-facts.mjs';
16
16
 
@@ -4,7 +4,7 @@ import { lstatSync, readFileSync, readdirSync, statSync } from 'node:fs';
4
4
  import { homedir, hostname } from 'node:os';
5
5
  import { basename, dirname, join, resolve } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
- import { fail } from '../references/scripts/markdown-blocks.mjs';
7
+ import { fail } from '../references/scripts/shared/index.mjs';
8
8
  import { isDirectRun } from './direct-run.mjs';
9
9
  import { AFTER_INSTALL, KEY_VARIABLE, NO_APPLY_LINE, RESTART_STEP, SKILL_PINS, claudeDirOf, connectLine, keySet, placeOf, printable, skillLine, skillState, skillTargets } from './jev-facts.mjs';
10
10
 
@@ -11,7 +11,7 @@ import { lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSyn
11
11
  import { homedir } from 'node:os';
12
12
  import { dirname, join, posix, win32 } from 'node:path';
13
13
  import { fileURLToPath } from 'node:url';
14
- import { fail } from '../references/scripts/markdown-blocks.mjs';
14
+ import { fail } from '../references/scripts/shared/index.mjs';
15
15
  import { isDirectRun } from './direct-run.mjs';
16
16
  import { AFTER_INSTALL, NO_APPLY_LINE, SKILL_FILES, SKILL_PINS, claudeDirOf, printable, skillLine, skillState,
17
17
  skillTargets } from './jev-facts.mjs';
@@ -15,9 +15,11 @@
15
15
  // references/contracts.md carries the human-readable mirror table, kept in sync by review.
16
16
  //
17
17
  // Pure, dependency-free, Node >= 22. The only fs touch is expandGlob (readdir/stat of a glob parent),
18
- // injected so the registry stays unit-testable without the real filesystem.
18
+ // injected so the registry stays unit-testable without the real filesystem; the kit folder's path is
19
+ // node-evidence.mjs's, the kit's one door to the script family (which reads its manifest on import).
19
20
 
20
21
  import { readdirSync, statSync } from 'node:fs';
22
+ import { KIT_SCRIPTS_DIR } from './node-evidence.mjs';
21
23
 
22
24
  // A typed STOP — a deliberate refusal we surface (never a silent skip, never a fail-open). Shared by
23
25
  // the writer tool (hide-footprint.mjs imports it) so both speak one error vocabulary. The codebase's
@@ -41,38 +43,14 @@ export const stop = (message, fields = {}) =>
41
43
  // follow-up-reconcile gap this entry closes. Never provisioned into a worktree (worktrees.mjs). `/docs/plans/` + both `.claude/settings*.json` are listed because a pure
42
44
  // hidden deploy has no tracked `.gitignore`; the classifier drops any candidate a tracked `.gitignore`
43
45
  // already covers, so in a repo that DOES track those ignores they are never re-written.
44
- // The enumeration must cover EVERY file the deploy copies into `scripts/` (bootstrap step 8 copies
45
- // `references/scripts/*.mjs` + `*.test.mjs` wholesale): a name missing here is a file a hidden
46
- // deployment leaves visible in `git status` — the exact leak this registry exists to prevent.
46
+ // The kit folder is the kit's whole, so one directory pattern covers every file placed in it; no flat
47
+ // `scripts/<name>` is listed, because the upgrade's scripts op removes the kit's old flat files in the
48
+ // run that places the kit folder (distribution-files, part flat-move: the window it leaves is stated there).
47
49
  export const KIT_OWN_PATHS = [
48
50
  '/AGENTS.md',
49
51
  '/CLAUDE.md',
50
52
  '/docs/ai/',
51
- '/scripts/_expect-shim.mjs',
52
- '/scripts/archive-caps.mjs',
53
- '/scripts/archive-caps.test.mjs',
54
- '/scripts/archive-changelog.mjs',
55
- '/scripts/archive-changelog.test.mjs',
56
- '/scripts/archive-conservation.test.mjs',
57
- '/scripts/archive-decisions.mjs',
58
- '/scripts/archive-decisions.test.mjs',
59
- '/scripts/archive-issues.mjs',
60
- '/scripts/archive-issues.test.mjs',
61
- '/scripts/archiver-structure.test.mjs',
62
- '/scripts/check-docs-size-cli.test.mjs',
63
- '/scripts/check-docs-size-ensure.test.mjs',
64
- '/scripts/check-docs-size.mjs',
65
- '/scripts/check-docs-size.test.mjs',
66
- '/scripts/install-git-hooks-repo-exec.test.mjs',
67
- '/scripts/install-git-hooks.mjs',
68
- '/scripts/install-git-hooks.test.mjs',
69
- '/scripts/markdown-blocks.mjs',
70
- '/scripts/markdown-blocks.test.mjs',
71
- '/scripts/migrate-gates-branches.test.mjs',
72
- '/scripts/migrate-gates.mjs',
73
- '/scripts/migrate-gates.test.mjs',
74
- '/scripts/spec-schema.mjs',
75
- '/scripts/spec-schema.test.mjs',
53
+ `/${KIT_SCRIPTS_DIR}/`,
76
54
  '/docs/plans/',
77
55
  '/.claude/settings.local.json',
78
56
  '/.claude/settings.json',
@@ -1,9 +1,10 @@
1
1
  // node-evidence.mjs — does Node PROVABLY run in this project tree? Contract: docs/ai/specs/kit/node-evidence.md.
2
2
  // Pure over an injectable lstat; no writes, no side effects on import. Dependency-free, Node >= 22.
3
3
 
4
- import { lstatSync, readdirSync } from 'node:fs';
5
- import { dirname, join } from 'node:path';
6
- import { fileURLToPath } from 'node:url';
4
+ import { lstatSync } from 'node:fs';
5
+ import { join, posix } from 'node:path';
6
+ import { readFamily } from '../references/scripts/family.mjs';
7
+ import { KIT_FOLDER_ROOT } from './source-size-config.mjs';
7
8
 
8
9
  export const NODE_EVIDENCE = Object.freeze({
9
10
  PACKAGE_JSON: 'package-json',
@@ -14,16 +15,18 @@ export const NODE_EVIDENCE = Object.freeze({
14
15
 
15
16
  export const PACKAGE_JSON_REL = 'package.json';
16
17
  export const SCRIPTS_DIR = 'scripts';
17
- export const INSTALLER_REL = `${SCRIPTS_DIR}/install-git-hooks.mjs`;
18
+ export const KIT_SCRIPTS_DIR = KIT_FOLDER_ROOT;
18
19
 
19
- // Every *.mjs of the kit's references/scripts/, sorted, the tests and the shim included: what the
20
- // enforcement copy places. Read from this kit copy at import, so a module the git-hooks leaf's own
21
- // imports reach names the bundle without importing that leaf back.
22
- export const BUNDLED_SCRIPT_NAMES = Object.freeze(readdirSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'references', 'scripts'))
23
- .filter((name) => name.endsWith('.mjs')).sort());
20
+ // The kit's one door to the script family: the mirrored manifest's deployed entries, each with its
21
+ // manifest path, module and seed flag, its deployed path in the kit folder and its bundled path in this
22
+ // kit. A manifest the reader refuses fails this module's import with the reader's message.
23
+ export const DEPLOYED_SCRIPTS = Object.freeze(readFamily().filter(({ role }) => role === 'deployed').map(({ path, module, seed }) =>
24
+ Object.freeze({ path, module, seed, deployed: `${KIT_SCRIPTS_DIR}/${path}`, bundled: `references/scripts/${path}` })));
25
+ export const INSTALLER_REL = DEPLOYED_SCRIPTS.find(({ module }) => module === 'git-hooks').deployed;
24
26
 
25
- // The runnable scripts the bootstrap copies from references/scripts/ — pinned against the bundle by the suite.
26
- export const NODE_EVIDENCE_SCRIPTS = Object.freeze([
27
+ // The nine flat runnable names probed before the kit folder (frozen, so a flat deployment keeps its
28
+ // evidence), then the deployed manifest paths, sorted — each relative to scripts/.
29
+ const FLAT_SCRIPTS = [
27
30
  'archive-caps.mjs',
28
31
  'archive-changelog.mjs',
29
32
  'archive-decisions.mjs',
@@ -33,6 +36,11 @@ export const NODE_EVIDENCE_SCRIPTS = Object.freeze([
33
36
  'markdown-blocks.mjs',
34
37
  'migrate-gates.mjs',
35
38
  'spec-schema.mjs',
39
+ ];
40
+ const KIT_UNDER_SCRIPTS = posix.relative(SCRIPTS_DIR, KIT_SCRIPTS_DIR);
41
+ export const NODE_EVIDENCE_SCRIPTS = Object.freeze([
42
+ ...FLAT_SCRIPTS,
43
+ ...DEPLOYED_SCRIPTS.map(({ path }) => path).sort().map((path) => `${KIT_UNDER_SCRIPTS}/${path}`),
36
44
  ]);
37
45
 
38
46
  export const NODE_EVIDENCE_PROBES = Object.freeze([PACKAGE_JSON_REL, ...NODE_EVIDENCE_SCRIPTS.map((name) => `${SCRIPTS_DIR}/${name}`)]);
@@ -46,10 +54,16 @@ const answer = (state, evidence, wrongKind, extra = {}) =>
46
54
  // probeNodeEvidence(cwd, lstat) -> { state, evidence, probed, wrongKind, error? }: the first regular file
47
55
  // among the probes answers; a probe failing with anything but ENOENT answers unreadable at once; a path of
48
56
  // the wrong node kind is not evidence — it is recorded in `wrongKind` and the walk continues. lstat does
49
- // not follow the LEAF but walks THROUGH a symlinked scripts/, whose files are not this tree's — so the
50
- // directory is proven plain before any script inside it counts.
57
+ // not follow the LEAF but walks THROUGH a symlinked folder, whose files are not this tree's — so scripts/,
58
+ // the kit folder and each module folder are proven plain, once each, before any script beneath counts.
51
59
  export const probeNodeEvidence = (cwd, lstat = lstatSync) => {
52
60
  const wrongKind = [];
61
+ const folders = new Map();
62
+ const plainFolder = (rel) => {
63
+ if (!folders.has(rel)) folders.set(rel, probeKind(rel, 'dir') === 'dir');
64
+ return folders.get(rel);
65
+ };
66
+ const foldersOf = (rel) => rel.split('/').slice(1, -1).map((_, at, parts) => [SCRIPTS_DIR, ...parts.slice(0, at + 1)].join('/'));
53
67
  const probeKind = (rel, wanted) => {
54
68
  let st;
55
69
  try {
@@ -64,9 +78,9 @@ export const probeNodeEvidence = (cwd, lstat = lstatSync) => {
64
78
  };
65
79
  try {
66
80
  if (probeKind(PACKAGE_JSON_REL, 'file') === 'file') return answer(NODE_EVIDENCE.PACKAGE_JSON, PACKAGE_JSON_REL, wrongKind);
67
- if (probeKind(SCRIPTS_DIR, 'dir') === 'dir') {
81
+ if (plainFolder(SCRIPTS_DIR)) {
68
82
  for (const rel of NODE_EVIDENCE_PROBES.slice(1)) {
69
- if (probeKind(rel, 'file') === 'file') return answer(NODE_EVIDENCE.DEPLOYED_SCRIPTS, rel, wrongKind);
83
+ if (foldersOf(rel).every(plainFolder) && probeKind(rel, 'file') === 'file') return answer(NODE_EVIDENCE.DEPLOYED_SCRIPTS, rel, wrongKind);
70
84
  }
71
85
  }
72
86
  } catch (err) {
package/tools/now-cli.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  // facts in now-facts.mjs, the phrases in now-render.mjs.
4
4
 
5
5
  import { resolve } from 'node:path';
6
- import { fail } from '../references/scripts/markdown-blocks.mjs';
6
+ import { fail } from '../references/scripts/shared/index.mjs';
7
7
  import { isDirectRun } from './direct-run.mjs';
8
8
  import { FORMATS, detectSurface } from './surface.mjs';
9
9
  import { gatherNowFacts } from './now-facts.mjs';