@kaynooo/cli-guard 0.14.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 +3 -3
  2. package/dist/cli.js +335 -149
  3. package/package.json +11 -11
package/README.md CHANGED
@@ -13,7 +13,7 @@ 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` |
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
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`) |
@@ -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", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
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,14 +902,62 @@ 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";
922
+
923
+ // ../kit/src/askpass.ts
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
+ }
807
961
 
808
962
  // ../kit/src/completions.ts
809
963
  var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
@@ -866,28 +1020,34 @@ compdef __kaynooo_cli_complete ${bins.join(" ")}
866
1020
  }
867
1021
 
868
1022
  // ../kit/src/notify.ts
869
- import process12 from "process";
1023
+ init_format();
1024
+ init_mode();
1025
+ import process13 from "process";
870
1026
  var NOTIFY_AFTER_MS = 1e4;
871
1027
  var CANCELLED = 130;
872
1028
  function base64(text) {
873
1029
  return Buffer.from(text).toString("base64");
874
1030
  }
875
- function notification(title, body, env = process12.env) {
876
- const id = `kit${process12.pid}`;
1031
+ function notification(title, body, env = process13.env) {
1032
+ const id = `kit${process13.pid}`;
877
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\\`];
878
1034
  return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
879
1035
  }
880
- function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
1036
+ function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
881
1037
  if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
882
1038
  return;
883
1039
  stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
884
1040
  }
885
1041
 
1042
+ // ../kit/src/cli.ts
1043
+ init_style();
1044
+ init_text();
1045
+
886
1046
  // ../kit/src/usage.ts
887
1047
  import { appendFileSync, mkdirSync } from "fs";
888
1048
  import { homedir as homedir3 } from "os";
889
1049
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
890
- import process13 from "process";
1050
+ import process14 from "process";
891
1051
 
892
1052
  // ../kit/src/logs.ts
893
1053
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -901,14 +1061,14 @@ var usageError;
901
1061
  function noteUsageError(message) {
902
1062
  usageError = message;
903
1063
  }
904
- function stateHome(env = process13.env) {
1064
+ function stateHome(env = process14.env) {
905
1065
  const dir = env.XDG_STATE_HOME;
906
1066
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
907
1067
  }
908
- function usagePath(env = process13.env) {
1068
+ function usagePath(env = process14.env) {
909
1069
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
910
1070
  }
911
- function usageRecorded(env = process13.env) {
1071
+ function usageRecorded(env = process14.env) {
912
1072
  const off = env.KAYNOOO_CLI_NO_USAGE;
913
1073
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
914
1074
  }
@@ -917,12 +1077,12 @@ function flagNames(argv) {
917
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);
918
1078
  return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
919
1079
  }
920
- function usageEntry(bin, command, argv, code, now = new Date) {
1080
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
921
1081
  const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
922
1082
  usageError = undefined;
923
- 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) } };
924
1084
  }
925
- function recordUsage(entry, env = process13.env) {
1085
+ function recordUsage(entry, env = process14.env) {
926
1086
  if (!usageRecorded(env))
927
1087
  return;
928
1088
  try {
@@ -1016,8 +1176,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1016
1176
  `);
1017
1177
  }
