architecture-harness 0.23.0 → 0.25.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 (71) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +20 -5
  3. package/src/cli/bash-command-guard.mjs +44 -5
  4. package/src/cli/bash-command-guard.test.mjs +35 -1
  5. package/src/cli/budget-guard.mjs +1 -0
  6. package/src/cli/budget-guard.test.mjs +7 -1
  7. package/src/cli/budget.mjs +3 -4
  8. package/src/cli/budget.test.mjs +5 -5
  9. package/src/cli/check-commands.mjs +82 -0
  10. package/src/cli/check-commands.test.mjs +190 -0
  11. package/src/cli/check.mjs +34 -13
  12. package/src/cli/ci-template.test.mjs +17 -15
  13. package/src/cli/cli.test.mjs +33 -2
  14. package/src/cli/commit-msg.mjs +12 -12
  15. package/src/cli/commit-msg.test.mjs +22 -7
  16. package/src/cli/generated-file-guard.mjs +11 -2
  17. package/src/cli/generated-file-guard.test.mjs +14 -2
  18. package/src/cli/init.mjs +70 -25
  19. package/src/cli/lint-changed.mjs +157 -0
  20. package/src/cli/lint-changed.test.mjs +102 -0
  21. package/src/cli/plugin-agents.test.mjs +1 -1
  22. package/src/cli/post-edit-gate.test.mjs +12 -3
  23. package/src/cli/pr-check.mjs +15 -2
  24. package/src/cli/pr-check.test.mjs +19 -9
  25. package/src/cli/qc.mjs +38 -7
  26. package/src/cli/scaffold.mjs +23 -2
  27. package/src/cli/scaffold.test.mjs +51 -0
  28. package/src/cli/shell-command.mjs +3 -1
  29. package/src/cli/stop-gate.test.mjs +49 -128
  30. package/src/cli/typecheck.mjs +46 -0
  31. package/src/cli/typecheck.test.mjs +43 -0
  32. package/src/cli/user-config-package.mjs +16 -0
  33. package/src/cli/user-config-toml.mjs +144 -0
  34. package/src/cli/user-config.mjs +155 -0
  35. package/src/cli/user-config.test.mjs +274 -0
  36. package/src/cli/work-order-guard.mjs +2 -2
  37. package/src/cli/worktree-gate.mjs +11 -12
  38. package/src/cli/worktree-gate.test.mjs +28 -29
  39. package/src/cli/worktree-isolation.mjs +3 -3
  40. package/src/cli/worktree-isolation.test.mjs +1 -1
  41. package/src/cli/worktree.mjs +9 -1
  42. package/src/cli/worktree.test.mjs +16 -1
  43. package/src/config.mjs +28 -11
  44. package/src/config.test.mjs +33 -1
  45. package/src/eslint/preset.mjs +8 -3
  46. package/src/eslint/preset.test.mjs +15 -8
  47. package/src/eslint/rules/no-raw-fetch.mjs +42 -2
  48. package/src/eslint/rules.test.mjs +15 -0
  49. package/src/gates/audit-append-only.mjs +18 -4
  50. package/src/gates/audit-append-only.test.mjs +19 -0
  51. package/src/gates/tenant-predicate.mjs +147 -7
  52. package/src/gates/tenant-predicate.test.mjs +55 -0
  53. package/src/gates/tenant-tables.mjs +5 -2
  54. package/src/gates/tenant-tables.test.mjs +8 -0
  55. package/src/gates/threshold-ratchet.mjs +12 -9
  56. package/src/gates/threshold-ratchet.test.mjs +16 -0
  57. package/src/plugin.test.mjs +28 -0
  58. package/src/screens/auth-run.test.mjs +20 -17
  59. package/src/screens/capture-idle.test.mjs +2 -1
  60. package/src/screens/catalog.test.mjs +3 -3
  61. package/src/screens/chrome.mjs +21 -0
  62. package/src/vale-style.test.mjs +5 -5
  63. package/templates/CLAUDE.md +2 -2
  64. package/templates/githooks/pre-commit +7 -10
  65. package/templates/github/workflows/ci.yml +25 -84
  66. package/templates/github/workflows/pr-policy.yml +36 -0
  67. package/user-config/claude/settings.shared.json +74 -0
  68. package/user-config/claude/statusline.js +323 -0
  69. package/user-config/codex/config.shared.toml +19 -0
  70. package/src/cli/edit-batch-guard.mjs +0 -77
  71. package/src/cli/edit-batch-guard.test.mjs +0 -131
@@ -43,7 +43,10 @@ function workspace(t, installed) {
43
43
  const cli = path.join(repo, "node_modules", "architecture-harness", "src", "cli");
44
44
  stubHarness(cli, "installed", log, installed.codes, installed.withDoctor, installed.outputs);
45
45
  }
46
- const ran = () => (existsSync(log) ? readFileSync(log, "utf8").trim().split("\n") : []);
46
+ // The typecheck and the lint run on every stop; `ran` lists the gates that judge the structure, `tools` the other two.
47
+ const lines = () => (existsSync(log) ? readFileSync(log, "utf8").trim().split("\n") : []);
48
+ const ran = () => lines().filter((line) => !/ (?:typecheck|lint)$/.test(line));
49
+ const tools = () => lines().filter((line) => / (?:typecheck|lint)$/.test(line));
47
50
  // Each workspace owns its temp folder, so the gate's memory of a block is shared with no other test.
48
51
  const tmp = path.join(base, "tmp");
