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
@@ -1,134 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * AgentVerdictCapture.hook.ts — SubagentStop hook
4
- *
5
- * Parses agent output for structured verdict blocks.
6
- * Writes verdict, testedSha, testedPaths, spawned to workflow-state.json.
7
- * Auto-appends blockers to verifyBlockers[].
8
- *
9
- * Issue: #439
10
- */
11
-
12
- import { readFileSync, writeFileSync, existsSync, readdirSync, statSync } from 'fs';
13
- import { join } from 'path';
14
- import { parseHookInput } from './lib/parseStdin';
15
- import { detectAgent } from './lib/agentDetection';
16
-
17
- const WORK_DIR = process.env.RUNGATE_WORK_DIR || process.env.PAI_WORK_DIR || join(process.env.HOME!, '.rungate');
18
-
19
- function findActiveWorkflow(): { path: string; data: any } | null {
20
- if (!existsSync(WORK_DIR)) return null;
21
- let best: { path: string; data: any; mtime: number } | null = null;
22
-
23
- function scan(dir: string) {
24
- try {
25
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
26
- if (!entry.isDirectory()) continue;
27
- const wfPath = join(dir, entry.name, 'workflow-state.json');
28
- if (existsSync(wfPath)) {
29
- try {
30
- const data = JSON.parse(readFileSync(wfPath, 'utf-8'));
31
- if (['BUILD', 'VERIFY', 'SHIP'].includes(data.phase)) {
32
- const mtime = statSync(wfPath).mtimeMs;
33
- if (!best || mtime > best.mtime) {
34
- best = { path: wfPath, data, mtime };
35
- }
36
- }
37
- } catch {}
38
- }
39
- const nested = join(dir, entry.name);
40
- try {
41
- for (const sub of readdirSync(nested, { withFileTypes: true })) {
42
- if (!sub.isDirectory()) continue;
43
- const nestedWf = join(nested, sub.name, 'workflow-state.json');
44
- if (!existsSync(nestedWf)) continue;
45
- try {
46
- const data = JSON.parse(readFileSync(nestedWf, 'utf-8'));
47
- if (['BUILD', 'VERIFY', 'SHIP'].includes(data.phase)) {
48
- const mtime = statSync(nestedWf).mtimeMs;
49
- if (!best || mtime > best.mtime) {
50
- best = { path: nestedWf, data, mtime };
51
- }
52
- }
53
- } catch {}
54
- }
55
- } catch {}
56
- }
57
- } catch {}
58
- }
59
-
60
- scan(WORK_DIR);
61
- return best ? { path: best.path, data: best.data } : null;
62
- }
63
-
64
- function extractVerdict(text: string): any | null {
65
- const match = text.match(/## Verdict\n(\{[\s\S]*?\n\})/);
66
- if (!match) return null;
67
- try {
68
- return JSON.parse(match[1]);
69
- } catch {
70
- return null;
71
- }
72
- }
73
-
74
- function identifyRole(toolInput: any): string | null {
75
- const detected = detectAgent(toolInput);
76
- if (detected) return detected.key;
77
- const name = (toolInput.name || '').toLowerCase();
78
- if (name.startsWith('quinn')) return 'quinn';
79
- if (name.startsWith('marcus')) return 'marcus';
80
- if (name.startsWith('rook')) return 'rook';
81
- return null;
82
- }
83
-
84
- async function main() {
85
- const payload = await parseHookInput();
86
- if (!payload) process.exit(0);
87
-
88
- const toolInput = payload.tool_input || {};
89
- const role = identifyRole(toolInput);
90
- if (!role) process.exit(0);
91
-
92
- const wf = findActiveWorkflow();
93
- if (!wf) process.exit(0);
94
-
95
- const resp = payload.tool_response;
96
- const respText = typeof resp === 'string' ? resp : (resp?.output || JSON.stringify(resp) || '');
97
-
98
- const verdict = extractVerdict(respText);
99
- const state = wf.data;
100
-
101
- if (!state.agents) state.agents = {};
102
- if (!state.agents[role]) state.agents[role] = {};
103
-
104
- state.agents[role].spawned = true;
105
-
106
- if (verdict) {
107
- state.agents[role].verdict = verdict.verdict || verdict.result || null;
108
- if (verdict.testedSha) state.agents[role].testedSha = verdict.testedSha;
109
- if (verdict.testedPaths) state.agents[role].testedPaths = verdict.testedPaths;
110
-
111
- if (verdict.blockers && Array.isArray(verdict.blockers)) {
112
- if (!state.verifyBlockers) state.verifyBlockers = [];
113
- for (const b of verdict.blockers) {
114
- const id = b.id || `${role}-blocker-${state.verifyBlockers.length + 1}`;
115
- if (!state.verifyBlockers.some((vb: any) => vb.id === id)) {
116
- state.verifyBlockers.push({
117
- id,
118
- description: b.description || b.detail || String(b),
119
- quinnReverified: false,
120
- });
121
- }
122
- }
123
- }
124
- } else {
125
- state.agents[role].verdict = null;
126
- }
127
-
128
- state.updatedTs = new Date().toISOString();
129
- writeFileSync(wf.path, JSON.stringify(state, null, 2));
130
- console.error(`[agent-verdict-capture] ${role}: verdict=${verdict?.verdict || 'null'}, path=${wf.path}`);
131
- process.exit(0);
132
- }
133
-
134
- main();
@@ -1,76 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * AutoVerifyGate.hook.ts — PostToolUse on Agent
4
- *
5
- * When Marcus/Quinn/Rook agent returns:
6
- * 1. Find active workflow-state.json in BUILD/VERIFY phase
7
- * 2. Write agents.<key>.verdict based on response content
8
- * 3. For Marcus: emit system-reminder to run verify gate
9
- * 4. For Quinn/Rook: record verdict only
10
- */
11
-
12
- import { writeFileSync, renameSync } from 'fs';
13
- import { join } from 'path';
14
- import { parseHookInput, detectAgent, findWorkflowState, extractIssueNumber, WORK_DIR, HARNESS_ROOT } from './lib/utils';
15
-
16
- function atomicWrite(path: string, data: string) {
17
- const tmp = `${path}.${process.pid}.tmp`;
18
- writeFileSync(tmp, data, 'utf-8');
19
- renameSync(tmp, path);
20
- }
21
-
22
- const NEGATIVE_PATTERNS = [
23
- /\b(no|zero|0)\s+(error|fail)/i,
24
- /\bfixed\s+the\s+(error|fail|bug|issue)/i,
25
- /\bpreviously\s+failed.*now\s+pass/i,
26
- /\b0\s+error/i, /\berror.*resolved/i, /\bno\s+failures/i,
27
- /\bfail(ure)?s?\s*:\s*0\b/i, /\berrors?\s*:\s*0\b/i,
28
- ];
29
-
30
- async function main() {
31
- const payload = await parseHookInput();
32
- if (!payload || payload.tool_name !== 'Agent') process.exit(0);
33
-
34
- const toolInput = payload.tool_input || {};
35
- const agent = detectAgent(toolInput);
36
- if (!agent) process.exit(0);
37
-
38
- const { key } = agent;
39
- const expectedPhase = key === 'marcus' ? 'BUILD' : 'VERIFY';
40
- const issueNum = extractIssueNumber(toolInput.prompt || '');
41
- const wf = findWorkflowState(issueNum, [expectedPhase]);
42
- if (!wf) { console.error('[auto-verify] No active workflow — skipping'); process.exit(0); }
43
-
44
- if (wf.data.phase !== expectedPhase) {
45
- console.error(`[auto-verify] Phase is ${wf.data.phase}, not ${expectedPhase} — skipping`);
46
- process.exit(0);
47
- }
48
-
49
- const resp = payload.tool_response;
50
- const respContent = typeof resp === 'string' ? resp : (resp?.content || resp?.output || '');
51
- const hasNeg = NEGATIVE_PATTERNS.some(p => p.test(respContent));
52
- const respLower = respContent.toLowerCase();
53
- const verdict = hasNeg ? 'PASS'
54
- : (respLower.includes('error') || respLower.includes('failed')) ? 'FAIL'
55
- : 'PASS';
56
-
57
- const state = wf.data;
58
- state.agents = state.agents || {};
59
- state.agents[key] = { verdict, completedTs: new Date().toISOString() };
60
- state.updatedTs = new Date().toISOString();
61
-
62
- const sfPath = join(WORK_DIR, wf.slug, 'workflow-state.json');
63
- try { atomicWrite(sfPath, JSON.stringify(state, null, 2)); } catch {
64
- console.error('[auto-verify] Failed to write workflow-state.json');
65
- process.exit(0);
66
- }
67
-
68
- console.error(`[auto-verify] ${key} verdict: ${verdict}`);
69
- if (key === 'marcus') {
70
- console.log(`\n<system-reminder>AUTO-VERIFY TRIGGERED: Run this command NOW:\nbun run ${HARNESS_ROOT}/gates/run-gate.ts --gate verify --slug ${wf.slug}\nDo NOT skip — auto-verify detected Marcus completion.</system-reminder>`);
71
- } else {
72
- console.log(`\n<system-reminder>${key} verdict recorded: ${verdict}. No gate trigger — ${key} runs are part of verification.</system-reminder>`);
73
- }
74
- }
75
-
76
- main();
@@ -1,273 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * GateEnforcement.hook.ts — PreToolUse gate for harness gate failures
4
- *
5
- * TRIGGER: PreToolUse (matcher: ".*" — fires on every tool call)
6
- *
7
- * PURPOSE:
8
- * When a harness gate fails, nag the DA on every tool call until fixed.
9
- * After max_strikes, block Skill calls (Bash/Read/Agent still work for fixing).
10
- * OUTCOME AC failures get immediate block — no strike counting.
11
- *
12
- * BEHAVIOR:
13
- * 1. Read MEMORY/STATE/gate-pending.json — if missing/expired → exit 0
14
- * 2. Cross-session guard: if pending session_id ≠ current → exit 0
15
- * 3. outcome_ac_failure → immediate block on Skill calls
16
- * 4. Skill + strike_count >= max_strikes → block
17
- * 5. Otherwise → nag (system-reminder), increment strike_count
18
- * 6. Write updated strike_count back
19
- * 7. Log to MEMORY/LEARNING/SIGNALS/signals.jsonl
20
- *
21
- * INPUT:
22
- * - stdin: PreToolUse JSON payload { tool_name, tool_input, session_id, ... }
23
- *
24
- * OUTPUT:
25
- * - stdout: JSON block decision OR system-reminder nag
26
- * - stderr: status messages
27
- * - exit(0): always
28
- */
29
-
30
- import {
31
- appendFileSync,
32
- existsSync,
33
- mkdirSync,
34
- readFileSync,
35
- readdirSync,
36
- unlinkSync,
37
- writeFileSync,
38
- } from 'fs';
39
- import { join } from 'path';
40
- import { BASE_DIR, WORK_DIR } from './lib/paths';
41
- import { parseHookInput } from './lib/parseStdin';
42
-
43
- const STATE_DIR = join(BASE_DIR, 'MEMORY', 'STATE');
44
- const SIGNALS_DIR = join(BASE_DIR, 'MEMORY', 'LEARNING', 'SIGNALS');
45
- const PENDING_FILE = join(STATE_DIR, 'gate-pending.json');
46
- const SIGNALS_FILE = join(SIGNALS_DIR, 'signals.jsonl');
47
-
48
- interface GateFailure {
49
- check: string;
50
- detail: string;
51
- }
52
-
53
- interface GatePending {
54
- session_id: string;
55
- gate: string;
56
- issue: number;
57
- slug: string;
58
- failures: GateFailure[];
59
- strike_count: number;
60
- max_strikes: number;
61
- outcome_ac_failure: boolean;
62
- created_at: string;
63
- expires_ts: number;
64
- }
65
-
66
- interface HookInput {
67
- session_id?: string;
68
- tool_name?: string;
69
- tool_input?: {
70
- skill?: string;
71
- [k: string]: unknown;
72
- };
73
- }
74
-
75
-
76
- function logSignal(event: Record<string, unknown>): void {
77
- try {
78
- if (!existsSync(SIGNALS_DIR)) mkdirSync(SIGNALS_DIR, { recursive: true });
79
- if (existsSync(SIGNALS_FILE)) {
80
- appendFileSync(SIGNALS_FILE, JSON.stringify(event) + '\n', 'utf-8');
81
- }
82
- } catch (err) {
83
- console.error(`[GateEnforcement] Signal log write failed: ${err}`);
84
- }
85
- }
86
-
87
- function formatFailures(failures: GateFailure[]): string {
88
- return failures.map(f => ` - ${f.check}: ${f.detail}`).join('\n');
89
- }
90
-
91
- interface WorkflowGateFailure {
92
- gate: string;
93
- issue: number;
94
- slug: string;
95
- failures: GateFailure[];
96
- hasOutcomeAcFailure: boolean;
97
- }
98
-
99
- function findWorkflowGateFailure(): WorkflowGateFailure | null {
100
- if (!existsSync(WORK_DIR)) return null;
101
-
102
- try {
103
- const dirs = readdirSync(WORK_DIR, { withFileTypes: true })
104
- .filter(d => d.isDirectory());
105
-
106
- for (const d of dirs) {
107
- const wfPath = join(WORK_DIR, d.name, 'workflow-state.json');
108
- if (!existsSync(wfPath)) continue;
109
-
110
- try {
111
- const wf = JSON.parse(readFileSync(wfPath, 'utf-8'));
112
- if (wf.phase === 'DONE') continue;
113
-
114
- const gates = wf.gates || {};
115
- for (const gateName of ['scope', 'verify', 'ship']) {
116
- const gate = gates[gateName];
117
- if (gate?.result === 'FAIL' && Array.isArray(gate.failures) && gate.failures.length > 0) {
118
- const acs = Array.isArray(wf.acs) ? wf.acs : [];
119
- const hasOutcomeAcFailure = acs.some(
120
- (ac: { type?: string; verdict?: string }) => ac.type === 'OUTCOME' && ac.verdict === 'FAIL'
121
- );
122
- return {
123
- gate: gateName,
124
- issue: wf.issue,
125
- slug: wf.slug || d.name,
126
- failures: gate.failures.map((f: { check?: string; id?: string; detail?: string; message?: string }) => ({
127
- check: f.check || f.id || 'unknown',
128
- detail: f.detail || f.message || JSON.stringify(f),
129
- })),
130
- hasOutcomeAcFailure,
131
- };
132
- }
133
- }
134
- } catch { /* skip malformed */ }
135
- }
136
- } catch { /* skip */ }
137
-
138
- return null;
139
- }
140
-
141
- async function main() {
142
- const input = await parseHookInput();
143
- if (!input) process.exit(0);
144
-
145
- try {
146
- // v2: Find active gate failures from workflow-state.json in ~/.rungate/
147
- const wfFailure = findWorkflowGateFailure();
148
- if (!wfFailure) {
149
- if (existsSync(PENDING_FILE)) {
150
- try { unlinkSync(PENDING_FILE); } catch {}
151
- }
152
- process.exit(0);
153
- }
154
-
155
- // Load strike count from cache (gate-pending.json) if it matches
156
- let strikeCount = 0;
157
- if (existsSync(PENDING_FILE)) {
158
- try {
159
- const cached = JSON.parse(readFileSync(PENDING_FILE, 'utf-8'));
160
- if (cached.issue === wfFailure.issue && cached.gate === wfFailure.gate) {
161
- strikeCount = cached.strike_count || 0;
162
- }
163
- } catch {}
164
- }
165
-
166
- const pending: GatePending = {
167
- session_id: input.session_id || '',
168
- gate: wfFailure.gate,
169
- issue: wfFailure.issue,
170
- slug: wfFailure.slug,
171
- failures: wfFailure.failures,
172
- strike_count: strikeCount,
173
- max_strikes: 3,
174
- outcome_ac_failure: wfFailure.hasOutcomeAcFailure,
175
- created_at: new Date().toISOString(),
176
- expires_ts: Date.now() + (4 * 60 * 60 * 1000),
177
- };
178
-
179
- const toolName = input.tool_name || '';
180
- const isSkillCall = toolName === 'Skill';
181
- const failureText = formatFailures(pending.failures);
182
-
183
- // OUTCOME AC failure → immediate block on Skill calls (no strike counting)
184
- if (pending.outcome_ac_failure && isSkillCall) {
185
- const decision = {
186
- decision: 'block',
187
- reason: `OUTCOME AC failed — must fix before proceeding. Gate: ${pending.gate}, issue #${pending.issue}.\n${failureText}`,
188
- };
189
- console.log(JSON.stringify(decision));
190
-
191
- logSignal({
192
- ts: new Date().toISOString(),
193
- type: 'gate_enforcement',
194
- gate: pending.gate,
195
- issue: pending.issue,
196
- strike: pending.strike_count,
197
- tool: toolName,
198
- action: 'block',
199
- reason: 'outcome_ac_failure',
200
- });
201
-
202
- console.error(`[GateEnforcement] BLOCKED Skill — outcome AC failure on ${pending.gate}`);
203
- process.exit(0);
204
- }
205
-
206
- // Strike-based block on Skill calls
207
- if (isSkillCall && pending.strike_count >= pending.max_strikes) {
208
- const decision = {
209
- decision: 'block',
210
- reason: `Gate blocked after ${pending.strike_count} strikes: ${pending.gate} (issue #${pending.issue}).\n${failureText}\nFix the failures or post skip-reason to the issue.`,
211
- };
212
- console.log(JSON.stringify(decision));
213
-
214
- logSignal({
215
- ts: new Date().toISOString(),
216
- type: 'gate_enforcement',
217
- gate: pending.gate,
218
- issue: pending.issue,
219
- strike: pending.strike_count,
220
- tool: toolName,
221
- action: 'block',
222
- reason: 'max_strikes',
223
- });
224
-
225
- console.error(`[GateEnforcement] BLOCKED Skill — ${pending.strike_count} strikes on ${pending.gate}`);
226
- process.exit(0);
227
- }
228
-
229
- // Nag — inject system-reminder on ALL tools, but only count strikes for Skill calls
230
- const newStrikeCount = isSkillCall ? pending.strike_count + 1 : pending.strike_count;
231
-
232
- const reminder = [
233
- '<system-reminder>',
234
- `⚠️ GATE FAIL (${pending.gate}): issue #${pending.issue}`,
235
- failureText,
236
- `Strike ${newStrikeCount}/${pending.max_strikes}. Fix before proceeding or post skip-reason to issue.`,
237
- '</system-reminder>',
238
- ].join('\n');
239
-
240
- console.log(reminder);
241
-
242
- // Write updated strike_count back — only when Skill call incremented it
243
- if (isSkillCall) {
244
- const updated: GatePending = { ...pending, strike_count: newStrikeCount };
245
- try {
246
- writeFileSync(PENDING_FILE, JSON.stringify(updated, null, 2), 'utf-8');
247
- } catch (err) {
248
- console.error(`[GateEnforcement] Failed to update strike_count: ${err}`);
249
- }
250
- }
251
-
252
- logSignal({
253
- ts: new Date().toISOString(),
254
- type: 'gate_enforcement',
255
- gate: pending.gate,
256
- issue: pending.issue,
257
- strike: newStrikeCount,
258
- tool: toolName,
259
- action: 'nag',
260
- });
261
-
262
- console.error(
263
- `[GateEnforcement] Nag injected for ${toolName} — strike ${newStrikeCount}/${pending.max_strikes} on ${pending.gate}`
264
- );
265
-
266
- process.exit(0);
267
- } catch (err) {
268
- console.error(`[GateEnforcement] Error: ${err}`);
269
- process.exit(0);
270
- }
271
- }
272
-
273
- main();
@@ -1,116 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * IssueCloseGuard.hook.ts — PreToolUse on Bash
4
- *
5
- * Blocks gh issue close if ship-gate hasn't passed.
6
- * Validates HMAC provenance on PASS results.
7
- * Also validates comment templates on gh issue comment.
8
- */
9
-
10
- import { createHmac } from 'crypto';
11
- import { readFileSync, existsSync, writeFileSync } from 'fs';
12
- import { join } from 'path';
13
- import { parseHookInput, findWorkflowState, HARNESS_ROOT } from './lib/utils';
14
-
15
- const TEMPLATE_RULES = [
16
- { marker: '## AC-', required: ['Type:', 'Metric:', 'Threshold:', 'Baseline:', 'Evidence Method:', 'Pass Criteria:'] },
17
- { marker: '## ATTEMPT', required: ['Approach:', 'Files Changed:', 'Result:', 'Evidence:', 'Why It Failed:'] },
18
- { marker: '## DISCOVERY', required: ['### Docs read', '### Issue context'] },
19
- { marker: '## Completion Report', required: ['### Evidence per AC', '### Ship Scorecard'] },
20
- { marker: '## Sizing Declaration', required: ['Predicted:', 'Files:'] },
21
- { marker: '## Sizing Outcome', required: ['Declared:', 'Actual:'] },
22
- ];
23
-
24
- function block(reason: string): never {
25
- console.log(JSON.stringify({ decision: 'block', reason }));
26
- process.exit(0);
27
- throw new Error('unreachable');
28
- }
29
-
30
- function validateCommentTemplate(command: string) {
31
- let body = '';
32
- const heredocMatch = command.match(/--body\s+"?\$\(cat\s+<<'?EOF'?\s*\n?([\s\S]*?)\nEOF/);
33
- if (heredocMatch) body = heredocMatch[1];
34
- else {
35
- const bodyMatch = command.match(/(?:--body|-b)\s+["']([^"']*(?:(?:\\.)[^"']*)*)['"]/);
36
- if (bodyMatch) body = bodyMatch[1];
37
- }
38
- if (!body) return;
39
-
40
- if (/^## AC-\d+/m.test(body))
41
- block('ACs (## AC-N) must be posted to the issue body via "gh issue edit --body", not as comments.');
42
- if (body.includes('### Docs read') && !body.includes('## DISCOVERY'))
43
- block('Comment contains "### Docs read" but no "## DISCOVERY" heading. Use the DISCOVERY template.');
44
- if (body.includes('### Evidence per AC') && !body.includes('## Completion Report'))
45
- block('Comment contains "### Evidence per AC" but no "## Completion Report" heading.');
46
- if (body.includes('REPLACE:'))
47
- block('Comment body contains unfilled REPLACE: placeholder(s).');
48
-
49
- for (const rule of TEMPLATE_RULES) {
50
- if (!body.includes(rule.marker)) continue;
51
- const missing = rule.required.filter(f => !body.includes(f));
52
- if (missing.length) block(`Template "${rule.marker}" missing fields: ${missing.join(', ')}. See TEMPLATES.md.`);
53
- }
54
- }
55
-
56
- function validateHmac(wf: any, slug: string, issueNum: string) {
57
- const gateHash = wf.gates?.ship?.hash;
58
- const saltPath = join(HARNESS_ROOT, 'gates', '.gate-salt');
59
- if (!gateHash || !existsSync(saltPath)) {
60
- if (!gateHash) console.error('[close-guard] WARN: Ship PASS without HMAC');
61
- return;
62
- }
63
- const salt = readFileSync(saltPath, 'utf-8').trim();
64
- const commitSha = wf.gates?.ship?.commitSha || 'unknown';
65
- const hmacInput = `${slug}:${wf.issue}:PASS:${commitSha}`;
66
- const expected = createHmac('sha256', salt).update(hmacInput).digest('hex').substring(0, 16);
67
- if (gateHash !== expected) block(`Cannot close #${issueNum} — gate HMAC mismatch. Results may be fabricated.`);
68
- }
69
-
70
- async function main() {
71
- const input = await parseHookInput();
72
- if (!input || input.tool_name !== 'Bash') process.exit(0);
73
-
74
- const command = input.tool_input?.command || '';
75
-
76
- if (/gh\s+issue\s+comment\s+\d+/.test(command)) {
77
- validateCommentTemplate(command);
78
- process.exit(0);
79
- }
80
-
81
- const closeMatch = command.match(/gh\s+issue\s+close\s+(\d+)/);
82
- if (!closeMatch) process.exit(0);
83
- const issueNum = closeMatch[1];
84
-
85
- const repoMatch = command.match(/--repo\s+(\S+)/);
86
- const repo = repoMatch?.[1] || 'hornjason/pai-config';
87
-
88
- const wf = findWorkflowState(issueNum);
89
- if (!wf) {
90
- try {
91
- const result = Bun.spawnSync(['gh', 'issue', 'view', issueNum, '--repo', repo, '--json', 'labels', '--jq', '.labels[].name']);
92
- const labels = result.stdout.toString().trim();
93
- if (labels.includes('p1-ship-next') || labels.includes('p2-this-week')) {
94
- block(`Cannot close #${issueNum} — has ${labels.includes('p1') ? 'p1-ship-next' : 'p2-this-week'} label but no workflow-state.json. Run /ship first.`);
95
- }
96
- } catch {}
97
- console.log(`<system-reminder>\nWARNING: Closing #${issueNum} but no workflow-state.json found.\nIf this issue went through ship, gates may not have been run.\n</system-reminder>`);
98
- process.exit(0);
99
- }
100
-
101
- const state = wf.data;
102
- if (state.gates?.ship?.result === 'PASS') {
103
- validateHmac(state, wf.slug, issueNum);
104
- try {
105
- state.phase = 'DONE';
106
- state.updatedTs = new Date().toISOString();
107
- writeFileSync(wf.path, JSON.stringify(state, null, 2) + '\n');
108
- console.error(`[close-guard] Updated phase to DONE for #${issueNum}`);
109
- } catch {}
110
- process.exit(0);
111
- }
112
-
113
- block(`Cannot close #${issueNum} — ship-gate result is "${state.gates?.ship?.result || 'not set'}". Run: bun run ${HARNESS_ROOT}/gates/run-gate.ts --gate ship --slug ${wf.slug}`);
114
- }
115
-
116
- main();
@@ -1,55 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * MergeGuard.hook.ts — PreToolUse on Bash
4
- *
5
- * Early warning when git merge targets main/master without verify-gate passing.
6
- * The pre-push hook is the hard enforcement; this warns so the agent can fix first.
7
- */
8
-
9
- import { readdirSync, readFileSync, existsSync, statSync } from 'fs';
10
- import { join } from 'path';
11
- import { parseHookInput, WORK_DIR, HARNESS_ROOT } from './lib/utils';
12
-
13
- const TTL_MS = 4 * 60 * 60 * 1000;
14
-
15
- function findActiveShipMarker(): { issue: number; workDir: string } | null {
16
- if (!existsSync(WORK_DIR)) return null;
17
- try {
18
- for (const d of readdirSync(WORK_DIR, { withFileTypes: true }).filter(d => d.isDirectory())) {
19
- const markerPath = join(WORK_DIR, d.name, '.ship-active');
20
- if (!existsSync(markerPath)) continue;
21
- if (Date.now() - statSync(markerPath).mtimeMs > TTL_MS) continue;
22
- try {
23
- const marker = JSON.parse(readFileSync(markerPath, 'utf-8'));
24
- if (marker.issue) return { issue: marker.issue, workDir: join(WORK_DIR, d.name) };
25
- } catch {}
26
- }
27
- } catch {}
28
- return null;
29
- }
30
-
31
- function checkVerifyGate(workDir: string): boolean {
32
- const wfPath = join(workDir, 'workflow-state.json');
33
- if (!existsSync(wfPath)) return false;
34
- try {
35
- return JSON.parse(readFileSync(wfPath, 'utf-8')).gates?.verify?.result === 'PASS';
36
- } catch { return false; }
37
- }
38
-
39
- async function main() {
40
- const input = await parseHookInput();
41
- if (!input || input.tool_name !== 'Bash') process.exit(0);
42
-
43
- const command = input.tool_input?.command || '';
44
- const isMerge = /git\s+merge\s+.*\b(main|master)\b/.test(command) ||
45
- /git\s+checkout\s+(main|master)\s*[;&|]+\s*git\s+merge/.test(command);
46
- if (!isMerge) process.exit(0);
47
-
48
- const ship = findActiveShipMarker();
49
- if (!ship || checkVerifyGate(ship.workDir)) process.exit(0);
50
-
51
- const slug = ship.workDir.split('/').pop();
52
- console.log(`<system-reminder>\n⚠️ MERGE WARNING: verify-gate has not passed for issue #${ship.issue}.\nThe pre-push hook will BLOCK this push. Run verify-gate first:\n bun run ${HARNESS_ROOT}/gates/run-gate.ts --gate verify --slug ${slug}\n</system-reminder>`);
53
- }
54
-
55
- main();