# Run-tape branch contract

> The harn_vm::run_tape host API records production model calls, tool dispatches, prompt sources, and observed workspace changes. A branch serves a recorded prefix and continues...

Website: https://harnlang.com/dev/run-tape.html

This page documents Harn, which is pre-1.0. Language, standard library, and CLI APIs may change. If the intended version is unclear, clarify before using this page.

---

The `harn_vm::run_tape` host API records production model calls, tool dispatches,
prompt sources, and observed workspace changes. A branch serves a recorded prefix
and continues with live inference after the selected model call.

## Recording

`start_recording` accepts a recording level and an optional `TapeWorkspace`.
Only a full recording with a workspace effect observer can be branched.
Metadata recordings can be inspected but cannot reproduce a prefix. A process
can hold one active recording.

Hosts declare additional durable storage directories in `TapeWorkspace.state_roots`.
The recording retains those roots so a branch can isolate writes to them.

`taped_command_run` wraps a host command before its policy hooks and execution.
It records the returned value and
observed workspace changes. Commands inside
an agent tool dispatch belong to that dispatch's recording and are not recorded
again. The host identifies background requests before entering the wrapper;
command policy cannot rewrite a request's background setting.

## Branch execution

`start_branch` takes the tape, the number of model calls to serve, a
`ReplayWorkspaceLocation`, and a fresh durable-state root. Pass the seed owner's
`location()` as `BranchPlan.workspace`. The location derives both the working copy
and its storage pool from one owned storage directory; callers cannot narrow the
pool while keeping the same workspace. Custom owners use the layout
`pool/storage/workspace` and `ReplayWorkspaceLocation::from_storage_root(storage)`;
relative storage roots refuse. Enter its `BranchScope` around the
execution. The host must supply the workspace state from before the recording;
the tape does not reconstruct that initial state.

Set `live_after_calls` to zero to change the first model request. The tape must
contain a recorded model call. Reads and tool operations before that call still
replay and must be consumed before live inference starts. A zero-prefix branch
that never reaches inference finishes with an `under-run branch` divergence.

Set `BranchPlan.host_state_roots` to the host's durable roots for the new execution,
including a fresh per-run home. Both recorded and current host roots remap into
the branch state directory; undeclared external roots remain refused in the prefix.

During the prefix, supported foreground commands return their recorded results
and apply their recorded workspace changes. Their policy hooks and processes do
not run again. Changing a command's arguments makes the prefix diverge. A host
must read `BranchGuard::finish` and treat divergence or an unfinished prefix as
failure.

A served tool dispatch replays recorded transcript field changes. For a child
created and closed entirely within that dispatch, the tape retains its initial
transcript, changes, and closure. Replay validates the initial transcript's type,
version, session identity, and required lists before applying workspace effects.
It applies changes separately from live sessions, without rerunning the child or
its hooks. A missing target without
that lifecycle evidence still refuses. A newly created session that remains open,
or a dispatch that closes a previously existing session, is marked unservable
when recorded. Bulk session-store resets record their closures but remain
unservable because they also reset runtime policy outside the transcripts.
A refused dispatch is not counted as served.
Tape version 5 carries these lifecycle records. Field-change records retain their
version 4 shape, so existing recordings remain readable by the new runtime.

A served dispatch also replays recorded runtime store set, delete, and clear
operations in order. They update the branch's store through the normal store
writer before execution continues. VMs sharing that store use one branch-owned
state, so later writes retain the replayed values. The recording's store file
isn't changed. Store values use the tape's normal payload redaction and storage.
Older tool records without `store_changes` remain readable, but can't be served
because they don't establish which store operations occurred. Record a new full
tape to replay those tools.

Reminder revocation and expiry inside the captured dispatch also record the
session's retired reminder identities. Replay checks that the session matches
the recorded initial state before applying effects, then installs the resulting
state. Later revocation requests retain their `already_revoked` or
`already_delivered` status. A missing
or changed initial state makes the dispatch diverge before file or transcript
effects. Exact branching requires a full tape recorded in format 9, which also
establishes that session permission grants were checked and command requests
were measured for every dispatch. Older recordings stay
inspectable but need to be recorded again for branching.

Workspace-location reads (`fs.cwd` and `fs.source_dir`) are recorded during the
prefix. Each branch has one workspace identity: the logical root is the original
recorded root, and the physical root is its private working copy. Pipeline and
model data retain the logical root, including tool results and request digests.
The original tape and its content-addressed payloads remain unchanged. Filesystem builtins
resolve paths before normal permission checks and refuse parent-component or
symlink escapes. Host filesystem adapters use `workspace_path` at their I/O
boundary. `BranchScope.workspace_identity()` exposes the two roots without
assigning path policy to the host.

