Skip to content

API Reference parrot.sdd.scripts.worktree_environment

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.sdd.scripts.worktree_environment

View source

Protect shared Python environments when executing SDD worktree commands.

This file deliberately uses only the standard library and can run directly as a Claude hook, even when importing the rest of Parrot is unavailable.

Attribute AGY_FILE_TOOLS

Attribute BACKENDS

Attribute BACKSTOP_MARGIN_RATIO

Attribute CLAUDE_SCRATCH_ROOT

Attribute CODER_EVIDENCE_DIR

Attribute DEGRADED_BANNER

Attribute EXPERIENCE_PLANE_DIR

Attribute EXTRA_WRITE_PATHS_KEY

Attribute HOST_DEFAULT_TIMEOUT_MS

Attribute HOST_MAX_TIMEOUT_MS

Attribute KILL_GRACE_SECONDS

Attribute LAUNCHER_MARKERS

Attribute MIN_BACKSTOP_MARGIN_SECONDS

Attribute NATIVE_BWRAP_DENIAL

Attribute POLICY_MESSAGE

Attribute RTK_ENV_SWITCH

Attribute RTK_REWRITE_TIMEOUT_SECONDS

Attribute SHARED_LEDGER_DIR

Attribute UID_MAP_PATH

Function agy_verdict

Return an Antigravity permission decision for one PreToolUse payload.

agy_verdict(payload: dict[str, Any], *, root: Path, backend: str, unattended: bool) -> tuple[Literal['deny', 'ask'], str, dict[str, str] | None]

Parameter Type Default Description
payload dict[str, Any] The Antigravity event payload.
root Path The active checkout root supplied by the caller.
backend str The configured sandbox backend.
unattended bool Whether the worker runs without an operator.

Returns: tuple[Literal['deny', 'ask'], str, dict[str, str] | None] — A decision, reason, and optional shallow CommandLine overwrite.

Function bounded_shell_argv

Build the /bin/bash -c argv for command, wrapped in timeout when bounded.

timeout sends SIGTERM to the whole command group at the bound and SIGKILL KILL_GRACE_SECONDS later, so the sandbox's main child always exits and Bubblewrap tears the PID namespace down with it.

bounded_shell_argv(command: str, tool_input: dict[str, Any]) -> list[str]

Parameter Type Default Description
command str The shell text the seat issued (already scope-guarded).
tool_input dict[str, Any] The native Bash tool input, for the timeout fields.

Returns: list[str] — The argv to place after Bubblewrap's -- separator.

Function claude_scratch_root

Return Claude Code's per-user scratchpad root, creating it when absent.

Claude Code creates a session's scratchpad lazily, so the root may not exist yet when the first sandboxed command runs. Creating it on the host lets a mkdir -p of the scratchpad from inside the sandbox land on the host instead of in the private tmpfs, where it would vanish with the command.

claude_scratch_root() -> Path

Returns: Path — The resolved root directory, private to the current user.

Function coder_evidence_dirs

Return the primary checkout's sdd-coder evidence store for a linked worktree.

parrot sdd task review prepare and parrot sdd task finalize resolve the store to <primary>/artifacts/logs/sdd-coder-usage and write the review checkpoint and the task journal there. Only that directory is returned: the rest of artifacts/ holds Python the unsandboxed host executes and stays read-only.

Unlike :func:shared_ledger_dirs, a missing directory is created rather than skipped: the store does not exist before the first execution, and Bubblewrap cannot bind a path that is not there.

coder_evidence_dirs(root: Path, git_dir: Path | None) -> tuple[Path, ...]

Parameter Type Default Description
root Path The checkout root resolved for the command's working directory.
git_dir Path | None The common Git directory, or None outside a repository.

Returns: tuple[Path, ...] — The evidence directory to bind writable, or an empty tuple for the primary checkout (already writable) and when it cannot be created.

Function command_policy_error

Give early feedback for package operations; filesystem mounts enforce safety.

command_policy_error(cwd: Path, argv: Sequence[str]) -> str | None

Parameter Type Default Description
cwd Path
argv Sequence[str]

Returns: str | None

Function command_timeout_seconds

Resolve the wall-clock backstop the sandboxed command must respect.

A process that prints an error and then never exits — an unclosed aiosqlite worker thread is the classic case — keeps Bubblewrap waiting on it, and the host's teardown does not always reach through the sandbox, so the command is bounded inside the sandbox too.

That bound is a backstop, never the first kill. The host does not kill a foreground Bash call that overruns tool_input["timeout"] (or its default, BASH_DEFAULT_TIMEOUT_MS / 120 s): it detaches it and lets it finish in the background. A sandbox kill at exactly the host's bound turns that rescue into exit 124 and discards the output of a healthy slow command — a merge-tier pytest sweep is the classic case. So every bound gets headroom, and an implicit one is lifted to at least the host's maximum (HOST_MAX_TIMEOUT_MS): once the host has detached a command, nothing else will ever reap it.

