@sabaiway/agent-workflow-kit 23.12.0 → 24.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +4 -4
  3. package/SKILL.md +1 -1
  4. package/bridges/codex-cli-bridge/SKILL.md +7 -2
  5. package/bridges/codex-cli-bridge/bin/codex-exec-jev.test.mjs +11 -6
  6. package/bridges/codex-cli-bridge/bin/codex-exec.sh +72 -33
  7. package/bridges/codex-cli-bridge/bin/codex-exec.test.mjs +111 -3
  8. package/bridges/codex-cli-bridge/bin/codex-fixtures-harness.test.mjs +16 -1
  9. package/bridges/codex-cli-bridge/bin/codex-model-posture.test.mjs +5 -3
  10. package/bridges/codex-cli-bridge/bin/codex-review.sh +1 -1
  11. package/bridges/codex-cli-bridge/capability.json +2 -2
  12. package/capability.json +1 -1
  13. package/package.json +1 -1
  14. package/references/advisor-writers.md +2 -0
  15. package/references/agents/author.md +21 -0
  16. package/references/agents/executor.md +12 -6
  17. package/references/contracts.md +4 -4
  18. package/references/hooks/gate-approve.mjs +7 -8
  19. package/references/hooks/stage-write-guard.mjs +314 -0
  20. package/references/modes/agents.md +6 -4
  21. package/references/modes/bootstrap.md +1 -1
  22. package/references/modes/flow-writer.md +10 -2
  23. package/references/modes/hook.md +4 -1
  24. package/references/modes/now.md +1 -1
  25. package/references/modes/procedures.md +49 -10
  26. package/references/modes/recipes.md +7 -7
  27. package/references/modes/recommendations.md +4 -3
  28. package/references/modes/robustness-brief.md +9 -8
  29. package/references/modes/set-recipe.md +1 -1
  30. package/references/modes/state-block-guard.md +4 -3
  31. package/references/modes/status.md +1 -1
  32. package/references/modes/upgrade.md +1 -1
  33. package/references/modes/worktrees.md +28 -5
  34. package/references/rules/story-sessions.md +2 -2
  35. package/references/scripts/archives/archive-caps.mjs +1 -1
  36. package/references/scripts/archives/archive-changelog.mjs +8 -8
  37. package/references/scripts/archives/archive-decisions.mjs +7 -7
  38. package/references/scripts/archives/archive-issues.mjs +5 -5
  39. package/references/scripts/archives/rotation-conservation.mjs +2 -1
  40. package/references/scripts/docs-size/check-docs-size.mjs +15 -15
  41. package/references/scripts/family.json +2 -0
  42. package/references/scripts/gates/kit-command-gates.mjs +7 -8
  43. package/references/scripts/gates/migrate-gates.mjs +10 -10
  44. package/references/scripts/git-hooks/install-git-hooks.mjs +13 -13
  45. package/references/scripts/run.mjs +1 -2
  46. package/references/scripts/shared/index.mjs +2 -0
  47. package/references/scripts/shared/locations.mjs +103 -0
  48. package/references/scripts/spec-schema/spec-schema.mjs +2 -1
  49. package/references/templates/orchestration.json +1 -1
  50. package/tools/ack-store.mjs +2 -1
  51. package/tools/apply-danger-check.mjs +20 -6
  52. package/tools/atomic-write.mjs +3 -2
  53. package/tools/attribution.mjs +2 -1
  54. package/tools/autonomy-config.mjs +2 -1
  55. package/tools/bridge-wiring.mjs +13 -11
  56. package/tools/carriers.mjs +54 -14
  57. package/tools/cheap-agents-read.mjs +28 -7
  58. package/tools/cheap-agents.mjs +15 -10
  59. package/tools/checker-gates-read.mjs +6 -5
  60. package/tools/commands.mjs +2 -2
  61. package/tools/coverage-declared/config.mjs +2 -1
  62. package/tools/coverage-producer.mjs +10 -9
  63. package/tools/delegation.mjs +7 -6
  64. package/tools/detect-backends.mjs +1 -1
  65. package/tools/dispatch-baseline.mjs +2 -1
  66. package/tools/distribution-files/scripts.mjs +4 -4
  67. package/tools/ensure-configs.mjs +2 -2
  68. package/tools/ensure-ops.mjs +24 -24
  69. package/tools/ensure-specs.mjs +7 -7
  70. package/tools/epic-shape-cli.mjs +2 -2
  71. package/tools/epic-shape-ledger.mjs +5 -5
  72. package/tools/epic-shape.mjs +5 -3
  73. package/tools/epic-store.mjs +2 -1
  74. package/tools/family-members.mjs +7 -5
  75. package/tools/family-registry.mjs +36 -30
  76. package/tools/feedback-record-cli.mjs +4 -5
  77. package/tools/flow-writer.mjs +26 -15
  78. package/tools/gate-hook.mjs +33 -28
  79. package/tools/gates-declaration.mjs +2 -1
  80. package/tools/gates-init.mjs +6 -5
  81. package/tools/git-hooks.mjs +64 -41
  82. package/tools/grounding.mjs +3 -2
  83. package/tools/hide-footprint.mjs +2 -1
  84. package/tools/hook-writer/index.mjs +147 -0
  85. package/tools/init-preflight.mjs +5 -4
  86. package/tools/init-project.mjs +12 -11
  87. package/tools/inject-methodology.mjs +3 -2
  88. package/tools/jev-guide.mjs +2 -2
  89. package/tools/known-footprint.mjs +27 -25
  90. package/tools/mcp-registration.mjs +6 -5
  91. package/tools/migration-blocks.mjs +2 -1
  92. package/tools/migration-notes.mjs +2 -2
  93. package/tools/node-evidence.mjs +4 -4
  94. package/tools/now-facts.mjs +5 -5
  95. package/tools/now-status.mjs +1 -5
  96. package/tools/orchestration-config.mjs +2 -1
  97. package/tools/orchestration-readme.mjs +7 -2
  98. package/tools/plan-approval/cli.mjs +45 -0
  99. package/tools/plan-approval/entries.mjs +109 -0
  100. package/tools/plan-approval/index.mjs +2 -0
  101. package/tools/plan-approval/record.mjs +198 -0
  102. package/tools/plan-files.mjs +6 -4
  103. package/tools/plan-shape-cli.mjs +10 -64
  104. package/tools/plan-shape-facts.mjs +240 -83
  105. package/tools/plan-shape.mjs +173 -160
  106. package/tools/plan-structure/cli.mjs +79 -0
  107. package/tools/plan-structure/index.mjs +67 -0
  108. package/tools/procedures.mjs +21 -17
  109. package/tools/profile-gaps.mjs +4 -6
  110. package/tools/project-rules/rules-priors.mjs +2 -0
  111. package/tools/project-rules/themes.mjs +6 -4
  112. package/tools/recipes.mjs +44 -29
  113. package/tools/recommendations.mjs +84 -33
  114. package/tools/reference-profile.mjs +2 -2
  115. package/tools/renderers.mjs +14 -8
  116. package/tools/repo-lex.mjs +84 -0
  117. package/tools/robustness-brief.mjs +14 -11
  118. package/tools/satellite-locator.mjs +3 -2
  119. package/tools/script-priors.mjs +3 -2
  120. package/tools/session-close-check.mjs +71 -15
  121. package/tools/set-flow.mjs +2 -2
  122. package/tools/set-recipe.mjs +17 -9
  123. package/tools/source-size/help.mjs +4 -4
  124. package/tools/source-size/layout.mjs +2 -1
  125. package/tools/source-size/piles.mjs +2 -2
  126. package/tools/source-size-config.mjs +3 -3
  127. package/tools/source-size-refusal.mjs +4 -3
  128. package/tools/source-size-report.mjs +41 -13
  129. package/tools/spec-check-cli.mjs +159 -21
  130. package/tools/spec-check-ops.mjs +74 -5
  131. package/tools/spec-check.mjs +54 -45
  132. package/tools/spec-coverage-cli.mjs +3 -2
  133. package/tools/stage-render/cli.mjs +231 -0
  134. package/tools/stage-render/index.mjs +340 -0
  135. package/tools/stage-render/stages.json +115 -0
  136. package/tools/stage-write-guard/cli.mjs +64 -0
  137. package/tools/stage-write-guard/index.mjs +56 -0
  138. package/tools/state-block-hook.mjs +38 -163
  139. package/tools/task-brief.mjs +8 -13
  140. package/tools/task-thread.mjs +3 -1
  141. package/tools/tier-guide-facts.mjs +23 -9
  142. package/tools/tier-preview.mjs +15 -19
  143. package/tools/transition/index.mjs +10 -9
  144. package/tools/uninstall.mjs +26 -12
  145. package/tools/vehicle-settings.mjs +2 -1
  146. package/tools/velocity-profile.mjs +5 -6
  147. package/tools/view-model.mjs +7 -4
  148. package/tools/worktree-prompt.mjs +7 -3
  149. package/tools/worktrees.mjs +235 -159
  150. package/tools/write-lanes.mjs +20 -14
