rungate 0.8.16 → 0.8.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/gates/.gate-salt CHANGED
@@ -1 +1 @@
1
- eae3d899be4a8464ebf582bcba421f8e6660953f898adc3e5967ce30abf41a5b
1
+ 1267e343f5b54c7a006014564da4b6b404022b6f2934457d083b0f37734afe18
@@ -125,6 +125,14 @@ export interface ProtectionFacts {
125
125
  * excuse `strict: true`.
126
126
  */
127
127
  mergeQueueEnabled: boolean | null;
128
+ /**
129
+ * Which of the three states the branch is in, when the probe established it
130
+ * (#2154). Only `required-checks` accepts a POST to `…/contexts`; an
131
+ * unprotected branch needs the protection created, and a protected one
132
+ * with no required checks cannot take that POST either. Absent when the
133
+ * reading was not taken.
134
+ */
135
+ statusChecks?: "unprotected" | "no-required-checks" | "required-checks";
128
136
  /**
129
137
  * `required_conversation_resolution`, or null when the payload said nothing
130
138
  * either way — CRC-C3, #1650.
@@ -541,7 +549,7 @@ export const githubProtectionProbe: ProtectionProbe = async (slug) => {
541
549
  // Reading it as `null` would call that unestablished when it is the one
542
550
  // case the endpoint lets us establish without admin (#1650).
543
551
  if (!isProtected) {
544
- return { slug, branch, strict: false, ownerType, contexts: [], mergeQueueEnabled: null, conversationResolution: false, unreadable: null };
552
+ return { slug, branch, strict: false, ownerType, contexts: [], mergeQueueEnabled: null, conversationResolution: false, unreadable: null, statusChecks: "unprotected" };
545
553
  }
546
554
 
547
555
  try {
@@ -582,7 +590,7 @@ export function protectionFactsFromPayload(
582
590
  // No required_status_checks block: protection exists but requires no
583
591
  // checks, so there is no strictness and nothing to be out of date against.
584
592
  if (!rsc || typeof rsc !== "object") {
585
- return { slug, branch, strict: false, ownerType, contexts: [], mergeQueueEnabled: mergeQueueFrom(d), conversationResolution: conversationResolutionFrom(d), unreadable: null };
593
+ return { slug, branch, strict: false, ownerType, contexts: [], mergeQueueEnabled: mergeQueueFrom(d), conversationResolution: conversationResolutionFrom(d), unreadable: null, statusChecks: "no-required-checks" };
586
594
  }
587
595
 
588
596
  const strict = typeof rsc.strict === "boolean" ? rsc.strict : null;
@@ -596,7 +604,7 @@ export function protectionFactsFromPayload(
596
604
  (c: unknown): c is string => typeof c === "string" && c.length > 0,
597
605
  );
598
606
 
599
- return { slug, branch, strict, ownerType, contexts, mergeQueueEnabled: mergeQueueFrom(d), conversationResolution: conversationResolutionFrom(d), unreadable: null };
607
+ return { slug, branch, strict, ownerType, contexts, mergeQueueEnabled: mergeQueueFrom(d), conversationResolution: conversationResolutionFrom(d), unreadable: null, statusChecks: "required-checks" };
600
608
  }
601
609
 
602
610
  function mergeQueueFrom(d: Record<string, any>): boolean | null {
@@ -270,8 +270,17 @@ export const CLI_COMMANDS: Record<string, CliCommand> = {
270
270
  script: "scripts/board-ready.ts",
271
271
  summary: "Move the work a closed blocker freed, or the top of the backlog, into the board's Ready lane",
272
272
  usage:
273
- "rungate board-ready --repo <owner/name> --project <node-id> [--closed-issue <n>] [--top-up] " +
274
- "[--moving-issue <n>] [--actor <login>] [--write] (at least one of --closed-issue, --top-up)",
273
+ "rungate board-ready --repo <owner/name> [--project <node-id>] [--project-root <dir>] [--closed-issue <n>] " +
274
+ "[--top-up] [--moving-issue <n>] [--actor <login>] [--write] (at least one of --closed-issue, --top-up; " +
275
+ "--project defaults to board.id in the rungate config)",
276
+ },
277
+ // #2173. For a generated workflow that works in shell (`board-intake.yml`,
278
+ // #2166) and so cannot read the config through the loader itself. No
279
+ // `projectRootFlag`: it reads `process.cwd()`, which the child inherits.
280
+ "board-id": {
281
+ script: "scripts/board-id.ts",
282
+ summary: "Print the board's node id from config",
283
+ usage: "rungate board-id [--project-root <dir>] (UNMEASURED and exit 2 when the config names no board)",
275
284
  },
276
285
  // Reads a `gh pr view`-shaped payload on stdin, which the dispatcher passes
277
286
  // through (`stdio: "inherit"`), or `--fixture` offline.
@@ -11,6 +11,7 @@ import { existsSync, readFileSync } from "fs";
11
11
  import { join } from "path";
12
12
  import type { ProjectScan } from "./types";
13
13
  import { OWNED_FILES, ownedFilesTable } from "../scaffold/owned-files";
14
+ import { ALIGNMENT_PROCESS_RULE_FILE, alignmentProcessRule } from "../scaffold/process-rules";
14
15
  import { commandRoutingTable } from "../cli-commands";
15
16
  import { isHarnessItself } from "../harness-identity";
16
17
  import { typecheckDecision } from "../typescript-project";
@@ -339,6 +340,7 @@ description: Shared behavioral principles for all agents working in this project
339
340
  - Skip ACs without rationale
340
341
  - Commit secrets or credentials
341
342
  - Spawn subagents for single-file tasks — do the work directly
343
+ - Hand-patch what a process tool's \`--write\` left red — that is a tool defect; fix the tool
342
344
  `,
343
345
  });
344
346
 
@@ -433,14 +435,21 @@ description: Every command the rungate CLI exposes in this project, generated fr
433
435
 
434
436
  ## Command Routing
435
437
 
436
- Generated from the CLI's own command registry, so it cannot list a subset.
437
- Run one as \`${cliPrefix} <command>\`.
438
- \`${cliPrefix} --help\` prints each command's own arguments.
438
+ Generated from the CLI's command registry. Run one as
439
+ \`${cliPrefix} <command>\`; \`--help\` prints its arguments.
439
440
 
440
441
  ${commandRoutingTable()}
441
442
  `,
442
443
  });
443
444
 
445
+ // #2049, ADR-014 decision 4: the four-step process, from the one source
446
+ // this repository's own rule 9 is checked against. Scoped only here, where
447
+ // AGENTS.md already carries rule 9 at launch — `lib/scaffold/process-rules.ts`.
448
+ rules.push({
449
+ filename: ALIGNMENT_PROCESS_RULE_FILE,
450
+ content: alignmentProcessRule({ scoped: isHarnessItself(scan.root) }),
451
+ });
452
+
444
453
  rules.push({
445
454
  filename: "harness-managed.md",
446
455
  content: `---
@@ -636,6 +645,17 @@ nobody can interpret becomes a number nobody lowers.
636
645
  `,
637
646
  });
638
647
 
648
+ // The filing gate runs from this repository's own hooks and no consumer's
649
+ // defaults install it, so the line would name machinery a consumer lacks
650
+ // (review of #2155).
651
+ const filingLine = isHarnessItself(scan.root)
652
+ ? `
653
+ **Filing:** \`gh issue create\` without \`--repo\`, from a session launched in
654
+ the project root. The filing gate reads its config from the launch directory,
655
+ and a \`--repo\` filing gets no queue raise.
656
+ `
657
+ : "";
658
+
639
659
  rules.push({
640
660
  filename: "parallel-sessions.md",
641
661
  content: `---
@@ -652,7 +672,7 @@ gh issue edit <N> --add-assignee @me # then start
652
672
  The issue tracker is the claim registry. It is the only place every session can
653
673
  see, so a claim that lives anywhere else — a message, another session's
654
674
  context, a branch nobody pushed — is not a claim.
655
-
675
+ ${filingLine}
656
676
  **Why this is a rule and not a nicety:** an issue reading "open" while the work
657
677
  is finished is indistinguishable from an issue nobody has started. That is not
658
678
  hypothetical. On 2026-10-06 one session described #70 as "unclaimed, small,
@@ -666,6 +686,9 @@ collided with a branch they could not see.
666
686
  When the work is done and CI is green: push, open a PR, merge it. Do not hold a
667
687
  finished branch pending approval, and do not ask whether to push.
668
688
 
689
+ Wait on checks with \`gh pr checks <N> --watch --fail-fast\`: the first red
690
+ ends the wait, not the whole suite.
691
+
669
692
  **Why:** unpushed finished work is invisible. It makes the tracker lie, it
670
693
  makes other sessions duplicate effort, and it is lost entirely if the session
671
694
  or the worktree goes away. Review happens on the PR, where it is durable and
package/lib/github.ts CHANGED
@@ -111,6 +111,15 @@ export interface GitHubClient {
111
111
  */
112
112
  listForRef: (params: { owner: string; repo: string; ref: string; per_page?: number }) => Promise<{ data: { total_count: number; check_runs: any[] } }>;
113
113
  };
