Skip to content

checkpoints: auto-snapshot files before edits + TUI /undo (opt-in) - #221

Merged
FMXExpress merged 2 commits into
mainfrom
claude/checkpoints-undo
Jun 11, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/checkpoints-undo

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

We had no rollback story at all. When the model fs_writes the wrong file, or fs_edit_hashlines into a state the operator doesn't want, the only recovery was undo-by-hand from version control — if there even was any.

This PR adds opt-in checkpoints + a TUI /undo command:

  • Auto-snapshot. fs_write and fs_edit_hashline now snapshot the pre-edit bytes of every file they touch into $PASCLAW_HOME/workspace/checkpoints/<session>/turn-NNNN/ BEFORE writing. Per-turn manifest.json + per-file blob.
  • /undo [N]. Rewinds N turns by restoring those captures. Walks oldest→newest across the rewound range so the EARLIEST captured pre-state of each file wins; /undo 2 from turn HEAD therefore restores everything to the state at the start of (HEAD-1), even if some files were edited in multiple of the rewound turns.
  • Model-created files left in place. v1 conservative semantic — deleting model-created files risks data loss if the model also rewrote an unrelated file in the same turn.
  • Idempotent. Snapshotting the same file twice in one turn keeps the earliest capture; /undo still rolls back to before the first edit.
  • KeepLast auto-prunes at BeginTurn so per-session disk usage is bounded (default 32).

Off by default

You warned this can be heavy — a turn that fs_writes a 5 MB generated file copies the whole 5 MB into the per-turn dir. So:

  • TConfig.CheckpointsEnabled defaults False; CheckpointsKeepLast defaults 0 (= module default 32). Both round-trip through config.json.
  • pasclaw onboard asks opt-in style with explicit "can be heavy" warning.
  • Cmd.TUI forwards Cfg.CheckpointsEnabled + KeepLast onto the TUI instance.
  • StartTurn (positioned TUI) and HandleUserInput (FPC legacy REPL) both call BeginTurn so each user message opens a fresh turn dir.

Files

  • New: src/pkg/checkpoints/PasClaw.Checkpoints.pas — transport-agnostic, thread-safe (per-instance CS), ~440 lines.
  • New: src/tests/checkpoints_tests.pas — 11 cases (disabled no-op, single + cross-turn undo, idempotency, clamp, reject paths, model-created-files-left-in-place, KeepLast pruning, multi-file per turn).
  • src/pkg/tools/PasClaw.Tools.FS.pas — SnapshotBeforeWrite hooked into both write tools.
  • src/pkg/config/PasClaw.Config.pas — fields + JSON round-trip.
  • src/cmd/PasClaw.Cmd.Onboard.pas — PromptCheckpoints opt-in question.
  • src/pkg/tui/PasClaw.TUI.pas — /undo slash command + BeginTurn per turn + RewireCheckpoints per session switch.
  • src/cmd/PasClaw.Cmd.TUI.pas — forwards config fields onto the TUI.
  • Makefile, src/pasclaw/PasClaw.dproj, build-delphi.bat, build-fpc.bat — search paths for the new unit + test-checkpoints target.

Test plan

  • make test — full suite green incl. new test-checkpoints (11/11)
  • make smoke — all subcommands OK
  • Manual: pasclaw onboard — verify the new "Enable checkpoints" prompt appears between Stats and AutoRouter
  • Manual: enable, pasclaw tui, ask the model to edit a file, then /undo — verify the file rolls back; check workspace/checkpoints/<session>/turn-NNNN/ exists
  • Manual: /undo 3 after 3 edits across 3 turns — verify file restores to its state before turn N-2
  • Delphi dcc64 build picks up the new unit (FPC verified locally)

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

We had no rollback story at all. When the model fs_writes the wrong file,
or fs_edit_hashlines into a state the operator doesn't want, the only
recovery was undo-by-hand from version control -- if there even was any.

This PR adds opt-in checkpoints + a TUI /undo command:

  - fs_write and fs_edit_hashline snapshot the pre-edit bytes of every
    file they touch into
        $PASCLAW_HOME/workspace/checkpoints/<session>/turn-NNNN/
    BEFORE writing. Per-turn manifest.json + per-file blob.

  - The TUI's /undo [N] rewinds N turns by restoring those captures.
    Walks oldest -> newest across the rewound range so the EARLIEST
    captured pre-state of each file wins; `/undo 2` from turn HEAD
    therefore restores everything to the state at the start of
    (HEAD - 1), even if some of those files were edited in multiple
    of the rewound turns.

  - Files the model CREATED inside a rewound turn (no pre-snapshot
    exists) are left in place. v1 is conservative -- deleting model-
    created files risks data loss if the model also rewrote an
    unrelated file in the same turn.

  - Idempotency: snapshotting the same file twice in one turn keeps
    the EARLIEST capture. fs_edit_hashline that touches a file twice
    in one turn still rolls back to BEFORE the first edit.

  - PruneOldTurns auto-trims at BeginTurn so per-session disk is
    bounded by checkpoints_keep_last (default 32).

