rungate 0.8.13 → 0.8.16

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 (88) hide show
  1. package/README.md +182 -0
  2. package/gates/.gate-salt +1 -1
  3. package/hooks/HarnessAFKGate.hook.ts +5 -1
  4. package/hooks/HookCurrency.hook.ts +11 -8
  5. package/hooks/MergeGuard.hook.ts +7 -1
  6. package/hooks/StaleTTLCleanup.hook.ts +4 -4
  7. package/hooks/VerifyPhaseLock.hook.ts +3 -3
  8. package/hooks/lib/findWorkflow.ts +3 -2
  9. package/hooks/lib/paths.ts +14 -2
  10. package/hooks/lib/utils.ts +23 -3
  11. package/lib/active-milestone.ts +50 -0
  12. package/lib/ai-review-rounds.ts +99 -0
  13. package/lib/ai-review-suppression.ts +200 -21
  14. package/lib/bash-write-guard.ts +397 -23
  15. package/lib/board-flow.ts +280 -0
  16. package/lib/board-lane-health.ts +578 -0
  17. package/lib/board-mirror.ts +136 -39
  18. package/lib/board-ready-fanout.ts +297 -14
  19. package/lib/board-ready-rule.ts +1211 -0
  20. package/lib/board-throughput.ts +136 -0
  21. package/lib/board-walkthrough.ts +240 -0
  22. package/lib/body-evidence.ts +203 -0
  23. package/lib/branch-protection.ts +399 -9
  24. package/lib/bun-version.ts +36 -0
  25. package/lib/cli-commands.ts +75 -4
  26. package/lib/closing-reference-audit.ts +307 -6
  27. package/lib/config-loader.ts +254 -25
  28. package/lib/config-readers.ts +170 -10
  29. package/lib/config-trackable.ts +96 -57
  30. package/lib/conformity.ts +121 -7
  31. package/lib/create-sc.ts +25 -2
  32. package/lib/derived-spec.ts +21 -9
  33. package/lib/filing-compliance.ts +367 -0
  34. package/lib/filing-plan.ts +47 -21
  35. package/lib/finding-arbiter.ts +79 -5
  36. package/lib/finding-jury.ts +43 -4
  37. package/lib/finding-promotion.ts +1123 -0
  38. package/lib/generators/agents-md.ts +149 -0
  39. package/lib/git-isolation.ts +137 -1
  40. package/lib/github-api-base.ts +66 -0
  41. package/lib/github.ts +194 -9
  42. package/lib/graphql-cursor.ts +80 -0
  43. package/lib/hook-scopes.ts +78 -0
  44. package/lib/issue-create-override.ts +415 -3
  45. package/lib/issue-decomposition.ts +124 -7
  46. package/lib/issue-extraction.ts +9 -7
  47. package/lib/issue-file-overlap.ts +373 -0
  48. package/lib/issue-filing-gate.ts +1109 -52
  49. package/lib/issue-repair.ts +90 -9
  50. package/lib/issue-shape.ts +199 -0
  51. package/lib/live-issues.ts +31 -2
  52. package/lib/local-work.ts +423 -0
  53. package/lib/markdown-fence.ts +134 -0
  54. package/lib/milestone-title.ts +46 -0
  55. package/lib/scaffold/ai-review-findings.ts +148 -3
  56. package/lib/scaffold/ai-review-step.ts +65 -5
  57. package/lib/scaffold/ai-review-unmeasured-workflow.ts +3 -0
  58. package/lib/scaffold/steps.ts +115 -9
  59. package/lib/source-census.ts +108 -0
  60. package/lib/spec-deps.ts +55 -11
  61. package/lib/spec-placement.ts +203 -13
  62. package/lib/spec-registry.ts +75 -16
  63. package/lib/spec-source.ts +609 -0
  64. package/lib/spec-write-sweep.ts +4 -0
  65. package/lib/stage-ladder.ts +896 -3
  66. package/lib/state-claim-readings.ts +252 -0
  67. package/lib/success-doc.ts +7 -6
  68. package/lib/test-command-positions.ts +135 -1
  69. package/lib/work-status.ts +551 -0
  70. package/lib/worktree-repo.ts +14 -2
  71. package/package.json +7 -1
  72. package/scripts/ai-review-findings.ts +8 -13
  73. package/scripts/ai-review-threads.ts +16 -17
  74. package/scripts/audit-closing-references.ts +330 -0
  75. package/scripts/audit-specs.ts +59 -103
  76. package/scripts/board-conformance.ts +747 -40
  77. package/scripts/board-mirror.ts +594 -13
  78. package/scripts/board-ready.ts +979 -0
  79. package/scripts/board-snapshot.ts +464 -12
  80. package/scripts/claim-files.ts +578 -0
  81. package/scripts/criterion-inventory.ts +526 -50
  82. package/scripts/finding-promotion.ts +547 -0
  83. package/scripts/generate-code-map.ts +1 -1
  84. package/scripts/plan-issues.ts +279 -40
  85. package/scripts/plan-spec.ts +105 -3
  86. package/scripts/sync-sc-status.ts +147 -7
  87. package/scripts/worktree-census.ts +958 -0
  88. package/scripts/worktree-sweep.ts +269 -0