command_timeout_seconds(tool_input: dict[str, Any]) -> int | None

Parameter Type Default Description
tool_input dict[str, Any] The native Bash tool input.

Returns: int | None — The backstop in whole seconds, or None for a background command without an explicit timeout, which the host never bounds.

Function derived_pythonpath_assignment

Shell text assigning PYTHONPATH from <root>/packages/*/src when the command runs.

Listing every package src is a ~3 KB literal that a model must echo back verbatim after an auto-mode refusal; the glob keeps the rewrite short and yields the same value. A pre-existing PYTHONPATH is appended.

derived_pythonpath_assignment(root: Path) -> str

Parameter Type Default Description
root Path The checkout root whose packages/*/src directories form the path.

Returns: str — A PYTHONPATH="…" assignment, safe as an env argument or a command prefix.

Function existing_directory

Resolve path, falling back to its nearest existing ancestor.

/sdd-done ends by removing the very worktree it runs in, and git worktree prune can drop an administration directory underneath a live session. Resolving strictly raises there, and because every native Bash call is wrapped by this module, a single raise denies every subsequent command — the session loses its own shell and cannot even cd back to the primary checkout. Anchoring on the nearest surviving ancestor keeps the sandbox on a real directory instead: for a removed worktree that is the primary checkout's worktree root, so the next command lands back inside the primary checkout.

existing_directory(path: Path) -> Path

Parameter Type Default Description
path Path The directory to resolve, which may no longer exist.

Returns: Path — The resolved directory, or the closest ancestor that still exists.

Function experience_dirs

Return the primary checkout's experience plane for a linked worktree.

The plane is created before the sandbox starts because Bubblewrap cannot bind a missing path. The primary checkout already owns its writable root, so it needs neither an additional bind nor a filesystem side effect.

experience_dirs(root: Path, git_dir: Path | None) -> tuple[Path, ...]

Parameter Type Default Description
root Path The checkout root resolved for the command's working directory.
git_dir Path | None The common Git directory, or None outside a repository.

Returns: tuple[Path, ...] — The experience directory to bind writable, or an empty tuple for the primary checkout, missing Git metadata, or a directory creation error.

Function hook_response

Apply guards and file checks for one of three backends; deny invalid modes.

  • bubblewrap (the keyword default; explicit legacy): wraps in bwrap unless a token-authenticated legacy shell prefix is active, in which case the prefix already applies Bubblewrap and a plain command is left unchanged.
  • claude-native (launcher): never nest bwrap. The launcher's backend variable is trusted (the hook cannot see the sandbox), so there is no runtime check; the command is rewritten only when its environment differs from the inherited one, the guard/RTK changed it, or it carries an explicit timeout/run_in_background. A hand-written bwrap command is denied.
  • auto (what main() selects when the backend is unset): one wrapper that runs natively inside the native sandbox and through bwrap outside it.

The Bash rewrite is idempotent: a command that already is this hook's output passes through without updatedInput, so auto mode can review the resent call.

hook_response(payload: dict[str, Any], *, backend: str = 'bubblewrap') -> dict[str, Any]

Parameter Type Default Description
payload dict[str, Any]
backend str 'bubblewrap'

Returns: dict[str, Any]

Function load_extra_write_paths

Read and validate [tool.parrot.sdd].sandbox_extra_write_paths from the primary checkout.

Each entry must be an absolute, already-normalized path. It is symlink-resolved, and the resolved directory is what the sandbox grants. An entry is refused when it resolves to the filesystem root or a top-level directory (/tmp, /home, /var: never a whole shared tree), or when it is equal to, inside, or an ancestor of the primary checkout, the user's home directory, or a shared environment.

load_extra_write_paths(primary: Path) -> tuple[Path, ...]

Parameter Type Default Description
primary Path The primary checkout root. Never pass a worktree: its pyproject.toml is session-writable.

Returns: tuple[Path, ...] — The resolved, de-duplicated directories, or an empty tuple when the file, table or key is absent.

Raises:

  • ValueError — If the file is malformed or an entry is not an acceptable path.

Function main

Serve a native PreToolUse hook without importing application dependencies.

main(argv: Sequence[str] | None = None) -> None

Parameter Type Default Description
argv Sequence[str] | None None

Function protected_argv

Build a fail-closed Linux filesystem sandbox for a command and its children.

