rungate 0.2.1 → 0.3.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/bin/rungate.ts +70 -0
- package/lib/aes-calculator.ts +66 -0
- package/lib/agent-audit.ts +139 -0
- package/lib/agent-brief-validation.ts +359 -0
- package/lib/agents-md-refs.ts +90 -0
- package/lib/bash-file-read.ts +197 -0
- package/lib/behavioral-cache.ts +78 -0
- package/lib/branch-cleanup.ts +234 -0
- package/lib/brief-context-parser.ts +35 -0
- package/lib/canary.ts +117 -0
- package/lib/check-registry.ts +226 -0
- package/lib/ci-checkout.ts +400 -0
- package/lib/cli-commands.ts +137 -0
- package/lib/compliance-backfill.ts +220 -0
- package/lib/compliance-report.ts +504 -0
- package/lib/compliance.ts +361 -0
- package/lib/config-loader.ts +255 -0
- package/lib/conformity.ts +1818 -131
- package/lib/container-provenance.ts +230 -0
- package/lib/create-brief.ts +150 -0
- package/lib/create-sc.ts +272 -0
- package/lib/deep-merge.ts +69 -0
- package/lib/dev-liveness.ts +214 -0
- package/lib/directive-extractor.ts +210 -0
- package/lib/distribution-standing.ts +113 -0
- package/lib/doc-hygiene.ts +238 -0
- package/lib/eval-criteria.ts +6 -0
- package/lib/evidence-portability.ts +123 -0
- package/lib/evidence-prevalidator.ts +390 -0
- package/lib/evidence-required.ts +150 -0
- package/lib/evidence-satisfiability.ts +288 -0
- package/lib/frontmatter.ts +163 -0
- package/lib/gap-scanner.ts +348 -0
- package/lib/gate-enforcement.ts +366 -0
- package/lib/generators/agent-briefs.ts +136 -0
- package/lib/generators/agents-md.ts +506 -0
- package/lib/generators/code-map.ts +60 -0
- package/lib/generators/types.ts +184 -0
- package/lib/git-ref-normalizer.ts +107 -0
- package/lib/github.ts +539 -0
- package/lib/harness-identity.ts +63 -0
- package/lib/hill-climb.ts +164 -0
- package/lib/instruction-effectiveness.ts +131 -0
- package/lib/issue-closure-audit.ts +225 -0
- package/lib/issue-create-override.ts +343 -0
- package/lib/js-top-level-code.ts +250 -0
- package/lib/liveness-contradiction.ts +149 -0
- package/lib/organize.ts +505 -0
- package/lib/paths.ts +197 -6
- package/lib/post-fix-verify.ts +157 -0
- package/lib/prior-branch.ts +489 -0
- package/lib/project-state-shape.ts +166 -0
- package/lib/promote-outputs.ts +156 -0
- package/lib/prove-label-gate.ts +35 -0
- package/lib/reachability.ts +302 -0
- package/lib/release-preflight.ts +186 -0
- package/lib/rule-health-pipeline.ts +264 -0
- package/lib/rule-health-trend.ts +161 -0
- package/lib/rule-provenance.ts +149 -0
- package/lib/rule-registry.ts +128 -0
- package/lib/rungate-schema.ts +114 -4
- package/lib/sc-claim-forms.ts +179 -0
- package/lib/sc-cover.ts +150 -0
- package/lib/sc-guard.ts +157 -0
- package/lib/sc-ids.ts +344 -0
- package/lib/scaffold/defaults.ts +165 -0
- package/lib/scaffold/managed-workflow.ts +370 -0
- package/lib/scaffold/owned-files.ts +265 -0
- package/lib/scaffold/steps.ts +2680 -0
- package/lib/scanner.ts +701 -0
- package/lib/screenshot-upload.ts +73 -0
- package/lib/secret-patterns.ts +112 -0
- package/lib/security-verdict.ts +616 -0
- package/lib/signal-phrases.ts +1 -0
- package/lib/spec-change-conformity.ts +80 -0
- package/lib/spec-files.ts +62 -0
- package/lib/spec-registry.ts +133 -0
- package/lib/spec-updater.ts +96 -0
- package/lib/stale-cleanup.ts +224 -0
- package/lib/stale-issue-scanner.ts +36 -0
- package/lib/strip-js-comments.ts +269 -0
- package/lib/suite-measurement.ts +228 -0
- package/lib/task-completion-checks.ts +177 -0
- package/lib/test-suite-lock.ts +1136 -0
- package/lib/transcript-checker.ts +1140 -0
- package/lib/validators/spec-validators.ts +171 -0
- package/lib/verdict-capture.ts +73 -0
- package/lib/verified-push.ts +358 -0
- package/lib/workflow-security.ts +174 -0
- package/lib/worktree-cleanup.ts +250 -0
- package/lib/worktree-collect.ts +283 -0
- package/lib/worktree-isolation.ts +82 -0
- package/package.json +24 -2
- package/prompts/ac-adversary.md +14 -2
- package/prompts/aditi.md +5 -0
- package/prompts/blast-radius.md +5 -0
- package/prompts/container-verify.md +5 -0
- package/prompts/discovery.md +4 -0
- package/prompts/environment.md +5 -0
- package/prompts/evidence-hierarchy.md +5 -0
- package/prompts/evidence-validator.md +11 -0
- package/prompts/marcus.md +5 -0
- package/prompts/prevention.md +5 -0
- package/prompts/prove-reproducer.md +12 -0
- package/prompts/quinn-decision-tree.md +5 -0
- package/prompts/quinn-ui-brief.md +5 -0
- package/prompts/quinn.md +5 -0
- package/prompts/rca.md +5 -0
- package/prompts/read-before-write.md +4 -0
- package/prompts/regression.md +5 -0
- package/prompts/serena.md +5 -0
- package/scripts/audit-specs.ts +464 -0
- package/scripts/convert-spec.ts +293 -0
- package/scripts/create-sc.ts +92 -0
- package/scripts/create-spec.ts +166 -0
- package/scripts/extract-constraints.ts +4 -3
- package/scripts/generate-code-map.ts +1 -1
- package/scripts/scaffold-project.ts +138 -1426
- package/scripts/sync-spec-tests.ts +211 -126
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which backtick spans in AGENTS.md are file references (#380).
|
|
3
|
+
*
|
|
4
|
+
* `refreshAgentsMd` checked that every path mentioned in AGENTS.md resolves.
|
|
5
|
+
* Its pattern was:
|
|
6
|
+
*
|
|
7
|
+
* ```
|
|
8
|
+
* /`([^`]+\.(md|json|ts|js|tsx|yml|yaml))`/g
|
|
9
|
+
* ```
|
|
10
|
+
*
|
|
11
|
+
* **A backtick span is not a path.** AGENTS.md has a Commands table, and
|
|
12
|
+
* several of its commands end in a filename, so the whole command string was
|
|
13
|
+
* handed to `existsSync`. Measured on this repo at the time of the fix:
|
|
14
|
+
*
|
|
15
|
+
* | span | verdict | correct? |
|
|
16
|
+
* |---|---|---|
|
|
17
|
+
* | `bun scripts/typecheck.ts` | BROKEN | no |
|
|
18
|
+
* | `bun scripts/test-clean-env.ts` | BROKEN | no |
|
|
19
|
+
* | `bun test test/scaffold-conformity.test.ts` | BROKEN | no |
|
|
20
|
+
*
|
|
21
|
+
* Three reports, three false positives, and **zero** true positives — the
|
|
22
|
+
* check had never once validated a real reference here.
|
|
23
|
+
*
|
|
24
|
+
* That is worse than noise. A standing false positive trains readers to
|
|
25
|
+
* ignore the whole class, so the day it finds a genuinely dangling pointer
|
|
26
|
+
* nobody looks. It is also unfixable from the doc's side: the span is not a
|
|
27
|
+
* path, so no edit to AGENTS.md makes it green except deleting the Commands
|
|
28
|
+
* row — the detector dictating the document.
|
|
29
|
+
*
|
|
30
|
+
* ## The predicate
|
|
31
|
+
*
|
|
32
|
+
* Positive, not a blacklist. A reference is a span that is *nothing but* a
|
|
33
|
+
* path: path characters only, ending in a known extension. A blacklist of
|
|
34
|
+
* "things that look like commands" is the detector-narrower-than-what-it-
|
|
35
|
+
* detects shape from `.claude/rules/checks-must-be-able-to-fail.md`, one
|
|
36
|
+
* unanticipated command away from being wrong again.
|
|
37
|
+
*
|
|
38
|
+
* ## The direction this is allowed to be wrong in
|
|
39
|
+
*
|
|
40
|
+
* Toward NOT reporting. A real path this refuses to check costs a dangling
|
|
41
|
+
* link nobody is told about — recoverable, and the same call
|
|
42
|
+
* `.claude/rules/claiming-sc-coverage.md` makes for the same reason. The
|
|
43
|
+
* other direction is what shipped: a report that cannot be acted on, three
|
|
44
|
+
* times a run, drowning the signal it exists to carry.
|
|
45
|
+
*
|
|
46
|
+
* Deliberately NOT done: extracting the path out of a command and checking
|
|
47
|
+
* that. It would catch more — `bun scripts/typecheck.ts` really does name a
|
|
48
|
+
* file — but a Commands table also holds `<file>` placeholders, generated
|
|
49
|
+
* build outputs and paths relative to somewhere else, and guessing which is
|
|
50
|
+
* which reintroduces the false positives from the other end.
|
|
51
|
+
*/
|
|
52
|
+
|
|
53
|
+
/** Extensions the reference check knows how to resolve. */
|
|
54
|
+
const EXTENSIONS = ["md", "json", "ts", "js", "tsx", "yml", "yaml"] as const;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* A span that is nothing but a relative path ending in a known extension.
|
|
58
|
+
*
|
|
59
|
+
* `[\w.\-/@]` admits what paths in this repo are made of and nothing else.
|
|
60
|
+
* No whitespace, so a command is out. No `:`, so a URL is out. No `<`, `[`
|
|
61
|
+
* or `$`, so a placeholder or a variable is out.
|
|
62
|
+
*/
|
|
63
|
+
const PATH_SPAN = new RegExp(`^[\\w.\\-/@]+\\.(?:${EXTENSIONS.join("|")})$`);
|
|
64
|
+
|
|
65
|
+
/** Every backtick span in the document, whether or not it is a path. */
|
|
66
|
+
const BACKTICK_SPAN = /`([^`\n]+)`/g;
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Whether one backtick span should be resolved against the filesystem.
|
|
70
|
+
*
|
|
71
|
+
* The single exported predicate. `refreshAgentsMd` has two scans — broken
|
|
72
|
+
* links and staleness — and they must agree about what a reference is, or
|
|
73
|
+
* the second silently stops covering spans the first rejects.
|
|
74
|
+
*/
|
|
75
|
+
export function isPathReference(span: string): boolean {
|
|
76
|
+
// No glob guard in front of this. The first draft had
|
|
77
|
+
// `if (span.includes("*")) return false;` and it scored 0 on mutation:
|
|
78
|
+
// `*` is not in the character class, so a glob never reached it. A branch
|
|
79
|
+
// that cannot change an answer reads to the next person as if it can.
|
|
80
|
+
return PATH_SPAN.test(span);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The path references in a document, in order, deduplicated. */
|
|
84
|
+
export function referencedPaths(content: string): string[] {
|
|
85
|
+
const out = new Set<string>();
|
|
86
|
+
for (const m of content.matchAll(BACKTICK_SPAN)) {
|
|
87
|
+
if (isPathReference(m[1])) out.add(m[1]);
|
|
88
|
+
}
|
|
89
|
+
return [...out];
|
|
90
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* bash-file-read.ts -- COMP-7 detection logic
|
|
3
|
+
* SC-368 (hook logic lives in lib/, hooks stay thin)
|
|
4
|
+
*
|
|
5
|
+
* Single source of truth for "is this Bash command reading a file with
|
|
6
|
+
* cat/head/tail?". Used by BOTH the enforcement hook (BashToolGuard) and the
|
|
7
|
+
* grader (lib/transcript-checker.ts) so enforcement and measurement can never
|
|
8
|
+
* drift apart.
|
|
9
|
+
*
|
|
10
|
+
* The distinction that matters: cat/head/tail with a FILE OPERAND read a file
|
|
11
|
+
* and must use the Read tool instead. The same commands with no operand read
|
|
12
|
+
* STDIN — they are output filters (`bun test | tail -30`), not file reads, and
|
|
13
|
+
* the Read tool cannot replace them.
|
|
14
|
+
*
|
|
15
|
+
* The previous rule blocked any pipe into head/tail. It had a high false
|
|
16
|
+
* positive rate: it blocked Anthropic's bundled skills, blocked `bun test`
|
|
17
|
+
* output filtering, and blocked the git commit of its own fix because the
|
|
18
|
+
* commit message body contained the literal text "| head -80".
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/** Commands that read files when given an operand. */
|
|
22
|
+
const FILE_READERS = new Set(['cat', 'head', 'tail']);
|
|
23
|
+
|
|
24
|
+
/** Flags that consume the following token as their value (`head -n 20 f`). */
|
|
25
|
+
const VALUE_FLAGS = new Set(['-n', '-c', '--lines', '--bytes']);
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Wrappers and prefixes that delegate to the real command, plus `VAR=value`
|
|
29
|
+
* assignments. `env FOO=1 /bin/cat x` must resolve to `cat`.
|
|
30
|
+
*/
|
|
31
|
+
const PREFIXES = new Set(['command', 'exec', 'builtin', 'env', 'nohup', 'time', 'sudo']);
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Drop wrapper prefixes and inline env assignments so the first remaining
|
|
35
|
+
* token is the actual command.
|
|
36
|
+
*/
|
|
37
|
+
function stripPrefixes(tokens: string[]): string[] {
|
|
38
|
+
let i = 0;
|
|
39
|
+
while (i < tokens.length && (PREFIXES.has(tokens[i]) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[i]))) i++;
|
|
40
|
+
return tokens.slice(i);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* A redirection operator, with an optional leading fd and an optionally
|
|
45
|
+
* attached target: `>`, `>>`, `2>`, `&>`, `>/tmp/x`, `2>&1`, `<`, `<>`.
|
|
46
|
+
*/
|
|
47
|
+
const REDIRECT = /^(\d*)(&?>>?\|?|<>?)(.*)$/;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* True when the token list (argv-style, command first) includes a file operand
|
|
51
|
+
* — i.e. a non-flag argument that is not the value of a preceding flag and not
|
|
52
|
+
* part of a redirection.
|
|
53
|
+
*
|
|
54
|
+
* Redirections are not operands. `cat > out.txt <<EOF` WRITES a file; it reads
|
|
55
|
+
* stdin, so the Read tool cannot replace it and blocking it is a false
|
|
56
|
+
* positive. Input redirection is the exception — `cat < file` genuinely reads
|
|
57
|
+
* a file and should still be blocked.
|
|
58
|
+
*/
|
|
59
|
+
function hasFileOperand(tokens: string[]): boolean {
|
|
60
|
+
for (let i = 1; i < tokens.length; i++) {
|
|
61
|
+
const tok = tokens[i];
|
|
62
|
+
if (VALUE_FLAGS.has(tok)) {
|
|
63
|
+
i++; // skip the flag's value
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (tok.startsWith('-')) continue; // -20, -n20, --lines=20, -f
|
|
67
|
+
|
|
68
|
+
const redirect = tok.match(REDIRECT);
|
|
69
|
+
if (redirect) {
|
|
70
|
+
const [, , op, attached] = redirect;
|
|
71
|
+
// An unattached target (`> out.txt`) sits in the next token.
|
|
72
|
+
if (!attached) i++;
|
|
73
|
+
if (op.startsWith('<')) return true; // `cat < file` does read a file
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Split a shell command into pipeline/chain segments on `|`, `||`, `&`, `&&`
|
|
84
|
+
* and `;`.
|
|
85
|
+
*
|
|
86
|
+
* Quote-aware by necessity: a naive regex split tears quoted strings apart, so
|
|
87
|
+
* `git commit -m "explain grep | head -80"` yielded a bogus `head -80"` segment
|
|
88
|
+
* and blocked the commit. Operators inside single or double quotes are literal
|
|
89
|
+
* text and must not split.
|
|
90
|
+
*/
|
|
91
|
+
function splitSegments(command: string): string[] {
|
|
92
|
+
const segments: string[] = [];
|
|
93
|
+
let current = '';
|
|
94
|
+
let quote: "'" | '"' | null = null;
|
|
95
|
+
|
|
96
|
+
for (let i = 0; i < command.length; i++) {
|
|
97
|
+
const ch = command[i];
|
|
98
|
+
|
|
99
|
+
if (quote) {
|
|
100
|
+
current += ch;
|
|
101
|
+
// Backslash escapes apply inside double quotes, not single quotes.
|
|
102
|
+
if (ch === '\\' && quote === '"' && i + 1 < command.length) current += command[++i];
|
|
103
|
+
else if (ch === quote) quote = null;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (ch === "'" || ch === '"') {
|
|
108
|
+
quote = ch;
|
|
109
|
+
current += ch;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (ch === '\\' && i + 1 < command.length) {
|
|
114
|
+
current += ch + command[++i];
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Newlines separate commands just like `;` does — multi-line scripts and
|
|
119
|
+
// interpreter heredocs put each command on its own line.
|
|
120
|
+
if (ch === '|' || ch === '&' || ch === ';' || ch === '\n') {
|
|
121
|
+
if ((ch === '|' || ch === '&') && command[i + 1] === ch) i++; // consume || and &&
|
|
122
|
+
segments.push(current);
|
|
123
|
+
current = '';
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
current += ch;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
segments.push(current);
|
|
131
|
+
return segments;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Shell interpreters that execute a heredoc body as commands. */
|
|
135
|
+
const INTERPRETERS = /(^|[\s;&|])(ba|z|k|da)?sh\s*$/;
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Remove heredoc bodies before scanning.
|
|
139
|
+
*
|
|
140
|
+
* A heredoc body is DATA, not commands — but the hook sees the whole raw
|
|
141
|
+
* command string, so `git commit -F - <<EOF ... cat package.json ... EOF`
|
|
142
|
+
* looked like a file read and blocked the commit. This matches the exemption
|
|
143
|
+
* lib/transcript-checker.ts already applies via its `<<` check.
|
|
144
|
+
*
|
|
145
|
+
* Exception: when the command feeding the heredoc is a shell interpreter
|
|
146
|
+
* (`bash <<EOF`), the body really does execute, so it is left in place.
|
|
147
|
+
*/
|
|
148
|
+
function stripHeredocBodies(command: string): string {
|
|
149
|
+
if (!command.includes('<<')) return command;
|
|
150
|
+
|
|
151
|
+
const out: string[] = [];
|
|
152
|
+
let delim: string | null = null;
|
|
153
|
+
let allowIndent = false;
|
|
154
|
+
|
|
155
|
+
for (const line of command.split('\n')) {
|
|
156
|
+
if (delim !== null) {
|
|
157
|
+
if ((allowIndent ? line.trimStart() : line) === delim) delim = null;
|
|
158
|
+
continue; // drop body and terminator
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const m = line.match(/<<(-?)\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\2/);
|
|
162
|
+
if (m && !INTERPRETERS.test(line.slice(0, m.index))) {
|
|
163
|
+
allowIndent = m[1] === '-';
|
|
164
|
+
delim = m[3];
|
|
165
|
+
out.push(line.slice(0, m.index) + line.slice(m.index! + m[0].length));
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
out.push(line);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return out.join('\n');
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Detects cat/head/tail being used to read a file in any segment of a shell
|
|
177
|
+
* command — direct, `;`-chained, `&&`-chained, or piped.
|
|
178
|
+
*
|
|
179
|
+
* Returns the offending segment, or null when the command is clean. Pure
|
|
180
|
+
* stdin filters (`cmd | head -80`, `cmd | tail -30`, `cmd | cat`) return null.
|
|
181
|
+
*/
|
|
182
|
+
export function detectBashFileRead(command: string): string | null {
|
|
183
|
+
for (const segment of splitSegments(stripHeredocBodies(command))) {
|
|
184
|
+
const tokens = stripPrefixes(segment.trim().split(/\s+/).filter(Boolean));
|
|
185
|
+
if (!tokens.length) continue;
|
|
186
|
+
// Basename so /bin/cat and /usr/bin/head resolve to cat and head.
|
|
187
|
+
const name = tokens[0].split('/').pop()!;
|
|
188
|
+
if (!FILE_READERS.has(name)) continue;
|
|
189
|
+
if (hasFileOperand(tokens)) return segment.trim();
|
|
190
|
+
}
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Convenience boolean wrapper. */
|
|
195
|
+
export function isBashFileRead(command: string): boolean {
|
|
196
|
+
return detectBashFileRead(command) !== null;
|
|
197
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* behavioral-cache.ts — Cached behavioral results for SC status sync
|
|
3
|
+
*
|
|
4
|
+
* Provides read/write access to .rungate/behavioral-results.json.
|
|
5
|
+
* Cache entries map SC IDs to { passed, evidence, timestamp }.
|
|
6
|
+
* Entries older than 7 days are treated as stale (unmatchable).
|
|
7
|
+
*
|
|
8
|
+
* Deep module: 3 public functions (readCache, writeCache, readFreshCache, isStale),
|
|
9
|
+
* simple interface hiding file I/O and staleness logic.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";
|
|
13
|
+
import { dirname } from "path";
|
|
14
|
+
|
|
15
|
+
// ── Types ───────────────────────────────────────────────
|
|
16
|
+
|
|
17
|
+
export interface CacheEntry {
|
|
18
|
+
passed: boolean;
|
|
19
|
+
evidence: string;
|
|
20
|
+
timestamp: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type BehavioralCache = Record<string, CacheEntry>;
|
|
24
|
+
|
|
25
|
+
// ── Constants ───────────────────────────────────────────
|
|
26
|
+
|
|
27
|
+
const STALE_THRESHOLD_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
|
|
28
|
+
|
|
29
|
+
// ── Public API ──────────────────────────────────────────
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Read the behavioral results cache from disk.
|
|
33
|
+
* Returns empty object if file doesn't exist or is malformed.
|
|
34
|
+
*/
|
|
35
|
+
export function readCache(path: string): BehavioralCache {
|
|
36
|
+
if (!existsSync(path)) return {};
|
|
37
|
+
try {
|
|
38
|
+
return JSON.parse(readFileSync(path, "utf-8"));
|
|
39
|
+
} catch {
|
|
40
|
+
return {};
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Write entries to the behavioral results cache, merging with existing.
|
|
46
|
+
* Creates parent directories if needed.
|
|
47
|
+
*/
|
|
48
|
+
export function writeCache(path: string, data: BehavioralCache): void {
|
|
49
|
+
const dir = dirname(path);
|
|
50
|
+
if (!existsSync(dir)) {
|
|
51
|
+
mkdirSync(dir, { recursive: true });
|
|
52
|
+
}
|
|
53
|
+
const existing = readCache(path);
|
|
54
|
+
const merged = { ...existing, ...data };
|
|
55
|
+
writeFileSync(path, JSON.stringify(merged, null, 2));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Check if a timestamp is older than 7 days.
|
|
60
|
+
*/
|
|
61
|
+
export function isStale(timestamp: string): boolean {
|
|
62
|
+
const age = Date.now() - new Date(timestamp).getTime();
|
|
63
|
+
return age >= STALE_THRESHOLD_MS;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Read cache and filter out stale entries (older than 7 days).
|
|
68
|
+
*/
|
|
69
|
+
export function readFreshCache(path: string): BehavioralCache {
|
|
70
|
+
const cache = readCache(path);
|
|
71
|
+
const fresh: BehavioralCache = {};
|
|
72
|
+
for (const [id, entry] of Object.entries(cache)) {
|
|
73
|
+
if (!isStale(entry.timestamp)) {
|
|
74
|
+
fresh[id] = entry;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return fresh;
|
|
78
|
+
}
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Branch cleanup — deletes abandoned ship branches that have no open PR.
|
|
3
|
+
*
|
|
4
|
+
* Two entry points:
|
|
5
|
+
* - cleanupBranch(): deletes a single branch (used by prove UNPROVEN flow)
|
|
6
|
+
* - cleanupStaleBranches(): bulk cleanup of remote branches older than N days
|
|
7
|
+
* (used by StaleTTLCleanup hook on session start)
|
|
8
|
+
*
|
|
9
|
+
* Safety:
|
|
10
|
+
* - NEVER deletes protected branches (main, master)
|
|
11
|
+
* - NEVER deletes branches with open PRs
|
|
12
|
+
* - When PR check fails, refuses to delete (safety default)
|
|
13
|
+
*
|
|
14
|
+
* GitHub issue #516
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { spawnSync } from "child_process";
|
|
18
|
+
import { createGitHubClient, listPRs, type GitHubClient } from "./github";
|
|
19
|
+
|
|
20
|
+
// ── Types ───────────────────────────────────────────────────
|
|
21
|
+
|
|
22
|
+
export interface CommandResult {
|
|
23
|
+
readonly stdout: string;
|
|
24
|
+
readonly stderr: string;
|
|
25
|
+
readonly status: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export type CommandExecutor = (
|
|
29
|
+
cmd: string,
|
|
30
|
+
args: readonly string[]
|
|
31
|
+
) => CommandResult;
|
|
32
|
+
|
|
33
|
+
export interface CleanupBranchOptions {
|
|
34
|
+
readonly branch: string;
|
|
35
|
+
readonly projectRoot: string;
|
|
36
|
+
readonly executor?: CommandExecutor;
|
|
37
|
+
readonly githubClient?: GitHubClient;
|
|
38
|
+
readonly repo?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface CleanupBranchResult {
|
|
42
|
+
readonly deleted: boolean;
|
|
43
|
+
readonly reason?: string;
|
|
44
|
+
readonly error?: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface CleanupStaleBranchesOptions {
|
|
48
|
+
readonly projectRoot: string;
|
|
49
|
+
readonly maxAgeDays?: number;
|
|
50
|
+
readonly executor?: CommandExecutor;
|
|
51
|
+
readonly githubClient?: GitHubClient;
|
|
52
|
+
readonly repo?: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface CleanupStaleBranchesResult {
|
|
56
|
+
readonly deleted: string[];
|
|
57
|
+
readonly skipped: string[];
|
|
58
|
+
readonly errors: string[];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// ── Constants ───────────────────────────────────────────────
|
|
62
|
+
|
|
63
|
+
const PROTECTED_BRANCHES = new Set(["main", "master"]);
|
|
64
|
+
const DEFAULT_MAX_AGE_DAYS = 7;
|
|
65
|
+
|
|
66
|
+
// ── Default executor ────────────────────────────────────────
|
|
67
|
+
|
|
68
|
+
function defaultExecutor(cmd: string, args: readonly string[]): CommandResult {
|
|
69
|
+
const result = spawnSync(cmd, [...args], {
|
|
70
|
+
encoding: "utf-8",
|
|
71
|
+
timeout: 15_000,
|
|
72
|
+
});
|
|
73
|
+
return {
|
|
74
|
+
stdout: result.stdout ?? "",
|
|
75
|
+
stderr: result.stderr ?? "",
|
|
76
|
+
status: result.status ?? 1,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// ── Core: check for open PRs via Octokit ────────────────────
|
|
81
|
+
|
|
82
|
+
async function hasOpenPR(
|
|
83
|
+
branch: string,
|
|
84
|
+
client?: GitHubClient,
|
|
85
|
+
repo?: string,
|
|
86
|
+
): Promise<{ hasPR: boolean; error?: string }> {
|
|
87
|
+
try {
|
|
88
|
+
const github = client || createGitHubClient();
|
|
89
|
+
const repoSlug = repo || "hornjason/pai-harness";
|
|
90
|
+
const prs = await listPRs(github, repoSlug, { state: "open", head: branch, per_page: 1 });
|
|
91
|
+
return { hasPR: Array.isArray(prs) && prs.length > 0 };
|
|
92
|
+
} catch (e: any) {
|
|
93
|
+
return { hasPR: false, error: `listPRs failed: ${e.message?.slice(0, 200)}` };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// ── cleanupBranch ───────────────────────────────────────────
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Delete a single branch (local + remote) if no open PR exists.
|
|
101
|
+
*
|
|
102
|
+
* Used by the prove workflow when verdict is UNPROVEN.
|
|
103
|
+
*/
|
|
104
|
+
export async function cleanupBranch(opts: CleanupBranchOptions): Promise<CleanupBranchResult> {
|
|
105
|
+
const { branch, projectRoot, executor = defaultExecutor, githubClient, repo } = opts;
|
|
106
|
+
|
|
107
|
+
// Guard: never delete protected branches
|
|
108
|
+
if (PROTECTED_BRANCHES.has(branch)) {
|
|
109
|
+
return { deleted: false, reason: `${branch} is a protected branch` };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Check for open PRs via Octokit
|
|
113
|
+
const prCheck = await hasOpenPR(branch, githubClient, repo);
|
|
114
|
+
if (prCheck.error) {
|
|
115
|
+
return {
|
|
116
|
+
deleted: false,
|
|
117
|
+
reason: "Cannot verify PR status — refusing to delete",
|
|
118
|
+
error: prCheck.error,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (prCheck.hasPR) {
|
|
123
|
+
return { deleted: false, reason: `open PR exists for ${branch}` };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Delete local branch
|
|
127
|
+
executor("git", ["-C", projectRoot, "branch", "-D", branch]);
|
|
128
|
+
|
|
129
|
+
// Delete remote branch (ignore failure — remote may not exist)
|
|
130
|
+
executor("git", ["-C", projectRoot, "push", "origin", "--delete", branch]);
|
|
131
|
+
|
|
132
|
+
return { deleted: true };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// ── cleanupStaleBranches ────────────────────────────────────
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Find and delete remote branches older than maxAgeDays with no open PR.
|
|
139
|
+
*
|
|
140
|
+
* Used by StaleTTLCleanup hook on session start.
|
|
141
|
+
*/
|
|
142
|
+
export async function cleanupStaleBranches(
|
|
143
|
+
opts: CleanupStaleBranchesOptions
|
|
144
|
+
): Promise<CleanupStaleBranchesResult> {
|
|
145
|
+
const {
|
|
146
|
+
projectRoot,
|
|
147
|
+
maxAgeDays = DEFAULT_MAX_AGE_DAYS,
|
|
148
|
+
executor = defaultExecutor,
|
|
149
|
+
githubClient,
|
|
150
|
+
repo,
|
|
151
|
+
} = opts;
|
|
152
|
+
|
|
153
|
+
const result: CleanupStaleBranchesResult = {
|
|
154
|
+
deleted: [],
|
|
155
|
+
skipped: [],
|
|
156
|
+
errors: [],
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
// List remote branches with their committer dates
|
|
160
|
+
const refList = executor("git", [
|
|
161
|
+
"-C",
|
|
162
|
+
projectRoot,
|
|
163
|
+
"for-each-ref",
|
|
164
|
+
"--format=%(committerdate:unix)\t%(refname)",
|
|
165
|
+
"refs/remotes/origin",
|
|
166
|
+
]);
|
|
167
|
+
|
|
168
|
+
if (refList.status !== 0) {
|
|
169
|
+
(result.errors as string[]).push(
|
|
170
|
+
`Failed to list remote branches: ${refList.stderr}`
|
|
171
|
+
);
|
|
172
|
+
return result;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const lines = refList.stdout.trim().split("\n").filter(Boolean);
|
|
176
|
+
const nowUnix = Math.floor(Date.now() / 1000);
|
|
177
|
+
const maxAgeSeconds = maxAgeDays * 24 * 60 * 60;
|
|
178
|
+
|
|
179
|
+
for (const line of lines) {
|
|
180
|
+
const [tsStr, refName] = line.split("\t");
|
|
181
|
+
if (!tsStr || !refName) continue;
|
|
182
|
+
|
|
183
|
+
const branchName = refName.replace(/^refs\/remotes\/origin\//, "");
|
|
184
|
+
|
|
185
|
+
// Skip protected branches
|
|
186
|
+
if (PROTECTED_BRANCHES.has(branchName)) continue;
|
|
187
|
+
|
|
188
|
+
// Skip HEAD pointer
|
|
189
|
+
if (branchName === "HEAD") continue;
|
|
190
|
+
|
|
191
|
+
// Check age
|
|
192
|
+
const ts = parseInt(tsStr, 10);
|
|
193
|
+
if (isNaN(ts)) continue;
|
|
194
|
+
|
|
195
|
+
const ageSeconds = nowUnix - ts;
|
|
196
|
+
if (ageSeconds < maxAgeSeconds) continue;
|
|
197
|
+
|
|
198
|
+
// Check for open PRs via Octokit
|
|
199
|
+
const prCheck = await hasOpenPR(branchName, githubClient, repo);
|
|
200
|
+
if (prCheck.error) {
|
|
201
|
+
(result.errors as string[]).push(
|
|
202
|
+
`Cannot check PRs for ${branchName}: ${prCheck.error}`
|
|
203
|
+
);
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (prCheck.hasPR) {
|
|
208
|
+
(result.skipped as string[]).push(
|
|
209
|
+
`${branchName} (open PR exists)`
|
|
210
|
+
);
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Delete remote branch
|
|
215
|
+
const delResult = executor("git", [
|
|
216
|
+
"-C",
|
|
217
|
+
projectRoot,
|
|
218
|
+
"push",
|
|
219
|
+
"origin",
|
|
220
|
+
"--delete",
|
|
221
|
+
branchName,
|
|
222
|
+
]);
|
|
223
|
+
|
|
224
|
+
if (delResult.status !== 0) {
|
|
225
|
+
(result.errors as string[]).push(
|
|
226
|
+
`Failed to delete ${branchName}: ${delResult.stderr}`
|
|
227
|
+
);
|
|
228
|
+
} else {
|
|
229
|
+
(result.deleted as string[]).push(branchName);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return result;
|
|
234
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
const CONTEXT_HEADING = /^##\s+Context\b/;
|
|
2
|
+
const NEXT_HEADING = /^##\s+/;
|
|
3
|
+
const BOLD_PATH = /\*\*([^*]+)\*\*/;
|
|
4
|
+
const SECTION_MARKER = /\s*§.*$/;
|
|
5
|
+
const FILE_PATH_PATTERN = /^[\w][\w./-]*\.\w+$/;
|
|
6
|
+
|
|
7
|
+
export function parseContextPaths(markdown: string): string[] {
|
|
8
|
+
const lines = markdown.split("\n");
|
|
9
|
+
let inContext = false;
|
|
10
|
+
const paths: string[] = [];
|
|
11
|
+
|
|
12
|
+
for (const line of lines) {
|
|
13
|
+
if (!inContext) {
|
|
14
|
+
if (CONTEXT_HEADING.test(line)) inContext = true;
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
if (NEXT_HEADING.test(line) && !CONTEXT_HEADING.test(line)) break;
|
|
18
|
+
|
|
19
|
+
const match = BOLD_PATH.exec(line);
|
|
20
|
+
if (!match) continue;
|
|
21
|
+
|
|
22
|
+
const raw = match[1].replace(SECTION_MARKER, "").trim();
|
|
23
|
+
if (FILE_PATH_PATTERN.test(raw)) paths.push(raw);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return paths;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function buildReadSteps(briefPath: string, contextPaths: string[]): string {
|
|
30
|
+
const steps = [`1. Read \`${briefPath}\``];
|
|
31
|
+
for (let i = 0; i < contextPaths.length; i++) {
|
|
32
|
+
steps.push(`${i + 2}. Read \`${contextPaths[i]}\``);
|
|
33
|
+
}
|
|
34
|
+
return steps.join("\n");
|
|
35
|
+
}
|