rungate 0.8.2 → 0.8.4

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 (74) hide show
  1. package/bin/rungate.ts +11 -6
  2. package/config/prove-evidence.schema.json +21 -3
  3. package/gates/.gate-salt +1 -1
  4. package/gates/gate-executor.ts +153 -1
  5. package/gates/prove.test.ts +12 -6
  6. package/gates/schema.ts +69 -6
  7. package/gates/workflow.test.ts +12 -5
  8. package/hooks/BunTestPathGuard.hook.ts +106 -0
  9. package/hooks/DocHygiene.hook.ts +2 -1
  10. package/hooks/GateResultProtection.hook.ts +28 -7
  11. package/hooks/HookCurrency.hook.ts +48 -1
  12. package/hooks/TopLevelCdGuard.hook.ts +38 -6
  13. package/hooks/VerifyPhaseLock.hook.ts +25 -8
  14. package/hooks/WorkflowStateGuard.hook.ts +24 -7
  15. package/lib/ai-review-jury.ts +725 -0
  16. package/lib/ai-review-rounds.ts +791 -4
  17. package/lib/ai-review-unmeasured.ts +361 -0
  18. package/lib/bash-write-guard.ts +1235 -102
  19. package/lib/bun-test-paths.ts +253 -0
  20. package/lib/cli-commands.ts +252 -11
  21. package/lib/closing-reference-audit.ts +163 -0
  22. package/lib/conformity.ts +17 -1
  23. package/lib/create-sc.ts +45 -12
  24. package/lib/derived-spec.ts +206 -0
  25. package/lib/file-claims.ts +335 -0
  26. package/lib/finding-arbiter.ts +502 -28
  27. package/lib/finding-jury.ts +61 -5
  28. package/lib/finding-pr-routing.ts +333 -0
  29. package/lib/frontmatter.ts +16 -0
  30. package/lib/gate-check-audit.ts +646 -0
  31. package/lib/generators/agents-md.ts +29 -0
  32. package/lib/github.ts +112 -7
  33. package/lib/hook-tree-currency.ts +494 -0
  34. package/lib/issue-closure-audit.ts +161 -14
  35. package/lib/issue-create-override.ts +53 -3
  36. package/lib/issue-filing-gate.ts +1073 -76
  37. package/lib/local-review-rounds.ts +523 -0
  38. package/lib/organize.ts +21 -1
  39. package/lib/project-state-shape.ts +56 -5
  40. package/lib/release-preflight.ts +90 -1
  41. package/lib/repo-path.ts +94 -0
  42. package/lib/report-provenance.ts +218 -3
  43. package/lib/risk-tier.ts +302 -0
  44. package/lib/rounds-to-pass.ts +274 -0
  45. package/lib/rule-row-drift.ts +199 -0
  46. package/lib/sc-claim-forms.ts +33 -5
  47. package/lib/sc-guard.ts +11 -1
  48. package/lib/sc-id-cross-tree.ts +17 -2
  49. package/lib/sc-ids.ts +71 -6
  50. package/lib/sc-reservations.ts +158 -14
  51. package/lib/scaffold/ai-review-findings.ts +1369 -27
  52. package/lib/scaffold/ai-review-step.ts +4095 -119
  53. package/lib/scaffold/ai-review-unmeasured-workflow.ts +243 -0
  54. package/lib/scaffold/owned-files.ts +14 -0
  55. package/lib/scaffold/steps.ts +100 -9
  56. package/lib/scratch-roots.ts +93 -3
  57. package/lib/spec-updater.ts +22 -2
  58. package/lib/spec-write-ast.ts +728 -0
  59. package/lib/spec-write-sweep.ts +470 -0
  60. package/lib/test-suite-lock.ts +127 -13
  61. package/lib/ts-ast.ts +26 -0
  62. package/lib/validators/spec-validators.ts +36 -7
  63. package/lib/write-spec.ts +138 -0
  64. package/package.json +2 -1
  65. package/scripts/ai-review-findings.ts +41 -1
  66. package/scripts/arbitrate-finding.ts +330 -12
  67. package/scripts/audit-specs.ts +225 -24
  68. package/scripts/convert-spec.ts +7 -2
  69. package/scripts/create-sc.ts +14 -2
  70. package/scripts/create-spec.ts +5 -2
  71. package/scripts/detect-sc-drift.ts +10 -2
  72. package/scripts/record-ai-review-unmeasured.ts +370 -0
  73. package/scripts/split-spec.ts +17 -4
  74. package/scripts/sync-sc-status.ts +14 -2
