SLOPSHOPPER

function-hooks

Shared command policies for Claude Code and Codex

guardtoastprocess
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · function-hooks
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ Denied by function-hooks: Command not parsed. failed. SyntaxError: JSON Parse error: Unexpected EOF ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

[RASM]

Rasm is a polyglot monorepo with macOS-first development and portable code and tooling for Linux and Windows.

[01]-[LAYOUT]

Rasm/
├── apps/
│   ├── blender/
│   ├── creative-cloud/
│   ├── macos/
│   ├── rhino/
│   └── web/
├── libs/
│   ├── dotnet/
│   ├── python/
│   ├── rust/
│   ├── swift/
│   └── typescript/
├── tests/
├── eng/
├── infra/                    # IaC programs for repository and app hosting resources
├── docs/                     # Research sheets, ignored under docs/research
├── tools/
│   ├── ast-grep/             # Grammar extensions, outlines, rules, and utilities per language
│   ├── bridge/               # rasm-mcp-bridge binary serving a stdio MCP server over Streamable HTTP
│   ├── dylint/               # Rust lints reading types and resolved paths Clippy lacks
│   ├── nx/                   # Nx plugin inferring a project from each project file
│   ├── refurb/               # Python checks reading mypy types Ruff lacks
│   ├── roslyn/               # C# analyzers, code fixes, and BannedSymbols*.txt bans
│   └── watch-apps/           # CLI for agents observing and driving desktop apps in the background
├── plugins/                  # Agent harness marketplace
├── mise.toml                 # Tool binaries, process environment, and local daemons
├── global.json               # .NET SDK versions
├── nx.json                   # Task graph
├── package.json              # Catalog rows except tool plugins, root Nx targets
├── pnpm-workspace.yaml       # TypeScript workspace globs and dependency catalog
├── pyproject.toml            # Python wheel project, dependency groups, and tool tables
├── Directory.Packages.props  # .NET central package versions
├── Directory.Build.props     # .NET build defaults and project classification by tree position
├── Directory.Build.targets   # .NET items, host package references, and build targets
├── Directory.Build.rsp       # MSBuild switches every command-line build under the root reads
├── Workspace.slnx            # .NET solution
├── NuGet.config              # NuGet source
├── Package.swift             # Swift modules, executables, and remote package catalog
├── Xcode.xcconfig            # Build settings every Xcode project inherits
├── tsconfig.base.json        # Compiler options every TypeScript project extends
├── tsconfig.json             # Root TypeScript project over files outside every package
├── vitest.config.ts          # Test and coverage options every project config imports
├── vite.shared.ts            # Bundling options every project config imports
├── biome.json                # TypeScript and JSON formatting and lint
├── pmd.xml                   # Java lint rules
├── sgconfig.yml              # ast-grep rule directories and language parsing
├── rust-toolchain.toml       # Rust toolchain channel and components
├── rustfmt.toml              # Rust format rules
├── clippy.toml               # Clippy lint options Cargo.toml lint tables lack
├── Cargo.toml                # Rust workspace and dependency catalog
├── .editorconfig             # Editor settings and .NET analyzer severity
├── .gitattributes            # Line endings, diff drivers, and LFS filters per extension
├── .gitignore                # Generated, secret, and machine-local paths
├── .swift-format             # Swift lint and format rules
├── .swiftlint.yml            # Swift lint rules swift-format lacks
├── .periphery.yml            # Swift unused code scan options
├── .yamllint.yaml            # YAML lint rules
├── .yamlfmt.yaml             # YAML format rules
├── .cargo/                   # Cargo build settings and compiler source link
├── .config/                  # Files tools find in .config/ or read through a path setting
├── .playwright/              # Playwright CLI workspace and browser options every CLI session reads
├── .github/                  # Continuous integration and repository workflows
├── .claude/                  # Claude Code knowledge and settings
├── .mcp.json                 # Claude Code MCP servers
├── .codex/                   # Codex knowledge and settings
├── .vscode/                  # VS Code settings and recommended extensions
├── CLAUDE.md                 # Agent standards, AGENTS.md is its symlink
└── README.md

[02]-[FLOW]

flowchart LR
    tools["Tool binary and SDK version"] --> toolchain["Installed toolchain"]
    variables["Process variable"] --> processes["Every process"]
    packages["Package version"] --> locks["Lock file"] --> installed["Installed packages"]
    project_files["Project file"] --> projects["Project with language and host tags"]
    defaults["Target defaults per tag"] --> targets["Project and root targets"]
    projects --> targets
    toolchain & processes & installed --> targets
    targets --> checks["Check, lint, format, build, test"]
    checks --> ci["CI per host runner"]

[03]-[TASKS]

