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
@@ -0,0 +1,246 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { test } from "node:test";
6
+ import { parseWatchArgs, runWatch } from "./watch.mjs";
7
+
8
+ const MIN = 60_000;
9
+
10
+ /** A clock that the sleep advances, so a bound of 55 minutes costs no time. */
11
+ function fakeClock() {
12
+ const clock = { now: 0 };
13
+ return { clock, now: () => clock.now, sleep: async (ms) => void (clock.now += ms) };
14
+ }
15
+
16
+ /** `answers` is a list of stdout values, one per gh call; the last one repeats. A function answer gets the arguments. `null` is a failing gh. */
17
+ function stubGh(answers) {
18
+ const calls = [];
19
+ const gh = (args) => {
20
+ calls.push(args);
21
+ const answer = answers[Math.min(calls.length - 1, answers.length - 1)];
22
+ return typeof answer === "function" ? answer(args) : answer;
23
+ };
24
+ return { gh, calls };
25
+ }
26
+
27
+ const rollup = (head, ...checks) => JSON.stringify({ headRefOid: head, statusCheckRollup: checks });
28
+ const check = (name, status, conclusion = "") => ({ __typename: "CheckRun", name, status, conclusion });
29
+
30
+ async function watch(argv, { gh, time = fakeClock() } = {}) {
31
+ const lines = [];
32
+ const warnings = [];
33
+ const code = await runWatch(argv, { gh, say: (line) => lines.push(line), warn: (line) => warnings.push(line), now: time.now, sleep: time.sleep });
34
+ return { code, lines, warnings, time };
35
+ }
36
+
37
+ test("parseWatchArgs reads repeated flags and the defaults", () => {
38
+ const parsed = parseWatchArgs(["--pr", "7", "--pr", "8", "--codex", "a.log", "--run", "ci.yml@feat/x", "--repo", "o/r"]);
39
+ assert.deepEqual(parsed.prs, [7, 8]);
40
+ assert.equal(parsed.codex.length, 1);
41
+ assert.deepEqual(parsed.runs, [{ workflow: "ci.yml", branch: "feat/x", sha: undefined }]);
42
+ assert.deepEqual(parseWatchArgs(["--run", "ci.yml@feat/x@abc1234"]).runs, [{ workflow: "ci.yml", branch: "feat/x", sha: "abc1234" }]);
43
+ assert.equal(parsed.repo, "o/r");
44
+ assert.equal(parsed.maxMinutes, 55);
45
+ assert.equal(parsed.intervalSeconds, 60);
46
+ });
47
+
48
+ test("parseWatchArgs refuses no item, a bad number, a bad run, and an unknown flag", () => {
49
+ assert.throws(() => parseWatchArgs([]), /--pr/);
50
+ assert.throws(() => parseWatchArgs(["--pr", "x"]), /--pr/);
51
+ assert.throws(() => parseWatchArgs(["--pr", "1", "--max", "0"]), /--max/);
52
+ assert.throws(() => parseWatchArgs(["--run", "ci.yml"]), /--run/);
53
+ assert.throws(() => parseWatchArgs(["--run", "ci.yml@"]), /--run/);
54
+ assert.throws(() => parseWatchArgs(["--pr", "1", "--nope"]), /--nope/);
55
+ assert.throws(() => parseWatchArgs(["--pr"]), /--pr/);
56
+ });
57
+
58
+ test("--pr exits 0 when every check completes and passes", async () => {
59
+ const done = rollup("abc123", check("a", "COMPLETED", "SUCCESS"), check("b", "COMPLETED", "SKIPPED"));
60
+ const { gh, calls } = stubGh([rollup("abc123", check("a", "IN_PROGRESS")), done]);
61
+ const { code, lines } = await watch(["--pr", "7", "--repo", "o/r"], { gh });
62
+ assert.equal(code, 0);
63
+ assert.deepEqual(lines, ["EVENT pr:7 passed abc123"]);
64
+ assert.deepEqual(calls[0], ["pr", "view", "7", "--json", "headRefOid,statusCheckRollup", "-R", "o/r"]);
65
+ });
66
+
67
+ test("--pr exits 5 as soon as one check fails, while others still run", async () => {
68
+ const { gh } = stubGh([rollup("abc123", check("a", "IN_PROGRESS"), check("b", "COMPLETED", "FAILURE"))]);
69
+ const { code, lines } = await watch(["--pr", "7"], { gh });
70
+ assert.equal(code, 5);
71
+ assert.deepEqual(lines, ["EVENT pr:7 failed abc123"]);
72
+ });
73
+
74
+ test("--pr counts a failed status context", async () => {
75
+ const { gh } = stubGh([rollup("h1", { __typename: "StatusContext", context: "ci", state: "FAILURE" })]);
76
+ assert.equal((await watch(["--pr", "7"], { gh })).code, 5);
77
+ });
78
+
79
+ test("--pr exits 6 when a job stays QUEUED past 15 minutes", async () => {
80
+ const { gh } = stubGh([rollup("abc123", check("a", "QUEUED"))]);
81
+ const { code, lines, time } = await watch(["--pr", "7"], { gh });
82
+ assert.equal(code, 6);
83
+ assert.deepEqual(lines, ["EVENT pr:7 queued abc123"]);
84
+ assert.ok(time.clock.now > 15 * MIN && time.clock.now <= 16 * MIN, `waited ${time.clock.now}`);
85
+ });
86
+
87
+ test("a new head restarts the queued timer for that PR", async () => {
88
+ // Head one queues for 14 minutes. Head two then queues: the timer starts over, so exit 6 comes 15 minutes later.
89
+ const time = fakeClock();
90
+ const { gh } = stubGh([() => rollup(time.clock.now < 14 * MIN ? "head1" : "head2", check("a", "QUEUED"))]);
91
+ const { code, lines } = await watch(["--pr", "7"], { gh, time });
92
+ assert.equal(code, 6);
93
+ assert.deepEqual(lines, ["EVENT pr:7 queued head2"]);
94
+ assert.ok(time.clock.now > 29 * MIN, `waited ${time.clock.now}`);
95
+ });
96
+
97
+ test("a failing gh read is retried, and is not an event", async () => {
98
+ const { gh } = stubGh([null, "not json", rollup("h", check("a", "COMPLETED", "SUCCESS"))]);
99
+ assert.equal((await watch(["--pr", "7"], { gh })).code, 0);
100
+ });
101
+
102
+ test("the bound prints EVENT timeout and exits 4", async () => {
103
+ const { gh } = stubGh([rollup("h", check("a", "IN_PROGRESS"))]);
104
+ const { code, lines, time } = await watch(["--pr", "7", "--max", "5"], { gh });
105
+ assert.equal(code, 4);
106
+ assert.deepEqual(lines, ["EVENT timeout"]);
107
+ assert.equal(time.clock.now, 5 * MIN);
108
+ });
109
+
110
+ test("the default bound is 55 minutes", async () => {
111
+ const { gh } = stubGh([rollup("h", check("a", "IN_PROGRESS"))]);
112
+ const { code, time } = await watch(["--pr", "7"], { gh });
113
+ assert.equal(code, 4);
114
+ assert.equal(time.clock.now, 55 * MIN);
115
+ });
116
+
117
+ function wrapper(t, text) {
118
+ const dir = mkdtempSync(path.join(os.tmpdir(), "qc-watch-"));
119
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
120
+ const file = path.join(dir, "wrapper.log");
121
+ if (text !== undefined) writeFileSync(file, text);
122
+ return file;
123
+ }
124
+
125
+ test("--codex exits 0 on a line that starts with `exit `", async (t) => {
126
+ const file = wrapper(t, "working\nmore output\nexit 2\n");
127
+ const { code, lines } = await watch(["--codex", file], { gh: () => null });
128
+ assert.equal(code, 0);
129
+ assert.deepEqual(lines, [`EVENT codex:${file} exit 2`]);
130
+ });
131
+
132
+ test("--codex ignores `exit` inside a line and a missing file, then times out", async (t) => {
133
+ const file = wrapper(t, "did not exit 1 yet\n");
134
+ assert.equal((await watch(["--codex", file, "--max", "2"], { gh: () => null })).code, 4);
135
+ const missing = path.join(path.dirname(file), "none.log");
136
+ assert.equal((await watch(["--codex", missing, "--max", "2"], { gh: () => null })).code, 4);
137
+ });
138
+
139
+ test("--codex reads only the last 2 KB", async (t) => {
140
+ const file = wrapper(t, `exit 9\n${"x".repeat(5000)}\n`);
141
+ assert.equal((await watch(["--codex", file, "--max", "2"], { gh: () => null })).code, 4);
142
+ });
143
+
144
+ test("--run exits 0 on a success and 5 on a failure", async () => {
145
+ const run = (status, conclusion) => (args) => (args[0] === "api" ? "deadbeef\n" : JSON.stringify([{ status, conclusion, headSha: "deadbeef" }]));
146
+ const pass = stubGh([run("in_progress", ""), run("in_progress", ""), run("completed", "success")]);
147
+ const first = await watch(["--run", "ci.yml@feat/x", "--repo", "o/r"], { gh: pass.gh });
148
+ assert.equal(first.code, 0);
149
+ assert.deepEqual(first.lines, ["EVENT run:ci.yml@feat/x passed deadbeef"]);
150
+ assert.deepEqual(pass.calls[0], ["api", "repos/o/r/commits/feat/x", "--jq", ".sha"]);
151
+ assert.deepEqual(pass.calls[1], ["run", "list", "--workflow", "ci.yml", "--branch", "feat/x", "--limit", "20", "--json", "status,conclusion,headSha", "-R", "o/r"]);
152
+ const fail = await watch(["--run", "ci.yml@feat/x"], { gh: stubGh([run("completed", "failure")]).gh });
153
+ assert.equal(fail.code, 5);
154
+ assert.deepEqual(fail.lines, ["EVENT run:ci.yml@feat/x failed deadbeef"]);
155
+ });
156
+
157
+ test("the first event among several items wins", async (t) => {
158
+ const file = wrapper(t, "exit 0\n");
159
+ const { gh } = stubGh([rollup("h", check("a", "IN_PROGRESS"))]);
160
+ const { code, lines } = await watch(["--pr", "7", "--codex", file], { gh });
161
+ assert.equal(code, 0);
162
+ assert.equal(lines.length, 1);
163
+ assert.match(lines[0], /^EVENT codex:/);
164
+ });
165
+
166
+
167
+ test("a --codex wrapper that PowerShell 5.1 wrote as UTF-16LE with a BOM fires on its exit line", async (t) => {
168
+ const file = wrapper(t);
169
+ writeFileSync(file, Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from("working\r\nexit 0\r\n", "utf16le")]));
170
+ const { code, lines } = await watch(["--codex", file], { gh: () => null });
171
+ assert.equal(code, 0);
172
+ assert.deepEqual(lines, [`EVENT codex:${file} exit 0`]);
173
+ });
174
+
175
+ test("a long UTF-16LE wrapper reads its tail at a character boundary", async (t) => {
176
+ const file = wrapper(t);
177
+ const text = `${"progress line that fills the log\r\n".repeat(200)}exit 3\r\n`;
178
+ writeFileSync(file, Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(text, "utf16le")]));
179
+ const { lines } = await watch(["--codex", file], { gh: () => null });
180
+ assert.deepEqual(lines, [`EVENT codex:${file} exit 3`]);
181
+ });
182
+
183
+ test("--codex drops the partial first line of a 2 KB tail, so a cut at `exit 1` mid-line is no event", async (t) => {
184
+ const quoted = `exit 1 is quoted in a long line${"k".repeat(2048)}`.slice(0, 2047);
185
+ const file = wrapper(t, `${"x".repeat(300)}-${quoted}\n`);
186
+ const { code, lines } = await watch(["--codex", file, "--max", "2"], { gh: () => null });
187
+ assert.equal(code, 4);
188
+ assert.deepEqual(lines, ["EVENT timeout"]);
189
+ });
190
+
191
+ test("--codex keeps a whole first line when the 2 KB cut lands on a line start", async (t) => {
192
+ const file = wrapper(t, `${"x".repeat(100)}\nexit 4\n${"z".repeat(2041)}`);
193
+ const { lines } = await watch(["--codex", file], { gh: () => null });
194
+ assert.deepEqual(lines, [`EVENT codex:${file} exit 4`]);
195
+ });
196
+
197
+ test("--run ignores a completed run on the previous head, and fires on the run of the current head", async () => {
198
+ const time = fakeClock();
199
+ const stale = { status: "completed", conclusion: "success", headSha: "oldhead" };
200
+ const fresh = { status: "completed", conclusion: "failure", headSha: "newhead" };
201
+ const answer = (args) => {
202
+ if (args[0] === "api") return "newhead\n";
203
+ return JSON.stringify(time.clock.now < 2 * MIN ? [stale] : [fresh, stale]);
204
+ };
205
+ const { code, lines } = await watch(["--run", "ci.yml@feat/x"], { gh: stubGh([answer]).gh, time });
206
+ assert.equal(code, 5);
207
+ assert.deepEqual(lines, ["EVENT run:ci.yml@feat/x failed newhead"]);
208
+ });
209
+
210
+ test("--run <wf>@<branch> never fires on a run of another head, so it times out", async () => {
211
+ const answer = (args) => (args[0] === "api" ? "newhead\n" : JSON.stringify([{ status: "completed", conclusion: "success", headSha: "oldhead" }]));
212
+ const { code, lines } = await watch(["--run", "ci.yml@feat/x", "--max", "5"], { gh: stubGh([answer]).gh });
213
+ assert.equal(code, 4);
214
+ assert.deepEqual(lines, ["EVENT timeout"]);
215
+ });
216
+
217
+ test("--run <wf>@<branch>@<sha> pins the head and reads no branch head", async () => {
218
+ const runs = JSON.stringify([
219
+ { status: "completed", conclusion: "failure", headSha: "other99" },
220
+ { status: "completed", conclusion: "success", headSha: "abc1234" },
221
+ ]);
222
+ const { gh, calls } = stubGh([runs]);
223
+ const { code, lines } = await watch(["--run", "ci.yml@feat/x@abc1234"], { gh });
224
+ assert.equal(code, 0);
225
+ assert.deepEqual(lines, ["EVENT run:ci.yml@feat/x@abc1234 passed abc1234"]);
226
+ assert.ok(calls.every((args) => args[0] === "run"), "no api call");
227
+ });
228
+
229
+ test("a gh error writes one stderr line with the first line of the error, and the wait goes on", async () => {
230
+ let calls = 0;
231
+ const gh = () => {
232
+ calls += 1;
233
+ if (calls === 1) throw new Error("HTTP 502 bad gateway\nmore detail");
234
+ return rollup("h", check("a", "COMPLETED", "SUCCESS"));
235
+ };
236
+ const { code, warnings, lines } = await watch(["--pr", "7"], { gh });
237
+ assert.equal(code, 0);
238
+ assert.deepEqual(warnings, ["watch: gh failed: HTTP 502 bad gateway"]);
239
+ assert.deepEqual(lines, ["EVENT pr:7 passed h"]);
240
+ });
241
+
242
+ test("a gh that answers null writes a stderr line and is not an event", async () => {
243
+ const { code, warnings } = await watch(["--pr", "7", "--max", "2"], { gh: () => null });
244
+ assert.equal(code, 4);
245
+ assert.ok(warnings.length >= 1 && warnings.every((line) => line.startsWith("watch: gh failed: ")));
246
+ });
package/src/config.mjs CHANGED
@@ -15,6 +15,10 @@ export const defaults = {
15
15
  featureDir: "features",
16
16
  publicFile: "index",
17
17
 
18
+ // `qc codex-implement`. `compactTokens` is the backstop that compacts a runaway session; one item
19
+ // runs in a fresh session and should finish under 200K.
20
+ codex: { compactTokens: 300000 },
21
+
18
22
  docs: {
19
23
  root: "docs",
20
24
  decisions: "docs/decisions.md",
@@ -403,8 +407,12 @@ export const defaults = {
403
407
  // Needs the composed contract, and the `yaml` peer to read it.
404
408
  "contract-idempotency": false,
405
409
  "contract-routes": false,
410
+ "contract-keys": false,
406
411
  // Needs `sagaKey.runners`, the names of a repository's saga runners.
407
412
  "saga-key": false,
413
+ // Each needs a repository to opt in: the UI it judges lives where only that repository knows.
414
+ "ui-catalog": false,
415
+ "ui-dupes": false,
408
416
  },
409
417
 
410
418
  // Gates that produce rather than inspect: a repository's codegen imports these and
@@ -463,6 +471,20 @@ export const defaults = {
463
471
  // Extra pipeline steps a repo composes in. The CLI never hardcodes a project's chain.
464
472
  pipeline: [],
465
473
 
474
+ // The UI tools: `qc ui`, and the `ui-catalog` and `ui-dupes` gates. A component is an exported React component
475
+ // under `componentRoots`, where `*` stands for one folder. `layers` names a layer by the folder that holds it.
476
+ // `catalog` is the generated catalog, and `catalogBaseline` lists the components that predate its gate.
477
+ // `classCallees` are the calls whose string arguments are class strings. `dupes` sets the shortest class
478
+ // string, the fewest files, and the baseline.
479
+ ui: {
480
+ componentRoots: ["frontend/src/platform/ui", "frontend/src/features/*/components"],
481
+ layers: { primitive: "frontend/src/platform/ui/primitives", pattern: "frontend/src/platform/ui/patterns" },
482
+ catalog: "docs/ui-catalog.md",
483
+ catalogBaseline: "ui-catalog.baseline.json",
484
+ classCallees: ["cn", "clsx", "cva", "twMerge"],
485
+ dupes: { minClassLength: 60, minFiles: 3, baseline: "ui-dupes.baseline.json" },
486
+ },
487
+
466
488
  // Files the browser rules apply to.
467
489
  clientFiles: ["frontend/src/**/*.{ts,tsx}"],
468
490
 
@@ -497,7 +519,10 @@ export const dispatchDefaults = {
497
519
  models: {},
498
520
  };
499
521
 
500
- const roleModels = (planning, working, other) => ({
522
+ // `watching` is the codex watcher, which only waits on a job. It defaults to `other`.
523
+ const roleModels = (planning, working, other, watching = other) => ({
524
+ codex: watching,
525
+ "architecture:codex": watching,
501
526
  "sdd-planner": planning,
502
527
  "architecture:sdd-planner": planning,
503
528
  "sdd-branch-reviewer": planning,
@@ -511,7 +536,7 @@ const roleModels = (planning, working, other) => ({
511
536
 
512
537
  // The default `swarm.dispatch.models` of each runtime that can run a session. A runtime calls only its own models.
513
538
  export const runtimeModels = {
514
- claude: roleModels(["opus"], ["sonnet"], ["sonnet", "haiku"]),
539
+ claude: roleModels(["opus"], ["sonnet"], ["sonnet", "haiku"], ["haiku", "sonnet"]),
515
540
  codex: roleModels(["gpt-6.1-sol"], ["gpt-6.1-sol"], ["gpt-6.1-sol"]),
516
541
  };
517
542
 
@@ -32,6 +32,9 @@ export const gateDescriptions = Object.freeze({
32
32
  "doc-claims": "A state-claim block in a document still matches the file it counts",
33
33
  "contract-idempotency": "Every write of the API contract declares its idempotency key or is listed in the ledger, and a ledger entry fails when it no longer owes the key or is new since the merge base",
34
34
  "saga-key": "A saga runner never takes a key minted at the call, so a retry resumes the saga rather than starting a second one",
35
+ "contract-keys": "No key of the composed contract ends with a dot or holds no value, the two marks of a YAML line that split a sentence",
36
+ "ui-catalog": "Every exported component under the UI roots carries a JSDoc sentence, and the generated component catalog matches the code",
37
+ "ui-dupes": "The same class string, component name or JSX tree is not written twice, except what a baseline holds",
35
38
  "contract-routes": "Every route a feature trigger declares is an operation of the API contract and the reverse, matched by method and path, and an exemption fails when it excuses nothing",
36
39
  });
37
40
 
@@ -0,0 +1,33 @@
1
+ // A YAML flow mapping such as `{ description: Rows, sorted. }` splits one sentence into a second key with
2
+ // no value. Redocly accepts it, so this gate reads the composed contract for the two marks it leaves.
3
+
4
+ const VALUE_KEYS = new Set(["example", "examples", "default", "const", "enum"]);
5
+
6
+ const pointer = (at, key) => `${at}/${String(key).replace(/~/g, "~0").replace(/\//g, "~1")}`;
7
+
8
+ /**
9
+ * @param {unknown} document the parsed contract
10
+ * @param {string} contract the contract path, as a problem names it
11
+ */
12
+ export function checkContractKeys(document, contract) {
13
+ const problems = [];
14
+ const visit = (node, at) => {
15
+ if (Array.isArray(node)) {
16
+ node.forEach((item, index) => visit(item, `${at}/${index}`));
17
+ return;
18
+ }
19
+ if (node === null || typeof node !== "object") return;
20
+ for (const [key, value] of Object.entries(node)) {
21
+ const here = pointer(at, key);
22
+ if (key.endsWith(".")) {
23
+ problems.push({ path: contract, rule: "contract-key-ends-with-dot", detail: `${here}: a key that ends with "." is the tail of a sentence the YAML split; quote the text it came from` });
24
+ }
25
+ if (value === null && !VALUE_KEYS.has(key)) {
26
+ problems.push({ path: contract, rule: "contract-null-value", detail: `${here} holds no value; give it one, or quote the text it was split from` });
27
+ }
28
+ if (!VALUE_KEYS.has(key) && !key.startsWith("x-")) visit(value, here);
29
+ }
30
+ };
31
+ visit(document, "#");
32
+ return problems;
33
+ }
@@ -0,0 +1,38 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { parse } from "yaml";
4
+ import { checkContractKeys } from "./contract-keys.mjs";
5
+
6
+ const SPLIT = [
7
+ "components:",
8
+ " schemas:",
9
+ " Row:",
10
+ " type: object",
11
+ " properties:",
12
+ " id: { type: string, description: Rows, sorted. }",
13
+ "",
14
+ ].join("\n");
15
+
16
+ test("a description split by a comma leaves a dotted key with no value, and both marks fail", () => {
17
+ const problems = checkContractKeys(parse(SPLIT), "api.yaml");
18
+ assert.deepEqual(problems.map((problem) => problem.rule).sort(), ["contract-key-ends-with-dot", "contract-null-value"]);
19
+ for (const problem of problems) assert.ok(problem.detail.startsWith("#/components/schemas/Row/properties/id/sorted."), problem.detail);
20
+ });
21
+
22
+ test("a key with no value fails, outside an example or a default", () => {
23
+ const problems = checkContractKeys(parse("components:\n schemas:\n Row:\n required:\n"), "api.yaml");
24
+ assert.deepEqual(problems.map((problem) => problem.rule), ["contract-null-value"]);
25
+ });
26
+
27
+ test("a quoted description, a null default, a null example, and an extension pass", () => {
28
+ const text = [
29
+ "components:",
30
+ " schemas:",
31
+ " Row:",
32
+ " properties:",
33
+ ' id: { type: string, description: "Rows, sorted." }',
34
+ ' note: { type: [string, "null"], default: null, example: { a: null }, x-note: { b: null } }',
35
+ "",
36
+ ].join("\n");
37
+ assert.deepEqual(checkContractKeys(parse(text), "api.yaml"), []);
38
+ });
@@ -18,7 +18,7 @@ export function checkMigrationNumbers(names, dir) {
18
18
  const problems = [];
19
19
  for (const [number, files] of byNumber) {
20
20
  if (files.length > 1) {
21
- problems.push({ path: dir, rule: "duplicate-migration-number", detail: `${files.sort().join(", ")} share number ${number}; give each migration its own` });
21
+ problems.push({ path: dir, rule: "duplicate-migration-number", detail: `${files.sort().join(", ")} share number ${number}; give each migration its own: \`qc migrations renumber --onto <base>\` moves this branch's migrations after the base's last` });
22
22
  }
23
23
  }
24
24
  const numbers = [...byNumber.keys()].sort((a, b) => a - b);
@@ -20,6 +20,7 @@ test("a duplicate prefix fails and names both files", () => {
20
20
  assert.equal(problems[0].path, DIR);
21
21
  assert.match(problems[0].detail, /0002_projects\.sql/);
22
22
  assert.match(problems[0].detail, /0002_sites\.sql/);
23
+ assert.match(problems[0].detail, /qc migrations renumber --onto <base>/);
23
24
  });
24
25
 
25
26
  test("a gap fails and names the missing numbers", () => {
@@ -0,0 +1,45 @@
1
+ // A component is described before anyone can reuse it. Every exported component under the configured
2
+ // roots carries a JSDoc sentence, and the generated catalog matches the code. A baseline lists the
3
+ // components that predate the gate; an entry that no longer fails is an error, so the list only shrinks.
4
+
5
+ import { sameCatalog } from "../ui/catalog.mjs";
6
+
7
+ const keyOf = (entry) => `${entry.path}#${entry.name}`;
8
+
9
+ /**
10
+ * @param {{name: string, path: string, line: number, description: string}[]} entries
11
+ * @param {{catalog: {path: string, actual: string | null, expected: string | null, command: string}, baseline: string[] | null, baselineFile: string}} options
12
+ * @returns {{path: string, rule: string, detail: string}[]}
13
+ */
14
+ export function checkUiCatalog(entries, { catalog, baseline, baselineFile }) {
15
+ const problems = [];
16
+ const excused = new Set(baseline ?? []);
17
+ const failing = new Set();
18
+
19
+ for (const entry of entries) {
20
+ if (entry.description !== "") continue;
21
+ failing.add(keyOf(entry));
22
+ if (excused.has(keyOf(entry))) continue;
23
+ problems.push({
24
+ path: `${entry.path}:${entry.line}`,
25
+ rule: "undocumented-component",
26
+ detail: `${entry.name} is exported with no JSDoc sentence; describe what it is for, so a reader can find it in the catalog before writing another`,
27
+ });
28
+ }
29
+ for (const key of [...excused].sort()) {
30
+ if (failing.has(key)) continue;
31
+ problems.push({
32
+ path: baselineFile,
33
+ rule: "stale-baseline",
34
+ detail: `${key} no longer fails; remove it from the baseline, or run \`qc ui catalog --baseline\``,
35
+ });
36
+ }
37
+ if (!sameCatalog(catalog.actual, catalog.expected)) {
38
+ const detail =
39
+ catalog.expected === null
40
+ ? `lists no component any more; remove it with \`${catalog.command}\``
41
+ : `is ${catalog.actual === null ? "missing" : "stale"}; write it with \`${catalog.command}\``;
42
+ problems.push({ path: catalog.path, rule: "stale-catalog", detail });
43
+ }
44
+ return problems;
45
+ }
@@ -0,0 +1,48 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { checkUiCatalog } from "./ui-catalog.mjs";
4
+
5
+ const documented = { name: "Button", path: "ui/button.tsx", line: 3, description: "A control." };
6
+ const bare = { name: "Grid", path: "ui/grid.tsx", line: 7, description: "" };
7
+ const fresh = { path: "docs/ui-catalog.md", actual: "same", expected: "same", command: "qc ui catalog" };
8
+ const options = (over = {}) => ({ catalog: fresh, baseline: null, baselineFile: "ui-catalog.baseline.json", ...over });
9
+
10
+ test("documented components and a fresh catalog pass", () => {
11
+ assert.deepEqual(checkUiCatalog([documented], options()), []);
12
+ });
13
+
14
+ test("an exported component with no JSDoc sentence fails, naming path:line", () => {
15
+ const [problem] = checkUiCatalog([documented, bare], options());
16
+ assert.equal(problem.rule, "undocumented-component");
17
+ assert.equal(problem.path, "ui/grid.tsx:7");
18
+ assert.match(problem.detail, /Grid/);
19
+ });
20
+
21
+ test("a stale catalog fails and names the command that writes it", () => {
22
+ const [problem] = checkUiCatalog([documented], options({ catalog: { ...fresh, actual: "old" } }));
23
+ assert.equal(problem.rule, "stale-catalog");
24
+ assert.match(problem.detail, /qc ui catalog/);
25
+ });
26
+
27
+ test("a catalog file that does not exist is stale when components exist", () => {
28
+ const [problem] = checkUiCatalog([documented], options({ catalog: { ...fresh, actual: null } }));
29
+ assert.equal(problem.rule, "stale-catalog");
30
+ });
31
+
32
+ test("a repository with no component and no catalog file passes", () => {
33
+ assert.deepEqual(checkUiCatalog([], options({ catalog: { ...fresh, actual: null, expected: null } })), []);
34
+ });
35
+
36
+ test("a baseline entry excuses its component", () => {
37
+ assert.deepEqual(checkUiCatalog([bare], options({ baseline: ["ui/grid.tsx#Grid"] })), []);
38
+ });
39
+
40
+ test("a baseline entry that no longer fails is an error, so the baseline only shrinks", () => {
41
+ const problems = checkUiCatalog([documented, bare], options({ baseline: ["ui/grid.tsx#Grid", "ui/button.tsx#Button", "ui/gone.tsx#Gone"] }));
42
+ assert.deepEqual(
43
+ problems.map((problem) => [problem.rule, problem.path]),
44
+ [["stale-baseline", "ui-catalog.baseline.json"], ["stale-baseline", "ui-catalog.baseline.json"]],
45
+ );
46
+ assert.match(problems[0].detail, /ui\/button\.tsx#Button/);
47
+ assert.match(problems[1].detail, /ui\/gone\.tsx#Gone/);
48
+ });
@@ -0,0 +1,36 @@
1
+ // The same UI is written once. A repeated class string, two components of one name, and two near-equal
2
+ // JSX trees fail unless a baseline holds them; a baseline entry that no longer occurs fails too, so the
3
+ // baseline only shrinks.
4
+
5
+ import { findingId } from "../ui/dupes.mjs";
6
+
7
+ const SAY = {
8
+ "class-string": "the same class string",
9
+ "component-name": "an exported component of the same name",
10
+ "jsx-tree": "a JSX tree that differs by a class or two",
11
+ };
12
+
13
+ /**
14
+ * @param {{kind: string, key: string, files: string[]}[]} findings
15
+ * @param {{baseline: string[] | null, baselineFile: string}} options `baseline` holds finding ids
16
+ * @returns {{path: string, rule: string, detail: string}[]}
17
+ */
18
+ export function checkUiDupes(findings, { baseline, baselineFile }) {
19
+ const excused = new Set(baseline ?? []);
20
+ const present = new Set(findings.map(findingId));
21
+ const problems = [];
22
+ for (const finding of findings) {
23
+ if (excused.has(findingId(finding))) continue;
24
+ const shown = finding.kind === "class-string" ? `"${finding.key.slice(0, 80)}${finding.key.length > 80 ? "..." : ""}"` : finding.key;
25
+ problems.push({
26
+ path: finding.files[0],
27
+ rule: `duplicate-${finding.kind}`,
28
+ detail: `${SAY[finding.kind] ?? finding.kind} (${shown}) is in ${finding.files.join(", ")}; reuse one, or extract it, or run \`qc ui dupes --baseline\``,
29
+ });
30
+ }
31
+ for (const id of [...excused].sort()) {
32
+ if (present.has(id)) continue;
33
+ problems.push({ path: baselineFile, rule: "stale-baseline", detail: `${id} no longer occurs; remove it from the baseline` });
34
+ }
35
+ return problems;
36
+ }
@@ -0,0 +1,29 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { checkUiDupes } from "./ui-dupes.mjs";
4
+
5
+ const card = { kind: "component-name", key: "Card", files: ["ui/a/card.tsx", "ui/b/card.tsx"] };
6
+ const classes = { kind: "class-string", key: "a b c", files: ["ui/a.tsx", "ui/b.tsx", "ui/c.tsx"] };
7
+ const options = (over = {}) => ({ baseline: null, baselineFile: "ui-dupes.baseline.json", ...over });
8
+
9
+ test("no finding passes", () => {
10
+ assert.deepEqual(checkUiDupes([], options()), []);
11
+ });
12
+
13
+ test("a finding outside the baseline fails, naming its files", () => {
14
+ const [problem] = checkUiDupes([card], options());
15
+ assert.equal(problem.rule, "duplicate-component-name");
16
+ assert.equal(problem.path, "ui/a/card.tsx");
17
+ assert.match(problem.detail, /ui\/b\/card\.tsx/);
18
+ });
19
+
20
+ test("a finding in the baseline passes", () => {
21
+ assert.deepEqual(checkUiDupes([card, classes], options({ baseline: ["component-name:Card", "class-string:a b c"] })), []);
22
+ });
23
+
24
+ test("a baseline entry that no longer occurs is an error, so the baseline only shrinks", () => {
25
+ const [problem] = checkUiDupes([card], options({ baseline: ["component-name:Card", "class-string:gone"] }));
26
+ assert.equal(problem.rule, "stale-baseline");
27
+ assert.equal(problem.path, "ui-dupes.baseline.json");
28
+ assert.match(problem.detail, /class-string:gone/);
29
+ });