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.
Files changed (63) hide show
  1. package/hooks/ActionVerificationGate.hook.ts +96 -0
  2. package/hooks/AgentBriefGuard.hook.ts +38 -0
  3. package/hooks/AgentVerdictCapture.hook.ts +87 -0
  4. package/hooks/AutoVerifyGate.hook.ts +79 -0
  5. package/hooks/BashToolGuard.hook.ts +65 -0
  6. package/hooks/BashWriteGuard.hook.ts +60 -0
  7. package/hooks/CommitEnforcement.hook.ts +130 -0
  8. package/hooks/DocHygiene.hook.ts +148 -0
  9. package/hooks/GateEnforcement.hook.ts +58 -0
  10. package/hooks/GateResultProtection.hook.ts +69 -0
  11. package/hooks/HarnessAFKGate.hook.ts +85 -0
  12. package/hooks/HookCurrency.hook.ts +99 -0
  13. package/hooks/IssueCloseGuard.hook.ts +149 -0
  14. package/hooks/MergeGuard.hook.ts +58 -0
  15. package/hooks/PostCompact.hook.ts +60 -0
  16. package/hooks/ProjectStateSync.hook.ts +103 -0
  17. package/hooks/SkillGuard.hook.ts +69 -0
  18. package/hooks/SpecConformityTrigger.hook.ts +43 -0
  19. package/hooks/SpecSCGuard.hook.ts +123 -0
  20. package/hooks/StaleTTLCleanup.hook.ts +141 -0
  21. package/hooks/TaskCompleted.hook.ts +51 -0
  22. package/hooks/TeamInit.hook.ts +85 -0
  23. package/hooks/TestSuiteGuard.hook.ts +70 -0
  24. package/hooks/TestSuiteRelease.hook.ts +85 -0
  25. package/hooks/TopLevelCdGuard.hook.ts +108 -0
  26. package/hooks/VerifyPhaseLock.hook.ts +84 -0
  27. package/hooks/WorkflowStateGuard.hook.ts +40 -0
  28. package/hooks/lib/agent-config.json +9 -0
  29. package/hooks/lib/agentDetection.ts +201 -0
  30. package/hooks/lib/comment-template.ts +86 -0
  31. package/hooks/lib/findWorkflow.ts +101 -0
  32. package/hooks/lib/parseStdin.ts +37 -0
  33. package/hooks/lib/paths.ts +111 -0
  34. package/hooks/lib/utils.ts +338 -0
  35. package/lib/affected-tests.ts +29 -0
  36. package/lib/bash-write-guard.ts +373 -0
  37. package/lib/branch-cleanup.ts +279 -7
  38. package/lib/config-trackable.ts +9 -0
  39. package/lib/distribution-currency.ts +55 -5
  40. package/lib/failure-intake.ts +7 -1
  41. package/lib/gate-enforcement.ts +222 -28
  42. package/lib/gate-names.ts +72 -0
  43. package/lib/gate-result-protection.ts +427 -0
  44. package/lib/intake-sources.ts +380 -0
  45. package/lib/late-env-spawn.ts +331 -0
  46. package/lib/launch-base.ts +128 -5
  47. package/lib/paths.ts +96 -3
  48. package/lib/phase2-decomposition.ts +1 -1
  49. package/lib/published-artifact.ts +162 -18
  50. package/lib/sc-id-cross-tree.ts +84 -8
  51. package/lib/scaffold/ai-review-findings.ts +7 -1
  52. package/lib/scaffold/ai-review-step.ts +861 -116
  53. package/lib/scaffold/defaults.ts +82 -1
  54. package/lib/scaffold/steps.ts +436 -44
  55. package/lib/security-verdict.ts +1 -1
  56. package/lib/shell-path-interpolation.ts +594 -0
  57. package/lib/text-dependents.ts +875 -0
  58. package/lib/workflow-security.ts +29 -0
  59. package/lib/workflow-taint.ts +732 -0
  60. package/lib/worktree-cleanup.ts +65 -38
  61. package/lib/worktree-repo.ts +32 -2
  62. package/package.json +3 -1
  63. package/scripts/check-installed-hook-currency.ts +825 -0
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * PostCompact.hook.ts — PostCompact hook
4
+ *
5
+ * SC-370 (HOOK-ARCHITECTURE-SPEC): Hook SC traceability
6
+ * SC-371 (HOOK-ARCHITECTURE-SPEC): No hook exceeds 150 lines
7
+ *
8
+ * Re-injects critical rules after context window compaction.
9
+ * Rules that survive compaction prevent agent drift in long sessions.
10
+ */
11
+
12
+ import { readFileSync, existsSync } from 'fs';
13
+ import { join } from 'path';
14
+
15
+ const HARNESS_ROOT = process.env.RUNGATE_HARNESS_ROOT || join(process.env.HOME!, 'Projects/rungate');
16
+ const PROJECT_ROOT = process.env.RUNGATE_PROJECT_ROOT || process.cwd();
17
+
18
+ function loadCriticalRules(): string[] {
19
+ const rules: string[] = [];
20
+
21
+ const claudeMd = join(PROJECT_ROOT, 'CLAUDE.md');
22
+ if (existsSync(claudeMd)) {
23
+ const content = readFileSync(claudeMd, 'utf-8');
24
+ const rulesSection = content.match(/## Rules\n([\s\S]*?)(?=\n##|\n---|\Z)/);
25
+ if (rulesSection) {
26
+ const ruleLines = rulesSection[1].split('\n').filter(l => l.startsWith('- '));
27
+ rules.push(...ruleLines.map(l => l.replace(/^-\s*/, '').replace(/\*\*/g, '')));
28
+ }
29
+ }
30
+
31
+ const agentsMd = join(PROJECT_ROOT, 'AGENTS.md');
32
+ if (existsSync(agentsMd)) {
33
+ const content = readFileSync(agentsMd, 'utf-8');
34
+ const rulesSection = content.match(/## Rules\n([\s\S]*?)(?=\n##|\Z)/);
35
+ if (rulesSection) {
36
+ const ruleLines = rulesSection[1].split('\n').filter(l => l.startsWith('- '));
37
+ rules.push(...ruleLines.map(l => l.replace(/^-\s*/, '').replace(/\*\*/g, '')));
38
+ }
39
+ }
40
+
41
+ return rules;
42
+ }
43
+
44
+ async function main() {
45
+ const rules = loadCriticalRules();
46
+ if (rules.length === 0) process.exit(0);
47
+
48
+ const output = [
49
+ '## Critical Rules (re-injected after context compaction)',
50
+ '',
51
+ ...rules.map((r, i) => `${i + 1}. ${r}`),
52
+ '',
53
+ 'Read PROJECT-STATE.md for current priorities and context.',
54
+ ];
55
+
56
+ console.log(`<system-reminder>\n${output.join('\n')}\n</system-reminder>`);
57
+ process.exit(0);
58
+ }
59
+
60
+ main();
@@ -0,0 +1,103 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * ProjectStateSync.hook.ts — Auto-regenerate PROJECT-STATE.md when project-state.json changes
4
+ *
5
+ * SC-370 (HOOK-ARCHITECTURE-SPEC): Hook SC traceability
6
+ * SC-371 (HOOK-ARCHITECTURE-SPEC): No hook exceeds 150 lines
7
+ *
8
+ * TRIGGER: PostToolUse (Write/Edit)
9
+ *
10
+ * Thin trigger: runs update-project-state.ts when project-state.json is modified.
11
+ *
12
+ * REGISTERED, in user scope, on BOTH Write and Edit. The header this replaced
13
+ * carried #898's unregistered declaration and said the hook had never fired.
14
+ * Measured 2026-10-21 by parsing `~/.claude/settings.json`:
15
+ *
16
+ * PostToolUse matcher='Write' bun ${RUNGATE_HOOKS_DIR}/ProjectStateSync.hook.ts
17
+ * PostToolUse matcher='Edit' bun ${RUNGATE_HOOKS_DIR}/ProjectStateSync.hook.ts
18
+ *
19
+ * #898's census counted THIS REPOSITORY's registries and read zero as
20
+ * absence. See `lib/hook-scopes.ts` for the reading that now cannot be taken
21
+ * from one scope (#713, #910).
22
+ *
23
+ * ## The #296 interaction is LIVE, not hypothetical
24
+ *
25
+ * #910 raised it as a question about whether to register: "PROJECT-STATE.md is
26
+ * DA-owned and an agent in a worktree must never write it (#296), so a
27
+ * PostToolUse hook firing on any agent's write is a decision with blast
28
+ * radius". That is the current configuration, taken by default, and it is
29
+ * still open — it is a decision for Jason, not something to settle by
30
+ * deregistering a hook from a user config an agent must not edit.
31
+ *
32
+ * What this hook can do is stop the question being unanswerable. Every
33
+ * decision on a `project-state.json` write now records the file path and the
34
+ * cwd in `hook-firings.jsonl` under the rungate work dir, so whether a
35
+ * worktree agent has ever triggered it is a question the evidence answers
36
+ * rather than an argument about blast radius.
37
+ *
38
+ * Only `project-state.json` writes are recorded. This hook is attached to
39
+ * EVERY Write and Edit in every session, and a record per call is a file
40
+ * nobody can read.
41
+ */
42
+
43
+ import { execFileSync } from "child_process";
44
+ import { parseHookInput } from "./lib/parseStdin";
45
+ import { errorFacts, recordHookFiring } from "../lib/hook-evidence";
46
+ import { projectStateTarget } from "../lib/project-state-root";
47
+
48
+ const HOOK = "ProjectStateSync";
49
+
50
+ const input = await parseHookInput();
51
+ if (!input) process.exit(0);
52
+
53
+ const filePath: string = input.tool_input?.file_path || "";
54
+ // Out of population: this hook has nothing to say about any other write, and
55
+ // records nothing. Everything below IS in population, and every path out of
56
+ // it leaves a record — a decline and a hook that never ran are otherwise the
57
+ // same observation, which is #910.
58
+ if (!filePath.endsWith("project-state.json")) process.exit(0);
59
+
60
+ const cwd = (input as { cwd?: string }).cwd;
61
+
62
+ // WHERE this may run is decided in `lib/project-state-root.ts`, not here —
63
+ // hooks are thin triggers, and a decision with a dozen inputs needs cases
64
+ // that reach each one without a subprocess. Read that module's header before
65
+ // trusting this to stop anything; its WHAT THIS DOES NOT COVER block is the
66
+ // honest boundary.
67
+ //
68
+ // `existsSync(script)` used to be the only gate, and the hook's own comment
69
+ // called it "a bar, not a wall — it only requires the payload to be a real
70
+ // directory, and /tmp is writable" (#1001).
71
+ const target = projectStateTarget(filePath);
72
+ if (!target.ok) {
73
+ recordHookFiring(HOOK, target.outcome, { ...target.detail, cwd });
74
+ process.exit(0);
75
+ }
76
+ const { projectRoot, script } = target;
77
+
78
+ try {
79
+ // ARGUMENT ARRAY, never a shell string (#971). `filePath` arrives from a
80
+ // tool call, `projectRoot` is its prefix, and `script` is built from that
81
+ // prefix — so every character between the start of the path and the
82
+ // trailing `project-state.json` is attacker-influenced. Interpolated into
83
+ // `execSync` it was parsed by a shell, on every Write and Edit in every
84
+ // session on this machine: a directory literally named
85
+ // `p$(touch /tmp/pwned)q` ran the `touch`. `execFileSync` spawns `bun`
86
+ // directly with an argv, so no metacharacter in a path is interpreted.
87
+ //
88
+ // That alone was never enough: WHERE this runs is the other half, and
89
+ // until #1001 it was wherever the tool call pointed. See
90
+ // `lib/project-state-root.ts`.
91
+ execFileSync("bun", [script, "--skip-tests"], {
92
+ cwd: projectRoot,
93
+ stdio: "pipe",
94
+ timeout: 10000,
95
+ });
96
+ recordHookFiring(HOOK, "synced", { filePath, cwd, script });
97
+ console.log("✅ PROJECT-STATE.md synced from project-state.json");
98
+ } catch (e: any) {
99
+ // The generator's message is not recorded: it quotes the argv that
100
+ // produced it (#970 review, finding 2).
101
+ recordHookFiring(HOOK, "sync-failed", { filePath, cwd, script, ...errorFacts(e) });
102
+ console.error(`WARN: PROJECT-STATE.md sync failed: ${e.message}`);
103
+ }
@@ -0,0 +1,69 @@
1
+ #!/usr/bin/env bun
2
+ import { parseHookInput } from './lib/parseStdin';
3
+ /**
4
+ * SkillGuard.hook.ts - Block False-Positive Skill Invocations (PreToolUse)
5
+ *
6
+ * Governing SCs: SC-370 (traceability), SC-371 (thin trigger, under 150 lines)
7
+ *
8
+ * PURPOSE:
9
+ * Prevents the well-documented bug where the model falsely invokes
10
+ * keybindings-help (or other position-biased built-in skills) when the
11
+ * user's request has nothing to do with keybindings.
12
+ *
13
+ * ROOT CAUSE:
14
+ * keybindings-help appears FIRST in every skills list injection, combined
15
+ * with the Skill tool's aggressive "BLOCKING REQUIREMENT" language. On
16
+ * ambiguous/short prompts, the model anchors on this first skill.
17
+ *
18
+ * TRIGGER: PreToolUse (matcher: Skill)
19
+ *
20
+ * INPUT:
21
+ * - stdin: Hook input JSON with tool_input containing Skill parameters
22
+ * - tool_input.skill: string (skill name being invoked)
23
+ *
24
+ * OUTPUT:
25
+ * - If blocked skill detected: "block" decision to prevent invocation
26
+ * - If legitimate skill: silent pass (exit 0)
27
+ *
28
+ * PORTABILITY (#713): this is a Claude Code platform defect that affects
29
+ * every consumer equally. `BLOCKED_SKILLS` is the whole configuration and
30
+ * the only import is `./lib/parseStdin`. No PAI-owned path is read.
31
+ */
32
+
33
+ // Skills that are known to false-positive due to list position bias.
34
+ // These get BLOCKED unless explicitly requested via /keybindings-help
35
+ const BLOCKED_SKILLS = ['keybindings-help'];
36
+
37
+ interface HookInput {
38
+ tool_name: string;
39
+ tool_input: {
40
+ skill?: string;
41
+ args?: string;
42
+ };
43
+ }
44
+
45
+ async function main() {
46
+ try {
47
+ const data = await parseHookInput<HookInput>();
48
+ if (!data) process.exit(0);
49
+ const skillName = (data.tool_input?.skill || '').toLowerCase().trim();
50
+
51
+ // Check if this is a blocked skill
52
+ if (BLOCKED_SKILLS.includes(skillName)) {
53
+ const decision = {
54
+ decision: 'block',
55
+ reason: `BLOCKED: "${skillName}" is a known false-positive skill triggered by position bias. The user did NOT ask about keybindings. Continue with the ACTUAL task the user requested. If the user genuinely wants keybinding help, they will explicitly say "keybindings" or use /keybindings-help.`,
56
+ };
57
+ console.log(JSON.stringify(decision));
58
+ process.exit(0);
59
+ }
60
+
61
+ // All other skills pass through
62
+ process.exit(0);
63
+ } catch {
64
+ // On any error, pass silently — don't block skill execution
65
+ process.exit(0);
66
+ }
67
+ }
68
+
69
+ main();
@@ -0,0 +1,43 @@
1
+ /**
2
+ * SpecConformityTrigger — PostToolUse hook that auto-runs conformity
3
+ *
4
+ * SC-370 (HOOK-ARCHITECTURE-SPEC): Hook SC traceability
5
+ * SC-371 (HOOK-ARCHITECTURE-SPEC): No hook exceeds 150 lines
6
+ * when spec files are modified via Edit or Write.
7
+ *
8
+ * Thin trigger: detects the event, delegates to lib/spec-change-conformity.
9
+ *
10
+ * Issue: #581
11
+ */
12
+
13
+ import { parseHookInput } from "./lib/parseStdin";
14
+ import { isSpecFile, runSpecChangeConformity } from "../lib/spec-change-conformity";
15
+
16
+ async function main() {
17
+ const input = await parseHookInput();
18
+ if (!input) process.exit(0);
19
+
20
+ const toolName = input.tool_name;
21
+ if (toolName !== "Edit" && toolName !== "Write") process.exit(0);
22
+
23
+ const filePath = input.tool_input?.file_path;
24
+ if (!filePath || !isSpecFile(filePath)) process.exit(0);
25
+
26
+ try {
27
+ const projectRoot = process.cwd();
28
+ const result = runSpecChangeConformity(projectRoot);
29
+
30
+ if (result.flippedCount > 0) {
31
+ console.error(`[SpecConformityTrigger] Flipped ${result.flippedCount} checkbox(es)`);
32
+ }
33
+ if (result.failing.length > 0) {
34
+ console.error(`[SpecConformityTrigger] ${result.failing.length} SC(s) still failing`);
35
+ }
36
+ } catch (err) {
37
+ console.error(`[SpecConformityTrigger] Error: ${err}`);
38
+ }
39
+
40
+ process.exit(0);
41
+ }
42
+
43
+ main();
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * SpecSCGuard.hook.ts — PostToolUse on Edit/Write
4
+ *
5
+ * SC-370 (HOOK-ARCHITECTURE-SPEC): Hook SC traceability
6
+ * SC-371 (HOOK-ARCHITECTURE-SPEC): No hook exceeds 150 lines
7
+ *
8
+ * TRIGGER: PostToolUse (matcher: Edit, Write)
9
+ *
10
+ * PURPOSE:
11
+ * Validate new SC lines added to specs/*.md files.
12
+ * Ensures every new SC is either:
13
+ * 1. Matchable by a pattern in config/matcher-registry.json
14
+ * 2. Explicitly marked with (behavioral) suffix
15
+ *
16
+ * BEHAVIOR:
17
+ * - Strict compliance specs: BLOCK edits adding unmatchable SCs
18
+ * - Permissive compliance specs: WARN but allow
19
+ *
20
+ * Issue: #591
21
+ */
22
+
23
+ import { readFileSync, existsSync } from "fs";
24
+ import { join } from "path";
25
+ import { parseHookInput } from "./lib/parseStdin";
26
+ import {
27
+ detectNewSCs,
28
+ validateNewSCs,
29
+ getLastCommittedContent,
30
+ getComplianceMode,
31
+ } from "../lib/sc-guard";
32
+
33
+ interface PostToolUseInput {
34
+ tool_name?: string;
35
+ tool_input?: {
36
+ file_path?: string;
37
+ content?: string;
38
+ old_string?: string;
39
+ new_string?: string;
40
+ [k: string]: unknown;
41
+ };
42
+ tool_response?: { output?: string; [k: string]: unknown } | string;
43
+ [k: string]: unknown;
44
+ }
45
+
46
+ async function main() {
47
+ const input = await parseHookInput<PostToolUseInput>();
48
+ if (!input) process.exit(0);
49
+
50
+ try {
51
+ const toolName = input.tool_name ?? "";
52
+
53
+ // Only process Edit and Write tool calls
54
+ if (toolName !== "Edit" && toolName !== "Write") {
55
+ process.exit(0);
56
+ }
57
+
58
+ const filePath = input.tool_input?.file_path ?? "";
59
+
60
+ // Only process specs/*.md files
61
+ if (!filePath.match(/specs\/[^/]+\.md$/)) {
62
+ process.exit(0);
63
+ }
64
+
65
+ // Read the current file content after the edit
66
+ if (!existsSync(filePath)) {
67
+ console.error(`[SpecSCGuard] File not found after edit: ${filePath}`);
68
+ process.exit(0);
69
+ }
70
+
71
+ const newContent = readFileSync(filePath, "utf-8");
72
+
73
+ // Get relative path for git operations
74
+ const specsMatch = filePath.match(/(specs\/[^/]+\.md)$/);
75
+ const relativePath = specsMatch ? specsMatch[1] : filePath;
76
+
77
+ // Get the previous version from git
78
+ const oldContent = getLastCommittedContent(relativePath);
79
+
80
+ // Detect new SC lines
81
+ const newSCs = detectNewSCs(oldContent, newContent);
82
+ if (newSCs.length === 0) {
83
+ console.error("[SpecSCGuard] No new SC lines detected");
84
+ process.exit(0);
85
+ }
86
+
87
+ // Get compliance mode from frontmatter
88
+ const compliance = getComplianceMode(newContent);
89
+
90
+ // Validate new SCs
91
+ const results = validateNewSCs(newSCs, compliance);
92
+ if (results.length === 0) {
93
+ console.error(`[SpecSCGuard] ${newSCs.length} new SCs validated OK`);
94
+ process.exit(0);
95
+ }
96
+
97
+ // Process validation results
98
+ const blocked = results.filter(r => r.blocked);
99
+ const warned = results.filter(r => !r.blocked);
100
+
101
+ if (warned.length > 0) {
102
+ const warnMessages = warned.map(r => r.message).join("\n");
103
+ console.error(`[SpecSCGuard] WARN: ${warned.length} SCs without matching patterns:\n${warnMessages}`);
104
+ }
105
+
106
+ if (blocked.length > 0) {
107
+ const blockMessages = blocked.map(r => r.message).join("\n");
108
+ const decision = {
109
+ decision: "block",
110
+ reason: `${blocked.length} new SC(s) have no matching pattern and no (behavioral) suffix.\n${blockMessages}`,
111
+ };
112
+ console.log(JSON.stringify(decision));
113
+ console.error(`[SpecSCGuard] BLOCKED: ${blocked.length} unmatchable SCs in strict spec`);
114
+ }
115
+
116
+ process.exit(0);
117
+ } catch (err) {
118
+ console.error(`[SpecSCGuard] Error: ${err}`);
119
+ process.exit(0);
120
+ }
121
+ }
122
+
123
+ main();
@@ -0,0 +1,141 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * StaleTTLCleanup.hook.ts — Auto-cleanup stale workflow-state.json and .ship-active files (#256, #270)
4
+ *
5
+ * SC-370 (HOOK-ARCHITECTURE-SPEC): Hook SC traceability
6
+ * SC-371 (HOOK-ARCHITECTURE-SPEC): No hook exceeds 150 lines
7
+ *
8
+ * TRIGGER: SessionStart
9
+ *
10
+ * Enforces 4h TTL on ship artifacts, 7d hard TTL on active phases.
11
+ * Thin trigger: delegates to lib/stale-cleanup.ts. Issue: #544
12
+ */
13
+
14
+ import { existsSync, appendFileSync } from 'fs';
15
+ import { join } from 'path';
16
+ import { cleanStaleFiles } from '../lib/stale-cleanup';
17
+ import { repoRootFrom } from '../lib/paths';
18
+
19
+ const PAI_WORK = process.env.RUNGATE_WORK_DIR || process.env.PAI_WORK_DIR || join(process.env.HOME!, '.rungate');
20
+ const STALE_LOG = join(process.env.HOME!, '.claude', 'state', 'stale-cleanup.log');
21
+ const FOUR_HOURS_MS = 4 * 60 * 60 * 1000;
22
+ const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000;
23
+
24
+ if (!existsSync(PAI_WORK)) process.exit(0);
25
+
26
+ const timestamp = new Date().toISOString();
27
+ function log(msg: string): void {
28
+ try { appendFileSync(STALE_LOG, `${timestamp} ${msg}\n`); } catch {}
29
+ }
30
+
31
+ // Core cleanup
32
+ const result = cleanStaleFiles(PAI_WORK, FOUR_HOURS_MS, SEVEN_DAYS_MS);
33
+ let deletedCount = result.deleted;
34
+ for (const msg of result.logs) log(msg);
35
+
36
+ // Resolve the project root ONCE from the repo, not from wherever the terminal
37
+ // happened to be (#68). A session opened in ~ used to skip worktree cleanup
38
+ // entirely while still reporting success.
39
+ const PROJECT_ROOT = repoRootFrom(process.cwd());
40
+ if (!PROJECT_ROOT) log('cleanup skipped: cwd is not inside a git repository');
41
+
42
+ // Worktree cleanup
43
+ if (PROJECT_ROOT) try {
44
+ const { cleanupWorktrees } = await import('../lib/worktree-cleanup.ts');
45
+ const projectRoot = PROJECT_ROOT;
46
+ if (existsSync(join(projectRoot, '.claude', 'worktrees'))) {
47
+ const wr = await cleanupWorktrees({ projectRoot, maxAgeMs: 24 * 60 * 60 * 1000 });
48
+ if (wr.removed.length) {
49
+ deletedCount += wr.removed.length;
50
+ log(`WORKTREE cleanup [${projectRoot}]: removed ${wr.removed.length} stale worktrees`);
51
+ }
52
+ }
53
+ } catch (e) { log(`WORKTREE cleanup error: ${e}`); }
54
+
55
+ // Scratch cleanup — test fixtures the suite leaked into the repo root (#437).
56
+ // Reported alongside worktree cleanup deliberately: both are resources created
57
+ // by tooling that only get cleaned on the happy path, and 34 of these
58
+ // accumulated because each one had to be found by eye.
59
+ if (PROJECT_ROOT) try {
60
+ const { cleanupScratchDirs } = await import('../lib/scratch-cleanup.ts');
61
+ // Gated on the directory the allowlist is derived FROM, the way the
62
+ // worktree block is gated on `.claude/worktrees`. Without a `test/` there
63
+ // is nothing to derive and nothing could be swept anyway — but a sweep
64
+ // that runs with an empty allowlist and reports success is the shape this
65
+ // repo keeps finding, so the skip is explicit rather than incidental.
66
+ const sr = existsSync(join(PROJECT_ROOT, 'test'))
67
+ ? cleanupScratchDirs({ repoRoot: PROJECT_ROOT })
68
+ : { removed: [], kept: [], refused: [], errors: [] };
69
+ if (sr.removed.length) {
70
+ deletedCount += sr.removed.length;
71
+ log(`SCRATCH cleanup [${PROJECT_ROOT}]: removed ${sr.removed.length} leaked test scratch dirs`);
72
+ }
73
+ for (const e of sr.errors) log(`SCRATCH cleanup error: ${e}`);
74
+ } catch (e) { log(`SCRATCH cleanup error: ${e}`); }
75
+
76
+ // Branch cleanup (#516, #1079). Thin trigger: lib/branch-cleanup.ts holds
77
+ // every decision. This arm issues `git push origin --delete`, the one
78
+ // irreversible thing this hook does and the only thing in it that reaches a
79
+ // remote, at EVERY SessionStart from the shared checkout — so it is DISARMED
80
+ // by default and signals nothing. Set RUNGATE_BRANCH_CLEANUP=1 to arm it.
81
+ //
82
+ // A disarmed arm and a run that could not resolve the repository both say so
83
+ // by name: zero deletions has three causes here and only one is a clean
84
+ // sweep. `.claude/rungate/hooks.json` names this arming and the #1079 slug
85
+ // refusal as the two things that must BOTH hold before this hook may be
86
+ // reconsidered for consumer deployment.
87
+ if (PROJECT_ROOT) try {
88
+ const { runBranchCleanupArm } = await import('../lib/branch-cleanup.ts');
89
+ const br = await runBranchCleanupArm({ projectRoot: PROJECT_ROOT, maxAgeDays: 7 });
90
+ deletedCount += br.deleted;
91
+ for (const line of br.lines) log(line);
92
+ } catch (e) { log(`BRANCH cleanup error: ${e}`); }
93
+
94
+ // Orphaned test-suite processes (#690). Thin trigger: lib/orphan-reaper.ts
95
+ // holds every decision. It is a READING by default and signals nothing —
96
+ // arming it is a deployment decision, not a code one, because this hook runs
97
+ // from the shared checkout at every SessionStart and a merge that armed it
98
+ // would arm it for every live peer at once. Set RUNGATE_REAP_ORPHANS=1 to
99
+ // signal; the log line is identical except that it says `armed`.
100
+ //
101
+ // The arming read is `armedFromEnv` and not an inline `===`, so there is one
102
+ // binding a case can drive over the values that must NOT arm it. A call site
103
+ // that stops passing it is itself a case — see test/orphan-reaper.test.ts.
104
+ let orphansSignalled = 0;
105
+ try {
106
+ const { reapOrphans, reapReportLines, armedFromEnv } = await import('../lib/orphan-reaper.ts');
107
+ const report = reapOrphans({ armed: armedFromEnv() });
108
+ const candidates = report.decisions.length;
109
+ orphansSignalled = report.signalled.length;
110
+ // Silence is reserved for "nothing to say about any process". A reading
111
+ // that could not be taken, and a reading with candidates in it, both go in
112
+ // the log naming pids and reasons — "Cleaned up N" with nothing behind it
113
+ // is what made #690 cost two days.
114
+ if (report.reading === 'UNMEASURED' || candidates > 0) {
115
+ for (const line of reapReportLines(report)) log(line);
116
+ }
117
+ } catch (e) { log(`ORPHAN reap error: ${e}`); }
118
+
119
+ // Gap scan — drift detection
120
+ let gapWarns = 0;
121
+ if (PROJECT_ROOT) try {
122
+ const { scanGaps } = await import('../lib/gap-scanner.ts');
123
+ const projectRoot = PROJECT_ROOT;
124
+ const gapResult = scanGaps(projectRoot, PAI_WORK);
125
+ for (const r of gapResult.results) {
126
+ if (r.status === 'WARN') {
127
+ gapWarns++;
128
+ log(`GAP ${r.check}: ${r.detail}`);
129
+ }
130
+ }
131
+ } catch (e) { log(`GAP scan error: ${e}`); }
132
+
133
+ const parts: string[] = [];
134
+ if (deletedCount > 0) parts.push(`${deletedCount} removed`);
135
+ if (orphansSignalled > 0) parts.push(`${orphansSignalled} orphaned processes signalled`);
136
+ if (gapWarns > 0) parts.push(`${gapWarns} gap warnings`);
137
+ if (parts.length > 0) {
138
+ console.log(`Stale TTL cleanup: ${parts.join(', ')}`);
139
+ } else {
140
+ console.log('Stale TTL cleanup: no stale files found');
141
+ }
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * TaskCompleted.hook.ts — Quality gate before task completion
4
+ *
5
+ * SC-370 (HOOK-ARCHITECTURE-SPEC): Hook SC traceability
6
+ * SC-372 (HOOK-ARCHITECTURE-SPEC): Hook logic in lib/ has unit tests
7
+ *
8
+ * TRIGGER: TaskCompleted
9
+ *
10
+ * Runs quality checks before allowing an agent to mark a task as complete:
11
+ * - Test suite must pass (no new failures)
12
+ * - Warns on uncommitted changes
13
+ * - Runs conformity checks if rungate.json exists
14
+ *
15
+ * Exit code 0 = allow completion
16
+ * Exit code 2 = block completion
17
+ *
18
+ * Issue: #579
19
+ */
20
+
21
+ import { parseHookInput } from './lib/parseStdin';
22
+ import { runAllCompletionChecks } from '../lib/task-completion-checks';
23
+
24
+ async function main() {
25
+ const input = await parseHookInput();
26
+ if (!input) process.exit(0);
27
+
28
+ const projectRoot = process.cwd();
29
+
30
+ const result = runAllCompletionChecks(projectRoot);
31
+
32
+ if (result.warnings.length > 0) {
33
+ console.error('[TaskCompleted] Warnings:');
34
+ for (const warning of result.warnings) {
35
+ console.error(` - ${warning}`);
36
+ }
37
+ }
38
+
39
+ if (!result.passed) {
40
+ console.error('[TaskCompleted] BLOCKED: Task completion blocked by quality gates:');
41
+ for (const blocker of result.blockers) {
42
+ console.error(` ✗ ${blocker}`);
43
+ }
44
+ process.exit(2); // Block completion
45
+ }
46
+
47
+ console.error('[TaskCompleted] Quality checks passed. Allowing task completion.');
48
+ process.exit(0);
49
+ }
50
+
51
+ main();
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * TeamInit.hook.ts — Ensure team directory exists for current session (SessionStart)
4
+ *
5
+ * Governing SCs: SC-370 (traceability), SC-371 (thin trigger, under 150 lines)
6
+ *
7
+ * PURPOSE:
8
+ * Creates <claude-config-dir>/teams/session-{id}/config.json when missing.
9
+ * Fixes typed agent spawns failing after context compaction with
10
+ * "team file not found".
11
+ *
12
+ * TRIGGER: SessionStart
13
+ *
14
+ * INPUT:
15
+ * - env: CLAUDE_CODE_SESSION_ID (full UUID, first 8 chars used)
16
+ *
17
+ * OUTPUT:
18
+ * - stdout: None (never)
19
+ * - stderr: Minimal status (dir created / already exists)
20
+ * - exit(0): Always
21
+ *
22
+ * SIDE EFFECTS:
23
+ * - Creates: <claude-config-dir>/teams/session-{id}/config.json (if missing)
24
+ *
25
+ * ERROR HANDLING:
26
+ * - CLAUDE_CODE_SESSION_ID not set: exit 0 silently
27
+ * - Existing valid config.json: no-op (idempotent)
28
+ * - All errors: exit 0 (never block session start)
29
+ *
30
+ * PORTABILITY (#713): `getPaiDir()` resolves `PAI_DIR` and otherwise
31
+ * `~/.claude` — Claude Code's OWN configuration directory, which is where
32
+ * `teams/` lives on every machine running Claude Code, PAI installed or not.
33
+ * The function name is PAI-flavoured; the directory it returns is not, and
34
+ * the bug this fixes reaches any agent-spawning product equally.
35
+ *
36
+ * Fixes: #151
37
+ */
38
+
39
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
40
+ import { join } from 'path';
41
+ import { getPaiDir } from './lib/paths';
42
+
43
+ const sessionId = process.env.CLAUDE_CODE_SESSION_ID;
44
+
45
+ // Guard: no session ID → exit silently
46
+ if (!sessionId) {
47
+ process.exit(0);
48
+ }
49
+
50
+ try {
51
+ const shortId = sessionId.substring(0, 8);
52
+ const teamDir = join(getPaiDir(), 'teams', `session-${shortId}`);
53
+ const configPath = join(teamDir, 'config.json');
54
+
55
+ // Check if config already exists and is valid JSON
56
+ if (existsSync(configPath)) {
57
+ try {
58
+ JSON.parse(readFileSync(configPath, 'utf-8'));
59
+ // Valid JSON exists — idempotent no-op
60
+ process.exit(0);
61
+ } catch {
62
+ // Invalid JSON — overwrite below
63
+ console.error(`[TeamInit] Invalid config.json at ${configPath} — recreating`);
64
+ }
65
+ }
66
+
67
+ // Create directory if missing
68
+ if (!existsSync(teamDir)) {
69
+ mkdirSync(teamDir, { recursive: true });
70
+ }
71
+
72
+ // Write minimal config
73
+ const config = {
74
+ session_id: `session-${shortId}`,
75
+ created: new Date().toISOString(),
76
+ };
77
+
78
+ writeFileSync(configPath, JSON.stringify(config), 'utf-8');
79
+ console.error(`[TeamInit] Created team config: session-${shortId}`);
80
+ } catch (err) {
81
+ // Never block session start
82
+ console.error(`[TeamInit] Error (non-fatal): ${String(err).slice(0, 80)}`);
83
+ }
84
+
85
+ process.exit(0);