rungate 0.2.0 → 0.3.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 (282) hide show
  1. package/bin/rungate.ts +70 -0
  2. package/lib/aes-calculator.ts +66 -0
  3. package/lib/agent-audit.ts +139 -0
  4. package/lib/agent-brief-validation.ts +359 -0
  5. package/lib/agents-md-refs.ts +90 -0
  6. package/lib/bash-file-read.ts +197 -0
  7. package/lib/behavioral-cache.ts +78 -0
  8. package/lib/branch-cleanup.ts +234 -0
  9. package/lib/brief-context-parser.ts +35 -0
  10. package/lib/canary.ts +117 -0
  11. package/lib/check-registry.ts +226 -0
  12. package/lib/ci-checkout.ts +400 -0
  13. package/lib/cli-commands.ts +137 -0
  14. package/lib/compliance-backfill.ts +220 -0
  15. package/lib/compliance-report.ts +504 -0
  16. package/lib/compliance.ts +361 -0
  17. package/lib/config-loader.ts +255 -0
  18. package/lib/conformity.ts +1818 -131
  19. package/lib/container-provenance.ts +230 -0
  20. package/lib/create-brief.ts +150 -0
  21. package/lib/create-sc.ts +272 -0
  22. package/lib/deep-merge.ts +69 -0
  23. package/lib/dev-liveness.ts +214 -0
  24. package/lib/directive-extractor.ts +210 -0
  25. package/lib/distribution-standing.ts +113 -0
  26. package/lib/doc-hygiene.ts +238 -0
  27. package/lib/eval-criteria.ts +6 -0
  28. package/lib/evidence-portability.ts +123 -0
  29. package/lib/evidence-prevalidator.ts +390 -0
  30. package/lib/evidence-required.ts +150 -0
  31. package/lib/evidence-satisfiability.ts +288 -0
  32. package/lib/frontmatter.ts +163 -0
  33. package/lib/gap-scanner.ts +348 -0
  34. package/lib/gate-enforcement.ts +366 -0
  35. package/lib/generators/agent-briefs.ts +136 -0
  36. package/lib/generators/agents-md.ts +506 -0
  37. package/lib/generators/code-map.ts +60 -0
  38. package/lib/generators/types.ts +184 -0
  39. package/lib/git-ref-normalizer.ts +107 -0
  40. package/lib/github.ts +539 -0
  41. package/lib/harness-identity.ts +63 -0
  42. package/lib/hill-climb.ts +164 -0
  43. package/lib/instruction-effectiveness.ts +131 -0
  44. package/lib/issue-closure-audit.ts +225 -0
  45. package/lib/issue-create-override.ts +343 -0
  46. package/lib/js-top-level-code.ts +250 -0
  47. package/lib/liveness-contradiction.ts +149 -0
  48. package/lib/organize.ts +505 -0
  49. package/lib/paths.ts +197 -6
  50. package/lib/post-fix-verify.ts +157 -0
  51. package/lib/prior-branch.ts +489 -0
  52. package/lib/project-state-shape.ts +166 -0
  53. package/lib/promote-outputs.ts +156 -0
  54. package/lib/prove-label-gate.ts +35 -0
  55. package/lib/reachability.ts +302 -0
  56. package/lib/release-preflight.ts +186 -0
  57. package/lib/rule-health-pipeline.ts +264 -0
  58. package/lib/rule-health-trend.ts +161 -0
  59. package/lib/rule-provenance.ts +149 -0
  60. package/lib/rule-registry.ts +128 -0
  61. package/lib/rungate-schema.ts +114 -4
  62. package/lib/sc-claim-forms.ts +179 -0
  63. package/lib/sc-cover.ts +150 -0
  64. package/lib/sc-guard.ts +157 -0
  65. package/lib/sc-ids.ts +344 -0
  66. package/lib/scaffold/defaults.ts +165 -0
  67. package/lib/scaffold/managed-workflow.ts +370 -0
  68. package/lib/scaffold/owned-files.ts +265 -0
  69. package/lib/scaffold/steps.ts +2680 -0
  70. package/lib/scanner.ts +701 -0
  71. package/lib/screenshot-upload.ts +73 -0
  72. package/lib/secret-patterns.ts +112 -0
  73. package/lib/security-verdict.ts +616 -0
  74. package/lib/signal-phrases.ts +1 -0
  75. package/lib/spec-change-conformity.ts +80 -0
  76. package/lib/spec-files.ts +62 -0
  77. package/lib/spec-registry.ts +133 -0
  78. package/lib/spec-updater.ts +96 -0
  79. package/lib/stale-cleanup.ts +224 -0
  80. package/lib/stale-issue-scanner.ts +36 -0
  81. package/lib/strip-js-comments.ts +269 -0
  82. package/lib/suite-measurement.ts +228 -0
  83. package/lib/task-completion-checks.ts +177 -0
  84. package/lib/test-suite-lock.ts +1136 -0
  85. package/lib/transcript-checker.ts +1140 -0
  86. package/lib/validators/spec-validators.ts +171 -0
  87. package/lib/verdict-capture.ts +73 -0
  88. package/lib/verified-push.ts +358 -0
  89. package/lib/workflow-security.ts +174 -0
  90. package/lib/worktree-cleanup.ts +250 -0
  91. package/lib/worktree-collect.ts +283 -0
  92. package/lib/worktree-isolation.ts +82 -0
  93. package/package.json +36 -3
  94. package/prompts/ac-adversary.md +14 -2
  95. package/prompts/aditi.md +5 -0
  96. package/prompts/blast-radius.md +5 -0
  97. package/prompts/container-verify.md +5 -0
  98. package/prompts/discovery.md +4 -0
  99. package/prompts/environment.md +5 -0
  100. package/prompts/evidence-hierarchy.md +5 -0
  101. package/prompts/evidence-validator.md +11 -0
  102. package/prompts/marcus.md +5 -0
  103. package/prompts/prevention.md +5 -0
  104. package/prompts/prove-reproducer.md +12 -0
  105. package/prompts/quinn-decision-tree.md +5 -0
  106. package/prompts/quinn-ui-brief.md +5 -0
  107. package/prompts/quinn.md +5 -0
  108. package/prompts/rca.md +5 -0
  109. package/prompts/read-before-write.md +4 -0
  110. package/prompts/regression.md +5 -0
  111. package/prompts/serena.md +5 -0
  112. package/scripts/audit-specs.ts +464 -0
  113. package/scripts/convert-spec.ts +293 -0
  114. package/scripts/create-sc.ts +92 -0
  115. package/scripts/create-spec.ts +166 -0
  116. package/scripts/extract-constraints.ts +4 -3
  117. package/scripts/generate-code-map.ts +1 -1
  118. package/scripts/scaffold-project.ts +138 -1426
  119. package/scripts/sync-spec-tests.ts +211 -126
  120. package/.claude/agents/aditi.md +0 -47
  121. package/.claude/agents/marcus.md +0 -50
  122. package/.claude/agents/quinn.md +0 -58
  123. package/.claude/agents/rook.md +0 -47
  124. package/.claude/agents/serena.md +0 -46
  125. package/.claude/rungate.json +0 -11
  126. package/.fallowrc.json +0 -28
  127. package/.github/copilot-instructions.md +0 -20
  128. package/.rungate/conformity-findings.json +0 -648
  129. package/AGENTS.md +0 -106
  130. package/CODE-MAP.md +0 -50
  131. package/HARNESS.md +0 -88
  132. package/bun.lock +0 -26
  133. package/bunfig.toml +0 -2
  134. package/config/brief-policies.json +0 -28
  135. package/config/ceremony-profiles.json +0 -212
  136. package/config/consumer-cascade-map.json +0 -24
  137. package/config/doc-cascade-map.json +0 -24
  138. package/config/eval.json +0 -84
  139. package/config/profiles/account-plan.yaml +0 -36
  140. package/config/profiles/campaign.yaml +0 -94
  141. package/config/prove-evidence.schema.json +0 -65
  142. package/config/spec-policies.json +0 -36
  143. package/config/workflow-schema.json +0 -281
  144. package/gates/SCHEMA-GUIDE.md +0 -121
  145. package/gates/ac-quality.test.ts +0 -106
  146. package/gates/adversarial.test.ts +0 -274
  147. package/gates/brief-assembler.test.ts +0 -429
  148. package/gates/brief-assembler.ts +0 -334
  149. package/gates/bunfig.toml +0 -2
  150. package/gates/chain.test.ts +0 -91
  151. package/gates/e2e-smoke.test.ts +0 -234
  152. package/gates/error-classifier.test.ts +0 -249
  153. package/gates/error-classifier.ts +0 -89
  154. package/gates/orchestrator.test.ts +0 -950
  155. package/gates/orchestrator.ts +0 -569
  156. package/gates/preload.ts +0 -77
  157. package/gates/prompts/ac-adversary.md +0 -20
  158. package/gates/prompts/evidence-validator.md +0 -22
  159. package/gates/prompts/prove-reproducer.md +0 -53
  160. package/gates/prove.test.ts +0 -164
  161. package/gates/run-gate.ts +0 -936
  162. package/gates/schema-parity.test.ts +0 -197
  163. package/gates/schema.ts +0 -362
  164. package/gates/self-heal.test.ts +0 -511
  165. package/gates/self-heal.ts +0 -121
  166. package/gates/ship-orchestrator.test.ts +0 -379
  167. package/gates/ship-orchestrator.ts +0 -363
  168. package/gates/test-fixtures/broken-no-environments.json +0 -60
  169. package/gates/test-fixtures/valid-standard.json +0 -54
  170. package/gates/test-utils.ts +0 -43
  171. package/gates/witness.ts +0 -220
  172. package/gates/workflow.test.ts +0 -1053
  173. package/hooks/AgentBriefGuard.hook.ts +0 -586
  174. package/hooks/AgentVerdictCapture.hook.ts +0 -134
  175. package/hooks/AutoVerifyGate.hook.ts +0 -76
  176. package/hooks/GateEnforcement.hook.ts +0 -273
  177. package/hooks/IssueCloseGuard.hook.ts +0 -116
  178. package/hooks/MergeGuard.hook.ts +0 -55
  179. package/hooks/StaleTTLCleanup.hook.ts +0 -133
  180. package/hooks/VerifyPhaseLock.hook.ts +0 -81
  181. package/hooks/WorkflowStateGuard.hook.ts +0 -37
  182. package/hooks/lib/agentDetection.ts +0 -70
  183. package/hooks/lib/findWorkflow.ts +0 -101
  184. package/hooks/lib/parseStdin.ts +0 -37
  185. package/hooks/lib/paths.ts +0 -111
  186. package/hooks/lib/utils.ts +0 -81
  187. package/reference/migration-manifest.json +0 -554
  188. package/reference/prompts/agent-aditi.md +0 -38
  189. package/reference/prompts/agent-marcus.md +0 -38
  190. package/reference/prompts/agent-quinn.md +0 -38
  191. package/reference/prompts/agent-rook.md +0 -37
  192. package/reference/prompts/agent-serena.md +0 -37
  193. package/reference/prompts/council-skill.md +0 -170
  194. package/reference/prompts/goal-skill.md +0 -235
  195. package/reference/prompts/prove-skill.md +0 -283
  196. package/reference/prompts/quinn-standard.md +0 -246
  197. package/reference/prompts/ship-convergence.md +0 -65
  198. package/reference/prompts/ship-escalation.md +0 -43
  199. package/reference/prompts/ship-iteration.md +0 -382
  200. package/reference/prompts/ship-pending-patches.md +0 -246
  201. package/reference/prompts/ship-reference.md +0 -250
  202. package/reference/prompts/ship-skill.md +0 -347
  203. package/reference/prompts/ship-templates.md +0 -215
  204. package/reference/scripts/batch-status.sh +0 -68
  205. package/reference/scripts/chain-compat-check.sh +0 -67
  206. package/reference/scripts/context-audit.sh +0 -314
  207. package/reference/scripts/dead-export-check.sh +0 -61
  208. package/reference/scripts/generate-qc-tables.sh +0 -92
  209. package/reference/scripts/harness-init.sh +0 -111
  210. package/reference/scripts/pai-054-baseline-check.sh +0 -40
  211. package/reference/scripts/prove-smoke-test.sh +0 -112
  212. package/reference/scripts/setup-keychain-salt.sh +0 -12
  213. package/reference/scripts/skill-optimizer-friday.sh +0 -88
  214. package/reference/scripts/skill-qc-test.sh +0 -351
  215. package/reference/scripts/skill-synthesize-tonight.sh +0 -66
  216. package/reference/specs/HARNESS-EXTRACTION-SPEC.md +0 -263
  217. package/reference/specs/harness-v3-bash-deletion-plan.md +0 -65
  218. package/reference/specs/harness-v3-migration-plan.md +0 -188
  219. package/scripts/decision-reconcile.sh +0 -74
  220. package/scripts/decision-reconcile.ts +0 -152
  221. package/scripts/git-hooks/pre-commit +0 -76
  222. package/scripts/git-hooks/pre-push +0 -271
  223. package/scripts/harness-skill-check.sh +0 -52
  224. package/scripts/lib/gap-emit.sh +0 -65
  225. package/scripts/lib/jq-update.sh +0 -30
  226. package/scripts/lib/resolve-slug.sh +0 -30
  227. package/scripts/lib/verify-spec-compliance.sh +0 -102
  228. package/scripts/prove-backfill.sh +0 -87
  229. package/scripts/scaffold-rungate-config.ts +0 -91
  230. package/scripts/self-containment-check.sh +0 -109
  231. package/scripts/skill-qc-validator.sh +0 -402
  232. package/scripts/slug-resolver.sh +0 -14
  233. package/specs/BOOTSTRAP-DATA-FLOW-SPEC.md +0 -2493
  234. package/specs/BOOTSTRAP-TEST-PLAN.md +0 -571
  235. package/specs/HARNESS-GATES.md +0 -256
  236. package/specs/HARNESS-SKILL-CHAIN.md +0 -286
  237. package/specs/HARNESS-SKILL-CONTRACT.md +0 -93
  238. package/specs/HARNESS-STANDARD.md +0 -488
  239. package/specs/SPEC-TEMPLATE.md +0 -53
  240. package/specs/bootstrap-data-flow.png +0 -0
  241. package/specs/harness-automation-matrix.md +0 -314
  242. package/specs/harness-automation-matrix.rules.json +0 -64
  243. package/test/anti.test.ts +0 -80
  244. package/test/contract-negative.test.ts +0 -86
  245. package/test/contract.test.ts +0 -158
  246. package/test/external-deps.test.ts +0 -48
  247. package/test/fixtures/golden-project/.env.example +0 -3
  248. package/test/fixtures/golden-project/Makefile +0 -7
  249. package/test/fixtures/golden-project/docs/adr/ADR-001-framework.md +0 -23
  250. package/test/fixtures/golden-project/docs/setup-guide.md +0 -10
  251. package/test/fixtures/golden-project/package.json +0 -10
  252. package/test/fixtures/golden-project/specs/api-spec.md +0 -20
  253. package/test/fixtures/golden-project/src/auth.ts +0 -8
  254. package/test/fixtures/golden-project/src/db.ts +0 -11
  255. package/test/fixtures/golden-project/src/index.ts +0 -19
  256. package/test/fixtures/golden-project/src/utils/format.ts +0 -3
  257. package/test/fixtures/golden-project/test/auth.test.ts +0 -15
  258. package/test/fixtures/golden-project/tsconfig.json +0 -12
  259. package/test/meta-sc-coverage.test.ts +0 -159
  260. package/test/phase-0.test.ts +0 -846
  261. package/test/phase-1.test.ts +0 -617
  262. package/test/phase-2.test.ts +0 -620
  263. package/test/phase-3.test.ts +0 -99
  264. package/test/scaffold-conformity.test.ts +0 -8
  265. package/test/schema-canary.test.ts +0 -51
  266. package/test/spec-compliance-auto.test.ts +0 -64
  267. package/test/spec-compliance.test.ts +0 -295
  268. package/test/spec-discovery.test.ts +0 -68
  269. package/test/spec-drift.test.ts +0 -5
  270. package/test/structure.test.ts +0 -165
  271. package/test/unit/agent-brief-guard-ship.test.ts +0 -293
  272. package/test/unit/extract-constraints.test.ts +0 -145
  273. package/test/unit/issue-close-guard.test.ts +0 -204
  274. package/test/unit/scaffold-project.test.ts +0 -417
  275. package/test/unit/skill-cooccurrence.test.ts +0 -177
  276. package/test/unit/skill-sequence-logger.test.ts +0 -244
  277. package/test/unit/workflow-state-guard.test.ts +0 -95
  278. package/workflows/batch-ship.js +0 -295
  279. package/workflows/council.js +0 -481
  280. package/workflows/prove.js +0 -560
  281. package/workflows/ship.js +0 -789
  282. package/workflows/verify.js +0 -236
