@hop-top/kit 0.5.0-alpha.10 → 0.5.0-alpha.11
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 +24 -0
- package/README.md +4 -4
- package/dist/alias.js +3 -3
- package/dist/{chunk-T46YPHKN.js → chunk-4FMALWYB.js} +45 -45
- package/dist/{chunk-WWUKGJB5.js → chunk-4GPCWBBA.js} +60 -7
- package/dist/{chunk-JZ22ZUFA.js → chunk-65VPWMPV.js} +4 -1
- package/dist/{chunk-YGYQUFGY.js → chunk-BXJ2J27B.js} +10 -10
- package/dist/chunk-CXBZTONY.js +65 -0
- package/dist/{chunk-K7VCKJ27.js → chunk-EE4M2UOF.js} +8 -4
- package/dist/{chunk-72XZWQX7.js → chunk-GFRAYYRD.js} +475 -162
- package/dist/{chunk-2JV3A7OP.js → chunk-IVQHLI56.js} +6 -10
- package/dist/{chunk-NLMS7HGP.js → chunk-IZ6Q4SE3.js} +3 -3
- package/dist/chunk-MFVUENZR.js +1549 -0
- package/dist/{chunk-BLS2OBIQ.js → chunk-ML7D5DWY.js} +2 -2
- package/dist/{chunk-GGWJRWWA.js → chunk-RYKLVOVK.js} +7 -7
- package/dist/{chunk-QPUCXQXT.js → chunk-T6OZMPPV.js} +2 -1
- package/dist/{chunk-MUIQVU6E.js → chunk-VGOA5Y7S.js} +11 -11
- package/dist/{chunk-ABQSE7AI.js → chunk-VWGP4NVJ.js} +38 -38
- package/dist/cli-RSRk1M36.d.ts +707 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +60 -5
- package/dist/completion.js +2 -2
- package/dist/{index-DCe1boBz.d.ts → index-CGE5yLBj.d.ts} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +22 -22
- package/dist/llm-anthropic.js +5 -5
- package/dist/llm-openai.js +5 -5
- package/dist/llm.js +3 -3
- package/dist/log.js +3 -3
- package/dist/mcp/index.js +3 -2
- package/dist/output.js +2 -4
- package/dist/routellm.js +6 -6
- package/dist/toolspec.js +4 -4
- package/dist/tui/index.d.ts +2 -2
- package/dist/tui/index.js +3 -3
- package/dist/{upgrade-p_zh3pvV.d.ts → upgrade-C3RWGwRi.d.ts} +23 -0
- package/dist/upgrade.d.ts +1 -1
- package/dist/upgrade.js +2 -2
- package/package.json +1 -1
- package/src/cli.root.conformance.test.ts +166 -0
- package/src/cli.ts +39 -0
- package/src/completion.conformance.test.ts +3 -2
- package/src/completion.test.ts +12 -0
- package/src/completion.ts +8 -3
- package/src/delegation.test.ts +299 -0
- package/src/delegation.ts +807 -0
- package/src/mcp/bridge.test.ts +28 -0
- package/src/mcp/bridge.ts +5 -10
- package/src/plan.ts +89 -0
- package/src/policy.ts +472 -0
- package/src/sideeffect.ts +105 -0
- package/src/toolspec-manifest.ts +7 -2
- package/src/upgrade.test.ts +291 -0
- package/src/upgrade.ts +116 -7
- package/dist/chunk-GHPJJV5L.js +0 -613
- package/dist/chunk-IXVQ62NZ.js +0 -334
- package/dist/cli-C5B5tnpA.d.ts +0 -400
- package/dist/{chunk-PSFYJGDG.js → chunk-K7E34Q3A.js} +2 -2
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// Runs the delegation slice of the shared corpus in contracts/cli-root-v1.
|
|
2
|
+
// The vectors are the source of truth: a failure means this port drifted
|
|
3
|
+
// from the contract (Go is canonical), not that a vector should be edited.
|
|
4
|
+
//
|
|
5
|
+
// This port implements the delegation gates (--confirm, --confirm-token,
|
|
6
|
+
// --max-ops, --policy, --dry-run) and the side-effect inference. Every case
|
|
7
|
+
// is either replayed or listed in a skip table with a reason; a case that
|
|
8
|
+
// is neither fails the run, so nothing is skipped silently.
|
|
9
|
+
|
|
10
|
+
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
11
|
+
import { tmpdir } from 'node:os';
|
|
12
|
+
import { dirname, join } from 'node:path';
|
|
13
|
+
import { Command, CommanderError } from 'commander';
|
|
14
|
+
import { describe, expect, it } from 'vitest';
|
|
15
|
+
|
|
16
|
+
import { createCLI } from './cli';
|
|
17
|
+
import { dryRunApplied, noPrompt, scriptedPrompt } from './delegation';
|
|
18
|
+
import { defaultPolicyLoader } from './policy';
|
|
19
|
+
|
|
20
|
+
const CORPUS = join(__dirname, '..', '..', '..', 'contracts', 'cli-root-v1', 'vectors.json');
|
|
21
|
+
|
|
22
|
+
interface Flag { long: string; help?: string; type?: string }
|
|
23
|
+
interface Cmd {
|
|
24
|
+
name: string;
|
|
25
|
+
about: string;
|
|
26
|
+
side_effect?: string;
|
|
27
|
+
annotations?: Record<string, string>;
|
|
28
|
+
dry_run?: string;
|
|
29
|
+
kind?: string;
|
|
30
|
+
flags?: Flag[];
|
|
31
|
+
commands?: Cmd[];
|
|
32
|
+
}
|
|
33
|
+
interface Tree {
|
|
34
|
+
program: string;
|
|
35
|
+
commands: Cmd[];
|
|
36
|
+
fixtures?: Record<string, string>;
|
|
37
|
+
policy?: boolean;
|
|
38
|
+
}
|
|
39
|
+
interface Case {
|
|
40
|
+
name: string;
|
|
41
|
+
tree: string;
|
|
42
|
+
args: string[];
|
|
43
|
+
exit: number;
|
|
44
|
+
stdout?: string | null;
|
|
45
|
+
stdout_contains?: string[];
|
|
46
|
+
stderr_contains?: string[];
|
|
47
|
+
stderr_json?: Record<string, unknown>;
|
|
48
|
+
prompt_answer?: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const file = JSON.parse(readFileSync(CORPUS, 'utf8')) as { version: string; trees: Record<string, Tree>; cases: Case[] };
|
|
52
|
+
|
|
53
|
+
/** Trees the delegation slice replays; every other tree is skipped whole. */
|
|
54
|
+
const REPLAYED = new Set(['ops', 'infer']);
|
|
55
|
+
|
|
56
|
+
const TREE_SKIP =
|
|
57
|
+
'outside the delegation slice: needs root-flag, alias, validate, signature or config features this port lacks';
|
|
58
|
+
|
|
59
|
+
/** Cases of a replayed tree that need a feature the TS CLI lacks. */
|
|
60
|
+
const CASE_SKIP: Array<[RegExp, string]> = [
|
|
61
|
+
[/^(chdir|no chdir)/, '-C/--chdir resolver not ported'],
|
|
62
|
+
[/^config /, '-c/--config layering and the cfg command not ported'],
|
|
63
|
+
[/^flag validator/, 'flag validators not ported'],
|
|
64
|
+
[
|
|
65
|
+
/^a malformed annotation is not inferred over$/,
|
|
66
|
+
'TS validates side-effect tiers at run time with no disable_validate; Go runs this tree with validation off',
|
|
67
|
+
],
|
|
68
|
+
];
|
|
69
|
+
|
|
70
|
+
function skipReason(c: Case): string | undefined {
|
|
71
|
+
if (!REPLAYED.has(c.tree)) return TREE_SKIP;
|
|
72
|
+
return CASE_SKIP.find(([re]) => re.test(c.name))?.[1];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function addCmd(parent: Command, c: Cmd, prefix: string, ran: { value: boolean }): void {
|
|
76
|
+
const path = `${prefix} ${c.name}`.trim();
|
|
77
|
+
const cmd = parent.command(c.name).description(c.about);
|
|
78
|
+
cmd.exitOverride();
|
|
79
|
+
for (const f of c.flags ?? []) cmd.option(f.type === 'bool' ? `--${f.long}` : `--${f.long} <v>`, f.help ?? '');
|
|
80
|
+
const ann: Record<string, string> = { ...(c.annotations ?? {}) };
|
|
81
|
+
if (c.side_effect) ann['kit/side-effect'] = c.side_effect;
|
|
82
|
+
if (c.dry_run === 'opted-out') ann['kit/dry-run'] = 'opted-out';
|
|
83
|
+
(cmd as unknown as { annotations: Record<string, string> }).annotations = ann;
|
|
84
|
+
if ((c.commands ?? []).length > 0) {
|
|
85
|
+
for (const s of c.commands ?? []) addCmd(cmd, s, path, ran);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
cmd.argument('[args...]');
|
|
89
|
+
cmd.action(() => {
|
|
90
|
+
ran.value = true;
|
|
91
|
+
cmd.configureOutput().writeOut?.(`${JSON.stringify({ dry_run: dryRunApplied(cmd), path })}\n`);
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function run(c: Case): { code: number; out: string; err: string } {
|
|
96
|
+
const t = file.trees[c.tree]!;
|
|
97
|
+
const tmp = mkdtempSync(join(tmpdir(), 'cli-root-'));
|
|
98
|
+
const sub = (s: string): string => s.split('{tmp}').join(tmp);
|
|
99
|
+
const saved = process.env['XDG_CONFIG_HOME'];
|
|
100
|
+
try {
|
|
101
|
+
for (const [name, body] of Object.entries(t.fixtures ?? {})) {
|
|
102
|
+
const p = join(tmp, name);
|
|
103
|
+
if (name.endsWith('/')) mkdirSync(p, { recursive: true });
|
|
104
|
+
else {
|
|
105
|
+
mkdirSync(dirname(p), { recursive: true });
|
|
106
|
+
writeFileSync(p, sub(body));
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
process.env['XDG_CONFIG_HOME'] = join(tmp, 'xdg');
|
|
110
|
+
const { program } = createCLI({
|
|
111
|
+
name: t.program,
|
|
112
|
+
version: '1.2.3',
|
|
113
|
+
description: 'Kit app',
|
|
114
|
+
promptSource: c.prompt_answer !== undefined ? scriptedPrompt([c.prompt_answer]) : noPrompt,
|
|
115
|
+
policy: t.policy ? defaultPolicyLoader(t.program) : undefined,
|
|
116
|
+
});
|
|
117
|
+
let out = '';
|
|
118
|
+
let err = '';
|
|
119
|
+
program.exitOverride();
|
|
120
|
+
program.configureOutput({ writeOut: (s) => { out += s; }, writeErr: (s) => { err += s; } });
|
|
121
|
+
const ran = { value: false };
|
|
122
|
+
for (const cc of t.commands) addCmd(program, cc, '', ran);
|
|
123
|
+
let code = 0;
|
|
124
|
+
try {
|
|
125
|
+
program.parse(['node', t.program, ...c.args.map(sub)]);
|
|
126
|
+
} catch (e) {
|
|
127
|
+
if (!(e instanceof CommanderError)) throw e;
|
|
128
|
+
code = e.exitCode;
|
|
129
|
+
}
|
|
130
|
+
return { code, out, err };
|
|
131
|
+
} finally {
|
|
132
|
+
if (saved === undefined) delete process.env['XDG_CONFIG_HOME'];
|
|
133
|
+
else process.env['XDG_CONFIG_HOME'] = saved;
|
|
134
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
describe('cli-root-v1 corpus (delegation slice)', () => {
|
|
139
|
+
it('is version v1', () => expect(file.version).toBe('v1'));
|
|
140
|
+
|
|
141
|
+
const skipped: Array<[string, string]> = [];
|
|
142
|
+
for (const c of file.cases) {
|
|
143
|
+
const reason = skipReason(c);
|
|
144
|
+
if (reason) {
|
|
145
|
+
skipped.push([c.name, reason]);
|
|
146
|
+
it.skip(`${c.tree}: ${c.name} [skip: ${reason}]`, () => {});
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
it(`${c.tree}: ${c.name}`, () => {
|
|
150
|
+
const r = run(c);
|
|
151
|
+
expect(r.code, `exit (stderr ${r.err})`).toBe(c.exit);
|
|
152
|
+
if (typeof c.stdout === 'string') expect(r.out).toBe(c.stdout);
|
|
153
|
+
if (c.stdout === null) expect(r.out).toBe('');
|
|
154
|
+
for (const s of c.stdout_contains ?? []) expect(r.out).toContain(s);
|
|
155
|
+
for (const s of c.stderr_contains ?? []) expect(r.err).toContain(s.replace('{tmp}', ''));
|
|
156
|
+
if (c.stderr_json) {
|
|
157
|
+
const j = JSON.parse(r.err) as Record<string, unknown>;
|
|
158
|
+
for (const [k, v] of Object.entries(c.stderr_json)) expect(j[k]).toEqual(v);
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
it('every skip carries a reason', () => {
|
|
164
|
+
for (const [, reason] of skipped) expect(reason.length).toBeGreaterThan(0);
|
|
165
|
+
});
|
|
166
|
+
});
|
package/src/cli.ts
CHANGED
|
@@ -32,6 +32,21 @@ import { EXIT_USAGE } from './output/error.js';
|
|
|
32
32
|
import { install as installNetPolicy, setProcessOffline } from './netpolicy.js';
|
|
33
33
|
import { installCompletionRequest } from './completion.js';
|
|
34
34
|
import './output/builtins.js';
|
|
35
|
+
import { installDelegation, type PromptSource } from './delegation.js';
|
|
36
|
+
import type { PolicyLoader } from './policy.js';
|
|
37
|
+
export { controllingTTY, destructiveToken, dryRunApplied, installConfirmTokenFlag,
|
|
38
|
+
isDryRun, noPrompt, resolveConfirmMode, resolveDryRunPolicy,
|
|
39
|
+
scriptedPrompt } from './delegation.js';
|
|
40
|
+
export type { ConfirmMode, DryRunPolicy, PromptSource, Prompter } from './delegation.js';
|
|
41
|
+
export { Engine, KIT_DEFAULT_NAME, MaxOpsExceededError, defaultPolicyLoader,
|
|
42
|
+
kitDefault, loadNamedPolicy, loadPolicy, resolvePolicyPath } from './policy.js';
|
|
43
|
+
export type { Policy, PolicyLoader, Verdict } from './policy.js';
|
|
44
|
+
export { INFERRED_TIER, SIDE_EFFECT_TIERS, destructiveNames, gateSideEffect,
|
|
45
|
+
inferredDestructive, isDestructiveLike, isDestructiveName,
|
|
46
|
+
isWriteLike } from './sideeffect.js';
|
|
47
|
+
export type { SideEffect } from './sideeffect.js';
|
|
48
|
+
export { renderPlan } from './plan.js';
|
|
49
|
+
export type { Effect, Plan } from './plan.js';
|
|
35
50
|
export { ErrOffline, OfflineError, guardFetch, isOffline, isOfflineError,
|
|
36
51
|
withOffline } from './netpolicy.js';
|
|
37
52
|
export { HintSet, hintsEnabled, renderHints, active,
|
|
@@ -333,8 +348,24 @@ export interface CLIConfig {
|
|
|
333
348
|
noColor?: boolean;
|
|
334
349
|
hints?: boolean;
|
|
335
350
|
offline?: boolean;
|
|
351
|
+
/** Drop the root `--dry-run` flag; it is then never applied. */
|
|
352
|
+
dryRun?: boolean;
|
|
336
353
|
};
|
|
337
354
|
|
|
355
|
+
/**
|
|
356
|
+
* Resolves a named root `--policy <name>`; see {@link defaultPolicyLoader}
|
|
357
|
+
* for the `$XDG_CONFIG_HOME/<name>/policies/<policy>.yaml` loader. Unset
|
|
358
|
+
* wires none: only the reserved `kit-default` policy resolves.
|
|
359
|
+
*/
|
|
360
|
+
policy?: PolicyLoader;
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* The terminal the `--confirm` prompt asks on. Defaults to the
|
|
364
|
+
* controlling terminal (`/dev/tty`); with none, an unset `--confirm`
|
|
365
|
+
* resolves to `no`.
|
|
366
|
+
*/
|
|
367
|
+
promptSource?: PromptSource;
|
|
368
|
+
|
|
338
369
|
/** Command groups for partitioned help (e.g. COMMANDS vs MANAGEMENT). */
|
|
339
370
|
groups?: Array<{
|
|
340
371
|
id: string; // e.g. "management"
|
|
@@ -813,6 +844,14 @@ export function createCLI(cfg: CLIConfig): CLIResult {
|
|
|
813
844
|
program.hook('preAction', (thisCmd) => stamp(thisCmd));
|
|
814
845
|
}
|
|
815
846
|
|
|
847
|
+
// Delegation gates: --dry-run, --confirm, --max-ops, --policy and the
|
|
848
|
+
// hooks enforcing them on every runnable leaf.
|
|
849
|
+
installDelegation(program, {
|
|
850
|
+
policy: cfg.policy,
|
|
851
|
+
promptSource: cfg.promptSource,
|
|
852
|
+
disableDryRun: cfg.disable?.dryRun === true,
|
|
853
|
+
});
|
|
854
|
+
|
|
816
855
|
// Stackable verbosity count flag (-VV = 2). The shorthand comes from the
|
|
817
856
|
// parity contract's verbosity block; commander takes the option spec as a
|
|
818
857
|
// runtime string, so it need not be a literal.
|
|
@@ -12,6 +12,7 @@ import { Command } from 'commander';
|
|
|
12
12
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
13
13
|
|
|
14
14
|
import { AliasStore, bridgeAliases, findCommand } from './alias';
|
|
15
|
+
import { createCLI } from './cli';
|
|
15
16
|
import { bindArgs, bindFlag, completeRequest, completionCommand } from './completion';
|
|
16
17
|
|
|
17
18
|
import {
|
|
@@ -184,11 +185,11 @@ function walk(cmd: Command, fn: (c: Command) => void): void {
|
|
|
184
185
|
for (const c of cmd.commands) walk(c, fn);
|
|
185
186
|
}
|
|
186
187
|
|
|
187
|
-
/** A kit root as the Go runner builds it
|
|
188
|
+
/** A kit root as the Go runner builds it (createCLI: persistent root flags included). */
|
|
188
189
|
function buildRoot(t: Tree): Command {
|
|
189
190
|
strictKeys(t, ['program', 'about', 'commands', 'aliases', 'flag_enums',
|
|
190
191
|
'flag_completers', 'arg_completers'], t.program);
|
|
191
|
-
const program =
|
|
192
|
+
const { program } = createCLI({ name: t.program, version: '1.0.0', description: t.about });
|
|
192
193
|
for (const c of t.commands) program.addCommand(buildCommand(c));
|
|
193
194
|
const store = new AliasStore('');
|
|
194
195
|
for (const [name, target] of Object.entries(t.aliases)) store.set(name, target);
|
package/src/completion.test.ts
CHANGED
|
@@ -192,6 +192,18 @@ describe('bindFlag / bindArgs', () => {
|
|
|
192
192
|
});
|
|
193
193
|
});
|
|
194
194
|
|
|
195
|
+
describe('root flags below the root', () => {
|
|
196
|
+
it('a subcommand inherits persistent root flags but not the local version flag', async () => {
|
|
197
|
+
const { program } = createCLI({ name: 'tool', version: '1.0.0', description: 'd' });
|
|
198
|
+
program.command('deploy').description('Deploy');
|
|
199
|
+
const sub = (await request(program, ['deploy', '--'], true)).out.split('\n');
|
|
200
|
+
expect(sub).toContain('--quiet');
|
|
201
|
+
expect(sub).not.toContain('--version');
|
|
202
|
+
const root = (await request(program, ['--ver'], true)).out.split('\n');
|
|
203
|
+
expect(root).toContain('--version');
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
|
|
195
207
|
describe('__complete requests', () => {
|
|
196
208
|
afterEach(() => {
|
|
197
209
|
vi.restoreAllMocks();
|
package/src/completion.ts
CHANGED
|
@@ -461,8 +461,9 @@ function toFlag(o: Option, owner: Command, root: Command, inherited: boolean): F
|
|
|
461
461
|
/**
|
|
462
462
|
* The flags of the last command of `chain`, as commander accepts them:
|
|
463
463
|
* ancestors' options (unless an ancestor has positional options), then
|
|
464
|
-
* its own plus its help option
|
|
465
|
-
* own, only help
|
|
464
|
+
* its own plus its help option (a root's version flag stays local to it).
|
|
465
|
+
* A root-alias shim takes no flags of its own, only help, plus the
|
|
466
|
+
* root's persistent flags like any child.
|
|
466
467
|
*/
|
|
467
468
|
function flagsOf(root: Command, chain: Command[]): Flag[] {
|
|
468
469
|
const cmd = chain[chain.length - 1]!;
|
|
@@ -470,7 +471,11 @@ function flagsOf(root: Command, chain: Command[]): Flag[] {
|
|
|
470
471
|
for (let i = chain.length - 2; i >= 0; i--) {
|
|
471
472
|
const anc = chain[i]!;
|
|
472
473
|
if (internals(anc)._enablePositionalOptions) break;
|
|
473
|
-
|
|
474
|
+
// cobra's version flag is local to the root: never inherited.
|
|
475
|
+
for (const o of anc.options) {
|
|
476
|
+
if (internals(anc)._versionOptionName === o.attributeName()) continue;
|
|
477
|
+
out.push(toFlag(o, anc, root, true));
|
|
478
|
+
}
|
|
474
479
|
}
|
|
475
480
|
if (isShim(root, cmd)) {
|
|
476
481
|
out.push({
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { Command, CommanderError } from 'commander';
|
|
5
|
+
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
|
6
|
+
|
|
7
|
+
import { createCLI } from './cli';
|
|
8
|
+
import {
|
|
9
|
+
destructiveToken, dryRunApplied, isDryRun, noPrompt, resolveConfirmMode,
|
|
10
|
+
resolveDryRunPolicy, scriptedPrompt, type PromptSource,
|
|
11
|
+
} from './delegation';
|
|
12
|
+
import { defaultPolicyLoader, Engine, kitDefault, pathMatch, resolvePolicyPath } from './policy';
|
|
13
|
+
import { destructiveNames, gateSideEffect, inferredDestructive } from './sideeffect';
|
|
14
|
+
|
|
15
|
+
interface Leaf {
|
|
16
|
+
name: string;
|
|
17
|
+
se?: string;
|
|
18
|
+
ann?: Record<string, string>;
|
|
19
|
+
opts?: string[];
|
|
20
|
+
run?: (cmd: Command) => void;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface Res { code: number; out: string; err: string; ran: string[] }
|
|
24
|
+
|
|
25
|
+
function build(leaves: Leaf[], cfg: { prompt?: PromptSource; policy?: boolean } = {}) {
|
|
26
|
+
const ran: string[] = [];
|
|
27
|
+
const { program } = createCLI({
|
|
28
|
+
name: 'kitapp', version: '1.0.0', description: 'd',
|
|
29
|
+
promptSource: cfg.prompt ?? noPrompt,
|
|
30
|
+
policy: cfg.policy ? defaultPolicyLoader('kitapp') : undefined,
|
|
31
|
+
});
|
|
32
|
+
let out = '';
|
|
33
|
+
let err = '';
|
|
34
|
+
program.exitOverride();
|
|
35
|
+
program.configureOutput({
|
|
36
|
+
writeOut: (s) => { out += s; },
|
|
37
|
+
writeErr: (s) => { err += s; },
|
|
38
|
+
});
|
|
39
|
+
for (const l of leaves) {
|
|
40
|
+
const c = program.command(l.name).description(l.name);
|
|
41
|
+
c.exitOverride();
|
|
42
|
+
for (const o of l.opts ?? []) c.option(o);
|
|
43
|
+
const ann = { ...(l.ann ?? {}) };
|
|
44
|
+
if (l.se !== undefined) ann['kit/side-effect'] = l.se;
|
|
45
|
+
(c as unknown as { annotations: Record<string, string> }).annotations = ann;
|
|
46
|
+
c.action(() => { ran.push(l.name); l.run?.(c); });
|
|
47
|
+
}
|
|
48
|
+
const run = (args: string[]): Res => {
|
|
49
|
+
let code = 0;
|
|
50
|
+
try {
|
|
51
|
+
program.parse(['node', 'kitapp', ...args]);
|
|
52
|
+
} catch (e) {
|
|
53
|
+
if (!(e instanceof CommanderError)) throw e;
|
|
54
|
+
code = e.exitCode;
|
|
55
|
+
}
|
|
56
|
+
return { code, out, err, ran };
|
|
57
|
+
};
|
|
58
|
+
return { program, run };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
let xdg: string;
|
|
62
|
+
beforeEach(() => {
|
|
63
|
+
xdg = mkdtempSync(join(tmpdir(), 'ts-gate-'));
|
|
64
|
+
process.env['XDG_CONFIG_HOME'] = xdg;
|
|
65
|
+
});
|
|
66
|
+
afterEach(() => { delete process.env['XDG_CONFIG_HOME']; });
|
|
67
|
+
|
|
68
|
+
function policyFile(name: string, body: string): void {
|
|
69
|
+
mkdirSync(join(xdg, 'kitapp', 'policies'), { recursive: true });
|
|
70
|
+
writeFileSync(join(xdg, 'kitapp', 'policies', `${name}.yaml`), body);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
describe('side-effect inference', () => {
|
|
74
|
+
it('infers only for an absent or empty annotation', () => {
|
|
75
|
+
expect(inferredDestructive('delete', {})).toBe(true);
|
|
76
|
+
expect(inferredDestructive('delete', { 'kit/side-effect': '' })).toBe(true);
|
|
77
|
+
expect(inferredDestructive('delete', { 'kit/side-effect': 'read' })).toBe(false);
|
|
78
|
+
expect(inferredDestructive('delete', { 'kit/side-effect': 'bogus' })).toBe(false);
|
|
79
|
+
expect(inferredDestructive('delete-all', {})).toBe(false);
|
|
80
|
+
expect(gateSideEffect('rm', undefined)).toBe('destructive-shared');
|
|
81
|
+
expect(destructiveNames()).toEqual(['delete', 'destroy', 'drop', 'purge', 'remove', 'rm']);
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
describe('confirm gate', () => {
|
|
86
|
+
const l: Leaf[] = [{ name: 'rm', se: 'destructive' }, { name: 'add', se: 'write' }];
|
|
87
|
+
|
|
88
|
+
it('refuses a destructive without a terminal', () => {
|
|
89
|
+
const r = build(l).run(['rm']);
|
|
90
|
+
expect(r.code).toBe(5);
|
|
91
|
+
expect(r.err).toContain('refused: --confirm=no (or non-TTY default)');
|
|
92
|
+
expect(r.ran).toEqual([]);
|
|
93
|
+
});
|
|
94
|
+
it.each(['yes', 'auto'])('--confirm %s lets it run', (m) => {
|
|
95
|
+
const r = build(l).run(['--confirm', m, 'rm']);
|
|
96
|
+
expect(r.code).toBe(0);
|
|
97
|
+
expect(r.ran).toEqual(['rm']);
|
|
98
|
+
});
|
|
99
|
+
it('prompt: y accepts, n aborts', () => {
|
|
100
|
+
expect(build(l, { prompt: scriptedPrompt(['y']) }).run(['--confirm', 'prompt', 'rm']).code).toBe(0);
|
|
101
|
+
const r = build(l, { prompt: scriptedPrompt(['n']) }).run(['--confirm', 'prompt', 'rm']);
|
|
102
|
+
expect(r.code).toBe(5);
|
|
103
|
+
expect(r.err).toContain('aborted by user at confirm prompt for kitapp rm');
|
|
104
|
+
});
|
|
105
|
+
it('unset confirm prompts only when a terminal exists', () => {
|
|
106
|
+
expect(resolveConfirmMode(noPrompt, '')).toBe('no');
|
|
107
|
+
expect(resolveConfirmMode(scriptedPrompt([]), '')).toBe('prompt');
|
|
108
|
+
expect(build(l, { prompt: scriptedPrompt(['yes']) }).run(['rm']).code).toBe(0);
|
|
109
|
+
});
|
|
110
|
+
it('a write needs no confirmation', () => {
|
|
111
|
+
expect(build(l).run(['add']).code).toBe(0);
|
|
112
|
+
});
|
|
113
|
+
it('machine format gets exactly one json envelope', () => {
|
|
114
|
+
const r = build(l).run(['--format', 'json', 'rm']);
|
|
115
|
+
expect(r.code).toBe(5);
|
|
116
|
+
expect(JSON.parse(r.err).code).toBe('UNAUTHORIZED');
|
|
117
|
+
});
|
|
118
|
+
it('a leaf-local --confirm is the leaf mode, as in Go', () => {
|
|
119
|
+
const r = build([{ name: 'rm', se: 'destructive', opts: ['--confirm <m>'] }]).run(['rm', '--confirm', 'yes']);
|
|
120
|
+
expect(r.code).toBe(0);
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
describe('typed token', () => {
|
|
125
|
+
const l: Leaf[] = [{ name: 'purge', se: 'destructive', ann: { 'kit/destructive-token': 'required' } }];
|
|
126
|
+
it('token is first 6 bytes of sha256 of the path', () => {
|
|
127
|
+
expect(destructiveToken('kitapp purge')).toBe('9bcc9064589a');
|
|
128
|
+
});
|
|
129
|
+
it('required, accepted, mismatched', () => {
|
|
130
|
+
const miss = build(l).run(['--confirm', 'yes', 'purge']);
|
|
131
|
+
expect(miss.code).toBe(5);
|
|
132
|
+
expect(miss.err).toContain('requires --confirm-token=9bcc9064589a');
|
|
133
|
+
expect(build(l).run(['purge', '--confirm-token', '9bcc9064589a']).code).toBe(0);
|
|
134
|
+
const bad = build(l).run(['purge', '--confirm-token', 'deadbeef0000']);
|
|
135
|
+
expect(bad.code).toBe(5);
|
|
136
|
+
expect(bad.err).toContain('--confirm-token mismatch for kitapp purge; expected 9bcc9064589a');
|
|
137
|
+
});
|
|
138
|
+
it('machine format carries the fix in the envelope, no prose preview', () => {
|
|
139
|
+
const r = build(l).run(['--format', 'json', 'purge']);
|
|
140
|
+
expect(JSON.parse(r.err).suggested_fix).toContain('--confirm-token=9bcc9064589a');
|
|
141
|
+
});
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
describe('policy', () => {
|
|
145
|
+
const l: Leaf[] = [
|
|
146
|
+
{ name: 'add', se: 'write' }, { name: 'ls', se: 'read' }, { name: 'rm', se: 'destructive' },
|
|
147
|
+
{ name: 'import', se: 'write', opts: ['--policy <file>'], run: () => {} },
|
|
148
|
+
];
|
|
149
|
+
it('refuses, and --confirm yes does not lift it', () => {
|
|
150
|
+
policyFile('readonly', 'allow:\n write: []\n destructive: []\n');
|
|
151
|
+
expect(build(l, { policy: true }).run(['--policy', 'readonly', 'add']).err).toContain('policy: write not allowed for add');
|
|
152
|
+
const r = build(l, { policy: true }).run(['--policy', 'readonly', '--confirm', 'yes', 'rm']);
|
|
153
|
+
expect(r.code).toBe(5);
|
|
154
|
+
expect(build(l, { policy: true }).run(['--policy', 'readonly', 'ls']).code).toBe(0);
|
|
155
|
+
});
|
|
156
|
+
it('require_confirm lifts a write into the gate', () => {
|
|
157
|
+
policyFile('confirm', 'require_confirm:\n - add\n');
|
|
158
|
+
expect(build(l, { policy: true }).run(['--policy', 'confirm', 'add']).err).toContain('refused: --confirm=no');
|
|
159
|
+
expect(build(l, { policy: true }).run(['--policy', 'confirm', '--confirm', 'yes', 'add']).code).toBe(0);
|
|
160
|
+
});
|
|
161
|
+
it('unknown and unparsable policies are usage errors', () => {
|
|
162
|
+
policyFile('broken', 'allow: [\n');
|
|
163
|
+
for (const n of ['ghost', 'broken']) {
|
|
164
|
+
const r = build(l, { policy: true }).run(['--policy', n, 'add']);
|
|
165
|
+
expect(r.code).toBe(2);
|
|
166
|
+
expect(r.err).toContain(`policy "${n}"`);
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
it('no loader wired: only kit-default resolves', () => {
|
|
170
|
+
expect(build(l).run(['--policy', 'x', 'add']).code).toBe(2);
|
|
171
|
+
const r = build(l).run(['--policy', 'kit-default', 'add']);
|
|
172
|
+
expect(r.code).toBe(5);
|
|
173
|
+
expect(r.err).toContain('policy kit-default:');
|
|
174
|
+
});
|
|
175
|
+
it('validates the name before any filesystem access', () => {
|
|
176
|
+
for (const n of ['../x', join(xdg, 'kitapp', 'policies', 'readonly'), 'a b', 'x'.repeat(65)]) {
|
|
177
|
+
const r = build(l, { policy: true }).run(['--policy', n, 'add']);
|
|
178
|
+
expect(r.code).toBe(2);
|
|
179
|
+
expect(r.err).toContain('invalid policy name');
|
|
180
|
+
}
|
|
181
|
+
expect(() => resolvePolicyPath('t', '..')).toThrow(/invalid policy name/);
|
|
182
|
+
});
|
|
183
|
+
it('a leaf-local --policy is not the delegation policy', () => {
|
|
184
|
+
const r = build(l, { policy: true }).run(['import', '--policy', '/tmp/some.yaml']);
|
|
185
|
+
expect(r.code).toBe(0);
|
|
186
|
+
expect(r.ran).toEqual(['import']);
|
|
187
|
+
});
|
|
188
|
+
it('a root --policy before a shadowing leaf still gates', () => {
|
|
189
|
+
policyFile('readonly', 'allow:\n write: []\n');
|
|
190
|
+
const r = build(l, { policy: true }).run(['--policy', 'readonly', 'import', '--policy', 'f']);
|
|
191
|
+
expect(r.code).toBe(5);
|
|
192
|
+
});
|
|
193
|
+
it('engine globs, tiers and budget', () => {
|
|
194
|
+
expect(pathMatch('a*', 'abc')).toBe(true);
|
|
195
|
+
expect(pathMatch('a*', 'a/b')).toBe(false);
|
|
196
|
+
const e = new Engine(kitDefault(), 1);
|
|
197
|
+
expect(e.authorize({ verb: 'x', sideEffect: 'destructive-shared' }).allowed).toBe(false);
|
|
198
|
+
e.recordOp();
|
|
199
|
+
expect(() => e.recordOp()).toThrow(/max-ops/);
|
|
200
|
+
});
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
describe('max-ops', () => {
|
|
204
|
+
it('within budget runs; a non-integer is a usage error', () => {
|
|
205
|
+
const l: Leaf[] = [{ name: 'add', se: 'write' }];
|
|
206
|
+
expect(build(l).run(['--max-ops', '1', 'add']).code).toBe(0);
|
|
207
|
+
expect(build(l).run(['--max-ops', 'x', 'add']).code).toBe(2);
|
|
208
|
+
});
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
describe('dry-run', () => {
|
|
212
|
+
const l: Leaf[] = [
|
|
213
|
+
{ name: 'ls', se: 'read' }, { name: 'add', se: 'write' }, { name: 'rm', se: 'destructive' },
|
|
214
|
+
{ name: 'shell', se: 'interactive' }, { name: 'sync', se: 'write', ann: { 'kit/dry-run': 'opted-out' } },
|
|
215
|
+
];
|
|
216
|
+
const seen: Record<string, boolean> = {};
|
|
217
|
+
const probe = (name: string): Leaf => ({ name, se: name === 'rm' ? 'destructive' : name === 'ls' ? 'read' : 'write',
|
|
218
|
+
run: (c) => { seen[name] = dryRunApplied(c); seen[`${name}:is`] = isDryRun(c); } });
|
|
219
|
+
|
|
220
|
+
it('applies to a write, skips the destructive confirm, no-ops a read', () => {
|
|
221
|
+
const b = build(['add', 'rm', 'ls'].map(probe));
|
|
222
|
+
expect(b.run(['--dry-run', 'add']).code).toBe(0);
|
|
223
|
+
expect(seen['add']).toBe(true);
|
|
224
|
+
expect(b.run(['--dry-run', 'rm']).code).toBe(0);
|
|
225
|
+
expect(seen['rm']).toBe(true);
|
|
226
|
+
expect(b.run(['--dry-run', 'ls']).code).toBe(0);
|
|
227
|
+
expect(seen['ls']).toBe(false);
|
|
228
|
+
expect(seen['ls:is']).toBe(true);
|
|
229
|
+
});
|
|
230
|
+
it('refuses interactive and opted-out leaves', () => {
|
|
231
|
+
const r = build(l).run(['--dry-run', 'shell']);
|
|
232
|
+
expect(r.code).toBe(2);
|
|
233
|
+
expect(r.err).toContain('"kitapp shell" does not accept --dry-run: interactive');
|
|
234
|
+
expect(build(l).run(['--dry-run', 'sync']).err).toContain('explicitly opted out');
|
|
235
|
+
expect(JSON.parse(build(l).run(['--format', 'json', '--dry-run', 'shell']).err).code).toBe('USAGE');
|
|
236
|
+
});
|
|
237
|
+
it('dry-run table', () => {
|
|
238
|
+
expect(resolveDryRunPolicy('delete', {})).toBe('allow');
|
|
239
|
+
expect(resolveDryRunPolicy('list', {})).toBe('reject-untagged');
|
|
240
|
+
expect(resolveDryRunPolicy('delete', { 'kit/side-effect': 'bogus' })).toBe('reject-malformed');
|
|
241
|
+
expect(resolveDryRunPolicy('x', { 'kit/side-effect': 'read' })).toBe('noop');
|
|
242
|
+
});
|
|
243
|
+
it('inferred destructive: kit previews, handler never runs, nothing mutates', () => {
|
|
244
|
+
let mutated = false;
|
|
245
|
+
const b = build([{ name: 'delete', run: () => { mutated = true; } }]);
|
|
246
|
+
const r = b.run(['--dry-run', '--format', 'json', 'delete']);
|
|
247
|
+
expect(r.code).toBe(0);
|
|
248
|
+
expect(mutated).toBe(false);
|
|
249
|
+
expect(r.ran).toEqual([]);
|
|
250
|
+
expect(JSON.parse(r.out).command).toBe('kitapp delete');
|
|
251
|
+
});
|
|
252
|
+
it('inferred destructive under a policy refusal is still refused in dry-run', () => {
|
|
253
|
+
policyFile('nodel', 'allow:\n destructive: []\n');
|
|
254
|
+
const b = build([{ name: 'delete' }], { policy: true });
|
|
255
|
+
expect(b.run(['--policy', 'nodel', '--dry-run', 'delete']).code).toBe(5);
|
|
256
|
+
});
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
describe('inferred destructive gate', () => {
|
|
260
|
+
const l: Leaf[] = [
|
|
261
|
+
{ name: 'delete' }, { name: 'list' }, { name: 'drop', se: 'read' }, { name: 'delete-all' },
|
|
262
|
+
];
|
|
263
|
+
it('gates the unannotated destructive name, nothing else', () => {
|
|
264
|
+
expect(build(l).run(['delete']).code).toBe(5);
|
|
265
|
+
expect(build(l).run(['--confirm', 'yes', 'delete']).code).toBe(0);
|
|
266
|
+
for (const n of ['list', 'drop', 'delete-all']) expect(build(l).run([n]).code).toBe(0);
|
|
267
|
+
});
|
|
268
|
+
it('the destructive name is the leaf name below a group', () => {
|
|
269
|
+
const { program } = createCLI({ name: 'kitapp', version: '1', description: 'd', promptSource: noPrompt });
|
|
270
|
+
program.exitOverride();
|
|
271
|
+
program.configureOutput({ writeErr: () => {} });
|
|
272
|
+
const g = program.command('widget').exitOverride();
|
|
273
|
+
g.command('remove').exitOverride().action(() => {});
|
|
274
|
+
g.command('list').exitOverride().action(() => {});
|
|
275
|
+
expect(() => program.parse(['node', 'k', 'widget', 'remove'])).toThrow();
|
|
276
|
+
expect(() => program.parse(['node', 'k', 'widget', 'list'])).not.toThrow();
|
|
277
|
+
});
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
describe('malformed side-effect tier', () => {
|
|
281
|
+
it('is refused as usage before the handler runs, unconfirmed or not', () => {
|
|
282
|
+
let mutated = false;
|
|
283
|
+
const mk = () => build([{ name: 'wipe', se: 'destructve', run: () => { mutated = true; } }]);
|
|
284
|
+
for (const args of [['wipe'], ['--confirm', 'yes', 'wipe'], ['--dry-run', 'wipe']]) {
|
|
285
|
+
const r = mk().run(args);
|
|
286
|
+
expect(r.code).toBe(2);
|
|
287
|
+
expect(r.err).toContain('malformed kit/side-effect tag "destructve"');
|
|
288
|
+
}
|
|
289
|
+
expect(mutated).toBe(false);
|
|
290
|
+
});
|
|
291
|
+
it('an explicit malformed tier beats the destructive name too', () => {
|
|
292
|
+
expect(build([{ name: 'purge', se: 'bogus' }]).run(['--confirm', 'yes', 'purge']).code).toBe(2);
|
|
293
|
+
});
|
|
294
|
+
it('the engine fails closed on an unknown non-empty tier', () => {
|
|
295
|
+
const e = new Engine({ ...kitDefault(), allow: undefined, unannotated: undefined }, 0);
|
|
296
|
+
expect(e.authorize({ verb: 'x', sideEffect: 'destructve' }).allowed).toBe(false);
|
|
297
|
+
expect(e.authorize({ verb: 'x', sideEffect: '' }).allowed).toBe(true);
|
|
298
|
+
});
|
|
299
|
+
});
|