@nanobpm/urban 0.98.5 → 0.99.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.
@@ -148,6 +148,10 @@ export interface OperationInfo {
148
148
  * Security-relevant: this is the single authoring switch that keeps an operator-only door (e.g.
149
149
  * a human-gated dispatch) out of the agent-facing tool surface. See {@link isMcpExcluded}. */
150
150
  mcpExcluded: boolean;
151
+ /** The parsed `x-cli` extension (ADR 0068 — CLI command projection), or absent when the
152
+ * operation declares none. Validated by {@link parseCliExtension}; command paths are unique
153
+ * across the document. A CLI reads the effective audience via {@link effectiveCliAudience}. */
154
+ cli?: CliExtension;
151
155
  summary?: string;
152
156
  }
153
157
  /** Parse an OpenAPI document from text. Accepts both YAML (the sanctioned authoring format for
@@ -177,6 +181,52 @@ export declare function resolveSchemaDeep(doc: OpenApiDoc, schema: OpenApiSchema
177
181
  * (path, method) order. Operations without an operationId are skipped here; the runtime mount logs
178
182
  * them at `warn` and skips them too — this keeps the pure collector total. */
179
183
  export declare function collectOperations(doc: OpenApiDoc): OperationInfo[];
184
+ /** The audiences an `x-cli` operation may declare. `operator` = shown by a CLI only behind an
185
+ * explicit operator switch (e.g. `--operator`). Absent = the default (everyone) audience. */
186
+ export type CliAudience = "operator";
187
+ /** A parsed, validated `x-cli` operation extension (ADR 0068). Optional authoring keys are
188
+ * normalised: `exclude` defaults to `false`, `positional`/`aliases` to `[]`. `command` is empty
189
+ * only for an excluded operation that omitted it. */
190
+ export interface CliExtension {
191
+ /** Namespace-relative kebab-case command words, e.g. `["start", "feature"]`. */
192
+ command: string[];
193
+ /** Hide the operation from CLI projection entirely. */
194
+ exclude: boolean;
195
+ audience?: CliAudience;
196
+ /** Body/parameter field names accepted positionally, in order. */
197
+ positional: string[];
198
+ /** Alternative command paths (each a kebab-case word list), e.g. `[["feature", "start"]]`. */
199
+ aliases: string[][];
200
+ }
201
+ /**
202
+ * Parse and validate the `x-cli` operation extension (ADR 0068 — CLI command projection). Returns
203
+ * `undefined` when the extension is absent; throws a `where`-qualified error (e.g.
204
+ * `paths./features.post.x-cli.command[1]: …`) on unknown keys, a `command` that is not a non-empty
205
+ * array of kebab-case words (required unless `exclude: true`), a non-boolean `exclude`, an unknown
206
+ * `audience`, a non-string-array `positional`, or malformed `aliases`. Cross-operation uniqueness
207
+ * of command paths is enforced by the walker ({@link collectOperations}).
208
+ *
209
+ * Default when ABSENT: a CLI derives names itself; an operation that `x-mcp` excludes and that has
210
+ * no `x-cli` is treated as `audience: operator` (see {@link effectiveCliAudience}).
211
+ */
212
+ export declare function parseCliExtension(ext: unknown, where?: string): CliExtension | undefined;
213
+ /**
214
+ * The effective CLI audience of an operation — the single documented default rule (ADR 0068), so
215
+ * CLIs never each invent one: an explicit `x-cli.audience` wins; otherwise an `x-mcp`-excluded
216
+ * operation WITHOUT `x-cli` is `operator` (an operator-only door withheld from agents must not be
217
+ * handed back to them via a shell); otherwise the default audience (`undefined`).
218
+ */
219
+ export declare function effectiveCliAudience(op: Pick<OperationInfo, "cli" | "mcpExcluded">): CliAudience | undefined;
220
+ /** One operation's CLI-projection facts (snapshot unit, mirrors {@link McpToolProjection}). */
221
+ export interface CliProjection {
222
+ operationId: string;
223
+ method: HttpMethodLower;
224
+ path: string;
225
+ cli?: CliExtension;
226
+ audience?: CliAudience;
227
+ }
228
+ /** Project every operationId-bearing operation to its CLI facts, in walker order. */
229
+ export declare function collectCliProjection(doc: OpenApiDoc): CliProjection[];
180
230
  /**
181
231
  * Read the `x-mcp` operation extension (ADR 0067 — MCP tool projection). An operation is EXPOSED as
182
232
  * an MCP tool by default; it is excluded only when it says so explicitly, so a spec author opts a
@@ -205,6 +205,7 @@ export function collectOperations(doc) {
205
205
  // door crash projection/guards for the whole document — even though that door is withheld.
206
206
  // Excluded ops therefore carry no `resolvedSchema`/`requestBodySchemaResolved` (unused).
207
207
  const mcpExcluded = isMcpExcluded(opRaw["x-mcp"]);
208
+ const cli = parseCliExtension(opRaw["x-cli"], `paths.${path}.${method}.x-cli`);
208
209
  const opParams = Array.isArray(opRaw.parameters) ? opRaw.parameters : [];
209
210
  const parameters = normalizeParameters([...pathParams, ...opParams]).map((p) => ({
210
211
  ...p,
@@ -241,12 +242,136 @@ export function collectOperations(doc) {
241
242
  security,
242
243
  eject: opRaw["x-urban-eject"] === true,
243
244
  mcpExcluded,
245
+ ...(cli ? { cli } : {}),
244
246
  summary: typeof opRaw.summary === "string" ? opRaw.summary : undefined,
245
247
  });
246
248
  }
247
249
  }
250
+ assertUniqueCliCommands(out);
248
251
  return out;
249
252
  }
253
+ const CLI_KEYS = ["command", "exclude", "audience", "positional", "aliases"];
254
+ const CLI_AUDIENCES = ["operator"];
255
+ const KEBAB_WORD = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
256
+ function isCliAudience(v) {
257
+ return CLI_AUDIENCES.some((a) => a === v);
258
+ }
259
+ function parseCommandWords(v, where) {
260
+ if (!Array.isArray(v) || v.length === 0) {
261
+ throw new Error(`${where}: must be a non-empty array of kebab-case words`);
262
+ }
263
+ return v.map((w, i) => {
264
+ if (typeof w !== "string" || !KEBAB_WORD.test(w)) {
265
+ throw new Error(`${where}[${i}]: ${JSON.stringify(w)} is not a kebab-case word (expected ${KEBAB_WORD})`);
266
+ }
267
+ return w;
268
+ });
269
+ }
270
+ /**
271
+ * Parse and validate the `x-cli` operation extension (ADR 0068 — CLI command projection). Returns
272
+ * `undefined` when the extension is absent; throws a `where`-qualified error (e.g.
273
+ * `paths./features.post.x-cli.command[1]: …`) on unknown keys, a `command` that is not a non-empty
274
+ * array of kebab-case words (required unless `exclude: true`), a non-boolean `exclude`, an unknown
275
+ * `audience`, a non-string-array `positional`, or malformed `aliases`. Cross-operation uniqueness
276
+ * of command paths is enforced by the walker ({@link collectOperations}).
277
+ *
278
+ * Default when ABSENT: a CLI derives names itself; an operation that `x-mcp` excludes and that has
279
+ * no `x-cli` is treated as `audience: operator` (see {@link effectiveCliAudience}).
280
+ */
281
+ export function parseCliExtension(ext, where = "x-cli") {
282
+ if (ext === undefined)
283
+ return undefined;
284
+ if (!isRecord(ext))
285
+ throw new Error(`${where}: must be an object`);
286
+ for (const key of Object.keys(ext)) {
287
+ if (!CLI_KEYS.includes(key)) {
288
+ throw new Error(`${where}: unknown key "${key}" (allowed: ${CLI_KEYS.join(", ")})`);
289
+ }
290
+ }
291
+ if (ext.exclude !== undefined && typeof ext.exclude !== "boolean") {
292
+ throw new Error(`${where}.exclude: must be a boolean`);
293
+ }
294
+ const exclude = ext.exclude === true;
295
+ const command = ext.command === undefined && exclude ? [] : parseCommandWords(ext.command, `${where}.command`);
296
+ if (ext.audience !== undefined && !isCliAudience(ext.audience)) {
297
+ throw new Error(`${where}.audience: ${JSON.stringify(ext.audience)} is not one of: ${CLI_AUDIENCES.join(", ")}`);
298
+ }
299
+ let positional = [];
300
+ if (ext.positional !== undefined) {
301
+ const raw = ext.positional;
302
+ if (!Array.isArray(raw))
303
+ throw new Error(`${where}.positional: must be an array of field names`);
304
+ positional = raw.map((f, i) => {
305
+ if (typeof f !== "string" || f.length === 0) {
306
+ throw new Error(`${where}.positional[${i}]: must be a non-empty string`);
307
+ }
308
+ return f;
309
+ });
310
+ const dup = positional.find((f, i) => positional.indexOf(f) !== i);
311
+ if (dup !== undefined)
312
+ throw new Error(`${where}.positional: duplicate field "${dup}"`);
313
+ }
314
+ let aliases = [];
315
+ if (ext.aliases !== undefined) {
316
+ const raw = ext.aliases;
317
+ if (!Array.isArray(raw))
318
+ throw new Error(`${where}.aliases: must be an array of command word arrays`);
319
+ aliases = raw.map((a, i) => parseCommandWords(a, `${where}.aliases[${i}]`));
320
+ }
321
+ return {
322
+ command,
323
+ exclude,
324
+ ...(ext.audience !== undefined && isCliAudience(ext.audience) ? { audience: ext.audience } : {}),
325
+ positional,
326
+ aliases,
327
+ };
328
+ }
329
+ /** Every command path (primary and aliases) of non-excluded operations must be unique across the
330
+ * document — two operations answering to the same words would make CLI dispatch ambiguous. */
331
+ function assertUniqueCliCommands(ops) {
332
+ const owner = new Map();
333
+ for (const op of ops) {
334
+ if (!op.cli || op.cli.exclude)
335
+ continue;
336
+ const where = `paths.${op.path}.${op.method}.x-cli`;
337
+ const paths = [
338
+ [`${where}.command`, op.cli.command],
339
+ ...op.cli.aliases.map((a, i) => [`${where}.aliases[${i}]`, a]),
340
+ ];
341
+ for (const [at, words] of paths) {
342
+ const key = words.join(" ");
343
+ const prior = owner.get(key);
344
+ if (prior !== undefined) {
345
+ throw new Error(`${at}: duplicate command path "${key}" (already declared at ${prior})`);
346
+ }
347
+ owner.set(key, at);
348
+ }
349
+ }
350
+ }
351
+ /**
352
+ * The effective CLI audience of an operation — the single documented default rule (ADR 0068), so
353
+ * CLIs never each invent one: an explicit `x-cli.audience` wins; otherwise an `x-mcp`-excluded
354
+ * operation WITHOUT `x-cli` is `operator` (an operator-only door withheld from agents must not be
355
+ * handed back to them via a shell); otherwise the default audience (`undefined`).
356
+ */
357
+ export function effectiveCliAudience(op) {
358
+ if (op.cli)
359
+ return op.cli.audience;
360
+ return op.mcpExcluded ? "operator" : undefined;
361
+ }
362
+ /** Project every operationId-bearing operation to its CLI facts, in walker order. */
363
+ export function collectCliProjection(doc) {
364
+ return collectOperations(doc).map((op) => {
365
+ const audience = effectiveCliAudience(op);
366
+ return {
367
+ operationId: op.operationId,
368
+ method: op.method,
369
+ path: op.path,
370
+ ...(op.cli ? { cli: op.cli } : {}),
371
+ ...(audience ? { audience } : {}),
372
+ };
373
+ });
374
+ }
250
375
  /**
251
376
  * Read the `x-mcp` operation extension (ADR 0067 — MCP tool projection). An operation is EXPOSED as
252
377
  * an MCP tool by default; it is excluded only when it says so explicitly, so a spec author opts a
@@ -18,6 +18,8 @@ export { buildSystemBrief, deriveSystemBrief, emitSystemBriefMd, foldOwnership,
18
18
  export type { DecisionRef, Ownership, SystemBrief } from "./derivers/system-brief.ts";
19
19
  export { collectOperations, HTTP_METHODS, isSafeOperationId, operationsWithoutId, operationsWithUnsafeId, parseSpec, refName, resolveSchema, toRouteMatcher, undeclaredPathParams, validateValue, } from "../openapi/spec.ts";
20
20
  export type { HttpMethodLower, OpenApiDoc, OpenApiParameter, OpenApiSchema, OperationInfo, } from "../openapi/spec.ts";
21
+ export { collectCliProjection, effectiveCliAudience, parseCliExtension, } from "../openapi/spec.ts";
22
+ export type { CliAudience, CliExtension, CliProjection, } from "../openapi/spec.ts";
21
23
  export declare const DERIVERS: readonly [import("./artifact.ts").Deriver<import("./derivers/migrations.ts").ToolkitManifest>, import("./artifact.ts").Deriver<import("./derivers/migrations.ts").ToolkitManifest>, import("./artifact.ts").Deriver<{
22
24
  models: import("./derivers/worker-io.ts").ModelSource[];
23
25
  declaredTypeIds: Iterable<string>;
@@ -15,6 +15,9 @@ export { apiDeriver, deriveApi, emitApiBindings, emitApiBindingsRuntime, emitApi
15
15
  export { buildSystemBrief, deriveSystemBrief, emitSystemBriefMd, foldOwnership, scanModelDecisions, systemBriefDeriver, SYSTEM_BRIEF_JSON, SYSTEM_BRIEF_MD, } from "./derivers/system-brief.js";
16
16
  // The OpenAPI machinery the deriver + runtime share (ADR 0058).
17
17
  export { collectOperations, HTTP_METHODS, isSafeOperationId, operationsWithoutId, operationsWithUnsafeId, parseSpec, refName, resolveSchema, toRouteMatcher, undeclaredPathParams, validateValue, } from "../openapi/spec.js";
18
+ // The CLI command projection (`x-cli`, ADR 0068): the parser, the single
19
+ // effective-audience rule, and the projection walker a CLI consumer reads.
20
+ export { collectCliProjection, effectiveCliAudience, parseCliExtension, } from "../openapi/spec.js";
18
21
  // The registry of all derivers (for discovery / IDE migration).
19
22
  import { migrationsDeriver } from "./derivers/migrations.js";
20
23
  import { domainDeriver } from "./derivers/domain.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nanobpm/urban",
3
- "version": "0.98.5",
3
+ "version": "0.99.0",
4
4
  "description": "Urban: build and run code-first apps on Nano — runtime, derivation toolkit, and CLI in one. Author durable processes with @nanobpm/workflow (defineFlow), a typed datasource, forms, triggers and surfaces from a nano.app.json manifest, on Node or Deno.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -0,0 +1,56 @@
1
+ # CLI-projection fixture (ADR 0068) — NOT an app spec.
2
+ #
3
+ # Exercises every `x-cli` form and the documented default so `cli-projection.snapshot.json`
4
+ # (asserted by `cli-projection.test.ts`) pins the parsed `cli` metadata:
5
+ # - full form (command + positional + aliases)
6
+ # - operator audience
7
+ # - exclude: true (command omitted)
8
+ # - x-mcp-excluded WITHOUT x-cli → effective audience `operator` (the default rule)
9
+ # - no extensions at all → no `cli`, default audience
10
+ # Regenerate with: UPDATE_CLI_SNAPSHOT=1 npm test -w packages/urban
11
+ openapi: 3.1.0
12
+ info:
13
+ title: cli-projection-fixture
14
+ version: 0.0.0
15
+ paths:
16
+ /features:
17
+ post:
18
+ operationId: startFeature
19
+ x-cli:
20
+ command: [start, feature]
21
+ positional: [issue]
22
+ aliases: [[feature, start]]
23
+ responses:
24
+ "202":
25
+ description: accepted
26
+ get:
27
+ operationId: listFeatures
28
+ responses:
29
+ "200":
30
+ description: ok
31
+ /delivery-graphs/dispatch:
32
+ post:
33
+ operationId: dispatchDeliveryGraph
34
+ x-mcp:
35
+ exclude: true
36
+ x-cli:
37
+ command: [dispatch, delivery-graph]
38
+ audience: operator
39
+ responses:
40
+ "202":
41
+ description: accepted
42
+ /hooks/agent:
43
+ post:
44
+ operationId: agentHook
45
+ x-cli:
46
+ exclude: true
47
+ responses:
48
+ "204":
49
+ description: no content
50
+ /internal/reindex:
51
+ post:
52
+ operationId: reindex
53
+ x-mcp: false
54
+ responses:
55
+ "202":
56
+ description: accepted
@@ -0,0 +1,61 @@
1
+ [
2
+ {
3
+ "operationId": "dispatchDeliveryGraph",
4
+ "method": "post",
5
+ "path": "/delivery-graphs/dispatch",
6
+ "cli": {
7
+ "command": [
8
+ "dispatch",
9
+ "delivery-graph"
10
+ ],
11
+ "exclude": false,
12
+ "audience": "operator",
13
+ "positional": [],
14
+ "aliases": []
15
+ },
16
+ "audience": "operator"
17
+ },
18
+ {
19
+ "operationId": "listFeatures",
20
+ "method": "get",
21
+ "path": "/features"
22
+ },
23
+ {
24
+ "operationId": "startFeature",
25
+ "method": "post",
26
+ "path": "/features",
27
+ "cli": {
28
+ "command": [
29
+ "start",
30
+ "feature"
31
+ ],
32
+ "exclude": false,
33
+ "positional": [
34
+ "issue"
35
+ ],
36
+ "aliases": [
37
+ [
38
+ "feature",
39
+ "start"
40
+ ]
41
+ ]
42
+ }
43
+ },
44
+ {
45
+ "operationId": "agentHook",
46
+ "method": "post",
47
+ "path": "/hooks/agent",
48
+ "cli": {
49
+ "command": [],
50
+ "exclude": true,
51
+ "positional": [],
52
+ "aliases": []
53
+ }
54
+ },
55
+ {
56
+ "operationId": "reindex",
57
+ "method": "post",
58
+ "path": "/internal/reindex",
59
+ "audience": "operator"
60
+ }
61
+ ]
@@ -0,0 +1,144 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { readFileSync, writeFileSync } from "node:fs";
4
+ import { dirname, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import {
7
+ collectCliProjection,
8
+ collectOperations,
9
+ effectiveCliAudience,
10
+ type OpenApiDoc,
11
+ parseCliExtension,
12
+ parseSpec,
13
+ } from "./spec.ts";
14
+
15
+ const HERE = dirname(fileURLToPath(import.meta.url));
16
+ const FIXTURE = resolve(HERE, "cli-projection.fixture.yaml");
17
+ const SNAPSHOT = resolve(HERE, "cli-projection.snapshot.json");
18
+
19
+ test("parseCliExtension: absent → undefined", () => {
20
+ assert.equal(parseCliExtension(undefined), undefined);
21
+ });
22
+
23
+ test("parseCliExtension: minimal command form normalises optional keys", () => {
24
+ assert.deepEqual(parseCliExtension({ command: ["start", "feature"] }), {
25
+ command: ["start", "feature"],
26
+ exclude: false,
27
+ positional: [],
28
+ aliases: [],
29
+ });
30
+ });
31
+
32
+ test("parseCliExtension: full form", () => {
33
+ assert.deepEqual(
34
+ parseCliExtension({
35
+ command: ["start", "feature"],
36
+ exclude: false,
37
+ audience: "operator",
38
+ positional: ["issue"],
39
+ aliases: [["feature", "start"]],
40
+ }),
41
+ {
42
+ command: ["start", "feature"],
43
+ exclude: false,
44
+ audience: "operator",
45
+ positional: ["issue"],
46
+ aliases: [["feature", "start"]],
47
+ },
48
+ );
49
+ });
50
+
51
+ test("parseCliExtension: exclude: true makes command optional", () => {
52
+ assert.deepEqual(parseCliExtension({ exclude: true }), { command: [], exclude: true, positional: [], aliases: [] });
53
+ });
54
+
55
+ const errors: [string, unknown, RegExp][] = [
56
+ ["non-object", ["start"], /^Error: w: must be an object/],
57
+ ["unknown key", { command: ["a"], verb: "x" }, /^Error: w: unknown key "verb"/],
58
+ ["missing command", {}, /^Error: w\.command: must be a non-empty array/],
59
+ ["empty command", { command: [] }, /^Error: w\.command: must be a non-empty array/],
60
+ ["string command", { command: "start" }, /^Error: w\.command: must be a non-empty array/],
61
+ ["non-kebab word", { command: ["start", "deliveryGraph"] }, /^Error: w\.command\[1\]: "deliveryGraph" is not a kebab-case word/],
62
+ ["empty word", { command: [""] }, /^Error: w\.command\[0\]: "" is not a kebab-case word/],
63
+ ["non-string word", { command: [1] }, /^Error: w\.command\[0\]: 1 is not a kebab-case word/],
64
+ ["non-boolean exclude", { command: ["a"], exclude: "yes" }, /^Error: w\.exclude: must be a boolean/],
65
+ ["unknown audience", { command: ["a"], audience: "admin" }, /^Error: w\.audience: "admin" is not one of: operator/],
66
+ ["non-array positional", { command: ["a"], positional: "issue" }, /^Error: w\.positional: must be an array/],
67
+ ["empty positional", { command: ["a"], positional: [""] }, /^Error: w\.positional\[0\]: must be a non-empty string/],
68
+ ["duplicate positional", { command: ["a"], positional: ["x", "x"] }, /^Error: w\.positional: duplicate field "x"/],
69
+ ["non-string positional", { command: ["a"], positional: [1] }, /^Error: w\.positional\[0\]: must be a non-empty string/],
70
+ ["non-array aliases", { command: ["a"], aliases: "b" }, /^Error: w\.aliases: must be an array of command word arrays/],
71
+ ["non-array alias element", { command: ["a"], aliases: ["b"] }, /^Error: w\.aliases\[0\]: must be a non-empty array/],
72
+ ["non-kebab alias", { command: ["a"], aliases: [["B"]] }, /^Error: w\.aliases\[0\]\[0\]: "B" is not a kebab-case word/],
73
+ ];
74
+ for (const [name, ext, re] of errors) {
75
+ test(`parseCliExtension rejects ${name} with a path-qualified error`, () => {
76
+ assert.throws(() => parseCliExtension(ext, "w"), re);
77
+ });
78
+ }
79
+
80
+ function docWith(ops: Record<string, Record<string, unknown>>): OpenApiDoc {
81
+ const paths: Record<string, unknown> = {};
82
+ for (const [path, op] of Object.entries(ops)) paths[path] = { post: { responses: {}, ...op } };
83
+ return JSON.parse(JSON.stringify({ openapi: "3.1.0", info: { title: "t", version: "0" }, paths }));
84
+ }
85
+
86
+ test("collectOperations exposes the parsed x-cli as `cli` and errors are path-qualified", () => {
87
+ const ops = collectOperations(docWith({ "/a": { operationId: "a", "x-cli": { command: ["do", "a"] } } }));
88
+ assert.deepEqual(ops[0].cli?.command, ["do", "a"]);
89
+ assert.throws(
90
+ () => collectOperations(docWith({ "/a": { operationId: "a", "x-cli": { command: ["Do"] } } })),
91
+ /^Error: paths\.\/a\.post\.x-cli\.command\[0\]/,
92
+ );
93
+ assert.equal(collectOperations(docWith({ "/b": { operationId: "b" } }))[0].cli, undefined);
94
+ });
95
+
96
+ test("collectOperations rejects duplicate command paths across operations", () => {
97
+ assert.throws(
98
+ () =>
99
+ collectOperations(
100
+ docWith({
101
+ "/a": { operationId: "a", "x-cli": { command: ["start", "feature"] } },
102
+ "/b": { operationId: "b", "x-cli": { command: ["start", "feature"] } },
103
+ }),
104
+ ),
105
+ /paths\.\/b\.post\.x-cli\.command: duplicate command path "start feature" \(already declared at paths\.\/a\.post\.x-cli\.command\)/,
106
+ );
107
+ });
108
+
109
+ test("an alias colliding with another operation's command is a duplicate", () => {
110
+ assert.throws(
111
+ () =>
112
+ collectOperations(
113
+ docWith({
114
+ "/a": { operationId: "a", "x-cli": { command: ["start", "feature"] } },
115
+ "/b": { operationId: "b", "x-cli": { command: ["go"], aliases: [["start", "feature"]] } },
116
+ }),
117
+ ),
118
+ /paths\.\/b\.post\.x-cli\.aliases\[0\]: duplicate command path "start feature"/,
119
+ );
120
+ });
121
+
122
+ test("excluded operations do not claim command paths", () => {
123
+ const ops = collectOperations(
124
+ docWith({
125
+ "/a": { operationId: "a", "x-cli": { command: ["x"], exclude: true } },
126
+ "/b": { operationId: "b", "x-cli": { command: ["x"] } },
127
+ }),
128
+ );
129
+ assert.equal(ops.length, 2);
130
+ });
131
+
132
+ test("effectiveCliAudience: x-mcp-excluded without x-cli defaults to operator; x-cli wins", () => {
133
+ const none = { exclude: false, command: ["a"], positional: [], aliases: [] };
134
+ assert.equal(effectiveCliAudience({ mcpExcluded: true }), "operator");
135
+ assert.equal(effectiveCliAudience({ mcpExcluded: false }), undefined);
136
+ assert.equal(effectiveCliAudience({ mcpExcluded: true, cli: none }), undefined);
137
+ assert.equal(effectiveCliAudience({ mcpExcluded: false, cli: { ...none, audience: "operator" } }), "operator");
138
+ });
139
+
140
+ test("CLI projection of the fixture matches the committed snapshot", () => {
141
+ const current = `${JSON.stringify(collectCliProjection(parseSpec(readFileSync(FIXTURE, "utf8"))), null, 2)}\n`;
142
+ if (process.env.UPDATE_CLI_SNAPSHOT === "1") writeFileSync(SNAPSHOT, current);
143
+ assert.equal(current, readFileSync(SNAPSHOT, "utf8"), "regenerate with UPDATE_CLI_SNAPSHOT=1 and review the diff");
144
+ });
@@ -49,3 +49,14 @@ npm run check:mcp-conformance -w packages/urban
49
49
 
50
50
  If a refreshed spec would project a broken tool the guard fails — then either the
51
51
  projection (`openapi/spec.ts`) or the offending consumer spec is fixed deliberately.
52
+
53
+ ## CLI projection (`x-cli`, ADR 0068)
54
+
55
+ Consumer specs may also carry the `x-cli` operation extension that names an operation's
56
+ CLI command (`command`, `exclude`, `audience`, `positional`, `aliases`). It is parsed and
57
+ validated by the same walker (`parseCliExtension` in `../spec.ts`), so a vendored spec
58
+ with an invalid `x-cli` — unknown key, non-kebab or empty `command`, or a command path
59
+ duplicated across operations — fails the conformance guard with a path-qualified error.
60
+ When an operation is `x-mcp`-excluded and has **no** `x-cli`, CLIs treat it as
61
+ `audience: operator` (`effectiveCliAudience`). See
62
+ [`docs/adr/0068-cli-command-projection.md`](../../../../../docs/adr/0068-cli-command-projection.md).
@@ -207,6 +207,10 @@ export interface OperationInfo {
207
207
  * Security-relevant: this is the single authoring switch that keeps an operator-only door (e.g.
208
208
  * a human-gated dispatch) out of the agent-facing tool surface. See {@link isMcpExcluded}. */