package/lib/paths.ts CHANGED
@@ -1,15 +1,178 @@
1
- import { join, resolve } from "path";
2
- import { existsSync } from "fs";
1
+ import { dirname, join, resolve } from "path";
2
+ import { spawnSync } from "child_process";
3
+ import { chmodSync, existsSync, mkdirSync, realpathSync, statSync, writeFileSync } from "fs";
4
+ import { randomBytes } from "crypto";
5
+ import { homedir } from "os";
3
6
 
4
- export function harnessRoot(): string {
7
+ /**
8
+ * Every refusal in this file routes through `refuse()`, and `refuse()` is the
9
+ * only reader of this constant, which appears exactly once. `test/harness-root.test.ts`
10
+ * builds a mutant copy of this module with it set to `0` and asserts the mutant
11
+ * does NOT refuse on inputs the real module rejects — the positive control
12
+ * required by .claude/rules/checks-must-be-able-to-fail.md. Inlining a `throw`
13
+ * anywhere below would bypass that control, so don't.
14
+ */
15
+ export const REFUSE_IMPLICIT_ROOT = 1;
16
+
17
+ function refuse(message: string): void {
18
+ if (REFUSE_IMPLICIT_ROOT) throw new Error(message);
19
+ }
20
+
21
+ /** `file:line` of the frame that called into this module, for refusal messages. */
22
+ function callSite(): string {
23
+ const frames = (new Error().stack || "").split("\n").slice(1);
24
+ for (const f of frames) {
25
+ if (f.includes("lib/paths.ts")) continue;
26
+ const m = f.match(/\(?([^()\s]+:\d+:\d+)\)?\s*$/);
27
+ if (m) return m[1];
28
+ }
29
+ return "unknown caller";
30
+ }
31
+
32
+ const FIXES =
33
+ "Either set HARNESS_ROOT to the root of the run, " +
34
+ "or pass the root you mean explicitly: harnessRootFor(root).";
35
+
36
+ /**
37
+ * The harness root the CALLER means, stated rather than inferred (#105).
38
+ *
39
+ * Use this from anything that is about to EXECUTE or WRITE — `gate-executor`
40
+ * spawning `bun scripts/sync-spec-tests.ts`, which regenerates files in the
41
+ * tree it is pointed at. For those, "whichever tree this module happens to sit
42
+ * in" is not a default, it is a coin flip between the run's root and the
43
+ * worktree the agent is editing, and the losing side gets written to.
44
+ */
45
+ export function harnessRootFor(root: string): string {
46
+ if (!root || !root.trim()) {
47
+ throw new Error(
48
+ `harnessRootFor() was given an empty root at ${callSite()}. ` +
49
+ "An explicit root is the caller naming the tree it means; there is no tree to fall back to.",
50
+ );
51
+ }
52
+ return resolve(root);
53
+ }
54
+
55
+ export interface ImplicitRootOptions {
56
+ /** Overrides the inferred `file:line` in refusal messages. */
57
+ caller?: string;
58
+ /**
59
+ * Set by callers whose resolved root will serve reads of harness-owned
60
+ * STATIC files — briefs, rules, templates, specs, generated tests.
61
+ *
62
+ * A dirty implicit root is refused for these. That combination is the exact
63
+ * failure this module exists to stop: nobody said which tree to use, the tree
64
+ * guessed has uncommitted edits, so the file being READ and the file under
65
+ * TEST are two different versions of the same path — and the read succeeds,
66
+ * which is why it was never visible.
67
+ */
68
+ staticReads?: boolean;
69
+ }
70
+
71
+ function isDirty(root: string): boolean {
72
+ const r = spawnSync("git", ["-C", root, "status", "--porcelain"], {
73
+ encoding: "utf-8",
74
+ timeout: 5000,
75
+ });
76
+ // Not a repo, or git unavailable: nothing to disagree about, so not dirty.
77
+ if (r.status !== 0) return false;
78
+ return (r.stdout || "").trim().length > 0;
79
+ }
80
+
81
+ /**
82
+ * The harness root inferred from the environment.
83
+ *
84
+ * Resolution order, with no fourth step on purpose: `HARNESS_ROOT`, then the
85
+ * tree this module sits in if it carries the `HARNESS.md` marker, then a
86
+ * refusal. The deleted fourth step was `join(process.env.HOME, ".claude")` —
87
+ * a path that almost always exists, so a misconfigured run, an agent in a
88
+ * worktree and a correct run all read happily from it and only one of them was
89
+ * reading the tree under test. A refusal names the call site; a successful read
90
+ * from the wrong tree names nothing.
91
+ */
92
+ export function harnessRoot(opts: ImplicitRootOptions = {}): string {
5
93
  if (process.env.HARNESS_ROOT) return process.env.HARNESS_ROOT;
94
+ const caller = opts.caller || callSite();
6
95
  const repoRoot = resolve(import.meta.dir, "..");
7
- if (existsSync(join(repoRoot, "HARNESS.md"))) return repoRoot;
8
- return join(process.env.HOME || "", ".claude");
96
+
97
+ if (!existsSync(join(repoRoot, "HARNESS.md"))) {
98
+ refuse(
99
+ `harnessRoot() cannot tell which harness tree ${caller} means: ` +
100
+ `HARNESS_ROOT is unset and ${repoRoot} carries no HARNESS.md marker. ${FIXES}`,
101
+ );
102
+ return repoRoot; // unreachable unless the refusal has been mutated out
103
+ }
104
+
105
+ if (opts.staticReads && isDirty(repoRoot)) {
106
+ refuse(
107
+ `harnessRoot() refuses to serve reads of harness-owned files to ${caller} ` +
108
+ `from ${repoRoot}: no root was given, and the tree it guessed has uncommitted ` +
109
+ `changes — so the file read and the file under test are different versions. ${FIXES}`,
110
+ );
111
+ }
112
+
113
+ return repoRoot;
114
+ }
115
+
116
+ /**
117
+ * The MAIN repository root containing `dir`, or null if `dir` is not in a repo
118
+ * (#68).
119
+ *
120
+ * SessionStart hooks were calling `process.cwd()` and treating it as the
121
+ * project root. A session opened in `~` therefore skipped worktree cleanup
122
+ * entirely while still reporting "no stale files found", and sessions started
123
+ * in `~/.claude` created a stray worktree tree at `~/.claude/.claude/worktrees`
124
+ * with 16 entries in it. Cleanup ran or didn't based on where a terminal
125
+ * happened to be.
126
+ *
127
+ * `--git-common-dir`, not `--show-toplevel`: from inside a LINKED WORKTREE,
128
+ * `--show-toplevel` returns that worktree. `.claude/worktrees/` lives in the
129
+ * main checkout, so resolving to the worktree would make cleanup look at a
130
+ * directory that is never there — failing silently in the exact situation the
131
+ * cleanup exists to handle. `--git-common-dir` always points at the main
132
+ * repo's `.git`, from a worktree or not.
133
+ */
134
+ export function repoRootFrom(dir: string): string | null {
135
+ const r = spawnSync("git", ["-C", dir, "rev-parse", "--git-common-dir"], {
136
+ encoding: "utf-8",
137
+ timeout: 5000,
138
+ });
139
+ if (r.status !== 0) return null;
140
+ const gitDir = r.stdout.trim();
141
+ if (!gitDir) return null;
142
+ // Relative when `dir` is already the repo root (".git"); absolute otherwise.
143
+ const repo = dirname(resolve(dir, gitDir));
144
+ // Always hand back a real path. Git returns an absolute, symlink-resolved
145
+ // path from inside a worktree but a bare relative ".git" from the root, so
146
+ // without this the same repo resolves to "/var/..." or "/private/var/..."
147
+ // depending on which directory you asked from. Callers compare these to
148
+ // decide whether to DELETE a worktree, so a string mismatch is not cosmetic.
149
+ try {
150
+ return realpathSync(repo);
151
+ } catch {
152
+ return repo;
153
+ }
154
+ }
155
+
156
+ /**
157
+ * `~/.claude`, named rather than spelled inline (#105).
158
+ *
159
+ * This directory is PAI's actual install location, so for `paiRoot()` it is the
160
+ * right answer. It was ALSO the last line of `harnessRoot()`, where it was the
161
+ * wrong answer — and the two were the same anonymous expression, which is how a
162
+ * harness read ended up pointed at PAI's tree with nothing in the output saying
163
+ * so. Giving the concept one name and one caller makes that confusion a visible
164
+ * edit instead of a copied line.
165
+ */
166
+ function paiHomeDir(): string {
167
+ // `homedir()` rather than `process.env.HOME || ""`: the old spelling degraded
168
+ // to the RELATIVE path ".claude" when HOME was unset, which resolves against
169
+ // the cwd — another way to read a plausible directory that is not the one
170
+ // meant. It still honours $HOME, which is what the paiRoot probe asserts.
171
+ return join(homedir(), ".claude");
9
172
  }
10
173
 
11
174
  export function paiRoot(): string {
12
- return process.env.PAI_ROOT || join(process.env.HOME || "", ".claude");
175
+ return process.env.PAI_ROOT || paiHomeDir();
13
176
  }
14
177
 
15
178
  export function workDir(slug: string): string {
@@ -21,3 +184,31 @@ export function workDir(slug: string): string {
21
184
  export function gateSaltPath(): string {
22
185
  return join(harnessRoot(), "gates", ".gate-salt");
23
186
  }
187
+
188
+ /**
189
+ * Return the gate salt path, minting the salt if it does not exist yet.
190
+ *
191
+ * The salt is gitignored, so a fresh checkout has none. Creation used to live
192
+ * inline in `generateHmac` (gates/orchestrator.ts), which made every other
193
+ * reader depend on that one function having run first: `gates/adversarial.test.ts`
194
+ * read the salt directly and threw ENOENT unless `gates/orchestrator.test.ts`
195
+ * happened to execute earlier in the same run. Eight tests were passing on
196
+ * readdir order, which is not alphabetical on ext4 — they would have flipped
197
+ * red on an unrelated commit, and the diff would have explained nothing.
198
+ *
199
+ * Deliberately NOT used by `gates/witness.ts`: verification must fail when the
200
+ * salt is missing rather than quietly mint a new one and validate against it.
201
+ */
202
+ export function ensureGateSalt(): string {
203
+ const path = gateSaltPath();
204
+ if (!existsSync(path)) {
205
+ mkdirSync(dirname(path), { recursive: true });
206
+ // mode at creation: writeFileSync-then-chmod leaves the salt world-readable
207
+ // for a moment, and a readable salt is a forgeable gate witness.
208
+ writeFileSync(path, randomBytes(32).toString("hex") + "\n", { mode: 0o600 });
209
+ }
210
+ // Re-assert the mode even when the file already existed: a salt readable by
211
+ // other users is a forgeable gate witness.
212
+ if ((statSync(path).mode & 0o777) !== 0o600) chmodSync(path, 0o600);
213
+ return path;
214
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Post-fix verification for ship-and-heal workflow.
3
+ *
4
+ * After a conformity fix is applied, verifies that the ROOT CAUSE was fixed
5
+ * (generator/template updated) not just the symptom (generated output file).
6
+ *
7
+ * Ref: Ship-and-heal post-fix verification (PROJECT-STATE P1)
8
+ */
9
+
10
+ import { spawnSync } from 'child_process';
11
+
12
+ export interface PostFixResult {
13
+ /** Overall assessment */
14
+ status: 'DURABLE' | 'WARN_NON_DURABLE' | 'UNKNOWN';
15
+ /** Files changed that are generators/templates */
16
+ generatorFilesChanged: string[];
17
+ /** Files changed that are generated outputs */
18
+ generatedFilesChanged: string[];
19
+ /** Files changed that are neither (normal source) */
20
+ otherFilesChanged: string[];
21
+ /** Human-readable message */
22
+ message: string;
23
+ }
24
+
25
+ /**
26
+ * Known generator/template file patterns.
27
+ * These are the SOURCE files that produce generated output.
28
+ */
29
+ const GENERATOR_PATTERNS = [
30
+ 'scripts/scaffold-project.ts',
31
+ 'templates/',
32
+ 'specs/', // Specs generate conformity tests
33
+ ] as const;
34
+
35
+ /**
36
+ * Known generated output file patterns.
37
+ * These files are PRODUCED by running scaffold-project.ts.
38
+ */
39
+ const GENERATED_PATTERNS = [
40
+ '.claude/agents/',
41
+ 'CODE-MAP.md',
42
+ 'test/scaffold-conformity.test.ts',
43
+ '.github/workflows/ci.yml',
44
+ '.github/workflows/gates.yml',
45
+ ] as const;
46
+
47
+ /**
48
+ * Classify a file path as generator, generated, or other.
49
+ */
50
+ function classifyFile(filePath: string): 'generator' | 'generated' | 'other' {
51
+ // Check generator patterns
52
+ for (const pattern of GENERATOR_PATTERNS) {
53
+ if (filePath.includes(pattern)) {
54
+ return 'generator';
55
+ }
56
+ }
57
+
58
+ // Check generated patterns
59
+ for (const pattern of GENERATED_PATTERNS) {
60
+ if (filePath.includes(pattern)) {
61
+ return 'generated';
62
+ }
63
+ }
64
+
65
+ return 'other';
66
+ }
67
+
68
+ /**
69
+ * Verify that a fix touched generator files, not just generated output.
70
+ *
71
+ * @param changedFiles - List of file paths that were changed during the fix
72
+ * @returns Analysis of what was changed and whether the fix is durable
73
+ *
74
+ * @example
75
+ * const result = verifyPostFix([
76
+ * '.claude/agents/marcus.md',
77
+ * 'templates/agent-briefs/marcus.md'
78
+ * ]);
79
+ * if (result.status === 'WARN_NON_DURABLE') {
80
+ * console.warn(result.message);
81
+ * }
82
+ */
83
+ export function verifyPostFix(changedFiles: string[]): PostFixResult {
84
+ const generatorFilesChanged: string[] = [];
85
+ const generatedFilesChanged: string[] = [];
86
+ const otherFilesChanged: string[] = [];
87
+
88
+ // Classify each changed file
89
+ for (const file of changedFiles) {
90
+ const classification = classifyFile(file);
91
+ switch (classification) {
92
+ case 'generator':
93
+ generatorFilesChanged.push(file);
94
+ break;
95
+ case 'generated':
96
+ generatedFilesChanged.push(file);
97
+ break;
98
+ case 'other':
99
+ otherFilesChanged.push(file);
100
+ break;
101
+ }
102
+ }
103
+
104
+ // Determine status
105
+ let status: PostFixResult['status'];
106
+ let message: string;
107
+
108
+ if (generatedFilesChanged.length > 0 && generatorFilesChanged.length === 0) {
109
+ // WARN: Only generated files were changed, no generator files
110
+ status = 'WARN_NON_DURABLE';
111
+ message = `Fix may not be durable — ${generatedFilesChanged.length} generated file(s) changed but no generator/template files updated. Next scaffold run will regenerate the broken version.`;
112
+ } else if (generatorFilesChanged.length > 0) {
113
+ // DURABLE: Generator files were changed
114
+ status = 'DURABLE';
115
+ message = `Fix is durable — ${generatorFilesChanged.length} generator/template file(s) updated.`;
116
+ } else if (changedFiles.length === 0) {
117
+ // UNKNOWN: No files changed
118
+ status = 'UNKNOWN';
119
+ message = 'No files changed during fix.';
120
+ } else {
121
+ // UNKNOWN: Only "other" files changed (not generator or generated)
122
+ status = 'UNKNOWN';
123
+ message = `${otherFilesChanged.length} source file(s) changed. Not scaffold-related.`;
124
+ }
125
+
126
+ return {
127
+ status,
128
+ generatorFilesChanged,
129
+ generatedFilesChanged,
130
+ otherFilesChanged,
131
+ message,
132
+ };
133
+ }
134
+
135
+ /**
136
+ * Get list of changed files from git diff.
137
+ *
138
+ * @param cwd - Working directory (project root)
139
+ * @param baseRef - Base ref to compare against (default: HEAD)
140
+ * @returns Array of file paths changed
141
+ */
142
+ export function getChangedFiles(cwd: string, baseRef: string = 'HEAD'): string[] {
143
+ // Get changed files since baseRef (unstaged + staged)
144
+ const result = spawnSync('git', ['diff', '--name-only', baseRef], {
145
+ cwd,
146
+ encoding: 'utf-8',
147
+ });
148
+
149
+ if (result.status !== 0) {
150
+ return [];
151
+ }
152
+
153
+ return result.stdout
154
+ .split('\n')
155
+ .map(line => line.trim())
156
+ .filter(line => line.length > 0);
157
+ }