Targets run tools with their arguments on the command, a pipeline or command list joins tools for work no single tool does.

  • nx run rasm:check runs every root checker and type checker, nx run rasm:lint:<tool> runs one checker
  • nx run <project>:check runs project checks and tests rasm:check leaves to each project
  • nx run <project>:<target> -- <arguments> appends to the command, paths in place of a root tool's default file set, switches to dotnet build
  • nx run rasm:format runs dotnet format over the solution and file-based apps, then every other writer
  • nx run rasm:format:files -- <paths> runs non-.NET writers over named Git files
  • nx run <project>:test:integration starts rasm:docker, then runs container cases test leaves out (Rust #[ignore], a Vitest project)
  • nx run <project>:install builds or packs a product and installs it into its host
  • nx run rasm:release on a clean tree tags and creates a GitHub release for each product Conventional Commits bump, then runs its publish
  • nx run <project>:publish --tag=<tag> pushes a released product to its host's channel
  • nx run rasm:infra:<preview|up|refresh> runs a Pulumi operation on repository resources
  • nx run <project>:hosting -- <cloudflare|docker> <preview|up|refresh|destroy> [--disposable] runs a Pulumi operation on a web app's stack
  • nx run rasm:upgrade moves catalogs, locks, action tags, and installed service binaries to newest releases
  • nx run rasm:clean removes declared outputs and tool residue, prunes caches and unused Pulumi plugins, and recovers stale macOS processes
  • nx run rasm:rewrite -- --filter='^<id>$' <path> applies one rule's fix across a path, rasm:outline -- <path> lists its declarations
  • Native Python consumers start under pixi run --locked -e hdf5 pixi run --locked -e default
  • Projects with .storybook/ run each story as a Chromium test case that fails on an axe violation
  • nx run <project>:e2e gives each Playwright worker its own app instance with empty stores
  • Xcode apps holding a UXP script build in a folder reference build that script first
  • Caches and outputs sit under root .cache/ and .artifacts/, each tool moved by one setting every run reads, or its guidance file states why not
  • Tool logs sit flat in .artifacts/logs/ as one <producer>.log, daemon and supervisor output sit in pitchfork's log store

[04]-[DELIVERY]

Products reach a person through separate levels:

  • Repository tooling serves development alone, installing builds over a host's previous install and running local services from the checkout
  • Each product's versioned tag and GitHub release mark one release and hold a packaged product's files as an alternative install path
  • Each host's install and update channel receives published products

[05]-[OWNERS]

[INDEX][CONCERN][OWNER]
[01]Tool binarymise.toml [tools] at latest
[02]Process variablemise.toml [env]
[03]SDK versionglobal.json for .NET, xcode-select for Swift, rust-toolchain.toml for Rust
[04]Package versionpnpm-workspace.yaml catalog, pyproject.toml [project] or group, Directory.Packages.props row
[05].NET tool packagedotnet dnx <id> on the command
[06]Task graphnx.json, root package.json nx
[07]Checker configurationTool's own file, pyproject.toml [tool.*] for every Python tool
[08]SecretDoppler agent-runtime/dev, named in the consuming target's doppler run prefix
[09]Resource or repository settingTyped row of an infra/ program, rasm:infra:up for the repository, <project>:hosting per app
[10]Tool with no consumerMachine setup
[11]Ghidra installOfficial distribution through mise
[12]Xcode build settingXcode.xcconfig, per-product rows in the .xcodeproj target
[13]Swift package versionRoot Package.swift dependencies row, .xcodeproj remote row for a package only an app imports
[14]Rust package versionCargo.toml [workspace.dependencies] row
[15]Agent harness pluginplugins/<name>
[16]Persistent local processmise.toml [daemons] row
[17]Python runtimeMise Python row, uv's .venv, host pyproject.toml requirements
[18]Native libraries for sdistsPixi environments in pyproject.toml, exact builds in pixi.lock
[19]Container runtimeMise clients, [daemons] docker row for Colima on macOS, Docker Engine on Linux
[20]Shared Vite configurationvite.shared.ts
[21]Shared Vitest configurationvitest.config.ts, browser settings and the story project every package derives
[22]Shared Storybook addons@rasm/test-support/preset and @rasm/test-support/preview entries
[23]Shared Playwright settings@rasm/test-support/playwright entry
[24]Test MCP suitestests/typescript/playwright.config.ts
[25]Agent browser options.playwright/cli.config.json
[26]GitHub Action versionPublished tag on each uses: row under .github/
[27]Product versionRelease tag rasm:release creates, MinVer reads it into builds and packages
  • Tool rows name a release where latest resolves a development build

[06]-[QUALITY]

  • Every compiler, analyzer, checker, and formatter a target runs stays at zero findings
  • Failing checks are fixed in the code or the rule, severity stays as configured
  • Mistakes no check reports become checks, held to the standards of the code they check

[07]-[STRUCTURE]

  • Libraries group under libs/<language>/<group>/ by domain or by host
  • Tests sit under tests/<language>/ at their source path without the language folder, Playwright suites in tests/typescript/e2e-<app>/
  • Task graph tags a project host:<host> for each apps/<host>/ folder name in its path
  • .NET build takes Rhino hosts from the rhino/ path folder
  • Grasshopper2 package references add Grasshopper 2 global usings
  • Installed Rhino supplies host assemblies at runtime, build output holds none
  • Project files are the language manifests and markers Nx plugins read, never project.json
  • Workspace.slnx lists every project .csproj
  • Swift modules are root Package.swift targets, each in its own folder under libs/swift/<group>/, executables under tools/
  • Projects hold no src/ directory
  • Schema libraries reconcile the live database to owning types, with no migration file or history table
  • Reconciles drop or retype only what owning types declare retired or retyped
Source 5 files
hooks/register.ts 38 lines
1import type { Register } from 'claude-code';
2import { none, some } from '../composition.ts';
3import { commandDecision, unrun, WORKTREE } from '../policies/policies.ts';
4
5// --- [COMPOSITION] ---------------------------------------------------------------------
6
7const register: Register = (on, options) => {
8    const project = String(options.project);
9    on('tool.call', { tool: 'EnterWorktree' }, () => ({ deny: `EnterWorktree ${WORKTREE}` }));
10    on('tool.call', { tool: 'Agent', isolation: 'worktree' }, () => ({ deny: `Agent with isolation worktree ${WORKTREE}` }));
11    on('tool.call', { tool: ['Bash', 'Monitor'] }, async ($, e, next) => {
12        if (e.command === undefined) {
13            return next(e);
14        }
15        const [repo, cwd, home] = await Promise.all([$.session.repo(), $.session.cwd(), $.env.get('HOME')]);
16        const decision = await commandDecision({ run: (argv, init) => $.process.run(argv, init), exists: (path) => $.fs.exists(path), plugin: $.plugin.root, root: repo === null ? none : some(repo.root), cwd, home: home === undefined ? none : some(home) }, e.command, project);
17        switch (decision.kind) {
18            case 'deny':
19                return { deny: decision.reason };
20            case 'allow':
21                return next(e);
22            default: {
23                const { command, notice } = decision;
24                const answer = await next({ ...e, command });
25                if (notice.kind === 'none' || answer.deny !== undefined) {
26                    return answer;
27                }
28                $.ui.toast(notice.value);
29                return { ...answer, context: [...(answer.context ?? []), notice.value] };
30            }
31        }
32    }).catch((_$, e, next) => (next.called ? next(e) : { deny: unrun(next.error.message ?? next.error.kind) }));
33};
34
35// --- [EXPORTS] -------------------------------------------------------------------------
36
37export { register };
38
composition.ts 28 lines
1// --- [TYPES] ---------------------------------------------------------------------------
2
3type Option<A> = { readonly kind: 'some'; readonly value: A } | { readonly kind: 'none' };
4type Fault = { readonly kind: 'exited'; readonly program: string; readonly code: number; readonly output: string } | { readonly kind: 'thrown'; readonly program: string; readonly cause: unknown };
5type Result<T> = { readonly kind: 'ok'; readonly value: T } | { readonly kind: 'fault'; readonly faults: readonly [Fault, ...Fault[]] };
6
7// --- [OPERATIONS] ----------------------------------------------------------------------
8
9// --- [CONSTRUCTORS]
10
11const none: Option<never> = { kind: 'none' };
12const some = <A>(value: A): Option<A> => ({ kind: 'some', value });
13const ok = <T>(value: T): Result<T> => ({ kind: 'ok', value });
14const fault = (...faults: readonly [Fault, ...Fault[]]): Result<never> => ({ kind: 'fault', faults });
15
16// --- [COMBINATORS]
17
18const map = <A, B>(result: Result<A>, f: (value: A) => B): Result<B> => (result.kind === 'ok' ? ok(f(result.value)) : result);
19const bind = <A, R extends Result<unknown> | Promise<Result<unknown>>>(result: Result<A>, f: (value: A) => R): R | Result<never> => (result.kind === 'ok' ? f(result.value) : result);
20const all = <T>(results: readonly Result<T>[]): Result<readonly T[]> => {
21    const [first, ...rest] = results.flatMap((result) => (result.kind === 'fault' ? result.faults : []));
22    return first === undefined ? ok(results.flatMap((result) => (result.kind === 'ok' ? [result.value] : []))) : fault(first, ...rest);
23};
24
25// --- [EXPORTS] -------------------------------------------------------------------------
26
27export { all, bind, type Fault, fault, map, none, type Option, ok, type Result, some };
28
policies/policies.ts 273 lines
1import { none, type Option, some } from '../composition.ts';
2import { parse, type Script } from './command.ts';
3import { declared, firstOperand, type Invocation, informational, invocations, operands, option, placed, waits, within } from './invocation.ts';
4
5// --- [TYPES] ---------------------------------------------------------------------------
6
7type Decision = { readonly kind: 'deny'; readonly reason: string } | { readonly kind: 'allow' } | { readonly kind: 'rewrite'; readonly command: string; readonly notice: Option<string> };
8
9interface System {
10    readonly run: (argv: Invocation, init: { readonly cwd: string; readonly stdin: string }) => Promise<{ readonly exitCode: number; readonly stdout: string; readonly stderr: string }>;
11    readonly exists: (path: string) => Promise<boolean>;
12    readonly plugin: string;
13    readonly root: Option<string>;
14    readonly cwd: string;
15    readonly home: Option<string>;
16}
17interface Call {
18    readonly system: System;
19    readonly script: Script;
20    readonly project: string;
21}
22
23// --- [CONSTANTS] -----------------------------------------------------------------------
24
25const WORKTREE = 'creates second checkout. Work in main checkout';
26const UNPLACED = 'runs after unresolved directory change. Run cd to named directory first';
27const ALIAS = 'defines alias that can hide refused subcommand';
28const OVERWRITES = 'overwrites working-tree files. Edit files';
29const BREAK = /(?<!\\)(?:\\\\)*\\n/u;
30const EXPANDS = /[$`]/u;
31const GLOB = /[*?[{]/u;
32const EXPRESSION = /^[-(!]/u;
33const NAMED = /[\p{L}\p{N}]/u;
34
35// --- [OPERATIONS] ----------------------------------------------------------------------
36
37// --- [DELETE]
38
39const deletes = ({ system: { root, home }, script: { commands }, project }: Call): readonly string[] => {
40    const finder = 'find -exec or fd -X';
41    const removing = (invocation: Invocation): readonly Invocation[] => {
42        if (invocation[0] !== 'git') {
43            return ['rm', 'rimraf', 'trash', 'unlink', 'shred'].includes(invocation[0]) ? [invocation] : [];
44        }
45        const [key, ...args] = invocation.slice(firstOperand(invocation, 1));
46        return key === 'rm' && !args.includes('--cached') ? [['rm', ...args]] : [];
47    };
48    const searched = (invocation: Invocation, cwd: Option<string>): { readonly roots: readonly string[]; readonly folder: Option<string>; readonly named: boolean } => {
49        const [program, ...args] = invocation;
50        if (program === 'find' || program === 'gfind') {
51            const tests = ['-name', '-iname', '-path', '-ipath', '-wholename', '-iwholename', '-regex', '-iregex'];
52            const end = args.findIndex((word) => EXPRESSION.test(word));
53            const roots = args.slice(0, end < 0 ? args.length : end);
54            return { roots: roots.length === 0 ? ['.'] : roots, folder: cwd, named: args.flatMap((word, at) => (tests.includes(word) ? args.slice(at + 1, at + 2) : [])).some((pattern) => NAMED.test(pattern)) };
55        }
56        const { leading, inputs, values } = operands(invocation);
57        const base = values.findLast(([name]) => name === '-C' || name === '--base-directory');
58        const given = values.flatMap(([name, value]) => (name === '--search-path' ? [value] : []));
59        return {
60            roots: [given, inputs].find((paths) => paths.length > 0) ?? ['.'],
61            folder: base === undefined ? cwd : placed(base[1], cwd, home),
62            named: [...leading, ...values.flatMap(([name, value]) => (name === '-e' || name === '--extension' ? [value] : []))].some((pattern) => NAMED.test(pattern)),
63        };
64    };
65    const anchored = (word: string, unbounded: boolean, cwd: Option<string>): Option<string> => {
66        const cut = unbounded ? word.search(GLOB) : -1;
67        return placed(cut < 0 ? word : word.slice(0, word.lastIndexOf('/', cut) + 1), cwd, home);
68    };
69    return commands.flatMap(({ words, invocations: chain, cwd }) => {
70        const last = chain.at(-1);
71        if (last === undefined) {
72            return [];
73        }
74        const [program] = last;
75        const loose = new Set(words.slice(words.length - last.length).flatMap(({ text, unbounded }) => (unbounded ? [text] : [])));
76        const judge =
77            (name: string, scope: (word: string) => string, start: Option<string>, selective: boolean) =>
78            (word: string): readonly string[] => {
79                if (loose.has(word) && EXPANDS.test(word)) {
80                    return [`${name} deletes ${word} expanded at run time. Name path or use ${finder}`];
81                }
82                const place = anchored(word, loose.has(word), start);
83                if (place.kind === 'none') {
84                    return [`${name} ${UNPLACED}`];
85                }
86                return root.kind === 'some' && !selective && within(root.value, place.value) ? [`${name} deletes ${scope(word)} at or above repository root. Name directory beneath root or run nx run ${project}:clean`] : [];
87            };
88        const { options, inner } = operands(last);
89        const [remover] = removing(last);
90        const [feeder] = chain.slice(0, -1).filter(([name]) => declared(name).stdin === 'always');
91        if (remover !== undefined) {
92            const name = program === 'git' ? 'git rm' : program;
93            return feeder === undefined ? operands(remover).inputs.flatMap(judge(name, String, cwd, false)) : [`${name} deletes paths ${feeder[0]} reads from standard input. Use ${finder}`];
94        }
95        if (!(options.includes('-delete') || invocations(inner).some((launched) => removing(launched).length > 0))) {
96            return [];
97        }
98        const { roots, folder, named } = searched(last, cwd);
99        return roots.flatMap(judge(program, (word) => `under ${word} with no name pattern`, folder, named));
100    });
101};
102
103// --- [GIT]
104
105const flagged = (args: readonly string[], reason: string, words: readonly string[], prefixes: readonly string[]): readonly string[] =>
106    args
107        .filter((word) => words.includes(word) || prefixes.some((prefix) => word.startsWith(prefix)))
108        .slice(0, 1)
109        .map((word) => `${word} ${reason}`);
110
111const GIT = new Map(
112    Object.entries<(args: readonly string[], present: (word: string) => boolean) => readonly string[]>({
113        branch: (args) => flagged(args, 'deletes or force-moves branch', ['-d', '-D', '-M', '--delete'], ['--force']),
114        checkout: (args, present) => {
115            const forced = flagged(args, 'discards local changes', ['-f', '-B', '-p', '--patch', '--ours', '--theirs'], ['--force']);
116            const [first, ...more] = args.filter((word) => word === '-' || !word.startsWith('-'));
117            const separated = args.includes('--');
118            const branching = !separated && args.some((word) => ['-b', '--orphan', '-t', '--track', '--detach'].includes(word));
119            const paths = separated || more.length > 0 || first === '.' || first?.startsWith(':') === true || (first !== undefined && first !== '-' && present(first));
120            return forced.length > 0 || branching || !paths ? forced : [`${args.join(' ')} ${OVERWRITES}`];
121        },
122        clean: () => ['deletes untracked files. Remove named files with rm'],
123        config: (args) => args.flatMap((word, at) => (word.startsWith('alias.') && args.slice(at + 1).some((value) => !value.startsWith('-')) ? [`${word} ${ALIAS}`] : [])).slice(0, 1),
124        push: (args) => flagged(args, 'rewrites or deletes remote history', ['-f', '-d', '--delete', '--mirror', '--prune'], ['--force', '+', ':']),
125        rebase: () => ['rewrites commits other agents can hold'],
126        reflog: (args) => flagged(args, 'erases reflog entries', ['delete', 'drop', 'expire'], []),
127        reset: (args, present) => {
128            const forced = flagged(args, 'discards working-tree or index state', ['--hard', '--merge', '--keep'], []);
129            const targets = args.filter((word) => !word.startsWith('-'));
130            const [target] = targets;
131            return forced.length > 0 || target === undefined || args.includes('--') || targets.some(present) ? forced : [`${target} moves HEAD and drops branch commits`];
132        },
133        restore: (args) => {
134            const { options } = operands(['git', ...args]);
135            return options.some((name) => name === '-S' || name === '--staged') && !options.some((name) => name === '-W' || name === '--worktree') ? [] : [OVERWRITES];
136        },
137        revert: () => ['reverses committed history'],
138        stash: ([first]) => (first === 'list' || first === 'show' ? [] : ['hides uncommitted work other agents depend on. Commit to branch']),
139        switch: (args) => flagged(args, 'discards local changes', ['-f', '-C', '--discard-changes'], ['--force']),
140        worktree: ([first]) => (first === 'list' ? [] : [WORKTREE]),
141    }),
142);
143
144const git = async ({ system: { exists, root, home }, script: { commands } }: Call): Promise<readonly string[]> => {
145    if (root.kind === 'none') {
146        return [];
147    }
148    const calls = commands.flatMap(({ invocations: chain, cwd }) =>
149        chain
150            .filter(([program]) => program === 'git')
151            .flatMap((invocation) => {
152                const index = firstOperand(invocation, 1);
153                const { values } = operands(['git', ...invocation.slice(1, index)]);
154                const moved = values.reduce((folder, [name, value]) => (name === '-C' ? placed(value, folder, home) : folder), cwd);
155                const [key, ...args] = invocation.slice(index);
156                return key === undefined || (moved.kind === 'some' && !within(moved.value, root.value)) ? [] : [{ values, key, args, moved }];
157            }),
158    );
159    const probed = calls.flatMap(({ args, moved }) => args.filter((word) => !word.startsWith('-')).map((word) => placed(word, moved, home))).flatMap((place) => (place.kind === 'some' ? [place.value] : []));
160    const found = new Set((await Promise.all(probed.map(async (path) => ((await exists(path)) ? [path] : [])))).flat());
161    return calls.flatMap(({ values, key, args, moved }) => {
162        const aliased = values.flatMap(([name, value]) => (value.startsWith('alias.') ? [`git ${name} ${value} ${ALIAS}`] : []));
163        const rule = GIT.get(key);
164        const judged =
165            rule === undefined
166                ? []
167                : [
168                      ...rule(args, (word) => {
169                          const place = placed(word, moved, home);
170                          return place.kind === 'some' && found.has(place.value);
171                      }),
172                      ...(moved.kind === 'none' ? rule(args, () => true) : []),
173                  ];
174        if (aliased.length > 0) {
175            return aliased;
176        }
177        if (moved.kind === 'none') {
178            return judged.length > 0 ? [`git ${key} ${UNPLACED}`] : [];
179        }
180        return judged.map((tail) => `git ${key} ${tail}`);
181    });
182};
183
184// --- [BACKGROUND]
185
186const detached = ({ script: { commands, background } }: Call): readonly string[] => (background && !commands.some(({ invocations: chain }) => chain.some(([program]) => program === 'wait')) ? ['Job started with & outlives call. Add wait or set run_in_background'] : []);
187
188// --- [STDIN]
189
190const stdin = ({ script: { commands } }: Call): readonly string[] => commands.flatMap(({ fed, words, invocations: chain }) => (!fed && chain.some(waits) ? [`${words.map(({ text }) => text).join(' ')} waits on unfed standard input. Pass file or pipe input`] : []));
191
192// --- [INLINE]
193
194const inline = ({ script: { commands } }: Call): readonly string[] =>
195    commands.flatMap(({ fed, invocations: chain }) =>
196        chain.flatMap((invocation) => {
197            const [program] = invocation;
198            const { code } = declared(program);
199            return code !== undefined && (operands(invocation).options.some((name) => code.includes(name)) || (fed && waits(invocation))) ? [`${program} runs inline program. Edit with Edit or sd, run installed tools by name`] : [];
200        }),
201    );
202
203// --- [DECISION]
204
205const unrun = (detail: string): string => `function-hooks policy did not run. ${detail}`;
206
207const without = (program: string, words: Script['commands'][number]['words'], dropped: readonly string[]) => {
208    const stop = words.findIndex(({ text }) => text === '--');
209    return words.slice(0, stop < 0 ? words.length : stop).flatMap(({ text, span }) => {
210        const { names, joined } = text.startsWith('-') ? option(declared(program), text) : { names: [], joined: [] };
211        const kept = names.filter((name) => !dropped.includes(name));
212        if (kept.length === names.length) {
213            return [];
214        }
215        return kept.length === 0 ? [{ start: span.start - 1, end: span.end, text: '', notice: none }] : [{ start: span.start, end: span.end, text: `-${kept.map((name) => name.slice(1)).join('')}${joined.join('')}`, notice: none }];
216    });
217};
218
219const commandDecision = async (system: System, command: string, project: string): Promise<Decision> => {
220    const parsed = await parse(system, command);
221    if (parsed.kind === 'fault') {
222        return { kind: 'deny', reason: `Command not parsed. ${parsed.faults.map((value) => (value.kind === 'exited' ? [`${value.program} exited ${value.code}`, value.output].filter((part) => part !== '').join('. ') : `${value.program} failed. ${String(value.cause)}`)).join('. ')}` };
223    }
224    const call = { system, script: parsed.value, project };
225    const reasons = new Set((await Promise.all([deletes, git, stdin, inline, detached].map((policy) => policy(call)))).flat());
226    if (reasons.size > 0) {
227        return { kind: 'deny', reason: [...reasons].join('. ') };
228    }
229    const changes = parsed.value.commands
230        .filter(({ nested }) => !nested)
231        .flatMap(({ words, invocations: chain }) => chain.slice(-1).flatMap((last) => words.slice(words.length - last.length, words.length - last.length + 1).map(({ span }) => ({ last, span, rest: words.slice(words.length - last.length + 1) }))))
232        .flatMap(({ last, span: { start, end }, rest }) => {
233            const [program] = last;
234            const { options, leading } = operands(last);
235            const given = (names: readonly string[]): boolean => informational(program, options) || names.some((name) => options.includes(name));
236            switch (program) {
237                case 'fd':
238                    return given(['-H', '--hidden', '--no-hidden', '-u', '--unrestricted']) ? [] : [{ start: end, end, text: ' --hidden', notice: none }];
239                case 'rg':
240                    return given(['-.', '--hidden', '--no-hidden', '-u', '--unrestricted', '--no-config']) ? [] : [{ start: end, end, text: ' --hidden', notice: none }];
241                case 'sd': {
242                    const [find] = leading;
243                    const breaks = find !== undefined && (find.includes('\n') || (!given(['-F', '--fixed-strings']) && BREAK.test(find)));
244                    return breaks && !given(['-A', '--across']) ? [{ start: end, end, text: ' -A', notice: none }] : [];
245                }
246                case 'tree':
247                    return without(program, rest, ['-a', '--all']);
248                case 'refurb': {
249                    const text = 'python -m tools.refurb';
250                    return [{ start, end, text, notice: some(`refurb ran as ${text} over mypy cache`) }];
251                }
252                default:
253                    return [];
254            }
255        });
256    if (changes.length === 0) {
257        return { kind: 'allow' };
258    }
259    const bytes = new TextEncoder().encode(command);
260    const decoder = new TextDecoder();
261    const sorted = changes.toSorted((left, right) => left.start - right.start);
262    const notices = [...new Set(changes.flatMap(({ notice }) => (notice.kind === 'some' ? [notice.value] : [])))];
263    return {
264        kind: 'rewrite',
265        command: [...sorted.map(({ start, text }, index) => `${decoder.decode(bytes.subarray(sorted[index - 1]?.end, start))}${text}`), decoder.decode(bytes.subarray(sorted.at(-1)?.end))].join(''),
266        notice: notices.length === 0 ? none : some(notices.join('. ')),
267    };
268};
269
270// --- [EXPORTS] -------------------------------------------------------------------------
271
272export { commandDecision, type System, unrun, WORKTREE };
273
policies/command.ts 173 lines
1import { all, bind, fault, map, none, type Option, ok, type Result } from '../composition.ts';
2import { declared, type Invocation, invocations, operands, placed, unquoted, waits } from './invocation.ts';
3import type { System } from './policies.ts';
4
5// --- [TYPES] ---------------------------------------------------------------------------
6
7interface Span {
8    readonly start: number;
9    readonly end: number;
10}
11interface Command {
12    readonly words: readonly { readonly text: string; readonly span: Span; readonly unbounded: boolean }[];
13    readonly invocations: readonly Invocation[];
14    readonly cwd: Option<string>;
15    readonly fed: boolean;
16    readonly nested: boolean;
17}
18interface Script {
19    readonly commands: readonly Command[];
20    readonly background: boolean;
21}
22interface Capture {
23    readonly text: string;
24    readonly range: { readonly byteOffset: Span };
25}
26
27type Hit = Capture &
28    (
29        | { readonly ruleId: 'command'; readonly metaVariables: { readonly single: { readonly CMD: Capture; readonly SCOPE?: Capture }; readonly multi: { readonly ARGS?: readonly Capture[] } } }
30        | { readonly ruleId: 'operand' | 'heredoc' | 'herestring'; readonly metaVariables: { readonly single: { readonly BODY: Capture } } }
31        | { readonly ruleId: 'fed' | 'unbounded' | 'background' }
32    );
33
34// --- [CONSTANTS] -----------------------------------------------------------------------
35
36const WORD = /^(?!\d*[<>]|&>)./su;
37const STACK = /^(?:-|[+-]\d+)$/u;
38
39// --- [OPERATIONS] ----------------------------------------------------------------------
40
41const parse = async (system: System, command: string): Promise<Result<Script>> => {
42    const exited = (argv: Invocation, stdin: string): Promise<Result<string>> =>
43        system.run(argv, { cwd: system.plugin, stdin }).then(
44            ({ exitCode, stdout, stderr }) => (exitCode === 0 ? ok(stdout) : fault({ kind: 'exited', program: argv[0], code: exitCode, output: stderr.trim() })),
45            (cause: unknown) => fault({ kind: 'thrown', program: argv[0], cause }),
46        );
47    const scripted = async (scan: Invocation, source: string, context: Pick<Command, 'cwd' | 'fed' | 'nested'>): Promise<Result<Script>> =>
48        bind(
49            bind(await exited(scan, source), (printed): Result<readonly Hit[]> => {
50                try {
51                    return ok(JSON.parse(printed));
52                } catch (cause) {
53                    return fault({ kind: 'thrown', program: scan[0], cause });
54                }
55            }),
56            async (hits) => {
57                const sorted = hits.toSorted((left, right) => left.range.byteOffset.start - right.range.byteOffset.start);
58                const inside = (outer: Capture | undefined, { range: { byteOffset } }: Capture): boolean => outer === undefined || (byteOffset.start >= outer.range.byteOffset.start && byteOffset.end <= outer.range.byteOffset.end);
59                const unbounded = new Set(sorted.flatMap((hit) => (hit.ruleId === 'unbounded' ? [hit.range.byteOffset.start] : [])));
60                const owned = Map.groupBy(sorted, (hit) => (hit.ruleId === 'operand' || hit.ruleId === 'heredoc' || hit.ruleId === 'herestring' ? hit.metaVariables.single.BODY : hit).range.byteOffset.start)
61                    .values()
62                    .flatMap((own) => {
63                        const hit = own.find((other) => other.ruleId === 'command');
64                        if (hit === undefined) {
65                            return [];
66                        }
67                        const words = [hit.metaVariables.single.CMD, ...(hit.metaVariables.multi.ARGS ?? []), ...own.filter((other) => other.ruleId === 'operand')]
68                            .filter(({ text }) => WORD.test(text))
69                            .map(({ text, range: { byteOffset } }) => ({ text: unquoted(text), span: byteOffset, unbounded: unbounded.has(byteOffset.start) }));
70                        const chain = invocations(words.map(({ text }) => text));
71                        return [
72                            {
73                                hit,
74                                words,
75                                invocations: chain,
76                                stdin: own
77                                    .filter((other) => other.ruleId === 'heredoc' || other.ruleId === 'herestring')
78                                    .slice(-1)
79                                    .map((given) => (given.ruleId === 'herestring' ? unquoted(given.text) : given.text)),
80                                targets: chain
81                                    .filter(([program]) => declared(program).chdir !== undefined)
82                                    .slice(0, 1)
83                                    .map((mover) => [...operands(mover).inputs, ...(declared(mover[0]).chdir ?? [])][0]),
84                                fed: context.fed || own.some((other) => other.ruleId === 'fed'),
85                                nested: context.nested,
86                            },
87                        ];
88                    })
89                    .toArray();
90                const located = owned.map((part) => ({
91                    ...part,
92                    cwd: owned
93                        .filter(({ hit }) => hit.range.byteOffset.end <= part.hit.range.byteOffset.start && inside(hit.metaVariables.single.SCOPE, part.hit))
94                        .flatMap(({ targets }) => targets)
95                        .reduce((folder, target) => (target === undefined || STACK.test(target) ? none : placed(target, folder, system.home)), context.cwd),
96                }));
97                const inner = all(
98                    await Promise.all(
99                        located.flatMap(({ invocations: chain, stdin, cwd, fed }) => {
100                            const last = chain.slice(-1);
101                            return [...last, ...last.flatMap((invocation) => invocations(operands(invocation).inner))]
102                                .flatMap((invocation) => [...operands(invocation).bodies, ...(declared(invocation[0]).shell !== undefined && waits(invocation) ? stdin : [])])
103                                .map((body) => scripted(scan, body, { cwd, fed, nested: true }));
104                        }),
105                    ),
106                );
107                return map(inner, (scripts) => ({
108                    commands: [...located.map(({ hit, stdin, targets, ...parsed }) => parsed), ...scripts.flatMap(({ commands }) => commands)],
109                    background: sorted.some(({ ruleId }) => ruleId === 'background') || scripts.some(({ background }) => background),
110                }));
111            },
112        );
113    const value = 'word, string, raw_string, concatenation, simple_expansion, expansion, command_substitution, number';
114    const owner = {
115        owner: { any: [{ inside: { kind: 'command', pattern: '$BODY' } }, { inside: { kind: 'heredoc_redirect', inside: { kind: 'redirected_statement', matches: 'statement' } } }, { inside: { kind: 'redirected_statement', matches: 'statement' } }] },
116        statement: { has: { field: 'body', matches: 'last' } },
117        last: {
118            any: [
119                { kind: 'command', pattern: '$BODY' },
120                { kind: 'list, pipeline, negated_command', has: { matches: 'last', nthChild: { position: 1, reverse: true } } },
121            ],
122        },
123    };
124    const scope = {
125        scope: { kind: 'program, subshell, command_substitution, process_substitution, pipeline' },
126        scoped: { any: [{ inside: { stopBy: { matches: 'scope' }, kind: 'program' } }, { inside: { stopBy: { matches: 'scope' }, matches: 'scope', not: { kind: 'program' }, pattern: '$SCOPE' } }] },
127    };
128    const scanner = [
129        'scan',
130        '--stdin',
131        '--config',
132        '/dev/null',
133        '--json=compact',
134        '--inline-rules',
135        [
136            { id: 'command', utils: scope, rule: { kind: 'command', any: [{ pattern: '$CMD $$$ARGS' }, { pattern: '$CMD' }], matches: 'scoped' } },
137            { id: 'operand', utils: owner, rule: { kind: value, follows: { kind: value }, inside: { kind: 'file_redirect', matches: 'owner' } } },
138            { id: 'heredoc', utils: owner, rule: { kind: 'heredoc_body', inside: { kind: 'heredoc_redirect', matches: 'owner' } } },
139            { id: 'herestring', utils: owner, rule: { kind: value, inside: { kind: 'herestring_redirect', matches: 'owner' } } },
140            {
141                id: 'fed',
142                utils: {
143                    input: { any: [{ kind: 'heredoc_redirect' }, { kind: 'herestring_redirect' }, { kind: 'file_redirect', regex: '^0?<' }] },
144                    tail: { any: [{ inside: { kind: 'redirected_statement', field: 'body', has: { matches: 'input' } } }, { nthChild: { position: 1, reverse: true }, inside: { kind: 'list, pipeline, negated_command', matches: 'tail' } }] },
145                    stage: { any: [{ matches: 'tail' }, { inside: { kind: 'pipeline' }, not: { nthChild: 1 } }, { inside: { kind: 'pipeline', inside: { kind: 'heredoc_redirect' } } }] },
146                },
147                rule: { kind: 'command', any: [{ has: { matches: 'input' } }, { matches: 'stage' }, { inside: { stopBy: 'end', not: { kind: 'list, pipeline, negated_command' }, matches: 'stage' } }] },
148            },
149            { id: 'background', rule: { pattern: '&' } },
150            {
151                id: 'unbounded',
152                rule: {
153                    inside: { kind: 'command' },
154                    any: [
155                        { kind: 'simple_expansion, expansion, command_substitution, process_substitution, arithmetic_expansion' },
156                        { kind: 'string, concatenation', has: { stopBy: 'end', kind: 'simple_expansion, expansion, command_substitution, arithmetic_expansion' } },
157                        { kind: 'word', regex: String.raw`[*?\[{]` },
158                        { kind: 'concatenation', has: { kind: 'word', regex: String.raw`[*?\[{]` } },
159                        { kind: 'word, string, raw_string', regex: String.raw`^["']?(?:~[^/"']*|\.{1,2}|\*+|\.\*)?(?:/+(?:\.{1,2}|\*+|\.\*)?)*["']?$` },
160                    ],
161                },
162            },
163        ]
164            .map((rule) => JSON.stringify({ language: 'bash', ...rule }))
165            .join('\n---\n'),
166    ] as const;
167    return bind(await exited(['mise', 'which', 'ast-grep'], ''), (path) => scripted([path.trim(), ...scanner], command, { cwd: placed(system.cwd, none, none), fed: false, nested: false }));
168};
169
170// --- [EXPORTS] -------------------------------------------------------------------------
171
172export { parse, type Script };
173
policies/invocation.ts 486 lines
1import { none, type Option, some } from '../composition.ts';
2
3// --- [TYPES] ---------------------------------------------------------------------------
4
5type Invocation = readonly [string, ...string[]];
6
7interface Program {
8    readonly valued?: readonly string[];
9    readonly arities?: Readonly<Record<string, number>>;
10    readonly bodies?: readonly string[];
11    readonly leading?: number;
12    readonly leadingOptions?: readonly string[];
13    readonly stdin?: 'default' | 'always';
14    readonly stdinless?: readonly string[];
15    readonly code?: readonly string[];
16    readonly shell?: readonly string[] | 'joined';
17    readonly chdir?: readonly string[];
18    readonly informational?: readonly string[];
19    readonly wholeWords?: true;
20    readonly runs?: readonly (readonly string[])[] | '--';
21    readonly execs?: readonly string[];
22}
23interface Operands {
24    readonly inputs: readonly string[];
25    readonly options: readonly string[];
26    readonly values: readonly (readonly [name: string, value: string])[];
27    readonly inner: readonly string[];
28}
29
30// --- [CONSTANTS] -----------------------------------------------------------------------
31
32const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/u;
33const TILDE = /^~(?<user>[^/]*)/u;
34const PYTHON: Program = { valued: ['-W', '-X'], stdin: 'default', stdinless: ['-m'], code: ['-c'], informational: ['-V'] };
35const SHELL: Program = { valued: ['-o', '-O'], stdin: 'default', shell: ['-c'] };
36const FD: Program = {
37    valued: [
38        '-e',
39        '--extension',
40        '-t',
41        '--type',
42        '-E',
43        '--exclude',
44        '-d',
45        '--max-depth',
46        '--min-depth',
47        '--exact-depth',
48        '-S',
49        '--size',
50        '--changed-within',
51        '--changed-before',
52        '-o',
53        '--owner',
54        '-C',
55        '--base-directory',
56        '--search-path',
57        '-j',
58        '--threads',
59        '--max-results',
60        '-c',
61        '--color',
62        '--format',
63        '--path-separator',
64        '--ignore-file',
65        '--ignore-contain',
66        '--and',
67        '--batch-size',
68    ],
69    leading: 1,
70    informational: ['-h', '-V'],
71    execs: ['-x', '-X', '--exec', '--exec-batch'],
72};
73const FIND: Program = { wholeWords: true, execs: ['-exec', '-execdir', '-ok', '-okdir'] };
74const SQL: Program = {
75    valued: ['-cmd', '-init', '-newline', '-nullvalue', '-separator', '-storage-version'],
76    leading: 1,
77    stdin: 'default',
78    stdinless: ['-c', '-s', '-f', '-no-stdin'],
79    informational: ['-h', '-help', '-version'],
80    wholeWords: true,
81};
82const PROGRAMS: ReadonlyMap<string, Program> = new Map(
83    Object.entries({
84        sudo: {
85            valued: ['-C', '-D', '-g', '-h', '-p', '-R', '-T', '-U', '-u', '--close-from', '--chdir', '--group', '--host', '--prompt', '--chroot', '--command-timeout', '--other-user', '--user'],
86            runs: [[]],
87        },
88        doas: { valued: ['-C', '-u'], runs: [[]] },
89        env: { valued: ['-C', '-P', '-S', '-u'], runs: [[]] },
90        command: { runs: [[]] },
91        exec: { valued: ['-a'], runs: [[]] },
92        nice: { valued: ['-n'], runs: [[]] },
93        nohup: { runs: [[]] },
94        setsid: { runs: [[]] },
95        stdbuf: { valued: ['-e', '-i', '-o'], runs: [[]] },
96        timeout: { valued: ['-k', '-s', '--kill-after', '--signal'], leading: 1, runs: [[]] },
97        time: { valued: ['-o'], runs: [[]] },
98        xargs: { valued: ['-E', '-I', '-J', '-L', '-n', '-P', '-R', '-S', '-s'], stdin: 'always', runs: [[]] },
99        caffeinate: { valued: ['-t', '-w'], runs: [[]] },
100        arch: { valued: ['-arch', '-d'], runs: [[]] },
101        xcrun: { valued: ['--sdk', '--toolchain'], runs: [[]] },
102        lockf: { valued: ['-t'], leading: 1, runs: [[]] },
103        npx: { runs: [[]] },
104        npm: { runs: [['exec'], ['x']] },
105        pnpm: { runs: [[], ['exec'], ['dlx']] },
106        uv: {
107            valued: [
108                '--extra',
109                '--no-extra',
110                '--group',
111                '--no-group',
112                '--only-group',
113                '--no-editable-package',
114                '--env-file',
115                '-w',
116                '--with',
117                '--with-editable',
118                '--with-requirements',
119                '--package',
120                '--python-platform',
121                '--from',
122                '-c',
123                '--constraints',
124                '-b',
125                '--build-constraints',
126                '--overrides',
127                '--torch-backend',
128                '--bump',
129                '--output-format',
130                '--index',
131                '--default-index',
132                '-i',
133                '--index-url',
134                '--extra-index-url',
135                '-f',
136                '--find-links',
137                '--index-strategy',
138                '--keyring-provider',
139                '-P',
140                '--upgrade-package',
141                '--upgrade-group',
142                '--resolution',
143                '--prerelease',
144                '--prerelease-package',
145                '--fork-strategy',
146                '--exclude-newer',
147                '--exclude-newer-package',
148                '--no-sources-package',
149                '--reinstall-package',
150                '--link-mode',
151                '-C',
152                '--config-setting',
153                '--config-settings-package',
154                '--no-build-isolation-package',
155                '--no-build-package',
156                '--no-binary-package',
157                '--cache-dir',
158                '--refresh-package',
159                '-p',
160                '--python',
161                '--color',
162                '--allow-insecure-host',
163                '--directory',
164                '--project',
165                '--config-file',
166            ],
167            runs: [['run'], ['tool', 'run']],
168        },
169        poetry: { runs: [['run']] },
170        hatch: { runs: [['run']] },
171        mise: { runs: '--' },
172        doppler: { runs: '--' },
173        op: { runs: '--' },
174        hyperfine: {
175            valued: [
176                '-w',
177                '--warmup',
178                '-m',
179                '--min-runs',
180                '-M',
181                '--max-runs',
182                '-r',
183                '--runs',
184                '--reference-name',
185                '-D',
186                '--parameter-step-size',
187                '-S',
188                '--shell',
189                '--style',
190                '--sort',
191                '-u',
192                '--time-unit',
193                '--export-asciidoc',
194                '--export-csv',
195                '--export-json',
196                '--export-markdown',
197                '--export-orgmode',
198                '--output',
199                '--input',
200                '-n',
201                '--command-name',
202            ],
203            arities: { '-P': 3, '--parameter-scan': 3, '-L': 2, '--parameter-list': 2 },
204            bodies: ['-s', '--setup', '--reference', '-p', '--prepare', '-C', '--conclude', '-c', '--cleanup'],
205        },
206        fd: FD,
207        fdfind: FD,
208        find: FIND,
209        gfind: FIND,
210        tree: { valued: ['-L', '--level', '-I', '--ignore-glob', '-s', '--sort', '-t', '--time', '-w', '--width'] },
211        git: { valued: ['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--config-env', '--exec-path'] },
212        grep: {
213            valued: [
214                '-A',
215                '--after-context',
216                '-B',
217                '--before-context',
218                '-C',
219                '--context',
220                '-d',
221                '--directories',
222                '-D',
223                '--devices',
224                '-e',
225                '--regexp',
226                '-f',
227                '--file',
228                '-g',
229                '--glob',
230                '--iglob',
231                '-J',
232                '--jobs',
233                '-M',
234                '--file-magic',
235                '-m',
236                '--max-count',
237                '-N',
238                '--neg-regexp',
239                '-O',
240                '--file-extension',
241                '-t',
242                '--file-type',
243                '--include',
244                '--exclude',
245                '--include-dir',
246                '--exclude-dir',
247                '--include-from',
248                '--exclude-from',
249                '--label',
250                '--binary-files',
251                '--color',
252                '--colour',
253                '--colors',
254                '--colours',
255                '--encoding',
256                '--format',
257                '--replace',
258                '--from',
259                '--config',
260            ],
261            leading: 1,
262            leadingOptions: ['-e', '--regexp', '-f', '--file', '-N', '--neg-regexp'],
263            stdin: 'default',
264            stdinless: ['-r', '-R', '--recursive', '--dereference-recursive'],
265        },
266        rg: {
267            valued: [
268                '-e',
269                '--regexp',
270                '-f',
271                '--file',
272                '--pre',
273                '--pre-glob',
274                '--dfa-size-limit',
275                '-E',
276                '--encoding',
277                '--engine',
278                '-m',
279                '--max-count',
280                '--regex-size-limit',
281                '-j',
282                '--threads',
283                '-g',
284                '--glob',
285                '--iglob',
286                '--ignore-file',
287                '-d',
288                '--max-depth',
289                '--max-filesize',
290                '-t',
291                '--type',
292                '-T',
293                '--type-not',
294                '--type-add',
295                '--type-clear',
296                '-A',
297                '--after-context',
298                '-B',
299                '--before-context',
300                '--color',
301                '--colors',
302                '-C',
303                '--context',
304                '--context-separator',
305                '--field-context-separator',
306                '--field-match-separator',
307                '--hostname-bin',
308                '--hyperlink-format',
309                '-M',
310                '--max-columns',
311                '--path-separator',
312                '-r',
313                '--replace',
314                '--sort',
315                '--sortr',
316                '--generate',
317            ],
318            leading: 1,
319            leadingOptions: ['-e', '--regexp', '-f', '--file', '--files', '--type-list', '--generate'],
320            informational: ['-h', '-V'],
321        },
322        cat: { stdin: 'default' },
323        wc: { stdin: 'default' },
324        head: { valued: ['-n', '-c'], stdin: 'default' },
325        tail: { valued: ['-b', '-c', '-n'], stdin: 'default' },
326        sort: { valued: ['-k', '-t', '-o', '-S', '-T', '--batch-size', '--parallel', '--random-source', '--compress-program'], stdin: 'default', stdinless: ['--files0-from'] },
327        uniq: { valued: ['-f', '-s'], stdin: 'default' },
328        cut: { valued: ['-b', '-c', '-f', '-d'], stdin: 'default' },
329        shasum: { valued: ['-a'], stdin: 'default' },
330        md5: { valued: ['-s'], stdin: 'default', stdinless: ['-s'] },
331        tr: { stdin: 'always' },
332        tee: { stdin: 'always' },
333        pbcopy: { stdin: 'always' },
334        read: { stdin: 'always', stdinless: ['-u'] },
335        base64: { valued: ['-b', '-i', '-o', '--break', '--input', '--output'], stdin: 'always', stdinless: ['-i', '--input'] },
336        sed: { valued: ['-e', '-f'], leading: 1, leadingOptions: ['-e', '-f', '--expression', '--file'], stdin: 'default' },
337        awk: { valued: ['-F', '-v', '-f'], leading: 1, leadingOptions: ['-f'], stdin: 'default' },
338        jq: { valued: ['-L', '--library-path', '--indent'], arities: { '--arg': 2, '--argjson': 2, '--slurpfile': 2, '--rawfile': 2 }, leading: 1, stdin: 'default', stdinless: ['-n', '--null-input'] },
339        yq: { valued: ['-o', '-p', '-I', '--output-format', '--input-format', '--indent', '--from-file'], leading: 1, leadingOptions: ['--from-file'], stdin: 'default', stdinless: ['-n', '--null-input'] },
340        sd: {
341            valued: ['-f', '-n', '--flags', '--max-replacements'],
342            leading: 2,
343            stdin: 'default',
344            informational: ['-h', '-V'],
345        },
346        node: { stdin: 'default', stdinless: ['--test', '--run'], code: ['-e', '-p', '--eval', '--print'], informational: ['-v'] },
347        perl: { valued: ['-I'], stdin: 'default', code: ['-e', '-E'], informational: ['-v', '-V', '-h'] },
348        ruby: { valued: ['-I', '-r', '-C', '-E'], stdin: 'default', code: ['-e'], informational: ['-v', '-h', '--copyright'] },
349        eval: { shell: 'joined' },
350        cd: { chdir: ['~'] },
351        pushd: { chdir: [] },
352        popd: { chdir: [] },
353        python: PYTHON,
354        python3: PYTHON,
355        bash: SHELL,
356        sh: SHELL,
357        zsh: SHELL,
358        dash: SHELL,
359        ksh: SHELL,
360        sqlite3: SQL,
361        duckdb: SQL,
362    } satisfies Record<string, Program>),
363);
364
365// --- [OPERATIONS] ----------------------------------------------------------------------
366
367// --- [OPTIONS]
368
369const declared = (program: string): Program => PROGRAMS.get(program) ?? {};
370
371const option = (row: Program, word: string) => {
372    const arity = (name: string): number => row.arities?.[name] ?? ([row.valued, row.bodies, row.code].some((listed) => listed?.includes(name) === true) ? 1 : 0);
373    const cut = word.indexOf('=');
374    const given = cut < 0 ? word : word.slice(0, cut);
375    const head = row.wholeWords === true && given.startsWith('--') ? given.slice(1) : given;
376    if (head.startsWith('--') || row.wholeWords === true || arity(head) > 0) {
377        return { names: [head], taken: cut < 0 ? arity(head) : 0, joined: cut < 0 ? [] : [word.slice(cut + 1)] };
378    }
379    const [, ...letters] = [...word];
380    const names = letters.map((letter) => `-${letter}`);
381    const arities = names.map(arity);
382    const at = arities.findIndex((count) => count > 0);
383    const attached = at < 0 ? '' : letters.slice(at + 1).join('');
384    const [taken = 0] = attached === '' ? arities.slice(at) : [];
385    return { names: at < 0 ? names : names.slice(0, at + 1), taken, joined: attached === '' ? [] : [attached] };
386};
387
388const firstOperand = (invocation: Invocation, index: number): number => {
389    const [program] = invocation;
390    const word = invocation[index];
391    return word === undefined || word === '-' || word === '--' || !word.startsWith('-') ? index : firstOperand(invocation, index + 1 + option(declared(program), word).taken);
392};
393
394const separated = (row: Program, [head, ...rest]: readonly string[]): Operands => {
395    if (head === undefined || head === '--') {
396        return { inputs: rest, options: [], values: [], inner: [] };
397    }
398    if (head === '-' || !head.startsWith('-')) {
399        const tail = separated(row, rest);
400        return { ...tail, inputs: [head, ...tail.inputs] };
401    }
402    const { names, taken, joined } = option(row, head);
403    const launches = names.some((name) => row.execs?.includes(name) === true);
404    const end = rest.findIndex((word) => word === ';' || word === '+');
405    const launched = launches ? rest.slice(0, end < 0 ? rest.length : end) : [];
406    const tail = separated(row, rest.slice(launches ? launched.length + 1 : taken));
407    return {
408        inputs: tail.inputs,
409        options: [...names, ...tail.options],
410        values: [...names.slice(-1).flatMap((name) => [...joined, ...rest.slice(0, taken)].map((value) => [name, value] as const)), ...tail.values],
411        inner: launches ? launched : tail.inner,
412    };
413};
414
415const operands = ([program, ...args]: Invocation) => {
416    const row = declared(program);
417    const { inputs: all, ...split } = separated(row, args);
418    const count = split.options.some((name) => row.leadingOptions?.includes(name) === true) ? 0 : (row.leading ?? 0);
419    const inputs = all.slice(count);
420    return {
421        ...split,
422        leading: all.slice(0, count),
423        inputs,
424        bodies: [...(row.shell === 'joined' ? [args.join(' ')] : inputs.slice(0, Number(split.options.some((name) => row.shell?.includes(name) === true)))), ...(row.bodies === undefined ? [] : inputs), ...split.values.filter(([name]) => row.bodies?.includes(name) === true).map(([, value]) => value)],
425    };
426};
427
428// --- [STDIN]
429
430const informational = (program: string, options: readonly string[]): boolean => options.some((name) => name === '--help' || name === '--version' || declared(program).informational?.includes(name) === true);
431
432const waits = (invocation: Invocation): boolean => {
433    const [program] = invocation;
434    const { stdin, stdinless = [], code = [] } = declared(program);
435    const { inputs, options } = operands(invocation);
436    return stdin !== undefined && !informational(program, options) && !options.some((name) => [...stdinless, ...code].includes(name)) && (stdin === 'always' || inputs.length === 0 || inputs.includes('-'));
437};
438
439// --- [INVOCATIONS]
440
441const placed = (word: string, cwd: Option<string>, home: Option<string>): Option<string> => {
442    const expanded = home.kind === 'none' ? word : word.replace(TILDE, (_match, user: string) => (user === '' ? home.value : `${home.value.slice(0, home.value.lastIndexOf('/'))}/${user}`));
443    const absolute = cwd.kind === 'some' && !expanded.startsWith('/') ? `${cwd.value}/${expanded}` : expanded;
444    return absolute.startsWith('/')
445        ? some(
446              `/${absolute
447                  .split('/')
448                  .filter((part) => part !== '' && part !== '.')
449                  .reduce<readonly string[]>((kept, part) => (part === '..' ? kept.slice(0, -1) : kept.concat(part)), [])
450                  .join('/')}`,
451          )
452        : none;
453};
454
455const within = (path: string, folder: string): boolean => path === folder || path.startsWith(folder === '/' ? '/' : `${folder}/`);
456
457const unquoted = (word: string): string => word.replace(/(?:\$?(?<quote>["'])|\\)(?<body>(?<=')[^']*|(?<=")(?:[^"\\]|\\.)*|(?<=\\)[\s\S])\k<quote>/gu, (_match, quote: string | undefined, body: string) => (quote === '"' ? body.replace(/\\(?<char>["\\$`\n])/gu, '$<char>') : body));
458
459const invocations = ([head, ...rest]: readonly string[]): readonly Invocation[] => {
460    if (head === undefined) {
461        return [];
462    }
463    if (ASSIGNMENT.test(head)) {
464        return invocations(rest);
465    }
466    const program = head.slice(head.lastIndexOf('/') + 1);
467    const row = declared(program);
468    const wrapped = (words: readonly string[], pending: readonly (readonly string[])[]): readonly string[] => {
469        const [first, ...more] = words;
470        const deeper = pending.flatMap(([step, ...steps]) => (step !== undefined && step === first ? [steps] : []));
471        if (first?.startsWith('-') === true) {
472            return wrapped(more.slice(option(row, first).taken), pending);
473        }
474        if (deeper.length > 0) {
475            return wrapped(more, deeper);
476        }
477        return pending.some((path) => path.length === 0) ? words.slice(row.leading ?? 0) : [];
478    };
479    const inner = row.runs === '--' ? rest.slice(rest.includes('--') ? rest.indexOf('--') + 1 : rest.length) : wrapped(rest, row.runs ?? []);
480    return [[program, ...rest.slice(0, rest.length - inner.length)], ...invocations(inner)];
481};
482
483// --- [EXPORTS] -------------------------------------------------------------------------
484
485export { declared, firstOperand, type Invocation, informational, invocations, operands, option, placed, unquoted, waits, within };
486