architecture-harness 0.4.2 → 0.5.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "architecture-harness",
3
- "version": "0.4.2",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
6
6
  "license": "MIT",
package/src/cli/check.mjs CHANGED
@@ -17,6 +17,7 @@ import { checkClaimedRequirements } from "../gates/claimed-requirements.mjs";
17
17
  import { allowedPublicRoutes, checkPublicRoutes, declaredPublicRoutes } from "../gates/public-routes.mjs";
18
18
  import { calledInternalRoutes, checkInternalRoutes, declaredInternalRoutes } from "../gates/internal-routes.mjs";
19
19
  import { checkHeadlessPipelines } from "../gates/headless-sagas.mjs";
20
+ import { checkFeatureCommands, governedFeatures } from "../gates/feature-cli.mjs";
20
21
  import { checkSagaTests, declaredSagas } from "../gates/saga-tests.mjs";
21
22
  import { checkGatesAreTested } from "../gates/gate-tests.mjs";
22
23
  import { checkAuditAppendOnly } from "../gates/audit-append-only.mjs";
@@ -381,6 +382,25 @@ export async function runCheck(config, only) {
381
382
  if (enabled(config.gates, "headless-sagas")) {
382
383
  problems.push(...checkHeadlessPipelines(contents, { block: config.saga.headlessBlock, viewModules: config.saga.viewModules }));
383
384
  }
385
+ if (enabled(config.gates, "feature-cli") && !relativeOnly) {
386
+ const rel = relativeTo(config.root);
387
+ const relativeFeatures = features.map((feature) => ({ ...feature, feature: rel(feature.feature) }));
388
+ const relativeContents = contents.map((file) => ({ ...file, path: rel(file.path) }));
389
+ problems.push(
390
+ ...checkFeatureCommands(relativeFeatures, relativeContents, {
391
+ block: config.cli.block,
392
+ roots: config.cli.roots,
393
+ viewModules: config.cli.viewModules,
394
+ serverModules: config.cli.serverModules,
395
+ factory: config.cli.factory,
396
+ publisher: config.cli.publisher,
397
+ drives: config.cli.drives,
398
+ sagaFactories: config.cli.sagaFactories,
399
+ tests: relativeContents.filter((file) => TEST_FILE.test(file.path)),
400
+ }),
401
+ );
402
+ lines.push(`OK commands ${governedFeatures(relativeFeatures, { roots: config.cli.roots })} feature(s) drivable headless through \`qc run\``);
403
+ }
384
404
  if (!rootless) lines.push(`OK structure ${features.length} feature folder(s)`);
385
405
 
386
406
  if (relativeOnly) return { problems, lines };
package/src/cli/qc.mjs CHANGED
@@ -10,6 +10,7 @@ const USAGE = `qc — architecture gates
10
10
  qc check [file] every structural gate; one file is the fast path a hook takes
11
11
  qc init scaffold the docs, config, hooks and workflow into this repository
12
12
  qc feature <name> scaffold a feature in the configured anatomy
13
+ qc run [name] drive one feature command headless; no name lists them
13
14
  qc install-hooks point git at the kit's pre-commit hook
14
15
  qc work-order-check refuse to commit on the wrong branch, per .claude/work-order.local.json
15
16
  qc commit-msg <file> refuse a commit message that credits a tool as an author
@@ -47,6 +48,10 @@ async function main() {
47
48
  await runScaffold(config, rest);
48
49
  return;
49
50
  }
51
+ case "run": {
52
+ const { runRun } = await import("./run.mjs");
53
+ process.exit(await runRun(config, rest));
54
+ }
50
55
  case "install-hooks": {
51
56
  const { installHooks } = await import("./install-hooks.mjs");
52
57
  await installHooks(config);
@@ -0,0 +1,52 @@
1
+ // Runs inside the repository's loader, so it may import a TypeScript registry. Kept separate from
2
+ // run.mjs for exactly that reason: the parent process must not need the loader to decide anything.
3
+
4
+ import process from "node:process";
5
+ import { pathToFileURL } from "node:url";
6
+ import { parseInput } from "./run.mjs";
7
+
8
+ /** Every command the registry publishes, sorted, one per line — what `qc run` with no name prints. */
9
+ export function listing(commands) {
10
+ return Object.keys(commands)
11
+ .sort()
12
+ .map((key) => {
13
+ const describe = commands[key]?.describe;
14
+ return describe === undefined ? ` ${key}` : ` ${key.padEnd(38)}${describe}`;
15
+ });
16
+ }
17
+
18
+ export async function dispatch(registry, name, argv) {
19
+ const module = await import(pathToFileURL(registry).href);
20
+ const commands = module.commands ?? module.default;
21
+ if (commands === undefined || typeof commands !== "object") {
22
+ console.error(`qc run: ${registry} exports no \`commands\` record`);
23
+ return 1;
24
+ }
25
+
26
+ if (name === undefined) {
27
+ console.log("qc run <feature>.<command> [--json '<payload>'] [--key value]\n");
28
+ for (const line of listing(commands)) console.log(line);
29
+ return 0;
30
+ }
31
+
32
+ const command = commands[name];
33
+ if (command === undefined) {
34
+ console.error(`qc run: no command \`${name}\`. Known commands:\n${listing(commands).join("\n")}`);
35
+ return 1;
36
+ }
37
+
38
+ const result = await command.run(parseInput(argv));
39
+ if (result !== undefined) console.log(JSON.stringify(result, null, 2));
40
+ return 0;
41
+ }
42
+
43
+ // Spawned by run.mjs under the repository's loader: argv is [registry, name?, ...rest].
44
+ if (process.argv[1] === new URL(import.meta.url).pathname) {
45
+ const [registry, name, ...rest] = process.argv.slice(2);
46
+ try {
47
+ process.exit(await dispatch(registry, name, rest));
48
+ } catch (cause) {
49
+ console.error(`qc run: ${cause instanceof Error ? cause.message : String(cause)}`);
50
+ process.exit(1);
51
+ }
52
+ }
@@ -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
+ });
package/src/config.mjs CHANGED
@@ -138,6 +138,31 @@ export const defaults = {
138
138
  headlessBlock: "pipeline",
139
139
  },
