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,489 @@
|
|
|
1
|
+
import { spawnSync } from 'child_process'
|
|
2
|
+
import { createGitHubClient, listPRs, type GitHubClient } from './github'
|
|
3
|
+
|
|
4
|
+
export interface PriorBranch {
|
|
5
|
+
/**
|
|
6
|
+
* Bare branch name, with no namespace. This is the push target —
|
|
7
|
+
* ship.js builds `HEAD:${branch}` from it — so it must stay bare even
|
|
8
|
+
* when the branch was only found on origin.
|
|
9
|
+
*/
|
|
10
|
+
branch: string;
|
|
11
|
+
/**
|
|
12
|
+
* A ref THIS repository resolves: `refs/heads/x` or `refs/remotes/origin/x`.
|
|
13
|
+
* Anything that merges, diffs or checks out the prior work uses this.
|
|
14
|
+
*/
|
|
15
|
+
refName: string;
|
|
16
|
+
/**
|
|
17
|
+
* Commits ahead of the base branch, or `null` when git could not answer.
|
|
18
|
+
* `0` is a claim ("nothing to resume"); `null` is the absence of one.
|
|
19
|
+
*/
|
|
20
|
+
commitCount: number | null;
|
|
21
|
+
/**
|
|
22
|
+
* Commits the base branch has that the candidate does not, or `null` when
|
|
23
|
+
* git could not answer (#185).
|
|
24
|
+
*
|
|
25
|
+
* Without this a branch 64 ahead and 4 behind reads exactly like one sitting
|
|
26
|
+
* on the tip, and the only consumer that matters — ship.js's push target —
|
|
27
|
+
* cannot tell them apart. The measured case: `run/254-wf19f7def7-rescue`,
|
|
28
|
+
* 1 ahead and 8 behind main, became `git push origin HEAD:run/254-…`, which
|
|
29
|
+
* the remote can only reject.
|
|
30
|
+
*
|
|
31
|
+
* Same contract as commitCount: `0` is the claim "level with the base",
|
|
32
|
+
* `null` is the absence of a claim.
|
|
33
|
+
*/
|
|
34
|
+
behindCount: number | null;
|
|
35
|
+
/** `behindCount > 0`. `null` when the count could not be taken. */
|
|
36
|
+
isBehind: boolean | null;
|
|
37
|
+
/**
|
|
38
|
+
* The base branch already contains everything the candidate has, measured by
|
|
39
|
+
* merging it into the base in memory and seeing whether the base's tree
|
|
40
|
+
* moves (#185).
|
|
41
|
+
*
|
|
42
|
+
* Tree comparison rather than `git cherry`, which compares patch-ids: this
|
|
43
|
+
* repository merges PRs by squash, and a squash commit's patch-id matches
|
|
44
|
+
* none of the commits it replaced, so patch-id comparison reports a fully
|
|
45
|
+
* landed branch as unmerged. `null` when the question could not be asked.
|
|
46
|
+
*/
|
|
47
|
+
isMerged: boolean | null;
|
|
48
|
+
testsPass: boolean;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface DetectOptions {
|
|
52
|
+
issueNumber: number;
|
|
53
|
+
projectRoot: string;
|
|
54
|
+
runTests?: boolean;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface PRCommandResult {
|
|
58
|
+
readonly stdout: string;
|
|
59
|
+
readonly stderr: string;
|
|
60
|
+
readonly status: number;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export type PRCommandExecutor = (
|
|
64
|
+
cmd: string,
|
|
65
|
+
args: readonly string[]
|
|
66
|
+
) => PRCommandResult;
|
|
67
|
+
|
|
68
|
+
export interface ExistingPR {
|
|
69
|
+
/** The open PR's number. Absent only when `unreadable`. */
|
|
70
|
+
prNumber?: number;
|
|
71
|
+
/** Its head branch. Absent only when `unreadable`. */
|
|
72
|
+
branch?: string;
|
|
73
|
+
/**
|
|
74
|
+
* The lookup could not be performed (#223).
|
|
75
|
+
*
|
|
76
|
+
* `null` means "there is no open PR for this issue", which is a claim.
|
|
77
|
+
* This flag is the absence of one. They used to be the same value: every
|
|
78
|
+
* API error returned `null` from a bare `catch`, so an unreachable GitHub
|
|
79
|
+
* read exactly like a clean issue — on the path that decides whether to
|
|
80
|
+
* implement work that may already exist.
|
|
81
|
+
*/
|
|
82
|
+
unreadable?: boolean;
|
|
83
|
+
/** Why the lookup could not be performed. Set iff `unreadable`. */
|
|
84
|
+
reason?: string;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface DetectExistingPROptions {
|
|
88
|
+
issueNumber: number;
|
|
89
|
+
repo: string;
|
|
90
|
+
executor?: PRCommandExecutor;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Does this text reference issue N? One binding, used by both detectors
|
|
95
|
+
* and by anything that reads a PR body (#223).
|
|
96
|
+
*
|
|
97
|
+
* The bound is on DIGITS, not on a `#`: the three places this has to match
|
|
98
|
+
* spell the reference three ways — `Closes #209` in a PR body, `fix(#209):`
|
|
99
|
+
* in the subject ship.js writes, and `209-deep-modules` in a branch name.
|
|
100
|
+
* The digit bound is what stops `515` matching `5150`, and it is the whole
|
|
101
|
+
* of the correctness condition; the `#` is decoration that two of the three
|
|
102
|
+
* forms do not have.
|
|
103
|
+
*
|
|
104
|
+
* Total over non-strings. It runs over `pr.body`, which GitHub returns as
|
|
105
|
+
* `null` for a PR opened with an empty body, and a throw on that path is a
|
|
106
|
+
* refusal the caller's error handling turns into a ship.
|
|
107
|
+
*
|
|
108
|
+
* The NUMBER is validated, and that is a different judgement from the text.
|
|
109
|
+
* It is interpolated into a regular expression, so a caller that reaches here
|
|
110
|
+
* with `".*"` — a workflow arg, a parsed CLI flag, a field off a JSON reply —
|
|
111
|
+
* builds a pattern matching every PR in the repo, and this predicate decides
|
|
112
|
+
* which prior work a run is about to collide with. Throwing is right where
|
|
113
|
+
* returning a never-matching predicate is not: a matcher that silently never
|
|
114
|
+
* fires is the vacuous assertion `.claude/rules/checks-must-be-able-to-fail.md`
|
|
115
|
+
* is about, and it would read exactly like an issue with no prior work.
|
|
116
|
+
*/
|
|
117
|
+
export function issueReference(issueNumber: number): (text: unknown) => boolean {
|
|
118
|
+
if (!Number.isSafeInteger(issueNumber) || issueNumber < 0) {
|
|
119
|
+
throw new TypeError(
|
|
120
|
+
`issueReference needs a non-negative integer issue number, got ${JSON.stringify(issueNumber)}`,
|
|
121
|
+
)
|
|
122
|
+
}
|
|
123
|
+
const pattern = new RegExp(`(^|[^\\d])${issueNumber}([^\\d]|$)`)
|
|
124
|
+
return (text: unknown) => typeof text === 'string' && pattern.test(text)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function git(args: string[], cwd: string, timeout = 15_000) {
|
|
128
|
+
return spawnSync('git', args, { cwd, encoding: 'utf-8', timeout })
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* The only ref namespaces a prior branch may come from (#164).
|
|
133
|
+
*
|
|
134
|
+
* `git branch -a --list` enumerates EVERY configured remote and the old code
|
|
135
|
+
* then stripped `remotes/<anything>/` off the result, so a sibling project
|
|
136
|
+
* added as a second remote donated its branch names to this repo's issues.
|
|
137
|
+
* for-each-ref over an explicit namespace list cannot do that: a ref outside
|
|
138
|
+
* these two is never returned in the first place.
|
|
139
|
+
*/
|
|
140
|
+
const CANDIDATE_REF_NAMESPACES = [
|
|
141
|
+
'refs/heads',
|
|
142
|
+
'refs/remotes/origin',
|
|
143
|
+
] as const
|
|
144
|
+
|
|
145
|
+
/** The base the prior branch's commits are counted against. */
|
|
146
|
+
const BASE_BRANCH = 'main'
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Refs the harness creates for its own bookkeeping (#185).
|
|
150
|
+
*
|
|
151
|
+
* None of these is a resumable implementation, and two of them are the
|
|
152
|
+
* opposite: `scripts/preserve-worktree-work.ts` exists to name work a run
|
|
153
|
+
* REFUSED to collect, so that it survives `git worktree remove --force`. The
|
|
154
|
+
* branch this repository carries for issue 254 says it in its own tip message
|
|
155
|
+
* — "rescued output of run wf_19f7def7-1bf — NOT reviewed, do not merge" — and
|
|
156
|
+
* detection nominated it anyway, because the only thing it read was whether
|
|
157
|
+
* the digits 254 appeared in the name.
|
|
158
|
+
*
|
|
159
|
+
* Matched on the namespace rather than on the message, because the names are
|
|
160
|
+
* assigned by the harness and the messages are written by whoever rescued the
|
|
161
|
+
* work.
|
|
162
|
+
*/
|
|
163
|
+
export function isHarnessScratchRef(branch: string): boolean {
|
|
164
|
+
return (
|
|
165
|
+
// lib/worktree-isolation.ts and the agent worktrees under .claude/.
|
|
166
|
+
branch.startsWith('worktree-') ||
|
|
167
|
+
// scripts/preserve-worktree-work.ts, detached-HEAD naming scheme.
|
|
168
|
+
branch.startsWith('rungate-preserved/') ||
|
|
169
|
+
// Per-run scratch namespace, where rescued output is parked by hand.
|
|
170
|
+
branch.startsWith('run/') ||
|
|
171
|
+
// A rescue branch filed outside either namespace.
|
|
172
|
+
/(^|[-/])rescue$/.test(branch)
|
|
173
|
+
)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Commits each side has that the other does not, or nulls when unanswerable. */
|
|
177
|
+
interface Divergence {
|
|
178
|
+
ahead: number | null;
|
|
179
|
+
behind: number | null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* How far the candidate has moved from the base, in both directions, from one
|
|
184
|
+
* symmetric rev-list (#185).
|
|
185
|
+
*
|
|
186
|
+
* One call rather than two: a pair of separate counts can disagree about which
|
|
187
|
+
* merge base they were taken from if a ref moves between them, and two call
|
|
188
|
+
* sites are two places for the `null` contract to be forgotten.
|
|
189
|
+
*/
|
|
190
|
+
function divergenceFromBase(projectRoot: string, refName: string): Divergence {
|
|
191
|
+
const result = git(
|
|
192
|
+
['rev-list', '--count', '--left-right', `${BASE_BRANCH}...${refName}`],
|
|
193
|
+
projectRoot
|
|
194
|
+
)
|
|
195
|
+
// A rev-list that cannot run has not told us the branch is current, and it
|
|
196
|
+
// has not told us it is fully merged either.
|
|
197
|
+
if (result.status !== 0) return { ahead: null, behind: null }
|
|
198
|
+
|
|
199
|
+
const [left, right] = result.stdout.trim().split(/\s+/)
|
|
200
|
+
const behind = parseInt(left, 10)
|
|
201
|
+
const ahead = parseInt(right, 10)
|
|
202
|
+
return {
|
|
203
|
+
ahead: Number.isFinite(ahead) ? ahead : null,
|
|
204
|
+
behind: Number.isFinite(behind) ? behind : null,
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** A tree object id, as git prints it on the first line of merge-tree. */
|
|
209
|
+
const TREE_OID = /^[0-9a-f]{40}([0-9a-f]{24})?$/
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Whether the base already contains everything the candidate has (#185).
|
|
213
|
+
*
|
|
214
|
+
* `git merge-tree --write-tree` merges in memory and prints the resulting
|
|
215
|
+
* tree. If that tree is the base's own tree, the merge would change nothing,
|
|
216
|
+
* which is what "already merged" means however the work landed — including a
|
|
217
|
+
* squash merge, where no commit on either side shares a patch-id with the
|
|
218
|
+
* other. The base is free to have moved on since; only the MERGE adding
|
|
219
|
+
* nothing is read, never the two trees happening to be equal.
|
|
220
|
+
*
|
|
221
|
+
* Exit codes: 0 clean, 1 either a conflict (a real tree is printed, and a
|
|
222
|
+
* candidate that conflicts is certainly not contained) or an unusable ref (no
|
|
223
|
+
* tree is printed). The first line tells the two apart, so an error is never
|
|
224
|
+
* reported as an answer.
|
|
225
|
+
*/
|
|
226
|
+
export function mergedIntoBase(projectRoot: string, refName: string): boolean | null {
|
|
227
|
+
const baseTree = git(['rev-parse', `${BASE_BRANCH}^{tree}`], projectRoot)
|
|
228
|
+
if (baseTree.status !== 0) return null
|
|
229
|
+
|
|
230
|
+
const merged = git(['merge-tree', '--write-tree', BASE_BRANCH, refName], projectRoot, 30_000)
|
|
231
|
+
if (merged.status !== 0 && merged.status !== 1) return null
|
|
232
|
+
|
|
233
|
+
const tree = merged.stdout.split('\n')[0].trim()
|
|
234
|
+
if (!TREE_OID.test(tree)) return null
|
|
235
|
+
return tree === baseTree.stdout.trim()
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
interface RefCandidate {
|
|
239
|
+
branch: string;
|
|
240
|
+
refName: string;
|
|
241
|
+
ts: number;
|
|
242
|
+
local: boolean;
|
|
243
|
+
/** The tip commit's subject line, or '' when git did not print one. */
|
|
244
|
+
subject: string;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Field separator for for-each-ref. A tab cannot appear in a refname and
|
|
249
|
+
* cannot appear in a unix timestamp, so the first two fields are unambiguous
|
|
250
|
+
* however the third is punctuated — which matters, because the third is a
|
|
251
|
+
* commit subject written by whoever made the commit.
|
|
252
|
+
*/
|
|
253
|
+
const REF_FIELD_SEP = '\t'
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Every local or origin branch, as a bare name paired with a ref that
|
|
257
|
+
* resolves. Returns [] when git cannot be asked at all.
|
|
258
|
+
*/
|
|
259
|
+
function listCandidateRefs(projectRoot: string): RefCandidate[] {
|
|
260
|
+
const result = git(
|
|
261
|
+
[
|
|
262
|
+
'for-each-ref',
|
|
263
|
+
`--format=%(refname)${REF_FIELD_SEP}%(committerdate:unix)${REF_FIELD_SEP}%(contents:subject)`,
|
|
264
|
+
...CANDIDATE_REF_NAMESPACES,
|
|
265
|
+
],
|
|
266
|
+
projectRoot
|
|
267
|
+
)
|
|
268
|
+
if (result.status !== 0) return []
|
|
269
|
+
|
|
270
|
+
// Local heads win over the origin copy of the same name: both resolve, but
|
|
271
|
+
// the local one is what a worktree can check out without detaching.
|
|
272
|
+
const byName = new Map<string, RefCandidate>()
|
|
273
|
+
for (const line of result.stdout.split('\n')) {
|
|
274
|
+
const [refName, rawTs, ...rest] = line.split(REF_FIELD_SEP)
|
|
275
|
+
if (!refName || rawTs === undefined) continue
|
|
276
|
+
const ts = parseInt(rawTs, 10)
|
|
277
|
+
// Rejoined rather than taken as rest[0]: a subject containing a tab is
|
|
278
|
+
// one field that happens to have punctuation in it, not two fields.
|
|
279
|
+
const subject = rest.join(REF_FIELD_SEP)
|
|
280
|
+
|
|
281
|
+
const namespace = CANDIDATE_REF_NAMESPACES.find(ns => refName.startsWith(`${ns}/`))
|
|
282
|
+
if (!namespace) continue
|
|
283
|
+
const branch = refName.slice(namespace.length + 1)
|
|
284
|
+
|
|
285
|
+
// `refs/remotes/origin/HEAD` is a symref to the default branch, not work.
|
|
286
|
+
if (!branch || branch === 'HEAD' || branch === 'main' || branch === 'master') continue
|
|
287
|
+
if (isHarnessScratchRef(branch)) continue
|
|
288
|
+
|
|
289
|
+
const candidate: RefCandidate = {
|
|
290
|
+
branch,
|
|
291
|
+
refName,
|
|
292
|
+
ts: Number.isFinite(ts) ? ts : 0,
|
|
293
|
+
local: namespace === 'refs/heads',
|
|
294
|
+
subject,
|
|
295
|
+
}
|
|
296
|
+
const existing = byName.get(branch)
|
|
297
|
+
if (!existing || (candidate.local && !existing.local)) byName.set(branch, candidate)
|
|
298
|
+
}
|
|
299
|
+
return [...byName.values()]
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export async function detectPriorBranch(opts: DetectOptions): Promise<PriorBranch | null> {
|
|
303
|
+
const { issueNumber, projectRoot, runTests = true } = opts
|
|
304
|
+
|
|
305
|
+
// A branch name is one of two places the issue number is written, and it is
|
|
306
|
+
// the one a run does not control (#223). ship.js commits
|
|
307
|
+
// `fix(#${ISSUE}): ${title}`, so the subject carries the number even when
|
|
308
|
+
// the name does not — which is how a branch called `fix/strict-matchers`
|
|
309
|
+
// becomes findable. Scratch refs are still excluded upstream by
|
|
310
|
+
// `isHarnessScratchRef`: a subject match widens which REAL branches are
|
|
311
|
+
// found, it does not readmit the ones #185 ruled out.
|
|
312
|
+
const refs = issueReference(issueNumber)
|
|
313
|
+
const matches = listCandidateRefs(projectRoot)
|
|
314
|
+
.filter(c => refs(c.branch) || refs(c.subject))
|
|
315
|
+
if (matches.length === 0) return null
|
|
316
|
+
|
|
317
|
+
// Most recent wins; a local head breaks a tie with its origin twin.
|
|
318
|
+
const selected = matches.reduce((best, c) =>
|
|
319
|
+
c.ts > best.ts || (c.ts === best.ts && c.local && !best.local) ? c : best
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
// Both directions, from one reading. Ahead alone cannot distinguish a branch
|
|
323
|
+
// sitting on the tip from one 8 commits behind it (#185).
|
|
324
|
+
const { ahead: commitCount, behind: behindCount } = divergenceFromBase(projectRoot, selected.refName)
|
|
325
|
+
const isBehind = behindCount === null ? null : behindCount > 0
|
|
326
|
+
const isMerged = mergedIntoBase(projectRoot, selected.refName)
|
|
327
|
+
|
|
328
|
+
let testsPass = false
|
|
329
|
+
if (runTests) {
|
|
330
|
+
const tmpDir = `/tmp/rungate-prior-test-${issueNumber}-${Date.now()}`
|
|
331
|
+
const add = git(['worktree', 'add', '--detach', tmpDir, selected.refName], projectRoot, 30_000)
|
|
332
|
+
if (add.status === 0) {
|
|
333
|
+
try {
|
|
334
|
+
const testResult = spawnSync('bun', ['test'], {
|
|
335
|
+
cwd: tmpDir, encoding: 'utf-8', timeout: 300_000,
|
|
336
|
+
})
|
|
337
|
+
testsPass = testResult.status === 0
|
|
338
|
+
} finally {
|
|
339
|
+
git(['worktree', 'remove', tmpDir, '--force'], projectRoot, 30_000)
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
return {
|
|
345
|
+
branch: selected.branch,
|
|
346
|
+
refName: selected.refName,
|
|
347
|
+
commitCount,
|
|
348
|
+
behindCount,
|
|
349
|
+
isBehind,
|
|
350
|
+
isMerged,
|
|
351
|
+
testsPass,
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// ── detectExistingPR ────────────────────────────────────────
|
|
356
|
+
|
|
357
|
+
export interface DetectExistingPROctokitOptions {
|
|
358
|
+
issueNumber: number;
|
|
359
|
+
repo: string;
|
|
360
|
+
client?: GitHubClient;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* How many open PRs are read. The repo's own backlog has sat above 30, and
|
|
365
|
+
* the duplicate this exists to prevent is likeliest exactly when several runs
|
|
366
|
+
* are in flight — so a window of 10 would be narrowest at the moment it has
|
|
367
|
+
* to be widest.
|
|
368
|
+
*/
|
|
369
|
+
const PR_PAGE_SIZE = 100
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Find an open PR for the given issue number (#223).
|
|
373
|
+
*
|
|
374
|
+
* Reads the head ref, the title AND the body, because the harness's own
|
|
375
|
+
* branches are named `worktree-wf_5e3ed885-98c-9` and carry the issue number
|
|
376
|
+
* in none of them — only `Fixes #209`, which ship.js writes into the body,
|
|
377
|
+
* says which issue the PR is for. A head-ref-only reading could not match the
|
|
378
|
+
* PRs this workflow opens.
|
|
379
|
+
*
|
|
380
|
+
* Returns `null` for "no open PR", a PR for "this one", and `{unreadable}`
|
|
381
|
+
* for "could not look". Never conflate the first and the last.
|
|
382
|
+
*/
|
|
383
|
+
export async function detectExistingPR(opts: DetectExistingPROptions | DetectExistingPROctokitOptions): Promise<ExistingPR | null> {
|
|
384
|
+
const { issueNumber, repo } = opts
|
|
385
|
+
|
|
386
|
+
let prs: unknown
|
|
387
|
+
try {
|
|
388
|
+
const client = ('client' in opts && opts.client) ? opts.client : createGitHubClient();
|
|
389
|
+
prs = await listPRs(client, repo, { state: 'open', per_page: PR_PAGE_SIZE });
|
|
390
|
+
} catch (err) {
|
|
391
|
+
return { unreadable: true, reason: err instanceof Error ? err.message : String(err) }
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
if (!Array.isArray(prs)) {
|
|
395
|
+
return { unreadable: true, reason: `the PR listing was ${typeof prs}, not an array` }
|
|
396
|
+
}
|
|
397
|
+
if (prs.length === 0) return null
|
|
398
|
+
|
|
399
|
+
// What the PR SAYS it is for. `pr.number` is deliberately not consulted:
|
|
400
|
+
// matching it made PR #209 the prior work for issue #209 whatever it was
|
|
401
|
+
// about, which is a false positive on the one path where a false positive
|
|
402
|
+
// stops a correct run from ever starting.
|
|
403
|
+
const refs = issueReference(issueNumber)
|
|
404
|
+
const match = prs.find((pr: any) => {
|
|
405
|
+
const headRef = pr?.head?.ref || pr?.headRefName || ''
|
|
406
|
+
return refs(headRef) || refs(pr?.title) || refs(pr?.body)
|
|
407
|
+
})
|
|
408
|
+
|
|
409
|
+
if (!match) return null
|
|
410
|
+
|
|
411
|
+
return {
|
|
412
|
+
prNumber: (match as any).number,
|
|
413
|
+
branch: (match as any).head?.ref || (match as any).headRefName || '',
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// ── priorWorkRefusal ────────────────────────────────────────
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Whether this run may implement issue N, given what it found (#223).
|
|
421
|
+
*
|
|
422
|
+
* Returns the reason to refuse, or `null` to proceed.
|
|
423
|
+
*
|
|
424
|
+
* ## What this does NOT refuse, and why
|
|
425
|
+
*
|
|
426
|
+
* An unmerged prior branch on its own is not a reason to stop. That is
|
|
427
|
+
* RESUME, and it already works: ship.js merges the prior ref into the
|
|
428
|
+
* worktree and pushes back onto the same branch. Refusing there would break
|
|
429
|
+
* the only mechanism that makes a second run cheap.
|
|
430
|
+
*
|
|
431
|
+
* The defect is narrower. Issue #209 was shipped twice because run 2 found
|
|
432
|
+
* NOTHING — the open PR's head was `worktree-wf_5e3ed885-98c-9`, excluded
|
|
433
|
+
* from branch detection as harness scratch (#185) and unmatchable by name
|
|
434
|
+
* anyway — so it branched from main and re-implemented. 45 minutes, 20
|
|
435
|
+
* agents, 911k tokens, and two divergent PRs where merging either silently
|
|
436
|
+
* discards the other's work.
|
|
437
|
+
*
|
|
438
|
+
* So the condition is "an open PR exists for this issue that this run is not
|
|
439
|
+
* working on": either no prior branch was picked up at all, or one was and it
|
|
440
|
+
* is not the PR's head. When they match, this run IS that PR's next commit
|
|
441
|
+
* and there is nothing to collide with.
|
|
442
|
+
*/
|
|
443
|
+
export function priorWorkRefusal(
|
|
444
|
+
issueNumber: number,
|
|
445
|
+
priorBranch: unknown,
|
|
446
|
+
existingPR: unknown,
|
|
447
|
+
): string | null {
|
|
448
|
+
if (!existingPR || typeof existingPR !== 'object') return null
|
|
449
|
+
const pr = existingPR as ExistingPR
|
|
450
|
+
|
|
451
|
+
if (pr.unreadable) {
|
|
452
|
+
return (
|
|
453
|
+
`Could not determine whether issue #${issueNumber} already has an open PR: ` +
|
|
454
|
+
`${pr.reason || 'the lookup failed with no detail'}. Refusing rather than ` +
|
|
455
|
+
`re-implementing: "no PR" and "could not look" are different facts, and ` +
|
|
456
|
+
`acting on the wrong one is how #209 was shipped twice.`
|
|
457
|
+
)
|
|
458
|
+
}
|
|
459
|
+
// A record that is neither `unreadable` nor a PR is a malformed reading,
|
|
460
|
+
// and a malformed reading is not "no PR" — `null` is how that is said. The
|
|
461
|
+
// only outcome left is the one this whole function exists to prevent, so
|
|
462
|
+
// the direction to be wrong in here is toward refusing.
|
|
463
|
+
if (typeof pr.prNumber !== 'number' || !Number.isFinite(pr.prNumber)) {
|
|
464
|
+
return (
|
|
465
|
+
`The existing-PR lookup for issue #${issueNumber} returned a record with ` +
|
|
466
|
+
`no PR number: ${JSON.stringify(existingPR)}. Refusing rather than ` +
|
|
467
|
+
`reading a malformed answer as "no open PR" — pass null for that.`
|
|
468
|
+
)
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
const prBranch = typeof pr.branch === 'string' ? pr.branch : ''
|
|
472
|
+
const working =
|
|
473
|
+
priorBranch && typeof priorBranch === 'object'
|
|
474
|
+
? (priorBranch as PriorBranch).branch
|
|
475
|
+
: ''
|
|
476
|
+
|
|
477
|
+
// This run is already standing on the PR's head, so its commit lands there.
|
|
478
|
+
if (working && prBranch && working === prBranch) return null
|
|
479
|
+
|
|
480
|
+
const where = working
|
|
481
|
+
? `this run picked up the branch "${working}" instead`
|
|
482
|
+
: `this run found no prior branch and would start from the base branch`
|
|
483
|
+
return (
|
|
484
|
+
`Issue #${issueNumber} already has open PR #${pr.prNumber} on branch ` +
|
|
485
|
+
`"${prBranch || '(unnamed)'}", and ${where}. Implementing now would open a ` +
|
|
486
|
+
`second PR for one issue, and merging either would silently discard the ` +
|
|
487
|
+
`other's work. Resume that branch or close that PR, then re-run.`
|
|
488
|
+
)
|
|
489
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Does `project-state.json` have the shape the renderer will read?
|
|
3
|
+
*
|
|
4
|
+
* Found by writing a malformed entry by hand. `scripts/update-project-state.ts`
|
|
5
|
+
* declares `interface Session { date: string; items: string[] }`, and that
|
|
6
|
+
* interface is erased at runtime: the file is `JSON.parse`d into it and
|
|
7
|
+
* nothing checks. An archived session carrying `summary` instead of `items`
|
|
8
|
+
* produced
|
|
9
|
+
*
|
|
10
|
+
* TypeError: undefined is not an object (evaluating 'session.items.forEach')
|
|
11
|
+
* at render (scripts/update-project-state.ts:134:15)
|
|
12
|
+
*
|
|
13
|
+
* and nothing else — no path, no index, no statement of what the file should
|
|
14
|
+
* have contained. The renderer runs from a pre-commit hook, where a stack
|
|
15
|
+
* trace with a line number into a script the committer did not open is close
|
|
16
|
+
* to no message at all.
|
|
17
|
+
*
|
|
18
|
+
* This is the mirror of the defect class the rest of this repo keeps finding.
|
|
19
|
+
* A fail-open reports success it did not earn; this reports a failure nobody
|
|
20
|
+
* can act on. Both end with a reader who cannot tell what happened, and the
|
|
21
|
+
* second is the one that trains people to re-run the command and hope.
|
|
22
|
+
*
|
|
23
|
+
* So: every problem at once, each naming the path into the document and what
|
|
24
|
+
* was there instead. Not the first one and then a crash — a writer fixing a
|
|
25
|
+
* hand-edited file wants the whole list, and a validator that stops at the
|
|
26
|
+
* first finding turns one bad edit into four round-trips.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/** Every shape violation in a parsed `project-state.json`, in document order. */
|
|
30
|
+
export function projectStateViolations(raw: unknown): string[] {
|
|
31
|
+
const out: string[] = [];
|
|
32
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
|
|
33
|
+
return [`the document is ${Array.isArray(raw) ? "an array" : typeof raw}, not an object`];
|
|
34
|
+
}
|
|
35
|
+
const doc = raw as Record<string, unknown>;
|
|
36
|
+
|
|
37
|
+
for (const key of ["updated", "priorities", "phases", "sessions"]) {
|
|
38
|
+
if (!(key in doc)) out.push(`missing required key: ${key}`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if ("sessions" in doc) {
|
|
42
|
+
if (!Array.isArray(doc.sessions)) {
|
|
43
|
+
out.push(`sessions is ${typeof doc.sessions}, not an array`);
|
|
44
|
+
} else {
|
|
45
|
+
doc.sessions.forEach((s, i) => {
|
|
46
|
+
const at = `sessions[${i}]`;
|
|
47
|
+
if (s === null || typeof s !== "object" || Array.isArray(s)) {
|
|
48
|
+
out.push(`${at} is not an object`);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
const e = s as Record<string, unknown>;
|
|
52
|
+
if (typeof e.date !== "string" || e.date.length === 0) {
|
|
53
|
+
out.push(`${at}.date is ${JSON.stringify(e.date)}, expected a non-empty string`);
|
|
54
|
+
}
|
|
55
|
+
if (!Array.isArray(e.items)) {
|
|
56
|
+
// The exact edit that produced the crash, named rather than thrown.
|
|
57
|
+
const hint = typeof e.summary === "string"
|
|
58
|
+
? ` — it has a "summary" instead; archived sessions use "items": [...]`
|
|
59
|
+
: "";
|
|
60
|
+
out.push(`${at}.items is ${JSON.stringify(e.items)}, expected an array of strings${hint}`);
|
|
61
|
+
} else {
|
|
62
|
+
e.items.forEach((it, j) => {
|
|
63
|
+
if (typeof it !== "string") out.push(`${at}.items[${j}] is ${typeof it}, expected a string`);
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if ("phases" in doc) {
|
|
71
|
+
if (!Array.isArray(doc.phases)) {
|
|
72
|
+
out.push(`phases is ${typeof doc.phases}, not an array`);
|
|
73
|
+
} else {
|
|
74
|
+
doc.phases.forEach((p, i) => {
|
|
75
|
+
const at = `phases[${i}]`;
|
|
76
|
+
if (p === null || typeof p !== "object" || Array.isArray(p)) {
|
|
77
|
+
out.push(`${at} is not an object`);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const e = p as Record<string, unknown>;
|
|
81
|
+
if (typeof e.name !== "string") out.push(`${at}.name is ${JSON.stringify(e.name)}, expected a string`);
|
|
82
|
+
if (!Array.isArray(e.scs)) {
|
|
83
|
+
out.push(`${at}.scs is ${JSON.stringify(e.scs)}, expected an array`);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
// The elements, not only the array. Found by a security review of the
|
|
87
|
+
// first commit: checking that `scs` is an array leaves
|
|
88
|
+
// `sc.id.toUpperCase()` and `sc.done` to crash on `[null]` or `[{}]`,
|
|
89
|
+
// which is the same unreadable TypeError this whole module replaces,
|
|
90
|
+
// one level deeper. A validator that stops at the container is a
|
|
91
|
+
// validator that moves the crash rather than removing it.
|
|
92
|
+
e.scs.forEach((sc, j) => {
|
|
93
|
+
const scAt = `${at}.scs[${j}]`;
|
|
94
|
+
if (sc === null || typeof sc !== "object" || Array.isArray(sc)) {
|
|
95
|
+
out.push(`${scAt} is not an object`);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const s = sc as Record<string, unknown>;
|
|
99
|
+
if (typeof s.id !== "string") out.push(`${scAt}.id is ${JSON.stringify(s.id)}, expected a string`);
|
|
100
|
+
if (typeof s.done !== "boolean") out.push(`${scAt}.done is ${JSON.stringify(s.done)}, expected a boolean`);
|
|
101
|
+
if (typeof s.what !== "string") out.push(`${scAt}.what is ${JSON.stringify(s.what)}, expected a string`);
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if ("priorities" in doc && Array.isArray(doc.priorities)) {
|
|
108
|
+
doc.priorities.forEach((p, i) => {
|
|
109
|
+
if (typeof p !== "string") out.push(`priorities[${i}] is ${typeof p}, expected a string`);
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// `session` is optional — the renderer guards it with `if (state.session)`
|
|
114
|
+
// — but a present one is dereferenced four fields deep without a guard,
|
|
115
|
+
// and a half-written session renders "Session undefined (undefined)".
|
|
116
|
+
if ("session" in doc && doc.session !== undefined && doc.session !== null) {
|
|
117
|
+
const s = doc.session;
|
|
118
|
+
if (typeof s !== "object" || Array.isArray(s)) {
|
|
119
|
+
out.push(`session is ${Array.isArray(s) ? "an array" : typeof s}, expected an object`);
|
|
120
|
+
} else {
|
|
121
|
+
const e = s as Record<string, unknown>;
|
|
122
|
+
if (typeof e.number !== "number") out.push(`session.number is ${JSON.stringify(e.number)}, expected a number`);
|
|
123
|
+
for (const k of ["date", "summary", "suite"]) {
|
|
124
|
+
if (typeof e[k] !== "string") out.push(`session.${k} is ${JSON.stringify(e[k])}, expected a string`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if ("priorities" in doc && !Array.isArray(doc.priorities)) {
|
|
130
|
+
out.push(`priorities is ${typeof doc.priorities}, not an array`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* A project with no `project-state.json` is not the same as a project that
|
|
138
|
+
* lost one.
|
|
139
|
+
*
|
|
140
|
+
* The script exited 0 with "project-state.json not found, skipping" for
|
|
141
|
+
* both. For a consumer project that does not use the feature that is right.
|
|
142
|
+
* For this repo — where the pre-commit hook renders the artifact every
|
|
143
|
+
* commit and `AGENTS.md` tells the next session to read it first — a missing
|
|
144
|
+
* source means the hook quietly stopped maintaining a file people are
|
|
145
|
+
* instructed to trust, and said "skipping" while doing it.
|
|
146
|
+
*
|
|
147
|
+
* The tell is the output: if `PROJECT-STATE.md` is there and its source is
|
|
148
|
+
* not, this project HAS the artifact and has lost the thing that writes it.
|
|
149
|
+
* Same distinction the spec-compliance probe draws between "no suite here"
|
|
150
|
+
* and "half a suite".
|
|
151
|
+
*/
|
|
152
|
+
export function missingStateVerdict(opts: {
|
|
153
|
+
jsonExists: boolean;
|
|
154
|
+
markdownExists: boolean;
|
|
155
|
+
}): { verdict: "OK" | "SKIP" | "REFUSE"; detail: string } {
|
|
156
|
+
if (opts.jsonExists) return { verdict: "OK", detail: "" };
|
|
157
|
+
if (opts.markdownExists) {
|
|
158
|
+
return {
|
|
159
|
+
verdict: "REFUSE",
|
|
160
|
+
detail:
|
|
161
|
+
"PROJECT-STATE.md exists but project-state.json does not — the rendered artifact has " +
|
|
162
|
+
"outlived its source, so it is now a file nobody maintains that the next session is told to trust",
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
return { verdict: "SKIP", detail: "project-state.json not found and no PROJECT-STATE.md to maintain — nothing to do" };
|
|
166
|
+
}
|