@hop-top/kit 0.5.0-alpha.1 → 0.5.0-alpha.10

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.
Files changed (285) hide show
  1. package/CHANGELOG.md +251 -0
  2. package/LICENSE +1 -1
  3. package/LICENSE-cobra.txt +174 -0
  4. package/NOTICE +15 -0
  5. package/README.md +55 -259
  6. package/dist/aim-DZHwwiIc.d.ts +139 -0
  7. package/dist/aim.d.ts +1 -116
  8. package/dist/aim.js +13 -414
  9. package/dist/alias-D9_qFlyP.d.ts +174 -0
  10. package/dist/alias.d.ts +2 -73
  11. package/dist/alias.js +27 -207
  12. package/dist/api-DAexsu2H.d.ts +77 -0
  13. package/dist/api.d.ts +1 -62
  14. package/dist/api.js +10 -164
  15. package/dist/auth-2-jfgiHn.d.ts +34 -0
  16. package/dist/auth.d.ts +1 -26
  17. package/dist/auth.js +6 -40
  18. package/dist/chunk-2JV3A7OP.js +1894 -0
  19. package/dist/chunk-3FIKGFKI.js +54 -0
  20. package/dist/chunk-4UE5TCMQ.js +104 -0
  21. package/dist/chunk-6HFAEZ52.js +29 -0
  22. package/dist/chunk-6SVOHNIC.js +17 -0
  23. package/dist/chunk-72XZWQX7.js +504 -0
  24. package/dist/chunk-ABQSE7AI.js +513 -0
  25. package/dist/chunk-BDNNPRX6.js +41 -0
  26. package/dist/chunk-BLS2OBIQ.js +263 -0
  27. package/dist/chunk-BRNEKPWX.js +37 -0
  28. package/dist/chunk-CSJWB6D3.js +151 -0
  29. package/dist/chunk-GGWJRWWA.js +309 -0
  30. package/dist/chunk-GHPJJV5L.js +613 -0
  31. package/dist/chunk-IXVQ62NZ.js +334 -0
  32. package/dist/chunk-JKMQSAJP.js +174 -0
  33. package/dist/chunk-JZ22ZUFA.js +1131 -0
  34. package/dist/chunk-K7VCKJ27.js +814 -0
  35. package/dist/chunk-KVG7YCTS.js +115 -0
  36. package/dist/chunk-L23O2FFE.js +51 -0
  37. package/dist/chunk-MQXYDYRD.js +968 -0
  38. package/dist/chunk-MUIQVU6E.js +251 -0
  39. package/dist/chunk-NLMS7HGP.js +178 -0
  40. package/dist/chunk-POR5L2DG.js +247 -0
  41. package/dist/chunk-PSFYJGDG.js +1445 -0
  42. package/dist/chunk-QJVSKKRQ.js +369 -0
  43. package/dist/chunk-QPUCXQXT.js +67 -0
  44. package/dist/chunk-QQQYCWSC.js +240 -0
  45. package/dist/chunk-R5U7XKVJ.js +16 -0
  46. package/dist/chunk-SNVGDYX7.js +187 -0
  47. package/dist/chunk-T46YPHKN.js +669 -0
  48. package/dist/chunk-UKZIAQA7.js +26 -0
  49. package/dist/chunk-WBVO43HU.js +355 -0
  50. package/dist/chunk-WUOAQVOA.js +86 -0
  51. package/dist/chunk-WWUKGJB5.js +90 -0
  52. package/dist/chunk-XJTRY453.js +868 -0
  53. package/dist/chunk-YGYQUFGY.js +219 -0
  54. package/dist/chunk-YOBAUCVN.js +583 -0
  55. package/dist/cli-C5B5tnpA.d.ts +400 -0
  56. package/dist/cli.d.ts +7 -309
  57. package/dist/cli.js +70 -945
  58. package/dist/completion-csVun6SP.d.ts +112 -0
  59. package/dist/completion-values-By-mnjNt.d.ts +142 -0
  60. package/dist/completion-values.d.ts +1 -0
  61. package/dist/completion-values.js +29 -0
  62. package/dist/completion.d.ts +3 -0
  63. package/dist/completion.js +34 -0
  64. package/dist/compliance-AxFf-uMy.d.ts +60 -0
  65. package/dist/compliance.d.ts +1 -0
  66. package/dist/compliance.js +17 -0
  67. package/dist/config-CaK60ByQ.d.ts +241 -0
  68. package/dist/config.d.ts +1 -97
  69. package/dist/config.js +8 -78
  70. package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
  71. package/dist/errcorrect.d.ts +1 -37
  72. package/dist/errcorrect.js +8 -68
  73. package/dist/error-Do8Qji43.d.ts +231 -0
  74. package/dist/id/index.d.ts +2 -83
  75. package/dist/id/index.js +14 -65
  76. package/dist/index-BKJZClJx.d.ts +1486 -0
  77. package/dist/index-C3Zw4wDJ.d.ts +359 -0
  78. package/dist/index-DCe1boBz.d.ts +328 -0
  79. package/dist/index-VLDcI5NF.d.ts +95 -0
  80. package/dist/index.d.ts +37 -0
  81. package/dist/index.js +132 -0
  82. package/dist/llm-DYuR7_uX.d.ts +1069 -0
  83. package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
  84. package/dist/llm-anthropic.d.ts +2 -0
  85. package/dist/llm-anthropic.js +13 -0
  86. package/dist/llm-openai-DyFrucmV.d.ts +87 -0
  87. package/dist/llm-openai.d.ts +2 -0
  88. package/dist/llm-openai.js +19 -0
  89. package/dist/llm.d.ts +1 -188
  90. package/dist/llm.js +101 -356
  91. package/dist/log-CkaxMX3U.d.ts +115 -0
  92. package/dist/log.d.ts +2 -0
  93. package/dist/log.js +14 -0
  94. package/dist/mcp/index.d.ts +4 -0
  95. package/dist/mcp/index.js +184 -0
  96. package/dist/netpolicy-Brx5XZUB.d.ts +151 -0
  97. package/dist/netpolicy.d.ts +1 -0
  98. package/dist/netpolicy.js +25 -0
  99. package/dist/output-CjZWmL8s.d.ts +420 -0
  100. package/dist/output.d.ts +3 -213
  101. package/dist/output.js +137 -447
  102. package/dist/parity-CvMuYcVI.d.ts +61 -0
  103. package/dist/progress-CAzyxeWl.d.ts +38 -0
  104. package/dist/progress.d.ts +1 -30
  105. package/dist/progress.js +6 -55
  106. package/dist/provenance-SMFHm5gx.d.ts +30 -0
  107. package/dist/provenance.d.ts +1 -24
  108. package/dist/provenance.js +6 -31
  109. package/dist/routellm-B0nv59mH.d.ts +111 -0
  110. package/dist/routellm.d.ts +2 -64
  111. package/dist/routellm.js +13 -255
  112. package/dist/rpc-D31Lg0Kc.d.ts +32 -0
  113. package/dist/rpc.d.ts +2 -25
  114. package/dist/rpc.js +4 -98
  115. package/dist/safety-CUaYEjZc.d.ts +30 -0
  116. package/dist/safety.d.ts +1 -24
  117. package/dist/safety.js +6 -43
  118. package/dist/scope-BrhYB4ij.d.ts +141 -0
  119. package/dist/scope.d.ts +1 -121
  120. package/dist/scope.js +20 -377
  121. package/dist/serve-D8yWMrTc.d.ts +646 -0
  122. package/dist/serve.d.ts +3 -0
  123. package/dist/serve.js +75 -0
  124. package/dist/sqlstore.js +6 -39
  125. package/dist/stream-CrjeCp0M.d.ts +44 -0
  126. package/dist/stream.d.ts +1 -35
  127. package/dist/stream.js +8 -51
  128. package/dist/telemetry/index.d.ts +1 -315
  129. package/dist/telemetry/index.js +26 -599
  130. package/dist/toolspec-DcPwwoAZ.d.ts +368 -0
  131. package/dist/toolspec.d.ts +2 -0
  132. package/dist/toolspec.js +37 -0
  133. package/dist/tui/index.d.ts +6 -298
  134. package/dist/tui/index.js +17 -381
  135. package/dist/upgrade-p_zh3pvV.d.ts +102 -0
  136. package/dist/upgrade.d.ts +1 -95
  137. package/dist/upgrade.js +6 -114
  138. package/dist/xdg-DB7Shoib.d.ts +179 -0
  139. package/dist/xdg.d.ts +1 -169
  140. package/dist/xdg.js +14 -128
  141. package/package.json +192 -24
  142. package/src/README.md +15 -0
  143. package/src/alias.conformance.test.ts +250 -0
  144. package/src/alias.test.ts +206 -2
  145. package/src/alias.ts +196 -21
  146. package/src/cli.help-command.test.ts +105 -0
  147. package/src/cli.offline.test.ts +93 -0
  148. package/src/cli.parity.test.ts +192 -0
  149. package/src/cli.test.ts +95 -1
  150. package/src/cli.ts +195 -25
  151. package/src/completion-scripts.ts +16 -0
  152. package/src/completion-values.test.ts +76 -16
  153. package/src/completion-values.ts +170 -66
  154. package/src/completion.conformance.test.ts +297 -0
  155. package/src/completion.test.ts +256 -145
  156. package/src/completion.ts +767 -121
  157. package/src/compliance.test.ts +196 -2
  158. package/src/compliance.ts +440 -20
  159. package/src/config-merge.test.ts +425 -0
  160. package/src/config.test.ts +228 -1
  161. package/src/config.ts +429 -16
  162. package/src/gen/crud_pb.ts +7 -7
  163. package/src/id/README.md +38 -0
  164. package/src/id/contract.test.ts +1 -1
  165. package/src/id/index.test.ts +1 -1
  166. package/src/id/index.ts +3 -2
  167. package/src/index.test.ts +71 -0
  168. package/src/index.ts +46 -0
  169. package/src/llm-anthropic.conformance.test.ts +1135 -0
  170. package/src/llm-anthropic.test.ts +152 -0
  171. package/src/llm-anthropic.ts +940 -0
  172. package/src/llm-choice-hermetic.test.ts +335 -0
  173. package/src/llm-config.test.ts +232 -0
  174. package/src/llm-config.ts +106 -0
  175. package/src/llm-endpoint.ts +254 -0
  176. package/src/llm-error.ts +17 -0
  177. package/src/llm-errors.ts +152 -0
  178. package/src/llm-file.ts +126 -0
  179. package/src/llm-http.ts +317 -0
  180. package/src/llm-keys.ts +167 -0
  181. package/src/llm-media.conformance.test.ts +87 -0
  182. package/src/llm-media.test.ts +279 -0
  183. package/src/llm-media.ts +322 -0
  184. package/src/llm-openai.conformance.test.ts +407 -0
  185. package/src/llm-openai.test.ts +510 -0
  186. package/src/llm-openai.ts +708 -0
  187. package/src/llm-payload.ts +155 -0
  188. package/src/llm-quote.ts +46 -0
  189. package/src/llm-routellm.conformance.test.ts +44 -0
  190. package/src/llm-toolnames.conformance.test.ts +112 -0
  191. package/src/llm-toolnames.test.ts +132 -0
  192. package/src/llm-toolnames.ts +298 -0
  193. package/src/llm-uri.ts +99 -0
  194. package/src/llm.test.ts +43 -15
  195. package/src/llm.toolcall.test.ts +175 -0
  196. package/src/llm.ts +602 -190
  197. package/src/log.parity.test.ts +105 -0
  198. package/src/log.test.ts +270 -1
  199. package/src/log.ts +228 -49
  200. package/src/mcp/README.md +63 -0
  201. package/src/mcp/args-separator.test.ts +164 -0
  202. package/src/mcp/args.test.ts +223 -0
  203. package/src/mcp/args.ts +160 -0
  204. package/src/mcp/audit.test.ts +520 -0
  205. package/src/mcp/audit.ts +70 -0
  206. package/src/mcp/bridge.test.ts +222 -0
  207. package/src/mcp/bridge.ts +291 -0
  208. package/src/mcp/conformance.test.ts +357 -0
  209. package/src/mcp/dispatch.ts +359 -0
  210. package/src/mcp/identity.test.ts +166 -0
  211. package/src/mcp/identity.ts +72 -0
  212. package/src/mcp/index.ts +176 -0
  213. package/src/mcp/legacy-notify.test.ts +59 -0
  214. package/src/mcp/legacy.ts +367 -0
  215. package/src/mcp/mcp.test.ts +707 -0
  216. package/src/mcp/modern-confirm.test.ts +520 -0
  217. package/src/mcp/modern-confirm.ts +484 -0
  218. package/src/mcp/modern.ts +788 -0
  219. package/src/mcp/stdio.test.ts +313 -0
  220. package/src/mcp/stdio.ts +254 -0
  221. package/src/mcp/tasks.ts +82 -0
  222. package/src/mcp/testtree.ts +250 -0
  223. package/src/mcp/toolname.test.ts +147 -0
  224. package/src/mcp/types.ts +689 -0
  225. package/src/netpolicy.test.ts +280 -0
  226. package/src/netpolicy.ts +256 -0
  227. package/src/output/README.md +46 -0
  228. package/src/output/builtins.ts +5 -5
  229. package/src/output/dispatch.ts +10 -2
  230. package/src/output/error.ts +459 -0
  231. package/src/output/formatter.ts +29 -5
  232. package/src/output/formatters/README.md +50 -0
  233. package/src/output/formatters/csv.ts +48 -12
  234. package/src/output/formatters/json.ts +4 -25
  235. package/src/output/formatters/project.ts +34 -0
  236. package/src/output/formatters/table.ts +8 -6
  237. package/src/output/formatters/text.ts +7 -3
  238. package/src/output/formatters/yaml.ts +5 -22
  239. package/src/output/projection.test.ts +298 -0
  240. package/src/output/projection.ts +33 -59
  241. package/src/output/template.ts +11 -21
  242. package/src/output.surface.test.ts +41 -0
  243. package/src/output.ts +64 -3
  244. package/src/published-types.test.ts +133 -0
  245. package/src/routellm.test.ts +209 -28
  246. package/src/routellm.toolcall.test.ts +521 -0
  247. package/src/routellm.ts +213 -177
  248. package/src/router/README.md +44 -0
  249. package/src/router/server.test.ts +41 -0
  250. package/src/router/server.ts +11 -0
  251. package/src/safety.test.ts +19 -9
  252. package/src/scope-defaults.json +29 -29
  253. package/src/serve.test.ts +1257 -0
  254. package/src/serve.ts +1665 -0
  255. package/src/telemetry/README.md +48 -0
  256. package/src/telemetry/client.test.ts +31 -0
  257. package/src/telemetry/client.ts +12 -6
  258. package/src/telemetry/offline.test.ts +64 -0
  259. package/src/toolspec-internal.ts +279 -0
  260. package/src/toolspec-manifest.test.ts +167 -0
  261. package/src/toolspec-manifest.ts +410 -0
  262. package/src/toolspec-spec-schemas.ts +12 -0
  263. package/src/toolspec-spec.test.ts +273 -0
  264. package/src/toolspec-spec.ts +458 -0
  265. package/src/toolspec.from-command.test.ts +350 -0
  266. package/src/toolspec.test.ts +2 -2
  267. package/src/toolspec.ts +222 -0
  268. package/src/triton/README.md +34 -0
  269. package/src/tui/README.md +42 -0
  270. package/src/tui/parity.test.ts +120 -31
  271. package/src/tui/parity.ts +58 -7
  272. package/src/wizard.test.ts +7 -7
  273. package/test/llm/conformance-helpers.ts +100 -0
  274. package/test/output/csv.test.ts +164 -0
  275. package/test/output/dispatch.test.ts +1 -2
  276. package/test/output/error.test.ts +277 -0
  277. package/test/output/smoke-capture.ts +2 -2
  278. package/test/output/smoke.test.ts +2 -2
  279. package/test/output/taxonomy-contract.test.ts +148 -0
  280. package/test/setup-env.ts +16 -0
  281. package/test/toolspec/fixture.ts +79 -0
  282. package/tsconfig.json +3 -1
  283. package/tsconfig.test.json +10 -0
  284. package/vitest.config.ts +9 -0
  285. package/src/tui/parity.json +0 -74
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Load-bearing coverage for the verbosity/streams wiring in `cli.ts`.
3
+ *
4
+ * These feed a *constructed* ParityData (never the shared parity.json) whose
5
+ * values differ from the shipped contract, and assert the flag names, label
6
+ * and destination follow it. A port that re-hardcodes `-V`, `--stream`,
7
+ * `[name] ` or `process.stderr` fails here.
8
+ *
9
+ * Mirrors `go/console/cli/verbose_parity_wiring_test.go` and
10
+ * `go/console/cli/streams_parity_wiring_test.go`.
11
+ */
12
+
13
+ import { Command } from 'commander';
14
+ import { describe, expect, it } from 'vitest';
15
+
16
+ import {
17
+ channel,
18
+ createCLI,
19
+ registerStream,
20
+ streamFlagName,
21
+ streamLabel,
22
+ streamOutput,
23
+ verbosityFlagSpec,
24
+ verbosityShorthand,
25
+ } from './cli';
26
+ import { parity, type ParityData } from './tui/parity';
27
+
28
+ /** A ParityData carrying only the given streams block. */
29
+ function streamsData(flag: string, labelFormat: string, output: string): ParityData {
30
+ return { streams: { flag, label_format: labelFormat, output } } as unknown as ParityData;
31
+ }
32
+
33
+ /** A ParityData carrying only the given verbosity flag. */
34
+ function verbosityData(flag: string): ParityData {
35
+ return { verbosity: { flag, levels: {}, quiet_override: 'warn' } } as unknown as ParityData;
36
+ }
37
+
38
+ /**
39
+ * Name a resolved destination. `process.stdout` and `process.stderr` render
40
+ * identically in vitest diffs, so assert on the name instead — a failure
41
+ * then reads "expected 'stderr' to be 'stdout'".
42
+ */
43
+ function destName(w: NodeJS.WritableStream): string {
44
+ if (w === process.stdout) return 'stdout';
45
+ if (w === process.stderr) return 'stderr';
46
+ return 'other';
47
+ }
48
+
49
+ /** Capture what a body writes to stdout and stderr. */
50
+ function captureStreams(fn: () => void): { out: string; err: string } {
51
+ const outChunks: string[] = [];
52
+ const errChunks: string[] = [];
53
+ const oo = process.stdout.write;
54
+ const oe = process.stderr.write;
55
+ process.stdout.write = ((c: string) => { outChunks.push(c); return true; }) as never;
56
+ process.stderr.write = ((c: string) => { errChunks.push(c); return true; }) as never;
57
+ try {
58
+ fn();
59
+ } finally {
60
+ process.stdout.write = oo;
61
+ process.stderr.write = oe;
62
+ }
63
+ return { out: outChunks.join(''), err: errChunks.join('') };
64
+ }
65
+
66
+ // ─── Load-bearing: streams ───────────────────────────────────────────────────
67
+
68
+ /**
69
+ * Swaps the label template, destination and flag name away from the shipped
70
+ * `[{name}]` / stderr / `--stream`. Hardcoded literals fail here.
71
+ */
72
+ describe('streams follow contract not literals', () => {
73
+ const d = streamsData('--channel', '<<{name}>>', 'stdout');
74
+
75
+ it('renders the contract label_format', () => {
76
+ expect(streamLabel(d, 'trace'), 'label must render label_format, not a hardcoded [name]')
77
+ .toBe('<<trace>> ');
78
+ });
79
+
80
+ it('resolves the contract output destination', () => {
81
+ expect(destName(streamOutput(d)),
82
+ 'destination must follow streams.output, not a hardcoded stderr').toBe('stdout');
83
+ });
84
+
85
+ it('resolves the contract flag name', () => {
86
+ expect(streamFlagName(d), 'flag name must follow streams.flag, not a hardcoded "stream"')
87
+ .toBe('channel');
88
+ });
89
+ });
90
+
91
+ // ─── Load-bearing: verbosity flag ────────────────────────────────────────────
92
+
93
+ /**
94
+ * Swaps the shorthand away from the shipped `-V`. A hardcoded `'-V, --verbose'`
95
+ * option spec fails here.
96
+ */
97
+ describe('verbosity flag follows contract not literals', () => {
98
+ it('takes the shorthand from the contract', () => {
99
+ expect(verbosityShorthand(verbosityData('-d')),
100
+ 'shorthand must follow verbosity.flag, not a hardcoded V').toBe('d');
101
+ expect(verbosityFlagSpec(verbosityData('-d')),
102
+ 'option spec must be built from the contract shorthand').toBe('-d, --verbose');
103
+ });
104
+
105
+ it('registers a diverging shorthand on a real commander program', () => {
106
+ // Commander takes the option spec as a runtime string, so the shorthand
107
+ // need not be a compile-time literal. This proves the wiring would work
108
+ // if the contract changed.
109
+ const p = new Command('t');
110
+ p.option(verbosityFlagSpec(verbosityData('-d')), 'Increase verbosity',
111
+ (_: string, prev: number) => prev + 1, 0);
112
+ p.command('run').action(() => {});
113
+ p.parse(['node', 't', 'run', '-dd']);
114
+ expect(p.opts().verbose).toBe(2);
115
+ });
116
+ });
117
+
118
+ // ─── Requirement pins: observable behavior unchanged ─────────────────────────
119
+
120
+ /**
121
+ * Pins the wiring to the values actually declared in parity.json. NOT
122
+ * load-bearing: it keeps passing if a literal is restored, by design.
123
+ */
124
+ describe('streams match shipped contract', () => {
125
+ it('pins the contract values', () => {
126
+ expect(parity.streams.label_format).toBe('[{name}]');
127
+ expect(parity.streams.output).toBe('stderr');
128
+ expect(parity.streams.flag).toBe('--stream');
129
+ });
130
+
131
+ it('renders the historical [name] prefix to stderr', () => {
132
+ expect(streamLabel(parity, 'trace')).toBe('[trace] ');
133
+ expect(destName(streamOutput(parity))).toBe('stderr');
134
+ expect(streamFlagName(parity)).toBe('stream');
135
+ });
136
+
137
+ it('registers --stream and prefixes enabled channels end-to-end', () => {
138
+ const { program } = createCLI({ name: 't', version: '1.0.0', description: 'd' });
139
+ const sub = program.command('run');
140
+ registerStream(sub, 'sql', 'SQL queries');
141
+ expect(sub.options.map((o) => o.flags)).toContain('--stream <names>');
142
+
143
+ program.parse(['node', 't', 'run', '--stream', 'sql']);
144
+ const { out, err } = captureStreams(() => {
145
+ channel(sub, 'sql').write('SELECT 1\n');
146
+ channel(sub, 'off').write('hidden\n');
147
+ });
148
+ expect(err).toBe('[sql] SELECT 1\n');
149
+ expect(out).toBe('');
150
+ });
151
+ });
152
+
153
+ describe('verbosity flag matches shipped contract', () => {
154
+ it('pins the contract flag', () => {
155
+ expect(parity.verbosity.flag).toBe('-V');
156
+ expect(verbosityShorthand(parity)).toBe('V');
157
+ expect(verbosityFlagSpec(parity)).toBe('-V, --verbose');
158
+ });
159
+
160
+ it('registers -V as a stacking count on the real CLI', () => {
161
+ const { program } = createCLI({ name: 't', version: '1.0.0', description: 'd' });
162
+ program.command('run').action(() => {});
163
+ program.parse(['node', 't', 'run', '-VVV']);
164
+ expect(program.opts().verbose).toBe(3);
165
+ });
166
+ });
167
+
168
+ // ─── Degradation ─────────────────────────────────────────────────────────────
169
+
170
+ describe('streams degrade safely', () => {
171
+ it('falls back on an empty contract', () => {
172
+ const empty = streamsData('', '', '');
173
+ expect(streamLabel(empty, 'trace'), 'absent label_format falls back to [name]')
174
+ .toBe('[trace] ');
175
+ expect(destName(streamOutput(empty)), 'absent output falls back to stderr').toBe('stderr');
176
+ expect(streamFlagName(empty), 'absent flag falls back to "stream"').toBe('stream');
177
+ });
178
+
179
+ it('renders a label_format without {name} verbatim', () => {
180
+ const noPlaceholder = streamsData('--s', 'LOG:', 'stderr');
181
+ expect(streamLabel(noPlaceholder, 'trace')).toBe('LOG: ');
182
+ expect(streamFlagName(noPlaceholder)).toBe('s');
183
+ });
184
+ });
185
+
186
+ describe('verbosity flag degrades safely', () => {
187
+ it('falls back when the contract flag is absent or not a shorthand', () => {
188
+ expect(verbosityShorthand(verbosityData('')), 'absent flag falls back to V').toBe('V');
189
+ expect(verbosityShorthand(verbosityData('--verbose')),
190
+ 'a multi-character flag is not a commander shorthand; fall back to V').toBe('V');
191
+ });
192
+ });
package/src/cli.test.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { describe, it, expect, afterEach } from 'vitest';
2
2
  import { createCLI, buildTheme, applyHelpTheme, Neon, Dark,
3
- setCommandGroup, verboseCount, registerStream,
3
+ setCommandGroup, verboseCount, isQuiet, registerStream,
4
4
  channel, getStreamDefs } from './cli';