140
140
 
141
+ // A feature is reachable over its routes and from a command line. `cli` names the second
142
+ // entrypoint: the block that drives the same pipeline with no server, which is what makes a
143
+ // feature runnable by a test, a script or a person. `qc run <feature>.<command>` dispatches it
144
+ // through the registry a repository's codegen writes to `registry`.
145
+ cli: {
146
+ block: "cli",
147
+ // Which feature roots must carry one. Empty means every root the structure gate walks.
148
+ roots: [],
149
+ viewModules: ["react", "react-dom"],
150
+ serverModules: ["fastify", "express", "koa", "@nestjs/core"],
151
+ factory: ["defineCommands"],
152
+ // The key a command entry names its workflow with. The gate's real check is that this table
153
+ // and the feature's declared sagas agree both ways, so the name has to be readable statically.
154
+ drives: "saga",
155
+ // Read with saga-tests' own factories by default: both gates must see the same declarations.
156
+ sagaFactories: ["definePipeline", "defineSaga"],
157
+ // Only the publishing block crosses a feature boundary, so the registry reaches commands through it.
158
+ publisher: "index",
159
+ // The composed registry `qc run` imports. A repository writes it; the harness only dispatches.
160
+ registry: "backend/src/features/commands.generated.ts",
161
+ // `node --import` specifiers the registry needs. A TypeScript registry is run under the
162
+ // repository's own loader, so the harness never depends on one.
163
+ loader: ["tsx"],
164
+ },
165
+
141
166
  // English is the one language in every set. Another language is data, not prose: it lives in a
142
167
  // declared path beside its English variant. `scripts` names the ranges a gate looks for.
