@litfamily/litmuse 0.1.21 → 0.1.23

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.
@@ -0,0 +1,1004 @@
1
+ import { existsSync, lstatSync, readdirSync, readFileSync, readlinkSync, realpathSync, statSync } from 'node:fs';
2
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
3
+ import { homedir, userInfo } from 'node:os';
4
+
5
+ // The start-work run guard reads one shell command and says what happens to it while a run is active:
6
+ // allow ordinary local work in the workspace or in a plan `Scope roots:` folder granted `write`
7
+ // (Muse's own approval mode and sandbox still decide the call)
8
+ // refuse secrets, host homes, run state and .git internals: denied and never stored
9
+ // park a step that needs the user's word: tier B (on the B allowlist, every path inside a known root and
10
+ // undoable) or tier X (everything else); a command the guard cannot follow is parked as held and is
11
+ // never replayed
12
+ // split a self-check refused only for its shape: the model is told which parts to run as separate calls
13
+ // It reads the command, never the scripts the command runs.
14
+
15
+ // Paths are compared case-folded on every OS: a case-sensitive Linux disk may still hold a case-folding mount, and
16
+ // refusing `.LitMuse` or `.GIT` there costs nothing.
17
+ const fold = (p) => p.toLowerCase();
18
+
19
+ const held = (reason) => ({ held: reason });
20
+
21
+ // --- words ---------------------------------------------------------------------------------------------------
22
+
23
+ // Splits a command into segments joined by &&, ||, ;, | or a line break. Expansion, substitution, escapes,
24
+ // subshells, background jobs, here-documents, comments and unpaired quotes make the command uncheckable.
25
+ export function tokenize(command) {
26
+ if (typeof command !== 'string' || !command.trim()) return held('empty command');
27
+ if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(command)) return held('control characters in the command');
28
+ const segments = [];
29
+ let seg = { words: [], redirects: [] };
30
+ let word = null;
31
+ let quote = null;
32
+ const pushWord = () => { if (word) seg.words.push(word); word = null; };
33
+ const endSeg = (sepText) => {
34
+ pushWord();
35
+ if (!seg.words.length && !seg.redirects.length) return false;
36
+ seg.sep = sepText;
37
+ segments.push(seg);
38
+ seg = { words: [], redirects: [] };
39
+ return true;
40
+ };
41
+ for (let i = 0; i < command.length; i += 1) {
42
+ const ch = command[i];
43
+ if (quote === "'") { if (ch === "'") quote = null; else word.text += ch; continue; }
44
+ if (quote === '"') {
45
+ if (ch === '"') quote = null;
46
+ else if ('$`\\'.includes(ch)) return held('expansion inside double quotes');
47
+ else word.text += ch;
48
+ continue;
49
+ }
50
+ if (ch === "'" || ch === '"') { word ??= { text: '', quoted: true }; word.quoted = true; quote = ch; continue; }
51
+ if (ch === ' ' || ch === '\t') { pushWord(); continue; }
52
+ if (ch === '\n' || ch === '\r' || ch === ';') { if (!endSeg(';')) return held('empty step'); continue; }
53
+ if (ch === '&') {
54
+ if (command[i + 1] === '&') { i += 1; if (!endSeg('&&')) return held('empty step'); continue; }
55
+ return held('background job or `&>` redirect');
56
+ }
57
+ if (ch === '|') {
58
+ const two = command[i + 1] === '|';
59
+ if (two) i += 1;
60
+ if (!endSeg(two ? '||' : '|')) return held('empty step');
61
+ continue;
62
+ }
63
+ if (ch === '>' || ch === '<') {
64
+ let fd = '';
65
+ if (word && /^\d+$/.test(word.text) && !word.quoted) { fd = word.text; word = null; }
66
+ pushWord();
67
+ let op = ch;
68
+ if (command[i + 1] === ch) { op += ch; i += 1; }
69
+ if (op === '<<' || command[i + 1] === '(') return held('here-document or process substitution');
70
+ if (command[i + 1] === '&') {
71
+ const dup = /^&(\d+|-)/.exec(command.slice(i + 1));
72
+ if (!dup) return held('unreadable redirect');
73
+ i += dup[0].length;
74
+ continue;
75
+ }
76
+ while (command[i + 1] === ' ' || command[i + 1] === '\t') i += 1;
77
+ const m = /^[^\s;&|<>()]+/.exec(command.slice(i + 1));
78
+ if (!m || /[$`'"\\*?[\]{}~]/.test(m[0])) return held('unreadable redirect target');
79
+ i += m[0].length;
80
+ seg.redirects.push({ op, fd, target: m[0] });
81
+ continue;
82
+ }
83
+ if (ch === '$') return held('shell expansion (`$`)');
84
+ if (ch === '`') return held('command substitution (backticks)');
85
+ if (ch === '\\') return held('backslash escape');
86
+ if (ch === '(' || ch === ')') return held('subshell or grouping');
87
+ if (ch === '#' && !word) return held('comment text');
88
+ word ??= { text: '' };
89
+ if ('*?['.includes(ch) || '{}'.includes(ch)) word.glob = true;
90
+ if (ch === '~' && word.text === '') word.tilde = true;
91
+ word.text += ch;
92
+ }
93
+ if (quote) return held('quotes do not pair');
94
+ if (!endSeg(null)) return held('empty step');
95
+ return { segments };
96
+ }
97
+
98
+ // --- paths ---------------------------------------------------------------------------------------------------
99
+
100
+ function realOr(p) {
101
+ try { return realpathSync(p); } catch { return resolve(p); }
102
+ }
103
+
104
+ const LINK_HOPS = 16;
105
+
106
+ // The real location a path names: the nearest existing ancestor through realpath, plus the rest. A dangling link
107
+ // counts as present and is reported, so a write through it is never taken for a new path inside the workspace; its
108
+ // whole chain is followed (each hop's own ancestors resolved too) up to LINK_HOPS, and a loop or a longer chain is
109
+ // reported as `loop`, which the protected check refuses.
110
+ export function locate(abs, hops = LINK_HOPS) {
111
+ let cur = abs;
112
+ const rest = [];
113
+ for (;;) {
114
+ let st = null;
115
+ try { st = lstatSync(cur); } catch { st = null; }
116
+ if (st) {
117
+ try {
118
+ return { real: join(realpathSync(cur), ...rest), exists: rest.length === 0, dangling: false };
119
+ } catch (err) {
120
+ if (err?.code === 'ELOOP' || hops <= 0) return { real: join(cur, ...rest), exists: false, dangling: true, loop: true };
121
+ let target;
122
+ try { target = resolve(dirname(cur), readlinkSync(cur)); } catch { return { real: join(cur, ...rest), exists: false, dangling: true }; }
123
+ const next = locate(target, hops - 1);
124
+ return { real: join(next.real, ...rest), exists: false, dangling: true, loop: Boolean(next.loop) };
125
+ }
126
+ }
127
+ const parent = dirname(cur);
128
+ if (parent === cur) return { real: abs, exists: false, dangling: false };
129
+ rest.unshift(basename(cur));
130
+ cur = parent;
131
+ }
132
+ }
133
+
134
+ export const within = (base, p) => {
135
+ const rel = relative(fold(base), fold(p));
136
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
137
+ };
138
+
139
+ function homes(env) {
140
+ const out = new Set();
141
+ for (const h of [env.HOME, homedir(), (() => { try { return userInfo().homedir; } catch { return null; } })()]) {
142
+ if (h) out.add(realOr(h));
143
+ }
144
+ return [...out];
145
+ }
146
+
147
+ const HOME_SECRETS = ['.ssh', '.aws', '.gnupg', '.npmrc', '.netrc', '.gitconfig', '.docker', '.kube', '.claude', '.claude.json',
148
+ '.codex', '.hermes', '.grok', '.gemini', '.zshrc', '.zprofile', '.zshenv', '.bashrc', '.bash_profile', '.profile',
149
+ '.config/muse', '.config/gh', '.config/opencode', '.local/state/litmuse'];
150
+ // Muse keeps session logs and long tool results in its data folder; a run may read its own there, never write.
151
+ const HOME_WRITE_ONLY = ['.local/share/muse'];
152
+ // Case-insensitive: on a case-folding disk `.ENV` and `ID_RSA` are the same files.
153
+ const ENV_FILE = /^\.env(?:\.[\w-]+)*$|^\.envrc$/i;
154
+ const ENV_EXAMPLE = /\.(?:example|sample|template)$/i;
155
+ const KEY_FILE = /^id_(?:rsa|dsa|ecdsa|ed25519)$|\.pem$|^\.mcp\.json$|^\.(?:npmrc|netrc|pypirc)$/i;
156
+
157
+ function stateHome(env) {
158
+ return env.XDG_STATE_HOME || join(env.HOME || homedir(), '.local', 'state');
159
+ }
160
+
161
+ // A write, move or remove whose target is, holds or sits inside the run's state: the hook state folder and the
162
+ // workspace's `.litmuse` folder (its session records outright; the whole folder when the target contains it).
163
+ function stateFolderReason(abs, real, env, root) {
164
+ const state = join(stateHome(env), 'litmuse');
165
+ const local = root ? join(root, '.litmuse') : null;
166
+ for (const p of new Set([resolve(abs), real])) {
167
+ for (const s of new Set([state, realOr(state)])) {
168
+ if (within(p, s) || within(s, p)) return 'LitMuse run state belongs to the hooks';
169
+ }
170
+ if (local && (within(p, local) || within(join(local, 'sessions'), p))) return 'the workspace .litmuse folder holds LitMuse run records';
171
+ }
172
+ return null;
173
+ }
174
+
175
+ // Why a path may never be touched during a run, or null. Checked on the lexical path and on its real location.
176
+ export function protectedReason(abs, env = process.env, write = false, root = null) {
177
+ const loc = locate(abs);
178
+ if (loc.loop) return 'a link loop or a link chain too long to follow';
179
+ if (write) {
180
+ const state = stateFolderReason(abs, loc.real, env, root);
181
+ if (state) return state;
182
+ }
183
+ for (const p of new Set([resolve(abs), loc.real])) {
184
+ const name = basename(p);
185
+ if (ENV_FILE.test(name) && !ENV_EXAMPLE.test(name)) return `${name} holds secrets`;
186
+ if (KEY_FILE.test(name)) return `${name} is a key or host config file`;
187
+ if (within(realOr(join(stateHome(env), 'litmuse')), p) || within(join(stateHome(env), 'litmuse'), p)) return 'LitMuse run state belongs to the hooks';
188
+ if (env.XDG_CONFIG_HOME && within(realOr(join(env.XDG_CONFIG_HOME, 'muse')), p)) return 'Muse configuration';
189
+ if (write && env.XDG_DATA_HOME && within(realOr(join(env.XDG_DATA_HOME, 'muse')), p)) return 'Muse data (read-only during a run)';
190
+ for (const home of homes(env)) {
191
+ for (const s of write ? [...HOME_SECRETS, ...HOME_WRITE_ONLY] : HOME_SECRETS) {
192
+ if (within(join(home, s), p)) return `${join('~', s)} is a secret or host home`;
193
+ }
194
+ }
195
+ }
196
+ return null;
197
+ }
198
+
199
+ // Any path through a `.git` folder, inside the workspace or not (a linked worktree's git dir lives elsewhere).
200
+ function inGit(root, real) {
201
+ return real.split(sep).some((part) => fold(part) === '.git');
202
+ }
203
+
204
+ // --- verbs ---------------------------------------------------------------------------------------------------
205
+
206
+ const OPAQUE = new Set(['pushd', 'popd', 'builtin', 'command', 'exec', 'eval', 'source', '.', 'alias', 'unalias', 'enable',
207
+ 'set', 'shopt', 'trap', 'env', 'sudo', 'doas', 'su', 'xargs', 'time', 'nice', 'nohup', 'timeout', 'stdbuf', 'ionice',
208
+ 'chroot', '!', 'watch', 'parallel', 'nsenter', 'unshare', 'script', 'osascript', 'open', 'caffeinate', 'until', 'while',
209
+ 'for', 'if', 'then', 'do', 'function', 'case', 'select', 'coproc', 'declare', 'export', 'local', 'readonly', 'typeset']);
210
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*\+?=/;
211
+ const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh', 'fish']);
212
+ const RUNNERS = new Set(['node', 'python', 'python3', 'perl', 'ruby', 'php', 'tsx', 'ts-node', ...SHELLS]);
213
+ const INLINE_FLAG = /^(?:-e|-p|-c|-lc|-ic|-[a-z]*c|--eval|--print|-E|-r)$/;
214
+ const NETWORK = new Set(['curl', 'wget', 'ssh', 'scp', 'sftp', 'rsync', 'ftp', 'nc', 'ncat', 'telnet', 'docker', 'podman', 'aws',
215
+ 'gcloud', 'az', 'kubectl', 'helm', 'terraform', 'gh', 'npx', 'bunx', 'pipx', 'vercel', 'netlify', 'fly', 'flyctl', 'heroku',
216
+ 'firebase', 'twine', 'gsutil', 's3cmd', 'muse']);
217
+ const PACKAGE_MANAGERS = new Set(['npm', 'pnpm', 'yarn', 'bun']);
218
+ // A package script is code the guard cannot read, so only the names a run checks itself with run directly.
219
+ const CHECK_SCRIPT = /^(?:test|check|lint|build|verify|typecheck|format|fmt)(?::[\w.-]+)?$/;
220
+ const PM_READERS = new Set(['ls', 'list', 'outdated', 'view', 'info', 'why', 'explain', 'audit', 'doctor', 'help', '--version', '-v']);
221
+ const INSTALLERS = new Set(['pip', 'pip3', 'brew', 'gem', 'cargo', 'go', 'apt', 'apt-get', 'yum', 'dnf', 'port', 'conda', 'uv']);
222
+ const INSTALL_SUBS = new Set(['install', 'uninstall', 'publish', 'upgrade', 'update', 'get', 'add', 'remove', 'login', 'yank', 'owner']);
223
+ const MAKE_SAFE = new Set(['test', 'check', 'verify', 'lint', 'build', 'fmt', 'format']);
224
+ // Toolchain subcommands that are a project's own tests and checks; any other subcommand (`go run`, `cargo run`,
225
+ // `uv run`, installs) parks.
226
+ const TOOLCHAIN_CHECKS = {
227
+ cargo: new Set(['test', 'check', 'clippy', 'fmt', 'build']),
228
+ go: new Set(['test', 'vet', 'build']),
229
+ pip: new Set(['list', 'show', 'freeze', 'check']),
230
+ pip3: new Set(['list', 'show', 'freeze', 'check']),
231
+ };
232
+ const TEST_RUNNERS = new Set(['pytest', 'vitest', 'jest', 'mocha', 'tsc', 'eslint', 'ruff', 'mypy', 'pyright']);
233
+ // Verbs that only read or print (their writing forms are caught by readerWrites first). Everything else parks.
234
+ const SAFE_VERBS = new Set(['cat', 'head', 'tail', 'wc', 'grep', 'egrep', 'fgrep', 'rg', 'find', 'ls', 'sed', 'jq', 'sort', 'uniq', 'cut',
235
+ 'diff', 'cmp', 'comm', 'stat', 'file', 'tr', 'nl', 'column', 'basename', 'dirname', 'pwd', 'echo', 'printf', 'true', 'false',
236
+ 'test', '[', 'realpath', 'readlink', 'du', 'df', 'tree', 'date', 'which', 'type', 'uname', 'sleep', 'shasum', 'sha256sum',
237
+ 'md5', 'md5sum', 'od', 'hexdump', 'xxd', 'fold', 'expand', 'paste', 'rev', 'seq', 'yes', 'tac', 'strings']);
238
+ const DELETERS = new Set(['rm', 'rmdir', 'unlink', 'shred']);
239
+ const B_FLAGS = { touch: /^$/, mkdir: /^-p$/, cp: /^-[rRp]+$/, mv: /^$/ };
240
+ const GIT_LOCAL = new Set(['status', 'diff', 'log', 'show', 'blame', 'ls-files', 'grep', 'rev-parse', 'describe', 'shortlog']);
241
+ const DECODERS = (w) => (w[0] === 'base64' && w.some((a) => /^(?:-d|-D|--decode)$/.test(a)))
242
+ || (w[0] === 'xxd' && w.includes('-r'))
243
+ || (w[0] === 'openssl' && w.some((a) => a === 'enc' || a === '-d' || a === 'base64'))
244
+ || w[0] === 'uudecode';
245
+
246
+ // Text-level test for a held step that may still reach outside or be irreversible: it keeps a finished run open.
247
+ export const OUTWARD_TEXT = /\b(?:push|publish|unpublish|deprecate|dist-tag|tag|version|release|deploy|gh|curl|wget|ssh|scp|sftp|rsync|ftp|nc|telnet|docker|podman|aws|gcloud|az|kubectl|helm|terraform|npx|reset|clean|fetch|pull|clone|ls-remote)\b|\bremote[ \t]+(?:show|update|add|set-url|set-head|set-branches|prune|remove|rm|rename)\b|\b(?:npm|pnpm|yarn|pip3?|brew|gem|cargo)[ \t]+(?:install|i|ci|add|update|upgrade)\b|(?:^|[\s;&|])make\b|\b(?:rm|rmdir|unlink|shred)\b|-delete\b/;
248
+
249
+ const rank = { allow: 0, B: 1, X: 2, held: 3, refuse: 4 };
250
+ const worse = (a, b) => (rank[b.level] >= rank[a.level] ? b : a);
251
+
252
+ // --- the guard -----------------------------------------------------------------------------------------------
253
+
254
+ // ctx: { cwd, root (the workspace, real), roots ([{path, write}] from Scope roots lines and granted boundaries),
255
+ // charter ([{branch, repo}]), check (the plan's Done-when command), denied ({commands, paths}), env }
256
+ export function classifyCommand(command, ctx) {
257
+ const env = ctx.env ?? process.env;
258
+ if (ctx.denied?.commands?.includes(command)) return { action: 'refuse', reason: 'the user answered `lit deny` to this exact step in this run' };
259
+ const tok = tokenize(command);
260
+ if (tok.held) {
261
+ const split = shapeSplit(command, ctx);
262
+ if (split) return { action: 'split', parts: split, reason: tok.held };
263
+ const prot = scanProtected(command, ctx);
264
+ if (prot) return { action: 'refuse', reason: prot };
265
+ return { action: 'park', tier: 'X', held: tok.held, reason: `cannot check this command: ${tok.held}` };
266
+ }
267
+ const st = { here: ctx.cwd, root: ctx.root, env };
268
+ let verdict = { level: 'allow' };
269
+ let bShaped = true;
270
+ for (const seg of tok.segments) {
271
+ const v = classifySegment(seg, st, ctx);
272
+ if (v.level === 'refuse') return { action: 'refuse', reason: v.reason };
273
+ if (!v.bVerb) bShaped = false;
274
+ if (seg.sep && seg.sep !== '&&') bShaped = false;
275
+ verdict = worse(verdict, v);
276
+ }
277
+ if (verdict.level === 'allow') return { action: 'allow' };
278
+ if (verdict.level === 'held') return { action: 'park', tier: 'X', held: verdict.reason, reason: `cannot check this command: ${verdict.reason}` };
279
+ if (verdict.level === 'B' && bShaped) return { action: 'park', tier: 'B', reason: verdict.reason };
280
+ return { action: 'park', tier: 'X', reason: verdict.reason };
281
+ }
282
+
283
+ // A held command still refuses outright when it plainly names a protected path (`cd ~ && cat .aws/credentials`).
284
+ function scanProtected(command, ctx) {
285
+ const env = ctx.env ?? process.env;
286
+ const plain = command.replace(/["']/g, '');
287
+ for (const raw of plain.split(/[\s;&|<>()=]+/)) {
288
+ if (!raw) continue;
289
+ const word = raw.replace(/^~(?=\/|$)/, homes(env)[0] ?? '~').replace(/^\$\{?HOME\}?(?=\/|$)/, env.HOME ?? homedir());
290
+ if (/^~[^/]/.test(word)) return 'a `~user` path names another account';
291
+ for (const base of [ctx.cwd, ...homes(env)]) {
292
+ const reason = protectedReason(resolve(base, word), env);
293
+ if (reason && (isAbsolute(word) || base === ctx.cwd)) return reason;
294
+ }
295
+ }
296
+ return null;
297
+ }
298
+
299
+ const STATUS_ONLY = /^(?:echo|printf|true|false|:)(?:\s|$)/;
300
+
301
+ // `node check.mjs; echo "exit=$?"` is held only for its shape. When every part is a reader, a status echo or the
302
+ // plan's own check, the model gets the parts to run one by one; nothing is parked.
303
+ function shapeSplit(command, ctx) {
304
+ const parts = command.split(/;|\|\||&&|\n/).map((p) => p.replace(/\s+2>&1\s*$/, '').trim()).filter(Boolean);
305
+ if (parts.length < 2) return null;
306
+ // A status echo is dropped only when it writes nothing: `echo x > ../f` is work, and it fails the reader test below.
307
+ const work = parts.filter((p) => !(STATUS_ONLY.test(p) && !/>/.test(p.replace(/\s*2>&1|\s*\d?>\s*\/dev\/null/g, ''))));
308
+ if (!work.length) return null;
309
+ for (const p of work) {
310
+ if (ctx.check && p === ctx.check) continue;
311
+ const v = classifyCommand(p, { ...ctx, check: null });
312
+ if (v.action !== 'allow' || !readerOnly(p)) return null;
313
+ }
314
+ return work;
315
+ }
316
+
317
+ // A split hint names only reading parts; a part with a redirect, an in-place edit or a writing option is never one.
318
+ const READERS = new Set(['cat', 'head', 'tail', 'wc', 'grep', 'rg', 'find', 'ls', 'sed', 'jq', 'sort', 'uniq', 'cut', 'diff', 'stat', 'file', 'git', 'node']);
319
+ function readerOnly(part) {
320
+ if (/>/.test(part.replace(/\s*2>&1|\s*\d?>\s*\/dev\/null/g, ''))) return false;
321
+ const w = part.split(/\s+/);
322
+ if (w[0] === 'git') return GIT_LOCAL.has(w[1]) && !w.some((a) => /^--output/.test(a));
323
+ if (w[0] === 'sed') return !w.some((a) => /^-[a-zA-Z]*i|^--in-place/.test(a));
324
+ if (w[0] === 'sort') return !w.some((a) => /^(?:-o|--output)/.test(a));
325
+ if (w[0] === 'uniq') return w.slice(1).filter((a) => !a.startsWith('-')).length <= 1;
326
+ if (w[0] === 'find') return !w.some((a) => /^-(?:exec|execdir|ok|okdir|delete|fprint|fprint0|fprintf|fls)$/.test(a));
327
+ return READERS.has(w[0]);
328
+ }
329
+
330
+ function homeWord(word, env) {
331
+ if (!word.tilde) return { text: word.text };
332
+ if (word.text === '~' || word.text.startsWith('~/')) return { text: join(homes(env)[0] ?? homedir(), word.text.slice(2)) };
333
+ return { refuse: 'a `~user` path names another account' };
334
+ }
335
+
336
+ // Where one path lands: the workspace, a Scope root (writable or read-only), or outside every known root.
337
+ function pathFacts(st, ctx, text) {
338
+ const abs = resolve(st.here, text);
339
+ const loc = locate(abs);
340
+ let zone = 'outside';
341
+ if (!loc.dangling) {
342
+ const root = (ctx.roots ?? []).find((r) => within(r.path, loc.real));
343
+ if (within(st.root, loc.real)) zone = 'workspace';
344
+ else if (root) zone = root.write ? 'root-write' : 'root-read';
345
+ }
346
+ return {
347
+ abs,
348
+ real: loc.real,
349
+ exists: loc.exists,
350
+ dangling: loc.dangling,
351
+ zone,
352
+ writable: zone === 'workspace' || zone === 'root-write',
353
+ git: inGit(st.root, loc.real) || inGit(st.root, abs),
354
+ };
355
+ }
356
+
357
+ const where = (f) => (f.dangling ? `a dangling link (${f.abs})` : f.zone === 'root-read' ? `a Scope root the plan grants for reading only (${f.abs})` : `a path outside the workspace (${f.abs})`);
358
+
359
+ // --- globs -----------------------------------------------------------------------------------------------------
360
+
361
+ const GLOB_WORDS = 256;
362
+
363
+ // One glob segment as a regex, the way bash matches it without dotglob: a leading dot is matched only by a pattern
364
+ // that starts with one. A `[` without its `]` is literal.
365
+ function globRegex(part) {
366
+ let re = '';
367
+ for (let i = 0; i < part.length; i += 1) {
368
+ const c = part[i];
369
+ if (c === '*') re += '.*';
370
+ else if (c === '?') re += '.';
371
+ else if (c === '[') {
372
+ let j = i + 1;
373
+ if (part[j] === '!' || part[j] === '^') j += 1;
374
+ if (part[j] === ']') j += 1;
375
+ const close = part.indexOf(']', j);
376
+ if (close < 0) { re += '\\['; continue; }
377
+ let body = part.slice(i + 1, close);
378
+ if (body[0] === '!') body = `^${body.slice(1)}`;
379
+ re += `[${body.replace(/\\/g, '\\\\')}]`;
380
+ i = close;
381
+ } else re += c.replace(/[.+^${}()|\\]/g, '\\$&');
382
+ }
383
+ return new RegExp(`^${part.startsWith('.') ? '' : '(?!\\.)'}${re}$`, 's');
384
+ }
385
+
386
+ // The words a one-pair brace word expands to, or null when the guard cannot tell (nested, several pairs, a sequence).
387
+ function braceWords(text) {
388
+ if (!/[{}]/.test(text)) return [text];
389
+ const m = /^([^{}]*)\{([^{}]*)\}([^{}]*)$/.exec(text);
390
+ if (!m) return /\{[^}]*\}/.test(text) ? null : [text];
391
+ if (m[2].includes('..')) return null;
392
+ return m[2].includes(',') ? m[2].split(',').map((alt) => m[1] + alt + m[3]) : [text];
393
+ }
394
+
395
+ // What one glob word in the workspace matches, walked with readdir, or null when a folder it walks is unreadable,
396
+ // or it climbs with `..`, uses `**` or matches too many names.
397
+ function globMatches(st, text) {
398
+ if (text.split('/').includes('..')) return null;
399
+ let dirs = [sep];
400
+ const parts = resolve(st.here, text).split(sep).filter(Boolean);
401
+ for (let p = 0; p < parts.length; p += 1) {
402
+ const part = parts[p];
403
+ if (!/[*?[]/.test(part)) { dirs = dirs.map((d) => join(d, part)); continue; }
404
+ if (part.includes('**')) return null;
405
+ const re = globRegex(part);
406
+ const last = p === parts.length - 1;
407
+ const next = [];
408
+ for (const d of dirs) {
409
+ let names;
410
+ try { names = readdirSync(d); } catch { return null; }
411
+ for (const name of names) {
412
+ if (!re.test(name)) continue;
413
+ const hit = join(d, name);
414
+ if (!last) {
415
+ try { if (!statSync(hit).isDirectory()) continue; } catch { continue; }
416
+ }
417
+ next.push(hit);
418
+ if (next.length > GLOB_WORDS) return null;
419
+ }
420
+ }
421
+ dirs = next.sort();
422
+ }
423
+ return dirs;
424
+ }
425
+
426
+ // Expands the unquoted braces and globs of a reader's operands in the workspace into the words the shell would pass,
427
+ // so the checks below see every file a pattern names. Verbs that write or delete, git, and patterns that leave the
428
+ // workspace keep their glob word and are held further down.
429
+ function expandWords(st, words) {
430
+ const verb = words[0]?.text;
431
+ if (!verb || words[0].glob || B_FLAGS[verb] || DELETERS.has(verb) || verb === 'git') return words;
432
+ const out = [words[0]];
433
+ for (const w of words.slice(1)) {
434
+ if (!w.glob) { out.push(w); continue; }
435
+ if (w.quoted) return { held: 'a glob word that is partly quoted' };
436
+ const alts = braceWords(w.text);
437
+ if (!alts) return { held: 'a brace form the guard cannot expand' };
438
+ for (const alt of alts) {
439
+ if (!/[*?[]/.test(alt)) { out.push({ text: alt }); continue; }
440
+ // POSIX classes, equivalence classes and collating symbols are left to the shell, which the regex cannot follow.
441
+ if (/\[[:=.]/.test(alt)) return { held: `\`${alt}\` uses a bracket class the guard does not read` };
442
+ if (!within(st.root, resolve(st.here, alt))) { out.push({ ...w, text: alt }); continue; }
443
+ const hits = globMatches(st, alt);
444
+ if (!hits) return { held: `the guard could not expand \`${alt}\` (an unreadable folder, \`..\`, \`**\` or too many matches)` };
445
+ // No match: the shell may still expand what the guard matched differently, so it is held, not passed as text.
446
+ if (!hits.length) return { held: `\`${alt}\` matches nothing the guard can see` };
447
+ out.push(...hits.map((h) => ({ text: h })));
448
+ }
449
+ if (out.length > GLOB_WORDS) return { held: 'a glob that matches too many names' };
450
+ }
451
+ return out;
452
+ }
453
+
454
+ function classifySegment(seg, st, ctx) {
455
+ const env = st.env;
456
+ const homed = [];
457
+ for (const w of seg.words) {
458
+ const h = homeWord(w, env);
459
+ if (h.refuse) return { level: 'refuse', reason: h.refuse };
460
+ homed.push({ ...w, text: h.text });
461
+ }
462
+ const raw = expandWords(st, homed);
463
+ if (raw.held) return { level: 'held', reason: raw.held };
464
+ const words = raw.map((w) => w.text);
465
+ // Every word that could name a path is checked against the protected list, wherever it sits.
466
+ // A `name=value` operand (dd of=, make DESTDIR=, --flag=) is checked on its value too.
467
+ for (const w of words.slice(1).concat(seg.redirects.map((r) => r.target))) {
468
+ const values = w.startsWith('-') ? [] : [w];
469
+ if (w.includes('=')) values.push(w.slice(w.indexOf('=') + 1));
470
+ // `REV:path` (git show HEAD:.env) and `host:path` name a path after the colon.
471
+ if (/^[^:/\s]+:[^/]/.test(w)) values.push(w.slice(w.indexOf(':') + 1));
472
+ // `:path` and `:<stage>:path` name a file in the git index (git show :.env).
473
+ const index = /^:(?:\d:)?(.+)/.exec(w);
474
+ if (index) values.push(index[1]);
475
+ for (const value of values.filter(Boolean)) {
476
+ const reason = protectedReason(resolve(st.here, value), env);
477
+ if (reason) return { level: 'refuse', reason };
478
+ if (ctx.denied?.paths?.some((d) => within(d, locate(resolve(st.here, value)).real))) return { level: 'refuse', reason: 'the user answered `lit deny` to this path in this run' };
479
+ }
480
+ }
481
+ for (const root of recursiveRoots(words[0], words.slice(1))) {
482
+ const reason = protectedBelow(resolve(st.here, root), env);
483
+ if (reason) return { level: 'refuse', reason };
484
+ }
485
+ let v = { level: 'allow' };
486
+ for (const r of seg.redirects) {
487
+ if (r.op === '<' || r.target === '/dev/null') continue;
488
+ v = worse(v, writeTarget(st, ctx, r.target));
489
+ if (v.level === 'refuse') return v;
490
+ }
491
+ const verb = words[0];
492
+ if (verb === undefined) return v;
493
+ if (raw[0].glob) return { level: 'held', reason: 'a glob in the verb' };
494
+ if (ASSIGNMENT.test(verb)) return { level: 'held', reason: `an assignment (\`${verb.split('=')[0]}=\`) before the verb changes what runs` };
495
+ if (OPAQUE.has(verb)) return { level: 'held', reason: `\`${verb}\` runs another verb or moves the shell in a way the guard cannot follow` };
496
+ if (DECODERS(words)) return { level: 'held', reason: 'decoded bytes may hide a command' };
497
+ if (raw.slice(1).some((w) => w.glob && !w.quoted)) {
498
+ const outside = raw.slice(1).some((w) => w.glob && !within(st.root, resolve(st.here, w.text)));
499
+ if (outside || B_FLAGS[verb] || DELETERS.has(verb) || verb === 'git') return { level: 'held', reason: 'a glob or brace the guard cannot expand' };
500
+ }
501
+ const args = words.slice(1);
502
+ const hidden = readerWrites(st, ctx, verb, args);
503
+ if (hidden) {
504
+ v = worse(v, hidden);
505
+ if (v.level === 'refuse' || v.level === 'held') return v;
506
+ }
507
+ if (verb === 'cd') return worse(v, cdSegment(st, ctx, args));
508
+ if (B_FLAGS[verb]) return worse(v, fileVerb(st, ctx, verb, args));
509
+ if (verb === 'git') return worse(v, gitSegment(st, ctx, args));
510
+ if (verb === 'tee') {
511
+ for (const a of args.filter((x) => !x.startsWith('-'))) v = worse(v, writeTarget(st, ctx, a));
512
+ return v;
513
+ }
514
+ if (DELETERS.has(verb)) return worse(v, deleter(st, ctx, args.filter((a) => !a.startsWith('-')), verb));
515
+ if (verb === 'find') {
516
+ if (args.some((a) => /^-(?:exec|execdir|ok|okdir)$/.test(a))) return { level: 'held', reason: '`find -exec` runs another verb' };
517
+ if (args.includes('-delete')) {
518
+ const starts = args.slice(0, Math.max(0, args.findIndex((a) => a.startsWith('-')))).filter(Boolean);
519
+ return worse(v, deleter(st, ctx, starts.length ? starts : ['.'], 'find -delete'));
520
+ }
521
+ return v;
522
+ }
523
+ if (NETWORK.has(verb)) return worse(v, { level: 'X', reason: `\`${verb}\` reaches outside the machine or a host home` });
524
+ if (PACKAGE_MANAGERS.has(verb)) return worse(v, packageScript(verb, args, ctx));
525
+ if (INSTALLERS.has(verb)) {
526
+ const sub = args.find((a) => !a.startsWith('-'));
527
+ if (TOOLCHAIN_CHECKS[verb]?.has(sub)) return v;
528
+ return worse(v, { level: 'X', reason: `\`${verb} ${sub ?? ''}\` ${sub && INSTALL_SUBS.has(sub) ? 'installs or publishes' : 'is not one of the project\'s test or check commands'}` });
529
+ }
530
+ if (TEST_RUNNERS.has(verb)) return v;
531
+ if (verb === 'make') {
532
+ const targets = args.filter((a) => !a.startsWith('-') && !a.includes('='));
533
+ if (!targets.length || targets.some((t) => !MAKE_SAFE.has(t))) return worse(v, { level: 'X', reason: '`make` runs whatever the target says' });
534
+ return v;
535
+ }
536
+ if (RUNNERS.has(verb) || verb.includes('/')) return worse(v, runner(st, ctx, verb, args));
537
+ if (SAFE_VERBS.has(verb)) return v;
538
+ // Default deny: a verb the guard does not know is parked, whatever it does.
539
+ return worse(v, { level: 'X', reason: `\`${verb}\` is not a verb the run guard knows` });
540
+ }
541
+
542
+ // A sed script is read only when it is a run of p, d, q and s///[gpiI0-9] commands with optional line or /re/
543
+ // addresses. Its w, W, r, R and e commands (and the s///w and s///e flags) write, read or run something else.
544
+ const SED_ADDR = String.raw`(?:\d+|\$|\/(?:[^\/\\]|\\.)*\/)`;
545
+ const SED_CMD = new RegExp(String.raw`\s*(?:${SED_ADDR}(?:,${SED_ADDR})?)?\s*!?\s*(?:[pdqP=]|s([^\s\\\n])(?:(?!\1)[^\\]|\\.)*\1(?:(?!\1)[^\\]|\\.)*\1[gpiI0-9]*)\s*(?:[;\n]|$)`, 'y');
546
+ export function sedScriptIsReadOnly(script) {
547
+ if (!script.trim()) return true;
548
+ SED_CMD.lastIndex = 0;
549
+ let at = 0;
550
+ while (at < script.length) {
551
+ SED_CMD.lastIndex = at;
552
+ const m = SED_CMD.exec(script);
553
+ if (!m || m[0].length === 0) return false;
554
+ at += m[0].length;
555
+ }
556
+ return true;
557
+ }
558
+
559
+ // Option values that name a file the verb writes (`sort -o f`, `git diff --output=f`) or a program it starts
560
+ // (`rg --pre cmd`, `sort --compress-program`), and operands that are output files (`uniq in out`).
561
+ function optionValues(args, names) {
562
+ const out = [];
563
+ for (let i = 0; i < args.length; i += 1) {
564
+ const a = args[i];
565
+ for (const n of names) {
566
+ if (a === n && args[i + 1] !== undefined) out.push(args[i + 1]);
567
+ else if (n.startsWith('--') && a.startsWith(`${n}=`)) out.push(a.slice(n.length + 1));
568
+ else if (!n.startsWith('--') && a.startsWith(n) && a.length > n.length) out.push(a.slice(n.length));
569
+ }
570
+ }
571
+ return out;
572
+ }
573
+
574
+ function readerWrites(st, ctx, verb, args) {
575
+ const writes = (targets) => targets.reduce((v, t) => worse(v, writeTarget(st, ctx, t)), { level: 'allow' });
576
+ if (verb === 'sed') {
577
+ if (args.some((a) => /^(?:-f|--file)(?:=|$)/.test(a) || /^-[a-zA-Z]*f$/.test(a))) return { level: 'held', reason: '`sed -f` reads its script from a file the guard cannot check' };
578
+ const exprs = optionValues(args, ['-e', '--expression']);
579
+ const operands = [];
580
+ for (let i = 0; i < args.length; i += 1) {
581
+ if (args[i] === '-e' || args[i] === '--expression') { i += 1; continue; }
582
+ if (!args[i].startsWith('-')) operands.push(args[i]);
583
+ }
584
+ const scripts = exprs.length ? exprs : operands.slice(0, 1);
585
+ const files = exprs.length ? operands : operands.slice(1);
586
+ if (!scripts.every(sedScriptIsReadOnly)) return { level: 'held', reason: 'a sed script with a w, W, r, R or e command (or an s///w or s///e flag) writes, reads or runs something the guard cannot check' };
587
+ if (args.some((a) => /^(?:-i|--in-place)/.test(a) || /^-[a-zA-Z]*i/.test(a) && !a.startsWith('--'))) return writes(files);
588
+ return null;
589
+ }
590
+ // A pager's +command runs on open (`+!cmd` starts a shell); jq can print the environment or the file it reads;
591
+ // rg --hostname-bin starts a program.
592
+ if ((verb === 'less' || verb === 'more') && args.some((a) => a.startsWith('+') || /^--?(?:cmd|command)/.test(a))) {
593
+ return { level: 'held', reason: `\`${verb} +command\` runs a command on open` };
594
+ }
595
+ if (verb === 'jq' && args.some((a) => /\benv\b|\$ENV\b|\binput_filename\b|\$__loc__|\$__prog_args\b/.test(a))) {
596
+ return { level: 'held', reason: '`jq` reading the environment or its own input names' };
597
+ }
598
+ if (verb === 'rg' && args.some((a) => /^--hostname-bin(?:=|$)/.test(a))) return { level: 'held', reason: '`rg --hostname-bin` starts a program' };
599
+ if (verb === 'grep' || verb === 'egrep' || verb === 'fgrep' || verb === 'rg') {
600
+ const { files } = searchArgs(verb, args);
601
+ if (files.some((p) => !p || pathFacts(st, ctx, p).zone === 'outside')) return { level: 'held', reason: `\`${verb} -f\` reads its patterns from a file outside the project` };
602
+ }
603
+ if (verb === 'awk' || verb === 'gawk' || verb === 'mawk' || verb === 'nawk') {
604
+ if (args.some((a) => a === '-f' || a.startsWith('--file'))) return { level: 'held', reason: '`awk -f` reads its program from a file the guard cannot check' };
605
+ const program = args.find((a) => !a.startsWith('-')) ?? '';
606
+ if (/\bsystem\s*\(|\bgetline\b|\||>|\bclose\s*\(|\bfflush\b|@load|@include/.test(program)) return { level: 'held', reason: 'an awk program that may run a command or write a file (system, getline, |, >)' };
607
+ return null;
608
+ }
609
+ if (verb === 'sort' || verb === 'file') {
610
+ const o = readOptions(args, OPTION_SPECS[verb]);
611
+ if (o.held) return { level: 'held', reason: `\`${verb} ${o.held}\` is not one of its read-only options` };
612
+ if (o.x) return { level: 'X', reason: `\`${verb} ${o.x}\` writes a file` };
613
+ return o.writes.length ? writes(o.writes) : null;
614
+ }
615
+ if (verb === 'uniq') {
616
+ const operands = args.filter((a) => !a.startsWith('-') || a === '-');
617
+ return operands.length > 1 ? writes(operands.slice(1)) : null;
618
+ }
619
+ if (verb === 'tree') return writes(optionValues(args, ['-o']));
620
+ if (verb === 'rg') {
621
+ if (optionValues(args, ['--pre']).length || args.some((a) => a === '--pre' || a.startsWith('--pre='))) return { level: 'held', reason: '`rg --pre` runs a program on every file' };
622
+ return null;
623
+ }
624
+ if (verb === 'git') {
625
+ if (args.some((a) => /^(?:-O|--open-files-in-pager)/.test(a))) return { level: 'held', reason: '`git grep -O` starts a pager program' };
626
+ if (args.some((a) => /^--(?:ext-diff|textconv)$/.test(a))) return { level: 'held', reason: 'an external diff or textconv program runs' };
627
+ return writes(optionValues(args, ['--output', '--output-directory']));
628
+ }
629
+ if (verb === 'find') {
630
+ const idx = args.findIndex((a) => /^-(?:fprint|fprint0|fprintf|fls)$/.test(a));
631
+ if (idx >= 0) return worse(writes([args[idx + 1] ?? '.']), { level: 'X', reason: '`find -fprint` writes a file' });
632
+ return null;
633
+ }
634
+ return null;
635
+ }
636
+
637
+ // Option allowlists for readers whose options can write or run something. Short options may be clustered
638
+ // (`-uo F`), long ones abbreviated to any unambiguous prefix (`--out=F`, `--comp`), as GNU tools accept; an option
639
+ // off the list, or an ambiguous prefix, is held. `write` names an output file, `x` writes by itself.
640
+ const OPTION_SPECS = {
641
+ sort: {
642
+ short: { flags: 'bdfghiMmnRrsuVzcC', value: 'ktS', write: 'o', held: 'T' },
643
+ long: { flags: ['ignore-leading-blanks', 'dictionary-order', 'ignore-case', 'general-numeric-sort', 'ignore-nonprinting', 'month-sort',
644
+ 'human-numeric-sort', 'numeric-sort', 'random-sort', 'reverse', 'version-sort', 'merge', 'stable', 'unique', 'zero-terminated', 'check',
645
+ 'debug', 'help', 'version'],
646
+ value: ['key', 'field-separator', 'buffer-size', 'parallel', 'sort'], write: ['output'],
647
+ held: ['compress-program', 'temporary-directory', 'files0-from', 'random-source'] },
648
+ },
649
+ file: {
650
+ short: { flags: 'bcdEhiIklLNnprsSvzZ0', value: 'eFP', x: 'C', held: 'fmM' },
651
+ long: { flags: ['brief', 'checking-printout', 'dereference', 'no-dereference', 'mime', 'mime-type', 'mime-encoding', 'keep-going', 'list',
652
+ 'raw', 'special-files', 'uncompress', 'uncompress-noreport', 'no-pad', 'no-buffer', 'preserve-date', 'print0', 'extension', 'apple',
653
+ 'help', 'version'],
654
+ value: ['separator', 'exclude', 'exclude-quiet', 'parameter'], x: ['compile'], held: ['magic-file', 'files-from'] },
655
+ },
656
+ };
657
+
658
+ function readOptions(args, spec) {
659
+ const out = { writes: [], held: null, x: null };
660
+ const longNames = Object.entries(spec.long).flatMap(([kind, names]) => names.map((n) => [n, kind]));
661
+ for (let i = 0; i < args.length; i += 1) {
662
+ const a = args[i];
663
+ if (a === '--') break;
664
+ if (a.startsWith('--')) {
665
+ const [name, inline] = a.slice(2).split(/=(.*)/s);
666
+ const exact = longNames.find(([n]) => n === name);
667
+ const hits = exact ? [exact] : longNames.filter(([n]) => n.startsWith(name));
668
+ if (hits.length !== 1) { out.held ??= a; continue; }
669
+ const [, kind] = hits[0];
670
+ const takes = kind === 'value' || kind === 'write' || kind === 'held';
671
+ const value = inline !== undefined ? inline : (takes ? args[(i += 1)] : undefined);
672
+ if (kind === 'held') out.held ??= a;
673
+ else if (kind === 'x') out.x ??= a;
674
+ else if (kind === 'write') out.writes.push(value ?? '');
675
+ continue;
676
+ }
677
+ if (!a.startsWith('-') || a === '-') continue;
678
+ for (let j = 1; j < a.length; j += 1) {
679
+ const c = a[j];
680
+ if (spec.short.flags.includes(c)) continue;
681
+ if (spec.short.x?.includes(c)) { out.x ??= a; continue; }
682
+ const takes = spec.short.value.includes(c) || spec.short.write?.includes(c) || spec.short.held?.includes(c);
683
+ if (!takes) { out.held ??= a; break; }
684
+ const value = j + 1 < a.length ? a.slice(j + 1) : args[(i += 1)];
685
+ if (spec.short.write?.includes(c)) out.writes.push(value ?? '');
686
+ else if (spec.short.held?.includes(c)) out.held ??= a;
687
+ break;
688
+ }
689
+ }
690
+ return out;
691
+ }
692
+
693
+ // grep and rg options that take a value, so the word after them (or the rest of a short cluster) is not a path.
694
+ const SEARCH_VALUES = {
695
+ grep: { short: 'ABCDdefm', long: ['after-context', 'before-context', 'context', 'devices', 'directories', 'regexp', 'file', 'max-count',
696
+ 'label', 'include', 'exclude', 'exclude-from', 'exclude-dir', 'group-separator', 'binary-files'] },
697
+ rg: { short: 'ABCdEefgjMmrTt', long: ['regexp', 'file', 'glob', 'iglob', 'type', 'type-not', 'type-add', 'type-clear', 'max-count', 'max-depth',
698
+ 'replace', 'encoding', 'threads', 'max-columns', 'after-context', 'before-context', 'context', 'pre', 'pre-glob', 'ignore-file',
699
+ 'path-separator', 'sort', 'sortr', 'colors', 'context-separator', 'field-match-separator', 'field-context-separator', 'max-filesize',
700
+ 'dfa-size-limit', 'regex-size-limit', 'engine', 'hostname-bin', 'hyperlink-format', 'generate'] },
701
+ };
702
+
703
+ // One parse of a grep or rg command line: whether it recurses, its pattern files, and the paths it reads. A short
704
+ // cluster may end in a value option (`-rf FILE`, `-reKEY`); a pattern given by -e or -f leaves every operand a path,
705
+ // and so does `rg --files`. A long option is matched by its unambiguous prefix, as GNU grep accepts.
706
+ function searchArgs(verb, args) {
707
+ const spec = SEARCH_VALUES[verb === 'rg' ? 'rg' : 'grep'];
708
+ const out = { recursive: verb === 'rg', files: [], paths: [] };
709
+ let given = false;
710
+ const operands = [];
711
+ const take = (name, value) => {
712
+ if (name === 'e' || name === 'regexp') given = true;
713
+ if (name === 'f' || name === 'file') { given = true; out.files.push(value ?? ''); }
714
+ if ((name === 'd' || name === 'directories') && verb !== 'rg' && value === 'recurse') out.recursive = true;
715
+ };
716
+ for (let i = 0; i < args.length; i += 1) {
717
+ const a = args[i];
718
+ if (a === '--') { operands.push(...args.slice(i + 1)); break; }
719
+ if (a.startsWith('--')) {
720
+ const [name, inline] = a.slice(2).split(/=(.*)/s);
721
+ if (verb !== 'rg' && (name === 'recursive' || name === 'dereference-recursive')) out.recursive = true;
722
+ if (verb === 'rg' && name === 'files') given = true;
723
+ const prefixed = spec.long.filter((n) => n.startsWith(name));
724
+ const known = spec.long.includes(name) ? name : prefixed.length === 1 ? prefixed[0] : null;
725
+ if (known) take(known, inline !== undefined ? inline : args[(i += 1)]);
726
+ continue;
727
+ }
728
+ if (!a.startsWith('-') || a === '-') { operands.push(a); continue; }
729
+ for (let j = 1; j < a.length; j += 1) {
730
+ const c = a[j];
731
+ if ((c === 'r' || c === 'R') && verb !== 'rg') { out.recursive = true; continue; }
732
+ if (!spec.short.includes(c)) continue;
733
+ take(c, j + 1 < a.length ? a.slice(j + 1) : args[(i += 1)]);
734
+ break;
735
+ }
736
+ }
737
+ out.paths = given ? operands : operands.slice(1);
738
+ return out;
739
+ }
740
+
741
+
742
+ // The folders a recursive reader would walk, or [] when it does not recurse. Over-reading an option value as a
743
+ // folder only checks one more path.
744
+ function recursiveRoots(verb, args) {
745
+ const nonOpt = args.filter((a) => !a.startsWith('-'));
746
+ if (verb === 'find') {
747
+ // -H, -L, -P, -O<level> and -D <list> come before the start paths.
748
+ let k = 0;
749
+ while (k < args.length && /^-(?:[HLP]+|O\d*|D)$/.test(args[k])) k += args[k] === '-D' ? 2 : 1;
750
+ const rest = args.slice(k);
751
+ const end = rest.findIndex((a) => a.startsWith('-') || a === '(' || a === '!');
752
+ const starts = (end < 0 ? rest : rest.slice(0, end)).filter(Boolean);
753
+ return starts.length ? starts : ['.'];
754
+ }
755
+ if (verb === 'grep' || verb === 'egrep' || verb === 'fgrep' || verb === 'rg') {
756
+ const s = searchArgs(verb, args);
757
+ if (!s.recursive) return [];
758
+ return s.paths.length ? s.paths : ['.'];
759
+ }
760
+ if (verb === 'diff') return args.some((a) => a === '--recursive' || (/^-[a-zA-Z]*r/.test(a) && !a.startsWith('--'))) ? nonOpt : [];
761
+ if (verb === 'ls') return args.some((a) => /^-[a-zA-Z]*R/.test(a) || a === '--recursive') ? (nonOpt.length ? nonOpt : ['.']) : [];
762
+ if (verb === 'tree' || verb === 'du') return nonOpt.length ? nonOpt : ['.'];
763
+ return [];
764
+ }
765
+
766
+ // Why walking this folder would read a protected place below it, or null.
767
+ export function protectedBelow(abs, env) {
768
+ const real = locate(abs).real;
769
+ for (const p of new Set([resolve(abs), real])) {
770
+ for (const home of homes(env)) {
771
+ for (const s of HOME_SECRETS) if (within(p, join(home, s))) return `a recursive read over ${join('~', s)}`;
772
+ }
773
+ if (within(p, join(stateHome(env), 'litmuse'))) return 'a recursive read over the LitMuse run state';
774
+ }
775
+ return null;
776
+ }
777
+
778
+ // npm, pnpm, yarn and bun: test and check scripts (and the plan's own check) run; every other script, install,
779
+ // publish, exec or download is parked as X, whatever its body says.
780
+ function packageScript(verb, args, ctx) {
781
+ const words = args.filter((a) => !a.startsWith('-'));
782
+ const [sub, name] = words;
783
+ if (ctx.check && [verb, ...args].join(' ') === ctx.check) return { level: 'allow' };
784
+ if (!sub && verb !== 'npm') return { level: 'X', reason: `a bare \`${verb}\` installs dependencies` };
785
+ if (!sub || PM_READERS.has(sub) || PM_READERS.has(args[0])) return { level: 'allow' };
786
+ if (sub === 'test' || sub === 't') return { level: 'allow' };
787
+ if ((sub === 'run' || sub === 'run-script') && name && CHECK_SCRIPT.test(name)) return { level: 'allow' };
788
+ if ((verb === 'yarn' || verb === 'pnpm' || verb === 'bun') && CHECK_SCRIPT.test(sub)) return { level: 'allow' };
789
+ return { level: 'X', reason: `\`${verb} ${sub}${name && (sub === 'run' || sub === 'run-script') ? ` ${name}` : ''}\` runs package code, changes dependencies or reaches the registry` };
790
+ }
791
+
792
+ // A write into the account's real home, outside the workspace and every Scope root, is refused, never parked.
793
+ function homeWrite(f, env) {
794
+ return f.zone === 'outside' && homes(env).some((h) => within(h, f.real) || within(h, f.abs)) ? 'a write into the real host home outside the workspace' : null;
795
+ }
796
+
797
+ // A shell write by redirect or tee. A writable Scope root takes it; inside the workspace it parks, because file
798
+ // edits go through the file tools (write_file, edit_file, apply_patch), which the guard checks path by path.
799
+ function writeTarget(st, ctx, text) {
800
+ const f = pathFacts(st, ctx, text);
801
+ const prot = protectedReason(f.abs, st.env, true, st.root) ?? homeWrite(f, st.env);
802
+ if (prot) return { level: 'refuse', reason: prot };
803
+ if (f.git) return { level: 'refuse', reason: 'writes inside .git are refused during a run' };
804
+ if (f.zone === 'root-write') return { level: 'allow' };
805
+ if (f.zone === 'workspace') return { level: 'X', reason: `a shell write to ${f.abs}; write files with write_file or edit_file instead` };
806
+ return { level: 'X', reason: where(f) };
807
+ }
808
+
809
+ function cdSegment(st, ctx, args) {
810
+ const dir = args.find((a) => !a.startsWith('-') || a === '-');
811
+ if (args.length && args.every((a) => a.startsWith('-') && a !== '-')) return { level: 'held', reason: '`cd` flags' };
812
+ if (dir === undefined) return { level: 'refuse', reason: 'a bare `cd` goes to the home folder' };
813
+ if (dir === '-') return { level: 'held', reason: '`cd -` goes to a folder the guard cannot see' };
814
+ st.here = resolve(st.here, dir);
815
+ const f = pathFacts({ ...st, here: st.here }, ctx, '.');
816
+ if (f.zone === 'outside') return { level: 'X', reason: `\`cd ${dir}\` leaves the workspace and its Scope roots`, bVerb: true };
817
+ return { level: 'allow', bVerb: true };
818
+ }
819
+
820
+ // touch, mkdir, cp and mv: writable roots run; a new destination in a read-only Scope root is tier B; anything that
821
+ // leaves every known root, follows a dangling link, overwrites or uses an unlisted flag is X. A destination that is
822
+ // an existing folder is checked as the paths written inside it, so `cp a .` in the project root is an ordinary copy;
823
+ // mv sources are removals and cp sources are reads of the run state, so both keep the run-state check.
824
+ function fileVerb(st, ctx, verb, args) {
825
+ const flags = args.filter((a) => a.startsWith('-'));
826
+ const paths = args.filter((a) => !a.startsWith('-'));
827
+ if (!paths.length) return { level: 'X', reason: `\`${verb}\` with no path`, bVerb: true };
828
+ if ((verb === 'cp' || verb === 'mv') && paths.length < 2) return { level: 'X', reason: `\`${verb}\` needs a source and a destination`, bVerb: true };
829
+ const sources = verb === 'cp' || verb === 'mv' ? paths.slice(0, -1) : [];
830
+ const dest = paths[paths.length - 1];
831
+ const landing = sources.length && isDir(pathFacts(st, ctx, dest).real) ? sources.map((p) => join(dest, basename(p))) : [dest];
832
+ const writes = verb === 'cp' ? landing : verb === 'mv' ? [...sources, ...landing] : paths;
833
+ const reads = verb === 'cp' ? sources : [];
834
+ let level = 'allow';
835
+ let reason;
836
+ for (const p of writes) {
837
+ const f = pathFacts(st, ctx, p);
838
+ const prot = protectedReason(f.abs, st.env, true, st.root) ?? homeWrite(f, st.env);
839
+ if (prot) return { level: 'refuse', reason: prot };
840
+ if (f.git) return { level: 'refuse', reason: 'writes inside .git are refused during a run' };
841
+ if (f.zone === 'outside') return { level: 'X', reason: where(f), bVerb: true };
842
+ if (f.zone !== 'root-write' && level === 'allow') {
843
+ level = 'B';
844
+ reason = f.zone === 'workspace' ? `a new path in the workspace made by the shell (${f.abs})` : where(f);
845
+ }
846
+ }
847
+ for (const p of reads) {
848
+ const f = pathFacts(st, ctx, p);
849
+ const state = stateFolderReason(f.abs, locate(f.abs).real, st.env, st.root);
850
+ if (state) return { level: 'refuse', reason: state };
851
+ if (f.zone === 'outside') return { level: 'X', reason: `a source outside the workspace and its Scope roots (${f.abs})`, bVerb: true };
852
+ }
853
+ if (verb === 'cp' || verb === 'mv') {
854
+ const dst = pathFacts(st, ctx, paths[paths.length - 1]);
855
+ let overwrite = dst.exists && !isDir(dst.real);
856
+ if (dst.exists && isDir(dst.real)) overwrite = paths.slice(0, -1).some((s) => existsSync(join(dst.real, basename(s))));
857
+ if (overwrite) return { level: 'X', reason: 'the destination exists, so this would overwrite it', bVerb: true };
858
+ }
859
+ if (level === 'B' && !flags.every((f) => B_FLAGS[verb].test(f))) return { level: 'X', reason: `\`${verb}\` with flags off the B list`, bVerb: true };
860
+ return { level, reason, bVerb: true };
861
+ }
862
+
863
+ function isDir(p) {
864
+ try { return statSync(p).isDirectory(); } catch { return false; }
865
+ }
866
+
867
+ // A delete cannot be undone, so it is always X; protected paths and .git refuse.
868
+ function deleter(st, ctx, paths, label) {
869
+ if (!paths.length) return { level: 'X', reason: `\`${label}\` with no path` };
870
+ for (const p of paths) {
871
+ const f = pathFacts(st, ctx, p);
872
+ const prot = protectedReason(f.abs, st.env, true, st.root) ?? homeWrite(f, st.env);
873
+ if (prot) return { level: 'refuse', reason: prot };
874
+ if (f.git) return { level: 'refuse', reason: 'deleting inside .git is refused during a run' };
875
+ }
876
+ return { level: 'X', reason: `\`${label}\` cannot be undone` };
877
+ }
878
+
879
+ function runner(st, ctx, verb, args) {
880
+ if (verb.includes('/')) {
881
+ const f = pathFacts(st, ctx, verb);
882
+ return f.writable ? { level: 'allow' } : { level: 'X', reason: `a program outside the workspace (${f.abs})` };
883
+ }
884
+ const flag = args.find((a) => a.startsWith('-'));
885
+ const script = args.find((a) => !a.startsWith('-'));
886
+ const firstIsFlag = args.length && args[0].startsWith('-');
887
+ if (args.some((a) => INLINE_FLAG.test(a)) && (verb !== 'node' || args.some((a) => /^(?:-e|-p|--eval|--print)$/.test(a)))) {
888
+ return { level: 'held', reason: `inline code (\`${verb} ${flag}\`)` };
889
+ }
890
+ if (SHELLS.has(verb) && (!script || firstIsFlag)) return { level: 'held', reason: `\`${verb}\` reading commands the guard cannot see` };
891
+ if (!script) return { level: 'allow' };
892
+ if ((verb === 'python' || verb === 'python3') && args[0] === '-m') {
893
+ return /^(?:pytest|unittest)$/.test(args[1] ?? '') ? { level: 'allow' } : { level: 'X', reason: `\`${verb} -m ${args[1] ?? ''}\` runs a module that is not the project's test runner` };
894
+ }
895
+ const f = pathFacts(st, ctx, script);
896
+ if (!f.writable) return { level: 'X', reason: `a script outside the workspace (${f.abs})` };
897
+ return { level: 'allow' };
898
+ }
899
+
900
+ // --- git -----------------------------------------------------------------------------------------------------
901
+
902
+ function gitSegment(st, ctx, args) {
903
+ let i = 0;
904
+ let here = st.here;
905
+ while (i < args.length && args[i].startsWith('-')) {
906
+ if (args[i] === '-C' && args[i + 1]) {
907
+ here = resolve(here, args[i + 1]);
908
+ if (!within(st.root, locate(here).real)) return { level: 'X', reason: '`git -C` names a folder outside the workspace' };
909
+ i += 2;
910
+ continue;
911
+ }
912
+ return { level: 'X', reason: `\`git ${args[i]}\` changes how git runs` };
913
+ }
914
+ const sub = args[i];
915
+ const rest = args.slice(i + 1);
916
+ const viaC = i > 0;
917
+ if (!sub) return { level: 'allow' };
918
+ if (GIT_LOCAL.has(sub)) return { level: 'allow' };
919
+ if (sub === 'branch' && rest.every((a) => /^(?:--show-current|--list|-a|-v|-vv|--all|-r)$/.test(a))) return { level: 'allow' };
920
+ if ((sub === 'worktree' || sub === 'stash') && rest[0] === 'list') return { level: 'allow' };
921
+ // `git remote`, `-v` and `get-url` read the local config; `show`, `update` and the rest reach or change a remote.
922
+ if (sub === 'remote' && (!rest.length || (rest.length === 1 && /^(?:-v|--verbose)$/.test(rest[0])) || (rest[0] === 'get-url' && rest.slice(1).every((a) => /^(?:--push|--all|[\w.-]+)$/.test(a))))) return { level: 'allow' };
923
+ if (sub === 'add') {
924
+ const added = gitAdd({ ...st, here }, ctx, rest);
925
+ return added.level === 'allow' && !ctx.charter?.length ? { level: 'B', reason: '`git add` stages files for a commit the plan has no `Run charter:` for', bVerb: true } : added;
926
+ }
927
+ if (sub === 'commit') return viaC ? { level: 'X', reason: '`git -C` commit is outside the charter' } : commitVerdict({ ...st, here }, ctx, rest);
928
+ return { level: 'X', reason: `\`git ${sub}\` may rewrite history, reach a remote, or is not a subcommand the guard knows` };
929
+ }
930
+
931
+ function gitAdd(st, ctx, rest) {
932
+ const paths = rest.filter((a) => !a.startsWith('-'));
933
+ if (rest.some((a) => /^(?:-A|--all|-u|--update|--no-ignore-removal|-f|--force|--)$/.test(a)) || !paths.length) {
934
+ return { level: 'X', reason: '`git add` must name the files (no -A, -u, -f or empty list)', bVerb: true };
935
+ }
936
+ for (const p of paths) {
937
+ if (p === '.' || p === ':/' || p.startsWith(':')) return { level: 'X', reason: '`git add .` stages everything', bVerb: true };
938
+ const f = pathFacts(st, ctx, p);
939
+ if (f.git) return { level: 'refuse', reason: '.git internals' };
940
+ if (f.zone !== 'workspace') return { level: 'X', reason: `\`git add\` outside the workspace (${f.abs})`, bVerb: true };
941
+ }
942
+ return { level: 'allow', bVerb: true };
943
+ }
944
+
945
+ export function gitRoot(dir) {
946
+ for (let cur = resolve(dir); ; cur = dirname(cur)) {
947
+ if (existsSync(join(cur, '.git'))) return cur;
948
+ if (dirname(cur) === cur) return null;
949
+ }
950
+ }
951
+
952
+ // The branch HEAD names, read at call time; a linked worktree's `.git` file points at its own HEAD.
953
+ export function headBranch(repo) {
954
+ try {
955
+ let gitDir = join(repo, '.git');
956
+ if (lstatSync(gitDir).isFile()) {
957
+ const m = /^gitdir:\s*(.+)\s*$/m.exec(readFileSync(gitDir, 'utf8'));
958
+ if (!m) return null;
959
+ gitDir = resolve(repo, m[1].trim());
960
+ }
961
+ const head = readFileSync(join(gitDir, 'HEAD'), 'utf8').trim();
962
+ const m = /^ref:\s*refs\/heads\/(.+)$/.exec(head);
963
+ return m ? m[1] : null;
964
+ } catch {
965
+ return null;
966
+ }
967
+ }
968
+
969
+ const COMMIT_SWITCH = /^(?:-[aq]+|--all|--quiet)$/;
970
+ const COMMIT_MESSAGE = /^-[aq]*([mF])$/;
971
+
972
+ // A commit runs only under a `Run charter: commit on <branch> in <repo>` line the run started with, on that branch
973
+ // in that repo, with a plain message. Amend, no-verify, other flags, other branches and other repos are parked.
974
+ function commitVerdict(st, ctx, rest) {
975
+ if (!ctx.charter?.length) return { level: 'X', reason: 'a commit needs a `Run charter:` line in the plan' };
976
+ for (let i = 0; i < rest.length; i += 1) {
977
+ const a = rest[i];
978
+ if (COMMIT_SWITCH.test(a)) continue;
979
+ const m = COMMIT_MESSAGE.exec(a);
980
+ if (m && rest[i + 1] !== undefined) { i += 1; continue; }
981
+ return { level: 'X', reason: `\`git commit ${a}\` is outside the charter (plain -m, -F, -a, -q only)` };
982
+ }
983
+ const repo = gitRoot(st.here);
984
+ const branch = repo && headBranch(repo);
985
+ const hit = ctx.charter.find((c) => repo && realOr(c.repo) === realOr(repo) && c.branch === branch);
986
+ if (!hit) return { level: 'X', reason: `the charter grants commits on ${ctx.charter.map((c) => `${c.branch} in ${c.repo}`).join(', ')}; this is ${branch ?? 'no branch'} in ${repo ?? 'no repo'}` };
987
+ return { level: 'allow' };
988
+ }
989
+
990
+ // File tools (write_file, edit_file, apply_patch, delete_file) during a run: protected and .git targets are refused;
991
+ // a target outside the workspace and every writable Scope root becomes a path boundary the user can grant.
992
+ export function classifyWrite(target, ctx) {
993
+ const abs = resolve(ctx.cwd, target);
994
+ const reason = protectedReason(abs, ctx.env ?? process.env, true, ctx.root);
995
+ if (reason) return { action: 'refuse', reason };
996
+ if (ctx.denied?.paths?.some((d) => within(d, locate(abs).real))) return { action: 'refuse', reason: 'the user answered `lit deny` to this path in this run' };
997
+ const f = pathFacts({ here: ctx.cwd, root: ctx.root }, ctx, abs);
998
+ if (f.git) return { action: 'refuse', reason: 'writes inside .git (hooks, config, worktrees) are refused during a run' };
999
+ const home = homeWrite(f, ctx.env ?? process.env);
1000
+ if (home) return { action: 'refuse', reason: home };
1001
+ if (f.writable) return { action: 'allow' };
1002
+ const boundary = f.exists && isDir(f.real) ? f.real : dirname(f.real);
1003
+ return { action: 'park', boundary, reason: f.zone === 'root-read' ? 'in a Scope root granted for reading only' : 'outside the workspace' };
1004
+ }