# File changes, Review and recovery

A historical rewind marker is shown only beside its anchor message in the loaded history window. An offscreen anchor must not move its marker to the latest message. Pending rewind controls remain at the current end.

## Undo, Revert, Rewind

|  | Undo latest turn | Revert this turn | Rewind to here |
| --- | --- | --- | --- |
| Scope | Latest turn on the current branch | One historical turn | Suffix of the source branch after the chosen checkpoint |
| Files | Restored after every file passes preflight | Restored only with no later same-path dependency and a matching digest | Target state projected from the journal, applied under a durable intent |
| Conversation | HEAD and all messages stay | Unchanged | The current branch moves back; its withdrawn suffix is recovery history, not another branch |
| Branch | None created or moved | HEAD stays | The same branch identity and name stay; later messages extend its rewound head |
| Conflict | Any path mismatch blocks the whole operation | No automatic reverse merge | Any unrecoverable item blocks it |
| After | Revert transaction appended; card shows Reverted; Redo when preflight allows | Branch Review folds the revert; Reapply when preflight allows | Original prompt prefilled; no workspace-alignment choice |

Turn cards show the applicable Undo or Revert; user checkpoints open a Restore sheet. Redo and Reapply are new transactions, with no linear redo stack. The transcript offers no branching; Copy conversation is in the conversation's ⋯ menu.

## Shared workspace and same-branch rewind

A conversation branch records a route through messages, not a private filesystem. Fork and retry retain their existing explicit conversation versions; switching them never restores files, pauses tools or asks which files to use. The model receives a current-workspace note and must reread files before editing.

Rewind is a different operation: withdraw the selected prompt and its suffix on the current branch, and restore its recorded file changes when code recovery is selected.

Existing sibling branches and their shared messages remain intact. Withdrawn messages remain in durable recovery storage for Undo and crash recovery, but disappear from branch lists, version navigation, the conversation graph and normal context.

A later message extends the same named branch. Undo and Redo change the withdrawal view on that same branch; their existing message-only semantics are stated explicitly and do not restore files.

Recovery must not overwrite later writes by another branch, another session or a human. A code recovery with an unsafe, missing or conflicting file is blocked before any file or conversation change; conversation-only recovery remains an explicit alternative.

Previews bind the head, target, file states and mode. Duplicate requests replay their recorded outcome; failures roll back and interrupted operations recover before exposure. Existing legacy intents retain their original recovery semantics. Old workspace-alignment flags have no authority to stop a message or tool.

| Acceptance path | Required outcome |
| --- | --- |
| Switch after edits, failed retry, old mismatch flag | Files unchanged; message and ordinarily permitted tools work; stale read baselines cleared on switch. |
| Rewind then send, including first prompt | Same branch identity and name; no withdrawn version offered; current file contents match the confirmed recovery. |
| Sibling shares part of withdrawn history | The sibling and its necessary ancestors survive; only the selected branch is withdrawn. |
| Conflict, stale preview, running writer, archive | No partial conversation or file change; a specific refusal explains recovery eligibility. |
| Undo, Redo, duplicate request, restart during apply | Consistent branch visibility, identity and files; recorded transactions determine the outcome. |

Branch identity is independent of its head message. When two rewinds converge at one checkpoint or ROOT, each ref retains its name and remains selectable by branch id. Undo marks belong to that identity. Selecting by head alone remains compatible for unambiguous legacy clients.

## Sources of truth

1. **Trusted mutators** write, edit, apply_patch, validated adapters
   
   Generic Bash, external writes: no receipt, no turn Undo
2. **Mutation journal** feeds This turn and Branch Review
3. **Git workspace** feeds Unstaged and Staged Review
4. **History planner** reads all three, with the conversation DAG; only the journal authorizes recovery
5. **Durable intent** lock, apply, verify, then HEAD if needed

Bash may run in sandboxes or worktrees. Git shows current changes without proving their turn or granting Undo.

## File window

Files open in preview. Edit autosaves. History lists human and model changes.

| Format | Preview | Edit |
| --- | --- | --- |
| Text, code, Markdown | Rendered | Source, autosave |
| DOCX, PPTX, XLSX | Local engine, full page or slide; text extraction is no substitute | Full edit in the local engine, formulas and structure kept |
| DOC, PPT, XLS | Yes | Saved explicitly as OOXML, never over the original |
| ODT, ODS, ODP | Yes | Original-format export |
| CSV, TSV | Table | Text |
| PDF | Continuous pages, zoom, search, outline, thumbnails | Highlights and free-text notes; 64 MiB limit |
| PNG, JPEG, WebP | Zoom | Crop, rotate, drawing, shapes, text. Conversions create a separate PNG. 64 MiB, 16 million pixels, 16384 px per side. |
| Animated or 16-bit PNG, BMP, GIF, SVG, TIFF | Yes | Read-only; a save never rasterizes silently |
| PSD | Composite and layer list | Read-only until a lossless round trip is verified |
| Audio, video | Local HTML players | Read-only |
| Corrupt, encrypted, oversized, unsupported | Explicit status and download | None |

| Situation | Behaviour |
| --- | --- |
| Switch tabs after editing | Edits persist as local drafts, then write in the background. No Save action or persistent Saved label. |
| Another program changed the file | “File changed by another operation.” The draft stays; inspect the disk version or Save a copy. Never overwrites. |
| Open an old version | The current file's previewer, read-only. Recovery is a new recorded operation that keeps pre-recovery content and can be reapplied. |

**Opening, adapters and engines**

