docks-kit 0.22.20 → 0.22.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.
- package/AGENTS.md +5 -5
- package/cli/docs/command-guards.md +5 -4
- package/cli/docs/omp-context.md +13 -9
- package/cli/docs/omp-models.md +90 -69
- package/cli/src/commands/omp.ts +25 -73
- package/cli/src/engine-native/harnesses.ts +5 -11
- package/cli/src/engine-native/kitDb.ts +7 -7
- package/cli/src/engine-native/ompOverlay.ts +23 -69
- package/cli/src/engine-native/ompRemovals.ts +47 -8
- package/cli/src/engine-native/sharedTypes.d.ts +0 -2
- package/cli/src/generated/sotPayload.ts +5 -5
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Generated by cli/scripts/generate-sot-payload.ts. DO NOT EDIT.
|
|
2
2
|
// Edit SoT/, notification.mp3, or package.json, then run: bun cli/scripts/generate-sot-payload.ts
|
|
3
3
|
|
|
4
|
-
export const GENERATED_PACKAGE_VERSION = "0.22.
|
|
4
|
+
export const GENERATED_PACKAGE_VERSION = "0.22.23"
|
|
5
5
|
|
|
6
6
|
export const GENERATED_PAYLOAD_TEXT = {
|
|
7
7
|
"SoT/.agents/skills.txt": "# Universal AI-agent skill manifest intentionally empty.\n# Global skill discovery is opt-in: add one slug per installed skill: <owner>/<repo>@<skill-name> (or a path to one skill directory).\n# EngineNative ignores comments and blank lines.\n",
|
|
@@ -18,14 +18,14 @@ export const GENERATED_PAYLOAD_TEXT = {
|
|
|
18
18
|
"SoT/.codex/plugins/marketplace.json": "{\n \"name\": \"docks\",\n \"interface\": {\n \"displayName\": \"DocksDocks\"\n },\n \"plugins\": [\n {\n \"name\": \"docks\",\n \"source\": {\n \"source\": \"git-subdir\",\n \"url\": \"https://github.com/DocksDocks/docks.git\",\n \"path\": \"./plugins/docks\",\n \"ref\": \"main\"\n },\n \"policy\": {\n \"installation\": \"AVAILABLE\",\n \"authentication\": \"ON_INSTALL\"\n },\n \"category\": \"Productivity\"\n },\n {\n \"name\": \"plan-lifecycle\",\n \"source\": {\n \"source\": \"git-subdir\",\n \"url\": \"https://github.com/DocksDocks/docks.git\",\n \"path\": \"./plugins/plan-lifecycle\",\n \"ref\": \"main\"\n },\n \"policy\": {\n \"installation\": \"AVAILABLE\",\n \"authentication\": \"ON_INSTALL\"\n },\n \"category\": \"Productivity\"\n }\n ]\n}\n",
|
|
19
19
|
"SoT/.codex/rules/docks.rules": "prefix_rule(pattern=[\"pwd\"], decision=\"allow\")\nprefix_rule(pattern=[\"ls\"], decision=\"allow\")\nprefix_rule(pattern=[\"cat\"], decision=\"allow\")\nprefix_rule(pattern=[\"head\"], decision=\"allow\")\nprefix_rule(pattern=[\"tail\"], decision=\"allow\")\nprefix_rule(pattern=[\"wc\"], decision=\"allow\")\nprefix_rule(pattern=[\"nl\"], decision=\"allow\")\nprefix_rule(pattern=[\"grep\"], decision=\"allow\")\nprefix_rule(pattern=[\"diff\"], decision=\"allow\")\nprefix_rule(pattern=[\"which\"], decision=\"allow\")\nprefix_rule(pattern=[\"date\"], decision=\"allow\")\nprefix_rule(pattern=[\"basename\"], decision=\"allow\")\nprefix_rule(pattern=[\"dirname\"], decision=\"allow\")\nprefix_rule(pattern=[\"realpath\"], decision=\"allow\")\nprefix_rule(pattern=[\"readlink\"], decision=\"allow\")\nprefix_rule(pattern=[\"jq\"], decision=\"allow\")\nprefix_rule(pattern=[\"cut\"], decision=\"allow\")\nprefix_rule(pattern=[\"tr\"], decision=\"allow\")\nprefix_rule(pattern=[\"echo\"], decision=\"allow\")\nprefix_rule(pattern=[\"printf\"], decision=\"allow\")\nprefix_rule(pattern=[\"printenv\"], decision=\"allow\")\nprefix_rule(pattern=[\"uname\"], decision=\"allow\")\nprefix_rule(pattern=[\"file\"], decision=\"allow\")\nprefix_rule(pattern=[\"stat\"], decision=\"allow\")\nprefix_rule(pattern=[\"du\"], decision=\"allow\")\nprefix_rule(pattern=[\"id\"], decision=\"allow\")\nprefix_rule(pattern=[\"whoami\"], decision=\"allow\")\n\nprefix_rule(pattern=[\"git\", \"status\"], decision=\"allow\")\nprefix_rule(pattern=[\"git\", \"blame\"], decision=\"allow\")\nprefix_rule(pattern=[\"git\", \"rev-parse\"], decision=\"allow\")\nprefix_rule(pattern=[\"git\", \"ls-files\"], decision=\"allow\")\nprefix_rule(pattern=[\"git\", \"ls-tree\"], decision=\"allow\")\nprefix_rule(pattern=[\"git\", \"branch\", \"--show-current\"], decision=\"allow\")\nprefix_rule(pattern=[\"git\", \"branch\", \"-vv\"], decision=\"allow\")\n\nprefix_rule(pattern=[\"gh\", \"pr\", \"view\"], decision=\"allow\")\nprefix_rule(pattern=[\"gh\", \"pr\", \"list\"], decision=\"allow\")\nprefix_rule(pattern=[\"gh\", \"pr\", \"diff\"], decision=\"allow\")\nprefix_rule(pattern=[\"gh\", \"pr\", \"status\"], decision=\"allow\")\nprefix_rule(pattern=[\"gh\", \"pr\", \"checks\"], decision=\"allow\")\n\nprefix_rule(pattern=[\"docker\", \"ps\"], decision=\"allow\")\n\nprefix_rule(pattern=[\"git\", \"push\"], decision=\"prompt\")\nprefix_rule(pattern=[\"git\", \"reset\"], decision=\"prompt\")\nprefix_rule(pattern=[\"git\", \"clean\"], decision=\"prompt\")\nprefix_rule(pattern=[\"git\", \"merge\"], decision=\"prompt\")\nprefix_rule(pattern=[\"git\", \"rebase\"], decision=\"prompt\")\nprefix_rule(pattern=[\"git\", \"checkout\"], decision=\"prompt\")\nprefix_rule(pattern=[\"git\", \"mv\"], decision=\"prompt\")\n\nprefix_rule(pattern=[\"rm\"], decision=\"prompt\")\nprefix_rule(pattern=[\"mv\"], decision=\"prompt\")\nprefix_rule(pattern=[\"chmod\"], decision=\"prompt\")\nprefix_rule(pattern=[\"chown\"], decision=\"prompt\")\nprefix_rule(pattern=[\"kill\"], decision=\"prompt\")\nprefix_rule(pattern=[\"pkill\"], decision=\"prompt\")\n\nprefix_rule(pattern=[\"npm\", \"install\"], decision=\"prompt\")\nprefix_rule(pattern=[\"npm\", \"uninstall\"], decision=\"prompt\")\nprefix_rule(pattern=[\"pnpm\", \"add\"], decision=\"prompt\")\nprefix_rule(pattern=[\"pnpm\", \"remove\"], decision=\"prompt\")\nprefix_rule(pattern=[\"yarn\", \"add\"], decision=\"prompt\")\nprefix_rule(pattern=[\"yarn\", \"remove\"], decision=\"prompt\")\nprefix_rule(pattern=[\"pip\", \"install\"], decision=\"prompt\")\nprefix_rule(pattern=[\"pip\", \"uninstall\"], decision=\"prompt\")\nprefix_rule(pattern=[\"pip3\", \"install\"], decision=\"prompt\")\nprefix_rule(pattern=[\"pip3\", \"uninstall\"], decision=\"prompt\")\n\nprefix_rule(pattern=[\"docker\", \"run\"], decision=\"prompt\")\nprefix_rule(pattern=[\"docker\", \"rm\"], decision=\"prompt\")\nprefix_rule(pattern=[\"docker\", \"stop\"], decision=\"prompt\")\nprefix_rule(pattern=[\"docker\", \"volume\"], decision=\"prompt\")\nprefix_rule(pattern=[\"docker\", \"system\"], decision=\"prompt\")\nprefix_rule(pattern=[\"docker\", \"compose\", \"up\"], decision=\"prompt\")\nprefix_rule(pattern=[\"docker\", \"compose\", \"down\"], decision=\"prompt\")\nprefix_rule(pattern=[\"docker\", \"compose\", \"rm\"], decision=\"prompt\")\nprefix_rule(pattern=[\"docker\", \"compose\", \"stop\"], decision=\"prompt\")\nprefix_rule(pattern=[\"docker-compose\", \"up\"], decision=\"prompt\")\nprefix_rule(pattern=[\"docker-compose\", \"down\"], decision=\"prompt\")\nprefix_rule(pattern=[\"docker-compose\", \"rm\"], decision=\"prompt\")\nprefix_rule(pattern=[\"docker-compose\", \"stop\"], decision=\"prompt\")\n\n# `tail -f`/`--follow` never returns and hangs the agent (bare `tail` stays allowed above).\nprefix_rule(pattern=[\"tail\", \"-f\"], decision=\"prompt\")\nprefix_rule(pattern=[\"tail\", \"--follow\"], decision=\"prompt\")\n# These commands are prompt or absent, NOT allow, because argv-prefix matching\n# cannot gate a later write or exec flag, and allow runs outside the sandbox:\n# rg --pre=CMD; sed -n 'e CMD' or -ni; sort -o FILE or --compress-program=CMD;\n# the uniq OUTPUT operand; tree -o FILE; git diff/log/show --output=FILE;\n# git grep --open-files-in-pager=CMD or -O; git mv into .git/hooks.\n# Without a rule, sort, uniq, tree, git diff/log/show, and git grep run in the\n# sandbox with no prompt.\nprefix_rule(pattern=[\"rg\"], decision=\"prompt\")\nprefix_rule(pattern=[\"sed\", \"-n\"], decision=\"prompt\")\nprefix_rule(pattern=[\"find\"], decision=\"prompt\")\nprefix_rule(pattern=[\"sed\", \"-i\"], decision=\"prompt\")\nprefix_rule(pattern=[\"sed\", \"--in-place\"], decision=\"prompt\")\nprefix_rule(pattern=[\"awk\"], decision=\"prompt\")\nprefix_rule(pattern=[\"xargs\"], decision=\"prompt\")\nprefix_rule(pattern=[\"tee\"], decision=\"prompt\")\nprefix_rule(pattern=[\"curl\"], decision=\"prompt\")\nprefix_rule(pattern=[\"env\"], decision=\"prompt\")\n\nprefix_rule(pattern=[\"sudo\"], decision=\"forbidden\")\nprefix_rule(pattern=[\"eval\"], decision=\"forbidden\")\nprefix_rule(pattern=[\"mkfs\"], decision=\"forbidden\")\nprefix_rule(pattern=[\"dd\"], decision=\"forbidden\")\nprefix_rule(pattern=[\"git\", \"push\", \"--force\", \"origin\", \"main\"], decision=\"forbidden\")\nprefix_rule(pattern=[\"git\", \"push\", \"--force\", \"origin\", \"master\"], decision=\"forbidden\")\nprefix_rule(pattern=[\"git\", \"push\", \"-f\", \"origin\", \"main\"], decision=\"forbidden\")\nprefix_rule(pattern=[\"git\", \"push\", \"-f\", \"origin\", \"master\"], decision=\"forbidden\")\n\n# Destructive-command guards. Codex applies the strictest matching rule\n# (forbidden > prompt > allow), so an allow rule in another .rules file cannot\n# loosen them, and a narrow allow cannot carve an exception out of a prompt.\n# The rm, find, git push, git reset, and git clean prompt rules above already\n# make every recursive or bulk deletion and every history-destroying git\n# command prompt. Codex prefix rules cannot see an option after an operand,\n# so every rm prompts, a single-file rm too. A prompt goes to the approvals\n# reviewer in config.toml (auto_review), not always to a person.\n#\n# rm of the filesystem root as Codex runs it: argv tokens, or a plain script\n# that Codex splits into argv tokens.\nprefix_rule(pattern=[\"rm\", \"/\"], decision=\"forbidden\", justification=\"Never remove the home directory or the filesystem root. Move a path to the trash with gio trash -- <path> (Linux) or trash <path> (macOS 15+).\")\nprefix_rule(pattern=[\"rm\", [\"-r\", \"-R\", \"-f\", \"-rf\", \"-fr\", \"-Rf\", \"-fR\", \"-rfv\", \"-vrf\", \"-v\", \"--recursive\", \"--force\", \"--no-preserve-root\", \"--\"], \"/\"], decision=\"forbidden\", justification=\"Never remove the home directory or the filesystem root. Move a path to the trash with gio trash -- <path> (Linux) or trash <path> (macOS 15+).\")\nprefix_rule(pattern=[\"rm\", [\"-r\", \"-R\", \"-f\", \"-rf\", \"-fr\", \"-Rf\", \"-fR\", \"-rfv\", \"-vrf\", \"-v\", \"--recursive\", \"--force\", \"--no-preserve-root\", \"--\"], [\"-r\", \"-R\", \"-f\", \"-rf\", \"-fr\", \"-Rf\", \"-fR\", \"-rfv\", \"-vrf\", \"-v\", \"--recursive\", \"--force\", \"--no-preserve-root\", \"--\"], \"/\"], decision=\"forbidden\", justification=\"Never remove the home directory or the filesystem root. Move a path to the trash with gio trash -- <path> (Linux) or trash <path> (macOS 15+).\")\nprefix_rule(pattern=[\"rm\", [\"-r\", \"-R\", \"-f\", \"-rf\", \"-fr\", \"-Rf\", \"-fR\", \"-rfv\", \"-vrf\", \"-v\", \"--recursive\", \"--force\", \"--no-preserve-root\", \"--\"], [\"-r\", \"-R\", \"-f\", \"-rf\", \"-fr\", \"-Rf\", \"-fR\", \"-rfv\", \"-vrf\", \"-v\", \"--recursive\", \"--force\", \"--no-preserve-root\", \"--\"], [\"-r\", \"-R\", \"-f\", \"-rf\", \"-fr\", \"-Rf\", \"-fR\", \"-rfv\", \"-vrf\", \"-v\", \"--recursive\", \"--force\", \"--no-preserve-root\", \"--\"], \"/\"], decision=\"forbidden\", justification=\"Never remove the home directory or the filesystem root. Move a path to the trash with gio trash -- <path> (Linux) or trash <path> (macOS 15+).\")\n# Codex does not split a script that holds ~, $HOME, a glob, or a substitution.\n# It matches the whole [shell, -c, script] invocation, so these rules forbid\n# only the exact scripts listed.\nprefix_rule(pattern=[[\"bash\", \"sh\", \"zsh\"], [\"-c\", \"-lc\"], [\"rm ~\", \"rm -r ~\", \"rm -R ~\", \"rm -f ~\", \"rm -rf ~\", \"rm -fr ~\", \"rm -Rf ~\", \"rm -fR ~\", \"rm -r -f ~\", \"rm -f -r ~\", \"rm --recursive ~\", \"rm --recursive --force ~\"]], decision=\"forbidden\", justification=\"Never remove the home directory or the filesystem root. Move a path to the trash with gio trash -- <path> (Linux) or trash <path> (macOS 15+).\")\nprefix_rule(pattern=[[\"bash\", \"sh\", \"zsh\"], [\"-c\", \"-lc\"], [\"rm ~/\", \"rm -r ~/\", \"rm -R ~/\", \"rm -f ~/\", \"rm -rf ~/\", \"rm -fr ~/\", \"rm -Rf ~/\", \"rm -fR ~/\", \"rm -r -f ~/\", \"rm -f -r ~/\", \"rm --recursive ~/\", \"rm --recursive --force ~/\"]], decision=\"forbidden\", justification=\"Never remove the home directory or the filesystem root. Move a path to the trash with gio trash -- <path> (Linux) or trash <path> (macOS 15+).\")\nprefix_rule(pattern=[[\"bash\", \"sh\", \"zsh\"], [\"-c\", \"-lc\"], [\"rm $HOME\", \"rm -r $HOME\", \"rm -R $HOME\", \"rm -f $HOME\", \"rm -rf $HOME\", \"rm -fr $HOME\", \"rm -Rf $HOME\", \"rm -fR $HOME\", \"rm -r -f $HOME\", \"rm -f -r $HOME\", \"rm --recursive $HOME\", \"rm --recursive --force $HOME\"]], decision=\"forbidden\", justification=\"Never remove the home directory or the filesystem root. Move a path to the trash with gio trash -- <path> (Linux) or trash <path> (macOS 15+).\")\nprefix_rule(pattern=[[\"bash\", \"sh\", \"zsh\"], [\"-c\", \"-lc\"], [\"rm $HOME/\", \"rm -r $HOME/\", \"rm -R $HOME/\", \"rm -f $HOME/\", \"rm -rf $HOME/\", \"rm -fr $HOME/\", \"rm -Rf $HOME/\", \"rm -fR $HOME/\", \"rm -r -f $HOME/\", \"rm -f -r $HOME/\", \"rm --recursive $HOME/\", \"rm --recursive --force $HOME/\"]], decision=\"forbidden\", justification=\"Never remove the home directory or the filesystem root. Move a path to the trash with gio trash -- <path> (Linux) or trash <path> (macOS 15+).\")\nprefix_rule(pattern=[[\"bash\", \"sh\", \"zsh\"], [\"-c\", \"-lc\"], [\"rm \\\"$HOME\\\"\", \"rm -r \\\"$HOME\\\"\", \"rm -R \\\"$HOME\\\"\", \"rm -f \\\"$HOME\\\"\", \"rm -rf \\\"$HOME\\\"\", \"rm -fr \\\"$HOME\\\"\", \"rm -Rf \\\"$HOME\\\"\", \"rm -fR \\\"$HOME\\\"\", \"rm -r -f \\\"$HOME\\\"\", \"rm -f -r \\\"$HOME\\\"\", \"rm --recursive \\\"$HOME\\\"\", \"rm --recursive --force \\\"$HOME\\\"\"]], decision=\"forbidden\", justification=\"Never remove the home directory or the filesystem root. Move a path to the trash with gio trash -- <path> (Linux) or trash <path> (macOS 15+).\")\nprefix_rule(pattern=[[\"bash\", \"sh\", \"zsh\"], [\"-c\", \"-lc\"], [\"rm \\\"$HOME/\\\"\", \"rm -r \\\"$HOME/\\\"\", \"rm -R \\\"$HOME/\\\"\", \"rm -f \\\"$HOME/\\\"\", \"rm -rf \\\"$HOME/\\\"\", \"rm -fr \\\"$HOME/\\\"\", \"rm -Rf \\\"$HOME/\\\"\", \"rm -fR \\\"$HOME/\\\"\", \"rm -r -f \\\"$HOME/\\\"\", \"rm -f -r \\\"$HOME/\\\"\", \"rm --recursive \\\"$HOME/\\\"\", \"rm --recursive --force \\\"$HOME/\\\"\"]], decision=\"forbidden\", justification=\"Never remove the home directory or the filesystem root. Move a path to the trash with gio trash -- <path> (Linux) or trash <path> (macOS 15+).\")\nprefix_rule(pattern=[[\"bash\", \"sh\", \"zsh\"], [\"-c\", \"-lc\"], [\"rm \\\"$HOME\\\"/\", \"rm -r \\\"$HOME\\\"/\", \"rm -R \\\"$HOME\\\"/\", \"rm -f \\\"$HOME\\\"/\", \"rm -rf \\\"$HOME\\\"/\", \"rm -fr \\\"$HOME\\\"/\", \"rm -Rf \\\"$HOME\\\"/\", \"rm -fR \\\"$HOME\\\"/\", \"rm -r -f \\\"$HOME\\\"/\", \"rm -f -r \\\"$HOME\\\"/\", \"rm --recursive \\\"$HOME\\\"/\", \"rm --recursive --force \\\"$HOME\\\"/\"]], decision=\"forbidden\", justification=\"Never remove the home directory or the filesystem root. Move a path to the trash with gio trash -- <path> (Linux) or trash <path> (macOS 15+).\")\nprefix_rule(pattern=[[\"bash\", \"sh\", \"zsh\"], [\"-c\", \"-lc\"], [\"rm ${HOME}\", \"rm -r ${HOME}\", \"rm -R ${HOME}\", \"rm -f ${HOME}\", \"rm -rf ${HOME}\", \"rm -fr ${HOME}\", \"rm -Rf ${HOME}\", \"rm -fR ${HOME}\", \"rm -r -f ${HOME}\", \"rm -f -r ${HOME}\", \"rm --recursive ${HOME}\", \"rm --recursive --force ${HOME}\"]], decision=\"forbidden\", justification=\"Never remove the home directory or the filesystem root. Move a path to the trash with gio trash -- <path> (Linux) or trash <path> (macOS 15+).\")\nprefix_rule(pattern=[[\"bash\", \"sh\", \"zsh\"], [\"-c\", \"-lc\"], [\"rm ${HOME}/\", \"rm -r ${HOME}/\", \"rm -R ${HOME}/\", \"rm -f ${HOME}/\", \"rm -rf ${HOME}/\", \"rm -fr ${HOME}/\", \"rm -Rf ${HOME}/\", \"rm -fR ${HOME}/\", \"rm -r -f ${HOME}/\", \"rm -f -r ${HOME}/\", \"rm --recursive ${HOME}/\", \"rm --recursive --force ${HOME}/\"]], decision=\"forbidden\", justification=\"Never remove the home directory or the filesystem root. Move a path to the trash with gio trash -- <path> (Linux) or trash <path> (macOS 15+).\")\nprefix_rule(pattern=[[\"bash\", \"sh\", \"zsh\"], [\"-c\", \"-lc\"], [\"rm \\\"${HOME}\\\"\", \"rm -r \\\"${HOME}\\\"\", \"rm -R \\\"${HOME}\\\"\", \"rm -f \\\"${HOME}\\\"\", \"rm -rf \\\"${HOME}\\\"\", \"rm -fr \\\"${HOME}\\\"\", \"rm -Rf \\\"${HOME}\\\"\", \"rm -fR \\\"${HOME}\\\"\", \"rm -r -f \\\"${HOME}\\\"\", \"rm -f -r \\\"${HOME}\\\"\", \"rm --recursive \\\"${HOME}\\\"\", \"rm --recursive --force \\\"${HOME}\\\"\"]], decision=\"forbidden\", justification=\"Never remove the home directory or the filesystem root. Move a path to the trash with gio trash -- <path> (Linux) or trash <path> (macOS 15+).\")\nprefix_rule(pattern=[[\"bash\", \"sh\", \"zsh\"], [\"-c\", \"-lc\"], [\"rm \\\"${HOME}/\\\"\", \"rm -r \\\"${HOME}/\\\"\", \"rm -R \\\"${HOME}/\\\"\", \"rm -f \\\"${HOME}/\\\"\", \"rm -rf \\\"${HOME}/\\\"\", \"rm -fr \\\"${HOME}/\\\"\", \"rm -Rf \\\"${HOME}/\\\"\", \"rm -fR \\\"${HOME}/\\\"\", \"rm -r -f \\\"${HOME}/\\\"\", \"rm -f -r \\\"${HOME}/\\\"\", \"rm --recursive \\\"${HOME}/\\\"\", \"rm --recursive --force \\\"${HOME}/\\\"\"]], decision=\"forbidden\", justification=\"Never remove the home directory or the filesystem root. Move a path to the trash with gio trash -- <path> (Linux) or trash <path> (macOS 15+).\")\nprefix_rule(pattern=[[\"bash\", \"sh\", \"zsh\"], [\"-c\", \"-lc\"], [\"rm \\\"${HOME}\\\"/\", \"rm -r \\\"${HOME}\\\"/\", \"rm -R \\\"${HOME}\\\"/\", \"rm -f \\\"${HOME}\\\"/\", \"rm -rf \\\"${HOME}\\\"/\", \"rm -fr \\\"${HOME}\\\"/\", \"rm -Rf \\\"${HOME}\\\"/\", \"rm -fR \\\"${HOME}\\\"/\", \"rm -r -f \\\"${HOME}\\\"/\", \"rm -f -r \\\"${HOME}\\\"/\", \"rm --recursive \\\"${HOME}\\\"/\", \"rm --recursive --force \\\"${HOME}\\\"/\"]], decision=\"forbidden\", justification=\"Never remove the home directory or the filesystem root. Move a path to the trash with gio trash -- <path> (Linux) or trash <path> (macOS 15+).\")\nprefix_rule(pattern=[[\"bash\", \"sh\", \"zsh\"], [\"-c\", \"-lc\"], [\"rm /*\", \"rm -r /*\", \"rm -R /*\", \"rm -f /*\", \"rm -rf /*\", \"rm -fr /*\", \"rm -Rf /*\", \"rm -fR /*\", \"rm -r -f /*\", \"rm -f -r /*\", \"rm --recursive /*\", \"rm --recursive --force /*\"]], decision=\"forbidden\", justification=\"Never remove the home directory or the filesystem root. Move a path to the trash with gio trash -- <path> (Linux) or trash <path> (macOS 15+).\")\nprefix_rule(pattern=[[\"bash\", \"sh\", \"zsh\"], [\"-c\", \"-lc\"], [\"export HOME=$(mktemp -d)\", \"export HOME=\\\"$(mktemp -d)\\\"\", \"HOME=$(mktemp -d)\", \"HOME=\\\"$(mktemp -d)\\\"\"]], decision=\"forbidden\", justification=\"Never reassign HOME. Each command runs in a new shell, so use literal absolute paths.\")\n\n# Forced git removal discards uncommitted changes, and the prefix cannot see a\n# later --force, so both commands ask in every form.\nprefix_rule(pattern=[\"git\", \"rm\"], decision=\"prompt\", justification=\"git rm --force and git worktree remove --force discard uncommitted changes. A prefix rule cannot see a later --force, so every git rm and git worktree remove asks.\")\nprefix_rule(pattern=[\"git\", \"worktree\", \"remove\"], decision=\"prompt\", justification=\"git rm --force and git worktree remove --force discard uncommitted changes. A prefix rule cannot see a later --force, so every git rm and git worktree remove asks.\")\n\n# gio trash can empty the trash or overwrite a restored path, and the prefix\n# cannot tell those forms from gio trash -- <path>, so every gio trash asks.\n# The macOS trash command has no such option.\nprefix_rule(pattern=[\"gio\", \"trash\"], decision=\"prompt\", justification=\"gio trash -f --empty, -ff --empty, and --restore --force delete or overwrite data, and a prefix rule cannot tell them from gio trash -- <path>, so every gio trash asks.\")\nprefix_rule(pattern=[\"trash\"], decision=\"allow\")\n",
|
|
20
20
|
"SoT/.omp/AGENTS.md": "# Global OMP guidance\n\n- Verify unfamiliar or version-sensitive APIs and configuration against current official documentation before implementation.\n- When the user asks for an assessment rather than a change, report findings without editing.\n- For Docks plan reviews, cross-company review is standing-authorized; host security policy still applies.\n- Please remove all mannered prose.\n\n## Asking me things\n\nIf you need an answer from me, it MUST go through `ask`; do not ask in prose.\n\nMUST use `ask` before:\n- Anything irreversible or destructive: deleting/overwriting files or data you did not create,\n force-push, history rewrite, dropping tables, running migrations, mass rename, touching\n secrets/credentials, or publishing outward (release, upstream PR, issue, comment).\n- Two or more viable approaches whose tradeoffs are mine to own: schema/API/protocol shape,\n adding a dependency, or establishing a convention this repo does not already have.\n- A fact only I hold: intended semantics of an ambiguous requirement, which of several\n conflicting existing patterns is canonical, or which environment/account/target to use.\n- A request that contradicts the repo: surface the conflict and let me resolve it; never\n silently pick one side.\n\nWhen I invoke the `yolo` skill, that invocation answers every ask this section requires,\nuntil the run asks its merge question. It does not cover destructive work, secrets, or\nproduction systems.\n\nIf `ask` is not registered — subagent, headless, or `-p` print runs, where `hasUI` is false —\nthe MUST above cannot be satisfied: do not fabricate the call and do not stall on it. Take the\nconservative reversible option and put the question, plus the assumption you made, in your\nfinal report so whoever spawned you can decide.\n\nNEVER use `ask` for:\n- Permission to begin, or to confirm scope already stated in the request.\n- Anything a tool, grep, or doc can answer — go read it.\n- A cheap reversible choice — take the conservative option and say which you took.\n- Something already answered earlier in the conversation.\n\nBatch every open question into one `ask` call with multiple questions; do not serialize\nround trips. Being overruled ends the discussion — execute my call without relitigating.\n\n## Removing files\n\nTo remove, use the trash or a command that checks the path.\n\n- To remove a temporary file or directory, use the `scratch_remove` tool or run `docks-kit scratch remove <path>`. Both remove only a path inside the scratch root, the system temporary directory, or `/var/tmp`. `gio trash` does not work on a `tmpfs` `/tmp`.\n- To remove any other file or directory, run `gio trash -- <path>` on Linux or `trash <path>` on macOS.\n- To remove a path from the git index, run `git rm -- <path>`.\n- To remove a worktree, run `git worktree remove -- <path>`.\n- If git refuses because the worktree has changes, make sure that each of its commits is on the remote. Then make sure that `git status --porcelain` lists only generated files. Then run `git worktree remove --force -- <path>`.\n- Never pass `--force` two times to `git worktree remove`.\n- Write the `--` exactly as shown.\n- Do not use `rm`. omp denies a recursive `rm`, `find -delete`, `find -exec rm`, and `xargs rm`.\n- Do not delete files through `eval`, Python, or Node code.\n- A subagent cannot get my approval, so omp rejects every ask in a subagent.\n- Do not delete in bulk yourself (`git clean`, `git reset --hard`). In the main session, ask me first.\n- If a deletion needs `rm -r` or a bulk command, put the paths in your report. I run that deletion myself.\n- Do not use `--force`, `-f`, or an abbreviation of it with `git rm` or `git push`.\n- Write each ref of a `git push` command as literal text. Run `git push` as its own command. omp denies a command that holds a `$` or a backtick after `git push`.\n- To push the current branch, run `git push -u origin HEAD`. To delete several remote branches, list them in one command: `git push origin --delete <branch-a> <branch-b>`.\n- Write literal absolute paths. Do not use `~` or `$HOME` in a command.\n- Do not set or export `HOME`.\n\n## Repository hooks\n\n- Do not skip or turn off a repository hook. Do not use `--no-verify`, `git commit -n`, `git am -n`, or a `core.hooksPath` change.\n- When a hook fails on a problem that your change did not cause, report the failure. In the main session, ask me before you continue.\n\n## Cleaning up what you create\n\n- Follow the `workspace-hygiene` skill for each resource that you create: worktrees, temporary files and directories, processes, containers, clusters, tunnels, scheduled jobs, global installs, and remote test resources.\n- Create a temporary directory with the `scratch_new` tool or `docks-kit scratch new <label>`. Put each temporary file in that directory. Do not put a temporary file, a temporary directory, a package store, a cache, or a clone in `/tmp`.\n- Create a worktree only at `<data>/agent-worktrees/<repository>/<name>`. `<data>` is `$XDG_DATA_HOME`, or `.local/share` in the home directory when that variable is not set. Write the literal absolute path.\n- Run a test suite in single-run mode. Start a server, a watcher, a tunnel, or a database only as a named bash service or an async job. Do not detach a process with `nohup`, `setsid`, `disown`, `tmux`, or `screen`.\n- Do not install a package globally, add a scheduled job, or enable a service unless I ask for it.\n- Do not remove a Docker volume, image, or build cache that you did not create, and do not run `docker system prune`.\n- Before your final answer, remove each resource that you created and that the task no longer needs. Keep a resource only when I ask for it or a later step needs it, and name it in your final answer.\n- A scratch directory is deleted after 7 idle days. Put evidence that you cite in the issue, the pull request, or the repository.\n- Resources on this workstation are always development. A remote resource is one that you reach through SSH or a provider CLI, such as `wrangler`, `vercel`, `netlify`, `fly`, `supabase`, `kubectl`, or a remote Docker host.\n- Clean up a remote resource only when its target is named local, development, dev, test, homolog, homologation, staging, or preview. Every other target is production. For example, `wrangler delete` without `--env` acts on the top-level Worker, which is usually production.\n- Never stop, remove, undeploy, or delete a production resource without an `ask` immediately before it. A production cleanup must be rare. A `yolo` invocation does not answer this ask. In a subagent, do not do it; name the resource in your report.\n\n## Output Standard\n\nApply Simplified Technical English to all agent text. This includes responses, messages,\ndocumentation, comments, and interface text.\n\nReply in the language I use, and apply every rule below to that language.\n\nA rule that names English grammar applies only to English. The contraction ban is one\nsuch rule. In another language, follow the normal grammar of that language. Portuguese,\nSpanish, French, Italian, and German merge a preposition with an article, and that merge\nis required, not optional.\n\nTreat the word limits as approximate outside English.\n\n- Use the simplest precise technical term.\n- Use each term consistently.\n- Expand an abbreviation at its first occurrence.\n- Explain a technical term when I ask for an explanation.\n- Write complete and grammatically correct sentences.\n- Use active voice and identify the actor.\n- Use the imperative form for instructions.\n- Put only one action in each instruction sentence.\n- Put a necessary condition before its instruction.\n- Use simple verb tenses.\n- Do not use contractions, idioms, or slang. Avoid humor and rhetorical questions.\n- Keep procedural sentences to 20 words or fewer.\n- Keep descriptive sentences to 25 words or fewer.\n- Keep each paragraph to one topic and six sentences or fewer.\n- Do not use more than three nouns together.\n- Use vertical lists for complex information.\n- Put a warning or caution before a related hazardous instruction.\n\n### Naming\n\n- Say what the thing does before you name it. Put the technical term after the plain\n description, once, in parentheses.\n- Do not use a technical term as the only name for something you just introduced.\n- Prefer the short common word. Use \"use\", not \"utilize\". Use \"set up\", not \"provision\".\n- Do not explain by metaphor alone. A metaphor may follow a literal statement.\n",
|
|
21
|
-
"SoT/.omp/config.yml": "statusLine:\n compactThinkingLevel: false\n\ndefaultThinkingLevel: high\n\ncycleOrder:\n - smol\n - default\n - slow\n - fable\n - astra\n\ntier:\n anthropic: none\n\nadvisor:\n enabled: true\n syncBacklog: \"1\"\n\ngithub:\n enabled: true\n\nfind:\n enabled: true\n\nbrowser:\n idleCloseSec: 600\n\ntask:\n eager: always\n showResolvedModelBadge: true\n softRequestBudget: 200\n softRequestBudgetNotice: true\n batch: true\n enableLsp: true\n enableEffort: false\n maxEffort: xhigh\n maxConcurrency: 16\n maxRecursionDepth: 2\n maxRuntimeMs: 3600000\n agentIdleTtlMs: 120000\n agentModelOverrides:\n reviewer: \"@reviewer\"\n security-reviewer: \"@reviewer\"\n code-reviewer: \"@reviewer\"\n plan-reviewer: \"@reviewer\"\n agentServiceTierOverrides:\n reviewer: inherit\n security-reviewer: inherit\n code-reviewer: inherit\n plan-reviewer: inherit\n\nmodelRoles:\n smol: openai-codex/gpt-6-luna:medium\n advisor: anthropic/claude-opus-5-5:medium\n designer: anthropic/claude-opus-5-5:high\n plan: anthropic/claude-opus-5-5:xhigh\n commit: openai-codex/gpt-6-luna:medium\n task: anthropic/claude-opus-5-5:high\n vision: anthropic/claude-opus-5-5:medium\n tiny: openai-codex/gpt-6-luna:low\n default: anthropic/claude-opus-5-5:high\n slow: anthropic/claude-opus-5-5:xhigh\n fable: anthropic/claude-fable-5-1:medium\n switch_fable: anthropic/claude-fable-5-1:medium\n astra: openai-codex/gpt-6-astra:xhigh\n reviewer: openai-codex/gpt-6.1-terra:high\n web: web/firecrawl\n\nmodelTags:\n fable:\n name: Fable 5.1\n switch_fable:\n name: Fable switch default\n hidden: true\n astra:\n name: GPT-6 Astra\n reviewer:\n name: Reviewer\n hidden: true\n\ndisplay:\n showTokenUsage: true\n\nproviders:\n anthropic:\n serverSideFallback: false\n fetch: auto\n webSearchTimeoutSeconds: 30\n\nretry:\n fallbackChains:\n default:\n - openai-codex/gpt-6.1-sol:high\n advisor: []\n task:\n - openai-codex/gpt-6.1-sol:high\n vision:\n - openai-codex/gpt-6.1-sol:medium\n smol:\n - anthropic/claude-opus-5-5:low\n tiny:\n - anthropic/claude-opus-5-5:low\n commit:\n - anthropic/claude-opus-5-5:medium\n switch_fable: []\n fable:\n - openai-codex/gpt-6-astra:xhigh\n astra:\n - anthropic/claude-fable-5-1:medium\n reviewer:\n - anthropic/claude-opus-5-5:high\n web:\n - web/exa\n - web/perplexity\n - openai-codex/gpt-6-luna\n - web/parallel\n - web/zai\n - web/tinyfish\n - web/jina\n - web/kagi\n - web/tavily\n - web/brave\n - web/kimi\n - web/synthetic\n - web/ollama\n - web/searxng\n - web/startpage\n - web/duckduckgo\n - web/ecosia\n - web/google\n - web/mojeek\n - web/public\n\nincludeWorkspaceTree: false\n\nbranchSummary:\n enabled: true\n\ncommands:\n enableOpencodeProject: false\n enableOpencodeUser: false\n\nskills:\n enableClaudeUser: false\n enableCodexUser: false\n enableAgentsUser: true\n\nsteeringMode: all\n\ndev:\n autoqa: false\n autoqaConsent: denied\n\ncompaction:\n thresholdTokens: -1\n idleEnabled: true\n handoffSaveToDisk: true\n\ndoubleEscapeAction: tree\ntextVerbosity: low\n\nfeatures:\n unexpectedStopDetection: smart\n\ncodexResets:\n autoRedeem: \"no\"\n\nstartup:\n quiet: true\n\ntools:\n approvalMode: yolo\n\nbash:\n # First match wins. omp checks deny rules against the whole line and each\n # quote-stripped segment, so `rm -rf \"$HOME\"` matches `rm * $HOME`. `*`\n # matches any text, spaces and slashes included; no escape spells a literal\n # `*`.\n # The kit ships no prompt rule, because a subagent rejects every prompt.\n # A command that no deny rule matches runs under yolo, unless a prompt rule\n # that the user added matches it: a plain rm, git rm, git worktree remove,\n # gio trash, docks-kit scratch remove, git clean, git reset --hard, and\n # every git push that the denies below do not stop.\n # omp's critical-command check turns a prompt into an allow under yolo, so\n # every rm shape it can flag is a deny.\n patterns:\n # Deny: rm of the home directory or the filesystem root, sudo before rm,\n # rm with an r or f option before an absolute path, recursive rm (bare, by\n # path, or after any word such as env, xargs, find -exec, or git), bulk\n # removal through find -delete, find -exec rm, and xargs rm, HOME\n # reassignment, a force push to main or master, and a $ or a backtick\n # after git push.\n - { match: \"rm /\", approval: deny }\n - { match: \"rm / *\", approval: deny }\n - { match: \"rm * /\", approval: deny }\n - { match: \"rm * / *\", approval: deny }\n - { match: \"rm ~\", approval: deny }\n - { match: \"rm ~ *\", approval: deny }\n - { match: \"rm * ~\", approval: deny }\n - { match: \"rm * ~ *\", approval: deny }\n - { match: \"rm ~/\", approval: deny }\n - { match: \"rm ~/ *\", approval: deny }\n - { match: \"rm * ~/\", approval: deny }\n - { match: \"rm * ~/ *\", approval: deny }\n - { match: \"rm $HOME\", approval: deny }\n - { match: \"rm $HOME *\", approval: deny }\n - { match: \"rm * $HOME\", approval: deny }\n - { match: \"rm * $HOME *\", approval: deny }\n - { match: \"rm $HOME/\", approval: deny }\n - { match: \"rm $HOME/ *\", approval: deny }\n - { match: \"rm * $HOME/\", approval: deny }\n - { match: \"rm * $HOME/ *\", approval: deny }\n - { match: \"rm ${HOME}\", approval: deny }\n - { match: \"rm ${HOME} *\", approval: deny }\n - { match: \"rm * ${HOME}\", approval: deny }\n - { match: \"rm * ${HOME} *\", approval: deny }\n - { match: \"rm ${HOME}/\", approval: deny }\n - { match: \"rm ${HOME}/ *\", approval: deny }\n - { match: \"rm * ${HOME}/\", approval: deny }\n - { match: \"rm * ${HOME}/ *\", approval: deny }\n - { match: \"* rm /\", approval: deny }\n - { match: \"* rm / *\", approval: deny }\n - { match: \"* rm * /\", approval: deny }\n - { match: \"* rm * / *\", approval: deny }\n - { match: \"* rm ~\", approval: deny }\n - { match: \"* rm ~ *\", approval: deny }\n - { match: \"* rm * ~\", approval: deny }\n - { match: \"* rm * ~ *\", approval: deny }\n - { match: \"* rm ~/\", approval: deny }\n - { match: \"* rm ~/ *\", approval: deny }\n - { match: \"* rm * ~/\", approval: deny }\n - { match: \"* rm * ~/ *\", approval: deny }\n - { match: \"* rm $HOME\", approval: deny }\n - { match: \"* rm $HOME *\", approval: deny }\n - { match: \"* rm * $HOME\", approval: deny }\n - { match: \"* rm * $HOME *\", approval: deny }\n - { match: \"* rm $HOME/\", approval: deny }\n - { match: \"* rm $HOME/ *\", approval: deny }\n - { match: \"* rm * $HOME/\", approval: deny }\n - { match: \"* rm * $HOME/ *\", approval: deny }\n - { match: \"* rm ${HOME}\", approval: deny }\n - { match: \"* rm ${HOME} *\", approval: deny }\n - { match: \"* rm * ${HOME}\", approval: deny }\n - { match: \"* rm * ${HOME} *\", approval: deny }\n - { match: \"* rm ${HOME}/\", approval: deny }\n - { match: \"* rm ${HOME}/ *\", approval: deny }\n - { match: \"* rm * ${HOME}/\", approval: deny }\n - { match: \"* rm * ${HOME}/ *\", approval: deny }\n - { match: \"*/rm /\", approval: deny }\n - { match: \"*/rm / *\", approval: deny }\n - { match: \"*/rm * /\", approval: deny }\n - { match: \"*/rm * / *\", approval: deny }\n - { match: \"*/rm ~\", approval: deny }\n - { match: \"*/rm ~ *\", approval: deny }\n - { match: \"*/rm * ~\", approval: deny }\n - { match: \"*/rm * ~ *\", approval: deny }\n - { match: \"*/rm ~/\", approval: deny }\n - { match: \"*/rm ~/ *\", approval: deny }\n - { match: \"*/rm * ~/\", approval: deny }\n - { match: \"*/rm * ~/ *\", approval: deny }\n - { match: \"*/rm $HOME\", approval: deny }\n - { match: \"*/rm $HOME *\", approval: deny }\n - { match: \"*/rm * $HOME\", approval: deny }\n - { match: \"*/rm * $HOME *\", approval: deny }\n - { match: \"*/rm $HOME/\", approval: deny }\n - { match: \"*/rm $HOME/ *\", approval: deny }\n - { match: \"*/rm * $HOME/\", approval: deny }\n - { match: \"*/rm * $HOME/ *\", approval: deny }\n - { match: \"*/rm ${HOME}\", approval: deny }\n - { match: \"*/rm ${HOME} *\", approval: deny }\n - { match: \"*/rm * ${HOME}\", approval: deny }\n - { match: \"*/rm * ${HOME} *\", approval: deny }\n - { match: \"*/rm ${HOME}/\", approval: deny }\n - { match: \"*/rm ${HOME}/ *\", approval: deny }\n - { match: \"*/rm * ${HOME}/\", approval: deny }\n - { match: \"*/rm * ${HOME}/ *\", approval: deny }\n - { match: \"sudo rm\", approval: deny }\n - { match: \"sudo rm *\", approval: deny }\n - { match: \"sudo * rm\", approval: deny }\n - { match: \"sudo * rm *\", approval: deny }\n - { match: \"sudo */rm\", approval: deny }\n - { match: \"sudo */rm *\", approval: deny }\n - { match: \"* sudo rm\", approval: deny }\n - { match: \"* sudo rm *\", approval: deny }\n - { match: \"* sudo * rm\", approval: deny }\n - { match: \"* sudo * rm *\", approval: deny }\n - { match: \"* sudo */rm\", approval: deny }\n - { match: \"* sudo */rm *\", approval: deny }\n - { match: \"*/sudo rm\", approval: deny }\n - { match: \"*/sudo rm *\", approval: deny }\n - { match: \"*/sudo * rm\", approval: deny }\n - { match: \"*/sudo * rm *\", approval: deny }\n - { match: \"*/sudo */rm\", approval: deny }\n - { match: \"*/sudo */rm *\", approval: deny }\n - { match: \"rm *-*r* /*\", approval: deny }\n - { match: \"rm *-*R* /*\", approval: deny }\n - { match: \"rm *-*f* /*\", approval: deny }\n - { match: \"rm *-*F* /*\", approval: deny }\n - { match: \"rm *--no-preserve-root*\", approval: deny }\n - { match: \"* rm *-*r* /*\", approval: deny }\n - { match: \"* rm *-*R* /*\", approval: deny }\n - { match: \"* rm *-*f* /*\", approval: deny }\n - { match: \"* rm *-*F* /*\", approval: deny }\n - { match: \"* rm *--no-preserve-root*\", approval: deny }\n - { match: \"*/rm *-*r* /*\", approval: deny }\n - { match: \"*/rm *-*R* /*\", approval: deny }\n - { match: \"*/rm *-*f* /*\", approval: deny }\n - { match: \"*/rm *-*F* /*\", approval: deny }\n - { match: \"*/rm *--no-preserve-root*\", approval: deny }\n - { match: \"rm *-r *\", approval: deny }\n - { match: \"rm *-r\", approval: deny }\n - { match: \"rm *-rf *\", approval: deny }\n - { match: \"rm *-rf\", approval: deny }\n - { match: \"rm *-fr *\", approval: deny }\n - { match: \"rm *-fr\", approval: deny }\n - { match: \"rm *-rv *\", approval: deny }\n - { match: \"rm *-rv\", approval: deny }\n - { match: \"rm *-vr *\", approval: deny }\n - { match: \"rm *-vr\", approval: deny }\n - { match: \"rm *-rfv *\", approval: deny }\n - { match: \"rm *-rfv\", approval: deny }\n - { match: \"rm *-rvf *\", approval: deny }\n - { match: \"rm *-rvf\", approval: deny }\n - { match: \"rm *-frv *\", approval: deny }\n - { match: \"rm *-frv\", approval: deny }\n - { match: \"rm *-fvr *\", approval: deny }\n - { match: \"rm *-fvr\", approval: deny }\n - { match: \"rm *-vrf *\", approval: deny }\n - { match: \"rm *-vrf\", approval: deny }\n - { match: \"rm *-vfr *\", approval: deny }\n - { match: \"rm *-vfr\", approval: deny }\n - { match: \"rm *-ri *\", approval: deny }\n - { match: \"rm *-ri\", approval: deny }\n - { match: \"rm *-ir *\", approval: deny }\n - { match: \"rm *-ir\", approval: deny }\n - { match: \"rm *-Ri *\", approval: deny }\n - { match: \"rm *-Ri\", approval: deny }\n - { match: \"rm *-iR *\", approval: deny }\n - { match: \"rm *-iR\", approval: deny }\n - { match: \"rm *-R *\", approval: deny }\n - { match: \"rm *-R\", approval: deny }\n - { match: \"rm *-Rf *\", approval: deny }\n - { match: \"rm *-Rf\", approval: deny }\n - { match: \"rm *-fR *\", approval: deny }\n - { match: \"rm *-fR\", approval: deny }\n - { match: \"rm *-Rv *\", approval: deny }\n - { match: \"rm *-Rv\", approval: deny }\n - { match: \"rm *-vR *\", approval: deny }\n - { match: \"rm *-vR\", approval: deny }\n - { match: \"rm *-Rfv *\", approval: deny }\n - { match: \"rm *-Rfv\", approval: deny }\n - { match: \"rm *-Rvf *\", approval: deny }\n - { match: \"rm *-Rvf\", approval: deny }\n - { match: \"rm *-fRv *\", approval: deny }\n - { match: \"rm *-fRv\", approval: deny }\n - { match: \"rm *-fvR *\", approval: deny }\n - { match: \"rm *-fvR\", approval: deny }\n - { match: \"rm *-vRf *\", approval: deny }\n - { match: \"rm *-vRf\", approval: deny }\n - { match: \"rm *-vfR *\", approval: deny }\n - { match: \"rm *-vfR\", approval: deny }\n - { match: \"rm *--recursive *\", approval: deny }\n - { match: \"rm *--recursive\", approval: deny }\n - { match: \"*/rm *-r *\", approval: deny }\n - { match: \"*/rm *-r\", approval: deny }\n - { match: \"*/rm *-rf *\", approval: deny }\n - { match: \"*/rm *-rf\", approval: deny }\n - { match: \"*/rm *-fr *\", approval: deny }\n - { match: \"*/rm *-fr\", approval: deny }\n - { match: \"*/rm *-rv *\", approval: deny }\n - { match: \"*/rm *-rv\", approval: deny }\n - { match: \"*/rm *-vr *\", approval: deny }\n - { match: \"*/rm *-vr\", approval: deny }\n - { match: \"*/rm *-rfv *\", approval: deny }\n - { match: \"*/rm *-rfv\", approval: deny }\n - { match: \"*/rm *-rvf *\", approval: deny }\n - { match: \"*/rm *-rvf\", approval: deny }\n - { match: \"*/rm *-frv *\", approval: deny }\n - { match: \"*/rm *-frv\", approval: deny }\n - { match: \"*/rm *-fvr *\", approval: deny }\n - { match: \"*/rm *-fvr\", approval: deny }\n - { match: \"*/rm *-vrf *\", approval: deny }\n - { match: \"*/rm *-vrf\", approval: deny }\n - { match: \"*/rm *-vfr *\", approval: deny }\n - { match: \"*/rm *-vfr\", approval: deny }\n - { match: \"*/rm *-ri *\", approval: deny }\n - { match: \"*/rm *-ri\", approval: deny }\n - { match: \"*/rm *-ir *\", approval: deny }\n - { match: \"*/rm *-ir\", approval: deny }\n - { match: \"*/rm *-Ri *\", approval: deny }\n - { match: \"*/rm *-Ri\", approval: deny }\n - { match: \"*/rm *-iR *\", approval: deny }\n - { match: \"*/rm *-iR\", approval: deny }\n - { match: \"*/rm *-R *\", approval: deny }\n - { match: \"*/rm *-R\", approval: deny }\n - { match: \"*/rm *-Rf *\", approval: deny }\n - { match: \"*/rm *-Rf\", approval: deny }\n - { match: \"*/rm *-fR *\", approval: deny }\n - { match: \"*/rm *-fR\", approval: deny }\n - { match: \"*/rm *-Rv *\", approval: deny }\n - { match: \"*/rm *-Rv\", approval: deny }\n - { match: \"*/rm *-vR *\", approval: deny }\n - { match: \"*/rm *-vR\", approval: deny }\n - { match: \"*/rm *-Rfv *\", approval: deny }\n - { match: \"*/rm *-Rfv\", approval: deny }\n - { match: \"*/rm *-Rvf *\", approval: deny }\n - { match: \"*/rm *-Rvf\", approval: deny }\n - { match: \"*/rm *-fRv *\", approval: deny }\n - { match: \"*/rm *-fRv\", approval: deny }\n - { match: \"*/rm *-fvR *\", approval: deny }\n - { match: \"*/rm *-fvR\", approval: deny }\n - { match: \"*/rm *-vRf *\", approval: deny }\n - { match: \"*/rm *-vRf\", approval: deny }\n - { match: \"*/rm *-vfR *\", approval: deny }\n - { match: \"*/rm *-vfR\", approval: deny }\n - { match: \"*/rm *--recursive *\", approval: deny }\n - { match: \"*/rm *--recursive\", approval: deny }\n - { match: \"* rm *-r *\", approval: deny }\n - { match: \"* rm *-r\", approval: deny }\n - { match: \"* rm *-rf *\", approval: deny }\n - { match: \"* rm *-rf\", approval: deny }\n - { match: \"* rm *-fr *\", approval: deny }\n - { match: \"* rm *-fr\", approval: deny }\n - { match: \"* rm *-rv *\", approval: deny }\n - { match: \"* rm *-rv\", approval: deny }\n - { match: \"* rm *-vr *\", approval: deny }\n - { match: \"* rm *-vr\", approval: deny }\n - { match: \"* rm *-rfv *\", approval: deny }\n - { match: \"* rm *-rfv\", approval: deny }\n - { match: \"* rm *-rvf *\", approval: deny }\n - { match: \"* rm *-rvf\", approval: deny }\n - { match: \"* rm *-frv *\", approval: deny }\n - { match: \"* rm *-frv\", approval: deny }\n - { match: \"* rm *-fvr *\", approval: deny }\n - { match: \"* rm *-fvr\", approval: deny }\n - { match: \"* rm *-vrf *\", approval: deny }\n - { match: \"* rm *-vrf\", approval: deny }\n - { match: \"* rm *-vfr *\", approval: deny }\n - { match: \"* rm *-vfr\", approval: deny }\n - { match: \"* rm *-R *\", approval: deny }\n - { match: \"* rm *-R\", approval: deny }\n - { match: \"* rm *-ri *\", approval: deny }\n - { match: \"* rm *-ri\", approval: deny }\n - { match: \"* rm *-ir *\", approval: deny }\n - { match: \"* rm *-ir\", approval: deny }\n - { match: \"* rm *-Ri *\", approval: deny }\n - { match: \"* rm *-Ri\", approval: deny }\n - { match: \"* rm *-iR *\", approval: deny }\n - { match: \"* rm *-iR\", approval: deny }\n - { match: \"* rm *-Rf *\", approval: deny }\n - { match: \"* rm *-Rf\", approval: deny }\n - { match: \"* rm *-fR *\", approval: deny }\n - { match: \"* rm *-fR\", approval: deny }\n - { match: \"* rm *-Rv *\", approval: deny }\n - { match: \"* rm *-Rv\", approval: deny }\n - { match: \"* rm *-vR *\", approval: deny }\n - { match: \"* rm *-vR\", approval: deny }\n - { match: \"* rm *-Rfv *\", approval: deny }\n - { match: \"* rm *-Rfv\", approval: deny }\n - { match: \"* rm *-Rvf *\", approval: deny }\n - { match: \"* rm *-Rvf\", approval: deny }\n - { match: \"* rm *-fRv *\", approval: deny }\n - { match: \"* rm *-fRv\", approval: deny }\n - { match: \"* rm *-fvR *\", approval: deny }\n - { match: \"* rm *-fvR\", approval: deny }\n - { match: \"* rm *-vRf *\", approval: deny }\n - { match: \"* rm *-vRf\", approval: deny }\n - { match: \"* rm *-vfR *\", approval: deny }\n - { match: \"* rm *-vfR\", approval: deny }\n - { match: \"* rm *--recursive *\", approval: deny }\n - { match: \"* rm *--recursive\", approval: deny }\n # Bulk removal: find -delete, find -exec rm, and xargs rm, in every position.\n - { match: \"find *-delete*\", approval: deny }\n - { match: \"*/find *-delete*\", approval: deny }\n - { match: \"* find *-delete*\", approval: deny }\n - { match: \"*-exec rm *\", approval: deny }\n - { match: \"*-exec */rm *\", approval: deny }\n - { match: \"*-execdir rm *\", approval: deny }\n - { match: \"*-execdir */rm *\", approval: deny }\n - { match: \"*-ok rm *\", approval: deny }\n - { match: \"*-ok */rm *\", approval: deny }\n - { match: \"*-okdir rm *\", approval: deny }\n - { match: \"*-okdir */rm *\", approval: deny }\n - { match: \"*xargs rm\", approval: deny }\n - { match: \"*xargs rm *\", approval: deny }\n - { match: \"*xargs * rm\", approval: deny }\n - { match: \"*xargs * rm *\", approval: deny }\n - { match: \"*xargs */rm\", approval: deny }\n - { match: \"*xargs */rm *\", approval: deny }\n - { match: \"HOME=*\", approval: deny }\n - { match: \"export HOME=*\", approval: deny }\n - { match: \"env HOME=*\", approval: deny }\n - { match: \"env * HOME=*\", approval: deny }\n - { match: \"git push --force origin main\", approval: deny }\n - { match: \"git push --force origin main *\", approval: deny }\n - { match: \"git push --force origin master\", approval: deny }\n - { match: \"git push --force origin master *\", approval: deny }\n - { match: \"git push -f origin main\", approval: deny }\n - { match: \"git push -f origin main *\", approval: deny }\n - { match: \"git push -f origin master\", approval: deny }\n - { match: \"git push -f origin master *\", approval: deny }\n # A $ or a backtick anywhere after git push: the matcher reads the text\n # before the shell expands it, so it cannot tell a branch name from +main\n # or --force. An unquoted value inside a word also splits into more words.\n # A deny, not a prompt: the agent reads the refusal and writes the ref\n # literally (git push -u origin HEAD). No person is asked.\n # The leading * also reaches a git push after a shell keyword such as do,\n # after a wrapper such as env, and after a path such as /usr/bin/git.\n - { match: \"*git push *$*\", approval: deny }\n - { match: \"*git push *`*\", approval: deny }\n # Allow: the macOS trash command.\n - { match: \"trash *\", approval: allow }\n",
|
|
21
|
+
"SoT/.omp/config.yml": "statusLine:\n compactThinkingLevel: false\n\ncycleOrder:\n - smol\n - default\n - slow\n - fable\n - astra\n\ngithub:\n enabled: true\n\nfind:\n enabled: true\n\nbrowser:\n idleCloseSec: 600\n\ntask:\n eager: always\n showResolvedModelBadge: true\n enableLsp: true\n maxEffort: xhigh\n maxConcurrency: 16\n maxRuntimeMs: 3600000\n agentIdleTtlMs: 120000\n agentModelOverrides:\n reviewer: \"@reviewer\"\n security-reviewer: \"@reviewer\"\n code-reviewer: \"@reviewer\"\n plan-reviewer: \"@reviewer\"\n agentServiceTierOverrides:\n reviewer: inherit\n security-reviewer: inherit\n code-reviewer: inherit\n plan-reviewer: inherit\n\nmodelRoles:\n smol: openai-codex/gpt-6-luna:medium\n designer: anthropic/claude-opus-5-5:high\n plan: anthropic/claude-opus-5-5:xhigh\n commit: openai-codex/gpt-6-luna:medium\n task: anthropic/claude-opus-5-5:high\n vision: anthropic/claude-opus-5-5:medium\n tiny: openai-codex/gpt-6-luna:low\n default: anthropic/claude-opus-5-5:high\n slow: anthropic/claude-opus-5-5:xhigh\n fable: anthropic/claude-fable-5-2:medium\n switch_fable: anthropic/claude-fable-5-2:medium\n astra: openai-codex/gpt-6-astra:xhigh\n reviewer: openai-codex/gpt-6.1-terra:high\n web: web/firecrawl\n\nmodelTags:\n fable:\n name: Fable 5.2\n switch_fable:\n name: Fable switch default\n hidden: true\n astra:\n name: GPT-6 Astra\n reviewer:\n name: Reviewer\n hidden: true\n\ndisplay:\n showTokenUsage: true\n\nproviders:\n webSearchTimeoutSeconds: 30\n\nretry:\n fallbackChains:\n default:\n - openai-codex/gpt-6.1-sol:high\n task:\n - openai-codex/gpt-6.1-sol:high\n vision:\n - openai-codex/gpt-6.1-sol:medium\n smol:\n - anthropic/claude-opus-5-5:low\n tiny:\n - anthropic/claude-opus-5-5:low\n commit:\n - anthropic/claude-opus-5-5:medium\n switch_fable: []\n fable:\n - openai-codex/gpt-6-astra:xhigh\n astra:\n - anthropic/claude-fable-5-2:medium\n reviewer:\n - anthropic/claude-opus-5-5:high\n web:\n - web/exa\n - web/perplexity\n - openai-codex/gpt-6-luna\n - web/parallel\n - web/zai\n - web/tinyfish\n - web/jina\n - web/kagi\n - web/tavily\n - web/brave\n - web/kimi\n - web/synthetic\n - web/ollama\n - web/searxng\n - web/startpage\n - web/duckduckgo\n - web/ecosia\n - web/google\n - web/mojeek\n - web/public\n\nbranchSummary:\n enabled: true\n\ncommands:\n enableOpencodeProject: false\n\nsteeringMode: all\n\ndev:\n autoqa: false\n autoqaConsent: denied\n\ncompaction:\n idleEnabled: true\n handoffSaveToDisk: true\n\ndoubleEscapeAction: tree\n\nfeatures:\n unexpectedStopDetection: smart\n\ncodexResets:\n autoRedeem5h: \"no\"\n autoRedeemWeekly: \"no\"\n\nstartup:\n quiet: true\n\nbash:\n # First match wins. omp checks deny rules against the whole line and each\n # quote-stripped segment, so `rm -rf \"$HOME\"` matches `rm * $HOME`. `*`\n # matches any text, spaces and slashes included; no escape spells a literal\n # `*`.\n # The kit ships no prompt rule, because a subagent rejects every prompt.\n # A command that no deny rule matches runs under yolo, unless a prompt rule\n # that the user added matches it: a plain rm, git rm, git worktree remove,\n # gio trash, docks-kit scratch remove, git clean, git reset --hard, and\n # every git push that the denies below do not stop.\n # omp's critical-command check turns a prompt into an allow under yolo, so\n # every rm shape it can flag is a deny.\n patterns:\n # Deny: rm of the home directory or the filesystem root, sudo before rm,\n # rm with an r or f option before an absolute path, recursive rm (bare, by\n # path, or after any word such as env, xargs, find -exec, or git), bulk\n # removal through find -delete, find -exec rm, and xargs rm, HOME\n # reassignment, a force push to main or master, and a $ or a backtick\n # after git push.\n - { match: \"rm /\", approval: deny }\n - { match: \"rm / *\", approval: deny }\n - { match: \"rm * /\", approval: deny }\n - { match: \"rm * / *\", approval: deny }\n - { match: \"rm ~\", approval: deny }\n - { match: \"rm ~ *\", approval: deny }\n - { match: \"rm * ~\", approval: deny }\n - { match: \"rm * ~ *\", approval: deny }\n - { match: \"rm ~/\", approval: deny }\n - { match: \"rm ~/ *\", approval: deny }\n - { match: \"rm * ~/\", approval: deny }\n - { match: \"rm * ~/ *\", approval: deny }\n - { match: \"rm $HOME\", approval: deny }\n - { match: \"rm $HOME *\", approval: deny }\n - { match: \"rm * $HOME\", approval: deny }\n - { match: \"rm * $HOME *\", approval: deny }\n - { match: \"rm $HOME/\", approval: deny }\n - { match: \"rm $HOME/ *\", approval: deny }\n - { match: \"rm * $HOME/\", approval: deny }\n - { match: \"rm * $HOME/ *\", approval: deny }\n - { match: \"rm ${HOME}\", approval: deny }\n - { match: \"rm ${HOME} *\", approval: deny }\n - { match: \"rm * ${HOME}\", approval: deny }\n - { match: \"rm * ${HOME} *\", approval: deny }\n - { match: \"rm ${HOME}/\", approval: deny }\n - { match: \"rm ${HOME}/ *\", approval: deny }\n - { match: \"rm * ${HOME}/\", approval: deny }\n - { match: \"rm * ${HOME}/ *\", approval: deny }\n - { match: \"* rm /\", approval: deny }\n - { match: \"* rm / *\", approval: deny }\n - { match: \"* rm * /\", approval: deny }\n - { match: \"* rm * / *\", approval: deny }\n - { match: \"* rm ~\", approval: deny }\n - { match: \"* rm ~ *\", approval: deny }\n - { match: \"* rm * ~\", approval: deny }\n - { match: \"* rm * ~ *\", approval: deny }\n - { match: \"* rm ~/\", approval: deny }\n - { match: \"* rm ~/ *\", approval: deny }\n - { match: \"* rm * ~/\", approval: deny }\n - { match: \"* rm * ~/ *\", approval: deny }\n - { match: \"* rm $HOME\", approval: deny }\n - { match: \"* rm $HOME *\", approval: deny }\n - { match: \"* rm * $HOME\", approval: deny }\n - { match: \"* rm * $HOME *\", approval: deny }\n - { match: \"* rm $HOME/\", approval: deny }\n - { match: \"* rm $HOME/ *\", approval: deny }\n - { match: \"* rm * $HOME/\", approval: deny }\n - { match: \"* rm * $HOME/ *\", approval: deny }\n - { match: \"* rm ${HOME}\", approval: deny }\n - { match: \"* rm ${HOME} *\", approval: deny }\n - { match: \"* rm * ${HOME}\", approval: deny }\n - { match: \"* rm * ${HOME} *\", approval: deny }\n - { match: \"* rm ${HOME}/\", approval: deny }\n - { match: \"* rm ${HOME}/ *\", approval: deny }\n - { match: \"* rm * ${HOME}/\", approval: deny }\n - { match: \"* rm * ${HOME}/ *\", approval: deny }\n - { match: \"*/rm /\", approval: deny }\n - { match: \"*/rm / *\", approval: deny }\n - { match: \"*/rm * /\", approval: deny }\n - { match: \"*/rm * / *\", approval: deny }\n - { match: \"*/rm ~\", approval: deny }\n - { match: \"*/rm ~ *\", approval: deny }\n - { match: \"*/rm * ~\", approval: deny }\n - { match: \"*/rm * ~ *\", approval: deny }\n - { match: \"*/rm ~/\", approval: deny }\n - { match: \"*/rm ~/ *\", approval: deny }\n - { match: \"*/rm * ~/\", approval: deny }\n - { match: \"*/rm * ~/ *\", approval: deny }\n - { match: \"*/rm $HOME\", approval: deny }\n - { match: \"*/rm $HOME *\", approval: deny }\n - { match: \"*/rm * $HOME\", approval: deny }\n - { match: \"*/rm * $HOME *\", approval: deny }\n - { match: \"*/rm $HOME/\", approval: deny }\n - { match: \"*/rm $HOME/ *\", approval: deny }\n - { match: \"*/rm * $HOME/\", approval: deny }\n - { match: \"*/rm * $HOME/ *\", approval: deny }\n - { match: \"*/rm ${HOME}\", approval: deny }\n - { match: \"*/rm ${HOME} *\", approval: deny }\n - { match: \"*/rm * ${HOME}\", approval: deny }\n - { match: \"*/rm * ${HOME} *\", approval: deny }\n - { match: \"*/rm ${HOME}/\", approval: deny }\n - { match: \"*/rm ${HOME}/ *\", approval: deny }\n - { match: \"*/rm * ${HOME}/\", approval: deny }\n - { match: \"*/rm * ${HOME}/ *\", approval: deny }\n - { match: \"sudo rm\", approval: deny }\n - { match: \"sudo rm *\", approval: deny }\n - { match: \"sudo * rm\", approval: deny }\n - { match: \"sudo * rm *\", approval: deny }\n - { match: \"sudo */rm\", approval: deny }\n - { match: \"sudo */rm *\", approval: deny }\n - { match: \"* sudo rm\", approval: deny }\n - { match: \"* sudo rm *\", approval: deny }\n - { match: \"* sudo * rm\", approval: deny }\n - { match: \"* sudo * rm *\", approval: deny }\n - { match: \"* sudo */rm\", approval: deny }\n - { match: \"* sudo */rm *\", approval: deny }\n - { match: \"*/sudo rm\", approval: deny }\n - { match: \"*/sudo rm *\", approval: deny }\n - { match: \"*/sudo * rm\", approval: deny }\n - { match: \"*/sudo * rm *\", approval: deny }\n - { match: \"*/sudo */rm\", approval: deny }\n - { match: \"*/sudo */rm *\", approval: deny }\n - { match: \"rm *-*r* /*\", approval: deny }\n - { match: \"rm *-*R* /*\", approval: deny }\n - { match: \"rm *-*f* /*\", approval: deny }\n - { match: \"rm *-*F* /*\", approval: deny }\n - { match: \"rm *--no-preserve-root*\", approval: deny }\n - { match: \"* rm *-*r* /*\", approval: deny }\n - { match: \"* rm *-*R* /*\", approval: deny }\n - { match: \"* rm *-*f* /*\", approval: deny }\n - { match: \"* rm *-*F* /*\", approval: deny }\n - { match: \"* rm *--no-preserve-root*\", approval: deny }\n - { match: \"*/rm *-*r* /*\", approval: deny }\n - { match: \"*/rm *-*R* /*\", approval: deny }\n - { match: \"*/rm *-*f* /*\", approval: deny }\n - { match: \"*/rm *-*F* /*\", approval: deny }\n - { match: \"*/rm *--no-preserve-root*\", approval: deny }\n - { match: \"rm *-r *\", approval: deny }\n - { match: \"rm *-r\", approval: deny }\n - { match: \"rm *-rf *\", approval: deny }\n - { match: \"rm *-rf\", approval: deny }\n - { match: \"rm *-fr *\", approval: deny }\n - { match: \"rm *-fr\", approval: deny }\n - { match: \"rm *-rv *\", approval: deny }\n - { match: \"rm *-rv\", approval: deny }\n - { match: \"rm *-vr *\", approval: deny }\n - { match: \"rm *-vr\", approval: deny }\n - { match: \"rm *-rfv *\", approval: deny }\n - { match: \"rm *-rfv\", approval: deny }\n - { match: \"rm *-rvf *\", approval: deny }\n - { match: \"rm *-rvf\", approval: deny }\n - { match: \"rm *-frv *\", approval: deny }\n - { match: \"rm *-frv\", approval: deny }\n - { match: \"rm *-fvr *\", approval: deny }\n - { match: \"rm *-fvr\", approval: deny }\n - { match: \"rm *-vrf *\", approval: deny }\n - { match: \"rm *-vrf\", approval: deny }\n - { match: \"rm *-vfr *\", approval: deny }\n - { match: \"rm *-vfr\", approval: deny }\n - { match: \"rm *-ri *\", approval: deny }\n - { match: \"rm *-ri\", approval: deny }\n - { match: \"rm *-ir *\", approval: deny }\n - { match: \"rm *-ir\", approval: deny }\n - { match: \"rm *-Ri *\", approval: deny }\n - { match: \"rm *-Ri\", approval: deny }\n - { match: \"rm *-iR *\", approval: deny }\n - { match: \"rm *-iR\", approval: deny }\n - { match: \"rm *-R *\", approval: deny }\n - { match: \"rm *-R\", approval: deny }\n - { match: \"rm *-Rf *\", approval: deny }\n - { match: \"rm *-Rf\", approval: deny }\n - { match: \"rm *-fR *\", approval: deny }\n - { match: \"rm *-fR\", approval: deny }\n - { match: \"rm *-Rv *\", approval: deny }\n - { match: \"rm *-Rv\", approval: deny }\n - { match: \"rm *-vR *\", approval: deny }\n - { match: \"rm *-vR\", approval: deny }\n - { match: \"rm *-Rfv *\", approval: deny }\n - { match: \"rm *-Rfv\", approval: deny }\n - { match: \"rm *-Rvf *\", approval: deny }\n - { match: \"rm *-Rvf\", approval: deny }\n - { match: \"rm *-fRv *\", approval: deny }\n - { match: \"rm *-fRv\", approval: deny }\n - { match: \"rm *-fvR *\", approval: deny }\n - { match: \"rm *-fvR\", approval: deny }\n - { match: \"rm *-vRf *\", approval: deny }\n - { match: \"rm *-vRf\", approval: deny }\n - { match: \"rm *-vfR *\", approval: deny }\n - { match: \"rm *-vfR\", approval: deny }\n - { match: \"rm *--recursive *\", approval: deny }\n - { match: \"rm *--recursive\", approval: deny }\n - { match: \"*/rm *-r *\", approval: deny }\n - { match: \"*/rm *-r\", approval: deny }\n - { match: \"*/rm *-rf *\", approval: deny }\n - { match: \"*/rm *-rf\", approval: deny }\n - { match: \"*/rm *-fr *\", approval: deny }\n - { match: \"*/rm *-fr\", approval: deny }\n - { match: \"*/rm *-rv *\", approval: deny }\n - { match: \"*/rm *-rv\", approval: deny }\n - { match: \"*/rm *-vr *\", approval: deny }\n - { match: \"*/rm *-vr\", approval: deny }\n - { match: \"*/rm *-rfv *\", approval: deny }\n - { match: \"*/rm *-rfv\", approval: deny }\n - { match: \"*/rm *-rvf *\", approval: deny }\n - { match: \"*/rm *-rvf\", approval: deny }\n - { match: \"*/rm *-frv *\", approval: deny }\n - { match: \"*/rm *-frv\", approval: deny }\n - { match: \"*/rm *-fvr *\", approval: deny }\n - { match: \"*/rm *-fvr\", approval: deny }\n - { match: \"*/rm *-vrf *\", approval: deny }\n - { match: \"*/rm *-vrf\", approval: deny }\n - { match: \"*/rm *-vfr *\", approval: deny }\n - { match: \"*/rm *-vfr\", approval: deny }\n - { match: \"*/rm *-ri *\", approval: deny }\n - { match: \"*/rm *-ri\", approval: deny }\n - { match: \"*/rm *-ir *\", approval: deny }\n - { match: \"*/rm *-ir\", approval: deny }\n - { match: \"*/rm *-Ri *\", approval: deny }\n - { match: \"*/rm *-Ri\", approval: deny }\n - { match: \"*/rm *-iR *\", approval: deny }\n - { match: \"*/rm *-iR\", approval: deny }\n - { match: \"*/rm *-R *\", approval: deny }\n - { match: \"*/rm *-R\", approval: deny }\n - { match: \"*/rm *-Rf *\", approval: deny }\n - { match: \"*/rm *-Rf\", approval: deny }\n - { match: \"*/rm *-fR *\", approval: deny }\n - { match: \"*/rm *-fR\", approval: deny }\n - { match: \"*/rm *-Rv *\", approval: deny }\n - { match: \"*/rm *-Rv\", approval: deny }\n - { match: \"*/rm *-vR *\", approval: deny }\n - { match: \"*/rm *-vR\", approval: deny }\n - { match: \"*/rm *-Rfv *\", approval: deny }\n - { match: \"*/rm *-Rfv\", approval: deny }\n - { match: \"*/rm *-Rvf *\", approval: deny }\n - { match: \"*/rm *-Rvf\", approval: deny }\n - { match: \"*/rm *-fRv *\", approval: deny }\n - { match: \"*/rm *-fRv\", approval: deny }\n - { match: \"*/rm *-fvR *\", approval: deny }\n - { match: \"*/rm *-fvR\", approval: deny }\n - { match: \"*/rm *-vRf *\", approval: deny }\n - { match: \"*/rm *-vRf\", approval: deny }\n - { match: \"*/rm *-vfR *\", approval: deny }\n - { match: \"*/rm *-vfR\", approval: deny }\n - { match: \"*/rm *--recursive *\", approval: deny }\n - { match: \"*/rm *--recursive\", approval: deny }\n - { match: \"* rm *-r *\", approval: deny }\n - { match: \"* rm *-r\", approval: deny }\n - { match: \"* rm *-rf *\", approval: deny }\n - { match: \"* rm *-rf\", approval: deny }\n - { match: \"* rm *-fr *\", approval: deny }\n - { match: \"* rm *-fr\", approval: deny }\n - { match: \"* rm *-rv *\", approval: deny }\n - { match: \"* rm *-rv\", approval: deny }\n - { match: \"* rm *-vr *\", approval: deny }\n - { match: \"* rm *-vr\", approval: deny }\n - { match: \"* rm *-rfv *\", approval: deny }\n - { match: \"* rm *-rfv\", approval: deny }\n - { match: \"* rm *-rvf *\", approval: deny }\n - { match: \"* rm *-rvf\", approval: deny }\n - { match: \"* rm *-frv *\", approval: deny }\n - { match: \"* rm *-frv\", approval: deny }\n - { match: \"* rm *-fvr *\", approval: deny }\n - { match: \"* rm *-fvr\", approval: deny }\n - { match: \"* rm *-vrf *\", approval: deny }\n - { match: \"* rm *-vrf\", approval: deny }\n - { match: \"* rm *-vfr *\", approval: deny }\n - { match: \"* rm *-vfr\", approval: deny }\n - { match: \"* rm *-R *\", approval: deny }\n - { match: \"* rm *-R\", approval: deny }\n - { match: \"* rm *-ri *\", approval: deny }\n - { match: \"* rm *-ri\", approval: deny }\n - { match: \"* rm *-ir *\", approval: deny }\n - { match: \"* rm *-ir\", approval: deny }\n - { match: \"* rm *-Ri *\", approval: deny }\n - { match: \"* rm *-Ri\", approval: deny }\n - { match: \"* rm *-iR *\", approval: deny }\n - { match: \"* rm *-iR\", approval: deny }\n - { match: \"* rm *-Rf *\", approval: deny }\n - { match: \"* rm *-Rf\", approval: deny }\n - { match: \"* rm *-fR *\", approval: deny }\n - { match: \"* rm *-fR\", approval: deny }\n - { match: \"* rm *-Rv *\", approval: deny }\n - { match: \"* rm *-Rv\", approval: deny }\n - { match: \"* rm *-vR *\", approval: deny }\n - { match: \"* rm *-vR\", approval: deny }\n - { match: \"* rm *-Rfv *\", approval: deny }\n - { match: \"* rm *-Rfv\", approval: deny }\n - { match: \"* rm *-Rvf *\", approval: deny }\n - { match: \"* rm *-Rvf\", approval: deny }\n - { match: \"* rm *-fRv *\", approval: deny }\n - { match: \"* rm *-fRv\", approval: deny }\n - { match: \"* rm *-fvR *\", approval: deny }\n - { match: \"* rm *-fvR\", approval: deny }\n - { match: \"* rm *-vRf *\", approval: deny }\n - { match: \"* rm *-vRf\", approval: deny }\n - { match: \"* rm *-vfR *\", approval: deny }\n - { match: \"* rm *-vfR\", approval: deny }\n - { match: \"* rm *--recursive *\", approval: deny }\n - { match: \"* rm *--recursive\", approval: deny }\n # Bulk removal: find -delete, find -exec rm, and xargs rm, in every position.\n - { match: \"find *-delete*\", approval: deny }\n - { match: \"*/find *-delete*\", approval: deny }\n - { match: \"* find *-delete*\", approval: deny }\n - { match: \"*-exec rm *\", approval: deny }\n - { match: \"*-exec */rm *\", approval: deny }\n - { match: \"*-execdir rm *\", approval: deny }\n - { match: \"*-execdir */rm *\", approval: deny }\n - { match: \"*-ok rm *\", approval: deny }\n - { match: \"*-ok */rm *\", approval: deny }\n - { match: \"*-okdir rm *\", approval: deny }\n - { match: \"*-okdir */rm *\", approval: deny }\n - { match: \"*xargs rm\", approval: deny }\n - { match: \"*xargs rm *\", approval: deny }\n - { match: \"*xargs * rm\", approval: deny }\n - { match: \"*xargs * rm *\", approval: deny }\n - { match: \"*xargs */rm\", approval: deny }\n - { match: \"*xargs */rm *\", approval: deny }\n - { match: \"HOME=*\", approval: deny }\n - { match: \"export HOME=*\", approval: deny }\n - { match: \"env HOME=*\", approval: deny }\n - { match: \"env * HOME=*\", approval: deny }\n - { match: \"git push --force origin main\", approval: deny }\n - { match: \"git push --force origin main *\", approval: deny }\n - { match: \"git push --force origin master\", approval: deny }\n - { match: \"git push --force origin master *\", approval: deny }\n - { match: \"git push -f origin main\", approval: deny }\n - { match: \"git push -f origin main *\", approval: deny }\n - { match: \"git push -f origin master\", approval: deny }\n - { match: \"git push -f origin master *\", approval: deny }\n # A $ or a backtick anywhere after git push: the matcher reads the text\n # before the shell expands it, so it cannot tell a branch name from +main\n # or --force. An unquoted value inside a word also splits into more words.\n # A deny, not a prompt: the agent reads the refusal and writes the ref\n # literally (git push -u origin HEAD). No person is asked.\n # The leading * also reaches a git push after a shell keyword such as do,\n # after a wrapper such as env, and after a path such as /usr/bin/git.\n - { match: \"*git push *$*\", approval: deny }\n - { match: \"*git push *`*\", approval: deny }\n # Allow: the macOS trash command.\n - { match: \"trash *\", approval: allow }\n",
|
|
22
22
|
"SoT/.omp/intercom.json": "{\n \"brokerCommand\": \"bun\",\n \"brokerArgs\": []\n}\n",
|
|
23
23
|
"SoT/.omp/mcp.json": "{\n \"$schema\": \"https://raw.githubusercontent.com/can1357/oh-my-pi/main/packages/coding-agent/src/config/mcp-schema.json\",\n \"disabledServers\": [\n \"chrome-devtools\",\n \"context7:context7\",\n \"openaiDeveloperDocs\"\n ]\n}\n",
|
|
24
24
|
"SoT/.omp/models.yml": "providers:\n openai-codex:\n modelOverrides:\n gpt-6-astra:\n thinking:\n mode: effort\n efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n defaultLevel: xhigh\n",
|
|
25
25
|
"SoT/.omp/plugin/package.json": "{\n \"name\": \"docks-kit-omp\",\n \"version\": \"0.0.0\",\n \"private\": true,\n \"type\": \"module\",\n \"description\": \"docks-kit integration for omp: workspace hygiene tools, reminders, the automatic tidy sweep, and plugin upgrade reminders\",\n \"omp\": { \"extensions\": [\"./extensions/hygiene.ts\", \"./extensions/pluginUpgrades.ts\"] }\n}\n",
|
|
26
|
-
"SoT/.omp/plugin/extensions/hygiene.ts": "/**\n * docks-kit-omp extension: workspace hygiene for omp sessions.\n *\n * - The tools scratch_new, scratch_remove, and tidy_report run docks-kit.\n * - The tool_result handler records each resource that a bash command\n * creates, and it adds a reminder that names the cleanup command.\n * - The session_stop handler lists the recorded resources that still exist.\n * - The session_start handler of a main session starts `docks-kit tidy --apply`\n * in the background, at most one time in each sweep interval. When the\n * sweep cannot start, the next tool result of the main session tells why.\n *\n * The module imports only node: modules, so omp loads it without a package\n * install. No subprocess uses a command interpreter, so a tool argument never\n * gets to a shell.\n */\nimport { execFile, spawn } from \"node:child_process\";\nimport { randomBytes, randomUUID } from \"node:crypto\";\nimport {\n accessSync,\n chmodSync,\n closeSync,\n constants,\n existsSync,\n mkdirSync,\n openSync,\n readdirSync,\n readFileSync,\n statSync,\n unlinkSync,\n utimesSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, isAbsolute, join, posix, resolve, win32 } from \"node:path\";\n\n// ------------------------------------------------------------- constants ----\n\nconst SWEEP_INTERVAL_MS = 12 * 60 * 60 * 1000;\nconst CLAIM_STALE_MS = 60 * 1000;\nconst STAMP_FILE = \"tidy.stamp\";\nconst CLAIM_FILE = \"tidy.stamp.claim\";\nconst TAKEOVER_FILE = \"tidy.stamp.takeover\";\nconst DOCKER_CHECK_TIMEOUT_MS = 5000;\nconst SCRATCH_TIMEOUT_MS = 60_000;\nconst REPORT_TIMEOUT_MS = 120_000;\nconst OUTPUT_LIMIT_BYTES = 16 * 1024 * 1024;\nconst COMMAND_TEXT_LIMIT = 120;\nconst LABEL_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;\nconst LABEL_ERROR = \"label must match ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$\";\nconst NOT_ON_PATH = \"docks-kit is not on PATH; install docks-kit and run docks-kit sync omp\";\n\n/**\n * A bash command that does not match this pattern creates no tracked\n * resource. Each detection rule below has a word in this pattern.\n */\nconst TRIGGER =\n /worktree\\s+add|compose|docker|scratch\\s+new|mktemp|nohup|setsid|disown|&|tmux|screen|ngrok|cloudflared|port-forward|ssh|cluster|minikube|multipass|limactl|machine|colima|crontab|\\bat\\b|systemctl|systemd-run|launchctl|install|(?:^|\\s)-g(?:\\s|$)|global|branches|branch\\s+create|vercel|netlify|wrangler|fly\\s|fork|codespace|stash/;\n\n/** The scope of the top-level command; a subshell scope extends it with `/<n>`. */\nconst ROOT_SCOPE = \"0\";\n\nconst UNRESOLVED = /[$`*]/;\nconst ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;\nconst VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst REDIRECT_OPERATOR = /^(?:\\d+|&)?(?:<<<|<<-?|>>|>&|<&|>\\||<>|>|<)$/;\nconst ATTACHED_REDIRECT = /^(?:\\d+|&)?[<>]/;\n/**\n * A word that is one redirection of the standard error alone: `2>&1`, `2>&-`,\n * `2>file`, `2>>file`, or the operator `2>` before its target. A second `<`\n * or `>` in the word is a second redirection. The segment parser splits\n * `2>|file` at the `|`, so that form gives the generic note.\n */\nconst STDERR_REDIRECT = /^2(?:>&(?:\\d+|-)|>>?[^<>]*)$/;\nconst SHORT_CLUSTER_WITH_D = /^-[A-Za-z]*d[A-Za-z]*$/;\n/** The long options of GNU mktemp, which also accepts a unique prefix of each. */\nconst MKTEMP_LONG_OPTIONS: ReadonlyArray<string> = [\n \"--directory\",\n \"--dry-run\",\n \"--quiet\",\n \"--suffix\",\n \"--tmpdir\",\n \"--help\",\n \"--version\",\n];\nconst CONTAINER_ID = /^[0-9a-f]{64}$/;\nconst SAFE_WORD = /^[A-Za-z0-9_/.:@%+=,-]+$/;\nconst RESERVED_WORDS: Record<string, true> = {\n \"{\": true,\n \"}\": true,\n \"!\": true,\n if: true,\n then: true,\n else: true,\n elif: true,\n do: true,\n while: true,\n until: true,\n time: true,\n};\n/**\n * Reserved words of a conditional, a loop, or a function body, where a\n * command may run once, many times, or never. The list holds the closing\n * words too, because a segment can start with one of them.\n */\nconst COMPOUND_WORDS: Record<string, true> = {\n if: true,\n then: true,\n else: true,\n elif: true,\n fi: true,\n for: true,\n select: true,\n while: true,\n until: true,\n do: true,\n done: true,\n case: true,\n esac: true,\n function: true,\n coproc: true,\n};\n/** A shell function name, as in `name()` or `name ()`. */\nconst FUNCTION_NAME = /^[A-Za-z_][A-Za-z0-9_.:-]*$/;\n\nconst GIT_VALUE_OPTIONS: Record<string, true> = { \"-C\": true, \"-c\": true };\nconst WORKTREE_VALUE_OPTIONS: Record<string, true> = { \"-b\": true, \"-B\": true, \"--reason\": true };\n/** Docker global options that select the daemon, mapped to their long names. */\nconst DOCKER_CONNECTION_VALUE_OPTIONS: Record<string, string> = {\n \"-c\": \"--context\",\n \"--context\": \"--context\",\n \"-H\": \"--host\",\n \"--host\": \"--host\",\n \"--config\": \"--config\",\n \"--tlscacert\": \"--tlscacert\",\n \"--tlscert\": \"--tlscert\",\n \"--tlskey\": \"--tlskey\",\n};\nconst DOCKER_CONNECTION_FLAGS: Record<string, true> = { \"--tls\": true, \"--tlsverify\": true };\nconst DOCKER_LOG_LEVEL_OPTIONS: Record<string, true> = { \"-l\": true, \"--log-level\": true };\n/** Environment variables that select the Docker daemon. */\nconst DOCKER_ENVIRONMENT: Record<string, true> = {\n DOCKER_HOST: true,\n DOCKER_CONTEXT: true,\n DOCKER_CONFIG: true,\n DOCKER_TLS_VERIFY: true,\n DOCKER_CERT_PATH: true,\n};\n/** Builtins that declare shell variables, with options and `NAME=value` words. */\nconst DECLARATION_COMMANDS: Record<string, true> = {\n declare: true,\n typeset: true,\n local: true,\n readonly: true,\n};\n/** Builtins that run shell code that detection does not read. */\nconst SHELL_CODE_COMMANDS: Record<string, true> = { eval: true, source: true, \".\": true };\nconst COMPOSE_VALUE_OPTIONS: Record<string, true> = {\n \"-f\": true,\n \"--file\": true,\n \"-p\": true,\n \"--project-name\": true,\n \"--project-directory\": true,\n \"--env-file\": true,\n \"--profile\": true,\n \"--ansi\": true,\n \"--progress\": true,\n};\nconst SSH_VALUE_FLAGS = \"BbcDEeFIiJLlmOoPpQRSWw\";\nconst STASH_WITHOUT_ENTRY: Record<string, true> = {\n list: true,\n show: true,\n pop: true,\n apply: true,\n drop: true,\n clear: true,\n branch: true,\n};\n\nconst RM_NOTE = \"Add `--rm` to `docker run` so that Docker removes the container when it stops.\";\nconst SCRATCH_NOTE =\n \"Create temporary files and directories inside a directory from the `scratch_new` tool or `docks-kit scratch new <label>`, not in `/tmp`.\";\nconst KEEP_SENTENCE =\n \"Remove each resource that the task no longer needs. Keep a resource only when the user asked for it or a later step needs it, and name it with the reason in your final answer. Never stop or delete a production resource without an ask in the main session.\";\n\ninterface OtherRule {\n readonly category: string;\n readonly hint: string;\n}\n\nconst BACKGROUND: OtherRule = {\n category: \"background process\",\n hint: \"Stop it before your final answer, or start it as a named bash service.\",\n};\nconst TERMINAL: OtherRule = {\n category: \"detached terminal session\",\n hint: \"Kill the session when the task no longer needs it.\",\n};\nconst TUNNEL: OtherRule = {\n category: \"tunnel\",\n hint: \"Stop the tunnel when the task no longer needs it.\",\n};\nconst CLUSTER: OtherRule = {\n category: \"cluster or virtual machine\",\n hint: \"Stop or delete it with the same tool when the task no longer needs it.\",\n};\nconst DOCKER_RESOURCE: OtherRule = {\n category: \"Docker resource\",\n hint: \"Remove it with docker volume rm, docker network rm, or docker buildx rm when the task no longer needs it.\",\n};\nconst SCHEDULED: OtherRule = {\n category: \"scheduled job or service\",\n hint: \"Remove the entry or unit that you added, or name it in your final answer.\",\n};\nconst GLOBAL_INSTALL: OtherRule = {\n category: \"global install\",\n hint: \"Uninstall it unless the user asked for it.\",\n};\nconst REMOTE: OtherRule = {\n category: \"remote resource\",\n hint: \"Delete it with the provider's command only when its target is local, development, dev, test, homolog, homologation, staging, or preview, and the task no longer needs it. For a production target, ask the user first. If you do not delete it, name it in your final answer.\",\n};\nconst STASH: OtherRule = {\n category: \"git stash\",\n hint: \"Apply the stash, or name it in your final answer.\",\n};\n\nconst CLUSTER_COMMANDS: ReadonlyArray<ReadonlyArray<string>> = [\n [\"kind\", \"create\", \"cluster\"],\n [\"k3d\", \"cluster\", \"create\"],\n [\"minikube\", \"start\"],\n [\"multipass\", \"launch\"],\n [\"limactl\", \"start\"],\n [\"podman\", \"machine\", \"start\"],\n [\"colima\", \"start\"],\n];\nconst REMOTE_COMMANDS: ReadonlyArray<ReadonlyArray<string>> = [\n [\"supabase\", \"branches\", \"create\"],\n [\"neonctl\", \"branches\", \"create\"],\n [\"pscale\", \"branch\", \"create\"],\n [\"netlify\", \"deploy\"],\n [\"wrangler\", \"deploy\"],\n [\"fly\", \"deploy\"],\n [\"fly\", \"launch\"],\n [\"gh\", \"repo\", \"fork\"],\n [\"gh\", \"codespace\", \"create\"],\n];\n\n// ----------------------------------------------------------------- types ----\n\n/**\n * The Docker daemon that a command used: the `DOCKER_*` environment variables\n * and the global options before the subcommand. An empty target is the\n * default daemon of the omp process.\n */\nexport interface DockerTarget {\n environment: Record<string, string>;\n options: Array<string>;\n}\n\nexport type HygieneResource =\n | { kind: \"worktree\"; path: string }\n | { kind: \"compose\"; workingDir: string; down: string; docker: DockerTarget }\n | { kind: \"container\"; id: string; down: string; docker: DockerTarget }\n | { kind: \"scratch\"; path: string }\n | { kind: \"tempDir\"; path: string }\n | { kind: \"tempFile\"; path: string }\n | { kind: \"other\"; category: string; command: string; hint: string };\n\ntype PathResource = Exclude<HygieneResource, { kind: \"other\" }>;\n\nexport interface ShellSegment {\n words: Array<string>;\n background: boolean;\n}\n\n/** The operator between two segments of one parse level; a newline counts as `;`. */\ntype Separator = \";\" | \"&&\" | \"||\" | \"|\" | \"&\";\n\n/** A segment with its subshell scope. A `cd` changes only its own scope. */\ninterface ScopedSegment extends ShellSegment {\n scope: string;\n /**\n * False when the control syntax of the segment's parse level can skip a\n * setup command (`cd`, `pushd`, `export`, `unset`) or run it in a subshell\n * while a later command still runs. See setupStateKnown.\n */\n setupKnown: boolean;\n}\n\nexport interface RunOptions {\n readonly signal?: AbortSignal;\n readonly timeoutMs: number;\n readonly env?: NodeJS.ProcessEnv;\n}\n\nexport interface RunResult {\n /** The exit code, or null when a signal or the timeout stopped the process. */\n readonly code: number | null;\n readonly stdout: string;\n readonly stderr: string;\n}\n\n// The local structural types below name only the omp extension API parts\n// that this module uses. The module does not import @oh-my-pi packages.\n\ninterface TextContent {\n readonly type: string;\n readonly text?: string;\n}\n\ninterface ExtensionContext {\n readonly cwd: string;\n readonly agent?: { readonly kind: \"main\" | \"sub\" };\n}\n\ninterface ToolResultEvent {\n readonly toolName: string;\n readonly input?: Readonly<Record<string, unknown>>;\n readonly content?: ReadonlyArray<TextContent>;\n readonly isError?: boolean;\n}\n\ninterface SessionStopEvent {\n readonly stop_hook_active?: boolean;\n}\n\ninterface Schema {\n describe(description: string): Schema;\n}\n\ninterface SchemaBuilder {\n object(shape: Record<string, Schema>): Schema;\n string(): Schema;\n array(item: Schema): Schema;\n}\n\ninterface ToolResult {\n content: Array<{ type: \"text\"; text: string }>;\n details: Record<string, unknown>;\n}\n\ninterface ToolDefinition<Params> {\n name: string;\n label: string;\n description: string;\n parameters: Schema;\n execute(\n toolCallId: string,\n params: Params,\n signal: AbortSignal | undefined,\n onUpdate: unknown,\n ctx: ExtensionContext,\n ): Promise<ToolResult>;\n}\n\nexport interface ExtensionApi {\n readonly zod: SchemaBuilder;\n on(\n event: \"tool_result\",\n handler: (\n event: ToolResultEvent,\n ctx: ExtensionContext,\n ) => Promise<{ additionalContext: string } | undefined>,\n ): void;\n on(\n event: \"session_stop\",\n handler: (\n event: SessionStopEvent,\n ctx: ExtensionContext,\n ) => Promise<{ continue: true; additionalContext: string } | undefined>,\n ): void;\n on(\n event: \"session_start\",\n handler: (event: unknown, ctx: ExtensionContext) => Promise<undefined>,\n ): void;\n registerTool<Params>(definition: ToolDefinition<Params>): void;\n}\n\n// ------------------------------------------------------------ subprocess ----\n\n/**\n * Runs `command` with `args` through execFile without a shell. Each argument\n * gets to the child as one literal argv entry. A non-zero exit, a signal, or\n * the timeout resolves; a spawn failure or an abort rejects.\n */\nexport function run(\n command: string,\n args: ReadonlyArray<string>,\n options: RunOptions,\n): Promise<RunResult> {\n const { promise, resolve: resolveRun, reject: rejectRun } = Promise.withResolvers<RunResult>();\n execFile(\n command,\n [...args],\n {\n encoding: \"utf8\",\n env: options.env,\n maxBuffer: OUTPUT_LIMIT_BYTES,\n shell: false,\n signal: options.signal,\n timeout: options.timeoutMs,\n windowsHide: true,\n },\n (error, stdout, stderr) => {\n if (error === null) resolveRun({ code: 0, stdout, stderr });\n else if (typeof error.code === \"number\") resolveRun({ code: error.code, stdout, stderr });\n else if (\n error.name !== \"AbortError\" &&\n (error.killed === true || (error.signal ?? null) !== null)\n ) {\n resolveRun({ code: null, stdout, stderr });\n } else rejectRun(error);\n },\n );\n return promise;\n}\n\n/**\n * Finds docks-kit on PATH. Windows accepts only `docks-kit.exe`, because\n * execFile without a shell cannot start a `.cmd` or `.bat` shim. A relative\n * PATH entry is skipped.\n */\nexport function resolveDocksKit(\n env: NodeJS.ProcessEnv = process.env,\n platform: NodeJS.Platform = process.platform,\n): string {\n const windows = platform === \"win32\";\n const paths = windows ? win32 : posix;\n const searchPath = env[\"PATH\"] ?? env[\"Path\"] ?? \"\";\n for (const entry of searchPath.split(windows ? \";\" : \":\")) {\n const directory = entry.replace(/^\"(.*)\"$/, \"$1\");\n if (directory === \"\" || !paths.isAbsolute(directory)) continue;\n const candidate = paths.join(directory, windows ? \"docks-kit.exe\" : \"docks-kit\");\n if (isRunnableFile(candidate, windows)) return candidate;\n }\n throw new Error(NOT_ON_PATH);\n}\n\nfunction isRunnableFile(path: string, windows: boolean): boolean {\n try {\n if (!statSync(path).isFile()) return false;\n if (!windows) accessSync(path, constants.X_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction errorCode(error: unknown): unknown {\n return typeof error === \"object\" && error !== null && \"code\" in error ? error.code : undefined;\n}\n\nfunction toError(error: unknown): Error {\n if (errorCode(error) === \"ENOENT\") return new Error(NOT_ON_PATH);\n return error instanceof Error ? error : new Error(String(error));\n}\n\nasync function runDocksKit(\n args: ReadonlyArray<string>,\n signal: AbortSignal | undefined,\n timeoutMs: number,\n): Promise<string> {\n const result = await run(resolveDocksKit(), args, { signal, timeoutMs });\n const output = [result.stdout.trim(), result.stderr.trim()].filter((text) => text !== \"\");\n if (result.code === 0) return result.stdout;\n const status = result.code === null ? \"was stopped\" : `exited with code ${result.code}`;\n throw new Error(output.length > 0 ? output.join(\"\\n\") : `docks-kit ${args.join(\" \")} ${status}`);\n}\n\n// --------------------------------------------------------- shell parsing ----\n\n/**\n * Splits a bash command into simple-command segments. This is a minimal\n * tokenizer: it removes single quotes, double quotes, and backslash escapes,\n * and it splits on `&&`, `||`, `;`, `|`, `&`, parentheses, and newlines.\n * `background` is true when a single `&` ended the segment. The command of a\n * `$(...)` or backtick substitution becomes a segment before its container.\n * A heredoc body is skipped.\n */\nexport function splitShellSegments(command: string): Array<ShellSegment> {\n return scopedSegments(command, ROOT_SCOPE).map(({ words, background }) => ({\n words,\n background,\n }));\n}\n\n/**\n * Does the work of splitShellSegments, and gives each segment its subshell\n * scope. A `( ... )` group, a `$( ... )` substitution, and a backtick\n * substitution each get a new scope `<parent>/<n>`. A `{ ...; }` group stays\n * in the scope around it, as in bash.\n *\n * Each call parses one level: the command, or the text of one substitution.\n * It stamps the segments of its level with setupStateKnown for the control\n * syntax of that level.\n */\nfunction scopedSegments(command: string, rootScope: string): Array<ScopedSegment> {\n const segments: Array<ScopedSegment> = [];\n const nested: Array<ScopedSegment> = [];\n const ownSegments: Array<ScopedSegment> = [];\n const separators = new Set<Separator>();\n const heredocs: Array<{ delimiter: string; strip: boolean }> = [];\n const scopes = [rootScope];\n let childScopes = 0;\n let words: Array<string> = [];\n let word = \"\";\n let inWord = false;\n /** True when the current word holds a quoted or escaped character. */\n let wordQuoted = false;\n /** The source index of the last character that the word took without quoting. */\n let lastUnquoted = -1;\n /** The strip flag of a `<<` operator whose delimiter is the next word. */\n let heredocOperator: boolean | undefined;\n /** The operators after the last segment; they count only when a segment follows. */\n const pendingSeparators = new Set<Separator>();\n let skipsCommands = false;\n\n const currentScope = (): string => scopes.at(-1) ?? rootScope;\n const childScope = (): string => `${currentScope()}/${childScopes++}`;\n const finishWord = (): void => {\n if (!inWord) return;\n if (heredocOperator !== undefined) {\n heredocs.push({ delimiter: word, strip: heredocOperator });\n heredocOperator = undefined;\n } else if (!word.includes(\"<<<\")) {\n const match = /^\\d*<<(-?)(.*)$/.exec(word);\n if (match !== null) {\n const strip = match[1] === \"-\";\n const delimiter = match[2] ?? \"\";\n if (delimiter === \"\") heredocOperator = strip;\n else heredocs.push({ delimiter, strip });\n }\n }\n words.push(word);\n word = \"\";\n inWord = false;\n wordQuoted = false;\n };\n\n /**\n * Ends the current segment. `ending` is the operator that ends it; a `(` or\n * a `)` passes undefined. Every operator between two segments counts, also\n * one that ends an empty segment, so `(true;) || cd` keeps both its `;` and\n * its `||`. An operator before the first segment of the level counts for\n * nothing.\n */\n const finishSegment = (ending: Separator | undefined): void => {\n finishWord();\n segments.push(...nested.splice(0));\n if (words.length > 0) {\n for (const separator of pendingSeparators) separators.add(separator);\n pendingSeparators.clear();\n if (changesControlFlow(words)) skipsCommands = true;\n const segment = {\n words,\n background: ending === \"&\",\n scope: currentScope(),\n setupKnown: true,\n };\n segments.push(segment);\n ownSegments.push(segment);\n }\n if (ending !== undefined && ownSegments.length > 0) pendingSeparators.add(ending);\n words = [];\n };\n\n const readSubstitution = (start: number): number => {\n let depth = 0;\n let openQuote: string | undefined;\n let index = start + 1;\n for (; index < command.length; index++) {\n const char = command[index];\n if (openQuote !== undefined) {\n if (char === \"\\\\\" && openQuote === '\"') index++;\n else if (char === openQuote) openQuote = undefined;\n continue;\n }\n if (char === \"\\\\\") index++;\n else if (char === \"'\" || char === '\"') openQuote = char;\n else if (char === \"(\") depth++;\n else if (char === \")\" && --depth === 0) break;\n }\n nested.push(...scopedSegments(command.slice(start + 2, index), childScope()));\n word += command.slice(start, index + 1);\n inWord = true;\n return index + 1;\n };\n\n const readBacktick = (start: number): number => {\n let index = start + 1;\n while (index < command.length && command[index] !== \"`\") {\n index += command[index] === \"\\\\\" ? 2 : 1;\n }\n nested.push(...scopedSegments(command.slice(start + 1, index), childScope()));\n word += command.slice(start, index + 1);\n inWord = true;\n return index + 1;\n };\n\n const readDoubleQuoted = (start: number): number => {\n let index = start;\n inWord = true;\n while (index < command.length && command[index] !== '\"') {\n const char = command[index];\n const next = command[index + 1];\n if (char === \"\\\\\" && next !== undefined && '\"\\\\$`\\n'.includes(next)) {\n if (next !== \"\\n\") word += next;\n index += 2;\n } else if (char === \"$\" && next === \"(\") {\n index = readSubstitution(index);\n } else if (char === \"`\") {\n index = readBacktick(index);\n } else {\n word += char;\n index++;\n }\n }\n return index + 1;\n };\n\n const skipHeredocBodies = (start: number): number => {\n let index = start;\n for (const { delimiter, strip } of heredocs.splice(0)) {\n while (index < command.length) {\n const newline = command.indexOf(\"\\n\", index);\n const end = newline === -1 ? command.length : newline;\n let line = command.slice(index, end);\n if (line.endsWith(\"\\r\")) line = line.slice(0, -1);\n index = end + 1;\n if ((strip ? line.replace(/^\\t+/, \"\") : line) === delimiter) break;\n }\n }\n heredocOperator = undefined;\n return index;\n };\n\n let index = 0;\n while (index < command.length) {\n const char = command[index] ?? \"\";\n const next = command[index + 1];\n if (char === \"'\") {\n const close = command.indexOf(\"'\", index + 1);\n const end = close === -1 ? command.length : close;\n word += command.slice(index + 1, end);\n inWord = true;\n wordQuoted = true;\n index = end + 1;\n } else if (char === '\"') {\n wordQuoted = true;\n index = readDoubleQuoted(index + 1);\n } else if (char === \"\\\\\") {\n if (next !== undefined && next !== \"\\n\") {\n word += next;\n inWord = true;\n wordQuoted = true;\n }\n index += 2;\n } else if (char === \"$\" && next === \"(\") {\n index = readSubstitution(index);\n } else if (char === \"`\") {\n index = readBacktick(index);\n } else if (char === \" \" || char === \"\\t\" || char === \"\\r\") {\n finishWord();\n index++;\n } else if (char === \"#\" && !inWord) {\n const newline = command.indexOf(\"\\n\", index);\n index = newline === -1 ? command.length : newline;\n } else if (char === \"\\n\") {\n // A line break after `&&`, `||`, or `|` continues the command, so it\n // separates nothing.\n const continues = words.length === 0 && !inWord && pendingSeparators.size > 0;\n finishSegment(continues ? undefined : \";\");\n index = skipHeredocBodies(index + 1);\n } else if (char === \"(\" && !inWord) {\n // `name ()` defines a function: its body runs only when it is called.\n if (definesFunction(words)) skipsCommands = true;\n finishSegment(undefined);\n scopes.push(childScope());\n index++;\n } else if (char === \")\") {\n finishSegment(undefined);\n if (scopes.length > 1) scopes.pop();\n index++;\n } else if (char === \";\") {\n finishSegment(\";\");\n index++;\n } else if (char === \"|\") {\n // In `>|file` the `|` belongs to the redirection; the split stays as it\n // was, but it separates nothing. Only an unquoted `>` directly before\n // the `|` makes a clobber, so `echo '>'|` and `echo \\>|` are pipes.\n const clobber = inWord && command[index - 1] === \">\" && lastUnquoted === index - 1;\n if (clobber) {\n finishSegment(undefined);\n index++;\n } else {\n finishSegment(next === \"|\" ? \"||\" : \"|\");\n index += next === \"|\" || next === \"&\" ? 2 : 1;\n }\n } else if (char === \"&\") {\n if (next === \"&\") {\n finishSegment(\"&&\");\n index += 2;\n } else if (next === \">\" || word.endsWith(\">\") || word.endsWith(\"<\")) {\n // A redirection such as `&>file` or `2>&1`.\n word += char;\n inWord = true;\n index++;\n } else {\n finishSegment(\"&\");\n index++;\n }\n } else {\n // `name()` without a space: an unquoted name word directly before `(`.\n if (char === \"(\" && words.length === 0 && !wordQuoted && FUNCTION_NAME.test(word)) {\n skipsCommands = true;\n }\n word += char;\n inWord = true;\n lastUnquoted = index;\n index++;\n }\n }\n finishSegment(undefined);\n const setupKnown = setupStateKnown(separators, skipsCommands);\n for (const segment of ownSegments) segment.setupKnown = setupKnown;\n return segments;\n}\n\n/**\n * True when each setup command of a parse level runs before every later\n * command of the level. A pure `&&` chain and a pure `;` list qualify. These\n * can skip a setup command, or run it in a subshell, while a later command\n * runs:\n *\n * - `||`, a pipeline, or a background job before a later segment;\n * - `!`, a conditional, a loop, or a function body;\n * - `&&` together with `;` or a newline.\n */\nfunction setupStateKnown(separators: ReadonlySet<Separator>, skipsCommands: boolean): boolean {\n if (skipsCommands) return false;\n if (separators.has(\"||\") || separators.has(\"|\") || separators.has(\"&\")) return false;\n return !(separators.has(\"&&\") && separators.has(\";\"));\n}\n\n/**\n * True when a segment starts or continues a conditional, a loop, or a\n * function body, or negates its status with `!`. A negation lets a `&&` chain\n * go on after a failed command. The scan passes the other leading reserved\n * words, such as `{` and `time`, as commandWords does.\n */\nfunction changesControlFlow(words: ReadonlyArray<string>): boolean {\n for (const word of words) {\n if (word === \"!\" || COMPOUND_WORDS[word] === true) return true;\n if (RESERVED_WORDS[word] !== true) return false;\n }\n return false;\n}\n\n/**\n * True when the words before a `(` define a function, as in `name ()`: one\n * name word. A reserved word before `(` starts a subshell, as in `time (make)`.\n */\nfunction definesFunction(words: ReadonlyArray<string>): boolean {\n const name = words.length === 1 ? words[0] : undefined;\n return name !== undefined && RESERVED_WORDS[name] !== true && FUNCTION_NAME.test(name);\n}\n\n/**\n * Removes redirections and leading reserved words, then splits off the\n * `NAME=value` words before the command, also after an `env`. The first of\n * the returned words is the command name. The words are empty when `sudo`\n * or an `env` option hides the command, its directory, or its Docker daemon.\n * `assignsShell` is true when the segment has only `NAME=value` words, which\n * then set shell variables.\n */\nfunction commandWords(segmentWords: ReadonlyArray<string>): {\n assignments: Array<string>;\n words: Array<string>;\n assignsShell: boolean;\n} {\n const result: Array<string> = [];\n for (let index = 0; index < segmentWords.length; index++) {\n const word = segmentWords[index] ?? \"\";\n if (REDIRECT_OPERATOR.test(word)) {\n index++;\n continue;\n }\n if (ATTACHED_REDIRECT.test(word)) continue;\n result.push(word);\n }\n const assignments: Array<string> = [];\n let start = 0;\n while (RESERVED_WORDS[result[start] ?? \"\"] === true) start++;\n while (ASSIGNMENT.test(result[start] ?? \"\")) assignments.push(result[start++] ?? \"\");\n if (start === result.length) return { assignments, words: [], assignsShell: true };\n // A command under sudo runs as another user, in an environment and a\n // directory that the sudoers policy controls, so it records nothing.\n if (result[start] === \"sudo\") return { assignments, words: [], assignsShell: false };\n if (result[start] === \"env\") {\n start++;\n // `env -u NAME` keeps the command and its directory when NAME is a literal\n // name that does not select the daemon. Another option can run another\n // program (`env -S`), change the directory (`env -C`), or clear the\n // environment (`env -i`), and `env -u DOCKER_HOST` or `env -u \"$name\"`\n // can change the daemon, so the command records nothing.\n while ((result[start] ?? \"\").startsWith(\"-\")) {\n const option = result[start] ?? \"\";\n if (option === \"--\") {\n start++;\n break;\n }\n const name = result[start + 1] ?? \"\";\n const keepsDaemon = VARIABLE_NAME.test(name) && DOCKER_ENVIRONMENT[name] !== true;\n if ((option !== \"-u\" && option !== \"--unset\") || !keepsDaemon) {\n return { assignments, words: [], assignsShell: false };\n }\n start += 2;\n }\n }\n while (ASSIGNMENT.test(result[start] ?? \"\")) assignments.push(result[start++] ?? \"\");\n return { assignments, words: result.slice(start), assignsShell: false };\n}\n\n/** Applies the `DOCKER_*=value` words of `assignments` to a copy of `environment`. */\nfunction dockerEnvironment(\n environment: Readonly<Record<string, string>>,\n assignments: ReadonlyArray<string>,\n): Record<string, string> {\n const result = { ...environment };\n for (const assignment of assignments) {\n if (!ASSIGNMENT.test(assignment)) continue;\n const equals = assignment.indexOf(\"=\");\n const variable = assignment.slice(0, equals);\n if (DOCKER_ENVIRONMENT[variable] === true) result[variable] = assignment.slice(equals + 1);\n }\n return result;\n}\n\n/**\n * The Docker environment after an `export` or an `unset`. When the command may\n * not run, a change makes the environment unknown, because a later command\n * can see either value.\n */\nfunction settledEnvironment(\n segment: ScopedSegment,\n before: Readonly<Record<string, string>> | undefined,\n after: Record<string, string> | undefined,\n): Record<string, string> | undefined {\n if (segment.setupKnown) return after;\n if (before === undefined || after === undefined) return undefined;\n const variables = new Set([...Object.keys(before), ...Object.keys(after)]);\n return [...variables].every((variable) => before[variable] === after[variable])\n ? after\n : undefined;\n}\n\n/** True when the `NAME` or `NAME=value` word names a variable that selects the Docker daemon. */\nfunction namesDaemonVariable(word: string): boolean {\n const equals = word.indexOf(\"=\");\n return DOCKER_ENVIRONMENT[equals < 0 ? word : word.slice(0, equals)] === true;\n}\n\n/**\n * True when detection can apply the `export` arguments: each operand is a\n * literal `NAME=value`, or a literal NAME that does not select the daemon.\n * An option such as `-n`, an operand that is not literal, or a daemon\n * variable without a value can give the daemon a value that detection does\n * not know. For example, `export DOCKER_HOST` exports a shell variable that\n * detection does not track.\n */\nfunction exportIsTracked(args: ReadonlyArray<string>): boolean {\n const operands = args[0] === \"--\" ? args.slice(1) : args;\n return operands.every(\n (word) => ASSIGNMENT.test(word) || (VARIABLE_NAME.test(word) && !namesDaemonVariable(word)),\n );\n}\n\n/**\n * Returns the variables that the `unset` arguments remove, or undefined when\n * detection cannot know them. Only `-v` and literal names keep them known:\n * `unset -f` and `unset -n` act on functions and name references, and\n * `unset \"$name\"` removes a variable that the command does not name.\n */\nfunction unsetVariables(args: ReadonlyArray<string>): ReadonlyArray<string> | undefined {\n let start = 0;\n while (args[start] === \"-v\") start++;\n if (args[start] === \"--\") start++;\n const operands = args.slice(start);\n return operands.every((word) => VARIABLE_NAME.test(word)) ? operands : undefined;\n}\n\n/**\n * True when the `declare`, `typeset`, `local`, or `readonly` arguments keep\n * the daemon variables unchanged: each word is a literal option, a literal\n * NAME, or a literal `NAME=value`, and no word names a daemon variable.\n */\nfunction declarationIsTracked(args: ReadonlyArray<string>): boolean {\n return args.every((word) => {\n if (word.startsWith(\"-\") || word.startsWith(\"+\")) return !UNRESOLVED.test(word);\n return (ASSIGNMENT.test(word) || VARIABLE_NAME.test(word)) && !namesDaemonVariable(word);\n });\n}\n\nfunction quote(word: string): string {\n return SAFE_WORD.test(word) ? word : `'${word.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\n/** Resolves a path word, or returns undefined when the word is not literal. */\nfunction resolvePath(word: string, base: string | undefined, home: string): string | undefined {\n if (UNRESOLVED.test(word)) return undefined;\n if (word === \"~\") return resolve(home);\n if (word.startsWith(\"~/\")) return resolve(home, word.slice(2));\n if (word.startsWith(\"~\")) return undefined;\n if (isAbsolute(word)) return resolve(word);\n return base === undefined ? undefined : resolve(base, word);\n}\n\nfunction changeDirectory(\n args: ReadonlyArray<string>,\n directory: string | undefined,\n home: string,\n): string | undefined {\n const target = args.find((word) => word === \"-\" || !word.startsWith(\"-\"));\n if (target === undefined) return resolve(home);\n if (target === \"-\") return undefined;\n return resolvePath(target, directory, home);\n}\n\nfunction lastAbsoluteLine(output: string): string | undefined {\n return output\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line !== \"\" && isAbsolute(line))\n .pop();\n}\n\n/** True when `sequence` occurs in `words` in order, with other words between. */\nfunction containsInOrder(words: ReadonlyArray<string>, sequence: ReadonlyArray<string>): boolean {\n let position = 0;\n for (const word of words) {\n if (word === sequence[position]) position++;\n if (position === sequence.length) return true;\n }\n return sequence.length === 0;\n}\n\nfunction matchesCommand(\n name: string,\n words: ReadonlyArray<string>,\n pattern: ReadonlyArray<string>,\n): boolean {\n return name === pattern[0] && containsInOrder(words.slice(1), pattern.slice(1));\n}\n\n/** Skips git global options and returns the effective directory and arguments. */\nfunction gitArguments(\n words: ReadonlyArray<string>,\n directory: string | undefined,\n home: string,\n): { directory: string | undefined; args: Array<string> } {\n let current = directory;\n let index = 1;\n while (index < words.length) {\n const word = words[index] ?? \"\";\n if (GIT_VALUE_OPTIONS[word] === true) {\n const value = words[index + 1];\n if (word === \"-C\")\n current = value === undefined ? undefined : resolvePath(value, current, home);\n index += 2;\n } else if (word.startsWith(\"-\")) {\n index++;\n } else {\n break;\n }\n }\n return { directory: current, args: words.slice(index) };\n}\n\n/**\n * Reads a docker command: the daemon target and the arguments after the\n * global options. `target` is undefined when the Docker environment is\n * unknown or a value of the target is not literal. Returns undefined for a\n * command that is not docker.\n */\nfunction dockerCommand(\n name: string,\n words: ReadonlyArray<string>,\n environment: Readonly<Record<string, string>> | undefined,\n): { target: DockerTarget | undefined; args: Array<string> } | undefined {\n if (name !== \"docker\" && name !== \"docker-compose\") return undefined;\n const target: DockerTarget = { environment: {}, options: [] };\n let literal = environment !== undefined;\n for (const [variable, value] of Object.entries(environment ?? {})) {\n if (value === \"\") continue;\n if (UNRESOLVED.test(value)) literal = false;\n target.environment[variable] = value;\n }\n if (name === \"docker-compose\") {\n return { target: literal ? target : undefined, args: [\"compose\", ...words.slice(1)] };\n }\n\n let index = 1;\n while (index < words.length && (words[index] ?? \"\").startsWith(\"-\")) {\n const word = words[index] ?? \"\";\n const equals = word.indexOf(\"=\");\n const option = equals > 0 ? word.slice(0, equals) : word;\n const longName = DOCKER_CONNECTION_VALUE_OPTIONS[option];\n if (longName !== undefined) {\n const value = equals > 0 ? word.slice(equals + 1) : words[index + 1];\n index += equals > 0 ? 1 : 2;\n if (value === undefined) break;\n if (UNRESOLVED.test(value)) literal = false;\n target.options.push(longName, value);\n } else {\n if (DOCKER_CONNECTION_FLAGS[option] === true) target.options.push(word);\n index += DOCKER_LOG_LEVEL_OPTIONS[option] === true && equals < 0 ? 2 : 1;\n }\n }\n return { target: literal ? target : undefined, args: words.slice(index) };\n}\n\n/** The docker command prefix that reaches `target`, for a cleanup command. */\nfunction dockerPrefix(target: DockerTarget): string {\n return [\n ...Object.entries(target.environment).map(([variable, value]) => `${variable}=${quote(value)}`),\n \"docker\",\n ...target.options.map(quote),\n ].join(\" \");\n}\n\nfunction sshFlags(args: ReadonlyArray<string>): Set<string> {\n const flags = new Set<string>();\n for (let index = 0; index < args.length; index++) {\n const word = args[index] ?? \"\";\n if (!word.startsWith(\"-\") || word.startsWith(\"--\") || word === \"-\") continue;\n for (let position = 1; position < word.length; position++) {\n const letter = word[position] ?? \"\";\n flags.add(letter);\n if (SSH_VALUE_FLAGS.includes(letter)) {\n if (position === word.length - 1) index++;\n break;\n }\n }\n }\n return flags;\n}\n\nfunction unresolvedNote(noun: string, command: string): string {\n return `You created a ${noun}. When the task no longer needs it, run \\`${command}\\`.`;\n}\n\n// ---------------------------------------------------------------- detect ----\n\ninterface Findings {\n readonly resource: (resource: HygieneResource) => void;\n readonly note: (note: string) => void;\n}\n\n/** The state that a `cd` or an `export` changes, one for each subshell scope. */\ninterface ScopeState {\n directory: string | undefined;\n /**\n * The `DOCKER_*` variables that the scope exported, or undefined when a\n * command changed them in a way that detection does not know. An unknown\n * environment stays unknown for the rest of the scope.\n */\n dockerEnvironment: Record<string, string> | undefined;\n}\n\n/** One simple command, with the state of its scope applied. */\ninterface CommandContext {\n readonly name: string;\n readonly words: ReadonlyArray<string>;\n readonly directory: string | undefined;\n /** The Docker environment of the command, or undefined when it is unknown. */\n readonly dockerEnvironment: Readonly<Record<string, string>> | undefined;\n}\n\n/**\n * Finds the resources that a successful bash command created. A resource\n * whose path or id is not literal in the command or the output gives a\n * generic note in place of a ledger entry.\n */\nexport function detectResources(\n command: string,\n cwd: string,\n output: string,\n home: string,\n platform: NodeJS.Platform = process.platform,\n): { resources: Array<HygieneResource>; notes: Array<string> } {\n const found = new Map<string, HygieneResource>();\n const notes: Array<string> = [];\n const findings: Findings = {\n resource: (resource) => {\n found.set(resourceKey(resource), resource);\n },\n note: (note) => {\n if (!notes.includes(note)) notes.push(note);\n },\n };\n\n // A subshell scope starts with a copy of its parent state at its first\n // command, so a `cd` or an unknown Docker environment in a subshell does\n // not change the commands after it.\n const states = new Map<string, ScopeState>([\n [ROOT_SCOPE, { directory: cwd, dockerEnvironment: {} }],\n ]);\n const stateOf = (scope: string): ScopeState => {\n const known = states.get(scope);\n if (known !== undefined) return known;\n const parent = stateOf(scope.slice(0, scope.lastIndexOf(\"/\")));\n const environment = parent.dockerEnvironment;\n const state = {\n directory: parent.directory,\n dockerEnvironment: environment === undefined ? undefined : { ...environment },\n };\n states.set(scope, state);\n return state;\n };\n\n const segments = scopedSegments(command, ROOT_SCOPE);\n const owned = ownedOutput(segments, output);\n for (const segment of segments) {\n const { assignments, words, assignsShell } = commandWords(segment.words);\n const first = words[0];\n if (first === undefined) {\n // `DOCKER_HOST=value` without a command changes the daemon when the\n // shell already exports DOCKER_HOST, which detection does not know.\n if (assignsShell && assignments.some(namesDaemonVariable)) {\n stateOf(segment.scope).dockerEnvironment = undefined;\n }\n continue;\n }\n const name = (first.split(/[\\\\/]/).pop() ?? first).replace(/\\.exe$/i, \"\");\n const state = stateOf(segment.scope);\n const args = words.slice(1);\n if (name === \"cd\" || name === \"pushd\") {\n const directory = changeDirectory(args, state.directory, home);\n state.directory = segment.setupKnown || directory === state.directory ? directory : undefined;\n continue;\n }\n if (name === \"export\") {\n const environment =\n state.dockerEnvironment !== undefined && exportIsTracked(args)\n ? dockerEnvironment(state.dockerEnvironment, args)\n : undefined;\n state.dockerEnvironment = settledEnvironment(segment, state.dockerEnvironment, environment);\n continue;\n }\n if (name === \"unset\") {\n const variables = unsetVariables(args);\n let environment: Record<string, string> | undefined;\n if (variables !== undefined && state.dockerEnvironment !== undefined) {\n environment = { ...state.dockerEnvironment };\n for (const variable of variables) delete environment[variable];\n }\n // The shell can inherit a daemon variable that the tracked environment\n // does not hold, so an unset that may not run leaves the daemon unknown.\n const inheritedChange =\n !segment.setupKnown && (variables === undefined || variables.some(namesDaemonVariable));\n state.dockerEnvironment = inheritedChange\n ? undefined\n : settledEnvironment(segment, state.dockerEnvironment, environment);\n continue;\n }\n if (\n SHELL_CODE_COMMANDS[name] === true ||\n (DECLARATION_COMMANDS[name] === true && !declarationIsTracked(args))\n ) {\n state.dockerEnvironment = undefined;\n }\n const context: CommandContext = {\n name,\n words,\n directory: state.directory,\n dockerEnvironment:\n state.dockerEnvironment === undefined\n ? undefined\n : dockerEnvironment(state.dockerEnvironment, assignments),\n };\n detectCreation(context, home, owned, platform, findings);\n const text = segment.words.map(quote).join(\" \").slice(0, COMMAND_TEXT_LIMIT);\n for (const rule of otherRules(context, segment.background, home)) {\n findings.resource({ kind: \"other\", category: rule.category, command: text, hint: rule.hint });\n }\n }\n return { resources: [...found.values()], notes };\n}\n\n/**\n * The tool output when one command owns it, else undefined. A command owns\n * the output only when it runs alone, without a wrapper, and prints to the\n * output. These cases fail:\n *\n * - A substitution such as `f=$(mktemp)` captures what mktemp prints.\n * - Another command can print an unrelated path or container ID, or `||`\n * can skip the command.\n * - A wrapper such as `env` or `time` stands between the command and the\n * output.\n * - A redirection or a process substitution sends the output elsewhere.\n *\n * The callers then give the generic note.\n */\nfunction ownedOutput(segments: ReadonlyArray<ScopedSegment>, output: string): string | undefined {\n const sole = segments.length === 1 ? segments[0] : undefined;\n return sole !== undefined && printsToOutput(sole.words) && runsWithoutWrapper(sole.words)\n ? output\n : undefined;\n}\n\nfunction detectCreation(\n context: CommandContext,\n home: string,\n owned: string | undefined,\n platform: NodeJS.Platform,\n findings: Findings,\n): void {\n const { name, words, directory } = context;\n if (name === \"git\") {\n const git = gitArguments(words, directory, home);\n if (git.args[0] === \"worktree\" && git.args[1] === \"add\") {\n detectWorktree(git.args.slice(2), git.directory, home, findings);\n }\n return;\n }\n\n const docker = dockerCommand(name, words, context.dockerEnvironment);\n if (docker !== undefined) {\n const { target, args } = docker;\n if (args[0] === \"compose\") detectCompose(args.slice(1), target, directory, home, findings);\n else if (args[0] === \"run\") detectContainer(args.slice(1), target, owned, findings);\n else if (args[0] === \"container\" && args[1] === \"run\") {\n detectContainer(args.slice(2), target, owned, findings);\n }\n return;\n }\n\n const ownPath = owned === undefined ? undefined : lastAbsoluteLine(owned);\n if (name === \"docks-kit\" && words[1] === \"scratch\" && words[2] === \"new\") {\n if (ownPath === undefined) {\n findings.note(unresolvedNote(\"scratch directory\", \"docks-kit scratch remove <path>\"));\n } else {\n findings.resource({ kind: \"scratch\", path: ownPath });\n }\n return;\n }\n\n if (name === \"mktemp\") detectMktemp(words.slice(1), ownPath, platform, findings);\n}\n\n/** mktemp creates a file, or a directory with `-d`; a dry run (`-u`) creates nothing. */\nfunction detectMktemp(\n args: ReadonlyArray<string>,\n path: string | undefined,\n platform: NodeJS.Platform,\n findings: Findings,\n): void {\n const effect = mktempEffect(args, platform);\n if (effect === \"nothing\") return;\n const directory = effect === \"directory\";\n if (path === undefined) {\n const noun = directory ? \"temporary directory\" : \"temporary file\";\n findings.note(unresolvedNote(noun, \"docks-kit scratch remove <path>\"));\n } else {\n findings.resource({ kind: directory ? \"tempDir\" : \"tempFile\", path });\n }\n findings.note(SCRATCH_NOTE);\n}\n\n/**\n * Reads the options of an mktemp call. GNU mktemp accepts options before and\n * after the template and a unique prefix of each long option; macOS mktemp\n * takes a prefix after `-t`. An option value, the template, and every word\n * after `--` are not options, so `--suffix -upload` is no dry run.\n */\nfunction mktempEffect(\n args: ReadonlyArray<string>,\n platform: NodeJS.Platform,\n): \"file\" | \"directory\" | \"nothing\" {\n let directory = false;\n for (let index = 0; index < args.length; index++) {\n const word = args[index] ?? \"\";\n if (word === \"--\") break;\n if (!word.startsWith(\"-\") || word === \"-\") continue;\n if (word.startsWith(\"--\")) {\n const typed = word.split(\"=\", 1)[0] ?? word;\n const matches = MKTEMP_LONG_OPTIONS.filter((option) => option.startsWith(typed));\n const option = matches.includes(typed)\n ? typed\n : matches.length === 1\n ? matches[0]\n : undefined;\n // mktemp stops on an unknown or ambiguous option, so it creates nothing.\n if (option === undefined || option === \"--dry-run\" || option === \"--help\") return \"nothing\";\n if (option === \"--version\") return \"nothing\";\n if (option === \"--directory\") directory = true;\n if (option === \"--suffix\" && !word.includes(\"=\")) index++;\n continue;\n }\n for (let at = 1; at < word.length; at++) {\n const flag = word[at];\n if (flag === \"u\") return \"nothing\";\n if (flag === \"d\") directory = true;\n if (flag === \"p\" || (flag === \"t\" && platform === \"darwin\")) {\n // `-p DIR` takes the next word; in `-pDIR` the rest of the word is the value.\n if (at === word.length - 1) index++;\n break;\n }\n }\n }\n return directory ? \"directory\" : \"file\";\n}\n\n/**\n * True when the command of the segment is its first word after the\n * `NAME=value` words and the redirections. A redirection before the command,\n * as in `2>/dev/null mktemp`, applies to the command itself, so it is no\n * wrapper.\n */\nfunction runsWithoutWrapper(words: ReadonlyArray<string>): boolean {\n let first: string | undefined;\n for (let index = 0; index < words.length && first === undefined; index++) {\n const word = words[index] ?? \"\";\n if (REDIRECT_OPERATOR.test(word)) index++;\n else if (!ATTACHED_REDIRECT.test(word) && !ASSIGNMENT.test(word)) first = word;\n }\n return first !== undefined && first === commandWords(words).words[0];\n}\n\n/**\n * True when the standard output of the segment reaches the tool output: no\n * word redirects the standard output or the input, and no word runs a\n * process substitution. A redirection of the standard error alone, such as\n * `2>&1` or `2>/dev/null`, keeps the standard output in place.\n */\nfunction printsToOutput(words: ReadonlyArray<string>): boolean {\n return !words.some(\n (word) =>\n ((REDIRECT_OPERATOR.test(word) || ATTACHED_REDIRECT.test(word)) &&\n !STDERR_REDIRECT.test(word)) ||\n word.includes(\"<(\") ||\n word.includes(\">(\"),\n );\n}\n\nfunction detectWorktree(\n args: ReadonlyArray<string>,\n directory: string | undefined,\n home: string,\n findings: Findings,\n): void {\n let optionsEnded = false;\n for (let index = 0; index < args.length; index++) {\n const word = args[index] ?? \"\";\n if (!optionsEnded && word === \"--\") {\n optionsEnded = true;\n } else if (!optionsEnded && WORKTREE_VALUE_OPTIONS[word] === true) {\n index++;\n } else if (optionsEnded || !word.startsWith(\"-\") || word === \"-\") {\n const path = resolvePath(word, directory, home);\n if (path === undefined) {\n findings.note(unresolvedNote(\"git worktree\", \"git worktree remove -- <path>\"));\n } else {\n findings.resource({ kind: \"worktree\", path });\n }\n return;\n }\n }\n}\n\nfunction detectCompose(\n args: ReadonlyArray<string>,\n target: DockerTarget | undefined,\n directory: string | undefined,\n home: string,\n findings: Findings,\n): void {\n const files: Array<string> = [];\n let project: string | undefined;\n let projectDirectory: string | undefined;\n let subcommand: string | undefined;\n for (let index = 0; index < args.length; index++) {\n const word = args[index] ?? \"\";\n const equals = word.startsWith(\"-\") ? word.indexOf(\"=\") : -1;\n const option = equals > 0 ? word.slice(0, equals) : word;\n if (COMPOSE_VALUE_OPTIONS[option] === true) {\n const value = equals > 0 ? word.slice(equals + 1) : args[++index];\n if (value === undefined) break;\n if (option === \"-f\" || option === \"--file\") files.push(value);\n else if (option === \"-p\" || option === \"--project-name\") project = value;\n else if (option === \"--project-directory\") projectDirectory = value;\n } else if (!word.startsWith(\"-\")) {\n subcommand = word;\n break;\n }\n }\n if (subcommand !== \"up\" && subcommand !== \"start\") return;\n\n const unresolved = unresolvedNote(\n \"detached container\",\n \"docker compose --project-directory <path> down\",\n );\n const resolvedFiles: Array<string> = [];\n for (const file of files) {\n const path = file === \"-\" ? undefined : resolvePath(file, directory, home);\n if (path === undefined) {\n findings.note(unresolved);\n return;\n }\n resolvedFiles.push(path);\n }\n const firstFile = resolvedFiles[0];\n const workingDir =\n projectDirectory !== undefined\n ? resolvePath(projectDirectory, directory, home)\n : firstFile !== undefined\n ? dirname(firstFile)\n : directory;\n if (\n target === undefined ||\n workingDir === undefined ||\n (project !== undefined && UNRESOLVED.test(project))\n ) {\n findings.note(unresolved);\n return;\n }\n\n const down = [dockerPrefix(target), \"compose\"];\n if (project !== undefined) down.push(\"-p\", quote(project));\n if (projectDirectory !== undefined || resolvedFiles.length === 0) {\n down.push(\"--project-directory\", quote(workingDir));\n }\n for (const file of resolvedFiles) down.push(\"-f\", quote(file));\n down.push(\"down\");\n findings.resource({ kind: \"compose\", workingDir, down: down.join(\" \"), docker: target });\n}\n\nfunction detectContainer(\n args: ReadonlyArray<string>,\n target: DockerTarget | undefined,\n owned: string | undefined,\n findings: Findings,\n): void {\n const detached = args.some(\n (word) => word === \"--detach\" || word === \"--detach=true\" || SHORT_CLUSTER_WITH_D.test(word),\n );\n const removesItself = args.some((word) => word === \"--rm\" || word === \"--rm=true\");\n if (detached) {\n const fullId = owned === undefined ? undefined : lastContainerIdLine(owned);\n if (target !== undefined && fullId !== undefined) {\n const id = fullId.slice(0, 12);\n const prefix = dockerPrefix(target);\n const down = removesItself\n ? `${prefix} stop ${id}`\n : `${prefix} stop ${id} && ${prefix} rm ${id}`;\n findings.resource({ kind: \"container\", id, down, docker: target });\n } else {\n findings.note(unresolvedNote(\"detached container\", \"docker stop <id>\"));\n }\n }\n if (!removesItself) findings.note(RM_NOTE);\n}\n\n/**\n * The last line that is a full container ID. omp appends notices such as\n * `Wall time: N seconds` after the command output, so the ID need not be the\n * last line.\n */\nfunction lastContainerIdLine(output: string): string | undefined {\n return output\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => CONTAINER_ID.test(line))\n .pop();\n}\n\nfunction otherRules(context: CommandContext, background: boolean, home: string): Array<OtherRule> {\n const { name, words } = context;\n const rules: Array<OtherRule> = [];\n const args = words.slice(1);\n const has = (word: string): boolean => args.includes(word);\n const hasAny = (...candidates: Array<string>): boolean => candidates.some(has);\n const global = hasAny(\"-g\", \"--global\");\n\n if (background || name === \"nohup\" || name === \"setsid\" || name === \"disown\" || has(\"disown\")) {\n rules.push(BACKGROUND);\n }\n\n const detachFlag = args.some((word) => SHORT_CLUSTER_WITH_D.test(word));\n if (((name === \"tmux\" && hasAny(\"new\", \"new-session\")) || name === \"screen\") && detachFlag) {\n rules.push(TERMINAL);\n }\n\n const ssh = name === \"ssh\" ? sshFlags(args) : undefined;\n if (\n name === \"ngrok\" ||\n (name === \"cloudflared\" && has(\"tunnel\")) ||\n (name === \"kubectl\" && has(\"port-forward\")) ||\n (ssh !== undefined &&\n (ssh.has(\"L\") || ssh.has(\"R\") || ssh.has(\"D\")) &&\n (ssh.has(\"N\") || ssh.has(\"f\")))\n ) {\n rules.push(TUNNEL);\n }\n\n if (CLUSTER_COMMANDS.some((pattern) => matchesCommand(name, words, pattern))) {\n rules.push(CLUSTER);\n }\n\n const docker = dockerCommand(name, words, context.dockerEnvironment)?.args;\n if (\n docker !== undefined &&\n (docker[0] === \"volume\" || docker[0] === \"network\" || docker[0] === \"buildx\") &&\n docker[1] === \"create\"\n ) {\n rules.push(DOCKER_RESOURCE);\n }\n\n if (\n (name === \"crontab\" && !has(\"-l\")) ||\n name === \"at\" ||\n (name === \"systemctl\" && has(\"--user\") && hasAny(\"enable\", \"start\")) ||\n (name === \"systemd-run\" && has(\"--user\")) ||\n (name === \"launchctl\" && hasAny(\"load\", \"bootstrap\"))\n ) {\n rules.push(SCHEDULED);\n }\n\n if (\n (name === \"npm\" && hasAny(\"i\", \"install\") && global) ||\n (name === \"bun\" && hasAny(\"add\", \"install\", \"i\") && global) ||\n (name === \"pnpm\" && has(\"add\") && global) ||\n (name === \"yarn\" && containsInOrder(args, [\"global\", \"add\"])) ||\n (/^pip[0-9.]*$/.test(name) && has(\"install\") && has(\"--user\")) ||\n ((name === \"pipx\" || name === \"cargo\" || name === \"go\") && has(\"install\"))\n ) {\n rules.push(GLOBAL_INSTALL);\n }\n\n if (\n (name === \"vercel\" && !has(\"env\")) ||\n REMOTE_COMMANDS.some((pattern) => matchesCommand(name, words, pattern))\n ) {\n rules.push(REMOTE);\n }\n\n if (name === \"git\") {\n const git = gitArguments(words, context.directory, home);\n if (git.args[0] === \"stash\" && STASH_WITHOUT_ENTRY[git.args[1] ?? \"\"] !== true) {\n rules.push(STASH);\n }\n }\n return rules;\n}\n\n// ----------------------------------------------------------- reminders ----\n\nfunction resourceKey(resource: HygieneResource): string {\n switch (resource.kind) {\n case \"worktree\":\n case \"scratch\":\n case \"tempDir\":\n case \"tempFile\":\n return `${resource.kind}:${resource.path}`;\n case \"compose\":\n return `compose:${dockerPrefix(resource.docker)}:${resource.workingDir}`;\n case \"container\":\n return `container:${dockerPrefix(resource.docker)}:${resource.id}`;\n case \"other\":\n return `other:${resource.category}:${resource.command}`;\n }\n}\n\nfunction describeResource(resource: PathResource): string {\n switch (resource.kind) {\n case \"worktree\":\n return `the worktree ${resource.path}`;\n case \"compose\":\n return `the compose project in ${resource.workingDir}`;\n case \"container\":\n return `the container ${resource.id}`;\n case \"scratch\":\n return `the scratch directory ${resource.path}`;\n case \"tempDir\":\n return `the temporary directory ${resource.path}`;\n case \"tempFile\":\n return `the temporary file ${resource.path}`;\n }\n}\n\nexport function cleanupCommand(resource: HygieneResource): string {\n switch (resource.kind) {\n case \"worktree\":\n return `git worktree remove -- ${quote(resource.path)}`;\n case \"compose\":\n case \"container\":\n return resource.down;\n case \"scratch\":\n case \"tempDir\":\n case \"tempFile\":\n return `docks-kit scratch remove ${quote(resource.path)}`;\n case \"other\":\n return resource.hint;\n }\n}\n\nexport function creationReminder(resource: HygieneResource): string {\n if (resource.kind === \"other\") {\n return `This command created a ${resource.category} (\\`${resource.command}\\`). ${resource.hint}`;\n }\n return `You created ${describeResource(resource)}. When the task no longer needs it, run \\`${cleanupCommand(resource)}\\`.`;\n}\n\nfunction stopLine(resource: HygieneResource): string {\n if (resource.kind === \"other\") {\n return `- ${resource.category}: \\`${resource.command}\\` (${resource.hint})`;\n }\n return `- ${describeResource(resource)}: run \\`${cleanupCommand(resource)}\\``;\n}\n\nexport function stopReminder(\n verified: ReadonlyArray<HygieneResource>,\n unverified: ReadonlyArray<HygieneResource>,\n): string {\n const lines: Array<string> = [];\n if (verified.length > 0) {\n lines.push(\"These resources from this session still exist:\", ...verified.map(stopLine));\n }\n if (unverified.length > 0) {\n lines.push(\n \"These commands from this session may have left something running, installed, or created:\",\n ...unverified.map(stopLine),\n );\n }\n lines.push(KEEP_SENTENCE);\n return lines.join(\"\\n\");\n}\n\n// ----------------------------------------------------------------- sweep ----\n\nexport function sweepDue(stampMtimeMs: number | undefined, nowMs: number): boolean {\n return stampMtimeMs === undefined || nowMs - stampMtimeMs >= SWEEP_INTERVAL_MS;\n}\n\nfunction mtimeMs(path: string): number | undefined {\n try {\n return statSync(path).mtimeMs;\n } catch {\n return undefined;\n }\n}\n\n/** A probe file of the claim or of the takeover mutex: `<file>.<pid>.<16 hex>.probe`. */\nconst PROBE_FILE = /^tidy\\.stamp\\.(?:claim|takeover)\\.(\\d+)\\.[0-9a-f]{16}\\.probe$/;\n\n/**\n * Creates `<path>.<pid>.<16 hex>.probe` with `wx`, then removes it. True when\n * both calls succeed: the folder lets this process create and delete files.\n * False when a call fails: the folder can deny the operation. A process that\n * stops between the two calls leaves the probe file, and removeExitedProbes\n * removes it later.\n */\nfunction probeSucceeds(path: string): boolean {\n const probe = `${path}.${process.pid}.${randomBytes(8).toString(\"hex\")}.probe`;\n try {\n closeSync(openSync(probe, \"wx\", 0o600));\n unlinkSync(probe);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True on Windows for an error of an operation on `path` that another process\n * causes when it deletes or holds `path`. libuv runs the `node:fs` calls of\n * Bun and Node.js on Windows. It gives EBUSY only for a sharing or lock\n * violation, so EBUSY is always contention. It gives EPERM for\n * ERROR_ACCESS_DENIED. Windows returns that error for an open or a delete of a\n * \"delete pending\" name. Such a name is a deleted file that another process\n * still has open. Windows also returns the error for a folder that denies the\n * operation. Thus EPERM counts as contention only when the probe succeeds;\n * otherwise the caller throws the EPERM. On POSIX, EPERM and EBUSY are real\n * faults, so they stay errors.\n */\nfunction isWindowsContention(error: unknown, path: string): boolean {\n if (process.platform !== \"win32\") return false;\n const code = errorCode(error);\n return code === \"EBUSY\" || (code === \"EPERM\" && probeSucceeds(path));\n}\n\n/**\n * Removes `path`. Ignores a path that is absent or, on Windows, a path that\n * another process deletes or holds.\n */\nfunction removeIfPresent(path: string): void {\n try {\n unlinkSync(path);\n } catch (error) {\n if (errorCode(error) !== \"ENOENT\" && !isWindowsContention(error, path)) throw error;\n }\n}\n\n/**\n * Creates `path` with `wx` and writes an owner token into it. Returns the\n * token, or undefined when the file exists or, on Windows, when another\n * process deletes or holds it now.\n */\nfunction createOwned(path: string): string | undefined {\n let descriptor: number;\n try {\n descriptor = openSync(path, \"wx\", 0o600);\n } catch (error) {\n if (errorCode(error) === \"EEXIST\" || isWindowsContention(error, path)) return undefined;\n throw error;\n }\n const token = `${process.pid} ${randomUUID()}`;\n try {\n writeFileSync(descriptor, token);\n } finally {\n closeSync(descriptor);\n }\n return token;\n}\n\n/**\n * Removes `path` only when it still holds `token`, so that no process removes\n * the file of another. Ignores a path that is absent or, on Windows, a path\n * that another process deletes or holds. Such a file stays until it is stale.\n */\nfunction releaseOwned(path: string, token: string): void {\n try {\n if (readFileSync(path, \"utf8\") === token) unlinkSync(path);\n } catch (error) {\n if (errorCode(error) !== \"ENOENT\" && !isWindowsContention(error, path)) throw error;\n }\n}\n\n/** True when no process has `pid`: `process.kill(pid, 0)` fails with ESRCH. */\nfunction hasExited(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return false;\n } catch (error) {\n return errorCode(error) === \"ESRCH\";\n }\n}\n\n/**\n * Removes each probe file of the claim and of the takeover mutex whose process\n * has exited. Keeps the probe file of a running process, which removes it.\n * The removal is best effort and makes no probe. So a folder that denies\n * deletes keeps the file and cannot get a new probe file on each sweep.\n */\nfunction removeExitedProbes(cacheDir: string): void {\n for (const name of readdirSync(cacheDir)) {\n const pid = PROBE_FILE.exec(name)?.[1];\n if (pid === undefined || !hasExited(Number(pid))) continue;\n try {\n unlinkSync(join(cacheDir, name));\n } catch {\n // The next sweep tries again.\n }\n }\n}\n\n/** True when `path` is missing or older than CLAIM_STALE_MS: its process stopped. */\nfunction isStale(path: string, nowMs: number): boolean {\n const mtime = mtimeMs(path);\n return mtime === undefined || nowMs - mtime > CLAIM_STALE_MS;\n}\n\n/**\n * Creates the claim and returns its token, or returns undefined when another\n * process holds it. Only the holder of the takeover mutex replaces a stale\n * claim, and it checks the claim again while it holds the mutex. A stale\n * takeover can still let two processes claim the sweep. Each then starts\n * `docks-kit tidy --apply`, and the second one finds `tidy-lock.db` held and\n * stops, or plans from the current state after the first one ends. Thus a\n * duplicate claim only adds load; the claim limits load and does not protect\n * files. On Windows, a create that fails because another process deletes or\n * holds the file gives no token for that attempt. When the claim is then stale\n * or gone, the takeover path can still take it; otherwise a later main session\n * claims the sweep. A delete or a release that fails this way removes nothing.\n */\nfunction acquireClaim(cacheDir: string, nowMs: number): string | undefined {\n const claim = join(cacheDir, CLAIM_FILE);\n const token = createOwned(claim);\n if (token !== undefined || !isStale(claim, nowMs)) return token;\n\n const takeover = join(cacheDir, TAKEOVER_FILE);\n let mutex = createOwned(takeover);\n if (mutex === undefined && isStale(takeover, nowMs)) {\n removeIfPresent(takeover);\n mutex = createOwned(takeover);\n }\n if (mutex === undefined) return undefined;\n try {\n if (!isStale(claim, nowMs)) return undefined;\n removeIfPresent(claim);\n return createOwned(claim);\n } finally {\n releaseOwned(takeover, mutex);\n }\n}\n\n/**\n * Lets one process in each sweep interval start the sweep. It first removes\n * the probe files of exited processes. The process that holds\n * `tidy.stamp.claim` reads the stamp again. When the sweep is still due, it\n * writes the stamp and returns true. In each case, it then releases its claim.\n * When the release fails on Windows because of contention, the claim stays\n * until it is stale.\n */\nexport function claimSweep(cacheDir: string, nowMs: number): boolean {\n mkdirSync(cacheDir, { recursive: true, mode: 0o700 });\n chmodSync(cacheDir, 0o700);\n removeExitedProbes(cacheDir);\n const token = acquireClaim(cacheDir, nowMs);\n if (token === undefined) return false;\n try {\n const stamp = join(cacheDir, STAMP_FILE);\n if (!sweepDue(mtimeMs(stamp), nowMs)) return false;\n writeFileSync(stamp, \"\", { mode: 0o600 });\n chmodSync(stamp, 0o600);\n const seconds = nowMs / 1000;\n utimesSync(stamp, seconds, seconds);\n return true;\n } finally {\n releaseOwned(join(cacheDir, CLAIM_FILE), token);\n }\n}\n\n// ---------------------------------------------------------------- ledger ----\n\n/**\n * One omp process shares module state across its sessions, so the main\n * session also sees the resources that its subagents created.\n */\nconst ledger = new Map<string, HygieneResource>();\nconst reminded = new Set<string>();\n\nasync function dockerListsAny(target: DockerTarget, args: ReadonlyArray<string>): Promise<boolean> {\n try {\n const result = await run(\"docker\", [...target.options, ...args], {\n env: { ...process.env, ...target.environment },\n timeoutMs: DOCKER_CHECK_TIMEOUT_MS,\n });\n return result.code === 0 && result.stdout.trim() !== \"\";\n } catch {\n return false;\n }\n}\n\nasync function stillExists(resource: HygieneResource): Promise<boolean> {\n switch (resource.kind) {\n case \"worktree\":\n case \"scratch\":\n case \"tempDir\":\n case \"tempFile\":\n return existsSync(resource.path);\n case \"compose\":\n return dockerListsAny(resource.docker, [\n \"ps\",\n \"-q\",\n \"--filter\",\n `label=com.docker.compose.project.working_dir=${resource.workingDir}`,\n ]);\n case \"container\":\n return dockerListsAny(resource.docker, [\"ps\", \"-aq\", \"--filter\", `id=${resource.id}`]);\n case \"other\":\n return true;\n }\n}\n\nfunction textResult(text: string, details: Record<string, unknown>): ToolResult {\n return { content: [{ type: \"text\", text }], details };\n}\n\n/**\n * Records each resource that a bash command created and returns its reminder\n * lines and the notes on resources that the command can create.\n */\nfunction resourceLines(event: ToolResultEvent, ctx: ExtensionContext): Array<string> {\n if (event.toolName !== \"bash\" || event.isError === true) return [];\n const command = event.input?.[\"command\"];\n if (typeof command !== \"string\" || !TRIGGER.test(command)) return [];\n const cwd = resolve(ctx.cwd, String(event.input?.[\"cwd\"] ?? \".\"));\n const output = (event.content ?? [])\n .map((block) => (block.type === \"text\" && typeof block.text === \"string\" ? block.text : \"\"))\n .join(\"\\n\");\n const { resources, notes } = detectResources(command, cwd, output, homedir());\n for (const resource of resources) ledger.set(resourceKey(resource), resource);\n return [...resources.map(creationReminder), ...notes];\n}\n\n// ------------------------------------------------------------- extension ----\n\nexport default function docksKitOmp(pi: ExtensionApi): void {\n const z = pi.zod;\n /**\n * The message of the error that stopped the last sweep start. The next tool\n * result of the main session shows it one time.\n */\n let sweepError: string | undefined;\n\n pi.registerTool<{ label: string }>({\n name: \"scratch_new\",\n label: \"Scratch New\",\n description:\n \"Create a private temporary directory under the docks-kit scratch root and return its path. Use it instead of /tmp, also for a single temporary file. Remove it with scratch_remove when the task no longer needs it.\",\n parameters: z.object({\n label: z.string().describe(\"Short name: letters, digits, dot, underscore, or hyphen\"),\n }),\n async execute(_toolCallId, params, signal) {\n try {\n if (!LABEL_PATTERN.test(params.label)) throw new Error(LABEL_ERROR);\n const output = await runDocksKit(\n [\"scratch\", \"new\", params.label],\n signal,\n SCRATCH_TIMEOUT_MS,\n );\n const path = lastAbsoluteLine(output);\n if (path === undefined) throw new Error(`docks-kit scratch new printed no path: ${output}`);\n const resource: HygieneResource = { kind: \"scratch\", path };\n ledger.set(resourceKey(resource), resource);\n return textResult(path, { path });\n } catch (error) {\n throw toError(error);\n }\n },\n });\n\n pi.registerTool<{ paths: Array<string> }>({\n name: \"scratch_remove\",\n label: \"Scratch Remove\",\n description:\n \"Remove temporary files and directories that you created. Use it instead of gio trash, which does not work on a tmpfs /tmp. Accepts only absolute paths inside the docks-kit scratch root, the system temporary directory, or /var/tmp; refuses every other path.\",\n parameters: z.object({\n paths: z.array(z.string()).describe(\"Absolute paths\"),\n }),\n async execute(_toolCallId, params, signal) {\n try {\n if (params.paths.length === 0) throw new Error(\"paths must not be empty\");\n const relative = params.paths.find((path) => !isAbsolute(path));\n if (relative !== undefined) throw new Error(`path must be absolute: ${relative}`);\n const output = await runDocksKit(\n [\"scratch\", \"remove\", ...params.paths],\n signal,\n SCRATCH_TIMEOUT_MS,\n );\n return textResult(output.trim(), { paths: params.paths });\n } catch (error) {\n throw toError(error);\n }\n },\n });\n\n pi.registerTool<Record<string, never>>({\n name: \"tidy_report\",\n label: \"Tidy Report\",\n description:\n \"List agent leftovers and other disk and memory use (worktrees, containers, orphaned processes, scratch, /tmp, caches, Trash, branches, scheduled jobs, global installs). Read-only.\",\n parameters: z.object({}),\n async execute(_toolCallId, _params, signal) {\n try {\n const output = await runDocksKit([\"tidy\", \"--report\"], signal, REPORT_TIMEOUT_MS);\n return textResult(output.trim(), {});\n } catch (error) {\n throw toError(error);\n }\n },\n });\n\n pi.on(\"tool_result\", async (event, ctx) => {\n let lines: Array<string>;\n try {\n lines = resourceLines(event, ctx);\n } catch {\n lines = [];\n }\n if (ctx.agent?.kind !== \"sub\" && sweepError !== undefined) {\n lines.push(`docks-kit sweep did not start: ${sweepError}`);\n sweepError = undefined;\n }\n return lines.length === 0 ? undefined : { additionalContext: lines.join(\"\\n\") };\n });\n\n pi.on(\"session_stop\", async (event) => {\n try {\n if (event.stop_hook_active === true) return undefined;\n const pending = [...ledger].filter(([key]) => !reminded.has(key));\n if (pending.length === 0) return undefined;\n const states = await Promise.all(\n pending.map(async ([key, resource]) => ({\n key,\n resource,\n exists: await stillExists(resource),\n })),\n );\n const verified: Array<HygieneResource> = [];\n const unverified: Array<HygieneResource> = [];\n for (const { key, resource, exists } of states) {\n if (!exists) {\n ledger.delete(key);\n continue;\n }\n reminded.add(key);\n if (resource.kind === \"other\") unverified.push(resource);\n else verified.push(resource);\n }\n if (verified.length === 0 && unverified.length === 0) return undefined;\n return { continue: true, additionalContext: stopReminder(verified, unverified) };\n } catch {\n return undefined;\n }\n });\n\n pi.on(\"session_start\", async (_event, ctx) => {\n try {\n if (ctx.agent?.kind === \"sub\") return undefined;\n // The same directory as kitCacheDir in the docks-kit CLI.\n const cacheDir = join(homedir(), \".cache\", \"docks-kit\");\n const now = Date.now();\n if (!sweepDue(mtimeMs(join(cacheDir, STAMP_FILE)), now)) return undefined;\n let docksKit: string;\n try {\n docksKit = resolveDocksKit();\n } catch {\n // A checkout user who runs ./docks-kit has no launcher on PATH. A line\n // in each session would only repeat that, so the sweep stays silent.\n return undefined;\n }\n if (!claimSweep(cacheDir, now)) return undefined;\n const child = spawn(docksKit, [\"tidy\", \"--apply\"], {\n cwd: homedir(),\n detached: true,\n shell: false,\n stdio: \"ignore\",\n windowsHide: true,\n });\n child.on(\"error\", () => {});\n child.unref();\n } catch (error) {\n // A sweep that cannot start must not stop the session; the next tool\n // result of the main session reports it.\n sweepError = error instanceof Error ? error.message : String(error);\n }\n return undefined;\n });\n}\n",
|
|
26
|
+
"SoT/.omp/plugin/extensions/hygiene.ts": "/**\n * docks-kit-omp extension: workspace hygiene for omp sessions.\n *\n * - The tools scratch_new, scratch_remove, and tidy_report run docks-kit.\n * - The tool_result handler records each resource that a bash command\n * creates, and it adds a reminder that names the cleanup command.\n * - The tool_call handler reads the stash list before a `git stash` command,\n * so the tool_result handler can name the stash entry that the command\n * added. The tool_execution_end handler drops the list of a blocked call.\n * - The session_stop handler lists the recorded resources that still exist.\n * - The session_start handler of a main session starts `docks-kit tidy --apply`\n * in the background, at most one time in each sweep interval. When the\n * sweep cannot start, the next tool result of the main session tells why.\n *\n * The module imports only node: modules, so omp loads it without a package\n * install. No subprocess uses a command interpreter, so a tool argument never\n * gets to a shell.\n */\nimport { execFile, spawn } from \"node:child_process\";\nimport { randomBytes, randomUUID } from \"node:crypto\";\nimport {\n accessSync,\n chmodSync,\n closeSync,\n constants,\n existsSync,\n mkdirSync,\n openSync,\n readdirSync,\n readFileSync,\n statSync,\n unlinkSync,\n utimesSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, isAbsolute, join, posix, resolve, win32 } from \"node:path\";\n\n// ------------------------------------------------------------- constants ----\n\nconst SWEEP_INTERVAL_MS = 12 * 60 * 60 * 1000;\nconst CLAIM_STALE_MS = 60 * 1000;\nconst STAMP_FILE = \"tidy.stamp\";\nconst CLAIM_FILE = \"tidy.stamp.claim\";\nconst TAKEOVER_FILE = \"tidy.stamp.takeover\";\nconst DOCKER_CHECK_TIMEOUT_MS = 5000;\nconst GIT_CHECK_TIMEOUT_MS = 5000;\n/** The pre-call stash read delays the command, so it gets a short timeout. */\nconst STASH_SNAPSHOT_TIMEOUT_MS = 1000;\n/** One line for each stash entry: full ID, short ID, and reflog message, split by NUL. */\nconst STASH_LIST_FORMAT = \"--format=%H%x00%h%x00%gs\";\nconst SCRATCH_TIMEOUT_MS = 60_000;\nconst REPORT_TIMEOUT_MS = 120_000;\nconst OUTPUT_LIMIT_BYTES = 16 * 1024 * 1024;\nconst COMMAND_TEXT_LIMIT = 120;\nconst LABEL_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;\nconst LABEL_ERROR = \"label must match ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$\";\nconst NOT_ON_PATH = \"docks-kit is not on PATH; install docks-kit and run docks-kit sync omp\";\n\n/**\n * A bash command that does not match this pattern creates no tracked\n * resource. Each detection rule below has a word in this pattern.\n */\nconst TRIGGER =\n /worktree\\s+add|compose|docker|scratch\\s+new|mktemp|nohup|setsid|disown|&|tmux|screen|ngrok|cloudflared|port-forward|ssh|cluster|minikube|multipass|limactl|machine|colima|crontab|\\bat\\b|systemctl|systemd-run|launchctl|install|(?:^|\\s)-g(?:\\s|$)|global|branches|branch\\s+create|vercel|netlify|wrangler|fly\\s|fork|codespace|stash/;\n\n/** The scope of the top-level command; a subshell scope extends it with `/<n>`. */\nconst ROOT_SCOPE = \"0\";\n\nconst UNRESOLVED = /[$`*]/;\nconst ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;\nconst VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst REDIRECT_OPERATOR = /^(?:\\d+|&)?(?:<<<|<<-?|>>|>&|<&|>\\||<>|>|<)$/;\nconst ATTACHED_REDIRECT = /^(?:\\d+|&)?[<>]/;\n/**\n * A word that is one redirection of the standard error alone: `2>&1`, `2>&-`,\n * `2>file`, `2>>file`, or the operator `2>` before its target. A second `<`\n * or `>` in the word is a second redirection. The segment parser splits\n * `2>|file` at the `|`, so that form gives the generic note.\n */\nconst STDERR_REDIRECT = /^2(?:>&(?:\\d+|-)|>>?[^<>]*)$/;\nconst SHORT_CLUSTER_WITH_D = /^-[A-Za-z]*d[A-Za-z]*$/;\n/** The long options of GNU mktemp, which also accepts a unique prefix of each. */\nconst MKTEMP_LONG_OPTIONS: ReadonlyArray<string> = [\n \"--directory\",\n \"--dry-run\",\n \"--quiet\",\n \"--suffix\",\n \"--tmpdir\",\n \"--help\",\n \"--version\",\n];\nconst CONTAINER_ID = /^[0-9a-f]{64}$/;\nconst SAFE_WORD = /^[A-Za-z0-9_/.:@%+=,-]+$/;\nconst RESERVED_WORDS: Record<string, true> = {\n \"{\": true,\n \"}\": true,\n \"!\": true,\n if: true,\n then: true,\n else: true,\n elif: true,\n do: true,\n while: true,\n until: true,\n time: true,\n};\n/**\n * Reserved words of a conditional, a loop, or a function body, where a\n * command may run once, many times, or never. The list holds the closing\n * words too, because a segment can start with one of them.\n */\nconst COMPOUND_WORDS: Record<string, true> = {\n if: true,\n then: true,\n else: true,\n elif: true,\n fi: true,\n for: true,\n select: true,\n while: true,\n until: true,\n do: true,\n done: true,\n case: true,\n esac: true,\n function: true,\n coproc: true,\n};\n/** A shell function name, as in `name()` or `name ()`. */\nconst FUNCTION_NAME = /^[A-Za-z_][A-Za-z0-9_.:-]*$/;\n\nconst GIT_VALUE_OPTIONS: Record<string, true> = { \"-C\": true, \"-c\": true };\nconst WORKTREE_VALUE_OPTIONS: Record<string, true> = { \"-b\": true, \"-B\": true, \"--reason\": true };\n/** Docker global options that select the daemon, mapped to their long names. */\nconst DOCKER_CONNECTION_VALUE_OPTIONS: Record<string, string> = {\n \"-c\": \"--context\",\n \"--context\": \"--context\",\n \"-H\": \"--host\",\n \"--host\": \"--host\",\n \"--config\": \"--config\",\n \"--tlscacert\": \"--tlscacert\",\n \"--tlscert\": \"--tlscert\",\n \"--tlskey\": \"--tlskey\",\n};\nconst DOCKER_CONNECTION_FLAGS: Record<string, true> = { \"--tls\": true, \"--tlsverify\": true };\nconst DOCKER_LOG_LEVEL_OPTIONS: Record<string, true> = { \"-l\": true, \"--log-level\": true };\n/** Environment variables that select the Docker daemon. */\nconst DOCKER_ENVIRONMENT: Record<string, true> = {\n DOCKER_HOST: true,\n DOCKER_CONTEXT: true,\n DOCKER_CONFIG: true,\n DOCKER_TLS_VERIFY: true,\n DOCKER_CERT_PATH: true,\n};\n/** Builtins that declare shell variables, with options and `NAME=value` words. */\nconst DECLARATION_COMMANDS: Record<string, true> = {\n declare: true,\n typeset: true,\n local: true,\n readonly: true,\n};\n/** Builtins that run shell code that detection does not read. */\nconst SHELL_CODE_COMMANDS: Record<string, true> = { eval: true, source: true, \".\": true };\nconst COMPOSE_VALUE_OPTIONS: Record<string, true> = {\n \"-f\": true,\n \"--file\": true,\n \"-p\": true,\n \"--project-name\": true,\n \"--project-directory\": true,\n \"--env-file\": true,\n \"--profile\": true,\n \"--ansi\": true,\n \"--progress\": true,\n};\nconst SSH_VALUE_FLAGS = \"BbcDEeFIiJLlmOoPpQRSWw\";\nconst STASH_WITHOUT_ENTRY: Record<string, true> = {\n list: true,\n show: true,\n pop: true,\n apply: true,\n drop: true,\n clear: true,\n branch: true,\n};\n\nconst RM_NOTE = \"Add `--rm` to `docker run` so that Docker removes the container when it stops.\";\nconst SCRATCH_NOTE =\n \"Create temporary files and directories inside a directory from the `scratch_new` tool or `docks-kit scratch new <label>`, not in `/tmp`.\";\nconst KEEP_SENTENCE =\n \"Remove each resource that the task no longer needs. Keep a resource only when the user asked for it or a later step needs it, and name it with the reason in your final answer. Never stop or delete a production resource without an ask in the main session.\";\n\ninterface OtherRule {\n readonly category: string;\n readonly hint: string;\n}\n\nconst BACKGROUND: OtherRule = {\n category: \"background process\",\n hint: \"Stop it before your final answer, or start it as a named bash service.\",\n};\nconst TERMINAL: OtherRule = {\n category: \"detached terminal session\",\n hint: \"Kill the session when the task no longer needs it.\",\n};\nconst TUNNEL: OtherRule = {\n category: \"tunnel\",\n hint: \"Stop the tunnel when the task no longer needs it.\",\n};\nconst CLUSTER: OtherRule = {\n category: \"cluster or virtual machine\",\n hint: \"Stop or delete it with the same tool when the task no longer needs it.\",\n};\nconst DOCKER_RESOURCE: OtherRule = {\n category: \"Docker resource\",\n hint: \"Remove it with docker volume rm, docker network rm, or docker buildx rm when the task no longer needs it.\",\n};\nconst SCHEDULED: OtherRule = {\n category: \"scheduled job or service\",\n hint: \"Remove the entry or unit that you added, or name it in your final answer.\",\n};\nconst GLOBAL_INSTALL: OtherRule = {\n category: \"global install\",\n hint: \"Uninstall it unless the user asked for it.\",\n};\nconst REMOTE: OtherRule = {\n category: \"remote resource\",\n hint: \"Delete it with the provider's command only when its target is local, development, dev, test, homolog, homologation, staging, or preview, and the task no longer needs it. For a production target, ask the user first. If you do not delete it, name it in your final answer.\",\n};\n\nconst CLUSTER_COMMANDS: ReadonlyArray<ReadonlyArray<string>> = [\n [\"kind\", \"create\", \"cluster\"],\n [\"k3d\", \"cluster\", \"create\"],\n [\"minikube\", \"start\"],\n [\"multipass\", \"launch\"],\n [\"limactl\", \"start\"],\n [\"podman\", \"machine\", \"start\"],\n [\"colima\", \"start\"],\n];\nconst REMOTE_COMMANDS: ReadonlyArray<ReadonlyArray<string>> = [\n [\"supabase\", \"branches\", \"create\"],\n [\"neonctl\", \"branches\", \"create\"],\n [\"pscale\", \"branch\", \"create\"],\n [\"netlify\", \"deploy\"],\n [\"wrangler\", \"deploy\"],\n [\"fly\", \"deploy\"],\n [\"fly\", \"launch\"],\n [\"gh\", \"repo\", \"fork\"],\n [\"gh\", \"codespace\", \"create\"],\n];\n\n// ----------------------------------------------------------------- types ----\n\n/**\n * The Docker daemon that a command used: the `DOCKER_*` environment variables\n * and the global options before the subcommand. An empty target is the\n * default daemon of the omp process.\n */\nexport interface DockerTarget {\n environment: Record<string, string>;\n options: Array<string>;\n}\n\nexport type HygieneResource =\n | { kind: \"worktree\"; path: string }\n | { kind: \"compose\"; workingDir: string; down: string; docker: DockerTarget }\n | { kind: \"container\"; id: string; down: string; docker: DockerTarget }\n | { kind: \"scratch\"; path: string }\n | { kind: \"tempDir\"; path: string }\n | { kind: \"tempFile\"; path: string }\n | {\n kind: \"stash\";\n /** The directory where the command ran; the reminder names it. */\n directory: string;\n /** The common git directory. A linked worktree shares its stash list with it. */\n gitDir: string;\n id: string;\n shortId: string;\n message: string;\n }\n | { kind: \"other\"; category: string; command: string; hint: string };\n\ntype PathResource = Exclude<HygieneResource, { kind: \"other\" }>;\n\n/** One line of `git stash list`. */\ninterface StashEntry {\n readonly id: string;\n readonly shortId: string;\n readonly message: string;\n}\n\nexport interface ShellSegment {\n words: Array<string>;\n background: boolean;\n}\n\n/** The operator between two segments of one parse level; a newline counts as `;`. */\ntype Separator = \";\" | \"&&\" | \"||\" | \"|\" | \"&\";\n\n/** A segment with its subshell scope. A `cd` changes only its own scope. */\ninterface ScopedSegment extends ShellSegment {\n scope: string;\n /**\n * False when the control syntax of the segment's parse level can skip a\n * setup command (`cd`, `pushd`, `export`, `unset`) or run it in a subshell\n * while a later command still runs. See setupStateKnown.\n */\n setupKnown: boolean;\n}\n\nexport interface RunOptions {\n readonly signal?: AbortSignal;\n readonly timeoutMs: number;\n readonly env?: NodeJS.ProcessEnv;\n}\n\nexport interface RunResult {\n /** The exit code, or null when a signal or the timeout stopped the process. */\n readonly code: number | null;\n readonly stdout: string;\n readonly stderr: string;\n}\n\n// The local structural types below name only the omp extension API parts\n// that this module uses. The module does not import @oh-my-pi packages.\n\ninterface TextContent {\n readonly type: string;\n readonly text?: string;\n}\n\ninterface ExtensionContext {\n readonly cwd: string;\n readonly agent?: { readonly kind: \"main\" | \"sub\" };\n}\n\ninterface ToolCallEvent {\n readonly toolName: string;\n readonly toolCallId?: string;\n readonly input?: Readonly<Record<string, unknown>>;\n}\n\ninterface ToolResultEvent extends ToolCallEvent {\n readonly content?: ReadonlyArray<TextContent>;\n readonly isError?: boolean;\n}\n\ninterface SessionStopEvent {\n readonly stop_hook_active?: boolean;\n}\n\ninterface Schema {\n describe(description: string): Schema;\n}\n\ninterface SchemaBuilder {\n object(shape: Record<string, Schema>): Schema;\n string(): Schema;\n array(item: Schema): Schema;\n}\n\ninterface ToolResult {\n content: Array<{ type: \"text\"; text: string }>;\n details: Record<string, unknown>;\n}\n\ninterface ToolDefinition<Params> {\n name: string;\n label: string;\n description: string;\n parameters: Schema;\n execute(\n toolCallId: string,\n params: Params,\n signal: AbortSignal | undefined,\n onUpdate: unknown,\n ctx: ExtensionContext,\n ): Promise<ToolResult>;\n}\n\nexport interface ExtensionApi {\n readonly zod: SchemaBuilder;\n on(\n event: \"tool_call\",\n handler: (event: ToolCallEvent, ctx: ExtensionContext) => Promise<undefined>,\n ): void;\n on(\n event: \"tool_execution_end\",\n handler: (event: { readonly toolCallId?: string }, ctx: ExtensionContext) => Promise<undefined>,\n ): void;\n on(\n event: \"tool_result\",\n handler: (\n event: ToolResultEvent,\n ctx: ExtensionContext,\n ) => Promise<{ additionalContext: string } | undefined>,\n ): void;\n on(\n event: \"session_stop\",\n handler: (\n event: SessionStopEvent,\n ctx: ExtensionContext,\n ) => Promise<{ continue: true; additionalContext: string } | undefined>,\n ): void;\n on(\n event: \"session_start\",\n handler: (event: unknown, ctx: ExtensionContext) => Promise<undefined>,\n ): void;\n registerTool<Params>(definition: ToolDefinition<Params>): void;\n}\n\n// ------------------------------------------------------------ subprocess ----\n\n/**\n * Runs `command` with `args` through execFile without a shell. Each argument\n * gets to the child as one literal argv entry. A non-zero exit, a signal, or\n * the timeout resolves; a spawn failure or an abort rejects.\n */\nexport function run(\n command: string,\n args: ReadonlyArray<string>,\n options: RunOptions,\n): Promise<RunResult> {\n const { promise, resolve: resolveRun, reject: rejectRun } = Promise.withResolvers<RunResult>();\n execFile(\n command,\n [...args],\n {\n encoding: \"utf8\",\n env: options.env,\n maxBuffer: OUTPUT_LIMIT_BYTES,\n shell: false,\n signal: options.signal,\n timeout: options.timeoutMs,\n windowsHide: true,\n },\n (error, stdout, stderr) => {\n if (error === null) resolveRun({ code: 0, stdout, stderr });\n else if (typeof error.code === \"number\") resolveRun({ code: error.code, stdout, stderr });\n else if (\n error.name !== \"AbortError\" &&\n (error.killed === true || (error.signal ?? null) !== null)\n ) {\n resolveRun({ code: null, stdout, stderr });\n } else rejectRun(error);\n },\n );\n return promise;\n}\n\n/**\n * Finds docks-kit on PATH. Windows accepts only `docks-kit.exe`, because\n * execFile without a shell cannot start a `.cmd` or `.bat` shim. A relative\n * PATH entry is skipped.\n */\nexport function resolveDocksKit(\n env: NodeJS.ProcessEnv = process.env,\n platform: NodeJS.Platform = process.platform,\n): string {\n const windows = platform === \"win32\";\n const paths = windows ? win32 : posix;\n const searchPath = env[\"PATH\"] ?? env[\"Path\"] ?? \"\";\n for (const entry of searchPath.split(windows ? \";\" : \":\")) {\n const directory = entry.replace(/^\"(.*)\"$/, \"$1\");\n if (directory === \"\" || !paths.isAbsolute(directory)) continue;\n const candidate = paths.join(directory, windows ? \"docks-kit.exe\" : \"docks-kit\");\n if (isRunnableFile(candidate, windows)) return candidate;\n }\n throw new Error(NOT_ON_PATH);\n}\n\nfunction isRunnableFile(path: string, windows: boolean): boolean {\n try {\n if (!statSync(path).isFile()) return false;\n if (!windows) accessSync(path, constants.X_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction errorCode(error: unknown): unknown {\n return typeof error === \"object\" && error !== null && \"code\" in error ? error.code : undefined;\n}\n\nfunction toError(error: unknown): Error {\n if (errorCode(error) === \"ENOENT\") return new Error(NOT_ON_PATH);\n return error instanceof Error ? error : new Error(String(error));\n}\n\nasync function runDocksKit(\n args: ReadonlyArray<string>,\n signal: AbortSignal | undefined,\n timeoutMs: number,\n): Promise<string> {\n const result = await run(resolveDocksKit(), args, { signal, timeoutMs });\n const output = [result.stdout.trim(), result.stderr.trim()].filter((text) => text !== \"\");\n if (result.code === 0) return result.stdout;\n const status = result.code === null ? \"was stopped\" : `exited with code ${result.code}`;\n throw new Error(output.length > 0 ? output.join(\"\\n\") : `docks-kit ${args.join(\" \")} ${status}`);\n}\n\n// --------------------------------------------------------- shell parsing ----\n\n/**\n * Splits a bash command into simple-command segments. This is a minimal\n * tokenizer: it removes single quotes, double quotes, and backslash escapes,\n * and it splits on `&&`, `||`, `;`, `|`, `&`, parentheses, and newlines.\n * `background` is true when a single `&` ended the segment. The command of a\n * `$(...)` or backtick substitution becomes a segment before its container.\n * A heredoc body is skipped.\n */\nexport function splitShellSegments(command: string): Array<ShellSegment> {\n return scopedSegments(command, ROOT_SCOPE).map(({ words, background }) => ({\n words,\n background,\n }));\n}\n\n/**\n * Does the work of splitShellSegments, and gives each segment its subshell\n * scope. A `( ... )` group, a `$( ... )` substitution, and a backtick\n * substitution each get a new scope `<parent>/<n>`. A `{ ...; }` group stays\n * in the scope around it, as in bash.\n *\n * Each call parses one level: the command, or the text of one substitution.\n * It stamps the segments of its level with setupStateKnown for the control\n * syntax of that level.\n */\nfunction scopedSegments(command: string, rootScope: string): Array<ScopedSegment> {\n const segments: Array<ScopedSegment> = [];\n const nested: Array<ScopedSegment> = [];\n const ownSegments: Array<ScopedSegment> = [];\n const separators = new Set<Separator>();\n const heredocs: Array<{ delimiter: string; strip: boolean }> = [];\n const scopes = [rootScope];\n let childScopes = 0;\n let words: Array<string> = [];\n let word = \"\";\n let inWord = false;\n /** True when the current word holds a quoted or escaped character. */\n let wordQuoted = false;\n /** The source index of the last character that the word took without quoting. */\n let lastUnquoted = -1;\n /** The strip flag of a `<<` operator whose delimiter is the next word. */\n let heredocOperator: boolean | undefined;\n /** The operators after the last segment; they count only when a segment follows. */\n const pendingSeparators = new Set<Separator>();\n let skipsCommands = false;\n\n const currentScope = (): string => scopes.at(-1) ?? rootScope;\n const childScope = (): string => `${currentScope()}/${childScopes++}`;\n const finishWord = (): void => {\n if (!inWord) return;\n if (heredocOperator !== undefined) {\n heredocs.push({ delimiter: word, strip: heredocOperator });\n heredocOperator = undefined;\n } else if (!word.includes(\"<<<\")) {\n const match = /^\\d*<<(-?)(.*)$/.exec(word);\n if (match !== null) {\n const strip = match[1] === \"-\";\n const delimiter = match[2] ?? \"\";\n if (delimiter === \"\") heredocOperator = strip;\n else heredocs.push({ delimiter, strip });\n }\n }\n words.push(word);\n word = \"\";\n inWord = false;\n wordQuoted = false;\n };\n\n /**\n * Ends the current segment. `ending` is the operator that ends it; a `(` or\n * a `)` passes undefined. Every operator between two segments counts, also\n * one that ends an empty segment, so `(true;) || cd` keeps both its `;` and\n * its `||`. An operator before the first segment of the level counts for\n * nothing.\n */\n const finishSegment = (ending: Separator | undefined): void => {\n finishWord();\n segments.push(...nested.splice(0));\n if (words.length > 0) {\n for (const separator of pendingSeparators) separators.add(separator);\n pendingSeparators.clear();\n if (changesControlFlow(words)) skipsCommands = true;\n const segment = {\n words,\n background: ending === \"&\",\n scope: currentScope(),\n setupKnown: true,\n };\n segments.push(segment);\n ownSegments.push(segment);\n }\n if (ending !== undefined && ownSegments.length > 0) pendingSeparators.add(ending);\n words = [];\n };\n\n const readSubstitution = (start: number): number => {\n let depth = 0;\n let openQuote: string | undefined;\n let index = start + 1;\n for (; index < command.length; index++) {\n const char = command[index];\n if (openQuote !== undefined) {\n if (char === \"\\\\\" && openQuote === '\"') index++;\n else if (char === openQuote) openQuote = undefined;\n continue;\n }\n if (char === \"\\\\\") index++;\n else if (char === \"'\" || char === '\"') openQuote = char;\n else if (char === \"(\") depth++;\n else if (char === \")\" && --depth === 0) break;\n }\n nested.push(...scopedSegments(command.slice(start + 2, index), childScope()));\n word += command.slice(start, index + 1);\n inWord = true;\n return index + 1;\n };\n\n const readBacktick = (start: number): number => {\n let index = start + 1;\n while (index < command.length && command[index] !== \"`\") {\n index += command[index] === \"\\\\\" ? 2 : 1;\n }\n nested.push(...scopedSegments(command.slice(start + 1, index), childScope()));\n word += command.slice(start, index + 1);\n inWord = true;\n return index + 1;\n };\n\n const readDoubleQuoted = (start: number): number => {\n let index = start;\n inWord = true;\n while (index < command.length && command[index] !== '\"') {\n const char = command[index];\n const next = command[index + 1];\n if (char === \"\\\\\" && next !== undefined && '\"\\\\$`\\n'.includes(next)) {\n if (next !== \"\\n\") word += next;\n index += 2;\n } else if (char === \"$\" && next === \"(\") {\n index = readSubstitution(index);\n } else if (char === \"`\") {\n index = readBacktick(index);\n } else {\n word += char;\n index++;\n }\n }\n return index + 1;\n };\n\n const skipHeredocBodies = (start: number): number => {\n let index = start;\n for (const { delimiter, strip } of heredocs.splice(0)) {\n while (index < command.length) {\n const newline = command.indexOf(\"\\n\", index);\n const end = newline === -1 ? command.length : newline;\n let line = command.slice(index, end);\n if (line.endsWith(\"\\r\")) line = line.slice(0, -1);\n index = end + 1;\n if ((strip ? line.replace(/^\\t+/, \"\") : line) === delimiter) break;\n }\n }\n heredocOperator = undefined;\n return index;\n };\n\n let index = 0;\n while (index < command.length) {\n const char = command[index] ?? \"\";\n const next = command[index + 1];\n if (char === \"'\") {\n const close = command.indexOf(\"'\", index + 1);\n const end = close === -1 ? command.length : close;\n word += command.slice(index + 1, end);\n inWord = true;\n wordQuoted = true;\n index = end + 1;\n } else if (char === '\"') {\n wordQuoted = true;\n index = readDoubleQuoted(index + 1);\n } else if (char === \"\\\\\") {\n if (next !== undefined && next !== \"\\n\") {\n word += next;\n inWord = true;\n wordQuoted = true;\n }\n index += 2;\n } else if (char === \"$\" && next === \"(\") {\n index = readSubstitution(index);\n } else if (char === \"`\") {\n index = readBacktick(index);\n } else if (char === \" \" || char === \"\\t\" || char === \"\\r\") {\n finishWord();\n index++;\n } else if (char === \"#\" && !inWord) {\n const newline = command.indexOf(\"\\n\", index);\n index = newline === -1 ? command.length : newline;\n } else if (char === \"\\n\") {\n // A line break after `&&`, `||`, or `|` continues the command, so it\n // separates nothing.\n const continues = words.length === 0 && !inWord && pendingSeparators.size > 0;\n finishSegment(continues ? undefined : \";\");\n index = skipHeredocBodies(index + 1);\n } else if (char === \"(\" && !inWord) {\n // `name ()` defines a function: its body runs only when it is called.\n if (definesFunction(words)) skipsCommands = true;\n finishSegment(undefined);\n scopes.push(childScope());\n index++;\n } else if (char === \")\") {\n finishSegment(undefined);\n if (scopes.length > 1) scopes.pop();\n index++;\n } else if (char === \";\") {\n finishSegment(\";\");\n index++;\n } else if (char === \"|\") {\n // In `>|file` the `|` belongs to the redirection; the split stays as it\n // was, but it separates nothing. Only an unquoted `>` directly before\n // the `|` makes a clobber, so `echo '>'|` and `echo \\>|` are pipes.\n const clobber = inWord && command[index - 1] === \">\" && lastUnquoted === index - 1;\n if (clobber) {\n finishSegment(undefined);\n index++;\n } else {\n finishSegment(next === \"|\" ? \"||\" : \"|\");\n index += next === \"|\" || next === \"&\" ? 2 : 1;\n }\n } else if (char === \"&\") {\n if (next === \"&\") {\n finishSegment(\"&&\");\n index += 2;\n } else if (next === \">\" || word.endsWith(\">\") || word.endsWith(\"<\")) {\n // A redirection such as `&>file` or `2>&1`.\n word += char;\n inWord = true;\n index++;\n } else {\n finishSegment(\"&\");\n index++;\n }\n } else {\n // `name()` without a space: an unquoted name word directly before `(`.\n if (char === \"(\" && words.length === 0 && !wordQuoted && FUNCTION_NAME.test(word)) {\n skipsCommands = true;\n }\n word += char;\n inWord = true;\n lastUnquoted = index;\n index++;\n }\n }\n finishSegment(undefined);\n const setupKnown = setupStateKnown(separators, skipsCommands);\n for (const segment of ownSegments) segment.setupKnown = setupKnown;\n return segments;\n}\n\n/**\n * True when each setup command of a parse level runs before every later\n * command of the level. A pure `&&` chain and a pure `;` list qualify. These\n * can skip a setup command, or run it in a subshell, while a later command\n * runs:\n *\n * - `||`, a pipeline, or a background job before a later segment;\n * - `!`, a conditional, a loop, or a function body;\n * - `&&` together with `;` or a newline.\n */\nfunction setupStateKnown(separators: ReadonlySet<Separator>, skipsCommands: boolean): boolean {\n if (skipsCommands) return false;\n if (separators.has(\"||\") || separators.has(\"|\") || separators.has(\"&\")) return false;\n return !(separators.has(\"&&\") && separators.has(\";\"));\n}\n\n/**\n * True when a segment starts or continues a conditional, a loop, or a\n * function body, or negates its status with `!`. A negation lets a `&&` chain\n * go on after a failed command. The scan passes the other leading reserved\n * words, such as `{` and `time`, as commandWords does.\n */\nfunction changesControlFlow(words: ReadonlyArray<string>): boolean {\n for (const word of words) {\n if (word === \"!\" || COMPOUND_WORDS[word] === true) return true;\n if (RESERVED_WORDS[word] !== true) return false;\n }\n return false;\n}\n\n/**\n * True when the words before a `(` define a function, as in `name ()`: one\n * name word. A reserved word before `(` starts a subshell, as in `time (make)`.\n */\nfunction definesFunction(words: ReadonlyArray<string>): boolean {\n const name = words.length === 1 ? words[0] : undefined;\n return name !== undefined && RESERVED_WORDS[name] !== true && FUNCTION_NAME.test(name);\n}\n\n/**\n * Removes redirections and leading reserved words, then splits off the\n * `NAME=value` words before the command, also after an `env`. The first of\n * the returned words is the command name. The words are empty when `sudo`\n * or an `env` option hides the command, its directory, or its Docker daemon.\n * `assignsShell` is true when the segment has only `NAME=value` words, which\n * then set shell variables.\n */\nfunction commandWords(segmentWords: ReadonlyArray<string>): {\n assignments: Array<string>;\n words: Array<string>;\n assignsShell: boolean;\n} {\n const result: Array<string> = [];\n for (let index = 0; index < segmentWords.length; index++) {\n const word = segmentWords[index] ?? \"\";\n if (REDIRECT_OPERATOR.test(word)) {\n index++;\n continue;\n }\n if (ATTACHED_REDIRECT.test(word)) continue;\n result.push(word);\n }\n const assignments: Array<string> = [];\n let start = 0;\n while (RESERVED_WORDS[result[start] ?? \"\"] === true) start++;\n while (ASSIGNMENT.test(result[start] ?? \"\")) assignments.push(result[start++] ?? \"\");\n if (start === result.length) return { assignments, words: [], assignsShell: true };\n // A command under sudo runs as another user, in an environment and a\n // directory that the sudoers policy controls, so it records nothing.\n if (result[start] === \"sudo\") return { assignments, words: [], assignsShell: false };\n if (result[start] === \"env\") {\n start++;\n // `env -u NAME` keeps the command and its directory when NAME is a literal\n // name that does not select the daemon. Another option can run another\n // program (`env -S`), change the directory (`env -C`), or clear the\n // environment (`env -i`), and `env -u DOCKER_HOST` or `env -u \"$name\"`\n // can change the daemon, so the command records nothing.\n while ((result[start] ?? \"\").startsWith(\"-\")) {\n const option = result[start] ?? \"\";\n if (option === \"--\") {\n start++;\n break;\n }\n const name = result[start + 1] ?? \"\";\n const keepsDaemon = VARIABLE_NAME.test(name) && DOCKER_ENVIRONMENT[name] !== true;\n if ((option !== \"-u\" && option !== \"--unset\") || !keepsDaemon) {\n return { assignments, words: [], assignsShell: false };\n }\n start += 2;\n }\n }\n while (ASSIGNMENT.test(result[start] ?? \"\")) assignments.push(result[start++] ?? \"\");\n return { assignments, words: result.slice(start), assignsShell: false };\n}\n\n/** Applies the `DOCKER_*=value` words of `assignments` to a copy of `environment`. */\nfunction dockerEnvironment(\n environment: Readonly<Record<string, string>>,\n assignments: ReadonlyArray<string>,\n): Record<string, string> {\n const result = { ...environment };\n for (const assignment of assignments) {\n if (!ASSIGNMENT.test(assignment)) continue;\n const equals = assignment.indexOf(\"=\");\n const variable = assignment.slice(0, equals);\n if (DOCKER_ENVIRONMENT[variable] === true) result[variable] = assignment.slice(equals + 1);\n }\n return result;\n}\n\n/**\n * The Docker environment after an `export` or an `unset`. When the command may\n * not run, a change makes the environment unknown, because a later command\n * can see either value.\n */\nfunction settledEnvironment(\n segment: ScopedSegment,\n before: Readonly<Record<string, string>> | undefined,\n after: Record<string, string> | undefined,\n): Record<string, string> | undefined {\n if (segment.setupKnown) return after;\n if (before === undefined || after === undefined) return undefined;\n const variables = new Set([...Object.keys(before), ...Object.keys(after)]);\n return [...variables].every((variable) => before[variable] === after[variable])\n ? after\n : undefined;\n}\n\n/** True when the `NAME` or `NAME=value` word names a variable that selects the Docker daemon. */\nfunction namesDaemonVariable(word: string): boolean {\n const equals = word.indexOf(\"=\");\n return DOCKER_ENVIRONMENT[equals < 0 ? word : word.slice(0, equals)] === true;\n}\n\n/**\n * True when detection can apply the `export` arguments: each operand is a\n * literal `NAME=value`, or a literal NAME that does not select the daemon.\n * An option such as `-n`, an operand that is not literal, or a daemon\n * variable without a value can give the daemon a value that detection does\n * not know. For example, `export DOCKER_HOST` exports a shell variable that\n * detection does not track.\n */\nfunction exportIsTracked(args: ReadonlyArray<string>): boolean {\n const operands = args[0] === \"--\" ? args.slice(1) : args;\n return operands.every(\n (word) => ASSIGNMENT.test(word) || (VARIABLE_NAME.test(word) && !namesDaemonVariable(word)),\n );\n}\n\n/**\n * Returns the variables that the `unset` arguments remove, or undefined when\n * detection cannot know them. Only `-v` and literal names keep them known:\n * `unset -f` and `unset -n` act on functions and name references, and\n * `unset \"$name\"` removes a variable that the command does not name.\n */\nfunction unsetVariables(args: ReadonlyArray<string>): ReadonlyArray<string> | undefined {\n let start = 0;\n while (args[start] === \"-v\") start++;\n if (args[start] === \"--\") start++;\n const operands = args.slice(start);\n return operands.every((word) => VARIABLE_NAME.test(word)) ? operands : undefined;\n}\n\n/**\n * True when the `declare`, `typeset`, `local`, or `readonly` arguments keep\n * the daemon variables unchanged: each word is a literal option, a literal\n * NAME, or a literal `NAME=value`, and no word names a daemon variable.\n */\nfunction declarationIsTracked(args: ReadonlyArray<string>): boolean {\n return args.every((word) => {\n if (word.startsWith(\"-\") || word.startsWith(\"+\")) return !UNRESOLVED.test(word);\n return (ASSIGNMENT.test(word) || VARIABLE_NAME.test(word)) && !namesDaemonVariable(word);\n });\n}\n\nfunction quote(word: string): string {\n return SAFE_WORD.test(word) ? word : `'${word.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\n/** Resolves a path word, or returns undefined when the word is not literal. */\nfunction resolvePath(word: string, base: string | undefined, home: string): string | undefined {\n if (UNRESOLVED.test(word)) return undefined;\n if (word === \"~\") return resolve(home);\n if (word.startsWith(\"~/\")) return resolve(home, word.slice(2));\n if (word.startsWith(\"~\")) return undefined;\n if (isAbsolute(word)) return resolve(word);\n return base === undefined ? undefined : resolve(base, word);\n}\n\nfunction changeDirectory(\n args: ReadonlyArray<string>,\n directory: string | undefined,\n home: string,\n): string | undefined {\n const target = args.find((word) => word === \"-\" || !word.startsWith(\"-\"));\n if (target === undefined) return resolve(home);\n if (target === \"-\") return undefined;\n return resolvePath(target, directory, home);\n}\n\nfunction lastAbsoluteLine(output: string): string | undefined {\n return output\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line !== \"\" && isAbsolute(line))\n .pop();\n}\n\n/** True when `sequence` occurs in `words` in order, with other words between. */\nfunction containsInOrder(words: ReadonlyArray<string>, sequence: ReadonlyArray<string>): boolean {\n let position = 0;\n for (const word of words) {\n if (word === sequence[position]) position++;\n if (position === sequence.length) return true;\n }\n return sequence.length === 0;\n}\n\nfunction matchesCommand(\n name: string,\n words: ReadonlyArray<string>,\n pattern: ReadonlyArray<string>,\n): boolean {\n return name === pattern[0] && containsInOrder(words.slice(1), pattern.slice(1));\n}\n\n/** Skips git global options and returns the effective directory and arguments. */\nfunction gitArguments(\n words: ReadonlyArray<string>,\n directory: string | undefined,\n home: string,\n): { directory: string | undefined; args: Array<string> } {\n let current = directory;\n let index = 1;\n while (index < words.length) {\n const word = words[index] ?? \"\";\n if (GIT_VALUE_OPTIONS[word] === true) {\n const value = words[index + 1];\n if (word === \"-C\")\n current = value === undefined ? undefined : resolvePath(value, current, home);\n index += 2;\n } else if (word.startsWith(\"-\")) {\n index++;\n } else {\n break;\n }\n }\n return { directory: current, args: words.slice(index) };\n}\n\n/**\n * Reads a docker command: the daemon target and the arguments after the\n * global options. `target` is undefined when the Docker environment is\n * unknown or a value of the target is not literal. Returns undefined for a\n * command that is not docker.\n */\nfunction dockerCommand(\n name: string,\n words: ReadonlyArray<string>,\n environment: Readonly<Record<string, string>> | undefined,\n): { target: DockerTarget | undefined; args: Array<string> } | undefined {\n if (name !== \"docker\" && name !== \"docker-compose\") return undefined;\n const target: DockerTarget = { environment: {}, options: [] };\n let literal = environment !== undefined;\n for (const [variable, value] of Object.entries(environment ?? {})) {\n if (value === \"\") continue;\n if (UNRESOLVED.test(value)) literal = false;\n target.environment[variable] = value;\n }\n if (name === \"docker-compose\") {\n return { target: literal ? target : undefined, args: [\"compose\", ...words.slice(1)] };\n }\n\n let index = 1;\n while (index < words.length && (words[index] ?? \"\").startsWith(\"-\")) {\n const word = words[index] ?? \"\";\n const equals = word.indexOf(\"=\");\n const option = equals > 0 ? word.slice(0, equals) : word;\n const longName = DOCKER_CONNECTION_VALUE_OPTIONS[option];\n if (longName !== undefined) {\n const value = equals > 0 ? word.slice(equals + 1) : words[index + 1];\n index += equals > 0 ? 1 : 2;\n if (value === undefined) break;\n if (UNRESOLVED.test(value)) literal = false;\n target.options.push(longName, value);\n } else {\n if (DOCKER_CONNECTION_FLAGS[option] === true) target.options.push(word);\n index += DOCKER_LOG_LEVEL_OPTIONS[option] === true && equals < 0 ? 2 : 1;\n }\n }\n return { target: literal ? target : undefined, args: words.slice(index) };\n}\n\n/** The docker command prefix that reaches `target`, for a cleanup command. */\nfunction dockerPrefix(target: DockerTarget): string {\n return [\n ...Object.entries(target.environment).map(([variable, value]) => `${variable}=${quote(value)}`),\n \"docker\",\n ...target.options.map(quote),\n ].join(\" \");\n}\n\nfunction sshFlags(args: ReadonlyArray<string>): Set<string> {\n const flags = new Set<string>();\n for (let index = 0; index < args.length; index++) {\n const word = args[index] ?? \"\";\n if (!word.startsWith(\"-\") || word.startsWith(\"--\") || word === \"-\") continue;\n for (let position = 1; position < word.length; position++) {\n const letter = word[position] ?? \"\";\n flags.add(letter);\n if (SSH_VALUE_FLAGS.includes(letter)) {\n if (position === word.length - 1) index++;\n break;\n }\n }\n }\n return flags;\n}\n\nfunction unresolvedNote(noun: string, command: string): string {\n return `You created a ${noun}. When the task no longer needs it, run \\`${command}\\`.`;\n}\n\n// ---------------------------------------------------------------- detect ----\n\ninterface Findings {\n readonly resource: (resource: HygieneResource) => void;\n readonly note: (note: string) => void;\n}\n\n/** The state that a `cd` or an `export` changes, one for each subshell scope. */\ninterface ScopeState {\n directory: string | undefined;\n /**\n * The `DOCKER_*` variables that the scope exported, or undefined when a\n * command changed them in a way that detection does not know. An unknown\n * environment stays unknown for the rest of the scope.\n */\n dockerEnvironment: Record<string, string> | undefined;\n}\n\n/** One simple command, with the state of its scope applied. */\ninterface CommandContext {\n readonly name: string;\n readonly words: ReadonlyArray<string>;\n readonly directory: string | undefined;\n /** The Docker environment of the command, or undefined when it is unknown. */\n readonly dockerEnvironment: Readonly<Record<string, string>> | undefined;\n}\n\n/**\n * Finds the resources that a successful bash command created. A resource\n * whose path or id is not literal in the command or the output gives a\n * generic note in place of a ledger entry.\n *\n * `stashes` lists the directories where a `git stash` command that can add a\n * stash entry ran. The command text cannot tell which entry it added, or if\n * it added one, so the handlers compare the stash list before and after the\n * command (see stashesBefore and createdStashes).\n */\nexport function detectResources(\n command: string,\n cwd: string,\n output: string,\n home: string,\n platform: NodeJS.Platform = process.platform,\n): { resources: Array<HygieneResource>; notes: Array<string>; stashes: Array<string> } {\n const found = new Map<string, HygieneResource>();\n const notes: Array<string> = [];\n const stashes = new Set<string>();\n const findings: Findings = {\n resource: (resource) => {\n found.set(resourceKey(resource), resource);\n },\n note: (note) => {\n if (!notes.includes(note)) notes.push(note);\n },\n };\n\n // A subshell scope starts with a copy of its parent state at its first\n // command, so a `cd` or an unknown Docker environment in a subshell does\n // not change the commands after it.\n const states = new Map<string, ScopeState>([\n [ROOT_SCOPE, { directory: cwd, dockerEnvironment: {} }],\n ]);\n const stateOf = (scope: string): ScopeState => {\n const known = states.get(scope);\n if (known !== undefined) return known;\n const parent = stateOf(scope.slice(0, scope.lastIndexOf(\"/\")));\n const environment = parent.dockerEnvironment;\n const state = {\n directory: parent.directory,\n dockerEnvironment: environment === undefined ? undefined : { ...environment },\n };\n states.set(scope, state);\n return state;\n };\n\n const segments = scopedSegments(command, ROOT_SCOPE);\n const owned = ownedOutput(segments, output);\n for (const segment of segments) {\n const { assignments, words, assignsShell } = commandWords(segment.words);\n const first = words[0];\n if (first === undefined) {\n // `DOCKER_HOST=value` without a command changes the daemon when the\n // shell already exports DOCKER_HOST, which detection does not know.\n if (assignsShell && assignments.some(namesDaemonVariable)) {\n stateOf(segment.scope).dockerEnvironment = undefined;\n }\n continue;\n }\n const name = (first.split(/[\\\\/]/).pop() ?? first).replace(/\\.exe$/i, \"\");\n const state = stateOf(segment.scope);\n const args = words.slice(1);\n if (name === \"cd\" || name === \"pushd\") {\n const directory = changeDirectory(args, state.directory, home);\n state.directory = segment.setupKnown || directory === state.directory ? directory : undefined;\n continue;\n }\n if (name === \"export\") {\n const environment =\n state.dockerEnvironment !== undefined && exportIsTracked(args)\n ? dockerEnvironment(state.dockerEnvironment, args)\n : undefined;\n state.dockerEnvironment = settledEnvironment(segment, state.dockerEnvironment, environment);\n continue;\n }\n if (name === \"unset\") {\n const variables = unsetVariables(args);\n let environment: Record<string, string> | undefined;\n if (variables !== undefined && state.dockerEnvironment !== undefined) {\n environment = { ...state.dockerEnvironment };\n for (const variable of variables) delete environment[variable];\n }\n // The shell can inherit a daemon variable that the tracked environment\n // does not hold, so an unset that may not run leaves the daemon unknown.\n const inheritedChange =\n !segment.setupKnown && (variables === undefined || variables.some(namesDaemonVariable));\n state.dockerEnvironment = inheritedChange\n ? undefined\n : settledEnvironment(segment, state.dockerEnvironment, environment);\n continue;\n }\n if (\n SHELL_CODE_COMMANDS[name] === true ||\n (DECLARATION_COMMANDS[name] === true && !declarationIsTracked(args))\n ) {\n state.dockerEnvironment = undefined;\n }\n const context: CommandContext = {\n name,\n words,\n directory: state.directory,\n dockerEnvironment:\n state.dockerEnvironment === undefined\n ? undefined\n : dockerEnvironment(state.dockerEnvironment, assignments),\n };\n detectCreation(context, home, owned, platform, findings);\n const text = segment.words.map(quote).join(\" \").slice(0, COMMAND_TEXT_LIMIT);\n for (const rule of otherRules(context, segment.background)) {\n findings.resource({ kind: \"other\", category: rule.category, command: text, hint: rule.hint });\n }\n const stash = stashDirectory(context, home);\n if (stash !== undefined) stashes.add(stash);\n }\n return { resources: [...found.values()], notes, stashes: [...stashes] };\n}\n\n/**\n * The tool output when one command owns it, else undefined. A command owns\n * the output only when it runs alone, without a wrapper, and prints to the\n * output. These cases fail:\n *\n * - A substitution such as `f=$(mktemp)` captures what mktemp prints.\n * - Another command can print an unrelated path or container ID, or `||`\n * can skip the command.\n * - A wrapper such as `env` or `time` stands between the command and the\n * output.\n * - A redirection or a process substitution sends the output elsewhere.\n *\n * The callers then give the generic note.\n */\nfunction ownedOutput(segments: ReadonlyArray<ScopedSegment>, output: string): string | undefined {\n const sole = segments.length === 1 ? segments[0] : undefined;\n return sole !== undefined && printsToOutput(sole.words) && runsWithoutWrapper(sole.words)\n ? output\n : undefined;\n}\n\nfunction detectCreation(\n context: CommandContext,\n home: string,\n owned: string | undefined,\n platform: NodeJS.Platform,\n findings: Findings,\n): void {\n const { name, words, directory } = context;\n if (name === \"git\") {\n const git = gitArguments(words, directory, home);\n if (git.args[0] === \"worktree\" && git.args[1] === \"add\") {\n detectWorktree(git.args.slice(2), git.directory, home, findings);\n }\n return;\n }\n\n const docker = dockerCommand(name, words, context.dockerEnvironment);\n if (docker !== undefined) {\n const { target, args } = docker;\n if (args[0] === \"compose\") detectCompose(args.slice(1), target, directory, home, findings);\n else if (args[0] === \"run\") detectContainer(args.slice(1), target, owned, findings);\n else if (args[0] === \"container\" && args[1] === \"run\") {\n detectContainer(args.slice(2), target, owned, findings);\n }\n return;\n }\n\n const ownPath = owned === undefined ? undefined : lastAbsoluteLine(owned);\n if (name === \"docks-kit\" && words[1] === \"scratch\" && words[2] === \"new\") {\n if (ownPath === undefined) {\n findings.note(unresolvedNote(\"scratch directory\", \"docks-kit scratch remove <path>\"));\n } else {\n findings.resource({ kind: \"scratch\", path: ownPath });\n }\n return;\n }\n\n if (name === \"mktemp\") detectMktemp(words.slice(1), ownPath, platform, findings);\n}\n\n/** mktemp creates a file, or a directory with `-d`; a dry run (`-u`) creates nothing. */\nfunction detectMktemp(\n args: ReadonlyArray<string>,\n path: string | undefined,\n platform: NodeJS.Platform,\n findings: Findings,\n): void {\n const effect = mktempEffect(args, platform);\n if (effect === \"nothing\") return;\n const directory = effect === \"directory\";\n if (path === undefined) {\n const noun = directory ? \"temporary directory\" : \"temporary file\";\n findings.note(unresolvedNote(noun, \"docks-kit scratch remove <path>\"));\n } else {\n findings.resource({ kind: directory ? \"tempDir\" : \"tempFile\", path });\n }\n findings.note(SCRATCH_NOTE);\n}\n\n/**\n * Reads the options of an mktemp call. GNU mktemp accepts options before and\n * after the template and a unique prefix of each long option; macOS mktemp\n * takes a prefix after `-t`. An option value, the template, and every word\n * after `--` are not options, so `--suffix -upload` is no dry run.\n */\nfunction mktempEffect(\n args: ReadonlyArray<string>,\n platform: NodeJS.Platform,\n): \"file\" | \"directory\" | \"nothing\" {\n let directory = false;\n for (let index = 0; index < args.length; index++) {\n const word = args[index] ?? \"\";\n if (word === \"--\") break;\n if (!word.startsWith(\"-\") || word === \"-\") continue;\n if (word.startsWith(\"--\")) {\n const typed = word.split(\"=\", 1)[0] ?? word;\n const matches = MKTEMP_LONG_OPTIONS.filter((option) => option.startsWith(typed));\n const option = matches.includes(typed)\n ? typed\n : matches.length === 1\n ? matches[0]\n : undefined;\n // mktemp stops on an unknown or ambiguous option, so it creates nothing.\n if (option === undefined || option === \"--dry-run\" || option === \"--help\") return \"nothing\";\n if (option === \"--version\") return \"nothing\";\n if (option === \"--directory\") directory = true;\n if (option === \"--suffix\" && !word.includes(\"=\")) index++;\n continue;\n }\n for (let at = 1; at < word.length; at++) {\n const flag = word[at];\n if (flag === \"u\") return \"nothing\";\n if (flag === \"d\") directory = true;\n if (flag === \"p\" || (flag === \"t\" && platform === \"darwin\")) {\n // `-p DIR` takes the next word; in `-pDIR` the rest of the word is the value.\n if (at === word.length - 1) index++;\n break;\n }\n }\n }\n return directory ? \"directory\" : \"file\";\n}\n\n/**\n * True when the command of the segment is its first word after the\n * `NAME=value` words and the redirections. A redirection before the command,\n * as in `2>/dev/null mktemp`, applies to the command itself, so it is no\n * wrapper.\n */\nfunction runsWithoutWrapper(words: ReadonlyArray<string>): boolean {\n let first: string | undefined;\n for (let index = 0; index < words.length && first === undefined; index++) {\n const word = words[index] ?? \"\";\n if (REDIRECT_OPERATOR.test(word)) index++;\n else if (!ATTACHED_REDIRECT.test(word) && !ASSIGNMENT.test(word)) first = word;\n }\n return first !== undefined && first === commandWords(words).words[0];\n}\n\n/**\n * True when the standard output of the segment reaches the tool output: no\n * word redirects the standard output or the input, and no word runs a\n * process substitution. A redirection of the standard error alone, such as\n * `2>&1` or `2>/dev/null`, keeps the standard output in place.\n */\nfunction printsToOutput(words: ReadonlyArray<string>): boolean {\n return !words.some(\n (word) =>\n ((REDIRECT_OPERATOR.test(word) || ATTACHED_REDIRECT.test(word)) &&\n !STDERR_REDIRECT.test(word)) ||\n word.includes(\"<(\") ||\n word.includes(\">(\"),\n );\n}\n\nfunction detectWorktree(\n args: ReadonlyArray<string>,\n directory: string | undefined,\n home: string,\n findings: Findings,\n): void {\n let optionsEnded = false;\n for (let index = 0; index < args.length; index++) {\n const word = args[index] ?? \"\";\n if (!optionsEnded && word === \"--\") {\n optionsEnded = true;\n } else if (!optionsEnded && WORKTREE_VALUE_OPTIONS[word] === true) {\n index++;\n } else if (optionsEnded || !word.startsWith(\"-\") || word === \"-\") {\n const path = resolvePath(word, directory, home);\n if (path === undefined) {\n findings.note(unresolvedNote(\"git worktree\", \"git worktree remove -- <path>\"));\n } else {\n findings.resource({ kind: \"worktree\", path });\n }\n return;\n }\n }\n}\n\nfunction detectCompose(\n args: ReadonlyArray<string>,\n target: DockerTarget | undefined,\n directory: string | undefined,\n home: string,\n findings: Findings,\n): void {\n const files: Array<string> = [];\n let project: string | undefined;\n let projectDirectory: string | undefined;\n let subcommand: string | undefined;\n for (let index = 0; index < args.length; index++) {\n const word = args[index] ?? \"\";\n const equals = word.startsWith(\"-\") ? word.indexOf(\"=\") : -1;\n const option = equals > 0 ? word.slice(0, equals) : word;\n if (COMPOSE_VALUE_OPTIONS[option] === true) {\n const value = equals > 0 ? word.slice(equals + 1) : args[++index];\n if (value === undefined) break;\n if (option === \"-f\" || option === \"--file\") files.push(value);\n else if (option === \"-p\" || option === \"--project-name\") project = value;\n else if (option === \"--project-directory\") projectDirectory = value;\n } else if (!word.startsWith(\"-\")) {\n subcommand = word;\n break;\n }\n }\n if (subcommand !== \"up\" && subcommand !== \"start\") return;\n\n const unresolved = unresolvedNote(\n \"detached container\",\n \"docker compose --project-directory <path> down\",\n );\n const resolvedFiles: Array<string> = [];\n for (const file of files) {\n const path = file === \"-\" ? undefined : resolvePath(file, directory, home);\n if (path === undefined) {\n findings.note(unresolved);\n return;\n }\n resolvedFiles.push(path);\n }\n const firstFile = resolvedFiles[0];\n const workingDir =\n projectDirectory !== undefined\n ? resolvePath(projectDirectory, directory, home)\n : firstFile !== undefined\n ? dirname(firstFile)\n : directory;\n if (\n target === undefined ||\n workingDir === undefined ||\n (project !== undefined && UNRESOLVED.test(project))\n ) {\n findings.note(unresolved);\n return;\n }\n\n const down = [dockerPrefix(target), \"compose\"];\n if (project !== undefined) down.push(\"-p\", quote(project));\n if (projectDirectory !== undefined || resolvedFiles.length === 0) {\n down.push(\"--project-directory\", quote(workingDir));\n }\n for (const file of resolvedFiles) down.push(\"-f\", quote(file));\n down.push(\"down\");\n findings.resource({ kind: \"compose\", workingDir, down: down.join(\" \"), docker: target });\n}\n\nfunction detectContainer(\n args: ReadonlyArray<string>,\n target: DockerTarget | undefined,\n owned: string | undefined,\n findings: Findings,\n): void {\n const detached = args.some(\n (word) => word === \"--detach\" || word === \"--detach=true\" || SHORT_CLUSTER_WITH_D.test(word),\n );\n const removesItself = args.some((word) => word === \"--rm\" || word === \"--rm=true\");\n if (detached) {\n const fullId = owned === undefined ? undefined : lastContainerIdLine(owned);\n if (target !== undefined && fullId !== undefined) {\n const id = fullId.slice(0, 12);\n const prefix = dockerPrefix(target);\n const down = removesItself\n ? `${prefix} stop ${id}`\n : `${prefix} stop ${id} && ${prefix} rm ${id}`;\n findings.resource({ kind: \"container\", id, down, docker: target });\n } else {\n findings.note(unresolvedNote(\"detached container\", \"docker stop <id>\"));\n }\n }\n if (!removesItself) findings.note(RM_NOTE);\n}\n\n/**\n * The last line that is a full container ID. omp appends notices such as\n * `Wall time: N seconds` after the command output, so the ID need not be the\n * last line.\n */\nfunction lastContainerIdLine(output: string): string | undefined {\n return output\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => CONTAINER_ID.test(line))\n .pop();\n}\n\nfunction otherRules(context: CommandContext, background: boolean): Array<OtherRule> {\n const { name, words } = context;\n const rules: Array<OtherRule> = [];\n const args = words.slice(1);\n const has = (word: string): boolean => args.includes(word);\n const hasAny = (...candidates: Array<string>): boolean => candidates.some(has);\n const global = hasAny(\"-g\", \"--global\");\n\n if (background || name === \"nohup\" || name === \"setsid\" || name === \"disown\" || has(\"disown\")) {\n rules.push(BACKGROUND);\n }\n\n const detachFlag = args.some((word) => SHORT_CLUSTER_WITH_D.test(word));\n if (((name === \"tmux\" && hasAny(\"new\", \"new-session\")) || name === \"screen\") && detachFlag) {\n rules.push(TERMINAL);\n }\n\n const ssh = name === \"ssh\" ? sshFlags(args) : undefined;\n if (\n name === \"ngrok\" ||\n (name === \"cloudflared\" && has(\"tunnel\")) ||\n (name === \"kubectl\" && has(\"port-forward\")) ||\n (ssh !== undefined &&\n (ssh.has(\"L\") || ssh.has(\"R\") || ssh.has(\"D\")) &&\n (ssh.has(\"N\") || ssh.has(\"f\")))\n ) {\n rules.push(TUNNEL);\n }\n\n if (CLUSTER_COMMANDS.some((pattern) => matchesCommand(name, words, pattern))) {\n rules.push(CLUSTER);\n }\n\n const docker = dockerCommand(name, words, context.dockerEnvironment)?.args;\n if (\n docker !== undefined &&\n (docker[0] === \"volume\" || docker[0] === \"network\" || docker[0] === \"buildx\") &&\n docker[1] === \"create\"\n ) {\n rules.push(DOCKER_RESOURCE);\n }\n\n if (\n (name === \"crontab\" && !has(\"-l\")) ||\n name === \"at\" ||\n (name === \"systemctl\" && has(\"--user\") && hasAny(\"enable\", \"start\")) ||\n (name === \"systemd-run\" && has(\"--user\")) ||\n (name === \"launchctl\" && hasAny(\"load\", \"bootstrap\"))\n ) {\n rules.push(SCHEDULED);\n }\n\n if (\n (name === \"npm\" && hasAny(\"i\", \"install\") && global) ||\n (name === \"bun\" && hasAny(\"add\", \"install\", \"i\") && global) ||\n (name === \"pnpm\" && has(\"add\") && global) ||\n (name === \"yarn\" && containsInOrder(args, [\"global\", \"add\"])) ||\n (/^pip[0-9.]*$/.test(name) && has(\"install\") && has(\"--user\")) ||\n ((name === \"pipx\" || name === \"cargo\" || name === \"go\") && has(\"install\"))\n ) {\n rules.push(GLOBAL_INSTALL);\n }\n\n if (\n (name === \"vercel\" && !has(\"env\")) ||\n REMOTE_COMMANDS.some((pattern) => matchesCommand(name, words, pattern))\n ) {\n rules.push(REMOTE);\n }\n return rules;\n}\n\n/**\n * The directory of a `git stash` command that can add a stash entry, else\n * undefined. An unknown directory also gives undefined: the handlers can then\n * read no stash list, so they record nothing and give no note.\n */\nfunction stashDirectory(context: CommandContext, home: string): string | undefined {\n if (context.name !== \"git\") return undefined;\n const git = gitArguments(context.words, context.directory, home);\n if (git.args[0] !== \"stash\" || STASH_WITHOUT_ENTRY[git.args[1] ?? \"\"] === true) return undefined;\n return git.directory;\n}\n\n// ----------------------------------------------------------- reminders ----\n\nfunction resourceKey(resource: HygieneResource): string {\n switch (resource.kind) {\n case \"worktree\":\n case \"scratch\":\n case \"tempDir\":\n case \"tempFile\":\n return `${resource.kind}:${resource.path}`;\n case \"compose\":\n return `compose:${dockerPrefix(resource.docker)}:${resource.workingDir}`;\n case \"container\":\n return `container:${dockerPrefix(resource.docker)}:${resource.id}`;\n case \"stash\":\n return `stash:${resource.gitDir}:${resource.id}`;\n case \"other\":\n return `other:${resource.category}:${resource.command}`;\n }\n}\n\nfunction describeResource(resource: PathResource): string {\n switch (resource.kind) {\n case \"worktree\":\n return `the worktree ${resource.path}`;\n case \"compose\":\n return `the compose project in ${resource.workingDir}`;\n case \"container\":\n return `the container ${resource.id}`;\n case \"scratch\":\n return `the scratch directory ${resource.path}`;\n case \"tempDir\":\n return `the temporary directory ${resource.path}`;\n case \"tempFile\":\n return `the temporary file ${resource.path}`;\n case \"stash\":\n return `the git stash entry ${resource.shortId} (${resource.message}) in ${resource.directory}`;\n }\n}\n\n/**\n * The command that removes the resource. For a stash entry, the command that\n * shows its current `stash@{n}` name: the name of an entry changes when\n * another entry is added or removed, so no fixed pop or drop command is safe.\n * When the worktree of the entry is gone, a read-only list of the common git\n * directory; it needs no worktree.\n */\nexport function cleanupCommand(resource: HygieneResource): string {\n switch (resource.kind) {\n case \"worktree\":\n return `git worktree remove -- ${quote(resource.path)}`;\n case \"compose\":\n case \"container\":\n return resource.down;\n case \"scratch\":\n case \"tempDir\":\n case \"tempFile\":\n return `docks-kit scratch remove ${quote(resource.path)}`;\n case \"stash\":\n return existsSync(resource.directory)\n ? `git -C ${quote(resource.directory)} stash list --format='%h %gd %gs'`\n : `git --git-dir=${quote(resource.gitDir)} stash list --format='%h %gd %gs'`;\n case \"other\":\n return resource.hint;\n }\n}\n\nexport function creationReminder(resource: HygieneResource): string {\n if (resource.kind === \"other\") {\n return `This command created a ${resource.category} (\\`${resource.command}\\`). ${resource.hint}`;\n }\n if (resource.kind === \"stash\") {\n return `The stash list got ${describeResource(resource)} while this command ran. When the task no longer needs it, ${cleanupAction(resource)}.`;\n }\n return `You created ${describeResource(resource)}. When the task no longer needs it, ${cleanupAction(resource)}.`;\n}\n\n/**\n * Names the entry, so the agent does not pop a stash entry of another owner.\n * The user or another session can add an entry while the command runs (see\n * createdStashes). A default message such as `WIP on main: abc1234 subject`\n * does not prove the owner, because two sessions on one branch make the same\n * message. So the agent pops the entry only when it holds a unique message\n * that the agent gave with `-m`, and it never drops the entry. When the\n * worktree of the entry is gone, a pop in another worktree would put the\n * changes into a checkout of the user or of another task, so the reminder\n * then asks only to name the entry.\n */\nfunction cleanupAction(resource: PathResource): string {\n if (resource.kind === \"stash\" && !existsSync(resource.directory)) {\n return `its worktree was removed. Run \\`${cleanupCommand(resource)}\\` to see ${resource.shortId}. Do not pop or drop it, and name it in your final answer`;\n }\n if (resource.kind === \"stash\") {\n return `run \\`${cleanupCommand(resource)}\\` and find ${resource.shortId}. Pop that entry by its \\`stash@{n}\\` name only when its message is a unique message that you gave with \\`-m\\`. Otherwise do not pop or drop it, and name it in your final answer`;\n }\n return `run \\`${cleanupCommand(resource)}\\``;\n}\n\nfunction stopLine(resource: HygieneResource): string {\n if (resource.kind === \"other\") {\n return `- ${resource.category}: \\`${resource.command}\\` (${resource.hint})`;\n }\n return `- ${describeResource(resource)}: ${cleanupAction(resource)}`;\n}\n\nexport function stopReminder(\n verified: ReadonlyArray<HygieneResource>,\n unverified: ReadonlyArray<HygieneResource>,\n): string {\n const lines: Array<string> = [];\n if (verified.length > 0) {\n lines.push(\"These resources from this session still exist:\", ...verified.map(stopLine));\n }\n if (unverified.length > 0) {\n lines.push(\n \"These commands from this session may have left something running, installed, or created:\",\n ...unverified.map(stopLine),\n );\n }\n lines.push(KEEP_SENTENCE);\n return lines.join(\"\\n\");\n}\n\n// ----------------------------------------------------------------- sweep ----\n\nexport function sweepDue(stampMtimeMs: number | undefined, nowMs: number): boolean {\n return stampMtimeMs === undefined || nowMs - stampMtimeMs >= SWEEP_INTERVAL_MS;\n}\n\nfunction mtimeMs(path: string): number | undefined {\n try {\n return statSync(path).mtimeMs;\n } catch {\n return undefined;\n }\n}\n\n/** A probe file of the claim or of the takeover mutex: `<file>.<pid>.<16 hex>.probe`. */\nconst PROBE_FILE = /^tidy\\.stamp\\.(?:claim|takeover)\\.(\\d+)\\.[0-9a-f]{16}\\.probe$/;\n\n/**\n * Creates `<path>.<pid>.<16 hex>.probe` with `wx`, then removes it. True when\n * both calls succeed: the folder lets this process create and delete files.\n * False when a call fails: the folder can deny the operation. A process that\n * stops between the two calls leaves the probe file, and removeExitedProbes\n * removes it later.\n */\nfunction probeSucceeds(path: string): boolean {\n const probe = `${path}.${process.pid}.${randomBytes(8).toString(\"hex\")}.probe`;\n try {\n closeSync(openSync(probe, \"wx\", 0o600));\n unlinkSync(probe);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True on Windows for an error of an operation on `path` that another process\n * causes when it deletes or holds `path`. libuv runs the `node:fs` calls of\n * Bun and Node.js on Windows. It gives EBUSY only for a sharing or lock\n * violation, so EBUSY is always contention. It gives EPERM for\n * ERROR_ACCESS_DENIED. Windows returns that error for an open or a delete of a\n * \"delete pending\" name. Such a name is a deleted file that another process\n * still has open. Windows also returns the error for a folder that denies the\n * operation. Thus EPERM counts as contention only when the probe succeeds;\n * otherwise the caller throws the EPERM. On POSIX, EPERM and EBUSY are real\n * faults, so they stay errors.\n */\nfunction isWindowsContention(error: unknown, path: string): boolean {\n if (process.platform !== \"win32\") return false;\n const code = errorCode(error);\n return code === \"EBUSY\" || (code === \"EPERM\" && probeSucceeds(path));\n}\n\n/**\n * Removes `path`. Ignores a path that is absent or, on Windows, a path that\n * another process deletes or holds.\n */\nfunction removeIfPresent(path: string): void {\n try {\n unlinkSync(path);\n } catch (error) {\n if (errorCode(error) !== \"ENOENT\" && !isWindowsContention(error, path)) throw error;\n }\n}\n\n/**\n * Creates `path` with `wx` and writes an owner token into it. Returns the\n * token, or undefined when the file exists or, on Windows, when another\n * process deletes or holds it now.\n */\nfunction createOwned(path: string): string | undefined {\n let descriptor: number;\n try {\n descriptor = openSync(path, \"wx\", 0o600);\n } catch (error) {\n if (errorCode(error) === \"EEXIST\" || isWindowsContention(error, path)) return undefined;\n throw error;\n }\n const token = `${process.pid} ${randomUUID()}`;\n try {\n writeFileSync(descriptor, token);\n } finally {\n closeSync(descriptor);\n }\n return token;\n}\n\n/**\n * Removes `path` only when it still holds `token`, so that no process removes\n * the file of another. Ignores a path that is absent or, on Windows, a path\n * that another process deletes or holds. Such a file stays until it is stale.\n */\nfunction releaseOwned(path: string, token: string): void {\n try {\n if (readFileSync(path, \"utf8\") === token) unlinkSync(path);\n } catch (error) {\n if (errorCode(error) !== \"ENOENT\" && !isWindowsContention(error, path)) throw error;\n }\n}\n\n/** True when no process has `pid`: `process.kill(pid, 0)` fails with ESRCH. */\nfunction hasExited(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return false;\n } catch (error) {\n return errorCode(error) === \"ESRCH\";\n }\n}\n\n/**\n * Removes each probe file of the claim and of the takeover mutex whose process\n * has exited. Keeps the probe file of a running process, which removes it.\n * The removal is best effort and makes no probe. So a folder that denies\n * deletes keeps the file and cannot get a new probe file on each sweep.\n */\nfunction removeExitedProbes(cacheDir: string): void {\n for (const name of readdirSync(cacheDir)) {\n const pid = PROBE_FILE.exec(name)?.[1];\n if (pid === undefined || !hasExited(Number(pid))) continue;\n try {\n unlinkSync(join(cacheDir, name));\n } catch {\n // The next sweep tries again.\n }\n }\n}\n\n/** True when `path` is missing or older than CLAIM_STALE_MS: its process stopped. */\nfunction isStale(path: string, nowMs: number): boolean {\n const mtime = mtimeMs(path);\n return mtime === undefined || nowMs - mtime > CLAIM_STALE_MS;\n}\n\n/**\n * Creates the claim and returns its token, or returns undefined when another\n * process holds it. Only the holder of the takeover mutex replaces a stale\n * claim, and it checks the claim again while it holds the mutex. A stale\n * takeover can still let two processes claim the sweep. Each then starts\n * `docks-kit tidy --apply`, and the second one finds `tidy-lock.db` held and\n * stops, or plans from the current state after the first one ends. Thus a\n * duplicate claim only adds load; the claim limits load and does not protect\n * files. On Windows, a create that fails because another process deletes or\n * holds the file gives no token for that attempt. When the claim is then stale\n * or gone, the takeover path can still take it; otherwise a later main session\n * claims the sweep. A delete or a release that fails this way removes nothing.\n */\nfunction acquireClaim(cacheDir: string, nowMs: number): string | undefined {\n const claim = join(cacheDir, CLAIM_FILE);\n const token = createOwned(claim);\n if (token !== undefined || !isStale(claim, nowMs)) return token;\n\n const takeover = join(cacheDir, TAKEOVER_FILE);\n let mutex = createOwned(takeover);\n if (mutex === undefined && isStale(takeover, nowMs)) {\n removeIfPresent(takeover);\n mutex = createOwned(takeover);\n }\n if (mutex === undefined) return undefined;\n try {\n if (!isStale(claim, nowMs)) return undefined;\n removeIfPresent(claim);\n return createOwned(claim);\n } finally {\n releaseOwned(takeover, mutex);\n }\n}\n\n/**\n * Lets one process in each sweep interval start the sweep. It first removes\n * the probe files of exited processes. The process that holds\n * `tidy.stamp.claim` reads the stamp again. When the sweep is still due, it\n * writes the stamp and returns true. In each case, it then releases its claim.\n * When the release fails on Windows because of contention, the claim stays\n * until it is stale.\n */\nexport function claimSweep(cacheDir: string, nowMs: number): boolean {\n mkdirSync(cacheDir, { recursive: true, mode: 0o700 });\n chmodSync(cacheDir, 0o700);\n removeExitedProbes(cacheDir);\n const token = acquireClaim(cacheDir, nowMs);\n if (token === undefined) return false;\n try {\n const stamp = join(cacheDir, STAMP_FILE);\n if (!sweepDue(mtimeMs(stamp), nowMs)) return false;\n writeFileSync(stamp, \"\", { mode: 0o600 });\n chmodSync(stamp, 0o600);\n const seconds = nowMs / 1000;\n utimesSync(stamp, seconds, seconds);\n return true;\n } finally {\n releaseOwned(join(cacheDir, CLAIM_FILE), token);\n }\n}\n\n// ---------------------------------------------------------------- ledger ----\n\n/**\n * One omp process shares module state across its sessions, so the main\n * session also sees the resources that its subagents created.\n */\nconst ledger = new Map<string, HygieneResource>();\nconst reminded = new Set<string>();\n/**\n * The stash IDs of each directory of a bash call before the call ran, keyed\n * by tool call ID. The tool_result handler takes the snapshot out. omp sends\n * no tool_result for a call that it blocks or that the user denies after the\n * tool_call handler, but it sends tool_execution_end for each call after its\n * tool_result, so that handler removes the snapshot of such a call.\n */\nconst stashSnapshots = new Map<string, ReadonlyMap<string, ReadonlySet<string>>>();\n\nasync function dockerListsAny(target: DockerTarget, args: ReadonlyArray<string>): Promise<boolean> {\n try {\n const result = await run(\"docker\", [...target.options, ...args], {\n env: { ...process.env, ...target.environment },\n timeoutMs: DOCKER_CHECK_TIMEOUT_MS,\n });\n return result.code === 0 && result.stdout.trim() !== \"\";\n } catch {\n return false;\n }\n}\n\n/**\n * The entries of `git <location> stash list`, or undefined when git fails or\n * the timeout stops it.\n */\nasync function stashList(\n location: ReadonlyArray<string>,\n timeoutMs: number,\n): Promise<Array<StashEntry> | undefined> {\n try {\n const result = await run(\"git\", [...location, \"stash\", \"list\", STASH_LIST_FORMAT], {\n timeoutMs,\n });\n if (result.code !== 0) return undefined;\n return result.stdout\n .split(/\\r?\\n/)\n .filter((line) => line !== \"\")\n .map((line) => {\n const [id = \"\", shortId = \"\", message = \"\"] = line.split(\"\\0\");\n return { id, shortId, message };\n });\n } catch {\n return undefined;\n }\n}\n\n/** The absolute common git directory of `directory`, or undefined when git fails. */\nasync function commonGitDir(directory: string): Promise<string | undefined> {\n try {\n const result = await run(\"git\", [\"-C\", directory, \"rev-parse\", \"--git-common-dir\"], {\n timeoutMs: GIT_CHECK_TIMEOUT_MS,\n });\n const path = result.stdout.trim();\n return result.code === 0 && path !== \"\" ? resolve(directory, path) : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function stillExists(resource: HygieneResource): Promise<boolean> {\n switch (resource.kind) {\n case \"worktree\":\n case \"scratch\":\n case \"tempDir\":\n case \"tempFile\":\n return existsSync(resource.path);\n case \"compose\":\n return dockerListsAny(resource.docker, [\n \"ps\",\n \"-q\",\n \"--filter\",\n `label=com.docker.compose.project.working_dir=${resource.workingDir}`,\n ]);\n case \"container\":\n return dockerListsAny(resource.docker, [\"ps\", \"-aq\", \"--filter\", `id=${resource.id}`]);\n case \"stash\": {\n // The read uses the common git directory, so it also works after the\n // agent removes the worktree where the command ran. A failed read gives\n // no reminder, the same as dockerListsAny. The read fails mainly when\n // the repository is gone, and its stash list is then gone too. A\n // reminder that the extension cannot check is a possible false reminder.\n const entries = await stashList([`--git-dir=${resource.gitDir}`], GIT_CHECK_TIMEOUT_MS);\n return entries?.some((entry) => entry.id === resource.id) === true;\n }\n case \"other\":\n return true;\n }\n}\n\nfunction textResult(text: string, details: Record<string, unknown>): ToolResult {\n return { content: [{ type: \"text\", text }], details };\n}\n\n/** The command and the directory of a bash call that TRIGGER matches, else undefined. */\nfunction bashCall(\n event: ToolCallEvent,\n ctx: ExtensionContext,\n): { command: string; cwd: string } | undefined {\n if (event.toolName !== \"bash\") return undefined;\n const command = event.input?.[\"command\"];\n if (typeof command !== \"string\" || !TRIGGER.test(command)) return undefined;\n return { command, cwd: resolve(ctx.cwd, String(event.input?.[\"cwd\"] ?? \".\")) };\n}\n\n/**\n * Before a bash call runs, reads the stash list of each directory where the\n * call can add a stash entry. createdStashes compares it with the list after\n * the call. Only this comparison proves which entries the call can have\n * added:\n *\n * - `git stash push -q` prints nothing, also when it adds an entry.\n * - With nothing to save, it adds no entry, and `refs/stash` still names an\n * older entry, which can belong to the user.\n * - A tool_result handler cannot read the list as it was before the call.\n *\n * The read delays the command, so it has a short timeout. A directory whose\n * list git cannot read in that time gets no snapshot, so the call then\n * records no stash there.\n */\nasync function stashesBefore(event: ToolCallEvent, ctx: ExtensionContext): Promise<void> {\n const call = bashCall(event, ctx);\n if (call === undefined || event.toolCallId === undefined) return;\n const { stashes } = detectResources(call.command, call.cwd, \"\", homedir());\n if (stashes.length === 0) return;\n const snapshot = new Map<string, ReadonlySet<string>>();\n await Promise.all(\n stashes.map(async (directory) => {\n const entries = await stashList([\"-C\", directory], STASH_SNAPSHOT_TIMEOUT_MS);\n if (entries !== undefined) snapshot.set(directory, new Set(entries.map((entry) => entry.id)));\n }),\n );\n stashSnapshots.set(event.toolCallId, snapshot);\n}\n\n/**\n * The stash entries that are in the list after the call and not in its\n * snapshot. The user or another session can add an entry between the two\n * reads, for example while omp waits for the approval of the call, and that\n * entry also counts. So the reminder names the entry and its message, and it\n * tells the agent to check the message and never to drop the entry.\n */\nasync function createdStashes(\n directories: ReadonlyArray<string>,\n snapshot: ReadonlyMap<string, ReadonlySet<string>> | undefined,\n): Promise<Array<HygieneResource>> {\n if (snapshot === undefined) return [];\n const created = await Promise.all(\n directories.map(async (directory): Promise<Array<HygieneResource>> => {\n const before = snapshot.get(directory);\n if (before === undefined) return [];\n const [entries, gitDir] = await Promise.all([\n stashList([\"-C\", directory], GIT_CHECK_TIMEOUT_MS),\n commonGitDir(directory),\n ]);\n if (entries === undefined || gitDir === undefined) return [];\n return entries\n .filter((entry) => !before.has(entry.id))\n .map((entry) => ({\n kind: \"stash\",\n directory,\n gitDir,\n id: entry.id,\n shortId: entry.shortId,\n message: entry.message.slice(0, COMMAND_TEXT_LIMIT),\n }));\n }),\n );\n return created.flat();\n}\n\n/**\n * Records each resource that a bash command created and returns its reminder\n * lines and the notes on resources that the command can create.\n */\nasync function resourceLines(event: ToolResultEvent, ctx: ExtensionContext): Promise<Array<string>> {\n const id = event.toolCallId;\n const snapshot = id === undefined ? undefined : stashSnapshots.get(id);\n if (id !== undefined) stashSnapshots.delete(id);\n const failed = event.isError === true;\n // A failed call can still have added a stash entry, as in\n // `git stash push -q && false`, so the stash lists are compared also then.\n if (failed && snapshot === undefined) return [];\n const call = bashCall(event, ctx);\n if (call === undefined) return [];\n const output = (event.content ?? [])\n .map((block) => (block.type === \"text\" && typeof block.text === \"string\" ? block.text : \"\"))\n .join(\"\\n\");\n const detected = detectResources(call.command, call.cwd, output, homedir());\n const resources: Array<HygieneResource> = failed ? [] : detected.resources;\n resources.push(...(await createdStashes(detected.stashes, snapshot)));\n for (const resource of resources) ledger.set(resourceKey(resource), resource);\n return [...resources.map(creationReminder), ...(failed ? [] : detected.notes)];\n}\n\n// ------------------------------------------------------------- extension ----\n\nexport default function docksKitOmp(pi: ExtensionApi): void {\n const z = pi.zod;\n /**\n * The message of the error that stopped the last sweep start. The next tool\n * result of the main session shows it one time.\n */\n let sweepError: string | undefined;\n\n pi.registerTool<{ label: string }>({\n name: \"scratch_new\",\n label: \"Scratch New\",\n description:\n \"Create a private temporary directory under the docks-kit scratch root and return its path. Use it instead of /tmp, also for a single temporary file. Remove it with scratch_remove when the task no longer needs it.\",\n parameters: z.object({\n label: z.string().describe(\"Short name: letters, digits, dot, underscore, or hyphen\"),\n }),\n async execute(_toolCallId, params, signal) {\n try {\n if (!LABEL_PATTERN.test(params.label)) throw new Error(LABEL_ERROR);\n const output = await runDocksKit(\n [\"scratch\", \"new\", params.label],\n signal,\n SCRATCH_TIMEOUT_MS,\n );\n const path = lastAbsoluteLine(output);\n if (path === undefined) throw new Error(`docks-kit scratch new printed no path: ${output}`);\n const resource: HygieneResource = { kind: \"scratch\", path };\n ledger.set(resourceKey(resource), resource);\n return textResult(path, { path });\n } catch (error) {\n throw toError(error);\n }\n },\n });\n\n pi.registerTool<{ paths: Array<string> }>({\n name: \"scratch_remove\",\n label: \"Scratch Remove\",\n description:\n \"Remove temporary files and directories that you created. Use it instead of gio trash, which does not work on a tmpfs /tmp. Accepts only absolute paths inside the docks-kit scratch root, the system temporary directory, or /var/tmp; refuses every other path.\",\n parameters: z.object({\n paths: z.array(z.string()).describe(\"Absolute paths\"),\n }),\n async execute(_toolCallId, params, signal) {\n try {\n if (params.paths.length === 0) throw new Error(\"paths must not be empty\");\n const relative = params.paths.find((path) => !isAbsolute(path));\n if (relative !== undefined) throw new Error(`path must be absolute: ${relative}`);\n const output = await runDocksKit(\n [\"scratch\", \"remove\", ...params.paths],\n signal,\n SCRATCH_TIMEOUT_MS,\n );\n return textResult(output.trim(), { paths: params.paths });\n } catch (error) {\n throw toError(error);\n }\n },\n });\n\n pi.registerTool<Record<string, never>>({\n name: \"tidy_report\",\n label: \"Tidy Report\",\n description:\n \"List agent leftovers and other disk and memory use (worktrees, containers, orphaned processes, scratch, /tmp, caches, Trash, branches, scheduled jobs, global installs). Read-only.\",\n parameters: z.object({}),\n async execute(_toolCallId, _params, signal) {\n try {\n const output = await runDocksKit([\"tidy\", \"--report\"], signal, REPORT_TIMEOUT_MS);\n return textResult(output.trim(), {});\n } catch (error) {\n throw toError(error);\n }\n },\n });\n\n pi.on(\"tool_call\", async (event, ctx) => {\n // omp blocks the call when a tool_call handler throws, so a failed stash\n // read must end here. The call then records no stash.\n try {\n await stashesBefore(event, ctx);\n } catch {\n // Nothing to do: createdStashes finds no snapshot.\n }\n return undefined;\n });\n\n pi.on(\"tool_result\", async (event, ctx) => {\n let lines: Array<string>;\n try {\n lines = await resourceLines(event, ctx);\n } catch {\n lines = [];\n }\n if (ctx.agent?.kind !== \"sub\" && sweepError !== undefined) {\n lines.push(`docks-kit sweep did not start: ${sweepError}`);\n sweepError = undefined;\n }\n return lines.length === 0 ? undefined : { additionalContext: lines.join(\"\\n\") };\n });\n\n pi.on(\"tool_execution_end\", async (event) => {\n if (event.toolCallId !== undefined) stashSnapshots.delete(event.toolCallId);\n return undefined;\n });\n\n pi.on(\"session_stop\", async (event) => {\n try {\n if (event.stop_hook_active === true) return undefined;\n const pending = [...ledger].filter(([key]) => !reminded.has(key));\n if (pending.length === 0) return undefined;\n const states = await Promise.all(\n pending.map(async ([key, resource]) => ({\n key,\n resource,\n exists: await stillExists(resource),\n })),\n );\n const verified: Array<HygieneResource> = [];\n const unverified: Array<HygieneResource> = [];\n for (const { key, resource, exists } of states) {\n if (!exists) {\n ledger.delete(key);\n continue;\n }\n reminded.add(key);\n if (resource.kind === \"other\") unverified.push(resource);\n else verified.push(resource);\n }\n if (verified.length === 0 && unverified.length === 0) return undefined;\n return { continue: true, additionalContext: stopReminder(verified, unverified) };\n } catch {\n return undefined;\n }\n });\n\n pi.on(\"session_start\", async (_event, ctx) => {\n try {\n if (ctx.agent?.kind === \"sub\") return undefined;\n // The same directory as kitCacheDir in the docks-kit CLI.\n const cacheDir = join(homedir(), \".cache\", \"docks-kit\");\n const now = Date.now();\n if (!sweepDue(mtimeMs(join(cacheDir, STAMP_FILE)), now)) return undefined;\n let docksKit: string;\n try {\n docksKit = resolveDocksKit();\n } catch {\n // A checkout user who runs ./docks-kit has no launcher on PATH. A line\n // in each session would only repeat that, so the sweep stays silent.\n return undefined;\n }\n if (!claimSweep(cacheDir, now)) return undefined;\n const child = spawn(docksKit, [\"tidy\", \"--apply\"], {\n cwd: homedir(),\n detached: true,\n shell: false,\n stdio: \"ignore\",\n windowsHide: true,\n });\n child.on(\"error\", () => {});\n child.unref();\n } catch (error) {\n // A sweep that cannot start must not stop the session; the next tool\n // result of the main session reports it.\n sweepError = error instanceof Error ? error.message : String(error);\n }\n return undefined;\n });\n}\n",
|
|
27
27
|
"SoT/.omp/plugin/extensions/pluginUpgrades.ts": "/**\n * docks-kit-omp extension: plugin upgrade reminders for omp sessions.\n *\n * omp deletes the previous plugin folder on `omp plugin upgrade`. A running\n * omp session keeps the plugin agents that it found at startup. So these\n * agents can fail after an upgrade, until the user runs /reload-plugins. The\n * skills of the session resolve to the new folder through `skill://`.\n * `docks-kit sync` writes one event file for each upgrade that changed a\n * version, or that can have changed it (the version `unknown`).\n *\n * In each tool_result of a main session, this extension reads the events that\n * finished after this omp process started. It adds one reminder for the events\n * that the session did not get before. A folder or file that it cannot read\n * gives no reminder for that tool result. The next tool result reads it again.\n *\n * The module imports only node: modules, so omp loads it without a package\n * install.\n */\nimport { readdirSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\n// ------------------------------------------------------------- constants ----\n\n/**\n * The start of this omp process. omp finds the plugin folders before it\n * imports extension modules, so a later upgrade can remove a loaded folder.\n */\nconst PROCESS_START_MS = Date.now() - process.uptime() * 1000;\n\n/** An event file name that `docks-kit sync` writes; a temporary name does not match. */\nconst EVENT_FILE = /^\\d+-[0-9a-f]+\\.json$/;\n/** A plugin id or version that the reminder can name without a quote. */\nconst SAFE_TOKEN = /^[A-Za-z0-9._@+-]+$/;\n\n// ----------------------------------------------------------- omp API types ----\n\n// The local structural types below name only the omp extension API parts\n// that this module uses. The module does not import @oh-my-pi packages.\n\ninterface ExtensionContext {\n readonly agent?: { readonly kind: \"main\" | \"sub\" };\n readonly sessionManager?: { getSessionId(): string };\n}\n\nexport interface ExtensionApi {\n on(\n event: \"tool_result\",\n handler: (\n event: unknown,\n ctx: ExtensionContext,\n ) => Promise<{ additionalContext: string } | undefined>,\n ): void;\n}\n\n// ---------------------------------------------------------------- events ----\n\n/** One plugin upgrade that `docks-kit sync` recorded. */\nexport interface PluginUpgradeEvent {\n readonly id: string;\n readonly before: string;\n readonly after: string;\n /** The time in milliseconds just after the upgrade command returned. */\n readonly finishedAtMs: number;\n}\n\n/** The upgrade log folder; `ompPlugins.ts syncPlugins` in the docks-kit CLI writes it. */\nexport function upgradeLogDir(home: string): string {\n return join(home, \".cache\", \"docks-kit\", \"omp-plugin-upgrades\");\n}\n\n/** The event in one event file, or undefined when the file is not a version 1 event. */\nexport function parseUpgradeEvent(text: string): PluginUpgradeEvent | undefined {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n return undefined;\n }\n if (typeof value !== \"object\" || value === null) return undefined;\n const { version, id, before, after, finishedAt } = value as Record<string, unknown>;\n if (version !== 1) return undefined;\n if (typeof id !== \"string\" || typeof before !== \"string\" || typeof after !== \"string\") {\n return undefined;\n }\n if (![id, before, after].every((token) => SAFE_TOKEN.test(token))) return undefined;\n const finishedAtMs = typeof finishedAt === \"string\" ? Date.parse(finishedAt) : Number.NaN;\n if (!Number.isFinite(finishedAtMs)) return undefined;\n return { id, before, after, finishedAtMs };\n}\n\n/** The reminder that names each upgrade. */\nexport function upgradeReminder(events: ReadonlyArray<PluginUpgradeEvent>): string {\n const upgrades = events.map((event) => `${event.id} ${event.before} -> ${event.after}`);\n return [\n `docks-kit sync upgraded these omp plugins after this omp process started: ${upgrades.join(\", \")}.`,\n \"omp removes the old plugin folder on upgrade, so this session's plugin agents may fail.\",\n \"Ask the user to run /reload-plugins in this session, then read each plugin skill again through skill:// before you run its scripts.\",\n \"Ask the user to restart omp instead when an upgraded plugin ships hooks, extension modules, or non-MCP tools.\",\n ].join(\" \");\n}\n\n// ------------------------------------------------------------- extension ----\n\nexport interface PluginUpgradesOptions {\n /** The home folder that holds the upgrade log. */\n readonly home: string;\n /** Events that finished at or before this time give no reminder. */\n readonly processStartMs: number;\n}\n\n/** The extension factory for one home folder and one process start. */\nexport function pluginUpgrades(options: PluginUpgradesOptions): (pi: ExtensionApi) => void {\n const dir = upgradeLogDir(options.home);\n /** Each event file read so far; undefined marks a file whose content is not an event. */\n const read = new Map<string, PluginUpgradeEvent | undefined>();\n /** For each session id, the event files that its reminders named. */\n const told = new Map<string, Set<string>>();\n\n /** The events of the log. Each file name is read until one read succeeds. */\n function currentEvents(): Array<{ name: string; event: PluginUpgradeEvent }> {\n let names: Array<string>;\n try {\n names = readdirSync(dir).filter((name) => EVENT_FILE.test(name));\n } catch {\n // A missing folder holds no events. Another error gives no events now,\n // and the next tool result reads the folder again.\n return [];\n }\n const present = new Set(names);\n // Sync prunes old files, so the cache forgets the names that are gone.\n for (const name of read.keys()) if (!present.has(name)) read.delete(name);\n const events: Array<{ name: string; event: PluginUpgradeEvent }> = [];\n for (const name of names) {\n if (!read.has(name)) {\n let text: string;\n try {\n text = readFileSync(join(dir, name), \"utf8\");\n } catch {\n // A prune removed the file (ENOENT), or the read failed for now.\n // The name stays out of the cache, so the next tool result reads it again.\n continue;\n }\n read.set(name, parseUpgradeEvent(text));\n }\n const event = read.get(name);\n if (event !== undefined) events.push({ name, event });\n }\n return events;\n }\n\n return (pi) => {\n pi.on(\"tool_result\", async (_event, ctx) => {\n try {\n if (ctx.agent?.kind !== \"main\") return undefined;\n const sessionId = ctx.sessionManager?.getSessionId();\n if (sessionId === undefined || sessionId === \"\") return undefined;\n const toldSession = told.get(sessionId) ?? new Set<string>();\n const fresh = currentEvents()\n .filter(\n ({ name, event }) =>\n event.finishedAtMs > options.processStartMs && !toldSession.has(name),\n )\n .sort(\n (a, b) => a.event.finishedAtMs - b.event.finishedAtMs || (a.name < b.name ? -1 : 1),\n );\n if (fresh.length === 0) return undefined;\n for (const { name } of fresh) toldSession.add(name);\n told.set(sessionId, toldSession);\n return { additionalContext: upgradeReminder(fresh.map(({ event }) => event)) };\n } catch {\n return undefined;\n }\n });\n };\n}\n\nexport default function docksKitPluginUpgrades(pi: ExtensionApi): void {\n pluginUpgrades({ home: homedir(), processStartMs: PROCESS_START_MS })(pi);\n}\n",
|
|
28
|
-
"SoT/.omp/plugin/skills/workspace-hygiene/SKILL.md": "---\nname: workspace-hygiene\ndescription: Use when a task creates or ends with worktrees, temporary files or directories, servers, watchers, test runners, containers, clusters, tunnels, scheduled jobs, global installs, or remote test resources, or when disk or memory fills up. Says where to create each resource and how to remove it. Not for git history cleanup or dead-code removal.\n---\n\n# Workspace hygiene\n\n<constraint>\nRemove only what this task created. Never delete user data, named Docker volumes, or anything outside the classes in this skill. In the main session, ask the user first; in a subagent, list the item in your final report. Every local workstation resource is a development resource. Stop or delete a production resource only after an `ask` in the main session; see Production resources.\n</constraint>\n\n## Track what you create\n\nWhile you work, keep a list of each resource that you create.\nFor each resource, write its path, id, port, or remote name.\n\n## Resource classes\n\n| Class | Create | Remove | Keep when |\n|---|---|---|---|\n| Git worktree | `<data>/agent-worktrees/<repo>/<name>`; reuse a worktree of the same branch | `git worktree remove -- <path>`, then `git worktree prune`; one `--force` only after the commits are on the remote and the changes are generated files | its pull request is open |\n| Temporary file or directory | a directory from `scratch_new` or `docks-kit scratch new <label>`; each temporary file inside it; never `/tmp` | `scratch_remove`, or `docks-kit scratch remove <path>`; `gio trash` does not work on a `tmpfs` `/tmp` | a later step reads it |\n| Test artifacts (coverage, test results, traces, screenshots, videos) | inside the worktree, git-ignored | removed with the worktree; in the user's checkout, `gio trash -- <path>` | the user asked for them |\n| Server, watcher, test runner, browser | named bash service or async job; single-run tests | `write proc://<id>/kill`; outside omp, `kill <pid>` | the user asked for it |\n| Container or compose stack | `docker run --rm`; `docker compose up` in the worktree; no restart policy | `docker compose down`; `docker stop <id>`; on a remote Docker host, only for a development target; ask first for production | its worktree is kept |\n| Docker volume, network, or buildx builder that the task created | only for the task | `docker volume rm`, `docker network rm`, `docker buildx rm` | never |\n| Cluster or virtual machine | only on request | the tool's stop or delete command; for a remote cluster, only for a development target; ask first for production | the user asked for it |\n| Tunnel or port forward | named bash service | stop the local service; delete a remote tunnel only for a development target; ask first for production | the user asked for it |\n| Detached terminal session | do not create | `tmux kill-session -t <name>`, `screen -S <name> -X quit` | never |\n| Scheduled job or service | only on request | remove the entry or unit | the user asked for it |\n| Global install | only on request | the matching uninstall command | the user asked for it |\n| Git stash or local branch | avoid stash; one branch per plan |
|
|
28
|
+
"SoT/.omp/plugin/skills/workspace-hygiene/SKILL.md": "---\nname: workspace-hygiene\ndescription: Use when a task creates or ends with worktrees, temporary files or directories, servers, watchers, test runners, containers, clusters, tunnels, scheduled jobs, global installs, or remote test resources, or when disk or memory fills up. Says where to create each resource and how to remove it. Not for git history cleanup or dead-code removal.\n---\n\n# Workspace hygiene\n\n<constraint>\nRemove only what this task created. Never delete user data, named Docker volumes, or anything outside the classes in this skill. In the main session, ask the user first; in a subagent, list the item in your final report. Every local workstation resource is a development resource. Stop or delete a production resource only after an `ask` in the main session; see Production resources.\n</constraint>\n\n## Track what you create\n\nWhile you work, keep a list of each resource that you create.\nFor each resource, write its path, id, port, or remote name.\n\n## Resource classes\n\n| Class | Create | Remove | Keep when |\n|---|---|---|---|\n| Git worktree | `<data>/agent-worktrees/<repo>/<name>`; reuse a worktree of the same branch | `git worktree remove -- <path>`, then `git worktree prune`; one `--force` only after the commits are on the remote and the changes are generated files | its pull request is open |\n| Temporary file or directory | a directory from `scratch_new` or `docks-kit scratch new <label>`; each temporary file inside it; never `/tmp` | `scratch_remove`, or `docks-kit scratch remove <path>`; `gio trash` does not work on a `tmpfs` `/tmp` | a later step reads it |\n| Test artifacts (coverage, test results, traces, screenshots, videos) | inside the worktree, git-ignored | removed with the worktree; in the user's checkout, `gio trash -- <path>` | the user asked for them |\n| Server, watcher, test runner, browser | named bash service or async job; single-run tests | `write proc://<id>/kill`; outside omp, `kill <pid>` | the user asked for it |\n| Container or compose stack | `docker run --rm`; `docker compose up` in the worktree; no restart policy | `docker compose down`; `docker stop <id>`; on a remote Docker host, only for a development target; ask first for production | its worktree is kept |\n| Docker volume, network, or buildx builder that the task created | only for the task | `docker volume rm`, `docker network rm`, `docker buildx rm` | never |\n| Cluster or virtual machine | only on request | the tool's stop or delete command; for a remote cluster, only for a development target; ask first for production | the user asked for it |\n| Tunnel or port forward | named bash service | stop the local service; delete a remote tunnel only for a development target; ask first for production | the user asked for it |\n| Detached terminal session | do not create | `tmux kill-session -t <name>`, `screen -S <name> -X quit` | never |\n| Scheduled job or service | only on request | remove the entry or unit | the user asked for it |\n| Global install | only on request | the matching uninstall command | the user asked for it |\n| Git stash or local branch | avoid stash; if you must stash, give a unique message with `-m`; one branch per plan | find the short ID that the reminder names with `git stash list --format='%h %gd %gs'`; pop that entry by its `stash@{n}` name, in the worktree where you made it, only when its message is a unique message that you gave with `-m`; otherwise do not pop or drop it, and name it in your final answer; when that worktree is removed, do not pop the entry in another worktree, and name it in your final answer; never apply, pop, or drop a stash entry that you did not create; `git branch -d <branch>` after the merge | the branch has an open pull request |\n| Remote test resource (database branch, preview deployment, fork, cloud instance) | only for the task | the provider's delete command, only for a development or preview target; ask first for production | the user asked for it |\n| Package or tool cache | never in `/tmp` | do not prune; report the size | always |\n\n## Production resources\n\n- A local workstation resource is always a development resource. This includes worktrees, local compose stacks, local servers and processes, scratch directories, and temporary files and directories. Remove it as this skill says, without an additional question.\n- A remote resource is a resource that you reach through SSH or a provider CLI, for example `wrangler`, `vercel`, `netlify`, `fly`, `supabase`, `neonctl`, `pscale`, `kubectl`, or `gh`. A Docker host that `DOCKER_HOST`, `DOCKER_CONTEXT`, or `docker --context` selects is also remote.\n- A remote target is a development target only when its name is `local`, `development`, `dev`, `test`, `homolog`, `homologation`, `staging`, or `preview`. Every other target is production.\n- Clean up a remote resource with a development target as this skill says.\n- Stop, remove, undeploy, or delete a production resource only after an `ask` in the main session immediately before the action. Do this rarely. A yolo run does not answer this ask.\n- In a subagent, never clean up a production resource. Name it in your final report.\n- Example: `wrangler delete` without `--env` acts on the top-level Worker. That Worker is usually production, so ask first.\n\n## Before your final answer\n\n1. Find each resource of your list in the table.\n2. Remove each resource that the task no longer needs. Use the command in the `Remove` column.\n3. Name each resource that you keep, and give the reason from the `Keep when` column.\n\n## Find what you cannot see\n\nRun the `tidy_report` tool, or run `docks-kit tidy --report`.\nAct only on the items that this task created.\nReport the other items to the user.\n\n## Plan runs\n\n- For a plan run, follow the Teardown rule in the `plan-lifecycle` plan contract (`plan-manager/references/plan-contract.md`). That rule decides when the run stops stacks and processes, removes the linked worktree, deletes the branch, and keeps a resource.\n\n## Automatic sweep\n\nOne time in 12 hours, a main session starts `docks-kit tidy --apply`.\nThe sweep removes merged idle worktrees and their containers.\nIt stops orphaned processes in agent directories.\nIt removes scratch directories that are idle for 7 days.\nDo not rely on the sweep for a resource that the task can remove itself.\n",
|
|
29
29
|
"SoT/.omp/plugin/commands/cleanup.md": "---\ndescription: Remove what this session created and list other leftovers\n---\nFollow the workspace-hygiene skill. List each resource that this session created. Remove each one that the task no longer needs. Remove only local resources and remote resources whose target is not production. For a production resource, ask first, and keep it if you get no answer. Then run tidy_report, and report the items that this session did not create without removing them.\n"
|
|
30
30
|
} as const
|
|
31
31
|
|
|
@@ -60,4 +60,4 @@ export const GENERATED_PAYLOAD_PATHS = [
|
|
|
60
60
|
"notification.mp3"
|
|
61
61
|
] as const
|
|
62
62
|
|
|
63
|
-
export const GENERATED_PAYLOAD_HASH = "
|
|
63
|
+
export const GENERATED_PAYLOAD_HASH = "a90b2be634be9fe6b3b7e4188475c24f15513d75fba718dd300f10f2ae407b2a"
|