143
168
  language: {
@@ -205,6 +230,8 @@ export const defaults = {
205
230
  // Bounded vertical slices.
206
231
  slice: {
207
232
  required: ["index.ts", "schema.ts", "trigger.ts"],
233
+ // Allowed at the root without being owed: `cli` is the headless entrypoint feature-cli reads.
234
+ optional: ["cli.ts"],
208
235
  sliceDir: "slices",
209
236
  sharedDir: "shared",
210
237
  sharedFiles: ["types.ts", "queries.ts", "guards.ts", "runner.ts", "components.ts"],
@@ -241,6 +268,7 @@ export const defaults = {
241
268
  "config-floor": false,
242
269
  "english-source": false,
243
270
  "adr-format": false,
271
+ "feature-cli": false,
244
272
  },
245
273
 
246
274
  // Gates that produce rather than inspect: a repository's codegen imports these and
@@ -11,6 +11,7 @@ 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",
@@ -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
+ });
@@ -0,0 +1,198 @@
1
+ // A feature is reachable two ways, and only one of them is usually built. Routes need a server,
2
+ // a session and a client; that is the path a person exercises by hand and a suite mocks away.
3
+ // This names the second one: a command block that drives the same pipeline with no server at all,
4
+ // so a test, a script or a person can run the feature and see what it really does.
5
+ //
6
+ // headless-sagas proves a pipeline *could* run without a view. This proves something *does*.
7
+ //
8
+ // The check that carries the gate is agreement, not existence: every saga a feature declares is
9
+ // named by a command, and every command names a saga the feature declares. A gate asserting only
10
+ // that an entrypoint file exists passes on day one and never fails again; this one fails every
11
+ // time a workflow is added and left undrivable -- the shape public-routes and internal-routes use.
12
+ //
13
+ // Off by default in the shipped config: a repository names its own command block and the roots
14
+ // that carry one, or the gate would red every tree the moment it upgraded the harness.
15
+
16
+ import { declaredSagas } from "./saga-tests.mjs";
17
+
18
+ const DEFAULT_BLOCK = "cli";
19
+ const DEFAULT_VIEW_MODULES = ["react", "react-dom"];
20
+ const DEFAULT_SERVER_MODULES = ["fastify", "express", "koa", "@nestjs/core"];
21
+ const DEFAULT_FACTORY = "defineCommands";
22
+ const DEFAULT_PUBLISHER = "index";
23
+ // What a command entry names as the workflow it drives. One key, so the table stays readable.
24
+ const DEFAULT_DRIVES = "saga";
25
+ // Kept beside saga-tests' own default: the two gates must read the same declarations.
26
+ const DEFAULT_SAGA_FACTORIES = ["definePipeline", "defineSaga"];
27
+
28
+ function escape(text) {
29
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
30
+ }
31
+
32
+ // An empty list would silently match nothing, disabling the check instead of failing it.
33
+ function names(value, label) {
34
+ const list = [value].flat();
35
+ if (list.length === 0 || list.some((name) => typeof name !== "string" || name === "")) {
36
+ throw new Error(`cli.${label} must be a name or a non-empty list of them, got ${JSON.stringify(value)}`);
37
+ }
38
+ return list;
39
+ }
40
+
41
+ function blockPattern(block) {
42
+ return new RegExp(`(?:^|/)${escape(block)}\\.[cm]?[jt]sx?$`);
43
+ }
44
+
45
+ function importPattern(modules) {
46
+ return new RegExp(`\\bfrom\\s+["'](?:${modules.map(escape).join("|")})["']`);
47
+ }
48
+
49
+ /** Every feature directory the roots cover, with the block file it carries and that file's text. */
50
+ function blocksOf(features, contents, block, roots) {
51
+ const matches = blockPattern(block);
52
+ const byPath = new Map(contents.map((file) => [file.path, file.contents]));
53
+ const found = [];
54
+ for (const { feature, files } of features) {
55
+ if (roots.length > 0 && !roots.some((root) => feature.includes(root))) continue;
56
+ const file = files.find((name) => matches.test(name));
57
+ found.push({
58
+ feature,
59
+ files,
60
+ path: file === undefined ? undefined : `${feature}/${file}`,
61
+ contents: file === undefined ? undefined : (byPath.get(`${feature}/${file}`) ?? ""),
62
+ });
63
+ }
64
+ return found;
65
+ }
66
+
67
+
68
+ /** Every workflow the command table names, read from the `drives` key of each entry. */
69
+ export function commandedSagas(contents, options = {}) {
70
+ const factories = names(options.factory ?? DEFAULT_FACTORY, "factory");
71
+ const drives = options.drives ?? DEFAULT_DRIVES;
72
+ const table = new RegExp(`\\b(?:${factories.map(escape).join("|")})\\s*[<(]`);
73
+ const opens = table.exec(contents);
74
+ if (opens === null) return [];
75
+ const body = contents.slice(opens.index);
76
+ const entry = new RegExp(`\\b${escape(drives)}\\s*:\\s*([A-Za-z_$][\\w$]*)`, "g");
77
+ const found = [];
78
+ for (const hit of body.matchAll(entry)) found.push(hit[1]);
79
+ return found;
80
+ }
81
+
82
+ /**
83
+ * @param {{feature: string, files: string[]}[]} features Feature folders, relative to the root.
84
+ * @param {{path: string, contents: string}[]} contents Every source file, relative to the root.
85
+ * @param {{block?: string, roots?: string[], viewModules?: string[], serverModules?: string[], factory?: string | string[], publisher?: string, tests?: {path: string, contents: string}[]}} [options]
86
+ * @returns {{path?: string, feature?: string, rule: string, detail: string}[]}
87
+ */
88
+ export function checkFeatureCommands(features, contents, options = {}) {
89
+ return check(features, contents, options).problems;
90
+ }
91
+
92
+ /** The problems, and how many features the roots actually cover — a summary line must not overcount. */
93
+ export function governedFeatures(features, options = {}) {
94
+ const roots = options.roots ?? [];
95
+ return features.filter((feature) => roots.length === 0 || roots.some((root) => feature.feature.includes(root))).length;
96
+ }
97
+
98
+ function check(features, contents, options) {
99
+ const block = names(options.block ?? DEFAULT_BLOCK, "block")[0];
100
+ const roots = options.roots ?? [];
101
+ const viewModules = options.viewModules ?? DEFAULT_VIEW_MODULES;
102
+ const serverModules = options.serverModules ?? DEFAULT_SERVER_MODULES;
103
+ const factories = names(options.factory ?? DEFAULT_FACTORY, "factory");
104
+ const publisher = options.publisher ?? DEFAULT_PUBLISHER;
105
+ const tests = options.tests ?? [];
106
+ const drives = options.drives ?? DEFAULT_DRIVES;
107
+ const sagaFactories = names(options.sagaFactories ?? DEFAULT_SAGA_FACTORIES, "sagaFactories");
108
+
109
+ const view = importPattern(viewModules);
110
+ const server = importPattern(serverModules);
111
+ const declares = new RegExp(`\\b(?:${factories.map(escape).join("|")})\\s*[<(]`);
112
+ const publishes = new RegExp(`\\bfrom\\s+["']\\.\\/${escape(block)}\\.(?:[cm]?[jt]sx?)["']`);
113
+
114
+ const problems = [];
115
+ const governed = blocksOf(features, contents, block, roots);
116
+ for (const found of governed) {
117
+ if (found.path === undefined) {
118
+ problems.push({
119
+ feature: found.feature,
120
+ rule: "feature-cli-missing",
121
+ detail: `${found.feature} declares no ${block} block: a feature that can only be driven over its routes cannot be run without a server`,
122
+ });
123
+ continue;
124
+ }
125
+ if (view.test(found.contents)) {
126
+ problems.push({
127
+ path: found.path,
128
+ rule: "feature-cli-no-view",
129
+ detail: `${block} is the headless entrypoint and cannot import ${viewModules.join(" or ")}`,
130
+ });
131
+ }
132
+ if (server.test(found.contents)) {
133
+ problems.push({
134
+ path: found.path,
135
+ rule: "feature-cli-no-server",
136
+ detail: `${block} drives the pipeline directly and cannot import ${serverModules.join(" or ")} — a command that needs a running server is a route, not a command`,
137
+ });
138
+ }
139
+ if (!declares.test(found.contents)) {
140
+ problems.push({
141
+ path: found.path,
142
+ rule: "feature-cli-undeclared",
143
+ detail: `${block} declares no command through ${factories.join(" or ")}, so nothing can dispatch it`,
144
+ });
145
+ }
146
+ const index = `${found.feature}/${publisher}`;
147
+ const republished = contents.find((file) => file.path.replace(/\.[cm]?[jt]sx?$/, "") === index);
148
+ if (republished === undefined || !publishes.test(republished.contents)) {
149
+ problems.push({
150
+ path: found.path,
151
+ rule: "feature-cli-unpublished",
152
+ detail: `${publisher} does not re-export ${block}: only ${publisher} crosses a feature boundary, so the registry cannot reach these commands`,
153
+ });
154
+ }
155
+ // The command block is the test seam. A block nothing imports is a claim, exactly as an
156
+ // untested saga is -- saga-tests makes the same demand of a workflow.
157
+ const named = tests.some((file) => publishes.test(file.contents) && file.path.startsWith(`${found.feature}/`));
158
+ if (tests.length > 0 && !named) {
159
+ problems.push({
160
+ path: found.path,
161
+ rule: "feature-cli-untested",
162
+ detail: `no test under ${found.feature} imports ${block}: the command block is what makes the feature testable without a server, and nothing runs it`,
163
+ });
164
+ }
165
+
166
+ // The gate's real work: the dispatch table and the feature's declared workflows agree, both
167
+ // ways. Existence alone would pass forever; this fails the next time a saga is added.
168
+ const owned = found.files
169
+ .filter((file) => /\.[cm]?tsx?$/.test(file) && !/\.test\.[cm]?tsx?$/.test(file))
170
+ .map((file) => `${found.feature}/${file}`);
171
+ const declared = new Set(
172
+ declaredSagas(
173
+ contents.filter((file) => owned.includes(file.path)),
174
+ { factories: sagaFactories },
175
+ ).map((saga) => saga.name),
176
+ );
177
+ const commanded = new Set(commandedSagas(found.contents, { factory: factories, drives }));
178
+ for (const saga of declared) {
179
+ if (!commanded.has(saga)) {
180
+ problems.push({
181
+ path: found.path,
182
+ rule: "feature-cli-undrivable-saga",
183
+ detail: `${saga} is declared in ${found.feature} but no command drives it: a workflow reachable only over a route cannot be run without a server`,
184
+ });
185
+ }
186
+ }
187
+ for (const saga of commanded) {
188
+ if (!declared.has(saga)) {
189
+ problems.push({
190
+ path: found.path,
191
+ rule: "feature-cli-unknown-saga",
192
+ detail: `a command names ${saga}, which ${found.feature} does not declare through ${sagaFactories.join(" or ")}`,
193
+ });
194
+ }
195
+ }
196
+ }
197
+ return { problems, governed: governed.length };
198
+ }
@@ -0,0 +1,172 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { checkFeatureCommands, governedFeatures } from "./feature-cli.mjs";
4
+
5
+ const FEATURE = "backend/src/features/progress";
6
+
7
+ function tree({ cli, index, test: testFile } = {}) {
8
+ const files = [];
9
+ if (cli !== undefined) files.push({ path: `${FEATURE}/cli.ts`, contents: cli });
10
+ if (index !== undefined) files.push({ path: `${FEATURE}/index.ts`, contents: index });
11
+ if (testFile !== undefined) files.push({ path: `${FEATURE}/cli.test.ts`, contents: testFile });
12
+ return files;
13
+ }
14
+
15
+ const GOOD_CLI = 'import { defineCommands } from "@qc/kernel";\nexport const commands = defineCommands("progress", {});';
16
+ const SAGA = 'export const createEntry = definePipeline({});';
17
+ const GOOD_INDEX = 'export { commands } from "./cli.js";';
18
+ const GOOD_TEST = 'import { commands } from "./cli.js";';
19
+
20
+ function features(files) {
21
+ return [{ feature: FEATURE, files: files.map((file) => file.path.slice(FEATURE.length + 1)) }];
22
+ }
23
+
24
+ test("a feature with a declared, published, tested command block passes", () => {
25
+ const files = tree({ cli: GOOD_CLI, index: GOOD_INDEX, test: GOOD_TEST });
26
+ assert.deepEqual(checkFeatureCommands(features(files), files, { tests: [files[2]] }), []);
27
+ });
28
+
29
+ test("a feature carrying no cli block fails and names feature-cli-missing", () => {
30
+ const files = tree({ index: GOOD_INDEX });
31
+ const problems = checkFeatureCommands(features(files), files);
32
+ assert.equal(problems.length, 1);
33
+ assert.equal(problems[0].rule, "feature-cli-missing");
34
+ assert.equal(problems[0].feature, FEATURE);
35
+ });
36
+
37
+ test("a cli block importing react fails and names feature-cli-no-view", () => {
38
+ const files = tree({ cli: `import * as React from "react";\n${GOOD_CLI}`, index: GOOD_INDEX });
39
+ const problems = checkFeatureCommands(features(files), files);
40
+ assert.deepEqual(problems.map((problem) => problem.rule), ["feature-cli-no-view"]);
41
+ });
42
+
43
+ test("a cli block importing a server framework fails and names feature-cli-no-server", () => {
44
+ const files = tree({ cli: `import Fastify from "fastify";\n${GOOD_CLI}`, index: GOOD_INDEX });
45
+ const problems = checkFeatureCommands(features(files), files);
46
+ assert.deepEqual(problems.map((problem) => problem.rule), ["feature-cli-no-server"]);
47
+ });
48
+
49
+ test("a cli block declaring no command through the factory fails", () => {
50
+ const files = tree({ cli: "export const commands = {};", index: GOOD_INDEX });
51
+ const problems = checkFeatureCommands(features(files), files);
52
+ assert.deepEqual(problems.map((problem) => problem.rule), ["feature-cli-undeclared"]);
53
+ });
54
+
55
+ test("a cli block the index does not re-export fails and names feature-cli-unpublished", () => {
56
+ const files = tree({ cli: GOOD_CLI, index: 'export { trigger } from "./trigger.js";' });
57
+ const problems = checkFeatureCommands(features(files), files);
58
+ assert.deepEqual(problems.map((problem) => problem.rule), ["feature-cli-unpublished"]);
59
+ });
60
+
61
+ test("a feature with no index at all fails as unpublished rather than throwing", () => {
62
+ const files = tree({ cli: GOOD_CLI });
63
+ const problems = checkFeatureCommands(features(files), files);
64
+ assert.deepEqual(problems.map((problem) => problem.rule), ["feature-cli-unpublished"]);
65
+ });
66
+
67
+ test("a command block no test imports fails and names feature-cli-untested", () => {
68
+ const files = tree({ cli: GOOD_CLI, index: GOOD_INDEX });
69
+ const elsewhere = { path: "backend/src/features/photos/cli.test.ts", contents: GOOD_TEST };
70
+ const problems = checkFeatureCommands(features(files), files, { tests: [elsewhere] });
71
+ assert.deepEqual(problems.map((problem) => problem.rule), ["feature-cli-untested"]);
72
+ });
73
+
74
+ test("a feature outside the configured roots is not asked for a command block", () => {
75
+ const files = tree({ index: GOOD_INDEX });
76
+ assert.deepEqual(checkFeatureCommands(features(files), files, { roots: ["frontend/src/features"] }), []);
77
+ });
78
+
79
+ test("the block name, the factory and the publisher come from options", () => {
80
+ const feature = "api/features/pins";
81
+ const files = [
82
+ { path: `${feature}/command.ts`, contents: 'export const run = defineTasks("pins", {});' },
83
+ { path: `${feature}/barrel.ts`, contents: 'export { run } from "./command.js";' },
84
+ ];
85
+ const found = [{ feature, files: ["command.ts", "barrel.ts"] }];
86
+ const options = { block: "command", factory: "defineTasks", publisher: "barrel" };
87
+ assert.deepEqual(checkFeatureCommands(found, files, options), []);
88
+ });
89
+
90
+ test("an empty block name fails loudly rather than matching nothing", () => {
91
+ assert.throws(() => checkFeatureCommands([], [], { block: "" }), /cli\.block/);
92
+ });
93
+
94
+ test("an empty factory list fails loudly rather than matching nothing", () => {
95
+ assert.throws(() => checkFeatureCommands([], [], { factory: [] }), /cli\.factory/);
96
+ });
97
+
98
+ test("a saga the command table does not drive fails and names feature-cli-undrivable-saga", () => {
99
+ const files = [
100
+ { path: `${FEATURE}/cli.ts`, contents: GOOD_CLI },
101
+ { path: `${FEATURE}/index.ts`, contents: GOOD_INDEX },
102
+ { path: `${FEATURE}/slices/create-entry.ts`, contents: SAGA },
103
+ ];
104
+ const found = [{ feature: FEATURE, files: ["cli.ts", "index.ts", "slices/create-entry.ts"] }];
105
+ const problems = checkFeatureCommands(found, files, {});
106
+ assert.deepEqual(problems.map((problem) => problem.rule), ["feature-cli-undrivable-saga"]);
107
+ assert.match(problems[0].detail, /createEntry/);
108
+ });
109
+
110
+ test("a command table driving every declared saga passes", () => {
111
+ const cli = 'export const commands = defineCommands("progress", { "create-entry": { saga: createEntry } });';
112
+ const files = [
113
+ { path: `${FEATURE}/cli.ts`, contents: cli },
114
+ { path: `${FEATURE}/index.ts`, contents: GOOD_INDEX },
115
+ { path: `${FEATURE}/slices/create-entry.ts`, contents: SAGA },
116
+ ];
117
+ const found = [{ feature: FEATURE, files: ["cli.ts", "index.ts", "slices/create-entry.ts"] }];
118
+ assert.deepEqual(checkFeatureCommands(found, files, {}), []);
119
+ });
120
+
121
+ test("a command naming a saga the feature does not declare fails", () => {
122
+ const cli = 'export const commands = defineCommands("progress", { "nope": { saga: notHere } });';
123
+ const files = [
124
+ { path: `${FEATURE}/cli.ts`, contents: cli },
125
+ { path: `${FEATURE}/index.ts`, contents: GOOD_INDEX },
126
+ ];
127
+ const found = [{ feature: FEATURE, files: ["cli.ts", "index.ts"] }];
128
+ const problems = checkFeatureCommands(found, files, {});
129
+ assert.deepEqual(problems.map((problem) => problem.rule), ["feature-cli-unknown-saga"]);
130
+ assert.match(problems[0].detail, /notHere/);
131
+ });
132
+
133
+ test("a saga declared in a sibling feature is not the one this command table owes", () => {
134
+ const cli = 'export const commands = defineCommands("progress", {});';
135
+ const files = [
136
+ { path: `${FEATURE}/cli.ts`, contents: cli },
137
+ { path: `${FEATURE}/index.ts`, contents: GOOD_INDEX },
138
+ { path: "backend/src/features/photos/slices/upload.ts", contents: "export const upload = definePipeline({});" },
139
+ ];
140
+ const found = [{ feature: FEATURE, files: ["cli.ts", "index.ts"] }];
141
+ assert.deepEqual(checkFeatureCommands(found, files, {}), []);
142
+ });
143
+
144
+ test("a saga declared only in a test file is not owed a command", () => {
145
+ const files = [
146
+ { path: `${FEATURE}/cli.ts`, contents: GOOD_CLI },
147
+ { path: `${FEATURE}/index.ts`, contents: GOOD_INDEX },
148
+ { path: `${FEATURE}/pipeline.test.ts`, contents: SAGA },
149
+ ];
150
+ const found = [{ feature: FEATURE, files: ["cli.ts", "index.ts", "pipeline.test.ts"] }];
151
+ assert.deepEqual(checkFeatureCommands(found, files, {}), []);
152
+ });
153
+
154
+ test("the key a command entry names its workflow with comes from options", () => {
155
+ const cli = 'export const commands = defineCommands("progress", { "create-entry": { runs: createEntry } });';
156
+ const files = [
157
+ { path: `${FEATURE}/cli.ts`, contents: cli },
158
+ { path: `${FEATURE}/index.ts`, contents: GOOD_INDEX },
159
+ { path: `${FEATURE}/slices/create-entry.ts`, contents: SAGA },
160
+ ];
161
+ const found = [{ feature: FEATURE, files: ["cli.ts", "index.ts", "slices/create-entry.ts"] }];
162
+ assert.deepEqual(checkFeatureCommands(found, files, { drives: "runs" }), []);
163
+ });
164
+
165
+ test("the governed count is the features the roots cover, not every feature in the tree", () => {
166
+ const found = [
167
+ { feature: "backend/src/features/progress", files: [] },
168
+ { feature: "frontend/src/features/progress", files: [] },
169
+ ];
170
+ assert.equal(governedFeatures(found, { roots: ["backend/src/features"] }), 1);
171
+ assert.equal(governedFeatures(found, {}), 2);
172
+ });