| Topic | Contract |
| --- | --- |
| File reference | Stable project or session ownership plus relative path. Display paths are not credentials. |
| Adapter choice | Extension, type and contents verified first |
| Adapter surface | Receives document content and version only, no disk access. Exposes byte or Blob export, change and error events, destroy. |
| Loading | Large Office and image resources load only for relevant files. KaTeX keeps complete WOFF2 without legacy fallbacks. Budgets: 2 MiB compressed initial transfer, 350 KiB compressed per chunk. |
| Large binaries | Bounded byte uploads or local staging, not chat messages. Size enforced while reading; temporary files cleaned on cancel. |
| Active content | Engine messages validate origin, instance and request ID. Document scripts, macros, active HTML and SVG get no main-window authority. |
| Third-party services | Only by explicit user configuration, with notice that files go there |
| No safe original-format write | Export a labelled copy; never PNG or OOXML bytes under another extension |

| Engine | Role |
| --- | --- |
| [PDF.js](https://github.com/mozilla/pdf.js) | PDF viewer, pinned |
| [ONLYOFFICE](https://github.com/ONLYOFFICE/DocumentServer) | Office editing, local, optional install. Complete servers remain configurable adapters. Candidates compared: [OnlyOffice browser/WASM](https://github.com/agentbridges-ai/onlyoffice-browser), [LibreOffice WASM](https://github.com/LibreOffice/core/blob/master/static/README.wasm.md). |
| `fabric` | Bitmap editing |
| [ag-psd](https://github.com/Agamnentzar/ag-psd), `utif` | PSD and TIFF decoding. ag-psd's colour-mode, text-layer and effect limits mean originals are kept. |
| [Photopea](https://www.photopea.com/api/) | Third-party hosted: never loaded and never sent local files by default |

### Markdown rendering

| Item | Rule |
| --- | --- |
| Raw HTML | Escaped |
| Links | Local references, bare fragments, HTTP(S), mailto. Protocol-relative destinations use HTTPS. |
| Images | Scoped local-file URLs and HTTP(S). Data and executable schemes rejected. |
| Local queries | Never supply authorization parameters; SVG fragments stay separate from disk paths |
| Math | Tokens outside literal code, escaped before typesetting, never restored through raw placeholder replacement |
| Outside this subset | Wiki links, embeds, outline, Agent section attachments |

### Markdown heading navigation

- **Key**: From visible inline heading text: Unicode letters and numbers kept, lowercased, punctuation other than `_` and `-` removed, whitespace runs become `-`. Empty uses `section`.
- **Repeats**: First unused numeric suffix, unique per parse, including collisions with explicitly numbered names. State resets per render.
- **Bare fragment**: Percent-decoded once; searches only the originating article by heading-key attribute, never through a CSS selector. Invalid or missing: no scroll.
- **Cross-file link**: Keeps the fragment through the existing destination parser and authorized opening path
- **Section request**: Ephemeral view state outside `CenterTab`, tab history, snapshots and window-transfer payloads. Holds a unique sequence, physical tab id, expected document identity and fragment.

**Section requests in detail**

- Project-file opens use the resolved destination id, including history-reused tabs. Attachment previews use the resolved file-preview id, not `activeId`, which may remain the chat.
- A rejected auto-open creates no request; an accepted no-section open clears an older one. Close or retarget invalidates it. Consumption compares the sequence, so an older render cannot remove a newer request.
- `PersistentFilePanes` keeps one physical `DocumentWindow` per document identity. A section request picks the active alias as preferred host and never creates a second `DocumentController`.
- The request travels through `FileTabPane`, `DocumentWindow`, `FileViewer`, `TextViewer` as view context, keeping authorization. It switches source mode to preview without discarding dirty bytes and waits for that exact draft or version to render.
- Links in a selected historical version use that version's headings. Attachment paths keep their read-only flag and original session.

| Case | Required result |
| --- | --- |
| Unicode, inline text, repeated headings, code fences | Stable unique keys; only headings participate |
| Two mounted documents share a heading | Bare fragment scrolls only its originating article |
| Cross-file load or repeated same-section request | Survives loading; each sequence scrolls once after rendering |
| History-reused id or chat-active preview | Reaches the actual file pane |
| Two aliases, dirty draft, source mode, selected version | One controller and buffer; correct alias and rendered version navigated |
| Rejected auto-open, no-section reopen, close, retarget, reload | No stale request applies |

### PDF reading and annotations

- **Layout**: Document tab above a flat toolbar; removable 180 px left sidebar with thumbnails and outline; continuous pages. Annotation row is contextual; narrow panels wrap controls without covering text.
- **Controls**: Page navigation, fit width, fit page, numeric zoom, selection, in-document links, highlighted search. 32 px high, application font at 13 px. Only implemented tools appear.
- **Colour**: Application theme tokens. Reference: ink #202124, toolbar #27272a, canvas #151517, paper #ffffff, divider #414145, focus #4a90e2.
- **Stylesheet**: Upstream viewer CSS is scoped to `[data-pdf-reader]`, root variables included, so generic names cannot change the shell
- **Copy**: Layout line breaks joined; paragraph breaks and punctuation kept; CJK joined without spaces; ordinary hyphens kept; soft hyphens removed. Clipboard only, text layer only. A visible checkbox keeps original breaks.
- **Annotations**: Standard PDF highlights and free-text notes, saved through the `DocumentController` rich-editor lease, durable drafts and revision checks. Draft-byte updates do not recreate the viewer or lose undo. History and attachments are read-only.
- **Disabled**: PDF scripting and external upload. Out of scope: original-text editing, OCR, page surgery, format conversion.

### PDF runtime

- **Decoder**: PDF.js 6.3.289, module and worker from `legacy/build`, served from same-origin `/document-assets/pdfjs/`. The manifest records version and distribution. Local CMaps, fonts, WASM and licence inventory are kept.
- **Why legacy**: The compatibility code must load in the page and the worker; a page-only polyfill cannot repair the worker. The modern build needs `Uint8Array.prototype.toHex`. Upstream: [browser support](https://github.com/mozilla/pdf.js/wiki/Frequently-Asked-Questions#faq-support).
- **Shell policy**: `connect-src 'self' blob:` lets decoders read retained versions through object URLs. External HTTP and WebSocket stay blocked; blob scripts, eval, objects and third-party frames stay off.
- **Viewer reference**: [viewer source](https://github.com/mozilla/pdf.js/tree/v6.3.289/web), [PDF Expert features](https://pdfexpert.com/features). [EmbedPDF](https://www.embedpdf.com/docs/react/viewer/getting-started) is not used: a second rendering engine adds nothing for reading, highlights and notes.

### Office install and loading

| Topic | Behaviour |
| --- | --- |
| Default builds | App, runtime and Python builds omit Office assets and do not download them. PDF is independent. |
| Choice | Opening an Office document checks local availability only. If missing: formats, about 699 MiB, local processing, ONLYOFFICE licence, Install and Cancel. Cancel downloads nothing. |
| Install | Owner-authenticated local-origin POST; fixed release URL, pinned archive SHA-256. Bounded download and extraction, unsafe paths and links rejected, full manifest verified, atomically published to the profile cache. Concurrent requests share one install. |
| Failure | Previous pack stays selected; temporary downloads removed |
| After install | The current worker serves it without restart and the document opens. Closing the document stops its requests; a requested install may finish. |
| Older packs | Profile resources stay usable; App-bundled resources are no longer selected. Development staging is a standalone command that ordinary builds ignore. |
| Isolation | Separate origin, resource-tree GET and HEAD only; no main API, authentication or WebSocket. Both pages validate origin, instance, request. Macros off. Remote deployments without a separate origin disable editing. |
| Loading | Full-size surface; nothing is drawn over it while resources load and the document opens. Only an install the user asked for shows a centered, theme-aware overlay with its progress, no simulated percentage. A startup error shows with Retry. |
| Teardown | Pinned mount and activate API, so closing destroys a pending host. An AbortSignal cancels availability and activation under a bounded deadline. Failed instances never attach to the controller. |
| Not provided | Generic extension registry, automatic updates, uninstall controls, third-party upload |

### Back and Forward

Each tab keeps its own page history: Folder A, subfolder B, file 1, file 2. Opening somewhere new after Back replaces forward history. Folders restore path, expansion and scroll; files keep autosave.

Only explicit positioning, search navigation or restoration moves the viewport; list paging, background refresh and size updates do not. Navigation history never mixes with file-version History, writes to disk or polls.

## Version lifecycle

| Situation | Stored | Shown |
| --- | --- | --- |
| Repeated edits, one turn | Original before; after updated. Records replaced only after the new version commits. | One net change |
| Interrupted save | Pending-confirmation marker. Success not inferred; after not invented from disk. | Incomplete, no exact recovery; never “no changes” |
| Cancelled attempt, confirmed uncommitted | Marked aborted | No change |
| Corrupt or unsupported manifest | Kept; no empty history created, nothing overwritten | Explicit error. Only a truly absent manifest means no records. |
| Reopen session | Same durable records; never script output or memory | Same files, Undo or Reapply |
| File changed later | Unchanged | Recovery blocked, later edits kept |

**Save order and publication**

1. Write each before and after as an independently complete file; verify it; fsync the version directory.
2. Publish the manifest. A failed update leaves referenced content intact; a failed attempt never overwrites published versions.
3. Retry rereads the current file as before only after explicit cancel of an unsuccessful attempt. A success keeps the turn's first before.

- Regular-file snapshots compare descriptor metadata before and after reading, and path metadata before opening and after reading.
- Device and inode must agree; metadata from different OS APIs is never compared as if alike. Any change aborts publication.
- The path observation supplies the stored mode.
- Legacy migration on Windows opens staged files writable before flushing and keeps the source until publication succeeds.

Old manifests and `blob_ref` stay readable without bulk rewrites. Lost history is not reconstructed. OS crashes and programs ignoring locks may need manual recovery: evidence is kept, uncertain overwrites refused.

**Publishing documents: `write(file_path, source_path=...)`**

| Topic | Contract |
| --- | --- |
| Arguments | Exactly one of `content` or `source_path`. The source is a local regular file under read permission, up to 64 MiB. Identical paths, directories, links and oversized or unreadable sources fail before any change. |
| Target checks | Targets keep write authorization, read baseline and approval fingerprint. Source and target fingerprints join approval waits and are rechecked before publication. |
| Write | Bytes go to a complete temporary file in the target directory, then replace. Failure cleans up and keeps the target. Raw bytes, never text-converted. |
| Locks | Advisory locks serialize cooperating writers only. Windows closes handles lacking delete sharing before replacement and revalidates; no OS conditional replace. |
| Read first | Models read originals, then generate staged versions. Binary reads return type and byte count. New files need no prior read. |
| Callers | Generators call this path; text tools keep write, edit and apply_patch and share prepare, commit and abort. `CheckpointStore` owns state; Review and summaries are projections. |
| Not provided | Word tracked changes, PPT visual diffs, Office semantic diffs, remote stores (these need conditional writes and verifiable version IDs before claiming recovery), full-disk scans, polling, plugin registry |

**Human edits, autosave and editor lifetime**

| Topic | Contract |
| --- | --- |
| Shared path | Human and model writes share version validation, complete-file publication and immutable before and after. `project_file_write` idempotency records hold results and fingerprints, not versions. |
| Attribution | Human records use `actor=user`; model records link the real session and turn. No fabricated chat turns; human history never becomes a sidebar session. History aggregates by file; turn Review keeps attribution. |
| Retention | Human project edits belong to projects, model records to sessions. Aggregate indexes reference versions without copies. Archived sessions stay readable. Permanent deletion removes owned versions and caches must not redisplay them; Memory sources show “Original session deleted” or lose links. Project files and human history survive chat deletion. Moved projects recover by current location; offline access is read-only. Legacy history backfills in bounded batches; unverifiable ownership is unavailable. |
| Autosave | Editor undo handles immediate changes. Drafts persist first; files publish after a short coalescing window, never waiting for a history period. Each publication validates the read revision; retries are idempotent; late responses cannot overwrite newer drafts. Failures keep drafts with a retryable error and do not close tabs. |
| History period | Continuous editing about five minutes apart. Switching documents, ending editing or recovery also closes a period. Restart reads records, never current files. |
| Rich editors | Independent of tabs: views hide while exporting engines live, and engines release only after the newest content reaches durable drafts. Office iframes survive React remounts and DOM moves. Rename and recovery await final export; failure keeps editor and draft. Preview and edit share one instance; history instances cannot write. Rename disables editing and reopens the new path after success. |
| Closing | Never waits: the tab goes at once and the pane stays mounted out of sight until the export is saved. A native editor is exported only for changes it reported: closing, refreshing or replacing one nobody changed never writes the file. Edits not yet exported are asked about first: Save, Don't Save or Cancel. |
| Incomplete reads | An engine that reads a file with slides or sheets missing would, on export, write back only what it kept. So a writable PPTX or XLSX editor is not bound to the document until one export, made as it opens and never kept, lists as many slides or sheets as the file (`apps/web/lib/documents/office-fidelity.ts`). One that lists fewer is not opened: an error names both counts and the file is left as it is. |
| Measured | ONLYOFFICE read a 10-slide deck written by python-pptx as 0 slides and, on close, replaced the file with an empty one |

## Mutation journal

One manifest per turn, under `CheckpointStore` (`openprogram/state/store/snapshot/checkpoint/`). Each file entry:

- **`path`, `operation`**: `create`, `modify`, `delete`, `rename`
- **`before`, `after`**: `{kind: "regular", digest, blob_ref, mode, size}` or `{kind: "absent"}`
- **`status`**: Prepared, committed or aborted, with `prepared_at`, `committed_at`
- **`stats`, `diff_state`**: Lines added and removed, binary; available, large, binary or timeout
- **`recoverability`**: Exact or unavailable, with `unavailable_reason`
- **`mutation_sequence`**: Durable and monotonic; multi-turn folding uses this, not DAG order

**Invariants**

| Item | Invariant |
| --- | --- |
| Prepared, committed | Prepared persists before the write; committed only after confirming the after state. If preparing fails, the mutator stops before touching disk. |
| `absent` | Absence was confirmed. A baseline read failure is `recoverability=unavailable`, never absent. |
| `unavailable` | Only for journaled mutations whose size or type policy omits blobs, never to hide journal failures |
| Folding | Same-file edits in a turn fold to net first-before to last-after; rename keeps lineage. Regular before and after both keep blob refs. |
| Paths | Recanonicalized at capture, plan and apply; parent chain, leaf lstat, device, inode and link count are checked with validated handles or no-follow primitives |
| Revert, Restore, Reapply | Also transactions; originals are immutable. Current branch folds the active lineage only. |
| Boundaries | Each prompt defines `before_turn`, assistant completion `after_turn`; the UI names the restored boundary |

### Four Review scopes

| Scope | Source | Contains | Recovery |
| --- | --- | --- | --- |
| This turn | Committed change sets of an origin turn | Parent's change set plus owned children, each with its own producer turn, deduplicated, actors shown | Undo or Revert: exact receipts across the closure, terminal actors, matching digests |
| Unstaged | Git working tree against the index, plus `git ls-files --others --exclude-standard` | Changes not yet staged, honouring `.gitignore` | No turn Undo; hunk Revert; Stage. Non-Git: unavailable. |
| Staged | Git index against HEAD | Changes staged for the next commit | No turn Undo; Unstage. Non-Git: unavailable. |
| Branch | Active-lineage journal projection | All turns and explicit revert, rewind, reapply; no siblings or external writes | From a specific turn or checkpoint; no one-click branch Undo |

## Rewind

One plan, one transaction. WebSocket `phase` defaults to `plan`; `apply` needs `plan_hash` and `idempotency_key`. Plan statuses: `ready`, `unavailable`, `blocked`, `stale_plan`, `error`. Intent ends `committed`, `rolled_back`, `recovery_required` or `aborted`.

| Phase | Rule | On failure |
| --- | --- | --- |
| Resolve lineage | Predecessors from HEAD to the target non-root user turn; subtrees only through explicit ownership | Off the active branch: rejected |
| Target state | Each prompt that starts a turn has a checkpoint, `.file-recovery/<session>/checkpoints/<user_msg_id>.json`: every tracked path to a state, content in shared `blobs/<sha256>`. A path it does not list takes the state recorded just before its first later edit. A prompt with no checkpoint (older sessions, steered messages) folds the journal on read, with no data rewrite. | A failed capture never blocks the tool; the path is `unavailable`. A prompt with no usable backup (`evicted`, `journal_gap`, `no_checkpoint`) reports `unavailable` for code modes; Conversation only stays. |
| Plan rows | Each target against the file on disk: `restore`, `delete` or `skip` with a reason and +A −D (1 MiB per file, 3 s budget). Only paths written by the withdrawn turns are eligible. Later changes outside that range are protected, including shell, manual, hunk Revert and Undo changes. Planning writes nothing and runs no crash recovery while a run owns the session. | Any skipped row blocks the entire code recovery before mutation: `other_session` (another session started or finished a trusted write after the target state was read; per-path index of each session's newest write under `mutation-locks/last-writers/`), `changed_since_edit` (the file no longer matches the recorded writes, or those writes have an intervening change), `unsafe_path`, `parent_missing`, `no_backup`, `changed_while_reading`. A running owned job blocks with `job_running`. |
| Other branches | A checkpoint names its turns (`turn_ids`); a file's state before a turn's first edit is recorded in that turn's checkpoint. The target is the listing read earliest in the range. For a path another prompt's turn also wrote, it is the earliest listing read after that write and before the range's own first write (`first_sequence` in the turn's journal record). A write a committed rewind took back (`restores_through` on its intent) is not counted. | That write is later than the range's own first write, or no listing was read between the two: `changed_since_edit`. See [two branches](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/control.html#branch-rewind). |
| Prepare intent | Holding the run slot, save the current content of each planned path as a blob, so a change no journal saw can still roll back; persist plan id, expected head, before and target images, mode, skipped rows; idempotent | Plan rebuilt under the workspace lock; a different hash returns `stale_plan`, zero writes |
| Apply | Workspace lock; per-action state persisted; atomic replace; delete only on matching digest | Rollback only if the digest still equals what this transaction applied; otherwise `recovery_required`, external content kept |
| Branch | Move the current branch with expected-head compare-and-set. The branch identity, withdrawal visibility and recovery metadata commit together. A pre-first-turn target uses the persistent ROOT. | Files restored per intent; source and active branch stay |
| Finalize | Append transaction and navigation events; old nodes not marked; writer epoch advances so old tasks cannot write back | Startup finishes or rolls back open intents, never guesses |

Multi-file recovery is not one filesystem atomic operation. The guarantee comes from durable intents, rollback staging, per-file atomic replacement and restart recovery. A preflight over thousands of files pages its conflicts; once applying, it finishes or rolls back.

| Mode | Files | Conversation | Next turn |
| --- | --- | --- | --- |
| Code and conversation | Restored | Current branch rewound after commit; prompt prefilled; withdrawn messages remain only as recovery history | Normal |
| Conversation only (`conversation`) | Kept | Current branch HEAD compare-and-set to the message before the target; later messages are withdrawn, not exposed as a branch | Told files were not reverted; send not blocked |
| Code only (`code`) | Restored | Kept; the transaction compares and sets HEAD to itself | Told files went back without the conversation |

### After a rewind

| Item | Rule |
| --- | --- |
| Rewind edge | Session meta `rewind_edges`, written with the HEAD move. Marks computed for the current chain: `pending` until the next send, then `back`; `forward` after Undo. |
| Undo, Redo | Compare-and-set HEAD along the edge while holding the run slot. Messages only. |
| Note to the model | Session meta `pending_rewind_note`, read once when the next turn builds its system prompt: `conversation_only`, `restored`, `branch_kept_files`, `partial` (an earlier conversation-only rewind still warns about files), `code_only`, `undo_kept_files`. |
| Read tracking | Rewind, Undo and Redo drop the session's read baselines; the next edit reads the file first. |
| Copying a session | `branch_session` carries checkpoints, blobs and write provenance for the copied messages and records source and mutation sequence in `origin.json`, so the source's earlier writes do not count as another session. |
| Retention | 100 turn directories and 100 checkpoints per session, counted separately. `intents`, `intent-locks`, `checkpoints`, `blobs` are never turn directories. Removed turn ids go to `evicted-turns.json`; a blob goes when no kept checkpoint or open intent refers to it. |

**Recovery objects**

| Object | Purpose |
| --- | --- |
| Branch | Stable id, HEAD, `head_version`, writer epoch; sessions store `active_branch_id`. Explicit Rewind moves the current branch HEAD backward; normal branch navigation never restores files. |
| Checkpoint | The recovery destination, without duplicating file lists |
| Change set | Producer and origin turn, actor. Cards group by origin and keep producers. |
| Plan | Read-only preview; plan hash prevents preview-to-confirm races |
| Intent | Confirmed durable record: `idempotency_key`, `plan_hash`, `expected_head_id`, `target_head_id`, source and target branch, actions. Restart never infers progress from directories. |

## Branches and actors

| Scenario | Meaning | Files |
| --- | --- | --- |
| Branch from a result | Target branch created and activated; source HEAD unchanged | Unchanged, “Files stay as they are” |
| Fork into a new task | Source task and HEAD kept; conversation history copied | Files stay shared unless the user explicitly requests filesystem isolation. |
| Checkout sibling | Selects another conversation lineage, without changing files or demanding file alignment | All ordinary branches share the current workspace. Clear read baselines and tell the model that files were not restored. Reads and writes follow normal permissions and current-file checks. |
| Owned child | By relation, `creates_agent`, origin turn; own producer and change sets | Running blocks parent restore. Finished joins the closure. |
| Independent actor | Background terminals, job runners, channels, schedulers | Running blocks same-workspace restore; writer epoch stops old write-backs |
| Existing peer, cross-session | Linked, not owned | Not modified; listed in impact; overlap blocks code recovery |
| Worktree child | Independent state | Parent Undo or Rewind never touches it; a merge is its own transaction |
| Sibling branch | Outside Rewind | Journals unchanged; current files shared on return |

**Resume, Archive, Purge**

| Operation | Contract | Never |
| --- | --- | --- |
| Resume | Unknown session: not found. Open transactions recover before real node ids, branch and revision load. | Treat an unknown id as new or fabricate ids |
| Empty branch | HEAD is the persistent ROOT. Web, TUI and CLI share one branch result. | Pick another tip automatically |
| Archive | Refs only; nodes, journals and checkpoints stay | Delete shared ancestors |
| Purge | Reference-counted, explicit, exclusive objects only | Delete leaves one by one or bypass references |

## Conflicts and unavailability

| Situation | Result |
| --- | --- |
| Later edit to the same file: Revert | No reverse merge |
| Later edit to the same file: Rewind | Later changes outside the withdrawn range block the complete code recovery; conversation-only remains available |
| Plan changed after confirmation | `stale_plan`, zero writes |
| Running turn or background task | No confirmable plan |
| Symlink, hardlink, special file | Not followed or overwritten; path and reason shown |
| Blobs garbage-collected | Review readable, code restore off |
| Large file, no blob | Path and size exact; line counts unknown; no Undo |
| Non-Git workspace | Journal scopes work; Unstaged and Staged unavailable |
| Reapply | Needs post-revert digest, no later same-lineage mutation, after blobs |
| Crash during apply | Rolled back, or `recovery_required` if rollback would destroy external writes |
| Exact edit to ignored or authorized outside path | Journaled, Undo works, not in Unstaged |
| Ignored background log growth | Excluded by design |
| Databases, APIs, deploys, installs, Git index, processes, network, unrecorded Bash | Outside Restore; confirmation lists possible repeated effects |

## Interface

| Place | Shows | Does | Never |
| --- | --- | --- | --- |
| Assistant turn card | File count, net additions and deletions including zero, first three files, about 40 px header, 19 px `FeatherIcon`, 2.5 px two-colour proportion bar. Basenames emphasized. At 420 px or less: “N files”. | Latest: Undo, then Redo. Historical: Revert, then Reapply. Every turn: Review. Header shows executable actions; unavailable and blocked explanations in the footer. | Header chips, disabled badges, product branding |
| User message | Restore checkpoint | Impact sheet, named boundary, default code and conversation | Restore on click |
| Conversation ⋯ menu | Copy conversation | History only; files stay | Implicit restore |
| Changes tab | Four scopes; file list and single-file diff; source labels; counts over the full filtered result | Unified or side-by-side, line comments, Open file, Reveal. A scope or filter change clears cursor, selection and diff. | Turn Undo in Workspace; client-only filtering |
| Impact sheet | Prompt, turn and file counts, branch result, mode, conflicts | Confirm; cancel has no effect | Force while blocked |
| Branch switch | Conversation changes; files stay | Continue talking and working on current files | File-alignment prompts or tool restrictions caused by branch history |

## File queries

Project explorer and Review read server snapshots. The order is fixed: resolve owner, snapshot, filter and sort on the server, paginate, render one page.

| Query | Source | Page | Goes stale on |
| --- | --- | --- | --- |
| Directory | Project root by `project_id`; normalized, root-relative, no traversal or symlink escape | Directories then files, by path; 100 per page | Directory version, ignore rules, project, path, sort |
| Project search | Same root and rules, independent of expanded nodes; names or relative paths | Filtered, ranked, then paged | Project switch, expired snapshot, root version |
| Review scope | Journal, or Git HEAD, index, worktree | Server filters by category, path, operation, diff state; 100 per page; totals cover the full result | Scope, message, filter, sort, snapshot, candidate or identity change |
| Review file diff | Paths from the same snapshot; recorded blob pairs | 200 lines or 256 KiB per request | Snapshot, candidate, identity or blob pair change |

Stale answers are `STALE_SNAPSHOT` or `STALE_CURSOR`; clients restart from page one.

**Cursors and Workspace snapshots**

- Cursors are opaque and valid only for the same snapshot, owner, query kind, filter and sort. Offsets, path anchors and cross-project tokens are rejected. Directory, search, Review list and diff cursors are not interchangeable.
- Snapshots keep a stable candidate order. Later pages never rescan. Capacity and TTL eviction report stale.
- A Workspace snapshot fixes staged, unstaged, untracked and rename or delete paths by relative path, pinning HEAD base, index blob and worktree identity, and old and new paths. Diffs render from that pair, never a later `git diff`.
- Before later pages or diffs: status vector, index tree and no-follow worktree identity are reread. Any change is stale.
- The worktree side compares as Git does: when `text`, `eol` or `core.autocrlf` clean line endings, CRLF becomes LF first (for `auto`, only when the indexed blob has no CR), so a CRLF checkout of an LF blob shows only edited lines.
- Hunk revert edits the file in its own line endings.
- Snapshot blobs share Review quotas; missing or expired blobs report stale, never approximate from the worktree.

### File WebSocket requests

| Rule | Contract | Never |
| --- | --- | --- |
| `request_id` | Client UUID on every browse, read, write, rename, copy, delete, reveal and Review request; echoed on every result | Match by type, path or arrival |
| Response check | Sole pending key, plus action, project, session, snapshot, target. Unmount or new query forgets old keys. | A global queue |
| `idempotency_key` | Separate key on side effects, with optimistic-lock conditions | Treat a new `request_id` as a new write |
| Errors | `error_code`: `STALE_SNAPSHOT`, `NOT_FOUND`, `CONFLICT`, `INVALID_REQUEST`, `IDEMPOTENCY_KEY_CONFLICT`, `OUTSIDE_PROJECT`, `TOO_LARGE`, `RECOVERY_REQUIRED` | Apply unidentified frames |

**Write idempotency**

| Topic | Rule |
| --- | --- |
| Record key | Owner (profile and project), action, key |
| Fingerprint | Action, owner, canonical payload (normalized paths, parameters, digests), preconditions (mtime or digest, paths, overwrite conditions, directory versions). `request_id` is excluded. |
| Record | Moves from `in_flight` to `completed`, `conflict` or `error`, with `operation_id` and the terminal result, claimed in the same durable scope as the mutation |
| Same key, different fingerprint | `IDEMPOTENCY_KEY_CONFLICT`, zero writes |
| Same fingerprint, in flight | Binds the operation until the deadline, then reports in flight; clients retry that key only |
| Same fingerprint, completed | Replays without re-executing |
| Restart | Recovers or classifies in-flight records before replay. Expiry never deletes them or replays a different fingerprint. |

### Cache and drafts

| Store | Limit | Rules |
| --- | --- | --- |
| Read cache | 64 entries, 16 MiB, LRU; keyed project, path, revision | Successful complete reads only; no dirty text |
| Text drafts | 32 entries, 8 MiB | IndexedDB `openprogram-file-drafts`, stores `drafts`, `project_index`; never evicted by LRU |
| Binary document drafts | 32 entries, 64 MiB each, 256 MiB total | Stores `document_drafts`, `document_draft_metadata`; per-file Blobs |

**Draft rules**

| Topic | Rule |
| --- | --- |
| Key | Project plus canonical path; never shared across projects |
| Contents | UTF-8 text, baseline bytes, revision, mtime, update order. Quotas count `TextEncoder` bytes of draft, baseline and metadata. |
| Kept | Reload, unmount, project switch and cache eviction keep dirty drafts. Server changes keep them in conflict state, saving against the original baseline. |
| Never resets buffers | Tree refresh, Review changes, registry gaps, background responses |
| Create, update, rename, discard | Draft and index in one transaction |
| Quota | Over quota: no writes. Budget is checked before accepting input; full storage offers save, revert, export or discard. On `QuotaExceededError` the last durable version stays and growth pauses. |
| Rename, copy, delete | Rename moves keys atomically; copy shares none; failed operations change nothing. Deleting a file with a draft requires save, export or discard. |
| Project cleanup | Waits for an explicit command, which does not exist yet; absence from `list_projects` is not authorization. Startup rebuilds a missing index by scanning, without deletion. |
| Privacy | This origin's IndexedDB only, outside logs, telemetry, model context, WebSocket and sync. Recovery never uploads automatically. |

## Limits, security, parity

| Topic | Rule |
| --- | --- |
| Turn finalize | Cost depends only on changed paths. Summaries persist and return with transcripts; cards mount at most 20 rows and no diffs. |
| Diff budget | Over budget returns timeout metadata, never blocking the Agent or approximating |
| Recovery blobs | Content-addressed, deduplicated, local-user only, outside session Git. |
| GC | Never collects pinned checkpoints, active tasks, unresolved conflicts, open intents or branch-referenced checkpoints |
| Secrets | Blobs outside logs, telemetry and model context. Session deletion cleans unreferenced blobs. External paths need authorization at capture and recovery. |
| Older sessions | Read as they are. Journal gone or discontinuous: code cannot be restored, Conversation only offered |
| TUI, CLI, App, Web | Same server plan before mode selection and confirmation, same idempotency; UI renders server impact without recomputing |
| Line comments | Bound to change set, blobs, side, hunk and line. Scope or recovery changes mark them stale. |

**Modules**

| Module | Does | Does not |
| --- | --- | --- |
| `openprogram/interfaces/server/ws_actions/files/` | Root authorization, listings, search, reads, mutations; validates ids and snapshots | Review computation, browser cache |
| `openprogram/interfaces/server/ws_actions/turn_files/` | Review scopes, filtered pages, snapshot-bound diffs | Project search |
| `openprogram/runtime/conversation/rewinds/revert.py`, `rewind.py` | Single-turn and multi-turn transactions | Git reset or revert; those keep separate entries |
| `apps/web/lib/net/ws/ws-request.ts` | Request ids, pending registry, timeouts, response checks | Match by type |
| `apps/web/lib/files/files-shared.ts` | Bounded read cache, drafts, invalidation | Review pages, socket listeners |
| `FileTree`, `FilesPage` | Server pages and search results | Scan loaded nodes as search |
| `ReviewTabPane` | Scope, filter, snapshot, cursor, selection | Current-page filtering |
| `FileTabPane` | Buffers, conflicts, draft lifecycle | Direct turn diffs; comparisons open in Review |

**Compared with Claude Code and Codex**

| System | Confirmed | Taken | Not taken or unknown |
| --- | --- | --- | --- |
| Claude Code [checkpoints](https://code.claude.com/docs/en/checkpointing) ([SDK](https://code.claude.com/docs/en/agent-sdk/file-checkpointing)) | Per prompt, tracks Write, Edit, NotebookEdit, not Bash. Restore code, conversation or both. Other subagent changes not restored except foreground `context: fork`. Non-regular paths skipped with warnings. 100 per session; cleaned by `cleanupPeriodDays`, default 30. | Prompt checkpoints, separate options, explicit unavailable | We block or roll back on any path failure; skipped paths cannot succeed |
| [Fork](https://code.claude.com/docs/en/sessions), [VS Code](https://code.claude.com/docs/en/vs-code) | `/branch` copies conversation only | Explicit conversation Branch and source-preserving Fork share current files; worktree isolation is a separate explicit action | Undisclosed reuse of current files after fork |
| [Desktop](https://code.claude.com/docs/en/desktop), [Web](https://code.claude.com/docs/en/web-quickstart) | File list and single-file diff, line comments; Web also Create PR | Separate Review, on-demand diffs, line feedback | Branding, dimensions, PR controls. Review code on Web unconfirmed. |
| [Codex turn diff](https://github.com/openai/codex/blob/main/codex-rs/core/src/turn_diff_tracker.rs) | In-memory aggregator of exact deltas for the current turn; inexact data invalidates it | Exact deltas as attribution; we add durable receipts and blobs | A durable Undo journal is not claimed for Codex |
| [Codex history](https://github.com/openai/codex/blob/main/codex-rs/app-server-protocol/src/protocol/v2/thread.rs), [backtrack](https://github.com/openai/codex/blob/main/codex-rs/tui/src/app_backtrack.rs) | `thread/fork` copies history; `thread/rollback` deprecated; `thread/revert` conversation only | Source-preserving forks, immutable history | Unpublished per-turn file Undo unknown |
| [Codex Git](https://github.com/openai/codex/blob/main/codex-rs/tui/src/get_git_diff.rs), [review](https://learn.chatgpt.com/docs/code-review) | Last turn versus Git; Unstaged, Staged, Commit, Branch; multi-repo; `--exclude-standard` | Workspace sub-scopes, ignored-file exclusion | Git Discard is not Restore |
| [DeepSeek JSONL](https://github.com/deepseek-ai/deepseek-harness/blob/c291e7961a515f6d7af9304e7fd1d257929aef26/packages/session/session-persistence-jsonl/src/index.ts), [repair](https://github.com/deepseek-ai/deepseek-harness/blob/c291e7961a515f6d7af9304e7fd1d257929aef26/packages/core/session/src/repair.ts), [fs-local](https://github.com/deepseek-ai/deepseek-harness/blob/c291e7961a515f6d7af9304e7fd1d257929aef26/packages/fs/fs-local/src/index.ts) | Synced temp files, exclusive publish, directory sync, corrupt versus missing; interrupted tools marked unknown; locking and version conditions without full-file undo | Integrity and interruption principles | Session-log recovery is not file recovery |
| [Codex shell snapshot](https://github.com/openai/codex/blob/main/codex-rs/core/src/shell_snapshot.rs) | Staging, verification, replacement of shell environments | The staging pattern | It is not document versioning |

Neither public reference guarantees external-concurrency rules, multi-file atomicity, digest preflight or crash consistency. Complete preflight, workspace locks, durable intents, rollback staging and crash recovery are OpenProgram's.

## Acceptance

| Area | Boundary | Must hold through public entries | Excludes |
| --- | --- | --- | --- |
| Journal | `programs/tools/files/`, turn finalize, checkpoint store | An existing file over 5 MiB is not new on first edit; ignored Bash logs stay out; failed edits leave no receipt | Review UI, user Git |
| Undo, Revert | `conversation/rewinds/revert.py`, workspace lock, intent | Later same-file edits: zero writes. Mismatched digests prevent deletion. Mid-operation I/O never partly succeeds. | Multi-turn HEAD moves |
| Rewind | `conversation/rewinds/rewind.py`, head API, intent recovery | One file across three turns; file failure keeps HEAD; siblings unaffected; stale plans write nothing | Compaction, DAG schema |
| Review | `turn_files/`, metadata, center tab, card | History does not query per message; Workspace excludes ignored files; one bounded diff mounted; consistent provenance. Plain replies mount no card; empty hides; failures retry. | Third pane, new window |
| Shared workspace, ownership | Checkout, active-lineage fold, ownership | Switching permits normal work on current files, with rereads before edits. Running owned children block parent restore; finished ones join. Peers and worktrees untouched. | Workspace cloning |
| Query snapshots | `files/` query, `FileTree` | Search finds unexpanded files. Directory changes after page one cannot enter old cursors; cross-project cursors rejected. Concurrent create or rename restarts in stable order. | Full-text search, layout |
| Request identity | File dispatch, `ws-request.ts`, idempotency | Out-of-order responses reach the right caller. Missing `request_id` rejected. Retries replay; different fingerprints conflict. | Non-file protocols |
| Cache, drafts | `files-shared.ts`, IndexedDB, tab lifecycle | Only clean LRU entries evicted. Dirty drafts survive reload, tab and project changes. Quota failure keeps old drafts atomically and shows a notice. | Collaboration, remote sync |
| Filtered Review | `turn_files/`, `ReviewTabPane` | Categories cover all pages. Changes invalidate cursors and diffs. Later index or worktree changes report stale. | New fact sources |
| Single entry path | File module call graph | No global queues, id-less actions, direct `turn_file_diff` UI calls or legacy fallbacks | Hidden compatibility switches |
| Documents | `write`, sessions, history | DOCX and PPTX versioned; byte-identical undo and reapply; external changes conflict; failed writes keep targets; text writes still valid | Office diffs |
| Each format | `FileViewer`, `DocumentWindow` | Real files, not fabricated binaries: edit, write back, reopen, recover. Concurrent edits, interrupted writes, corruption, oversized files, cancel, offline, project moves, legacy history. | Partial-format success |
| PDF | Under the real shell policy | Nonblank selectable pages, clipboard cases, sidebar, zoom, search, read-only history, annotations persisted and read by a separate decoder, failure retention, external fetch refused, same checks without native `toHex` and `Math.sumPrecise` in page and worker | A permissive harness is not installed-App evidence |
| Crash | Every intent phase | Ends committed, rolled back or per-path `recovery_required`; never false commit or external overwrite |  |

## Implementation status

| Item | State |
| --- | --- |
| Built | Journal, Undo, Revert, code-and-conversation Rewind, three Review scopes, query snapshots, request identity, durable mutations, bounded cache, drafts, unified file window, History, format adapters, optional Office install, document publication |
| PDF | Reader, annotations and runtime compatibility built |
| Markdown | Rendering and heading navigation built; installed-App acceptance pending |
| Not built | Project unlink and its draft cleanup; Office semantic diffs; remote conditional storage |

[Chat turn visual specification](https://fzkuji.github.io/OpenProgram/docs/reference/design/ui/chat/chat-turn-visual-spec.html)

Shared workspace and same-branch rewind are implemented. Independent specification and quality reviews and the affected verification suite pass.
