rungate 0.8.14 → 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 (72) hide show
  1. package/README.md +105 -5
  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/lib/findWorkflow.ts +3 -2
  8. package/hooks/lib/paths.ts +14 -2
  9. package/hooks/lib/utils.ts +23 -3
  10. package/lib/active-milestone.ts +50 -0
  11. package/lib/bash-write-guard.ts +347 -18
  12. package/lib/board-flow.ts +45 -0
  13. package/lib/board-lane-health.ts +198 -1
  14. package/lib/board-mirror.ts +83 -4
  15. package/lib/board-ready-fanout.ts +242 -2
  16. package/lib/board-ready-rule.ts +742 -76
  17. package/lib/bun-version.ts +36 -0
  18. package/lib/cli-commands.ts +75 -4
  19. package/lib/closing-reference-audit.ts +307 -6
  20. package/lib/config-loader.ts +254 -25
  21. package/lib/config-readers.ts +170 -10
  22. package/lib/config-trackable.ts +96 -57
  23. package/lib/conformity.ts +26 -5
  24. package/lib/create-sc.ts +25 -2
  25. package/lib/derived-spec.ts +21 -9
  26. package/lib/filing-plan.ts +47 -21
  27. package/lib/finding-jury.ts +43 -4
  28. package/lib/finding-promotion.ts +1123 -0
  29. package/lib/git-isolation.ts +137 -1
  30. package/lib/github-api-base.ts +66 -0
  31. package/lib/github.ts +115 -9
  32. package/lib/hook-scopes.ts +78 -0
  33. package/lib/issue-decomposition.ts +91 -4
  34. package/lib/issue-extraction.ts +9 -7
  35. package/lib/issue-file-overlap.ts +42 -9
  36. package/lib/issue-filing-gate.ts +938 -46
  37. package/lib/issue-repair.ts +77 -0
  38. package/lib/issue-shape.ts +8 -5
  39. package/lib/live-issues.ts +31 -2
  40. package/lib/local-work.ts +423 -0
  41. package/lib/markdown-fence.ts +134 -0
  42. package/lib/milestone-title.ts +46 -0
  43. package/lib/scaffold/ai-review-findings.ts +139 -2
  44. package/lib/scaffold/ai-review-step.ts +30 -4
  45. package/lib/scaffold/ai-review-unmeasured-workflow.ts +3 -0
  46. package/lib/scaffold/steps.ts +115 -9
  47. package/lib/spec-deps.ts +24 -3
  48. package/lib/spec-placement.ts +96 -14
  49. package/lib/spec-registry.ts +75 -16
  50. package/lib/spec-source.ts +609 -0
  51. package/lib/spec-write-sweep.ts +4 -0
  52. package/lib/stage-ladder.ts +868 -0
  53. package/lib/state-claim-readings.ts +252 -0
  54. package/lib/success-doc.ts +7 -6
  55. package/lib/test-command-positions.ts +135 -1
  56. package/lib/work-status.ts +210 -82
  57. package/lib/worktree-repo.ts +14 -2
  58. package/package.json +7 -1
  59. package/scripts/audit-closing-references.ts +330 -0
  60. package/scripts/audit-specs.ts +59 -103
  61. package/scripts/board-conformance.ts +747 -40
  62. package/scripts/board-mirror.ts +408 -40
  63. package/scripts/board-ready.ts +979 -0
  64. package/scripts/board-snapshot.ts +464 -12
  65. package/scripts/claim-files.ts +578 -0
  66. package/scripts/criterion-inventory.ts +526 -50
  67. package/scripts/finding-promotion.ts +547 -0
  68. package/scripts/plan-issues.ts +279 -40
  69. package/scripts/plan-spec.ts +49 -25
  70. package/scripts/sync-sc-status.ts +147 -7
  71. package/scripts/worktree-census.ts +958 -0
  72. package/scripts/worktree-sweep.ts +269 -0
package/README.md CHANGED
@@ -16,11 +16,103 @@ issue → SCOPE → BUILD → VERIFY → CLOSE → SHIP_PASSED | SHIP_FAILED
16
16
 
17
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
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.
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
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
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
22
  - **Workflows** for `ship`, `prove` (reproduce and attest a fix), `verify`, `batch-ship`, `ship-and-heal` and multi-agent `council` decisions.
23
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
+
24
116
  ## What "done" means
25
117
 
26
118
  The project measures itself against falsifiable claims in [`SUCCESS.md`](SUCCESS.md). Each claim has a named check:
@@ -37,8 +129,9 @@ A green test suite, a passing gate and a merged PR don't count as progress unles
37
129
 
38
130
  ## Where it stands
39
131
 
40
- - **Working:** the ship pipeline and gates, the spec tooling, AI-review adjudication, scaffolding, and release automation to npm. About 1,500 commits and 900 merged PRs, most shipped through the harness itself. Since 2026-10-19 the repo has been shipping directly while RunGate is stabilised.
41
- - **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 issue intake to be governed so every issue names the criterion it serves.
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)).
42
135
  - **Next:** a full run on a consumer project with a different config layout (claim 5). Until that is done, consumer support is unproven.
43
136
 
44
137
  Live session-by-session state is in [`PROJECT-STATE.md`](PROJECT-STATE.md).
@@ -52,22 +145,28 @@ Requires [Bun](https://bun.sh).
52
145
  bunx rungate scaffold . # agent files, rules and conformity suite
53
146
  bunx rungate create-success # seed SUCCESS.md: what the project is for
54
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
55
150
  bunx rungate board-mirror --project <id> # show the spec's criteria on the project board
56
151
  bunx rungate board-conformance # does the board match the spec? non-zero if not
57
152
  bunx rungate --help # every command and its arguments
58
153
  ```
59
154
 
60
- Projects are configured in `.claude/rungate.json` (project slug, code and issue repos, dev/test/prod commands). See [`HARNESS.md`](HARNESS.md) for the schema and workflow entry points.
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.
61
158
 
62
159
  ## Repository layout
63
160
 
64
161
  | Path | What lives there |
65
162
  |---|---|
66
163
  | `bin/`, `lib/` | CLI and core library |
164
+ | `scripts/` | The commands the CLI and the workflows run, plus `work-status.ts` |
67
165
  | `gates/` | Gate runner, ship orchestrator and gate tests |
68
166
  | `workflows/` | `ship`, `prove`, `verify`, `council` and friends |
167
+ | `.github/workflows/` | CI, AI review, `closing-references`, and the board workflows |
69
168
  | `specs/` | Specs that govern the harness's own behaviour |
70
- | `docs/adr/` | Architecture decisions |
169
+ | `docs/adr/` | Architecture decisions, and `TEMPLATE.md` for new ones |
71
170
  | `templates/`, `prompts/` | What `scaffold` writes and the agents read |
72
171
  | `test/` | The suite. Run with `bun scripts/test-clean-env.ts` |
73
172
 
@@ -77,6 +176,7 @@ Projects are configured in `.claude/rungate.json` (project slug, code and issue
77
176
  bun install
78
177
  bun scripts/test-clean-env.ts # the suite in a clean environment (trust this one)
79
178
  bun test <file> # a single file
179
+ bun scripts/work-status.ts # lanes, Ready and the plan, on one screen
80
180
  ```
81
181
 
82
182
  Start with [`AGENTS.md`](AGENTS.md) and [`CODE-MAP.md`](CODE-MAP.md).
package/gates/.gate-salt CHANGED
@@ -1 +1 @@
1
- c12fa16b484d2832d774f0c27f2e81e29259ed31eb32ca4332faa9ed6b42face
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
@@ -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
+ }