Skip to content

Commit 8b55e44

Browse files
committed
fix(cli): expose nested help and preserve generated option tables
1 parent ac6e1b3 commit 8b55e44

7 files changed

Lines changed: 141 additions & 17 deletions

File tree

‎scripts/generate-ocx-skill-surface.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ function renderIndex(assignments: Map<Capability, string>): string {
7575
"These answer in the CLI head and never reach the proxy, so they work with nothing running.", "",
7676
"| Invocation | Purpose |", "|---|---|"];
7777
for (const head of HEAD_CAPABILITIES) {
78-
lines.push(`| \`${head.invocations.join("` `")}\` | ${head.summary} |`);
78+
lines.push(`| \`${head.invocations.join("` `")}\` | ${tableCell(head.summary)} |`);
7979
}
8080
lines.push("", "## Task chapters", "", "| Chapter | Declared capabilities |", "|---|---|");
8181
for (const domain of DOMAINS) {
@@ -101,6 +101,11 @@ function renderIndex(assignments: Map<Capability, string>): string {
101101
return lines.join("\n");
102102
}
103103

104+
/** Preserve literal prose inside a Markdown table cell, including enum separators. */
105+
function tableCell(value: string | undefined): string {
106+
return (value ?? "").replaceAll("\\", "\\\\").replaceAll("|", "\\|").replace(/\r\n|[\r\n]/g, "<br>");
107+
}
108+
104109
function renderCapability(cap: Capability): string[] {
105110
const invocation = capabilityInvocation(cap);
106111
const handoff = SECRET_HANDOFFS.has(invocation);
@@ -117,7 +122,7 @@ function renderCapability(cap: Capability): string[] {
117122
lines.push("");
118123
if (cap.flags.length > 0) {
119124
lines.push("| Flag | Value | Meaning |", "|---|---|---|");
120-
for (const flag of cap.flags) lines.push(`| \`${flag.name}\` | ${flag.value} | ${flag.summary} |`);
125+
for (const flag of cap.flags) lines.push(`| \`${flag.name}\` | ${tableCell(flag.value)} | ${tableCell(flag.summary)} |`);
121126
lines.push("");
122127
}
123128
lines.push(`JSON mode: \`${cap.json}\`.`, "");

‎src/cli/help-catalog.ts‎

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { CLI_COMMANDS, findCommand, type CliCommandEntry } from "./registry";
33

44
export type HelpResolution =
55
| { kind: "entry"; entry: CliCommandEntry; canonicalName: string; children: readonly Capability[] }
6-
| { kind: "capability"; path: string[]; capability: Capability }
6+
| { kind: "capability"; path: string[]; capability: Capability; children: readonly Capability[] }
77
| { kind: "prefix"; path: string[]; children: readonly Capability[] }
88
| { kind: "models-context"; path: string[] }
99
| { kind: "unavailable"; path: string[]; parent?: string[] };
@@ -22,6 +22,18 @@ function canonicalEntry(entry: CliCommandEntry): CliCommandEntry {
2222
return CLI_COMMANDS.find(candidate => candidate.aliases?.includes(entry.name)) ?? entry;
2323
}
2424

25+
/** Help-only aliases from access dispatch; never rewrite execution argv or operands. */
26+
function canonicalHelpPath(requested: readonly string[], entry: CliCommandEntry): string[] {
27+
const path = entry.name === "api-key"
28+
? ["access", "key", ...requested.slice(1)]
29+
: [canonicalEntry(entry).name, ...requested.slice(1)];
30+
if (path[0] === "access") {
31+
if (path[1] === "keys") path[1] = "key";
32+
if (path[1] === "key" && path[2] === "delete") path[2] = "remove";
33+
}
34+
return path;
35+
}
36+
2537
export interface HelpRecoveryCandidate {
2638
names: string[];
2739
path: string[];
@@ -35,19 +47,24 @@ export function helpRecoveryCandidates(parent: readonly string[] = []): HelpReco
3547
if (entry.hidden) continue;
3648
const canonical = canonicalEntry(entry);
3749
if (canonical.hidden) continue;
38-
const candidate = candidates.get(canonical.name) ?? { names: [], path: [canonical.name] };
50+
const path = canonicalHelpPath([entry.name], entry);
51+
const identity = path.join(" ");
52+
const candidate = candidates.get(identity) ?? { names: [], path };
3953
candidate.names = [...new Set([...candidate.names, entry.name, ...(entry.aliases ?? [])])];
40-
candidates.set(canonical.name, candidate);
54+
candidates.set(identity, candidate);
4155
}
4256
} else {
43-
if (parent.length >= MAX_DOCUMENTED_DEPTH) return [];
4457
const entry = findCommand(parent[0]);
4558
if (!entry || entry.hidden) return [];
46-
const prefix = [canonicalEntry(entry).name, ...parent.slice(1)];
59+
const prefix = canonicalHelpPath(parent, entry);
60+
if (prefix.length >= MAX_DOCUMENTED_DEPTH) return [];
4761
for (const documented of DOCUMENTED_PATHS) {
4862
if (documented.length <= prefix.length || !startsWithPath(documented, prefix)) continue;
4963
const path = documented.slice(0, prefix.length + 1);
50-
candidates.set(path.join(" "), { names: [path[path.length - 1]], path });
64+
const names = [path[path.length - 1]];
65+
if (path.join(" ") === "access key") names.push("keys");
66+
if (path.join(" ") === "access key remove") names.push("delete");
67+
candidates.set(path.join(" "), { names, path });
5168
}
5269
}
5370
return [...candidates.values()];
@@ -58,19 +75,18 @@ export function resolveHelpPath(requested: readonly string[]): HelpResolution {
5875
const entry = requested[0] ? findCommand(requested[0]) : undefined;
5976
if (!entry) return { kind: "unavailable", path: [...requested] };
6077
// Keep exact-name alias entries for root help; nested topics use the owner.
61-
const canonical = canonicalEntry(entry);
78+
const path = canonicalHelpPath(requested, entry);
6279
const declared = CAPABILITIES.filter(capability => !findCommand(capability.command[0])?.hidden);
6380
if (requested.length === 1) return {
64-
kind: "entry", entry, canonicalName: canonical.name,
65-
children: entry.hidden ? [] : declared.filter(candidate => candidate.command.length > 1 && candidate.command[0] === canonical.name),
81+
kind: "entry", entry, canonicalName: path.join(" "),
82+
children: entry.hidden ? [] : declared.filter(candidate => candidate.command.length > path.length && startsWithPath(candidate.command, path)),
6683
};
67-
const path = [canonical.name, ...requested.slice(1)];
6884
if (path.length === 2 && path[0] === "models" && path[1] === "context") {
6985
return { kind: "models-context", path };
7086
}
7187
const capability = declared.find(candidate => candidate.command.length === path.length && startsWithPath(candidate.command, path));
72-
if (capability) return { kind: "capability", path, capability };
73-
const children = declared.filter(candidate => startsWithPath(candidate.command, path));
88+
const children = declared.filter(candidate => candidate.command.length > path.length && startsWithPath(candidate.command, path));
89+
if (capability) return { kind: "capability", path, capability, children };
7490
if (children.length) return { kind: "prefix", path, children };
7591

7692
for (let length = Math.min(path.length - 1, MAX_DOCUMENTED_DEPTH); length > 1; length--) {
@@ -80,5 +96,5 @@ export function resolveHelpPath(requested: readonly string[]): HelpResolution {
8096
return { kind: "unavailable", path, parent };
8197
}
8298
}
83-
return { kind: "unavailable", path, parent: [canonical.name] };
99+
return { kind: "unavailable", path, parent: [path[0]] };
84100
}

‎src/cli/help-recovery.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,9 @@ function distance(left: string, right: string, limit: number): number {
3535
export function suggestHelpPaths(path: readonly string[]): string[][] {
3636
if (!path.length || path.length > MAX_PATH_DEPTH || !path.every(safeToken)) return [];
3737
const result = resolveHelpPath(path);
38-
if (result.kind !== "unavailable") return [];
38+
if (result.kind !== "unavailable" || result.path.length > MAX_PATH_DEPTH) return [];
3939
const parent = result.parent ?? [];
40-
const token = path[parent.length].toLowerCase();
40+
const token = result.path[parent.length].toLowerCase();
4141
const limit = token.length < 6 ? 1 : 2;
4242
return helpRecoveryCandidates(parent).map(candidate => ({
4343
path: candidate.path,

‎src/cli/help.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,10 @@ export function printSubcommandUsage(
163163
}
164164
}
165165
if (capability.details?.length) write(`\n${capability.details.join("\n")}`);
166+
if (result.children.length) {
167+
write("\nDeclared commands (incomplete):");
168+
for (const child of result.children) write(` ocx help ${child.command.join(" ")} ${child.summary}`);
169+
}
166170
if (capability.usage === undefined) {
167171
write("\nCapability metadata is incomplete; this is not the full operand grammar.");
168172
}

‎tests/ci-workflows/skill-ocx-generated.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,29 @@ describe("generated operating-skill chapter contract", () => {
241241
});
242242
});
243243

244+
test("rendered flag tables retain enum choices, literal slashes and multiline meanings", () => {
245+
withGenerator(root => {
246+
const flags = [
247+
{ name: "--selection", value: "string", summary: "Choose alpha|beta|gamma." },
248+
{ name: "--path", value: "string", summary: "Use C:\\data\\* with left\\|right.\nNext line.\r\nFinal line." },
249+
{ name: "--optional", summary: "No explicit value kind." },
250+
];
251+
const result = renderFixture(root, `Object.assign(CAPABILITIES.find(cap => cap.command.join(" ") === "access key list"), { flags: ${JSON.stringify(flags)} });`);
252+
expect(result.status).toBe(0);
253+
const files = JSON.parse(result.stdout) as Record<string, string>;
254+
const markdown = files["01_surface_access-remote.md"]!.split("### `ocx access key list`\n")[1]!.split("\n### ")[0]!;
255+
const html = Bun.markdown.html(markdown);
256+
const rows = [...html.matchAll(/<tr>([\s\S]*?)<\/tr>/g)].map(row =>
257+
[...row[1]!.matchAll(/<td>([\s\S]*?)<\/td>/g)].map(cell => cell[1]!));
258+
const flagRows = rows.filter(row => row[0]?.startsWith("<code>--"));
259+
expect(flagRows).toEqual([
260+
["<code>--selection</code>", "string", "Choose alpha|beta|gamma."],
261+
["<code>--path</code>", "string", "Use C:\\data\\* with left\\|right.<br>Next line.<br>Final line."],
262+
["<code>--optional</code>", "", "No explicit value kind."],
263+
]);
264+
});
265+
});
266+
244267
test("unknown roots, duplicate invocations, anchor collisions and oversize chapters fail closed", () => {
245268
withGenerator((root) => {
246269
for (const [mutation, message] of [

‎tests/cli/cli-help-paths.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,26 @@ describe("explicit CLI help paths", () => {
111111
expect(result.stdout).not.toContain("Usage:");
112112
});
113113

114+
test("runnable capability parents retain their usage and expose deeper help", () => {
115+
const path = ["access", "key"];
116+
const result = resolveHelpPath(path);
117+
expect(result.kind).toBe("capability");
118+
if (result.kind !== "capability") throw new Error("expected capability help");
119+
expect(result.children.map(child => child.command.join(" "))).toContain("access key list");
120+
expect(result.children.map(child => child.command.join(" "))).toContain("access key rotate commit");
121+
expect(result.children.some(child => child.command.length <= path.length)).toBe(false);
122+
const output = help(["help", ...path]);
123+
expect(output.status).toBe(0);
124+
expect(output.stderr).toBe("");
125+
expect(output.stdout).toContain("Usage: ocx access key list [--json]");
126+
expect(output.stdout).toContain("Declared commands (incomplete)");
127+
expect(output.stdout).toContain("ocx help access key list");
128+
expect(output.stdout).toContain("ocx help access key rotate commit");
129+
expect(output.stdout).toContain("Parent help: ocx help access");
130+
const leaf = resolveHelpPath(["access", "key", "list"]);
131+
expect(leaf).toMatchObject({ kind: "capability", children: [] });
132+
});
133+
114134
test("undeclared detail does not claim runtime grammar is invalid", () => {
115135
for (const [path, parent] of [
116136
[["service", "not-declared"], "service"],
@@ -153,6 +173,40 @@ describe("explicit CLI help paths", () => {
153173
expect(resolveHelpPath(["account", "list"]).kind).toBe("capability");
154174
});
155175

176+
test("access aliases resolve nested help without changing exact root help", () => {
177+
const root = resolveHelpPath(["api-key"]);
178+
expect(root).toMatchObject({ kind: "entry", entry: { name: "api-key" }, canonicalName: "access key" });
179+
const rootOutput = help(["help", "api-key"]);
180+
expect(rootOutput.status).toBe(0);
181+
expect(rootOutput.stdout).toContain("Usage: ocx api-key ");
182+
expect(rootOutput.stdout).toContain("Canonical help: ocx help access key");
183+
expect(rootOutput.stdout).toContain("ocx help access key list");
184+
const canonical = help(["help", "access", "key", "remove"]);
185+
expect(canonical.status).toBe(0);
186+
for (const path of [["api-key", "delete"], ["api-key", "remove"], ["access", "keys", "delete"], ["access", "key", "delete"]]) {
187+
const before = [...path];
188+
expect(resolveHelpPath(path)).toMatchObject({ kind: "capability", path: ["access", "key", "remove"] });
189+
expect(path).toEqual(before);
190+
for (const args of [["help", ...path], [...path, "--help"]]) {
191+
const output = help(args);
192+
expect(output.status).toBe(0);
193+
expect(output.stderr).toBe("");
194+
expect(output.stdout).toBe(canonical.stdout);
195+
}
196+
}
197+
const rotate = help(["help", "api-key", "rotate", "commit"]);
198+
expect(rotate.status).toBe(0);
199+
expect(rotate.stdout).toContain("Parent help: ocx help access key rotate");
200+
const operand = ["access", "keys", "get", "delete"];
201+
expect(resolveHelpPath(operand)).toMatchObject({
202+
kind: "unavailable", path: ["access", "key", "get", "delete"], parent: ["access", "key", "get"],
203+
});
204+
expect(operand).toEqual(["access", "keys", "get", "delete"]);
205+
for (const path of [["access", "delete"], ["provider", "delete"], ["access", "key", "rotate", "delete"]]) {
206+
expect(resolveHelpPath(path)).toMatchObject({ kind: "unavailable", path });
207+
}
208+
});
209+
156210
test("help lookup and rendering preserve machine capability JSON", async () => {
157211
const metadata = JSON.stringify({ CAPABILITIES, HEAD_CAPABILITIES });
158212
const lines: string[] = [];

‎tests/cli/cli-help-recovery.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,28 @@ describe("CLI help recovery", () => {
7575
expect(suggestHelpPaths(["internla"])).toEqual([]);
7676
});
7777

78+
test("access alias recovery uses canonical depth and stays deterministic", () => {
79+
expect(helpRecoveryCandidates(["api-key"])).toEqual(helpRecoveryCandidates(["access", "key"]));
80+
expect(helpRecoveryCandidates(["access", "keys"])).toEqual(helpRecoveryCandidates(["access", "key"]));
81+
for (const prefix of [["api-key"], ["access", "keys"], ["access", "key"]]) {
82+
expect(suggestHelpPaths([...prefix, "lisst"])).toEqual([["access", "key", "list"]]);
83+
expect(suggestHelpPaths([...prefix, "delet"])).toEqual([["access", "key", "remove"]]);
84+
expect(suggestHelpPaths([...prefix, "rotate", "commti"])).toEqual([["access", "key", "rotate", "commit"]]);
85+
expect(formatHelpRecovery([...prefix, "lisst"])).toBe(
86+
"Detailed help unavailable for the requested topic.\nDid you mean:\n ocx help access key list\nSee: ocx help access key");
87+
}
88+
expect(suggestHelpPaths(["api-ke"])).toEqual([["access", "key"]]);
89+
expect(suggestHelpPaths(["access", "kyes"])).toEqual([["access", "key"]]);
90+
expect(suggestHelpPaths(["api-key", "qzxv"])).toEqual([]);
91+
expect(suggestHelpPaths(["api-key", "lisst", "private\u001b[2J"])).toEqual([]);
92+
expect(suggestHelpPaths(["api-key", "lisst", ...Array(6).fill("operand")])).toEqual([]);
93+
const result = cli(["help", "api-key", "lisst"]);
94+
expect(result.status).toBe(1);
95+
expect(result.stdout).toBe("");
96+
expect(result.stderr).toBe(formatHelpRecovery(["api-key", "lisst"]) + "\n");
97+
expect(result.stderr).not.toContain("TypeError");
98+
});
99+
78100
test("matching rejects unsafe tokens and excessive depth without truncating to candidates", () => {
79101
for (const token of ["mo", "modles\u001b", "modles\n", "modles\u0085", "modles\u2028", "mödles", "modles" + "x".repeat(59)]) {
80102
expect(suggestHelpPaths([token])).toEqual([]);

0 commit comments

Comments
 (0)