rungate 0.8.19 → 0.8.21

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.
@@ -0,0 +1,314 @@
1
+ /**
2
+ * Undone work declared in a repository's prose that no open issue covers (#2100).
3
+ *
4
+ * #1953 (PR #2096) built the structured half: `board-conformance`'s
5
+ * `declared-work` reading covers unticked criteria and open stage items. This
6
+ * is the prose half: a TODO, a "we need to", a priority paragraph, a fact kept
7
+ * only in agent memory.
8
+ *
9
+ * RunGate ships to consumers, and a consumer repository has no stages and
10
+ * usually no plan file or agent memory. So sources are DISCOVERED from what the
11
+ * repository contains, never typed into a list. A source that is not there is
12
+ * ABSENT, a source that is there but cannot be read is UNMEASURED, and neither
13
+ * is ever reported as zero.
14
+ *
15
+ * A declaration is accounted for only when it cites an issue that is open now.
16
+ * It errs toward reporting too much: a false positive costs a glance, while a
17
+ * false negative is the defect itself and cannot be seen. So a citation whose
18
+ * state could not be read is not credited.
19
+ */
20
+ import { spawnSync } from "child_process";
21
+ import { existsSync, lstatSync, readdirSync, readFileSync } from "fs";
22
+ import { join } from "path";
23
+
24
+ export type SourceName = "tracked-files" | "plan-file" | "agent-memory";
25
+
26
+ export interface Declaration {
27
+ source: SourceName;
28
+ /** Relative to the root for repository sources; absolute for agent memory, which lives outside it. */
29
+ path: string;
30
+ line: number;
31
+ text: string;
32
+ cites: number[];
33
+ }
34
+
35
+ export type SourceReading =
36
+ | { source: SourceName; kind: "READ"; declarations: Declaration[]; unreadable: string[]; files: number }
37
+ | { source: SourceName; kind: "ABSENT"; why: string }
38
+ | { source: SourceName; kind: "UNMEASURED"; why: string };
39
+
40
+ /** The phrases that declare undone work. Matched per line. */
41
+ export const PROSE_MARKERS: readonly RegExp[] = [/\bTODO\b/, /\bFIXME\b/, /\bwe need to\b/i, /\bnot yet built\b/i];
42
+
43
+ /** The plan file a repository may carry. Read by its own source, so the tracked-file scan skips it. */
44
+ export const PLAN_FILE = "project-state.json";
45
+
46
+ /**
47
+ * `#N` standing alone: not `page#14`, not ``. At most nine digits, so every
48
+ * value is a GraphQL `Int` (32-bit) and one hash-prefixed id cannot fail the batched
49
+ * issue-state query for every real citation (review round 3 of PR #2188).
50
+ */
51
+ export function citationsIn(text: string): number[] {
52
+ return [...text.matchAll(/(?<![\w&/#])#(\d{1,9})\b(?!;)/g)].map(m => Number(m[1]));
53
+ }
54
+
55
+ const clip = (s: string) => (s.length > 160 ? `${s.slice(0, 157)}...` : s);
56
+
57
+ /** Every line of `text` carrying a marker. */
58
+ export function declarationsIn(text: string, path: string, source: SourceName): Declaration[] {
59
+ const out: Declaration[] = [];
60
+ text.split("\n").forEach((line, i) => {
61
+ if (PROSE_MARKERS.some(re => re.test(line))) {
62
+ out.push({ source, path, line: i + 1, text: clip(line.trim()), cites: citationsIn(line) });
63
+ }
64
+ });
65
+ return out;
66
+ }
67
+
68
+ const looksBinary = (b: Buffer) => b.subarray(0, 8000).includes(0);
69
+
70
+ /** Read `abs`, or say why not; `null` text for a binary file, which holds no prose. */
71
+ function readProse(abs: string): { text: string | null } | { why: string } {
72
+ try {
73
+ const buf = readFileSync(abs);
74
+ return { text: looksBinary(buf) ? null : buf.toString("utf-8") };
75
+ } catch (e) {
76
+ return { why: (e as Error).message };
77
+ }
78
+ }
79
+
80
+ /** Every file git tracks in `root`. A file list that cannot be read is UNMEASURED. */
81
+ export function trackedFilesSource(root: string): SourceReading {
82
+ const source = "tracked-files";
83
+ const r = spawnSync("git", ["ls-files", "-z"], { cwd: root, encoding: "utf-8", timeout: 30_000, maxBuffer: 256 * 1024 * 1024 });
84
+ if (r.error) return { source, kind: "UNMEASURED", why: `git ls-files could not run (${r.error.message})` };
85
+ if (r.status !== 0) return { source, kind: "UNMEASURED", why: `git ls-files exited ${r.status}: ${(r.stderr ?? "").trim()}` };
86
+ const files = r.stdout.split("\0").filter(Boolean);
87
+ const declarations: Declaration[] = [];
88
+ const unreadable: string[] = [];
89
+ for (const rel of files) {
90
+ if (rel === PLAN_FILE) continue;
91
+ const abs = join(root, rel);
92
+ let st;
93
+ try {
94
+ st = lstatSync(abs);
95
+ } catch (e) {
96
+ unreadable.push(`${rel} could not be read (${(e as Error).message})`);
97
+ continue;
98
+ }
99
+ // A symlink points at content tracked elsewhere, or outside; a directory is a submodule.
100
+ if (!st.isFile()) continue;
101
+ const read = readProse(abs);
102
+ if ("why" in read) unreadable.push(`${rel} could not be read (${read.why})`);
103
+ else if (read.text !== null) declarations.push(...declarationsIn(read.text, rel, source));
104
+ }
105
+ return { source, kind: "READ", declarations, unreadable, files: files.length };
106
+ }
107
+
108
+ /**
109
+ * The plan file's `priorities`. Each one states work, so each is a declaration,
110
+ * placed at the line where its text starts.
111
+ */
112
+ export function planFileSource(root: string): SourceReading {
113
+ const source = "plan-file";
114
+ const abs = join(root, PLAN_FILE);
115
+ if (!existsSync(abs)) return { source, kind: "ABSENT", why: `no ${PLAN_FILE}` };
116
+ let raw: string;
117
+ let parsed: unknown;
118
+ try {
119
+ raw = readFileSync(abs, "utf-8");
120
+ parsed = JSON.parse(raw);
121
+ } catch (e) {
122
+ return { source, kind: "UNMEASURED", why: `${PLAN_FILE} could not be read (${(e as Error).message})` };
123
+ }
124
+ const priorities = (parsed as { priorities?: unknown })?.priorities;
125
+ // No key is ABSENT; a key holding something else is a source present and
126
+ // unreadable, never zero (review round 4 of PR #2188).
127
+ if (priorities === undefined) return { source, kind: "ABSENT", why: `${PLAN_FILE} has no priorities` };
128
+ if (!Array.isArray(priorities)) return { source, kind: "UNMEASURED", why: `${PLAN_FILE}'s priorities is not an array` };
129
+ // A JSON-aware walk rather than a text search: an object-valued priority
130
+ // never appears in the file as its compact stringification, and a search
131
+ // slice can cut an escape in half (review of PR #2188). A walk that cannot
132
+ // place every entry says so; it never prints line 0 as a location.
133
+ const lines = arrayElementLines(raw, "priorities");
134
+ if (lines === null || lines.length !== priorities.length) {
135
+ const found = lines === null ? "no top-level priorities array" : `${lines.length} element(s) for ${priorities.length}`;
136
+ return { source, kind: "UNMEASURED", why: `${PLAN_FILE}'s priorities could not be placed by line (${found})` };
137
+ }
138
+ const declarations = priorities.map((p, i): Declaration => {
139
+ const text = typeof p === "string" ? p : JSON.stringify(p);
140
+ return { source, path: PLAN_FILE, line: lines[i]!, text: clip(text), cites: citationsIn(text) };
141
+ });
142
+ return { source, kind: "READ", declarations, unreadable: [], files: 1 };
143
+ }
144
+
145
+ /**
146
+ * The line each element of the top-level array `key` starts on, from a walk
147
+ * that tracks strings, escapes and depth; `null` when there is no such array.
148
+ * A raw newline cannot occur inside a JSON string, so counting every `\n`
149
+ * counts lines.
150
+ */
151
+ export function arrayElementLines(raw: string, key: string): number[] | null {
152
+ let depth = 0;
153
+ let line = 1;
154
+ let inString = false;
155
+ let stringStart = -1;
156
+ let lastKey: string | null = null;
157
+ let afterKeyColon = false;
158
+ let inArray = false;
159
+ let expectElement = false;
160
+ const lines: number[] = [];
161
+ for (let i = 0; i < raw.length; i++) {
162
+ const c = raw[i]!;
163
+ if (c === "\n") line++;
164
+ if (inString) {
165
+ if (c === "\\") i++;
166
+ else if (c === '"') {
167
+ inString = false;
168
+ if (depth === 1 && !inArray) lastKey = raw.slice(stringStart + 1, i);
169
+ }
170
+ continue;
171
+ }
172
+ if (/\s/.test(c)) continue;
173
+ if (expectElement && c !== "]") {
174
+ lines.push(line);
175
+ expectElement = false;
176
+ }
177
+ if (c === '"') {
178
+ inString = true;
179
+ stringStart = i;
180
+ } else if (c === ":") {
181
+ afterKeyColon = depth === 1 && lastKey === key;
182
+ continue;
183
+ } else if (c === "{" || c === "[") {
184
+ depth++;
185
+ if (afterKeyColon && c === "[" && depth === 2) {
186
+ inArray = true;
187
+ expectElement = true;
188
+ }
189
+ } else if (c === "}" || c === "]") {
190
+ if (inArray && depth === 2 && c === "]") return lines;
191
+ depth--;
192
+ } else if (c === "," && inArray && depth === 2) {
193
+ expectElement = true;
194
+ }
195
+ afterKeyColon = false;
196
+ }
197
+ return null;
198
+ }
199
+
200
+ /** Where Claude Code keeps agent memory for a session launched in `root`. */
201
+ export function memoryDirFor(root: string, home: string): string {
202
+ return join(home, ".claude", "projects", root.replace(/[^A-Za-z0-9]/g, "-"), "memory");
203
+ }
204
+
205
+ /** The markdown files in this root's agent memory, which live outside the repository. */
206
+ export function agentMemorySource(root: string, home: string): SourceReading {
207
+ const source = "agent-memory";
208
+ const dir = memoryDirFor(root, home);
209
+ if (!existsSync(dir)) return { source, kind: "ABSENT", why: `no agent memory at ${dir}` };
210
+ let names: string[];
211
+ try {
212
+ names = readdirSync(dir).filter(n => n.endsWith(".md") && n !== "MEMORY.md");
213
+ } catch (e) {
214
+ return { source, kind: "UNMEASURED", why: `${dir} could not be listed (${(e as Error).message})` };
215
+ }
216
+ const declarations: Declaration[] = [];
217
+ const unreadable: string[] = [];
218
+ for (const name of names) {
219
+ const abs = join(dir, name);
220
+ const read = readProse(abs);
221
+ if ("why" in read) unreadable.push(`${abs} could not be read (${read.why})`);
222
+ else if (read.text !== null) declarations.push(...declarationsIn(read.text, abs, source));
223
+ }
224
+ return { source, kind: "READ", declarations, unreadable, files: names.length };
225
+ }
226
+
227
+ /** Every source this command knows how to discover, in report order. */
228
+ export function discoverSources(root: string, home: string): SourceReading[] {
229
+ return [trackedFilesSource(root), planFileSource(root), agentMemorySource(root, home)];
230
+ }
231
+
232
+ /** The open/closed state of each cited number, or why it could not be read. */
233
+ export type IssueStates = { kind: "READ"; open: ReadonlySet<number> } | { kind: "UNMEASURED"; why: string };
234
+
235
+ /** Accounted for only by an issue that is open now. An unread state credits nothing. */
236
+ export function isAccounted(d: Declaration, states: IssueStates): boolean {
237
+ return states.kind === "READ" && d.cites.some(n => states.open.has(n));
238
+ }
239
+
240
+ export interface Report {
241
+ root: string;
242
+ sources: Array<{ source: SourceName; kind: SourceReading["kind"]; why?: string; files?: number; declarations?: number }>;
243
+ issueStates: { kind: IssueStates["kind"]; why?: string; cited: number; open?: number };
244
+ unaccounted: Declaration[];
245
+ unmeasured: string[];
246
+ }
247
+
248
+ export function buildReport(root: string, sources: readonly SourceReading[], cited: readonly number[], states: IssueStates): Report {
249
+ const all = sources.flatMap(s => (s.kind === "READ" ? s.declarations : []));
250
+ const unmeasured = sources.flatMap(s =>
251
+ s.kind === "UNMEASURED" ? [`${s.source} — ${s.why}`] : s.kind === "READ" ? s.unreadable.map(u => `${s.source} — ${u}`) : [],
252
+ );
253
+ // Whether or not anything cites an issue: an unreadable --issues-fixture is a
254
+ // bad input, and dropping it when nothing cites is a refusal swallowed (review
255
+ // round 2 of PR #2188). A live read only happens when something cites.
256
+ if (states.kind === "UNMEASURED") unmeasured.push(`issue-states — ${states.why}`);
257
+ return {
258
+ root,
259
+ sources: sources.map(s =>
260
+ s.kind === "READ"
261
+ ? { source: s.source, kind: s.kind, files: s.files, declarations: s.declarations.length }
262
+ : { source: s.source, kind: s.kind, why: s.why },
263
+ ),
264
+ issueStates:
265
+ states.kind === "READ"
266
+ ? { kind: "READ", cited: cited.length, open: cited.filter(n => states.open.has(n)).length }
267
+ : { kind: "UNMEASURED", why: states.why, cited: cited.length },
268
+ unaccounted: all.filter(d => !isAccounted(d, states)),
269
+ unmeasured,
270
+ };
271
+ }
272
+
273
+ /** The distinct numbers cited across every source. */
274
+ export function citedNumbers(sources: readonly SourceReading[]): number[] {
275
+ const set = new Set(sources.flatMap(s => (s.kind === "READ" ? s.declarations.flatMap(d => d.cites) : [])));
276
+ return [...set].sort((a, b) => a - b);
277
+ }
278
+
279
+ export function renderReport(r: Report): string[] {
280
+ const lines = [`unaccounted-work: ${r.root}`];
281
+ for (const s of r.sources) {
282
+ lines.push(
283
+ s.kind === "READ"
284
+ ? ` ${s.source}: READ — ${s.files} file(s), ${s.declarations} declaration(s)`
285
+ : ` ${s.source}: ${s.kind} — ${s.why}`,
286
+ );
287
+ }
288
+ const st = r.issueStates;
289
+ lines.push(st.kind === "READ" ? ` issue-states: READ — ${st.cited} cited, ${st.open} open` : ` issue-states: UNMEASURED — ${st.why} (${st.cited} cited)`);
290
+ lines.push(`UNACCOUNTED (${r.unaccounted.length}) — declared undone, citing no open issue:`);
291
+ for (const d of r.unaccounted) {
292
+ lines.push(` ${d.path}:${d.line} ${d.text}${d.cites.length ? ` [cites ${d.cites.map(n => `#${n}`).join(", ")}]` : ""}`);
293
+ }
294
+ for (const u of r.unmeasured) lines.push(`UNMEASURED: ${u}`);
295
+ return lines;
296
+ }
297
+
298
+ /**
299
+ * The open issues among `chunk` in one `repository { nN: issueOrPullRequest }`
300
+ * page. A page with no `repository` (a wrong or renamed name, or one this token
301
+ * cannot see) throws: it is a reading not taken, and reading it as "none open"
302
+ * would report every citation as unaccounted (review round 5 of PR #2188).
303
+ * A pull request, a missing number and a closed issue are not open.
304
+ */
305
+ export function openIssuesInPage(data: unknown, chunk: readonly number[]): number[] {
306
+ const repository = (data as { repository?: Record<string, unknown> | null } | null | undefined)?.repository;
307
+ if (!repository) {
308
+ throw new Error("the response carried no repository (a wrong or renamed name, or one this token cannot see)");
309
+ }
310
+ return chunk.filter(n => {
311
+ const node = repository[`n${n}`] as { __typename?: string; state?: string } | null | undefined;
312
+ return node?.__typename === "Issue" && node.state === "OPEN";
313
+ });
314
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rungate",
3
- "version": "0.8.19",
3
+ "version": "0.8.21",
4
4
  "type": "module",
5
5
  "description": "Ship harness — conformity tests, scaffold, and agent briefs for AI-first development",
6
6
  "repository": {
@@ -36,6 +36,8 @@
36
36
  "scripts/plan-issues.ts",
37
37
  "scripts/board-ready.ts",
38
38
  "scripts/board-id.ts",
39
+ "scripts/unaccounted-work.ts",
40
+ "scripts/board-intake-move.ts",
39
41
  "scripts/audit-closing-references.ts",
40
42
  "scripts/create-spec.ts",
41
43
  "scripts/create-success.ts",
@@ -32,13 +32,17 @@
32
32
  */
33
33
  import { createGitHubClient } from "../lib/github";
34
34
  import {
35
+ AI_REVIEW_PR_IS_FORK_VAR,
35
36
  aiReviewThreadsExitCode,
36
37
  postReviewThreads,
38
+ prIsForkReading,
39
+ threadsDetailLines,
37
40
  threadsLandedPhrase,
38
41
  type AiReviewThreadPoster,
39
42
  type AiReviewThreadResponse,
40
43
  } from "../lib/ai-review-threads";
41
44
  import {
45
+ escapeAnnotation,
42
46
  readAiReviewChangedFiles,
43
47
  readAiReviewFindingsFile,
44
48
  } from "../lib/scaffold/ai-review-findings";
@@ -113,7 +117,11 @@ if (!parsed.ok) {
113
117
  // UNMEASURED, not a refusal. A step invoked wrongly has not discovered that
114
118
  // a review produced no threads; it has not looked. Exiting non-zero here
115
119
  // would red the job for a reason that says nothing about the review.
116
- console.log(`::warning title=AI review threads::${COMMAND}: ${parsed.error} — UNMEASURED, nothing was posted`);
120
+ // Escaped: the error quotes the positionals, which are this process's argv
121
+ // (#1992).
122
+ console.log(
123
+ `::warning title=AI review threads::${COMMAND}: ${escapeAnnotation(parsed.error)} — UNMEASURED, nothing was posted`,
124
+ );
117
125
  process.exit(0);
118
126
  }
119
127
 
@@ -180,8 +188,12 @@ const post: AiReviewThreadPoster = async request => {
180
188
  // every round would re-post every thread. `lineTextFor` comes off the SAME
181
189
  // reader the gate above was built from, so it is the same cache and the same
182
190
  // normalisation rather than a second one that happens to agree.
183
- const result = await postReviewThreads(reading, post, f => carryKey(f, lineTextFor(f)));
184
- for (const line of result.detail) console.log(`${COMMAND}: ${line}`);
191
+ // #1992: whether this run is a fork, read exactly from the variable the
192
+ // workflow sets (#2203). Unset reads null, which keeps the fork degrade — so
193
+ // this CLI under a workflow that does not yet set it behaves as before.
194
+ const fork = prIsForkReading(process.env[AI_REVIEW_PR_IS_FORK_VAR]);
195
+ const result = await postReviewThreads(reading, post, f => carryKey(f, lineTextFor(f)), fork);
196
+ for (const line of threadsDetailLines(result, COMMAND)) console.log(line);
185
197
  console.log(
186
198
  `${COMMAND}: ${result.outcome} — attempted ${result.attempted}, posted ${result.posted}, ` +
187
199
  `demoted ${result.demoted}`,
@@ -0,0 +1,80 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * `rungate board-intake-move --project <id> --item <id> --column <name>` —
4
+ * move a board item to a column and verify it in both the item's field value
5
+ * and the project's search index (#2193, part 1 of #2183). The logic, and
6
+ * why each refusal exists, is in `lib/board-intake-move.ts`.
7
+ *
8
+ * Prints a `::notice` on success and a `::error` naming the cause on every
9
+ * refusal, so a workflow step that runs it shows the reason as an annotation.
10
+ * An empty `--item` is accepted here and refused by the library as NO_ITEM,
11
+ * which says which half of the intake failed.
12
+ *
13
+ * Relative imports are `../lib/` only, so a test can run a copy of it from a
14
+ * temp directory.
15
+ */
16
+ import { createGitHubClient } from "../lib/github";
17
+ import { moveToColumn } from "../lib/board-intake-move";
18
+
19
+ /** The one non-zero exit. Assigned once. */
20
+ export const EXIT_REFUSED = 1;
21
+
22
+ const USAGE = "rungate board-intake-move --project <node-id> --item <item-id> --column <name>";
23
+
24
+ export async function main(argv: readonly string[]): Promise<number> {
25
+ const values: Record<string, string | undefined> = {};
26
+ for (let i = 0; i < argv.length; i++) {
27
+ const a = argv[i]!;
28
+ const key = a.replace(/^--/, "");
29
+ if (!["--project", "--item", "--column"].includes(a)) {
30
+ console.error(`::error title=Board intake::unknown argument ${JSON.stringify(a)}. Usage: ${USAGE}. Nothing was read.`);
31
+ return EXIT_REFUSED;
32
+ }
33
+ const next = argv[i + 1];
34
+ if (next === undefined || next.startsWith("--")) {
35
+ console.error(`::error title=Board intake::${a} needs a value after it. Usage: ${USAGE}. Nothing was read.`);
36
+ return EXIT_REFUSED;
37
+ }
38
+ values[key] = next;
39
+ i++;
40
+ }
41
+ for (const required of ["project", "column"]) {
42
+ if (!values[required]) {
43
+ console.error(`::error title=Board intake::--${required} is required. Usage: ${USAGE}. Nothing was read.`);
44
+ return EXIT_REFUSED;
45
+ }
46
+ }
47
+ // A missing or refused credential is a refusal with its own message, not a
48
+ // stack trace (review of PR #2194).
49
+ let client: ReturnType<typeof createGitHubClient>;
50
+ try {
51
+ client = createGitHubClient();
52
+ } catch (e) {
53
+ console.error(`::error title=Board intake::no GitHub client, so nothing was read or written: ${(e as Error).message}`);
54
+ return EXIT_REFUSED;
55
+ }
56
+ // The library names every fault it can; this is the last line, so nothing
57
+ // reaches the workflow log as a stack trace (review of PR #2194).
58
+ let result: Awaited<ReturnType<typeof moveToColumn>>;
59
+ try {
60
+ result = await moveToColumn(
61
+ { projectId: values.project!, itemId: values.item ?? "", column: values.column! },
62
+ {
63
+ graphql: (query, variables) => client.graphql(query, variables),
64
+ sleep: ms => new Promise(resolve => setTimeout(resolve, ms)),
65
+ log: line => console.log(line),
66
+ },
67
+ );
68
+ } catch (e) {
69
+ console.error(`::error title=Board intake::the move stopped on an unexpected fault, so the item's Status is UNKNOWN: ${(e as Error)?.message ?? String(e)}`);
70
+ return EXIT_REFUSED;
71
+ }
72
+ if (result.ok) {
73
+ console.log(`::notice title=Board intake::${result.message}`);
74
+ return 0;
75
+ }
76
+ console.error(`::error title=Board intake::${result.message}`);
77
+ return EXIT_REFUSED;
78
+ }
79
+
80
+ if (import.meta.main) process.exitCode = await main(process.argv.slice(2));
@@ -0,0 +1,122 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * `rungate unaccounted-work` — undone work declared in a repository's prose
4
+ * that no open issue covers, by file and line (#2100). The logic is in
5
+ * `lib/unaccounted-work.ts`; this file parses arguments, asks GitHub which
6
+ * cited issues are open, and picks the exit code.
7
+ *
8
+ * rungate unaccounted-work [--project-root <dir>] [--repo <owner/name>]
9
+ * [--issues-fixture <file.json>] [--json]
10
+ *
11
+ * Exit 0: every source read and nothing unaccounted. `EXIT_UNACCOUNTED`:
12
+ * declarations cite no open issue. `EXIT_REFUSED`: a source, a file, or the
13
+ * citations' issue states could not be read, so the report is a floor, not a
14
+ * count.
15
+ *
16
+ * Relative imports are `../lib/` only: `test/unaccounted-work.test.ts`
17
+ * rewrites them to absolute paths to run a mutant from a temp directory.
18
+ */
19
+ import { spawnSync } from "child_process";
20
+ import { readFileSync } from "fs";
21
+ import { homedir } from "os";
22
+ import { resolve } from "path";
23
+
24
+ import { createGitHubClient, parseOwnerRepo } from "../lib/github";
25
+ import { buildReport, citedNumbers, discoverSources, openIssuesInPage, renderReport, type IssueStates } from "../lib/unaccounted-work";
26
+ import { parseRemoteSlug } from "../lib/verified-push";
27
+
28
+ /** The one exit for a reading not taken. Assigned once; the test mutates it. */
29
+ export const EXIT_REFUSED = 2;
30
+ /** Declarations were found that cite no open issue. */
31
+ export const EXIT_UNACCOUNTED = 1;
32
+
33
+ const USAGE =
34
+ "rungate unaccounted-work [--project-root <dir>] [--repo <owner/name>] [--issues-fixture <file.json>] [--json]";
35
+
36
+ /** `{ "12": "OPEN", "13": "CLOSED" }`; a number absent from it is not open. */
37
+ function fixtureStates(path: string): IssueStates {
38
+ try {
39
+ const raw = JSON.parse(readFileSync(path, "utf-8")) as Record<string, unknown>;
40
+ return { kind: "READ", open: new Set(Object.entries(raw).filter(([, s]) => s === "OPEN").map(([n]) => Number(n))) };
41
+ } catch (e) {
42
+ return { kind: "UNMEASURED", why: `--issues-fixture ${path} could not be read (${(e as Error).message})` };
43
+ }
44
+ }
45
+
46
+ /** The repository citations are checked against: `--repo`, else the origin remote's. */
47
+ function repoFor(root: string, flag: string | undefined): string | null {
48
+ if (flag) return flag;
49
+ const r = spawnSync("git", ["remote", "get-url", "origin"], { cwd: root, encoding: "utf-8", timeout: 5000 });
50
+ return r.status === 0 ? parseRemoteSlug(r.stdout) : null;
51
+ }
52
+
53
+ /** Which of `numbers` are open issues. A PR, a missing number or a closed issue is not. */
54
+ async function liveStates(repo: string, numbers: readonly number[]): Promise<IssueStates> {
55
+ try {
56
+ const { owner, repo: name } = parseOwnerRepo(repo);
57
+ const client = createGitHubClient();
58
+ const open = new Set<number>();
59
+ for (let i = 0; i < numbers.length; i += 50) {
60
+ const chunk = numbers.slice(i, i + 50);
61
+ const fields = chunk.map(n => `n${n}: issueOrPullRequest(number: ${n}) { __typename ... on Issue { state } }`).join("\n");
62
+ const query = `query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ${fields} } }`;
63
+ let data: any;
64
+ try {
65
+ data = await client.graphql(query, { owner, name });
66
+ } catch (e) {
67
+ // A number that names nothing fails the whole query but still returns
68
+ // the rest. Without that partial data, nothing was read.
69
+ data = (e as { data?: unknown }).data;
70
+ if (!data) throw e;
71
+ }
72
+ for (const n of openIssuesInPage(data, chunk)) open.add(n);
73
+ }
74
+ return { kind: "READ", open };
75
+ } catch (e) {
76
+ return { kind: "UNMEASURED", why: `GitHub could not say which cited issues are open (${(e as Error).message})` };
77
+ }
78
+ }
79
+
80
+ export async function main(argv: readonly string[]): Promise<number> {
81
+ let rootArg: string | undefined;
82
+ let repoArg: string | undefined;
83
+ let fixture: string | undefined;
84
+ let asJson = false;
85
+ for (let i = 0; i < argv.length; i++) {
86
+ const a = argv[i];
87
+ if (a === "--json") asJson = true;
88
+ else if (a === "--project-root" || a === "--repo" || a === "--issues-fixture") {
89
+ const next = argv[i + 1];
90
+ if (next === undefined || next.startsWith("--")) {
91
+ console.error(`UNMEASURED: ${a} needs a value after it. Usage: ${USAGE}. Nothing was read.`);
92
+ return EXIT_REFUSED;
93
+ }
94
+ if (a === "--project-root") rootArg = next;
95
+ else if (a === "--repo") repoArg = next;
96
+ else fixture = next;
97
+ i++;
98
+ } else {
99
+ console.error(`UNMEASURED: unknown argument ${JSON.stringify(a)}. Usage: ${USAGE}. Nothing was read.`);
100
+ return EXIT_REFUSED;
101
+ }
102
+ }
103
+ const root = resolve(rootArg ?? process.cwd());
104
+ const sources = discoverSources(root, homedir());
105
+ const cited = citedNumbers(sources);
106
+ let states: IssueStates;
107
+ if (fixture) states = fixtureStates(fixture);
108
+ else if (cited.length === 0) states = { kind: "READ", open: new Set() };
109
+ else {
110
+ const repo = repoFor(root, repoArg);
111
+ states = repo
112
+ ? await liveStates(repo, cited)
113
+ : { kind: "UNMEASURED", why: "no repository to check citations against: pass --repo, or give the tree an origin remote" };
114
+ }
115
+ const report = buildReport(root, sources, cited, states);
116
+ if (asJson) console.log(JSON.stringify(report, null, 2));
117
+ else console.log(renderReport(report).join("\n"));
118
+ if (report.unmeasured.length > 0) return EXIT_REFUSED;
119
+ return report.unaccounted.length > 0 ? EXIT_UNACCOUNTED : 0;
120
+ }
121
+
122
+ if (import.meta.main) process.exitCode = await main(process.argv.slice(2));