1018
1178
  function printError(prefix, message, hint, cause) {
1019
- const colors = paint(process14.stderr);
1020
- const styled = takesControlCodes(process14.stderr);
1179
+ const colors = paint(process15.stderr);
1180
+ const styled = takesControlCodes(process15.stderr);
1021
1181
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1022
1182
  const under = (label, text, tint) => text === undefined ? "" : `
1023
1183
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1060,11 +1220,11 @@ async function dispatch(level, typed, { version, redact }) {
1060
1220
  }
1061
1221
  }
1062
1222
  if (name === undefined && level.path.length > 1) {
1063
- 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));
1064
1224
  return 2;
1065
1225
  }
1066
1226
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1067
- 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));
1068
1228
  return 0;
1069
1229
  }
1070
1230
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1210,6 +1370,9 @@ function packageVersion(entry = Bun.main) {
1210
1370
  }
1211
1371
  async function runCli(cli, argv = scriptArgs()) {
1212
1372
  const version = cli.version ?? packageVersion();
1373
+ const answered = await askpassClient(argv);
1374
+ if (answered !== undefined)
1375
+ return answered;
1213
1376
  if (argv[0] === COMPLETE)
1214
1377
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1215
1378
  if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
@@ -1220,7 +1383,7 @@ async function runCli(cli, argv = scriptArgs()) {
1220
1383
  notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1221
1384
  if (cli.usage !== false) {
1222
1385
  try {
1223
- recordUsage(usageEntry(cli.name, command, argv, code));
1386
+ recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
1224
1387
  } catch {}
1225
1388
  }
1226
1389
  return code;
@@ -1240,19 +1403,47 @@ function commandPath(scope, argv) {
1240
1403
  }
1241
1404
  return path.length === 0 ? undefined : path.join(" ");
1242
1405
  }
1243
- // ../kit/src/folders.ts
1244
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1245
- function ignoredFolders(extra = [], where = {}) {
1246
- const configured = readUserConfig("config", where).ignore;
1247
- const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
1248
- return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
1249
- }
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();
1250
1428
  // ../kit/src/secrets.ts
1251
1429
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1252
1430
  // ../kit/src/sessions.ts
1253
1431
  var {Glob } = globalThis.Bun;
1254
1432
  var SESSION_FILES = new Glob("*.json");
1255
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();
1256
1447
  // ../kit/src/shell.ts
1257
1448
  var SEPARATORS = new Set([`
1258
1449
  `, ";", "|"]);
@@ -2546,7 +2737,7 @@ var INTERPRETERS = new Set(["bun", "deno", "node", "python", "python3", "ruby",
2546
2737
  var CODE_OPTIONS = new Set(["-e", "-c", "-p", "-E", "-pe", "-r", "--eval", "--print", "--command"]);
2547
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;
2548
2739
  var DECLARERS = new Set(["export", "declare", "local", "readonly", "typeset"]);
2549
- var HARMLESS = new Set(["ev", "redact", "ls", "stat", "test", "[", "[[", "touch"]);
2740
+ var HARMLESS = new Set(["ev", "ls", "stat", "test", "[", "[[", "touch"]);
2550
2741
  var GIT_HARMLESS = new Set(["check-ignore", "ls-files", "status"]);
2551
2742
  function variablesOf(command) {
2552
2743
  const variables = new Map;
@@ -2607,7 +2798,7 @@ function namesEnv(piece, variables) {
2607
2798
  }
2608
2799
 
2609
2800
  // ../env/src/guard-pipes.ts
2610
- 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", ""]);
2611
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"]);
2612
2803
  var IDENTIFIER = /^[A-Z_]\w*$/i;
2613
2804
  var READ_VALUE_OPTIONS = new Set(["-a", "-d", "-i", "-n", "-N", "-p", "-t", "-u"]);
@@ -2654,7 +2845,7 @@ function loopReadsListedEnv(pieces, index, variables) {
2654
2845
 
2655
2846
  // ../env/src/guard.ts
2656
2847
  var ENV_DUMP = /(?:console\.\w+|JSON\.stringify|Object\.(?:entries|keys|values)|print)\(\s*process\.env\s*[,)]/;
2657
- 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`.';
2658
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> .`.";
2659
2850
  function touchingPieces(command, options = {}) {
2660
2851
  const pieces = splitCommand(command);
@@ -2669,7 +2860,8 @@ function touchingPieces(command, options = {}) {
2669
2860
  if (!isDump)
2670
2861
  return false;
2671
2862
  for (let at = index;pieces[at]?.separator === "|"; at++) {
2672
- 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")
2673
2865
  return false;
2674
2866
  }
2675
2867
  return true;
@@ -2870,7 +3062,7 @@ function wrap(command) {
2870
3062
  // ../pkg/src/added.ts
2871
3063
  import { existsSync as existsSync4, readdirSync, readFileSync as readFileSync5 } from "fs";
2872
3064
  import { dirname as dirname4, join as join6 } from "path";
2873
- import process16 from "process";
3065
+ import process17 from "process";
2874
3066
  var REDIRECT2 = /^\d*[<>]/;
2875
3067
  var BARE_REDIRECT = /^\d*(?:[<>]|>>)$/;
2876
3068
  var ADDS = {
@@ -2902,7 +3094,7 @@ function manifestName(folder) {
2902
3094
  }
2903
3095
  function ownPackages() {
2904
3096
  const names = new Set;
2905
- let folder = process16.cwd();
3097
+ let folder = process17.cwd();
2906
3098
  while (true) {
2907
3099
  const name = manifestName(folder);
2908
3100
  if (name !== undefined)
@@ -3100,7 +3292,7 @@ var RISKY_CONFIG = /^(?:alias\.|core\.(?:sshcommand|hookspath|pager|editor|fsmon
3100
3292
  var RISKY_ENV = /^GIT_(?:CONFIG_(?:COUNT|PARAMETERS)|EXTERNAL_DIFF|ASKPASS|PROXY_COMMAND|PAGER)=/;
3101
3293
  var READS_CONFIG = new Set(["--get", "--get-all", "--get-regexp", "--list", "-l", "--unset", "--unset-all", "--show-origin", "--show-scope"]);
3102
3294
  var STAGE_BY_PATH = `Stage by path: the tree carries unrelated work and peer sessions edit it live. ${USE_GC}`;
3103
- 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`.";
3104
3296
  var ADD_ALL = `\`git add\` over the whole tree is refused. ${STAGE_BY_PATH}`;
3105
3297
  var COMMIT_ALL = `\`git commit -a\` stages the whole tree and is refused. ${STAGE_BY_PATH}`;
3106
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.";
@@ -4135,18 +4327,15 @@ function checkPath(path) {
4135
4327
 
4136
4328
  // src/bins.ts
4137
4329
  var BINS = {
4138
- 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).",
4139
- 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.",
4140
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.",
4141
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`.',
4142
- 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.",
4143
- 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`.",
4144
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.",
4145
- 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.",
4146
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.",
4147
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.",
4148
- 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).",
4149
- 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).",
4150
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`.",
4151
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.",
4152
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`.",
@@ -4159,11 +4348,9 @@ var BINS = {
4159
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.",
4160
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.",
4161
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.",
4162
- 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.",
4163
- "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.",
4164
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.",
4165
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.",
4166
- 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.",
4167
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`.",
4168
4355
  out: "`out -- <cmd>`: folds long output, keeping the errors and saving the full log; run noisy builds, installs, tests and linters through it.",
4169
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."
@@ -4282,11 +4469,10 @@ var LISTED = [
4282
4469
  var RULES2 = LISTED.map((rule) => ({ runs: "check and hook", ...rule }));
4283
4470
 
4284
4471
  // src/cli.ts
4285
- 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
4286
4473
 
4287
- 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).
4288
- Prints each broken rule with the route to take instead and exits 1, prints nothing and exits 0 when the command is clean.
4289
- 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>\`.`;
4290
4476
  var CHECK_EXITS = [[0, "the command is clean"], [1, "a rule is broken"], [2, "a usage error"]];
4291
4477
  var checkOptions = {
4292
4478
  json: jsonOption("{violations, command, notes, packages} for a hook"),
@@ -4304,7 +4490,7 @@ var pathOptions = {
4304
4490
  var hookUsage = `guard hook <${EVENTS.join("|")}>
4305
4491
 
4306
4492
  Answers a Claude Code hook: reads the event JSON on stdin and prints the reply JSON, nothing when the call goes ahead untouched.
4307
- 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.
4308
4494
  A failure exits 1, which Claude Code reports without blocking the call.`;
4309
4495
  var HOOK_EXITS = [[0, "it answered"], [1, "a failure or an unknown event (never 2, which would block the call)"]];
4310
4496
  var MAX_READ = 1e6;
@@ -4318,7 +4504,7 @@ function readText(path) {
4318
4504
  }
4319
4505
  function report2(violations) {
4320
4506
  for (const { rule, message } of violations)
4321
- console.log(`${role("problem", process17.stdout)(rule)}: ${message}`);
4507
+ console.log(`${role("problem", process18.stdout)(rule)}: ${message}`);
4322
4508
  }
4323
4509
  async function check(args) {
4324
4510
  const parsed = parse(args, checkUsage, checkOptions, { exits: CHECK_EXITS });
@@ -4330,7 +4516,7 @@ ${checkUsage}`);
4330
4516
  const given = positionals[0] ?? "-";
4331
4517
  const command = given === "-" ? await readInput("-", { noStdin: "give the command, or pipe it on stdin" }) : given;
4332
4518
  const context = {
4333
- cwd: values.cwd ?? process17.cwd(),
4519
+ cwd: values.cwd ?? process18.cwd(),
4334
4520
  home: homedir4(),
4335
4521
  isPushAsked: values["push-asked"] === true,
4336
4522
  canRewrite: true,
@@ -4345,7 +4531,7 @@ ${checkUsage}`);
4345
4531
  else
4346
4532
  report2(verdict.violations);
4347
4533
  if (values.json !== true && verdict.command !== command)
4348
- 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) => `
4349
4535
  ${note}`).join("")}`);
4350
4536
  return verdict.violations.length > 0 ? 1 : 0;
4351
4537
  }
@@ -4376,7 +4562,7 @@ function rules(args) {
4376
4562
  return 0;
4377
4563
  }
4378
4564
  for (const rule of RULES2)
4379
- 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}
4380
4566
  ${" ".repeat(16)} -> ${rule.route}${rule.runs === "hook" ? " (hook only)" : ""}`);
4381
4567
  return 0;
4382
4568
  }
@@ -4415,7 +4601,7 @@ ${hookUsage}`, 1);
4415
4601
  console.log(JSON.stringify(reply));
4416
4602
  return 0;
4417
4603
  }
4418
- process17.exitCode = await runCli({
4604
+ process18.exitCode = await runCli({
4419
4605
  name: "guard",
4420
4606
  usage: false,
4421
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.14.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.14.0",
42
- "@kaynooo/cli-git": "0.16.0",
43
- "@kaynooo/cli-kit": "0.41.0",
44
- "@kaynooo/cli-out": "0.14.4",
45
- "@kaynooo/cli-pkg": "0.16.0"
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
  }