@kaynooo/cli-guard 0.13.0 → 0.14.2

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 (3) hide show
  1. package/README.md +4 -4
  2. package/dist/cli.js +427 -152
  3. package/package.json +11 -11
package/README.md CHANGED
@@ -13,8 +13,8 @@ guard check --json --cwd "$PWD" - < command.txt
13
13
  | Rule | Refuses | Lives in |
14
14
  | --- | --- | --- |
15
15
  | `remote` | `ssh`, `scp`, `sftp`, `mosh`, `rsync` to a host, `DOCKER_HOST=ssh://`, `docker -H ssh://` | `src/remote.ts` |
16
- | `git` | `git stash` (pointing at `proof`, `base`, a commit first or `git worktree add`), `git add -A`/`.`/`-u`, `git commit -a` in any flag cluster, `git push` the user did not ask for, `git push --tags` without `--atomic` | `src/git.ts` |
17
- | `destructive` | `git reset --hard`, discarding the whole tree (`checkout -- .`, `checkout -f`, `restore .`, `switch -f`), `git clean -f`, a force push (`--force`, `-f`, `--mirror`, `+refspec`; `--force-with-lease` passes), `git branch -D`, a `git rebase` (`--continue` and `--abort` pass), `filter-branch`, `rm -r` on `/`, `~`, `$HOME`, `.`, `..`, `*` or a top-level directory, a download piped into a shell (`curl ... \| sh`, `bash <(curl ...)`); each refusal names the safe route: a commit with `gc` first, `base`, `git worktree add`, `--force-with-lease` | `src/destructive.ts` |
16
+ | `git` | `git stash` (pointing at `base proof`, `base`, a commit first or `git worktree add`), `git add -A`/`.`/`-u`, `git commit -a` in any flag cluster, `git push` the user did not ask for, `git push --tags` without `--atomic` | `src/git.ts` |
17
+ | `destructive` | `git reset --hard`, discarding the whole tree (`checkout -- .`, `checkout -f`, `restore .`, `switch -f`), `git clean -f`, a force push (`--force`, `-f`, `--mirror`, `+refspec`; `--force-with-lease` passes), `git branch -D`, a `git rebase` (`--continue` and `--abort` pass), `filter-branch`, `rm -r` on `/`, `~`, `$HOME`, `.`, `..`, `*` or a top-level directory, a download piped into a shell (`curl ... \| sh`, `bash <(curl ...)`), `dl --exec --yes` on a script no `--sha256` or `--sums` pins; each refusal names the safe route: a commit with `gc` first, `base`, `git worktree add`, `--force-with-lease`, `dl <url>` then `dl <url> --exec --sha256 <sha>` | `src/destructive.ts` |
18
18
  | `commit` | a commit message breaking the format: no Conventional Commit title, a trailer, a body over two lines, a bullet list, a hard wrap; `-m`, `-F <file>` and `-F -` with a heredoc are read; the refusal spells the rule out and points at `gc` | `src/commit.ts`, the validator in `@kaynooo/cli-git` |
19
19
  | `sql` | a SQL client, console or dump tool fed a write (INSERT, UPDATE, DELETE, DDL, migrations, fixtures) outside a test database | `@kaynooo/cli-db` (`src/clients.ts`, `src/guard.ts`) |
20
20
  | `env` | a command reading, writing or printing an env file or the whole environment; `guard path` refuses a file tool opening one | `@kaynooo/cli-env` (`src/guard.ts`) |
@@ -39,7 +39,7 @@ Every rule reads the command with one shell parser (`packages/kit/src/shell.ts`)
39
39
 
40
40
  `guard hook <event>` speaks Claude Code's hook protocol, the event JSON on stdin and the reply JSON on stdout; the `cli-hooks` plugin at the repo root registers it (see the root README).
41
41
 