5
5
 
6
6
  describe('createCLI', () => {
@@ -247,6 +247,45 @@ describe('help structure — line-by-line parity', () => {
247
247
  });
248
248
  });
249
249
 
250
+ describe('help ARGUMENTS section', () => {
251
+ /** Plain help lines for a `gen` command with the given arguments. */
252
+ function genHelpLines(withDescriptions: boolean): string[] {
253
+ const { program } = createCLI({ name: 'mytool', version: '1.2.3', description: 'A tool' });
254
+ const gen = program.command('gen').description('Generate');
255
+ if (withDescriptions) {
256
+ gen.argument('<shell>', 'shell to generate for')
257
+ .argument('[out]', 'output path');
258
+ } else {
259
+ gen.argument('<shell>').argument('[out]');
260
+ }
261
+ gen.option('--force', 'overwrite');
262
+ return stripANSI(gen.helpInformation()).split('\n');
263
+ }
264
+
265
+ it('lists described arguments with their descriptions', () => {
266
+ const lines = genHelpLines(true);
267
+ const argIdx = lines.findIndex(l => l.trim() === 'ARGUMENTS:');
268
+ expect(argIdx).toBeGreaterThanOrEqual(0);
269
+ expect(lines[argIdx + 1]).toMatch(/^\s+shell\s+shell to generate for$/);
270
+ expect(lines[argIdx + 2]).toMatch(/^\s+out\s+output path$/);
271
+ });
272
+
273
+ it('ARGUMENTS: appears after the description and before FLAGS:', () => {
274
+ const lines = genHelpLines(true);
275
+ const descIdx = lines.findIndex(l => l.trim() === 'Generate');
276
+ const argIdx = lines.findIndex(l => l.trim() === 'ARGUMENTS:');
277
+ const flagIdx = lines.findIndex(l => l.trim() === 'FLAGS:');
278
+ expect(descIdx).toBeLessThan(argIdx);
279
+ expect(argIdx).toBeLessThan(flagIdx);
280
+ });
281
+
282
+ it('omits ARGUMENTS: when no argument has a description', () => {
283
+ const lines = genHelpLines(false);
284
+ expect(lines.some(l => l.trim() === 'ARGUMENTS:')).toBe(false);
285
+ expect(lines.some(l => l.trim() === 'Arguments:')).toBe(false);
286
+ });
287
+ });
288
+
250
289
  describe('CLIConfig disable', () => {
251
290
  it('disable.format=true → no format key in opts after parse', () => {
252
291
  const { program } = createCLI({
@@ -608,6 +647,61 @@ describe('verbose flag', () => {
608
647
  });
609
648
  });
610
649
 
650
+ // ---------------------------------------------------------------------------
651
+ // Quiet accessor
652
+ // ---------------------------------------------------------------------------
653
+
654
+ describe('isQuiet', () => {
655
+ async function quietOf(argv: string[], disableQuiet = false): Promise<boolean | undefined> {
656
+ const { program } = createCLI({
657
+ name: 't', version: '0.1.0', description: 't',
658
+ disable: { quiet: disableQuiet },
659
+ });
660
+ let quiet: boolean | undefined;
661
+ program.command('run').action(function (this: any) {
662
+ quiet = isQuiet(this);
663
+ });
664
+ await program.parseAsync(['node', 't', ...argv]);
665
+ return quiet;
666
+ }
667
+
668
+ it('is false before parsing', () => {
669
+ const { program } = createCLI({ name: 't', version: '0.1.0', description: 't' });
670
+ const run = program.command('run');
671
+ expect(isQuiet(program)).toBe(false);
672
+ expect(isQuiet(run)).toBe(false);
673
+ });
674
+
675
+ it('is false when --quiet is absent', async () => {
676
+ expect(await quietOf(['run'])).toBe(false);
677
+ });
678
+
679
+ it('reads root --quiet from a subcommand', async () => {
680
+ expect(await quietOf(['--quiet', 'run'])).toBe(true);
681
+ });
682
+
683
+ it('reads root --quiet given after the subcommand', async () => {
684
+ expect(await quietOf(['run', '--quiet'])).toBe(true);
685
+ });
686
+
687
+ it('is false when the flag is disabled', async () => {
688
+ expect(await quietOf(['run'], true)).toBe(false);
689
+ });
690
+
691
+ it('wins over -V: quiet reported, verbose count 0', async () => {
692
+ const { program } = createCLI({ name: 't', version: '0.1.0', description: 't' });
693
+ let quiet: boolean | undefined;
694
+ let count = -1;
695
+ program.command('run').action(function (this: any) {
696
+ quiet = isQuiet(this);
697
+ count = verboseCount(this);
698
+ });
699
+ await program.parseAsync(['node', 't', '-VV', '--quiet', 'run']);
700
+ expect(quiet).toBe(true);
701
+ expect(count).toBe(0);
702
+ });
703
+ });
704
+
611
705
  // ---------------------------------------------------------------------------
612
706
  // Named streams
613
707
  // ---------------------------------------------------------------------------
package/src/cli.ts CHANGED
@@ -26,18 +26,47 @@
26
26
  */
27
27
 
28
28
  import { Command, Help } from 'commander';
29
- import { parity } from './tui/parity.js';
29
+ import { parity, type ParityData } from './tui/parity.js';
30
30
  import { registerOutputFlags } from './output/flags.js';
31
+ import { EXIT_USAGE } from './output/error.js';
32
+ import { install as installNetPolicy, setProcessOffline } from './netpolicy.js';
33
+ import { installCompletionRequest } from './completion.js';
31
34
  import './output/builtins.js';
35
+ export { ErrOffline, OfflineError, guardFetch, isOffline, isOfflineError,
36
+ withOffline } from './netpolicy.js';
32
37
  export { HintSet, hintsEnabled, renderHints, active,
33
38
  registerUpgradeHints, registerVersionHints } from './hint.js';
34
39
  export type { Hint, HintOptions } from './hint.js';
35
40
 
36
41
  // ---------------------------------------------------------------------------
37
- // Verbose count — stacking -V flags
42
+ // Verbose count — stacking -V flags; quiet
38
43
  // ---------------------------------------------------------------------------
39
44
 
40
45
  const verboseCountMap = new WeakMap<Command, number>();
46
+ const quietMap = new WeakMap<Command, boolean>();
47
+
48
+ /**
49
+ * Return the single-character shorthand declared by the parity contract's
50
+ * `verbosity.flag`, with leading dashes stripped. A contract value that is
51
+ * not a single character after stripping falls back to `V`.
52
+ *
53
+ * Taking the contract as a parameter (rather than reading the module-level
54
+ * `parity`) keeps the mapping testable against a constructed `ParityData`
55
+ * without mutating the shared `parity.json`.
56
+ */
57
+ export function verbosityShorthand(d: ParityData): string {
58
+ const s = (d.verbosity?.flag ?? '').replace(/^-+/, '');
59
+ return s.length === 1 ? s : 'V';
60
+ }
61
+
62
+ /**
63
+ * Render the `-V` option spec commander registers, e.g. `-V, --verbose`.
64
+ * The shorthand comes from the parity contract; the long name is
65
+ * kit-local (the contract declares only the shorthand).
66
+ */
67
+ export function verbosityFlagSpec(d: ParityData): string {
68
+ return `-${verbosityShorthand(d)}, --verbose`;
69
+ }
41
70
 
42
71
  /** Read the accumulated -V count for a parsed command tree. */
43
72
  export function verboseCount(cmd: Command): number {
@@ -51,6 +80,24 @@ export function verboseCount(cmd: Command): number {
51
80
  return 0;
52
81
  }
53
82
 
83
+ /**
84
+ * Report whether `--quiet` is in effect for a parsed command tree.
85
+ *
86
+ * `--quiet` wins over `-V`: when set, `verboseCount` reads 0 and the
87
+ * logger level is the contract's `verbosity.quiet_override`. False before
88
+ * parsing and when `disable.quiet` drops the flag.
89
+ */
90
+ export function isQuiet(cmd: Command): boolean {
91
+ // Walk up to root to find the stored flag.
92
+ let c: Command | null = cmd;
93
+ while (c) {
94
+ const q = quietMap.get(c);
95
+ if (q !== undefined) return q;
96
+ c = c.parent ?? null;
97
+ }
98
+ return false;
99
+ }
100
+
54
101
  // ---------------------------------------------------------------------------
55
102
  // Named streams — registerStream / channel
56
103
  // ---------------------------------------------------------------------------
@@ -62,9 +109,43 @@ interface StreamDef {
62
109
 
63
110
  const streamDefsMap = new WeakMap<Command, StreamDef[]>();
64
111
 
112
+ /**
113
+ * Return the long flag name declared by the parity contract's
114
+ * `streams.flag`, with leading dashes stripped (commander's parsed option
115
+ * key is the undashed camelCase name). Falls back to `stream`.
116
+ *
117
+ * Taking the contract as a parameter (rather than reading the module-level
118
+ * `parity`) keeps the mapping testable against a constructed `ParityData`
119
+ * without mutating the shared `parity.json`.
120
+ */
121
+ export function streamFlagName(d: ParityData): string {
122
+ const name = (d.streams?.flag ?? '').replace(/^-+/, '');
123
+ return name === '' ? 'stream' : name;
124
+ }
125
+
126
+ /**
127
+ * Render a stream's prefix from the parity contract's
128
+ * `streams.label_format` template. The template's `{name}` placeholder is
129
+ * substituted with the stream name; a trailing space separates the label
130
+ * from the payload.
131
+ */
132
+ export function streamLabel(d: ParityData, name: string): string {
133
+ const format = d.streams?.label_format || '[{name}]';
134
+ return format.split('{name}').join(name) + ' ';
135
+ }
136
+
137
+ /**
138
+ * Resolve the parity contract's `streams.output` destination to a stream.
139
+ * Anything other than `stdout` resolves to stderr, which is the contract's
140
+ * declared destination.
141
+ */
142
+ export function streamOutput(d: ParityData): NodeJS.WritableStream {
143
+ return d.streams?.output === 'stdout' ? process.stdout : process.stderr;
144
+ }
145
+
65
146
  /**
66
147
  * Register a named diagnostic stream on a command.
67
- * Adds a `--stream <names>` option (comma-separated) on first call.
148
+ * Adds the parity contract's stream option (comma-separated) on first call.
68
149
  *
69
150
  * Parity note: Go uses StringSlice (repeatable --stream); TS and Python
70
151
  * use a single comma-separated string value.
@@ -76,9 +157,9 @@ export function registerStream(
76
157
  if (!defs) {
77
158
  defs = [];
78
159
  streamDefsMap.set(cmd, defs);
79
- // Add --stream option on first registration.
160
+ // Add the contract's stream option on first registration.
80
161
  cmd.option(
81
- '--stream <names>',
162
+ `--${streamFlagName(parity)} <names>`,
82
163
  'Enable diagnostic streams (comma-separated)',
83
164
  );
84
165
  }
@@ -93,24 +174,37 @@ export function getStreamDefs(cmd: Command): StreamDef[] {
93
174
  const noopWriter = { write(_s: string): boolean { return true; } };
94
175
 
95
176
  /**
96
- * Return a writer for a named stream. When the stream is enabled via
97
- * `--stream`, writes go to stderr with a `[name] ` prefix. Otherwise
98
- * writes are discarded.
177
+ * Commander stores a parsed option under the camelCased form of its long
178
+ * name (`--log-level` → `opts.logLevel`), so the contract's flag name must
179
+ * be camelCased before it is read back off `cmd.opts()`.
180
+ */
181
+ function optionKey(flagName: string): string {
182
+ return flagName.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());
183
+ }
184
+
185
+ /**
186
+ * Return a writer for a named stream. When the stream is enabled via the
187
+ * parity contract's stream flag, writes go to the contract's
188
+ * `streams.output` destination, prefixed with its `streams.label_format`
189
+ * label. Otherwise writes are discarded.
99
190
  */
100
191
  export function channel(
101
192
  cmd: Command, name: string,
102
193
  ): { write(s: string): boolean } {
103
194
  const opts = cmd.opts();
104
- const enabled = typeof opts.stream === 'string'
105
- ? opts.stream.split(',').map((s: string) => s.trim()).includes(name)
195
+ const raw = opts[optionKey(streamFlagName(parity))];
196
+ const enabled = typeof raw === 'string'
197
+ ? raw.split(',').map((s: string) => s.trim()).includes(name)
106
198
  : false;
107
199
  if (!enabled) return noopWriter;
200
+ const prefix = streamLabel(parity, name);
201
+ const w = streamOutput(parity);
108
202
  return {
109
203
  write(s: string): boolean {
110
204
  // Split on newlines and prefix each line (parity with Go/Python).
111
205
  const lines = s.split('\n');
112
206
  for (const line of lines) {
113
- if (line) process.stderr.write(`[${name}] ${line}\n`);
207
+ if (line) w.write(`${prefix}${line}\n`);
114
208
  }
115
209
  return true;
116
210
  },
@@ -238,6 +332,7 @@ export interface CLIConfig {
238
332
  quiet?: boolean;
239
333
  noColor?: boolean;
240
334
  hints?: boolean;
335
+ offline?: boolean;
241
336
  };
242
337
 
243
338
  /** Command groups for partitioned help (e.g. COMMANDS vs MANAGEMENT). */
@@ -463,6 +558,21 @@ export function applyHelpTheme(
463
558
  output.push('');
464
559
  }
465
560
 
561
+ // Arguments — only listed when at least one carries a description
562
+ // (Commander's visibleArguments rule); title from parity.json.
563
+ const argList = helper.visibleArguments(cmd);
564
+ if (argList.length > 0) {
565
+ const title = parity.help.sections?.['arguments']?.title ?? 'ARGUMENTS';
566
+ output.push(helper.styleTitle(`${title}:`));
567
+ for (const a of argList) {
568
+ output.push(callFormatItem(
569
+ helper.styleArgumentTerm(helper.argumentTerm(a)),
570
+ helper.styleArgumentDescription(helper.argumentDescription(a)),
571
+ ));
572
+ }
573
+ output.push('');
574
+ }
575
+
466
576
  // Collect sections in parity order.
467
577
  const helpSections: { name: string; items: string[] }[] = [];
468
578
 
@@ -598,6 +708,22 @@ export function applyHelpTheme(
598
708
  });
599
709
  }
600
710
 
711
+ /**
712
+ * Resolves operands as a command path below root, matching names and
713
+ * aliases. Only a fully-resolved path counts: "remote nosuch" names no
714
+ * command rather than falling back to "remote".
715
+ */
716
+ function findHelpTarget(root: Command, operands: string[]): Command | undefined {
717
+ let cmd: Command | undefined;
718
+ let scope = root;
719
+ for (const word of operands) {
720
+ cmd = scope.commands.find(c => c.name() === word || c.aliases().includes(word));
721
+ if (!cmd) return undefined;
722
+ scope = cmd;
723
+ }
724
+ return cmd;
725
+ }
726
+
601
727
  // ---------------------------------------------------------------------------
602
728
  // Factory
603
729
  // ---------------------------------------------------------------------------
@@ -663,16 +789,43 @@ export function createCLI(cfg: CLIConfig): CLIResult {
663
789
  program.option('--no-hints', 'Suppress next-step hints after command output', false);
664
790
  }
665
791
 
666
- // -V / --verbose: accumulator pattern for stacking (-VV = 2).
792
+ // --offline (cli-parity-guide, "Global Flags") disables all network
793
+ // access. It is the highest-precedence override: per-command network
794
+ // opt-ins (peer discovery, sync replication, repo creation, initial
795
+ // push, upgrade checks) must behave as if their corresponding opt-out
796
+ // flag had been passed. The override only forces opt-outs ON — it never
797
+ // un-sets an explicitly passed --no-* flag, which is why it stamps a
798
+ // marker rather than rewriting parsed options.
799
+ //
800
+ // Registering the flag alone would be advisory: a leaf that never
801
+ // consults the marker would still reach the wire. installNetPolicy
802
+ // guards globalThis.fetch so the refusal happens beneath naive callers.
803
+ if (!cfg.disable?.offline) {
804
+ program.option('--offline', 'Disable network access', false);
805
+ installNetPolicy();
806
+ // preSubcommand fires before a subcommand's action handler, and the
807
+ // root's own action for a leaf-less program; hook both so the marker
808
+ // is set whichever shape the adopter uses.
809
+ const stamp = (thisCmd: Command) => {
810
+ setProcessOffline(thisCmd.opts()['offline'] === true);
811
+ };
812
+ program.hook('preSubcommand', (thisCmd) => stamp(thisCmd));
813
+ program.hook('preAction', (thisCmd) => stamp(thisCmd));
814
+ }
815
+
816
+ // Stackable verbosity count flag (-VV = 2). The shorthand comes from the
817
+ // parity contract's verbosity block; commander takes the option spec as a
818
+ // runtime string, so it need not be a literal.
667
819
  program.option(
668
- '-V, --verbose', 'Increase verbosity',
820
+ verbosityFlagSpec(parity), 'Increase verbosity',
669
821
  (_: string, prev: number) => prev + 1, 0,
670
822
  );
671
- // Store count after parse; quiet overrides verbose.
823
+ // Store count + quiet after parse; quiet overrides verbose.
672
824
  program.hook('preAction', (thisCmd) => {
673
825
  const opts = thisCmd.opts();
674
- const count = opts.quiet ? 0 : (opts.verbose ?? 0);
675
- verboseCountMap.set(thisCmd, count);
826
+ const quiet = opts.quiet === true;
827
+ quietMap.set(thisCmd, quiet);
828
+ verboseCountMap.set(thisCmd, quiet ? 0 : (opts.verbose ?? 0));
676
829
  });
677
830
 
678
831
  if (cfg.groups?.some(g => g.hidden)) {
@@ -690,21 +843,34 @@ export function createCLI(cfg: CLIConfig): CLIResult {
690
843
  });
691
844
  }
692
845
 
693
- // help <group> subcommand (hidden from default help).
846
+ // help [command | group] subcommand (hidden from default help).
847
+ // Operands resolve in order: "all", a fully-resolved command path
848
+ // (a command wins over a group of the same name), a group ID; else a
849
+ // usage error (exit 2).
694
850
  if (cfg.groups && cfg.groups.length > 0) {
695
851
  const groupIds = cfg.groups.map(g => g.id);
696
- const helpCmd = program.command('help [group]')
697
- .description('Show help for a command group')
698
- .action((group?: string) => {
699
- if (group === 'all') {
700
- process.argv.push('--help-all');
852
+ const helpCmd = program.command('help [operands...]')
853
+ .description('Show help for a command or command group')
854
+ .action((operands: string[]) => {
855
+ if (operands.length === 0) {
701
856
  program.help();
702
- } else if (group && groupIds.includes(group)) {
703
- process.argv.push(`--help-${group}`);
857
+ }
858
+ if (operands.length === 1 && operands[0] === 'all') {
859
+ process.argv.push('--help-all');
704
860
  program.help();
705
- } else {
861
+ }
862
+ const target = findHelpTarget(program, operands);
863
+ if (target) {
864
+ target.help();
865
+ }
866
+ if (operands.length === 1 && groupIds.includes(operands[0]!)) {
867
+ process.argv.push(`--help-${operands[0]}`);
706
868
  program.help();
707
869
  }
870
+ program.error(
871
+ `error: unknown help topic '${operands.join(' ')}' for '${program.name()}'`,
872
+ { exitCode: EXIT_USAGE, code: 'commander.unknownCommand' },
873
+ );
708
874
  });
709
875
  // Hide from default help output.
710
876
  (helpCmd as any).hideHelp = true;
@@ -716,6 +882,10 @@ export function createCLI(cfg: CLIConfig): CLIResult {
716
882
  program.option(flag, g.usage, g.default ?? '');
717
883
  }
718
884
 
885
+ // Shell completion scripts call back into `<name> __complete`; answer
886
+ // it ahead of commander's parse so no hook or action runs on tab.
887
+ installCompletionRequest(program);
888
+
719
889
  // Apply brand color scheme + section order to --help output.
720
890
  // noColor is read lazily at render time inside applyHelpTheme.
721
891
  applyHelpTheme(program, theme, false, cfg.help?.sectionOrder,