@hop-top/kit 0.5.0-alpha.5 → 0.5.0-alpha.7
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/CHANGELOG.md +43 -0
- package/LICENSE-cobra.txt +174 -0
- package/NOTICE +15 -0
- package/README.md +10 -10
- package/dist/{alias-BOj0-VAr.d.ts → alias-BsJ2jGqQ.d.ts} +9 -1
- package/dist/alias.d.ts +1 -1
- package/dist/alias.js +4 -2
- package/dist/chunk-263IZ6Z6.js +915 -0
- package/dist/{chunk-S45UHXQF.js → chunk-DIDN4X5C.js} +8 -6
- package/dist/{chunk-ZC5TZYZJ.js → chunk-GHPJJV5L.js} +7 -3
- package/dist/chunk-JKMQSAJP.js +174 -0
- package/dist/chunk-JZ22ZUFA.js +1131 -0
- package/dist/chunk-NLMS7HGP.js +178 -0
- package/dist/chunk-QQQYCWSC.js +240 -0
- package/dist/chunk-XJTRY453.js +868 -0
- package/dist/{cli-8rfITnv4.d.ts → cli-C5B5tnpA.d.ts} +1 -60
- package/dist/cli.d.ts +2 -1
- package/dist/cli.js +5 -3
- package/dist/completion-sDKVXPUL.d.ts +109 -0
- package/dist/completion-values-By-mnjNt.d.ts +142 -0
- package/dist/completion-values.d.ts +1 -0
- package/dist/completion-values.js +29 -0
- package/dist/completion.d.ts +3 -0
- package/dist/completion.js +34 -0
- package/dist/compliance-AxFf-uMy.d.ts +60 -0
- package/dist/compliance.d.ts +1 -0
- package/dist/compliance.js +17 -0
- package/dist/config-CaK60ByQ.d.ts +241 -0
- package/dist/config.d.ts +1 -1
- package/dist/config.js +4 -2
- package/dist/{index-DEyjGoo2.d.ts → index-DCe1boBz.d.ts} +1 -1
- package/dist/index.d.ts +10 -4
- package/dist/index.js +40 -20
- package/dist/log-CkaxMX3U.d.ts +115 -0
- package/dist/log.d.ts +2 -0
- package/dist/log.js +14 -0
- package/dist/parity-CvMuYcVI.d.ts +61 -0
- package/dist/toolspec-UrWnoJ3Y.d.ts +336 -0
- package/dist/toolspec.d.ts +2 -0
- package/dist/toolspec.js +36 -0
- package/dist/tui/index.d.ts +3 -2
- package/package.json +43 -3
- package/src/alias.test.ts +110 -1
- package/src/alias.ts +19 -4
- package/src/cli.ts +5 -0
- package/src/completion-scripts.ts +16 -0
- package/src/completion-values.test.ts +70 -10
- package/src/completion-values.ts +170 -66
- package/src/completion.conformance.test.ts +297 -0
- package/src/completion.test.ts +256 -145
- package/src/completion.ts +764 -121
- package/src/config-merge.test.ts +425 -0
- package/src/config.test.ts +41 -0
- package/src/config.ts +265 -18
- package/src/index.test.ts +2 -1
- package/src/index.ts +8 -1
- package/src/log.test.ts +270 -1
- package/src/log.ts +172 -44
- package/src/published-types.test.ts +18 -0
- package/src/toolspec-internal.ts +197 -0
- package/src/toolspec-manifest.test.ts +82 -0
- package/src/toolspec-manifest.ts +404 -0
- package/src/toolspec-spec-schemas.ts +12 -0
- package/src/toolspec-spec.test.ts +273 -0
- package/src/toolspec-spec.ts +458 -0
- package/src/toolspec.from-command.test.ts +216 -0
- package/src/toolspec.ts +159 -0
- package/test/toolspec/fixture.ts +73 -0
- package/dist/chunk-IQXEISMC.js +0 -142
- package/dist/config-Bm9fBXch.d.ts +0 -134
|
@@ -0,0 +1,458 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Port of Go's `<tool> spec` subcommand and `spec coverage`
|
|
3
|
+
* (go/ai/toolspec/cli/spec_command.go, coverage.go,
|
|
4
|
+
* coverage_command.go). Output bytes for json / kit-manifest are
|
|
5
|
+
* pinned against Go by sdk/tests/cross-lang/fixtures/toolspec-spec*.json.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { EventEmitter } from "events";
|
|
9
|
+
import { Command, Option } from "commander";
|
|
10
|
+
import * as yaml from "js-yaml";
|
|
11
|
+
import { EXIT_CONFLICT, EXIT_GENERIC } from "./output/error.js";
|
|
12
|
+
import { render as renderOutput, type Format } from "./output.js";
|
|
13
|
+
import {
|
|
14
|
+
annotationsOf,
|
|
15
|
+
encodeGoJSON,
|
|
16
|
+
goFormat0,
|
|
17
|
+
isBuiltin,
|
|
18
|
+
isRunnable,
|
|
19
|
+
pflagTypes,
|
|
20
|
+
walkCommands,
|
|
21
|
+
} from "./toolspec-internal.js";
|
|
22
|
+
import {
|
|
23
|
+
buildManifest,
|
|
24
|
+
negotiateSchemaVersion,
|
|
25
|
+
renderManifestJSON,
|
|
26
|
+
SCHEMA_VERSION_ENV,
|
|
27
|
+
type Manifest,
|
|
28
|
+
} from "./toolspec-manifest.js";
|
|
29
|
+
import {
|
|
30
|
+
COVERAGE_REPORT_OUTPUT_SCHEMA,
|
|
31
|
+
MANIFEST_OUTPUT_SCHEMA,
|
|
32
|
+
} from "./toolspec-spec-schemas.js";
|
|
33
|
+
|
|
34
|
+
/** Annotation marking kit's spec subcommands (Go specCommandAnnotation). */
|
|
35
|
+
export const SPEC_COMMAND_ANNOTATION = "kit/spec-command";
|
|
36
|
+
|
|
37
|
+
const KIT_MANIFEST = "kit-manifest";
|
|
38
|
+
const KIT_MANIFEST_ALIASES = ["kit", "manifest"];
|
|
39
|
+
const LEGACY_FORMATS = ["json", "yaml", "table", "csv", "text"];
|
|
40
|
+
|
|
41
|
+
export interface RegisterSpecOptions {
|
|
42
|
+
/** Depth-1 verbs the tool reserves; "spec" is always added. */
|
|
43
|
+
reserved?: Iterable<string>;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
type Annotated = Command & { annotations?: Record<string, string> };
|
|
47
|
+
|
|
48
|
+
/** Value and whether it was given on the command line (pflag Changed). */
|
|
49
|
+
function formatFlag(cmd: Command): [string, boolean] {
|
|
50
|
+
const v = cmd.optsWithGlobals<{ format?: unknown }>().format;
|
|
51
|
+
const src = cmd.getOptionValueSourceWithGlobals("format");
|
|
52
|
+
return [typeof v === "string" ? v : "", src === "cli"];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** yaml with JSON-projected (snake_case) keys; strings double-quoted. */
|
|
56
|
+
function toYAML(v: unknown): string {
|
|
57
|
+
return yaml.dump(v, { quotingType: '"', lineWidth: -1 });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function manifestYAML(m: Manifest): string {
|
|
61
|
+
const projected = {
|
|
62
|
+
...m,
|
|
63
|
+
commands: m.commands.map((c) =>
|
|
64
|
+
c.output_schema === undefined
|
|
65
|
+
? c
|
|
66
|
+
: { ...c, output_schema: JSON.parse(c.output_schema) as unknown },
|
|
67
|
+
),
|
|
68
|
+
};
|
|
69
|
+
return toYAML(projected);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Attach a `spec` subcommand emitting the tool's capability manifest
|
|
74
|
+
* (Go RegisterSpecCommand). Call once after registering every
|
|
75
|
+
* command.
|
|
76
|
+
*
|
|
77
|
+
* - `--format`: `kit-manifest` (default; aliases `kit`, `manifest`)
|
|
78
|
+
* and `json` emit Go-identical JSON; `yaml` emits the same document
|
|
79
|
+
* as YAML; `table`/`csv`/`text` emit nothing, as Go does today.
|
|
80
|
+
* The program's global `--format` is used when it has one,
|
|
81
|
+
* otherwise spec adds its own.
|
|
82
|
+
* - `--version`: print only the schema version.
|
|
83
|
+
* - `--include-deprecated`: list deprecated commands too.
|
|
84
|
+
*
|
|
85
|
+
* schemaVersion is a floor: each run resolves the emitted version
|
|
86
|
+
* against KIT_TOOLSPEC_SCHEMA (negotiateSchemaVersion).
|
|
87
|
+
*
|
|
88
|
+
* commander parses a program's own options anywhere on the line, so
|
|
89
|
+
* a program-level `--version` (commander `.version()`, which
|
|
90
|
+
* createCLI sets) would answer `spec --version` with the tool
|
|
91
|
+
* version. The program's version listener is wrapped so a literal
|
|
92
|
+
* `--version` is forwarded to spec when spec is the command being
|
|
93
|
+
* executed; `tool --version`, `-v`, and `--version` on any other
|
|
94
|
+
* command keep commander's behaviour. See forwardVersionToSpec.
|
|
95
|
+
*/
|
|
96
|
+
export function registerSpecCommand(
|
|
97
|
+
program: Command,
|
|
98
|
+
schemaVersion: string,
|
|
99
|
+
opts: RegisterSpecOptions = {},
|
|
100
|
+
): Command {
|
|
101
|
+
const reserved = [...(opts.reserved ?? []), "spec"];
|
|
102
|
+
const tool = program.name();
|
|
103
|
+
|
|
104
|
+
const spec = new Command("spec")
|
|
105
|
+
.summary("Emit machine-readable capability manifest")
|
|
106
|
+
.description(
|
|
107
|
+
"Emit the tool's full capability manifest as JSON/YAML/table. " +
|
|
108
|
+
"Agents consume this for capability negotiation and dispatch. " +
|
|
109
|
+
"--version prints only the schema version.",
|
|
110
|
+
)
|
|
111
|
+
.option("--version", "Print the schema version only (capability negotiation)")
|
|
112
|
+
.option(
|
|
113
|
+
"--include-deprecated",
|
|
114
|
+
"Include deprecated commands in the manifest (default: hidden)",
|
|
115
|
+
);
|
|
116
|
+
if (!program.options.some((o) => o.long === "--format")) {
|
|
117
|
+
spec.option("--format <format>", "Output format");
|
|
118
|
+
}
|
|
119
|
+
(spec as Annotated).annotations = {
|
|
120
|
+
"kit/side-effect": "read",
|
|
121
|
+
"kit/idempotent": "yes",
|
|
122
|
+
[SPEC_COMMAND_ANNOTATION]: "true",
|
|
123
|
+
"kit/top-level-verb": "true",
|
|
124
|
+
"kit/output-schema": MANIFEST_OUTPUT_SCHEMA,
|
|
125
|
+
"kit/output-schema-version": schemaVersion,
|
|
126
|
+
"kit/examples": JSON.stringify([
|
|
127
|
+
{ title: "Full capabilities", command: `${tool} spec --format json` },
|
|
128
|
+
{ title: "Schema probe", command: `${tool} spec --version` },
|
|
129
|
+
{ title: "Filter to old clients", command: `${tool} spec --api-version=1.0` },
|
|
130
|
+
]),
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
let versionForwarded = false;
|
|
134
|
+
forwardVersionToSpec(program, spec, () => {
|
|
135
|
+
versionForwarded = true;
|
|
136
|
+
}, () => {
|
|
137
|
+
versionForwarded = false;
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
spec.action(function (this: Command) {
|
|
141
|
+
const out = (s: string): void => this.configureOutput().writeOut!(s);
|
|
142
|
+
const resolved = negotiateSchemaVersion(
|
|
143
|
+
schemaVersion,
|
|
144
|
+
process.env[SCHEMA_VERSION_ENV] ?? "",
|
|
145
|
+
);
|
|
146
|
+
const local = this.opts<{ version?: boolean; includeDeprecated?: boolean }>();
|
|
147
|
+
const [given, changed] = formatFlag(this);
|
|
148
|
+
const format = changed ? given : "";
|
|
149
|
+
|
|
150
|
+
if (local.version || versionForwarded) {
|
|
151
|
+
const vf = format === "" ? "json" : format;
|
|
152
|
+
if (vf === "json") {
|
|
153
|
+
out(encodeGoJSON({ schema_version: resolved }, 0, new Set()) + "\n");
|
|
154
|
+
} else if (vf === "yaml") {
|
|
155
|
+
out(toYAML({ schema_version: resolved }));
|
|
156
|
+
} else {
|
|
157
|
+
out(resolved + "\n");
|
|
158
|
+
}
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
let outputFormat: string;
|
|
163
|
+
if (format === "" || format === KIT_MANIFEST || KIT_MANIFEST_ALIASES.includes(format)) {
|
|
164
|
+
outputFormat = "json";
|
|
165
|
+
} else if (LEGACY_FORMATS.includes(format)) {
|
|
166
|
+
outputFormat = format;
|
|
167
|
+
} else {
|
|
168
|
+
const valid = [KIT_MANIFEST, ...LEGACY_FORMATS].join(", ");
|
|
169
|
+
this.error(`unknown --format ${JSON.stringify(format)} (valid: ${valid})`, {
|
|
170
|
+
exitCode: EXIT_GENERIC,
|
|
171
|
+
code: "kit.spec.unknownFormat",
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const manifest = buildManifest(program, resolved, {
|
|
176
|
+
includeDeprecated: local.includeDeprecated === true,
|
|
177
|
+
reserved,
|
|
178
|
+
invokedCommand: this,
|
|
179
|
+
});
|
|
180
|
+
if (outputFormat === "json") out(renderManifestJSON(manifest));
|
|
181
|
+
else if (outputFormat === "yaml") out(manifestYAML(manifest));
|
|
182
|
+
// table/csv/text: the Manifest has no tabular projection; Go
|
|
183
|
+
// renders nothing for it, and so does this port.
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
registerCoverageCommand(spec, program, reserved);
|
|
187
|
+
program.addCommand(spec);
|
|
188
|
+
return spec;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// --- spec --version forwarding ---
|
|
192
|
+
|
|
193
|
+
const WRAPPED = new WeakSet<(...args: unknown[]) => void>();
|
|
194
|
+
|
|
195
|
+
/** The subcommand of cmd that args select, skipping known option values. */
|
|
196
|
+
function selectedSubcommand(cmd: Command, args: readonly string[]): [Command, string[]] | undefined {
|
|
197
|
+
const options = [cmd, ...ancestors(cmd)].flatMap((c) => c.options as readonly Option[]);
|
|
198
|
+
const find = (flag: string) =>
|
|
199
|
+
options.find((o) => o.long === flag || o.short === flag);
|
|
200
|
+
for (let i = 0; i < args.length; i++) {
|
|
201
|
+
const a = args[i];
|
|
202
|
+
if (a === "--") return undefined;
|
|
203
|
+
if (a.length > 1 && a.startsWith("-")) {
|
|
204
|
+
const long = a.startsWith("--");
|
|
205
|
+
const opt = find(long ? a.split("=")[0] : a.slice(0, 2));
|
|
206
|
+
const inline = long ? a.includes("=") : a.length > 2;
|
|
207
|
+
const next = args[i + 1];
|
|
208
|
+
if (
|
|
209
|
+
opt &&
|
|
210
|
+
!inline &&
|
|
211
|
+
(opt.required || (opt.optional && next !== undefined && !next.startsWith("-")))
|
|
212
|
+
) {
|
|
213
|
+
i++;
|
|
214
|
+
}
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
const sub = cmd.commands.find((c) => c.name() === a || c.aliases().includes(a));
|
|
218
|
+
return sub ? [sub, args.slice(i + 1)] : undefined;
|
|
219
|
+
}
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function ancestors(cmd: Command): Command[] {
|
|
224
|
+
const out: Command[] = [];
|
|
225
|
+
for (let c = cmd.parent; c; c = c.parent) out.push(c);
|
|
226
|
+
return out;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Route a literal `--version` to spec when spec is the executing
|
|
231
|
+
* command. The program's parseOptions (public) is wrapped per
|
|
232
|
+
* instance to see the user args at each parse; the program's
|
|
233
|
+
* `option:version` listeners (commander 15 registers one in
|
|
234
|
+
* `.version()`, emitted from parseOptions) are wrapped lazily there,
|
|
235
|
+
* so a `.version()` call after registerSpecCommand is covered too.
|
|
236
|
+
* When forwarding, the wrapped listener records the request instead
|
|
237
|
+
* of printing and exiting. commander internals relied on (pinned
|
|
238
|
+
* 15.0.0): the `option:<name>` event convention, that `.version()`
|
|
239
|
+
* reacts through such a listener, that the program's own
|
|
240
|
+
* parseOptions is invoked via `this` (so the instance override
|
|
241
|
+
* applies), and the EventEmitter base typed locally below.
|
|
242
|
+
*/
|
|
243
|
+
function forwardVersionToSpec(
|
|
244
|
+
program: Command,
|
|
245
|
+
spec: Command,
|
|
246
|
+
forward: () => void,
|
|
247
|
+
reset: () => void,
|
|
248
|
+
): void {
|
|
249
|
+
let forwarding = false;
|
|
250
|
+
const original = program.parseOptions.bind(program);
|
|
251
|
+
|
|
252
|
+
const wrapListeners = (): void => {
|
|
253
|
+
const versionOpt = (program.options as readonly Option[]).find(
|
|
254
|
+
(o) => o.long === "--version",
|
|
255
|
+
);
|
|
256
|
+
if (!versionOpt) return;
|
|
257
|
+
const event = `option:${versionOpt.name()}`;
|
|
258
|
+
// commander 15's Command extends EventEmitter at runtime; its
|
|
259
|
+
// typings only declare on(), so the emitter surface is typed here.
|
|
260
|
+
const emitter = program as unknown as EventEmitter;
|
|
261
|
+
for (const l of emitter.listeners(event) as ((...a: unknown[]) => void)[]) {
|
|
262
|
+
if (WRAPPED.has(l)) continue;
|
|
263
|
+
const wrapped = function (this: unknown, ...a: unknown[]): void {
|
|
264
|
+
if (forwarding) {
|
|
265
|
+
forward();
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
l.apply(this, a);
|
|
269
|
+
};
|
|
270
|
+
WRAPPED.add(wrapped);
|
|
271
|
+
emitter.removeListener(event, l);
|
|
272
|
+
emitter.on(event, wrapped);
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
program.parseOptions = (args: string[]) => {
|
|
277
|
+
reset();
|
|
278
|
+
wrapListeners();
|
|
279
|
+
let executing: Command = program;
|
|
280
|
+
let rest: readonly string[] = args;
|
|
281
|
+
for (let sel = selectedSubcommand(executing, rest); sel; sel = selectedSubcommand(executing, rest)) {
|
|
282
|
+
[executing, rest] = sel;
|
|
283
|
+
}
|
|
284
|
+
forwarding = executing === spec && args.includes("--version");
|
|
285
|
+
try {
|
|
286
|
+
return original(args);
|
|
287
|
+
} finally {
|
|
288
|
+
forwarding = false;
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// --- spec coverage ---
|
|
294
|
+
|
|
295
|
+
/** Go CoverageReport: annotation coverage over a command tree. */
|
|
296
|
+
export interface CoverageReport {
|
|
297
|
+
tool: string;
|
|
298
|
+
total: number;
|
|
299
|
+
annotated: number;
|
|
300
|
+
unannotated: number;
|
|
301
|
+
inferred: number;
|
|
302
|
+
malformed: number;
|
|
303
|
+
unannotated_paths?: string[];
|
|
304
|
+
malformed_paths?: string[];
|
|
305
|
+
measurable: boolean;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const KNOWN_SIDE_EFFECTS = new Set([
|
|
309
|
+
"read",
|
|
310
|
+
"write",
|
|
311
|
+
"write-local",
|
|
312
|
+
"write-shared",
|
|
313
|
+
"destructive",
|
|
314
|
+
"destructive-local",
|
|
315
|
+
"destructive-shared",
|
|
316
|
+
"interactive",
|
|
317
|
+
]);
|
|
318
|
+
|
|
319
|
+
const DESTRUCTIVE_NAMES = new Set(["delete", "remove", "rm", "destroy", "purge", "drop"]);
|
|
320
|
+
|
|
321
|
+
export interface CoverageOptions {
|
|
322
|
+
/** Depth-1 verbs the tool reserves (not measured). */
|
|
323
|
+
reserved?: Iterable<string>;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Measure kit/side-effect annotation coverage (Go CoverageOf):
|
|
328
|
+
* runnable commands, excluding framework builtins, reserved verbs and
|
|
329
|
+
* kit's spec commands. Deprecated and hidden commands count.
|
|
330
|
+
*/
|
|
331
|
+
export function coverageOf(program: Command, opts: CoverageOptions = {}): CoverageReport {
|
|
332
|
+
const rep: CoverageReport = {
|
|
333
|
+
tool: program.name(),
|
|
334
|
+
total: 0,
|
|
335
|
+
annotated: 0,
|
|
336
|
+
unannotated: 0,
|
|
337
|
+
inferred: 0,
|
|
338
|
+
malformed: 0,
|
|
339
|
+
measurable: false,
|
|
340
|
+
};
|
|
341
|
+
const unannotated: string[] = [];
|
|
342
|
+
const malformed: string[] = [];
|
|
343
|
+
|
|
344
|
+
walkCommands(program, opts.reserved, (cmd, parent, path, reserved) => {
|
|
345
|
+
const ann = annotationsOf(cmd);
|
|
346
|
+
if (!isRunnable(cmd) || isBuiltin(cmd, parent) || reserved) return;
|
|
347
|
+
if (ann[SPEC_COMMAND_ANNOTATION] === "true") return;
|
|
348
|
+
rep.total++;
|
|
349
|
+
const p = path.join(" ");
|
|
350
|
+
const raw = ann["kit/side-effect"] ?? "";
|
|
351
|
+
if (raw !== "" && !KNOWN_SIDE_EFFECTS.has(raw)) {
|
|
352
|
+
rep.malformed++;
|
|
353
|
+
malformed.push(`${p}=${JSON.stringify(raw)}`);
|
|
354
|
+
unannotated.push(p);
|
|
355
|
+
} else if (raw === "") {
|
|
356
|
+
if (DESTRUCTIVE_NAMES.has(cmd.name())) rep.inferred++;
|
|
357
|
+
rep.unannotated++;
|
|
358
|
+
unannotated.push(p);
|
|
359
|
+
} else {
|
|
360
|
+
rep.annotated++;
|
|
361
|
+
}
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
rep.unannotated += rep.malformed;
|
|
365
|
+
if (unannotated.length > 0) rep.unannotated_paths = unannotated.sort();
|
|
366
|
+
if (malformed.length > 0) rep.malformed_paths = malformed.sort();
|
|
367
|
+
rep.measurable = rep.total > 0;
|
|
368
|
+
// Re-insert measurable last so encoded key order matches Go.
|
|
369
|
+
const { measurable, ...rest } = rep;
|
|
370
|
+
return { ...rest, measurable };
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function coveragePercent(r: CoverageReport): number {
|
|
374
|
+
return r.total === 0 ? 0 : (r.annotated / r.total) * 100;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function coverageMeets(r: CoverageReport, threshold: number): boolean {
|
|
378
|
+
if (threshold <= 0) return true;
|
|
379
|
+
if (!r.measurable) return false;
|
|
380
|
+
return coveragePercent(r) >= threshold;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** Collects TS output-registry renders into a string. */
|
|
384
|
+
function captureRender(format: string, v: unknown): string {
|
|
385
|
+
let buf = "";
|
|
386
|
+
const sink = {
|
|
387
|
+
write(chunk: unknown): boolean {
|
|
388
|
+
buf += String(chunk);
|
|
389
|
+
return true;
|
|
390
|
+
},
|
|
391
|
+
} as unknown as NodeJS.WritableStream;
|
|
392
|
+
renderOutput(sink, format as Format, v);
|
|
393
|
+
return buf;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function registerCoverageCommand(spec: Command, program: Command, reserved: string[]): void {
|
|
397
|
+
const tool = program.name();
|
|
398
|
+
const min = new Option(
|
|
399
|
+
"--min <percent>",
|
|
400
|
+
"Minimum coverage percentage; exit CONFLICT (4) below it (0 disables the gate)",
|
|
401
|
+
)
|
|
402
|
+
.argParser((v: string) => {
|
|
403
|
+
const n = Number(v);
|
|
404
|
+
if (v.trim() === "" || Number.isNaN(n)) {
|
|
405
|
+
throw new Error(`invalid argument "${v}" for "--min" flag`);
|
|
406
|
+
}
|
|
407
|
+
return n;
|
|
408
|
+
})
|
|
409
|
+
.default(0);
|
|
410
|
+
pflagTypes.set(min, "float64");
|
|
411
|
+
|
|
412
|
+
const cmd = new Command("coverage")
|
|
413
|
+
.summary("Report kit/side-effect annotation coverage")
|
|
414
|
+
.description(
|
|
415
|
+
"Report how many of this tool's commands declare a " +
|
|
416
|
+
"kit/side-effect class, list the ones that do not, and " +
|
|
417
|
+
"exit non-zero when coverage falls below --min.\n\n" +
|
|
418
|
+
"An unannotated command is not a read-only command: it " +
|
|
419
|
+
"is one kit knows nothing about, and every safety gate " +
|
|
420
|
+
"that consumes the manifest must fail closed on it. This " +
|
|
421
|
+
"report is how an adopter finds and closes that gap, and " +
|
|
422
|
+
"how CI keeps it closed.",
|
|
423
|
+
)
|
|
424
|
+
.addOption(min);
|
|
425
|
+
(cmd as Annotated).annotations = {
|
|
426
|
+
"kit/side-effect": "read",
|
|
427
|
+
"kit/idempotent": "yes",
|
|
428
|
+
"kit/exit-codes": "OK,CONFLICT",
|
|
429
|
+
[SPEC_COMMAND_ANNOTATION]: "true",
|
|
430
|
+
"kit/output-schema": COVERAGE_REPORT_OUTPUT_SCHEMA,
|
|
431
|
+
"kit/output-schema-version": "1.0",
|
|
432
|
+
"kit/examples": JSON.stringify([
|
|
433
|
+
{ title: "See the gap", command: `${tool} spec coverage --format json` },
|
|
434
|
+
{ title: "Gate in CI", command: `${tool} spec coverage --min 80` },
|
|
435
|
+
]),
|
|
436
|
+
};
|
|
437
|
+
|
|
438
|
+
cmd.action(function (this: Command) {
|
|
439
|
+
const rep = coverageOf(program, { reserved });
|
|
440
|
+
const [given, changed] = formatFlag(this);
|
|
441
|
+
const format = changed && given !== "" ? given : "json";
|
|
442
|
+
const text =
|
|
443
|
+
format === "json" ? encodeGoJSON(rep, 0, new Set()) + "\n" : captureRender(format, rep);
|
|
444
|
+
this.configureOutput().writeOut!(text);
|
|
445
|
+
|
|
446
|
+
const threshold = this.opts<{ min: number }>().min;
|
|
447
|
+
if (coverageMeets(rep, threshold)) return;
|
|
448
|
+
const message = !rep.measurable
|
|
449
|
+
? `annotation coverage unmeasurable: no reflectable commands in ${JSON.stringify(rep.tool)} ` +
|
|
450
|
+
`(--min ${goFormat0(threshold)}% cannot be evaluated)`
|
|
451
|
+
: `annotation coverage ${goFormat0(coveragePercent(rep))}% (${rep.annotated}/${rep.total}) ` +
|
|
452
|
+
`is below --min ${goFormat0(threshold)}%; unannotated: ` +
|
|
453
|
+
(rep.unannotated_paths ?? []).join(", ");
|
|
454
|
+
this.error(message, { exitCode: EXIT_CONFLICT, code: "kit.spec.coverageBelowMin" });
|
|
455
|
+
});
|
|
456
|
+
|
|
457
|
+
spec.addCommand(cmd);
|
|
458
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import * as fs from "fs";
|
|
3
|
+
import * as os from "os";
|
|
4
|
+
import * as path from "path";
|
|
5
|
+
import { Command, Option } from "commander";
|
|
6
|
+
import {
|
|
7
|
+
findCommand,
|
|
8
|
+
loadToolSpec,
|
|
9
|
+
toolSpecFromCommand,
|
|
10
|
+
validateToolSpec,
|
|
11
|
+
} from "./toolspec";
|
|
12
|
+
|
|
13
|
+
function buildProgram(): Command {
|
|
14
|
+
const program = new Command("spaced").version("1.0.0");
|
|
15
|
+
program.option("--format <fmt>", "Output format");
|
|
16
|
+
|
|
17
|
+
program
|
|
18
|
+
.command("launch <mission> [vehicle]")
|
|
19
|
+
.alias("go")
|
|
20
|
+
.description("Launch a mission")
|
|
21
|
+
.option("--payload <items...>", "Payload manifest")
|
|
22
|
+
.option("-o, --output <file>", "Write JSON report to file")
|
|
23
|
+
.option("--dry-run", "Simulate launch without executing")
|
|
24
|
+
.addOption(new Option("--orbit <orbit>", "Target orbit").makeOptionMandatory())
|
|
25
|
+
.addOption(new Option("--secret", "internal").hideHelp())
|
|
26
|
+
.action(() => {});
|
|
27
|
+
|
|
28
|
+
const mission = program.command("mission").description("Mission catalog");
|
|
29
|
+
mission.command("list").description("List missions").action(() => {});
|
|
30
|
+
mission.command("purge").description("Purge catalog").action(() => {});
|
|
31
|
+
|
|
32
|
+
program.command("internal", { hidden: true }).action(() => {});
|
|
33
|
+
return program;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
describe("toolSpecFromCommand", () => {
|
|
37
|
+
it("projects names, descriptions, aliases and children", () => {
|
|
38
|
+
const spec = toolSpecFromCommand(buildProgram());
|
|
39
|
+
expect(spec.name).toBe("spaced");
|
|
40
|
+
expect(spec.commands.map((c) => c.name)).toEqual(["launch", "mission"]);
|
|
41
|
+
|
|
42
|
+
const launch = findCommand(spec, "launch")!;
|
|
43
|
+
expect(launch.short).toBe("Launch a mission");
|
|
44
|
+
expect(launch.aliases).toEqual(["go"]);
|
|
45
|
+
|
|
46
|
+
const mission = findCommand(spec, "mission")!;
|
|
47
|
+
expect(mission.children!.map((c) => c.name)).toEqual(["list", "purge"]);
|
|
48
|
+
expect(mission.children![0].short).toBe("List missions");
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it("omits hidden commands and hidden options", () => {
|
|
52
|
+
const spec = toolSpecFromCommand(buildProgram());
|
|
53
|
+
expect(findCommand(spec, "internal")).toBeUndefined();
|
|
54
|
+
const launch = findCommand(spec, "launch")!;
|
|
55
|
+
expect(launch.flags!.some((f) => f.name === "secret")).toBe(false);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it("projects flags with Go walker naming", () => {
|
|
59
|
+
const spec = toolSpecFromCommand(buildProgram());
|
|
60
|
+
const flags = findCommand(spec, "launch")!.flags!;
|
|
61
|
+
expect(flags).toEqual([
|
|
62
|
+
{ name: "payload", type: "stringSlice", description: "Payload manifest" },
|
|
63
|
+
{
|
|
64
|
+
name: "output",
|
|
65
|
+
short: "o",
|
|
66
|
+
type: "string",
|
|
67
|
+
description: "Write JSON report to file",
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
name: "dry-run",
|
|
71
|
+
type: "bool",
|
|
72
|
+
description: "Simulate launch without executing",
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
name: "orbit",
|
|
76
|
+
type: "string",
|
|
77
|
+
description: "Target orbit",
|
|
78
|
+
required: true,
|
|
79
|
+
},
|
|
80
|
+
]);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it("puts root options on spec.flags", () => {
|
|
84
|
+
const spec = toolSpecFromCommand(buildProgram());
|
|
85
|
+
expect(spec.flags!.map((f) => f.name)).toEqual(["version", "format"]);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("projects positional arguments in order", () => {
|
|
89
|
+
const spec = toolSpecFromCommand(buildProgram());
|
|
90
|
+
expect(findCommand(spec, "launch")!.args).toEqual([
|
|
91
|
+
{ name: "mission", required: true },
|
|
92
|
+
{ name: "vehicle" },
|
|
93
|
+
]);
|
|
94
|
+
expect(findCommand(spec, "list")!.args).toBeUndefined();
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it("includes commands registered after construction", () => {
|
|
98
|
+
const program = buildProgram();
|
|
99
|
+
program.command("plugin-" + "dyn").description("dynamic").action(() => {});
|
|
100
|
+
const spec = toolSpecFromCommand(program);
|
|
101
|
+
expect(findCommand(spec, "plugin-dyn")!.short).toBe("dynamic");
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it("merges per-command annotations keyed by path", () => {
|
|
105
|
+
const spec = toolSpecFromCommand(buildProgram(), {
|
|
106
|
+
annotations: {
|
|
107
|
+
launch: {
|
|
108
|
+
contract: { idempotent: false, retryable: false },
|
|
109
|
+
safety: { level: "dangerous" },
|
|
110
|
+
previewModes: ["--dry-run"],
|
|
111
|
+
short: "Launch (annotated)",
|
|
112
|
+
},
|
|
113
|
+
"mission list": {
|
|
114
|
+
contract: { idempotent: true, retryable: true },
|
|
115
|
+
safety: { level: "safe" },
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
const launch = findCommand(spec, "launch")!;
|
|
120
|
+
expect(launch.safety).toEqual({ level: "dangerous" });
|
|
121
|
+
expect(launch.previewModes).toEqual(["--dry-run"]);
|
|
122
|
+
expect(launch.short).toBe("Launch (annotated)");
|
|
123
|
+
expect(launch.flags!.length).toBe(4);
|
|
124
|
+
const list = findCommand(spec, "list")!;
|
|
125
|
+
expect(list.contract).toEqual({ idempotent: true, retryable: true });
|
|
126
|
+
expect(findCommand(spec, "purge")!.safety).toBeUndefined();
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it("produces a spec that validates and defaults schemaVersion", () => {
|
|
130
|
+
const spec = toolSpecFromCommand(buildProgram());
|
|
131
|
+
expect(spec.schemaVersion).toBe("1");
|
|
132
|
+
expect(validateToolSpec(spec)).toEqual([]);
|
|
133
|
+
const custom = toolSpecFromCommand(buildProgram(), { schemaVersion: "2" });
|
|
134
|
+
expect(custom.schemaVersion).toBe("2");
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it("serializes without undefined keys", () => {
|
|
138
|
+
const spec = toolSpecFromCommand(buildProgram());
|
|
139
|
+
const list = findCommand(spec, "list")!;
|
|
140
|
+
expect(Object.keys(list).sort()).toEqual(["name", "short"]);
|
|
141
|
+
});
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
describe("toolSpecFromCommand exit codes", () => {
|
|
145
|
+
it("reads kit/exit-codes off the command, annotation map wins", () => {
|
|
146
|
+
const program = new Command("t");
|
|
147
|
+
const get = program.command("get").action(() => {});
|
|
148
|
+
(get as Command & { annotations?: Record<string, string> }).annotations = {
|
|
149
|
+
"kit/exit-codes": "OK, NOT_FOUND,TRANSIENT",
|
|
150
|
+
};
|
|
151
|
+
const put = program.command("put").action(() => {});
|
|
152
|
+
(put as Command & { annotations?: Record<string, string> }).annotations = {
|
|
153
|
+
"kit/exit-codes": "OK",
|
|
154
|
+
};
|
|
155
|
+
program.command("plain").action(() => {});
|
|
156
|
+
|
|
157
|
+
const spec = toolSpecFromCommand(program, {
|
|
158
|
+
annotations: { put: { exitCodes: ["OK", "CONFLICT"] } },
|
|
159
|
+
});
|
|
160
|
+
expect(findCommand(spec, "get")!.exitCodes).toEqual([
|
|
161
|
+
"OK",
|
|
162
|
+
"NOT_FOUND",
|
|
163
|
+
"TRANSIENT",
|
|
164
|
+
]);
|
|
165
|
+
expect(findCommand(spec, "put")!.exitCodes).toEqual(["OK", "CONFLICT"]);
|
|
166
|
+
expect(findCommand(spec, "plain")!.exitCodes).toBeUndefined();
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it("validateToolSpec rejects an empty exit-code symbol", () => {
|
|
170
|
+
const errors = validateToolSpec({
|
|
171
|
+
name: "t",
|
|
172
|
+
schemaVersion: "1",
|
|
173
|
+
commands: [{ name: "get", exitCodes: ["OK", ""] }],
|
|
174
|
+
});
|
|
175
|
+
expect(errors.some((e) => e.includes("exit code"))).toBe(true);
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
describe("loadToolSpec args/short/required", () => {
|
|
180
|
+
it("maps args, undeclared_args, short and flag required from YAML", () => {
|
|
181
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "toolspec-"));
|
|
182
|
+
const file = path.join(dir, "t.toolspec.yaml");
|
|
183
|
+
fs.writeFileSync(
|
|
184
|
+
file,
|
|
185
|
+
[
|
|
186
|
+
"name: t",
|
|
187
|
+
'schema_version: "1"',
|
|
188
|
+
"commands:",
|
|
189
|
+
" - name: get",
|
|
190
|
+
" short: Get a thing",
|
|
191
|
+
" undeclared_args: true",
|
|
192
|
+
" exit_codes: [OK, NOT_FOUND]",
|
|
193
|
+
" args:",
|
|
194
|
+
" - name: id",
|
|
195
|
+
" required: true",
|
|
196
|
+
" - name: field",
|
|
197
|
+
" flags:",
|
|
198
|
+
" - name: out",
|
|
199
|
+
" required: true",
|
|
200
|
+
].join("\n"),
|
|
201
|
+
);
|
|
202
|
+
try {
|
|
203
|
+
const get = loadToolSpec(file).commands[0];
|
|
204
|
+
expect(get.short).toBe("Get a thing");
|
|
205
|
+
expect(get.undeclaredArgs).toBe(true);
|
|
206
|
+
expect(get.exitCodes).toEqual(["OK", "NOT_FOUND"]);
|
|
207
|
+
expect(get.args).toEqual([
|
|
208
|
+
{ name: "id", required: true },
|
|
209
|
+
{ name: "field", required: undefined },
|
|
210
|
+
]);
|
|
211
|
+
expect(get.flags![0].required).toBe(true);
|
|
212
|
+
} finally {
|
|
213
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
});
|