rungate 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/bin/rungate.ts +70 -0
  2. package/lib/aes-calculator.ts +66 -0
  3. package/lib/agent-audit.ts +139 -0
  4. package/lib/agent-brief-validation.ts +359 -0
  5. package/lib/agents-md-refs.ts +90 -0
  6. package/lib/bash-file-read.ts +197 -0
  7. package/lib/behavioral-cache.ts +78 -0
  8. package/lib/branch-cleanup.ts +234 -0
  9. package/lib/brief-context-parser.ts +35 -0
  10. package/lib/brief-precedence.ts +114 -0
  11. package/lib/canary.ts +117 -0
  12. package/lib/check-registry.ts +226 -0
  13. package/lib/ci-checkout.ts +426 -0
  14. package/lib/cli-commands.ts +137 -0
  15. package/lib/compliance-backfill.ts +232 -0
  16. package/lib/compliance-report.ts +605 -0
  17. package/lib/compliance.ts +361 -0
  18. package/lib/config-loader.ts +255 -0
  19. package/lib/config-readers.ts +86 -0
  20. package/lib/conformity.ts +2161 -137
  21. package/lib/container-provenance.ts +230 -0
  22. package/lib/create-brief.ts +150 -0
  23. package/lib/create-sc.ts +267 -0
  24. package/lib/decomposition-waves.ts +197 -0
  25. package/lib/deep-merge.ts +69 -0
  26. package/lib/dev-liveness.ts +214 -0
  27. package/lib/directive-extractor.ts +210 -0
  28. package/lib/distribution-standing.ts +113 -0
  29. package/lib/doc-hygiene.ts +238 -0
  30. package/lib/eval-criteria.ts +6 -0
  31. package/lib/evidence-portability.ts +123 -0
  32. package/lib/evidence-prevalidator.ts +390 -0
  33. package/lib/evidence-required.ts +150 -0
  34. package/lib/evidence-satisfiability.ts +288 -0
  35. package/lib/frontmatter.ts +163 -0
  36. package/lib/gap-scanner.ts +348 -0
  37. package/lib/gate-check-audit.ts +190 -0
  38. package/lib/gate-enforcement.ts +366 -0
  39. package/lib/generators/agent-briefs.ts +136 -0
  40. package/lib/generators/agents-md.ts +511 -0
  41. package/lib/generators/code-map.ts +60 -0
  42. package/lib/generators/types.ts +184 -0
  43. package/lib/git-ref-normalizer.ts +107 -0
  44. package/lib/github.ts +539 -0
  45. package/lib/harness-identity.ts +63 -0
  46. package/lib/hill-climb.ts +164 -0
  47. package/lib/instruction-effectiveness.ts +131 -0
  48. package/lib/issue-closure-audit.ts +225 -0
  49. package/lib/issue-create-override.ts +343 -0
  50. package/lib/issue-extraction.ts +368 -0
  51. package/lib/js-top-level-code.ts +250 -0
  52. package/lib/liveness-contradiction.ts +149 -0
  53. package/lib/organize.ts +505 -0
  54. package/lib/paths.ts +197 -6
  55. package/lib/phase2-decomposition.ts +270 -0
  56. package/lib/post-fix-verify.ts +157 -0
  57. package/lib/prior-branch.ts +512 -0
  58. package/lib/project-state-shape.ts +166 -0
  59. package/lib/promote-outputs.ts +156 -0
  60. package/lib/prove-label-gate.ts +128 -0
  61. package/lib/reachability.ts +302 -0
  62. package/lib/release-preflight.ts +288 -0
  63. package/lib/rule-health-pipeline.ts +264 -0
  64. package/lib/rule-health-trend.ts +161 -0
  65. package/lib/rule-provenance.ts +149 -0
  66. package/lib/rule-registry.ts +128 -0
  67. package/lib/rungate-schema.ts +127 -5
  68. package/lib/sc-claim-forms.ts +179 -0
  69. package/lib/sc-cover.ts +150 -0
  70. package/lib/sc-guard.ts +157 -0
  71. package/lib/sc-ids.ts +344 -0
  72. package/lib/scaffold/defaults.ts +165 -0
  73. package/lib/scaffold/managed-workflow.ts +370 -0
  74. package/lib/scaffold/owned-files.ts +265 -0
  75. package/lib/scaffold/pre-push-hook.ts +165 -0
  76. package/lib/scaffold/steps.ts +2621 -0
  77. package/lib/scanner.ts +701 -0
  78. package/lib/scope-denylist.ts +258 -0
  79. package/lib/screenshot-upload.ts +73 -0
  80. package/lib/secret-patterns.ts +112 -0
  81. package/lib/security-verdict.ts +616 -0
  82. package/lib/signal-phrases.ts +1 -0
  83. package/lib/spec-change-conformity.ts +80 -0
  84. package/lib/spec-files.ts +62 -0
  85. package/lib/spec-registry.ts +133 -0
  86. package/lib/spec-updater.ts +96 -0
  87. package/lib/stale-cleanup.ts +224 -0
  88. package/lib/stale-issue-scanner.ts +36 -0
  89. package/lib/strip-js-comments.ts +269 -0
  90. package/lib/suite-measurement.ts +228 -0
  91. package/lib/task-completion-checks.ts +224 -0
  92. package/lib/test-suite-lock.ts +1136 -0
  93. package/lib/transcript-checker.ts +1140 -0
  94. package/lib/typescript-project.ts +233 -0
  95. package/lib/validators/spec-validators.ts +171 -0
  96. package/lib/verdict-capture.ts +73 -0
  97. package/lib/verified-push.ts +535 -0
  98. package/lib/workflow-security.ts +174 -0
  99. package/lib/worktree-cleanup.ts +432 -0
  100. package/lib/worktree-collect.ts +283 -0
  101. package/lib/worktree-isolation.ts +82 -0
  102. package/lib/worktree-repo.ts +300 -0
  103. package/package.json +27 -3
  104. package/prompts/ac-adversary.md +14 -2
  105. package/prompts/aditi.md +5 -0
  106. package/prompts/blast-radius.md +5 -0
  107. package/prompts/container-verify.md +5 -0
  108. package/prompts/discovery.md +4 -0
  109. package/prompts/environment.md +5 -0
  110. package/prompts/evidence-hierarchy.md +5 -0
  111. package/prompts/evidence-validator.md +11 -0
  112. package/prompts/marcus.md +5 -0
  113. package/prompts/prevention.md +5 -0
  114. package/prompts/prove-reproducer.md +12 -0
  115. package/prompts/quinn-decision-tree.md +5 -0
  116. package/prompts/quinn-ui-brief.md +5 -0
  117. package/prompts/quinn.md +5 -0
  118. package/prompts/rca.md +5 -0
  119. package/prompts/read-before-write.md +4 -0
  120. package/prompts/regression.md +5 -0
  121. package/prompts/serena.md +5 -0
  122. package/scripts/audit-specs.ts +464 -0
  123. package/scripts/convert-spec.ts +293 -0
  124. package/scripts/create-sc.ts +92 -0
  125. package/scripts/create-spec.ts +166 -0
  126. package/scripts/extract-constraints.ts +4 -3
  127. package/scripts/generate-code-map.ts +1 -1
  128. package/scripts/scaffold-project.ts +138 -1426
  129. package/scripts/sync-spec-tests.ts +211 -126
