# Slice 5b: bounded per-file diffs

Status: approved by the controller, 2026-11-26. ProtocolChangeDiffs = 35 (reallocated by the controller after main shipped 32, then Assistant files 33 and Places 34).

## Source and transport

Use the runner's existing private Git object store, alongside Engineering's
`changeFiles` measurement in `internal/runner/thin/engineer.go`. The thin instance
relays candidate packs between runners; it does not maintain a forge clone
(`internal/equipo/chat/transfers.go`). Do not introduce instance forge credentials
or a new clone solely to display a diff.

Prepare a bounded collection of display patches for the accepted Engineering
candidate, then upload it separately from the ordinary step/task view. This
makes a viewed diff available when the runner is offline and keeps device GETs
read-only. Bind every upload to instance, assigned runner, task, step, attempt,
base and candidate, with a digest and declared byte count. Validate all bindings
at acceptance; publish the collection only with its matching accepted report.
An interrupted collection remains unavailable and is pruned. Duplicate uploads
must match their digest and content; conflicting replacements are refused.

This needs a new runner protocol capability and bounded chunk frames, following
the research-image transfer pattern, plus a small final-report reference. The
number must be allocated with the controller before code, considering other
open branches. Old runners and old steps keep the reviewed Amadan link. No
patches go into task lists, snapshots, events, the Coordinator tool or prompts.
The existing Review measurements and merge authority remain unchanged.

## Device endpoint and binding

`GET /api/v1/tasks/{id}/changes/diff?candidate_sha=<sha>&path=<encoded-path>`

Use exactly the task-read authority, including current membership. Resolve the
current candidate's latest Engineering step on the server. The requested path
must exactly match a validated change_files entry; derive base and rename source
from that entry, never from caller-supplied Git arguments. A candidate mismatch
returns a reviewed conflict; unknown or invisible tasks are indistinguishable.
The candidate and task visibility are checked again before returning bytes.

Return task/step/attempt/base/candidate/path identity, status, old path if renamed,
and either bounded unified patch text or an explicit unavailable reason.
Flags distinguish truncation, binary content and secret withholding. Native
renders plain text, never HTML, and discards responses for a candidate or file
that is no longer selected. Responses use no-store and never offer a raw-file
or unredacted-download mode. New user-facing reasons require reviewed copy.

## Computation and bounds

Only entries already included in the at-most-200-file facts listing are eligible.
Use the exact candidate against its recorded base, including the existing
verified initial-commit/empty-tree behavior. Read Git objects, not checkout paths;
never follow symlinks or submodules. Treat paths literally, with the shared path
validator (including U+061C), NUL-safe listing and no shell interpolation.
Disable hooks, external diff, textconv, filters, config discovery and network
access, following the existing trusted Git environment. Rename identity comes
from the measured entries, not a second heuristic applied to one path.

Approved hard limits: 1 MiB per input blob, 8 MiB of input across a collection,
200 files, 64 KiB and 2,000 lines of patch text per file, 2 MiB retained patch text
per candidate, and 128 KiB encoded JSON per device response. Process files in
stable path order. Apply a 10-second total collection deadline and one collector
per runner; cap unaccepted uploads per attempt and prune them after 15 minutes.
No unbounded subprocess buffering; kill and wait on timeout/overflow. Collection
failure must not fail Engineering or affect merging.

Binary/non-UTF-8 files have metadata only. Large blobs, symlinks and submodules
link out without content. Oversized scanned text patches may end at a complete
line with truncated=true; omitted files get an explicit unavailable result, not
an empty diff. Native retains the file counts and the Amadan action throughout.
Accepted collections are replaced when the candidate changes and expire after
seven days; the task then falls back to Amadan. These display limits are separate
from the Review gate's evidence limits.

## Secret handling

Scan complete bounded before/after blobs before generating or clipping patches.
Use the runner's pinned Gitleaks rules and trusted scanner setup already used by
Preview (`preview_security.go`); repository configs, ignores and inline allow
comments cannot weaken it. Also apply known credential-value and existing token
redaction checks. If a secret is detected, withhold that file's whole diff for
this slice. If scanning fails, times out or encounters an over-limit input,
withhold it as unavailable. Never ship a partially scanned prefix.

The instance independently rechecks the bounded incoming patch with the same
trusted detection rules before persistence; a runner's clean flag is not proof.
Do not store rejected patch bytes, secret matches or raw scanner reports. Audit
identity, digest, outcome and sizes only. This reduces accidental disclosure;
pattern scanning cannot prove arbitrary source text contains no secret.

## Tests and approval points

Test task visibility/revocation, stale candidate races, wrong runner/attempt and
upload replay, literal paths and renames, initial commits, binary/large files,
every byte/line/time cap, interrupted uploads, expiry, and old-runner fallback.
Secrets tests cover added/deleted/context lines, multiline keys, encoded values,
cut boundaries, scanner failure and hostile repository scanner configuration.
Mutate each guard. Add OpenAPI/contract coverage and a perf budget record; native
fake-server tests prove the selected file and candidate reach the endpoint.

Controller decisions before implementation: approve precomputed runner patches
and their storage/retention bounds, allocate the protocol capability, and confirm
whole-file withholding for detected secrets. This note proposes no new copy.


## Implementation refinements

A complete 64 KiB file patch fits a single base64 durable frame under the
256 KiB stream bound. There are no partial unscanned chunks in storage. The
collection hash binds every path, refusal, truncation flag and patch byte; its
matching accepted report publishes the collection transactionally.

Both ends scan in memory with the pinned Gitleaks 8.30.1 embedded default rules,
using a fresh detector, a trusted configuration and no path-based exemptions.
No candidate files configure it. The library logger is disabled. Known-token
checks run on decoded layers too. Full before/after inputs are scanned on the
runner; the instance independently scans each complete patch before storage.

Expired bytes are pruned by the existing sweep and during uploads. An internal
attempt-bound deadline remains on the step to distinguish expiry from an old
runner that never supplied a patch. It is never projected to the Coordinator.
