architecture-harness 0.4.2 → 0.6.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 +1 -1
- package/src/cli/check.mjs +32 -6
- package/src/cli/cli.test.mjs +44 -0
- package/src/cli/lease-file.mjs +33 -0
- package/src/cli/lease.mjs +136 -0
- package/src/cli/lease.test.mjs +140 -0
- package/src/cli/post-edit-gate.test.mjs +75 -0
- package/src/cli/qc.mjs +22 -10
- package/src/cli/run-dispatch.mjs +52 -0
- package/src/cli/run.mjs +75 -0
- package/src/cli/run.test.mjs +71 -0
- package/src/cli/work-order-guard.mjs +0 -0
- package/src/cli/work-order-guard.test.mjs +127 -2
- package/src/cli/worktree-isolation.mjs +48 -14
- package/src/cli/worktree-isolation.test.mjs +57 -0
- package/src/config.mjs +34 -0
- package/src/descriptions.mjs +2 -1
- package/src/gates/eight-blocks.mjs +5 -1
- package/src/gates/eight-blocks.test.mjs +21 -0
- package/src/gates/feature-cli.mjs +198 -0
- package/src/gates/feature-cli.test.mjs +172 -0
- package/src/gates/test-mirror.mjs +57 -37
- package/src/gates/test-mirror.test.mjs +67 -4
- package/templates/githooks/pre-push +18 -0
package/src/cli/run.mjs
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// `qc run <feature>.<command>` — the headless entrypoint the feature-cli gate exists to guarantee.
|
|
2
|
+
//
|
|
3
|
+
// The harness stays dumb on purpose: it resolves the registry a repository's codegen writes,
|
|
4
|
+
// looks up one key and calls it. Every decision about what a command *does* belongs to the
|
|
5
|
+
// repository, so the kit can dispatch a tree it knows nothing about.
|
|
6
|
+
//
|
|
7
|
+
// The registry module exports `commands`: a record keyed `<feature>.<command>`, each entry a
|
|
8
|
+
// `{ describe?, run(input) }`. Composing it is codegen's job — a hand-edited registry drifts.
|
|
9
|
+
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import process from "node:process";
|
|
12
|
+
import { spawn } from "node:child_process";
|
|
13
|
+
import { existsSync } from "node:fs";
|
|
14
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
15
|
+
|
|
16
|
+
const SHIM = fileURLToPath(new URL("./run-dispatch.mjs", import.meta.url));
|
|
17
|
+
|
|
18
|
+
/** `--json '<payload>'` is the whole input; `--key value` pairs build one. Both, and the pairs win. */
|
|
19
|
+
export function parseInput(argv) {
|
|
20
|
+
const flags = {};
|
|
21
|
+
let json;
|
|
22
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
23
|
+
const arg = argv[index];
|
|
24
|
+
if (!arg.startsWith("--")) continue;
|
|
25
|
+
const [name, inline] = arg.slice(2).split(/=(.*)/s);
|
|
26
|
+
const value = inline ?? (argv[index + 1]?.startsWith("--") ? "true" : argv[++index]);
|
|
27
|
+
if (name === "json") json = value;
|
|
28
|
+
else flags[name] = value === undefined ? true : value;
|
|
29
|
+
}
|
|
30
|
+
let parsed = {};
|
|
31
|
+
if (json !== undefined) {
|
|
32
|
+
try {
|
|
33
|
+
parsed = JSON.parse(json);
|
|
34
|
+
} catch (cause) {
|
|
35
|
+
throw new Error(`--json is not valid JSON: ${cause.message}`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return { ...parsed, ...flags };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* A TypeScript registry needs the repository's own loader; a JavaScript one is imported here.
|
|
43
|
+
* Spawning rather than registering keeps the harness free of a loader dependency it does not own.
|
|
44
|
+
*/
|
|
45
|
+
export function needsLoader(registry, loader) {
|
|
46
|
+
return loader.length > 0 && /\.[cm]?tsx?$/.test(registry);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function runRun(config, argv) {
|
|
50
|
+
const cli = config.cli ?? {};
|
|
51
|
+
const registry = path.resolve(config.root, cli.registry ?? "");
|
|
52
|
+
const loader = cli.loader ?? [];
|
|
53
|
+
|
|
54
|
+
if (cli.registry === undefined || cli.registry === "") {
|
|
55
|
+
console.error("qc run: no cli.registry in qc.config.json — nothing to dispatch");
|
|
56
|
+
return 1;
|
|
57
|
+
}
|
|
58
|
+
if (!existsSync(registry)) {
|
|
59
|
+
console.error(`qc run: ${cli.registry} does not exist — run this repository's codegen to compose it`);
|
|
60
|
+
return 1;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const [name, ...rest] = argv;
|
|
64
|
+
if (needsLoader(registry, loader)) {
|
|
65
|
+
const args = loader.flatMap((specifier) => ["--import", specifier]);
|
|
66
|
+
const child = spawn(process.execPath, [...args, SHIM, registry, ...(name === undefined ? [] : [name]), ...rest], {
|
|
67
|
+
cwd: config.root,
|
|
68
|
+
stdio: "inherit",
|
|
69
|
+
});
|
|
70
|
+
return await new Promise((resolve) => child.on("exit", (code) => resolve(code ?? 1)));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const { dispatch } = await import(pathToFileURL(SHIM).href);
|
|
74
|
+
return await dispatch(registry, name, rest);
|
|
75
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { mkdtemp, writeFile } from "node:fs/promises";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { needsLoader, parseInput, runRun } from "./run.mjs";
|
|
7
|
+
import { listing } from "./run-dispatch.mjs";
|
|
8
|
+
|
|
9
|
+
test("--json carries the whole input", () => {
|
|
10
|
+
assert.deepEqual(parseInput(["--json", '{"projectId":"P3","qty":12}']), { projectId: "P3", qty: 12 });
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
test("--key value pairs build an input without any json", () => {
|
|
14
|
+
assert.deepEqual(parseInput(["--project", "P3", "--title", "a task"]), { project: "P3", title: "a task" });
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test("--key=value is read the same way", () => {
|
|
18
|
+
assert.deepEqual(parseInput(["--project=P3"]), { project: "P3" });
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test("a flag with no value reads as true rather than swallowing the next flag", () => {
|
|
22
|
+
assert.deepEqual(parseInput(["--dry-run", "--project", "P3"]), { "dry-run": "true", project: "P3" });
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
test("a pair overrides the same key inside --json", () => {
|
|
26
|
+
assert.deepEqual(parseInput(["--json", '{"project":"P1"}', "--project", "P3"]), { project: "P3" });
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("invalid json fails loudly rather than dispatching an empty input", () => {
|
|
30
|
+
assert.throws(() => parseInput(["--json", "{nope"]), /not valid JSON/);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("a typescript registry needs the configured loader, a javascript one does not", () => {
|
|
34
|
+
assert.equal(needsLoader("a/commands.generated.ts", ["tsx"]), true);
|
|
35
|
+
assert.equal(needsLoader("a/commands.generated.mjs", ["tsx"]), false);
|
|
36
|
+
assert.equal(needsLoader("a/commands.generated.ts", []), false);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test("the listing names every command, sorted, with its description", () => {
|
|
40
|
+
const commands = { "tasks.kanban": { describe: "board columns" }, "progress.entries": {} };
|
|
41
|
+
assert.deepEqual(listing(commands), [" progress.entries", ` ${"tasks.kanban".padEnd(38)}board columns`]);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test("a repository that configures no registry is told so rather than crashing", async () => {
|
|
45
|
+
const code = await runRun({ root: process.cwd(), cli: {} }, ["tasks.kanban"]);
|
|
46
|
+
assert.equal(code, 1);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test("a configured registry that does not exist names codegen as the fix", async () => {
|
|
50
|
+
const code = await runRun({ root: process.cwd(), cli: { registry: "nowhere/commands.generated.ts" } }, []);
|
|
51
|
+
assert.equal(code, 1);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test("a javascript registry dispatches in process and returns the command's result", async () => {
|
|
55
|
+
const dir = await mkdtemp(path.join(tmpdir(), "qc-run-"));
|
|
56
|
+
const registry = "commands.generated.mjs";
|
|
57
|
+
await writeFile(
|
|
58
|
+
path.join(dir, registry),
|
|
59
|
+
'export const commands = { "tasks.kanban": { run: (input) => ({ seen: input }) } };',
|
|
60
|
+
);
|
|
61
|
+
const code = await runRun({ root: dir, cli: { registry, loader: [] } }, ["tasks.kanban", "--project", "P3"]);
|
|
62
|
+
assert.equal(code, 0);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test("an unknown command fails and does not run anything", async () => {
|
|
66
|
+
const dir = await mkdtemp(path.join(tmpdir(), "qc-run-"));
|
|
67
|
+
const registry = "commands.generated.mjs";
|
|
68
|
+
await writeFile(path.join(dir, registry), 'export const commands = { "tasks.kanban": { run: () => 1 } };');
|
|
69
|
+
const code = await runRun({ root: dir, cli: { registry, loader: [] } }, ["tasks.nope"]);
|
|
70
|
+
assert.equal(code, 1);
|
|
71
|
+
});
|
|
Binary file
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { strict as assert } from "node:assert";
|
|
2
|
-
import {
|
|
2
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
3
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
3
5
|
import path from "node:path";
|
|
4
6
|
import { test } from "node:test";
|
|
5
7
|
import { fileURLToPath } from "node:url";
|
|
6
|
-
import { branchMismatch, denyOutput, globToRegExp, inSpecialGitOperation, isAllowed } from "./work-order-guard.mjs";
|
|
8
|
+
import { branchMismatch, decide, denyOutput, globToRegExp, inSpecialGitOperation, isAllowed } from "./work-order-guard.mjs";
|
|
7
9
|
|
|
8
10
|
test("a path under a declared glob is allowed", () => {
|
|
9
11
|
assert.equal(isAllowed("frontend/src/platform/ui/button.tsx", ["frontend/src/platform/**"]), true);
|
|
@@ -77,3 +79,126 @@ test("the installed pre-commit hook checks the work order before its staged-file
|
|
|
77
79
|
assert.notEqual(filterLine, -1, "pre-commit should still filter staged files by extension");
|
|
78
80
|
assert.ok(checkLine < filterLine, "the branch check must run before the extension filter, or a .tf/.yml/.md commit skips it");
|
|
79
81
|
});
|
|
82
|
+
|
|
83
|
+
/** A primary checkout on main that requires worktree isolation, one linked worktree, and a folder in no checkout. */
|
|
84
|
+
function isolatedRepository() {
|
|
85
|
+
const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-guard-")));
|
|
86
|
+
const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe" });
|
|
87
|
+
const primary = path.join(base, "primary");
|
|
88
|
+
const linked = path.join(base, "linked");
|
|
89
|
+
const outside = path.join(base, "outside");
|
|
90
|
+
mkdirSync(primary);
|
|
91
|
+
mkdirSync(outside);
|
|
92
|
+
git(primary, "init", "-q", "-b", "main");
|
|
93
|
+
writeFileSync(path.join(primary, "qc.config.json"), JSON.stringify({ swarm: { isolation: { require: "worktree" } } }));
|
|
94
|
+
git(primary, "add", ".");
|
|
95
|
+
git(primary, "-c", "user.name=qc", "-c", "user.email=qc@example.com", "commit", "-q", "-m", "init");
|
|
96
|
+
git(primary, "worktree", "add", "-q", linked, "-b", "feat/work-order");
|
|
97
|
+
return { primary, linked, outside, cleanup: () => rmSync(base, { recursive: true, force: true }) };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const editOf = (file) => ({ tool_input: { file_path: file }, session_id: "session-aaaa" });
|
|
101
|
+
|
|
102
|
+
test("an edit to a file in no git checkout is allowed, whatever branch the project is on", async (t) => {
|
|
103
|
+
const repo = isolatedRepository();
|
|
104
|
+
t.after(repo.cleanup);
|
|
105
|
+
assert.equal(await decide(editOf(path.join(repo.outside, "memory", "note.md")), repo.primary), null);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("an edit in a linked worktree on a work-order branch is judged by that worktree, not the project", async (t) => {
|
|
109
|
+
const repo = isolatedRepository();
|
|
110
|
+
t.after(repo.cleanup);
|
|
111
|
+
assert.equal(await decide(editOf(path.join(repo.linked, "src", "new-folder", "file.ts")), repo.primary), null);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("an edit in the primary checkout on a protected branch is still refused", async (t) => {
|
|
115
|
+
const repo = isolatedRepository();
|
|
116
|
+
t.after(repo.cleanup);
|
|
117
|
+
const output = await decide(editOf(path.join(repo.primary, "src", "file.ts")), repo.primary);
|
|
118
|
+
assert.match(output.hookSpecificOutput.permissionDecisionReason, /"main" is a protected branch/);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test("the primary checkout is refused even when the session opened the linked worktree", async (t) => {
|
|
122
|
+
const repo = isolatedRepository();
|
|
123
|
+
t.after(repo.cleanup);
|
|
124
|
+
const output = await decide(editOf(path.join(repo.primary, "src", "file.ts")), repo.linked);
|
|
125
|
+
assert.match(output.hookSpecificOutput.permissionDecisionReason, /"main" is a protected branch/);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
const GUARD = fileURLToPath(new URL("./work-order-guard.mjs", import.meta.url));
|
|
129
|
+
const QC = fileURLToPath(new URL("./qc.mjs", import.meta.url));
|
|
130
|
+
const slashed = (file) => file.split(path.sep).join("/");
|
|
131
|
+
const hookEditOf = (file, sessionId) => ({
|
|
132
|
+
hook_event_name: "PreToolUse",
|
|
133
|
+
tool_name: "Edit",
|
|
134
|
+
tool_input: { file_path: file },
|
|
135
|
+
session_id: sessionId,
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
function leaseFileOf(worktree) {
|
|
139
|
+
const gitDir = execFileSync("git", ["rev-parse", "--absolute-git-dir"], { cwd: worktree, encoding: "utf8" }).trim();
|
|
140
|
+
return path.join(realpathSync.native(gitDir), "qc-agent-lease.json");
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Runs the guard as its own process, the way a hand test does, with the project pinned to the temp repository. */
|
|
144
|
+
function runGuard(worktree, input) {
|
|
145
|
+
return spawnSync(process.execPath, [GUARD], {
|
|
146
|
+
cwd: worktree,
|
|
147
|
+
input,
|
|
148
|
+
env: { ...process.env, CLAUDE_PROJECT_DIR: worktree },
|
|
149
|
+
encoding: "utf8",
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
test("a direct run of the guard with no hook input writes no lease", (t) => {
|
|
154
|
+
const repo = isolatedRepository();
|
|
155
|
+
t.after(repo.cleanup);
|
|
156
|
+
const result = runGuard(repo.linked, "");
|
|
157
|
+
assert.equal(result.status, 0, result.stderr);
|
|
158
|
+
assert.equal(existsSync(leaseFileOf(repo.linked)), false);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
test("a hand-built input with a made-up session and no hook event writes no lease", (t) => {
|
|
162
|
+
const repo = isolatedRepository();
|
|
163
|
+
t.after(repo.cleanup);
|
|
164
|
+
const input = JSON.stringify({ tool_input: { file_path: path.join(repo.linked, "src", "a.ts") }, session_id: "test-session" });
|
|
165
|
+
const result = runGuard(repo.linked, input);
|
|
166
|
+
assert.equal(result.status, 0, result.stderr);
|
|
167
|
+
assert.equal(existsSync(leaseFileOf(repo.linked)), false);
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
test("PreToolUse hook input claims the lease for its session and branch", (t) => {
|
|
171
|
+
const repo = isolatedRepository();
|
|
172
|
+
t.after(repo.cleanup);
|
|
173
|
+
const result = runGuard(repo.linked, JSON.stringify(hookEditOf(path.join(repo.linked, "src", "a.ts"), "session-aaaa")));
|
|
174
|
+
assert.equal(result.status, 0, result.stderr);
|
|
175
|
+
const lease = JSON.parse(readFileSync(leaseFileOf(repo.linked), "utf8"));
|
|
176
|
+
assert.equal(lease.sessionId, "session-aaaa");
|
|
177
|
+
assert.equal(lease.branch, "feat/work-order");
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
test("PreToolUse hook input with a blank session id claims no lease", async (t) => {
|
|
181
|
+
const repo = isolatedRepository();
|
|
182
|
+
t.after(repo.cleanup);
|
|
183
|
+
assert.equal(await decide(hookEditOf(path.join(repo.linked, "src", "a.ts"), " "), repo.linked), null);
|
|
184
|
+
assert.equal(existsSync(leaseFileOf(repo.linked)), false);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
test("a second session is refused with the lease file, its holder, and commands this copy can run", async (t) => {
|
|
188
|
+
const repo = isolatedRepository();
|
|
189
|
+
t.after(repo.cleanup);
|
|
190
|
+
const file = path.join(repo.linked, "src", "a.ts");
|
|
191
|
+
assert.equal(await decide(hookEditOf(file, "session-aaaa"), repo.linked), null);
|
|
192
|
+
const output = await decide(hookEditOf(file, "session-bbbb"), repo.linked);
|
|
193
|
+
const reason = output.hookSpecificOutput.permissionDecisionReason;
|
|
194
|
+
assert.ok(reason.includes(slashed(leaseFileOf(repo.linked))), reason);
|
|
195
|
+
assert.ok(reason.includes("session session-aaaa"), reason);
|
|
196
|
+
assert.ok(reason.includes(`lease release "${slashed(repo.linked)}" --force`), reason);
|
|
197
|
+
|
|
198
|
+
const status = reason.match(/`node "([^"]+)" lease status "([^"]+)"`/);
|
|
199
|
+
assert.ok(status, `the refusal names no runnable status command: ${reason}`);
|
|
200
|
+
assert.equal(path.resolve(status[1]), QC, "the command must name this copy of the CLI, not whichever qc is on the path");
|
|
201
|
+
const shown = spawnSync(process.execPath, [status[1], "lease", "status", status[2]], { cwd: repo.outside, encoding: "utf8" });
|
|
202
|
+
assert.equal(shown.status, 0, shown.stderr);
|
|
203
|
+
assert.match(shown.stdout, /session-aaaa/);
|
|
204
|
+
});
|
|
@@ -39,13 +39,54 @@ export function worktreeKind(gitDir, gitCommonDir) {
|
|
|
39
39
|
return path.resolve(gitDir) === path.resolve(gitCommonDir) ? "primary" : "linked";
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
-
|
|
42
|
+
const HOUR = 3_600_000;
|
|
43
|
+
|
|
44
|
+
/** A session id is a non-empty string; anything else is no session at all. */
|
|
45
|
+
export function sessionIdOf(value) {
|
|
46
|
+
return typeof value === "string" && value.trim() !== "" ? value.trim() : null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The lease clock, the one place its age and lapse are computed. A lease binds only while it is fresh,
|
|
51
|
+
* so an abandoned session cannot wedge a worktree; no holder, or a bad or future time, never binds.
|
|
52
|
+
*/
|
|
53
|
+
export function leaseState(lease, now, leaseHours) {
|
|
54
|
+
const holder = sessionIdOf(lease?.sessionId);
|
|
55
|
+
const written = Date.parse(lease?.updatedAt ?? "");
|
|
56
|
+
const age = now - written;
|
|
57
|
+
const lapsesAt = written + leaseHours * HOUR;
|
|
58
|
+
const live = holder !== null && age >= 0 && now <= lapsesAt;
|
|
59
|
+
return { holder, branch: lease?.branch ?? null, written, age, lapsesAt, live };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** @returns the lease state when another session holds the worktree, or null. */
|
|
43
63
|
export function leaseHeldByAnother(lease, sessionId, now, leaseHours) {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
64
|
+
const caller = sessionIdOf(sessionId);
|
|
65
|
+
const state = leaseState(lease, now, leaseHours);
|
|
66
|
+
if (!caller || !state.live || state.holder === caller) return null;
|
|
67
|
+
return state;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function duration(ms) {
|
|
71
|
+
const minutes = Math.floor(ms / 60_000);
|
|
72
|
+
if (minutes < 1) return `${Math.floor(ms / 1000)}s`;
|
|
73
|
+
const hours = Math.floor(minutes / 60);
|
|
74
|
+
return hours > 0 ? `${hours}h ${minutes % 60}m` : `${minutes}m`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export const timestamp = (ms) => new Date(ms).toISOString();
|
|
78
|
+
|
|
79
|
+
function heldRefusal(held, { branch, now, leaseFile, root, qc }) {
|
|
80
|
+
const at = `"${root}"`;
|
|
81
|
+
return (
|
|
82
|
+
`Another agent (session ${held.holder}) is already working in this worktree on ` +
|
|
83
|
+
`"${held.branch ?? branch}". Two agents on one branch lose each other's edits. ` +
|
|
84
|
+
`Take your own: \`git worktree add ../<slug> -b <branch>\`. ` +
|
|
85
|
+
`The lease is ${leaseFile}, written ${duration(held.age)} ago; it lapses at ` +
|
|
86
|
+
`${timestamp(held.lapsesAt)}, in ${duration(held.lapsesAt - now)}. See it: \`${qc} lease status ${at}\`. ` +
|
|
87
|
+
`Its holder releases it: \`${qc} lease release ${at} --session <id>\`. ` +
|
|
88
|
+
`Releasing another session's lease is a person's call: \`${qc} lease release ${at} --force\`.`
|
|
89
|
+
);
|
|
49
90
|
}
|
|
50
91
|
|
|
51
92
|
/**
|
|
@@ -73,14 +114,7 @@ export function isolationRefusal(state) {
|
|
|
73
114
|
);
|
|
74
115
|
}
|
|
75
116
|
const held = leaseHeldByAnother(lease, sessionId, now, settings.leaseHours);
|
|
76
|
-
|
|
77
|
-
return (
|
|
78
|
-
`Another agent (session ${held.sessionId.slice(0, 8)}) is already working in this worktree on ` +
|
|
79
|
-
`"${held.branch ?? branch}". Two agents on one branch lose each other's edits. ` +
|
|
80
|
-
`Take your own: \`git worktree add ../<slug> -b <branch>\`.`
|
|
81
|
-
);
|
|
82
|
-
}
|
|
83
|
-
return null;
|
|
117
|
+
return held ? heldRefusal(held, state) : null;
|
|
84
118
|
}
|
|
85
119
|
|
|
86
120
|
export function denyOutput(reason) {
|
|
@@ -4,13 +4,17 @@ import {
|
|
|
4
4
|
BRANCH,
|
|
5
5
|
OFF,
|
|
6
6
|
WORKTREE,
|
|
7
|
+
duration,
|
|
7
8
|
isolationRefusal,
|
|
8
9
|
isolationSettings,
|
|
9
10
|
leaseHeldByAnother,
|
|
11
|
+
leaseState,
|
|
12
|
+
sessionIdOf,
|
|
10
13
|
worktreeKind,
|
|
11
14
|
} from "./worktree-isolation.mjs";
|
|
12
15
|
|
|
13
16
|
const NOW = Date.parse("2026-09-20T12:00:00Z");
|
|
17
|
+
const LEASE_FILE = "/repo/.git/worktrees/tasks/qc-agent-lease.json";
|
|
14
18
|
const base = (overrides = {}) => ({
|
|
15
19
|
settings: isolationSettings({ isolation: { require: WORKTREE } }),
|
|
16
20
|
branch: "feat/tasks",
|
|
@@ -19,6 +23,9 @@ const base = (overrides = {}) => ({
|
|
|
19
23
|
lease: null,
|
|
20
24
|
sessionId: "session-aaaa",
|
|
21
25
|
now: NOW,
|
|
26
|
+
leaseFile: LEASE_FILE,
|
|
27
|
+
root: "/repo-tasks",
|
|
28
|
+
qc: "qc",
|
|
22
29
|
...overrides,
|
|
23
30
|
});
|
|
24
31
|
|
|
@@ -65,6 +72,56 @@ test("an abandoned lease expires, so a crashed session cannot wedge a worktree",
|
|
|
65
72
|
assert.equal(isolationRefusal(base({ lease: stale })), null);
|
|
66
73
|
});
|
|
67
74
|
|
|
75
|
+
test("the refusal of a held lease names the file, the holder, its age, its lapse, and both lease commands", () => {
|
|
76
|
+
const lease = { sessionId: "session-bbbb-0000-1111", branch: "feat/tasks", updatedAt: "2026-09-20T11:30:00Z" };
|
|
77
|
+
const reason = isolationRefusal(base({ lease }));
|
|
78
|
+
assert.ok(reason.includes(LEASE_FILE), reason);
|
|
79
|
+
assert.ok(reason.includes("session session-bbbb-0000-1111"), "the holder is named in full, so --session can match it");
|
|
80
|
+
assert.ok(reason.includes("30m ago"), reason);
|
|
81
|
+
assert.ok(reason.includes("lapses at 2026-09-20T19:30:00.000Z, in 7h 30m"), reason);
|
|
82
|
+
assert.ok(reason.includes('`qc lease status "/repo-tasks"`'), reason);
|
|
83
|
+
assert.ok(reason.includes('`qc lease release "/repo-tasks" --session <id>`'), reason);
|
|
84
|
+
assert.ok(reason.includes('`qc lease release "/repo-tasks" --force`'), reason);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test("a lease lapses leaseHours after its last write, and not before", () => {
|
|
88
|
+
const lease = { sessionId: "session-bbbb", branch: "feat/tasks", updatedAt: "2026-09-20T11:00:00Z" };
|
|
89
|
+
const fresh = leaseState(lease, NOW, 8);
|
|
90
|
+
assert.deepEqual(
|
|
91
|
+
{ holder: fresh.holder, branch: fresh.branch, age: fresh.age, lapsesAt: fresh.lapsesAt, live: fresh.live },
|
|
92
|
+
{ holder: "session-bbbb", branch: "feat/tasks", age: 3_600_000, lapsesAt: Date.parse("2026-09-20T19:00:00Z"), live: true },
|
|
93
|
+
);
|
|
94
|
+
assert.equal(leaseState(lease, NOW, 1).live, true, "a lease exactly leaseHours old still binds");
|
|
95
|
+
assert.equal(leaseState(lease, NOW + 1, 1).live, false);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test("a lease with no readable holder or time never binds, and never crashes the guard", () => {
|
|
99
|
+
const written = "2026-09-20T11:30:00Z";
|
|
100
|
+
for (const lease of [
|
|
101
|
+
{ sessionId: 123, updatedAt: written },
|
|
102
|
+
{ sessionId: " ", updatedAt: written },
|
|
103
|
+
{ sessionId: "session-bbbb", updatedAt: "yesterday-ish" },
|
|
104
|
+
{ sessionId: "session-bbbb", updatedAt: "2026-09-20T13:00:00Z" },
|
|
105
|
+
]) {
|
|
106
|
+
assert.equal(leaseState(lease, NOW, 8).live, false, JSON.stringify(lease));
|
|
107
|
+
assert.equal(isolationRefusal(base({ lease })), null, JSON.stringify(lease));
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
test("a blank or non-string session id is no session, so it neither holds nor is refused", () => {
|
|
112
|
+
assert.equal(sessionIdOf(" "), null);
|
|
113
|
+
assert.equal(sessionIdOf(42), null);
|
|
114
|
+
assert.equal(sessionIdOf(" session-aaaa "), "session-aaaa");
|
|
115
|
+
const lease = { sessionId: "session-bbbb", branch: "feat/tasks", updatedAt: "2026-09-20T11:30:00Z" };
|
|
116
|
+
assert.equal(isolationRefusal(base({ lease, sessionId: " " })), null);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test("a duration reads in whole hours and minutes, and seconds under a minute", () => {
|
|
120
|
+
assert.equal(duration(45_000), "45s");
|
|
121
|
+
assert.equal(duration(30 * 60_000 + 59_000), "30m");
|
|
122
|
+
assert.equal(duration(7 * 3_600_000 + 5 * 60_000), "7h 5m");
|
|
123
|
+
});
|
|
124
|
+
|
|
68
125
|
test("a detached HEAD is refused, but not mid-rebase when detaching is the point", () => {
|
|
69
126
|
assert.match(isolationRefusal(base({ branch: "" })), /HEAD is detached/);
|
|
70
127
|
assert.equal(isolationRefusal(base({ branch: "", inSpecialOperation: true })), null);
|
package/src/config.mjs
CHANGED
|
@@ -128,6 +128,12 @@ export const defaults = {
|
|
|
128
128
|
// Files that may only present, never orchestrate.
|
|
129
129
|
presenters: "frontend/src/features/*/trigger",
|
|
130
130
|
|
|
131
|
+
// Where the test-mirror gate looks. A test in `src` is misplaced; a test in `tests` mirrors a source
|
|
132
|
+
// file there, unless its root is `testOnly`: a package whose code is test support.
|
|
133
|
+
testMirror: {
|
|
134
|
+
roots: [{ src: "frontend/src", tests: "frontend/tests" }],
|
|
135
|
+
},
|
|
136
|
+
|
|
131
137
|
// A workflow is headless-first: declared by one of these, and proven by a test that
|
|
132
138
|
// imports none of the view modules. docs/architecture.md.
|
|
133
139
|
saga: {
|
|
@@ -138,6 +144,31 @@ export const defaults = {
|
|
|
138
144
|
headlessBlock: "pipeline",
|
|
139
145
|
},
|
|
140
146
|
|
|
147
|
+
// A feature is reachable over its routes and from a command line. `cli` names the second
|
|
148
|
+
// entrypoint: the block that drives the same pipeline with no server, which is what makes a
|
|
149
|
+
// feature runnable by a test, a script or a person. `qc run <feature>.<command>` dispatches it
|
|
150
|
+
// through the registry a repository's codegen writes to `registry`.
|
|
151
|
+
cli: {
|
|
152
|
+
block: "cli",
|
|
153
|
+
// Which feature roots must carry one. Empty means every root the structure gate walks.
|
|
154
|
+
roots: [],
|
|
155
|
+
viewModules: ["react", "react-dom"],
|
|
156
|
+
serverModules: ["fastify", "express", "koa", "@nestjs/core"],
|
|
157
|
+
factory: ["defineCommands"],
|
|
158
|
+
// The key a command entry names its workflow with. The gate's real check is that this table
|
|
159
|
+
// and the feature's declared sagas agree both ways, so the name has to be readable statically.
|
|
160
|
+
drives: "saga",
|
|
161
|
+
// Read with saga-tests' own factories by default: both gates must see the same declarations.
|
|
162
|
+
sagaFactories: ["definePipeline", "defineSaga"],
|
|
163
|
+
// Only the publishing block crosses a feature boundary, so the registry reaches commands through it.
|
|
164
|
+
publisher: "index",
|
|
165
|
+
// The composed registry `qc run` imports. A repository writes it; the harness only dispatches.
|
|
166
|
+
registry: "backend/src/features/commands.generated.ts",
|
|
167
|
+
// `node --import` specifiers the registry needs. A TypeScript registry is run under the
|
|
168
|
+
// repository's own loader, so the harness never depends on one.
|
|
169
|
+
loader: ["tsx"],
|
|
170
|
+
},
|
|
171
|
+
|
|
141
172
|
// English is the one language in every set. Another language is data, not prose: it lives in a
|
|
142
173
|
// declared path beside its English variant. `scripts` names the ranges a gate looks for.
|
|
143
174
|
language: {
|
|
@@ -205,6 +236,8 @@ export const defaults = {
|
|
|
205
236
|
// Bounded vertical slices.
|
|
206
237
|
slice: {
|
|
207
238
|
required: ["index.ts", "schema.ts", "trigger.ts"],
|
|
239
|
+
// Allowed at the root without being owed: `cli` is the headless entrypoint feature-cli reads.
|
|
240
|
+
optional: ["cli.ts"],
|
|
208
241
|
sliceDir: "slices",
|
|
209
242
|
sharedDir: "shared",
|
|
210
243
|
sharedFiles: ["types.ts", "queries.ts", "guards.ts", "runner.ts", "components.ts"],
|
|
@@ -241,6 +274,7 @@ export const defaults = {
|
|
|
241
274
|
"config-floor": false,
|
|
242
275
|
"english-source": false,
|
|
243
276
|
"adr-format": false,
|
|
277
|
+
"feature-cli": false,
|
|
244
278
|
},
|
|
245
279
|
|
|
246
280
|
// Gates that produce rather than inspect: a repository's codegen imports these and
|
package/src/descriptions.mjs
CHANGED
|
@@ -11,10 +11,11 @@ export const gateDescriptions = Object.freeze({
|
|
|
11
11
|
"internal-routes": "Every path a worker posts to is a route the api serves",
|
|
12
12
|
"headless-sagas": "The block that carries a workflow runs without a view layer",
|
|
13
13
|
"saga-tests": "Every workflow is named by a test that imports no view module",
|
|
14
|
+
"feature-cli": "Every feature is drivable headless through a published command block, with no server",
|
|
14
15
|
"gate-tests": "A repository's own gates each ship a case that must fail",
|
|
15
16
|
"audit-append-only": "The audit log has no update or delete path in any repository",
|
|
16
17
|
"frontend-boundaries": "Platform remains a thin substrate and never holds feature domain logic or junk drawer directories",
|
|
17
|
-
"test-mirror": "
|
|
18
|
+
"test-mirror": "Tests mirror src paths 1:1 in every configured root, and no test is orphaned without a source file",
|
|
18
19
|
"enforcement-map": "Every rule names a check, and every check the kit runs is named",
|
|
19
20
|
"config-floor": "A check the kit ships on is switched off only by naming the decision that says why",
|
|
20
21
|
"english-source": "Comments, docs and rules are English; another language is data, declared beside its English variant",
|
|
@@ -18,6 +18,9 @@ export const BLOCKS = Object.freeze([
|
|
|
18
18
|
export const REQUIRED_BLOCKS = Object.freeze(["index", "trigger", "pipeline", "resource"]);
|
|
19
19
|
|
|
20
20
|
export const SLICE_REQUIRED_ROOTS = Object.freeze(["index", "trigger", "schema"]);
|
|
21
|
+
// Allowed at a slice's root without being owed: a feature declaring none is complete, one
|
|
22
|
+
// declaring it is not carrying an unknown block. `cli` is the headless entrypoint feature-cli reads.
|
|
23
|
+
export const SLICE_OPTIONAL_ROOTS = Object.freeze(["cli"]);
|
|
21
24
|
export const ALLOWED_SUBDIRS = Object.freeze(["slices", "shared", "components"]);
|
|
22
25
|
export const ALLOWED_SHARED_FILES = Object.freeze(["types", "queries", "guards", "runner", "components"]);
|
|
23
26
|
|
|
@@ -35,6 +38,7 @@ function anatomyOf(options = {}) {
|
|
|
35
38
|
const block = options.block ?? {};
|
|
36
39
|
return {
|
|
37
40
|
sliceRequired: stems(slice.required ?? SLICE_REQUIRED_ROOTS),
|
|
41
|
+
sliceOptional: stems(slice.optional ?? SLICE_OPTIONAL_ROOTS),
|
|
38
42
|
sliceDir: slice.sliceDir ?? "slices",
|
|
39
43
|
sharedDir: slice.sharedDir ?? "shared",
|
|
40
44
|
componentsDir: slice.componentsDir ?? "components",
|
|
@@ -117,7 +121,7 @@ function checkSliceFeature(feature, files, anatomy) {
|
|
|
117
121
|
}
|
|
118
122
|
if (file.endsWith(TEST_SUFFIX) || file.endsWith(TEST_SUFFIX_TSX)) continue;
|
|
119
123
|
const name = file.replace(/\.tsx?$/, "");
|
|
120
|
-
if (!anatomy.sliceRequired.includes(name)) {
|
|
124
|
+
if (!anatomy.sliceRequired.includes(name) && !anatomy.sliceOptional.includes(name)) {
|
|
121
125
|
problems.push({ feature, rule: "unknown-block", detail: file });
|
|
122
126
|
continue;
|
|
123
127
|
}
|
|
@@ -357,3 +357,24 @@ test("a slice feature with deeply nested components (> depth 3) fails", () => {
|
|
|
357
357
|
assert.equal(problems[0].detail, "components/a/b/c.tsx");
|
|
358
358
|
});
|
|
359
359
|
|
|
360
|
+
|
|
361
|
+
test("a cli block at a slice's root is allowed without being owed", () => {
|
|
362
|
+
const feature = [{ feature: "backend/src/features/progress", files: ["index.ts", "trigger.ts", "schema.ts", "cli.ts", "slices/entries.ts"] }];
|
|
363
|
+
assert.deepEqual(checkFeatureAnatomy(feature), []);
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
test("a feature carrying no cli block is still a complete slice", () => {
|
|
367
|
+
const feature = [{ feature: "backend/src/features/progress", files: ["index.ts", "trigger.ts", "schema.ts", "slices/entries.ts"] }];
|
|
368
|
+
assert.deepEqual(checkFeatureAnatomy(feature), []);
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
test("a root block that is neither required nor optional is still unknown", () => {
|
|
372
|
+
const feature = [{ feature: "backend/src/features/progress", files: ["index.ts", "trigger.ts", "schema.ts", "helpers.ts", "slices/entries.ts"] }];
|
|
373
|
+
const problems = checkFeatureAnatomy(feature);
|
|
374
|
+
assert.deepEqual(problems.map((problem) => problem.rule), ["unknown-block"]);
|
|
375
|
+
});
|
|
376
|
+
|
|
377
|
+
test("the optional roots come from config, so a repository may name its own", () => {
|
|
378
|
+
const feature = [{ feature: "a/features/pins", files: ["index.ts", "trigger.ts", "schema.ts", "command.ts", "slices/x.ts"] }];
|
|
379
|
+
assert.deepEqual(checkFeatureAnatomy(feature, { slice: { optional: ["command"] } }), []);
|
|
380
|
+
});
|