SLOPSHOPPER

sandbox-tuner

Explains each Claude Code sandbox block in plain words and turns recurring blocks into reviewed, one-press, undoable edits of your user settings.

panebandguardcommandtimer
v1.3.1MITupdated 2026-10-25dot-agi/sandbox-tuner
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · sandbox-tuner
│ ┃ Sandbox Tuner ✕ › fix the failing auth test and add an audit log call │ ┃ Settings file: ~/.claude/settings.json │ ┃ The sandbox is off in this session. Sandbox ● sandbox-tuner: sandbox-tuner: tool.call (Bash): hook failed (throw) │ ┃ Tuner has nothing to tune. ● sandbox-tuner: sandbox-tuner: tool.call (Bash): hook failed (throw) │ ┃ ⏺ Read(src/auth.ts) │ ┃ Sandbox Tuner has not seen a sandbox block ⎿ Read 6 lines │ ┃ in this session yet. ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /sandbox-tuner │ ⎿ sandbox-tuner: 0 fixes ready, 0 targets. The pane is open. │ ● sandbox-tuner: sandbox-tuner: tool.call (Bash): hook failed (throw) │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Sandbox Tuner
Settings file: ~/.claude/settings.json The sandbox is off in this session. Sandbox Tuner has nothing to tune. Sandbox Tuner has not seen a sandbox block in this session yet.
README

<img src="https://img.shields.io/badge/Claude_Code-2.1.288%2B-D97757" alt="Claude Code 2.1.288+"> <img src="https://img.shields.io/badge/Claude_Code-mod-555555" alt="Claude Code mod"> <img src="https://img.shields.io/badge/license-MIT-78997A" alt="License: MIT"> <img src="https://img.shields.io/badge/version-1.3.1-555555" alt="Version: 1.3.1">

Terminal: a sandboxed curl to example.org fails. The band names the block, counts the sightings, states the exact settings change, and shows Allow.

After a repeated network block, the band explains it and offers Allow.

Why

Sandbox blocks can look like broken networking or file permissions, and the same targets can fail again next session. Sandbox Tuner handles sandbox blocks, not permission prompts: it explains the blocks that it recognizes, within the known limits, and counts the hosts and write folders that recur across sessions. Claude Code's sandbox applies to Bash commands and does not cover Write or WebFetch tool calls (issue #89762). So Sandbox Tuner reads Bash results, and the hosts that background Bash commands and shell Monitor launches list when they start.

Features

  • An explanation above the prompt. The band names the blocked target, the command, and the reason, in the terminal and the desktop app.
  • A ranking for the current session. /sandbox-tuner lists the hosts and write folders that the current session saw, with ready fixes first. The targets that have no fix come last, under Nothing to allow here. Each count, such as 5 confirmed blocks or 27 guessed from error text, also includes the sightings of earlier sessions. Hide the targets that you do not want to see, except a target that your settings already allow.
  • A change you review. Allow shows the exact entry and its effect before you press it. Deny appears for a host that you refused at the network prompt, unless an allowlist lock applies.
  • Undo and a backup. Each settings edit gets an Undo record. The pane lists the edits of the current session. A branch also lists the edits of its history up to the branch, each with Undo. A backup keeps the settings file as it was before the latest write.
  • Every session on request. Set the scope option to all to show the targets and the edits of every session, as Sandbox Tuner 1.1.3 does.
  • Narrow fixes. Folder grants go only to eligible cache and temp folders. A folder strictly inside /tmp, such as /tmp/build, can get Allow. A file directly in /tmp gets no Allow, because /tmp itself is too broad. Sandbox Tuner offers no wildcard hosts and no command exclusions.

The Sandbox Tuner pane beside the transcript: example.org is ready with Allow and Hide, example.net waits at 1 of 3 sightings.

/sandbox-tuner ranks blocked hosts: a ready fix first, then waiting ones. Targets that have no fix come last, under Nothing to allow here.

Terminal: a write to .git/hooks fails in the sandbox, and the band explains that no setting opens such a path.

Some blocks have no safe setting. Sandbox Tuner says so.

How it works

flowchart TD
    A[Read each Bash result or shell launch] --> B[Save host and write-folder sightings]
    B --> C[Check counts and current settings]
    C --> D[Explain waiting, covered, or no-fix targets]
    C --> E[Show eligible change and its effect]
    E --> F[You press Allow or Deny]
    F --> G[Reload sightings and recheck settings]
    G -->|Refused| D
    G -->|Eligible| H[Lock, read again, back up, record Undo, write, and confirm]
    H --> I[You can press Undo]
  • A sighting is a reported block, a host that Claude lists in a command's allowed_domains, or a path taken from a permission error. A reported block is confirmed. A path taken from a permission error is guessed: the sandbox did not confirm it. Allow appears after minimumSightings sightings (3 by default), confirmed or guessed. The threshold filters noise. It is not a security check. On macOS 27, Claude Code reports no folder block in the Bash result, so a folder Allow there rests on guessed blocks. Sandbox Tuner offers it only for the cache and temp folders that it names, with the label Guessed from error text: the sandbox did not confirm this block. next to the Allow. Nothing changes until you press Allow, and the press first checks where the folder really lies. Confirmed and guessed blocks has the details.
  • Each press of Allow, Deny, or Undo changes one entry in sandbox.network.allowedDomains, sandbox.network.deniedDomains, or sandbox.filesystem.allowWrite of your user settings file: ~/.claude/settings.json, or $CLAUDE_CONFIG_DIR/settings.json.
  • Grants apply to every project. An allowed host can receive data on any port. Programs outside the sandbox may later load files written into an allowed folder.
  • Each grant respects managed settings, and is checked against the loaded settings and a fresh read of the file. Folder checks follow symbolic links and refuse protected paths, credentials, system folders, and folders on PATH.
  • Before a write, Sandbox Tuner takes a lock file next to the settings file, so that presses in other sessions wait their turn. Under the lock, it reads the file, the sightings, and the Undo journal again, checks the press again, and applies it to the current text or refuses. Then the previous file goes to backups/settings.json.sandbox-tuner.bak in the config folder. Sandbox Tuner checks that nothing else changed the file, writes it as 2-space JSON, reads it back, frees the lock, and checks the file again two seconds later.
  • Undo removes only the entry that its press added. While a removal is unconfirmed, its row in the Applied list keeps Retry Undo. The usage guide has the full rules and the recovery steps.

Install

Requires Claude Code 2.1.288 or later, with the sandbox turned on through /sandbox, on macOS, Linux, or WSL2. Tested with Claude Code 2.1.296.

Inside Claude Code:

/plugin marketplace add dot-agi/sandbox-tuner
/plugin install sandbox-tuner@sandbox-tuner

From a shell:

claude plugin marketplace add dot-agi/sandbox-tuner
claude plugin install sandbox-tuner@sandbox-tuner

To try it for one session from a clone:

claude --plugin-dir ./sandbox-tuner

Agents and scripts

Install from a shell with Claude Code 2.1.292 or later. The second part turns on auto-update. It runs only when the install succeeds and the marketplace entry exists:

claude plugin install sandbox-tuner --marketplace dot-agi/sandbox-tuner --scope user --json \
  && f="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/settings.json" \
  && jq -e --arg name sandbox-tuner '.extraKnownMarketplaces[$name].source' "$f" > /dev/null \
  && tmp=$(mktemp "$f.XXXXXX") \
  && { jq --arg name sandbox-tuner '.extraKnownMarketplaces[$name].autoUpdate = true' "$f" > "$tmp" && mv "$tmp" "$f" || { rm -f "$tmp"; false; }; }

Claude Code 2.1.288 to 2.1.291 has no --marketplace option. Add the marketplace first, then run the auto-update part above:

claude plugin marketplace add dot-agi/sandbox-tuner --scope user --json \
  && claude plugin install sandbox-tuner@sandbox-tuner --scope user --json

Auto-update runs only in interactive sessions. A headless job updates at its start, before the session that uses the mod:

claude plugin update sandbox-tuner@sandbox-tuner --json

Check the result. The first command prints the installed version. The second prints the latest release:

claude plugin list --json | jq -r '.[] | select(.id == "sandbox-tuner@sandbox-tuner") | "\(.version) enabled=\(.enabled)"' \
  && git ls-remote --tags --refs https://github.com/dot-agi/sandbox-tuner 'sandbox-tuner--v*' | sed 's/.*--v//' | sort -V | tail -n 1
  • On a host with no SSH key for GitHub, set CLAUDE_CODE_PLUGIN_PREFER_HTTPS=1 in the environment of every claude command and session.
  • New code loads in the next session, or after /reload-plugins. An agent cannot type /reload-plugins, so it starts a new session.
  • Running install again does not update. Use update.
  • The mv replaces the settings file, with mode 600. If settings.json is a symbolic link, edit its target instead.

Commands

CommandWhat it does
/sandbox-tunerOpens the pane with the targets and edits of the current session, in a branch with those that it inherited, and loads the sightings of those targets that other sessions saved. With scope: all, it shows every session's targets and edits. Prints the text report when the app cannot place the pane.
claude -p "/sandbox-tuner"Prints the ranking as text. Never writes settings. A claude -p run is a new session, so with the default scope: session the report lists no target. Set scope to all for the ranking of every session.

The band's buttons have no hotkeys. Click one, or press Ctrl+X, then Tab, to focus the band. Then Tab moves between the buttons, Enter presses one, and Esc goes back to the prompt. When the row has room, the band shows this path after its last button, dim: ctrl+x tab to choose. Ctrl+X, then Tab is Claude Code's own focus chord. Release Ctrl before Tab: many terminals read Ctrl+Tab as next tab. In Emacs terminals, click the band's button, or rebind abovePrompt:focus with /keybindings. In the pane, Tab moves between buttons, Enter presses one, the arrow keys scroll, and Esc closes it.

Options

OptionDefaultRangeMeaning
minimumSightings31–100How many times a host or write folder must recur before Sandbox Tuner offers Allow. Refusals at the network prompt stay in the counts but do not count toward it.
linkCheckMinutes150–1440How often, in minutes, an interactive session checks again for links into the folders that Allow opened. 0 turns the timed check off.
scopesessionsession, allsession: the band, the pane, and /sandbox-tuner show only the hosts and write folders that the current session saw, and the Applied list shows only the edits of the current session. After /clear, the new session starts with nothing to show. After /branch, the branch inherits the view of its history: the targets and the edits, with Undo, that the session before saw and made up to the branch. Then it adds its own, and the session before never shows them. With managed settings or a Team or Enterprise sign-in, a branch inherits nothing (see Known limits). After /resume, the session shows its own earlier sightings and edits, and a branch also what it inherited, while its branch record stays. Past 200 branch records, a later /branch removes the oldest records that no saved target or change needs. all: they show the targets and the edits of every session, as Sandbox Tuner 1.1.3 does. With both values, the counts and minimumSightings include the sightings of every session, and the link check covers every folder that Allow opened in any session.

Set them with /plugin configure sandbox-tuner@sandbox-tuner, or in /config.

How it compares

Feature or projectWhat it doesWhat Sandbox Tuner adds
Built-in /sandboxConfigures Claude Code's sandbox and its operating mode.Explanations for observed blocks, counts across sessions, and reviewed edits with Undo.
Built-in network prompt approvalsApproves hosts for the current session.Persistent user-settings entries after you review a recurring target. Prompt approvals themselves are not counted.
Bash allowed_domainsLets a command declare needed hosts in auto mode, subject to network policy. Saves no lasting grant.Counts those declarations across sessions and offers an eligible persistent setting after the threshold.
ktrysmt's sandbox auto-allow hookAutomatically extracts hosts from many error patterns and appends them to allowedDomains; uses a lock for settings writes.Review before each grant, Undo, a backup, recurring-target counts, and guarded cache/temp folder fixes.

Known limits

What it catches

  • Sources. Network and write blocks in Bash results, and the hosts that Claude lists in allowed_domains, across sessions.
  • Fixes. The band explains each block that it recognizes, also a block that no setting fixes.
  • Links. Links between a folder that Allow opens and protected, credentials, or PATH folders: before Allow, then at each session start and every 15 minutes by default.
  • Fake reports. It skips a sandbox report that more output follows, because a command printed it.

What it does not catch

  • Sources. Blocks in the later output of background commands and shell Monitors.
  • Fixes. No fix for read, Mach lookup, or socket blocks, or for tools that ignore the sandbox proxy. A folder known only from error text gets a labeled Allow, and only when it is a cache or temp folder.
  • Links. Hard links, links in skipped or deep folders, and links made since the last check.
  • Fake reports. A fake report that a failing command prints last. Check the host or folder before you press Allow.

