architecture-harness 0.21.2 → 0.22.0

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 (68) hide show
  1. package/package.json +8 -3
  2. package/src/cli/check.mjs +61 -0
  3. package/src/cli/child-run.mjs +39 -0
  4. package/src/cli/child-run.test.mjs +16 -0
  5. package/src/cli/ci-template.test.mjs +28 -0
  6. package/src/cli/codex-implement.mjs +72 -3
  7. package/src/cli/codex-implement.test.mjs +141 -4
  8. package/src/cli/dispatch-guard.mjs +24 -1
  9. package/src/cli/dispatch-guard.test.mjs +30 -0
  10. package/src/cli/dispatch-reminder.mjs +4 -4
  11. package/src/cli/dispatch-reminder.test.mjs +3 -3
  12. package/src/cli/dispatch-slot.mjs +12 -0
  13. package/src/cli/gate-slot.mjs +151 -0
  14. package/src/cli/gate-slot.test.mjs +90 -0
  15. package/src/cli/integrate.mjs +122 -0
  16. package/src/cli/integrate.test.mjs +94 -0
  17. package/src/cli/ledger.mjs +25 -3
  18. package/src/cli/ledger.test.mjs +9 -0
  19. package/src/cli/merge-guard.mjs +13 -3
  20. package/src/cli/merge-guard.test.mjs +24 -1
  21. package/src/cli/migrations.mjs +127 -0
  22. package/src/cli/migrations.test.mjs +94 -0
  23. package/src/cli/plugin-agents.test.mjs +35 -8
  24. package/src/cli/qc.mjs +44 -0
  25. package/src/cli/report-stop.mjs +3 -0
  26. package/src/cli/report-stop.test.mjs +8 -0
  27. package/src/cli/retry-failed.mjs +80 -0
  28. package/src/cli/retry-failed.test.mjs +51 -0
  29. package/src/cli/review-gate.mjs +16 -7
  30. package/src/cli/slot-guard.mjs +43 -0
  31. package/src/cli/slot-guard.test.mjs +28 -0
  32. package/src/cli/task-gate-review.test.mjs +10 -0
  33. package/src/cli/task-gate.mjs +39 -7
  34. package/src/cli/task-gate.test.mjs +45 -0
  35. package/src/cli/throwaway-db.mjs +127 -0
  36. package/src/cli/throwaway-db.test.mjs +83 -0
  37. package/src/cli/ui-reuse-hint.mjs +89 -0
  38. package/src/cli/ui-reuse-hint.test.mjs +60 -0
  39. package/src/cli/ui.mjs +181 -0
  40. package/src/cli/ui.test.mjs +137 -0
  41. package/src/cli/watch.mjs +211 -0
  42. package/src/cli/watch.test.mjs +246 -0
  43. package/src/config.mjs +27 -2
  44. package/src/descriptions.mjs +3 -0
  45. package/src/gates/contract-keys.mjs +33 -0
  46. package/src/gates/contract-keys.test.mjs +38 -0
  47. package/src/gates/migration-numbers.mjs +1 -1
  48. package/src/gates/migration-numbers.test.mjs +1 -0
  49. package/src/gates/ui-catalog.mjs +45 -0
  50. package/src/gates/ui-catalog.test.mjs +48 -0
  51. package/src/gates/ui-dupes.mjs +36 -0
  52. package/src/gates/ui-dupes.test.mjs +29 -0
  53. package/src/ui/catalog.mjs +87 -0
  54. package/src/ui/catalog.test.mjs +54 -0
  55. package/src/ui/class-sites.mjs +151 -0
  56. package/src/ui/class-sites.test.mjs +41 -0
  57. package/src/ui/codemod.mjs +138 -0
  58. package/src/ui/codemod.test.mjs +140 -0
  59. package/src/ui/components.mjs +176 -0
  60. package/src/ui/components.test.mjs +87 -0
  61. package/src/ui/dupes.mjs +141 -0
  62. package/src/ui/dupes.test.mjs +85 -0
  63. package/src/ui/find.mjs +45 -0
  64. package/src/ui/find.test.mjs +48 -0
  65. package/src/ui/options.mjs +40 -0
  66. package/src/ui/scan.mjs +78 -0
  67. package/src/ui/typescript.mjs +29 -0
  68. package/templates/github/workflows/ci.yml +54 -0