Only the checkout, Git administration directory, the primary checkout's worktree directory (the resolved worktree root, so a worktree agent can run git worktree add/remove for /sdd-done), the primary checkout's shared SDD ledger (.parrot/ledger, so a worktree agent can file and claim ledger issues), the sdd-coder evidence store (artifacts/logs/sdd-coder-usage, so review checkpoints and task journals can be written), the operator-declared sandbox_extra_write_paths of the primary checkout's pyproject.toml, private temporary storage, the shared experience plane (.parrot/experience), and Claude Code's scratchpad root (/tmp/claude-<uid>, bound back over the private /tmp so a seat's scratchpad survives between commands) are writable. The rest of the primary checkout and existing shared environments remain read-only even when the checkout is the primary repository. No host chmod or mount changes are performed. Network isolation is outside this policy's scope.

derive_pythonpath=True omits the --setenv PYTHONPATH literal: the caller sets PYTHONPATH in the command's environment (see derived_pythonpath_assignment), which bwrap passes through.

protected_argv(cwd: Path, argv: Sequence[str], *, derive_pythonpath: bool = False) -> list[str]

Parameter Type Default Description
cwd Path
argv Sequence[str]
derive_pythonpath bool False

Returns: list[str]

Function repository_paths

Find the checkout root and common Git directory, including pool worktrees.

repository_paths(cwd: Path) -> tuple[Path, Path | None]

Parameter Type Default Description
cwd Path

Returns: tuple[Path, Path | None]

Function rtk_rewrite

Return RTK's token-optimized form of command, or None to keep it as is.

rtk rewrite prints the rewritten command when RTK has an equivalent and prints nothing when it has none. Only that output is trusted, because the exit status is RTK's permission verdict against the Claude settings: 0 when an allow rule matches, 3 when the host should ask, 2 (with no output) when a deny rule matches. This hook grants no approval, so 0 and 3 are equivalent here. -- ends RTK's own options, so a command that starts with - is rewritten as text instead of being parsed as an RTK flag. Every failure (RTK not installed, disabled with PARROT_SANDBOX_RTK=0, a timeout, a crash) keeps the original command, because output compaction must never block a command.

rtk_rewrite(command: str) -> str | None

Parameter Type Default Description
command str The shell text to run, after the test-scope guard.

Returns: str | None — The rewritten command, or None when RTK is unavailable or has no equivalent.

Function sandbox_extra_write_dirs

Return the operator-declared extra writable directories for a linked worktree.

The declaration is read from the primary checkout only. A session running in the primary checkout itself gets none: it can edit that pyproject.toml, so the value is not trusted there.

This never raises — protected_argv wraps every Bash call, so one raise would deny the whole session. An invalid declaration grants nothing (the launcher reports it through load_launch_config), and a directory that cannot be created is skipped: Bubblewrap cannot bind a path that is not there.

sandbox_extra_write_dirs(root: Path, git_dir: Path | None) -> tuple[Path, ...]

Parameter Type Default Description
root Path The checkout root resolved for the command's working directory.
git_dir Path | None The common Git directory, or None outside a repository.

Returns: tuple[Path, ...] — The existing directories to make writable.

Function shared_environments

Resolve environment symlinks so aliases receive the same protection.

shared_environments(cwd: Path) -> tuple[Path, ...]

Parameter Type Default Description
cwd Path

Returns: tuple[Path, ...]

Function shared_ledger_dirs

Return the primary checkout's ledger directory when root is a linked worktree.

wikitoolkit ledger open/claim/close/unclaim resolve the ledger through find_shared_root to <primary>/.parrot/ledger. Only that directory is returned — SQLite needs its -wal/-shm siblings next to ledger.db — so the wiki plane and the rest of .parrot stay read-only.

shared_ledger_dirs(root: Path, git_dir: Path | None) -> tuple[Path, ...]

Parameter Type Default Description
root Path The checkout root resolved for the command's working directory.
git_dir Path | None The common Git directory, or None outside a repository.

Returns: tuple[Path, ...] — The existing ledger directory to bind writable, or an empty tuple for the primary checkout (already writable) and for primaries without a ledger.

Function validate_agy_write_path

Confine an Antigravity file-tool target to checkout.

validate_agy_write_path(checkout: Path, raw_path: str) -> Path

Parameter Type Default Description
checkout Path The active checkout root.
raw_path str The relative or absolute target received from Antigravity.

Returns: Path — The canonical target path.

Raises:

  • ValueError — If the target escapes the checkout, enters Git metadata, or aliases a protected shared Python environment.

Function validate_write_path

Reject direct file-tool writes through aliases into shared environments.

validate_write_path(cwd: Path, path: Path) -> None

Parameter Type Default Description
cwd Path
path Path

Function worktree_admin_dirs

Return the primary checkout's worktree directory when root is a linked worktree.

Linked worktrees (feature and pool checkouts) live under the primary checkout's resolved worktree root (default .parrot/worktrees). /sdd-done run from inside one must create a throwaway ledger-snapshot worktree there and remove the feature worktree itself, and both operations write to that directory rather than to the worktree being executed in. The rest of the primary checkout is intentionally not returned so it stays read-only.

worktree_admin_dirs(root: Path, git_dir: Path | None) -> tuple[Path, ...]

Parameter Type Default Description
root Path The checkout root resolved for the command's working directory.
git_dir Path | None The common Git directory, or None outside a repository.

Returns: tuple[Path, ...] — The existing admin directory to bind writable, or an empty tuple for the primary checkout (already writable) and for linked checkouts whose primary has no such directory.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally