Skip to content

API Reference parrot_tools.tool_optimizations.patches

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

parrot_tools.tool_optimizations.patches

View source

Unified-diff parsing, in-memory application and artifact storage (FEAT-543).

This module is pure Python, stdlib-only and model-free. It takes the unified diff a delegate returned and decides — deterministically — whether it is a legal, in-scope CREATE/MODIFY patch, then applies it in memory against the expected source bytes so nothing is written until the caller has verified the outcome.

Two deliberate design choices:

  • Patches are applied in pure Python with exact context matching and zero fuzz. No external diff tool is invoked, so a model-written path can never reach an external command's argument list, and a mismatch is a clean rejection returned to the thinking model rather than a guess.
  • v1 supports CREATE and MODIFY only. Deletions, renames, copies, mode changes, binary payloads and submodule updates are each rejected with their own code, so the refusal is explainable.

Artifacts live under <repo_root>/artifacts/tool-optimizations/<id>/, which is gitignored (.gitignore:283), with 0o700 directories and 0o600 files.

Class ApplyJournal

A recovery journal for one multi-file apply operation.

Multi-file filesystem mutation is not globally atomic, so the journal records what was intended and what was achieved, allowing a targeted rollback that never overwrites a concurrent edit.

Fields:

Field Type Default Description
artifact_id str The artifact being applied.
started_at str ISO-8601 UTC start time.
entries list[JournalEntry] One entry per target file.
state Literal['pending', 'applied', 'rolled_back', 'recovery_required'] 'pending' The operation's overall outcome.

Class ArtifactStore

Durable, restrictive storage for generated patch artifacts.

Artifacts are opaque data, never executable commands: ids are random hex, directories are 0o700 and files are 0o600.

Parameter Type Default Description
repo_root Path The repository root; artifacts live beneath it.

Method ArtifactStore.new_id

Return a fresh opaque artifact id.

new_id() -> str

Returns: str — 32 lowercase hex characters.

Method ArtifactStore.write_generation

Store a generated artifact atomically.

Everything is written into a private temp directory and published with a single rename, so a crash can never leave a half-written artifact that :meth:load would accept.

write_generation(artifact_id: str, *, manifest: PatchManifest, patch_text: str, packet_json: str) -> Path

Parameter Type Default Description
artifact_id str The artifact identifier.
manifest PatchManifest The provenance manifest.
patch_text str The normalized patch.
packet_json str The canonical packet JSON.

Returns: Path — The published artifact directory.

Raises:

  • PatchError — The id is malformed.

Method ArtifactStore.load

Load an artifact, verifying it has not been edited.

load(artifact_id: str) -> tuple[PatchManifest, str, str]

Parameter Type Default Description
artifact_id str The artifact identifier.

Returns: tuple[PatchManifest, str, str] — A (manifest, patch_text, packet_json) tuple.

Raises:

  • PatchError — The artifact is missing, or its stored patch or packet no longer hashes to the manifest's recorded value.

Method ArtifactStore.write_journal

Persist the recovery journal for an apply operation.

write_journal(artifact_id: str, journal: ApplyJournal) -> None

Parameter Type Default Description
artifact_id str The artifact identifier.
journal ApplyJournal The journal to write.

Method ArtifactStore.read_journal

Read the recovery journal, if one exists.

read_journal(artifact_id: str) -> Optional[ApplyJournal]

Parameter Type Default Description
artifact_id str The artifact identifier.

Returns: Optional[ApplyJournal] — The journal, or None when the artifact has never been applied.

Method ArtifactStore.save_before

Save a file's pre-application bytes for rollback.

save_before(artifact_id: str, index: int, data: Optional[bytes]) -> None

Parameter Type Default Description
artifact_id str The artifact identifier.
index int The journal entry index.
data Optional[bytes] The original bytes, or None when the file did not exist (in which case nothing is stored and rollback means delete).

Method ArtifactStore.load_before

Load a file's saved pre-application bytes.

load_before(artifact_id: str, index: int) -> Optional[bytes]

Parameter Type Default Description
artifact_id str The artifact identifier.
index int The journal entry index.

Returns: Optional[bytes] — The original bytes, or None when the file did not exist.

Method ArtifactStore.directory_mode

Return the artifact directory's permission bits.