@@ -0,0 +1,335 @@
1
+ /**
2
+ * Who is writing which files right now, DECLARED rather than detected (#1413).
3
+ *
4
+ * `.github/workflows/ai-review.yml` is generated from
5
+ * `lib/scaffold/ai-review-step.ts`, so every pull request that changes review
6
+ * behaviour touches both, and therefore conflicts with every other such pull
7
+ * request by construction. On 2026-10-23 #1370 went DIRTY five times in three
8
+ * hours, #1387 rebased four times, and a fourth agent declined to open a pull
9
+ * request at all. Every one of those conflicts had the same three-step
10
+ * resolution: take `origin/main`'s copy, re-run the generator, confirm the
11
+ * second `--fix` pass reports unchanged. A conflict whose resolution is always
12
+ * identical is not a conflict. It is a missing lock.
13
+ *
14
+ * ## Why this is a declaration and not a detector
15
+ *
16
+ * Measured on this machine before any of it was written, and both results
17
+ * killed the obvious implementation:
18
+ *
19
+ * - `find -newermt '-6 hours'` silently matches nothing here. It returned
20
+ * empty against a file modified four seconds earlier. `-newer <ref>` works.
21
+ * - Even working, mtime cannot separate an edit from a checkout. `git
22
+ * worktree add` bumps every mtime, so a sweep returned 36,939 "recently
23
+ * edited" files and roughly 30 worktrees "touching" one script. Across 233
24
+ * worktrees there is no reading that answers who is editing a file now.
25
+ *
26
+ * And the instruments that *are* accurate — `gh pr list`,
27
+ * `closingIssuesReferences`, the tracker — all describe PUSHED state, while
28
+ * the dangerous window is the one before a push. So the signal has to be
29
+ * something a writer WRITES. The gap this closes is that declaring was
30
+ * voluntary and unrecorded, not that it was impossible.
31
+ *
32
+ * ## What this does not cover, stated rather than implied
33
+ *
34
+ * A path with no claim reads as free, and that is a true statement about the
35
+ * registry, not about the disk. This refuses to guess: an undeclared writer is
36
+ * invisible here exactly as it is invisible to `gh pr list`. What it buys is
37
+ * that a writer who declares can be seen by everyone before they branch, with
38
+ * one command, and that the registry is a serialisation point — two agents
39
+ * claiming at once conflict on a JSON array, which is a conflict a person may
40
+ * resolve, unlike the generated YAML this exists to protect.
41
+ *
42
+ * ## Liveness is resolved, never trusted
43
+ *
44
+ * `specs/sc-reservations.json` asks owners to delete their entry when the
45
+ * branch merges, and `.claude/rules/parallel-sessions.md` records that a block
46
+ * nobody prunes is headroom nobody can use. A stale claim is worse than that
47
+ * here: it reports a live writer forever and the next agent routes around a
48
+ * file nobody holds. So {@link liveClaims} takes the set of branches that
49
+ * still exist and are not merged, and a claim whose owner is not among them is
50
+ * DEAD regardless of what the file says.
51
+ */
52
+
53
+ import { underPrefix } from "./repo-path.ts";
54
+
55
+ /** The key that tells a store apart from an empty object. See {@link readFileClaims}. */
56
+ export const FILE_CLAIMS_CONTROL_KEY = "claims";
57
+
58
+ /** Repository-relative path of the registry. */
59
+ export const FILE_CLAIMS_PATH = "specs/file-claims.json";
60
+
61
+ /** One declared writer. */
62
+ export interface FileClaim {
63
+ /** The branch doing the writing. The thing another session looks you up by. */
64
+ owner: string;
65
+ /**
66
+ * Repository-relative paths this branch is writing. A directory claims
67
+ * everything beneath it; a file claims only itself.
68
+ */
69
+ paths: string[];
70
+ /** The issue the work is for, so a reader can go and read why. */
71
+ issue?: number;
72
+ /** Anything the next agent needs that the issue does not say. */
73
+ note?: string;
74
+ }
75
+
76
+ export type FileClaimStatus = "read" | "absent" | "unreadable";
77
+
78
+ export interface FileClaimReading {
79
+ status: FileClaimStatus;
80
+ /** Where the reading was taken from, whether or not anything was there. */
81
+ path: string;
82
+ /** Empty under every status except a `read` of a store that declares claims. */
83
+ claims: FileClaim[];
84
+ /** Why it is absent or unreadable. Absent on a clean read. */
85
+ reason?: string;
86
+ }
87
+
88
+ /**
89
+ * Validate one entry, returning why it is unusable or `null`.
90
+ *
91
+ * Every fault refuses the WHOLE store rather than dropping the entry. A
92
+ * registry the reader only partly understands is unreadable, not partly read
93
+ * — the same rule `lib/sc-reservations.ts` applies to an unknown namespace,
94
+ * and for the same reason: a claim silently dropped is a lock silently
95
+ * released, which is the one failure this file must not have.
96
+ */
97
+ function claimFault(raw: unknown, index: number): string | null {
98
+ const at = `${FILE_CLAIMS_CONTROL_KEY}[${index}]`;
99
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return `${at} is not an object`;
100
+ const c = raw as Record<string, unknown>;
101
+ if (typeof c.owner !== "string" || c.owner.trim() === "") return `${at} has no owner`;
102
+ const who = c.owner as string;
103
+ if (!Array.isArray(c.paths) || c.paths.length === 0) {
104
+ return `${at} (${who}) claims no paths`;
105
+ }
106
+ for (const [i, p] of (c.paths as unknown[]).entries()) {
107
+ if (typeof p !== "string" || p.trim() === "") return `${at} (${who}) paths[${i}] is not a path`;
108
+ // Repository-relative and nothing else. An absolute path is a claim about
109
+ // one machine, and `..` is a claim about a tree this registry does not
110
+ // describe — both read as a path that no caller's `git diff --name-only`
111
+ // will ever produce, so they would silently never match.
112
+ if (p.startsWith("/")) return `${at} (${who}) paths[${i}] is absolute: ${p}`;
113
+ if (p.split("/").includes("..")) return `${at} (${who}) paths[${i}] escapes the repository: ${p}`;
114
+ }
115
+ if (c.issue !== undefined && (typeof c.issue !== "number" || !Number.isSafeInteger(c.issue))) {
116
+ return `${at} (${who}) has a non-integer issue`;
117
+ }
118
+ if (c.note !== undefined && typeof c.note !== "string") return `${at} (${who}) has a non-string note`;
119
+ return null;
120
+ }
121
+
122
+ /**
123
+ * Read the registry from the bytes of the file.
124
+ *
125
+ * Three outcomes, and the caller must not collapse them:
126
+ *
127
+ * - `absent` — `raw` is `null`, nobody has declared anything. A real reading.
128
+ * - `unreadable` — present and not understood. NOT an empty reading: a
129
+ * registry that fails to parse would otherwise report every file free,
130
+ * which is the fail-open this whole mechanism exists to prevent.
131
+ * - `read` — understood, `claims` is what it declares.
132
+ *
133
+ * `{}` and `{"claims": []}` are different facts and the control key is what
134
+ * separates them. The first is a file that has lost its contents; the second
135
+ * is a registry saying, deliberately, that nobody holds anything.
136
+ */
137
+ export function readFileClaims(raw: string | null, path = FILE_CLAIMS_PATH): FileClaimReading {
138
+ if (raw === null) {
139
+ return { status: "absent", path, claims: [], reason: "no registry at this path" };
140
+ }
141
+ let parsed: unknown;
142
+ try {
143
+ parsed = JSON.parse(raw);
144
+ } catch (e) {
145
+ const why = (e instanceof Error ? e.message : String(e)).split("\n")[0];
146
+ return { status: "unreadable", path, claims: [], reason: `not JSON (${why})` };
147
+ }
148
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
149
+ return { status: "unreadable", path, claims: [], reason: "the store is not an object" };
150
+ }
151
+ const store = parsed as Record<string, unknown>;
152
+ if (!(FILE_CLAIMS_CONTROL_KEY in store)) {
153
+ return {
154
+ status: "unreadable",
155
+ path,
156
+ claims: [],
157
+ reason: `the store declares no \`${FILE_CLAIMS_CONTROL_KEY}\` key, so it cannot be told from a file that lost its contents`,
158
+ };
159
+ }
160
+ const list = store[FILE_CLAIMS_CONTROL_KEY];
161
+ if (!Array.isArray(list)) {
162
+ return { status: "unreadable", path, claims: [], reason: `\`${FILE_CLAIMS_CONTROL_KEY}\` is not an array` };
163
+ }
164
+ for (const [i, entry] of list.entries()) {
165
+ const fault = claimFault(entry, i);
166
+ if (fault !== null) return { status: "unreadable", path, claims: [], reason: fault };
167
+ }
168
+ return { status: "read", path, claims: list as FileClaim[] };
169
+ }
170
+
171
+ /**
172
+ * Does `claimed` cover `path`? A directory covers everything beneath it.
173
+ *
174
+ * This is `underPrefix` and nothing else. It used to be four lines of
175
+ * `startsWith` here, which was a SECOND DECIDER for a question
176
+ * `lib/repo-path.ts` already answers —
177
+ * `.claude/rules/checks-must-be-able-to-fail.md`, *two deciders* — and the
178
+ * two disagreed on exactly the inputs a caller produces by accident. The
179
+ * registry side was never the gap: `claimFault` already rejects absolute and
180
+ * `..` paths. It was the CALLER-supplied path, which nothing normalised, and
181
+ * `./lib/x.ts` is what tab-completion hands you.
182
+ *
183
+ * Measured against the local copy before the swap, for the claim `lib`:
184
+ *
185
+ * | path | the old local rule | `underPrefix` |
186
+ * |---|---|---|
187
+ * | `./lib/x.ts` | false | **true** |
188
+ * | `Lib/x.ts` | false | **true** |
189
+ * | `lib\x.ts` | false | **true** |
190
+ * | `library/x.ts` | false | false |
191
+ * | `../lib/x.ts` | false | false |
192
+ *
193
+ * Three contended paths reading FREE, and the last two rows are why the fix
194
+ * is a swap rather than a patch: the centralised rule is segment-aware and
195
+ * refuses a `..` escape, so it is stricter where it matters and looser only
196
+ * where the old rule was wrong. Every fixture anyone would naturally write
197
+ * passes under both, which is why the suite was green (#1436 review).
198
+ */
199
+ export function claimCovers(claimed: string, path: string): boolean {
200
+ return underPrefix(path, claimed);
201
+ }
202
+
203
+ /** What a declared owner's branch is doing. Three states, never two. */
204
+ export type OwnerState = "live" | "landed" | "unmeasured";
205
+
206
+ /** The one field of a pull request this decision reads. `gh`'s spelling. */
207
+ export interface PullState {
208
+ number: number;
209
+ /** `OPEN`, `CLOSED` or `MERGED`. A draft pull request is `OPEN`. */
210
+ state: string;
211
+ }
212
+
213
+ /**
214
+ * Is this owner still working, judged by its pull requests?
215
+ *
216
+ * ## Two git-only rules were tried first, and both were wrong
217
+ *
218
+ * **Ancestry.** `git merge-base --is-ancestor` and `git branch -r
219
+ * --no-merged` compare commits, and this repository squash-merges: the squash
220
+ * commit is a new object, so a merged branch's tip is never an ancestor of
221
+ * the base and both report it UNMERGED forever. Measured —
222
+ * `rg/1168-eviction-note` merged at 17:43 on 2026-10-23 and `--no-merged`
223
+ * still listed it afterwards.
224
+ *
225
+ * **Subjects.** The replacement asked whether every subject the branch
226
+ * carries ahead of the base also appears among the base's subjects. That is
227
+ * true for a SINGLE-commit pull request, whose squash subject is the commit
228
+ * subject with ` (#N)` appended — and false for every other one. GitHub's
229
+ * squash subject for a multi-commit branch is the PULL REQUEST TITLE; the
230
+ * individual commit subjects go into the squash BODY as `* ` bullets, where
231
+ * `git log --format=%s` cannot see them. Measured against the 15 most
232
+ * recently merged pull requests with surviving refs: **11 of 12 answered
233
+ * `landed=false`**, every one of them merged. Only the one single-commit row
234
+ * was right, and the battery that passed this rule in review had sampled
235
+ * nothing but single-commit branches — it could not have discriminated.
236
+ *
237
+ * Both failures point the same way, and it is the fail-open direction for a
238
+ * lock: a merged branch that reads LIVE holds its files forever.
239
+ * `RUNGATE_BRANCH_CLEANUP` is deliberately unset here, so merged refs are
240
+ * never deleted and nothing else would ever clear the entry. A lock nobody
241
+ * can acquire is worse than no lock, because people route around it.
242
+ *
243
+ * ## So ask the tracker, which is told rather than inferred
244
+ *
245
+ * A pull request's state is a fact somebody recorded, not a shape guessed out
246
+ * of a commit graph that squashing has already destroyed. It is also the same
247
+ * place this project keeps every other claim about who is doing what.
248
+ *
249
+ * The cases, each reachable and each separately witnessed:
250
+ *
251
+ * - `pulls === null` — the tracker could not be read. UNMEASURED. This does
252
+ * not fall through to landed; an unread tracker is not an empty one.
253
+ * - any pull is `OPEN` — LIVE. Draft counts: a draft is someone working.
254
+ * - pulls exist and none is open — LANDED, merged or abandoned alike. Both
255
+ * mean nobody is writing those files under this name any more.
256
+ * - no pull at all, but the ref is on the remote — LIVE. A pushed branch with
257
+ * no pull request yet is the EARLIEST moment a claim matters, and it is
258
+ * exactly when a second agent is deciding whether to start.
259
+ * - no pull and no ref, refs refreshed — LANDED. There is nothing there.
260
+ * - no pull and no ref, refs NOT refreshed — UNMEASURED. A branch nobody
261
+ * fetched and a branch somebody deleted look identical, and only one of
262
+ * them is safe to call free.
263
+ */
264
+ export function ownerState(
265
+ pulls: readonly PullState[] | null,
266
+ refExists: boolean,
267
+ refsRefreshed: boolean,
268
+ ): { state: OwnerState; why: string } {
269
+ if (pulls === null) {
270
+ return { state: "unmeasured", why: "the tracker could not be read for this branch" };
271
+ }
272
+ const open = pulls.filter(p => p.state.toUpperCase() === "OPEN");
273
+ if (open.length > 0) {
274
+ return { state: "live", why: `open pull request ${open.map(p => `#${p.number}`).join(", ")}` };
275
+ }
276
+ if (pulls.length > 0) {
277
+ return {
278
+ state: "landed",
279
+ why: `no open pull request (${pulls.map(p => `#${p.number} ${p.state.toLowerCase()}`).join(", ")})`,
280
+ };
281
+ }
282
+ if (refExists) {
283
+ return { state: "live", why: "branch is on the remote with no pull request yet" };
284
+ }
285
+ if (refsRefreshed) {
286
+ return { state: "landed", why: "no pull request and no branch on the remote" };
287
+ }
288
+ return {
289
+ state: "unmeasured",
290
+ why: "no pull request, and the refs were not refreshed, so \"deleted\" and \"never fetched\" cannot be told apart",
291
+ };
292
+ }
293
+
294
+ /**
295
+ * The claims that cover `path`, among those whose owner is still live.
296
+ *
297
+ * `liveOwners` is the set of branches that exist and are unmerged, supplied by
298
+ * the caller because resolving it is a git operation and this module decides
299
+ * nothing from the filesystem. A claim whose owner is absent from that set is
300
+ * DEAD — the branch merged or went away and nobody pruned the entry — and a
301
+ * dead claim must not hold a file, or the registry becomes a list of places
302
+ * nobody may ever work again.
303
+ */
304
+ export function liveClaims(
305
+ claims: readonly FileClaim[],
306
+ path: string,
307
+ liveOwners: ReadonlySet<string>,
308
+ ): FileClaim[] {
309
+ return claims.filter(c => liveOwners.has(c.owner) && c.paths.some(p => claimCovers(p, path)));
310
+ }
311
+
312
+ /** Every claim on `path`, live or not, so a report can say which is which. */
313
+ export function allClaims(claims: readonly FileClaim[], path: string): FileClaim[] {
314
+ return claims.filter(c => c.paths.some(p => claimCovers(p, path)));
315
+ }
316
+
317
+ /**
318
+ * The claims a set of paths runs into, keyed by path.
319
+ *
320
+ * Entries with no live claim are omitted rather than mapped to `[]`: the
321
+ * caller's question is "what is contended", and an empty map is the answer
322
+ * "nothing", which is different from "I checked nothing".
323
+ */
324
+ export function contention(
325
+ claims: readonly FileClaim[],
326
+ paths: readonly string[],
327
+ liveOwners: ReadonlySet<string>,
328
+ ): Map<string, FileClaim[]> {
329
+ const out = new Map<string, FileClaim[]>();
330
+ for (const p of paths) {
331
+ const hits = liveClaims(claims, p, liveOwners);
332
+ if (hits.length > 0) out.set(p, hits);
333
+ }
334
+ return out;
335
+ }