Skip to content

API Reference parrot.tools.optimizations.policy

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

parrot.tools.optimizations.policy

View source

Operation policy, result budget, path checks and worktree lock (FEAT-543).

This module owns the deterministic safety layer shared by the three tool-optimizations toolkits:

  • :class:OptimizationPolicy — the configured limits (line/byte thresholds, serialized result budget, subprocess timeouts).
  • Byte-budget helpers — :func:compact_json, :func:measure_json_bytes and :func:fit_to_budget, which shrink content and re-serialize rather than slicing JSON text into something unparseable.
  • Path policy — :func:resolve_operand composes the existing confinement helpers (containment + secret deny-list) with a new symlink-component rejection pass.
  • :class:WorktreeLock — a cross-process advisory lock (fcntl.flock / msvcrt.locking) used to serialize cooperating mutations per worktree.

Class BudgetError

Raised when a configured byte budget is unusable.

Class LockTimeoutError

Raised when a :class:WorktreeLock could not be acquired in time.

Attribute MIN_RESULT_BYTES

Class OptimizationPolicy

Configured limits shared by every tool-optimizations toolkit.

Fields:

Field Type Default Description
repo_root Path The repository checkout every operand is confined to. Resolved at construction; must be an existing directory.
max_lines int 350 Line threshold above which a read requires explicit ranges.
large_file_bytes int 64000 Byte threshold above which a read requires ranges.
max_result_bytes int 64000 Budget applied to the serialized domain result.
command_timeout_seconds float 30.0 Timeout for a local subprocess.
network_timeout_seconds float 120.0 Timeout for a network-bound subprocess.
deny_secret_files bool True When True, the existing secret deny-list applies.

Class PolicyError

Base class for every policy violation raised by this module.

Class SymlinkRejectedError

Raised when a path traverses a symlinked component below the root.

Class WorktreeLock

A cross-process advisory lock serializing mutations per worktree.

Built on fcntl.flock(LOCK_EX) (msvcrt.locking on Windows). flock is advisory and is released by the kernel when the owning process dies, so a stale lock file is never possible and the lock file is therefore never unlinked — deleting it would break the mutual exclusion of processes already holding it.

External Git processes do not honor this lock, so Git's own index lock and the toolkit's revision checks remain necessary.

Parameter Type Default Description
lock_path Path The lock file path. Created if absent, never removed.
timeout_seconds float How long to wait for the lock before failing.

Function check_no_symlink_components

Reject a path any of whose components below root is a symlink.

The candidate is normalized, not resolved, so the returned path keeps the caller's spelling; each existing component below the root is then lstat-ed. This closes the gap left by containment checks, which legitimately follow symlinks and therefore accept a link that happens to point back inside the root.

check_no_symlink_components(root: Path, candidate: str) -> Path

Parameter Type Default Description
root Path The (already resolved) repository root.
candidate str A caller-supplied relative or absolute path.

Returns: Path — The normalized absolute path, with no symlinked component.

Raises:

  • PathOutsideRootError — The normalized path escapes root.
  • SymlinkRejectedError — A component below root is a symlink.

Function compact_json

Serialize obj with the canonical compact encoding.

This exact encoding defines what max_result_bytes measures: the UTF-8 encoding of the compact JSON domain result, including metadata and escaped content, before any MCP transport wrapping.

compact_json(obj: Any) -> str

Parameter Type Default Description
obj Any Any JSON-compatible object.

Returns: str — The compact JSON text.

Function fit_to_budget

Shrink result until its serialized form fits budget bytes.

Content is reduced and re-serialized; JSON text is never sliced, so the returned object always parses. The reduction order is deliberate — step diagnostics first, then payload records, then the payload as a whole, so that status/error identity survives to the very last stage.

fit_to_budget(result: OperationResult, budget: int) -> OperationResult

Parameter Type Default Description
result OperationResult The domain result to bound.
budget int The serialized byte budget (at least :data:MIN_RESULT_BYTES).

Returns: OperationResult — A result whose model_dump(mode="json") measures at most budget bytes. truncated is set whenever anything was dropped.

Raises:

  • BudgetError — budget is below :data:MIN_RESULT_BYTES.

Function measure_json_bytes

Return the UTF-8 byte length of :func:compact_json for obj.

measure_json_bytes(obj: Any) -> int

Parameter Type Default Description
obj Any Any JSON-compatible object.

Returns: int — The measured byte count.

Function relative_posix

Return target as a repo-relative POSIX path.

relative_posix(root: Path, target: Path) -> str

Parameter Type Default Description
root Path The repository root.
target Path An absolute path inside root.

Returns: str — The repo-relative POSIX path ("." for the root itself).

Raises:

  • PathOutsideRootError — target is not inside root.

Function resolve_operand

Resolve one caller-supplied path under the configured policy.

Checks run in a deliberate order: containment first (and the secret deny-list when enabled), then symlink-component rejection, then existence. Running containment first means an escaping path is reported as such even when it also happens to be a symlink.

resolve_operand(policy: OptimizationPolicy, candidate: str, *, must_exist: bool) -> Path

Parameter Type Default Description
policy OptimizationPolicy The active policy supplying the root and secret setting.
candidate str A caller-supplied relative or absolute path.
must_exist bool When True, a missing path is an error.

Returns: Path — The normalized absolute path, guaranteed inside the root and free of symlinked components.

Raises:

  • PathOutsideRootError — The path escapes the repository root.
  • SecretFileError — The path matches the secret deny-list.
  • SymlinkRejectedError — A component below the root is a symlink.
  • PolicyError — must_exist is True and the path does not exist.

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