Skip to content

checkpoints: zpaq backend + /redo end-to-end - #299

Merged
FMXExpress merged 3 commits into
mainfrom
claude/zpaq-undo-redo
Jun 16, 2026
Merged

FMXExpress merged 3 commits into
mainfrom
claude/zpaq-undo-redo

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Vendors the Xelitan Free Pascal port of libzpaq 7.15 and wires it into a new cbZpaq checkpoint backend, finally giving PasClaw real /redo alongside /undo. Storage is one streaming archive per session (compressed) plus a JSON journal of turn → archive-index mappings + a redo stack.

Two commits

  1. Foundation — make get-zpaq vendor target, PasClaw.Checkpoints.Zpaq wrapper (Append / List / Extract), round-trip tests. Skips with exit-0 when the vendor isn't on disk.
  2. Backend + /redo — full cbZpaq storage layer, dispatch in PasClaw.Checkpoints, RedoTurns + CanRedo public API, TUI wiring in both variants, end-to-end tests, docs.

Design highlights

  • Backend dispatch. InitCheckpoints picks cbZpaq when vendor/zpaq is on disk and the session is fresh / already-zpaq, else falls back to the original cbLegacy blob-tree backend. Both keep working side-by-side; no migration of old session dirs.
  • /redo via redo stack. UndoTurns snapshots the current state of every touched path into the archive before rewinding, then pushes the bundle onto redo_stack in index.json. /redo pops bundles and extracts. The first real SnapshotBeforeWrite after an undo clears the stack (standard editor semantics; /redo itself doesn't trigger snapshot, so undo / redo / undo / redo cycles cleanly).
  • KeepLast honoured under both backends. Zpaq mode prunes the oldest turn records from index.json at BeginTurn; archive segments stay on disk (no compaction yet — punted; vendor doesn't expose journaling-format compaction).
  • Carve-out preserved. Files the model created in a rewound turn are left in place — same as today's legacy semantic. Fixing this needs a post-write snapshot path and is deferred.
  • Compression tier. LZ77 method 1 on the hot path. Higher tiers (2–5) save more disk at higher CPU cost; tune via PasClaw.Checkpoints.Zpaq.ZpaqDefaultMethod.

Files

Makefile                                          # get-zpaq target, -dPASCLAW_HAVE_ZPAQ when present
src/pkg/checkpoints/PasClaw.Checkpoints.pas       # +TCheckpointBackend, cbZpaq impl, RedoTurns
src/pkg/checkpoints/PasClaw.Checkpoints.Zpaq.pas  # new: wrapper over the vendored port
src/pkg/json/PasClaw.JSON.pas                     # +TJsonArray.Delete (FPC + Delphi)
src/pkg/tui/PasClaw.TUI.pas                       # /redo slash in both TUI variants
src/tests/checkpoints_zpaq_tests.pas              # new: wrapper round-trip
src/tests/checkpoints_redo_tests.pas              # new: end-to-end undo/redo cycle
docs/checkpoints.md                               # new: backend selection + index.json schema

Test plan

  • make test-checkpoints — legacy backend, 100% passes (KeepLast still prunes under zpaq via ZpaqPruneOldTurns).
  • make test-checkpoints-zpaq — wrapper Append/List/Extract round-trip (4 tests).
  • make test-checkpoints-redo — full BeginTurn / SnapshotBeforeWrite / UndoTurns / RedoTurns flow incl. redo-stack invalidation on new write, multi-path-per-turn (4 tests).
  • make — full binary compiles under FPC 3.2.2.
  • make test-agents-md — regression check (PR agent.prompt: read AGENTS.md from project root; pasclaw init + /init #298 unchanged).
  • Delphi build — vendor unit is {$mode objfpc} so cbZpaq is FPC-only. Delphi keeps cbLegacy (covered by existing delphi_build_tests).
  • Manual smoke: pasclaw tui → write a file via the agent, /undo, /redo, watch the file content flip back and forth.

Vendoring

The vendor is MIT-licensed (vendor/zpaq/LICENSE). Cloned via make get-zpaq, same pattern as make get-indy. .gitignore already excludes vendor/ so nothing extra is tracked in this repo.

Known limitations (documented in docs/checkpoints.md)

  • No cross-turn dedup. The Pascal port writes the streaming format; libzpaq's JIDAC journaling format (which gives fragment-level dedup) would need more of the port's public API than it currently exposes. Storage is still compressed per-segment.
  • No archive compaction on prune. KeepLast drops records from the journal; archive segments stay. Disk grows monotonically per session.
  • Created files not deleted on undo. Same carve-out as today's legacy backend.

Each of these is a clean follow-up PR — none block the main /redo win.


Generated by Claude Code

claude added 2 commits June 16, 2026 18:07
Foundation for the zpaq-backed undo/redo checkpoint store (the
storage refactor + RedoTurns + /redo wiring follow in subsequent
commits on this branch).

* Makefile: `make get-zpaq` clones the Xelitan Free Pascal port of
  libzpaq 7.15 (https://github.com/Xelitan/...) into vendor/zpaq/,
  mirroring the existing `make get-indy` pattern. The vendor is
  `{$mode objfpc}` so it's FPC-only; the Makefile sets
  -dPASCLAW_HAVE_ZPAQ only when libzpaq.pas is on disk, and the
  wrapper unit compiles to "not available" stubs otherwise.

* PasClaw.Checkpoints.Zpaq (new):
  - ZpaqAvailable -- True iff the wrapper can dispatch.
  - ZpaqAppendBytes(archive, body, name, method) -- append one
    streaming segment via TZpaqPacker.  No PASCLAW-side index;
    callers maintain the count in their own metadata.
  - ZpaqListEntries(archive) -- enumerate every segment in order.
  - ZpaqExtractByIndex(archive, idx) -- read segment N back.
  - ZpaqDefaultMethod -- LZ77 (method 1), the fast tier we use for
    the snapshot-before-write hot path.

  Note for future PRs: the port's TZpaqPacker writes the streaming
  format only.  Cross-segment fragment dedup (libzpaq's journaling
  / JIDAC format) requires more of the port exposed than its public
  API currently offers; punted to a follow-up.  The streaming format
  still gives us per-segment compression, multi-version history in
  one file, and indexed extraction -- enough for undo/redo.

* src/tests/checkpoints_zpaq_tests.pas + Makefile target
  test-checkpoints-zpaq:
  - TestMultiVersionRoundtrip -- three appends with same logical
    name surface as three list entries; each round-trips its bytes.
  - TestBinaryRoundtrip -- 0..255 byte payload (NULs + high bytes)
    survives, since the port internally uses AnsiString.
  - TestExtractOutOfRange -- bad idx returns False + useful Err.
  - TestListMissingArchive -- nonexistent archive path -> False +
    "not found" message.
  - Skip-with-exit-0 when PASCLAW_HAVE_ZPAQ is undefined so a fresh
    clone without `make get-zpaq` doesn't false-fail CI.
Builds on the vendor+wrapper foundation (earlier commit on this
branch) to give PasClaw real undo/redo via the zpaq journal.

* PasClaw.Checkpoints.pas:
  - New TCheckpointBackend = (cbDisabled, cbLegacy, cbZpaq) enum
    + CheckpointsBackend public getter.
  - InitCheckpoints picks the backend: existing archive.zpaq -> resume
    zpaq mode; existing turn-NNNN dirs -> resume legacy; otherwise zpaq
    when ZpaqAvailable, else legacy.  Both backends keep working
    side-by-side; no migration of old session dirs (an opt-in feature
    -- old sessions age out naturally).
  - cbZpaq backend, all-new (~470 LOC under one heading): one
    archive.zpaq per session, JSON journal index.json mapping
    turn -> { entries: [{path, archive_idx, was_created}] }, plus a
    redo_stack of bundles UndoTurns captures BEFORE rewinding.
    SnapshotBeforeWrite appends one segment per distinct path per
    turn; subsequent edits in the same turn are deduped (earliest-
    wins, matching legacy semantic).  UndoTurns captures the current
    state of every touched path into a fresh bundle, pushes it on
    redo_stack, then extracts the pre-window snapshot per file.
    RedoTurns pops bundles off the stack and extracts.  The first
    real SnapshotBeforeWrite after an UndoTurns clears the redo
    stack (standard editor semantic; /redo itself doesn't trigger
    SnapshotBeforeWrite, so undo/redo/undo/redo cycles cleanly).
  - ZpaqPruneOldTurns honours KeepLast at BeginTurn time, matching
    the legacy backend's prune timing.  Pruned turn records leave
    their archive segments on disk (no compaction yet -- punted to a
    follow-up); index.json forgets them.
  - UndoTurns dispatch in the public function routes to ZpaqUndoTurns
    when GBackend = cbZpaq; falls back to the original blob-tree
    walk under cbLegacy.
  - New public RedoTurns + CanRedo.  RedoTurns under cbLegacy returns
    False with an explicit "redo not supported by this backend"
    message naming `make get-zpaq` as the fix.

* PasClaw.JSON: TJsonArray.Delete(Index: Integer).  Used by the redo-
  stack pop and by ZpaqPruneOldTurns.  Implemented for both FPC
  (fpjson.TJSONArray.Delete) and Delphi (System.JSON.TJSONArray.Remove
  + Free of the returned ref).

* TUI (both variants):
  - /redo [N] slash command alongside the existing /undo.  Positioned
    Delphi TUI uses Flash for status; FPC line REPL uses PrintLn.
  - /help line in the positioned TUI lists /redo; FPC ShowHelp now
    documents /undo + /redo + /init.

* Tests:
  - src/tests/checkpoints_redo_tests.pas (new) drives the full public
    surface against a temp PASCLAW_HOME:
      TestRedoRoundtrip  -- write/snap/rewrite/undo/redo cycle.
      TestRedoInvalidatedByNewWrite -- standard editor semantic.
      TestRedoMultiPathInTurn -- multiple files in one turn restored
                                 then redone independently.
      TestCanRedoFalseInitially -- fresh session reports CanRedo=False.
    Skip with "ok - skipped" exit-0 when ZpaqAvailable is False.
  - test-checkpoints (legacy) still passes -- ZpaqPruneOldTurns
    keeps the KeepLast contract under zpaq mode too, so the
    TestKeepLastPrunesOlderTurns assertion still holds when the
    session ran under cbZpaq.
  - Both new test targets (test-checkpoints-zpaq from the foundation
    commit, test-checkpoints-redo new here) added to the aggregate
    `make test` list.

* docs/checkpoints.md (new): backend selection rules, the index.json
  schema, the carve-out (model-created files left in place on undo),
  and the KeepLast-with-no-archive-compaction trade-off.
  docs/README.md gets a sibling link.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 85b8c5680b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +640 to +642
WindowHi := GTurn;
WindowLo := GTurn - N + 1;
if WindowLo < 1 then WindowLo := 1;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Derive undo windows from recorded zpaq turns

When zpaq is selected, chat-only turns still increment GTurn in ZpaqBeginTurn but never create an index.json turn record. After a common flow like edit a file, have one no-file turn, then run /undo, these bounds point at the empty current turn, TouchedPaths stays empty, and the edit is not restored; the legacy backend instead trims to the newest snapshotted turn directories. Use the newest recorded zpaq turn (or persist empty turns) when choosing the undo window.

Useful? React with 👍 / 👎.

Comment on lines +490 to +492
GTurn := Index.GetInt('current_turn', 0);
GZpaqArchiveCount := Index.GetInt('archive_count', 0);
GZpaqRedoDirty := False;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Persist redo invalidation across restarts

After /undo, redo_stack is saved in index.json, but the flag that makes the next edit clear it is reset to false when the session is reloaded. If PasClaw restarts after an undo and before the next write, a fresh edit will keep the old redo bundle, so /redo can later replay the abandoned branch over the new changes. Initialize this flag from a non-empty persisted redo stack, or clear redo history on any new zpaq snapshot when the stack is non-empty.

Useful? React with 👍 / 👎.

Per review: the Pascal port is ~180 KB across three files, MIT-
licensed, and pinned to v7.15 (Aug 2016, no upstream changes since).
At that size there's no reason to require a separate `make get-zpaq`
step on every fresh clone -- just commit the source.

Moved src/pkg/vendor/zpaq/ alongside the existing
src/pkg/vendor/dmvcframework/ convention (.gitignore already exempts
src/pkg/vendor/ from its vendor/ rule). Files vendored:

  libzpaq.pas       (4091 LOC, MIT)
  ZpaqClasses.pas   ( 877 LOC, MIT -- high-level Packer/Unpacker)
  ZpaqSimple.pas    ( 265 LOC, MIT -- streaming helpers)
  LICENSE
  NOTICE            -- provenance: Xelitan upstream URL + bundled
                       sub-licenses (libdivsufsort MIT,
                       libtomcrypt PD, Salsa20/8 PD, LibZPaq PD)

Demo (zpaq.lpr) and Lazarus project (zpaq.lpi) NOT vendored -- we
drive the library through its Pascal API rather than the CLI.

Makefile:
* `make get-zpaq` deleted.
* ZPAQ_DIR now points at src/pkg/vendor/zpaq (was vendor/zpaq).
* `-Fu$(ZPAQ_DIR)` is unconditional (was guarded by a `wildcard`
  test of libzpaq.pas presence).
* `-dPASCLAW_HAVE_ZPAQ` define removed; PasClaw.Checkpoints.Zpaq
  now keys on `{$IFDEF FPC}` directly. The vendor is `{$mode
  objfpc}` so it's structurally FPC-only -- the PASCLAW_HAVE_ZPAQ
  define existed only to gate "was the vendor fetched", which is
  moot now that it's always in the repo.
* .PHONY drops get-zpaq.

PasClaw.Checkpoints.Zpaq.pas:
* Header rewritten to point at src/pkg/vendor/zpaq/ and explain the
  FPC-only gate (was: "PASCLAW_HAVE_ZPAQ define set by Makefile").
* All `{$IFDEF PASCLAW_HAVE_ZPAQ}` -> `{$IFDEF FPC}`.

docs/checkpoints.md: backend-selection language updated -- cbZpaq
is now "selected when built under FPC", not "selected when
`make get-zpaq` was run".

All four test suites still green:
  test-checkpoints (legacy)        PASS
  test-checkpoints-zpaq (wrapper)  ok
  test-checkpoints-redo (e2e)      ok
  test-agents-md (regression)      ok
@FMXExpress
FMXExpress merged commit 85241e8 into main Jun 16, 2026
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
The README + docs/changelog.md last entry was 2026-06-13 (FMXExpress#244). Five
substantial PRs (FMXExpress#314 FMXExpress#315 FMXExpress#316 FMXExpress#317 FMXExpress#318) and ten more feature PRs
between them and that entry shipped without changelog entries. This
brings both files current through today.

Twenty new entries (newest first, matching the existing style):

  2026-06-21
    FMXExpress#318  Relay pull-worker provider (queue + provider + /v1/relay/* HTTP)

  2026-06-20
    FMXExpress#317  pasclaw plan + build PLAN.md pickup + build --goal + cog mode
    FMXExpress#316  Cloudflare AI Gateway provider catalog rows
    FMXExpress#315  MCP progressive disclosure + tool_search
    FMXExpress#314  Stock defaults adopt lean-edit shape; fs_grep split-gate

  2026-06-18
    FMXExpress#312  Web UI workspace.zip export + import
    FMXExpress#310  Model-callable cron tool
    FMXExpress#309  FTS5 snippet window widened 24 -> 60
    FMXExpress#307  Windows cmd.exe quoting fix

  2026-06-17
    FMXExpress#306  cog-build honours profile=security sandbox
    FMXExpress#304  cog-build default profile = max-build
    FMXExpress#303  cog-build list[Path] outputs + Secret inputs + -q

  2026-06-16
    FMXExpress#302  cog-build optional workspace_in
    FMXExpress#300  pasclaw build cmd + cog-build/ predictor (parent feature)
    FMXExpress#299  Checkpoints zpaq backend + /redo
    FMXExpress#298  AGENTS.md + pasclaw init + /init
    FMXExpress#297  tool_choice force-a-specific-tool form
    FMXExpress#296  Delphi ExtraEnv injection fix
    FMXExpress#295  KB native PDF ingest

  2026-06-15
    FMXExpress#292  pasclaw profile diff + bench

Skipped per the changelog's stated convention ("Bug fixes and review
follow-ups are in the full git log"):

  FMXExpress#293  cmd/profile dcc64 fix
  FMXExpress#294  skills_manage gemini empty-enum fix
  FMXExpress#301  cmd.build dcc64 fix
  FMXExpress#311  cron dcc64 fix

Files updated identically (the docs/changelog.md note at the top says
"This file mirrors the changelog section at the top of the root
README.md"):

  M README.md           20 entries + 20 link refs added
  M docs/changelog.md   same

The link-ref block at the bottom of each file gained 20 [#NNN] entries
keeping the existing one-per-line / sorted-numerically format.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants