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,70 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* TestSuiteGuard.hook.ts -- PreToolUse on Bash
|
|
4
|
+
* SC-473, SC-370. Tier 3 mechanical enforcement for DIR-L29 + issue #67.
|
|
5
|
+
*
|
|
6
|
+
* Thin trigger: detect a full-suite Bash command, ask lib/test-suite-lock.ts,
|
|
7
|
+
* report the verdict. Both the per-session budget and the cross-session
|
|
8
|
+
* concurrency cap live in the lib module.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { parseHookInput } from './lib/utils';
|
|
12
|
+
import { deriveRunId, deriveWorkerId, evaluateFullSuiteRequest } from '../lib/test-suite-lock';
|
|
13
|
+
|
|
14
|
+
async function main() {
|
|
15
|
+
const input = await parseHookInput();
|
|
16
|
+
if (!input) process.exit(0);
|
|
17
|
+
if (input.tool_name !== 'Bash') process.exit(0);
|
|
18
|
+
|
|
19
|
+
const command = (input.tool_input?.command as string) || '';
|
|
20
|
+
const sessionId = input.session_id || 'default';
|
|
21
|
+
// Sub-agents inherit the parent's session_id, so the rate budget has to be
|
|
22
|
+
// keyed on the worker — session plus working directory (#239). The release
|
|
23
|
+
// hook derives the same identity; acquire and release must agree.
|
|
24
|
+
const workerId = deriveWorkerId(sessionId, input.cwd);
|
|
25
|
+
// ...and the run the worker belongs to, which is the bound #239's fix left
|
|
26
|
+
// open: every agent in a ship run got its own four. Null outside a run
|
|
27
|
+
// worktree, and then only the per-worker rate applies (#194).
|
|
28
|
+
const runId = deriveRunId(input.cwd) ?? undefined;
|
|
29
|
+
|
|
30
|
+
// Fails open: a broken guard must never be able to block the suite it
|
|
31
|
+
// guards. It does NOT fail silently, which is a different thing and was the
|
|
32
|
+
// defect — a guard whose broken state and whose satisfied state look
|
|
33
|
+
// identical cannot be known to have ever fired (#194 SC-642).
|
|
34
|
+
try {
|
|
35
|
+
// `cwd` decides whose repository this suite belongs to (#510). A full
|
|
36
|
+
// suite of a scratch tree — a reviewer's `git archive` export, a fixture
|
|
37
|
+
// repo — is twenty tests and under a second, and charging it against a
|
|
38
|
+
// budget sized for this repository's 400-second run made careful review
|
|
39
|
+
// the thing the guard rationed.
|
|
40
|
+
const decision = evaluateFullSuiteRequest(sessionId, command, {
|
|
41
|
+
workerId,
|
|
42
|
+
runId,
|
|
43
|
+
cwd: input.cwd,
|
|
44
|
+
});
|
|
45
|
+
if (!decision.allow) {
|
|
46
|
+
console.log(JSON.stringify({
|
|
47
|
+
decision: 'block',
|
|
48
|
+
reason: decision.reason,
|
|
49
|
+
}));
|
|
50
|
+
} else if (decision.warning) {
|
|
51
|
+
// Allowed, but the cap is not being enforced. This must reach the
|
|
52
|
+
// transcript: stderr from a hook that exits 0 is only visible under
|
|
53
|
+
// --debug, so the earlier console.error was itself a silent fail-open.
|
|
54
|
+
console.log(JSON.stringify({ systemMessage: decision.warning }));
|
|
55
|
+
}
|
|
56
|
+
} catch (e) {
|
|
57
|
+
// systemMessage, not stderr: stderr from a hook that exits 0 is only
|
|
58
|
+
// visible under --debug, so printing there is the same silence with extra
|
|
59
|
+
// steps.
|
|
60
|
+
console.log(JSON.stringify({
|
|
61
|
+
systemMessage:
|
|
62
|
+
`GUARD-FAILURE-VISIBLE: TestSuiteGuard could not evaluate this full-suite request ` +
|
|
63
|
+
`and allowed it. DIR-L29 is NOT being enforced right now. ` +
|
|
64
|
+
`${(e as Error)?.message ?? e}`,
|
|
65
|
+
}));
|
|
66
|
+
process.exit(0);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
main();
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* TestSuiteRelease.hook.ts -- PostToolUse on Bash
|
|
4
|
+
* Issue #67, SC-370.
|
|
5
|
+
*
|
|
6
|
+
* Thin trigger: when a full suite finishes, hand its concurrency slot back so
|
|
7
|
+
* the next session is not stuck waiting out the 420s TTL after a ~190s run.
|
|
8
|
+
*
|
|
9
|
+
* The TTL is the backstop for when this never fires (crash, reboot, kill -9) --
|
|
10
|
+
* it is what stops a dead session from wedging the repo, so slot correctness
|
|
11
|
+
* does not depend on this hook running.
|
|
12
|
+
*
|
|
13
|
+
* REGISTERED, in user scope. The header this replaced carried #898's
|
|
14
|
+
* unregistered declaration and said the TTL backstop above had been the only
|
|
15
|
+
* mechanism since #67. That was false in both of its claims. Measured
|
|
16
|
+
* 2026-10-21 by parsing `~/.claude/settings.json`:
|
|
17
|
+
*
|
|
18
|
+
* PostToolUse matcher='Bash' bun ${RUNGATE_HOOKS_DIR}/TestSuiteRelease.hook.ts
|
|
19
|
+
*
|
|
20
|
+
* #898's census counted THIS REPOSITORY's registries and read zero as
|
|
21
|
+
* absence; "registered nowhere" is a claim about every scope. The repo's own
|
|
22
|
+
* `test/test-suite-guard-registration.test.ts` has asserted the opposite since
|
|
23
|
+
* #67-A and was green the whole time. `lib/hook-scopes.ts` is the reading that
|
|
24
|
+
* now cannot be taken from one scope (#713, #910).
|
|
25
|
+
*
|
|
26
|
+
* ## Execution evidence, which was the part nobody could check
|
|
27
|
+
*
|
|
28
|
+
* This hook used to write nothing. So "did it release the slot?" had no
|
|
29
|
+
* answer available to any search, and an absent slot file was equally
|
|
30
|
+
* consistent with a release that fired and a TTL that expired. Every decision
|
|
31
|
+
* on a full-suite command now leaves a record in `hook-firings.jsonl` under
|
|
32
|
+
* the rungate work dir -- `released`, `declined-background`, or
|
|
33
|
+
* `release-failed`.
|
|
34
|
+
*
|
|
35
|
+
* Only full-suite commands are recorded. This hook is attached to EVERY Bash
|
|
36
|
+
* call in every session, and a record per call is a file nobody can read.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
import { parseHookInput } from './lib/utils';
|
|
40
|
+
import { deriveWorkerId, isFullSuiteCommand, releaseFullSuiteSlot } from '../lib/test-suite-lock';
|
|
41
|
+
import { commandDigestFacts, errorFacts, recordHookFiring } from '../lib/hook-evidence';
|
|
42
|
+
|
|
43
|
+
const HOOK = 'TestSuiteRelease';
|
|
44
|
+
|
|
45
|
+
async function main() {
|
|
46
|
+
const input = await parseHookInput();
|
|
47
|
+
if (!input) process.exit(0);
|
|
48
|
+
if (input.tool_name !== 'Bash') process.exit(0);
|
|
49
|
+
|
|
50
|
+
const command = (input.tool_input?.command as string) || '';
|
|
51
|
+
const sessionId = input.session_id || 'default';
|
|
52
|
+
// Never the raw command: a Bash call routinely carries leading env
|
|
53
|
+
// assignments, and those carry tokens (#970 review, finding 1).
|
|
54
|
+
const facts = commandDigestFacts(command);
|
|
55
|
+
|
|
56
|
+
try {
|
|
57
|
+
// Out of population: not a full suite, so this hook has nothing to say
|
|
58
|
+
// about it and records nothing. Everything below IS in population, and
|
|
59
|
+
// every path out of it leaves a record -- a decline and a hook that never
|
|
60
|
+
// ran are otherwise the same observation, which is #910.
|
|
61
|
+
if (!isFullSuiteCommand(command)) process.exit(0);
|
|
62
|
+
|
|
63
|
+
// A backgrounded Bash call returns immediately while the suite keeps
|
|
64
|
+
// running. Releasing here would hand the slot back mid-run and restore the
|
|
65
|
+
// concurrency the guard exists to prevent. Let the TTL reclaim it instead.
|
|
66
|
+
if (input.tool_input?.run_in_background) {
|
|
67
|
+
recordHookFiring(HOOK, 'declined-background', { ...facts, sessionId, cwd: input.cwd });
|
|
68
|
+
process.exit(0);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Same derivation as the guard (#239): a release that named only the
|
|
72
|
+
// session could free a sibling worker's slot while its suite still runs.
|
|
73
|
+
const workerId = deriveWorkerId(sessionId, input.cwd);
|
|
74
|
+
releaseFullSuiteSlot(sessionId, { workerId });
|
|
75
|
+
recordHookFiring(HOOK, 'released', { ...facts, sessionId, workerId, cwd: input.cwd });
|
|
76
|
+
} catch (e) {
|
|
77
|
+
// A failed release is recovered by the TTL; never surface it as a tool
|
|
78
|
+
// error. It IS recorded: a release that threw and a release that never
|
|
79
|
+
// happened leave the same empty lock dir behind.
|
|
80
|
+
recordHookFiring(HOOK, 'release-failed', { ...facts, sessionId, ...errorFacts(e) });
|
|
81
|
+
process.exit(0);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
main();
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* TopLevelCdGuard.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
|
+
* The decision lives in lib/top-level-cd.ts and not here — hooks are thin
|
|
9
|
+
* triggers (HOOK-ARCHITECTURE-SPEC), the same shape as VerifyPhaseLock over
|
|
10
|
+
* lib/issue-create-override.ts and BashToolGuard over lib/bash-file-read.ts.
|
|
11
|
+
*
|
|
12
|
+
* Refuses a Bash command whose TOP LEVEL begins with or chains to `cd`.
|
|
13
|
+
*
|
|
14
|
+
* Why a hook and not a sentence. A top-level `cd` moves the SESSION's primary
|
|
15
|
+
* working directory, and the agent runtime resolves `isolation: 'worktree'`
|
|
16
|
+
* against that directory — so a `cd` out of the repo kills another agent's
|
|
17
|
+
* worktree creation hours later, with no error naming the cause. The prose
|
|
18
|
+
* rule existed, at maximum emphasis, at the top of every brief. On 2026-10-21
|
|
19
|
+
* four independent actors broke it in one evening, including the person who
|
|
20
|
+
* wrote it and the agent that built this hook. The conclusion was not to state
|
|
21
|
+
* it more loudly: `VerifyPhaseLock` holds because it is not advice.
|
|
22
|
+
*
|
|
23
|
+
* REGISTERED, as a hard refusal, by #992. Jason's decision, taken against the
|
|
24
|
+
* measurement on that issue — 32.7% of 31,577 recorded commands carry a
|
|
25
|
+
* top-level `cd`, so this fires often, and that is the point rather than an
|
|
26
|
+
* argument against it. The registration is four positions and they must agree
|
|
27
|
+
* (`.claude/rules/self-referential-tests.md`): this comment's `SC-` ids,
|
|
28
|
+
* `.claude/rungate/hooks.json`, the current-state table in
|
|
29
|
+
* `specs/HOOK-ARCHITECTURE-SPEC.md`, and `.claude/settings.json`.
|
|
30
|
+
*
|
|
31
|
+
* It is registered at PROJECT scope. `${CLAUDE_PROJECT_DIR}` resolves to the
|
|
32
|
+
* worktree a session is in, every worktree carries the committed
|
|
33
|
+
* `.claude/settings.json`, and worktree isolation — the thing a stray `cd`
|
|
34
|
+
* breaks — is a harness concern. Machine-wide registration lives in
|
|
35
|
+
* `~/.claude/settings.json`, which no PR can carry and no test here can
|
|
36
|
+
* honestly assert (`test/hook-registration-reconciler.test.ts`).
|
|
37
|
+
*
|
|
38
|
+
* ## The rung, and what #1040 left behind
|
|
39
|
+
*
|
|
40
|
+
* #1040 built the ladder — `RUNGATE_CD_GUARD` reads `warn` | `block` | `off`
|
|
41
|
+
* — and took no rung, so the decision would be a configuration choice rather
|
|
42
|
+
* than a code change made under pressure. The choice has now been made and
|
|
43
|
+
* it is `block`: `cdGuardMode`'s default moved, so the hook refuses unless a
|
|
44
|
+
* caller opts out. `warn` and `off` are both still reachable, which is what
|
|
45
|
+
* makes this reversible without touching code.
|
|
46
|
+
*
|
|
47
|
+
* It is SCOPED to harnessed projects via `lib/harness-project.ts`, the same
|
|
48
|
+
* decider `BashToolGuard` uses — #1040's scoping, unchanged. A top-level
|
|
49
|
+
* `cd` costs something only in a session with concurrent agents holding
|
|
50
|
+
* worktrees.
|
|
51
|
+
*
|
|
52
|
+
* ## What this will cost, measured rather than guessed
|
|
53
|
+
*
|
|
54
|
+
* 21 Bash commands in this repo's own agent prompts — `workflows/ship.js`,
|
|
55
|
+
* `prove.js`, `verify.js` — open with a top-level `cd` and are refused by
|
|
56
|
+
* this guard. Those workflows are not in use (`.claude/rules/ship-workflow.md`,
|
|
57
|
+
* direct-ship mode since 2026-10-19) and the count is on #992's PR, but it is
|
|
58
|
+
* the first thing to fix if harness mode comes back. `git -C`, a subshell and
|
|
59
|
+
* `bun --cwd` are each a one-line change at those sites.
|
|
60
|
+
*
|
|
61
|
+
* The parse, and what it cannot see, is `lib/top-level-cd.ts`. Read its
|
|
62
|
+
* WHAT THIS DOES NOT COVER block before trusting this to stop anything.
|
|
63
|
+
*
|
|
64
|
+
* Issue: #992
|
|
65
|
+
*/
|
|
66
|
+
|
|
67
|
+
import { parseHookInput } from './lib/parseStdin';
|
|
68
|
+
import { CD_GUARD_DECISION, cdGuardMode, topLevelCdRefusal } from '../lib/top-level-cd';
|
|
69
|
+
import { isHarnessProject } from '../lib/harness-project';
|
|
70
|
+
|
|
71
|
+
async function main() {
|
|
72
|
+
const payload = await parseHookInput();
|
|
73
|
+
if (!payload) process.exit(0);
|
|
74
|
+
|
|
75
|
+
if (payload.tool_name !== 'Bash') process.exit(0);
|
|
76
|
+
|
|
77
|
+
// Scope before parse: outside a harnessed project there are no peer
|
|
78
|
+
// worktrees to kill, so there is nothing for this to protect.
|
|
79
|
+
if (!isHarnessProject(process.cwd())) process.exit(0);
|
|
80
|
+
|
|
81
|
+
const { mode, unrecognised } = cdGuardMode();
|
|
82
|
+
if (mode === 'off') process.exit(0);
|
|
83
|
+
|
|
84
|
+
// The raw value, NOT `|| ''`. An absent command is unreadable, and the one
|
|
85
|
+
// decider refuses it rather than letting the guard pass over nothing.
|
|
86
|
+
const refusal = topLevelCdRefusal(payload.tool_input?.command);
|
|
87
|
+
if (refusal === null) process.exit(0);
|
|
88
|
+
|
|
89
|
+
const note = unrecognised
|
|
90
|
+
? `\n(${'RUNGATE_CD_GUARD'}=${JSON.stringify(unrecognised)} is not a mode I know; refusing, which is the default.)`
|
|
91
|
+
: '';
|
|
92
|
+
|
|
93
|
+
// `mode` is the configured RUNG and `CD_GUARD_DECISION` is the field the
|
|
94
|
+
// hook protocol reads. They spell the same word today and are not the same
|
|
95
|
+
// fact — collapsing them would break the rung if the protocol ever renamed
|
|
96
|
+
// its verdict — so they stay two names.
|
|
97
|
+
if (mode === 'block') {
|
|
98
|
+
console.log(JSON.stringify({ decision: CD_GUARD_DECISION, reason: refusal.message + note }));
|
|
99
|
+
process.exit(0);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// WARN: the command RUNS. Written to stderr so it reaches the transcript
|
|
103
|
+
// without becoming a tool result the model might read as a refusal.
|
|
104
|
+
console.error(`[top-level-cd] ${refusal.message}${note}`);
|
|
105
|
+
process.exit(0);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
main();
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* VerifyPhaseLock.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 `gh issue create` during VERIFY phase.
|
|
9
|
+
* Use verifyBlockers[] instead. Allows `gh issue create` carrying one of the
|
|
10
|
+
* override labels in lib/issue-create-override.ts.
|
|
11
|
+
*
|
|
12
|
+
* The decision lives in lib/ and not here (#365, HOOK-ARCHITECTURE-SPEC:
|
|
13
|
+
* hooks are thin triggers). It used to be a substring test on the whole
|
|
14
|
+
* command, which a `follow-up` in an issue TITLE satisfied.
|
|
15
|
+
*
|
|
16
|
+
* Issue: #443
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { readFileSync, existsSync, readdirSync, statSync } from 'fs';
|
|
20
|
+
import { join } from 'path';
|
|
21
|
+
import { parseHookInput } from './lib/parseStdin';
|
|
22
|
+
import { verifyPhaseRefusal } from '../lib/issue-create-override';
|
|
23
|
+
|
|
24
|
+
const WORK_DIR = process.env.RUNGATE_WORK_DIR || process.env.PAI_WORK_DIR || join(process.env.HOME!, '.rungate');
|
|
25
|
+
|
|
26
|
+
function findActiveWorkflow(): { path: string; data: any } | null {
|
|
27
|
+
if (!existsSync(WORK_DIR)) return null;
|
|
28
|
+
let best: { path: string; data: any; mtime: number } | null = null;
|
|
29
|
+
|
|
30
|
+
try {
|
|
31
|
+
for (const entry of readdirSync(WORK_DIR, { withFileTypes: true })) {
|
|
32
|
+
if (!entry.isDirectory()) continue;
|
|
33
|
+
const wfPath = join(WORK_DIR, entry.name, 'workflow-state.json');
|
|
34
|
+
if (existsSync(wfPath)) {
|
|
35
|
+
try {
|
|
36
|
+
const data = JSON.parse(readFileSync(wfPath, 'utf-8'));
|
|
37
|
+
const mtime = statSync(wfPath).mtimeMs;
|
|
38
|
+
if (!best || mtime > best.mtime) {
|
|
39
|
+
best = { path: wfPath, data, mtime };
|
|
40
|
+
}
|
|
41
|
+
} catch {}
|
|
42
|
+
}
|
|
43
|
+
const nested = join(WORK_DIR, entry.name);
|
|
44
|
+
try {
|
|
45
|
+
for (const sub of readdirSync(nested, { withFileTypes: true })) {
|
|
46
|
+
if (!sub.isDirectory()) continue;
|
|
47
|
+
const nestedWf = join(nested, sub.name, 'workflow-state.json');
|
|
48
|
+
if (!existsSync(nestedWf)) continue;
|
|
49
|
+
try {
|
|
50
|
+
const data = JSON.parse(readFileSync(nestedWf, 'utf-8'));
|
|
51
|
+
const mtime = statSync(nestedWf).mtimeMs;
|
|
52
|
+
if (!best || mtime > best.mtime) {
|
|
53
|
+
best = { path: nestedWf, data, mtime };
|
|
54
|
+
}
|
|
55
|
+
} catch {}
|
|
56
|
+
}
|
|
57
|
+
} catch {}
|
|
58
|
+
}
|
|
59
|
+
} catch {}
|
|
60
|
+
|
|
61
|
+
return best ? { path: best.path, data: best.data } : null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function main() {
|
|
65
|
+
const payload = await parseHookInput();
|
|
66
|
+
if (!payload) process.exit(0);
|
|
67
|
+
|
|
68
|
+
if (payload.tool_name !== 'Bash') process.exit(0);
|
|
69
|
+
|
|
70
|
+
const cmd = payload.tool_input?.command || '';
|
|
71
|
+
|
|
72
|
+
// Ask the owner BEFORE reading the workflow state. Cheap, and it keeps the
|
|
73
|
+
// whole decision in one place rather than half here and half in lib/.
|
|
74
|
+
const refusal = verifyPhaseRefusal(cmd);
|
|
75
|
+
if (refusal === null) process.exit(0);
|
|
76
|
+
|
|
77
|
+
const wf = findActiveWorkflow();
|
|
78
|
+
if (!wf || wf.data.phase !== 'VERIFY') process.exit(0);
|
|
79
|
+
|
|
80
|
+
console.log(JSON.stringify({ decision: "block", reason: refusal }));
|
|
81
|
+
process.exit(0);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
main();
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* WorkflowStateGuard.hook.ts -- PreToolUse on Write, Edit
|
|
4
|
+
*
|
|
5
|
+
* SC-370 (HOOK-ARCHITECTURE-SPEC): Hook SC traceability
|
|
6
|
+
* SC-371 (HOOK-ARCHITECTURE-SPEC): No hook exceeds 150 lines
|
|
7
|
+
*
|
|
8
|
+
* Blocks direct Write/Edit of workflow-state.json.
|
|
9
|
+
* All writes must go through writeWorkflowState() for Zod validation.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { parseHookInput } from './lib/utils';
|
|
13
|
+
|
|
14
|
+
async function main() {
|
|
15
|
+
const input = await parseHookInput();
|
|
16
|
+
if (!input) process.exit(0);
|
|
17
|
+
|
|
18
|
+
const tool = input.tool_name;
|
|
19
|
+
if (tool !== 'Write' && tool !== 'Edit') process.exit(0);
|
|
20
|
+
|
|
21
|
+
const toolInput = input.tool_input || {};
|
|
22
|
+
|
|
23
|
+
// Write tool uses file_path; Edit tool uses file_path
|
|
24
|
+
const path = (toolInput.file_path as string) || (toolInput.path as string) || '';
|
|
25
|
+
|
|
26
|
+
if (!path.includes('workflow-state.json')) process.exit(0);
|
|
27
|
+
|
|
28
|
+
// Block the write
|
|
29
|
+
const reason = [
|
|
30
|
+
'BLOCKED: workflow-state.json is protected.',
|
|
31
|
+
'All writes must go through writeWorkflowState() for Zod validation.',
|
|
32
|
+
'Use this pattern instead:',
|
|
33
|
+
'',
|
|
34
|
+
'bun -e "import {writeWorkflowState} from \'./gates/orchestrator.ts\'; import {readFileSync} from \'fs\'; const s = JSON.parse(readFileSync(\'WORK_DIR/workflow-state.json\',\'utf8\')); /* apply fix */; writeWorkflowState(\'WORK_DIR/workflow-state.json\', s);"',
|
|
35
|
+
].join('\n');
|
|
36
|
+
|
|
37
|
+
console.log(JSON.stringify({ decision: 'block', reason }));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
main();
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"agents": {
|
|
3
|
+
"marcus": { "match": ["marcus", "engineer", "marcus webb"], "exclude": ["council"] },
|
|
4
|
+
"quinn": { "match": ["quinn", "qatester", "quinn torres"], "exclude": [] },
|
|
5
|
+
"rook": { "match": ["rook", "pentester", "rook blackburn"], "exclude": [] },
|
|
6
|
+
"serena": { "match": ["serena", "architect", "serena blackwood"], "exclude": [] },
|
|
7
|
+
"aditi": { "match": ["aditi", "designer", "aditi sharma"], "exclude": [] }
|
|
8
|
+
}
|
|
9
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared Agent Detection — Config-Driven
|
|
3
|
+
*
|
|
4
|
+
* Reads agent matching patterns from agent-config.json instead of hardcoding.
|
|
5
|
+
* Adding new agents requires only a JSON change, zero code changes.
|
|
6
|
+
*
|
|
7
|
+
* ## The config was not in the tree, and the `catch` hid it (#1000)
|
|
8
|
+
*
|
|
9
|
+
* From #382 until 2026-10-21 this module read an `agent-config.json` that was
|
|
10
|
+
* in no commit on any branch of this repository. `readFileSync` threw
|
|
11
|
+
* `ENOENT`, a bare `catch` returned `{ agents: {} }`, the loop below ran zero
|
|
12
|
+
* times, and `detectAgent` returned `null` for **every** input. Its only
|
|
13
|
+
* consumer, `hooks/CommitEnforcement.hook.ts`, exits on `null` — so that
|
|
14
|
+
* hook's UI-file detection and its uncommitted-changes tripwire never fired
|
|
15
|
+
* once, in either this tree or the registered one.
|
|
16
|
+
*
|
|
17
|
+
* Two things follow, and the second is the one that matters:
|
|
18
|
+
*
|
|
19
|
+
* 1. The config now ships beside this file. Its five agents and the
|
|
20
|
+
* `exclude: ["council"]` on `marcus` are RECOVERED from the copy that has
|
|
21
|
+
* sat at `~/.claude/hooks/lib/agent-config.json` since Sep 9 — not
|
|
22
|
+
* reconstructed from the match patterns, which would have invented the
|
|
23
|
+
* exclusions. (#1000 said the file "has never existed on any branch",
|
|
24
|
+
* which is true of this repo and false of the machine: a census over one
|
|
25
|
+
* scope reporting confident absence, which is #910 and #713 again.)
|
|
26
|
+
*
|
|
27
|
+
* 2. **An unreadable config is a REFUSAL.** Adding the file fixes the outage;
|
|
28
|
+
* it does not fix the thing that let the outage last a month. A bare
|
|
29
|
+
* `catch` returning an empty reading is `.claude/rules/config-access.md`'s
|
|
30
|
+
* *Silent Default Substitution*: "no agent matched" and "I could not read
|
|
31
|
+
* my own config" produced the same `null`, so no search, log or test could
|
|
32
|
+
* tell them apart. Absent, unparseable, wrong-shaped and **zero-agent**
|
|
33
|
+
* configs all throw now. Zero agents is included deliberately — it is the
|
|
34
|
+
* exact value the `catch` used to fabricate, and a real file holding it
|
|
35
|
+
* would reinstate the defect in a form every other check passes.
|
|
36
|
+
*
|
|
37
|
+
* Callers must decide what to do with the throw; `CommitEnforcement` records
|
|
38
|
+
* it as `unmeasured-agent-config` through `lib/hook-evidence.ts` so a hook
|
|
39
|
+
* that COULD NOT RUN stays distinguishable from one that declined (#910).
|
|
40
|
+
*
|
|
41
|
+
* Issue: #374 (extracted from AutoVerifyGate + MarcusCommitCheck)
|
|
42
|
+
* Refactored: #382 (config-driven, supports N agents)
|
|
43
|
+
* Fixed: #1000 (config shipped; silent default substitution removed)
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
import { readFileSync } from 'fs';
|
|
47
|
+
import { fileURLToPath } from 'url';
|
|
48
|
+
import { join, dirname } from 'path';
|
|
49
|
+
import { errorFacts, recordHookFiring } from '../../lib/hook-evidence';
|
|
50
|
+
|
|
51
|
+
interface AgentConfig {
|
|
52
|
+
match: string[];
|
|
53
|
+
exclude?: string[];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
interface AgentConfigFile {
|
|
57
|
+
agents: Record<string, AgentConfig>;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export type AgentKey = string;
|
|
61
|
+
|
|
62
|
+
export interface DetectedAgent {
|
|
63
|
+
key: AgentKey;
|
|
64
|
+
name: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
let _configCache: AgentConfigFile | null = null;
|
|
68
|
+
|
|
69
|
+
/** Raised instead of substituting an empty reading. Named so a caller can tell this apart from a bug in the matcher. */
|
|
70
|
+
export class AgentConfigUnreadable extends Error {
|
|
71
|
+
readonly name = 'AgentConfigUnreadable';
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The config beside this module.
|
|
76
|
+
*
|
|
77
|
+
* `fileURLToPath` and not `new URL(…).pathname`: the latter is
|
|
78
|
+
* percent-encoded, so under any checkout whose path contains a space it
|
|
79
|
+
* produced `…/My%20Repo/…`, `ENOENT`, and — through the old `catch` — this
|
|
80
|
+
* issue's exact symptom from a second, environment-dependent direction.
|
|
81
|
+
*/
|
|
82
|
+
export function agentConfigPath(): string {
|
|
83
|
+
return join(dirname(fileURLToPath(import.meta.url)), 'agent-config.json');
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function loadConfig(): AgentConfigFile {
|
|
87
|
+
if (_configCache) return _configCache;
|
|
88
|
+
const configPath = agentConfigPath();
|
|
89
|
+
|
|
90
|
+
let raw: string;
|
|
91
|
+
try {
|
|
92
|
+
raw = readFileSync(configPath, 'utf-8');
|
|
93
|
+
} catch (e) {
|
|
94
|
+
throw new AgentConfigUnreadable(
|
|
95
|
+
`agent-config.json could not be read at ${configPath}: ${(e as Error).message}`,
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
let parsed: unknown;
|
|
100
|
+
try {
|
|
101
|
+
parsed = JSON.parse(raw);
|
|
102
|
+
} catch (e) {
|
|
103
|
+
throw new AgentConfigUnreadable(
|
|
104
|
+
`agent-config.json at ${configPath} is not valid JSON: ${(e as Error).message}`,
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const agents = (parsed as AgentConfigFile | null)?.agents;
|
|
109
|
+
if (typeof agents !== 'object' || agents === null || Array.isArray(agents)) {
|
|
110
|
+
throw new AgentConfigUnreadable(
|
|
111
|
+
`agent-config.json at ${configPath} has no "agents" object`,
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
// The value the old `catch` invented. A file that really holds it detects
|
|
115
|
+
// nothing, exactly as the missing file did, and would pass every check that
|
|
116
|
+
// only asks whether the config loaded.
|
|
117
|
+
if (Object.keys(agents).length === 0) {
|
|
118
|
+
throw new AgentConfigUnreadable(
|
|
119
|
+
`agent-config.json at ${configPath} declares zero agents, so nothing can ever match`,
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
for (const [key, cfg] of Object.entries(agents)) {
|
|
123
|
+
if (!Array.isArray(cfg?.match) || cfg.match.length === 0) {
|
|
124
|
+
throw new AgentConfigUnreadable(
|
|
125
|
+
`agent-config.json at ${configPath}: agent "${key}" has no match patterns, so it can never be detected`,
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
_configCache = { agents };
|
|
131
|
+
return _configCache;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Detect which known agent a tool invocation targets.
|
|
136
|
+
* Returns null if no agent from config matches.
|
|
137
|
+
*
|
|
138
|
+
* THROWS `AgentConfigUnreadable` if the config cannot be read, parsed, or
|
|
139
|
+
* declares no usable agent. `null` means "no agent matched" and nothing else;
|
|
140
|
+
* a caller that treats the throw as `null` reinstates #1000.
|
|
141
|
+
*
|
|
142
|
+
* Detection signals (checked per agent):
|
|
143
|
+
* 1. Exclude check — if prompt contains any exclude term, skip agent
|
|
144
|
+
* 2. Name contains a match pattern
|
|
145
|
+
* 3. subagent_type equals a match pattern
|
|
146
|
+
* 4. Prompt contains a match pattern
|
|
147
|
+
*/
|
|
148
|
+
export function detectAgent(toolInput: { name?: string; subagent_type?: string; prompt?: string }): DetectedAgent | null {
|
|
149
|
+
const agentName = (toolInput.name || '').toLowerCase();
|
|
150
|
+
const agentType = (toolInput.subagent_type || '').toLowerCase();
|
|
151
|
+
const prompt = (toolInput.prompt || '').toLowerCase();
|
|
152
|
+
const config = loadConfig();
|
|
153
|
+
|
|
154
|
+
for (const [key, cfg] of Object.entries(config.agents)) {
|
|
155
|
+
const excluded = (cfg.exclude || []).some(ex => prompt.includes(ex));
|
|
156
|
+
if (excluded) continue;
|
|
157
|
+
|
|
158
|
+
const matched = cfg.match.some(pattern =>
|
|
159
|
+
agentName.includes(pattern) || agentType === pattern || prompt.includes(pattern)
|
|
160
|
+
);
|
|
161
|
+
if (matched) return { key, name: toolInput.name || key };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* `detectAgent`, with the unreadable case RECORDED instead of silent.
|
|
169
|
+
*
|
|
170
|
+
* This is the form a hook should call. `detectAgent` throws so that no
|
|
171
|
+
* caller can mistake "could not read my config" for "no agent matched", but
|
|
172
|
+
* a `PreToolUse`/`PostToolUse` hook that throws is a crash on every tool
|
|
173
|
+
* call — so the hook needs the throw turned back into a skip, and the ONLY
|
|
174
|
+
* thing that makes that skip safe is the record it leaves behind.
|
|
175
|
+
*
|
|
176
|
+
* Both halves live here rather than in the hook for the reason #1000 exists:
|
|
177
|
+
* the next consumer that writes its own `try { detectAgent() } catch {}` will
|
|
178
|
+
* write the `catch {}`, and that is precisely the defect. One place knows
|
|
179
|
+
* what "could not run" looks like, and it is the place that knows how the
|
|
180
|
+
* reading can fail.
|
|
181
|
+
*
|
|
182
|
+
* Returns `null` for both outcomes; the evidence file is what distinguishes
|
|
183
|
+
* them. Only the unreadable case is recorded — this hook is attached to every
|
|
184
|
+
* `Agent` call, and a record per call is a file nobody can read.
|
|
185
|
+
*/
|
|
186
|
+
export function detectAgentOrRecord(
|
|
187
|
+
toolInput: { name?: string; subagent_type?: string; prompt?: string },
|
|
188
|
+
hook: string,
|
|
189
|
+
detail: Record<string, unknown> = {},
|
|
190
|
+
): DetectedAgent | null {
|
|
191
|
+
try {
|
|
192
|
+
return detectAgent(toolInput);
|
|
193
|
+
} catch (e) {
|
|
194
|
+
recordHookFiring(hook, 'unmeasured-agent-config', {
|
|
195
|
+
...detail,
|
|
196
|
+
configPath: agentConfigPath(),
|
|
197
|
+
...errorFacts(e),
|
|
198
|
+
});
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
}
|