@@ -4,7 +4,7 @@
4
4
  import { readFileSync, realpathSync, writeFileSync } from 'node:fs';
5
5
  import { spawnSync } from 'node:child_process';
6
6
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
7
- import { fail } from '../references/scripts/shared/index.mjs';
7
+ import { fail, GATES } from '../references/scripts/shared/index.mjs';
8
8
  import { isDirectRun } from './direct-run.mjs';
9
9
  import { readFileBytesNoFollowCapped } from './fs-read-nofollow.mjs';
10
10
  import { GIT_MAX_BUFFER, resolveGitLocation, stripGitLocationEnv, withGitPath } from './git-env.mjs';
@@ -13,7 +13,6 @@ import { judgeAnchors, parseRecord, ratchetLine, REFUSALS, renderExcerpts, rende
13
13
 
14
14
  const RECORD_MAX_BYTES = 1024 * 1024;
15
15
  export const EXCERPTS_FRAMING_RESERVE_BYTES = 4096;
16
- const GATES_REL = 'docs/ai/gates.json';
17
16
  const QUEUE_GATE_TOKEN = 'queue-audit-cli.mjs';
18
17
  const MODE_FLAGS = Object.freeze(['--check', '--rows']);
19
18
  const FATAL_PARSE_REFUSALS = Object.freeze(REFUSALS.slice(0, 4));
@@ -217,13 +216,13 @@ const inspectGit = ({ cwd, env, spawn, head, headLine, anchors }) => {
217
216
  };
218
217
 
219
218
  const readRatchet = (cwd, rows) => {
220
- const path = join(cwd, GATES_REL);
219
+ const path = join(cwd, GATES);
221
220
  const parsed = (() => {
222
221
  try { return { value: JSON.parse(readFileSync(path, 'utf8')), error: null }; }
223
222
  catch (err) { return { value: null, error: err }; }
224
223
  })();
225
- if (parsed.error?.code === 'ENOENT') return `ratchet: ${GATES_REL} is absent`;
226
- if (parsed.error) return `ratchet: ${GATES_REL} cannot be read (${parsed.error.message})`;
224
+ if (parsed.error?.code === 'ENOENT') return `ratchet: ${GATES} is absent`;
225
+ if (parsed.error) return `ratchet: ${GATES} cannot be read (${parsed.error.message})`;
227
226
  const gate = Array.isArray(parsed.value?.gates)
228
227
  ? parsed.value.gates.find((entry) => typeof entry?.cmd === 'string' && entry.cmd.includes(QUEUE_GATE_TOKEN))
229
228
  : null;
@@ -50,6 +50,7 @@ import { readFileSync, lstatSync, realpathSync } from 'node:fs';
50
50
  import { join, dirname, resolve, isAbsolute, sep } from 'node:path';
51
51
  import { fileURLToPath } from 'node:url';
52
52
  import { createHash, randomBytes } from 'node:crypto';
53
+ import { PLANS } from '../references/scripts/shared/index.mjs';
53
54
  import {
54
55
  FLOW_SCHEMA_VERSION, CHAIN_KIND, canonicalFlowDigest, flowTreeIdentity,
55
56
  SAFE_NONCE_RE, findingManifestBasename, decodeFindingManifest,
@@ -73,17 +74,16 @@ import { loadConfig } from './orchestration-config.mjs';
73
74
  import { computePlanAdoptionCoverage, plansInFlight, quoteReportName } from './review-state.mjs';
74
75
  import { writeContainedFileAtomic, lstatNoFollow } from './atomic-write.mjs';
75
76
  import { readFileBytesNoFollowCapped } from './fs-read-nofollow.mjs';
76
- import { readShippedRobustnessLiterals } from './robustness-literals.mjs';
77
+ import { classIds, readShippedRobustnessLiterals } from './robustness-literals.mjs';
77
78
  import { expandSweepPaths } from './plan-shape-facts.mjs';
78
- import { checkPlanStructure, isSweep } from './plan-shape.mjs';
79
+ import { RETIRED_FORM_CODES, checkPlanStructure, isSweep, unique } from './plan-shape.mjs';
79
80
  import { escapeForDisplay } from './repo-lex.mjs';
80
- import { computeRowCoverage, isCoverageDocument } from './robustness-brief.mjs';
81
+ import { computeRowCoverage, isCoverageDocument, ROBUST_CLASS_CODE } from './robustness-brief.mjs';
81
82
  import { decideFoldScope, findDebtRow, normalize } from './fold-scope.mjs';
82
83
  import { capIssue, walkIssue, escalationIssue, findingQuoted, validateWalk } from './flow-round-gates.mjs';
83
84
  const usageFail = (message) => Object.assign(new Error(message), { exitCode: 2 });
84
85
  const refuse = (message) => Object.assign(new Error(message), { exitCode: 1 });
85
86
 
86
- const PLANS_DIR = 'docs/plans';
87
87
  const HEX64_RE = /^[0-9a-f]{64}$/;
88
88
  const PLAN_READ_CAP = 1_048_576;
89
89
  const WALK_READ_CAP = 65_536;
@@ -391,7 +391,7 @@ const decodeUtf8 = (bytes, label, stop = refuse) => {
391
391
  }
392
392
  };
393
393
  const readBoundPlan = (root, plan, adoption) => {
394
- const path = join(root, PLANS_DIR, plan);
394
+ const path = join(root, PLANS, plan);
395
395
  const read = readFileBytesNoFollowCapped(path, PLAN_READ_CAP);
396
396
  if (read.outcome !== 'ok') throw refuse(`the adopted plan ${plan} is not a readable regular file (${read.className ?? read.code ?? read.outcome})`);
397
397
  if (sha256(read.bytes) !== adoption.planDigest) throw refuse(`the adopted plan ${plan} no longer matches its adoption record`);
@@ -686,7 +686,6 @@ const terminalMoveIssue = ({ flowRecords, chain, cycle, stepId, tree, cwd }) =>
686
686
  // receipts-file byte-length watermark, a fresh nonce}; receipt/manifest digests stay null until
687
687
  // round-land. A boundary invocation opens the step (opensFrom = the chain's prior terminal); an
688
688
  // in-step invocation opens the NEXT round (a fingerprint move never rides a revision).
689
- const walkObligation = (planText) => checkPlanStructure(planText, {}).parsed.rows.some((row) => row.valid);
690
689
  const buildRoundOpen = ({ planId, stepId, backends, newCycle, justification, cwd, env, timestamp }) => {
691
690
  // The backend list is judged BEFORE any store read — a usage-shaped input never surfaces as a
692
691
  // state-dependent refusal.
@@ -701,7 +700,18 @@ const buildRoundOpen = ({ planId, stepId, backends, newCycle, justification, cwd
701
700
  const { chain, state, commitEpoch } = chainContext(records, planId, tree.owner);
702
701
  const root = gitLine(['rev-parse', '--show-toplevel'], cwd) ?? cwd;
703
702
  const adopted = resolveAdoptedPlan({ root, records, planId, owner: tree.owner, arm: 'round-open' });
704
- const walkRequired = walkObligation(adopted.planText);
703
+ const { parsed, findings } = checkPlanStructure(adopted.planText, {});
704
+ if (parsed === null) {
705
+ const [finding] = findings;
706
+ throw refuse(`round-open cannot judge the adopted plan: ${finding.code}: ${escapeForDisplay(finding.message)}`);
707
+ }
708
+ const retiredSizeField = findings.find(({ code }) => code === RETIRED_FORM_CODES.sizeField);
709
+ const walkRequired = retiredSizeField !== undefined || parsed.rows.some(({ valid }) => valid);
710
+ const getMissingWalk = (records) => {
711
+ if (!walkRequired) return null;
712
+ const issue = walkIssue({ records, planId, cycle: target.cycle, stepId: target.stepId, round: target.round, base: tree.base, fingerprint: tree.fingerprint });
713
+ return issue && retiredSizeField ? `${issue}; adopted plan: ${retiredSizeField.code} — the walk option above is unavailable for these adopted bytes, and editing them invalidates the adoption digest. Retry round-open with --justification <text>` : issue;
714
+ };
705
715
  const inStep = state.mode === 'in-step' && !state.parked && !state.completed;
706
716
  if (newCycle && inStep) throw usageFail('--new-cycle opens at a step boundary only — an open step continues through its own rounds');
707
717
  // The in-step guard re-runs on the LOCKED snapshot too (M6) — this closure is the preflight.
@@ -714,7 +724,7 @@ const buildRoundOpen = ({ planId, stepId, backends, newCycle, justification, cwd
714
724
  const lockedReadManifest = (backend, nonce) => readManifestDecoded({ receiptsPath: lockedReceipts.path, backend, nonce });
715
725
  const lockedCap = capIssue({ heads: stepRoundHeads(lockedChain, target.cycle, target.stepId), receipts: lockedReceiptMap, readManifest: lockedReadManifest });
716
726
  if (lockedCap.issue != null) throw refuse([...lockedCap.advisories, lockedCap.issue].join('\n'));
717
- const lockedMissingWalk = walkRequired ? walkIssue({ records: flowRecords, planId, cycle: target.cycle, stepId: target.stepId, round: target.round, base: tree.base, fingerprint: tree.fingerprint }) : null;
727
+ const lockedMissingWalk = getMissingWalk(flowRecords);
718
728
  if (lockedMissingWalk != null && recordedJustification == null) throw refuse(lockedMissingWalk);
719
729
  if (lockedMissingWalk == null && missingWalk != null && !roundOverCap && !valveOverCap) {
720
730
  gateCapJustification({ justification, overCap: false, refusal: null });
@@ -751,7 +761,7 @@ const buildRoundOpen = ({ planId, stepId, backends, newCycle, justification, cwd
751
761
  const readManifest = (backend, nonce) => readManifestDecoded({ receiptsPath, backend, nonce });
752
762
  const cap = capIssue({ heads: stepRoundHeads(chain, target.cycle, target.stepId), receipts: receiptMap, readManifest });
753
763
  if (cap.issue != null) throw refuse([...cap.advisories, cap.issue].join('\n'));
754
- const missingWalk = walkRequired ? walkIssue({ records, planId, cycle: target.cycle, stepId: target.stepId, round: target.round, base: tree.base, fingerprint: tree.fingerprint }) : null;
764
+ const missingWalk = getMissingWalk(records);
755
765
  const recordedJustification = gateCapJustification({
756
766
  justification,
757
767
  overCap: roundOverCap || valveOverCap || missingWalk != null,
@@ -1032,9 +1042,10 @@ const buildInternalAttestation = ({ planId, lenses, degraded, model, effort, tie
1032
1042
  throw refuse(`internal-attestation refuses (#68): ${uncovered.map((p) => `plan ${quoteReportName(p.plan)} — ${p.reason}`).join('; ')} — an uncovered in-flight plan is a refusal, never a relaxation`);
1033
1043
  }
1034
1044
  const checkedWalk = walk === undefined ? undefined : (() => {
1035
- const shape = checkPlanStructure(adopted.planText, {});
1036
1045
  const list = readShippedRobustnessLiterals();
1037
- if (shape.findings.length > 0) throw usageFail('--walk cannot measure an adopted plan that fails structural validation');
1046
+ const shape = checkPlanStructure(adopted.planText, { robustClasses: classIds(list) });
1047
+ const blockers = unique(shape.findings.map(({ code }) => code).filter((code) => code !== ROBUST_CLASS_CODE));
1048
+ if (blockers.length > 0) throw usageFail(`--walk cannot measure an adopted plan that fails structural validation: ${blockers.join(', ')}`);
1038
1049
  const patterns = shape.parsed.rows.filter((row) => row.valid && isSweep(row.path) && !isCoverageDocument(row.path)).map((row) => row.path);
1039
1050
  const expansions = patterns.length === 0 ? {} : expandSweepPaths(root, patterns);
1040
1051
  const measured = computeRowCoverage(adopted.planText, list, { expandRowPath: (path) => expansions[path] ?? [],
@@ -1087,9 +1098,9 @@ const writePlanId = ({ planPath, planId, cwd, ctx }) => {
1087
1098
  // lexicalRepoRelative NORMALIZES interior dot segments — a "docs/plans/../…" spelling would pass
1088
1099
  // a raw prefix check while resolving outside the plans dir, so segments are refused explicitly.
1089
1100
  if (planPath.split('/').some((s) => s === '..' || s === '.' || s === '')) {
1090
- throw refuse(`the plan path must be a plain forward-slash path without "." or ".." segments (got "${planPath}") — write-plan-id is bounded to ${PLANS_DIR}/ lexically`);
1101
+ throw refuse(`the plan path must be a plain forward-slash path without "." or ".." segments (got "${planPath}") — write-plan-id is bounded to ${PLANS}/ lexically`);
1091
1102
  }
1092
- if (!planPath.startsWith(`${PLANS_DIR}/`)) throw refuse(`the plan path must live under ${PLANS_DIR}/ (got "${planPath}") — write-plan-id is bounded to the plans dir`);
1103
+ if (!planPath.startsWith(`${PLANS}/`)) throw refuse(`the plan path must live under ${PLANS}/ (got "${planPath}") — write-plan-id is bounded to the plans dir`);
1093
1104
  const full = join(cwd, planPath);
1094
1105
  const lstat = ctx.lstatSync ?? lstatSync;
1095
1106
  const st = lstatNoFollow(full, lstat);
@@ -1112,7 +1123,7 @@ const writePlanId = ({ planPath, planId, cwd, ctx }) => {
1112
1123
  throw refuse(`${planPath} already carries planId "${existing}" — a DIFFERENT id refuses: chain identity never silently changes (#58)`);
1113
1124
  }
1114
1125
  const next = composePlanIdFrontmatter(text, planId);
1115
- writeContainedFileAtomic(join(cwd, PLANS_DIR), full, next, ctx, { stop: refuse, label: planPath });
1126
+ writeContainedFileAtomic(join(cwd, PLANS), full, next, ctx, { stop: refuse, label: planPath });
1116
1127
  return { noop: false, message: `wrote planId "${planId}" into ${planPath} (contained-atomic); the adoption mint reads exactly this frontmatter line` };
1117
1128
  };
1118
1129
 
@@ -1154,7 +1165,7 @@ Every arm computes its tree context (owner, base, fingerprint; cycle/round from
1154
1165
  and appends through the lock-serialized store append — an illegal transition surfaces the store's
1155
1166
  own refusal verbatim; the writer adds NO second validator. Chain arms refuse a foreign worktree's
1156
1167
  chain (#57). maintainer-override prints its FULL bound set and requires --checkpoint-approved
1157
- (#38). write-plan-id is bounded to an existing regular file under ${PLANS_DIR}/ (same-id
1168
+ (#38). write-plan-id is bounded to an existing regular file under ${PLANS}/ (same-id
1158
1169
  idempotent, different-id refuses, contained-atomic; #58).
1159
1170
 
1160
1171
  The round lifecycle (Plan 4 Phase 3): ONE record per round, revised in place — round-open mints
@@ -40,6 +40,7 @@
40
40
  import { constants as fsConstants, existsSync, lstatSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
41
41
  import { dirname, join, resolve } from 'node:path';
42
42
  import { fileURLToPath } from 'node:url';
43
+ import { GATE_HOOK, HOOKS_DIR, LANES } from '../references/scripts/shared/index.mjs';
43
44
  import {
44
45
  CLAUDE_DIR,
45
46
  EXPECTED_WORKFLOW_VERSION,
@@ -62,13 +63,13 @@ export const GATE_HOOK_TOOL = fileURLToPath(import.meta.url);
62
63
  const q = shellQuoteArg;
63
64
 
64
65
  export const BUNDLED_HOOK_PATH = resolve(HERE, '..', 'references', 'hooks', 'gate-approve.mjs');
65
- export const HOOKS_DIR = '.claude/hooks';
66
- export const HOOK_FILE_REL = `${HOOKS_DIR}/agent-workflow-gates.mjs`;
66
+ export { HOOKS_DIR } from '../references/scripts/shared/index.mjs';
67
+ export const HOOK_FILE_REL = GATE_HOOK;
67
68
  export const PRE_TOOL_USE_EVENT = 'PreToolUse';
68
69
  export const HOOK_MATCHER = 'Bash';
69
- // The literal settings fragment (the plan/test fixture): $CLAUDE_PROJECT_DIR is resolved by
70
+ // The settings fragment (the plan/test fixture): $CLAUDE_PROJECT_DIR is resolved by
70
71
  // Claude Code when it runs the hook command, so the entry survives project relocation.
71
- export const HOOK_COMMAND = 'node "$CLAUDE_PROJECT_DIR/.claude/hooks/agent-workflow-gates.mjs"';
72
+ export const HOOK_COMMAND = `node "$CLAUDE_PROJECT_DIR/${HOOK_FILE_REL}"`;
72
73
  export const HOOK_TIMEOUT_SECONDS = 30;
73
74
 
74
75
  export const GATE_HOOK_STAMP = 'GATE_HOOK_STAMP';
@@ -78,7 +79,7 @@ export const GATE_HOOK_MALFORMED = 'GATE_HOOK_MALFORMED';
78
79
  export const GATE_HOOK_DIVERGED = 'GATE_HOOK_DIVERGED';
79
80
  export const GATE_HOOK_BUNDLE = 'GATE_HOOK_BUNDLE';
80
81
  // --read-lane (AD-055 Part II): the opt-in read-only compound lane toggle + its currency guard.
81
- export const LANES_REL = 'docs/ai/lanes.json';
82
+ export const LANES_REL = LANES;
82
83
  export const READ_LANE_KEY = 'readLane';
83
84
  export const GATE_HOOK_STALE = 'GATE_HOOK_STALE'; // the placed hook is absent/stale — the lane cannot fire
84
85
  export const GATE_HOOK_LANE = 'GATE_HOOK_LANE'; // a lanes.json write refusal (deployment/malformed)
@@ -93,6 +94,8 @@ const ERROR_PREFIX = '[agent-workflow-kit]';
93
94
  const SETTINGS_JSON_INDENT = 2;
94
95
  const JSON_NEWLINE_PATTERN = /\n/gu;
95
96
 
97
+ const GATE_HOOK_BYPASS_REASON = 'refusing because it auto-approves Bash';
98
+
96
99
  const TARGET_PLACE = 'place';
97
100
  const TARGET_CURRENT = 'already-current';
98
101
  const TARGET_DIVERGED = 'diverged';
@@ -191,6 +194,28 @@ export const assertDirSafe = (absPath, relPath, fs) => {
191
194
  if (!stat.isDirectory()) throw makeGateHookError(GATE_HOOK_SYMLINK, `${relPath} exists but is not a directory — refusing to write through it`);
192
195
  };
193
196
 
197
+ export const assertSafeModes = (projectData, localData, bypassReason) => {
198
+ const { bypassPermissionsPresent, unsafeModePresent } = resolveEffectiveMode(projectData, localData);
199
+ if (bypassPermissionsPresent) {
200
+ throw makeGateHookError(GATE_HOOK_UNSAFE_MODE, `${UNSAFE_BYPASS_MODE} appears in Claude settings - ${bypassReason}`);
201
+ }
202
+ if (unsafeModePresent) {
203
+ throw makeGateHookError(
204
+ GATE_HOOK_UNSAFE_MODE,
205
+ `an unsafe or unknown permissions.defaultMode is present in Claude settings - accepted modes: ${SAFE_DEFAULT_MODES.join(', ')}`,
206
+ );
207
+ }
208
+ };
209
+
210
+ export const assertStampCurrent = (stamp) => {
211
+ if (stamp !== EXPECTED_WORKFLOW_VERSION) {
212
+ throw makeGateHookError(
213
+ GATE_HOOK_STAMP,
214
+ `not a deployed agent-workflow project at lineage ${EXPECTED_WORKFLOW_VERSION} (found ${stamp ?? 'none'}) — run init/upgrade first`,
215
+ );
216
+ }
217
+ };
218
+
194
219
  export const assertSettingsWritable = (absPath, fs) => {
195
220
  const stat = lstatNoFollow(absPath, fs);
196
221
  if (stat !== null && !stat.isFile()) {
@@ -276,17 +301,7 @@ export const preflightGateHook = ({ cwd }, deps = {}) => {
276
301
  assertSettingsWritable(join(projectDir, SETTINGS_FILE), fs);
277
302
  const projectSettings = readSettingsFile(join(projectDir, SETTINGS_FILE), { ...deps, cwd: projectDir });
278
303
  const localSettings = readSettingsFile(join(projectDir, SETTINGS_LOCAL_FILE), { ...deps, cwd: projectDir });
279
- const { bypassPermissionsPresent, unsafeModePresent } = resolveEffectiveMode(projectSettings.data, localSettings.data);
280
-
281
- if (bypassPermissionsPresent) {
282
- throw makeGateHookError(GATE_HOOK_UNSAFE_MODE, `${UNSAFE_BYPASS_MODE} appears in Claude settings - refusing because it auto-approves Bash`);
283
- }
284
- if (unsafeModePresent) {
285
- throw makeGateHookError(
286
- GATE_HOOK_UNSAFE_MODE,
287
- `an unsafe or unknown permissions.defaultMode is present in Claude settings - accepted modes: ${SAFE_DEFAULT_MODES.join(', ')}`,
288
- );
289
- }
304
+ assertSafeModes(projectSettings.data, localSettings.data, GATE_HOOK_BYPASS_REASON);
290
305
  assertHooksShape(projectSettings.data, SETTINGS_FILE);
291
306
 
292
307
  const wiredInProject = isHookWired(projectSettings.data);
@@ -308,12 +323,7 @@ export const writeGateHook = ({ cwd, dryRun = true } = {}, deps = {}) => {
308
323
  const base = { placePlanned, replacePlanned, wirePlanned, ...preflight };
309
324
  if (dryRun) return { wrote: false, dryRun: true, ...base };
310
325
 
311
- if (!preflight.stampOk) {
312
- throw makeGateHookError(
313
- GATE_HOOK_STAMP,
314
- `not a deployed agent-workflow project at lineage ${EXPECTED_WORKFLOW_VERSION} (found ${preflight.stamp ?? 'none'}) — run init/upgrade first`,
315
- );
316
- }
326
+ assertStampCurrent(preflight.stamp);
317
327
 
318
328
  // Place FIRST, then wire — a wired-but-missing hook would error on every Bash call.
319
329
  const hookAbs = join(preflight.projectDir, HOOK_FILE_REL);
@@ -455,12 +465,7 @@ export const writeReadLane = ({ cwd, dryRun = true } = {}, deps = {}) => {
455
465
  `${HOOK_FILE_REL} is placed and current but NOT wired into ${SETTINGS_FILE} — the read-lane cannot fire. Wire it first:\n ${applyGateHookCommand(plan.root)}\nthen re-run with --read-lane.`,
456
466
  );
457
467
  }
458
- if (!stampOk) {
459
- throw makeGateHookError(
460
- GATE_HOOK_STAMP,
461
- `not a deployed agent-workflow project at lineage ${EXPECTED_WORKFLOW_VERSION} (found ${stamp ?? 'none'}) — run init/upgrade first`,
462
- );
463
- }
468
+ assertStampCurrent(stamp);
464
469
  if (plan.already) return { wrote: false, dryRun: false, currency, wired, stamp, stampOk, ...plan };
465
470
  const body = `${JSON.stringify(plan.merged, null, SETTINGS_JSON_INDENT)}\n`;
466
471
  writeDocsAiFileAtomic(plan.root, LANES_REL, body, deps, { stop: laneStop, noun: 'the read-lane toggle' });
@@ -9,6 +9,7 @@
9
9
  import { readFileSync, lstatSync, realpathSync } from 'node:fs';
10
10
  import { join, isAbsolute } from 'node:path';
11
11
  import { fileURLToPath } from 'node:url';
12
+ import { GATES } from '../references/scripts/shared/index.mjs';
12
13
  import { CHECKER_CLAIM, checkerClaimTool, classifyCheckerClaim } from './checker-claim.mjs';
13
14
  import { fail, loadConfig, CONFIG_REL } from './orchestration-config.mjs';
14
15
  import { readsAsCoverageProducer, retiredProducerFormOf } from './coverage-producer.mjs';
@@ -16,7 +17,7 @@ import { matchesSourceSizeGate } from './source-size-core.mjs';
16
17
 
17
18
  // The per-project declaration (strict JSON, hand-editable). cwd-relative — errors show a path the
18
19
  // user can open (the orchestration-config CONFIG_REL idiom).
19
- export const GATES_REL = 'docs/ai/gates.json';
20
+ export const GATES_REL = GATES;
20
21
 
21
22
  // Parity: run-gates.mjs EXIT.malformed — its exit-code table stays the CLI authority (pinned by
22
23
  // run-gates.test.mjs); this module throws the same tagged shape so the CLI surfaces it unchanged.
@@ -61,6 +61,7 @@
61
61
  import { existsSync, lstatSync, readFileSync } from 'node:fs';
62
62
  import { join, resolve, dirname } from 'node:path';
63
63
  import { fileURLToPath } from 'node:url';
64
+ import { PACKAGE_JSON, PNPM_LOCK, WORKFLOW_STAMP, YARN_LOCK } from '../references/scripts/shared/index.mjs';
64
65
  import { isDirectRun } from './direct-run.mjs';
65
66
  import { discoverGateCandidates, EXPECTED_WORKFLOW_VERSION } from './velocity-profile.mjs';
66
67
  import { GATES_REL, validateDeclaration } from './run-gates.mjs';
@@ -85,7 +86,7 @@ const TEMPLATE_PATH = join(KIT_ROOT, 'references', 'templates', 'gates.json');
85
86
  const REVIEW_STATE_TOOL = join(KIT_ROOT, 'tools', 'review-state.mjs');
86
87
  const COVERAGE_CHECK_TOOL = join(KIT_ROOT, 'tools', 'coverage-check.mjs');
87
88
  const FLOW_CHECK_TOOL = join(KIT_ROOT, 'tools', 'flow-check.mjs');
88
- const STAMP_REL = join('docs', 'ai', '.workflow-version');
89
+ const STAMP_REL = join(WORKFLOW_STAMP);
89
90
 
90
91
  const EXIT_OK = 0;
91
92
  const EXIT_PRECONDITION = 1;
@@ -246,7 +247,7 @@ export const detectPackageManager = (cwd, deps = {}) => {
246
247
  const exists = deps.exists ?? existsSync;
247
248
  const fromField = (() => {
248
249
  try {
249
- const pkg = JSON.parse(String(read(join(cwd, 'package.json'), 'utf8')));
250
+ const pkg = JSON.parse(String(read(join(cwd, PACKAGE_JSON), 'utf8')));
250
251
  const pm = typeof pkg.packageManager === 'string' ? pkg.packageManager.split('@')[0] : null;
251
252
  return pm === 'pnpm' || pm === 'yarn' || pm === 'npm' ? pm : null;
252
253
  } catch {
@@ -254,8 +255,8 @@ export const detectPackageManager = (cwd, deps = {}) => {
254
255
  }
255
256
  })();
256
257
  if (fromField) return fromField;
257
- if (exists(join(cwd, 'pnpm-lock.yaml'))) return 'pnpm';
258
- if (exists(join(cwd, 'yarn.lock'))) return 'yarn';
258
+ if (exists(join(cwd, PNPM_LOCK))) return 'pnpm';
259
+ if (exists(join(cwd, YARN_LOCK))) return 'yarn';
259
260
  return 'npm';
260
261
  };
261
262
 
@@ -267,7 +268,7 @@ const deriveScripts = (cwd, deps = {}) => {
267
268
  const read = deps.readFile ?? readFileSync;
268
269
  const pkg = (() => {
269
270
  try {
270
- return JSON.parse(String(read(join(cwd, 'package.json'), 'utf8')));
271
+ return JSON.parse(String(read(join(cwd, PACKAGE_JSON), 'utf8')));
271
272
  } catch {
272
273
  return null; // no/unreadable package.json → no script candidates (an honest empty offer)
273
274
  }
@@ -2,19 +2,21 @@
2
2
  // git-hooks.mjs — the thin writer of the three git-hook items (`enforcement`, `commit-guard`,
3
3
  // `hook-checks`): it copies the deployed scripts create-only into the kit folder and spawns the project's
4
4
  // own installer (INSTALLER_REL) as it stands, which decides the hook at the write. The leaf
5
- // decides nothing about the hook: the danger check binds the copies and the installer bytes this dry run
5
+ // decides nothing about the hook: the danger check binds the deployed set 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.
8
8
  import { lstatSync, readFileSync, readdirSync, rmdirSync, statSync, unlinkSync } from 'node:fs';
9
9
  import { createHash } from 'node:crypto';
10
10
  import { spawnSync } from 'node:child_process';
11
- import { dirname, join, resolve } from 'node:path';
11
+ import { dirname, join, posix, resolve } from 'node:path';
12
12
  import { fileURLToPath } from 'node:url';
13
13
  import { writeProjectFileCreateOnly } from './atomic-write.mjs';
14
+ import { bundledImportsOf, dependenciesFirst } from './ensure-ops.mjs';
14
15
  import { readDeployedScripts, INSTALLER_REL, readNodeEvidenceScripts, SCRIPTS_DIR } from './node-evidence.mjs';
15
- import { shellQuoteArg } from './repo-lex.mjs';
16
+ import { escapeRegExp, shellQuoteArg } from './repo-lex.mjs';
16
17
  import { GIT_MAX_BUFFER } from './git-env.mjs';
17
- import { KIT_COMMAND_PATH, KIT_COMMANDS } from '../references/scripts/run.mjs';
18
+ import { KIT_COMMANDS } from '../references/scripts/run.mjs';
19
+ import { KIT_COMMAND, KIT_FOLDER } from '../references/scripts/shared/index.mjs';
18
20
  import { isDirectRun } from './direct-run.mjs';
19
21
  import { checkRules } from './project-rules/index.mjs';
20
22
  import { readLayoutSetup } from './source-size-core.mjs';
@@ -29,6 +31,7 @@ const EXIT_USAGE = 2;
29
31
  const EXIT_REFUSED = 3;
30
32
  const VARIANTS = ['enforcement', 'commit-guard', 'hook-checks'];
31
33
  const USAGE = 'usage: git-hooks (--enforcement | --commit-guard | --hook-checks) [--cwd <root>] [--apply]';
34
+ const ABSENT_RUN_ENTRY = '-:';
32
35
  const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
33
36
  const usageError = (message) => Object.assign(new Error(message), { exitCode: EXIT_USAGE });
34
37
  const refusal = (message) => Object.assign(new Error(message), { exitCode: EXIT_REFUSED });
@@ -64,10 +67,9 @@ export const resolveGitHooksPath = (projectDir, env = process.env) => {
64
67
  };
65
68
 
66
69
  export const INSTALLER_MARKER_RE = /:install-git-hooks\.mjs\r?$/m;
67
- const escapeRe = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
68
- const COMMAND_LINE_RE = new RegExp(`^node ${escapeRe(KIT_COMMAND_PATH)} docs-size\\r?$`, 'm');
70
+ const COMMAND_LINE_RE = new RegExp(`^node ${escapeRegExp(KIT_COMMAND)} docs-size\\r?$`, 'm');
69
71
  // Armed means the exact line the installer writes on the kit's own guard path; a commented or lookalike line is not.
70
- export const canonicalGuardLineRe = (toolsDir = TOOLS) => new RegExp(`^node "${escapeRe(join(toolsDir, 'commit-guard.mjs'))}" --check$`, 'm');
72
+ export const canonicalGuardLineRe = (toolsDir = TOOLS) => new RegExp(`^node "${escapeRegExp(join(toolsDir, 'commit-guard.mjs'))}" --check$`, 'm');
71
73
 
72
74
  // The one safe shell representation of an armed path, the installer's rule: on win32 its separators
73
75
  // made `/`; null when a byte would not name the file inside the hook's double quotes.
@@ -83,7 +85,7 @@ const ROLES = Object.freeze([
83
85
  ]);
84
86
  const roleLineRe = ({ role, tool }, toolsDir, platform) => {
85
87
  const path = safeHookPath(tool(toolsDir), platform);
86
- return path === null ? /(?!)/ : new RegExp(`^node "${escapeRe(path)}" --check # ${role}$`, 'm');
88
+ return path === null ? /(?!)/ : new RegExp(`^node "${escapeRegExp(path)}" --check # ${role}$`, 'm');
87
89
  };
88
90
  export const canonicalRulesLineRe = (toolsDir = TOOLS, platform = process.platform) => roleLineRe(ROLES[0], toolsDir, platform);
89
91
  export const canonicalLayoutLineRe = (toolsDir = TOOLS, platform = process.platform) => roleLineRe(ROLES[1], toolsDir, platform);
@@ -114,9 +116,13 @@ export const readPreCommitState = (root, deps = {}) => {
114
116
  command: COMMAND_LINE_RE.test(hook), ...roleStates(hook, deps.toolsDir ?? TOOLS, deps.platform) };
115
117
  };
116
118
 
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)));
119
+ const findMissingHookCommandFile = (root, isPresent) => {
120
+ const missing = [INSTALLER_REL, KIT_COMMAND, ...Object.values(KIT_COMMANDS).map((target) => posix.join(KIT_FOLDER, target))]
121
+ .find((rel) => !isPresent(rel));
122
+ return missing === undefined ? undefined : join(root, missing);
123
+ };
124
+ export const missingHookCommandFile = (root, deps = {}) => findMissingHookCommandFile(root,
125
+ (rel) => isFile(nodeAt(join(root, rel), deps.lstat ?? lstatSync)));
120
126
 
121
127
  // The two read-only answers the hook-checks dry run and the advisor's probe ask, on the tree on disk.
122
128
  export const hookCheckAnswers = (root, deps = {}) => {
@@ -138,15 +144,14 @@ export const unsafeToolsPath = (toolsDir, platform) => (ROLES.some(({ tool }) =>
138
144
  ? `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);
139
145
 
140
146
  // hook-checks: the lines it arms, from the two answers and the hook; the installer runs as it stands.
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`);
147
+ const planHookChecks = ({ root, toolsDir, isPresent, deps }) => {
143
148
  const unsafe = unsafeToolsPath(toolsDir, deps.platform);
144
149
  if (unsafe !== null) throw refusal(unsafe);
145
150
  const hook = readPreCommitState(root, { toolsDir, platform: deps.platform, gitHooksPath: deps.gitHooksPath });
146
151
  if (hook.state === 'unreadable') throw refusal(`${hook.path} is unreadable (${hook.code}) — the pre-commit hook cannot be judged`);
147
152
  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
153
  const switchCommand = hook.state === 'managed' && !hook.command;
149
- const missing = switchCommand ? missingHookCommandFile(root, { lstat }) : undefined;
154
+ const missing = switchCommand ? findMissingHookCommandFile(root, isPresent) : undefined;
150
155
  if (missing) throw refusal(`${missing} is not a regular file — re-run /agent-workflow-kit upgrade, then apply this item again`);
151
156
  const answers = hookCheckAnswers(root, deps);
152
157
  const roles = plannedRoles(answers, hook);
@@ -154,50 +159,68 @@ const planHookChecks = ({ root, toolsDir, installer, installerNode, lstat, readF
154
159
  throw refusal(`nothing to plan — ${ROLES.map(({ key, role }) => `the ${role} line: ${hook[`${key}Armed`] ? 'armed' : `not armable (${answers[key].why})`}`).join('; ')}`);
155
160
  }
156
161
  const flags = roles.flatMap(({ flag, tool }) => [flag, tool(toolsDir)]);
157
- return { root, variant: 'hook-checks', folders: [], copies: [], switchCommand, roles: roles.map(({ key }) => key),
158
- runs: { argv: ['node', installer, ...flags], shown: ['node', INSTALLER_REL, ...flags], bytes: readFile(installer) } };
162
+ return { switchCommand, roles: roles.map(({ key }) => key), flags };
163
+ };
164
+
165
+ const probePath = (path, lstat, isKind, kind, read = () => true) => {
166
+ try {
167
+ const node = nodeAt(path, lstat);
168
+ if (node === null) return null;
169
+ if (isKind(node)) return read(path);
170
+ } catch (error) {
171
+ throw refusal(`${path} is unreadable (${error?.code ?? String(error)})`);
172
+ }
173
+ throw refusal(`${path} is not ${kind}`);
159
174
  };
160
175
 
161
176
  // The dry run: what the apply copies and the installer it runs, with the bytes of each.
162
177
  export const planGitHooks = ({ root, variant, toolsDir = TOOLS, lstat = lstatSync, readFile = readFileSync, ...deps }) => {
163
178
  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 ? readDeployedScripts().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');
179
+ const entries = readDeployedScripts();
180
+ const folders = new Map();
181
+ const deployedBytes = new Map();
182
+ const beneathAbsent = (rel) => foldersOf(rel).some((folder) => folders.get(folder) === null);
183
+ for (const { deployed: rel } of entries) {
184
+ for (const folder of foldersOf(rel)) {
185
+ if (!folders.has(folder)) folders.set(folder, beneathAbsent(folder) ? null : probePath(join(root, folder), lstat, isPlainDir, 'a plain directory'));
186
+ }
187
+ deployedBytes.set(rel, beneathAbsent(rel) ? null : probePath(join(root, rel), lstat, isFile, 'a regular file', readFile));
178
188
  }
179
189
  const installer = join(root, INSTALLER_REL);
180
- if (variant === 'hook-checks') return planHookChecks({ root, toolsDir, installer, installerNode: nodes.get(INSTALLER_REL), lstat, readFile, deps });
190
+ const isPresent = (rel) => deployedBytes.has(rel) && deployedBytes.get(rel) !== null;
181
191
  // 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 && readNodeEvidenceScripts().some((name) => evidence(`${SCRIPTS_REL}/${name}`));
184
- const copies = enforcing && !deployed ? readDeployedScripts().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`);
192
+ const evidence = (rel) => (deployedBytes.has(rel) ? isPresent(rel) : folders.get(SCRIPTS_REL) !== null && isFile(nodeAt(join(root, rel), lstat)));
193
+ const willCopy = enforcing && !readNodeEvidenceScripts().some((name) => evidence(`${SCRIPTS_REL}/${name}`));
194
+ if (!willCopy && !isPresent(INSTALLER_REL)) throw refusal(`${installer} is absent — nothing here places the hook installer`);
188
195
  const guard = variant === 'commit-guard' ? ['--commit-guard', join(toolsDir, 'commit-guard.mjs')] : [];
196
+ const { flags = guard, ...hookChecks } = variant === 'hook-checks' ? planHookChecks({ root, toolsDir, isPresent, deps }) : {};
197
+ const runEntries = entries.map(({ path, deployed: rel, bundled }) => ({ path, rel,
198
+ bytes: willCopy ? readFile(join(toolsDir, '..', bundled)) : deployedBytes.get(rel) }));
199
+ const copies = willCopy ? dependenciesFirst(runEntries.map((entry) => ({ ...entry, imports: bundledImportsOf(entry.path, entry.bytes) })))
200
+ .map(({ rel, bytes }) => ({ rel, path: join(root, rel), action: 'created', bytes })) : [];
189
201
  return {
190
202
  root,
191
203
  variant,
192
- folders: copies.length === 0 ? [] : folders.filter((folder) => nodes.get(folder) === null),
204
+ ...hookChecks,
205
+ folders: willCopy ? [...folders].filter(([, node]) => node === null).map(([folder]) => folder) : [],
193
206
  copies,
194
- runs: { argv: ['node', installer, ...guard], shown: ['node', INSTALLER_REL, ...guard], bytes: placed ? placed.bytes : readFile(installer) },
207
+ runs: { argv: ['node', installer, ...flags], shown: ['node', INSTALLER_REL, ...flags], entries: runEntries },
195
208
  };
196
209
  };
197
210
 
211
+ const hashRunEntries = (entries) => {
212
+ const hash = createHash('sha256');
213
+ for (const { rel, bytes } of entries) {
214
+ hash.update(`${Buffer.byteLength(rel)}:${rel}`);
215
+ if (bytes === null) hash.update(ABSENT_RUN_ENTRY);
216
+ else hash.update(`${Buffer.byteLength(bytes)}:`).update(bytes);
217
+ }
218
+ return hash.digest('hex');
219
+ };
220
+
198
221
  export const formatPlan = (plan) => [
199
222
  ...plan.copies.map(({ rel, action, bytes }) => `copy: ${rel} ${action}${action === 'created' ? ` sha256:${sha(bytes)}` : ''}`),
200
- `runs: ${plan.runs.shown.map(shellQuoteArg).join(' ')} sha256:${sha(plan.runs.bytes)}`,
223
+ `runs: ${plan.runs.shown.map(shellQuoteArg).join(' ')} sha256:${hashRunEntries(plan.runs.entries)}`,
201
224
  ];
202
225
 
203
226
  // Removes exactly the files this run created, then each folder this run created, deepest first, when it is
@@ -217,7 +240,7 @@ const rollBack = (plan, created, io) => {
217
240
  left.push(path);
218
241
  }
219
242
  };
220
- for (const { rel, path } of created.files) {
243
+ for (const { rel, path } of created.files.toReversed()) {
221
244
  if (intact(rel) && isFile(nodeOrNull(path, io.lstat))) remove(path, io.unlink);
222
245
  else left.push(path);
223
246
  }
@@ -30,6 +30,7 @@ import { readFileSync, writeFileSync, lstatSync, realpathSync } from 'node:fs';
30
30
  import { resolve, join, relative, isAbsolute, dirname, basename, sep } from 'node:path';
31
31
  import { tmpdir } from 'node:os';
32
32
  import { spawnSync } from 'node:child_process';
33
+ import { AGENTS_FILE, GIT_DIR } from '../references/scripts/shared/index.mjs';
33
34
  import { isDirectRun } from './direct-run.mjs';
34
35
  import { fail } from './orchestration-config.mjs';
35
36
  import { readRegularFileNoFollow } from './fs-read-nofollow.mjs';
@@ -349,7 +350,7 @@ export const main = (argv, ctx = {}) => {
349
350
  throw fail(1, `${label} '${path}' is unreadable (${(err && err.code) || err}) — STOP`);
350
351
  }
351
352
  };
352
- const constraintsText = constraints ? readOrStop('AGENTS.md', 'root AGENTS.md') : null;
353
+ const constraintsText = constraints ? readOrStop(AGENTS_FILE, 'root AGENTS.md') : null;
353
354
  const autonomyText = autonomy ? resolveAutonomyFacts({ cwd }) : null;
354
355
  // --plan is CONFINED to the git work tree: the bridge tier auto-allows this tool
355
356
  // with an args wildcard, so an unattended invocation could otherwise point --plan at ANY
@@ -392,7 +393,7 @@ export const main = (argv, ctx = {}) => {
392
393
  });
393
394
  // The linked-worktree `.git` is a FILE inside the tree yet outside both answers above —
394
395
  // repository metadata all the same.
395
- gitDirsReal.push(join(topReal, '.git'));
396
+ gitDirsReal.push(join(topReal, GIT_DIR));
396
397
  return { tempRoots, topReal, gitDirsReal };
397
398
  };
398
399
  const surface = extra.some((v) => v.startsWith('@')) ? extraReadSurface() : null;
@@ -25,6 +25,7 @@ import {
25
25
  import { join, resolve, relative, isAbsolute, basename } from 'node:path';
26
26
  import { execFileSync } from 'node:child_process';
27
27
  import os from 'node:os';
28
+ import { AGENTS_FILE, DOCS_TREE } from '../references/scripts/shared/index.mjs';
28
29
  import { isDirectRun } from './direct-run.mjs';
29
30
  import {
30
31
  KIT_OWN_PATHS, KNOWN_FOOTPRINT, FOOTPRINT_STOP, stop,
@@ -223,7 +224,7 @@ const presentOnDisk = (pattern, fsx, dir) => {
223
224
  // untracked AND ignored → HIDDEN (run the reconcile)
224
225
  // untracked AND not ignored → AMBIGUOUS (fresh-uncommitted vs broken-hidden → the agent ASKs)
225
226
  export const inferVisibility = (deps, dir, fsx = fsOf(deps)) => {
226
- const anchors = ['/AGENTS.md', '/docs/ai/'];
227
+ const anchors = [`/${AGENTS_FILE}`, `/${DOCS_TREE}/`];
227
228
  // VISIBLE keys on tracked-ness (git state), not disk presence — a committed-but-deleted AGENTS.md is
228
229
  // still visible. Check BOTH anchors before falling through to the ignored/ambiguous test.
229
230
  for (const a of anchors) {