Off by default. The user warned this can be heavy -- a turn that
fs_writes a 5 MB generated file copies the whole 5 MB into the
per-turn dir, and operators on big-codebase sessions are exactly the
ones who'd hit the watermark. So the wiring is:

  - TConfig.CheckpointsEnabled defaults False; CheckpointsKeepLast
    defaults 0 ("use the module's default = 32"). Both round-trip
    through config.json.

  - `pasclaw onboard` asks the operator opt-in style:
        "Auto-snapshot files BEFORE fs_write / fs_edit_hashline
         mutates them. The TUI /undo [N] rewinds N turns by
         restoring those captures.
         (Off by default -- can be heavy when the model writes
          large files. No rollback story without this.)
         Enable checkpoints [y/N]:"

  - Cmd.TUI forwards Cfg.CheckpointsEnabled + KeepLast onto the
    TTUI instance; the TUI rewires the checkpoints module on every
    session switch (new / load / delete -> resurrect) so /undo
    stays bound to whatever session is on screen.

  - StartTurn calls BeginTurn(Stats.Turns + 1) so each user message
    opens a fresh turn dir. The FPC legacy REPL path opens the same
    boundary in HandleUserInput.

New unit: src/pkg/checkpoints/PasClaw.Checkpoints.pas (~440 lines,
transport-agnostic, thread-safe).

New tests: src/tests/checkpoints_tests.pas -- 11 cases pinning
the disabled-no-op semantic, single-turn undo, idempotent snapshot
keeping the earliest state, cross-turn undo with oldest-wins
restoration, clamping when N exceeds available history, the reject
paths (zero / negative N, disabled module, empty session), the
v1 left-in-place semantic for model-created files, KeepLast
auto-pruning, and the multi-file-per-turn happy path.

Wired into Makefile + Delphi dproj + Windows .bat search paths so
all four build configurations pick up the new unit.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon

@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: 53c17612e9

ℹ️ 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 thread src/pkg/tui/PasClaw.TUI.pas Resolved
Comment thread src/pkg/tui/PasClaw.TUI.pas Resolved
#221)

Two Codex findings, both legit:

1) Decouple checkpoint turns from stats collection.

   The old design pulled BeginTurn's TurnNumber from
   TSession.Meta.Stats.Turns. That counter only increments inside
   ApplyLoopResultTo when StatsCollectionEnabled is True -- the
   opt-in stats subsystem. With stats off (the DEFAULT), every TUI
   turn called BeginTurn(1) and overwrote the same turn-0001
   manifest. /undo N could only ever see the latest snapshotted
   turn instead of the last N.

   Fix: the checkpoints module now owns the counter. At
   InitCheckpoints we scan SessionDir for the highest existing
   turn-NNNN entry and resume from there; each BeginTurn (no arg
   now) just increments. Independent of stats; survives pasclaw
   restarts cleanly (turn numbers don't repeat across runs of the
   same session).

   New test (TestInitResumesFromExistingTurnDirs) pins it: drop a
   turn-0001 dir on disk, re-Init the same session, verify the
   next BeginTurn lands on turn-0002 and /undo 1 restores the
   start-of-turn-2 state correctly.