209
209
  mcpExcluded: boolean;
210
+ /** The parsed `x-cli` extension (ADR 0068 — CLI command projection), or absent when the
211
+ * operation declares none. Validated by {@link parseCliExtension}; command paths are unique
212
+ * across the document. A CLI reads the effective audience via {@link effectiveCliAudience}. */
213
+ cli?: CliExtension;
210
214
  summary?: string;
211
215
  }
212
216
 
@@ -366,6 +370,7 @@ export function collectOperations(doc: OpenApiDoc): OperationInfo[] {
366
370
  // door crash projection/guards for the whole document — even though that door is withheld.
367
371
  // Excluded ops therefore carry no `resolvedSchema`/`requestBodySchemaResolved` (unused).
368
372
  const mcpExcluded = isMcpExcluded(opRaw["x-mcp"]);
373
+ const cli = parseCliExtension(opRaw["x-cli"], `paths.${path}.${method}.x-cli`);
369
374
  const opParams = Array.isArray(opRaw.parameters) ? opRaw.parameters : [];
370
375
  const parameters = normalizeParameters([...pathParams, ...opParams]).map((p) => ({
371
376
  ...p,
@@ -404,13 +409,166 @@ export function collectOperations(doc: OpenApiDoc): OperationInfo[] {
404
409
  security,
405
410
  eject: opRaw["x-urban-eject"] === true,
406
411
  mcpExcluded,
412
+ ...(cli ? { cli } : {}),
407
413
  summary: typeof opRaw.summary === "string" ? opRaw.summary : undefined,
408
414
  });
409
415
  }
410
416
  }
417
+ assertUniqueCliCommands(out);
411
418
  return out;
412
419
  }