114
+ /**
115
+ * Repository Actions settings, read by `lib/scaffold/human-steps.ts`
116
+ * (#2051). Both 404 when the secret or variable is not set, which is a
117
+ * reading; anything else is not.
118
+ */
119
+ actions: {
120
+ getRepoSecret: (params: { owner: string; repo: string; secret_name: string }) => Promise<{ data: any }>;
121
+ getRepoVariable: (params: { owner: string; repo: string; name: string }) => Promise<{ data: { value?: string } }>;
122
+ };
114
123
  };
115
124
  /**
116
125
  * The GraphQL endpoint, for the handful of operations REST does not expose.
@@ -0,0 +1,219 @@
1
+ /**
2
+ * `.github/workflows/adr-accepted.yml`, generated — #2046, ADR-014 row 3,
3
+ * SC-2744.
4
+ *
5
+ * Merging an ADR whose status changes to accepted places its plan on the board
6
+ * with no command typed by hand (SC-2738, ADR-013 rule 9 step 3). The file was
7
+ * hand-written and caller-owned, and it ran `bun scripts/…` — paths a consumer
8
+ * does not have. Rule 9 is every consumer's process, so the scaffold now
9
+ * writes it, and this repository's copy is the generated one (ADR-014
10
+ * decision 1).
11
+ *
12
+ * ## It calls the published CLI
13
+ *
14
+ * A consumer has `node_modules/rungate`, not `scripts/` (ADR-014 decision 2),
15
+ * so every step runs `bunx rungate@<version> <command>`, at the generating
16
+ * version — the same reading every other `bunx` pin takes.
17
+ *
18
+ * ## The engine's spec and family are read at scaffold time
19
+ *
20
+ * The hand-written file read `board.engineSpec` and `board.milestonePrefix`
21
+ * at run time by importing `./lib/config-readers`, which a consumer does not
22
+ * have either. They are read here instead, through the one loader, and
23
+ * written into the job's `env:`. A config change is a re-scaffold, and the
24
+ * workflow drift check sees a committed file that no longer matches.
25
+ *
26
+ * A value that is unset, or one that would be read as something other than
27
+ * itself — a newline, or an Actions expression — is not written. The
28
+ * acceptance step then refuses UNMEASURED, naming the key and why: a skipped
29
+ * step reads as satisfied, and a missing family is not "nothing to place".
30
+ */
31
+
32
+ /** The file this module generates, under `.github/workflows/`. */
33
+ export const ADR_ACCEPTED_WORKFLOW_FILE = "adr-accepted.yml";
34
+
35
+ /** The one job in it. */
36
+ export const ADR_ACCEPTED_JOB = "place-the-plan";
37
+
38
+ /**
39
+ * The five commands, in the order each needs the one before it, after the
40
+ * acceptance read (`plan-issues --accepted-since`). Each must be registered in
41
+ * `lib/cli-commands.ts`, or the workflow calls a command `bin/rungate.ts`
42
+ * refuses (#675's defect).
43
+ */
44
+ export const ADR_ACCEPTED_COMMANDS = ["plan-issues", "plan-spec", "plan-deps", "board-mirror", "board-ready"] as const;
45
+
46
+ /** One engine input as the generator will write it, or why it will not. */
47
+ export type BoardInput = { value: string } | { value: null; why: string };
48
+
49
+ /**
50
+ * Whether `raw` can be written into the job's `env:` as itself. A newline
51
+ * could forge a second key wherever a step echoes it, and `${{` is evaluated
52
+ * by Actions before the shell sees it — either way the step would read
53
+ * something the config does not say.
54
+ */
55
+ export function boardInput(key: string, raw: string | null): BoardInput {
56
+ if (raw === null) return { value: null, why: `board.${key} is not set` };
57
+ if (/[\r\n]/.test(raw)) return { value: null, why: `board.${key} contains a newline` };
58
+ if (raw.includes("${{")) return { value: null, why: `board.${key} contains an Actions expression marker, a dollar sign and two braces` };
59
+ return { value: raw };
60
+ }
61
+
62
+ export interface AdrAcceptedWorkflowOptions {
63
+ /** The `runs-on:` value, already JSON-quoted by the caller. */
64
+ runsOn: string;
65
+ /** The pinned `actions/checkout` reference. */
66
+ checkout: string;
67
+ /** The pinned `oven-sh/setup-bun` reference. */
68
+ setupBun: string;
69
+ /** The `with:` body of that step, at ten spaces — the project's single bun declaration (#622). */
70
+ setupBunWith: string;
71
+ /** The step's `env:` block, from `setupBunEnv` (#2039). */
72
+ setupBunEnv: string;
73
+ /** The published harness version every step runs through `bunx`. */
74
+ version: string;
75
+ /** `board.engineSpec`, read through `readBoardInputs`. */
76
+ engineSpec: string | null;
77
+ /** `board.milestonePrefix`, read through `readBoardInputs`. */
78
+ milestonePrefix: string | null;
79
+ }
80
+
81
+ /** The whole `adr-accepted.yml` body. */
82
+ export function buildAdrAcceptedWorkflow(opts: AdrAcceptedWorkflowOptions): string {
83
+ const spec = boardInput("engineSpec", opts.engineSpec);
84
+ const prefix = boardInput("milestonePrefix", opts.milestonePrefix);
85
+ const missing = [spec, prefix].flatMap(i => (i.value === null ? [i.why] : []));
86
+ const cli = `bunx rungate@${opts.version}`;
87
+ // JSON is a YAML double-quoted scalar, so a quote or backslash in a value
88
+ // stays inside it.
89
+ const envValue = (i: BoardInput) => JSON.stringify(i.value ?? "");
90
+ const refusal =
91
+ missing.length === 0
92
+ ? ""
93
+ : `
94
+ echo "::error::UNMEASURED — ${missing.join("; ")}, so this push's plan has no milestones to land in. Nothing was written. Set board.engineSpec and board.milestonePrefix in the rungate config and re-run rungate scaffold."
95
+ exit 1`;
96
+
97
+ return `# Managed by rungate — do not edit. Set board.engineSpec and board.milestonePrefix
98
+ # in .claude/rungate/config.json and re-run \`rungate scaffold\`.
99
+ #
100
+ # SC-2738 (ADR-013 row 5): merging an ADR whose status changes to accepted
101
+ # places its plan on the board, with no command typed by hand. Generated since
102
+ # #2046 (ADR-014 row 3), so a consumer gets step 3 of the four-step process and
103
+ # this repository's copy is the generated one.
104
+ #
105
+ # The five commands, in the order each needs the one before it:
106
+ #
107
+ # plan-spec the engine spec's milestones, so every row's milestone exists
108
+ # plan-issues the ADR's Decomposition rows become issues, with blocked-by
109
+ # plan-deps the phase-order links between milestones
110
+ # board-mirror the Criteria column on the board
111
+ # board-ready a Ready top-up, because issues created with GITHUB_TOKEN
112
+ # fire no \`issues: opened\` run of board-ready.yml
113
+ #
114
+ # Every one is idempotent, so a re-run writes only what is missing. An edit to
115
+ # an ADR that was ALREADY accepted lists nothing and every later step is skipped.
116
+ #
117
+ # CREDENTIALS, SPLIT BY STEP. The issue, milestone and edge writes use the
118
+ # job's own GITHUB_TOKEN, passed as GITHUB_TOKEN because plan-issues drops
119
+ # GH_TOKEN. RUNGATE_PROJECT_TOKEN reaches only the two board steps, in their
120
+ # own env (#1761). The first \`bunx\` runs in the acceptance step, which holds
121
+ # no token, so the package is fetched before any step that holds the PAT.
122
+ name: ADR accepted — place its plan on the board
123
+
124
+ on:
125
+ push:
126
+ branches: [main]
127
+ paths: ["docs/adr/**"]
128
+
129
+ permissions:
130
+ contents: read
131
+ # Issues, milestones and blocked-by edges. Nothing else this job writes is
132
+ # reachable with GITHUB_TOKEN.
133
+ issues: write
134
+
135
+ # Two merges in quick succession must not race each other's issue creation:
136
+ # the second run reads the tracker the first one wrote.
137
+ concurrency:
138
+ group: adr-accepted
139
+ cancel-in-progress: false
140
+
141
+ jobs:
142
+ ${ADR_ACCEPTED_JOB}:
143
+ runs-on: ${opts.runsOn}
144
+ env:
145
+ SPEC: ${envValue(spec)}
146
+ PREFIX: ${envValue(prefix)}
147
+ steps:
148
+ # fetch-depth 0: the acceptance read compares each ADR with the commit
149
+ # before this push, and refuses when that commit is not in the clone.
150
+ - uses: ${opts.checkout}
151
+ with:
152
+ fetch-depth: 0
153
+ - uses: ${opts.setupBun}
154
+ with:
155
+ ${opts.setupBunWith}
156
+ ${opts.setupBunEnv}
157
+ - id: accepted
158
+ name: Which ADRs did this push accept?
159
+ env:
160
+ BEFORE: \${{ github.event.before }}
161
+ run: |
162
+ ${cli} plan-issues --accepted-since "$BEFORE" > accepted.txt
163
+ echo "Accepted by this push:"
164
+ cat accepted.txt
165
+ if [ ! -s accepted.txt ]; then
166
+ echo "any=false" >> "$GITHUB_OUTPUT"
167
+ exit 0
168
+ fi${refusal}
169
+ echo "any=true" >> "$GITHUB_OUTPUT"
170
+
171
+ - name: Milestones from the engine spec's placement table
172
+ if: steps.accepted.outputs.any == 'true'
173
+ env:
174
+ GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }}
175
+ run: ${cli} plan-spec "$SPEC" --repo "$GITHUB_REPOSITORY" --prefix "$PREFIX" --write
176
+
177
+ # One ADR at a time; \`bash -e\` stops at the first refusal, so a plan the
178
+ # filing tool refuses is a red run naming the ADR.
179
+ - name: Issues and blocked-by edges from each accepted ADR
180
+ if: steps.accepted.outputs.any == 'true'
181
+ env:
182
+ GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }}
183
+ run: |
184
+ while IFS= read -r adr; do
185
+ echo "== $adr"
186
+ ${cli} plan-issues --decompose "$adr" --repo "$GITHUB_REPOSITORY" --write
187
+ done < accepted.txt
188
+
189
+ - name: Phase-order links between milestones
190
+ if: steps.accepted.outputs.any == 'true'
191
+ env:
192
+ GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }}
193
+ run: ${cli} plan-deps --repo "$GITHUB_REPOSITORY" --milestone-prefix "$PREFIX" --write
194
+
195
+ # The board steps. THE SECRET IS \`RUNGATE_PROJECT_TOKEN\`: board-mirror
196
+ # reads it as GITHUB_TOKEN, board-ready as BOARD_PROJECT_TOKEN. An absent
197
+ # secret is the empty string with no error, so each command's own
198
+ # UNMEASURED refusal is what reports it.
199
+ - name: Criteria column on the board
200
+ if: steps.accepted.outputs.any == 'true'
201
+ env:
202
+ GITHUB_TOKEN: \${{ secrets.RUNGATE_PROJECT_TOKEN }}
203
+ PROJECT_ID: \${{ vars.RUNGATE_PROJECT_ID }}
204
+ run: |
205
+ if [ -z "$PROJECT_ID" ]; then
206
+ echo "::error::UNMEASURED — RUNGATE_PROJECT_ID is not set, so there is no board to write."
207
+ exit 1
208
+ fi
209
+ ${cli} board-mirror --project "$PROJECT_ID" --write
210
+
211
+ - name: Top up Ready from the new issues
212
+ if: steps.accepted.outputs.any == 'true'
213
+ env:
214
+ BOARD_PROJECT_TOKEN: \${{ secrets.RUNGATE_PROJECT_TOKEN }}
215
+ PROJECT_ID: \${{ vars.RUNGATE_PROJECT_ID }}
216
+ ACTOR: \${{ github.actor }}
217
+ run: ${cli} board-ready --repo "$GITHUB_REPOSITORY" --project "$PROJECT_ID" --actor "$ACTOR" --top-up --write
218
+ `;
219
+ }
@@ -0,0 +1,248 @@
1
+ /**
2
+ * `.github/workflows/board-ready.yml`, generated — #2047, ADR-014 row 4,
3
+ * half of SC-2745 (`board-intake.yml` is #2166's).
4
+ *
5
+ * It keeps the board's Ready lane full from the events the repository
6
+ * already emits (#1744): a close fans out to what that close freed, and the
7
+ * other `issues:` types top the lane up from every open issue (#1842). It was
8
+ * hand-written and caller-owned while it ran `bun scripts/board-ready.ts`
9
+ * from this checkout. A consumer has no `scripts/` (ADR-014 decision 2), so
10
+ * the scaffold now writes it and this repository's copy is the generated one.
11
+ *
12
+ * ## It names no board
13
+ *
14
+ * The step passes no `--project`. `rungate board-ready` reads `board.id`
15
+ * from the checked-out tree's rungate config since #2165, so the board's
16
+ * identity lives in one place a consumer already edits, and no generated
17
+ * workflow carries a project id or URL (SC-2745). That is why the job still
18
+ * checks the tree out: the config is the input.
19
+ *
20
+ * ## What is kept from the hand-written file, and why each piece is load-bearing
21
+ *
22
+ * Every property below is asserted in `test/board-ready-fanout.test.ts`, so
23
+ * the record of WHY lives here, beside the bytes, and the generated YAML
24
+ * carries one line each.
25
+ *
26
+ * - **No schedule (BR-12).** A cron is the thing #1744 exists to remove.
27
+ * - **The trust gate runs first and needs no checkout.** `issues:` events on
28
+ * a public repository are triggerable by anyone, and the job holds a
29
+ * board-writing PAT. The gate authorises the repository OWNER without an
30
+ * API call (BR-34: dispatch `42074926758` refused the owner because the
31
+ * PAT could not read the permission endpoint), then asks
32
+ * `collaborators/{actor}/permission` for anyone else. A permission nobody
33
+ * could read refuses. `WRITING_PERMISSIONS` in `lib/board-ready-fanout.ts`
34
+ * is the decider; BR-33 holds this `case` to the same set.
35
+ * - **The secret is `RUNGATE_PROJECT_TOKEN`, the env var
36
+ * `BOARD_PROJECT_TOKEN` (BR-13).** An absent secret is the empty string
37
+ * with no error, so a wrong name made the gate authorise nothing and go
38
+ * green (run `41950972882`).
39
+ * - **One run at a time, never cancelling the running one.** Occupancy is
40
+ * read once and written later, so two overlapping runs over-fill Ready.
41
+ * Every mode is a pure function of live state, so a dropped PENDING run
42
+ * loses nothing.
43
+ * - **No `continue-on-error` (BR-20).** It swallowed every failure into a
44
+ * green run.
45
+ * - **Every input reaches the script through `env:` (BR-16), and the
46
+ * argument list is an array with every expansion quoted (BR-54).** A
47
+ * dispatch `issue: "7 --write"` once word-split into a real write.
48
+ * - **`assigned` names the moving issue (BR-51, #1905); a close runs both
49
+ * sources (#1917).**
50
+ */
51
+
52
+ /** The file this module generates, under `.github/workflows/`. */
53
+ export const BOARD_READY_WORKFLOW_FILE = "board-ready.yml";
54
+
55
+ /** The one job in it. */
56
+ export const BOARD_READY_JOB = "move-freed-issues-to-ready";
57
+
58
+ /**
59
+ * The CLI command the step runs. `lib/cli-commands.ts` must register it, or
60
+ * the workflow calls a command `bin/rungate.ts` refuses (#675's defect).
61
+ */
62
+ export const BOARD_READY_COMMAND = "board-ready";
63
+
64
+ /**
65
+ * The trust gate's `run:` body. It needs only `gh`, which the runner has,
66
+ * so an untrusted trigger is refused before any checkout or install.
67
+ */
68
+ export function buildBoardReadyGateScript(): string {
69
+ return `if [ -z "$GH_TOKEN" ]; then
70
+ echo "::warning::UNMEASURED — BOARD_PROJECT_TOKEN is not set, so the acting identity could not be authorised and nothing was read. This run is UNMEASURED, not clean."
71
+ echo "trusted=false" >> "$GITHUB_OUTPUT"
72
+ exit 0
73
+ fi
74
+ # The owner may move its own board, with no API call and no token scope (BR-34).
75
+ if [ "$ACTOR" = "$OWNER" ]; then
76
+ echo "trusted=true" >> "$GITHUB_OUTPUT"
77
+ exit 0
78
+ fi
79
+ # A read that failed is "" and refuses with the rest — a permission we could
80
+ # not read is not a permission we were granted.
81
+ perm=$(gh api "repos/$GITHUB_REPOSITORY/collaborators/$ACTOR/permission" --jq .permission 2>/dev/null) || perm=""
82
+ case "$perm" in
83
+ admin|maintain|write)
84
+ echo "trusted=true" >> "$GITHUB_OUTPUT"
85
+ ;;
86
+ *)
87
+ echo "::warning::refusing to run: $ACTOR has permission \\"\${perm:-UNMEASURED}\\" on $GITHUB_REPOSITORY, and this job holds a board-writing credential."
88
+ echo "trusted=false" >> "$GITHUB_OUTPUT"
89
+ ;;
90
+ esac
91
+ `;
92
+ }
93
+
94
+ /**
95
+ * The fill step's `run:` body. Exported so a test can read THIS text rather
96
+ * than a paraphrase. No `--project`: the board is `board.id` in the config
97
+ * the checkout brought (#2165).
98
+ */
99
+ export function buildBoardReadyScript(version: string): string {
100
+ return `# An array, and every expansion quoted, so no input can become a flag (BR-54).
101
+ args=(--repo "$GITHUB_REPOSITORY" --actor "$ACTOR")
102
+ case "$MODE" in
103
+ closed)
104
+ case "$ISSUE" in
105
+ '' | *[!0-9]*)
106
+ echo "::warning::UNMEASURED — mode 'closed' needs a plain issue NUMBER and got \\"$ISSUE\\". Nothing was read."
107
+ exit 1
108
+ ;;
109
+ esac
110
+ # Both sources: a close frees a slot even when it blocked nothing (#1917).
111
+ args+=(--closed-issue "$ISSUE" --top-up)
112
+ ;;
113
+ assigned)
114
+ # board-flow moves this card out of Ready on the same event (#1905).
115
+ args+=(--top-up --moving-issue "$ISSUE")
116
+ ;;
117
+ top-up | unassigned | opened | reopened | milestoned | demilestoned | labeled | unlabeled)
118
+ args+=(--top-up)
119
+ ;;
120
+ *)
121
+ echo "::warning::UNMEASURED — unrecognised mode \\"$MODE\\", so no candidate source was chosen. Nothing was read."
122
+ exit 1
123
+ ;;
124
+ esac
125
+ if [ -n "$WRITE" ]; then
126
+ args+=(--write)
127
+ fi
128
+ echo "mode=$MODE, args=\${args[*]}"
129
+ # A tree with no board.id is UNMEASURED, an annotation and not a red run
130
+ # (.claude/rules/config-access.md). Only that refusal is: every other exit stands.
131
+ err="$RUNNER_TEMP/board-ready.stderr"
132
+ code=0
133
+ bunx rungate@${version} ${BOARD_READY_COMMAND} "\${args[@]}" 2>"$err" || code=$?
134
+ cat "$err" >&2
135
+ if [ "$code" -eq 2 ] && grep -q '^${NO_BOARD_REFUSAL}' "$err"; then
136
+ echo "::warning::UNMEASURED — no board.id in the rungate config, so there is no board to read. Set board.id and this runs."
137
+ exit 0
138
+ fi
139
+ exit "$code"
140
+ `;
141
+ }
142
+
143
+ /**
144
+ * How `rungate board-ready` begins its one refusal for a tree with no board
145
+ * (#2165). The fill step turns exactly that refusal into an annotation, so a
146
+ * consumer who sets the token before `board.id` gets a warning on each issue
147
+ * event and not a red run. `test/board-ready-fanout.test.ts` holds this to
148
+ * the script's own text, so the two cannot drift apart.
149
+ */
150
+ export const NO_BOARD_REFUSAL = "UNMEASURED: no board";
151
+
152
+ export interface BoardReadyWorkflowOptions {
153
+ /** The `runs-on:` value, already JSON-quoted by the caller. */
154
+ runsOn: string;
155
+ /** The pinned `actions/checkout` reference. */
156
+ checkout: string;
157
+ /** The pinned `oven-sh/setup-bun` reference. */
158
+ setupBun: string;
159
+ /** The `with:` body of that step, at ten spaces — the project's single bun declaration (#622). */
160
+ setupBunWith: string;
161
+ /** The step's `env:` block, from `setupBunEnv` (#2039). */
162
+ setupBunEnv: string;
163
+ /** The published harness version the step runs through `bunx`. */
164
+ version: string;
165
+ }
166
+
167
+ /** The whole `board-ready.yml` body. */
168
+ export function buildBoardReadyWorkflow(opts: BoardReadyWorkflowOptions): string {
169
+ const indent = (text: string, pad: string) =>
170
+ text
171
+ .trimEnd()
172
+ .split("\n")
173
+ .map(line => (line === "" ? "" : `${pad}${line}`))
174
+ .join("\n");
175
+
176
+ return `# Managed by rungate — do not edit. The board is board.id in .claude/rungate/config.json.
177
+ #
178
+ # Keeps the board's Ready lane full from the events the repository already
179
+ # emits (#1744). A close fans out to what it freed; the other issue events top
180
+ # the lane up from every open issue (#1842). No schedule: every trigger is an
181
+ # event a person caused. Generated since #2047, and it names no project id —
182
+ # \`rungate ${BOARD_READY_COMMAND}\` reads board.id from the checked-out config.
183
+ #
184
+ # Needs the RUNGATE_PROJECT_TOKEN secret: a token that can write the project
185
+ # board, which GITHUB_TOKEN cannot.
186
+ name: Board — keep Ready full from the events the repo already emits
187
+
188
+ on:
189
+ issues:
190
+ types: [closed, assigned, unassigned, opened, reopened, milestoned, demilestoned, labeled, unlabeled]
191
+ workflow_dispatch:
192
+ inputs:
193
+ mode:
194
+ description: "closed = fan out from \`issue\`; top-up = consider every open issue"
195
+ type: choice
196
+ default: closed
197
+ options: [closed, "top-up"]
198
+ issue:
199
+ description: "Issue number to fan out from (mode: closed only)"
200
+ required: false
201
+ type: string
202
+ write:
203
+ description: "Perform the moves (default: report only)"
204
+ type: boolean
205
+ default: false
206
+
207
+ permissions:
208
+ contents: read
209
+
210
+ # One run at a time: occupancy is read once and written later, so overlapping
211
+ # runs over-fill Ready. Never cancel the running one — it can be mid-write.
212
+ concurrency:
213
+ group: board-ready
214
+ cancel-in-progress: false
215
+
216
+ jobs:
217
+ ${BOARD_READY_JOB}:
218
+ runs-on: ${opts.runsOn}
219
+ steps:
220
+ # Before any checkout: an untrusted trigger is refused with only gh.
221
+ - id: gate
222
+ name: May the acting identity move the board?
223
+ env:
224
+ GH_TOKEN: \${{ secrets.RUNGATE_PROJECT_TOKEN }}
225
+ ACTOR: \${{ github.actor }}
226
+ OWNER: \${{ github.repository_owner }}
227
+ run: |
228
+ ${indent(buildBoardReadyGateScript(), " ")}
229
+ # The checkout is the config the command reads the board from.
230
+ - if: steps.gate.outputs.trusted == 'true'
231
+ uses: ${opts.checkout}
232
+ - if: steps.gate.outputs.trusted == 'true'
233
+ uses: ${opts.setupBun}
234
+ with:
235
+ ${opts.setupBunWith}
236
+ ${opts.setupBunEnv}
237
+ - name: Fill Ready from whatever this event changed
238
+ if: steps.gate.outputs.trusted == 'true'
239
+ env:
240
+ BOARD_PROJECT_TOKEN: \${{ secrets.RUNGATE_PROJECT_TOKEN }}
241
+ ISSUE: \${{ github.event.issue.number || inputs.issue }}
242
+ WRITE: \${{ (github.event_name == 'issues' || inputs.write) && '--write' || '' }}
243
+ MODE: \${{ github.event.action || inputs.mode }}
244
+ ACTOR: \${{ github.actor }}
245
+ run: |
246
+ ${indent(buildBoardReadyScript(opts.version), " ")}
247
+ `;
248
+ }