@@ -0,0 +1,512 @@
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
+ // The bound is on HEX digits and `_`, not on decimal digits alone (#433).
124
+ //
125
+ // `[^\d]` was right about the case it was written for — it stops `55`
126
+ // matching `550` — and wrong about the case this repo actually generates.
127
+ // Workflow fan-out branches are named `worktree-wf_<runid>-<n>` with a hex
128
+ // run id, and in `worktree-wf_55baa4aa-a00-9` the `55` is preceded by `_`
129
+ // and followed by `b`. Both are non-digits, so it matched, and
130
+ // `detectPriorBranch` reported a stranger's fan-out worktree as issue 55's
131
+ // prior work. There were 149 such branches here when this was found.
132
+ //
133
+ // The bound is `\b`, which is what "word-boundary matching" meant all
134
+ // along. A hand-rolled hex class was tried first and a mutation scored
135
+ // ZERO against widening it to all letters — the fixtures could not tell
136
+ // the two apart, because every real form separates the number with
137
+ // punctuation. The zero was the finding: the narrower class was buying
138
+ // nothing over the broader one, and `\b` IS the broader one, already
139
+ // treating `_` and every letter as a word character.
140
+ //
141
+ // `\b55\b` rejects `worktree-wf_55baa4aa-a00-9` (`_` and `b` are word
142
+ // characters, so neither side is a boundary) and `550-matcher-registry`
143
+ // (`0` likewise), and accepts `209-deep-modules`, `fix/55`, `Closes #209`
144
+ // and `fix(#209):`. All of them are asserted in
145
+ // test/prior-branch-reference.test.ts rather than trusted to this comment.
146
+ const pattern = new RegExp(`\\b${issueNumber}\\b`)
147
+ return (text: unknown) => typeof text === 'string' && pattern.test(text)
148
+ }
149
+
150
+ function git(args: string[], cwd: string, timeout = 15_000) {
151
+ return spawnSync('git', args, { cwd, encoding: 'utf-8', timeout })
152
+ }
153
+
154
+ /**
155
+ * The only ref namespaces a prior branch may come from (#164).
156
+ *
157
+ * `git branch -a --list` enumerates EVERY configured remote and the old code
158
+ * then stripped `remotes/<anything>/` off the result, so a sibling project
159
+ * added as a second remote donated its branch names to this repo's issues.
160
+ * for-each-ref over an explicit namespace list cannot do that: a ref outside
161
+ * these two is never returned in the first place.
162
+ */
163
+ const CANDIDATE_REF_NAMESPACES = [
164
+ 'refs/heads',
165
+ 'refs/remotes/origin',
166
+ ] as const
167
+
168
+ /** The base the prior branch's commits are counted against. */
169
+ const BASE_BRANCH = 'main'
170
+
171
+ /**
172
+ * Refs the harness creates for its own bookkeeping (#185).
173
+ *
174
+ * None of these is a resumable implementation, and two of them are the
175
+ * opposite: `scripts/preserve-worktree-work.ts` exists to name work a run
176
+ * REFUSED to collect, so that it survives `git worktree remove --force`. The
177
+ * branch this repository carries for issue 254 says it in its own tip message
178
+ * — "rescued output of run wf_19f7def7-1bf — NOT reviewed, do not merge" — and
179
+ * detection nominated it anyway, because the only thing it read was whether
180
+ * the digits 254 appeared in the name.
181
+ *
182
+ * Matched on the namespace rather than on the message, because the names are
183
+ * assigned by the harness and the messages are written by whoever rescued the
184
+ * work.
185
+ */
186
+ export function isHarnessScratchRef(branch: string): boolean {
187
+ return (
188
+ // lib/worktree-isolation.ts and the agent worktrees under .claude/.
189
+ branch.startsWith('worktree-') ||
190
+ // scripts/preserve-worktree-work.ts, detached-HEAD naming scheme.
191
+ branch.startsWith('rungate-preserved/') ||
192
+ // Per-run scratch namespace, where rescued output is parked by hand.
193
+ branch.startsWith('run/') ||
194
+ // A rescue branch filed outside either namespace.
195
+ /(^|[-/])rescue$/.test(branch)
196
+ )
197
+ }
198
+
199
+ /** Commits each side has that the other does not, or nulls when unanswerable. */
200
+ interface Divergence {
201
+ ahead: number | null;
202
+ behind: number | null;
203
+ }
204
+
205
+ /**
206
+ * How far the candidate has moved from the base, in both directions, from one
207
+ * symmetric rev-list (#185).
208
+ *
209
+ * One call rather than two: a pair of separate counts can disagree about which
210
+ * merge base they were taken from if a ref moves between them, and two call
211
+ * sites are two places for the `null` contract to be forgotten.
212
+ */
213
+ function divergenceFromBase(projectRoot: string, refName: string): Divergence {
214
+ const result = git(
215
+ ['rev-list', '--count', '--left-right', `${BASE_BRANCH}...${refName}`],
216
+ projectRoot
217
+ )
218
+ // A rev-list that cannot run has not told us the branch is current, and it
219
+ // has not told us it is fully merged either.
220
+ if (result.status !== 0) return { ahead: null, behind: null }
221
+
222
+ const [left, right] = result.stdout.trim().split(/\s+/)
223
+ const behind = parseInt(left, 10)
224
+ const ahead = parseInt(right, 10)
225
+ return {
226
+ ahead: Number.isFinite(ahead) ? ahead : null,
227
+ behind: Number.isFinite(behind) ? behind : null,
228
+ }
229
+ }
230
+
231
+ /** A tree object id, as git prints it on the first line of merge-tree. */
232
+ const TREE_OID = /^[0-9a-f]{40}([0-9a-f]{24})?$/
233
+
234
+ /**
235
+ * Whether the base already contains everything the candidate has (#185).
236
+ *
237
+ * `git merge-tree --write-tree` merges in memory and prints the resulting
238
+ * tree. If that tree is the base's own tree, the merge would change nothing,
239
+ * which is what "already merged" means however the work landed — including a
240
+ * squash merge, where no commit on either side shares a patch-id with the
241
+ * other. The base is free to have moved on since; only the MERGE adding
242
+ * nothing is read, never the two trees happening to be equal.
243
+ *
244
+ * Exit codes: 0 clean, 1 either a conflict (a real tree is printed, and a
245
+ * candidate that conflicts is certainly not contained) or an unusable ref (no
246
+ * tree is printed). The first line tells the two apart, so an error is never
247
+ * reported as an answer.
248
+ */
249
+ export function mergedIntoBase(projectRoot: string, refName: string): boolean | null {
250
+ const baseTree = git(['rev-parse', `${BASE_BRANCH}^{tree}`], projectRoot)
251
+ if (baseTree.status !== 0) return null
252
+
253
+ const merged = git(['merge-tree', '--write-tree', BASE_BRANCH, refName], projectRoot, 30_000)
254
+ if (merged.status !== 0 && merged.status !== 1) return null
255
+
256
+ const tree = merged.stdout.split('\n')[0].trim()
257
+ if (!TREE_OID.test(tree)) return null
258
+ return tree === baseTree.stdout.trim()
259
+ }
260
+
261
+ interface RefCandidate {
262
+ branch: string;
263
+ refName: string;
264
+ ts: number;
265
+ local: boolean;
266
+ /** The tip commit's subject line, or '' when git did not print one. */
267
+ subject: string;
268
+ }
269
+
270
+ /**
271
+ * Field separator for for-each-ref. A tab cannot appear in a refname and
272
+ * cannot appear in a unix timestamp, so the first two fields are unambiguous
273
+ * however the third is punctuated — which matters, because the third is a
274
+ * commit subject written by whoever made the commit.
275
+ */
276
+ const REF_FIELD_SEP = '\t'
277
+
278
+ /**
279
+ * Every local or origin branch, as a bare name paired with a ref that
280
+ * resolves. Returns [] when git cannot be asked at all.
281
+ */
282
+ function listCandidateRefs(projectRoot: string): RefCandidate[] {
283
+ const result = git(
284
+ [
285
+ 'for-each-ref',
286
+ `--format=%(refname)${REF_FIELD_SEP}%(committerdate:unix)${REF_FIELD_SEP}%(contents:subject)`,
287
+ ...CANDIDATE_REF_NAMESPACES,
288
+ ],
289
+ projectRoot
290
+ )
291
+ if (result.status !== 0) return []
292
+
293
+ // Local heads win over the origin copy of the same name: both resolve, but
294
+ // the local one is what a worktree can check out without detaching.
295
+ const byName = new Map<string, RefCandidate>()
296
+ for (const line of result.stdout.split('\n')) {
297
+ const [refName, rawTs, ...rest] = line.split(REF_FIELD_SEP)
298
+ if (!refName || rawTs === undefined) continue
299
+ const ts = parseInt(rawTs, 10)
300
+ // Rejoined rather than taken as rest[0]: a subject containing a tab is
301
+ // one field that happens to have punctuation in it, not two fields.
302
+ const subject = rest.join(REF_FIELD_SEP)
303
+
304
+ const namespace = CANDIDATE_REF_NAMESPACES.find(ns => refName.startsWith(`${ns}/`))
305
+ if (!namespace) continue
306
+ const branch = refName.slice(namespace.length + 1)
307
+
308
+ // `refs/remotes/origin/HEAD` is a symref to the default branch, not work.
309
+ if (!branch || branch === 'HEAD' || branch === 'main' || branch === 'master') continue
310
+ if (isHarnessScratchRef(branch)) continue
311
+
312
+ const candidate: RefCandidate = {
313
+ branch,
314
+ refName,
315
+ ts: Number.isFinite(ts) ? ts : 0,
316
+ local: namespace === 'refs/heads',
317
+ subject,
318
+ }
319
+ const existing = byName.get(branch)
320
+ if (!existing || (candidate.local && !existing.local)) byName.set(branch, candidate)
321
+ }
322
+ return [...byName.values()]
323
+ }
324
+
325
+ export async function detectPriorBranch(opts: DetectOptions): Promise<PriorBranch | null> {
326
+ const { issueNumber, projectRoot, runTests = true } = opts
327
+
328
+ // A branch name is one of two places the issue number is written, and it is
329
+ // the one a run does not control (#223). ship.js commits
330
+ // `fix(#${ISSUE}): ${title}`, so the subject carries the number even when
331
+ // the name does not — which is how a branch called `fix/strict-matchers`
332
+ // becomes findable. Scratch refs are still excluded upstream by
333
+ // `isHarnessScratchRef`: a subject match widens which REAL branches are
334
+ // found, it does not readmit the ones #185 ruled out.
335
+ const refs = issueReference(issueNumber)
336
+ const matches = listCandidateRefs(projectRoot)
337
+ .filter(c => refs(c.branch) || refs(c.subject))
338
+ if (matches.length === 0) return null
339
+
340
+ // Most recent wins; a local head breaks a tie with its origin twin.
341
+ const selected = matches.reduce((best, c) =>
342
+ c.ts > best.ts || (c.ts === best.ts && c.local && !best.local) ? c : best
343
+ )
344
+
345
+ // Both directions, from one reading. Ahead alone cannot distinguish a branch
346
+ // sitting on the tip from one 8 commits behind it (#185).
347
+ const { ahead: commitCount, behind: behindCount } = divergenceFromBase(projectRoot, selected.refName)
348
+ const isBehind = behindCount === null ? null : behindCount > 0
349
+ const isMerged = mergedIntoBase(projectRoot, selected.refName)
350
+
351
+ let testsPass = false
352
+ if (runTests) {
353
+ const tmpDir = `/tmp/rungate-prior-test-${issueNumber}-${Date.now()}`
354
+ const add = git(['worktree', 'add', '--detach', tmpDir, selected.refName], projectRoot, 30_000)
355
+ if (add.status === 0) {
356
+ try {
357
+ const testResult = spawnSync('bun', ['test'], {
358
+ cwd: tmpDir, encoding: 'utf-8', timeout: 300_000,
359
+ })
360
+ testsPass = testResult.status === 0
361
+ } finally {
362
+ git(['worktree', 'remove', tmpDir, '--force'], projectRoot, 30_000)
363
+ }
364
+ }
365
+ }
366
+
367
+ return {
368
+ branch: selected.branch,
369
+ refName: selected.refName,
370
+ commitCount,
371
+ behindCount,
372
+ isBehind,
373
+ isMerged,
374
+ testsPass,
375
+ }
376
+ }
377
+
378
+ // ── detectExistingPR ────────────────────────────────────────
379
+
380
+ export interface DetectExistingPROctokitOptions {
381
+ issueNumber: number;
382
+ repo: string;
383
+ client?: GitHubClient;
384
+ }
385
+
386
+ /**
387
+ * How many open PRs are read. The repo's own backlog has sat above 30, and
388
+ * the duplicate this exists to prevent is likeliest exactly when several runs
389
+ * are in flight — so a window of 10 would be narrowest at the moment it has
390
+ * to be widest.
391
+ */
392
+ const PR_PAGE_SIZE = 100
393
+
394
+ /**
395
+ * Find an open PR for the given issue number (#223).
396
+ *
397
+ * Reads the head ref, the title AND the body, because the harness's own
398
+ * branches are named `worktree-wf_5e3ed885-98c-9` and carry the issue number
399
+ * in none of them — only `Fixes #209`, which ship.js writes into the body,
400
+ * says which issue the PR is for. A head-ref-only reading could not match the
401
+ * PRs this workflow opens.
402
+ *
403
+ * Returns `null` for "no open PR", a PR for "this one", and `{unreadable}`
404
+ * for "could not look". Never conflate the first and the last.
405
+ */
406
+ export async function detectExistingPR(opts: DetectExistingPROptions | DetectExistingPROctokitOptions): Promise<ExistingPR | null> {
407
+ const { issueNumber, repo } = opts
408
+
409
+ let prs: unknown
410
+ try {
411
+ const client = ('client' in opts && opts.client) ? opts.client : createGitHubClient();
412
+ prs = await listPRs(client, repo, { state: 'open', per_page: PR_PAGE_SIZE });
413
+ } catch (err) {
414
+ return { unreadable: true, reason: err instanceof Error ? err.message : String(err) }
415
+ }
416
+
417
+ if (!Array.isArray(prs)) {
418
+ return { unreadable: true, reason: `the PR listing was ${typeof prs}, not an array` }
419
+ }
420
+ if (prs.length === 0) return null
421
+
422
+ // What the PR SAYS it is for. `pr.number` is deliberately not consulted:
423
+ // matching it made PR #209 the prior work for issue #209 whatever it was
424
+ // about, which is a false positive on the one path where a false positive
425
+ // stops a correct run from ever starting.
426
+ const refs = issueReference(issueNumber)
427
+ const match = prs.find((pr: any) => {
428
+ const headRef = pr?.head?.ref || pr?.headRefName || ''
429
+ return refs(headRef) || refs(pr?.title) || refs(pr?.body)
430
+ })
431
+
432
+ if (!match) return null
433
+
434
+ return {
435
+ prNumber: (match as any).number,
436
+ branch: (match as any).head?.ref || (match as any).headRefName || '',
437
+ }
438
+ }
439
+
440
+ // ── priorWorkRefusal ────────────────────────────────────────
441
+
442
+ /**
443
+ * Whether this run may implement issue N, given what it found (#223).
444
+ *
445
+ * Returns the reason to refuse, or `null` to proceed.
446
+ *
447
+ * ## What this does NOT refuse, and why
448
+ *
449
+ * An unmerged prior branch on its own is not a reason to stop. That is
450
+ * RESUME, and it already works: ship.js merges the prior ref into the
451
+ * worktree and pushes back onto the same branch. Refusing there would break
452
+ * the only mechanism that makes a second run cheap.
453
+ *
454
+ * The defect is narrower. Issue #209 was shipped twice because run 2 found
455
+ * NOTHING — the open PR's head was `worktree-wf_5e3ed885-98c-9`, excluded
456
+ * from branch detection as harness scratch (#185) and unmatchable by name
457
+ * anyway — so it branched from main and re-implemented. 45 minutes, 20
458
+ * agents, 911k tokens, and two divergent PRs where merging either silently
459
+ * discards the other's work.
460
+ *
461
+ * So the condition is "an open PR exists for this issue that this run is not
462
+ * working on": either no prior branch was picked up at all, or one was and it
463
+ * is not the PR's head. When they match, this run IS that PR's next commit
464
+ * and there is nothing to collide with.
465
+ */
466
+ export function priorWorkRefusal(
467
+ issueNumber: number,
468
+ priorBranch: unknown,
469
+ existingPR: unknown,
470
+ ): string | null {
471
+ if (!existingPR || typeof existingPR !== 'object') return null
472
+ const pr = existingPR as ExistingPR
473
+
474
+ if (pr.unreadable) {
475
+ return (
476
+ `Could not determine whether issue #${issueNumber} already has an open PR: ` +
477
+ `${pr.reason || 'the lookup failed with no detail'}. Refusing rather than ` +
478
+ `re-implementing: "no PR" and "could not look" are different facts, and ` +
479
+ `acting on the wrong one is how #209 was shipped twice.`
480
+ )
481
+ }
482
+ // A record that is neither `unreadable` nor a PR is a malformed reading,
483
+ // and a malformed reading is not "no PR" — `null` is how that is said. The
484
+ // only outcome left is the one this whole function exists to prevent, so
485
+ // the direction to be wrong in here is toward refusing.
486
+ if (typeof pr.prNumber !== 'number' || !Number.isFinite(pr.prNumber)) {
487
+ return (
488
+ `The existing-PR lookup for issue #${issueNumber} returned a record with ` +
489
+ `no PR number: ${JSON.stringify(existingPR)}. Refusing rather than ` +
490
+ `reading a malformed answer as "no open PR" — pass null for that.`
491
+ )
492
+ }
493
+
494
+ const prBranch = typeof pr.branch === 'string' ? pr.branch : ''
495
+ const working =
496
+ priorBranch && typeof priorBranch === 'object'
497
+ ? (priorBranch as PriorBranch).branch
498
+ : ''
499
+
500
+ // This run is already standing on the PR's head, so its commit lands there.
501
+ if (working && prBranch && working === prBranch) return null
502
+
503
+ const where = working
504
+ ? `this run picked up the branch "${working}" instead`
505
+ : `this run found no prior branch and would start from the base branch`
506
+ return (
507
+ `Issue #${issueNumber} already has open PR #${pr.prNumber} on branch ` +
508
+ `"${prBranch || '(unnamed)'}", and ${where}. Implementing now would open a ` +
509
+ `second PR for one issue, and merging either would silently discard the ` +
510
+ `other's work. Resume that branch or close that PR, then re-run.`
511
+ )
512
+ }
@@ -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
+ }