rungate 0.7.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/gates/.gate-salt +1 -0
- package/gates/SCHEMA-GUIDE.md +485 -0
- package/gates/ac-quality.test.ts +106 -0
- package/gates/adversarial.test.ts +283 -0
- package/gates/brief-assembler.test.ts +487 -0
- package/gates/brief-assembler.ts +448 -0
- package/gates/bunfig.toml +2 -0
- package/gates/chain.test.ts +91 -0
- package/gates/e2e-smoke.test.ts +234 -0
- package/gates/error-classifier.test.ts +250 -0
- package/gates/error-classifier.ts +99 -0
- package/gates/gate-executor.ts +3071 -0
- package/gates/orchestrator.test.ts +968 -0
- package/gates/orchestrator.ts +827 -0
- package/gates/preload.ts +89 -0
- package/gates/prompts/ac-adversary.md +20 -0
- package/gates/prompts/evidence-validator.md +22 -0
- package/gates/prompts/prove-reproducer.md +53 -0
- package/gates/prompts.sha256 +3 -0
- package/gates/prove.test.ts +164 -0
- package/gates/rook-state.test.ts +108 -0
- package/gates/run-attribution.ts +290 -0
- package/gates/run-gate.ts +163 -0
- package/gates/schema-parity.test.ts +378 -0
- package/gates/schema.ts +1209 -0
- package/gates/self-heal.test.ts +511 -0
- package/gates/self-heal.ts +125 -0
- package/gates/ship-orchestrator.test.ts +399 -0
- package/gates/ship-orchestrator.ts +384 -0
- package/gates/spec-compliance-probe.ts +159 -0
- package/gates/test-fixtures/broken-no-environments.json +110 -0
- package/gates/test-fixtures/consumer-directory-layout.json +90 -0
- package/gates/test-fixtures/valid-standard.json +91 -0
- package/gates/test-utils.ts +43 -0
- package/gates/typecheck-gate.ts +111 -0
- package/gates/witness.ts +349 -0
- package/gates/workflow.test.ts +2018 -0
- 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 +95 -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 +64 -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 +627 -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 +360 -38
- package/lib/gate-names.ts +72 -0
- package/lib/gate-result-protection.ts +437 -0
- package/lib/generators/code-map.ts +55 -4
- package/lib/generators/types.ts +27 -1
- package/lib/intake-sources.ts +380 -0
- package/lib/js-top-level-code.ts +20 -2
- package/lib/junit-checks.ts +239 -1
- package/lib/late-env-spawn.ts +331 -0
- package/lib/launch-base.ts +128 -5
- package/lib/package-closure.ts +114 -0
- 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 +149 -4
- package/lib/scaffold/ai-review-step.ts +1006 -132
- package/lib/scaffold/defaults.ts +82 -1
- package/lib/scaffold/steps.ts +642 -54
- package/lib/scanner.ts +4 -2
- package/lib/security-verdict.ts +1 -1
- package/lib/shell-path-interpolation.ts +594 -0
- package/lib/text-dependents.ts +875 -0
- package/lib/transcript-checker.ts +6 -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 +4 -1
- package/scripts/check-installed-hook-currency.ts +825 -0
- package/scripts/generate-code-map.ts +13 -8
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Issue-comment template validation, lifted out of IssueCloseGuard.
|
|
3
|
+
*
|
|
4
|
+
* HOOK-ARCHITECTURE-SPEC wants hooks to be thin triggers that delegate to
|
|
5
|
+
* lib, and SC-371 caps a hook at 150 lines — which the guard crossed when
|
|
6
|
+
* #140 made its failure handling explicit. Moving this out is the fix the
|
|
7
|
+
* spec asks for rather than a cap raise, and it makes the rules unit-testable
|
|
8
|
+
* without driving a subprocess.
|
|
9
|
+
*
|
|
10
|
+
* Returns the reason a comment should be refused, or null to allow it. The
|
|
11
|
+
* caller owns the blocking, so the rules stay pure.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { readFileSync } from 'fs';
|
|
15
|
+
|
|
16
|
+
export const TEMPLATE_RULES = [
|
|
17
|
+
{ marker: '## AC-', required: ['Type:', 'Metric:', 'Threshold:', 'Baseline:', 'Evidence Method:', 'Pass Criteria:'] },
|
|
18
|
+
{ marker: '## ATTEMPT', required: ['Approach:', 'Files Changed:', 'Result:', 'Evidence:', 'Why It Failed:'] },
|
|
19
|
+
{ marker: '## DISCOVERY', required: ['### Docs read', '### Issue context'] },
|
|
20
|
+
{ marker: '## Completion Report', required: ['### Evidence per AC', '### Ship Scorecard'] },
|
|
21
|
+
{ marker: '## Sizing Declaration', required: ['Predicted:', 'Files:'] },
|
|
22
|
+
{ marker: '## Sizing Outcome', required: ['Declared:', 'Actual:'] },
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Whether this command posts an issue comment.
|
|
27
|
+
*
|
|
28
|
+
* Two forms now. `gh issue comment` is what a person types. `github-op.ts
|
|
29
|
+
* comment` is what workflow steps run since #137 — the MCP tools those steps
|
|
30
|
+
* used to name do not exist in this harness, so they went through the Octokit
|
|
31
|
+
* script instead. Matching only the first would have quietly exempted every
|
|
32
|
+
* comment the harness itself posts, which is most of them.
|
|
33
|
+
*/
|
|
34
|
+
export const COMMENT_INVOCATION = /gh\s+issue\s+comment\s+\d+|github-op\.ts\s+comment\b/;
|
|
35
|
+
|
|
36
|
+
/** The `--body` text of a comment command — heredoc, quoted, or a file. */
|
|
37
|
+
export function extractCommentBody(
|
|
38
|
+
command: string,
|
|
39
|
+
readFile: (path: string) => string = defaultReadFile,
|
|
40
|
+
): string {
|
|
41
|
+
const heredoc = command.match(/--body\s+"?\$\(cat\s+<<'?EOF'?\s*\n?([\s\S]*?)\nEOF/);
|
|
42
|
+
if (heredoc) return heredoc[1];
|
|
43
|
+
|
|
44
|
+
// `--body-file` is how #137 passes anything with a newline in it, so the
|
|
45
|
+
// template rules have to follow the body into the file or stop applying to
|
|
46
|
+
// exactly the comments that carry templates.
|
|
47
|
+
const file = command.match(/--body-file[\s=]+['"]?([^\s'"]+)/);
|
|
48
|
+
if (file) {
|
|
49
|
+
try {
|
|
50
|
+
return readFile(file[1]);
|
|
51
|
+
} catch {
|
|
52
|
+
// Unreadable here means unreadable for the command too, which will fail
|
|
53
|
+
// on its own. Nothing to validate, and refusing would block on a path
|
|
54
|
+
// this hook simply cannot see (a heredoc writes it in the same command).
|
|
55
|
+
return '';
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const quoted = command.match(/(?:--body|-b)\s+["']([^"']*(?:(?:\\.)[^"']*)*)['"]/);
|
|
60
|
+
return quoted ? quoted[1] : '';
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function defaultReadFile(path: string): string {
|
|
64
|
+
return readFileSync(path, 'utf-8');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function commentTemplateViolation(command: string): string | null {
|
|
68
|
+
const body = extractCommentBody(command);
|
|
69
|
+
if (!body) return null;
|
|
70
|
+
|
|
71
|
+
if (/^## AC-\d+/m.test(body))
|
|
72
|
+
return 'ACs (## AC-N) must be posted to the issue body via "gh issue edit --body", not as comments.';
|
|
73
|
+
if (body.includes('### Docs read') && !body.includes('## DISCOVERY'))
|
|
74
|
+
return 'Comment contains "### Docs read" but no "## DISCOVERY" heading. Use the DISCOVERY template.';
|
|
75
|
+
if (body.includes('### Evidence per AC') && !body.includes('## Completion Report'))
|
|
76
|
+
return 'Comment contains "### Evidence per AC" but no "## Completion Report" heading.';
|
|
77
|
+
if (body.includes('REPLACE:'))
|
|
78
|
+
return 'Comment body contains unfilled REPLACE: placeholder(s).';
|
|
79
|
+
|
|
80
|
+
for (const rule of TEMPLATE_RULES) {
|
|
81
|
+
if (!body.includes(rule.marker)) continue;
|
|
82
|
+
const missing = rule.required.filter(f => !body.includes(f));
|
|
83
|
+
if (missing.length) return `Template "${rule.marker}" missing fields: ${missing.join(', ')}. See TEMPLATES.md.`;
|
|
84
|
+
}
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* findWorkflow.ts — Shared workflow discovery for hooks
|
|
3
|
+
*
|
|
4
|
+
* Used by: ScopeGateGuard, AutoVerifyGate
|
|
5
|
+
* Issue: #269
|
|
6
|
+
*
|
|
7
|
+
* Finds workflow-state.json by issue number (preferred) or mtime fallback.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { readdirSync, readFileSync, existsSync, statSync } from 'fs';
|
|
11
|
+
import { join } from 'path';
|
|
12
|
+
|
|
13
|
+
const RUNGATE_WORK_DIR = process.env.RUNGATE_WORK_DIR || process.env.RUNGATE_WORK_DIR || join(process.env.HOME!, '.rungate');
|
|
14
|
+
|
|
15
|
+
interface WorkflowState {
|
|
16
|
+
path: string;
|
|
17
|
+
data: any;
|
|
18
|
+
slug: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function findWorkflowForIssue(issueNum?: string, phases?: string[], repo?: string, projectRoot?: string): WorkflowState | null {
|
|
22
|
+
if (!existsSync(RUNGATE_WORK_DIR)) return null;
|
|
23
|
+
|
|
24
|
+
const validPhases = phases || ['BUILD', 'VERIFY', 'SCOPE', 'SHIP', 'DONE'];
|
|
25
|
+
let candidates: { path: string; data: any; mtime: number; slug: string }[] = [];
|
|
26
|
+
|
|
27
|
+
// Collect all valid workflow entries
|
|
28
|
+
const collectWorkflow = (wfPath: string, slug: string) => {
|
|
29
|
+
if (!existsSync(wfPath)) return;
|
|
30
|
+
try {
|
|
31
|
+
const data = JSON.parse(readFileSync(wfPath, 'utf-8'));
|
|
32
|
+
if (!validPhases.includes(data.phase)) return;
|
|
33
|
+
const mtime = statSync(wfPath).mtimeMs;
|
|
34
|
+
candidates.push({ path: wfPath, data, mtime, slug });
|
|
35
|
+
} catch {}
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
const dirs = readdirSync(RUNGATE_WORK_DIR, { withFileTypes: true })
|
|
40
|
+
.filter(d => d.isDirectory());
|
|
41
|
+
|
|
42
|
+
for (const d of dirs) {
|
|
43
|
+
// Level 1: direct children
|
|
44
|
+
collectWorkflow(join(RUNGATE_WORK_DIR, d.name, 'workflow-state.json'), d.name);
|
|
45
|
+
|
|
46
|
+
// Level 2: nested subdirectories (e.g., pai/361)
|
|
47
|
+
const subDir = join(RUNGATE_WORK_DIR, d.name);
|
|
48
|
+
try {
|
|
49
|
+
const subDirs = readdirSync(subDir, { withFileTypes: true }).filter(sd => sd.isDirectory());
|
|
50
|
+
for (const sd of subDirs) {
|
|
51
|
+
collectWorkflow(join(subDir, sd.name, 'workflow-state.json'), `${d.name}/${sd.name}`);
|
|
52
|
+
}
|
|
53
|
+
} catch {}
|
|
54
|
+
}
|
|
55
|
+
} catch {}
|
|
56
|
+
|
|
57
|
+
if (candidates.length === 0) return null;
|
|
58
|
+
|
|
59
|
+
// Resolution priority: projectRoot > issueNum > mtime fallback
|
|
60
|
+
|
|
61
|
+
// Priority 1: Match by projectRoot
|
|
62
|
+
if (projectRoot) {
|
|
63
|
+
const byRoot = candidates.filter(c => c.data.projectRoot === projectRoot);
|
|
64
|
+
if (byRoot.length === 1) return { path: byRoot[0].path, data: byRoot[0].data, slug: byRoot[0].slug };
|
|
65
|
+
if (byRoot.length > 1) {
|
|
66
|
+
// Multiple matches — narrow by issue if available
|
|
67
|
+
if (issueNum) {
|
|
68
|
+
const rootAndIssue = byRoot.find(c => String(c.data.issue) === issueNum);
|
|
69
|
+
if (rootAndIssue) return { path: rootAndIssue.path, data: rootAndIssue.data, slug: rootAndIssue.slug };
|
|
70
|
+
}
|
|
71
|
+
// Return most recent among projectRoot matches
|
|
72
|
+
byRoot.sort((a, b) => b.mtime - a.mtime);
|
|
73
|
+
return { path: byRoot[0].path, data: byRoot[0].data, slug: byRoot[0].slug };
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Priority 2: Match by issue number
|
|
78
|
+
if (issueNum) {
|
|
79
|
+
const byIssue = candidates.filter(c => String(c.data.issue) === issueNum);
|
|
80
|
+
if (byIssue.length > 0) {
|
|
81
|
+
// Narrow by repo if provided
|
|
82
|
+
if (repo) {
|
|
83
|
+
const byRepo = byIssue.find(c => c.data.repo === repo);
|
|
84
|
+
if (byRepo) return { path: byRepo.path, data: byRepo.data, slug: byRepo.slug };
|
|
85
|
+
}
|
|
86
|
+
return { path: byIssue[0].path, data: byIssue[0].data, slug: byIssue[0].slug };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// If issueNum was specified but not matched, don't fall back to mtime
|
|
91
|
+
if (issueNum) return null;
|
|
92
|
+
|
|
93
|
+
// Priority 3: Most recent by mtime (last resort)
|
|
94
|
+
candidates.sort((a, b) => b.mtime - a.mtime);
|
|
95
|
+
return { path: candidates[0].path, data: candidates[0].data, slug: candidates[0].slug };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function extractIssueNumber(text: string): string | undefined {
|
|
99
|
+
const match = text.match(/#(\d+)/);
|
|
100
|
+
return match ? match[1] : undefined;
|
|
101
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared Stdin Parsing
|
|
3
|
+
*
|
|
4
|
+
* Centralizes JSON stdin reading used by all hooks.
|
|
5
|
+
* Single source of truth — replaces stream, text, and event patterns.
|
|
6
|
+
*
|
|
7
|
+
* Issue: #370 (extracted from 34 hooks)
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export interface HookInput {
|
|
11
|
+
tool_name?: string;
|
|
12
|
+
tool_input?: { command?: string; file_path?: string; prompt?: string; [k: string]: unknown };
|
|
13
|
+
tool_response?: { output?: string; [k: string]: unknown } | string;
|
|
14
|
+
session_id?: string;
|
|
15
|
+
transcript_path?: string;
|
|
16
|
+
hook_event_name?: string;
|
|
17
|
+
[k: string]: unknown;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Read and parse JSON from stdin with timeout.
|
|
22
|
+
* Returns parsed object or null on failure/timeout/empty.
|
|
23
|
+
*/
|
|
24
|
+
export async function parseHookInput<T = HookInput>(timeoutMs = 2000): Promise<T | null> {
|
|
25
|
+
try {
|
|
26
|
+
const raw = await Promise.race([
|
|
27
|
+
Bun.stdin.text(),
|
|
28
|
+
new Promise<string>((_, reject) =>
|
|
29
|
+
setTimeout(() => reject(new Error('stdin timeout')), timeoutMs),
|
|
30
|
+
),
|
|
31
|
+
]);
|
|
32
|
+
if (!raw?.trim()) return null;
|
|
33
|
+
return JSON.parse(raw) as T;
|
|
34
|
+
} catch {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Centralized Path Resolution
|
|
3
|
+
*
|
|
4
|
+
* Handles environment variable expansion for portable PAI configuration.
|
|
5
|
+
* Claude Code doesn't expand $HOME in settings.json env values, so we do it here.
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* import { getPaiDir, getSettingsPath } from './lib/paths';
|
|
9
|
+
* const paiDir = getPaiDir(); // Always returns expanded absolute path
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { homedir } from 'os';
|
|
13
|
+
import { join } from 'path';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Expand shell variables in a path string
|
|
17
|
+
* Supports: $HOME, ${HOME}, ~
|
|
18
|
+
*/
|
|
19
|
+
export function expandPath(path: string): string {
|
|
20
|
+
const home = homedir();
|
|
21
|
+
|
|
22
|
+
return path
|
|
23
|
+
.replace(/^\$HOME(?=\/|$)/, home)
|
|
24
|
+
.replace(/^\$\{HOME\}(?=\/|$)/, home)
|
|
25
|
+
.replace(/^~(?=\/|$)/, home);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Get the PAI directory (expanded)
|
|
30
|
+
* Priority: PAI_DIR env var (expanded) → ~/.claude
|
|
31
|
+
*/
|
|
32
|
+
export function getPaiDir(): string {
|
|
33
|
+
const envPaiDir = process.env.PAI_DIR;
|
|
34
|
+
|
|
35
|
+
if (envPaiDir) {
|
|
36
|
+
return expandPath(envPaiDir);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return join(homedir(), '.claude');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Get the settings.json path
|
|
44
|
+
*/
|
|
45
|
+
export function getSettingsPath(): string {
|
|
46
|
+
return join(getPaiDir(), 'settings.json');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Get a path relative to PAI_DIR
|
|
51
|
+
*/
|
|
52
|
+
export function paiPath(...segments: string[]): string {
|
|
53
|
+
return join(getPaiDir(), ...segments);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Get the hooks directory
|
|
58
|
+
* Priority: PAI_HOOKS_DIR env var → ~/.pai/hooks
|
|
59
|
+
*/
|
|
60
|
+
export function getHooksDir(): string {
|
|
61
|
+
const envHooksDir = process.env.PAI_HOOKS_DIR;
|
|
62
|
+
if (envHooksDir) return expandPath(envHooksDir);
|
|
63
|
+
return join(homedir(), '.pai', 'hooks');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Get the skills directory
|
|
68
|
+
*/
|
|
69
|
+
export function getSkillsDir(): string {
|
|
70
|
+
return paiPath('skills');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Get the MEMORY directory
|
|
75
|
+
*/
|
|
76
|
+
export function getMemoryDir(): string {
|
|
77
|
+
return paiPath('MEMORY');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Get the PAI work directory (expanded)
|
|
82
|
+
* Priority: RUNGATE_WORK_DIR env var (expanded) → ~/.rungate
|
|
83
|
+
*/
|
|
84
|
+
export function getWorkDir(): string {
|
|
85
|
+
const envWorkDir = process.env.RUNGATE_WORK_DIR;
|
|
86
|
+
|
|
87
|
+
if (envWorkDir) {
|
|
88
|
+
return expandPath(envWorkDir);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return join(homedir(), '.rungate');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Get a path relative to WORK_DIR
|
|
96
|
+
*/
|
|
97
|
+
export function workPath(...segments: string[]): string {
|
|
98
|
+
return join(getWorkDir(), ...segments);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Get the signals directory
|
|
103
|
+
*/
|
|
104
|
+
export function getSignalDir(): string {
|
|
105
|
+
return workPath('signals');
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Convenience constants (evaluated once at module load)
|
|
109
|
+
export const BASE_DIR = getPaiDir();
|
|
110
|
+
export const WORK_DIR = getWorkDir();
|
|
111
|
+
export const SIGNAL_DIR = getSignalDir();
|