413
420
 
421
+ /** The audiences an `x-cli` operation may declare. `operator` = shown by a CLI only behind an
422
+ * explicit operator switch (e.g. `--operator`). Absent = the default (everyone) audience. */
423
+ export type CliAudience = "operator";
424
+
425
+ /** A parsed, validated `x-cli` operation extension (ADR 0068). Optional authoring keys are
426
+ * normalised: `exclude` defaults to `false`, `positional`/`aliases` to `[]`. `command` is empty
427
+ * only for an excluded operation that omitted it. */
428
+ export interface CliExtension {
429
+ /** Namespace-relative kebab-case command words, e.g. `["start", "feature"]`. */
430
+ command: string[];
431
+ /** Hide the operation from CLI projection entirely. */
432
+ exclude: boolean;
433
+ audience?: CliAudience;
434
+ /** Body/parameter field names accepted positionally, in order. */
435
+ positional: string[];
436
+ /** Alternative command paths (each a kebab-case word list), e.g. `[["feature", "start"]]`. */
437
+ aliases: string[][];
438
+ }
439
+
440
+ const CLI_KEYS: readonly string[] = ["command", "exclude", "audience", "positional", "aliases"];
441
+ const CLI_AUDIENCES: readonly CliAudience[] = ["operator"];
442
+ const KEBAB_WORD = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
443
+
444
+ function isCliAudience(v: unknown): v is CliAudience {
445
+ return CLI_AUDIENCES.some((a) => a === v);
446
+ }
447
+
448
+ function parseCommandWords(v: unknown, where: string): string[] {
449
+ if (!Array.isArray(v) || v.length === 0) {
450
+ throw new Error(`${where}: must be a non-empty array of kebab-case words`);
451
+ }
452
+ return v.map((w, i) => {
453
+ if (typeof w !== "string" || !KEBAB_WORD.test(w)) {
454
+ throw new Error(`${where}[${i}]: ${JSON.stringify(w)} is not a kebab-case word (expected ${KEBAB_WORD})`);
455
+ }
456
+ return w;
457
+ });
458
+ }
459
+
460
+ /**
461
+ * Parse and validate the `x-cli` operation extension (ADR 0068 — CLI command projection). Returns
462
+ * `undefined` when the extension is absent; throws a `where`-qualified error (e.g.
463
+ * `paths./features.post.x-cli.command[1]: …`) on unknown keys, a `command` that is not a non-empty
464
+ * array of kebab-case words (required unless `exclude: true`), a non-boolean `exclude`, an unknown
465
+ * `audience`, a non-string-array `positional`, or malformed `aliases`. Cross-operation uniqueness
466
+ * of command paths is enforced by the walker ({@link collectOperations}).
467
+ *
468
+ * Default when ABSENT: a CLI derives names itself; an operation that `x-mcp` excludes and that has
469
+ * no `x-cli` is treated as `audience: operator` (see {@link effectiveCliAudience}).
470
+ */
471
+ export function parseCliExtension(ext: unknown, where = "x-cli"): CliExtension | undefined {
472
+ if (ext === undefined) return undefined;
473
+ if (!isRecord(ext)) throw new Error(`${where}: must be an object`);
474
+ for (const key of Object.keys(ext)) {
475
+ if (!CLI_KEYS.includes(key)) {
476
+ throw new Error(`${where}: unknown key "${key}" (allowed: ${CLI_KEYS.join(", ")})`);
477
+ }
478
+ }
479
+ if (ext.exclude !== undefined && typeof ext.exclude !== "boolean") {
480
+ throw new Error(`${where}.exclude: must be a boolean`);
481
+ }
482
+ const exclude = ext.exclude === true;
483
+ const command =
484
+ ext.command === undefined && exclude ? [] : parseCommandWords(ext.command, `${where}.command`);
485
+ if (ext.audience !== undefined && !isCliAudience(ext.audience)) {
486
+ throw new Error(`${where}.audience: ${JSON.stringify(ext.audience)} is not one of: ${CLI_AUDIENCES.join(", ")}`);
487
+ }
488
+ let positional: string[] = [];
489
+ if (ext.positional !== undefined) {
490
+ const raw = ext.positional;
491
+ if (!Array.isArray(raw)) throw new Error(`${where}.positional: must be an array of field names`);
492
+ positional = raw.map((f, i) => {
493
+ if (typeof f !== "string" || f.length === 0) {
494
+ throw new Error(`${where}.positional[${i}]: must be a non-empty string`);
495
+ }
496
+ return f;
497
+ });
498
+ const dup = positional.find((f, i) => positional.indexOf(f) !== i);
499
+ if (dup !== undefined) throw new Error(`${where}.positional: duplicate field "${dup}"`);
500
+ }
501
+ let aliases: string[][] = [];
502
+ if (ext.aliases !== undefined) {
503
+ const raw = ext.aliases;
504
+ if (!Array.isArray(raw)) throw new Error(`${where}.aliases: must be an array of command word arrays`);
505
+ aliases = raw.map((a, i) => parseCommandWords(a, `${where}.aliases[${i}]`));
506
+ }
507
+ return {
508
+ command,
509
+ exclude,
510
+ ...(ext.audience !== undefined && isCliAudience(ext.audience) ? { audience: ext.audience } : {}),
511
+ positional,
512
+ aliases,
513
+ };
514
+ }
515
+
516
+ /** Every command path (primary and aliases) of non-excluded operations must be unique across the
517
+ * document — two operations answering to the same words would make CLI dispatch ambiguous. */
518
+ function assertUniqueCliCommands(ops: OperationInfo[]): void {
519
+ const owner = new Map<string, string>();
520
+ for (const op of ops) {
521
+ if (!op.cli || op.cli.exclude) continue;
522
+ const where = `paths.${op.path}.${op.method}.x-cli`;
523
+ const paths: [string, string[]][] = [
524
+ [`${where}.command`, op.cli.command],
525
+ ...op.cli.aliases.map((a, i): [string, string[]] => [`${where}.aliases[${i}]`, a]),
526
+ ];
527
+ for (const [at, words] of paths) {
528
+ const key = words.join(" ");
529
+ const prior = owner.get(key);
530
+ if (prior !== undefined) {
531
+ throw new Error(`${at}: duplicate command path "${key}" (already declared at ${prior})`);
532
+ }
533
+ owner.set(key, at);
534
+ }
535
+ }
536
+ }
537
+
538
+ /**
539
+ * The effective CLI audience of an operation — the single documented default rule (ADR 0068), so
540
+ * CLIs never each invent one: an explicit `x-cli.audience` wins; otherwise an `x-mcp`-excluded
541
+ * operation WITHOUT `x-cli` is `operator` (an operator-only door withheld from agents must not be
542
+ * handed back to them via a shell); otherwise the default audience (`undefined`).
543
+ */
544
+ export function effectiveCliAudience(op: Pick<OperationInfo, "cli" | "mcpExcluded">): CliAudience | undefined {
545
+ if (op.cli) return op.cli.audience;
546
+ return op.mcpExcluded ? "operator" : undefined;
547
+ }
548
+
549
+ /** One operation's CLI-projection facts (snapshot unit, mirrors {@link McpToolProjection}). */
550
+ export interface CliProjection {
551
+ operationId: string;
552
+ method: HttpMethodLower;
553
+ path: string;
554
+ cli?: CliExtension;
555
+ audience?: CliAudience;
556
+ }
557
+
558
+ /** Project every operationId-bearing operation to its CLI facts, in walker order. */
559
+ export function collectCliProjection(doc: OpenApiDoc): CliProjection[] {
560
+ return collectOperations(doc).map((op) => {
561
+ const audience = effectiveCliAudience(op);
562
+ return {
563
+ operationId: op.operationId,
564
+ method: op.method,
565
+ path: op.path,
566
+ ...(op.cli ? { cli: op.cli } : {}),
567
+ ...(audience ? { audience } : {}),
568
+ };
569
+ });
570
+ }
571
+
414
572
  /**
415
573
  * Read the `x-mcp` operation extension (ADR 0067 — MCP tool projection). An operation is EXPOSED as
416
574
  * an MCP tool by default; it is excluded only when it says so explicitly, so a spec author opts a
@@ -758,6 +758,16 @@ test("serves the OpenAPI spec at {base}-docs/openapi.json, rebased to the mounte
758
758
  assert.deepEqual(doc.servers, [{ url: "api" }]);
759
759
  });
760
760
 
761
+ test("the served openapi.json keeps the x-cli extension (CLIs read it at runtime, ADR 0068)", async () => {
762
+ const doc0 = JSON.parse(spec);
763
+ doc0.paths["/invoices"].post["x-cli"] = { command: ["invoice", "create"], positional: ["id"] };
764
+ const { router } = build({ spec: "openapi.json" }, {}, JSON.stringify(doc0));
765
+ const res = await router(req("GET", "/app/api-docs/openapi.json"));
766
+ assert.equal(res.status, 200);
767
+ const doc = JSON.parse(res.body ?? "{}");
768
+ assert.deepEqual(doc.paths["/invoices"].post["x-cli"], { command: ["invoice", "create"], positional: ["id"] });
769
+ });
770
+
761
771
  test("serves the Swagger UI page at {base}-docs by default", async () => {
762
772
  const { router } = build({ spec: "openapi.json" }, {});
763
773
  const res = await router(req("GET", "/app/api-docs"));
@@ -144,6 +144,19 @@ export type {
144
144
  OperationInfo,
145
145
  } from "../openapi/spec.ts";
146
146
 
147
+ // The CLI command projection (`x-cli`, ADR 0068): the parser, the single
148
+ // effective-audience rule, and the projection walker a CLI consumer reads.
149
+ export {
150
+ collectCliProjection,
151
+ effectiveCliAudience,
152
+ parseCliExtension,
153
+ } from "../openapi/spec.ts";
154
+ export type {
155
+ CliAudience,
156
+ CliExtension,
157
+ CliProjection,
158
+ } from "../openapi/spec.ts";
159
+
147
160
  // The registry of all derivers (for discovery / IDE migration).
148
161
  import { migrationsDeriver } from "./derivers/migrations.ts";
149
162
  import { domainDeriver } from "./derivers/domain.ts";