rungate 0.2.0 → 0.2.1

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 (164) hide show
  1. package/package.json +14 -3
  2. package/.claude/agents/aditi.md +0 -47
  3. package/.claude/agents/marcus.md +0 -50
  4. package/.claude/agents/quinn.md +0 -58
  5. package/.claude/agents/rook.md +0 -47
  6. package/.claude/agents/serena.md +0 -46
  7. package/.claude/rungate.json +0 -11
  8. package/.fallowrc.json +0 -28
  9. package/.github/copilot-instructions.md +0 -20
  10. package/.rungate/conformity-findings.json +0 -648
  11. package/AGENTS.md +0 -106
  12. package/CODE-MAP.md +0 -50
  13. package/HARNESS.md +0 -88
  14. package/bun.lock +0 -26
  15. package/bunfig.toml +0 -2
  16. package/config/brief-policies.json +0 -28
  17. package/config/ceremony-profiles.json +0 -212
  18. package/config/consumer-cascade-map.json +0 -24
  19. package/config/doc-cascade-map.json +0 -24
  20. package/config/eval.json +0 -84
  21. package/config/profiles/account-plan.yaml +0 -36
  22. package/config/profiles/campaign.yaml +0 -94
  23. package/config/prove-evidence.schema.json +0 -65
  24. package/config/spec-policies.json +0 -36
  25. package/config/workflow-schema.json +0 -281
  26. package/gates/SCHEMA-GUIDE.md +0 -121
  27. package/gates/ac-quality.test.ts +0 -106
  28. package/gates/adversarial.test.ts +0 -274
  29. package/gates/brief-assembler.test.ts +0 -429
  30. package/gates/brief-assembler.ts +0 -334
  31. package/gates/bunfig.toml +0 -2
  32. package/gates/chain.test.ts +0 -91
  33. package/gates/e2e-smoke.test.ts +0 -234
  34. package/gates/error-classifier.test.ts +0 -249
  35. package/gates/error-classifier.ts +0 -89
  36. package/gates/orchestrator.test.ts +0 -950
  37. package/gates/orchestrator.ts +0 -569
  38. package/gates/preload.ts +0 -77
  39. package/gates/prompts/ac-adversary.md +0 -20
  40. package/gates/prompts/evidence-validator.md +0 -22
  41. package/gates/prompts/prove-reproducer.md +0 -53
  42. package/gates/prove.test.ts +0 -164
  43. package/gates/run-gate.ts +0 -936
  44. package/gates/schema-parity.test.ts +0 -197
  45. package/gates/schema.ts +0 -362
  46. package/gates/self-heal.test.ts +0 -511
  47. package/gates/self-heal.ts +0 -121
  48. package/gates/ship-orchestrator.test.ts +0 -379
  49. package/gates/ship-orchestrator.ts +0 -363
  50. package/gates/test-fixtures/broken-no-environments.json +0 -60
  51. package/gates/test-fixtures/valid-standard.json +0 -54
  52. package/gates/test-utils.ts +0 -43
  53. package/gates/witness.ts +0 -220
  54. package/gates/workflow.test.ts +0 -1053
  55. package/hooks/AgentBriefGuard.hook.ts +0 -586
  56. package/hooks/AgentVerdictCapture.hook.ts +0 -134
  57. package/hooks/AutoVerifyGate.hook.ts +0 -76
  58. package/hooks/GateEnforcement.hook.ts +0 -273
  59. package/hooks/IssueCloseGuard.hook.ts +0 -116
  60. package/hooks/MergeGuard.hook.ts +0 -55
  61. package/hooks/StaleTTLCleanup.hook.ts +0 -133
  62. package/hooks/VerifyPhaseLock.hook.ts +0 -81
  63. package/hooks/WorkflowStateGuard.hook.ts +0 -37
  64. package/hooks/lib/agentDetection.ts +0 -70
  65. package/hooks/lib/findWorkflow.ts +0 -101
  66. package/hooks/lib/parseStdin.ts +0 -37
  67. package/hooks/lib/paths.ts +0 -111
  68. package/hooks/lib/utils.ts +0 -81
  69. package/reference/migration-manifest.json +0 -554
  70. package/reference/prompts/agent-aditi.md +0 -38
  71. package/reference/prompts/agent-marcus.md +0 -38
  72. package/reference/prompts/agent-quinn.md +0 -38
  73. package/reference/prompts/agent-rook.md +0 -37
  74. package/reference/prompts/agent-serena.md +0 -37
  75. package/reference/prompts/council-skill.md +0 -170
  76. package/reference/prompts/goal-skill.md +0 -235
  77. package/reference/prompts/prove-skill.md +0 -283
  78. package/reference/prompts/quinn-standard.md +0 -246
  79. package/reference/prompts/ship-convergence.md +0 -65
  80. package/reference/prompts/ship-escalation.md +0 -43
  81. package/reference/prompts/ship-iteration.md +0 -382
  82. package/reference/prompts/ship-pending-patches.md +0 -246
  83. package/reference/prompts/ship-reference.md +0 -250
  84. package/reference/prompts/ship-skill.md +0 -347
  85. package/reference/prompts/ship-templates.md +0 -215
  86. package/reference/scripts/batch-status.sh +0 -68
  87. package/reference/scripts/chain-compat-check.sh +0 -67
  88. package/reference/scripts/context-audit.sh +0 -314
  89. package/reference/scripts/dead-export-check.sh +0 -61
  90. package/reference/scripts/generate-qc-tables.sh +0 -92
  91. package/reference/scripts/harness-init.sh +0 -111
  92. package/reference/scripts/pai-054-baseline-check.sh +0 -40
  93. package/reference/scripts/prove-smoke-test.sh +0 -112
  94. package/reference/scripts/setup-keychain-salt.sh +0 -12
  95. package/reference/scripts/skill-optimizer-friday.sh +0 -88
  96. package/reference/scripts/skill-qc-test.sh +0 -351
  97. package/reference/scripts/skill-synthesize-tonight.sh +0 -66
  98. package/reference/specs/HARNESS-EXTRACTION-SPEC.md +0 -263
  99. package/reference/specs/harness-v3-bash-deletion-plan.md +0 -65
  100. package/reference/specs/harness-v3-migration-plan.md +0 -188
  101. package/scripts/decision-reconcile.sh +0 -74
  102. package/scripts/decision-reconcile.ts +0 -152
  103. package/scripts/git-hooks/pre-commit +0 -76
  104. package/scripts/git-hooks/pre-push +0 -271
  105. package/scripts/harness-skill-check.sh +0 -52
  106. package/scripts/lib/gap-emit.sh +0 -65
  107. package/scripts/lib/jq-update.sh +0 -30
  108. package/scripts/lib/resolve-slug.sh +0 -30
  109. package/scripts/lib/verify-spec-compliance.sh +0 -102
  110. package/scripts/prove-backfill.sh +0 -87
  111. package/scripts/scaffold-rungate-config.ts +0 -91
  112. package/scripts/self-containment-check.sh +0 -109
  113. package/scripts/skill-qc-validator.sh +0 -402
  114. package/scripts/slug-resolver.sh +0 -14
  115. package/specs/BOOTSTRAP-DATA-FLOW-SPEC.md +0 -2493
  116. package/specs/BOOTSTRAP-TEST-PLAN.md +0 -571
  117. package/specs/HARNESS-GATES.md +0 -256
  118. package/specs/HARNESS-SKILL-CHAIN.md +0 -286
  119. package/specs/HARNESS-SKILL-CONTRACT.md +0 -93
  120. package/specs/HARNESS-STANDARD.md +0 -488
  121. package/specs/SPEC-TEMPLATE.md +0 -53
  122. package/specs/bootstrap-data-flow.png +0 -0
  123. package/specs/harness-automation-matrix.md +0 -314
  124. package/specs/harness-automation-matrix.rules.json +0 -64
  125. package/test/anti.test.ts +0 -80
  126. package/test/contract-negative.test.ts +0 -86
  127. package/test/contract.test.ts +0 -158
  128. package/test/external-deps.test.ts +0 -48
  129. package/test/fixtures/golden-project/.env.example +0 -3
  130. package/test/fixtures/golden-project/Makefile +0 -7
  131. package/test/fixtures/golden-project/docs/adr/ADR-001-framework.md +0 -23
  132. package/test/fixtures/golden-project/docs/setup-guide.md +0 -10
  133. package/test/fixtures/golden-project/package.json +0 -10
  134. package/test/fixtures/golden-project/specs/api-spec.md +0 -20
  135. package/test/fixtures/golden-project/src/auth.ts +0 -8
  136. package/test/fixtures/golden-project/src/db.ts +0 -11
  137. package/test/fixtures/golden-project/src/index.ts +0 -19
  138. package/test/fixtures/golden-project/src/utils/format.ts +0 -3
  139. package/test/fixtures/golden-project/test/auth.test.ts +0 -15
  140. package/test/fixtures/golden-project/tsconfig.json +0 -12
  141. package/test/meta-sc-coverage.test.ts +0 -159
  142. package/test/phase-0.test.ts +0 -846
  143. package/test/phase-1.test.ts +0 -617
  144. package/test/phase-2.test.ts +0 -620
  145. package/test/phase-3.test.ts +0 -99
  146. package/test/scaffold-conformity.test.ts +0 -8
  147. package/test/schema-canary.test.ts +0 -51
  148. package/test/spec-compliance-auto.test.ts +0 -64
  149. package/test/spec-compliance.test.ts +0 -295
  150. package/test/spec-discovery.test.ts +0 -68
  151. package/test/spec-drift.test.ts +0 -5
  152. package/test/structure.test.ts +0 -165
  153. package/test/unit/agent-brief-guard-ship.test.ts +0 -293
  154. package/test/unit/extract-constraints.test.ts +0 -145
  155. package/test/unit/issue-close-guard.test.ts +0 -204
  156. package/test/unit/scaffold-project.test.ts +0 -417
  157. package/test/unit/skill-cooccurrence.test.ts +0 -177
  158. package/test/unit/skill-sequence-logger.test.ts +0 -244
  159. package/test/unit/workflow-state-guard.test.ts +0 -95
  160. package/workflows/batch-ship.js +0 -295
  161. package/workflows/council.js +0 -481
  162. package/workflows/prove.js +0 -560
  163. package/workflows/ship.js +0 -789
  164. 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();