package/src/cli/ui.mjs ADDED
@@ -0,0 +1,181 @@
1
+ // `qc ui`: find a component before writing one, and change class tokens across a frontend in one command.
2
+ // Each subcommand is a thin reader over the pure modules in ../ui.
3
+
4
+ import { readFileSync } from "node:fs";
5
+ import { readFile as readFileAsync, writeFile } from "node:fs/promises";
6
+ import path from "node:path";
7
+ import { baselineOfFindings, findDupes } from "../ui/dupes.mjs";
8
+ import { findComponents, formatFound } from "../ui/find.mjs";
9
+ import { arbitraryTokens, codemodSource, parseMap, suggest, themeVariables } from "../ui/codemod.mjs";
10
+ import { sameCatalog } from "../ui/catalog.mjs";
11
+ import { uiOptions } from "../ui/options.mjs";
12
+ import {
13
+ CATALOG_COMMAND,
14
+ catalogText,
15
+ clientSourceFiles,
16
+ listFiles,
17
+ readFiles,
18
+ requireTypeScript,
19
+ scanComponents,
20
+ writeCatalog,
21
+ writeCatalogBaseline,
22
+ } from "../ui/scan.mjs";
23
+
24
+ const USAGE = `qc ui — the component catalog, the duplicate finder and the class codemod
25
+
26
+ qc ui catalog [--json] [--check] [--baseline]
27
+ write the catalog; --check exits 1 when it is stale; --baseline writes ui-catalog.baseline.json
28
+ qc ui find <words...> [--json]
29
+ the eight catalog entries nearest the words, as name — path — description
30
+ qc ui dupes [--json] [--baseline]
31
+ repeated class strings, repeated component names, near-equal JSX trees
32
+ qc ui codemod --map <json|file> [--write]
33
+ rewrite whole class tokens in class sites; a dry run unless --write
34
+ qc ui codemod --suggest every arbitrary-value token with its count, and the @theme variable with its value`;
35
+
36
+ const say = (line) => console.log(line);
37
+
38
+ /** `--flag` words and the rest, split. A flag that takes a value is named in `valued`. */
39
+ function parse(args, valued = []) {
40
+ const flags = new Map();
41
+ const words = [];
42
+ for (let index = 0; index < args.length; index += 1) {
43
+ const arg = args[index];
44
+ if (!arg.startsWith("--")) words.push(arg);
45
+ else if (valued.includes(arg)) flags.set(arg, args[(index += 1)]);
46
+ else flags.set(arg, true);
47
+ }
48
+ return { flags, words };
49
+ }
50
+
51
+ async function catalog(config, args) {
52
+ const { flags } = parse(args);
53
+ const { options, entries } = await scanComponents(config);
54
+ const expected = catalogText(entries, options);
55
+ if (flags.has("--json")) {
56
+ say(JSON.stringify(entries, null, 2));
57
+ return 0;
58
+ }
59
+ if (flags.has("--check")) {
60
+ const actual = await readFileAsync(path.join(config.root, options.catalog), "utf8").catch(() => null);
61
+ if (sameCatalog(actual, expected)) return 0;
62
+ console.error(`${options.catalog} is stale; run \`${CATALOG_COMMAND}\``);
63
+ return 1;
64
+ }
65
+ if (flags.has("--baseline")) {
66
+ await writeCatalogBaseline(config, entries, options);
67
+ say(`wrote ${options.catalogBaseline}: ${entries.filter((entry) => entry.description === "").length} undocumented component(s)`);
68
+ return 0;
69
+ }
70
+ const written = await writeCatalog(config);
71
+ say(written.entries === 0 ? `no component under ${options.componentRoots.join(", ")}; no catalog` : `wrote ${written.path}: ${written.entries} component(s)`);
72
+ return 0;
73
+ }
74
+
75
+ async function find(config, args) {
76
+ const { flags, words } = parse(args);
77
+ if (words.length === 0) {
78
+ console.error("qc ui find <words...>");
79
+ return 1;
80
+ }
81
+ const { entries } = await scanComponents(config);
82
+ const found = findComponents(entries, words);
83
+ if (flags.has("--json")) say(JSON.stringify(found.map(({ entry, score }) => ({ ...entry, score })), null, 2));
84
+ else for (const one of found) say(formatFound(one));
85
+ return 0;
86
+ }
87
+
88
+ async function dupes(config, args) {
89
+ const { flags } = parse(args);
90
+ const { options, files, entries, ts } = await scanComponents(config);
91
+ const found = ts ? findDupes(ts, files, { entries, callees: options.classCallees, ...options.dupes }) : [];
92
+ if (flags.has("--baseline")) {
93
+ await writeFile(path.join(config.root, options.dupes.baseline), `${JSON.stringify(baselineOfFindings(found), null, 2)}\n`);
94
+ say(`wrote ${options.dupes.baseline}: ${found.length} finding(s)`);
95
+ return 0;
96
+ }
97
+ if (flags.has("--json")) {
98
+ say(JSON.stringify(found, null, 2));
99
+ return 0;
100
+ }
101
+ const titles = { "class-string": "Repeated class strings", "component-name": "Repeated component names", "jsx-tree": "Near-equal JSX trees" };
102
+ for (const kind of Object.keys(titles)) {
103
+ const ofKind = found.filter((one) => one.kind === kind);
104
+ say(`${titles[kind]}: ${ofKind.length}`);
105
+ for (const one of ofKind) {
106
+ const where = one.locations ? one.locations.join(" ~ ") : one.files.join(", ");
107
+ say(` ${kind === "class-string" ? `"${one.key}"` : one.key}\n ${where}`);
108
+ }
109
+ }
110
+ return 0;
111
+ }
112
+
113
+ /** The map of `--map`: inline JSON, or the path of a JSON file. */
114
+ function mapOf(value, root) {
115
+ if (typeof value !== "string") throw new Error("--map needs a JSON object, or the path of a JSON file");
116
+ const text = value.trimStart().startsWith("{") ? value : readFileSync(path.resolve(root, value), "utf8");
117
+ return parseMap(text);
118
+ }
119
+
120
+ async function stylesheets(config, listed) {
121
+ const css = await readFiles(config.root, listed.filter((rel) => rel.endsWith(".css")));
122
+ return css.filter((file) => file.contents.includes("@theme")).flatMap((file) => themeVariables(file.contents));
123
+ }
124
+
125
+ async function codemod(config, args) {
126
+ const { flags } = parse(args, ["--map"]);
127
+ const options = uiOptions(config);
128
+ const ts = requireTypeScript(config.root);
129
+ const listed = await listFiles(config);
130
+ const files = await clientSourceFiles(config, listed);
131
+
132
+ if (flags.has("--suggest")) {
133
+ const counts = new Map();
134
+ for (const file of files) {
135
+ for (const [token, count] of arbitraryTokens(ts, file.path, file.contents, options.classCallees)) counts.set(token, (counts.get(token) ?? 0) + count);
136
+ }
137
+ for (const line of suggest(counts, await stylesheets(config, listed))) {
138
+ say(`${String(line.count).padStart(5)} ${line.token}${line.variable ? ` -> ${line.variable}: ${line.value}` : ""}`);
139
+ }
140
+ say(`${counts.size} arbitrary-value token(s)`);
141
+ return 0;
142
+ }
143
+
144
+ let map;
145
+ try {
146
+ map = mapOf(flags.get("--map"), config.root);
147
+ } catch (cause) {
148
+ console.error(`qc ui codemod: ${cause.message}`);
149
+ return 1;
150
+ }
151
+ let total = 0;
152
+ let touched = 0;
153
+ for (const file of files) {
154
+ const out = codemodSource(ts, file.path, file.contents, map, options.classCallees);
155
+ if (out.count === 0) continue;
156
+ total += out.count;
157
+ touched += 1;
158
+ say(`${file.path} ${out.count}`);
159
+ if (flags.has("--write")) await writeFile(path.join(config.root, file.path), out.text);
160
+ }
161
+ say(`${total} token(s) in ${touched} file(s)${flags.has("--write") ? " rewritten" : "; a dry run, pass --write to apply"}`);
162
+ return 0;
163
+ }
164
+
165
+ const COMMANDS = { catalog, find, dupes, codemod };
166
+
167
+ /** @returns {Promise<number>} the exit code */
168
+ export async function runUi(config, args) {
169
+ const [name, ...rest] = args;
170
+ const run = COMMANDS[name];
171
+ if (!run) {
172
+ say(USAGE);
173
+ return name === undefined || name === "help" ? 0 : 1;
174
+ }
175
+ try {
176
+ return await run(config, rest);
177
+ } catch (cause) {
178
+ console.error(`qc ui ${name}: ${cause.message}`);
179
+ return 1;
180
+ }
181
+ }
@@ -0,0 +1,137 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { test } from "node:test";
6
+ import { load } from "../config.mjs";
7
+ import { runCheck } from "./check.mjs";
8
+ import { runUi } from "./ui.mjs";
9
+
10
+ const ROOT_UI = "frontend/src/platform/ui";
11
+ // A project with no feature folder also trips the unrelated root check.
12
+ const uiProblems = async (config) => (await runCheck(config)).problems.filter((problem) => problem.rule !== "unfound-root");
13
+
14
+ function project(files, config = {}) {
15
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-ui-"));
16
+ writeFileSync(path.join(root, "qc.config.json"), JSON.stringify(config));
17
+ for (const [rel, contents] of Object.entries(files)) {
18
+ mkdirSync(path.dirname(path.join(root, rel)), { recursive: true });
19
+ writeFileSync(path.join(root, rel), contents);
20
+ }
21
+ return root;
22
+ }
23
+
24
+ async function ui(root, ...args) {
25
+ const out = [];
26
+ const err = [];
27
+ const { log, error } = console;
28
+ console.log = (line) => out.push(String(line));
29
+ console.error = (line) => err.push(String(line));
30
+ try {
31
+ const code = await runUi(load(root), args);
32
+ return { code, out: out.join("\n"), err: err.join("\n") };
33
+ } finally {
34
+ console.log = log;
35
+ console.error = error;
36
+ }
37
+ }
38
+
39
+ const FILES = {
40
+ [`${ROOT_UI}/button.tsx`]: `/** A pressable control. */\nexport function Button({ label }: { label: string }) { return <button className="text-[11px] rounded-[4px]">{label}</button>; }\n`,
41
+ [`${ROOT_UI}/panel.tsx`]: `export const Panel = () => <div className={cn("text-[11px]")} />;\n`,
42
+ };
43
+
44
+ test("qc ui catalog writes the catalog, --check passes then fails once a component changes", async () => {
45
+ const root = project(FILES);
46
+ try {
47
+ assert.match((await ui(root, "catalog")).out, /wrote docs\/ui-catalog\.md: 2 component/);
48
+ const text = readFileSync(path.join(root, "docs/ui-catalog.md"), "utf8");
49
+ assert.match(text, /`Button`/);
50
+ assert.equal((await ui(root, "catalog", "--check")).code, 0);
51
+ writeFileSync(path.join(root, ROOT_UI, "card.tsx"), "export const Card = () => null;\n");
52
+ const stale = await ui(root, "catalog", "--check");
53
+ assert.equal(stale.code, 1);
54
+ assert.match(stale.err, /stale/);
55
+ assert.equal(JSON.parse((await ui(root, "catalog", "--json")).out).length, 3);
56
+ } finally {
57
+ rmSync(root, { recursive: true, force: true });
58
+ }
59
+ });
60
+
61
+ test("a repository with no component under its roots gets no catalog and no failure", async () => {
62
+ const root = project({ "src/readme.txt": "none" });
63
+ try {
64
+ assert.match((await ui(root, "catalog")).out, /no catalog/);
65
+ assert.equal(existsSync(path.join(root, "docs/ui-catalog.md")), false);
66
+ const config = { ...load(root), gates: { ...load(root).gates, "ui-catalog": true, "ui-dupes": true } };
67
+ assert.deepEqual(await uiProblems(config), []);
68
+ } finally {
69
+ rmSync(root, { recursive: true, force: true });
70
+ }
71
+ });
72
+
73
+ test("qc ui find prints name, path and description of the nearest entries", async () => {
74
+ const root = project(FILES);
75
+ try {
76
+ const { out } = await ui(root, "find", "pressable", "button");
77
+ assert.equal(out, `Button — ${ROOT_UI}/button.tsx — A pressable control.`);
78
+ } finally {
79
+ rmSync(root, { recursive: true, force: true });
80
+ }
81
+ });
82
+
83
+ test("qc ui codemod is a dry run until --write, and --suggest counts arbitrary values", async () => {
84
+ const root = project(FILES);
85
+ const map = JSON.stringify({ "text-[11px]": "text-2xs" });
86
+ try {
87
+ const dry = await ui(root, "codemod", "--map", map);
88
+ assert.match(dry.out, /button\.tsx {2}1/);
89
+ assert.match(dry.out, /2 token\(s\) in 2 file\(s\); a dry run/);
90
+ assert.match(readFileSync(path.join(root, ROOT_UI, "button.tsx"), "utf8"), /text-\[11px\]/);
91
+ await ui(root, "codemod", "--map", map, "--write");
92
+ assert.match(readFileSync(path.join(root, ROOT_UI, "button.tsx"), "utf8"), /className="text-2xs rounded-\[4px\]"/);
93
+ const suggestion = await ui(root, "codemod", "--suggest");
94
+ assert.match(suggestion.out, /1 {2}rounded-\[4px\]/);
95
+ assert.equal((await ui(root, "codemod")).code, 1);
96
+ } finally {
97
+ rmSync(root, { recursive: true, force: true });
98
+ }
99
+ });
100
+
101
+ test("the ui-catalog gate fails an undocumented component and a stale catalog, and a baseline excuses and then must shrink", async () => {
102
+ const root = project(FILES);
103
+ const gated = () => ({ ...load(root), gates: { ...load(root).gates, "ui-catalog": true } });
104
+ try {
105
+ await ui(root, "catalog");
106
+ const first = (await uiProblems(gated())).filter((problem) => problem.rule.endsWith("component") || problem.rule.includes("catalog") || problem.rule.includes("baseline"));
107
+ assert.deepEqual(first.map((problem) => [problem.rule, problem.path]), [["undocumented-component", `${ROOT_UI}/panel.tsx:1`]]);
108
+
109
+ await ui(root, "catalog", "--baseline");
110
+ assert.deepEqual((await uiProblems(gated())), []);
111
+
112
+ writeFileSync(path.join(root, ROOT_UI, "panel.tsx"), `/** A panel. */\nexport const Panel = () => <div />;\n`);
113
+ await ui(root, "catalog");
114
+ const shrunk = (await uiProblems(gated()));
115
+ assert.deepEqual(shrunk.map((problem) => problem.rule), ["stale-baseline"]);
116
+ } finally {
117
+ rmSync(root, { recursive: true, force: true });
118
+ }
119
+ });
120
+
121
+ test("the ui-dupes gate fails a finding outside the baseline and the baseline only shrinks", async () => {
122
+ const files = {
123
+ [`${ROOT_UI}/a/card.tsx`]: "/** A card. */\nexport const Card = () => null;\n",
124
+ [`${ROOT_UI}/b/card.tsx`]: "/** Another card. */\nexport const Card = () => null;\n",
125
+ };
126
+ const root = project(files);
127
+ const gated = () => ({ ...load(root), gates: { ...load(root).gates, "ui-dupes": true } });
128
+ try {
129
+ assert.deepEqual((await uiProblems(gated())).map((problem) => problem.rule), ["duplicate-component-name"]);
130
+ await ui(root, "dupes", "--baseline");
131
+ assert.deepEqual((await uiProblems(gated())), []);
132
+ rmSync(path.join(root, ROOT_UI, "b"), { recursive: true });
133
+ assert.deepEqual((await uiProblems(gated())).map((problem) => problem.rule), ["stale-baseline"]);
134
+ } finally {
135
+ rmSync(root, { recursive: true, force: true });
136
+ }
137
+ });
@@ -0,0 +1,211 @@
1
+ // `qc watch`: block until the first event among the pull requests, Codex jobs and workflow runs it watches.
2
+ // The wait is a shell command, so it costs no model tokens, and its exit is the event.
3
+
4
+ import { spawnSync } from "node:child_process";
5
+ import { closeSync, fstatSync, openSync, readSync } from "node:fs";
6
+ import path from "node:path";
7
+
8
+ const DEFAULT_MAX_MINUTES = 55;
9
+ const DEFAULT_INTERVAL_SECONDS = 60;
10
+ const QUEUED_LIMIT_MS = 15 * 60_000;
11
+ const CODEX_TAIL_BYTES = 2048;
12
+ const GH_TIMEOUT_MS = 20_000;
13
+ const SHA_SUFFIX = /^(.+)@([0-9a-f]{7,40})$/i;
14
+ const FAILED_CONCLUSIONS = new Set(["FAILURE", "CANCELLED", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE"]);
15
+ const FAILED_STATES = new Set(["FAILURE", "ERROR"]);
16
+
17
+ export const EXIT = { PASSED: 0, BAD_INPUT: 1, TIMEOUT: 4, FAILED: 5, QUEUED: 6 };
18
+
19
+ const USAGE =
20
+ "usage: qc watch [--pr <n>]... [--codex <wrapper.log>]... [--run <workflow>@<branch>[@<sha>]]... [--max <minutes>] [--repo <owner/name>] [--interval <seconds>]\n" +
21
+ "exit 0 the item finished well, 1 bad input, 4 the bound passed, 5 a check or run failed, 6 a job stayed queued past 15 minutes";
22
+
23
+ const positive = (flag, text) => {
24
+ const value = Number(text);
25
+ if (!Number.isInteger(value) || value < 1) throw new Error(`${flag} must be a positive integer, got ${text}`);
26
+ return value;
27
+ };
28
+
29
+ /** @returns the items to watch and the settings; throws an Error naming the bad flag. */
30
+ export function parseWatchArgs(argv) {
31
+ const parsed = { prs: [], codex: [], runs: [], repo: undefined, maxMinutes: DEFAULT_MAX_MINUTES, intervalSeconds: DEFAULT_INTERVAL_SECONDS };
32
+ for (let index = 0; index < argv.length; index += 2) {
33
+ const flag = argv[index];
34
+ const value = argv[index + 1];
35
+ if (!["--pr", "--codex", "--run", "--max", "--repo", "--interval"].includes(flag)) throw new Error(`unknown argument ${flag}`);
36
+ if (value === undefined) throw new Error(`${flag} needs a value`);
37
+ if (flag === "--pr") parsed.prs.push(positive(flag, value));
38
+ else if (flag === "--codex") parsed.codex.push(path.resolve(value));
39
+ else if (flag === "--run") {
40
+ const at = value.indexOf("@");
41
+ if (at < 1 || at === value.length - 1) throw new Error(`--run needs <workflow>@<branch>[@<sha>], got ${value}`);
42
+ const rest = value.slice(at + 1);
43
+ const pinned = SHA_SUFFIX.exec(rest);
44
+ parsed.runs.push({ workflow: value.slice(0, at), branch: pinned ? pinned[1] : rest, sha: pinned?.[2] });
45
+ } else if (flag === "--max") parsed.maxMinutes = positive(flag, value);
46
+ else if (flag === "--interval") parsed.intervalSeconds = positive(flag, value);
47
+ else parsed.repo = value;
48
+ }
49
+ if (parsed.prs.length + parsed.codex.length + parsed.runs.length === 0) throw new Error("name at least one item: --pr, --codex or --run");
50
+ return parsed;
51
+ }
52
+
53
+ /**
54
+ * PowerShell 5.1 writes `*>` as UTF-16LE with a BOM, so the first two bytes pick the decoder.
55
+ * When the file is longer than 2 KB, the read starts one character early and the text up to the first
56
+ * newline is dropped, so a line that the cut split never matches.
57
+ * @returns the last 2 KB of a file as whole lines of text, or null when it cannot be read yet.
58
+ */
59
+ function readTail(file) {
60
+ let fd;
61
+ try {
62
+ fd = openSync(file, "r");
63
+ const size = fstatSync(fd).size;
64
+ const bom = Buffer.alloc(Math.min(size, 2));
65
+ readSync(fd, bom, 0, bom.length, 0);
66
+ const utf16 = bom.length === 2 && bom[0] === 0xff && bom[1] === 0xfe;
67
+ const unit = utf16 ? 2 : 1;
68
+ const cut = size > CODEX_TAIL_BYTES;
69
+ let start = cut ? size - CODEX_TAIL_BYTES - unit : 0;
70
+ if (utf16 && start % 2 === 1) start += 1;
71
+ const buffer = Buffer.alloc(size - start);
72
+ readSync(fd, buffer, 0, buffer.length, start);
73
+ const text = buffer.toString(utf16 ? "utf16le" : "utf8");
74
+ if (!cut) return text.replace(/^/, "");
75
+ const newline = text.indexOf("\n");
76
+ return newline < 0 ? "" : text.slice(newline + 1);
77
+ } catch {
78
+ return null;
79
+ } finally {
80
+ if (fd !== undefined) closeSync(fd);
81
+ }
82
+ }
83
+
84
+ const parseJson = (text) => {
85
+ if (text === null) return null;
86
+ try {
87
+ return JSON.parse(text);
88
+ } catch {
89
+ return null;
90
+ }
91
+ };
92
+
93
+ /** @returns "failed", "queued", "pending", or "passed" for one rollup entry, a check run or a status context. */
94
+ function entryState(entry) {
95
+ if (entry.__typename === "StatusContext" || entry.context !== undefined) {
96
+ if (FAILED_STATES.has(entry.state)) return "failed";
97
+ return entry.state === "SUCCESS" ? "passed" : "pending";
98
+ }
99
+ if (entry.status !== "COMPLETED") return entry.status === "QUEUED" ? "queued" : "pending";
100
+ if (FAILED_CONCLUSIONS.has(entry.conclusion)) return "failed";
101
+ return "passed";
102
+ }
103
+
104
+ /**
105
+ * Watches one pull request. The queued timers belong to a head, so a new head starts them over.
106
+ * @returns a function that polls once and answers `{ state, detail, code }` for an event, or null.
107
+ */
108
+ function pullRequestWatcher(number, { repo, gh, now }) {
109
+ let head = null;
110
+ let queuedSince = new Map();
111
+ const args = ["pr", "view", String(number), "--json", "headRefOid,statusCheckRollup", ...(repo ? ["-R", repo] : [])];
112
+ return () => {
113
+ const view = parseJson(gh(args));
114
+ if (!view || !Array.isArray(view.statusCheckRollup)) return null;
115
+ if (view.headRefOid !== head) {
116
+ head = view.headRefOid;
117
+ queuedSince = new Map();
118
+ }
119
+ const at = now();
120
+ const states = view.statusCheckRollup.map((entry) => [entry.name ?? entry.context, entryState(entry)]);
121
+ if (states.some(([, state]) => state === "failed")) return { state: "failed", detail: head, code: EXIT.FAILED };
122
+ for (const [name] of [...queuedSince]) if (!states.some(([other, state]) => other === name && state === "queued")) queuedSince.delete(name);
123
+ for (const [name, state] of states) if (state === "queued" && !queuedSince.has(name)) queuedSince.set(name, at);
124
+ if ([...queuedSince.values()].some((since) => at - since > QUEUED_LIMIT_MS)) return { state: "queued", detail: head, code: EXIT.QUEUED };
125
+ if (states.length > 0 && states.every(([, state]) => state === "passed")) return { state: "passed", detail: head, code: EXIT.PASSED };
126
+ return null;
127
+ };
128
+ }
129
+
130
+ function codexWatcher(file) {
131
+ return () => {
132
+ const tail = readTail(file);
133
+ const line = tail?.split(/\r?\n/).reverse().find((text) => text.startsWith("exit "));
134
+ return line === undefined ? null : { state: "exit", detail: line.slice("exit ".length).trim(), code: EXIT.PASSED };
135
+ };
136
+ }
137
+
138
+ /**
139
+ * Watches one workflow on one branch. Only a run of the armed head counts: the head the branch has at each poll,
140
+ * or the one that `@<sha>` pins. A run of an earlier head never fires.
141
+ */
142
+ function runWatcher({ workflow, branch, sha }, { repo, gh }) {
143
+ const headArgs = ["api", `repos/${repo ?? "{owner}/{repo}"}/commits/${branch}`, "--jq", ".sha"];
144
+ const listArgs = ["run", "list", "--workflow", workflow, "--branch", branch, "--limit", "20", "--json", "status,conclusion,headSha", ...(repo ? ["-R", repo] : [])];
145
+ return () => {
146
+ const head = sha ?? gh(headArgs)?.trim();
147
+ if (!head) return null;
148
+ const latest = parseJson(gh(listArgs))?.find((run) => typeof run.headSha === "string" && run.headSha.startsWith(head.toLowerCase()) || run.headSha === head);
149
+ if (!latest || latest.status !== "completed") return null;
150
+ return latest.conclusion === "success"
151
+ ? { state: "passed", detail: latest.headSha, code: EXIT.PASSED }
152
+ : { state: "failed", detail: latest.headSha, code: EXIT.FAILED };
153
+ };
154
+ }
155
+
156
+ /** @returns gh's stdout on exit 0; throws an Error with gh's message when gh fails, times out, or is missing. */
157
+ function readGh(args) {
158
+ const result = spawnSync("gh", args, { encoding: "utf8", windowsHide: true, timeout: GH_TIMEOUT_MS });
159
+ if (result.status === 0) return result.stdout ?? "";
160
+ const reason = (result.stderr ?? "").split(/\r?\n/).find((line) => line.trim()) ?? result.error?.message ?? `gh exited ${result.status}`;
161
+ throw new Error(reason.trim());
162
+ }
163
+
164
+ const realSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
165
+
166
+ /**
167
+ * A gh error writes one `watch: gh failed: <first line>` line to stderr and the wait goes on. It is never an event.
168
+ * @param deps `gh` returns stdout, null, or throws; `say`, `warn`, `now` and `sleep` replace the output and the clock, for a test.
169
+ * @returns the exit code: 0 an item finished well, 4 the bound passed, 5 a check or run failed, 6 a job stayed queued.
170
+ */
171
+ export async function runWatch(argv, { gh = readGh, say = console.log, warn = console.error, now = Date.now, sleep = realSleep } = {}) {
172
+ let parsed;
173
+ try {
174
+ parsed = parseWatchArgs(argv);
175
+ } catch (error) {
176
+ console.error(`${error.message}\n${USAGE}`);
177
+ return EXIT.BAD_INPUT;
178
+ }
179
+ const read = (args) => {
180
+ try {
181
+ const out = gh(args);
182
+ if (out === null) warn("watch: gh failed: no answer");
183
+ return out;
184
+ } catch (error) {
185
+ warn(`watch: gh failed: ${String(error?.message ?? error).split(/\r?\n/)[0]}`);
186
+ return null;
187
+ }
188
+ };
189
+ const context = { repo: parsed.repo, gh: read, now };
190
+ const watchers = [
191
+ ...parsed.prs.map((number) => ({ item: `pr:${number}`, poll: pullRequestWatcher(number, context) })),
192
+ ...parsed.codex.map((file) => ({ item: `codex:${file}`, poll: codexWatcher(file) })),
193
+ ...parsed.runs.map((entry) => ({ item: `run:${entry.workflow}@${entry.branch}${entry.sha ? `@${entry.sha}` : ""}`, poll: runWatcher(entry, context) })),
194
+ ];
195
+ const deadline = now() + parsed.maxMinutes * 60_000;
196
+ for (;;) {
197
+ for (const { item, poll } of watchers) {
198
+ const event = poll();
199
+ if (event) {
200
+ say(`EVENT ${item} ${event.state} ${event.detail}`);
201
+ return event.code;
202
+ }
203
+ }
204
+ const remaining = deadline - now();
205
+ if (remaining <= 0) {
206
+ say("EVENT timeout");
207
+ return EXIT.TIMEOUT;
208
+ }
209
+ await sleep(Math.min(parsed.intervalSeconds * 1000, remaining));
210
+ }
211
+ }