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.
- package/package.json +8 -3
- package/src/cli/check.mjs +61 -0
- package/src/cli/child-run.mjs +39 -0
- package/src/cli/child-run.test.mjs +16 -0
- package/src/cli/ci-template.test.mjs +28 -0
- package/src/cli/codex-implement.mjs +72 -3
- package/src/cli/codex-implement.test.mjs +141 -4
- package/src/cli/dispatch-guard.mjs +24 -1
- package/src/cli/dispatch-guard.test.mjs +30 -0
- package/src/cli/dispatch-reminder.mjs +4 -4
- package/src/cli/dispatch-reminder.test.mjs +3 -3
- package/src/cli/dispatch-slot.mjs +12 -0
- package/src/cli/gate-slot.mjs +151 -0
- package/src/cli/gate-slot.test.mjs +90 -0
- package/src/cli/integrate.mjs +122 -0
- package/src/cli/integrate.test.mjs +94 -0
- package/src/cli/ledger.mjs +25 -3
- package/src/cli/ledger.test.mjs +9 -0
- package/src/cli/merge-guard.mjs +13 -3
- package/src/cli/merge-guard.test.mjs +24 -1
- package/src/cli/migrations.mjs +127 -0
- package/src/cli/migrations.test.mjs +94 -0
- package/src/cli/plugin-agents.test.mjs +35 -8
- package/src/cli/qc.mjs +44 -0
- package/src/cli/report-stop.mjs +3 -0
- package/src/cli/report-stop.test.mjs +8 -0
- package/src/cli/retry-failed.mjs +80 -0
- package/src/cli/retry-failed.test.mjs +51 -0
- package/src/cli/review-gate.mjs +16 -7
- package/src/cli/slot-guard.mjs +43 -0
- package/src/cli/slot-guard.test.mjs +28 -0
- package/src/cli/task-gate-review.test.mjs +10 -0
- package/src/cli/task-gate.mjs +39 -7
- package/src/cli/task-gate.test.mjs +45 -0
- package/src/cli/throwaway-db.mjs +127 -0
- package/src/cli/throwaway-db.test.mjs +83 -0
- package/src/cli/ui-reuse-hint.mjs +89 -0
- package/src/cli/ui-reuse-hint.test.mjs +60 -0
- package/src/cli/ui.mjs +181 -0
- package/src/cli/ui.test.mjs +137 -0
- package/src/cli/watch.mjs +211 -0
- package/src/cli/watch.test.mjs +246 -0
- package/src/config.mjs +27 -2
- package/src/descriptions.mjs +3 -0
- package/src/gates/contract-keys.mjs +33 -0
- package/src/gates/contract-keys.test.mjs +38 -0
- package/src/gates/migration-numbers.mjs +1 -1
- package/src/gates/migration-numbers.test.mjs +1 -0
- package/src/gates/ui-catalog.mjs +45 -0
- package/src/gates/ui-catalog.test.mjs +48 -0
- package/src/gates/ui-dupes.mjs +36 -0
- package/src/gates/ui-dupes.test.mjs +29 -0
- package/src/ui/catalog.mjs +87 -0
- package/src/ui/catalog.test.mjs +54 -0
- package/src/ui/class-sites.mjs +151 -0
- package/src/ui/class-sites.test.mjs +41 -0
- package/src/ui/codemod.mjs +138 -0
- package/src/ui/codemod.test.mjs +140 -0
- package/src/ui/components.mjs +176 -0
- package/src/ui/components.test.mjs +87 -0
- package/src/ui/dupes.mjs +141 -0
- package/src/ui/dupes.test.mjs +85 -0
- package/src/ui/find.mjs +45 -0
- package/src/ui/find.test.mjs +48 -0
- package/src/ui/options.mjs +40 -0
- package/src/ui/scan.mjs +78 -0
- package/src/ui/typescript.mjs +29 -0
- package/templates/github/workflows/ci.yml +54 -0
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// `qc gate-slot -- <command>`: run a heavy local command only while one of the machine's gate slots is free.
|
|
2
|
+
// A claim records its process id and start; a claim whose process is gone, or that is too old, is freed.
|
|
3
|
+
|
|
4
|
+
import { mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { parseArgs } from "node:util";
|
|
8
|
+
import { commandLine, runInShell, splitAtDashes } from "./child-run.mjs";
|
|
9
|
+
|
|
10
|
+
export const USAGE = `qc gate-slot — share the machine's slots for heavy local commands
|
|
11
|
+
|
|
12
|
+
qc gate-slot [--slots <n>] [--max-minutes <m>] -- <command...>
|
|
13
|
+
wait for a free slot, run the command, and free the slot when the command ends
|
|
14
|
+
qc gate-slot --status
|
|
15
|
+
list each held slot: its process, its age, its folder, and its command
|
|
16
|
+
|
|
17
|
+
Wrap the local check, a test run of more than one file, a browser test, a live database test,
|
|
18
|
+
a commit, and a push. QC_GATE_SLOTS sets the count (3 by default); QC_GATE_SLOT_DIR, the folder.`;
|
|
19
|
+
|
|
20
|
+
export const DEFAULT_SLOTS = 3;
|
|
21
|
+
export const DEFAULT_MAX_MINUTES = 120;
|
|
22
|
+
const MINUTE_MS = 60_000;
|
|
23
|
+
const WAIT_MS = 20_000;
|
|
24
|
+
const SLOT_FILE = /^slot-(\d+)\.json$/;
|
|
25
|
+
|
|
26
|
+
/** The machine-wide folder of the gate slots. */
|
|
27
|
+
export const gateSlotDirOf = (env = process.env, tmp = os.tmpdir()) => env.QC_GATE_SLOT_DIR || path.join(tmp, "architecture-kit", "gate-slots");
|
|
28
|
+
|
|
29
|
+
/** True while a process with this id runs; a process this user may not signal still runs. */
|
|
30
|
+
export function isAlive(pid) {
|
|
31
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
32
|
+
try {
|
|
33
|
+
process.kill(pid, 0);
|
|
34
|
+
return true;
|
|
35
|
+
} catch (error) {
|
|
36
|
+
return error.code === "EPERM";
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Each claim in the folder, with its parsed holder, or a null holder for a file that does not parse. */
|
|
41
|
+
export function claimsIn(dir) {
|
|
42
|
+
let names;
|
|
43
|
+
try {
|
|
44
|
+
names = readdirSync(dir).filter((name) => SLOT_FILE.test(name));
|
|
45
|
+
} catch (error) {
|
|
46
|
+
if (error.code === "ENOENT") return [];
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
return names.map((name) => {
|
|
50
|
+
const file = path.join(dir, name);
|
|
51
|
+
let holder = null;
|
|
52
|
+
let mtimeMs = null;
|
|
53
|
+
try {
|
|
54
|
+
holder = JSON.parse(readFileSync(file, "utf8"));
|
|
55
|
+
mtimeMs = statSync(file).mtimeMs;
|
|
56
|
+
} catch {
|
|
57
|
+
// The holder freed it between the listing and this read, or is still writing it.
|
|
58
|
+
}
|
|
59
|
+
return { file, index: Number(SLOT_FILE.exec(name)[1]), holder, mtimeMs };
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Removes each claim whose process is gone or that is older than the limit. A file that does not parse waits a minute. */
|
|
64
|
+
export function freeStale(dir, now, maxMinutes, alive = isAlive) {
|
|
65
|
+
const freed = [];
|
|
66
|
+
for (const claim of claimsIn(dir)) {
|
|
67
|
+
const startedAt = Date.parse(claim.holder?.startedAt ?? "");
|
|
68
|
+
const readable = claim.holder !== null && Number.isInteger(claim.holder.pid) && !Number.isNaN(startedAt);
|
|
69
|
+
const stale = readable
|
|
70
|
+
? !alive(claim.holder.pid) || now - startedAt > maxMinutes * MINUTE_MS
|
|
71
|
+
: claim.mtimeMs !== null && now - claim.mtimeMs > MINUTE_MS;
|
|
72
|
+
if (stale) {
|
|
73
|
+
rmSync(claim.file, { force: true });
|
|
74
|
+
freed.push(claim);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return freed;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Claims the first free slot below the count by an exclusive create. @returns the slot file, or null when all are held */
|
|
81
|
+
export function claimSlot(dir, count, holder) {
|
|
82
|
+
mkdirSync(dir, { recursive: true });
|
|
83
|
+
for (let index = 0; index < count; index += 1) {
|
|
84
|
+
const file = path.join(dir, `slot-${index}.json`);
|
|
85
|
+
try {
|
|
86
|
+
writeFileSync(file, JSON.stringify(holder), { flag: "wx" });
|
|
87
|
+
return file;
|
|
88
|
+
} catch (error) {
|
|
89
|
+
if (error.code !== "EEXIST") throw error;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const positive = (text, flag) => {
|
|
96
|
+
const value = Number(text);
|
|
97
|
+
if (!Number.isInteger(value) || value < 1) throw new Error(`${flag} must be a positive integer, got ${text}`);
|
|
98
|
+
return value;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/** `qc gate-slot`. @returns the command's exit code, or 2 on a usage error */
|
|
102
|
+
export async function runGateSlot(argv, deps = {}) {
|
|
103
|
+
const {
|
|
104
|
+
env = process.env,
|
|
105
|
+
now = Date.now,
|
|
106
|
+
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
107
|
+
run = runInShell,
|
|
108
|
+
say = (line) => console.error(line),
|
|
109
|
+
alive = isAlive,
|
|
110
|
+
pid = process.pid,
|
|
111
|
+
} = deps;
|
|
112
|
+
const { flags, command } = splitAtDashes(argv);
|
|
113
|
+
let values;
|
|
114
|
+
let slots;
|
|
115
|
+
let maxMinutes;
|
|
116
|
+
try {
|
|
117
|
+
({ values } = parseArgs({ args: flags, options: { slots: { type: "string" }, "max-minutes": { type: "string" }, status: { type: "boolean" } }, strict: true }));
|
|
118
|
+
slots = positive(values.slots ?? env.QC_GATE_SLOTS ?? String(DEFAULT_SLOTS), "--slots");
|
|
119
|
+
maxMinutes = positive(values["max-minutes"] ?? String(DEFAULT_MAX_MINUTES), "--max-minutes");
|
|
120
|
+
if (!values.status && command.length === 0) throw new Error("name the command after --");
|
|
121
|
+
} catch (error) {
|
|
122
|
+
say(`qc gate-slot: ${error.message}\n\n${USAGE}`);
|
|
123
|
+
return 2;
|
|
124
|
+
}
|
|
125
|
+
const dir = gateSlotDirOf(env);
|
|
126
|
+
if (values.status) {
|
|
127
|
+
const claims = claimsIn(dir);
|
|
128
|
+
if (claims.length === 0) say(`no gate slot is held in ${dir}`);
|
|
129
|
+
for (const { index, holder } of claims) {
|
|
130
|
+
const age = holder ? `${Math.round((now() - Date.parse(holder.startedAt)) / MINUTE_MS)} min` : "unreadable";
|
|
131
|
+
say(`slot-${index} pid ${holder?.pid ?? "?"} ${age} ${holder?.cwd ?? ""} ${holder?.command ?? ""}`);
|
|
132
|
+
}
|
|
133
|
+
return 0;
|
|
134
|
+
}
|
|
135
|
+
const line = commandLine(command);
|
|
136
|
+
let file = null;
|
|
137
|
+
let waited = false;
|
|
138
|
+
while (file === null) {
|
|
139
|
+
freeStale(dir, now(), maxMinutes, alive);
|
|
140
|
+
file = claimSlot(dir, slots, { pid, startedAt: new Date(now()).toISOString(), cwd: process.cwd(), command: line });
|
|
141
|
+
if (file !== null) break;
|
|
142
|
+
if (!waited) say(`qc gate-slot: all ${slots} slots are held; waiting. \`qc gate-slot --status\` lists them.`);
|
|
143
|
+
waited = true;
|
|
144
|
+
await sleep(WAIT_MS);
|
|
145
|
+
}
|
|
146
|
+
try {
|
|
147
|
+
return await run(line, env);
|
|
148
|
+
} finally {
|
|
149
|
+
rmSync(file, { force: true });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { strict as assert } from "node:assert";
|
|
2
|
+
import { existsSync, mkdirSync, mkdtempSync, readdirSync, 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 { claimSlot, freeStale, gateSlotDirOf, isAlive, runGateSlot } from "./gate-slot.mjs";
|
|
7
|
+
|
|
8
|
+
function slotDir(t) {
|
|
9
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), "qc-gate-slot-"));
|
|
10
|
+
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
|
11
|
+
return dir;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const holder = (pid, startedAt) => JSON.stringify({ pid, startedAt: new Date(startedAt).toISOString(), cwd: "x", command: "pnpm check:local" });
|
|
15
|
+
|
|
16
|
+
test("the folder is machine-wide under the temp folder, and QC_GATE_SLOT_DIR moves it", () => {
|
|
17
|
+
assert.equal(gateSlotDirOf({}, "/tmp"), path.join("/tmp", "architecture-kit", "gate-slots"));
|
|
18
|
+
assert.equal(gateSlotDirOf({ QC_GATE_SLOT_DIR: "/slots" }, "/tmp"), "/slots");
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test("this process is alive, and an id that is no number is not", () => {
|
|
22
|
+
assert.equal(isAlive(process.pid), true);
|
|
23
|
+
assert.equal(isAlive(0), false);
|
|
24
|
+
assert.equal(isAlive(Number.NaN), false);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test("a claim whose process is gone, or that outlived the limit, is freed; a live one stays", (t) => {
|
|
28
|
+
const dir = slotDir(t);
|
|
29
|
+
const now = Date.parse("2026-01-01T12:00:00Z");
|
|
30
|
+
writeFileSync(path.join(dir, "slot-0.json"), holder(111, now));
|
|
31
|
+
writeFileSync(path.join(dir, "slot-1.json"), holder(222, now - 121 * 60_000));
|
|
32
|
+
writeFileSync(path.join(dir, "slot-2.json"), holder(333, now));
|
|
33
|
+
const freed = freeStale(dir, now, 120, (pid) => pid !== 111);
|
|
34
|
+
assert.deepEqual(freed.map((claim) => claim.index).sort(), [0, 1]);
|
|
35
|
+
assert.deepEqual(readdirSync(dir), ["slot-2.json"]);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test("a claim takes the first free slot, and a full set returns null", (t) => {
|
|
39
|
+
const dir = slotDir(t);
|
|
40
|
+
assert.ok(claimSlot(dir, 2, { pid: 1 }).endsWith("slot-0.json"));
|
|
41
|
+
assert.ok(claimSlot(dir, 2, { pid: 2 }).endsWith("slot-1.json"));
|
|
42
|
+
assert.equal(claimSlot(dir, 2, { pid: 3 }), null);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("a dead holder's slot is freed for the next run, which frees its own slot when the command ends", async (t) => {
|
|
46
|
+
const dir = slotDir(t);
|
|
47
|
+
writeFileSync(path.join(dir, "slot-0.json"), holder(999999, Date.now()));
|
|
48
|
+
const ran = [];
|
|
49
|
+
const code = await runGateSlot(["--slots", "1", "--", "pnpm", "check:local"], {
|
|
50
|
+
env: { QC_GATE_SLOT_DIR: dir },
|
|
51
|
+
alive: (pid) => pid !== 999999,
|
|
52
|
+
run: async (command) => {
|
|
53
|
+
ran.push(command);
|
|
54
|
+
assert.ok(existsSync(path.join(dir, "slot-0.json")));
|
|
55
|
+
return 4;
|
|
56
|
+
},
|
|
57
|
+
say: () => {},
|
|
58
|
+
});
|
|
59
|
+
assert.equal(code, 4);
|
|
60
|
+
assert.deepEqual(ran, ["pnpm check:local"]);
|
|
61
|
+
assert.deepEqual(readdirSync(dir), []);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test("a full set waits until a slot frees", async (t) => {
|
|
65
|
+
const dir = slotDir(t);
|
|
66
|
+
mkdirSync(dir, { recursive: true });
|
|
67
|
+
writeFileSync(path.join(dir, "slot-0.json"), holder(555, Date.now()));
|
|
68
|
+
let alive = true;
|
|
69
|
+
const said = [];
|
|
70
|
+
const code = await runGateSlot(["--slots", "1", "--", "node", "-v"], {
|
|
71
|
+
env: { QC_GATE_SLOT_DIR: dir },
|
|
72
|
+
alive: () => alive,
|
|
73
|
+
sleep: async () => {
|
|
74
|
+
alive = false;
|
|
75
|
+
},
|
|
76
|
+
run: async () => 0,
|
|
77
|
+
say: (line) => said.push(line),
|
|
78
|
+
});
|
|
79
|
+
assert.equal(code, 0);
|
|
80
|
+
assert.match(said.join("\n"), /all 1 slots are held/);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test("--status lists each holder, and a missing command is a usage error", async (t) => {
|
|
84
|
+
const dir = slotDir(t);
|
|
85
|
+
writeFileSync(path.join(dir, "slot-0.json"), holder(process.pid, Date.now()));
|
|
86
|
+
const said = [];
|
|
87
|
+
assert.equal(await runGateSlot(["--status"], { env: { QC_GATE_SLOT_DIR: dir }, say: (line) => said.push(line) }), 0);
|
|
88
|
+
assert.match(said.join("\n"), new RegExp(`slot-0 +pid ${process.pid}`));
|
|
89
|
+
assert.equal(await runGateSlot([], { env: { QC_GATE_SLOT_DIR: dir }, say: () => {} }), 2);
|
|
90
|
+
});
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// `qc integrate`: one integration branch for a batch of branches, so the batch runs one CI and merges once.
|
|
2
|
+
// Each merge renumbers its migrations, and a conflict in generated files is settled by the generator.
|
|
3
|
+
|
|
4
|
+
import { spawnSync } from "node:child_process";
|
|
5
|
+
import { parseArgs } from "node:util";
|
|
6
|
+
import { globMatcher } from "../glob.mjs";
|
|
7
|
+
import { posixDir, renumber } from "./migrations.mjs";
|
|
8
|
+
|
|
9
|
+
export const USAGE = `qc integrate — one integration branch for a batch of branches
|
|
10
|
+
|
|
11
|
+
qc integrate --issue <n> [--type <type>] [--slug <slug>] [--from <ref>] <branch>...
|
|
12
|
+
make <type>/<n>-<slug> from <ref> (worktree.base by default), or continue it when it exists;
|
|
13
|
+
merge each branch in order, renumber its migrations after the last one before it, and commit;
|
|
14
|
+
then run generated.command and commit what it changes. A conflict stops the run and lists the
|
|
15
|
+
files. Resolve it, commit, and run the same command again: a branch already merged is skipped.`;
|
|
16
|
+
|
|
17
|
+
function tryGit(cwd, args) {
|
|
18
|
+
const result = spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true });
|
|
19
|
+
return { ok: result.status === 0, out: result.stdout ?? "", err: (result.stderr ?? "").trim() };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function git(cwd, args) {
|
|
23
|
+
const result = tryGit(cwd, args);
|
|
24
|
+
if (!result.ok) throw new Error(`git ${args.join(" ")}: ${result.err || "failed"}`);
|
|
25
|
+
return result.out;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const lines = (text) => text.split(/\r?\n/).filter(Boolean);
|
|
29
|
+
|
|
30
|
+
function runShell(command, cwd) {
|
|
31
|
+
return spawnSync(command, { cwd, shell: true, stdio: "inherit", windowsHide: true }).status ?? 1;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The branch name `<type>/<issue>-<slug>`; throws on an issue that is no number or a type that is no word. */
|
|
35
|
+
export function integrationBranch({ issue, type = "feat", slug = "integration" }) {
|
|
36
|
+
if (!/^[1-9]\d*$/.test(String(issue ?? ""))) throw new Error(`--issue must be an issue number, got ${issue}`);
|
|
37
|
+
if (!/^[a-z]+$/.test(type)) throw new Error(`--type must be lowercase letters, got ${type}`);
|
|
38
|
+
const tail = String(slug).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
39
|
+
return `${type}/${issue}-${tail || "integration"}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function parse(argv) {
|
|
43
|
+
const { values, positionals } = parseArgs({
|
|
44
|
+
args: argv,
|
|
45
|
+
options: { issue: { type: "string" }, type: { type: "string" }, slug: { type: "string" }, from: { type: "string" } },
|
|
46
|
+
allowPositionals: true,
|
|
47
|
+
strict: true,
|
|
48
|
+
});
|
|
49
|
+
if (!values.issue) throw new Error("--issue <n> is required");
|
|
50
|
+
if (positionals.length === 0) throw new Error("name at least one branch to merge");
|
|
51
|
+
return { ...values, branches: positionals };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const conflictReport = (branch, files) =>
|
|
55
|
+
[
|
|
56
|
+
`CONFLICT merging ${branch}; the merge is left in progress. Files:`,
|
|
57
|
+
...files.map((file) => ` ${file}`),
|
|
58
|
+
"Resolve them, run `qc migrations renumber --onto HEAD --branch MERGE_HEAD`, commit, and run qc integrate again.",
|
|
59
|
+
].join("\n");
|
|
60
|
+
|
|
61
|
+
/** `qc integrate`. @returns the exit code */
|
|
62
|
+
export async function runIntegrate(config, argv, { say = (line) => console.log(line), run = runShell } = {}) {
|
|
63
|
+
let options;
|
|
64
|
+
try {
|
|
65
|
+
options = parse(argv);
|
|
66
|
+
} catch (error) {
|
|
67
|
+
console.error(`qc integrate: ${error.message}\n\n${USAGE}`);
|
|
68
|
+
return 2;
|
|
69
|
+
}
|
|
70
|
+
const root = config.root;
|
|
71
|
+
try {
|
|
72
|
+
const name = integrationBranch(options);
|
|
73
|
+
const pattern = config.branches?.pattern;
|
|
74
|
+
if (pattern && !new RegExp(pattern).test(name)) throw new Error(`${name} does not match branches.pattern ${pattern}`);
|
|
75
|
+
if (tryGit(root, ["rev-parse", "-q", "--verify", "MERGE_HEAD"]).ok) throw new Error("a merge is in progress: resolve it, commit it, then run qc integrate again");
|
|
76
|
+
if (git(root, ["status", "--porcelain"]).trim() !== "") throw new Error("the working tree has changes: commit or stash them first");
|
|
77
|
+
tryGit(root, ["fetch", "--quiet", "origin"]);
|
|
78
|
+
if (git(root, ["branch", "--show-current"]).trim() !== name) {
|
|
79
|
+
if (tryGit(root, ["rev-parse", "-q", "--verify", `refs/heads/${name}`]).ok) git(root, ["switch", "-q", name]);
|
|
80
|
+
else git(root, ["switch", "-q", "-c", name, options.from ?? config.worktree?.base ?? "origin/main"]);
|
|
81
|
+
}
|
|
82
|
+
const dir = posixDir(config.paths?.migrations);
|
|
83
|
+
const generated = globMatcher(config.generated?.globs ?? []);
|
|
84
|
+
for (const branch of options.branches) {
|
|
85
|
+
if (tryGit(root, ["merge-base", "--is-ancestor", branch, "HEAD"]).ok) {
|
|
86
|
+
say(`skip ${branch}: already merged`);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
const merged = tryGit(root, ["merge", "--no-ff", "--no-commit", branch]);
|
|
90
|
+
if (!merged.ok) {
|
|
91
|
+
const conflicts = lines(git(root, ["diff", "--name-only", "--diff-filter=U"]));
|
|
92
|
+
if (conflicts.length === 0) throw new Error(`git merge ${branch}: ${merged.err}`);
|
|
93
|
+
const byHand = conflicts.filter((file) => !generated(file));
|
|
94
|
+
if (byHand.length > 0) {
|
|
95
|
+
say(conflictReport(branch, byHand));
|
|
96
|
+
return 1;
|
|
97
|
+
}
|
|
98
|
+
git(root, ["checkout", "--ours", "--", ...conflicts]);
|
|
99
|
+
git(root, ["add", "--", ...conflicts]);
|
|
100
|
+
}
|
|
101
|
+
if (dir) {
|
|
102
|
+
for (const { from, to } of renumber(root, dir, { onto: "HEAD", branch: "MERGE_HEAD" }).plan) say(`rename ${dir}/${from} -> ${to}`);
|
|
103
|
+
}
|
|
104
|
+
git(root, ["commit", "-q", "--no-edit"]);
|
|
105
|
+
say(`merge ${branch}`);
|
|
106
|
+
}
|
|
107
|
+
const command = config.generated?.command;
|
|
108
|
+
if (command) {
|
|
109
|
+
if (run(command, root) !== 0) throw new Error(`${command} failed; fix it, commit, and run qc integrate again`);
|
|
110
|
+
if (git(root, ["status", "--porcelain"]).trim() !== "") {
|
|
111
|
+
git(root, ["add", "-A"]);
|
|
112
|
+
git(root, ["commit", "-q", "-m", "chore: regenerate the generated files", "-m", `Refs #${options.issue}`]);
|
|
113
|
+
say(`commit the output of ${command}`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
say(`OK ${name} holds ${options.branches.length} branch(es). Push it: git push -u origin ${name}`);
|
|
117
|
+
return 0;
|
|
118
|
+
} catch (error) {
|
|
119
|
+
console.error(`qc integrate: ${error.message}`);
|
|
120
|
+
return 1;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { strict as assert } from "node:assert";
|
|
2
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
3
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { test } from "node:test";
|
|
7
|
+
import { integrationBranch, runIntegrate } from "./integrate.mjs";
|
|
8
|
+
|
|
9
|
+
const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe", encoding: "utf8" }).trim();
|
|
10
|
+
const quiet = (lines) => (line) => lines.push(line);
|
|
11
|
+
const run = (command, cwd) => spawnSync(command, { cwd, shell: true, stdio: "pipe" }).status ?? 1;
|
|
12
|
+
|
|
13
|
+
function commitFile(dir, file, text) {
|
|
14
|
+
mkdirSync(path.dirname(path.join(dir, file)), { recursive: true });
|
|
15
|
+
writeFileSync(path.join(dir, file), text);
|
|
16
|
+
git(dir, "add", ".");
|
|
17
|
+
git(dir, "commit", "-q", "-m", file);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** A repository on main with one migration and a generator, and two branches that each add a migration. */
|
|
21
|
+
function batch(t) {
|
|
22
|
+
const dir = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-integrate-")));
|
|
23
|
+
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
|
24
|
+
git(dir, "init", "-q", "-b", "main");
|
|
25
|
+
for (const [key, value] of [["user.name", "qc"], ["user.email", "qc@example.com"], ["commit.gpgsign", "false"], ["core.autocrlf", "false"]]) git(dir, "config", key, value);
|
|
26
|
+
commitFile(dir, "db/0001_init.sql", "select 1;\n");
|
|
27
|
+
commitFile(dir, "gen.mjs", 'import { writeFileSync } from "node:fs";\nwriteFileSync("out.generated.txt", "regenerated\\n");\n');
|
|
28
|
+
commitFile(dir, "a.txt", "base\n");
|
|
29
|
+
for (const name of ["a", "b"]) {
|
|
30
|
+
git(dir, "switch", "-q", "-c", `feat/${name === "a" ? 1 : 2}-${name}`, "main");
|
|
31
|
+
commitFile(dir, `db/0002_${name}.sql`, `select '${name}';\n`);
|
|
32
|
+
}
|
|
33
|
+
git(dir, "switch", "-q", "main");
|
|
34
|
+
return dir;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const config = (dir, command = "node gen.mjs") => ({
|
|
38
|
+
root: dir,
|
|
39
|
+
paths: { migrations: "db" },
|
|
40
|
+
generated: { globs: ["**/*.generated.*"], command },
|
|
41
|
+
branches: { pattern: "^[a-z]+/[0-9]+-" },
|
|
42
|
+
worktree: { base: "main" },
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("the integration branch names its issue, and an issue that is no number is refused", () => {
|
|
46
|
+
assert.equal(integrationBranch({ issue: "7" }), "feat/7-integration");
|
|
47
|
+
assert.equal(integrationBranch({ issue: "7", type: "fix", slug: "Desktop Round" }), "fix/7-desktop-round");
|
|
48
|
+
assert.throws(() => integrationBranch({ issue: "x" }), /issue number/);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test("integrate merges each branch in order and renumbers the later branch's migration", async (t) => {
|
|
52
|
+
const dir = batch(t);
|
|
53
|
+
const said = [];
|
|
54
|
+
const code = await runIntegrate(config(dir), ["--issue", "7", "--from", "main", "feat/1-a", "feat/2-b"], { say: quiet(said), run });
|
|
55
|
+
assert.equal(code, 0, said.join("\n"));
|
|
56
|
+
assert.equal(git(dir, "branch", "--show-current"), "feat/7-integration");
|
|
57
|
+
assert.deepEqual(readdirSync(path.join(dir, "db")).sort(), ["0001_init.sql", "0002_a.sql", "0003_b.sql"]);
|
|
58
|
+
assert.equal(readFileSync(path.join(dir, "out.generated.txt"), "utf8"), "regenerated\n");
|
|
59
|
+
assert.equal(git(dir, "status", "--porcelain"), "");
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test("a conflict stops the run with the file list, and a second run after the resolution continues", async (t) => {
|
|
63
|
+
const dir = batch(t);
|
|
64
|
+
for (const branch of ["feat/1-a", "feat/2-b"]) {
|
|
65
|
+
git(dir, "switch", "-q", branch);
|
|
66
|
+
commitFile(dir, "a.txt", `${branch}\n`);
|
|
67
|
+
}
|
|
68
|
+
git(dir, "switch", "-q", "main");
|
|
69
|
+
const said = [];
|
|
70
|
+
assert.equal(await runIntegrate(config(dir, null), ["--issue", "7", "--from", "main", "feat/1-a", "feat/2-b"], { say: quiet(said), run }), 1);
|
|
71
|
+
const report = said.join("\n");
|
|
72
|
+
assert.match(report, /a\.txt/);
|
|
73
|
+
assert.match(report, /qc migrations renumber --onto HEAD --branch MERGE_HEAD/);
|
|
74
|
+
assert.ok(existsSync(path.join(dir, ".git", "MERGE_HEAD")));
|
|
75
|
+
writeFileSync(path.join(dir, "a.txt"), "both\n");
|
|
76
|
+
git(dir, "add", "a.txt");
|
|
77
|
+
git(dir, "commit", "-q", "--no-edit");
|
|
78
|
+
const again = [];
|
|
79
|
+
assert.equal(await runIntegrate(config(dir, null), ["--issue", "7", "--from", "main", "feat/1-a", "feat/2-b"], { say: quiet(again), run }), 0);
|
|
80
|
+
assert.equal(again.filter((line) => line.startsWith("skip")).length, 2);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test("a conflict only in generated files is settled by the generator", async (t) => {
|
|
84
|
+
const dir = batch(t);
|
|
85
|
+
for (const branch of ["feat/1-a", "feat/2-b"]) {
|
|
86
|
+
git(dir, "switch", "-q", branch);
|
|
87
|
+
commitFile(dir, "out.generated.txt", `${branch}\n`);
|
|
88
|
+
}
|
|
89
|
+
git(dir, "switch", "-q", "main");
|
|
90
|
+
const said = [];
|
|
91
|
+
assert.equal(await runIntegrate(config(dir), ["--issue", "7", "--from", "main", "feat/1-a", "feat/2-b"], { say: quiet(said), run }), 0, said.join("\n"));
|
|
92
|
+
assert.equal(readFileSync(path.join(dir, "out.generated.txt"), "utf8"), "regenerated\n");
|
|
93
|
+
assert.equal(git(dir, "status", "--porcelain"), "");
|
|
94
|
+
});
|
package/src/cli/ledger.mjs
CHANGED
|
@@ -92,8 +92,30 @@ export function shaMatches(a, b) {
|
|
|
92
92
|
}
|
|
93
93
|
|
|
94
94
|
/** The newest verdict of one of `kinds` that names `sha`, or null. */
|
|
95
|
-
export const latestVerdictFor = (records, sha, kinds) =>
|
|
96
|
-
records.findLast(
|
|
95
|
+
export const latestVerdictFor = (records, sha, kinds, scope) =>
|
|
96
|
+
records.findLast(
|
|
97
|
+
(record) =>
|
|
98
|
+
record.type === "verdict" && kinds.includes(record.kind) && shaMatches(record.sha, sha) && (scope === undefined || (record.scope ?? null) === scope),
|
|
99
|
+
) ?? null;
|
|
100
|
+
|
|
101
|
+
/** The scopes of the branch reviews dispatched on the branch of any dispatch whose head is `sha`. */
|
|
102
|
+
export function dispatchedScopesFor(records, sha) {
|
|
103
|
+
const branches = new Set(
|
|
104
|
+
records.filter((record) => record.type === "dispatch" && typeof record.branch === "string" && shaMatches(record.head, sha)).map((record) => record.branch),
|
|
105
|
+
);
|
|
106
|
+
const scopes = records.filter((record) => record.type === "dispatch" && branches.has(record.branch) && typeof record.scope === "string").map((record) => record.scope);
|
|
107
|
+
return [...new Set(scopes)];
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The verdict that decides `sha`: the newest of each scope, where a CHANGES_REQUIRED wins. Null when none names it. */
|
|
111
|
+
export function decidingVerdictFor(records, sha, kinds) {
|
|
112
|
+
const newest = new Map();
|
|
113
|
+
for (const record of records) {
|
|
114
|
+
if (record.type === "verdict" && kinds.includes(record.kind) && shaMatches(record.sha, sha)) newest.set(record.scope ?? null, record);
|
|
115
|
+
}
|
|
116
|
+
const verdicts = [...newest.values()];
|
|
117
|
+
return verdicts.find((record) => record.verdict !== "APPROVED") ?? verdicts.at(-1) ?? null;
|
|
118
|
+
}
|
|
97
119
|
|
|
98
120
|
/** The newest verdict of any kind on `branch`, or null. */
|
|
99
121
|
export const latestVerdictOn = (records, branch) =>
|
|
@@ -107,7 +129,7 @@ const short = (sha) => (typeof sha === "string" ? sha.slice(0, MIN_SHA) : "");
|
|
|
107
129
|
|
|
108
130
|
const SUMMARIES = {
|
|
109
131
|
dispatch: (r) =>
|
|
110
|
-
`${r.agentType} ${r.task ? `${r.branch} ${short(r.head)}` : "(no task)"}${r.resumeReason ? ` NO-RESUME: ${r.resumeReason}` : ""}${
|
|
132
|
+
`${r.agentType} ${r.task ? `${r.branch} ${short(r.head)}` : "(no task)"}${r.resumeReason ? ` NO-RESUME: ${r.resumeReason}` : ""}${r.fix ? ` FIX: ${r.fix}` : ""}${
|
|
111
133
|
r.ciPass ? ` CI-PASS: ${short(r.ciPass.sha)} ${r.ciPass.reason}` : ""
|
|
112
134
|
}${
|
|
113
135
|
r.handoff ? ` HANDOFF: ${r.handoff}` : ""
|
package/src/cli/ledger.test.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import { test } from "node:test";
|
|
|
7
7
|
import { fileURLToPath } from "node:url";
|
|
8
8
|
import {
|
|
9
9
|
appendRecord,
|
|
10
|
+
decidingVerdictFor,
|
|
10
11
|
commonDirOf,
|
|
11
12
|
formatRecord,
|
|
12
13
|
lastTaskDispatchOn,
|
|
@@ -185,3 +186,11 @@ test("a cost record prints as one line in the plain ledger listing", () => {
|
|
|
185
186
|
const line = formatRecord({ ...cost("a1", "implementer", "feat/1-x", 10, 100, 5), at: "2026-10-09T10:00:00.000Z" });
|
|
186
187
|
assert.match(line, /^2026-10-09T10:00:00.000Z {2}cost {10}implementer sdd-implementer a1 feat\/1-x in 10 out 100 .* tools 5$/);
|
|
187
188
|
});
|
|
189
|
+
|
|
190
|
+
test("the deciding verdict on a sha is a CHANGES_REQUIRED that is the newest of its scope, else the newest APPROVED", () => {
|
|
191
|
+
const sha = "a".repeat(40);
|
|
192
|
+
const v = (verdict, scope) => ({ type: "verdict", kind: "branch", verdict, sha, branch: "b", ...(scope ? { scope } : {}) });
|
|
193
|
+
assert.equal(decidingVerdictFor([v("APPROVED", "x"), v("CHANGES_REQUIRED", "y")], sha, ["branch"]).verdict, "CHANGES_REQUIRED");
|
|
194
|
+
assert.equal(decidingVerdictFor([v("CHANGES_REQUIRED", "y"), v("APPROVED", "y")], sha, ["branch"]).verdict, "APPROVED");
|
|
195
|
+
assert.equal(decidingVerdictFor([v("APPROVED")], sha, ["task"]), null);
|
|
196
|
+
});
|
package/src/cli/merge-guard.mjs
CHANGED
|
@@ -11,7 +11,7 @@ import { LANE_BUDGET_MS, mergeLane, sizeLine } from "./direct-lane.mjs";
|
|
|
11
11
|
import { ghApiMerges, ghMerges } from "./gh-merge-command.mjs";
|
|
12
12
|
import { runGh } from "./gh-run.mjs";
|
|
13
13
|
import { originOf, repoOfSpelling } from "./git-read.mjs";
|
|
14
|
-
import { appendRecord, latestVerdictFor, readLedger } from "./ledger.mjs";
|
|
14
|
+
import { appendRecord, decidingVerdictFor, dispatchedScopesFor, latestVerdictFor, readLedger } from "./ledger.mjs";
|
|
15
15
|
import { workflowAt } from "./workflow-settings.mjs";
|
|
16
16
|
import { worktreeRuleAt } from "./worktree-settings.mjs";
|
|
17
17
|
|
|
@@ -36,8 +36,18 @@ export function mergeVerdict(merges, records, kind, lane = null) {
|
|
|
36
36
|
if (!merge.sha) {
|
|
37
37
|
return { refusal: `Merge guard: \`gh pr merge\` must pass \`--match-head-commit <sha>\` with the head the ${kind} review approved, so a push after the review cannot merge unreviewed. Add it.` };
|
|
38
38
|
}
|
|
39
|
-
const verdict =
|
|
40
|
-
|
|
39
|
+
const verdict = decidingVerdictFor(records, merge.sha, [kind]);
|
|
40
|
+
const missing = dispatchedScopesFor(records, merge.sha).find(
|
|
41
|
+
(scope) => latestVerdictFor(records, merge.sha, [kind], scope)?.verdict !== "APPROVED",
|
|
42
|
+
);
|
|
43
|
+
if (verdict?.verdict === "APPROVED" && missing === undefined) continue;
|
|
44
|
+
if (missing !== undefined) {
|
|
45
|
+
return {
|
|
46
|
+
refusal:
|
|
47
|
+
`Merge guard: the ledger holds no APPROVED ${kind} review of scope "${missing}" on ${merge.sha}, and a review of that scope was dispatched. ` +
|
|
48
|
+
`Dispatch ${REVIEWER[kind]} with \`Scope: ${missing}\` on that head, and merge after every scope approves.`,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
41
51
|
const fit = lane ? lane(merge) : null;
|
|
42
52
|
if (fit && fit.problem === null) {
|
|
43
53
|
direct.push(fit.note);
|
|
@@ -6,7 +6,7 @@ import path from "node:path";
|
|
|
6
6
|
import { test } from "node:test";
|
|
7
7
|
import { fileURLToPath } from "node:url";
|
|
8
8
|
import { appendRecord, readLedger } from "./ledger.mjs";
|
|
9
|
-
import { decide, namedIssues } from "./merge-guard.mjs";
|
|
9
|
+
import { decide, mergeVerdict, namedIssues } from "./merge-guard.mjs";
|
|
10
10
|
|
|
11
11
|
const HOOK = fileURLToPath(new URL("./merge-guard.mjs", import.meta.url));
|
|
12
12
|
const SHA = "0123456789abcdef0123456789abcdef01234567";
|
|
@@ -491,3 +491,26 @@ test("a gh answer with no base commit closes the lane", (t) => {
|
|
|
491
491
|
const reason = denied(decide(merge7(dir, head), { gh: fakeGh(JSON.stringify({ baseRefName: "main" })).gh })) ?? "";
|
|
492
492
|
assert.match(reason, /does not apply: gh returned no base commit for the PR/);
|
|
493
493
|
});
|
|
494
|
+
|
|
495
|
+
test("a merge waits while the newest review of any scope on the head asks for changes", () => {
|
|
496
|
+
const sha = "b".repeat(40);
|
|
497
|
+
const records = [
|
|
498
|
+
{ type: "verdict", kind: "branch", verdict: "CHANGES_REQUIRED", sha, branch: "f", scope: "a" },
|
|
499
|
+
{ type: "verdict", kind: "branch", verdict: "APPROVED", sha, branch: "f", scope: "b" },
|
|
500
|
+
];
|
|
501
|
+
assert.match(mergeVerdict([{ sha }], records, "branch").refusal ?? "", /CHANGES_REQUIRED/);
|
|
502
|
+
records.push({ type: "verdict", kind: "branch", verdict: "APPROVED", sha, branch: "f", scope: "a" });
|
|
503
|
+
assert.equal(mergeVerdict([{ sha }], records, "branch").refusal, null);
|
|
504
|
+
});
|
|
505
|
+
|
|
506
|
+
test("a merge needs an APPROVED review of every scope dispatched on the branch", () => {
|
|
507
|
+
const sha = "c".repeat(40);
|
|
508
|
+
const records = [
|
|
509
|
+
{ type: "dispatch", task: false, agentType: "sdd-branch-reviewer", branch: "f", head: sha, scope: "a" },
|
|
510
|
+
{ type: "dispatch", task: false, agentType: "sdd-branch-reviewer", branch: "f", head: sha, scope: "b" },
|
|
511
|
+
{ type: "verdict", kind: "branch", verdict: "APPROVED", sha, branch: "f", scope: "a" },
|
|
512
|
+
];
|
|
513
|
+
assert.match(mergeVerdict([{ sha }], records, "branch").refusal ?? "", /scope "b"/);
|
|
514
|
+
records.push({ type: "verdict", kind: "branch", verdict: "APPROVED", sha, branch: "f", scope: "b" });
|
|
515
|
+
assert.equal(mergeVerdict([{ sha }], records, "branch").refusal, null);
|
|
516
|
+
});
|