49
52
  mkdirSync(tmp, { recursive: true });
@@ -62,7 +65,7 @@ function workspace(t, installed) {
62
65
  },
63
66
  encoding: "utf8",
64
67
  });
65
- return { ran, run, tmpDir: tmp, installedCli: installed ? path.join(repo, "node_modules", "architecture-harness", "src", "cli") : null };
68
+ return { ran, tools, run, tmpDir: tmp, installedCli: installed ? path.join(repo, "node_modules", "architecture-harness", "src", "cli") : null };
66
69
  }
67
70
 
68
71
  test("an installed harness newer than the bundled one judges the repository, and the stop passes", (t) => {
@@ -80,43 +83,35 @@ test("with no installed harness, the bundled copy judges the repository", (t) =>
80
83
  assert.match(result.stderr, /FAIL {2}check from plugin/);
81
84
  });
82
85
 
83
- test("drift alone refuses the first stop, and names the setup, not the code", (t) => {
86
+ test("drift alone never blocks: the stop passes with a note that names the setup", (t) => {
84
87
  const ws = workspace(t, { codes: { doctor: 1 }, withDoctor: true });
85
88
  const result = ws.run();
86
- assert.equal(result.status, 2);
87
- assert.deepEqual(ws.ran(), ["installed doctor", "installed check"]);
88
- assert.match(result.stderr, /FAIL {2}doctor from installed/);
89
- assert.match(result.stderr, /kit setup, not in your code/);
90
- });
91
-
92
- test("drift alone after a refused stop lets the session end with a note, so a stale plugin never loops it", (t) => {
93
- const ws = workspace(t, { codes: { doctor: 1 }, withDoctor: true });
94
- const result = ws.run({ stop_hook_active: true });
95
89
  assert.equal(result.status, 0, result.stderr);
96
- assert.match(JSON.parse(result.stdout).systemMessage, /The kit setup still drifts/);
90
+ assert.deepEqual(ws.ran(), ["installed doctor", "installed check"]);
91
+ const message = JSON.parse(result.stdout).systemMessage;
92
+ assert.match(message, /kit setup drifts/);
93
+ assert.match(message, /FAIL {2}doctor from installed/);
97
94
  });
98
95
 
99
- test("a red check after a refused stop still refuses, because only drift is excused", (t) => {
96
+ test("a red check beside drift blocks, and the block text carries the code failure, not the drift", (t) => {
100
97
  const ws = workspace(t, { codes: { doctor: 1, check: 1 }, withDoctor: true });
101
- const result = ws.run({ stop_hook_active: true });
98
+ const result = ws.run();
102
99
  assert.equal(result.status, 2);
103
100
  assert.match(result.stderr, /FAIL {2}check from installed/);
101
+ assert.doesNotMatch(result.stderr, /doctor from installed/);
104
102
  });
105
103
 
106
104
  const HOOK_DRIFT = "FAIL .githooks/pre-commit hook-drift: pre-commit never calls `qc work-order-check`, so that step is off.";
107
105
 
108
- test("hook drift reported only through qc check is drift, so a refused stop may end with a note", (t) => {
106
+ test("hook drift reported only through qc check is drift, so the stop passes with a note", (t) => {
109
107
  const output = [HOOK_DRIFT, "", "1 problem(s). docs/enforcement.md"].join("\n");
110
108
  const ws = workspace(t, { codes: { check: 1 }, withDoctor: false, outputs: { check: output } });
111
- const refused = ws.run();
112
- assert.equal(refused.status, 2);
113
- assert.match(refused.stderr, /kit setup, not in your code/);
114
- const result = ws.run({ stop_hook_active: true });
109
+ const result = ws.run();
115
110
  assert.equal(result.status, 0, result.stderr);
116
- assert.match(JSON.parse(result.stdout).systemMessage, /The kit setup still drifts/);
111
+ assert.match(JSON.parse(result.stdout).systemMessage, /kit setup drifts/);
117
112
  });
118
113
 
119
- test("hook drift beside a real gate failure still refuses a stop after a refused one", (t) => {
114
+ test("hook drift beside a real gate failure blocks", (t) => {
120
115
  const output = [HOOK_DRIFT, "FAIL orders citations: ADR-0099 is cited but not defined", "", "2 problem(s)."].join("\n");
121
116
  const ws = workspace(t, { codes: { check: 1 }, withDoctor: false, outputs: { check: output } });
122
117
  const result = ws.run({ stop_hook_active: true });
@@ -276,118 +271,27 @@ test("the memory file holds a hash of the failure text, not the text", (t) => {
276
271
  assert.ok(!stored.includes("ADR-0099"));
277
272
  });
278
273
 
279
- /**
280
- * A workspace whose typecheck is `npx tsc`, answered by a stub `npx` first on the PATH. `runs` lists each run's exit code and output;
281
- * a run past the list repeats the last. `count()` is the number of times the gate ran the typecheck.
282
- */
283
- function tscWorkspace(t, runs) {
284
- const ws = workspace(t, { codes: {}, withDoctor: false });
285
- const base = path.dirname(ws.tmpDir);
286
- const repo = path.join(base, "repo");
287
- mkdirSync(path.join(repo, "node_modules", ".bin"), { recursive: true });
288
- writeFileSync(path.join(repo, "node_modules", ".bin", "tsc"), "");
289
- const stubDir = path.join(base, "stub");
290
- mkdirSync(stubDir, { recursive: true });
291
- runs.forEach((run, i) => {
292
- writeFileSync(path.join(stubDir, `run-${i + 1}.code`), String(run.code));
293
- writeFileSync(path.join(stubDir, `run-${i + 1}.out`), run.out);
294
- });
295
- const counter = path.join(stubDir, "count");
296
- writeFileSync(
297
- path.join(stubDir, "npx"),
298
- [
299
- "#!/usr/bin/env bash",
300
- `[ "$1" = tsc ] || exit 0`,
301
- `n=$(cat "${counter}" 2>/dev/null || echo 0); n=$((n + 1)); echo $n > "${counter}"`,
302
- `while [ ! -f "${stubDir}/run-$n.code" ]; do n=$((n - 1)); done`,
303
- `cat "${stubDir}/run-$n.out"`,
304
- `exit $(cat "${stubDir}/run-$n.code")`,
305
- ].join("\n") + "\n",
306
- { mode: 0o755 },
307
- );
308
- const run = (input = {}) => ws.run(input, { PATH: `${stubDir}${path.delimiter}${process.env.PATH}` });
309
- const count = () => (existsSync(counter) ? Number(readFileSync(counter, "utf8")) : 0);
310
- return { run, count };
311
- }
312
-
313
- const TS2307 = "src/a.ts(1,22): error TS2307: Cannot find module 'zod' or its corresponding type declarations.\n";
314
- const TS2322 = "src/b.ts(4,7): error TS2322: Type 'string' is not assignable to type 'number'.\n";
315
-
316
- test("a typecheck that fails only with TS2307 runs once more, and a second pass ends the stop green", (t) => {
317
- const gate = tscWorkspace(t, [{ code: 2, out: TS2307 }, { code: 0, out: "" }]);
318
- const result = gate.run();
319
- assert.equal(result.status, 0, result.stderr);
320
- assert.equal(gate.count(), 2);
321
- });
322
-
323
- test("a typecheck that still fails with TS2307 on the second run blocks, with the second run's text", (t) => {
324
- const gate = tscWorkspace(t, [{ code: 2, out: TS2307 }, { code: 2, out: TS2307.replace("zod", "hono") }]);
325
- const result = gate.run();
326
- assert.equal(result.status, 2);
327
- assert.equal(gate.count(), 2);
328
- assert.match(result.stderr, /typecheck failed/);
329
- assert.match(result.stderr, /hono/);
274
+ test("an installed harness with `qc lint` runs the typecheck and the lint, and an older one leaves both to the plugin", (t) => {
275
+ const current = workspace(t, { codes: {}, withDoctor: false });
276
+ writeFileSync(path.join(current.installedCli, "lint-changed.mjs"), "");
277
+ assert.equal(current.run().status, 0);
278
+ assert.deepEqual(current.tools(), ["installed typecheck", "installed lint"]);
279
+ const older = workspace(t, { codes: {}, withDoctor: false });
280
+ assert.equal(older.run().status, 0);
281
+ assert.deepEqual(older.tools(), ["plugin typecheck", "plugin lint"]);
330
282
  });
331
283
 
332
- test("a TS2322 next to a TS2307 does not retry, and a TS2322 alone does not either", (t) => {
333
- for (const out of [TS2322 + TS2307, TS2322]) {
334
- const gate = tscWorkspace(t, [{ code: 2, out }, { code: 0, out: "" }]);
335
- const result = gate.run();
284
+ test("a red typecheck or a red lint blocks, each under its own heading", (t) => {
285
+ for (const command of ["typecheck", "lint"]) {
286
+ const ws = workspace(t, { codes: { [command]: 1 }, withDoctor: false });
287
+ writeFileSync(path.join(ws.installedCli, "lint-changed.mjs"), "");
288
+ const result = ws.run();
336
289
  assert.equal(result.status, 2);
337
- assert.equal(gate.count(), 1);
338
- assert.match(result.stderr, /TS2322/);
290
+ assert.match(result.stderr, new RegExp(`${command} failed:\nFAIL {2}${command} from installed`));
291
+ assert.match(result.stderr, /The change is red/);
339
292
  }
340
293
  });
341
294
 
342
- test("a large TS2322 log does not retry, since the early exit of the filter must not read as a pipe failure", (t) => {
343
- const out = TS2322.repeat(20_000);
344
- const gate = tscWorkspace(t, [{ code: 2, out }, { code: 0, out: "" }]);
345
- const result = gate.run();
346
- assert.equal(result.status, 2);
347
- assert.equal(gate.count(), 1);
348
- });
349
-
350
- test("a failing typecheck with no error line does not retry, and a passing one runs once", (t) => {
351
- const broken = tscWorkspace(t, [{ code: 1, out: "tsc: command crashed\n" }, { code: 0, out: "" }]);
352
- assert.equal(broken.run().status, 2);
353
- assert.equal(broken.count(), 1);
354
- const green = tscWorkspace(t, [{ code: 0, out: "" }]);
355
- assert.equal(green.run().status, 0);
356
- assert.equal(green.count(), 1);
357
- });
358
-
359
- test("a root typecheck script replaces tsc -b, keeps the TS2307 retry, and the lint call carries a cache", (t) => {
360
- const ws = workspace(t, { codes: {}, withDoctor: false });
361
- const base = path.dirname(ws.tmpDir);
362
- const repo = path.join(base, "repo");
363
- mkdirSync(path.join(repo, "node_modules", ".bin"), { recursive: true });
364
- writeFileSync(path.join(repo, "node_modules", ".bin", "eslint"), "");
365
- writeFileSync(path.join(repo, "package.json"), JSON.stringify({ scripts: { typecheck: "tsgo" } }));
366
- writeFileSync(path.join(repo, "pnpm-lock.yaml"), "");
367
- const stubDir = path.join(base, "stub");
368
- mkdirSync(stubDir, { recursive: true });
369
- const calls = path.join(stubDir, "calls");
370
- const counter = path.join(stubDir, "count");
371
- writeFileSync(
372
- path.join(stubDir, "pnpm"),
373
- [
374
- "#!/usr/bin/env bash",
375
- `echo "pnpm $*" >> "${calls}"`,
376
- `n=$(cat "${counter}" 2>/dev/null || echo 0); n=$((n + 1)); echo $n > "${counter}"`,
377
- `if [ $n -eq 1 ]; then printf '%s' "${TS2307.trim()}"; exit 2; fi`,
378
- "exit 0",
379
- ].join("\n") + "\n",
380
- { mode: 0o755 },
381
- );
382
- writeFileSync(path.join(stubDir, "npx"), ["#!/usr/bin/env bash", `echo "npx $*" >> "${calls}"`, "exit 0"].join("\n") + "\n", { mode: 0o755 });
383
- const result = ws.run({}, { PATH: `${stubDir}${path.delimiter}${process.env.PATH}` });
384
- assert.equal(result.status, 0, result.stderr);
385
- const lines = readFileSync(calls, "utf8").trim().split("\n");
386
- assert.deepEqual(lines.slice(0, 2), ["pnpm run -s typecheck", "pnpm run -s typecheck"]);
387
- assert.ok(!lines.some((l) => l.startsWith("npx tsc")));
388
- assert.ok(lines.includes("npx eslint . --max-warnings 0 --cache --cache-location node_modules/.cache/eslint-stop-gate"));
389
- });
390
-
391
295
  /** A workspace whose repository is a git repository with one commit, so the gate can fingerprint it. */
392
296
  function gitWorkspace(t, installed = { codes: {}, withDoctor: false }) {
393
297
  const ws = workspace(t, installed);
@@ -441,6 +345,23 @@ test("a new commit makes the next stop run the full gate", (t) => {
441
345
  assert.equal(ws.ran().length, 2);
442
346
  });
443
347
 
348
+ test("a new installed harness on an unchanged checkout makes the next stop run the full gate", (t) => {
349
+ const ws = gitWorkspace(t);
350
+ ws.run();
351
+ writeFileSync(path.join(ws.repo, "node_modules", "architecture-harness", "package.json"), '{"version":"9.9.9"}');
352
+ ws.run();
353
+ assert.equal(ws.ran().length, 2);
354
+ ws.run();
355
+ assert.equal(ws.ran().length, 2);
356
+ });
357
+
358
+ test("a new extra stop step on an unchanged checkout makes the next stop run the full gate", (t) => {
359
+ const ws = gitWorkspace(t);
360
+ ws.run();
361
+ ws.run({}, { QC_STOP_EXTRA: "true" });
362
+ assert.equal(ws.ran().length, 2);
363
+ });
364
+
444
365
  test("a red first run stores nothing, so the next stop runs the full gate again", (t) => {
445
366
  const ws = gitWorkspace(t, { codes: { check: 1 }, withDoctor: false });
446
367
  assert.equal(ws.run().status, 2);
@@ -0,0 +1,46 @@
1
+ // `qc typecheck`: the repository's own `typecheck` script when it has one, else the installed tsc.
2
+ // tsc builds only a tsconfig with project references, because a build writes a .tsbuildinfo file
3
+ // and leaves the tree dirty. The hooks and CI call this one command, so they run the same check.
4
+
5
+ import { spawnSync } from "node:child_process";
6
+ import { existsSync, readFileSync } from "node:fs";
7
+ import path from "node:path";
8
+
9
+ /** The command that typechecks `root`, or null when it has no typecheck script and no tsc. */
10
+ export function typecheckCommand(root) {
11
+ const manifest = path.join(root, "package.json");
12
+ let scripts = {};
13
+ try {
14
+ scripts = JSON.parse(readFileSync(manifest, "utf8")).scripts ?? {};
15
+ } catch {}
16
+ if (typeof scripts.typecheck === "string") {
17
+ const manager = existsSync(path.join(root, "pnpm-lock.yaml")) ? "pnpm" : existsSync(path.join(root, "yarn.lock")) ? "yarn" : "npm";
18
+ return { cmd: manager, args: ["run", "-s", "typecheck"], shell: true };
19
+ }
20
+ const tsc = path.join(root, "node_modules", "typescript", "bin", "tsc");
21
+ const tsconfig = path.join(root, "tsconfig.json");
22
+ if (!existsSync(tsc) || !existsSync(tsconfig)) return null;
23
+ const references = /"references"\s*:/.test(readFileSync(tsconfig, "utf8"));
24
+ return { cmd: process.execPath, args: [tsc, ...(references ? ["-b"] : ["--noEmit", "-p", "."]), "--pretty", "false"], shell: false };
25
+ }
26
+
27
+ /** True when every error is TS2307, which a concurrent install produces while a module is missing for a moment. */
28
+ export function onlyMissingModules(output) {
29
+ const errors = output.split(/\r?\n/).filter((line) => /error TS\d+/.test(line));
30
+ return errors.length > 0 && errors.every((line) => line.includes("error TS2307"));
31
+ }
32
+
33
+ /** @returns the exit code of the typecheck, or 0 when the repository has nothing to typecheck. */
34
+ export function runTypecheck(config) {
35
+ const command = typecheckCommand(config.root);
36
+ if (command === null) {
37
+ console.log("typecheck skipped: no typecheck script and no tsc with a tsconfig.json");
38
+ return 0;
39
+ }
40
+ const once = () => spawnSync(command.cmd, command.args, { cwd: config.root, encoding: "utf8", shell: command.shell, windowsHide: true, maxBuffer: 1 << 26 });
41
+ let result = once();
42
+ if (result.status !== 0 && onlyMissingModules(`${result.stdout}${result.stderr}`)) result = once();
43
+ process.stdout.write(result.stdout ?? "");
44
+ process.stderr.write(result.stderr ?? "");
45
+ return result.status ?? 1;
46
+ }
@@ -0,0 +1,43 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { mkdirSync, 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 { onlyMissingModules, typecheckCommand } from "./typecheck.mjs";
7
+
8
+ function root(t, files) {
9
+ const dir = mkdtempSync(path.join(os.tmpdir(), "qc-typecheck-"));
10
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
11
+ for (const [name, text] of Object.entries(files)) {
12
+ mkdirSync(path.dirname(path.join(dir, name)), { recursive: true });
13
+ writeFileSync(path.join(dir, name), text);
14
+ }
15
+ return dir;
16
+ }
17
+
18
+ const TSC = { "node_modules/typescript/bin/tsc": "" };
19
+
20
+ test("a typecheck script wins, run by the package manager of the lockfile", (t) => {
21
+ const dir = root(t, { "package.json": '{ "scripts": { "typecheck": "tsc" } }', "pnpm-lock.yaml": "", "tsconfig.json": "{}", ...TSC });
22
+ assert.deepEqual(typecheckCommand(dir), { cmd: "pnpm", args: ["run", "-s", "typecheck"], shell: true });
23
+ });
24
+
25
+ test("without a script, tsc checks with --noEmit, so no .tsbuildinfo is written", (t) => {
26
+ const dir = root(t, { "package.json": "{}", "tsconfig.json": '{ "compilerOptions": {} }', ...TSC });
27
+ assert.deepEqual(typecheckCommand(dir).args.slice(1), ["--noEmit", "-p", ".", "--pretty", "false"]);
28
+ });
29
+
30
+ test("a tsconfig with project references builds, because --noEmit would check none of them", (t) => {
31
+ const dir = root(t, { "tsconfig.json": '{ "files": [], "references": [{ "path": "a" }] }', ...TSC });
32
+ assert.deepEqual(typecheckCommand(dir).args.slice(1), ["-b", "--pretty", "false"]);
33
+ });
34
+
35
+ test("no script and no tsc means nothing to typecheck", (t) => {
36
+ assert.equal(typecheckCommand(root(t, { "package.json": "{}", "tsconfig.json": "{}" })), null);
37
+ });
38
+
39
+ test("a run whose only errors are TS2307 is retried; any other error is not", () => {
40
+ assert.equal(onlyMissingModules("a.ts(1,1): error TS2307: Cannot find module 'x'."), true);
41
+ assert.equal(onlyMissingModules("a.ts(1,1): error TS2307: x\nb.ts(2,2): error TS2322: y"), false);
42
+ assert.equal(onlyMissingModules("npm ERR! missing script"), false);
43
+ });
@@ -0,0 +1,16 @@
1
+ // A pipeline that stages the root user configuration for the npm package.
2
+
3
+ import { copyFileSync, mkdirSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ export function packageUserConfig(source, target) {
8
+ for (const file of ["claude/statusline.js", "claude/settings.shared.json", "codex/config.shared.toml"]) {
9
+ mkdirSync(path.dirname(path.join(target, file)), { recursive: true });
10
+ copyFileSync(path.join(source, file), path.join(target, file));
11
+ }
12
+ }
13
+
14
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
15
+ packageUserConfig(fileURLToPath(new URL("../../../../user-config/", import.meta.url)), fileURLToPath(new URL("../../user-config/", import.meta.url)));
16
+ }
@@ -0,0 +1,144 @@
1
+ // A fragment that edits shared TOML assignments without rewriting other text.
2
+
3
+ export const CODEX_KEYS = Object.freeze([
4
+ "approval_policy", "default_permissions", "model", "model_reasoning_effort",
5
+ "model_auto_compact_token_limit", "model_post_turn_compact_threshold_percent", "service_tier",
6
+ ]);
7
+
8
+ function unquote(value) {
9
+ if (value.startsWith('"')) return JSON.parse(value);
10
+ if (value.startsWith("'")) return value.slice(1, -1);
11
+ return value;
12
+ }
13
+
14
+ function scanValue(text, start) {
15
+ let quote = "";
16
+ let depth = 0;
17
+ for (let i = start; i < text.length; i += 1) {
18
+ const char = text[i];
19
+ if (quote) {
20
+ if (quote.includes('"') && char === "\\") { i += 1; continue; }
21
+ if (text.startsWith(quote, i)) { i += quote.length - 1; quote = ""; }
22
+ continue;
23
+ }
24
+ if (char === '"' || char === "'") {
25
+ quote = text.startsWith(char.repeat(3), i) ? char.repeat(3) : char;
26
+ i += quote.length - 1;
27
+ } else if (char === "[" || char === "{") depth += 1;
28
+ else if (char === "]" || char === "}") depth -= 1;
29
+ else if (char === "#") {
30
+ if (depth === 0) return { end: i, next: text.indexOf("\n", i) < 0 ? text.length : text.indexOf("\n", i) + 1 };
31
+ const newline = text.indexOf("\n", i);
32
+ if (newline < 0) break;
33
+ i = newline - 1;
34
+ } else if (char === "\n" && depth === 0) return { end: i, next: i + 1 };
35
+ }
36
+ if (quote || depth !== 0) throw new Error("Unterminated TOML value");
37
+ return { end: text.length, next: text.length };
38
+ }
39
+
40
+ function documentOf(text) {
41
+ const sections = [{ name: "", start: 0, end: text.length, fields: new Map() }];
42
+ let section = sections[0];
43
+ let offset = 0;
44
+ while (offset < text.length) {
45
+ const newline = text.indexOf("\n", offset);
46
+ const next = newline < 0 ? text.length : newline + 1;
47
+ const line = text.slice(offset, next).trimEnd();
48
+ const header = /^\s*(\[\[?.*?\]\]?)\s*(?:#.*)?$/.exec(line);
49
+ if (header) {
50
+ section.end = offset;
51
+ const named = /^\[\s*(plugins|marketplaces)\s*\.\s*("(?:[^"\\]|\\.)*"|'[^']*'|[\w-]+)\s*\]$/.exec(header[1]);
52
+ section = { name: header[1], kind: named?.[1], plugin: named && unquote(named[2]), start: offset, end: text.length, fields: new Map() };
53
+ sections.push(section);
54
+ } else {
55
+ const assignment = /^\s*("(?:[^"\\]|\\.)*"|'[^']*'|[\w-]+)((?:\s*\.\s*(?:"(?:[^"\\]|\\.)*"|'[^']*'|[\w-]+))*)\s*=\s*/.exec(line);
56
+ if (assignment) {
57
+ const key = assignment[2] ? `${assignment[1]}${assignment[2]}` : unquote(assignment[1]);
58
+ const start = offset + assignment[0].length;
59
+ const value = scanValue(text, start);
60
+ const raw = text.slice(start, value.end).trimEnd();
61
+ if (section.fields.has(key)) throw new Error(`Duplicate TOML key: ${key}`);
62
+ section.fields.set(key, { start, end: start + raw.length, raw });
63
+ offset = value.next;
64
+ continue;
65
+ }
66
+ }
67
+ offset = next;
68
+ }
69
+ return sections;
70
+ }
71
+
72
+ function sharedFields(text) {
73
+ const sections = documentOf(text);
74
+ const top = new Map([...sections[0].fields].filter(([key]) => CODEX_KEYS.includes(key)));
75
+ const local = new Set(sections.filter((s) => s.kind === "marketplaces" && (
76
+ s.fields.get("source_type")?.raw.match(/^["']local["']$/)
77
+ || s.fields.get("source")?.raw.match(/^["'](?:[A-Za-z]:|[\\/~.])/)
78
+ )).map((s) => s.plugin));
79
+ const plugins = sections.filter((s) => s.kind === "plugins" && !local.has(s.plugin.split("@").at(-1)))
80
+ .map((s) => ({ ...s, fields: new Map([...s.fields].filter(([key]) => key === "enabled")) }))
81
+ .filter((s) => s.fields.size);
82
+ for (const [key, field] of top) {
83
+ if (!/^(?:"(?:[^"\\\r\n]|\\.)*"|'[^'\r\n]*'|\d+)$/.test(field.raw)) {
84
+ throw new Error(`Expected a scalar shared TOML value: ${key}`);
85
+ }
86
+ }
87
+ for (const plugin of plugins) {
88
+ if (!/^(true|false)$/.test(plugin.fields.get("enabled").raw)) throw new Error(`Expected a plugin boolean: ${plugin.plugin}`);
89
+ }
90
+ return { top, plugins };
91
+ }
92
+
93
+ export function captureCodexConfig(text) {
94
+ const { top, plugins } = sharedFields(text);
95
+ const rows = [...top].map(([key, value]) => `${key} = ${value.raw}`);
96
+ for (const plugin of plugins) rows.push("", `[plugins.${JSON.stringify(plugin.plugin)}]`, `enabled = ${plugin.fields.get("enabled").raw}`);
97
+ return rows.length ? `${rows.join("\n")}\n` : "";
98
+ }
99
+
100
+ export function mergeCodexConfig(local, shared) {
101
+ const sections = documentOf(local);
102
+ if (sections[0].fields.get("plugins")?.raw.startsWith("{")) {
103
+ throw new Error('Inline TOML plugins tables are unsupported; use [plugins."name"] tables.');
104
+ }
105
+ const desired = sharedFields(shared);
106
+ const edits = [];
107
+ const additions = new Map();
108
+ const newTables = [];
109
+ const changed = [];
110
+ const eol = local.includes("\r\n") ? "\r\n" : "\n";
111
+ function add(section, line) {
112
+ additions.set(section, [...(additions.get(section) ?? []), line]);
113
+ }
114
+ function merge(section, fields, label) {
115
+ for (const [key, value] of fields) {
116
+ const previous = section.fields.get(key);
117
+ if (previous && unquote(previous.raw) === unquote(value.raw)) continue;
118
+ changed.push(`${label}${key}`);
119
+ if (previous) edits.push({ start: previous.start, end: previous.end, text: value.raw });
120
+ else add(section, `${key} = ${value.raw}`);
121
+ }
122
+ }
123
+ merge(sections[0], desired.top, "");
124
+ for (const plugin of desired.plugins) {
125
+ const matches = sections.filter((s) => s.kind === "plugins" && s.plugin === plugin.plugin);
126
+ if (matches.length > 1) throw new Error(`Duplicate plugin table: ${plugin.plugin}`);
127
+ if (matches.length) merge(matches[0], plugin.fields, `plugins.${plugin.plugin}.`);
128
+ else {
129
+ const section = { fields: new Map() };
130
+ newTables.push(section);
131
+ add(section, `[plugins.${JSON.stringify(plugin.plugin)}]`);
132
+ merge(section, plugin.fields, `plugins.${plugin.plugin}.`);
133
+ }
134
+ }
135
+ for (const section of sections) {
136
+ const lines = additions.get(section);
137
+ if (lines) edits.push({ start: section.end, end: section.end,
138
+ text: `${section.end && local[section.end - 1] !== "\n" ? eol : ""}${lines.join(eol)}${eol}` });
139
+ }
140
+ let text = local;
141
+ for (const edit of edits.sort((a, b) => b.start - a.start)) text = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
142
+ for (const section of newTables) text += `${text && !text.endsWith("\n") ? eol : ""}${eol}${additions.get(section).join(eol)}${eol}`;
143
+ return { text, changed };
144
+ }
@@ -0,0 +1,155 @@
1
+ // A pipeline that synchronizes the kit's shared user settings.
2
+
3
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
4
+ import { constants } from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { parseArgs } from "node:util";
9
+ import { isDeepStrictEqual } from "node:util";
10
+ import { captureCodexConfig, mergeCodexConfig } from "./user-config-toml.mjs";
11
+
12
+ export { captureCodexConfig, mergeCodexConfig } from "./user-config-toml.mjs";
13
+
14
+ export const CLAUDE_KEYS = Object.freeze([
15
+ "cleanupPeriodDays", "syncClaudeAiPlugins", "env", "permissions", "model", "skillOverrides",
16
+ "statusLine", "enabledPlugins", "extraKnownMarketplaces", "effortLevel", "modelSettings",
17
+ "awaySummaryEnabled", "autoUpdatesChannel", "tui", "skipWorkflowUsageWarning", "theme",
18
+ "autoCompactEnabled", "autoContinueAtUsageLimit", "agentPushNotifEnabled", "skipAutoPermissionPrompt",
19
+ ]);
20
+ const ENV_KEYS = ["CLAUDE_CODE_DISABLE_MOUSE", "CLAUDE_CODE_DISABLE_BG_SHELL_PRESSURE_REAP"];
21
+ const MAP_KEYS = ["enabledPlugins", "extraKnownMarketplaces", "env"];
22
+ const STATUS_COMMAND = 'node "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/statusline.js"';
23
+ const USAGE = "qc user-config apply|check|capture [--dry-run] [--kit-dir <path>] [--claude-dir <path>] [--codex-dir <path>]";
24
+
25
+ export function assertSafePath(file) {
26
+ const name = file.replaceAll("\\", "/").split("/").at(-1).toLowerCase();
27
+ if ([".claude.json", ".credentials.json", "auth.json"].includes(name) || /token|secret|credential|auth/i.test(name)) {
28
+ throw new Error(`Refusing credential file: ${file}`);
29
+ }
30
+ }
31
+
32
+ function safeFile(file) {
33
+ assertSafePath(file);
34
+ if (existsSync(file)) {
35
+ assertSafePath(realpathSync(file));
36
+ if (!statSync(file).isFile()) throw new Error(`Expected a regular file: ${file}`);
37
+ }
38
+ }
39
+
40
+ export function configPaths(home = os.homedir(), env = process.env) {
41
+ const paths = /^[A-Za-z]:[\\/]|^\\\\/.test(home) ? path.win32 : path.posix;
42
+ const claudeDir = env.CLAUDE_CONFIG_DIR || paths.join(home, ".claude");
43
+ const codexDir = env.CODEX_HOME || paths.join(home, ".codex");
44
+ return { claude: paths.join(claudeDir, "settings.json"), statusline: paths.join(claudeDir, "statusline.js"), codex: paths.join(codexDir, "config.toml") };
45
+ }
46
+
47
+ function objectOf(text) {
48
+ const value = JSON.parse(text);
49
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Expected a JSON settings object");
50
+ return value;
51
+ }
52
+
53
+ function sharedClaude(text) {
54
+ const source = objectOf(text);
55
+ const shared = Object.fromEntries(CLAUDE_KEYS.filter((key) => Object.hasOwn(source, key)).map((key) => [key, source[key]]));
56
+ if (shared.env) shared.env = Object.fromEntries(ENV_KEYS.filter((key) => Object.hasOwn(shared.env, key)).map((key) => [key, shared.env[key]]));
57
+ if (shared.permissions) shared.permissions = Object.fromEntries(["defaultMode"].filter((key) => Object.hasOwn(shared.permissions, key)).map((key) => [key, shared.permissions[key]]));
58
+ if (shared.statusLine) shared.statusLine = { type: "command", command: STATUS_COMMAND };
59
+ const local = new Set(["skills-dir"]);
60
+ if (shared.extraKnownMarketplaces) {
61
+ shared.extraKnownMarketplaces = Object.fromEntries(Object.entries(shared.extraKnownMarketplaces).filter(([name, entry]) => {
62
+ const remote = ["github", "git"].includes(entry?.source?.source);
63
+ if (!remote) local.add(name);
64
+ return remote;
65
+ }));
66
+ }
67
+ if (shared.enabledPlugins) shared.enabledPlugins = Object.fromEntries(Object.entries(shared.enabledPlugins).filter(([name]) => !local.has(name.split("@").at(-1))));
68
+ return shared;
69
+ }
70
+
71
+ export function mergeClaudeSettings(local, shared) {
72
+ const target = objectOf(local);
73
+ const source = sharedClaude(shared);
74
+ const changed = [];
75
+ for (const [key, value] of Object.entries(source)) {
76
+ if ([...MAP_KEYS, "permissions"].includes(key)) {
77
+ const before = target[key] ?? {};
78
+ const merged = { ...before };
79
+ for (const [name, entry] of Object.entries(value)) {
80
+ if (!isDeepStrictEqual(before[name], entry)) { changed.push(`${key}.${name}`); Object.defineProperty(merged, name, { value: entry, enumerable: true, writable: true, configurable: true }); }
81
+ }
82
+ target[key] = merged;
83
+ } else if (!isDeepStrictEqual(target[key], value)) { changed.push(key); target[key] = value; }
84
+ }
85
+ return { text: changed.length ? `${JSON.stringify(target, null, 2)}\n` : local, changed };
86
+ }
87
+
88
+ export function kitUserConfigDir(moduleUrl = import.meta.url) {
89
+ const packageDir = fileURLToPath(new URL("../../user-config/", moduleUrl));
90
+ const checkoutDir = fileURLToPath(new URL("../../../../user-config/", moduleUrl));
91
+ const plugin = fileURLToPath(new URL("../../../../.claude-plugin/plugin.json", moduleUrl));
92
+ return existsSync(plugin) && existsSync(checkoutDir) ? checkoutDir : packageDir;
93
+ }
94
+
95
+ function readOptional(file, fallback) {
96
+ try { return readFileSync(file, "utf8"); } catch (error) {
97
+ if (error.code === "ENOENT") return fallback;
98
+ throw error;
99
+ }
100
+ }
101
+
102
+ function stamp(now) {
103
+ const pad = (n) => String(n).padStart(2, "0");
104
+ return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
105
+ }
106
+
107
+ function backupFile(file, now) {
108
+ mkdirSync(path.dirname(file), { recursive: true });
109
+ if (existsSync(file)) copyFileSync(file, `${file}.bak-${stamp(now)}`, constants.COPYFILE_EXCL);
110
+ }
111
+
112
+ export async function runUserConfig(args, options = {}) {
113
+ const log = options.log ?? console.log;
114
+ try {
115
+ for (const arg of args) assertSafePath(arg);
116
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
117
+ "dry-run": { type: "boolean" }, "kit-dir": { type: "string" }, "claude-dir": { type: "string" }, "codex-dir": { type: "string" },
118
+ } });
119
+ const [verb] = positionals;
120
+ if (positionals.length !== 1 || !["apply", "check", "capture"].includes(verb)) throw new Error(USAGE);
121
+ const env = { ...(options.env ?? process.env) };
122
+ if (values["claude-dir"]) env.CLAUDE_CONFIG_DIR = values["claude-dir"];
123
+ if (values["codex-dir"]) env.CODEX_HOME = values["codex-dir"];
124
+ const paths = configPaths(options.home ?? os.homedir(), env);
125
+ const kit = values["kit-dir"] ?? options.kitDir ?? kitUserConfigDir();
126
+ const files = [
127
+ { machine: paths.claude, kit: path.join(kit, "claude/settings.shared.json"), fallback: "{}", merge: mergeClaudeSettings, capture: (text) => `${JSON.stringify(sharedClaude(text), null, 2)}\n` },
128
+ { machine: paths.codex, kit: path.join(kit, "codex/config.shared.toml"), fallback: "", merge: mergeCodexConfig, capture: captureCodexConfig },
129
+ { machine: paths.statusline, kit: path.join(kit, "claude/statusline.js"), fallback: "", merge: (local, shared) => ({ text: shared, changed: local === shared ? [] : ["statusline.js"] }), capture: (text) => text },
130
+ ];
131
+ for (const file of files) { safeFile(file.machine); safeFile(file.kit); }
132
+ const plans = files.map((file) => {
133
+ const target = verb === "capture" ? file.kit : file.machine;
134
+ const local = readOptional(target, file.fallback);
135
+ const source = readFileSync(verb === "capture" ? file.machine : file.kit, "utf8");
136
+ const result = verb === "capture" ? { text: file.capture(source), changed: [path.basename(file.kit)] } : file.merge(local, source);
137
+ return { target, ...result, changed: result.text === local ? [] : result.changed };
138
+ });
139
+ for (const plan of plans) {
140
+ for (const key of plan.changed) log(`${values["dry-run"] ? "Would change" : verb === "check" ? "Drift" : "Change"} ${plan.target}: ${key}`);
141
+ }
142
+ if (verb !== "check" && !values["dry-run"]) {
143
+ const changes = plans.filter((plan) => plan.changed.length);
144
+ const now = options.now ?? new Date();
145
+ for (const plan of changes) backupFile(plan.target, now);
146
+ for (const plan of changes) writeFileSync(plan.target, plan.text, { mode: 0o600 });
147
+ }
148
+ const drift = plans.some((plan) => plan.changed.length);
149
+ if (!drift) log("Shared user configuration matches.");
150
+ return verb === "check" && drift ? 1 : 0;
151
+ } catch (error) {
152
+ (options.log ?? console.error)(`qc user-config: ${error.message}`);
153
+ return 2;
154
+ }
155
+ }