The usage guide has every limit in full, also rare ones such as races, size caps, and unusual setups.

  • Wildcard rules and rules with no known anchor make Sandbox Tuner cautious. It counts an Edit(<folder>/) allow rule as cover only when the folder has no wildcard. So it can offer Allow for a folder that a wildcard Edit rule already opens. A deny rule with a wildcard, in permissions.deny or in sandbox.filesystem, withholds Allow for every folder under the folder that holds its first wildcard. For example, Read(~//*.key) withholds Allow for every folder in your home folder. In command-line or managed settings, a rule path that starts with a single /, and a relative sandbox.filesystem entry, have no known anchor. Such an Edit allow rule or allowWrite entry counts as no cover. Such a deny rule or denyWrite or denyRead entry withholds Allow for every folder.
  • Paths from error text can be wrong. When no sandbox report names a file, Sandbox Tuner takes the path from a permission error such as Operation not permitted. Punctuation in the error can cut the path short. A relative path counts from the session working directory, which can differ from the folder where the command ran. The error can also come from a blocked read. So a guessed block can name the wrong folder. Sandbox Tuner offers Allow for it only for a cache or temp folder, after minimumSightings, with a label next to the Allow. Read the path and the command before you press.
  • A failed command can forge a sandbox report. Claude Code adds the sandbox report of a failed command at the end of the command's output, and can add a proxy note after it. So Sandbox Tuner reads only the <sandbox_violations> block that ends that output, before any proxy note. It skips a block that other output follows, and writes a debug line. But a command that prints a block as its last output, for example from a file, and then fails, still forges a report: Sandbox Tuner counts that block as a block. Such a block counts only while the sandbox is on, and not when the command ran outside the sandbox at Claude's request. A Claude Code version that adds other text after its report makes Sandbox Tuner skip the real report too, with the same debug line. Before you press Allow, check that you expect the host or folder. Also check the command that the band names, or the programs that the pane lists.
  • Read, Mach lookup, and socket blocks get no fix. When a sandbox report names such an operation, the band explains it for the current session only. Sandbox Tuner saves no count for it and offers no Allow. For an operation that it does not know, the band says that it cannot classify it.
  • Later background output goes unseen. For a background Bash command or a shell Monitor launch, Sandbox Tuner counts the hosts that the launch declared, once, when it starts. It does not read the later output, so blocks there give no sighting.
  • A tool that ignores the sandbox proxy can still fail for an allowed host. Covered rows in the band, the pane, and the report suggest checking the tool's proxy settings and supported protocols. Sandbox Tuner offers no command exclusion.
  • Managed settings and Team or Enterprise sign-ins hide the start of a switched session. There, Claude Code's built-in guard keeps the SessionStart event from installed mods. So after /clear, /resume, or /branch, Sandbox Tuner loads the new session's view and runs the link check of a session start once Claude Code names the new session. It checks for that twice a second for 5 minutes, and at its next Bash call, press, or /sandbox-tuner. Until then, /sandbox-tuner says that a switch is in progress and shows no target, and Allow and Deny write nothing. Sandbox Tuner cannot tell /branch from /resume there, so with scope: session a branch inherits no target, edit, Undo, band, or dismissal of the session before. To undo an edit of the session before, /resume that session or set scope to all. After a failed sighting save, Allow and Deny refuse in each session that /resume or /branch starts that is not among the 200 sessions that this Claude Code process ran last since Sandbox Tuner loaded. The usage guide has the details.

Privacy

Sandbox Tuner makes no network request and starts no process. Nothing leaves your machine.

  • Hooks. Sandbox Tuner reads each Bash call and each shell Monitor launch after Claude Code has handled it. It changes no tool call and no tool result, adds no instructions for Claude, and hooks no permission event. If a hook fails, it writes a sandbox-tuner: line to the debug log. The pane and the command then show the error, and every other hook passes its event on unchanged. Every hook is in hooks/register.tsx.
  • Reads. The command, its listed hosts, and its output and error output, only to find sandbox blocks. Your settings from every source (user, project, local, command line, and managed), and the text of your user settings file. The variables HOME, CLAUDE_CONFIG_DIR, and PATH, the working directory, the project root, and the session id. When you press Allow on a write folder, it also finds where that folder, your home folder, the config folder, the working directory, the protected places, the credentials folders (such as ~/.ssh), and each PATH folder really lie. At the start of an interactive session, also after /clear, /resume, or /branch, and every 15 minutes during it (linkCheckMinutes), while a folder that Allow opened is still in your settings file, it finds where that folder, the protected places, the credentials folders, and each PATH folder lie. This check lists names and follows links. It opens no file. What a write changes has the full list.
  • Writes. Sandbox Tuner writes three files itself, and only when you press Allow, Deny, or Undo: your user settings file, its backup, and the lock file next to the settings file. An edit changes one entry under sandbox and keeps every other key. The lock file holds only a random token of the press and a time. All other data goes to Claude Code's plugin store.
  • The backup. It is a full copy of your user settings file, which can hold secrets in env. It is created with your default file mode, which can be wider than the mode of your settings file. Sandbox Tuner uses no secret, and saves none apart from this copy.
  • The store. Sandbox Tuner keeps its data in Claude Code's plugin store ($CLAUDE_CONFIG_DIR/plugins/store/, or ~/.claude/plugins/store/ when CLAUDE_CONFIG_DIR is unset): hosts, ports, folder targets, one denied path for each folder, program names, session ids, counts, times, Hide choices, the Undo journal (each entry that it added, the file it went into, and the session id of the press), a branch record for each /branch, the oldest removed past 200 (the session ids of the branch and of the session that it started from, the time, and the targets that the session before saw by then), and the session id and time of each session in which Allow and Deny refuse after a sighting that could not be saved, the oldest removed past 200. It saves no command line, no output, and no other settings content.
  • Problems. A problem that Sandbox Tuner shows or writes to the debug log quotes only sandbox and permissions entries of your settings. When your settings file is not valid JSON, the problem shows … in place of the file text that the JSON parser quotes.

Troubleshooting

  • No band. The sandbox is off, the session runs in VS Code or the mobile app (no band there), a survey holds the band, you dismissed that block, or you already fixed it. /clear and /resume also clear the band of the session before. /branch keeps it with scope: session only, and not with managed settings or a Team or Enterprise sign-in. Run /sandbox-tuner.
  • A target or an Undo of another session is missing. With the default scope: session, the band, the pane, and the report show only what the current session saw and applied, and in a branch what its history saw and applied up to the branch. A target or an edit of the session before that came after the branch does not show in the branch. An inherited edit shows the live state of its entry: both sessions share one settings file, so an Undo of it in either session shows in both. Set scope to all to show every session's targets and edits again.
  • No Allow. The target has not recurred enough, managed settings lock the allowlist, your settings already allow it, the folder is no cache or temp folder, or a rule of yours refuses it. The row says which.
  • "Claude Code has not applied it yet". Your settings file holds the entry, but the session did not load it. Run /status to check that the session loads user settings, and look for a ConfigChange hook that blocks the change.
  • "Your settings already allow it", and the sandbox still blocks it. The tool may ignore the sandbox proxy, the block may be a read, or file permissions may refuse it. Check the tool's proxy settings and supported protocols. Run /status or /doctor for managed-settings warnings.
  • "is not valid JSON". Fix your user settings file ($CLAUDE_CONFIG_DIR/settings.json, or ~/.claude/settings.json when CLAUDE_CONFIG_DIR is unset), then press again. Sandbox Tuner never edits a file it cannot p
Source 11 files
hooks/register.tsx 2011 lines
1// Sandbox Tuner's hooks module: every hook and every $ call.
2
3import { atom, read, update } from 'claude-code'
4import type { EngineInterface, HookFailure, Register, RenderElement, Timer, ToolCallResult } from 'claude-code'
5
6import type { SandboxTunerAction, SandboxTunerApplied, SandboxTunerLatest, SandboxTunerLineage, SandboxTunerNotice, SandboxTunerRecord, SandboxTunerScope } from '../types'
7import { KeyFailure, causeOf, diagnostic, shownCause } from './diagnostics'
8import { TMP, absolutePath, commandLine, cutText, displayPath, isTempFolder, isUnder, pathFolders, plainText } from './names'
9import { JOURNAL_PREFIX, LINEAGE_PREFIX, REFUSAL_LIMIT, REFUSAL_PREFIX, WRITER_PREFIX, HIDDEN_PREFIX, aggregateRecords, appliedIn, hasLaterOwner, isLineage, isUndoUnresolved, isFixedSince, isPressedAgain, isRecord, journalOf, keptBranches, keysSeenBy, lineageStep, mergeSighting, newestRefusals, recordKey, seenIn, shownRecords } from './records'
10import type { Lineage } from './records'
11import { addEntry, fileInfo, isApplied, lockText, parseSettings, readLock, removeEntry, serializeSettings } from './settings-file'
12import type { FileInfo, ParsedSettings } from './settings-file'
13import { keepGated, latestOf, readCall, reportQuote } from './sightings'
14import type { BashCall, BashOutcome, GatedSighting, Sighting } from './sightings'
15import { anchorEntry, credentialEntries, denialEntries, denialVerdict, grantsMet, guardedPlaces, guardedWalks, isGuessedAllow, isGuessedFolder, isSkipped, rateRecords, sandboxFacts, verdictOf } from './verdicts'
16import type { Change, Context, Sources, Verdict, Walk } from './verdicts'
17import { bandTree, buildBand, buildObservation, buildPane, canUndo, drawable, paneTree, reportText, summaryLine } from './views'
18import {
19  COMMAND_DESCRIPTION, NOTHING_TO_CHANGE, NOTHING_TO_UNDO, SWITCHING, absentNotice, addedNotice, displayTarget, grantWarning, hiddenNotice, notAppliedText, notPlaced,
20  nothingApplied, hostText, refusalText, removedNotice, shownNotice, verdictSentences, verificationRefusalText,
21} from './words'
22
23type BashInput = { command: string; run_in_background?: boolean; dangerouslyDisableSandbox?: boolean; allowed_domains?: string[] }
24
25const backgroundTasks = atom({ plugin: 'sandbox-tuner', key: 'backgroundTasks' } as const, [] as string[])
26const writerId = crypto.randomUUID()
27const evidenceIncomplete = atom({ plugin: 'sandbox-tuner', key: 'evidenceIncomplete' } as const, false)
28const records = atom({ plugin: 'sandbox-tuner', key: 'records' } as const, [] as SandboxTunerRecord[])
29const applied = atom({ plugin: 'sandbox-tuner', key: 'applied' } as const, [] as SandboxTunerApplied[])
30const appliedOffset = atom({ plugin: 'sandbox-tuner', key: 'appliedOffset' } as const, 0)
31const latest = atom({ plugin: 'sandbox-tuner', key: 'latest' } as const, null as SandboxTunerLatest | null)
32const fault = atom({ plugin: 'sandbox-tuner', key: 'fault' } as const, null as string | null)
33
34// Sandbox Tuner's own cap on a debug line. The cut keeps the start of its diagnostic.
35const LOG_LIMIT = 4096
36
37function logDebug($: EngineInterface, text: string): void {
38  $.ui.log(cutText(plainText(text), LOG_LIMIT), { to: 'debug' })
39}
40
41// One queue per module instance, so the store writes of one session never interleave. A hot reload starts a new one.
42let queue: Promise<unknown> = Promise.resolve()
43
44function enqueue<T>(job: () => Promise<T>): Promise<T> {
45  const run = queue.then(job)
46  queue = run.catch(() => undefined)
47  return run
48}
49
50// With scope session, the session that classic.SessionStart starts at /clear, /resume, or /branch, while its dispatch
51// runs (whileStarting). The settings SessionStart hooks run beneath the mods in that dispatch, and until it ends,
52// $.session.id() still names the session before at /resume and /branch. One per module instance, as the queue.
53let starting: string | null = null
54
55// How often Sandbox Tuner reads the session id while a switch waits (pending), and for how long at most. A hook, a
56// press, or a timer of Sandbox Tuner that comes later settles the switch too.
57const SWITCH_POLL_MS = 500
58const SWITCH_POLL_LIMIT_MS = 5 * 60_000
59// The event that the diagnostics of a switch that Sandbox Tuner settles itself name (settleSwitch).
60const SWITCH_EVENT = 'session.switch'
61
62/**
63 * A /clear, /resume, or /branch that session.end began: its reason, and `ended`, the session that ended. It waits until
64 * classic.SessionStart takes it, or until Sandbox Tuner settles it once $.session.id() names another session
65 * (settleSwitch). `isIncomplete`: whether a sighting of the session that ended could not be saved, also when that could
66 * not be read. The settle needs the view options and whether a person is at the prompt. `poll` reads the session id.
67 */
68type Pending = { reason: 'clear' | 'resume'; ended: string; isIncomplete: boolean; scope: SandboxTunerScope; threshold: number; isInteractive: boolean; poll: Timer | null }
69// The switch that waits. One per module instance, as the queue.
70let pending: Pending | null = null
71/**
72 * The last switch that Sandbox Tuner settled itself, until the next session.end or classic.SessionStart: the session
73 * that it started, its reason, and the session that ended before it, with its band (`before`).
74 */
75let settled: { session: string; reason: 'clear' | 'resume'; before: Ended | null } | null = null
76// The most session ids that `known` keeps: the newest.
77const KNOWN_LIMIT = 200
78// The sessions that this process ran or started last, the newest last, at most KNOWN_LIMIT (remember). A /resume to
79// another session is a /resume to a session of this process (an in-app /resume), or to a session that is new to it: a
80// /branch, or a session of another process. A session that left `known` counts as new, which fails closed (settleSwitch).
81const known = new Set<string>()
82// The sessions in which Allow and Deny refuse, as after a sighting that could not be saved, that this module instance
83// took itself: the newest last, at most REFUSAL_LIMIT (remember). Claude Code resets $.state at a switch, so an in-app
84// /resume takes the refusal back from here (startSession), and a press checks it too (targetRecord): a press that
85// settles a switch reads the $.state of before. The store keeps each refusal as well (saveRefusal), so that a reload of
86// the mod and another process keep it (loadRefusals).
87const incomplete = new Set<string>()
88// The sessions whose refusal the store keeps, as the last load found them (loadRefusals), with the saves and removals
89// of this module instance since (saveRefusal). The bound of `incomplete` never drops one of them.
90const stored = new Set<string>()
91
92/** Whether this module instance holds the refusal of Allow and Deny in `session`: its own (incomplete) or the store's (stored). */
93function isHeld(session: string): boolean {
94  return incomplete.has(session) || stored.has(session)
95}
96
97/**
98 * Whether Allow and Deny refuse in `session`: this module instance holds its refusal (isHeld), or the store keeps it
99 * now, saved by another Claude Code process too. Rejects when the store cannot be read.
100 */
101async function isRefusedIn($: EngineInterface, session: string): Promise<boolean> {
102  return isHeld(session) || (await $.store.get(REFUSAL_PREFIX + session)) !== undefined
103}
104
105/** Adds `session` to `sessions` as the newest, then removes the oldest past `limit`. */
106function remember(sessions: Set<string>, session: string, limit: number): void {
107  sessions.delete(session)
108  sessions.add(session)
109  for (const oldest of sessions) {
110    if (sessions.size <= limit) break
111    sessions.delete(oldest)
112  }
113}
114
115/** The saved refusals (REFUSAL_PREFIX): each session and the time that its key holds. */
116async function savedRefusals($: EngineInterface): Promise<Map<string, unknown>> {
117  const saved = new Map<string, unknown>()
118  for (const key of await $.store.keys()) {
119    if (key.startsWith(REFUSAL_PREFIX)) saved.set(key.slice(REFUSAL_PREFIX.length), await $.store.get(key))
120  }
121  return saved
122}
123
124/**
125 * Takes every refusal that the store keeps (saveRefusal), also of another Claude Code process, into `stored`, in place
126 * of the ones that the last load found. Runs in the module queue, at session.start and at each switch. Rejects when the
127 * store cannot be read: then `stored` keeps what it held, and a press reads the refusal of its session from the store
128 * before it writes (targetRecord).
129 */
130async function loadRefusals($: EngineInterface): Promise<void> {
131  const saved = (await $.store.keys()).filter(key => key.startsWith(REFUSAL_PREFIX)).map(key => key.slice(REFUSAL_PREFIX.length))
132  stored.clear()
133  for (const session of saved) stored.add(session)
134}
135
136/**
137 * Saves the refusal of Allow and Deny in `session` in the store, with the time, so that a reload of the mod, and
138 * another Claude Code process that runs the session later, keep it (loadRefusals). Then it removes the oldest refusals
139 * past the REFUSAL_LIMIT newest from the store. Runs in the module queue. A problem goes to the debug log: the refusal
140 * still holds in this module instance (incomplete). It never rejects.
141 */
142async function saveRefusal($: EngineInterface, session: string, event: string): Promise<void> {
143  try {
144    await $.store.set(REFUSAL_PREFIX + session, await $.clock.now())
145    stored.add(session)
146    for (const oldest of newestRefusals(await savedRefusals($)).slice(REFUSAL_LIMIT)) {
147      await $.store.delete(REFUSAL_PREFIX + oldest)
148      stored.delete(oldest)
149    }
150  } catch (error) {
151    // At session.end, the session is no longer current, so no later end of it tries again: only an in-app /resume of
152    // it (startSession, settleSwitch).
153    const retry = event === 'session.end'
154      ? 'The session has ended, so a reload of Sandbox Tuner or another Claude Code process does not keep the refusal. Sandbox Tuner tries again at an in-app /resume of the session.'
155      : 'Sandbox Tuner tries again when the session ends.'
156    logDebug($, diagnostic(event, null, `could not save the refusal of Allow and Deny after a sighting that could not be saved: ${causeOf(error)}. Allow and Deny still refuse in this Claude Code process. ${retry}`))
157  }
158}
159// With scope session, the session that ended last, for a /branch that follows (forkOf). It lives outside $.state:
160// Claude Code resets $.state between session.end and classic.SessionStart. The next classic.SessionStart takes it.
161let ended: Ended | null = null
162
163/** The cause of a session id read while a switch is in progress: Claude Code still names the session that ended. */
164class SwitchFailure extends Error {
165  constructor() {
166    super('a switch to another session is in progress')
167  }
168}
169
170/**
171 * The current session: the one that classic.SessionStart starts while its dispatch runs (starting), else $.session.id().
172 * While a switch waits (pending) and $.session.id() still names the session that ended, there is no current session: it
173 * rejects with a SwitchFailure, so that no load, press, or call counts for the session that ended or the next one.
174 */
175async function sessionNow($: EngineInterface): Promise<string> {
176  if (starting !== null) return starting
177  const session = await $.session.id()
178  if (pending !== null && session === pending.ended) throw new SwitchFailure()
179  return session
180}
181
182/** Ends the switch that waits, and its poll. */
183function endSwitch(): void {
184  pending?.poll?.cancel()
185  pending = null
186}
187
188/**
189 * Keeps the switch that session.end begins at /clear, /resume, or /branch (pending), and reads the session id every
190 * SWITCH_POLL_MS until Sandbox Tuner settles the switch or classic.SessionStart takes it, at most SWITCH_POLL_LIMIT_MS.
191 * A later session.end replaces it.
192 */
193function beginSwitch($: EngineInterface, next: Omit<Pending, 'poll'>): Pending {
194  endSwitch()
195  settled = null
196  const begun: Pending = { ...next, poll: null }
197  pending = begun
198  let polls = 0
199  begun.poll = $.clock.every(SWITCH_POLL_MS, () => {
200    polls += 1
201    if (pending !== begun || polls * SWITCH_POLL_MS > SWITCH_POLL_LIMIT_MS) begun.poll?.cancel()
202    else void settleSwitch($)
203  })
204  return begun
205}
206
207/**
208 * Settles the switch that waits (pending) once $.session.id() names another session than the one that ended. This is
209 * for sessions where classic.SessionStart does not reach Sandbox Tuner: with managed settings or a Team or Enterprise
210 * sign-in, Claude Code's built-in guard keeps every classic event from mods. In the queue, it does what classic.SessionStart
211 * does for /clear and /resume, then it runs the check of a session start. A /branch looks like a /resume of a session
212 * that is new to this process, so the new session inherits nothing. When the session that ended had a failed sighting
213 * save, such a session keeps the refusal of Allow and Deny, because it can be a branch of it. A session of this process
214 * takes its own refusal back. It runs at the start of each hook, press, and timer of Sandbox Tuner, outside the queue,
215 * and never in a ui.render hook, which cannot write state. Returns whether the switch is still in progress:
216 * $.session.id() still names the session that ended. It never rejects.
217 */
218async function settleSwitch($: EngineInterface): Promise<boolean> {
219  const found = pending
220  if (found === null) return false
221  let session: string
222  try {
223    session = await $.session.id()
224  } catch {
225    // The hook reads the session id again, and says why it fails.
226    return false
227  }
228  // Another hook settled the switch during the read, or classic.SessionStart took it.
229  if (pending !== found) return false
230  if (session === found.ended) return true
231  endSwitch()
232  settled = { session, reason: found.reason, before: ended }
233  ended = null
234  const isKnown = known.has(session)
235  remember(known, session, KNOWN_LIMIT)
236  // The settle in the queue reads the refusal of the session from the store too (startSession).
237  const isRefused = isHeld(session) || (found.reason === 'resume' && !isKnown && found.isIncomplete)
238  // At once: a press that settles the switch checks it in the queue after the settle (targetRecord).
239  if (isRefused) remember(incomplete, session, REFUSAL_LIMIT)
240  const { scope, threshold, isInteractive } = found
241  const check = () => {
242    if (isInteractive) void recheckOnce($, threshold, scope, true)
243  }
244  void enqueue(() => startSession($, scope, { session, event: SWITCH_EVENT, fork: null, isRefused, isSettled: false })).then(check, check)
245  return false
246}
247
248/** Runs the dispatch of classic.SessionStart with `session`, the session that it starts, as the current one (sessionNow). */
249async function whileStarting<T>(session: string, dispatch: () => Promise<T>): Promise<T> {
250  starting = session
251  try {
252    return await dispatch()
253  } finally {
254    // A switch that started during this dispatch owns the value now.
255    if (starting === session) starting = null
256  }
257}
258
259// With scope session, the branches in this process that could not keep the refusal of Allow and Deny after a sighting
260// that their parent could not save (keepRefusal). Claude Code resets $.state at a switch, so they live here. One per
261// module instance, as the queue.
262const unrestored = new Set<string>()
263
264/**
265 * A /branch with scope session whose record waits in the module queue (saveLineage): its parent, its time, and the
266 * targets that the parent saw by that time, once read (keepBranchKeys), or the error of that read.
267 */
268type WaitingBranch = { parent: string; at: number; seen: { keys: string[] } | { error: unknown } | null }
269// The waiting /branch records, by branch. One per module instance, as the queue.
270const waiting = new Map<string, WaitingBranch>()
271
272/**
273 * Before a sighting of `session` at `now` is saved, reads the targets that it saw by the time of each waiting /branch
274 * from it that came before `now`. A Bash call that ended before /branch can wait in the queue, and its sightings came
275 * after the branch: the branch does not inherit them.
276 */
277async function keepBranchKeys($: EngineInterface, session: string | null, now: number): Promise<void> {
278  for (const branch of waiting.values()) {
279    if (branch.parent !== session || now <= branch.at || branch.seen !== null) continue
280    try {
281      branch.seen = { keys: keysSeenBy(await readWriterRecords($), session, branch.at) }
282    } catch (error) {
283      branch.seen = { error }
284    }
285  }
286}
287
288/**
289 * Logs a background problem and keeps it for the pane, as `shown` when the pane must show it in other words. Never
290 * rejects, so no background job ends in silence.
291 */
292async function noteFault($: EngineInterface, text: string, shown = text): Promise<void> {
293  const unshown = await update($, fault, () => shown).then(
294    () => '',
295    (error: unknown) => ` The pane cannot show this problem: ${causeOf(error)}.`,
296  )
297  logDebug($, `${text}${unshown}`)
298}
299
300function hookFailed($: EngineInterface, event: string, detail: string | null, failure: HookFailure): string {
301  const text = diagnostic(event, detail, `hook failed (${failure.kind}): ${failure.message ?? 'no message'}`)
302  logDebug($, text)
303  return text
304}
305
306/** A folder from the environment, resolved from `base` when relative; an empty value counts as unset, as in a shell. */
307function folderOf(value: string | undefined, base: string): string | undefined {
308  return value === undefined || value === '' ? undefined : absolutePath(value, base)
309}
310
311async function homeOf($: EngineInterface): Promise<string | undefined> {
312  return folderOf(await $.env.get('HOME'), '/')
313}
314
315function toCall(e: BashInput): BashCall {
316  return {
317    command: e.command,
318    isBackground: e.run_in_background === true,
319    isUnsandboxed: e.dangerouslyDisableSandbox === true,
320    allowedDomains: e.allowed_domains ?? [],
321  }
322}
323
324// The Bash matcher types the result: on the success arm `result` is Bash's record, which core validates.
325function toOutcome(out: ToolCallResult<'Bash'>): BashOutcome {
326  if (out.deny !== undefined) return { isDenied: true, isError: false, text: '', stderr: '' }
327  if (out.isError === true) return { isDenied: false, isError: true, isReadOnly: out.isReadOnly === true, text: out.text ?? '', stderr: '' }
328  return { isDenied: false, isError: false, isReadOnly: out.isReadOnly === true, backgroundTaskId: out.result.backgroundTaskId, isUnsandboxed: out.result.dangerouslyDisableSandbox, text: out.text ?? '', stderr: out.result.stderr }
329}
330
331/**
332 * The session of a press or a tool call, read once when it starts: its id, or why Claude Code could not give it, and
333 * whether a switch was in progress then (`isSwitching`, SwitchFailure).
334 */
335type Origin = { session: string } | { session: null; cause: string; isSwitching: boolean }
336
337// The session of a press that starts while a switch is in progress (runPress).
338const SWITCH_ORIGIN: Origin = { session: null, cause: causeOf(new SwitchFailure()), isSwitching: true }
339
340/** Reads the session of a press or a tool call when it starts, before it waits for the call or the module queue. */
341async function sessionOrigin($: EngineInterface): Promise<Origin> {
342  try {
343    return { session: await sessionNow($) }
344  } catch (error) {
345    return { session: null, cause: causeOf(error), isSwitching: error instanceof SwitchFailure }
346  }
347}
348
349/**
350 * What a call starts in, read before it runs with scope session: its session, and its working directory, which
351 * resolves a relative path in its output. Null when the working directory cannot be read: then the call reads it again
352 * once it ends.
353 */
354type CallStart = { origin: Origin; cwd: string | null }
355
356async function callStart($: EngineInterface): Promise<CallStart> {
357  return { origin: await sessionOrigin($), cwd: await $.session.cwd().catch(() => null) }
358}
359
360/** Keeps a problem of a call for the pane (noteFault), or only in the debug log for a call of another session. */
361async function noteCallFault($: EngineInterface, isShown: boolean, text: string, shown = text): Promise<void> {
362  if (isShown) await noteFault($, text, shown)
363  else logDebug($, text)
364}
365
366async function gatedSightings($: EngineInterface, gated: readonly GatedSighting[], tool: string, isShown: boolean): Promise<Sighting[]> {
367  try {
368    return keepGated(gated, sandboxFacts(await $.settings.read()))
369  } catch (error) {
370    await noteCallFault($, isShown, diagnostic('tool.call', tool, `could not read settings to check the sandbox: ${causeOf(error)}. Kept only sandbox reports, and none of a call that failed.`))
371    return []
372  }
373}
374
375/**
376 * The session id that the sightings of a call name: with scope session, the session that ran the call (`origin`, read
377 * before the call ran), and with scope all, read now (`origin` null), as in Sandbox Tuner 1.1.3.
378 */
379async function sessionIdOf($: EngineInterface, tool: string, origin: Origin | null, isShown: boolean): Promise<string | null> {
380  const found = origin ?? (await sessionOrigin($))
381  if (found.session !== null) return found.session
382  await noteCallFault($, isShown, diagnostic('tool.call', tool, `could not read the session id: ${found.cause}`))
383  return null
384}
385
386/**
387 * Saves one sighting. It adds the target to the targets that the pane shows only for a call of this session (`isShown`).
388 * Returns whether the sighting is saved.
389 */
390async function saveSighting($: EngineInterface, scope: SandboxTunerScope, sighting: Sighting, sessionId: string | null, now: number, tool: string, isShown: boolean): Promise<boolean> {
391  const key = recordKey(sighting)
392  try {
393    const storeKey = `${WRITER_PREFIX}${writerId}:${key}`
394    const stored = await $.store.get(storeKey)
395    const merged = mergeSighting(isRecord(stored) ? stored : undefined, sighting, sessionId, now)
396    await $.store.set(storeKey, merged)
397    const refreshed = (await readRecords($, key))[0]
398    if (refreshed === undefined) throw new Error('saved evidence was not returned by the store')
399    // With scope session, a sighting with no session id names no session: it adds no target, and a load would not show it.
400    const isListed = (list: readonly SandboxTunerRecord[]) => scope === 'all' || sessionId !== null || list.some(record => record.key === key)
401    if (isShown) await update($, records, list => (isListed(list) ? [...list.filter(record => record.key !== key), refreshed] : list))
402    return true
403  } catch (error) {
404    // The session that ran the call refuses, also after an in-app /resume of it (startSession) and a reload (recordCall).
405    if (sessionId !== null) remember(incomplete, sessionId, REFUSAL_LIMIT)
406    await update($, evidenceIncomplete, () => true)
407    const problem = (cause: string) => diagnostic('tool.call', tool, `could not save the sighting of ${key}: ${cause}`)
408    await noteCallFault($, isShown, problem(causeOf(error)), problem(shownCause(scope, error)))
409    return false
410  }
411}
412
413/**
414 * Records the sandbox blocks of one call. With scope session, `start` holds the session that ran it and its working
415 * directory, read before it ran. When /clear, /resume, or /branch started another session during the call, its
416 * sightings name the session that ran it, and the session now shows nothing of it: its problems go to the debug log
417 * only. A call whose session is unknown shows in no session, the same way. With scope all (`start` null), both are read
418 * once the call ends, as in Sandbox Tuner 1.1.3.
419 */
420async function recordCall($: EngineInterface, scope: SandboxTunerScope, start: CallStart | null, call: BashCall, outcome: BashOutcome, signal: AbortSignal, tool = 'Bash'): Promise<void> {
421  if (signal.aborted) return
422  const taskId = outcome.backgroundTaskId
423  if (taskId !== undefined && (await read($, backgroundTasks)).includes(taskId)) return
424  const origin = start?.origin ?? null
425  const { reports, gated, unknownLine, observation, skipped } = readCall(call, outcome, await homeOf($), start?.cwd ?? (await $.session.cwd()))
426  const isQuiet = reports.length === 0 && gated.length === 0 && unknownLine === null && observation === undefined
427  const isShown = origin === null || isQuiet || (await isSessionNow($, scope, origin.session))
428  // The debug log only: the pane would show a block that the command printed as a problem.
429  if (skipped) logDebug($, diagnostic('tool.call', tool, 'skipped a <sandbox_violations> block that does not end the text of a failed call (not quoted: the command can print one)'))
430  if (unknownLine !== null) {
431    const quote = reportQuote(unknownLine)
432    const cause = quote === null
433      ? `skipped a sandbox report line of an unknown form (${unknownLine.length} characters, not quoted: it does not start like a report line)`
434      : `skipped a sandbox report line of an unknown form: ${quote}`
435    await noteCallFault($, isShown, diagnostic('tool.call', tool, cause))
436  }
437  const sightings = gated.length === 0 ? reports : [...reports, ...(await gatedSightings($, gated, tool, isShown))]
438  if (observation !== undefined && isShown) {
439    const at = await $.clock.now()
440    await update($, latest, () => ({ recordKey: `observation:${at}`, detail: observation.detail, reason: 'operation', reasonText: observation.operation, command: commandLine(call.command), at }))
441  }
442  if (taskId !== undefined) await update($, backgroundTasks, list => [...list, taskId])
443  if (sightings.length === 0) return
444  const sessionId = await sessionIdOf($, tool, origin, isShown)
445  const now = await $.clock.now()
446  await keepBranchKeys($, sessionId, now)
447  let isLost = false
448  for (const sighting of sightings) {
449    if (signal.aborted) break
450    if (!(await saveSighting($, scope, sighting, sessionId, now, tool, isShown))) isLost = true
451  }
452  // Once for the call: the store that could not save a sighting can refuse this write too.
453  if (isLost && sessionId !== null) await saveRefusal($, sessionId, 'tool.call')
454  if (signal.aborted) return
455  const newest = latestOf(sightings, commandLine(call.command), now)
456  if (newest !== null && isShown) await update($, latest, () => newest)
457}
458
459/** Every writer's saved record, of `targetKey` only when given. A record that is not valid fails the read. */
460async function readWriterRecords($: EngineInterface, targetKey?: string): Promise<SandboxTunerRecord[]> {
461  const found: SandboxTunerRecord[] = []
462  for (const key of await $.store.keys()) {
463    if (!key.startsWith(WRITER_PREFIX)) continue
464    const writerSeparator = key.indexOf(':', WRITER_PREFIX.length)
465    if (writerSeparator <= WRITER_PREFIX.length) throw new KeyFailure('invalid writer key', key)
466    const storedTarget = key.slice(writerSeparator + 1)
467    if (targetKey !== undefined && storedTarget !== targetKey) continue
468    const value = await $.store.get(key)
469    if (!isRecord(value) || storedTarget !== value.key) {
470      throw new KeyFailure('invalid saved safety evidence', key)
471    }
472    found.push(value)
473  }
474  return found
475}
476
477/**
478 * Read durable evidence before displaying it or authorizing a new grant. With `lineage`, only the targets that a
479 * session of the lineage saw by its time (seenIn), each with the sightings of every session.
480 */
481async function readRecords($: EngineInterface, targetKey?: string, lineage?: readonly Lineage[]): Promise<SandboxTunerRecord[]> {
482  const found = await readWriterRecords($, targetKey)
483  const combined = aggregateRecords(lineage === undefined ? found : seenIn(found, lineage))
484  for (const record of combined) {
485    const hidden = await $.store.get(HIDDEN_PREFIX + record.key)
486    if (hidden !== undefined && typeof hidden !== 'boolean') throw new KeyFailure('invalid hidden preference', record.key)
487    if (typeof hidden === 'boolean') record.isHidden = hidden
488  }
489  return combined
490}
491
492/**
493 * The sessions whose sightings and changes the view of `session` shows with scope session: the session itself, then
494 * each session that it branched from, with the targets that it saw by that branch and up to the time of that branch,
495 * at most 10 steps up (lineageStep). A branch record that cannot be read or is not valid ends the walk, and the debug
496 * log says why: the view then shows less.
497 */
498async function lineageOf($: EngineInterface, session: string, event: string, detail: string | null): Promise<Lineage[]> {
499  const lineage: Lineage[] = [{ session, until: Number.POSITIVE_INFINITY, keys: null }]
500  for (let child = session; ;) {
501    const key = LINEAGE_PREFIX + child
502    let found: unknown
503    try {
504      found = await $.store.get(key)
505    } catch (error) {
506      logDebug($, diagnostic(event, detail, `could not read the branch record ${key}: ${causeOf(error)}`))
507      return lineage
508    }
509    if (found === undefined) return lineage
510    if (!isLineage(found, child)) {
511      logDebug($, diagnostic(event, detail, `skipped a branch record that is not valid: ${key}`))
512      return lineage
513    }
514    const step = lineageStep(lineage, found)
515    if (step === null) return lineage
516    lineage.push(step)
517    child = step.session
518  }
519}
520
521/** The lineage of the current session (sessionNow, lineageOf). */
522async function currentLineage($: EngineInterface, event: string, detail: string | null): Promise<Lineage[]> {
523  return lineageOf($, await sessionNow($), event, detail)
524}
525
526/**
527 * Keeps the refusal of Allow and Deny in `session`: a branch whose parent could not save a sighting, a session of this
528 * process that could not, or after a switch that Sandbox Tuner settled, a session that can be a branch of one
529 * (settleSwitch). While $.state refuses it, the session stays in `unrestored`: Allow and Deny refuse, and a load shows
530 * no target that a branch inherited (targetLineage). The store keeps the refusal too (saveRefusal). Returns why $.state
531 * could not keep the refusal, or null.
532 */
533async function keepRefusal($: EngineInterface, session: string, event: string): Promise<string | null> {
534  remember(incomplete, session, REFUSAL_LIMIT)
535  try {
536    await update($, evidenceIncomplete, () => true)
537    unrestored.delete(session)
538    return null
539  } catch (error) {
540    unrestored.add(session)
541    return causeOf(error)
542  } finally {
543    await saveRefusal($, session, event)
544  }
545}
546
547/**
548 * The lineage whose targets a load shows: only the current session while it, or a session of its lineage, could not
549 * keep the refusal of its parent (unrestored). Each load tries to keep the refusal in the current session, and once one
550 * does, the branch shows what it inherited.
551 */
552async function targetLineage($: EngineInterface, event: string, detail: string | null, lineage: readonly Lineage[]): Promise<readonly Lineage[]> {
553  const [own] = lineage
554  if (own === undefined || !lineage.some(item => unrestored.has(item.session))) return lineage
555  const cause = await keepRefusal($, own.session, event)
556  if (cause === null) return lineage
557  logDebug($, diagnostic(event, detail, `could not keep the refusal after a sighting that the session before could not save, so the branch shows no target of it: ${cause}`))
558  return [own]
559}
560
561/**
562 * Whether the current session, or a session of its lineage, is a branch that could not keep the refusal of its parent
563 * (unrestored). Also when the lineage cannot be read then.
564 */
565async function isUnrestored($: EngineInterface, buttonKey: string): Promise<boolean> {
566  if (unrestored.size === 0) return false
567  return currentLineage($, 'ui.press', buttonKey).then(lineage => lineage.some(item => unrestored.has(item.session)), () => true)
568}
569
570/**
571 * Display retention never deletes another writer's mutable safety evidence. With scope session, the display keeps only
572 * the targets of the lineage of the current session (currentLineage), and a problem names no saved key (shownCause).
573 * Returns the targets, or the problem as the report shows it.
574 */
575async function loadSaved($: EngineInterface, scope: SandboxTunerScope, event: string, detail: string | null): Promise<SandboxTunerRecord[] | string> {
576  try {
577    const lineage = scope === 'all' ? undefined : await currentLineage($, event, detail)
578    const found = await readRecords($, undefined, lineage === undefined ? undefined : await targetLineage($, event, detail, lineage))
579    const journal = journalOf(await reconcileJournal($, scope, await readJournal($), lineage))
580    const kept = shownRecords(found, await $.clock.now())
581    await update($, records, () => kept)
582    await update($, applied, () => journal)
583    return kept
584  } catch (error) {
585    const problem = (cause: string) => diagnostic(event, detail, `could not load saved targets: ${cause}`)
586    const shown = problem(shownCause(scope, error))
587    await noteFault($, problem(causeOf(error)), shown)
588    return shown
589  }
590}
591
592// A press that wrote the settings file names the change, which the press checks again once the write has settled.
593type Written = { file: FileInfo; entry: SandboxTunerApplied }
594type PressResult = { text: string; isError: boolean; written: Written | null }
595
596const dismissed = atom({ plugin: 'sandbox-tuner', key: 'dismissed' } as const, null as string | null)
597const notice = atom({ plugin: 'sandbox-tuner', key: 'notice' } as const, null as SandboxTunerNotice | null)
598const PANE = 'sandbox-tuner'
599const PANE_OPEN = { id: PANE, title: 'Sandbox Tuner', focus: true, closeOnEscape: true } as const
600// Claude Code applies a settings edit once its file watcher sees it: draw again after that had time to happen.
601const REDRAW_AFTER_WRITE_MS = 2000
602// The error code that ends the text of a failed $.fs call for a path where nothing is.
603const MISSING = /\b(?:ENOENT|ENOTDIR)$/
604
605type JournalChange = { buttonKey: string; file: FileInfo; entry: SandboxTunerApplied; success: string; didWrite: boolean }
606
607/** The text of a file, or null when it does not exist. */
608async function fileText($: EngineInterface, path: string): Promise<string | null> {
609  return (await $.fs.exists(path)) ? $.fs.read(path) : null
610}
611
612async function isCanonicalFile($: EngineInterface, path: string, event: string): Promise<boolean> {
613  try {
614    const text = await fileText($, path)
615    if (text === null) return true
616    const parsed = parseSettings(text)
617    return 'refusal' in parsed || parsed.isCanonical
618  } catch (error) {
619    logDebug($, diagnostic(event, null, `could not read ${path} to check its format: ${causeOf(error)}`))
620    return true
621  }
622}
623
624/** The settings files of the journal's Undo rows that are not in the 2-space JSON format: an Undo re-formats them. */
625async function reformattedFiles($: EngineInterface, journal: readonly SandboxTunerApplied[], context: Context): Promise<string[]> {
626  const found: string[] = []
627  for (const path of new Set(journal.filter(canUndo).map(entry => entry.file))) {
628    const isCanonical = path === context.file?.path ? context.isCanonical : await isCanonicalFile($, path, 'ui.render (Pane)')
629    if (!isCanonical) found.push(path)
630  }
631  return found
632}
633
634async function loadContext($: EngineInterface, threshold: number, event: string): Promise<Context> {
635  const sources: Sources = {
636    user: await $.settings.read({ source: 'user' }),
637    project: await $.settings.read({ source: 'project' }),
638    local: await $.settings.read({ source: 'local' }),
639    flag: await $.settings.read({ source: 'flag' }),
640    policy: await $.settings.read({ source: 'policy' }),
641  }
642  const home = await homeOf($)
643  const cwd = await $.session.cwd()
644  const root = await $.session.root()
645  // A relative CLAUDE_CONFIG_DIR is taken from the session root, read again on each call: the folder the session
646  // started in, or where /cd or a worktree move took it (types: session.root). The docs ask for an absolute path.
647  const configDir = folderOf(await $.env.get('CLAUDE_CONFIG_DIR'), root) ?? (home === undefined ? undefined : `${home}/.claude`)
648  const file = configDir === undefined ? undefined : fileInfo(`${configDir}/settings.json`, home)
649  return {
650    sources,
651    home,
652    configDir,
653    ...guardedPlaces(home, configDir, [cwd, root]),
654    pathDirs: pathFolders(await $.env.get('PATH'), cwd),
655    tmp: TMP,
656    cwd,
657    root,
658    threshold,
659    file,
660    isCanonical: file === undefined || (await isCanonicalFile($, file.path, event)),
661  }
662}
663
664function failure(buttonKey: string, cause: string): PressResult {
665  return { text: diagnostic('ui.press', buttonKey, cause), isError: true, written: null }
666}
667
668function info(text: string): PressResult {
669  return { text, isError: false, written: null }
670}
671
672/** The text of the settings file as one read found it, null when there was no file, and what it holds. */
673type Loaded = { original: string | null; parsed: ParsedSettings }
674
675/** The text of the settings file (`found`), or the result of a press that cannot read it. */
676async function readText($: EngineInterface, file: FileInfo, buttonKey: string): Promise<{ found: string | null } | PressResult> {
677  try {
678    return { found: await fileText($, file.path) }
679  } catch (error) {
680    return failure(buttonKey, `could not read ${file.display}: ${causeOf(error)}. Nothing was written.`)
681  }
682}
683
684async function readSettingsFile($: EngineInterface, file: FileInfo, buttonKey: string): Promise<Loaded | PressResult> {
685  const read = await readText($, file, buttonKey)
686  if (!('found' in read)) return read
687  const parsed = parseSettings(read.found ?? '')
688  return 'refusal' in parsed ? failure(buttonKey, refusalText(parsed, file)) : { original: read.found, parsed }
689}
690
691// The lock of a settings file, `file.lock` next to it (fileInfo), so that presses in different sessions edit the file in
692// turn. $.fs has no exclusive create and no delete: a press claims the lock file by writing its own token and reading it
693// back, and frees it by writing a free record. Right before its settings write, it checks that it still holds the lock.
694const LOCK_POLL_MS = 100
695// How long a press waits for a lock that another press holds. The press waits in the module queue, so it stays short.
696const LOCK_WAIT_MS = 3_000
697// A lock that no press freed for this long is left over, from a press that stopped: the next press takes it over.
698const LOCK_STALE_MS = 30_000
699
700/** The token of the press that a lock file names, or null when it names none. */
701function holderOf(text: string | null): string | null {
702  const found = readLock(text)
703  return found === null || found === 'free' ? null : found.holder
704}
705
706/**
707 * Takes the lock of the settings file for one press: once it is free, or once it is left over. Returns the press's
708 * token, or the result of a press that cannot take it.
709 */
710async function takeLock($: EngineInterface, file: FileInfo, buttonKey: string): Promise<string | PressResult> {
711  const token = crypto.randomUUID()
712  const started = await $.clock.now()
713  for (;;) {
714    const now = await $.clock.now()
715    try {
716      const found = readLock(await fileText($, file.lock))
717      // A lock file of other text, such as one that a write has not finished, ages from its last change.
718      const since = found === 'free' ? now : found === null ? (await $.fs.stat(file.lock)).mtimeMs : found.since
719      const isLeft = Math.abs(now - since) >= LOCK_STALE_MS
720      if (found === 'free' || isLeft) {
721        await $.fs.write(file.lock, lockText(token, now))
722        // Another press that found the lock free at the same moment can claim it last: then it holds the lock.
723        if (holderOf(await $.fs.read(file.lock)) === token) {
724          if (isLeft) logDebug($, diagnostic('ui.press', buttonKey, `took over the lock on ${file.display} (${file.lockDisplay}), which no press freed within ${LOCK_STALE_MS / 1000} seconds`))
725          return token
726        }
727      }
728    } catch (error) {
729      return failure(buttonKey, `could not take the lock on ${file.display} (${file.lockDisplay}): ${causeOf(error)}. Nothing was written.`)
730    }
731    if (now - started >= LOCK_WAIT_MS) {
732      return failure(buttonKey, `another Sandbox Tuner session holds the lock on ${file.display} (${file.lockDisplay}) and did not free it within ${LOCK_WAIT_MS / 1000} seconds. Nothing was written. Press again.`)
733    }
734    await $.clock.sleep(LOCK_POLL_MS)
735  }
736}
737
738/** Frees the lock that the press holds, and leaves a lock that another press took over. It never rejects. */
739async function freeLock($: EngineInterface, file: FileInfo, token: string, buttonKey: string): Promise<void> {
740  try {
741    if (holderOf(await fileText($, file.lock)) === token) await $.fs.write(file.lock, lockText(null, await $.clock.now()))
742  } catch (error) {
743    logDebug($, diagnostic('ui.press', buttonKey, `could not free the lock on ${file.display} (${file.lockDisplay}): ${causeOf(error)}. Other sessions take it over ${LOCK_STALE_MS / 1000} seconds after this press took it.`))
744  }
745}
746
747/** Null while the press holds the lock of the settings file, else why the press stops. */
748async function lockLoss($: EngineInterface, file: FileInfo, token: string): Promise<string | null> {
749  try {
750    if (holderOf(await fileText($, file.lock)) === token) return null
751    return `another Sandbox Tuner session took over the lock on ${file.display} (${file.lockDisplay}) during this press. Sandbox Tuner left the file as it is. Press again.`
752  } catch (error) {
753    return `could not check the lock on ${file.display} (${file.lockDisplay}): ${causeOf(error)}. Sandbox Tuner left the file as it is. Press again.`
754  }
755}
756
757/**
758 * Writes `file.backup`, a copy of the old text, then `file.path`, the user settings file. The path is not fixed text:
759 * it is `$CLAUDE_CONFIG_DIR/settings.json`, else `$HOME/.claude/settings.json` (loadContext), or for Undo the file that
760 * the change went into. The copy is `backups/settings.json.sandbox-tuner.bak` in the same folder (fileInfo). The press
761 * holds the lock of the file (`token`).
762 */
763async function writeSettings($: EngineInterface, buttonKey: string, file: FileInfo, original: string | null, text: string, entry: SandboxTunerApplied, token: string, sessionChange: () => Promise<string | null>): Promise<PressResult | null> {
764  const previous = original === null ? 'The file did not exist before.' : `The previous file is saved at ${file.backupDisplay}.`
765  if (original !== null) {
766    try {
767      await $.fs.write(file.backup, original)
768    } catch (error) {
769      return failure(buttonKey, `could not save a copy of ${file.display} to ${file.backupDisplay}: ${causeOf(error)}. Nothing was written.`)
770    }
771  }
772  const pending = await saveJournal($, { buttonKey, file, entry, success: '', didWrite: false })
773  if (pending.isError) return pending
774  // $.fs has no conditional write: check last that no other session or program saved the file since the press read it,
775  // that no other press took the lock over, and with scope session, that the session of the press is still current.
776  const change = await fileText($, file.path).then(
777    current => (current === original ? null : 'another program changed it'),
778    (error: unknown) => causeOf(error),
779  )
780  const stop = change === null
781    ? (await lockLoss($, file, token)) ?? (await sessionChange())
782    : `could not confirm that ${file.display} is unchanged since Sandbox Tuner read it (${change}). Sandbox Tuner left the file as it is. Press again.`
783  if (stop !== null) {
784    // No settings write was attempted, so this addition cannot own an entry in the file.
785    if (entry.applyState === 'pending') {
786      try {
787        await $.store.delete(JOURNAL_PREFIX + entry.id)
788        await update($, applied, list => list.filter(item => item.id !== entry.id))
789      } catch (error) {
790        await noteFault($, diagnostic('ui.press', buttonKey, `could not discard the unwritten addition from the Undo journal: ${causeOf(error)}`))
791      }
792    }
793    return failure(buttonKey, stop)
794  }
795  // Keep Undo even if the write or its read-back fails after changing the file.
796  const written = { file, entry }
797  try {
798    await $.fs.write(file.path, text)
799  } catch (error) {
800    const repair = original === null ? 'Delete it if a damaged copy is left.' : `Copy it back if ${file.display} is now damaged.`
801    return { ...failure(buttonKey, `could not write ${file.display}: ${causeOf(error)}. ${previous} ${repair}`), written }
802  }
803  const problem = await $.fs.read(file.path).then(
804    readBack => (readBack === text ? null : 'another program changed it'),
805    (error: unknown) => causeOf(error),
806  )
807  return problem === null ? null : { ...failure(buttonKey, `${file.display} does not hold the new text after the write (${problem}). ${previous}`), written }
808}
809
810async function saveJournal($: EngineInterface, change: JournalChange): Promise<PressResult> {
811  const { entry } = change
812  try {
813    await $.store.set(JOURNAL_PREFIX + entry.id, entry)
814    await update($, applied, list => journalOf([...list.filter(item => item.id !== entry.id), entry]))
815    // The band of a fixed block stays hidden, even once the journal keeps the fix no longer.
816    await update($, latest, last => (last !== null && isFixedSince([entry], last) ? null : last))
817    return { text: change.success, isError: false, written: change.didWrite ? { file: change.file, entry } : null }
818  } catch (error) {
819    const cause = change.didWrite
820      ? `${change.file.display} is saved, but Sandbox Tuner could not update its Undo journal: ${causeOf(error)}. Check "${entry.entry}" in ${entry.settingsKey} by hand.`
821      : entry.applyState === 'pending'
822        ? `could not save the Undo journal: ${causeOf(error)}. Nothing was written to ${change.file.display}.`
823        : `could not mark "${entry.entry}" as undone: ${causeOf(error)}`
824    return { ...failure(change.buttonKey, cause), written: change.didWrite ? { file: change.file, entry } : null }
825  }
826}
827
828/**
829 * True when nothing is at the path: $.fs.stat rejects ENOENT for a missing path, or ENOTDIR below a file. It does not
830 * follow a link, so it finds a link that leads nowhere. Any other failure rejects: then no one knows what is there.
831 */
832async function isMissing($: EngineInterface, path: string): Promise<boolean> {
833  return $.fs.stat(path).then(
834    () => false,
835    (error: unknown) => {
836      if (MISSING.test(causeOf(error))) return true
837      throw error
838    },
839  )
840}
841
842/**
843 * Where an absolute path really lies, found one name at a time as the system finds it: a link is followed before a
844 * `..` after it, which $.fs cannot do, because it folds `..` first. `known` holds the names already looked up in this
845 * press, so a folder that many paths share is looked up once.
846 */
847async function realLocation($: EngineInterface, path: string, known: Map<string, string>): Promise<string> {
848  let real = '/'
849  for (const name of path.split('/')) {
850    if (name === '' || name === '.') continue
851    if (name === '..') {
852      real = real.slice(0, real.lastIndexOf('/')) || '/'
853      continue
854    }
855    const next = `${real === '/' ? '' : real}/${name}`
856    real = known.get(next) ?? (await landing($, next, known))
857  }
858  return real
859}
860
861/**
862 * Where one path whose folder is real lands: its real path, or itself when nothing is there yet. Rejects, naming the
863 * path, when it is a link that leads nowhere or the file system withholds where it lands, because then no one can
864 * tell where a write through it goes (types: FsStat.realPath).
865 */
866async function landing($: EngineInterface, path: string, known: Map<string, string>): Promise<string> {
867  let landed = path
868  if (await $.fs.exists(path)) {
869    const found = (await $.fs.stat(path, { resolve: true })).realPath
870    if (found === undefined) throw new Error(`the file system gave no real path for ${path}`)
871    landed = found
872  } else if (!(await isMissing($, path))) {
873    throw new Error(`${path} is a link that Sandbox Tuner cannot follow`)
874  }
875  known.set(path, landed)
876  return landed
877}
878
879async function realPlaces($: EngineInterface, paths: readonly string[], known: Map<string, string>): Promise<string[]> {
880  const places: string[] = []
881  for (const path of paths) places.push(await realLocation($, path, known))
882  return places
883}
884
885// The most folders and entries that one walk of guarded places lists. With the data folders of the config folder
886// skipped, the walk of a config folder with many plugins and skills lists about 450 folders and 3,000 entries. The
887// walk of 77 VS Code extensions, two levels of each, adds about 340 folders and 4,000 entries.
888const WALK_FOLDERS = 1000
889const WALK_ENTRIES = 25_000
890
891/** A folder that Allow opened: its entry, the settings files that hold it, and where it really lies. */
892type Grant = Granted & { place: string }
893/** A link or guarded place, as listed, whose real place lies inside or holds folders that Allow opened: each of them. */
894type Finding = { path: string; place: string; met: { grant: Grant; isInside: boolean }[] }
895/**
896 * What the check at session start gives a walk: the folders that Allow opened, and where the walk keeps what it finds
897 * and the links that it cannot follow, so that a walk that stops keeps both.
898 */
899type Recheck = { grants: Grant[]; found: Finding[]; skipped: string[] }
900
901/** Where a path leads, or null when the check at session start cannot follow it: the check then names it. */
902async function followed($: EngineInterface, path: string, known: Map<string, string>, recheck: Recheck): Promise<string | null> {
903  try {
904    return await realLocation($, path, known)
905  } catch {
906    recheck.skipped.push(path)
907    return null
908  }
909}
910
911/** Keeps a place that meets a folder that Allow opened as a finding. The walk does not enter such a place. */
912function isFinding(recheck: Recheck, path: string, place: string): boolean {
913  const met = grantsMet(place, recheck.grants)
914  if (met.length > 0) recheck.found.push({ path, place, met })
915  return met.length > 0
916}
917
918/**
919 * The real places that the links inside guarded places lead to, nested links too: each walk lists its levels, with
920 * bounded work and cycle detection. A link counts wherever it is listed, and the walk goes on where it leads. For the
921 * check at session start (`recheck`), a link that meets a folder that Allow opened is a finding, and a link that
922 * cannot be followed is skipped.
923 */
924async function linksInside($: EngineInterface, walks: readonly Walk[], known: Map<string, string>, recheck?: Recheck): Promise<string[]> {
925  const places: string[] = []
926  // `at` holds the names from the walked place down to the folder, for its skip entries.
927  const pending = walks.map(walk => ({ ...walk, at: [] as readonly string[] }))
928  // The most levels listed from each folder, so that a folder reached again is listed again only for more levels.
929  const listed = new Map<string, number>()
930  let folders = 0
931  let entries = 0
932  while (pending.length > 0) {
933    const { path: folder, levels, skip, at } = pending.pop()!
934    if ((listed.get(folder) ?? 0) >= levels) continue
935    listed.set(folder, levels)
936    if (!(await $.fs.exists(folder))) {
937      if (!(await isMissing($, folder))) throw new Error(`cannot resolve guarded path ${folder}`)
938      continue
939    }
940    if ((await $.fs.stat(folder)).kind !== 'dir') continue
941    if (++folders > WALK_FOLDERS) throw new Error('guarded directory traversal limit exceeded')
942    const children = await $.fs.list(folder)
943    entries += children.length
944    if (entries > WALK_ENTRIES) throw new Error('guarded directory traversal limit exceeded')
945    for (const entry of children) {
946      const path = `${folder}/${entry.name}`
947      const below = { levels: levels - 1, skip, at: [...at, entry.name] }
948      const isEntered = levels > 1 && !isSkipped(skip, below.at)
949      if (entry.isLink) {
950        const real = recheck === undefined ? await realLocation($, path, known) : await followed($, path, known, recheck)
951        if (real === null || (recheck !== undefined && isFinding(recheck, path, real))) continue
952        places.push(real)
953        if (isEntered) pending.push({ ...below, path: real })
954      } else if (entry.kind === 'dir' && isEntered) pending.push({ ...below, path })
955    }
956  }
957  return places
958}
959
960/** The real places of guarded places, with every place that a link inside them leads to. */
961async function realGuards($: EngineInterface, walks: readonly Walk[], known: Map<string, string>, recheck?: Recheck): Promise<string[]> {
962  const located: Walk[] = []
963  for (const walk of walks) {
964    const path = recheck === undefined ? await realLocation($, walk.path, known) : await followed($, walk.path, known, recheck)
965    if (path !== null && (recheck === undefined || !isFinding(recheck, walk.path, path))) located.push({ ...walk, path })
966  }
967  return [...located.map(walk => walk.path), ...(await linksInside($, located, known, recheck))]
968}
969
970/**
971 * Rates a folder Allow again where the folder really lies, with HOME, the config dir, the working directory, the
972 * protected places and the credentials folders (with the links that their walks find, see guardedWalks), denial
973 * paths, the PATH folders, and for a folder in /tmp also /tmp, resolved the same way. A folder outside /tmp is rated
974 * with no temp folder, as in Sandbox Tuner 1.1.1. The verdict reads spellings, and a link can hide behind one; an
975 * allow-list on realPath is the robust guard (types: FsStat.realPath). Hard links, links in the places that the walks
976 * skip, and later filesystem changes remain outside these checks. Returns why the folder stays closed, or null.
977 */
978async function checkRealFolder($: EngineInterface, record: SandboxTunerRecord, context: Context): Promise<string | null> {
979  const shown = displayPath(record.target, context.home)
980  try {
981    const known = new Map<string, string>()
982    const target = await realLocation($, record.target, known)
983    const denials = denialEntries(context)
984    for (const entry of [...denials]) denials.push({ ...entry, path: await realLocation($, entry.path, known) })
985    const real: Context = {
986      ...context,
987      home: context.home === undefined ? undefined : await realLocation($, context.home, known),
988      configDir: context.configDir === undefined ? undefined : await realLocation($, context.configDir, known),
989      protectedDirs: await realGuards($, guardedWalks(context.protectedDirs, context), known),
990      credentialDirs: await realGuards($, guardedWalks([...context.credentialDirs, ...credentialEntries(context).map(entry => entry.path)], { home: undefined, configDir: undefined }), known),
991      pathDirs: await realPlaces($, context.pathDirs, known),
992      tmp: isTempFolder(record.target, context.home) ? await realLocation($, TMP, known) : null,
993      cwd: await realLocation($, context.cwd, known),
994    }
995    // The denied file is rated where the write really lands: it can be a link too.
996    const located = { ...record, target, sample: await realLocation($, record.sample, known) }
997    const verdict = denialVerdict([record.sample, located.sample], denials) ?? verdictOf(located, real, isGuessedFolder(record))
998    const place = displayPath(target, real.home)
999    const leads = place === shown ? '' : `${shown} leads to ${place}. `
1000    if (verdict.status === 'ready') {
1001      // A folder in /tmp must really lie strictly inside /tmp, also where it is a cache folder.
1002      if (real.tmp !== null && !isTempFolder(target, real.home, real.tmp)) {
1003        return `${leads}Sandbox Tuner opens a folder in /tmp only when it really lies inside ${displayPath(real.tmp, real.home)}, the real place of /tmp, and your home folder neither holds that place nor lies inside it. Nothing was written.`
1004      }
1005      // The verdict compares with case, and a file system that ignores case reads two spellings as one place.
1006      const folded = target.toLowerCase()
1007      const alias = [...real.pathDirs, ...real.protectedDirs, ...real.credentialDirs].find(dir => isUnder(folded, dir.toLowerCase()) || isUnder(dir.toLowerCase(), folded))
1008      return alias === undefined ? null : `${place} and ${displayPath(alias, real.home)} name one place on a file system that ignores letter case. Nothing was written.`
1009    }
1010    return `${leads}${verdictSentences(located, verdict, real).join(' ')} Nothing was written.`
1011  } catch (error) {
1012    return `could not check where ${shown} leads: ${causeOf(error)}. Nothing was written.`
1013  }
1014}
1015
1016// A warning of the check at session start names a link, a folder, and what to do: it stays long enough to read.
1017const WARNING_MS = 15_000
1018
1019/** A folder entry that Allow added, with each settings file that still holds it. */
1020type Granted = { entry: string; files: string[] }
1021/**
1022 * Where the warning about a folder entry sends the person: whether a row of the pane can undo it, and each settings
1023 * file that holds it with no such row, where only a hand edit removes it.
1024 */
1025type Advice = { hasUndo: boolean; byHand: string[] }
1026
1027/**
1028 * The rows of the Applied list, as the pane shows them: with scope session, only the edits of the lineage of the current
1029 * session. The pane cannot draw that list without the session id, so then no row has an Undo, and each warning names
1030 * the file.
1031 */
1032async function listedRows($: EngineInterface, scope: SandboxTunerScope, event: RecheckEvent, journal: readonly SandboxTunerApplied[]): Promise<SandboxTunerApplied[]> {
1033  const rows = journalOf(journal)
1034  if (scope === 'all') return rows
1035  try {
1036    return appliedIn(rows, await currentLineage($, event, null))
1037  } catch (error) {
1038    logDebug($, diagnostic(event, null, `could not read the session id, so each warning names the settings file to edit: ${causeOf(error)}`))
1039    return []
1040  }
1041}
1042
1043/**
1044 * The entries of the folders that Allow opened in any session that their settings file still holds. The file decides,
1045 * whatever the journal says: an unconfirmed addition, an Undo that failed or is unconfirmed, or an entry marked undone
1046 * that is back.
1047 */
1048async function grantedEntries($: EngineInterface, journal: readonly SandboxTunerApplied[]): Promise<Granted[]> {
1049  const granted = new Map<string, Set<string>>()
1050  const values = new Map<string, Record<string, unknown> | null>()
1051  for (const entry of journal) {
1052    if (entry.settingsKey !== 'sandbox.filesystem.allowWrite') continue
1053    if (!values.has(entry.file)) {
1054      const parsed = parseSettings((await fileText($, entry.file)) ?? '')
1055      values.set(entry.file, 'refusal' in parsed ? null : parsed.value)
1056    }
1057    const value = values.get(entry.file)
1058    if (value === undefined || value === null || !('isPresent' in addEntry(value, entry.settingsKey, entry.entry))) continue
1059    const files = granted.get(entry.entry) ?? new Set<string>()
1060    granted.set(entry.entry, files)
1061    files.add(entry.file)
1062  }
1063  return [...granted].map(([entry, files]) => ({ entry, files: [...files] }))
1064}
1065
1066/**
1067 * The advice of each warning, as the pane shows the Applied list when the walk ends. With scope session, it reads the
1068 * journal and the session id again: /clear, /resume, or /branch can start a session with other rows during the walk.
1069 * With scope all, the journal of the start of the check decides, as in Sandbox Tuner 1.1.3.
1070 */
1071async function adviceOf($: EngineInterface, scope: SandboxTunerScope, event: RecheckEvent, journal: readonly SandboxTunerApplied[], granted: readonly Granted[]): Promise<Map<string, Advice>> {
1072  let rows = journal
1073  if (scope === 'session') {
1074    try {
1075      rows = await readJournal($)
1076    } catch (error) {
1077      logDebug($, diagnostic(event, null, `could not read the Undo journal again, so each warning names the settings file to edit: ${causeOf(error)}`))
1078      rows = []
1079    }
1080  }
1081  const listed = new Set(await listedRows($, scope, event, rows))
1082  const advice = new Map<string, Advice>()
1083  for (const { entry, files } of granted) {
1084    // A row with an Undo button whose press does not refuse: Undo refuses an entry that a later change owns.
1085    const undoable = new Set(rows.filter(row => row.settingsKey === 'sandbox.filesystem.allowWrite' && row.entry === entry && files.includes(row.file) && listed.has(row) && canUndo(row) && !hasLaterOwner(rows, row)).map(row => row.file))
1086    advice.set(entry, { hasUndo: undoable.size > 0, byHand: files.filter(file => !undoable.has(file)) })
1087  }
1088  return advice
1089}
1090
1091/** The event that a check reports with: a check at a session start, or a timed check during the session. */
1092type RecheckEvent = 'session.start' | 'clock.every'
1093/**
1094 * The warnings that a check does not show again (`skip`), and where it keeps the warnings that it shows (`shown`) and
1095 * every warning that it finds, shown or not (`found`). See recheckOnce.
1096 */
1097type Warnings = { skip: readonly ReadonlySet<string>[]; shown: Set<string>; found: Set<string> }
1098
1099/**
1100 * At the start of an interactive session, and on a timer during it, checks the folders that Allow opened and that
1101 * their settings file still holds. It walks the guarded places as a folder Allow does, once for all those folders, and
1102 * finds where the PATH folders lie. Each link or guarded place that leads into such a folder, or to a folder that holds
1103 * one, gives one toast, unless `warnings.skip` holds it. It warns and writes nothing. It runs outside the queue, so that
1104 * its walk never holds back the recording of a Bash call. It never rejects: the hook and the timer drop what it returns.
1105 */
1106async function recheckGrants($: EngineInterface, threshold: number, scope: SandboxTunerScope, event: RecheckEvent, warnings: Warnings): Promise<void> {
1107  let journal: SandboxTunerApplied[]
1108  let entries: Granted[]
1109  let context: Context
1110  try {
1111    journal = await readJournal($)
1112    entries = await grantedEntries($, journal)
1113    if (entries.length === 0) return
1114    context = await loadContext($, threshold, event)
1115  } catch (error) {
1116    logDebug($, diagnostic(event, null, `could not check the folders that Allow opened: ${causeOf(error)}`))
1117    return
1118  }
1119  const known = new Map<string, string>()
1120  const recheck: Recheck = { grants: [], found: [], skipped: [] }
1121  for (const granted of entries) {
1122    const path = anchorEntry(granted.entry, 'user', context)
1123    const place = path === null ? null : await followed($, path, known, recheck)
1124    if (place !== null) recheck.grants.push({ ...granted, place })
1125  }
1126  const problems: string[] = []
1127  if (recheck.grants.length > 0) {
1128    const credentials = [...context.credentialDirs, ...credentialEntries(context).map(entry => entry.path)]
1129    for (const walks of [guardedWalks(context.protectedDirs, context), guardedWalks(credentials, { home: undefined, configDir: undefined })]) {
1130      // A walk that stops keeps what it found before.
1131      await realGuards($, walks, known, recheck).catch((error: unknown) => problems.push(causeOf(error)))
1132    }
1133    for (const dir of context.pathDirs) {
1134      const place = await followed($, dir, known, recheck)
1135      if (place !== null) isFinding(recheck, dir, place)
1136    }
1137  }
1138  const display = (path: string) => displayPath(path, context.home)
1139  // Read when the walk ends, right before the toasts (adviceOf).
1140  const advice = recheck.found.length === 0 ? new Map<string, Advice>() : await adviceOf($, scope, event, journal, entries)
1141  const warned = new Set<string>()
1142  for (const { path, place, met } of recheck.found) {
1143    if (warned.has(path)) continue
1144    warned.add(path)
1145    const grants = met.map(({ grant, isInside }) => {
1146      const { hasUndo, byHand } = advice.get(grant.entry) ?? { hasUndo: false, byHand: grant.files }
1147      return { grant: grant.entry, isInside, hasUndo, byHand: byHand.map(file => fileInfo(file, context.home).display) }
1148    })
1149    const warning = grantWarning(display(path), display(place), grants)
1150    const isWarned = warnings.skip.some(skipped => skipped.has(warning))
1151    warnings.found.add(warning)
1152    if (isWarned) continue
1153    warnings.shown.add(warning)
1154    const text = diagnostic(event, null, warning)
1155    logDebug($, text)
1156    $.ui.toast(drawable(hostText(text)), { timeoutMs: WARNING_MS })
1157  }
1158  if (recheck.skipped.length > 0) problems.unshift(`links that it cannot follow: ${[...new Set(recheck.skipped)].map(display).join(', ')}`)
1159  if (problems.length > 0) {
1160    await noteFault($, diagnostic(event, null, `could not finish the link check of the folders that Allow opened (${problems.join('; ')}). A link that the check did not reach can still lead into one of them.`))
1161  }
1162}
1163
1164// One check at a time in each module instance: `claude --resume` raises session.start and classic.SessionStart at once,
1165// and the timer of the session can fire during a walk. Each request waits for the check that runs or waits last.
1166let lastRecheck: Promise<void> = Promise.resolve()
1167// The number of the newest request. A request that a newer one follows before its turn does not run.
1168let newestRecheck = 0
1169// The warnings that the checks showed since the last time that no check ran or waited.
1170let shownWarnings = new Set<string>()
1171// Whether a session start asked for a check that has not begun yet: the next check to begin is then its check.
1172let isStartPending = false
1173// The warnings that the checks found since the last check of a session start began, shown or not: a timed check does
1174// not show them, because the session was warned about them.
1175let startWarnings = new Set<string>()
1176
1177/**
1178 * Runs recheckGrants, one check at a time. A request that comes while a check runs waits, the newest only, and its
1179 * check runs right after that check ends, with the context that its session has then: a session that /clear,
1180 * /resume, or /branch starts during a walk gets a check of its own. A check that waited does not show a warning again
1181 * that a check before it showed, so one start warns once. A timed request (`isStart` false) shows only what the
1182 * session was not warned about since its start, and a session start that a timed request follows before its turn still
1183 * gets its check. It never rejects.
1184 */
1185async function recheckOnce($: EngineInterface, threshold: number, scope: SandboxTunerScope, isStart: boolean): Promise<void> {
1186  newestRecheck += 1
1187  const request = newestRecheck
1188  if (isStart) isStartPending = true
1189  const run = async () => {
1190    if (request !== newestRecheck) return
1191    const isStartCheck = isStartPending
1192    isStartPending = false
1193    if (isStartCheck) startWarnings = new Set()
1194    const skip = isStartCheck ? [shownWarnings] : [shownWarnings, startWarnings]
1195    await recheckGrants($, threshold, scope, isStartCheck ? 'session.start' : 'clock.every', { skip, shown: shownWarnings, found: startWarnings })
1196  }
1197  const check = lastRecheck.then(run, run)
1198  lastRecheck = check
1199  try {
1200    await check
hooks/diagnostics.ts 32 lines
1// The diagnostic form: the mod, the event, and the cause.
2
3import type { SandboxTunerScope } from '../types'
4
5const MOD = 'sandbox-tuner'
6
7export function diagnostic(event: string, detail: string | null, cause: string): string {
8  return `${MOD}: ${event}${detail === null ? '' : ` (${detail})`}: ${cause}`
9}
10
11export function causeOf(error: unknown): string {
12  return error instanceof Error && error.message !== '' ? error.message : String(error)
13}
14
15/** A failure that names a saved key, which can name a target of another session. */
16export class KeyFailure extends Error {
17  readonly reason: string
18
19  constructor(reason: string, key: string) {
20    super(`${reason}: ${key}`)
21    this.reason = reason
22  }
23}
24
25/**
26 * The cause of a failure as the band, the pane, and the report show it. With scope session, a failure that names a
27 * saved key leaves the key out, so that no target of another session shows. The debug log keeps the full cause.
28 */
29export function shownCause(scope: SandboxTunerScope, error: unknown): string {
30  return scope === 'session' && error instanceof KeyFailure ? `${error.reason} (the debug log names its key)` : causeOf(error)
31}
32
hooks/names.ts 236 lines
1// Naming rules for hosts, write folders, and commands.
2
3type HostPort = { host: string; port: number | null }
4
5const LABEL = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/
6// IPv4 also accepts fewer components, octal digits, and hexadecimal components.
7const IPV4 = /^(?:\d+|0x[0-9a-f]*)(?:\.(?:\d+|0x[0-9a-f]*)){0,3}$/i
8const LOCAL_NAMESPACES = ['localhost', 'local', 'home.arpa', 'internal']
9// Under HOME, `<root>/<name>/...` gives the cache folder `<root>/<name>` of any tool.
10const NAMED_CACHE_ROOTS: readonly (readonly string[])[] = [['.cache'], ['Library', 'Caches']]
11// Under HOME, `<cache>/...` gives `<cache>`: package caches that hold downloads only.
12const PACKAGE_CACHES: readonly (readonly string[])[] = [
13  ['.npm', '_cacache'],
14  ['.cargo', 'registry'],
15  ['.cargo', 'git'],
16  ['.gradle', 'caches'],
17  ['.m2', 'repository'],
18  ['.local', 'share', 'pnpm', 'store'],
19  ['Library', 'pnpm', 'store'],
20]
21const TEMP_ROOTS: readonly (readonly string[])[] = [
22  ['', 'var', 'folders'],
23  ['', 'private', 'var', 'folders'],
24]
25const TEMP_MARKERS: ReadonlySet<string> = new Set(['T', 'C'])
26// The temp folder that every app shares. A folder strictly inside it is a temp folder. /tmp itself is too broad.
27export const TMP = '/tmp'
28const COMMAND_LIMIT = 120
29// What the engine refuses in a text: control characters other than tab, newline, and carriage return, a lone
30// surrogate, and its own placeholder character.
31const UNDRAWABLE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\ud800-\udfff\u{10eeee}]/gu
32const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/
33// An assignment whose value holds no quote, substitution, brace, or escape: it ends at the next space.
34const PLAIN_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=[^'"`$(){}\\]*$/
35// A file name: at most 255 characters, the most a file system takes.
36const PROGRAM_NAME = /^[\w.+-]{1,255}$/
37// Protected names that hold in any folder: settings or code in them can run outside the sandbox.
38export const CLAUDE_PROTECTED: ReadonlySet<string> = new Set(['settings.json', 'settings.local.json', 'skills', 'agents', 'commands', 'hooks', 'workflows', 'scheduled_tasks.json'])
39const GIT_PROTECTED: ReadonlySet<string> = new Set(['hooks', 'config'])
40const EDITOR_FOLDERS: ReadonlySet<string> = new Set(['.vscode', '.idea'])
41const MCP_FILE = '.mcp.json'
42// Shell startup files and the git configuration.
43const STARTUP_FILES: ReadonlySet<string> = new Set(['.bashrc', '.bash_profile', '.bash_login', '.bash_logout', '.profile', '.zshrc', '.zshenv', '.zprofile', '.zlogin', '.zlogout', '.gitconfig'])
44/** Every protected place that a folder can hold, as a path from that folder. */
45export const PROTECTED_PLACES: readonly string[] = [
46  ...[...CLAUDE_PROTECTED].map(name => `.claude/${name}`),
47  ...[...GIT_PROTECTED].map(name => `.git/${name}`),
48  ...EDITOR_FOLDERS,
49  MCP_FILE,
50  ...STARTUP_FILES,
51]
52const KEY_FILE = /\.(?:pem|key)$/i
53
54/** A host as the sandbox compares it: lowercase, one trailing dot cut. */
55export function normalHost(host: string): string {
56  const lower = host.toLowerCase()
57  return lower.endsWith('.') ? lower.slice(0, -1) : lower
58}
59
60/** The host and port of `host:port`, `[v6]:port`, or a bare host. */
61export function splitHost(text: string): HostPort {
62  const isBracketed = text.startsWith('[')
63  const end = isBracketed ? text.indexOf(']') + 1 : text.lastIndexOf(':')
64  const hasPort = end > 0 && /^:\d+$/.test(text.slice(end))
65  return {
66    host: normalHost(hasPort || isBracketed ? text.slice(0, end) : text),
67    port: hasPort ? Number(text.slice(end + 1)) : null,
68  }
69}
70
71/** True for a DNS name of two or more labels that is no IP literal and no local name. */
72export function isDnsName(host: string): boolean {
73  const labels = host.split('.')
74  return (
75    host.length <= 253 &&
76    labels.length >= 2 &&
77    !IPV4.test(host) &&
78    !LOCAL_NAMESPACES.some(name => host === name || host.endsWith(`.${name}`)) &&
79    labels.every(label => label.length <= 63 && LABEL.test(label))
80  )
81}
82
83/** Whether a settings host entry covers the host on every given port. A record keeps at most five ports, so an earlier port can be missing. */
84export function hostMatches(entry: string, host: string, ports: readonly number[]): boolean {
85  const pattern = splitHost(entry.trim())
86  const isPortMatch = pattern.port === null || (ports.length > 0 && ports.every(port => port === pattern.port))
87  if (!isPortMatch) return false
88  if (pattern.host === '*') return true
89  if (pattern.host.startsWith('*.')) return host.endsWith(pattern.host.slice(1))
90  return pattern.host === host
91}
92
93/** True when `path` is `folder` or lies inside it. */
94export function isUnder(path: string, folder: string): boolean {
95  const base = folder.replace(/\/+$/, '')
96  return path === base || path.startsWith(`${base}/`)
97}
98
99/** `path` made absolute from `base` when relative, with `.`, `..`, and empty segments resolved, as the sandbox resolves it. */
100export function absolutePath(path: string, base: string): string {
101  const parts: string[] = []
102  for (const part of (path.startsWith('/') ? path : `${base}/${path}`).split('/')) {
103    if (part === '..') parts.pop()
104    else if (part !== '' && part !== '.') parts.push(part)
105  }
106  return `/${parts.join('/')}`
107}
108
109/**
110 * The folders of a PATH value as the shell spells them, each made absolute: an empty or relative entry (an empty PATH
111 * too) starts at the working directory. The spelling stays, because the system follows a link before a `..` after it.
112 */
113export function pathFolders(value: string | undefined, cwd: string): string[] {
114  return value === undefined ? [] : value.split(':').map(entry => (entry.startsWith('/') ? entry : `${cwd}/${entry}`))
115}
116
117/** A path that a protected name covers in any folder, in any letter case: many file systems ignore case. */
118export function isProtectedName(path: string): boolean {
119  const parts = path.toLowerCase().split('/')
120  const last = parts.at(-1) ?? ''
121  const follows = (segment: string, names: ReadonlySet<string>) => parts.some((part, index) => part === segment && names.has(parts[index + 1] ?? ''))
122  return follows('.claude', CLAUDE_PROTECTED) || follows('.git', GIT_PROTECTED) || parts.some(part => EDITOR_FOLDERS.has(part)) || last === MCP_FILE || STARTUP_FILES.has(last)
123}
124
125/** A key or certificate file, by its name, in any letter case. */
126export function isKeyFile(path: string): boolean {
127  return KEY_FILE.test(path)
128}
129
130/** A denied path whose name alone rules out Allow for its folder: a protected name or a key file. */
131export function isGuardedPath(path: string): boolean {
132  return isProtectedName(path) || isKeyFile(path)
133}
134
135/** `~/...` for a path under HOME, else the path. */
136export function displayPath(path: string, home: string | undefined): string {
137  return home !== undefined && isUnder(path, home) ? `~${path.slice(home.length)}` : path
138}
139
140function startsWithParts(parts: readonly string[], prefix: readonly string[]): boolean {
141  return prefix.every((part, index) => parts[index] === part)
142}
143
144/** How many leading parts name the macOS per-user temp (T) or cache (C) folder, or null. */
145function sharedFolderLength(parts: readonly string[]): number | null {
146  const root = TEMP_ROOTS.find(prefix => startsWithParts(parts, prefix) && TEMP_MARKERS.has(parts[prefix.length + 2] ?? ''))
147  return root === undefined ? null : root.length + 3
148}
149
150/**
151 * How many leading parts name the cache or temp folder that holds the path, or null. A folder (`isFolder`) can be that
152 * cache or temp folder itself.
153 */
154function cacheLength(parts: readonly string[], home: string | undefined, isFolder: boolean): number | null {
155  // An empty, `.`, or `..` segment makes the text name another folder (`~/.cache/..` is HOME), so no cache holds it.
156  if (parts.slice(1).some(part => part === '' || part === '.' || part === '..')) return null
157  // The parts that a path must have past the cache folder: a file lies in it, a folder can be it.
158  const past = isFolder ? 0 : 1
159  const shared = sharedFolderLength(parts)
160  if (shared !== null) return parts.length >= shared + past ? shared : null
161  const homeParts = home?.split('/')
162  if (homeParts === undefined || !startsWithParts(parts, homeParts)) return null
163  const rest = parts.slice(homeParts.length)
164  // `<root>/<name>/...`: a file directly in a root names no cache.
165  const named = NAMED_CACHE_ROOTS.find(root => startsWithParts(rest, root) && rest.length >= root.length + 1 + past)
166  if (named !== undefined) return homeParts.length + named.length + 1
167  const store = PACKAGE_CACHES.find(cache => startsWithParts(rest, cache) && rest.length >= cache.length + past)
168  return store === undefined ? null : homeParts.length + store.length
169}
170
171/**
172 * The cache or temp folder that holds a denied path, or null when none does. A folder that a command tried to create
173 * (`isFolder`) can be its own cache folder, such as `~/.cache/tool` from `mkdir ~/.cache/tool`.
174 */
175export function cacheFolder(path: string, home: string | undefined, isFolder = false): string | null {
176  const parts = path.split('/')
177  const length = cacheLength(parts, home, isFolder)
178  return length === null ? null : parts.slice(0, length).join('/')
179}
180
181/**
182 * The folder target of a denied path: its cache or temp folder, else the folder that holds it. A folder that a command
183 * tried to create (`isFolder`) is its own target when no cache folder holds it.
184 */
185export function folderTarget(path: string, home: string | undefined, isFolder = false): string {
186  return cacheFolder(path, home, isFolder) ?? (isFolder ? path : path.slice(0, path.lastIndexOf('/')) || '/')
187}
188
189/**
190 * Whether a folder lies strictly inside `tmp`: /tmp as spelled, or where a press found it. It compares spellings, as
191 * cacheLength does, so a spelling with an empty, `.`, or `..` segment names no temp folder. `tmp` holds no temp folder
192 * when it holds HOME or HOME holds it, in any letter case: many file systems ignore case.
193 */
194export function isTempFolder(folder: string, home: string | undefined, tmp = TMP): boolean {
195  if (folder.split('/').slice(1).some(part => part === '' || part === '.' || part === '..')) return false
196  const [foldedHome, foldedTmp] = [home?.toLowerCase(), tmp.toLowerCase()]
197  if (foldedHome !== undefined && (isUnder(foldedHome, foldedTmp) || isUnder(foldedTmp, foldedHome))) return false
198  return folder !== tmp && isUnder(folder, tmp)
199}
200
201/** True for the macOS per-user temp or cache folder, or a folder strictly inside /tmp: every app of the person shares it. */
202export function isSharedFolder(path: string): boolean {
203  const parts = path.split('/')
204  return sharedFolderLength(parts) === parts.length || isTempFolder(path, undefined)
205}
206
207/** The text cut to at most `limit` characters, with `…` when cut, never between the two halves of one character. */
208export function cutText(text: string, limit: number): string {
209  if (text.length <= limit) return text
210  const end = /[\ud800-\udbff]/.test(text.charAt(limit - 2)) ? limit - 2 : limit - 1
211  return `${text.slice(0, end)}…`
212}
213
214/** The text with each character that the engine refuses to show replaced by `�`. */
215export function plainText(text: string): string {
216  return text.replace(UNDRAWABLE, '\ufffd')
217}
218
219/** A command as one line of at most 120 characters. */
220export function commandLine(command: string): string {
221  return cutText(plainText(command.replace(/\s+/g, ' ').trim()), COMMAND_LIMIT)
222}
223
224/**
225 * The program name of a command, for `seenWith`, or '' when none is sure. A quoted or substituted assignment value
226 * can hold spaces, so the word after it may be part of that value, such as a token: no name is taken then.
227 */
228export function programName(command: string): string {
229  const words = command.trim().replace(/^(?:cd\s+\S+\s*&&\s*)+/, '').split(/\s+/)
230  const index = words.findIndex(word => !ASSIGNMENT.test(word))
231  if (index === -1 || !words.slice(0, index).every(word => PLAIN_ASSIGNMENT.test(word))) return ''
232  const [word = ''] = words.slice(index, index + 1)
233  const program = word.slice(word.lastIndexOf('/') + 1)
234  return PROGRAM_NAME.test(program) ? program : ''
235}
236
hooks/records.ts 251 lines
1// Saved records: store keys, the merge of a sighting, counts, shape, retention, and the lineage of a branch.
2
3import type { SandboxTunerApplied, SandboxTunerCounts, SandboxTunerLatest, SandboxTunerLineage, SandboxTunerRecord } from '../types'
4import { isGuardedPath, normalHost } from './names'
5import { isCount, isListOf, isPlainObject, isText } from './shapes'
6import type { Sighting } from './sightings'
7
8// Writers keep independent records.
9export const WRITER_PREFIX = 'writer:'
10export const HIDDEN_PREFIX = 'hidden:'
11export const JOURNAL_PREFIX = 'applied:'
12export const LINEAGE_PREFIX = 'lineage:'
13// One key per session in which Allow and Deny refuse after a sighting that could not be saved. It holds the time of
14// the refusal.
15export const REFUSAL_PREFIX = 'refusal:'
16// The most refusals that the store keeps, the newest (newestRefusals), and the most that a module instance holds of its
17// own. A module instance also holds every refusal that the store keeps.
18export const REFUSAL_LIMIT = 200
19const JOURNAL_LIMIT = 50
20// The most steps that a view follows up from a branch to the sessions that it started from.
21const LINEAGE_LIMIT = 10
22// The most branch records that the store keeps (keptBranches).
23const BRANCH_LIMIT = 200
24
25const RECORD_LIMIT = 300
26const RECORD_AGE_MS = 30 * 24 * 60 * 60 * 1000
27const PORT_LIMIT = 5
28const PROGRAM_LIMIT = 3
29const SESSION_LIMIT = 20
30const COUNTERS = ['blocked', 'refused', 'listed', 'inferred'] as const
31const KINDS: ReadonlySet<unknown> = new Set(['host', 'path'])
32
33export function recordKey(sighting: Pick<Sighting, 'kind' | 'target'>): string {
34  return `${sighting.kind}:${sighting.target}`
35}
36
37function joinNewest<T>(list: readonly T[], item: T, limit: number): T[] {
38  return [...list.filter(value => value !== item), item].slice(-limit)
39}
40
41/** Distinct values, the newer record's last so that the cut keeps them: a value in both takes its newer place. */
42function mergeNewest<T>(older: readonly T[], newer: readonly T[], limit: number): T[] {
43  const joined = [...older, ...newer]
44  return joined.filter((value, index) => joined.lastIndexOf(value) === index).slice(-limit)
45}
46
47export function mergeSighting(record: SandboxTunerRecord | undefined, sighting: Sighting, sessionId: string | null, now: number): SandboxTunerRecord {
48  const base: SandboxTunerRecord = record ?? {
49    key: recordKey(sighting),
50    kind: sighting.kind,
51    target: sighting.target,
52    counts: { blocked: 0, refused: 0, listed: 0, inferred: 0 },
53    ports: [],
54    sample: '',
55    seenWith: [],
56    sessions: [],
57    firstSeen: now,
58    lastSeen: now,
59    isHidden: false,
60  }
61  return {
62    ...base,
63    counts: {
64      ...base.counts,
65      [sighting.counter]: base.counts[sighting.counter] + 1,
66      refused: base.counts.refused + (sighting.reason === 'refused' ? 1 : 0),
67    },
68    ports: sighting.ports.reduce((list, port) => joinNewest(list, port, PORT_LIMIT), base.ports),
69    seenWith: sighting.program === '' ? base.seenWith : joinNewest(base.seenWith, sighting.program, PROGRAM_LIMIT),
70    sessions: sessionId === null ? base.sessions : joinNewest(base.sessions, sessionId, SESSION_LIMIT),
71    // A folder keeps a protected or key file as its sample, so a later write beside it cannot bring Allow back.
72    sample: base.kind === 'path' && isGuardedPath(base.sample) && !isGuardedPath(sighting.detail) ? base.sample : sighting.detail,
73    lastSeen: now,
74  }
75}
76
77export function sightingTotal(counts: SandboxTunerCounts): number {
78  return counts.blocked + counts.listed + counts.inferred
79}
80
81export function allowCount(counts: SandboxTunerCounts): number {
82  return sightingTotal(counts) - counts.refused
83}
84
85export function isRecord(value: unknown): value is SandboxTunerRecord {
86  if (!isPlainObject(value) || !isPlainObject(value.counts)) return false
87  const counts = value.counts
88  return (
89    KINDS.has(value.kind) &&
90    isText(value.target) &&
91    value.key === `${String(value.kind)}:${value.target}` &&
92    COUNTERS.every(name => isCount(counts[name])) &&
93    isListOf(value.ports, isCount) &&
94    isText(value.sample) &&
95    isListOf(value.seenWith, isText) &&
96    isListOf(value.sessions, isText) &&
97    isCount(value.firstSeen) &&
98    isCount(value.lastSeen) &&
99    typeof value.isHidden === 'boolean'
100  )
101}
102
103/** The record keys omitted from the display after 30 days or beyond the 300 newest targets. */
104export function staleKeys(records: readonly SandboxTunerRecord[], now: number): string[] {
105  const fresh = records.filter(record => now - record.lastSeen <= RECORD_AGE_MS)
106  const kept = new Set([...fresh].sort((a, b) => b.lastSeen - a.lastSeen).slice(0, RECORD_LIMIT).map(record => record.key))
107  return records.filter(record => !kept.has(record.key)).map(record => record.key)
108}
109
110/** The records that the display shows at `now`: each seen within 30 days, at most the 300 newest. */
111export function shownRecords(records: readonly SandboxTunerRecord[], now: number): SandboxTunerRecord[] {
112  const stale = new Set(staleKeys(records, now))
113  return records.filter(record => !stale.has(record.key))
114}
115
116/**
117 * A session that a view shows with scope session, and up to when: the current session with no end (`until` Infinity)
118 * and each target that a record names it in (`keys` null), then each session that it branched from, up to the time of
119 * that branch, with the targets that the branch record holds (lineageStep).
120 */
121export type Lineage = { session: string; until: number; keys: ReadonlySet<string> | null }
122
123/** Whether a value is the record of the /branch that started `session` (LINEAGE_PREFIX). */
124export function isLineage(value: unknown, session: string): value is SandboxTunerLineage {
125  return isPlainObject(value) && value.session === session && isText(value.parent) && isCount(value.at) && isListOf(value.keys, isText)
126}
127
128/**
129 * The next step of a lineage up: the session that the branch of the last session started from, with the targets that
130 * it saw by that branch, up to the time of that branch or of any branch below it, whichever is first. Null after 10
131 * steps, and when the step leads to a session of the lineage again.
132 */
133export function lineageStep(lineage: readonly Lineage[], branch: SandboxTunerLineage): Lineage | null {
134  const last = lineage[lineage.length - 1]
135  if (last === undefined || lineage.length > LINEAGE_LIMIT || lineage.some(item => item.session === branch.parent)) return null
136  return { session: branch.parent, until: Math.min(last.until, branch.at), keys: new Set(branch.keys) }
137}
138
139/**
140 * The targets that a record of `session` names by `at`, the time of a /branch from that session, each once and sorted:
141 * what the branch record of that /branch keeps, so that a target record holds no time for each session. A record first
142 * seen after `at` saw `session` after it too. A record that names other sessions keeps no time of `session`, so it
143 * counts when it was first seen by `at`.
144 */
145export function keysSeenBy(records: readonly SandboxTunerRecord[], session: string, at: number): string[] {
146  return [...new Set(records.filter(record => record.sessions.includes(session) && record.firstSeen <= at).map(record => record.key))].sort()
147}
148
149/**
150 * The sessions whose branch records the store keeps after the /branch that started `current`: every one while there
151 * are 200 or fewer. Past 200, the oldest go first, but never the record of `current` or of a branch that a target record
152 * or an Undo journal entry names (`named`), nor the 9 records above each of those, which its view walks (lineageStep).
153 * So more than 200 stay when those alone pass 200.
154 */
155export function keptBranches(branches: readonly SandboxTunerLineage[], named: ReadonlySet<string>, current: string): Set<string> {
156  const kept = new Set(branches.map(branch => branch.session))
157  if (kept.size <= BRANCH_LIMIT) return kept
158  const bySession = new Map(branches.map(branch => [branch.session, branch]))
159  const needed = new Set<string>()
160  // Each walk takes all its steps: another walk can reach a record with fewer steps left.
161  const keep = (session: string) => {
162    let next = bySession.get(session)
163    for (let step = 0; next !== undefined && step < LINEAGE_LIMIT; step += 1, next = bySession.get(next.parent)) needed.add(next.session)
164  }
165  keep(current)
166  for (const branch of branches) if (named.has(branch.session)) keep(branch.session)
167  const oldest = branches.filter(branch => !needed.has(branch.session))
168    .sort((a, b) => a.at - b.at || (a.session < b.session ? -1 : a.session > b.session ? 1 : 0))
169  for (const branch of oldest.slice(0, kept.size - BRANCH_LIMIT)) kept.delete(branch.session)
170  return kept
171}
172
173/**
174 * The sessions of the saved refusals (`saved`: each session and the time that its REFUSAL_PREFIX key holds), the newest
175 * first. A time that is not valid counts as the oldest. Equal times go by session id, as in keptBranches.
176 */
177export function newestRefusals(saved: ReadonlyMap<string, unknown>): string[] {
178  const timeOf = (value: unknown) => (isCount(value) ? value : -1)
179  return [...saved].map(([session, at]) => ({ session, at: timeOf(at) }))
180    .sort((a, b) => b.at - a.at || (a.session < b.session ? 1 : a.session > b.session ? -1 : 0))
181    .map(item => item.session)
182}
183
184/** Whether a session of the lineage saw a target: by a record that names it, or by the branch record of the step. */
185function isSeenBy(record: SandboxTunerRecord, { session, keys }: Lineage): boolean {
186  return keys === null ? record.sessions.includes(session) : keys.has(record.key)
187}
188
189/** Every writer's record of each target that a session of the lineage saw by its time: so the counts keep every session. */
190export function seenIn(records: readonly SandboxTunerRecord[], lineage: readonly Lineage[]): SandboxTunerRecord[] {
191  const keys = new Set(records.filter(record => lineage.some(item => isSeenBy(record, item))).map(record => record.key))
192  return records.filter(record => keys.has(record.key))
193}
194
195/** The journal entries that a press of a session of the lineage saved by its time. An entry of Sandbox Tuner 1.1.3 names no session. */
196export function appliedIn(journal: readonly SandboxTunerApplied[], lineage: readonly Lineage[]): SandboxTunerApplied[] {
197  return journal.filter(entry => lineage.some(item => entry.session === item.session && entry.appliedAt <= item.until))
198}
199
200/** The 50 newest history entries plus every unresolved edit, oldest first. */
201export function journalOf(entries: readonly SandboxTunerApplied[]): SandboxTunerApplied[] {
202  const sorted = [...entries].sort((a, b) => a.appliedAt - b.appliedAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
203  const unresolved = (entry: SandboxTunerApplied) => entry.applyState === 'pending' || isUndoUnresolved(entry)
204  const history = sorted.filter(entry => !unresolved(entry)).slice(-JOURNAL_LIMIT)
205  return sorted.filter(entry => unresolved(entry) || history.includes(entry))
206}
207
208/** An unconfirmed removal retains its retry action. */
209export function isUndoUnresolved(entry: SandboxTunerApplied): boolean {
210  return entry.undoState === 'pending' || entry.undoState === 'retry'
211}
212
213export function hasLaterOwner(journal: readonly SandboxTunerApplied[], entry: SandboxTunerApplied): boolean {
214  return journal.some(item => item.id !== entry.id && item.file === entry.file && item.settingsKey === entry.settingsKey &&
215    (entry.settingsKey === 'sandbox.filesystem.allowWrite' ? item.entry === entry.entry : normalHost(item.entry) === normalHost(entry.entry)) &&
216    item.appliedAt >= entry.appliedAt)
217}
218
219export function isPressedAgain(journal: readonly SandboxTunerApplied[], written: SandboxTunerApplied): boolean {
220  return hasLaterOwner(journal, written) || journal.some(item => item.id === written.id && item.undoneAt !== written.undoneAt)
221}
222
223/** True when a press changed settings for the target of the latest block at or after that block. */
224export function isFixedSince(journal: readonly SandboxTunerApplied[], latest: SandboxTunerLatest): boolean {
225  return journal.some(entry => entry.applyState !== 'pending' && entry.recordKey === latest.recordKey && entry.appliedAt >= latest.at)
226}
227
228/** Combine independent writers without losing a protected sample or inferred evidence. */
229export function aggregateRecords(records: readonly SandboxTunerRecord[]): SandboxTunerRecord[] {
230  const result = new Map<string, SandboxTunerRecord>()
231  for (const record of [...records].sort((a, b) => a.lastSeen - b.lastSeen)) {
232    const previous = result.get(record.key)
233    if (previous === undefined) { result.set(record.key, record); continue }
234    result.set(record.key, {
235      ...record,
236      counts: {
237        blocked: previous.counts.blocked + record.counts.blocked,
238        refused: previous.counts.refused + record.counts.refused,
239        listed: previous.counts.listed + record.counts.listed,
240        inferred: previous.counts.inferred + record.counts.inferred,
241      },
242      sample: isGuardedPath(previous.sample) ? previous.sample : record.sample,
243      ports: mergeNewest(previous.ports, record.ports, PORT_LIMIT),
244      seenWith: mergeNewest(previous.seenWith, record.seenWith, PROGRAM_LIMIT),
245      sessions: mergeNewest(previous.sessions, record.sessions, SESSION_LIMIT),
246      firstSeen: Math.min(previous.firstSeen, record.firstSeen),
247    })
248  }
249  return [...result.values()]
250}
251
hooks/settings-file.ts 194 lines
1// Parses, edits, and serializes the user settings file, formats and parses the record of its lock file, and checks the
2// shape of a journal entry.
3
4import type { SandboxTunerApplied, SandboxTunerSettingsKey } from '../types'
5import { causeOf } from './diagnostics'
6import { displayPath, normalHost, plainText } from './names'
7import { isCount, isListOf, isPlainObject, isText } from './shapes'
8
9export type FileInfo = { path: string; display: string; backup: string; backupDisplay: string; lock: string; lockDisplay: string }
10export type ParsedSettings = { value: Record<string, unknown>; bom: string; trailingNewline: boolean; isCanonical: boolean }
11export type Refusal =
12  | { refusal: 'invalid-json'; message: string }
13  | { refusal: 'wrong-type'; path: string; found: string; expected: string }
14type AddResult = { value: Record<string, unknown>; created: string[] } | { isPresent: true } | Refusal
15type RemoveResult = { value: Record<string, unknown> } | { isAbsent: true } | Refusal
16type KeyPath = { parents: readonly string[]; leaf: string }
17type Link = { holder: Record<string, unknown>; name: string; dotted: string }
18type Walked = { node: Record<string, unknown>; links: Link[]; created: string[] }
19
20const BOM = '\ufeff'
21const KEY_PATHS: Readonly<Record<SandboxTunerSettingsKey, KeyPath>> = {
22  'sandbox.network.allowedDomains': { parents: ['sandbox', 'network'], leaf: 'allowedDomains' },
23  'sandbox.network.deniedDomains': { parents: ['sandbox', 'network'], leaf: 'deniedDomains' },
24  'sandbox.filesystem.allowWrite': { parents: ['sandbox', 'filesystem'], leaf: 'allowWrite' },
25}
26const HOST_KEYS: ReadonlySet<SandboxTunerSettingsKey> = new Set(['sandbox.network.allowedDomains', 'sandbox.network.deniedDomains'])
27
28/**
29 * The paths of a settings file, its backup, and its lock file, each with the text that shows it: CLAUDE_CONFIG_DIR can
30 * hold any character.
31 */
32export function fileInfo(path: string, home: string | undefined): FileInfo {
33  const backup = `${path.slice(0, path.lastIndexOf('/'))}/backups/settings.json.sandbox-tuner.bak`
34  const lock = `${path}.sandbox-tuner.lock`
35  return { path, display: plainText(displayPath(path, home)), backup, backupDisplay: plainText(displayPath(backup, home)), lock, lockDisplay: plainText(displayPath(lock, home)) }
36}
37
38/** Who holds the lock of a settings file: the token of one press, and when it took the lock. */
39export type LockRecord = { holder: string; since: number }
40
41/** The text of a lock file: held by the press `holder` since `since`, or free since `since` when `holder` is null. */
42export function lockText(holder: string | null, since: number): string {
43  return `${JSON.stringify({ holder, since })}\n`
44}
45
46/**
47 * What a lock file holds: its holder, `free` when the file is missing or free, or null when its text is no lock record,
48 * such as an empty file that a write has not finished.
49 */
50export function readLock(text: string | null): LockRecord | 'free' | null {
51  if (text === null) return 'free'
52  let value: unknown
53  try {
54    value = JSON.parse(text)
55  } catch {
56    return null
57  }
58  if (!isPlainObject(value) || !isCount(value.since)) return null
59  if (value.holder === null) return 'free'
60  return isText(value.holder) && value.holder !== '' ? { holder: value.holder, since: value.since } : null
61}
62
63function typeName(value: unknown): string {
64  if (value === null) return 'null'
65  if (Array.isArray(value)) return 'an array'
66  return typeof value === 'object' ? 'an object' : `a ${typeof value}`
67}
68
69function wrongType(path: string, value: unknown, expected: string): Refusal {
70  return { refusal: 'wrong-type', path, found: typeName(value), expected }
71}
72
73/**
74 * The JSON parser's reason without the text of the file, because settings can hold secrets in `env` and the
75 * reason goes to the debug log. The parsers quote the file near the fault: V8 quotes the token and an excerpt,
76 * JavaScriptCore quotes the identifier. So all from the first quote to the last one becomes `…`. JavaScriptCore
77 * also names a bad escape character without quotes, so that character goes too.
78 */
79export function parserReason(message: string): string {
80  return message
81    .replace(/["'][\s\S]*["'](?:\.\.\.)?/, '…')
82    .replace(/(escape character) \S+/, '$1')
83    .replace(/\s+/g, ' ')
84    .trim()
85}
86
87export function parseSettings(text: string): ParsedSettings | Refusal {
88  const bom = text.startsWith(BOM) ? BOM : ''
89  const body = text.slice(bom.length)
90  const isBlank = body.trim() === ''
91  let value: unknown
92  try {
93    value = isBlank ? {} : JSON.parse(body)
94  } catch (error) {
95    return { refusal: 'invalid-json', message: parserReason(causeOf(error)) }
96  }
97  if (!isPlainObject(value)) return wrongType('the top level', value, 'an object')
98  const canonical = JSON.stringify(value, null, 2)
99  return { value, bom, trailingNewline: isBlank || body.endsWith('\n'), isCanonical: body === canonical || body === `${canonical}\n` }
100}
101
102function cloneSettings(root: Record<string, unknown>): Record<string, unknown> {
103  return JSON.parse(JSON.stringify(root)) as Record<string, unknown>
104}
105
106function walk(root: Record<string, unknown>, parents: readonly string[], isCreating: true): Walked | Refusal
107function walk(root: Record<string, unknown>, parents: readonly string[], isCreating: false): Walked | Refusal | 'missing'
108function walk(root: Record<string, unknown>, parents: readonly string[], isCreating: boolean): Walked | Refusal | 'missing' {
109  const walked: Walked = { node: root, links: [], created: [] }
110  for (const name of parents) {
111    const dotted = [...walked.links.map(link => link.name), name].join('.')
112    const child = walked.node[name]
113    if (child === undefined && !isCreating) return 'missing'
114    if (child !== undefined && !isPlainObject(child)) return wrongType(dotted, child, 'an object')
115    if (child === undefined) {
116      walked.node[name] = {}
117      walked.created.push(dotted)
118    }
119    walked.links.push({ holder: walked.node, name, dotted })
120    walked.node = walked.node[name] as Record<string, unknown>
121  }
122  return walked
123}
124
125function listAt(node: Record<string, unknown>, leaf: string, key: SandboxTunerSettingsKey): string[] | undefined | Refusal {
126  const list = node[leaf]
127  return list === undefined || isListOf(list, isText) ? list : wrongType(key, list, 'an array of strings')
128}
129
130function sameEntry(key: SandboxTunerSettingsKey, left: string, right: string): boolean {
131  return HOST_KEYS.has(key) ? normalHost(left) === normalHost(right) : left === right
132}
133
134export function addEntry(root: Record<string, unknown>, key: SandboxTunerSettingsKey, entry: string): AddResult {
135  const copy = cloneSettings(root)
136  const { parents, leaf } = KEY_PATHS[key]
137  const walked = walk(copy, parents, true)
138  if ('refusal' in walked) return walked
139  const list = listAt(walked.node, leaf, key)
140  if (list === undefined) {
141    walked.node[leaf] = [entry]
142    return { value: copy, created: [...walked.created, key] }
143  }
144  if ('refusal' in list) return list
145  if (list.some(item => sameEntry(key, item, entry))) return { isPresent: true }
146  list.push(entry)
147  return { value: copy, created: walked.created }
148}
149
150export function removeEntry(root: Record<string, unknown>, key: SandboxTunerSettingsKey, entry: string, created: readonly string[]): RemoveResult {
151  const copy = cloneSettings(root)
152  const { parents, leaf } = KEY_PATHS[key]
153  const walked = walk(copy, parents, false)
154  if (walked === 'missing') return { isAbsent: true }
155  if ('refusal' in walked) return walked
156  const list = listAt(walked.node, leaf, key)
157  if (list === undefined) return { isAbsent: true }
158  if ('refusal' in list) return list
159  const index = list.findIndex(item => sameEntry(key, item, entry))
160  if (index === -1) return { isAbsent: true }
161  list.splice(index, 1)
162  for (const link of [...walked.links, { holder: walked.node, name: leaf, dotted: key }].reverse()) {
163    const value = link.holder[link.name]
164    const isEmpty = (Array.isArray(value) && value.length === 0) || (isPlainObject(value) && Object.keys(value).length === 0)
165    if (isEmpty && created.includes(link.dotted)) delete link.holder[link.name]
166  }
167  return { value: copy }
168}
169
170export function serializeSettings(value: Record<string, unknown>, format: Pick<ParsedSettings, 'bom' | 'trailingNewline'>): string {
171  return `${format.bom}${JSON.stringify(value, null, 2)}${format.trailingNewline ? '\n' : ''}`
172}
173
174/** The shape of one journal entry. */
175export function isApplied(value: unknown): value is SandboxTunerApplied {
176  return (
177    isPlainObject(value) &&
178    isText(value.id) &&
179    isText(value.recordKey) &&
180    (value.action === 'allow' || value.action === 'deny') &&
181    isText(value.settingsKey) &&
182    Object.hasOwn(KEY_PATHS, value.settingsKey) &&
183    isText(value.entry) &&
184    isText(value.file) &&
185    (value.backup === null || isText(value.backup)) &&
186    isListOf(value.created, isText) &&
187    isCount(value.appliedAt) &&
188    (value.undoneAt === null || isCount(value.undoneAt)) &&
189    (value.applyState === undefined || (value.applyState === 'pending' && value.undoneAt === null)) &&
190    (value.undoState === undefined || (value.undoneAt !== null && ['pending', 'retry', 'superseded'].includes(String(value.undoState)))) &&
191    (value.session === undefined || isText(value.session))
192  )
193}
194
hooks/sightings.ts 241 lines
1// Reads one Bash call into sightings.
2
3import type { SandboxTunerKind, SandboxTunerLatest } from '../types'
4import { absolutePath, cacheFolder, folderTarget, isGuardedPath, plainText, programName, splitHost } from './names'
5import { recordKey } from './records'
6
7type Counter = 'blocked' | 'listed' | 'inferred'
8type BlockReason = SandboxTunerLatest['reason']
9export type Sighting = {
10  kind: SandboxTunerKind
11  target: string
12  counter: Counter
13  reason: BlockReason | null
14  reasonText: string
15  ports: readonly number[]
16  detail: string
17  program: string
18}
19type Gate = 'sandbox-on' | 'sandbox-required'
20export type GatedSighting = { gate: Gate; sighting: Sighting }
21type CallSightings = { reports: Sighting[]; gated: GatedSighting[]; unknownLine: string | null; observation?: { operation: string; detail: string }; skipped?: true }
22export type SandboxFacts = { isEnabled: boolean; allowsUnsandboxed: boolean }
23export type BashCall = { command: string; isBackground: boolean; isUnsandboxed: boolean; allowedDomains: readonly string[] }
24export type BashOutcome = { backgroundTaskId?: string; isDenied: boolean; isError: boolean; isReadOnly?: boolean; isUnsandboxed?: boolean; text: string; stderr: string }
25
26const SCAN_LIMIT = 200_000
27// No host, path, or reason that the sandbox reports is longer than the longest path a file system takes, or holds a
28// character that the engine refuses to draw. Such a one is noise, such as output that imitates a report.
29const SIGHTING_TEXT_LIMIT = 4096
30const PATH_LIMIT = 3
31const UNKNOWN_LIMIT = 80
32const OPEN_TAG = '<sandbox_violations>'
33const CLOSE_TAG = '</sandbox_violations>'
34// Claude Code 2.1.296 ends the text of a failed call with its report, each tag on a line of its own. Only its proxy
35// note can follow the report.
36const REPORT_OPEN = `\n${OPEN_TAG}\n`
37const REPORT_CLOSE = `\n${CLOSE_TAG}`
38const PROXY_NOTE = '\n\n[agent-proxy] While this command ran, '
39const NETWORK = /^deny network-outbound (\S+) \((.*)\)$/
40const MAC_LINE = /^\S+\(\d+\) deny\(\d+\) \S/
41const MAC_FILE = /^\S+\(\d+\) deny\(\d+\) file-/
42const MAC_WRITE = /^\S+\(\d+\) deny\(\d+\) file-write-[a-z-]+\s+(\/.*)$/
43const LINUX_WRITE = /^deny [a-z0-9_]+ (\/.*)$/
44// The start of every report line: `deny ` for a network line and on Linux, `<program>(<pid>) ` on macOS.
45const REPORT_START = /^(?:deny |\S+\(\d+\) )/
46const EXIT_CODE = /^Exit code \d+/
47const PERMISSION_ERROR = /operation not permitted|read-only file system/i
48// An error of mkdir, BSD or GNU: the path that it names is the folder that it tried to create.
49const MKDIR_ERROR = /^mkdir: /
50const SOCKET_WORDS = /\b(?:listen|connect|socket)\b/i
51const PATH_START = /(?:^|[\s'"‘`(])\/(?!\/)/g
52const PATH_CANDIDATE = /(?:^|[\s'"‘`(])(\/(?!\/)[^\s'"’`:,)]+)(?=[:'"’`,)]|$)/g
53const DEVICE_PATH = /^\/(?:dev|proc|sys)\//
54
55function fits(sighting: Sighting): boolean {
56  const text = `${sighting.detail}${sighting.reasonText}`
57  return text.length <= SIGHTING_TEXT_LIMIT && plainText(text) === text
58}
59
60function distinct<T>(items: readonly T[], keyOf: (item: T) => string): T[] {
61  const seen = new Set<string>()
62  return items.filter(item => {
63    const key = keyOf(item)
64    const isNew = !seen.has(key)
65    seen.add(key)
66    return isNew
67  })
68}
69
70/** A line that must speak for its target: a refusal keeps Deny, and a protected or key file keeps Allow away. */
71function isWeighty(sighting: Sighting): boolean {
72  return sighting.reason === 'refused' || (sighting.kind === 'path' && isGuardedPath(sighting.detail))
73}
74
75/**
76 * One sighting per target and counter, however many lines of the call name the target. It keeps the ports of
77 * every line, and it leads with the first weighty line, so the order of the lines does not change the verdict.
78 */
79function combine(sightings: readonly Sighting[]): Sighting[] {
80  const byKey = new Map<string, Sighting>()
81  for (const sighting of sightings) {
82    const key = `${recordKey(sighting)}:${sighting.counter}`
83    const held = byKey.get(key)
84    const lead = held === undefined || (!isWeighty(held) && isWeighty(sighting)) ? sighting : held
85    byKey.set(key, { ...lead, ports: distinct([...(held?.ports ?? []), ...sighting.ports], String) })
86  }
87  return [...byKey.values()]
88}
89
90function capPaths(sightings: readonly Sighting[]): Sighting[] {
91  const unique = combine(sightings)
92  const paths = unique.filter(sighting => sighting.kind === 'path').slice(0, PATH_LIMIT)
93  return unique.filter(sighting => sighting.kind !== 'path' || paths.includes(sighting))
94}
95
96function hostDetail(host: string, port: number | null): string {
97  return port === null ? host : `${host}:${port}`
98}
99
100function hostSighting(text: string, counter: 'blocked' | 'listed', reason: BlockReason | null, reasonText: string, program: string): Sighting {
101  const { host, port } = splitHost(text)
102  return { kind: 'host', target: host, counter, reason, reasonText, ports: port === null ? [] : [port], detail: hostDetail(host, port), program }
103}
104
105/** A write-folder sighting. Its target is the folder that `folderTarget` names, of a folder path when `isFolder`. */
106function pathSighting(path: string, counter: 'blocked' | 'inferred', home: string | undefined, program: string, isFolder = false): Sighting {
107  const reason: BlockReason = counter === 'blocked' ? 'write' : 'inferred'
108  return { kind: 'path', target: folderTarget(path, home, isFolder), counter, reason, reasonText: '', ports: [], detail: path, program }
109}
110
111/**
112 * A write-folder sighting guessed from error text. Its path names a folder when mkdir tried to create it, and when it
113 * names a cache folder itself, such as `~/.cache/tool`: so the target is never a whole cache root.
114 */
115function guessedSighting(path: string, line: string, home: string | undefined, program: string): Sighting {
116  return pathSighting(path, 'inferred', home, program, MKDIR_ERROR.test(line) || cacheFolder(path, home, true) === path)
117}
118
119function reportLines(sources: readonly string[]): string[] {
120  const lines = sources.flatMap(source => source.split(OPEN_TAG).slice(1).flatMap(part => part.split(CLOSE_TAG, 1).join('').split('\n')))
121  return distinct(lines.map(line => line.trim()).filter(line => line !== ''), line => line)
122}
123
124/**
125 * The report at the end of the text of a failed call: its last block, when only space or Claude Code's proxy note
126 * follows it. The command's output comes before the report, so a block there is output, and the call skips it.
127 */
128function tailReport(text: string): { lines: string[]; skipped: boolean } {
129  const open = text.lastIndexOf(REPORT_OPEN)
130  const close = open < 0 ? -1 : text.indexOf(REPORT_CLOSE, open + REPORT_OPEN.length - 1)
131  const rest = text.slice(close + REPORT_CLOSE.length)
132  const isTail = close >= 0 && (rest.trim() === '' || rest.startsWith(PROXY_NOTE))
133  const lines = isTail ? reportLines([text.slice(open, close + REPORT_CLOSE.length)]) : []
134  return { lines, skipped: (isTail ? text.slice(0, open) : text).includes(OPEN_TAG) }
135}
136
137/**
138 * The start of a report line of an unknown form, to name in a diagnostic, or null when the line does not start like a
139 * report line: output can imitate a report, so such a line can be any text, even a secret.
140 */
141export function reportQuote(line: string): string | null {
142  return REPORT_START.test(line) ? line.slice(0, UNKNOWN_LIMIT) : null
143}
144
145function reportSighting(line: string, home: string | undefined, program: string): Sighting | null {
146  const network = NETWORK.exec(line)
147  if (network !== null) {
148    const [, reported = '', reasonText = ''] = network
149    const reason: BlockReason = /user denied/i.test(reasonText) ? 'refused' : reasonText.includes('allowed_domains') ? 'unlisted' : 'other'
150    return hostSighting(reported, 'blocked', reason, reasonText, program)
151  }
152  const [, path] = MAC_WRITE.exec(line) ?? LINUX_WRITE.exec(line) ?? []
153  return path === undefined ? null : pathSighting(path, 'blocked', home, program)
154}
155
156/** A report line about a file of any operation: the report then speaks for the call's file blocks. */
157function isFileLine(line: string): boolean {
158  return MAC_FILE.test(line) || LINUX_WRITE.test(line)
159}
160
161/** A report line of a form Sandbox Tuner knows: one it counts, or one it knows and ignores (a read, a lookup, a socket). */
162function isKnownLine(line: string): boolean {
163  return NETWORK.test(line) || MAC_LINE.test(line) || LINUX_WRITE.test(line)
164}
165
166/**
167 * The path of a permission error: the last path on the line. When a later path does not parse (it holds a space),
168 * that one may be the path that was blocked, so the line names none rather than an earlier path in its place.
169 */
170function inferredPath(line: string, cwd: string | undefined): string | null {
171  if (!PERMISSION_ERROR.test(line) || SOCKET_WORDS.test(line)) return null
172  const last = Array.from(line.matchAll(PATH_CANDIDATE)).at(-1)
173  if (last === undefined && cwd !== undefined) {
174    const relative = /(?:^|: )['"]?((?:\.\.?\/)?[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)+)['"]?: (?:Operation not permitted|Read-only file system)$/i.exec(line)?.[1]
175    return relative === undefined ? null : absolutePath(relative, cwd)
176  }
177  if (last === undefined || last.index !== Array.from(line.matchAll(PATH_START)).at(-1)?.index) return null
178  const [, candidate = ''] = last
179  const path = candidate.replace(/\.$/, '')
180  return DEVICE_PATH.test(path) ? null : path
181}
182
183/** The host and write-folder sightings of one Bash call. */
184export function readCall(call: BashCall, outcome: BashOutcome, home: string | undefined, cwd?: string): CallSightings {
185  if (outcome.isDenied || (call.isBackground && !outcome.backgroundTaskId)) return { reports: [], gated: [], unknownLine: null }
186  const ran = !outcome.isError || EXIT_CODE.test(outcome.text)
187  const sources = [outcome.text, outcome.stderr].map(source => source.slice(-SCAN_LIMIT))
188  const program = programName(call.command)
189  // Claude Code writes the report of a call that succeeded to its error output, apart from the command's output in the
190  // text. A failed call has one text: the command's output, then the report, then any proxy note. So only the block at
191  // the end of that text counts, and the command can print one there: it is gated below.
192  const tail = outcome.isError ? tailReport(outcome.text.slice(-SCAN_LIMIT)) : { lines: reportLines([outcome.stderr.slice(-SCAN_LIMIT)]), skipped: false }
193  const { lines } = tail
194  const reports = capPaths(lines.flatMap(line => reportSighting(line, home, program) ?? []))
195  const listed = ran
196    ? combine(call.allowedDomains.filter(entry => !entry.includes('*')).map(entry => hostSighting(entry.trim(), 'listed', null, '', program)))
197    : []
198  if (outcome.backgroundTaskId !== undefined) {
199    return { reports: [], gated: outcome.isError ? [] : listed.filter(fits).map(sighting => ({ gate: 'sandbox-on', sighting })), unknownLine: null }
200  }
201  const isUnsandboxed = outcome.isUnsandboxed ?? call.isUnsandboxed
202  // Without a reported override, strict sandbox mode can have ignored the requested override.
203  const canInfer = ran && !outcome.isReadOnly && outcome.isUnsandboxed !== true && !lines.some(isFileLine)
204  const inferred = canInfer
205    ? capPaths(sources.flatMap(source => source.split('\n')).flatMap(line => {
206        const path = inferredPath(line, cwd)
207        return path === null ? [] : [guessedSighting(path, line, home, program)]
208      }))
209    : []
210  // The command of a failed call can print a block at the end of its text: it counts only while the sandbox ran the call.
211  const reportGate: Gate = isUnsandboxed ? 'sandbox-required' : 'sandbox-on'
212  return {
213    reports: outcome.isError ? [] : reports.filter(fits),
214    gated: [
215      ...(outcome.isError ? reports : []).map((sighting): GatedSighting => ({ gate: reportGate, sighting })),
216      ...listed.map((sighting): GatedSighting => ({ gate: 'sandbox-on', sighting })),
217      ...inferred.map((sighting): GatedSighting => ({ gate: isUnsandboxed ? 'sandbox-required' : 'sandbox-on', sighting })),
218    ].filter(({ sighting }) => fits(sighting)),
219    observation: lines.flatMap(line => {
220      if (reportSighting(line, home, program) !== null) return []
221      const operation = /^\S+\(\d+\) deny\(\d+\) (\S+)/.exec(line)?.[1] ?? 'unknown'
222      return [{ operation, detail: plainText(line.slice(0, UNKNOWN_LIMIT)) }]
223    }).at(-1),
224    unknownLine: lines.find(line => !isKnownLine(line)) ?? null,
225    skipped: tail.skipped || undefined,
226  }
227}
228
229export function keepGated(gated: readonly GatedSighting[], facts: SandboxFacts): Sighting[] {
230  return gated
231    .filter(({ gate }) => facts.isEnabled && (gate === 'sandbox-on' || !facts.allowsUnsandboxed))
232    .map(({ sighting }) => sighting)
233}
234
235export function latestOf(sightings: readonly Sighting[], command: string, now: number): SandboxTunerLatest | null {
236  const block = [...sightings].reverse().find((sighting): sighting is Sighting & { reason: BlockReason } => sighting.reason !== null)
237  return block === undefined
238    ? null
239    : { recordKey: recordKey(block), detail: block.detail, reason: block.reason, reasonText: block.reasonText, command, at: now }
240}
241
hooks/verdicts.ts 440 lines
1// Verdicts: what each record means against the current settings.
2
3import type { Settings } from 'claude-code'
4
5import type { SandboxTunerAction, SandboxTunerRecord, SandboxTunerSettingsKey } from '../types'
6import { CLAUDE_PROTECTED, PROTECTED_PLACES, absolutePath, cacheFolder, displayPath, folderTarget, hostMatches, isDnsName, isKeyFile, isProtectedName, isTempFolder, isUnder } from './names'
7import { allowCount, sightingTotal } from './records'
8import type { FileInfo } from './settings-file'
9import { isPlainObject, isText } from './shapes'
10import type { SandboxFacts } from './sightings'
11
12export type SourceName = 'user' | 'project' | 'local' | 'flag' | 'policy'
13export type Sources = Readonly<Record<SourceName, Settings>>
14export type Context = {
15  sources: Sources
16  home: string | undefined
17  configDir: string | undefined
18  // Where the protected places and the credentials folders lie: as spelled, or where a press found them.
19  protectedDirs: readonly string[]
20  credentialDirs: readonly string[]
21  pathDirs: readonly string[]
22  // Where /tmp lies: as spelled, or where a press found it. Null at the press of a folder outside /tmp, which keeps the
23  // rule of Sandbox Tuner 1.1.1.
24  tmp: string | null
25  cwd: string
26  root: string
27  threshold: number
28  file: FileInfo | undefined
29  isCanonical: boolean
30}
31export type Change = { action: SandboxTunerAction; settingsKey: SandboxTunerSettingsKey; entry: string; file: FileInfo }
32export type NoFixReason =
33  | 'not-dns' | 'denied-by-settings' | 'managed-lock' | 'protected' | 'credentials' | 'system' | 'too-broad'
34  | 'glob' | 'on-path' | 'inside-workspace' | 'deny-rule' | 'write-pattern' | 'read-rule' | 'read-pattern' | 'not-a-cache' | 'no-settings-file'
35export type Verdict =
36  | { status: 'ready'; allow: Change; deny: Change | null }
37  | { status: 'waiting'; deny: Change | null }
38  | { status: 'covered'; source: SourceName | 'combined' }
39  | { status: 'no-fix'; reason: NoFixReason; detail: string }
40export type Rated = { record: SandboxTunerRecord; verdict: Verdict }
41
42type Entry = { text: string; path: string }
43type DenialEntry = Entry & { reason: 'read-rule' | 'deny-rule' | 'read-pattern' | 'write-pattern' }
44
45const SOURCE_NAMES: readonly SourceName[] = ['user', 'project', 'local', 'flag', 'policy']
46// The sources a repository cannot write: user settings, --settings, and managed settings.
47const TRUSTED_SOURCES: readonly SourceName[] = ['user', 'flag', 'policy']
48const POLICY_ONLY: readonly SourceName[] = ['policy']
49const WEB_FETCH = /^WebFetch\(domain:(.+)\)$/
50const GLOB = /[*?[]/
51const STATUS_RANK: Readonly<Record<Verdict['status'], number>> = { ready: 0, waiting: 1, 'no-fix': 2, covered: 3 }
52// A git or Claude folder outside the working directory, in any letter case: its hooks and settings run outside the sandbox.
53const REPO_FOLDERS: ReadonlySet<string> = new Set(['.git', '.claude'])
54// Under HOME, beside the protected places that any folder can hold: Claude Code's own settings and the global git configuration.
55const HOME_PROTECTED = ['.claude.json', '.config/git']
56const CREDENTIAL_FOLDERS = ['.ssh', '.gnupg', '.aws', '.azure', '.config/gcloud', '.config/gh', '.docker', '.netrc', '.npmrc', '.pypirc', '.git-credentials', '.password-store', '.local/share/keyrings', 'Library/Keychains']
57const SYSTEM_FOLDERS = ['/bin', '/sbin', '/usr', '/etc', '/private/etc', '/System', '/Library', '/Applications', '/opt/homebrew', '/opt/local', '/nix', '/boot', '/lib', '/lib64']
58const READ_BLOCK = 'permissions.blockReadsOutsideWorkingDirectories'
59// The roots that hold user files, which the read block closes to sandboxed commands (settings-reference.md).
60const USER_ROOTS = ['/Users', '/home', '/root', '/Volumes', '/mnt', '/media', '/run/media', '/srv']
61
62function at(value: unknown, path: readonly string[]): unknown {
63  return path.reduce<unknown>((node, name) => (isPlainObject(node) ? node[name] : undefined), value)
64}
65
66function strings(value: unknown): string[] {
67  return Array.isArray(value) ? value.filter(isText) : []
68}
69
70export function sandboxFacts(merged: Settings): SandboxFacts {
71  return {
72    isEnabled: at(merged, ['sandbox', 'enabled']) === true,
73    allowsUnsandboxed: at(merged, ['sandbox', 'allowUnsandboxedCommands']) !== false,
74  }
75}
76
77function isManagedDomainsOnly(sources: Sources): boolean {
78  return at(sources.policy, ['sandbox', 'network', 'allowManagedDomainsOnly']) === true
79}
80
81function isStrict(sources: Sources): boolean {
82  return TRUSTED_SOURCES.some(name => at(sources[name], ['sandbox', 'network', 'strictAllowlist']) === true)
83}
84
85function honoredSources(sources: Sources): readonly SourceName[] {
86  const policyRetry = at(sources.policy, ['sandbox', 'allowUnsandboxedCommands'])
87  const flagRetry = at(sources.flag, ['sandbox', 'allowUnsandboxedCommands'])
88  const isAdminRequired = policyRetry === false || (flagRetry === false && policyRetry !== true) || isManagedDomainsOnly(sources)
89  return isAdminRequired ? TRUSTED_SOURCES : SOURCE_NAMES
90}
91
92/** The sources whose host entries the sandbox honors. */
93function networkAllowSources(sources: Sources): readonly SourceName[] {
94  if (isManagedDomainsOnly(sources)) return POLICY_ONLY
95  return isStrict(sources) ? TRUSTED_SOURCES : honoredSources(sources)
96}
97
98function hostEntries(settings: Settings, list: 'allowedDomains' | 'deniedDomains', rules: 'allow' | 'deny'): string[] {
99  const fromRules = strings(at(settings, ['permissions', rules])).flatMap(rule => {
100    const [, domain] = WEB_FETCH.exec(rule) ?? []
101    return domain === undefined ? [] : [domain]
102  })
103  return [...strings(at(settings, ['sandbox', 'network', list])), ...fromRules]
104}
105
106/** Anchor a settings path without folding `..`: a press follows links before their following segments. */
107export function anchorEntry(text: string, source: SourceName, context: Context): string | null {
108  const entry = text.replace(/\/\*\*$/, '')
109  if (GLOB.test(entry)) return null
110  const isHome = entry === '~' || entry.startsWith('~/')
111  const base = entry.startsWith('/')
112    ? '/'
113    : isHome
114      ? context.home
115      : source === 'user'
116        ? context.configDir
117        : source === 'project' || source === 'local'
118          ? context.root
119          : undefined
120  return base === undefined ? null : entry.startsWith('/') ? entry : `${base}/${isHome ? entry.slice(2) : entry}`
121}
122
123function resolveAll(texts: readonly string[], source: SourceName, context: Context): Entry[] {
124  return texts.flatMap(text => {
125    const path = anchorEntry(text, source, context)
126    return path === null ? [] : [{ text, path: absolutePath(path, '/') }]
127  })
128}
129
130function entriesOf(context: Context, names: readonly SourceName[], path: readonly string[]): Entry[] {
131  return names.flatMap(name => resolveAll(strings(at(context.sources[name], path)), name, context))
132}
133
134/** Anchor the last literal parent of a sandbox pattern, retaining links and their following segments. */
135function sandboxPath(text: string, source: SourceName, context: Context): { path: string; isPattern: boolean } {
136  const entry = text.replace(/\/\*\*$/, '')
137  const wildcard = entry.search(GLOB)
138  const literal = wildcard < 0 ? entry : entry.slice(0, wildcard)
139  const parent = wildcard < 0 ? literal : literal.slice(0, literal.lastIndexOf('/') + 1) || '.'
140  return { path: anchorEntry(parent, source, context) ?? '/', isPattern: wildcard >= 0 }
141}
142
143/** Denial paths, or the last complete literal parent of each pattern, anchored before following links. */
144export function denialEntries(context: Context): DenialEntry[] {
145  const entries = permissionEntries(context)
146  for (const source of SOURCE_NAMES) {
147    for (const list of ['denyWrite', 'denyRead'] as const) {
148      for (const text of strings(at(context.sources[source], ['sandbox', 'filesystem', list]))) {
149        const { path, isPattern } = sandboxPath(text, source, context)
150        const reason = list === 'denyRead' ? (isPattern ? 'read-pattern' : 'read-rule') : (isPattern ? 'write-pattern' : 'deny-rule')
151        entries.push({ text, path, reason })
152      }
153    }
154  }
155  return entries
156}
157
158/** Permission rules use source-relative slash anchors and working-directory relative bare paths. */
159function permissionAnchor(pattern: string, source: SourceName, context: Context): { base: string | undefined; entry: string } {
160  if (pattern.startsWith('//')) return { base: '/', entry: pattern.slice(2) }
161  if (pattern.startsWith('~/')) return { base: context.home, entry: pattern.slice(2) }
162  if (pattern.startsWith('/')) return { base: source === 'user' ? context.configDir : source === 'project' || source === 'local' ? context.root : undefined, entry: pattern.slice(1) }
163  return { base: context.cwd, entry: pattern.replace(/^\.\//, '') }
164}
165
166/** Only a literal subtree can prove coverage of the entire proposed folder. */
167function editGrants(context: Context, source: SourceName): Entry[] {
168  return strings(at(context.sources[source], ['permissions', 'allow'])).flatMap(text => {
169    const pattern = /^Edit\((.+)\/\*\*\)$/.exec(text)?.[1]
170    if (pattern === undefined || /[*?[\\!]/.test(pattern)) return []
171    const { base, entry } = permissionAnchor(pattern, source, context)
172    if (base === undefined) return []
173    return [{ text, path: absolutePath(entry, base) }]
174  })
175}
176
177/** Permission paths have different anchors from sandbox paths. Uncertain patterns cannot justify opening a folder. */
178function permissionEntries(context: Context): DenialEntry[] {
179  const entries: DenialEntry[] = []
180  for (const source of SOURCE_NAMES) {
181    for (const rule of strings(at(context.sources[source], ['permissions', 'deny']))) {
182      const match = /^(Read|Edit)(?:\((.*)\))?$/.exec(rule)
183      if (match === null) continue
184      const isRead = match[1] === 'Read'
185      const pattern = match[2]
186      const uncertainReason = isRead ? 'read-pattern' : 'write-pattern'
187      if (pattern === undefined || pattern === '') {
188        entries.push({ text: rule, path: '/', reason: uncertainReason })
189        continue
190      }
191      const anchored = permissionAnchor(pattern, source, context)
192      const base = anchored.base
193      let entry = anchored.entry
194      if (!pattern.startsWith('/') && !pattern.startsWith('~/') && !entry.replace(/\/\*\*$/, '').includes('/')) entry = `**/${entry}`
195      if (base === undefined) {
196        entries.push({ text: rule, path: '/', reason: uncertainReason })
197        continue
198      }
199      entry = entry.replace(/\/\*\*$/, '')
200      // Escapes and negation need the full gitignore matcher. Keep their entire anchor uncertain.
201      const wildcard = /[\\!]/.test(entry) ? 0 : entry.search(GLOB)
202      const literal = wildcard < 0 ? entry : entry.slice(0, wildcard)
203      const parent = wildcard < 0 ? literal : literal.slice(0, literal.lastIndexOf('/') + 1)
204      entries.push({ text: rule, path: `${base}/${parent}`, reason: wildcard < 0 ? (isRead ? 'read-rule' : 'deny-rule') : uncertainReason })
205    }
206  }
207  return entries
208}
209
210/** Denials apply to both a requested path and its real location. */
211export function denialVerdict(samples: readonly string[], entries: readonly DenialEntry[]): Verdict | null {
212  const denied = entries.find(entry => samples.some(sample => isUnder(absolutePath(sample, '/'), absolutePath(entry.path, '/'))))
213  return denied === undefined ? null : noFix(denied.reason, denied.text)
214}
215
216/** Keep credential paths anchored for link resolution, using literal parents for patterns and `/` for unknown anchors. */
217export function credentialEntries(context: Context): Entry[] {
218  return SOURCE_NAMES.flatMap(name => {
219    const files = at(context.sources[name], ['sandbox', 'credentials', 'files'])
220    const paths = Array.isArray(files) ? files.map(file => at(file, ['path'])) : []
221    return strings(paths).map(text => ({ text, path: sandboxPath(text, name, context).path }))
222  })
223}
224
225/** A folder and each folder above it, up to the root. */
226function foldersUp(folder: string): string[] {
227  const folders = [folder]
228  let at = folder
229  while (at !== '/') {
230    at = at.slice(0, at.lastIndexOf('/')) || '/'
231    folders.push(at)
232  }
233  return folders
234}
235
236/**
237 * The protected places and the credentials folders, as spelled: the config dir and its protected names, Claude Code's
238 * files and the git configuration under HOME, and the protected places in HOME, in each project folder, and in every
239 * folder above a project folder, where Claude Code protects the `.claude` settings too.
240 */
241export function guardedPlaces(home: string | undefined, configDir: string | undefined, projects: readonly string[]): Pick<Context, 'protectedDirs' | 'credentialDirs'> {
242  const under = (folder: string | undefined, names: Iterable<string>) => (folder === undefined ? [] : [...names].map(name => `${folder === '/' ? '' : folder}/${name}`))
243  const places = [
244    ...(configDir === undefined ? [] : [configDir]),
245    ...under(configDir, CLAUDE_PROTECTED),
246    ...under(home, HOME_PROTECTED),
247    ...[home, ...projects.flatMap(foldersUp)].flatMap(folder => under(folder, PROTECTED_PLACES)),
248  ]
249  return { protectedDirs: [...new Set(places)], credentialDirs: under(home, CREDENTIAL_FOLDERS) }
250}
251
252/**
253 * A guarded place that the link check of a folder Allow walks: `levels` is how many levels of folders it lists, the
254 * place itself first (Infinity for every level), and `skip` names the folders it never enters, each as a path from the
255 * place, where `*` stands for any one name.
256 */
257export type Walk = { path: string; levels: number; skip: readonly string[] }
258
259// In the config folder, the walk lists only the places where code or settings that run outside the sandbox live.
260// It skips the data folders, such as transcripts (projects), todos, logs, and file history. Plugin code is too large to
261// list whole, so the walk lists the top two levels of each installed plugin, marketplace, and plugin data folder.
262const CONFIG_WALKS: readonly Walk[] = [
263  // Beside the protected names: the output styles.
264  { path: 'output-styles', levels: Infinity, skip: [] },
265  { path: 'plugins', levels: 1, skip: [] },
266  // <marketplace>/<plugin>/<version>, then two levels of the plugin.
267  { path: 'plugins/cache', levels: 5, skip: [] },
268  // <marketplace>, then two levels of it, without its git clone data.
269  { path: 'plugins/marketplaces', levels: 3, skip: ['*/.git'] },
270  // <plugin>, then two levels of the folder where a plugin keeps its installed dependencies.
271  { path: 'plugins/data', levels: 3, skip: [] },
272  // A local install of Claude Code.
273  { path: 'local', levels: 2, skip: [] },
274]
275
276// VS Code keeps the extensions it installs in the `.vscode` folder of HOME. They are too large to list whole, so the
277// walk lists the rest of that folder whole, and `extensions`: its top level, then two levels of each extension.
278const EDITOR_FOLDER = '.vscode'
279const EXTENSIONS_WALK: Walk = { path: 'extensions', levels: 3, skip: [] }
280
281/** Whether a walk skips the folder at `at`, the names from the walked place down to that folder. */
282export function isSkipped(skip: readonly string[], at: readonly string[]): boolean {
283  return skip.some(entry => {
284    const names = entry.split('/')
285    return names.length === at.length && names.every((name, index) => name === '*' || name === at[index])
286  })
287}
288
289/**
290 * The walks of the link check over guarded places. Each place is walked whole, except two. The config folder: its top
291 * level, its protected names (in `paths` already), and CONFIG_WALKS. The `.vscode` folder of HOME: the rest of it, and
292 * EXTENSIONS_WALK. A `.vscode` folder elsewhere holds settings only, so it is walked whole.
293 */
294export function guardedWalks(paths: readonly string[], { home, configDir }: Pick<Context, 'home' | 'configDir'>): Walk[] {
295  const inside = (folder: string, walk: Walk): Walk => ({ ...walk, path: `${folder === '/' ? '' : folder}/${walk.path}` })
296  const editor = home === undefined ? undefined : `${home === '/' ? '' : home}/${EDITOR_FOLDER}`
297  const walks = paths.map(path => ({ path, levels: path === configDir ? 1 : Infinity, skip: path === editor ? [EXTENSIONS_WALK.path] : [] }))
298  const config = configDir !== undefined && paths.includes(configDir) ? CONFIG_WALKS.map(walk => inside(configDir, walk)) : []
299  const extensions = editor !== undefined && paths.includes(editor) ? [inside(editor, EXTENSIONS_WALK)] : []
300  return [...walks, ...config, ...extensions]
301}
302
303/**
304 * Each folder that Allow opened that a real place lies inside or holds, and which of the two. As the Allow check does,
305 * it compares in any letter case: a file system that ignores case reads two spellings as one place.
306 */
307export function grantsMet<G extends { place: string }>(place: string, grants: readonly G[]): { grant: G; isInside: boolean }[] {
308  const folded = place.toLowerCase()
309  return grants.flatMap(grant => {
310    const opened = grant.place.toLowerCase()
311    const isInside = isUnder(folded, opened)
312    return isInside || isUnder(opened, folded) ? [{ grant, isInside }] : []
313  })
314}
315
316function isProtected(path: string, context: Context): boolean {
317  return context.protectedDirs.some(dir => isUnder(path, dir)) || isProtectedName(path)
318}
319
320function isCredential(record: SandboxTunerRecord, context: Context): boolean {
321  return [record.target, record.sample].some(path => context.credentialDirs.some(dir => isUnder(path, dir))) || isKeyFile(record.sample)
322}
323
324function isTooBroad(target: string, home: string | undefined): boolean {
325  return target.split('/').filter(part => part !== '').length < 2 || (home !== undefined && isUnder(home, target))
326}
327
328function isReadBlocked(path: string, context: Context): boolean {
329  const isOn = SOURCE_NAMES.some(name => at(context.sources[name], ['permissions', 'blockReadsOutsideWorkingDirectories']) === true)
330  const roots = context.home === undefined ? USER_ROOTS : [context.home, ...USER_ROOTS]
331  return isOn && roots.some(root => isUnder(path, root))
332}
333
334function noFix(reason: NoFixReason, detail: string): Verdict {
335  return { status: 'no-fix', reason, detail }
336}
337
338function withFile(context: Context, build: (file: FileInfo) => Verdict): Verdict {
339  return context.file === undefined ? noFix('no-settings-file', '') : build(context.file)
340}
341
342function byCount(record: SandboxTunerRecord, context: Context, allow: Change, deny: Change | null): Verdict {
343  return allowCount(record.counts) < context.threshold ? { status: 'waiting', deny } : { status: 'ready', allow, deny }
344}
345
346function hostVerdict(record: SandboxTunerRecord, context: Context): Verdict {
347  if (!isDnsName(record.target)) return noFix('not-dns', '')
348  const ports = record.ports.length === 0 ? [[]] : record.ports.map(port => [port])
349  const denied = SOURCE_NAMES.flatMap(name => hostEntries(context.sources[name], 'deniedDomains', 'deny')).find(entry => ports.some(port => hostMatches(entry, record.target, port)))
350  if (denied !== undefined) return noFix('denied-by-settings', denied)
351  const allowed = networkAllowSources(context.sources).map(source => ({ source, entries: hostEntries(context.sources[source], 'allowedDomains', 'allow') }))
352  const coverage = ports.map(port => allowed.find(({ entries }) => entries.some(entry => hostMatches(entry, record.target, port)))?.source)
353  const first = coverage[0]
354  if (first !== undefined && coverage.every(source => source !== undefined)) {
355    return { status: 'covered', source: coverage.every(source => source === first) ? first : 'combined' }
356  }
357  if (isManagedDomainsOnly(context.sources)) return noFix('managed-lock', record.target)
358  return withFile(context, file => {
359    // Deny only a host the person refused at the network prompt. Under strictAllowlist the sandbox refuses it already.
360    const canDeny = record.counts.refused > 0 && !isStrict(context.sources)
361    const deny: Change | null = canDeny ? { action: 'deny', settingsKey: 'sandbox.network.deniedDomains', entry: record.target, file } : null
362    return byCount(record, context, { action: 'allow', settingsKey: 'sandbox.network.allowedDomains', entry: record.target, file }, deny)
363  })
364}
365
366/**
367 * Whether the saved sample of a folder target names the folder itself: a folder that a command tried to create, guessed
368 * from error text (sightings.ts). Only a target with guessed sightings can have one. The target of a file is always a
369 * folder that holds it. Compare the saved paths, as written, before any link is resolved.
370 */
371export function isGuessedFolder(record: SandboxTunerRecord): boolean {
372  return record.kind === 'path' && record.counts.inferred > 0 && record.sample === record.target
373}
374
375/** `isFolder`: whether the sample names the folder itself (isGuessedFolder), from the saved record. */
376function pathVerdict(record: SandboxTunerRecord, context: Context, isFolder: boolean): Verdict {
377  const { target, sample } = record
378  if (isProtected(target, context) || isProtected(sample, context)) return noFix('protected', '')
379  if (isCredential(record, context)) return noFix('credentials', '')
380  if (SYSTEM_FOLDERS.some(folder => isUnder(target, folder))) return noFix('system', '')
381  if (isTooBroad(target, context.home)) return noFix('too-broad', '')
382  if (GLOB.test(target)) return noFix('glob', '')
383  const pathDir = context.pathDirs.map(dir => absolutePath(dir, '/')).find(dir => isUnder(target, dir) || isUnder(dir, target))
384  if (pathDir !== undefined) return noFix('on-path', pathDir)
385  if (isUnder(target, context.cwd)) return noFix('inside-workspace', '')
386  if (target.toLowerCase().split('/').some(part => REPO_FOLDERS.has(part))) return noFix('protected', '')
387  const denied = denialVerdict([sample], denialEntries(context))
388  if (denied !== null) return denied
389  const credentials = credentialEntries(context).map(entry => ({ ...entry, path: absolutePath(entry.path, '/') }))
390  const readRule = credentials.find(entry => isUnder(sample, entry.path))
391  if (readRule !== undefined) return noFix('read-rule', readRule.text)
392  if (isReadBlocked(sample, context)) return noFix('read-rule', READ_BLOCK)
393  const coveredBy = honoredSources(context.sources).find(name =>
394    [...entriesOf(context, [name], ['sandbox', 'filesystem', 'allowWrite']), ...entriesOf(context, [name], ['permissions', 'additionalDirectories']), ...editGrants(context, name)]
395      .some(entry => isUnder(target, entry.path)),
396  )
397  if (coveredBy !== undefined) return { status: 'covered', source: coveredBy }
398  // A folder strictly inside /tmp that holds the denied file is a temp folder: the target that Sandbox Tuner 1.1.1 names.
399  const isTemp = context.tmp !== null && isTempFolder(target, context.home, context.tmp) && folderTarget(sample, context.home, isFolder) === target
400  if (cacheFolder(sample, context.home, isFolder) !== target && !isTemp) return noFix('not-a-cache', '')
401  // A temp folder in a system folder in another letter case, which a file system that ignores case treats as the same.
402  if (isTemp && SYSTEM_FOLDERS.some(folder => isUnder(target.toLowerCase(), folder.toLowerCase()))) return noFix('system', '')
403  // Guard the entire folder, including credentials elsewhere inside it.
404  if (context.protectedDirs.some(dir => isUnder(dir, target))) return noFix('protected', '')
405  if ([...context.credentialDirs, ...credentials.map(entry => entry.path)].some(path => isUnder(path, target))) return noFix('credentials', '')
406  return withFile(context, file => byCount(record, context, { action: 'allow', settingsKey: 'sandbox.filesystem.allowWrite', entry: displayPath(target, context.home), file }, null))
407}
408
409/** Whether the Allow of a record rests on blocks guessed from error text: then it carries the guessed-block label. */
410export function isGuessedAllow(record: SandboxTunerRecord, verdict: Verdict): boolean {
411  return verdict.status === 'ready' && record.counts.inferred > 0
412}
413
414/**
415 * The verdict of a record. A check of where a folder really lies passes the record with resolved paths, and
416 * `isFolder` of the saved record: a link can make a resolved sample equal its target.
417 */
418export function verdictOf(record: SandboxTunerRecord, context: Context, isFolder = isGuessedFolder(record)): Verdict {
419  switch (record.kind) {
420    case 'host':
421      return hostVerdict(record, context)
422    case 'path':
423      return pathVerdict(record, context, isFolder)
424  }
425}
426
427function compareRated(a: Rated, b: Rated): number {
428  const byTarget = a.record.target < b.record.target ? -1 : a.record.target > b.record.target ? 1 : 0
429  return (
430    STATUS_RANK[a.verdict.status] - STATUS_RANK[b.verdict.status] ||
431    sightingTotal(b.record.counts) - sightingTotal(a.record.counts) ||
432    b.record.lastSeen - a.record.lastSeen ||
433    byTarget
434  )
435}
436
437export function rateRecords(records: readonly SandboxTunerRecord[], context: Context): Rated[] {
438  return records.map(record => ({ record, verdict: verdictOf(record, context) })).sort(compareRated)
439}
440
hooks/views.tsx 308 lines
1// Drawings: the band, the pane, and the text report.
2
3import type { BoxProps, ButtonProps, ElementConstructor, RenderElement, RenderNode, TextProps } from 'claude-code'
4
5import type { SandboxTunerApplied, SandboxTunerLatest, SandboxTunerNotice, SandboxTunerRecord, SandboxTunerScope } from '../types'
6import { cutText, plainText } from './names'
7import { isUndoUnresolved } from './records'
8import { fileInfo } from './settings-file'
9import { isGuessedAllow } from './verdicts'
10import type { Context, Rated, Verdict } from './verdicts'
11import {
12  APPLIED_NEXT, APPLIED_PREVIOUS, APPLY_HINT, BAND_KEY_HINT, GUESSED_ALLOW, NO_BLOCKS, SANDBOX_OFF, STILL_BLOCKED, appliedLine, countsSentence, countsSummary, displayTarget, explanation, lastProblem, moreRows,
13  openedLine, reformatSentence, reportHeadline, settingsHeader, undoSentence, verdictSentences,
14} from './words'
15
16type Kit = { Box: ElementConstructor<BoxProps>; Text: ElementConstructor<TextProps>; Button: ElementConstructor<ButtonProps> }
17// `guessed`: the label of an Allow whose target has blocks guessed from error text (guessedLabel), else null.
18type BandModel = { explanation: string; counts: string; sentences: string[]; guessed: string | null; error: string | null; canAllow: boolean; canDeny: boolean }
19type BandActions = { allow: () => void; deny: () => void; open: () => void; dismiss: () => void }
20
21// Sandbox Tuner's own cap on one problem text, so that a long cause leaves the pane lists their room in TEXT_BUDGET.
22const TEXT_LIMIT = 10_000
23
24/** A problem text that a drawing can show, cut to TEXT_LIMIT: its cause can hold any characters at any length. */
25export function drawable(text: string): string {
26  return cutText(plainText(text), TEXT_LIMIT)
27}
28
29function fixActions(verdict: Verdict): { canAllow: boolean; canDeny: boolean } {
30  return { canAllow: verdict.status === 'ready', canDeny: 'deny' in verdict && verdict.deny !== null }
31}
32
33function displaySentences(record: SandboxTunerRecord, verdict: Verdict, context: Context): string[] {
34  return [...verdictSentences(record, verdict, context), ...(verdict.status === 'covered' ? [STILL_BLOCKED] : [])]
35}
36
37/** The label of an Allow whose target has blocks guessed from error text, or null: it goes next to the Allow. */
38function guessedLabel(record: SandboxTunerRecord, verdict: Verdict): string | null {
39  return isGuessedAllow(record, verdict) ? GUESSED_ALLOW : null
40}
41
42export function buildBand(latest: SandboxTunerLatest, record: SandboxTunerRecord, verdict: Verdict, context: Context, notice: SandboxTunerNotice | null): BandModel {
43  return {
44    ...buildObservation(latest, notice),
45    counts: countsSentence(record),
46    sentences: displaySentences(record, verdict, context),
47    guessed: guessedLabel(record, verdict),
48    ...fixActions(verdict),
49  }
50}
51
52export function buildObservation(latest: SandboxTunerLatest, notice: SandboxTunerNotice | null): BandModel {
53  return {
54    explanation: explanation(latest), counts: '', sentences: [], guessed: null, canAllow: false, canDeny: false,
55    error: notice !== null && notice.isError && notice.at >= latest.at ? notice.text : null,
56  }
57}
58
59const BAND_LABELS = { allow: 'Allow', deny: 'Deny', open: 'Open Sandbox Tuner', dismiss: 'Dismiss' } as const
60// The band's padding at each side, and the cells between the elements of its Button row.
61const BAND_PADDING = 1
62const ROW_GAP = 2
63
64/**
65 * Whether the key hint fits after the Buttons on one row of `bodyColumns` cells (types AbovePrompt.bodyColumns), with
66 * the terminal's measure: it draws a Button as `[ label ]`. Else the hint is left out, so the row never wraps.
67 */
68export function hasHintRoom(labels: readonly string[], bodyColumns: number): boolean {
69  const buttons = labels.reduce((sum, label) => sum + label.length + 4, 0)
70  return 2 * BAND_PADDING + buttons + ROW_GAP * labels.length + BAND_KEY_HINT.length <= bodyColumns
71}
72
73// No band Button has a hotkey: a bare digit typed into an empty prompt would press it (types ButtonProps.hotkey).
74// The AbovePrompt render input does not say whether the band holds the focus, so the key hint stays the same.
75// One blank row above the band, so it does not look like the last line of the transcript.
76export function bandTree(kit: Kit, model: BandModel, actions: BandActions, beneath: RenderElement, bodyColumns: number): RenderElement {
77  const { Box, Text, Button } = kit
78  const labels = [...(model.canAllow ? [BAND_LABELS.allow] : []), ...(model.canDeny ? [BAND_LABELS.deny] : []), BAND_LABELS.open, BAND_LABELS.dismiss]
79  return (
80    <Box flexDirection="column">
81      <Box flexDirection="column" paddingX={BAND_PADDING} marginTop={1}>
82        <Text wrap="wrap">{model.explanation}</Text>
83        <Text dimColor>{model.counts}</Text>
84        {model.sentences.map(sentence => (
85          <Text wrap="wrap">{sentence}</Text>
86        ))}
87        {model.error === null ? null : (
88          <Text color="red" wrap="wrap">
89            {drawable(model.error)}
90          </Text>
91        )}
92        {model.guessed === null ? null : <Text color="yellow" wrap="wrap">{model.guessed}</Text>}
93        <Box gap={ROW_GAP}>
94          {model.canAllow ? <Button key="band-allow" label={BAND_LABELS.allow} variant="primary" onPress={actions.allow} /> : null}
95          {model.canDeny ? <Button key="band-deny" label={BAND_LABELS.deny} onPress={actions.deny} /> : null}
96          <Button key="band-open" label={BAND_LABELS.open} onPress={actions.open} />
97          <Button key="band-dismiss" label={BAND_LABELS.dismiss} role="dismiss" onPress={actions.dismiss} />
98          {hasHintRoom(labels, bodyColumns) ? <Text dimColor wrap="truncate-end">{BAND_KEY_HINT}</Text> : null}
99        </Box>
100      </Box>
101      {beneath}
102    </Box>
103  )
104}
105
106const ROW_LIMIT = 25
107// The engine refuses a drawing past 100,000 characters of text, keys, and labels, and draws its own in place of the
108// pane. A pane list ends with `+<n> more` past ROW_LIMIT rows, or once its next row would pass this budget.
109const TEXT_BUDGET = 90_000
110
111const SECTIONS = [
112  { kind: 'host', title: 'Hosts' },
113  { kind: 'path', title: 'Write folders' },
114] as const
115// The heading of the targets that have no fix: no settings fix, or a target that the settings already allow.
116const NOTHING_TO_ALLOW = 'Nothing to allow here'
117
118type RecordRow = { key: string; target: string; summary: string; sentences: string[]; guessed: string | null; canAllow: boolean; canDeny: boolean; canHide: boolean }
119type PaneSection = { title: string; rows: RecordRow[] }
120type AppliedRow = { id: string; line: string; undo: string | null; retry: boolean }
121
122// `reformatted`: the settings files of the journal that are not in the 2-space JSON format, so an Undo re-formats them.
123// `scope`: the scope option, which names what an empty pane has not seen.
124type PaneInput = { rated: readonly Rated[]; applied: readonly SandboxTunerApplied[]; reformatted: readonly string[]; appliedOffset: number; notice: SandboxTunerNotice | null; fault: string | null; isSandboxOn: boolean; context: Context; now: number; scope: SandboxTunerScope }
125type PaneModel = { header: string; isSandboxOn: boolean; notice: SandboxTunerNotice | null; fault: string | null; sections: PaneSection[]; hidden: { key: string; target: string }[]; applied: AppliedRow[]; appliedOffset: number; empty: string }
126// `isLabeled`: whether the drawing of the Allow showed the guessed-block label.
127type PaneActions = { allow: (key: string, isLabeled: boolean) => void; deny: (key: string) => void; hide: (key: string) => void; unhide: (key: string) => void; undo: (id: string) => void; moveApplied: (delta: number) => void }
128
129function visible(rated: readonly Rated[]): Rated[] {
130  return rated.filter(({ record }) => !record.isHidden)
131}
132
133/** A target with a fix: Allow now or after more sightings, or Deny. */
134function hasFix({ verdict }: Rated): boolean {
135  return verdict.status === 'ready' || verdict.status === 'waiting'
136}
137
138/**
139 * The lists of shown targets in the pane and the report: the hosts, then the write folders, that have a fix, then every
140 * target with no fix under one heading, hosts first. Each list keeps the ranked order.
141 */
142function targetLists(shown: readonly Rated[]): { title: string; rows: Rated[] }[] {
143  const ofKind = (kind: SandboxTunerRecord['kind'], isFixable: boolean) => shown.filter(rated => rated.record.kind === kind && hasFix(rated) === isFixable)
144  return [
145    ...SECTIONS.map(({ kind, title }) => ({ title, rows: ofKind(kind, true) })),
146    { title: NOTHING_TO_ALLOW, rows: SECTIONS.flatMap(({ kind }) => ofKind(kind, false)) },
147  ].filter(list => list.rows.length > 0)
148}
149
150/** A journal entry whose row offers Undo: a change still in place, or a removal not yet confirmed. */
151export function canUndo(entry: SandboxTunerApplied): boolean {
152  return entry.undoneAt === null || isUndoUnresolved(entry)
153}
154
155function recordRow({ record, verdict }: Rated, context: Context, now: number): RecordRow {
156  return {
157    key: record.key,
158    target: displayTarget(record, context.home),
159    summary: countsSummary(record, now),
160    sentences: displaySentences(record, verdict, context),
161    guessed: guessedLabel(record, verdict),
162    ...fixActions(verdict),
163    canHide: verdict.status !== 'covered',
164  }
165}
166
167export function buildPane(input: PaneInput): PaneModel {
168  const { context, now } = input
169  const shown = visible(input.rated)
170  return {
171    header: settingsHeader(context.file),
172    isSandboxOn: input.isSandboxOn,
173    notice: input.notice,
174    fault: input.fault,
175    appliedOffset: Math.max(0, Math.min(input.appliedOffset, input.applied.length - 1)),
176    empty: NO_BLOCKS[input.scope],
177    sections: targetLists(shown).map(({ title, rows }) => ({ title, rows: rows.map(rated => recordRow(rated, context, now)) })),
178    hidden: input.rated.filter(({ record }) => record.isHidden).map(({ record }) => ({ key: record.key, target: displayTarget(record, context.home) })),
179    applied: [...input.applied].reverse().map(entry => {
180      const file = fileInfo(entry.file, context.home)
181      const reformat = input.reformatted.includes(entry.file) ? [reformatSentence(file)] : []
182      return {
183        id: entry.id,
184        line: appliedLine(entry, now),
185        retry: isUndoUnresolved(entry),
186        undo: canUndo(entry) ? [undoSentence(entry, file), ...reformat].join(' ') : null,
187      }
188    }),
189  }
190}
191
192/** The characters of a drawing that count against the engine's text bound: its text, keys, and labels. */
193function textSize(node: RenderNode): number {
194  if (typeof node === 'string') return node.length
195  const props: Readonly<Record<string, unknown>> = 'props' in node ? (node.props ?? {}) : {}
196  const own = [props.key, props.label].reduce<number>((sum, value) => sum + (typeof value === 'string' ? value.length : 0), 0)
197  return 'children' in node ? (node.children ?? []).reduce((sum, child) => sum + textSize(child), own) : own
198}
199
200export function paneTree(kit: Kit, model: PaneModel, actions: PaneActions): RenderElement {
201  const { Box, Text, Button } = kit
202  const head = (
203    <Box flexDirection="column">
204      <Text bold>{model.header}</Text>
205      {model.isSandboxOn ? null : <Text color="yellow" wrap="wrap">{SANDBOX_OFF}</Text>}
206      {model.notice === null ? null : <Text color={model.notice.isError ? 'red' : 'green'} wrap="wrap">{drawable(model.notice.text)}</Text>}
207      {model.fault === null ? null : <Text color="red" wrap="wrap">{drawable(lastProblem(model.fault))}</Text>}
208    </Box>
209  )
210  let room = TEXT_BUDGET - textSize(head)
211  // Draws the rows that fit, in order, and counts the others as `+<n> more`.
212  const list = <T,>(key: string, title: string, rows: readonly T[], draw: (row: T) => RenderElement, offset = 0, move?: (delta: number) => void): RenderElement => {
213    const drawn: RenderElement[] = []
214    for (const row of rows.slice(offset, offset + ROW_LIMIT)) {
215      const element = draw(row)
216      const size = textSize(element)
217      if (size > room) break
218      room -= size
219      drawn.push(element)
220    }
221    return (
222      <Box key={key} flexDirection="column">
223        <Text bold>{title}</Text>
224        {drawn}
225        {rows.length > offset + drawn.length ? <Text dimColor>{moreRows(rows.length - offset - drawn.length)}</Text> : null}
226        {move === undefined ? null : (
227          <Box gap={2}>
228            {offset > 0 ? <Button key="applied-previous" label={APPLIED_PREVIOUS} onPress={() => move(-Math.min(offset, ROW_LIMIT))} /> : null}
229            {offset + drawn.length < rows.length ? <Button key="applied-next" label={APPLIED_NEXT} onPress={() => move(drawn.length)} /> : null}
230          </Box>
231        )}
232      </Box>
233    )
234  }
235  // Undo rows take their room first: they are the way back from every write.
236  const applied = model.applied.length === 0 ? null : list('applied', 'Applied', model.applied, row => (
237    <Box key={`applied:${row.id}`} flexDirection="column">
238      <Text>{row.line}</Text>
239      {row.undo === null ? null : (
240        <Box gap={2}>
241          <Text dimColor wrap="wrap">{row.undo}</Text>
242          <Button key={`undo:${row.id}`} label={row.retry ? 'Retry Undo' : 'Undo'} onPress={() => actions.undo(row.id)} />
243        </Box>
244      )}
245    </Box>
246  ), model.appliedOffset, actions.moveApplied)
247  const sections = model.sections.map(section => list(`section:${section.title}`, section.title, section.rows, row => (
248    <Box key={`row:${row.key}`} flexDirection="column" marginTop={1}>
249      <Text wrap="truncate-end">
250        <Text bold>{row.target}</Text>
251        <Text dimColor>{`  ${row.summary}`}</Text>
252      </Text>
253      {row.sentences.map(sentence => (
254        <Text wrap="wrap">{sentence}</Text>
255      ))}
256      {row.guessed === null ? null : <Text color="yellow" wrap="wrap">{row.guessed}</Text>}
257      <Box gap={2}>
258        {row.canAllow ? <Button key={`allow:${row.key}`} label="Allow" variant="primary" onPress={() => actions.allow(row.key, row.guessed !== null)} /> : null}
259        {row.canDeny ? <Button key={`deny:${row.key}`} label="Deny" onPress={() => actions.deny(row.key)} /> : null}
260        {row.canHide ? <Button key={`hide:${row.key}`} label="Hide" onPress={() => actions.hide(row.key)} /> : null}
261      </Box>
262    </Box>
263  )))
264  const hidden = model.hidden.length === 0 ? null : list('hidden', 'Hidden', model.hidden, row => (
265    <Box key={`hidden:${row.key}`} gap={2}>
266      <Text>{row.target}</Text>
267      <Button key={`unhide:${row.key}`} label="Unhide" onPress={() => actions.unhide(row.key)} />
268    </Box>
269  ))
270  const isEmpty = model.sections.length === 0 && model.hidden.length === 0 && model.applied.length === 0
271  return (
272    <Box flexDirection="column" gap={1}>
273      {head}
274      {isEmpty ? <Text dimColor>{model.empty}</Text> : null}
275      {sections}
276      {hidden}
277      {applied}
278    </Box>
279  )
280}
281
282function statusCount(rated: readonly Rated[], status: Verdict['status']): number {
283  return rated.filter(({ verdict }) => verdict.status === status).length
284}
285
286export function reportText(rated: readonly Rated[], context: Context, isSandboxOn: boolean, now: number, scope: SandboxTunerScope): string {
287  if (rated.length === 0) return NO_BLOCKS[scope]
288  const shown = visible(rated)
289  const lines = [
290    reportHeadline({ ready: statusCount(shown, 'ready'), waiting: statusCount(shown, 'waiting'), 'no-fix': statusCount(shown, 'no-fix'), covered: statusCount(shown, 'covered') }),
291    settingsHeader(context.file),
292    ...(isSandboxOn ? [] : [SANDBOX_OFF]),
293  ]
294  for (const { title, rows } of targetLists(shown)) {
295    lines.push('', title)
296    for (const { record, verdict } of rows.slice(0, ROW_LIMIT)) {
297      const guessed = guessedLabel(record, verdict)
298      lines.push(`- ${displayTarget(record, context.home)}: ${countsSummary(record, now)}`, ...[...displaySentences(record, verdict, context), ...(guessed === null ? [] : [guessed])].map(sentence => `  ${sentence}`))
299    }
300  }
301  return [...lines, '', APPLY_HINT].join('\n')
302}
303
304export function summaryLine(rated: readonly Rated[]): string {
305  const shown = visible(rated)
306  return openedLine(statusCount(shown, 'ready'), shown.length)
307}
308
hooks/words.ts 275 lines
1// The sentences of the band, the pane, the report, the command, and the notices.
2
3import type { SandboxTunerApplied, SandboxTunerLatest, SandboxTunerRecord, SandboxTunerScope, SandboxTunerSettingsKey } from '../types'
4import { cutText, displayPath, isSharedFolder, plainText } from './names'
5import { allowCount, sightingTotal } from './records'
6import type { FileInfo, Refusal } from './settings-file'
7import type { Change, Context, NoFixReason, SourceName, Verdict } from './verdicts'
8
9const MINUTE = 60_000
10// A settings entry that a sentence quotes can come from a cloned project: a long one is cut.
11const QUOTE_LIMIT = 200
12const HOUR = 60 * MINUTE
13const DAY = 24 * HOUR
14
15export const NO_BLOCKS: Readonly<Record<SandboxTunerScope, string>> = {
16  session: 'Sandbox Tuner has not seen a sandbox block in this session yet.',
17  all: 'Sandbox Tuner has not seen a sandbox block yet.',
18}
19export const SANDBOX_OFF = 'The sandbox is off in this session. Sandbox Tuner has nothing to tune.'
20const NO_SETTINGS_FILE = 'Sandbox Tuner cannot find your user settings file because HOME and CLAUDE_CONFIG_DIR are not set.'
21export const NOTHING_TO_UNDO = 'Nothing to undo.'
22export const NOTHING_TO_CHANGE = 'Nothing to change: the target is no longer listed.'
23export const APPLY_HINT = 'To apply a fix, run /sandbox-tuner in an interactive session and press Allow or Deny.'
24export const COMMAND_DESCRIPTION = 'Review the hosts and write folders the sandbox keeps blocking.'
25// What /sandbox-tuner prints while Claude Code still names the session that /clear, /resume, or /branch ended.
26export const SWITCHING = 'A switch to another session is in progress, so Sandbox Tuner shows no target yet. Run /sandbox-tuner again in a moment.'
27// The keyboard path to the band Buttons, drawn dim after them: Claude Code's focus chord, then Tab, Enter, or Esc.
28export const BAND_KEY_HINT = 'ctrl+x tab to choose'
29// The label next to an Allow whose target has blocks that Sandbox Tuner guessed from error text.
30export const GUESSED_ALLOW = 'Guessed from error text: the sandbox did not confirm this block.'
31export const STILL_BLOCKED = 'If the sandbox still blocks it, the cause is elsewhere, such as a tool that ignores the sandbox proxy, a read block, or file permissions. Check the client’s proxy settings and supported protocols. Run /status or /doctor for managed-settings warnings.'
32
33const SHARED_FOLDER = 'Every app you run keeps files in this folder, so sandboxed commands could change files that other apps read.'
34const SOURCE_LABELS: Readonly<Record<SourceName | 'combined', string>> = { user: 'user', project: 'project', local: 'local project', flag: '--settings', policy: 'managed', combined: 'combined' }
35const CHANGE_EFFECTS: Readonly<Record<SandboxTunerSettingsKey, string>> = {
36  'sandbox.network.allowedDomains': 'Sandboxed commands in every project can then reach it on any port, with no prompt and no per-command list, and can send it data.',
37  'sandbox.network.deniedDomains': 'The sandbox then refuses the host in every project, without a prompt.',
38  'sandbox.filesystem.allowWrite': 'Sandboxed commands can then write anywhere under it, and programs that run outside the sandbox may later load what they wrote.',
39}
40const NO_FIX: Readonly<Record<NoFixReason, (detail: string, target: string) => string>> = {
41  'not-dns': () => 'Sandbox Tuner does not suggest IP addresses or local host names.',
42  'denied-by-settings': detail => `Your setting "${detail}" already refuses this host.`,
43  'managed-lock': (_, target) => `Your organization's managed settings lock the network allowlist. Ask your administrator to allow ${target}.`,
44  protected: () =>
45    "Sandbox Tuner never opens this path to writes, because settings or code in it can run outside the sandbox. No setting opens such a path in your working directory or in Claude Code's config folder. If you expected this write, approve an unsandboxed retry or run the command yourself.",
46  credentials: () => 'This folder holds credentials. Sandbox Tuner never opens it to writes.',
47  system: () => 'This is a system or software-install folder. Sandbox Tuner never opens it to writes.',
48  'too-broad': (_, target) => `${target} is too broad to open to writes.`,
49  glob: (_, target) => `${target} holds *, ?, or [, which the sandbox reads as a pattern, so Sandbox Tuner cannot name it as a folder.`,
50  'on-path': (detail, target) => `${target} holds or sits inside ${detail}, a folder on your PATH, so a program written there could run in place of one you call.`,
51  'inside-workspace': () => 'Sandboxed commands can already write here. The block came from a protected file, a denyWrite rule, or a cause outside the sandbox.',
52  'deny-rule': detail => `Your write deny rule "${detail}" blocks it.`,
53  'write-pattern': detail => `Your write deny pattern "${detail}" may cover this path. Sandbox Tuner cannot safely suggest write access for this block.`,
54  'read-rule': detail => `Your read rule "${detail}" covers this path, so the block may be a read. Sandbox Tuner does not tune reads.`,
55  'read-pattern': detail => `Your read pattern "${detail}" may cover this path. Sandbox Tuner cannot safely suggest write access for this block.`,
56  'not-a-cache': () =>
57    'Sandbox Tuner suggests only cache and temp folders, because files in other folders can set up or start programs that run outside the sandbox. If you expected this write, approve an unsandboxed retry or run the command yourself.',
58  'no-settings-file': () => NO_SETTINGS_FILE,
59}
60
61function plural(count: number, one: string, many = `${one}s`): string {
62  return `${count} ${count === 1 ? one : many}`
63}
64
65function age(elapsedMs: number): string {
66  if (elapsedMs < MINUTE) return 'just now'
67  if (elapsedMs < HOUR) return `${Math.floor(elapsedMs / MINUTE)} min ago`
68  if (elapsedMs < DAY) return `${Math.floor(elapsedMs / HOUR)} h ago`
69  return `${Math.floor(elapsedMs / DAY)} d ago`
70}
71
72export function displayTarget(record: SandboxTunerRecord, home: string | undefined): string {
73  return record.kind === 'path' ? displayPath(record.target, home) : record.target
74}
75
76export function explanation(latest: SandboxTunerLatest): string {
77  const blocked = `Sandbox blocked ${latest.detail} for "${latest.command}".`
78  switch (latest.reason) {
79    case 'unlisted':
80      return `${blocked} The host is not on your sandbox allowlist, so Claude must list it on each command.`
81    case 'refused':
82      return `${blocked} You denied this host at the network prompt.`
83    case 'other':
84      return `${blocked} Reason: ${latest.reasonText}.`
85    case 'write':
86      return `Sandbox blocked a write to ${latest.detail} for "${latest.command}".`
87    case 'operation': {
88      const operation = latest.reasonText
89      const label = operation.startsWith('file-read-') ? 'a file read' : operation === 'mach-lookup' ? 'a Mach service lookup' : /socket|network-(?:bind|inbound)/.test(operation) ? 'a socket operation' : null
90      return label === null
91        ? `Sandbox Tuner cannot classify this sandbox operation: ${latest.detail}. No Allow action is available.`
92        : `The sandbox reported ${label} for "${latest.command}": ${latest.detail}. A write-folder grant cannot repair this operation. No Allow action is available.`
93    }
94    case 'inferred':
95      return `"${latest.command}" failed with a permission error on ${latest.detail}. The path and sandbox cause are unverified.`
96  }
97}
98
99export function countsSentence(record: SandboxTunerRecord): string {
100  return `Seen ${plural(sightingTotal(record.counts), 'time')} in ${plural(record.sessions.length, 'session')}.`
101}
102
103/**
104 * The counts of a target in words: its confirmed blocks (sandbox reports), and for a folder the blocks guessed from
105 * error text, or for a host the commands that listed it. A part that is 0 is left out, unless every part is 0.
106 */
107function countWords(record: SandboxTunerRecord): string {
108  const { blocked, refused, listed, inferred } = record.counts
109  const confirmed = `${plural(blocked, 'confirmed block')}${refused > 0 ? ` (you denied ${refused})` : ''}`
110  const parts: [number, string][] =
111    record.kind === 'path'
112      ? [[blocked, confirmed], [inferred, `${inferred} guessed from error text`]]
113      : [[blocked, confirmed], [listed, `listed on ${plural(listed, 'command')}`]]
114  const counted = parts.filter(([count]) => count > 0).map(([, words]) => words)
115  // A host is never guessed from error text: with nothing counted, its line still says how many blocks were confirmed.
116  return counted.length > 0 ? counted.join(' · ') : record.kind === 'path' ? parts.map(([, words]) => words).join(' · ') : confirmed
117}
118
119export function countsSummary(record: SandboxTunerRecord, now: number): string {
120  const head = countWords(record)
121  const programs = record.seenWith.length > 0 ? ` · with ${record.seenWith.join(', ')}` : ''
122  const ports = record.ports.length > 0 ? ` · ports ${record.ports.join(', ')}` : ''
123  return `${head} · ${plural(record.sessions.length, 'session')} · last ${age(now - record.lastSeen)}${programs}${ports}`
124}
125
126function changeSentence(change: Change): string {
127  const verb = change.action === 'allow' ? 'Allow' : 'Deny'
128  const shared = isSharedFolder(change.entry) ? ` ${SHARED_FOLDER}` : ''
129  return `${verb} adds "${change.entry}" to ${change.settingsKey} in ${change.file.display}. ${CHANGE_EFFECTS[change.settingsKey]}${shared}`
130}
131
132function refusalNote(record: SandboxTunerRecord): string[] {
133  return record.counts.refused > 0 ? [`You denied this host ${plural(record.counts.refused, 'time')} at the network prompt.`] : []
134}
135
136function statusSentences(record: SandboxTunerRecord, verdict: Verdict, context: Context): string[] {
137  switch (verdict.status) {
138    case 'ready':
139      return refusalNote(record)
140    case 'waiting':
141      return [...refusalNote(record), `Sandbox Tuner offers Allow after ${plural(context.threshold, 'sighting')} (${allowCount(record.counts)} so far).`]
142    case 'covered':
143      return [`Your ${SOURCE_LABELS[verdict.source]} settings already allow it.`]
144    case 'no-fix':
145      return [NO_FIX[verdict.reason](cutText(plainText(displayPath(verdict.detail, context.home)), QUOTE_LIMIT), displayTarget(record, context.home))]
146  }
147}
148
149/** The warning before a press saves a file that is not in the 2-space JSON format that Claude Code writes. */
150export function reformatSentence(file: FileInfo): string {
151  return `Saving also re-formats ${file.display} as 2-space JSON.`
152}
153
154export function verdictSentences(record: SandboxTunerRecord, verdict: Verdict, context: Context): string[] {
155  const changes = [verdict.status === 'ready' ? verdict.allow : null, 'deny' in verdict ? verdict.deny : null].filter((change): change is Change => change !== null)
156  const reformat = context.isCanonical ? [] : changes.slice(0, 1).map(change => reformatSentence(change.file))
157  return [...statusSentences(record, verdict, context), ...changes.map(changeSentence), ...reformat]
158}
159
160export function addedNotice(change: Change, hadFile: boolean): string {
161  const previous = hadFile ? `The previous file is saved at ${change.file.backupDisplay}.` : 'The file is new.'
162  return `Added "${change.entry}" to ${change.settingsKey} in ${change.file.display}. ${previous}`
163}
164
165export function removedNotice(entry: SandboxTunerApplied, file: FileInfo): string {
166  return `Removed "${entry.entry}" from ${entry.settingsKey} in ${file.display}. The previous file is saved at ${file.backupDisplay}.`
167}
168
169/** The cause when the file holds the entry, but the settings that Claude Code loaded do not. */
170export function notAppliedText(change: Change): string {
171  return `"${change.entry}" is already in ${change.settingsKey} in ${change.file.display}, but Claude Code has not applied it yet. If this stays, run /status to check that the session loads user settings, and look for a ConfigChange hook that blocks the change. Nothing was written.`
172}
173
174export function absentNotice(entry: SandboxTunerApplied): string {
175  return `"${entry.entry}" is no longer in ${entry.settingsKey}. Marked as undone.`
176}
177
178export function hiddenNotice(target: string): string {
179  return `${target} is hidden. Find it under Hidden.`
180}
181
182export function shownNotice(target: string): string {
183  return `${target} is shown again.`
184}
185
186export function nothingApplied(sentences: readonly string[]): string {
187  return `Nothing applied: ${sentences.join(' ')}`
188}
189
190function refusalCause(refusal: Refusal, file: FileInfo): string {
191  return refusal.refusal === 'invalid-json'
192    ? `${file.display} is not valid JSON (${refusal.message}).`
193    : `${refusal.path} in ${file.display} is ${refusal.found}, not ${refusal.expected}.`
194}
195
196export function refusalText(refusal: Refusal, file: FileInfo): string {
197  return `${refusalCause(refusal, file)} Nothing was written.${refusal.refusal === 'invalid-json' ? ' Fix the file, then press again.' : ''}`
198}
199
200export function verificationRefusalText(refusal: Refusal, file: FileInfo): string {
201  return `could not check ${file.display} after the write: ${refusalCause(refusal, file)} Check the file before trying again.`
202}
203
204export function appliedLine(entry: SandboxTunerApplied, now: number): string {
205  const undone = entry.applyState === 'pending' ? ', addition unconfirmed' : entry.undoState === 'superseded' ? ', a later change owns this entry' : entry.undoState === 'pending' || entry.undoState === 'retry' ? ', removal unconfirmed' : entry.undoneAt === null ? '' : `, undone ${age(now - entry.undoneAt)}`
206  return `${entry.entry} in ${entry.settingsKey}, ${age(now - entry.appliedAt)}${undone}`
207}
208
209export function undoSentence(entry: SandboxTunerApplied, file: FileInfo): string {
210  return `Undo removes "${entry.entry}" from ${entry.settingsKey} in ${file.display}.`
211}
212
213export function settingsHeader(file: FileInfo | undefined): string {
214  return file === undefined ? NO_SETTINGS_FILE : `Settings file: ${file.display}`
215}
216
217/** `a`, `a and b`, or `a, b, and c`. */
218function series(items: readonly string[]): string {
219  return items.length < 3 ? items.join(' and ') : `${items.slice(0, -1).join(', ')}, and ${items.at(-1)}`
220}
221
222/**
223 * A folder that Allow opened, as a warning of the link check at session start names it: whether a row of the pane can
224 * undo it, and each settings file that holds it with no such row, where only a hand edit removes it.
225 */
226type MetGrant = { grant: string; isInside: boolean; hasUndo: boolean; byHand: readonly string[] }
227
228/**
229 * The warning of the link check at session start: a link or a guarded place meets folders that Allow opened. It names
230 * each of them, because the exposure stays until each one is removed: with Undo where the pane offers it, else by hand.
231 */
232export function grantWarning(path: string, place: string, met: readonly MetGrant[]): string {
233  const isLink = path !== place
234  const subject = isLink ? `${path} leads to ${place}, which` : path
235  const quoted = (items: readonly MetGrant[]) => items.map(item => `"${item.grant}"`)
236  const relations = [[quoted(met.filter(item => item.isInside)), 'lies inside'], [quoted(met.filter(item => !item.isInside)), 'holds']] as const
237  const relation = relations.filter(([grants]) => grants.length > 0).map(([grants, verb]) => `${verb} ${series(grants)}`).join(' and ')
238  const folders = met.length === 1 ? 'a folder' : 'folders'
239  const undo = met.filter(item => item.hasUndo).map(item => `for "${item.grant}"`)
240  const steps = [
241    ...(undo.length > 0 ? [`press Undo ${series(undo)} in /sandbox-tuner`] : []),
242    ...[...new Set(met.flatMap(item => item.byHand))].map(file =>
243      `remove ${series(quoted(met.filter(item => item.byHand.includes(file))))} from sandbox.filesystem.allowWrite in ${file} by hand`),
244  ]
245  return `${subject} ${relation}, ${folders} that your settings open to sandboxed writes. So sandboxed commands can change what ${isLink ? 'the link' : 'it'} names. To close this, ${series(steps)}${isLink ? ', or remove the link' : ''}.`
246}
247
248export function lastProblem(fault: string): string {
249  return `Last background problem: ${fault}`
250}
251
252export function moreRows(count: number): string {
253  return `+${count} more`
254}
255
256export const APPLIED_PREVIOUS = 'Newer changes'
257export const APPLIED_NEXT = 'Older changes'
258
259export function reportHeadline(counts: Readonly<Record<Verdict['status'], number>>): string {
260  return `${plural(counts.ready, 'fix', 'fixes')} ready, ${counts.waiting} waiting, ${counts['no-fix']} without a settings fix, ${counts.covered} already allowed.`
261}
262
263export function openedLine(ready: number, targets: number): string {
264  return `${plural(ready, 'fix', 'fixes')} ready, ${plural(targets, 'target')}. The pane is open.`
265}
266
267export function notPlaced(reason: string): string {
268  return `The pane is not placed: ${reason}`
269}
270
271/** Command results and toasts already carry the plugin name. */
272export function hostText(text: string): string {
273  return text.replace(/^sandbox-tuner: /gm, '').replace(/^Sandbox Tuner has not seen/, 'Has not seen')
274}
275
hooks/shapes.ts 18 lines
1// JSON shape checks shared by saved records, the journal, and settings edits.
2
3export function isText(value: unknown): value is string {
4  return typeof value === 'string'
5}
6
7export function isCount(value: unknown): value is number {
8  return typeof value === 'number' && Number.isInteger(value) && value >= 0
9}
10
11export function isPlainObject(value: unknown): value is Record<string, unknown> {
12  return typeof value === 'object' && value !== null && !Array.isArray(value)
13}
14
15export function isListOf<T>(value: unknown, isItem: (item: unknown) => item is T): value is T[] {
16  return Array.isArray(value) && value.every(isItem)
17}
18
types/index.d.ts 83 lines
1export type SandboxTunerKind = 'host' | 'path'
2
3export type SandboxTunerCounts = {
4  blocked: number      // reports of a block (network, or file write)
5  refused: number      // host reports with reason "user denied"; part of blocked
6  listed: number       // runs that named the host in allowed_domains
7  inferred: number     // inferred blocks of a folder
8}
9
10export type SandboxTunerRecord = {
11  key: string          // `${kind}:${target}`
12  kind: SandboxTunerKind
13  target: string       // host (lowercase) or absolute folder
14  counts: SandboxTunerCounts
15  ports: number[]      // hosts: distinct ports, newest last, at most 5
16  sample: string       // the last host:port or absolute path seen; a folder keeps a protected or key file
17  seenWith: string[]   // program names, newest last, at most 3
18  sessions: string[]   // session ids, newest last, at most 20
19  firstSeen: number
20  lastSeen: number
21  isHidden: boolean
22}
23
24// One /branch with scope session, saved under `lineage:<session>`: the branch, the session that it started from, the
25// time of the branch, and the keys of the targets that a record named that session in by then, sorted.
26export type SandboxTunerLineage = { session: string; parent: string; at: number; keys: string[] }
27
28export type SandboxTunerAction = 'allow' | 'deny'
29
30export type SandboxTunerSettingsKey =
31  | 'sandbox.network.allowedDomains'
32  | 'sandbox.network.deniedDomains'
33  | 'sandbox.filesystem.allowWrite'
34
35export type SandboxTunerApplied = {
36  id: string           // unique identifier for one settings addition
37  recordKey: string
38  action: SandboxTunerAction
39  settingsKey: SandboxTunerSettingsKey
40  entry: string
41  file: string         // absolute path of the user settings file
42  backup: string | null // absolute path of the backup; null when the file was new
43  created: string[]    // dotted key paths that the apply created, outermost first
44  appliedAt: number
45  undoneAt: number | null
46  applyState?: 'pending'
47  undoState?: 'pending' | 'retry' | 'superseded'
48  session?: string     // the session id of the press that applied it; absent when unknown, as in Sandbox Tuner 1.1.3
49}
50
51// The `scope` option: what the band, the pane, and the report show. `session`, only what the current session saw and
52// applied, with what each session that it branched from saw and applied before the branch; `all`, what every session
53// saw and applied.
54export type SandboxTunerScope = 'session' | 'all'
55
56export type SandboxTunerLatest = {
57  recordKey: string
58  detail: string       // host:port, or the absolute path
59  reason: 'unlisted' | 'refused' | 'other' | 'write' | 'inferred' | 'operation'
60  reasonText: string   // the report's reason in parentheses; '' when none
61  command: string      // one line, at most 120 characters
62  at: number
63}
64
65// `session`: with scope session, the session id of the press that made the notice; only that session shows it.
66export type SandboxTunerNotice = { text: string; isError: boolean; at: number; session?: string }
67
68declare module 'claude-code' {
69  interface PluginState {
70    'sandbox-tuner': {
71      backgroundTasks: string[]
72      evidenceIncomplete: boolean
73      records: SandboxTunerRecord[]
74      applied: SandboxTunerApplied[]
75      appliedOffset: number
76      latest: SandboxTunerLatest | null
77      dismissed: string | null
78      notice: SandboxTunerNotice | null
79      fault: string | null
80    }
81  }
82}
83