package/README.md ADDED
@@ -0,0 +1,182 @@
1
+ # RunGate
2
+
3
+ A ship harness for AI-first development: from issue to merged PR, with a report you can trust.
4
+
5
+ You should be able to trust that report without checking it again by hand. Coding agents can write a lot of code quickly. The hard part is believing what they say about it. "Tests pass", "0 regressions" and "security: clean" are only useful if the thing reporting them could have said something else. RunGate is built around that. The automation isn't really the product. The product is a report you don't have to re-measure.
6
+
7
+ > **Status: active development, pre-1.0.** Published on npm as [`rungate`](https://www.npmjs.com/package/rungate). It is used daily on this repo and is being proven on a second, unrelated project. Expect breaking changes between minor versions.
8
+
9
+ ## What it does
10
+
11
+ RunGate sits between an issue tracker and a coding agent (Claude Code today; the design is agent-agnostic) and runs every change through a fixed pipeline:
12
+
13
+ ```
14
+ issue → SCOPE → BUILD → VERIFY → CLOSE → SHIP_PASSED | SHIP_FAILED
15
+ ```
16
+
17
+ - **Gates, not guidelines.** Each phase ends at a gate: typecheck, tests, test-first sequencing, security review, compliance grade, review currency, and commit receipt. A failed gate stops the ship. It is not just written into a log.
18
+ - **Specs with checkable criteria.** Work is driven by specs whose success criteria name the evidence that proves them. A criterion ticked without evidence is refused.
19
+ - **Spec → board, automatically.** A spec's phases become milestones, issues and `blocked by` edges on the GitHub project board. Nobody has to place the plan there by hand. See [From spec to merged PR](#from-spec-to-merged-pr).
20
+ - **Project-specific agent rules.** `scaffold` gives a repo its agent files and a conformity suite. `extract-constraints` mines the repo's own docs and history for rules an agent couldn't work out from the code.
21
+ - **AI review that blocks.** AI code-review findings are judged and posted as review threads on the PR diff, and a blocking finding fails the check.
22
+ - **Workflows** for `ship`, `prove` (reproduce and attest a fix), `verify`, `batch-ship`, `ship-and-heal` and multi-agent `council` decisions.
23
+
24
+ ## From spec to merged PR
25
+
26
+ This is how work moves in this repository. The ten rules behind it are in [`AGENTS.md`](AGENTS.md); the engine is governed by [`specs/SPEC-TO-BOARD-PIPELINE-SPEC.md`](specs/SPEC-TO-BOARD-PIPELINE-SPEC.md) and the board lanes by [`specs/BOARD-FLOW-SPEC.md`](specs/BOARD-FLOW-SPEC.md).
27
+
28
+ ```mermaid
29
+ flowchart TD
30
+ S["Spec: success criteria and a Phase placement table"] --> A["ADR with a Decomposition table"]
31
+ A -->|"owner merges it as accepted"| W["adr-accepted.yml"]
32
+ W --> I["Issues, one per table row"]
33
+ W --> M["Milestones from phases, blocked-by edges"]
34
+ I --> R["Board: Ready lane, active milestone only"]
35
+ M --> R
36
+ R --> P["PR that closes its issue: closing-references and AI review"]
37
+ P --> G["Merge to main"]
38
+ G --> C["board-conformance: does the board say what the spec says?"]
39
+ ```
40
+
41
+ ### A spec says what must be true
42
+
43
+ A spec in `specs/` lists success criteria (`- [ ] SC-<N>: …`), each naming the evidence that would prove it. **A spec is never the to-do list** (rule 1): its checkboxes record what has been proved, and the work itself comes off the issue tracker. A ticked criterion must carry a `proved-by:` line naming the test that ran; `rungate audit-spec-evidence` refuses one that does not.
44
+
45
+ ### Work bigger than one issue is an ADR
46
+
47
+ Small, agreed work is filed as one issue straight away. The issue names the files it will change, and there are fewer than ten (rules 2 and 3).
48
+
49
+ Anything bigger than one issue, or any change to a rule or a gate, is an ADR copied from [`docs/adr/TEMPLATE.md`](docs/adr/TEMPLATE.md) (rule 9). Its **Decomposition table** has one row per issue: the criterion it serves, the outcome (which becomes the issue title), the files, the milestone, and what blocks it. The criteria are written into the governing spec first. The `/dry-run` command (`.claude/commands/dry-run.md`) shows what the planning tools would do, without writing anything, until the repo owner agrees.
50
+
51
+ When the owner merges the ADR with `status: accepted`, [`.github/workflows/adr-accepted.yml`](.github/workflows/adr-accepted.yml) places the plan with no command typed by hand: `plan-spec`, then `plan-issues --decompose` (one issue per row), then `plan-deps`, `board-mirror` and a Ready top-up.
52
+
53
+ ### Phases become milestones, and order becomes edges
54
+
55
+ A planned spec carries a **Phase placement** table that puts every criterion in exactly one phase.
56
+
57
+ - `rungate plan-spec` turns the phases into GitHub milestones (here, `Pipeline Phase 0` to `Pipeline Phase 9`).
58
+ - `rungate plan-deps` writes the phase order onto the tracker as GitHub `blocked by` edges. "What's next" is then everything unblocked, worked out by GitHub instead of read from a sentence (rule 4).
59
+
60
+ Both only report unless you pass `--write`.
61
+
62
+ ### The board is a Kanban
63
+
64
+ The GitHub Project board has six lanes, and every move is triggered by a GitHub event, not by a person dragging a card:
65
+
66
+ | Lane | An issue enters when | Moved by |
67
+ |---|---|---|
68
+ | Backlog | it is filed or reopened, or anything moves backwards | `board-intake.yml`, `board-flow.yml` |
69
+ | Ready | it is unblocked, unassigned, in the active milestone, and Ready has room | `board-ready.yml` |
70
+ | In progress | someone is assigned to it | `board-flow.yml`, `board-sweep.yml` |
71
+ | In review | a linked PR is ready for review (not a draft) | `board-flow.yml` |
72
+ | Done | it is closed as completed | `board-flow.yml` |
73
+ | Cancelled | it is closed as not planned, or as a duplicate | `board-flow.yml` |
74
+
75
+ **Ready is filled only from the active milestone**: the lowest Pipeline phase that still has an open issue (`activeMilestone` in `lib/board-ready-rule.ts`). Only issues with no open blocker enter, oldest first, and Ready's size is set from recent throughput. Three more rules:
76
+
77
+ - An issue labelled `work-this-next` (the expedite label) may enter from outside the active milestone.
78
+ - An issue with no phase milestone, only a label, never enters on its own. Milestones from other specs (here, `Convergence Phase N`) become the focus only when no Pipeline phase has an open issue.
79
+ - A card in Ready from outside the active milestone goes back to Backlog.
80
+
81
+ `board-ready.yml` refills Ready on every issue event that could change the answer (closed, assigned, unassigned, opened, reopened, milestoned, demilestoned, labeled, unlabeled), never on a schedule. `rungate board-mirror --ready --write` applies the same rule by hand.
82
+
83
+ **New issues reach the board by being filed.** `board-intake.yml` adds every issue and pull request when it is opened. An issue transferred in from another repository is not picked up; file it instead.
84
+
85
+ The board's identity, its labels, the engine spec and the milestone prefix are read from the `board` section of `.claude/rungate/config.json`.
86
+
87
+ ### Every PR closes an issue, and gets an AI review
88
+
89
+ Each PR says `Fixes #N` in its description. The required `closing-references` check ([`.github/workflows/closing-references.yml`](.github/workflows/closing-references.yml)) refuses a PR that closes no issue, or whose issue names neither a criterion nor "serves no criterion". The one exception is a PR that changes only the session-record files (`project-state.json`, `PROJECT-STATE.md`, `SUCCESS.md`), and the diff decides that, not the branch name.
90
+
91
+ Every PR also gets an AI review ([`.github/workflows/ai-review.yml`](.github/workflows/ai-review.yml)). `rungate ai-review-findings` judges the findings and fails the check on a blocking one; `rungate ai-review-threads` posts them as review threads on the diff.
92
+
93
+ ### Does the board say what the spec says?
94
+
95
+ `rungate board-conformance` takes eight readings and exits non-zero while any one is short of its target:
96
+
97
+ | Reading | Asks whether |
98
+ |---|---|
99
+ | `milestones` | every phase the spec places has its milestone on the board |
100
+ | `criterion-coverage` | every engine criterion has an open issue, or is recorded as already true |
101
+ | `blocked-by-edges` | every engine issue is a declared starting point or carries a `blocked by` edge |
102
+ | `criteria-field` | the board's Criteria column is filled in for every engine issue |
103
+ | `queue-label` | every engine issue carries the queue label |
104
+ | `spec-placement` | every criterion in an in-scope spec sits in a phase, or its spec is named as unplanned |
105
+ | `criteria-named` | every open issue names the criteria it serves, or says it serves none |
106
+ | `dependency-edges` | every ordering the plan implies is a `blocked by` edge on the tracker |
107
+
108
+ [`.github/workflows/board-conformance.yml`](.github/workflows/board-conformance.yml) runs it on every push to `main`. It reports and blocks nothing: a merge that closes the last issue for a criterion leaves the board short for the minutes until that criterion is ticked, and a blocking check would turn correct work red. `--list-readings` prints the readings; `--reading <name>` takes one.
109
+
110
+ ### One screen for all of it
111
+
112
+ `bun scripts/work-status.ts` shows this repository's lanes, what is in Ready and why, progress through the active milestone, and the plan's stages from `project-state.json`. It is read-only. It needs a GitHub token that can read the project board (the `read:project` or `project` scope) in `GITHUB_TOKEN` or `GH_TOKEN`.
113
+
114
+ **These board workflows run in this repository only, for now.** `rungate scaffold` does not yet install them in other projects; [ADR-014](docs/adr/ADR-014-the-process-reaches-consumers.md) is the work that will.
115
+
116
+ ## What "done" means
117
+
118
+ The project measures itself against falsifiable claims in [`SUCCESS.md`](SUCCESS.md). Each claim has a named check:
119
+
120
+ 1. **Every gate can fail, and has been seen failing.** A mutant with the refusal removed must ship where the real gate refuses.
121
+ 2. **Every number a run reports describes the committed tree.** No figure can come from before the last edit it describes.
122
+ 3. **A bad ship is stopped, not described.** Every verdict the harness computes can return `SHIP_FAILED`.
123
+ 4. **"Could not measure" never reads as "nothing wrong."** Missing, empty or broken input is a separate, loud result.
124
+ 5. **It works on a repo that isn't this one.**
125
+ 6. **A managed repo carries its own rules**, mined from that repo's history, not just a generic baseline.
126
+ 7. **The plan is on the tracker, and no person or agent put it there.**
127
+
128
+ A green test suite, a passing gate and a merged PR don't count as progress unless they meet these claims. Each of them has been wrong in this repo before.
129
+
130
+ ## Where it stands
131
+
132
+ - **Working:** the ship pipeline and gates, the spec tooling, AI-review adjudication, scaffolding, and release automation to npm. About 1,700 commits and 1,080 merged PRs (2026-11-13), shipped through the harness itself until 2026-10-19 and directly since, while RunGate is stabilised.
133
+ - **Working in this repo:** the spec-to-board pipeline above. Accepted ADRs place their own plans, Ready refills itself from the active milestone, and every PR must close an issue that names a criterion.
134
+ - **In progress:** the *engine*. The goal is for a spec to become a readable project board with no hand-run steps ([ADR-009](docs/adr/ADR-009-engine-goal-and-build-order.md)), and for the same process to reach other projects through `scaffold` ([ADR-014](docs/adr/ADR-014-the-process-reaches-consumers.md)).
135
+ - **Next:** a full run on a consumer project with a different config layout (claim 5). Until that is done, consumer support is unproven.
136
+
137
+ Live session-by-session state is in [`PROJECT-STATE.md`](PROJECT-STATE.md).
138
+
139
+ ## Quick start
140
+
141
+ Requires [Bun](https://bun.sh).
142
+
143
+ ```bash
144
+ # In the repository you want to manage
145
+ bunx rungate scaffold . # agent files, rules and conformity suite
146
+ bunx rungate create-success # seed SUCCESS.md: what the project is for
147
+ bunx rungate create-spec "Title" # a spec with checkable success criteria
148
+ bunx rungate plan-spec <spec.md> --repo <owner/name> --prefix <name> # milestones from phases
149
+ bunx rungate plan-deps --repo <owner/name> --milestone-prefix <name> # blocked-by edges from phase order
150
+ bunx rungate board-mirror --project <id> # show the spec's criteria on the project board
151
+ bunx rungate board-conformance # does the board match the spec? non-zero if not
152
+ bunx rungate --help # every command and its arguments
153
+ ```
154
+
155
+ The planning and board commands only report until you add `--write`.
156
+
157
+ Projects are configured in `.claude/rungate/config.json` (project slug, code and issue repos, dev/test/prod commands, the board). The older single file `.claude/rungate.json` is still read. See [`HARNESS.md`](HARNESS.md) for the schema and workflow entry points.
158
+
159
+ ## Repository layout
160
+
161
+ | Path | What lives there |
162
+ |---|---|
163
+ | `bin/`, `lib/` | CLI and core library |
164
+ | `scripts/` | The commands the CLI and the workflows run, plus `work-status.ts` |
165
+ | `gates/` | Gate runner, ship orchestrator and gate tests |
166
+ | `workflows/` | `ship`, `prove`, `verify`, `council` and friends |
167
+ | `.github/workflows/` | CI, AI review, `closing-references`, and the board workflows |
168
+ | `specs/` | Specs that govern the harness's own behaviour |
169
+ | `docs/adr/` | Architecture decisions, and `TEMPLATE.md` for new ones |
170
+ | `templates/`, `prompts/` | What `scaffold` writes and the agents read |
171
+ | `test/` | The suite. Run with `bun scripts/test-clean-env.ts` |
172
+
173
+ ## Development
174
+
175
+ ```bash
176
+ bun install
177
+ bun scripts/test-clean-env.ts # the suite in a clean environment (trust this one)
178
+ bun test <file> # a single file
179
+ bun scripts/work-status.ts # lanes, Ready and the plan, on one screen
180
+ ```
181
+
182
+ Start with [`AGENTS.md`](AGENTS.md) and [`CODE-MAP.md`](CODE-MAP.md).
package/gates/.gate-salt CHANGED
@@ -1 +1 @@
1
- 747398b3ddaddadd72ae597e21f050587654bc584d2f72286d66b4c2a921e001
1
+ eae3d899be4a8464ebf582bcba421f8e6660953f898adc3e5967ce30abf41a5b
@@ -31,13 +31,17 @@
31
31
  import { readdirSync, readFileSync, statSync } from 'fs';
32
32
  import { join } from 'path';
33
33
  import { WORK_DIR } from './lib/paths';
34
+ import { isRunDirectory } from '../lib/active-workflow';
34
35
 
35
36
  const BLOCKED_PHASES = new Set(['build', 'execute', 'verify']);
36
37
 
37
38
  function findLatestPRD(): { path: string; phase: string } | null {
38
39
  try {
40
+ // Filtered (#1668). This picks the PRD by newest mtime, which is the
41
+ // exact shape #1648 describes: an archived run's PRD.md is written last,
42
+ // so unfiltered it always wins and the gate reads a finished run's plan.
39
43
  const dirs = readdirSync(WORK_DIR, { withFileTypes: true })
40
- .filter(d => d.isDirectory())
44
+ .filter(d => d.isDirectory() && isRunDirectory(d.name))
41
45
  .map(d => {
42
46
  const prdPath = join(WORK_DIR, d.name, 'PRD.md');
43
47
  try {
@@ -45,6 +45,7 @@ import { join } from 'path';
45
45
  import { tryLoadRungateConfig } from '../lib/config-loader';
46
46
  import { repoRootFrom } from '../lib/paths';
47
47
  import { currencyReportLines, readRegistrationCurrency, spawnGitRunner } from '../lib/hook-tree-currency';
48
+ import { liveClaimReport } from '../lib/hook-scopes';
48
49
  import {
49
50
  readHookCurrency,
50
51
  currencyClass,
@@ -113,26 +114,28 @@ try {
113
114
  }
114
115
 
115
116
  // ── Second reading: how old are the hooks a session actually executes (#1216)
116
- // Its own `try`: two readings of different files, so one throwing must not
117
- // take the other's with it — a shared `catch` would be one refusal standing
118
- // for two, and nobody could tell which was never taken. The `hooks/` gate is
119
- // the `.git/hooks` gate above, for the same reason: a tree the scaffold never
117
+ // Its own `try`: two readings of different files, so one throwing must not take
118
+ // the other's with it — a shared `catch` would be one refusal standing for two.
119
+ // The `hooks/` gate is the `.git/hooks` gate above: a tree the scaffold never
120
120
  // touched owns no hooks of ours to be stale.
121
121
  try {
122
122
  const hooksDir = join(PROJECT_ROOT, 'hooks');
123
123
  if (existsSync(hooksDir)) {
124
124
  const config = tryLoadRungateConfig(PROJECT_ROOT) as { hooks?: unknown[] } | null;
125
+ const readFile = (p: string) => (existsSync(p) ? readFileSync(p, 'utf-8') : null);
126
+ const registryCommands = (config?.hooks ?? []).map(h => String((h as { command?: string })?.command ?? h));
127
+ // #1986 first, and it catches its own failure: a git error below cannot silence it.
128
+ for (const line of liveClaimReport({ repoRoot: PROJECT_ROOT, home: homedir(), readFile, registry: config?.hooks ?? [], registryCommands })) report(line);
125
129
  const reading = readRegistrationCurrency({
126
130
  repoRoot: PROJECT_ROOT,
127
131
  home: homedir(),
128
- // Named at the call site, not defaulted inside the module — its header
129
- // says why.
132
+ // Named at the call site, not defaulted inside the module — its header says why.
130
133
  base: 'origin/main',
131
- readFile: p => (existsSync(p) ? readFileSync(p, 'utf-8') : null),
134
+ readFile,
132
135
  ownedHooks: readdirSync(hooksDir)
133
136
  .filter(n => n.endsWith('.hook.ts'))
134
137
  .map(n => n.replace(/\.hook\.ts$/, '')),
135
- registryCommands: (config?.hooks ?? []).map(h => String((h as { command?: string })?.command ?? h)),
138
+ registryCommands,
136
139
  // `spawnGitRunner`, never an inline spawn: these directories are the
137
140
  // unsupervised ones, and git executes its own config. See the module.
138
141
  git: spawnGitRunner(spawnSync),
@@ -12,13 +12,19 @@
12
12
  import { readdirSync, readFileSync, existsSync, statSync } from 'fs';
13
13
  import { join } from 'path';
14
14
  import { parseHookInput, WORK_DIR, HARNESS_ROOT } from './lib/utils';
15
+ import { isRunDirectory } from '../lib/active-workflow';
15
16
 
16
17
  const TTL_MS = 4 * 60 * 60 * 1000;
17
18
 
18
19
  function findActiveShipMarker(): { issue: number; workDir: string } | null {
19
20
  if (!existsSync(WORK_DIR)) return null;
20
21
  try {
21
- for (const d of readdirSync(WORK_DIR, { withFileTypes: true }).filter(d => d.isDirectory())) {
22
+ // Filtered (#1668). `.archive/<slug>/.ship-active` is a finished run's
23
+ // marker; unfiltered, it is returned as the active ship and this guard
24
+ // gates a merge on behalf of a run that ended. The TTL below bounds how
25
+ // long that lasts but does not prevent it — an archive written inside the
26
+ // window reads exactly like a live run.
27
+ for (const d of readdirSync(WORK_DIR, { withFileTypes: true }).filter(d => d.isDirectory() && isRunDirectory(d.name))) {
22
28
  const markerPath = join(WORK_DIR, d.name, '.ship-active');
23
29
  if (!existsSync(markerPath)) continue;
24
30
  if (Date.now() - statSync(markerPath).mtimeMs > TTL_MS) continue;
@@ -51,11 +51,11 @@ if (PROJECT_ROOT) try {
51
51
  }
52
52
  }
53
53
  } catch (e) { log(`WORKTREE cleanup error: ${e}`); }
54
+ // Sibling worktrees (#2022): the census's ABANDONED rows anywhere; detached, and not gated on PROJECT_ROOT.
55
+ try { (await import('../scripts/worktree-sweep.ts')).spawnSweep(STALE_LOG); } catch (e) { log(`WORKTREE sweep error: ${e}`); }
54
56
 
55
- // Scratch cleanup — test fixtures the suite leaked into the repo root (#437).
56
- // Reported alongside worktree cleanup deliberately: both are resources created
57
- // by tooling that only get cleaned on the happy path, and 34 of these
58
- // accumulated because each one had to be found by eye.
57
+ // Scratch cleanup — test fixtures the suite leaked into the repo root (#437):
58
+ // tooling cleans them only on the happy path; 34 accumulated, found by eye.
59
59
  if (PROJECT_ROOT) try {
60
60
  const { cleanupScratchDirs } = await import('../lib/scratch-cleanup.ts');
61
61
  // Gated on the directory the allowlist is derived FROM, the way the
@@ -5,9 +5,9 @@
5
5
  * SC-370 (HOOK-ARCHITECTURE-SPEC): Hook SC traceability
6
6
  * SC-371 (HOOK-ARCHITECTURE-SPEC): No hook exceeds 150 lines
7
7
  *
8
- * TWO independent gates on one chokepoint — `gh issue create` reaching Bash.
9
- * Both decisions live in lib/ and not here (#365, HOOK-ARCHITECTURE-SPEC:
10
- * hooks are thin triggers).
8
+ * TWO independent gates on one chokepoint — a filing reaching Bash, in any
9
+ * spelling `createsIssue` knows (#1759). Both decisions live in lib/ and
10
+ * not here (#365, HOOK-ARCHITECTURE-SPEC: hooks are thin triggers).
11
11
  *
12
12
  * 1. **The VERIFY-phase lock** (#443, #365). Workflow discipline: during
13
13
  * VERIFY, use verifyBlockers[] instead. Waived by the override labels in
@@ -49,8 +49,9 @@ export function findWorkflowForIssue(issueNum?: string, phases?: string[], repo?
49
49
  // Blast radius, since an earlier version of this comment got it wrong:
50
50
  // `CommitEnforcement.hook.ts` is the ONLY hook importing this module.
51
51
  // `IssueCloseGuard` and `AutoVerifyGate` use `findWorkflowState` from
52
- // `./utils`, a third implementation of this scan that is still
53
- // unfiltered — #1668. Fixing this file does not reach them.
52
+ // `./utils`, a third implementation of this scan — fixing this file does
53
+ // not reach them. #1668 filtered that one too, and added a census over
54
+ // every work-dir scan site so a fourth copy cannot ship unfiltered.
54
55
  const dirs = readdirSync(RUNGATE_WORK_DIR, { withFileTypes: true })
55
56
  .filter(d => d.isDirectory() && isRunDirectory(d.name));
56
57
 
@@ -79,10 +79,22 @@ export function getMemoryDir(): string {
79
79
 
80
80
  /**
81
81
  * Get the PAI work directory (expanded)
82
- * Priority: RUNGATE_WORK_DIR env var (expanded) → ~/.rungate
82
+ * Priority: RUNGATE_WORK_DIR → PAI_WORK_DIR → ~/.rungate, each expanded.
83
+ *
84
+ * `PAI_WORK_DIR` is the fallback six siblings already spell — VerifyPhaseLock,
85
+ * StaleTTLCleanup, AgentVerdictCapture, findWorkflow, issue-filing-gate and
86
+ * local-review-rounds — and this function did not, so a tree setting only
87
+ * `PAI_WORK_DIR` sent these callers to `~/.rungate` while the rest of the
88
+ * harness used the override (#1668).
89
+ *
90
+ * This is the ONE binding for the question. `hooks/lib/utils.ts` used to
91
+ * declare a second one as `join(RUNGATE_WORK_DIR || HOME, '.rungate')` — the
92
+ * `join` outside the `||`, so an absolute override resolved to
93
+ * `$RUNGATE_WORK_DIR/.rungate` — and it now re-exports this instead of
94
+ * carrying a ninth copy of the expression.
83
95
  */
84
96
  export function getWorkDir(): string {
85
- const envWorkDir = process.env.RUNGATE_WORK_DIR;
97
+ const envWorkDir = process.env.RUNGATE_WORK_DIR || process.env.PAI_WORK_DIR;
86
98
 
87
99
  if (envWorkDir) {
88
100
  return expandPath(envWorkDir);
@@ -1,7 +1,19 @@
1
1
  import { readdirSync, readFileSync, existsSync, statSync } from 'fs';
2
2
  import { join } from 'path';
3
+ import { isRunDirectory } from '../../lib/active-workflow';
3
4
 
4
- export const WORK_DIR = join(process.env.RUNGATE_WORK_DIR || process.env.HOME!, '.rungate');
5
+ // One binding for "where is the work directory", in `./paths` (#1668). This
6
+ // file used to declare a second one as
7
+ // `join(RUNGATE_WORK_DIR || HOME, '.rungate')`, with the `join` outside the
8
+ // `||`: an absolute override resolved to `$RUNGATE_WORK_DIR/.rungate`, and a
9
+ // ship run and the test harness both set that variable, so in exactly those
10
+ // conditions IssueCloseGuard and AutoVerifyGate read a directory that does not
11
+ // exist and found no live workflow at all. It was also missing the
12
+ // `PAI_WORK_DIR` fallback that six siblings spell.
13
+ // Imported as well as re-exported: `findWorkflowState` below reads it, and a
14
+ // bare `export ... from` would not bind it in this module's scope.
15
+ import { WORK_DIR } from './paths';
16
+ export { WORK_DIR };
5
17
  export const HARNESS_ROOT = process.env.HARNESS_ROOT || join(process.env.HOME!, 'Projects', 'rungate');
6
18
 
7
19
  export interface HookInput {
@@ -65,11 +77,19 @@ export function findWorkflowState(issueNum?: string, phases?: string[]): Workflo
65
77
  } catch {}
66
78
  };
67
79
 
80
+ // BOTH levels filtered (#1648, #1668). A hidden entry is the work dir's own
81
+ // bookkeeping, not a run: `.archive/<slug>/workflow-state.json` is a
82
+ // finished run, and being written last it is the newest file, so an
83
+ // unfiltered scan hands it to every caller here. Filtering only the outer
84
+ // level leaves the same defect one level deeper — a hidden directory INSIDE
85
+ // a live run — and that is one filtered reading beside one unfiltered
86
+ // reading of the same question, which no behavioural case can tell apart
87
+ // while the outer one is right.
68
88
  try {
69
- for (const d of readdirSync(WORK_DIR, { withFileTypes: true }).filter(d => d.isDirectory())) {
89
+ for (const d of readdirSync(WORK_DIR, { withFileTypes: true }).filter(d => d.isDirectory() && isRunDirectory(d.name))) {
70
90
  collect(join(WORK_DIR, d.name, 'workflow-state.json'), d.name);
71
91
  try {
72
- for (const sd of readdirSync(join(WORK_DIR, d.name), { withFileTypes: true }).filter(sd => sd.isDirectory()))
92
+ for (const sd of readdirSync(join(WORK_DIR, d.name), { withFileTypes: true }).filter(sd => sd.isDirectory() && isRunDirectory(sd.name)))
73
93
  collect(join(WORK_DIR, d.name, sd.name, 'workflow-state.json'), `${d.name}/${sd.name}`);
74
94
  } catch {}
75
95
  }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The population the active milestone is read over: every OPEN issue in the
3
+ * repository (#2037).
4
+ *
5
+ * `activeMilestone` in `lib/board-ready-rule.ts` decides the focus; this
6
+ * module only reads what it decides over. `scripts/board-ready.ts` already
7
+ * read the whole repository (its labels pass), `scripts/work-status.ts` did
8
+ * too, and `scripts/board-mirror.ts` read the open cards on the project
9
+ * board instead — so an earlier-phase issue that never reached the board (a
10
+ * failed intake run) moved the hand-run writer's focus and nobody else's.
11
+ *
12
+ * ## A partial read is UNMEASURED, never a short list
13
+ *
14
+ * A shorter list is exactly what a repository with fewer open issues
15
+ * produces, and fewer open issues in a low phase moves the focus FORWARD. So
16
+ * any page that cannot be read — no repository, no issues connection, a
17
+ * `pageInfo` that cannot say whether more exist, a thrown request — returns
18
+ * `null`, and the caller does not compute a focus from it.
19
+ */
20
+ import { nextCursor } from "./graphql-cursor";
21
+
22
+ export const OPEN_MILESTONES_QUERY = `query($o:String!,$n:String!,$c:String){repository(owner:$o,name:$n){issues(first:100,after:$c,states:[OPEN]){pageInfo{hasNextPage endCursor} nodes{milestone{title}}}}}`;
23
+
24
+ export type GraphQlFn = (query: string, vars: Record<string, unknown>) => Promise<any>;
25
+
26
+ export async function readOpenIssueMilestones(
27
+ gql: GraphQlFn,
28
+ owner: string,
29
+ name: string,
30
+ ): Promise<{ milestone: string | null }[] | null> {
31
+ const out: { milestone: string | null }[] = [];
32
+ let c: string | null = null;
33
+ try {
34
+ do {
35
+ const d = await gql(OPEN_MILESTONES_QUERY, { o: owner, n: name, c });
36
+ // No `if (!page) return null` guard: a missing repository or
37
+ // connection throws on the next line and the `catch` returns the same
38
+ // `null`. Two guards for one answer is a guard no test can see die
39
+ // (`.claude/rules/checks-must-be-able-to-fail.md`).
40
+ const page = d?.repository?.issues;
41
+ for (const i of page.nodes) out.push({ milestone: i?.milestone?.title ?? null });
42
+ const step = nextCursor(page.pageInfo);
43
+ if (step.kind === "unreadable") return null;
44
+ c = step.kind === "more" ? step.cursor : null;
45
+ } while (c);
46
+ } catch {
47
+ return null;
48
+ }
49
+ return out;
50
+ }
@@ -585,6 +585,105 @@ export function carryKey(finding: unknown, lineText?: unknown): string | null {
585
585
  return `${file}\u0000${anchor}\u0000${summary}`;
586
586
  }
587
587
 
588
+ /**
589
+ * THE SAME KEY WITH THE WORDING DROPPED — `file \0 t:<text>` (#1168).
590
+ *
591
+ * @identity file+text — `file` and the TEXT of the cited line, and nothing
592
+ * else. It answers a THIRD question, which is why it has a third name: not
593
+ * *is this the same finding* (`carryKey`, which adds the summary) and not
594
+ * *is this worth adjudicating* (`advisoryKey`), but **is this the same PLACE
595
+ * an earlier round already objected to**. It is derived from a `carryKey`
596
+ * string rather than from a finding, so the two cannot drift apart: there is
597
+ * no second parse of a finding here to disagree with the first.
598
+ *
599
+ * `carryKey` ends in the summary, and `suppressRepeats`' docblock below
600
+ * states what that buys: *a finding whose summary changed is not [a repeat]*.
601
+ * That was a deliberate trade — protect a genuinely different finding that
602
+ * happens to sit at a line an earlier round cited — and the measurement says
603
+ * it costs everything to buy nothing.
604
+ *
605
+ * Read on the last 25 merged pull requests of this repository, 25 round-2+
606
+ * findings: **0 repeats the full key could see, and 8 real ones**. Every one
607
+ * of the eight was the same defect restated in different words, every one
608
+ * confirmed by reading the pair, and **zero** were the case the summary
609
+ * component protects. The reviewer rewords on essentially every re-raise, so
610
+ * the population the full key can match is empty by construction — the `0` is
611
+ * the shape of the key, not the state of the repo.
612
+ *
613
+ * ## Only a TEXT anchor, and that is the whole safety argument
614
+ *
615
+ * `carryKey` falls back to `n:<line>` when the caller could not read the
616
+ * line. Two unrelated findings at line 4 of one file share that namespace and
617
+ * nothing else, so matching on it would suppress across completely different
618
+ * defects. This returns `null` for `n:` and the caller suppresses nothing —
619
+ * which also keeps the asymmetry `checkoutLineText`'s docblock describes from
620
+ * turning into over-suppression when a checkout cannot be read.
621
+ *
622
+ * ## A TEXT anchor is not automatically a DISTINCTIVE one
623
+ *
624
+ * A line reading `}` or `return null;` keys the same anchor wherever it
625
+ * recurs in its file, so two findings at two different occurrences collide
626
+ * here and this cannot tell them apart. That screen is the CALLER's, not
627
+ * this function's — it needs the file, and this takes a string. See
628
+ * `checkoutLineReader` and the uniqueness condition in
629
+ * `lib/ai-review-suppression.ts`.
630
+ *
631
+ * Measured on the same 25 pull requests, 60 findings carrying a text anchor:
632
+ * **5 — 8.3% — cite a line whose text recurs in its own file.** A minimum
633
+ * anchor LENGTH does not separate them and was the fix not taken: four of the
634
+ * five normalise to over twenty characters and one to forty-five
635
+ * (`for (const t of tokenize(heredocView(cmd))) {`). Counting occurrences is
636
+ * the only screen the reading supports.
637
+ *
638
+ * ## The direction this is allowed to be wrong in has CHANGED, deliberately
639
+ *
640
+ * Everything else here errs toward reporting a repeat twice. This errs toward
641
+ * calling two differently-worded findings one finding, which can be wrong,
642
+ * which is why the caller must report a DIFFERENT reason for it: a reader has
643
+ * to be able to tell a verbatim re-post from a judgement. The judgement is
644
+ * the only one of the two that can be appealed.
645
+ *
646
+ * Exported and total so there is one binding to mutate, and so the battery
647
+ * can drive it without a thread list.
648
+ */
649
+ export function anchorOnlyKey(key: string | null): string | null {
650
+ if (typeof key !== "string") return null;
651
+ const parts = key.split("\u0000");
652
+ if (parts.length !== 3) return null;
653
+ const [file, anchor] = parts as [string, string, string];
654
+ if (!anchor.startsWith("t:") || anchor === "t:") return null;
655
+ if (file === "") return null;
656
+ return `${file}\u0000${anchor}`;
657
+ }
658
+
659
+ /**
660
+ * The normalised TEXT out of an anchor key, so the distinctiveness screen
661
+ * counts occurrences of the same string the key was built from (#1861).
662
+ *
663
+ * Not an identity and never used as one — it returns a component, and that
664
+ * is why it is not named `…Key`. It exists so the caller does not re-derive
665
+ * the text from the finding: a second derivation is a second decider, and the
666
+ * two would agree until one of them was mutated, at which point the other
667
+ * holds every case up. `null` for anything `anchorOnlyKey` would reject.
668
+ */
669
+ export function anchorTextOf(anchorKey: string | null): string | null {
670
+ if (typeof anchorKey !== "string") return null;
671
+ const parts = anchorKey.split("\u0000");
672
+ if (parts.length !== 2) return null;
673
+ const anchor = parts[1] as string;
674
+ if (!anchor.startsWith("t:") || anchor === "t:") return null;
675
+ return anchor.slice(2);
676
+ }
677
+
678
+ /**
679
+ * The normalisation `carryKey` applies to a cited line, exported so a reader
680
+ * counting occurrences of that line compares like with like. One binding; a
681
+ * private copy in the reader would be the two-deciders fault again.
682
+ */
683
+ export function normaliseLineText(v: unknown): string {
684
+ return normalise(v);
685
+ }
686
+
588
687
  export interface SuppressionReading {
589
688
  /** Findings this round may report. */
590
689
  kept: ReviewFinding[];