Enter the branch scope before calling `start_recording` to record a descendant.
Its header retains prior physical workspace roots, oldest first, while its request
payloads retain the original logical identity. A later branch resolves every
retained root at the filesystem boundary and preserves the original prompt source
identity. The recording refuses a workspace that differs from its scope.
Alternate root spellings are retained separately from physical ancestor roots.
They resolve at I/O boundaries even after an alias disappears; their spelling
in recorded prompt and tool data stays unchanged.

External source packages also retain their physical history when a branch is
recorded. Model data keeps the earliest logical root across later moves, while
file I/O resolves every retained root to the current package. Prompt edits use the
selected tape's own recorded template identities. Missing restored packages,
relative retained names, and overlapping source ownership refuse before execution.
Source packages cannot overlap the replay storage pool. Moving only a source
package also activates command confinement: grants cannot reopen its earlier
locations, while an exact grant to the current package remains usable.

On Linux, local foreground commands use the existing OS-hardened sandbox with
the branch workspace, required runtime/toolchain access, and projected explicit
host grants. Process working directories resolve to the physical root. Command
arguments and environment values remain unchanged. The OS
renderer refuses any implicit grant that would reopen the recorded workspace or
the branch storage pool outside this arm. Ambient temporary trees, package
configuration, and external mounts are withheld. A restored script's embedded
absolute path is not edited: accessing the recorded tree or a peer is denied.
Declared path grants retain recorded alias names even after unlinking, then
resolve filesystem aliases before the final physical projection. Explicit
denials retain both their original and mapped locations.

## Prompt source edits

`BranchPlan.prompt_edits` accepts `PromptSourceEdit` records for complete literal
spans in the tape. Each edit names the template URI and revision, one-based
Unicode line and column, recorded text, replacement text, and `activation`.
Admission requires
that exact literal and location in recorded provenance. Interpolated values and
partial spans are not source edits.
Replacement text cannot contain `{{` or `}}`, or form either delimiter against
adjacent source text. Template expressions, comments, and raw-block terminators
are refused rather than interpreted as replacement text.

With `Origin`, the template renderer applies edits from the start, including
values rendered early and sent to a model later. Earlier model requests still
have to match their recorded digests. `AfterPrefix` is an explicit mid-run
intervention: earlier renders retain the original source. Filesystem templates,
included templates, and embedded standard-library assets use the same renderer;
source files are never written. Source revision changes, overlapping ranges,
and edits never loaded by the run make the branch incomplete.

For edits with `Origin` activation, `plan_prompt_branch(&tape, &edits)` returns the first
attributed model call that used any edited literal and its `live_after_calls`
prefix. Its `first_consumers` list records the first use of every edit in input
order. Pass that prefix and the same edits to `BranchPlan`. The planner refuses
unused or unattributed edits, ambiguous overlapping source attribution, and
malformed source identities. Like replay admission, planning refuses tapes with
redacted payloads: stored render bytes may no longer match source span offsets.
A short render without request attribution is
unavailable for automatic planning, even if the tape recorded its source.
Recorded renders remain candidates for attribution throughout the run, so a
value first consumed later or reused after an unrelated call keeps its source.

`BranchReport.prompt_edits` reports how many renders prepared each edit. This is
not proof that the edited text reached inference: a script can render text and
discard it. Experiments must verify use in the actual recorded model request.
An explicit `live_after_calls` remains available for a host offering a labeled
mid-run intervention. Neither a planned boundary nor a successful replay
establishes whether an edit improves model behavior.

## Refusals and limits

- Live commands in a relocated workspace require the enforced local Linux view
  above. Other platforms, unconfined runtime commands, and host command adapters
  that cannot bind that view retain their refusal. Workspace name projection
  alone does not confine arbitrary host tools or external processes.
  A baseline recorded in an isolated workspace can replay at that same path;
  the host restores its initial contents between runs.
- Each tool dispatch records whether it requested a command, including requests
  refused before launch. On non-Linux hosts, admission refuses a moved replay
  with recorded command requests after the served prefix, before any model call.
  Answer-only and filesystem-only replay remain available. Served commands need
  no child process and retain their command evidence in descendant recordings.
  Linux checks the active command policy and filesystem backend at execution;
  a Linux host without that backend can make a model call before refusing the
  command. New live commands still pass the runtime confinement check. Missing
  command evidence requires a new recording; it never means no commands were requested.