2) Keep in-flight snapshots bound to their origin session.

   When the operator switched sessions while a tool loop was still
   running, SelectSession called InitCheckpoints for the newly
   displayed session -- mutating the module globals while the
   background worker's fs_write hooks still expected the OLD
   session's state. Subsequent writes landed in the WRONG session's
   dir; /undo on the origin session couldn't see them; /undo on
   the displayed session would later restore unrelated files.

   Fix: SelectSession (and the post-delete-resurrect path) only
   call RewireCheckpoints when FLoopThread is nil. Otherwise they
   set a new FPendingCheckpointRewire flag. PollLoopWorker fires
   the deferred rewire at every completion path (happy / failure /
   timeout), so the next user turn on the displayed session
   correctly initialises checkpoints for THAT session before
   StartTurn calls BeginTurn.

   This mirrors the same "loop owns the session it started in"
   shape FLoopSessionId already enforces for result delivery
   (Codex P1 on PR #122).

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
@FMXExpress
FMXExpress merged commit 24be197 into main Jun 11, 2026
FMXExpress pushed a commit that referenced this pull request Jun 13, 2026
Both changelog files were stuck at the 2026-06-10 TUI / background-
subagent / session_search / tool-RPC entries. ~7 weeks of merged
PRs (#214 through #244) had landed without a corresponding entry in
either file -- the git log was the only record of features like the
knowledgebase, inbound MCP server mode, checkpoints + /undo,
heartbeat daemon, shell backends (local | docker), send_message,
promptware defense, Windows shell-output encoding fixes, fs_grep
ripgrep optimisations, OpenTelemetry traces, and `pasclaw agent
--quiet`.

Added (newest first):

  2026-06-13
    #244  agent --quiet log-level clamp

  2026-06-12
    #243  dcc64 search path + agent --quiet / -q
    #242  OpenTelemetry traces (OTLP/HTTP+JSON)
    #241  fs_grep tier 5+6 (byte walker + Boyer-Moore-Horspool)
    #240  fs_grep tier 1-4 (deferred hash + skip-dirs + binary
          sniff + size cap)

  2026-06-11
    #239  Windows shell output: auto-detect UTF-8 vs OEM
    #238  Hashline fs_read header mojibake fix (¶ vs ¶)
    #237  Windows shell output: OEM codepage decode

  2026-06-10
    #233  Shell backends (local | docker via IShellBackend)
    #232  Heartbeat daemon + reversible condensation (CCR)
    #230  send_message tool + condenser families + promptware
          defense + task-aware MEMORY.md slicing

  2026-06-09
    #223  /goal Ralph loop + judge model + JSON-aware condenser
    #222  /undo wired into agent + sample dprojs
    #221  Checkpoints (auto-snapshot + TUI /undo)
    #220  mcp catalog: lenient hub projector
    #219  mcp: SSE / Streamable HTTP / stdio hub transports
    #218  Inbound MCP server mode
    #217  onboard: offer to index docs into the knowledgebase
    #214  Knowledgebase (RAG over operator-curated docs)

Skipped from this changelog (build-system / Delphi-fix / FPC-fix
PRs visible in the git log but not user-facing features):
#215, #216, #224, #225, #226, #227, #228, #229, #231, #234, #236.

Both files (README.md and docs/changelog.md) updated with the same
entries -- intentional mirror so a reader on either surface sees
the same history. Same prose in both; same footnote refs at the
bottom.

Validated: every [#N] reference in both files has a matching [#N]:
URL footnote (no broken links).
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
Two related fixes for the checkpoints feature shipped in PR FMXExpress#221:

1) dcc64 F2613 Unit 'PasClaw.Checkpoints' not found
   src/pasclaw/PasClaw.dproj picked it up at FMXExpress#221's merge, but the
   three sample dprojs under samples/component-console/ each carry
   their OWN DCC_UnitSearchPath -- and those didn't get the new
   entry. The samples import PasClaw.Agent + PasClaw.Tools, which
   transitively pull in PasClaw.Tools.FS, which now imports
   PasClaw.Checkpoints. dcc64 walked the search path, didn't find
   the unit, and failed at PasClaw.Tools.FS.pas line 46 for anyone
   building SampleConsole / SampleServer / SampleSimple.

   Fix: add ..\..\src\pkg\checkpoints to each sample dproj's search
   path, slotted between the existing skills and agent entries to
   keep them in the same package-dir order PasClaw.dproj uses.

2) `pasclaw agent` interactive mode now has /undo

   PR FMXExpress#221 wired /undo into the TUI (positioned + FPC legacy paths)
   but `pasclaw agent` runs its own line-based REPL with a distinct
   slash-command dispatcher. Without /undo there, an operator who
   prefers `agent` over `tui` had no rollback story even with
   checkpoints turned on. Symmetric wiring:

     - Import PasClaw.Checkpoints into Cmd.Agent.
     - RewireCheckpoints helper called when the session is first
       created AND after /new resurrects a fresh session id.
     - BeginTurn() fires right before every RunToolLoop call so
       each user turn opens its own turn-NNNN dir.
     - HandleUndoCommand mirrors the TUI's behaviour: `/undo` ->
       1 turn, `/undo N` -> N turns, prints the restored file paths
       so the operator sees what came back.
     - /help text lists the new command.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
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