42
- - `pre-tool-use`: a Bash call breaking a rule is denied with the routes, an install with the wrong manager with the command to run instead, an install `pkg` refuses with its report; a Read, Edit or Write of an env file is denied.
42
+ - `pre-tool-use`: a Bash call breaking a rule is denied with the routes, an install with the wrong manager with the command to run instead, an install `pkg` refuses (or fails to check) with its report; a file tool (Read, Edit, MultiEdit, Write, NotebookEdit, Grep, Glob) reaching an env file is denied.
43
43
  - `user-prompt-submit`: a prompt naming a push lets `git push` through until the next prompt; the state sits in `$XDG_STATE_HOME/guard/push-asked/<session>`, an empty file left behind by each session that ended on such a prompt. Claude Code sends no origin with the event, so a prompt it sends itself (a notification, a peer session's message) counts too, where the dotfiles mod counts only what the user typed.
44
- - `session-start`: the installed @kaynooo/cli-* bins, one line each, handed to Claude as context.
44
+ - `session-start`: the installed `@kaynooo/cli-*` bins, one line each, handed to Claude as context.
45
45
  - Nothing printed lets the call go ahead. Any failure exits 1, which Claude Code reports without blocking, never 2, which would block.
package/dist/cli.js CHANGED
@@ -1,19 +1,19 @@
1
1
  #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
2
  // @bun
3
-
4
- // src/cli.ts
5
- import { appendFileSync as appendFileSync2, existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync6, rmSync, statSync as statSync2, writeFileSync } from "fs";
6
- import { homedir as homedir4 } from "os";
7
- import { dirname as dirname5 } from "path";
8
- import process17 from "process";
9
- // ../kit/src/args.ts
10
- import process9 from "process";
11
- import { parseArgs } from "util";
3
+ var __esm = (fn, res, err) => () => {
4
+ if (fn)
5
+ try {
6
+ res = fn(fn = 0);
7
+ } catch (e) {
8
+ err = [e];
9
+ }
10
+ if (err)
11
+ throw err[0];
12
+ return res;
13
+ };
12
14
 
13
15
  // ../kit/src/mode.ts
14
16
  import process2 from "process";
15
- var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
16
- var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
17
17
  function isSet(value) {
18
18
  return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
19
19
  }
@@ -27,12 +27,13 @@ function outputMode(stream = process2.stdout, env = process2.env) {
27
27
  return "terminal";
28
28
  return isSet(env.CI) ? "ci" : "pipe";
29
29
  }
30
+ var MODES, AGENT_VARIABLES;
31
+ var init_mode = __esm(() => {
32
+ MODES = new Set(["terminal", "ci", "agent", "pipe"]);
33
+ AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
34
+ });
30
35
 
31
- // ../kit/src/style.ts
32
- import process6 from "process";
33
-
34
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
35
- var G = /^[a-f0-9]+$/i;
36
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
36
37
  function b(r) {
37
38
  let e = r.startsWith("#") ? r.slice(1) : r;
38
39
  if (!G.test(e))
@@ -43,11 +44,6 @@ function b(r) {
43
44
  throw Error(`Invalid hex color length: ${e.length}`);
44
45
  return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
45
46
  }
46
- var B = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
47
- let [l, n, c] = b(r);
48
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
49
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
50
- var h = new Set(["", "1", "2", "3", "true"]);
51
47
  function C(r, e = globalThis.process?.env ?? {}) {
52
48
  if (e.FORCE_COLOR !== undefined)
53
49
  return h.has(e.FORCE_COLOR);
@@ -84,13 +80,21 @@ function f(r, e = []) {
84
80
  function Fe(r = {}) {
85
81
  return f(r);
86
82
  }
87
- var o = Fe();
83
+ var G, B, h, o;
84
+ var init_chunk_x450vn3m = __esm(() => {
85
+ G = /^[a-f0-9]+$/i;
86
+ B = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
87
+ let [l, n, c] = b(r);
88
+ return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
89
+ }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
90
+ h = new Set(["", "1", "2", "3", "true"]);
91
+ o = Fe();
92
+ });
88
93
 
89
- // ../kit/src/theme.ts
90
- import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
91
- import { homedir as homedir2 } from "os";
92
- import { join as join3, resolve as resolve2 } from "path";
93
- import process5 from "process";
94
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
95
+ var init_colors = __esm(() => {
96
+ init_chunk_x450vn3m();
97
+ });
94
98
 
95
99
  // ../kit/src/config.ts
96
100
  import { existsSync } from "fs";
@@ -106,6 +110,9 @@ function findUp(names, from = process3.cwd(), stop = () => false) {
106
110
  return;
107
111
  }
108
112
  }
113
+ var init_config = __esm(() => {
114
+ init_args();
115
+ });
109
116
 
110
117
  // ../kit/src/user-config.ts
111
118
  import { existsSync as existsSync2, readFileSync } from "fs";
@@ -141,36 +148,18 @@ function configuredNumber(bin, key, fallback, where = {}, legacy = []) {
141
148
  const value = readUserConfig(bin, where, legacy)[key];
142
149
  return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
143
150
  }
151
+ var init_user_config = () => {};
144
152
 
145
153
  // ../kit/src/theme.ts
146
- var ENDS = new Map;
147
- var DEFAULT = {
148
- colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
149
- glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
150
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
151
- bins: {},
152
- gradient: ["#c084fc", "#67e8f9"]
153
- };
154
- var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
155
- var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
156
- var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
157
- var PRESETS = {
158
- default: {},
159
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
160
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
161
- ascii: { glyphs: ASCII }
162
- };
163
- var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
164
- var HEX = /^#[0-9a-f]{6}$/i;
165
- var CONTROL = /\p{Cc}/u;
166
- var MAX_FILE_BYTES = 64 * 1024;
167
- var SPACES = /\s+/;
154
+ import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
155
+ import { homedir as homedir2 } from "os";
156
+ import { join as join3, resolve as resolve2 } from "path";
157
+ import process5 from "process";
168
158
  function isColorSpec(spec) {
169
159
  if (typeof spec === "number")
170
160
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
171
161
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
172
162
  }
173
- var CUBE = [0, 95, 135, 175, 215, 255];
174
163
  function cubeLevel(channel) {
175
164
  return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
176
165
  }
@@ -275,7 +264,6 @@ function applyFile(theme, file, where, warn) {
275
264
  function endsWalk(home) {
276
265
  return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
277
266
  }
278
- var warned = new Set;
279
267
  function warnOnce(message) {
280
268
  if (warned.has(message))
281
269
  return;
@@ -312,8 +300,6 @@ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(
312
300
  }
313
301
  return { theme, sources, preset };
314
302
  }
315
- var current;
316
- var currentKey = "";
317
303
  function activeTheme() {
318
304
  const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
319
305
  if (current === undefined || key !== currentKey) {
@@ -322,8 +308,38 @@ function activeTheme() {
322
308
  }
323
309
  return current;
324
310
  }
311
+ var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
312
+ var init_theme = __esm(() => {
313
+ init_config();
314
+ init_user_config();
315
+ ENDS = new Map;
316
+ DEFAULT = {
317
+ colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
318
+ glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
319
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
320
+ bins: {},
321
+ gradient: ["#c084fc", "#67e8f9"]
322
+ };
323
+ BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
324
+ MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
325
+ ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
326
+ PRESETS = {
327
+ default: {},
328
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
329
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
330
+ ascii: { glyphs: ASCII }
331
+ };
332
+ STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
333
+ HEX = /^#[0-9a-f]{6}$/i;
334
+ CONTROL = /\p{Cc}/u;
335
+ MAX_FILE_BYTES = 64 * 1024;
336
+ SPACES = /\s+/;
337
+ CUBE = [0, 95, 135, 175, 215, 255];
338
+ warned = new Set;
339
+ });
325
340
 
326
341
  // ../kit/src/style.ts
342
+ import process6 from "process";
327
343
  function takesControlCodes(stream, env = process6.env) {
328
344
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
329
345
  }
@@ -334,17 +350,22 @@ function role(name, stream, env = process6.env) {
334
350
  const colors = paint(stream, env);
335
351
  return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
336
352
  }
337
- var STATUS_WORDS = {
338
- passed: ["passed", "success", "succeeded", "ok"],
339
- failed: ["failed", "failure", "error", "errored"],
340
- running: ["running", "in_progress", "started", "holding"],
341
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
342
- skipped: ["skipped", "cancelled", "canceled", "manual"]
343
- };
344
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
353
+ var STATUS_WORDS, STATUS_OF;
354
+ var init_style = __esm(() => {
355
+ init_colors();
356
+ init_mode();
357
+ init_theme();
358
+ STATUS_WORDS = {
359
+ passed: ["passed", "success", "succeeded", "ok"],
360
+ failed: ["failed", "failure", "error", "errored"],
361
+ running: ["running", "in_progress", "started", "holding"],
362
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
363
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
364
+ };
365
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
366
+ });
345
367
 
346
368
  // ../kit/src/format.ts
347
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
348
369
  function formatSeconds(total) {
349
370
  let rest = Math.max(0, Math.round(total));
350
371
  const amounts = UNITS.map(([unit, size]) => {
@@ -365,15 +386,38 @@ function upTo(text, separator) {
365
386
  const end = text.indexOf(separator);
366
387
  return end === -1 ? text : text.slice(0, end);
367
388
  }
368
- var ESCAPE = String.fromCharCode(27);
389
+ var UNITS, ESCAPE;
390
+ var init_format = __esm(() => {
391
+ init_mode();
392
+ init_style();
393
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
394
+ ESCAPE = String.fromCharCode(27);
395
+ });
369
396
 
370
397
  // ../kit/src/help.ts
371
398
  import process7 from "process";
372
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
373
- var USAGE_PREFIX = /^usage:\s*/i;
374
- var FULL_STOP = /\.$/;
375
399
  function usageLine(usage, colors = paint(process7.stdout)) {
376
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
400
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
401
+ `);
402
+ const blank = lines.indexOf("");
403
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
404
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
405
+ const colon = synopses[0].indexOf(": ");
406
+ const inline = synopses[0].slice(colon + 2);
407
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
408
+ if (colon !== -1)
409
+ synopses[0] = synopses[0].slice(0, colon);
410
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
411
+ `)}`;
412
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
413
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
414
+ return [head, ...lead, ...rest].join(`
415
+ `);
416
+ }
417
+ function prose(line, colors) {
418
+ if (colors.cyan("x") === "x")
419
+ return line;
420
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
377
421
  }
378
422
  function helpText(usage, options, colors = paint(process7.stdout), { examples = [], exits = [] } = {}) {
379
423
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -408,7 +452,6 @@ function exampleRows(examples, colors = paint(process7.stdout)) {
408
452
  return [];
409
453
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
410
454
  }
411
- var MAX_INLINE_CHOICES = 24;
412
455
  function optionRows(options, colors = paint(process7.stdout)) {
413
456
  const rows = Object.entries(options).map(([name, option]) => {
414
457
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -423,6 +466,15 @@ function optionRows(options, colors = paint(process7.stdout)) {
423
466
  const width = Math.max(0, ...rows.map((row) => row.width));
424
467
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
425
468
  }
469
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
470
+ var init_help = __esm(() => {
471
+ init_mode();
472
+ init_style();
473
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
474
+ USAGE_PREFIX = /^usage:\s*/i;
475
+ FULL_STOP = /\.$/;
476
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
477
+ });
426
478
 
427
479
  // ../kit/src/text.ts
428
480
  function distance(a, b) {
@@ -450,6 +502,8 @@ function closest(name, names) {
450
502
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
451
503
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
452
504
  }
505
+ var init_text = () => {};
506
+
453
507
  // ../kit/src/input.ts
454
508
  import process8 from "process";
455
509
  async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
@@ -463,40 +517,23 @@ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
463
517
  fail(`no file ${path}`);
464
518
  return file.text();
465
519
  }
520
+ var init_input = __esm(() => {
521
+ init_args();
522
+ });
466
523
 
467
524
  // ../kit/src/args.ts
468
- var DASHES = /^-+/;
525
+ import process9 from "process";
526
+ import { parseArgs } from "util";
469
527
  function jsonOption(holds) {
470
528
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
471
529
  }
472
- class Exit extends Error {
473
- code;
474
- hint;
475
- constructor(message, code, hint) {
476
- super(message);
477
- this.code = code;
478
- this.hint = hint;
479
- }
480
- }
481
530
  function fail(message, code = 2, hint) {
482
531
  throw new Exit(message, code, hint);
483
532
  }
484
-
485
- class UsageError extends Exit {
486
- constructor(message, hint) {
487
- super(message, 2, hint);
488
- }
489
- }
490
533
  function badUsage(message) {
491
534
  throw new UsageError(message);
492
535
  }
493
536
 
494
- class HelpShown extends Exit {
495
- constructor() {
496
- super("help shown", 0);
497
- }
498
- }
499
-
500
537
  class Completing {
501
538
  options;
502
539
  positionals;
@@ -507,11 +544,6 @@ class Completing {
507
544
  this.candidates = candidates;
508
545
  }
509
546
  }
510
- var completion = { active: false };
511
- var OUTPUT_OPTIONS = {
512
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
513
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
514
- };
515
547
  function applyOutput(color, plain, env = process9.env) {
516
548
  const when = plain === true ? "never" : color ?? "auto";
517
549
  if (when === "auto")
@@ -665,7 +697,6 @@ function parseError(error) {
665
697
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
666
698
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
667
699
  }
668
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
669
700
  function nearestOption(message, options, allowNegative) {
670
701
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
671
702
  if (typed === undefined)
@@ -681,6 +712,69 @@ function nearestOption(message, options, allowNegative) {
681
712
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
682
713
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
683
714
  }
715
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
716
+ var init_args = __esm(() => {
717
+ init_format();
718
+ init_help();
719
+ init_text();
720
+ init_help();
721
+ init_input();
722
+ DASHES = /^-+/;
723
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
724
+ Exit = class Exit extends Error {
725
+ code;
726
+ hint;
727
+ [EXIT] = true;
728
+ constructor(message, code, hint) {
729
+ super(message);
730
+ this.code = code;
731
+ this.hint = hint;
732
+ }
733
+ static [Symbol.hasInstance](value) {
734
+ if (this !== Exit)
735
+ return Function.prototype[Symbol.hasInstance].call(this, value);
736
+ return typeof value === "object" && value !== null && value[EXIT] === true;
737
+ }
738
+ };
739
+ UsageError = class UsageError extends Exit {
740
+ constructor(message, hint) {
741
+ super(message, 2, hint);
742
+ }
743
+ };
744
+ HelpShown = class HelpShown extends Exit {
745
+ constructor() {
746
+ super("help shown", 0);
747
+ }
748
+ };
749
+ completion = { active: false };
750
+ OUTPUT_OPTIONS = {
751
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
752
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
753
+ };
754
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
755
+ });
756
+
757
+ // ../kit/src/folders.ts
758
+ function ignoredFolders(extra = [], where = {}) {
759
+ const configured = readUserConfig("config", where).ignore;
760
+ const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
761
+ return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
762
+ }
763
+ var SKIPPED_FOLDERS;
764
+ var init_folders = __esm(() => {
765
+ init_user_config();
766
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
767
+ });
768
+
769
+ // src/cli.ts
770
+ import { appendFileSync as appendFileSync2, existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync6, rmSync, statSync as statSync2, writeFileSync } from "fs";
771
+ import { homedir as homedir4 } from "os";
772
+ import { dirname as dirname5 } from "path";
773
+ import process18 from "process";
774
+
775
+ // ../kit/src/index.ts
776
+ init_args();
777
+
684
778
  // ../kit/src/argv.ts
685
779
  import { readFileSync as readFileSync3, realpathSync } from "fs";
686
780
  import { resolve as resolve3 } from "path";
@@ -705,6 +799,18 @@ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), scr
705
799
  const after = at === -1 ? [] : cmdline.slice(at + 1);
706
800
  return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
707
801
  }
802
+ // ../kit/src/chart.ts
803
+ init_format();
804
+ init_mode();
805
+ init_style();
806
+ init_theme();
807
+ // ../kit/src/ci.ts
808
+ init_args();
809
+ init_format();
810
+
811
+ // ../kit/src/progress.ts
812
+ init_format();
813
+
708
814
  // ../kit/src/process.ts
709
815
  import { constants } from "os";
710
816
  import process11 from "process";
@@ -716,10 +822,10 @@ function exitCodeOf(code, signal) {
716
822
  return 128 + signal;
717
823
  return signal === null ? 129 : 128 + constants.signals[signal];
718
824
  }
719
- async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
825
+ async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
720
826
  const chunks = [];
721
827
  const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
722
- const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
828
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin: input === undefined ? stdin : new TextEncoder().encode(input), stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
723
829
  const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
724
830
  const timers = [];
725
831
  const killGroup = (killing) => {
@@ -796,38 +902,152 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
796
902
  }
797
903
 
798
904
  // ../kit/src/progress.ts
905
+ init_style();
906
+ init_theme();
799
907
  var ESC = String.fromCharCode(27);
800
908
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
801
909
  var RESET_STYLE = `${ESC}[0m`;
802
910
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
911
+
912
+ // ../kit/src/ci.ts
913
+ init_style();
914
+
915
+ // ../kit/src/tool.ts
916
+ init_format();
803
917
  // ../kit/src/cli.ts
918
+ init_args();
804
919
  import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
805
920
  import { dirname as dirname3, join as join5 } from "path";
806
- import process14 from "process";
921
+ import process15 from "process";
807
922
 
808
- // ../kit/src/notify.ts
923
+ // ../kit/src/askpass.ts
809
924
  import process12 from "process";
925
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
926
+ async function askpassClient(argv) {
927
+ const socketPath = process12.env[SOCKET_VARIABLE];
928
+ if (socketPath === undefined)
929
+ return;
930
+ const request = { prompt: argv[0] ?? "", ...process12.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
931
+ const { promise, resolve } = Promise.withResolvers();
932
+ let received = "";
933
+ try {
934
+ await Bun.connect({
935
+ unix: socketPath,
936
+ socket: {
937
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
938
+ `),
939
+ data: (_, chunk) => {
940
+ received += chunk.toString();
941
+ },
942
+ close: () => resolve(received),
943
+ error: () => resolve("")
944
+ }
945
+ });
946
+ } catch {
947
+ return 1;
948
+ }
949
+ const reply = await promise;
950
+ if (reply === "")
951
+ return 1;
952
+ const { answer } = JSON.parse(reply);
953
+ if (request.notice === true)
954
+ return 0;
955
+ if (answer === undefined)
956
+ return 1;
957
+ process12.stdout.write(`${answer}
958
+ `);
959
+ return 0;
960
+ }
961
+
962
+ // ../kit/src/completions.ts
963
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
964
+ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
965
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
966
+ set -l current (commandline -ct)
967
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
968
+ if test "$line" = __files__
969
+ __fish_complete_path $current
970
+ else
971
+ echo $line
972
+ end
973
+ end
974
+ end`;
975
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
976
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
977
+ local -a lines
978
+ COMPREPLY=()
979
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
980
+ for line in "\${lines[@]}"; do
981
+ if [[ $line == __files__ ]]; then
982
+ COMPREPLY+=($(compgen -f -- "$cur"))
983
+ else
984
+ words+="\${line%%$'\\t'*}"$'\\n'
985
+ fi
986
+ done
987
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
988
+ }`;
989
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
990
+ local line
991
+ local -a described plain
992
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
993
+ if [[ $line == __files__ ]]; then
994
+ _files
995
+ elif [[ $line == *$'\\t'* ]]; then
996
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
997
+ else
998
+ plain+=("$line")
999
+ fi
1000
+ done
1001
+ (( \${#described} )) && _describe -V value described
1002
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
1003
+ return 0
1004
+ }`;
1005
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1006
+ if (shell === "fish")
1007
+ return `${header}
1008
+ ${FISH_FUNCTION}
1009
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1010
+ `).join("")}`;
1011
+ if (shell === "bash")
1012
+ return `${header}
1013
+ ${BASH_FUNCTION}
1014
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
1015
+ `;
1016
+ return `${header}
1017
+ ${ZSH_FUNCTION}
1018
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
1019
+ `;
1020
+ }
1021
+
1022
+ // ../kit/src/notify.ts
1023
+ init_format();
1024
+ init_mode();
1025
+ import process13 from "process";
810
1026
  var NOTIFY_AFTER_MS = 1e4;
811
1027
  var CANCELLED = 130;
812
1028
  function base64(text) {
813
1029
  return Buffer.from(text).toString("base64");
814
1030
  }
815
- function notification(title, body, env = process12.env) {
816
- const id = `kit${process12.pid}`;
1031
+ function notification(title, body, env = process13.env) {
1032
+ const id = `kit${process13.pid}`;
817
1033
  const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
818
1034
  return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
819
1035
  }
820
- function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
1036
+ function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
821
1037
  if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
822
1038
  return;
823
1039
  stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
824
1040
  }
825
1041
 
1042
+ // ../kit/src/cli.ts
1043
+ init_style();
1044
+ init_text();
1045
+
826
1046
  // ../kit/src/usage.ts
827
1047
  import { appendFileSync, mkdirSync } from "fs";
828
1048
  import { homedir as homedir3 } from "os";
829
1049
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
830
- import process13 from "process";
1050
+ import process14 from "process";
831
1051
 
832
1052
  // ../kit/src/logs.ts
833
1053
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -841,14 +1061,14 @@ var usageError;
841
1061
  function noteUsageError(message) {
842
1062
  usageError = message;
843
1063
  }
844
- function stateHome(env = process13.env) {
1064
+ function stateHome(env = process14.env) {
845
1065
  const dir = env.XDG_STATE_HOME;
846
1066
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
847
1067
  }
848
- function usagePath(env = process13.env) {
1068
+ function usagePath(env = process14.env) {
849
1069
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
850
1070
  }
851
- function usageRecorded(env = process13.env) {
1071
+ function usageRecorded(env = process14.env) {
852
1072
  const off = env.KAYNOOO_CLI_NO_USAGE;
853
1073
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
854
1074
  }
@@ -857,12 +1077,12 @@ function flagNames(argv) {
857
1077
  const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
858
1078
  return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
859
1079
  }
860
- function usageEntry(bin, command, argv, code, now = new Date) {
1080
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
861
1081
  const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
862
1082
  usageError = undefined;
863
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1083
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
864
1084
  }
865
- function recordUsage(entry, env = process13.env) {
1085
+ function recordUsage(entry, env = process14.env) {
866
1086
  if (!usageRecorded(env))
867
1087
  return;
868
1088
  try {
@@ -878,7 +1098,11 @@ var LEVEL_OPTIONS = {
878
1098
  ...OUTPUT_OPTIONS,
879
1099
  help: { type: "boolean", short: "h", description: "show this help" }
880
1100
  };
881
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1101
+ var TOP_OPTIONS = {
1102
+ ...LEVEL_OPTIONS,
1103
+ version: { type: "boolean", short: "v", description: "print the version" },
1104
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1105
+ };
882
1106
  async function commandRows(all, colors) {
883
1107
  const commands = shown(all);
884
1108
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -952,8 +1176,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
952
1176
  `);
953
1177
  }
954
1178
  function printError(prefix, message, hint, cause) {
955
- const colors = paint(process14.stderr);
956
- const styled = takesControlCodes(process14.stderr);
1179
+ const colors = paint(process15.stderr);
1180
+ const styled = takesControlCodes(process15.stderr);
957
1181
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
958
1182
  const under = (label, text, tint) => text === undefined ? "" : `
959
1183
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -996,11 +1220,11 @@ async function dispatch(level, typed, { version, redact }) {
996
1220
  }
997
1221
  }
998
1222
  if (name === undefined && level.path.length > 1) {
999
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
1223
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stderr));
1000
1224
  return 2;
1001
1225
  }
1002
1226
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1003
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
1227
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stdout));
1004
1228
  return 0;
1005
1229
  }
1006
1230
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1111,6 +1335,19 @@ async function candidates(scope, defaultCommand, words, before = []) {
1111
1335
  }
1112
1336
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1113
1337
  }
1338
+ var COMPLETIONS = "--completions";
1339
+ function flagValue([flag = "", ...rest]) {
1340
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1341
+ }
1342
+ function printCompletionScript(name, args) {
1343
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1344
+ if (shell === undefined || args.length !== 1) {
1345
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1346
+ return 2;
1347
+ }
1348
+ console.log(completionScript(shell, [name]).trimEnd());
1349
+ return 0;
1350
+ }
1114
1351
  async function printCandidates(found) {
1115
1352
  for (const line of await found)
1116
1353
  console.log(line);
@@ -1133,15 +1370,20 @@ function packageVersion(entry = Bun.main) {
1133
1370
  }
1134
1371
  async function runCli(cli, argv = scriptArgs()) {
1135
1372
  const version = cli.version ?? packageVersion();
1373
+ const answered = await askpassClient(argv);
1374
+ if (answered !== undefined)
1375
+ return answered;
1136
1376
  if (argv[0] === COMPLETE)
1137
1377
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1378
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1379
+ return printCompletionScript(cli.name, flagValue(argv));
1138
1380
  const started = performance.now();
1139
1381
  const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
1140
1382
  const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1141
1383
  notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1142
1384
  if (cli.usage !== false) {
1143
1385
  try {
1144
- recordUsage(usageEntry(cli.name, command, argv, code));
1386
+ recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
1145
1387
  } catch {}
1146
1388
  }
1147
1389
  return code;
@@ -1161,19 +1403,47 @@ function commandPath(scope, argv) {
1161
1403
  }
1162
1404
  return path.length === 0 ? undefined : path.join(" ");
1163
1405
  }
1164
- // ../kit/src/folders.ts
1165
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1166
- function ignoredFolders(extra = [], where = {}) {
1167
- const configured = readUserConfig("config", where).ignore;
1168
- const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
1169
- return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
1170
- }
1406
+
1407
+ // ../kit/src/index.ts
1408
+ init_config();
1409
+
1410
+ // ../kit/src/excerpt.ts
1411
+ init_text();
1412
+
1413
+ // ../kit/src/index.ts
1414
+ init_folders();
1415
+ init_format();
1416
+
1417
+ // ../kit/src/git.ts
1418
+ init_args();
1419
+ // ../kit/src/limit.ts
1420
+ init_args();
1421
+
1422
+ // ../kit/src/index.ts
1423
+ init_mode();
1424
+
1425
+ // ../kit/src/report.ts
1426
+ init_style();
1427
+ init_text();
1171
1428
  // ../kit/src/secrets.ts
1172
1429
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1173
1430
  // ../kit/src/sessions.ts
1174
1431
  var {Glob } = globalThis.Bun;
1175
1432
  var SESSION_FILES = new Glob("*.json");
1176
1433
  var ACCOUNT_DIRS = new Glob("*/sessions");
1434
+
1435
+ // ../kit/src/index.ts
1436
+ init_style();
1437
+ init_text();
1438
+ init_theme();
1439
+ init_user_config();
1440
+
1441
+ // ../kit/src/watch.ts
1442
+ init_args();
1443
+ init_input();
1444
+ init_style();
1445
+ // ../kit/src/workspace-root.ts
1446
+ init_user_config();
1177
1447
  // ../kit/src/shell.ts
1178
1448
  var SEPARATORS = new Set([`
1179
1449
  `, ";", "|"]);
@@ -2467,7 +2737,7 @@ var INTERPRETERS = new Set(["bun", "deno", "node", "python", "python3", "ruby",
2467
2737
  var CODE_OPTIONS = new Set(["-e", "-c", "-p", "-E", "-pe", "-r", "--eval", "--print", "--command"]);
2468
2738
  var CAN_REACH_FILES = /read|write|open|exec|spawn|system|popen|import|require|eval|load|fetch|glob|stream|source|getline|constructor|file(?!s\b)|\bcat\b|\b(?:Bun|Deno|fs|os|io|sh|bash|process|globalThis|window|Function|qx)\b|\$\s*[`({]|`/i;
2469
2739
  var DECLARERS = new Set(["export", "declare", "local", "readonly", "typeset"]);
2470
- var HARMLESS = new Set(["ev", "redact", "ls", "stat", "test", "[", "[[", "touch"]);
2740
+ var HARMLESS = new Set(["ev", "ls", "stat", "test", "[", "[[", "touch"]);
2471
2741
  var GIT_HARMLESS = new Set(["check-ignore", "ls-files", "status"]);
2472
2742
  function variablesOf(command) {
2473
2743
  const variables = new Map;
@@ -2528,7 +2798,7 @@ function namesEnv(piece, variables) {
2528
2798
  }
2529
2799
 
2530
2800
  // ../env/src/guard-pipes.ts
2531
- var XARGS_SAFE = new Set(["ls", "stat", "wc", "test", "[", "touch", "echo", "printf", "basename", "dirname", "ev", "redact", ""]);
2801
+ var XARGS_SAFE = new Set(["ls", "stat", "wc", "test", "[", "touch", "echo", "printf", "basename", "dirname", "ev", ""]);
2532
2802
  var PARALLEL_VALUE_OPTIONS = new Set(["-j", "--jobs", "-P", "--max-procs", "-S", "--sshlogin", "-C", "--colsep", "-n", "--max-args", "-N", "-d", "--delimiter", "-E", "-I", "--timeout", "--delay", "--joblog", "--results", "--tmpdir", "-a", "--arg-file", "--halt", "--retries", "--tag-string"]);
2533
2803
  var IDENTIFIER = /^[A-Z_]\w*$/i;
2534
2804
  var READ_VALUE_OPTIONS = new Set(["-a", "-d", "-i", "-n", "-N", "-p", "-t", "-u"]);
@@ -2575,7 +2845,7 @@ function loopReadsListedEnv(pieces, index, variables) {
2575
2845
 
2576
2846
  // ../env/src/guard.ts
2577
2847
  var ENV_DUMP = /(?:console\.\w+|JSON\.stringify|Object\.(?:entries|keys|values)|print)\(\s*process\.env\s*[,)]/;
2578
- var USE_EV = '.env files hold secrets that must never reach the transcript, so they are not read, edited or printed directly. Use `ev` instead: `ev list`, `ev get KEY` (masked), `ev grep <regex>` for the keys matching it, `ev show <rev>:<file>` for one at a git revision, `printf %s "$value" | ev set KEY [file]` (`--empty` for an empty value), `ev unset KEY`, `ev cp KEY --from .env --to .env.local`, `ev mv KEY --from .env --to .env.local`, `ev diff a b`, `ev missing`; and pipe output that may carry a secret through `redact`, as `docker compose exec <svc> printenv | redact` or `docker compose config | redact`. If `ev` is missing: `bun install -g @kaynooo/cli-env`.';
2848
+ var USE_EV = '.env files hold secrets that must never reach the transcript, so they are not read, edited or printed directly. Use `ev` instead: `ev list`, `ev get KEY` (masked), `ev grep <regex>` for the keys matching it, `ev show <rev>:<file>` for one at a git revision, `printf %s "$value" | ev set KEY [file]` (`--empty` for an empty value), `ev unset KEY`, `ev cp KEY --from .env --to .env.local`, `ev mv KEY --from .env --to .env.local`, `ev diff a b`, `ev missing`; and pipe output that may carry a secret through `ev redact`, as `docker compose exec <svc> printenv | ev redact` or `docker compose config | ev redact`. If `ev` is missing: `bun install -g @kaynooo/cli-env`.';
2579
2849
  var USE_EV_SEARCH = "To search them, `ev grep <regex>` prints the matching keys, masked. `grep -l`, `-L` and `-c` (file names and counts) are allowed, and a tree-wide search can run as `rg <regex>`, which skips gitignored files, or `grep -r --exclude='.env*' <regex> .`.";
2580
2850
  function touchingPieces(command, options = {}) {
2581
2851
  const pieces = splitCommand(command);
@@ -2590,7 +2860,8 @@ function touchingPieces(command, options = {}) {
2590
2860
  if (!isDump)
2591
2861
  return false;
2592
2862
  for (let at = index;pieces[at]?.separator === "|"; at++) {
2593
- if (parseCommand(pieces[at + 1]?.command ?? "").program === "redact")
2863
+ const next = parseCommand(pieces[at + 1]?.command ?? "");
2864
+ if (next.program === "ev" && next.args[0] === "redact")
2594
2865
  return false;
2595
2866
  }
2596
2867
  return true;
@@ -2791,7 +3062,7 @@ function wrap(command) {
2791
3062
  // ../pkg/src/added.ts
2792
3063
  import { existsSync as existsSync4, readdirSync, readFileSync as readFileSync5 } from "fs";
2793
3064
  import { dirname as dirname4, join as join6 } from "path";
2794
- import process16 from "process";
3065
+ import process17 from "process";
2795
3066
  var REDIRECT2 = /^\d*[<>]/;
2796
3067
  var BARE_REDIRECT = /^\d*(?:[<>]|>>)$/;
2797
3068
  var ADDS = {
@@ -2823,7 +3094,7 @@ function manifestName(folder) {
2823
3094
  }
2824
3095
  function ownPackages() {
2825
3096
  const names = new Set;
2826
- let folder = process16.cwd();
3097
+ let folder = process17.cwd();
2827
3098
  while (true) {
2828
3099
  const name = manifestName(folder);
2829
3100
  if (name !== undefined)
@@ -3021,7 +3292,7 @@ var RISKY_CONFIG = /^(?:alias\.|core\.(?:sshcommand|hookspath|pager|editor|fsmon
3021
3292
  var RISKY_ENV = /^GIT_(?:CONFIG_(?:COUNT|PARAMETERS)|EXTERNAL_DIFF|ASKPASS|PROXY_COMMAND|PAGER)=/;
3022
3293
  var READS_CONFIG = new Set(["--get", "--get-all", "--get-regexp", "--list", "-l", "--unset", "--unset-all", "--show-origin", "--show-scope"]);
3023
3294
  var STAGE_BY_PATH = `Stage by path: the tree carries unrelated work and peer sessions edit it live. ${USE_GC}`;
3024
- var STASH = "Never `git stash`: a pop with nothing saved applies someone else's old stash. To prove a test fails without your change, `proof --keep <test> -- <cmd>` runs it at HEAD in a temporary worktree and again here; `base -- <cmd>` runs any command at HEAD (`--ref <rev>` another commit), the working tree untouched. To set edits aside before a cherry-pick, a rebase or a checkout, commit them with `gc` first, or do the other work in `git worktree add`.";
3295
+ var STASH = "Never `git stash`: a pop with nothing saved applies someone else's old stash. To prove a test fails without your change, `base proof --keep <test> -- <cmd>` runs it at HEAD in a temporary worktree and again here; `base -- <cmd>` runs any command at HEAD (`--ref <rev>` another commit), the working tree untouched. To set edits aside before a cherry-pick, a rebase or a checkout, commit them with `gc` first, or do the other work in `git worktree add`.";
3025
3296
  var ADD_ALL = `\`git add\` over the whole tree is refused. ${STAGE_BY_PATH}`;
3026
3297
  var COMMIT_ALL = `\`git commit -a\` stages the whole tree and is refused. ${STAGE_BY_PATH}`;
3027
3298
  var PUSH = "`git push` and `gp` run only when the user asked for a push in their latest prompt: say the commit is ready and let them ask.";
@@ -3297,7 +3568,9 @@ var PROTECTED_RM = "Never `rm -r` on a `.git` directory, on `~/Workspace` itself
3297
3568
  var FIND_DELETE_HOME = 'Never `find ~ -delete` or `find / -exec rm` (also `$HOME`): it deletes matches across the whole home or disk. Start `find` in the project folder or `.` and name the pattern, such as `find . -name "*.tmp" -delete`.';
3298
3569
  var REFLOG_EXPIRE = "Never `git reflog expire`, `git gc --prune=now` or `git update-ref -d`: they drop the reflog, unreachable commits or a ref, the only way back from a bad reset or rebase. Let git prune on its own schedule, and ask the user to run one when it is really wanted.";
3299
3570
  var DOCKER_PRUNE_ALL = "Never `docker system prune -a` (`--all`): it removes every image not used by a running container, volumes of other projects' stacks included with --volumes. `docker system prune` without -a drops only dangling data; remove named images with `docker rmi`.";
3300
- var PIPE_TO_SHELL = 'Never run what `curl`/`wget` fetches straight in a shell (`| sh`, `bash <(curl ...)`, `eval "$(curl ...)"`): it runs code nobody read. Download it to a file, read it, then run it, or hand the command to the user.';
3571
+ var PINNED_RUN = "`dl <url>` downloads it and prints its path and sha256; read that file, then `dl <url> --exec --sha256 <sha>` runs exactly what was read.";
3572
+ var PIPE_TO_SHELL = `Never run what \`curl\`/\`wget\` fetches straight in a shell (\`| sh\`, \`bash <(curl ...)\`, \`eval "$(curl ...)"\`): it runs code nobody read. ${PINNED_RUN} Or hand the command to the user.`;
3573
+ var UNPINNED_EXEC = `Never \`dl --exec --yes\` a script no \`--sha256\` or \`--sums\` pins: it runs code nobody read. ${PINNED_RUN}`;
3301
3574
  function hasOption(args, long, shorts) {
3302
3575
  for (const arg of args) {
3303
3576
  if (arg === "--")
@@ -3414,11 +3687,18 @@ function runsDownload(command) {
3414
3687
  return (SHELLS.has(program) || EVALUATORS.has(program)) && FETCH_SUBSTITUTION.test(piece.command);
3415
3688
  });
3416
3689
  }
3690
+ function runsUnpinned(args) {
3691
+ const own = args.includes("--") ? args.slice(0, args.indexOf("--")) : args;
3692
+ const given = (name) => own.some((arg) => arg === name || arg.startsWith(`${name}=`));
3693
+ return given("--exec") && given("--yes") && !given("--sha256") && !given("--sums");
3694
+ }
3417
3695
  function destructiveViolation(command) {
3418
3696
  if (runsDownload(command))
3419
3697
  return PIPE_TO_SHELL;
3420
3698
  for (const piece of splitCommand(command)) {
3421
3699
  const { program, args } = parseCommand(piece.command);
3700
+ if (program === "dl" && runsUnpinned(args))
3701
+ return UNPINNED_EXEC;
3422
3702
  if (program === "rm" && removesBroadly(args))
3423
3703
  return BROAD_RM;
3424
3704
  if (program === "rm" && recursiveTargets(args).some(isProtectedPath))
@@ -4047,18 +4327,15 @@ function checkPath(path) {
4047
4327
 
4048
4328
  // src/bins.ts
4049
4329
  var BINS = {
4050
- check: "`check`: runs the repo's check, typecheck, lint and test steps (package.json, composer.json and PHP tool configs, a Justfile, a Makefile) and prints only what failed, each full log saved to a file; a step runs inside the running compose service that mounts its folder (`--in <service>`, `--host`), never starting one; validate a change with it rather than chaining the scripts or `docker compose exec` by hand (`--only lint,test`, `--list`, `--slot`, `--failed` to re-run what failed last, `--fix` for the fixers).",
4051
- fix: "`fix` (the alias of `check --fix`): runs the repo's fixers and formatters (its fix, lint:fix and format scripts, php-cs-fixer, just fmt, go fmt, cargo fmt, ruff), in the compose service like `check`, and lists the files they changed.",
4330
+ check: "`check`: runs the repo's check, typecheck, lint and test steps (package.json, composer.json and PHP tool configs, a Justfile, a Makefile) and prints only what failed, each full log saved to a file; a step runs inside the running compose service that mounts its folder (`--in <service>`, `--host`), never starting one; validate a change with it rather than chaining the scripts or `docker compose exec` by hand (`--only lint,test`, `--list`, `--slot`, `--failed` to re-run what failed last); `check --fix` runs its fixers and formatters instead (its fix, lint:fix and format scripts, php-cs-fixer, just fmt, go fmt, cargo fmt, ruff) and lists the files they changed.",
4052
4331
  errs: "`errs [log]`, `errs -- <cmd>`: turns tsc, tsgo, eslint, bun check, bun test, vitest, playwright, phpunit, phpstan and php-cs-fixer output into one `file:line:col: message (rule)` line per error, counting the lines it did not recognise (`--json`); use it instead of reading raw type, lint or test logs.",
4053
4332
  db: '`db "<sql>"`: one read-only statement against the Postgres, MySQL or MariaDB in DATABASE_URL (`-e KEY` for another) or, without one, the compose project\'s running database service (`-s <service>`, `-c <container>` for any container, `-d <database>`), credentials never shown; a write runs on a database whose name ends in `_test` and is printed for the user to run otherwise; `db tables`, `db describe <table>`, `db dbs`; use it instead of `docker exec <container> psql` or `mysql`.',
4054
- ev: "`ev`: .env files read and edited with values masked (`ev list`, `ev get KEY`, `ev grep <regex>`, `ev show <rev>:<file>`, `ev set`, `ev diff`, `ev missing`); `ev audit [dir]` finds env files others can read or git tracks, and compose files writing secrets out; `ev pins [dir]` lists the env vars reaching outside that the tests of an app leave unpinned.",
4055
- redact: "`redact`: masks secrets in piped output, `<cmd> | redact`.",
4333
+ ev: "`ev`: .env files read and edited with values masked (`ev list`, `ev get KEY`, `ev grep <regex>`, `ev show <rev>:<file>`, `ev set`, `ev diff`, `ev missing`); `ev audit [dir]` finds env files others can read or git tracks, and compose files writing secrets out; `ev pins [dir]` lists the env vars reaching outside that the tests of an app leave unpinned; `ev redact` masks secrets in piped output, `<cmd> | ev redact`.",
4056
4334
  pkg: "`pkg <name>[@version]`: checks an npm package before it is added: whether the name exists or is a near miss of a popular one, the newest version at least two weeks old, licence, install scripts; `bun add`, `npm install`, `pnpm add` and `yarn add` run it first and are refused on what it flags. `pkg bump <@scope/lib> [version]` waits until the registry serves a release, then `bun add --exact`s it in every consumer under ~/Workspace (`--dry-run`), `pkg consumers <name>` lists them; use it instead of a `bun info` and sleep loop and a `bun add` per repo.",
4057
- stack: "`stack port <name>`: the port a service name always hashes to, for every host port a compose file publishes; `stack audit [dir]` cross-checks release.config.ts against its compose files.",
4335
+ stack: "`stack port <name>`: the port a service name always hashes to, for every host port a compose file publishes.",
4058
4336
  ft: "`ft`: Forgejo CI runs, logs and waits, releases, issue checklists and claims, milestones (`ft milestones`, `ft milestone <m>`, `ft new -m`), in a repo whose origin is on Forgejo.",
4059
4337
  sub: "`sub --from <text> --to <text> <file>...`: replaces text, writing nothing unless each match count is as expected (1, `-n N`, `--all`), `--regex`, `--dry-run --diff`; multi-line text goes as SEARCH/REPLACE blocks on stdin from a quoted heredoc (`sub <file> <<'EOF'`, see `sub --help`), no escaping; use it instead of sed -i, a bun -e or python editor.",
4060
- base: "`base [--ref <rev>] [--keep <path>...] -- <cmd>`: runs a command at HEAD (or a ref) in a temporary worktree, removed afterwards, ignored env files and node_modules/vendor linked; use it instead of git stash to see whether a test fails without your change (`--keep` the new test).",
4061
- proof: "`proof [--ref <rev>] [--keep <path>...] -- <cmd>`: runs the command at HEAD (or a ref) in a temporary worktree, then in the working tree, and exits 0 only when it fails before and passes now, printing the failing side's output; use it to prove a new test fails without your change (`--keep` the test).",
4338
+ base: "`base [--ref <rev>] [--keep <path>...] -- <cmd>`: runs a command at HEAD (or a ref) in a temporary worktree, removed afterwards, ignored env files and node_modules/vendor linked; use it instead of git stash; `base proof` runs it at HEAD (or a ref), then in the working tree, and exits 0 only when it fails before and passes now, printing the failing side's output; use it to prove a new test fails without your change (`--keep` the test).",
4062
4339
  gst: "`gst [--log N]`: branch, upstream, changed counts and HEAD in one line, then the changed paths by staged, unstaged and untracked, `gst --repos` one line per repository nested below; use it instead of `git status --short` and `git log --oneline`.",
4063
4340
  gc: "`gc <title> [-m <line>]... [--ticket <line>]... -- <path>...`: commits exactly those paths, refusing with nothing staged when the message breaks a commit rule, a path has no change or other files are already staged; use it instead of chaining git add, status and commit.",
4064
4341
  gp: "`gp [--repos] [dir]...`: pushes the current branch when it is ahead of its upstream, with `-u` to origin when it has none, `--repos` every repository nested below too, `--dry-run` saying what would go, flags for git push after `--`; only when the user asked for a push, like `git push`.",
@@ -4071,11 +4348,10 @@ var BINS = {
4071
4348
  waitfor: "`waitfor --file <log> --until <regex> [--fail <regex>]`, `--port <n>`, `--url <url>`, `--pid <n>` (`-t 5m`): waits until the line shows, the port listens, the URL answers 2xx or the process exits, exits 1 on a --fail line with the lines around it, 2 on a timeout with the last lines; `waitfor task <id>` waits for a background Bash task and prints its exit code, last lines and failure lines; use it instead of sleep and tail, `until ! pgrep -f` or polling loops.",
4072
4349
  slot: "`slot [-l <lock>] -- <cmd>`: waits for one of the machine-wide slots shared by every session (half the CPUs), then runs the command; `--lock <name>` also holds a named lock for what must not run twice (a shared test database), `slot ls` lists holders and waiters; run heavy jobs (phpunit, playwright, vue-tsc, a full test suite) through it instead of a flock wrapper.",
4073
4350
  gl: "`gl ci [ref]` waits for the GitLab pipeline covering a commit and prints each failed job's tests (exit 0/1/2), `gl runs`, `gl logs <pipeline> [-j job] [--full]`; use it instead of `glab ci` or `glab api .../pipelines/<id>/jobs` polled in a sleep loop.",
4074
- peek: "`peek <file:from-to>...` prints several spans with line numbers in one call, `peek --def <symbol>` a whole declaration, `--refs <symbol>` its usages by file, `--outline <file>` the declarations and members, `--around <regex> -C 3` the lines around matches; use it instead of `sed -n N,Mp`, `grep -n` chains and whole-file reads.",
4075
- "todo-scan": "`todo-scan [path...]` lists the TODO, FIXME and owner/repo#N comments as `<file>:<line>: <comment>`, `--stale` only those whose issue is closed (exit 1), through ft; use it to find the workarounds a shipped fix lets you drop.",
4351
+ src: "`src peek <file:from-to>...` prints several spans with line numbers in one call, `src peek --def <symbol>` a whole declaration, `--refs <symbol>` its usages by file, `--outline <file>` the declarations and members, `--around <regex> -C 3` the lines around matches; use it instead of `sed -n N,Mp`, `grep -n` chains and whole-file reads; `src todo-scan [path...]` lists the TODO, FIXME and owner/repo#N comments as `<file>:<line>: <comment>`, `--stale` only those whose issue is closed (exit 1), through ft; use it to find the workarounds a shipped fix lets you drop; `src hotspots [dir] [--since <date>] [-n 20]` ranks the source files by complexity times git churn (commits touching each in the window, 6 months by default), tests and generated files left out, `--json`; use it to pick which complex files are worth splitting first.",
4076
4352
  doctor: "`doctor`: checks this host's @kaynooo/cli-* install, one line per check with its fix: each bin's version against the registry, tea's login, the Claude Code hooks, the Bun floor (`--json`); run it when a bin lacks a command or a flag its docs name.",
4077
4353
  cli: "`cli list`: every @kaynooo/cli-* bin in one line, what it does and what it is reached for instead of, read from each bin's own --help (`--json` adds the synopsis and examples); run it to find the bin that fits a task.",
4078
- hotspots: "`hotspots [dir] [--since <date>] [-n 20]`: ranks the source files by complexity times git churn (commits touching each in the window, 6 months by default), tests and generated files left out, `--json`; use it to pick which complex files are worth splitting first.",
4354
+ dl: "`dl <url>`: downloads into a new folder and prints the path, size, final URL and sha256, with the diff of a text file since its last download; `--sha256 <hex>` or `--sums <url>` checks it, `-x` extracts, `--bin [name]` installs into ~/.local/bin, `--exec --sha256 <sha>` runs a script exactly as read, `dl ls` lists what it installed or ran; use it instead of `curl | sh`, `curl -LO` and `sha256sum -c`.",
4079
4355
  out: "`out -- <cmd>`: folds long output, keeping the errors and saving the full log; run noisy builds, installs, tests and linters through it.",
4080
4356
  changelog: "`changelog --dry`: the release notes since the last tag, grouped from the conventional commits, without publishing them; `changelog` publishes them as the Forgejo release of the tag at HEAD, `changelog undo [tag]` takes a release back."
4081
4357
  };
@@ -4182,7 +4458,7 @@ async function hook(event, input, machine) {
4182
4458
  var LISTED = [
4183
4459
  { name: "remote", refuses: "ssh, scp, rsync and deploys to a remote machine", route: "hand the command to the user" },
4184
4460
  { name: "git", refuses: "stash, whole-tree add and commit, push without being asked, tags", route: "stage by path with `gc`, push only when asked" },
4185
- { name: "destructive", refuses: "reset --hard, discarding the tree, clean -f, force push, branch -D, rebase, filter-branch, rm -r on a broad path, curl piped to a shell", route: "commit with `gc` first, `base`, `git worktree add`, `--force-with-lease` only when asked" },
4461
+ { name: "destructive", refuses: "reset --hard, discarding the tree, clean -f, force push, branch -D, rebase, filter-branch, rm -r on a broad path, curl piped to a shell, dl --exec --yes on an unpinned script", route: "commit with `gc` first, `base`, `git worktree add`, `--force-with-lease` only when asked, `dl <url>` then `dl <url> --exec --sha256 <sha>`" },
4186
4462
  { name: "commit", refuses: "a commit message breaking the format, an unreadable one, trailers", route: "`gc <title> -m <line> -- <path>...`" },
4187
4463
  { name: "sql", refuses: "SQL writes and DDL, a file the client cannot read", route: '`db "<sql>"`, writes on a `*_test` database or handed over' },
4188
4464
  { name: "env", refuses: "reading or printing an env file, a diff of a tracked one", route: "`ev`, and `rg` for a tree-wide search" },
@@ -4193,11 +4469,10 @@ var LISTED = [
4193
4469
  var RULES2 = LISTED.map((rule) => ({ runs: "check and hook", ...rule }));
4194
4470
 
4195
4471
  // src/cli.ts
4196
- var checkUsage = `guard check [options] [<command> | -]
4472
+ var checkUsage = `guard check [options] [<command> | -]: checks a shell command against the rules and names the route to take instead of each one it breaks
4197
4473
 
4198
- Checks a shell command against the rules: remote machines, git (stash, whole-tree add and commit, push, tags), destructive commands (reset --hard, force push, rebase, broad rm), commit messages, SQL writes, env files, package managers and in-place edits (sed -i and replace scripts, pointed at sub).
4199
- Prints each broken rule with the route to take instead and exits 1, prints nothing and exits 0 when the command is clean.
4200
- The command is read from stdin with - or when none is given; a rule may rewrite it instead (the pinned package manager, a noisy run through out), printed as \`runs as: <command>\`.`;
4474
+ The rules (\`guard rules\` lists them) cover remote machines, git, destructive commands, commit messages, SQL writes, env files, package managers and in-place edits. A clean command prints nothing and exits 0.
4475
+ The command is read from stdin with - or when none is given; a rule may rewrite it instead, printed as \`runs as: <command>\`.`;
4201
4476
  var CHECK_EXITS = [[0, "the command is clean"], [1, "a rule is broken"], [2, "a usage error"]];
4202
4477
  var checkOptions = {
4203
4478
  json: jsonOption("{violations, command, notes, packages} for a hook"),
@@ -4215,7 +4490,7 @@ var pathOptions = {
4215
4490
  var hookUsage = `guard hook <${EVENTS.join("|")}>
4216
4491
 
4217
4492
  Answers a Claude Code hook: reads the event JSON on stdin and prints the reply JSON, nothing when the call goes ahead untouched.
4218
- pre-tool-use refuses a Bash call breaking a rule, an install pkg refuses (or fails to check), and a file tool (Read, Edit, MultiEdit, Write, NotebookEdit, Grep, Glob) reaching an env file; user-prompt-submit remembers whether the prompt asked for a push; session-start lists the installed @kaynooo/cli-* bins.
4493
+ \`pre-tool-use\` refuses a Bash call breaking a rule, an install \`pkg\` refuses and a file tool reaching an env file; \`user-prompt-submit\` remembers whether the prompt asked for a push; \`session-start\` lists the installed bins.
4219
4494
  A failure exits 1, which Claude Code reports without blocking the call.`;
4220
4495
  var HOOK_EXITS = [[0, "it answered"], [1, "a failure or an unknown event (never 2, which would block the call)"]];
4221
4496
  var MAX_READ = 1e6;
@@ -4229,7 +4504,7 @@ function readText(path) {
4229
4504
  }
4230
4505
  function report2(violations) {
4231
4506
  for (const { rule, message } of violations)
4232
- console.log(`${role("problem", process17.stdout)(rule)}: ${message}`);
4507
+ console.log(`${role("problem", process18.stdout)(rule)}: ${message}`);
4233
4508
  }
4234
4509
  async function check(args) {
4235
4510
  const parsed = parse(args, checkUsage, checkOptions, { exits: CHECK_EXITS });
@@ -4241,7 +4516,7 @@ ${checkUsage}`);
4241
4516
  const given = positionals[0] ?? "-";
4242
4517
  const command = given === "-" ? await readInput("-", { noStdin: "give the command, or pipe it on stdin" }) : given;
4243
4518
  const context = {
4244
- cwd: values.cwd ?? process17.cwd(),
4519
+ cwd: values.cwd ?? process18.cwd(),
4245
4520
  home: homedir4(),
4246
4521
  isPushAsked: values["push-asked"] === true,
4247
4522
  canRewrite: true,
@@ -4256,7 +4531,7 @@ ${checkUsage}`);
4256
4531
  else
4257
4532
  report2(verdict.violations);
4258
4533
  if (values.json !== true && verdict.command !== command)
4259
- console.log(`${role("label", process17.stdout)("runs as:")} ${verdict.command}${verdict.notes.map((note) => `
4534
+ console.log(`${role("label", process18.stdout)("runs as:")} ${verdict.command}${verdict.notes.map((note) => `
4260
4535
  ${note}`).join("")}`);
4261
4536
  return verdict.violations.length > 0 ? 1 : 0;
4262
4537
  }
@@ -4287,7 +4562,7 @@ function rules(args) {
4287
4562
  return 0;
4288
4563
  }
4289
4564
  for (const rule of RULES2)
4290
- console.log(`${role("id", process17.stdout)(rule.name)}${" ".repeat(Math.max(0, 16 - rule.name.length))} ${rule.refuses}
4565
+ console.log(`${role("id", process18.stdout)(rule.name)}${" ".repeat(Math.max(0, 16 - rule.name.length))} ${rule.refuses}
4291
4566
  ${" ".repeat(16)} -> ${rule.route}${rule.runs === "hook" ? " (hook only)" : ""}`);
4292
4567
  return 0;
4293
4568
  }
@@ -4326,7 +4601,7 @@ ${hookUsage}`, 1);
4326
4601
  console.log(JSON.stringify(reply));
4327
4602
  return 0;
4328
4603
  }
4329
- process17.exitCode = await runCli({
4604
+ process18.exitCode = await runCli({
4330
4605
  name: "guard",
4331
4606
  usage: false,
4332
4607
  about: "the safety rules a Claude Code Bash call is held to, each refusal naming the route",
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-guard",
3
3
  "type": "module",
4
- "version": "0.13.0",
4
+ "version": "0.14.2",
5
5
  "description": "guard: the safety rules a Claude Code Bash call is held to (git, remote machines, SQL writes, env files, package managers, commit messages), each refusal naming the route.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
8
- "homepage": "https://git.kaynooo.fr/kaynooo/cli/src/branch/main/packages/guard#readme",
8
+ "homepage": "https://github.com/Kayno0o/cli/tree/main/packages/guard#readme",
9
9
  "repository": {
10
10
  "type": "git",
11
- "url": "git+https://git.kaynooo.fr/kaynooo/cli.git",
11
+ "url": "git+https://github.com/Kayno0o/cli.git",
12
12
  "directory": "packages/guard"
13
13
  },
14
- "bugs": "https://git.kaynooo.fr/kaynooo/cli/issues",
14
+ "bugs": "https://github.com/Kayno0o/cli/issues",
15
15
  "keywords": [
16
16
  "claude-code",
17
17
  "cli",
@@ -36,12 +36,12 @@
36
36
  "guard": "$npm_execpath src/cli.ts"
37
37
  },
38
38
  "devDependencies": {
39
- "@kaynooo/cli-db": "0.13.0",
40
- "@kaynooo/cli-edit": "0.11.0",
41
- "@kaynooo/cli-env": "0.13.3",
42
- "@kaynooo/cli-git": "0.16.0",
43
- "@kaynooo/cli-kit": "0.39.0",
44
- "@kaynooo/cli-out": "0.14.4",
45
- "@kaynooo/cli-pkg": "0.15.2"
39
+ "@kaynooo/cli-db": "0.13.3",
40
+ "@kaynooo/cli-edit": "0.11.3",
41
+ "@kaynooo/cli-env": "0.15.1",
42
+ "@kaynooo/cli-git": "0.17.2",
43
+ "@kaynooo/cli-kit": "0.45.1",
44
+ "@kaynooo/cli-out": "0.14.6",
45
+ "@kaynooo/cli-pkg": "0.17.0"
46
46
  }
47
47
  }