directory_mode(artifact_id: str) -> int

Parameter Type Default Description
artifact_id str The artifact identifier.

Returns: int — The mode bits, e.g. 0o700.

Class FilePatch

All hunks that apply to one file.

Fields:

Field Type Default Description
path str The repo-relative POSIX path, with any a//b/ prefix stripped.
is_create bool False True when the patch creates the file (--- /dev/null).
hunks list[Hunk] The hunks, in file order.

Class Hunk

One @@ hunk of a unified diff.

Fields:

Field Type Default Description
old_start int 1-based start line in the original file (0 for a create).
old_count int Number of original lines the hunk covers.
new_start int 1-based start line in the resulting file.
new_count int Number of resulting lines the hunk produces.
lines list[str] Body lines with their leading ' ', '-' or '+' marker preserved.
no_newline_old bool False The original file had no trailing newline.
no_newline_new bool False The resulting file has no trailing newline.

Class JournalEntry

The recorded state of one file during an apply operation.

Fields:

Field Type Default Description
path str The repo-relative path.
before_sha256 Optional[str] None The file's digest before, or None when it was absent.
after_sha256 str The digest this operation intended to write.
before_index int Index of the saved before/<n>.bin payload.
before_mode Optional[int] None The file's original permission bits, so a rollback restores them instead of silently normalizing to 0644.
state Literal['pending', 'written', 'verified', 'restored', 'unrecoverable'] 'pending' How far this file got.

Class PatchError

A patch is malformed, out of scope, or does not match its source.

Parameter Type Default Description
code str The stable rejection code.
message str '' A human-readable explanation.
details Optional[dict[str, Any]] None Structured context (path, hunk index, expected vs actual).

Attributes:

Attribute Type Description
code A stable snake_case code identifying the rejection.
details Structured context for the thinking model.

Function apply_file_patch

Apply one file's hunks in memory, with exact context matching.

There is no fuzz factor and no offset search: a context line that does not match the source exactly is a rejection, not a guess.

apply_file_patch(before: Optional[bytes], patch: FilePatch) -> bytes

Parameter Type Default Description
before Optional[bytes] The original file bytes, or None for a create.
patch FilePatch The parsed patch for this file.

Returns: bytes — The resulting file bytes.

Raises:

  • PatchError — The source does not decode as UTF-8, a hunk is out of order, or a context/removed line does not match the source.

Function apply_in_memory

Apply every file patch against its expected source bytes.

apply_in_memory(patches: list[FilePatch], sources: dict[str, Optional[bytes]]) -> dict[str, bytes]

Parameter Type Default Description
patches list[FilePatch] The parsed, scope-checked patches.
sources dict[str, Optional[bytes]] Path -> current bytes, or None when the file is absent.

Returns: dict[str, bytes] — Path -> resulting bytes, for every patched path.

Raises:

  • PatchError — A modify target is missing, or a hunk does not match.

Function check_scope

Verify every patched path is approved with matching create semantics.

check_scope(patches: list[FilePatch], allowed: dict[str, str]) -> None

Parameter Type Default Description
patches list[FilePatch] The parsed patches.
allowed dict[str, str] Approved path -> "create" or "modify".

Raises:

  • PatchError — A path is outside the approved scope, or its create / modify semantics disagree with the packet.

Function normalize_patch

Canonicalize patch text and reject prose or fenced output.

The returned text is what gets hashed and stored, so this function is idempotent: normalize_patch(normalize_patch(x)) == normalize_patch(x).

normalize_patch(text: str) -> str

Parameter Type Default Description
text str The raw model output.

Returns: str — The canonical patch text, ending in a single newline.

Raises:

  • PatchError — The text is fenced, contains prose before the first header, or has no diff header at all (not_a_patch).

Function parse_patch

Parse a normalized unified diff into per-file patches.

parse_patch(text: str, *, max_bytes: int) -> list[FilePatch]

Parameter Type Default Description
text str Normalized patch text (see :func:normalize_patch).
max_bytes int The largest patch accepted.

Returns: list[FilePatch] — class:FilePatch per target file, in patch order.

Raises:

  • PatchError — The patch is too large, uses an unsupported feature, has an invalid path, targets a file twice, or has a malformed hunk.

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