rungate 0.7.0 → 0.8.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.
- package/hooks/ActionVerificationGate.hook.ts +96 -0
- package/hooks/AgentBriefGuard.hook.ts +38 -0
- package/hooks/AgentVerdictCapture.hook.ts +87 -0
- package/hooks/AutoVerifyGate.hook.ts +79 -0
- package/hooks/BashToolGuard.hook.ts +65 -0
- package/hooks/BashWriteGuard.hook.ts +60 -0
- package/hooks/CommitEnforcement.hook.ts +130 -0
- package/hooks/DocHygiene.hook.ts +148 -0
- package/hooks/GateEnforcement.hook.ts +58 -0
- package/hooks/GateResultProtection.hook.ts +69 -0
- package/hooks/HarnessAFKGate.hook.ts +85 -0
- package/hooks/HookCurrency.hook.ts +99 -0
- package/hooks/IssueCloseGuard.hook.ts +149 -0
- package/hooks/MergeGuard.hook.ts +58 -0
- package/hooks/PostCompact.hook.ts +60 -0
- package/hooks/ProjectStateSync.hook.ts +103 -0
- package/hooks/SkillGuard.hook.ts +69 -0
- package/hooks/SpecConformityTrigger.hook.ts +43 -0
- package/hooks/SpecSCGuard.hook.ts +123 -0
- package/hooks/StaleTTLCleanup.hook.ts +141 -0
- package/hooks/TaskCompleted.hook.ts +51 -0
- package/hooks/TeamInit.hook.ts +85 -0
- package/hooks/TestSuiteGuard.hook.ts +70 -0
- package/hooks/TestSuiteRelease.hook.ts +85 -0
- package/hooks/TopLevelCdGuard.hook.ts +108 -0
- package/hooks/VerifyPhaseLock.hook.ts +84 -0
- package/hooks/WorkflowStateGuard.hook.ts +40 -0
- package/hooks/lib/agent-config.json +9 -0
- package/hooks/lib/agentDetection.ts +201 -0
- package/hooks/lib/comment-template.ts +86 -0
- package/hooks/lib/findWorkflow.ts +101 -0
- package/hooks/lib/parseStdin.ts +37 -0
- package/hooks/lib/paths.ts +111 -0
- package/hooks/lib/utils.ts +338 -0
- package/lib/affected-tests.ts +29 -0
- package/lib/bash-write-guard.ts +373 -0
- package/lib/branch-cleanup.ts +279 -7
- package/lib/config-trackable.ts +9 -0
- package/lib/distribution-currency.ts +55 -5
- package/lib/failure-intake.ts +7 -1
- package/lib/gate-enforcement.ts +222 -28
- package/lib/gate-names.ts +72 -0
- package/lib/gate-result-protection.ts +427 -0
- package/lib/intake-sources.ts +380 -0
- package/lib/late-env-spawn.ts +331 -0
- package/lib/launch-base.ts +128 -5
- package/lib/paths.ts +96 -3
- package/lib/phase2-decomposition.ts +1 -1
- package/lib/published-artifact.ts +162 -18
- package/lib/sc-id-cross-tree.ts +84 -8
- package/lib/scaffold/ai-review-findings.ts +7 -1
- package/lib/scaffold/ai-review-step.ts +861 -116
- package/lib/scaffold/defaults.ts +82 -1
- package/lib/scaffold/steps.ts +436 -44
- package/lib/security-verdict.ts +1 -1
- package/lib/shell-path-interpolation.ts +594 -0
- package/lib/text-dependents.ts +875 -0
- package/lib/workflow-security.ts +29 -0
- package/lib/workflow-taint.ts +732 -0
- package/lib/worktree-cleanup.ts +65 -38
- package/lib/worktree-repo.ts +32 -2
- package/package.json +3 -1
- package/scripts/check-installed-hook-currency.ts +825 -0
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* DocHygiene.hook.ts — PostToolUse on Write + Edit, for `.md` files
|
|
4
|
+
*
|
|
5
|
+
* Governing SCs: SC-370 (traceability), SC-371 (thin trigger, under 150 lines)
|
|
6
|
+
*
|
|
7
|
+
* Stamps the three INFERABLE frontmatter fields onto a markdown document that
|
|
8
|
+
* is missing them, and reports a doc that is not indexed in DOCS.md.
|
|
9
|
+
* `owner:` is deliberately not among them (#1119) — see the stamp call.
|
|
10
|
+
*
|
|
11
|
+
* PORTABILITY (#713): the `.pai` copy carried its own 90-line copy of the
|
|
12
|
+
* frontmatter parser and said so in its header — "Mirror of lib/frontmatter.ts
|
|
13
|
+
* in rungate, which is where this is tested". That mirror is deleted here
|
|
14
|
+
* rather than moved: this hook now calls `../lib/frontmatter`, which is the
|
|
15
|
+
* binding the tests already drive, so the two cannot drift apart again. The
|
|
16
|
+
* add-only stamping rule, the refusal to rewrite a block it cannot parse, and
|
|
17
|
+
* the blank-line handling that #299 turned on are all that module's now.
|
|
18
|
+
*
|
|
19
|
+
* ONE DELIBERATE BEHAVIOUR CHANGE, recorded because it is not a file move:
|
|
20
|
+
* the `.pai` copy treated a REQUIRED key present with an EMPTY value as
|
|
21
|
+
* missing and overwrote it. `stampFrontmatter` leaves any key that is present
|
|
22
|
+
* exactly as it is. The library's rule is the correct one — filling a gap is
|
|
23
|
+
* this hook's job, having opinions about a value somebody wrote is not — and
|
|
24
|
+
* it is the behaviour `test/rules-frontmatter.test.ts` already asserts.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { readFileSync, writeFileSync, existsSync } from 'fs';
|
|
28
|
+
import { dirname, basename, join } from 'path';
|
|
29
|
+
import { stampFrontmatter } from '../lib/frontmatter';
|
|
30
|
+
import { localCalendarDay } from '../lib/local-calendar-day';
|
|
31
|
+
|
|
32
|
+
const input = JSON.parse(readFileSync(0, 'utf-8'));
|
|
33
|
+
const toolInput = input?.tool_input || {};
|
|
34
|
+
const filePath: string = toolInput.file_path || '';
|
|
35
|
+
|
|
36
|
+
// ── Guard: only .md files
|
|
37
|
+
if (!filePath.endsWith('.md')) process.exit(0);
|
|
38
|
+
|
|
39
|
+
// ── Guard: skip excluded paths
|
|
40
|
+
// `/tmp/` and `~/.rungate/` hold markdown that is a PAYLOAD, not a document:
|
|
41
|
+
// GitHub issue bodies, PR bodies and comments, written to a file and handed to
|
|
42
|
+
// `--body-file`. Stamping a doc header on those publishes
|
|
43
|
+
// `doc-type: reference / owner: jason` as the first four lines of the issue,
|
|
44
|
+
// where it renders as literal text.
|
|
45
|
+
// `.claude/rules/mutations/` is the same shape as `.claude/agents/`: a
|
|
46
|
+
// committed, in-repo markdown class whose first line belongs to a different
|
|
47
|
+
// consumer than the doc index. A mutation record is identified by its one `# `
|
|
48
|
+
// heading, so a stamp there is not a missing field being filled in, it is a
|
|
49
|
+
// convention being broken one file at a time.
|
|
50
|
+
const SKIP_PATTERNS = [
|
|
51
|
+
'/archive/',
|
|
52
|
+
'/MEMORY/WORK/',
|
|
53
|
+
'/.pai-work/',
|
|
54
|
+
'/config/',
|
|
55
|
+
'/test-results/',
|
|
56
|
+
'.claude/worktrees/',
|
|
57
|
+
'.claude/agents/',
|
|
58
|
+
'.claude/rules/mutations/',
|
|
59
|
+
'/tmp/',
|
|
60
|
+
'/.rungate/',
|
|
61
|
+
];
|
|
62
|
+
if (SKIP_PATTERNS.some(p => filePath.includes(p))) process.exit(0);
|
|
63
|
+
if (basename(filePath) === 'PRD.md') process.exit(0);
|
|
64
|
+
|
|
65
|
+
const tag = `[doc-hygiene] ${basename(filePath)}`;
|
|
66
|
+
|
|
67
|
+
let content: string;
|
|
68
|
+
try {
|
|
69
|
+
content = readFileSync(filePath, 'utf-8');
|
|
70
|
+
} catch {
|
|
71
|
+
process.exit(0);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// ── Infer the values for any of the four that are absent
|
|
75
|
+
const fname = basename(filePath).toUpperCase();
|
|
76
|
+
|
|
77
|
+
function inferDocType(): string {
|
|
78
|
+
if (filePath.includes('/adr/')) return 'adr';
|
|
79
|
+
if (/RUNBOOK|SETUP|PLAYBOOK|ADDING/.test(fname)) return 'runbook';
|
|
80
|
+
if (/ARCHITECTURE|PRINCIPLES|HERO-INSTALL/.test(fname)) return 'architecture';
|
|
81
|
+
if (fname === 'BACKLOG.MD') return 'backlog';
|
|
82
|
+
return 'reference';
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// #1119. No `owner:`, and no config key behind it. It was the literal
|
|
86
|
+
// `'jason'`, writing this repo's owner into a consumer's documents. The keys
|
|
87
|
+
// below are INFERRED from the document or the clock, which is what makes them
|
|
88
|
+
// safe to invent; an owner is not, so the honest stamp is none. A configured
|
|
89
|
+
// default is the same defect with a longer supply chain, and nothing
|
|
90
|
+
// downstream reads the key. Add-only (#299) leaves a declared owner alone.
|
|
91
|
+
const result = stampFrontmatter(content, {
|
|
92
|
+
'doc-type': inferDocType(),
|
|
93
|
+
status: 'active',
|
|
94
|
+
// #600. `updated:` is the day the author edited the document, which is a
|
|
95
|
+
// LOCAL calendar day — not a UTC one. The raw spelling this replaces was
|
|
96
|
+
// wrong for the four hours a day when the two disagree, and the stamp that
|
|
97
|
+
// results is written, committed and then read as a date by everything
|
|
98
|
+
// downstream. `localCalendarDay` is the one binding for this question, and
|
|
99
|
+
// its own docstring names `updated:` frontmatter as the case it exists for.
|
|
100
|
+
updated: localCalendarDay(),
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
if (result.refused) {
|
|
104
|
+
// Unreadable block. Leave it exactly as it is — rewriting one you cannot
|
|
105
|
+
// read is what #299 was.
|
|
106
|
+
console.log(`${tag} — ${result.refused}`);
|
|
107
|
+
checkDocsIndex(filePath, tag);
|
|
108
|
+
process.exit(0);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (result.stamped.length > 0) {
|
|
112
|
+
try {
|
|
113
|
+
writeFileSync(filePath, result.content, 'utf-8');
|
|
114
|
+
console.log(`${tag} — auto-stamped header (${result.stamped.join(', ')})`);
|
|
115
|
+
} catch {
|
|
116
|
+
console.log(`${tag} — could not auto-stamp header (write failed)`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ── Check DOCS.md index coverage
|
|
121
|
+
checkDocsIndex(filePath, tag);
|
|
122
|
+
|
|
123
|
+
function checkDocsIndex(fp: string, t: string): void {
|
|
124
|
+
// Walk up from the file to find DOCS.md at the project root
|
|
125
|
+
let dir = dirname(fp);
|
|
126
|
+
let docsIndex: string | null = null;
|
|
127
|
+
for (let i = 0; i < 5; i++) {
|
|
128
|
+
const candidate = join(dir, 'DOCS.md');
|
|
129
|
+
if (existsSync(candidate)) {
|
|
130
|
+
docsIndex = candidate;
|
|
131
|
+
break;
|
|
132
|
+
}
|
|
133
|
+
const parent = dirname(dir);
|
|
134
|
+
if (parent === dir) break;
|
|
135
|
+
dir = parent;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (!docsIndex) return;
|
|
139
|
+
|
|
140
|
+
const name = basename(fp);
|
|
141
|
+
try {
|
|
142
|
+
if (!readFileSync(docsIndex, 'utf-8').includes(name)) {
|
|
143
|
+
console.log(`${t} — not in DOCS.md index (add a row if this is a permanent doc)`);
|
|
144
|
+
}
|
|
145
|
+
} catch {
|
|
146
|
+
// DOCS.md unreadable — skip silently
|
|
147
|
+
}
|
|
148
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* GateEnforcement.hook.ts — PreToolUse gate for harness gate failures
|
|
4
|
+
*
|
|
5
|
+
* SC-369 (HOOK-ARCHITECTURE-SPEC): hook under 100 lines, logic in lib/
|
|
6
|
+
* SC-370 (HOOK-ARCHITECTURE-SPEC): Hook SC traceability
|
|
7
|
+
*
|
|
8
|
+
* TRIGGER: PreToolUse (matcher: ".*" — fires on every tool call)
|
|
9
|
+
*
|
|
10
|
+
* PURPOSE:
|
|
11
|
+
* When a harness gate fails, nag the DA on every tool call until fixed.
|
|
12
|
+
* After max_strikes, block Skill calls (Bash/Read/Agent still work for fixing).
|
|
13
|
+
* OUTCOME AC failures get immediate block — no strike counting.
|
|
14
|
+
*
|
|
15
|
+
* This file is a trigger only: parse stdin, call runGateEnforcement, print,
|
|
16
|
+
* exit 0. Every decision — strike counting, block vs nag, signal logging, the
|
|
17
|
+
* doc-hygiene sweep — lives in lib/gate-enforcement.ts, where it is reachable
|
|
18
|
+
* from a test without simulating a PreToolUse payload (HOOK-ARCHITECTURE D-1).
|
|
19
|
+
*
|
|
20
|
+
* INPUT:
|
|
21
|
+
* - stdin: PreToolUse JSON payload { tool_name, tool_input, session_id, ... }
|
|
22
|
+
*
|
|
23
|
+
* OUTPUT:
|
|
24
|
+
* - stdout: JSON block decision OR system-reminder nag
|
|
25
|
+
* - stderr: status messages
|
|
26
|
+
* - exit(0): always
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import { join } from 'path';
|
|
30
|
+
import { BASE_DIR, WORK_DIR } from './lib/paths';
|
|
31
|
+
import { parseHookInput } from './lib/parseStdin';
|
|
32
|
+
import { runGateEnforcement } from '../lib/gate-enforcement';
|
|
33
|
+
|
|
34
|
+
const SIGNALS_DIR = join(BASE_DIR, 'MEMORY', 'LEARNING', 'SIGNALS');
|
|
35
|
+
|
|
36
|
+
async function main() {
|
|
37
|
+
const input = await parseHookInput();
|
|
38
|
+
if (!input) process.exit(0);
|
|
39
|
+
|
|
40
|
+
try {
|
|
41
|
+
const { stdout } = runGateEnforcement({
|
|
42
|
+
workDir: WORK_DIR,
|
|
43
|
+
signalsDir: SIGNALS_DIR,
|
|
44
|
+
signalsFile: join(SIGNALS_DIR, 'signals.jsonl'),
|
|
45
|
+
pendingFile: join(BASE_DIR, 'MEMORY', 'STATE', 'gate-pending.json'),
|
|
46
|
+
projectRoot: join(BASE_DIR, '..'),
|
|
47
|
+
sessionId: input.session_id || '',
|
|
48
|
+
toolName: input.tool_name || '',
|
|
49
|
+
});
|
|
50
|
+
if (stdout) console.log(stdout);
|
|
51
|
+
} catch (err) {
|
|
52
|
+
console.error(`[GateEnforcement] Error: ${err}`);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
process.exit(0);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
main();
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* GateResultProtection.hook.ts — PreToolUse on Write + Edit
|
|
4
|
+
*
|
|
5
|
+
* Governing SCs: SC-370 (traceability), SC-371 (thin trigger, under 150 lines)
|
|
6
|
+
*
|
|
7
|
+
* TRIGGER: PreToolUse (matcher: Write, Edit)
|
|
8
|
+
*
|
|
9
|
+
* PURPOSE:
|
|
10
|
+
* Block direct writes to workflow-state.json that modify gate result fields.
|
|
11
|
+
* Gate results must be produced by the gate runner, not written directly.
|
|
12
|
+
*
|
|
13
|
+
* PROTECTED FIELDS:
|
|
14
|
+
* - gates.<name>.result, for every name in lib/gate-names.ts
|
|
15
|
+
* - phase = "DONE" (only the gate runner advances to DONE)
|
|
16
|
+
*
|
|
17
|
+
* ALLOWED:
|
|
18
|
+
* - Writes that don't target workflow-state.json
|
|
19
|
+
* - Writes to workflow-state.json that don't touch gate result fields
|
|
20
|
+
* (e.g., adding ACs, updating changelog, setting phase to BUILD/SCOPE/VERIFY)
|
|
21
|
+
*
|
|
22
|
+
* REFUSED, and this is the #1137 change:
|
|
23
|
+
* - A Write to workflow-state.json whose content does not parse as JSON.
|
|
24
|
+
* It used to be allowed. See lib/gate-result-protection.ts for why that
|
|
25
|
+
* was backwards, and for why the Edit branch decodes unicode escapes.
|
|
26
|
+
*
|
|
27
|
+
* PORTABILITY (#713): `workflow-state.json` is a rungate gate artifact. Both
|
|
28
|
+
* imports are rungate-owned and both sit in `package.json` `files[]`, so this
|
|
29
|
+
* guards the same artifact on a consumer repo as it does here.
|
|
30
|
+
*
|
|
31
|
+
* Issues: #471, #1137
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
import { parseHookInput } from './lib/parseStdin';
|
|
35
|
+
import { decideGateResultWrite } from '../lib/gate-result-protection';
|
|
36
|
+
|
|
37
|
+
async function main() {
|
|
38
|
+
const input = await parseHookInput();
|
|
39
|
+
// No parseable hook payload is not a tool call we can read, and every hook
|
|
40
|
+
// in this tree treats it as a no-op. It is not the decision surface: by
|
|
41
|
+
// definition it names no file, so it cannot be a write to a gate artifact.
|
|
42
|
+
if (!input) process.exit(0);
|
|
43
|
+
|
|
44
|
+
let decision;
|
|
45
|
+
try {
|
|
46
|
+
decision = decideGateResultWrite(
|
|
47
|
+
input.tool_name || '',
|
|
48
|
+
(input.tool_input || {}) as Record<string, unknown>,
|
|
49
|
+
);
|
|
50
|
+
} catch (e) {
|
|
51
|
+
// A guard that crashes must not thereby allow the thing it guards (#1137).
|
|
52
|
+
// Scoped to a payload that already named workflow-state.json, so a bug
|
|
53
|
+
// here refuses writes to one artifact rather than bricking the session.
|
|
54
|
+
const named = String((input.tool_input as { file_path?: unknown })?.file_path ?? '');
|
|
55
|
+
if (!named.endsWith('workflow-state.json')) process.exit(0);
|
|
56
|
+
decision = {
|
|
57
|
+
blocked: true,
|
|
58
|
+
reason: `Refused: gate-result protection could not evaluate this write (${String(e)}).`,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (decision.blocked) {
|
|
63
|
+
console.log(JSON.stringify({ decision: 'block', reason: decision.reason }));
|
|
64
|
+
}
|
|
65
|
+
// If not blocked, exit silently (allow)
|
|
66
|
+
process.exit(0);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
main().catch(() => process.exit(0));
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* HarnessAFKGate.hook.ts - Block AskUserQuestion during AFK harness runs (PreToolUse)
|
|
4
|
+
*
|
|
5
|
+
* Governing SCs: SC-370 (traceability), SC-371 (thin trigger, under 150 lines)
|
|
6
|
+
*
|
|
7
|
+
* PURPOSE:
|
|
8
|
+
* When a harness PRD exists with phase in build/execute/verify (post-approval
|
|
9
|
+
* phases), block AskUserQuestion calls. The agent must make judgment calls
|
|
10
|
+
* autonomously — interrupting the user during AFK harness runs is a protocol
|
|
11
|
+
* violation.
|
|
12
|
+
*
|
|
13
|
+
* TRIGGER: PreToolUse (matcher: AskUserQuestion)
|
|
14
|
+
*
|
|
15
|
+
* BEHAVIOR:
|
|
16
|
+
* - Scans WORK_DIR for the most recently modified PRD.md
|
|
17
|
+
* - If PRD frontmatter has phase: build|execute|verify → BLOCK (exit 2 with reason)
|
|
18
|
+
* - If no PRD, or phase is observe|think|plan|complete|learn → ALLOW (exit 0)
|
|
19
|
+
*
|
|
20
|
+
* This is a mechanical enforcement — impossible to violate.
|
|
21
|
+
* See HARNESS-STANDARD.md "AFK autonomy rule" for the policy.
|
|
22
|
+
*
|
|
23
|
+
* PORTABILITY (#713): the work directory comes from `./lib/paths`'s
|
|
24
|
+
* `WORK_DIR`, which resolves `RUNGATE_WORK_DIR` and otherwise `~/.rungate` —
|
|
25
|
+
* a rungate-owned directory, not a PAI one. The `.pai` copy's docstring said
|
|
26
|
+
* it scanned `MEMORY/WORK/`; that was stale there and is corrected here,
|
|
27
|
+
* because a shipped hook's stated behaviour is what a consumer debugs against.
|
|
28
|
+
* The PRD-driven ship lifecycle is rungate's own.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import { readdirSync, readFileSync, statSync } from 'fs';
|
|
32
|
+
import { join } from 'path';
|
|
33
|
+
import { WORK_DIR } from './lib/paths';
|
|
34
|
+
|
|
35
|
+
const BLOCKED_PHASES = new Set(['build', 'execute', 'verify']);
|
|
36
|
+
|
|
37
|
+
function findLatestPRD(): { path: string; phase: string } | null {
|
|
38
|
+
try {
|
|
39
|
+
const dirs = readdirSync(WORK_DIR, { withFileTypes: true })
|
|
40
|
+
.filter(d => d.isDirectory())
|
|
41
|
+
.map(d => {
|
|
42
|
+
const prdPath = join(WORK_DIR, d.name, 'PRD.md');
|
|
43
|
+
try {
|
|
44
|
+
const stat = statSync(prdPath);
|
|
45
|
+
return { path: prdPath, mtime: stat.mtimeMs };
|
|
46
|
+
} catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
})
|
|
50
|
+
.filter(Boolean)
|
|
51
|
+
.sort((a, b) => b!.mtime - a!.mtime) as { path: string; mtime: number }[];
|
|
52
|
+
|
|
53
|
+
if (dirs.length === 0) return null;
|
|
54
|
+
|
|
55
|
+
const content = readFileSync(dirs[0].path, 'utf-8');
|
|
56
|
+
const phaseMatch = content.match(/^phase:\s*(.+)$/m);
|
|
57
|
+
if (!phaseMatch) return null;
|
|
58
|
+
|
|
59
|
+
return { path: dirs[0].path, phase: phaseMatch[1].trim() };
|
|
60
|
+
} catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function main() {
|
|
66
|
+
const prd = findLatestPRD();
|
|
67
|
+
|
|
68
|
+
if (!prd) {
|
|
69
|
+
process.exit(0); // No active harness — allow questions
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (BLOCKED_PHASES.has(prd.phase)) {
|
|
73
|
+
// BLOCK: harness is in post-approval phase
|
|
74
|
+
const reason = `HARNESS AFK GATE: Active PRD in "${prd.phase}" phase — AskUserQuestion blocked. Make the judgment call yourself. Only circuit breakers and destructive actions may interrupt the user.`;
|
|
75
|
+
console.error(`[HarnessAFKGate] BLOCKED: ${prd.phase} phase active`);
|
|
76
|
+
// Exit 2 = block with reason shown to the AI
|
|
77
|
+
process.stdout.write(JSON.stringify({ error: reason }));
|
|
78
|
+
process.exit(2);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Phase is observe/think/plan/complete/learn — allow questions
|
|
82
|
+
process.exit(0);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
main();
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* HookCurrency.hook.ts — report installed git hooks that are not what the
|
|
4
|
+
* generator produces today (#879)
|
|
5
|
+
*
|
|
6
|
+
* SC-370 (HOOK-ARCHITECTURE-SPEC): Hook SC traceability
|
|
7
|
+
* SC-371 (HOOK-ARCHITECTURE-SPEC): No hook exceeds 150 lines
|
|
8
|
+
*
|
|
9
|
+
* TRIGGER: SessionStart
|
|
10
|
+
*
|
|
11
|
+
* CADENCE, stated rather than implied: once per session. Not PreToolUse.
|
|
12
|
+
* The reading costs a `git rev-parse`, two file reads and a string compare,
|
|
13
|
+
* which is nothing per session and is noise on every tool call — and a
|
|
14
|
+
* message an operator sees forty times an hour is a message they stop
|
|
15
|
+
* reading, which is the failure mode this hook exists to avoid rather than
|
|
16
|
+
* one it can afford to risk.
|
|
17
|
+
*
|
|
18
|
+
* #874 taught the check to read the hook git will actually run. #891 taught
|
|
19
|
+
* it to read every hook the scaffold installs rather than one. Neither
|
|
20
|
+
* reached anybody, because nothing ran it: the script had to be remembered,
|
|
21
|
+
* and `.git/hooks/` is untracked, so a developer whose pre-commit predates a
|
|
22
|
+
* fix has no position in the repository that can tell them. Measured on this
|
|
23
|
+
* repository on 2026-10-21, both hooks were stale and had been for days.
|
|
24
|
+
*
|
|
25
|
+
* Thin trigger: every decision is `scripts/check-installed-hook-currency.ts`.
|
|
26
|
+
* This file chooses a root, prints, and exits 0.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import { existsSync } from 'fs';
|
|
30
|
+
import { join } from 'path';
|
|
31
|
+
import { repoRootFrom } from '../lib/paths';
|
|
32
|
+
import {
|
|
33
|
+
readHookCurrency,
|
|
34
|
+
currencyClass,
|
|
35
|
+
currencyLines,
|
|
36
|
+
defaultGeneratorRoot,
|
|
37
|
+
REFUSAL_PREFIX,
|
|
38
|
+
} from '../scripts/check-installed-hook-currency';
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* A SessionStart hook never fails the session. Every exit here is 0, and
|
|
42
|
+
* that is the whole of #879's third criterion: a fresh clone, a CI checkout
|
|
43
|
+
* and a tree whose hooks are perfect must all be survivable, so the only
|
|
44
|
+
* thing this hook can do about a stale hook is SAY so.
|
|
45
|
+
*
|
|
46
|
+
* It is also why the refusal CLASS matters more here than the exit code.
|
|
47
|
+
* With no class to read, "no pre-commit is installed" and "the pre-commit
|
|
48
|
+
* that runs on every commit predates #728" would arrive under one label,
|
|
49
|
+
* and the fresh clone's harmless reading would train the operator to
|
|
50
|
+
* ignore the other one.
|
|
51
|
+
*/
|
|
52
|
+
function report(line: string): void {
|
|
53
|
+
console.log(line);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const PROJECT_ROOT = repoRootFrom(process.cwd());
|
|
57
|
+
if (!PROJECT_ROOT) {
|
|
58
|
+
// Not a refusal and not a clean report. UNMEASURED by name, because a
|
|
59
|
+
// session opened outside a repository has not been found to have current
|
|
60
|
+
// hooks — it has not been asked (#68 is the same mistake, made silently).
|
|
61
|
+
report('Hook currency UNMEASURED: cwd is not inside a git repository');
|
|
62
|
+
process.exit(0);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// A tree the scaffold has never touched has no hooks of ours to be stale,
|
|
66
|
+
// and reporting on one every session would be noise in exactly the projects
|
|
67
|
+
// that have not opted in. Gated on the directory the hooks live in, the way
|
|
68
|
+
// StaleTTLCleanup gates its sweeps.
|
|
69
|
+
if (!existsSync(join(PROJECT_ROOT, '.git')) && !existsSync(join(PROJECT_ROOT, '.git/hooks'))) {
|
|
70
|
+
process.exit(0);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
try {
|
|
74
|
+
const { current, refusals } = await readHookCurrency(PROJECT_ROOT, defaultGeneratorRoot());
|
|
75
|
+
const cls = currencyClass(refusals);
|
|
76
|
+
|
|
77
|
+
if (cls === null) {
|
|
78
|
+
// Said out loud rather than passed over in silence. Silence is what the
|
|
79
|
+
// last two fixes shipped into, and it is indistinguishable from a hook
|
|
80
|
+
// that did not run.
|
|
81
|
+
report(`Hook currency: ${current.length} installed hook(s) current`);
|
|
82
|
+
} else {
|
|
83
|
+
// No remedy line here. The refusal already carries one, composed by the
|
|
84
|
+
// code that knows WHICH fix the installed copy predates, and a second
|
|
85
|
+
// one written at this distance was both a duplicate decider and wrong:
|
|
86
|
+
// it hardcoded a `node_modules/rungate/` path, which is right for a
|
|
87
|
+
// consumer and wrong in rungate's own checkout. Measured before it was
|
|
88
|
+
// deleted.
|
|
89
|
+
report(`${REFUSAL_PREFIX[cls]}: ${currencyLines(refusals)}`);
|
|
90
|
+
if (current.length > 0) report(` (current: ${current.length} other hook(s))`);
|
|
91
|
+
}
|
|
92
|
+
} catch (e) {
|
|
93
|
+
// A hook that cannot take the reading says so. Swallowing this would make
|
|
94
|
+
// a broken check byte-indistinguishable from a clean tree, which is the
|
|
95
|
+
// state #879 found the repository in.
|
|
96
|
+
report(`Hook currency UNMEASURED: ${e instanceof Error ? e.message : String(e)}`);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
process.exit(0);
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* IssueCloseGuard.hook.ts — PreToolUse on Bash
|
|
4
|
+
*
|
|
5
|
+
* SC-370 (HOOK-ARCHITECTURE-SPEC): Hook SC traceability
|
|
6
|
+
* SC-371 (HOOK-ARCHITECTURE-SPEC): No hook exceeds 150 lines
|
|
7
|
+
*
|
|
8
|
+
* Blocks a close if ship-gate hasn't passed. Validates HMAC provenance on
|
|
9
|
+
* PASS results, and comment templates on gh issue comment.
|
|
10
|
+
*
|
|
11
|
+
* ## This is a speed bump. It is not an authorization boundary. (#144)
|
|
12
|
+
*
|
|
13
|
+
* Read this before opening a security review against the parser below.
|
|
14
|
+
* Deciding, from the TEXT of a Bash command, whether it will close an issue
|
|
15
|
+
* means reimplementing shell quoting and expansion plus gh's flag parser.
|
|
16
|
+
* Five review rounds on 2026-10-06 each found a real differential; a sixth
|
|
17
|
+
* would too. `gh api -X PATCH repos/o/n/issues/23 -f state=closed` mentions
|
|
18
|
+
* neither word it looks for, and neither does a wrapper script, an alias,
|
|
19
|
+
* `xargs`, curl, or the web UI.
|
|
20
|
+
*
|
|
21
|
+
* **Jason's decision, 2026-10-08: Option C.** Kept, because it is fast and
|
|
22
|
+
* has caught real mistakes — and reclassified to fast feedback. The control
|
|
23
|
+
* is `scripts/audit-issue-closures.ts`, scheduled by
|
|
24
|
+
* `.github/workflows/issue-audit.yml`, which reads the OUTCOME and so cannot
|
|
25
|
+
* be bypassed by phrasing. A bypass found here is NOT a defect to file;
|
|
26
|
+
* tightening the pattern is the loop #144 exists to end. See
|
|
27
|
+
* specs/HARNESS-STANDARD.md § SC-833..836.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { createHmac } from 'crypto';
|
|
31
|
+
import { readFileSync, existsSync, writeFileSync } from 'fs';
|
|
32
|
+
import { join } from 'path';
|
|
33
|
+
import { parseHookInput, findWorkflowState, parseCloseTarget, redactSecrets, HARNESS_ROOT } from './lib/utils';
|
|
34
|
+
import { commentTemplateViolation, COMMENT_INVOCATION } from './lib/comment-template';
|
|
35
|
+
import { createGitHubClient, getIssue } from '../lib/github';
|
|
36
|
+
|
|
37
|
+
function block(reason: string): never {
|
|
38
|
+
console.log(JSON.stringify({ decision: 'block', reason }));
|
|
39
|
+
process.exit(0);
|
|
40
|
+
throw new Error('unreachable');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Rules live in hooks/lib/comment-template.ts — SC-371 caps this file at 150.
|
|
44
|
+
function validateCommentTemplate(command: string) {
|
|
45
|
+
const violation = commentTemplateViolation(command);
|
|
46
|
+
if (violation) block(violation);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function validateHmac(wf: any, slug: string, issueNum: string) {
|
|
50
|
+
const gateHash = wf.gates?.ship?.hash;
|
|
51
|
+
const saltPath = join(HARNESS_ROOT, 'gates', '.gate-salt');
|
|
52
|
+
if (!gateHash || !existsSync(saltPath)) {
|
|
53
|
+
if (!gateHash) console.error('[close-guard] WARN: Ship PASS without HMAC');
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
const salt = readFileSync(saltPath, 'utf-8').trim();
|
|
57
|
+
const commitSha = wf.gates?.ship?.commitSha || 'unknown';
|
|
58
|
+
const hmacInput = `${slug}:${wf.issue}:PASS:${commitSha}`;
|
|
59
|
+
const expected = createHmac('sha256', salt).update(hmacInput).digest('hex').substring(0, 16);
|
|
60
|
+
if (gateHash !== expected) block(`Cannot close #${issueNum} — gate HMAC mismatch. Results may be fabricated.`);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function main() {
|
|
64
|
+
const input = await parseHookInput();
|
|
65
|
+
if (!input || input.tool_name !== 'Bash') process.exit(0);
|
|
66
|
+
|
|
67
|
+
const command = input.tool_input?.command || '';
|
|
68
|
+
|
|
69
|
+
if (COMMENT_INVOCATION.test(command)) {
|
|
70
|
+
validateCommentTemplate(command);
|
|
71
|
+
process.exit(0);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// parseCloseTarget reports whether the command is simple enough to vet.
|
|
75
|
+
// Anything unreadable is refused, not guessed: a guess here checks one
|
|
76
|
+
// issue's labels and closes another's.
|
|
77
|
+
const target = parseCloseTarget(command);
|
|
78
|
+
if (target.kind === 'none') process.exit(0);
|
|
79
|
+
if (target.kind === 'ambiguous') {
|
|
80
|
+
block(`Cannot vet this close — ${target.reason}.`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const issueNum = target.issue;
|
|
84
|
+
|
|
85
|
+
// #143: the repo must come from the same parse result as the issue number,
|
|
86
|
+
// and only from the closing segment. Do NOT infer it from the git remote —
|
|
87
|
+
// PR #154 did and review found two bypasses. See HOOK-ARCHITECTURE-SPEC.
|
|
88
|
+
if (!target.repo) {
|
|
89
|
+
block(
|
|
90
|
+
`Cannot close #${issueNum} — the command names no repository, so the guard cannot tell ` +
|
|
91
|
+
// Deliberately no GH_REPO suggestion: the parser matches --repo/-R only,
|
|
92
|
+
// so naming it here taught operators how to create the bypass.
|
|
93
|
+
`which issue #${issueNum} is. Re-run it naming one: --repo owner/name.`,
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
const repo = target.repo;
|
|
97
|
+
|
|
98
|
+
const wf = findWorkflowState(issueNum);
|
|
99
|
+
if (!wf) {
|
|
100
|
+
// #140: the labels are the only evidence left here, and FAILING to read
|
|
101
|
+
// them is not the same as reading them and finding nothing. Only one of
|
|
102
|
+
// those is safe to treat as permission, so the catch below blocks rather
|
|
103
|
+
// than warning. Do not reintroduce an empty catch.
|
|
104
|
+
let labelNames: string;
|
|
105
|
+
try {
|
|
106
|
+
const github = createGitHubClient();
|
|
107
|
+
const issueData = await getIssue(github, repo, parseInt(issueNum, 10));
|
|
108
|
+
labelNames = (issueData.labels || []).map((l: any) => typeof l === 'string' ? l : l.name).join('\n');
|
|
109
|
+
} catch (e: any) {
|
|
110
|
+
// Scrub before printing — the message can carry the request URL, and a
|
|
111
|
+
// block reason is echoed into transcripts and issue comments.
|
|
112
|
+
const detail = redactSecrets(String(e?.message || e)).slice(0, 200);
|
|
113
|
+
block(
|
|
114
|
+
// Naming the repo is not decoration: it is how anyone sees WHICH
|
|
115
|
+
// repository the guard vetted, which is the defect #143 reports.
|
|
116
|
+
`Cannot close #${issueNum} — no workflow-state.json, and its labels in ${repo} could ` +
|
|
117
|
+
`not be read to check whether it is protected: ${detail}\n` +
|
|
118
|
+
`Fix the GitHub access (GITHUB_TOKEN or GH_TOKEN) and retry, or close it on GitHub ` +
|
|
119
|
+
`directly if you have already confirmed it does not need to ship.`,
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
if (labelNames.includes('p1-ship-next') || labelNames.includes('p2-this-week')) {
|
|
124
|
+
block(`Cannot close #${issueNum} — has ${labelNames.includes('p1') ? 'p1-ship-next' : 'p2-this-week'} label but no workflow-state.json. Run /ship first.`);
|
|
125
|
+
}
|
|
126
|
+
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>`);
|
|
127
|
+
process.exit(0);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const state = wf.data;
|
|
131
|
+
if (state.gates?.ship?.result === 'PASS') {
|
|
132
|
+
validateHmac(state, wf.slug, issueNum);
|
|
133
|
+
try {
|
|
134
|
+
state.phase = 'DONE';
|
|
135
|
+
state.updatedTs = new Date().toISOString();
|
|
136
|
+
writeFileSync(wf.path, JSON.stringify(state, null, 2) + '\n');
|
|
137
|
+
console.error(`[close-guard] Updated phase to DONE for #${issueNum}`);
|
|
138
|
+
} catch (e: any) {
|
|
139
|
+
// Was `catch {}`. Non-fatal (the ship gate passed), but a failed write
|
|
140
|
+
// leaves state reading un-shipped on a closed issue — report it (SC-606).
|
|
141
|
+
console.error(`[close-guard] Could not persist phase=DONE for #${issueNum}: ${redactSecrets(String(e?.message || e)).slice(0, 200)}`);
|
|
142
|
+
}
|
|
143
|
+
process.exit(0);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
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}`);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
main();
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* MergeGuard.hook.ts — PreToolUse on Bash
|
|
4
|
+
*
|
|
5
|
+
* SC-370 (HOOK-ARCHITECTURE-SPEC): Hook SC traceability
|
|
6
|
+
* SC-371 (HOOK-ARCHITECTURE-SPEC): No hook exceeds 150 lines
|
|
7
|
+
*
|
|
8
|
+
* Early warning when git merge targets main/master without verify-gate passing.
|
|
9
|
+
* The pre-push hook is the hard enforcement; this warns so the agent can fix first.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { readdirSync, readFileSync, existsSync, statSync } from 'fs';
|
|
13
|
+
import { join } from 'path';
|
|
14
|
+
import { parseHookInput, WORK_DIR, HARNESS_ROOT } from './lib/utils';
|
|
15
|
+
|
|
16
|
+
const TTL_MS = 4 * 60 * 60 * 1000;
|
|
17
|
+
|
|
18
|
+
function findActiveShipMarker(): { issue: number; workDir: string } | null {
|
|
19
|
+
if (!existsSync(WORK_DIR)) return null;
|
|
20
|
+
try {
|
|
21
|
+
for (const d of readdirSync(WORK_DIR, { withFileTypes: true }).filter(d => d.isDirectory())) {
|
|
22
|
+
const markerPath = join(WORK_DIR, d.name, '.ship-active');
|
|
23
|
+
if (!existsSync(markerPath)) continue;
|
|
24
|
+
if (Date.now() - statSync(markerPath).mtimeMs > TTL_MS) continue;
|
|
25
|
+
try {
|
|
26
|
+
const marker = JSON.parse(readFileSync(markerPath, 'utf-8'));
|
|
27
|
+
if (marker.issue) return { issue: marker.issue, workDir: join(WORK_DIR, d.name) };
|
|
28
|
+
} catch {}
|
|
29
|
+
}
|
|
30
|
+
} catch {}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function checkVerifyGate(workDir: string): boolean {
|
|
35
|
+
const wfPath = join(workDir, 'workflow-state.json');
|
|
36
|
+
if (!existsSync(wfPath)) return false;
|
|
37
|
+
try {
|
|
38
|
+
return JSON.parse(readFileSync(wfPath, 'utf-8')).gates?.verify?.result === 'PASS';
|
|
39
|
+
} catch { return false; }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function main() {
|
|
43
|
+
const input = await parseHookInput();
|
|
44
|
+
if (!input || input.tool_name !== 'Bash') process.exit(0);
|
|
45
|
+
|
|
46
|
+
const command = input.tool_input?.command || '';
|
|
47
|
+
const isMerge = /git\s+merge\s+.*\b(main|master)\b/.test(command) ||
|
|
48
|
+
/git\s+checkout\s+(main|master)\s*[;&|]+\s*git\s+merge/.test(command);
|
|
49
|
+
if (!isMerge) process.exit(0);
|
|
50
|
+
|
|
51
|
+
const ship = findActiveShipMarker();
|
|
52
|
+
if (!ship || checkVerifyGate(ship.workDir)) process.exit(0);
|
|
53
|
+
|
|
54
|
+
const slug = ship.workDir.split('/').pop();
|
|
55
|
+
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>`);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
main();
|