- Background commands cannot be served because their process handles do not
  exist in the branch. A dispatch that starts one is marked unservable.
  Relocated branches also refuse live background commands because the workspace
  owner cannot retain their filesystem view through independent shutdown.
- Overlapping dispatches cannot be served because their workspace scans and
  transcript changes do not establish a reproducible order.
- A dispatch containing nested inference cannot be served.
- A dispatch that creates or uses a session-scoped dynamic permission grant
  cannot be served. The grant cache is not portable approval authority, so the
  branch refuses before replaying the dispatch's effects. Once-only grants do
  not populate that cache and remain eligible for replay.
- A failed runtime store write or a store mutation outside the recorded dispatch
  context makes the dispatch unservable.
- A mismatch between observed reminder retirements and captured changes makes
  the dispatch unservable.
- Redacted payloads, incomplete file-effect observations, and unconsumed prefix
  operations prevent an exact replay.
- Only observed workspace changes are reapplied. External effects from the
  recording are not repeated.
- Dropping a branch scope does not cancel a session. Hosts must use their
  session cancellation path and wait for its terminal result.

## Private trial workspaces

For a pipeline package outside the editable project, retain and restore a separate
`ReplayWorkspace`. Pass its original and restored roots as `ReplaySourceRoot`
values to `start_branch_with_sources`, and grant the restored package read-only
access in the host sandbox. Harn maps filesystem reads and prompt identities
through these roots. Original package files may be absent. Overlapping roots,
escaping paths, and changed edited source are refused. Keep both workspace leases
alive until execution ends, including detached shutdown work.

`harn_hostlib::workspace_checkpoint::ReplayWorkspace` captures a private seed
and a disposable working copy. `path()` names the same working directory
after every `restore()`. Stop the previous session and its children before
restoring; the workspace owner does not cancel execution.

Capture includes ignored and untracked regular files, empty directories, file and directory
permission bits, and relative symbolic links that resolve inside the source.
External or broken links, special files, and non-UTF-8 paths refuse. Source
content is measured twice before publishing the copy. `SeedLimits` bounds
entry count, depth, per-file content, and total bytes; its defaults allow
100,000 entries, depth 128, 128 MiB per file, and 1 GiB overall.

`receipt()` reports the observed entries, regular files, bytes, and a SHA-256
identity covering sorted paths, contents, link targets, and file and directory permissions.
Restore verifies that identity before replacing the working copy. A changed
seed leaves the previous working copy available. Dropping an ordinary owner
deletes its private storage without changing the source.

For a run that must survive an application restart, `persist()` retains the
directory and returns a serializable `SavedReplayWorkspace`. Save that descriptor
with the run in private product storage. It carries the original directory,
seed receipt, and capture limits. `ReplayWorkspace::restore_saved(&saved)`
acquires an exclusive operating-system file lock, verifies the seed, and restores
the working copy before returning it for a new trial. A competing owner refuses
before restoration. Closing a retained owner releases its lock but keeps its
files; the product's run-retention policy owns their eventual retirement.

For independent trials, use `ReplayWorkspace::fork_saved_in(&saved, parent)`.
It acquires a shared seed-read lease while verifying and copying into new private
storage, then owns an exclusive lease on that copy. Multiple forks can read the
same saved seed concurrently. The original seed and working copy are unchanged;
each fork is deleted when its owner drops unless explicitly persisted.
Pass `location()` as `BranchPlan.workspace`; it binds `path()` to the whole pool.
`restore_saved` remains the in-place restart operation and excludes competing owners.

Keep the handle inside the execution owner until the session and every child
process has stopped. A frontend holding it on behalf of an independent worker
does not establish that lifetime after a frontend crash. Reopening recovers
either half of an interrupted workspace replacement and removes abandoned
restore staging. It does not resume a partially executed trial. A saved root
must remain at its original canonical path; Unix reopening also refuses a root
whose permissions now allow other users to access it.

Unix storage is created with owner-only access, including under shared temporary
directories. On Windows, the storage parent must have a user-private ACL; child
directories inherit it. `capture_in` callers must supply that protected parent.
Source ACLs, ownership, and timestamps are not copied.

Offline coding replay uses this owner for its file-only fixtures and includes
the seed receipt in trial evidence. Its effect oracle still rejects symbolic
links. The seed API supplies filesystem isolation between trial copies, not
process confinement; hosts must also grant each execution only its working
copy and required read-only assets.

Outstanding replay cases are tracked in
[remaining prefix cases](https://github.com/burin-labs/harn/issues/10805).

---

## Read next

- [Testbench mode](https://harnlang.com/dev/testbench.md)
- [DES runtime mode](https://harnlang.com/dev/des-mode.md)
