Repository navigation
Persistent session management — durable conversations across restarts - #117
Conversation
…estarts
Serialise the in-flight TMessageArray (plus model, provider, title, and
any /compact summary) to $PASCLAW_HOME/workspace/sessions/<id>.json after
each turn, so killing pasclaw mid-conversation no longer drops context.
- new TSession class + module helpers in src/pkg/session/
PasClaw.Session.Store.pas: Save / Load / List / Delete on disk,
AutoTitle from first user message, MetaExists check, Touch for
UpdatedAt; session id is yyyymmddTHHMMSS-<8 hex> (sortable +
collision-safe). Tool_calls + tool_call_id pairs round-trip
through JSON intact.
- pasclaw session list / show / delete / export CLI in
src/cmd/PasClaw.Cmd.Session.pas — list shows id/age/title columns,
show trims to the last 8 messages, export prints raw JSON to
stdout (pipe through jq), delete removes the file.
- pasclaw resume <id> top-level shortcut wired in Cmd.Root —
rewrites argv to `agent --session <id>` so the resume path goes
through the same RunInteractive loop as a fresh chat.
- --session <id> flag on `pasclaw agent`: missing id starts a fresh
session at that id; existing id loads messages + SystemPromptOverride
and continues. Save runs after every turn (interactive only).
- /new spawns a new session id; /reset clears history in place and
keeps the same id — matches openclaw's two-knob design and avoids
the foot-gun where /reset would silently abandon the saved file.
Verified end-to-end with a focused roundtrip test that creates a session
with user + assistant-with-tool_use + tool_result + assistant messages,
saves, frees, reloads, asserts every field (including tool_call_id
pairing and SystemPromptOverride), then deletes — all 4 phases clean.
https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d109854ed5
ℹ️ 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".
| { Persist after every successful turn — crash / Ctrl-C in | ||
| the middle of the NEXT user prompt only loses what they | ||
| were typing, not the existing conversation. } | ||
| if Session <> nil then |
There was a problem hiding this comment.
Persist ordinary interactive chats by default
When the user runs the documented pasclaw agent command without --session, Session remains nil because it is only constructed inside the A.Session <> '' branch, so this guard skips every save. The same guard also prevents /new from creating a durable session in an ordinary chat. As a result, the primary workflow described in README.md as surviving restarts still loses the entire conversation unless the user already knows to opt into --session; initialize a generated session for interactive chats instead of treating persistence as opt-in.
Useful? React with 👍 / 👎.
| function SessionPath(const Id: string): string; | ||
| begin | ||
| Result := JoinPath(SessionsDir, Id + '.json'); | ||
| end; |
There was a problem hiding this comment.
Reject path separators in session IDs
Because JoinPath only concatenates its arguments, an ID such as ../../config resolves outside workspace/sessions. This affects every new session-facing command: pasclaw session export ../../config can read $PASCLAW_HOME/config.json, pasclaw session delete ../../config can delete it, and pasclaw agent --session ../../config can overwrite it after a successful turn. Validate IDs as single safe filename components before constructing the path.
Useful? React with 👍 / 👎.
| S.Text := Root.ToJSON; | ||
| S.SaveToFile(SessionPath(Meta.Id)); | ||
| FExists := True; |
There was a problem hiding this comment.
When a process is interrupted or the disk write fails while persisting a turn, SaveToFile writes directly over the only copy of the session file. A partially written JSON file then prevents the advertised restart recovery and can also make session list fail while parsing that file. Write a temporary file in the sessions directory and rename it over the destination only after the complete JSON has been flushed.
Useful? React with 👍 / 👎.
| { Persist after every successful turn — crash / Ctrl-C in | ||
| the middle of the NEXT user prompt only loses what they | ||
| were typing, not the existing conversation. } | ||
| if Session <> nil then |
There was a problem hiding this comment.
Persist explicit compaction before returning to the prompt
For a resumed session, /compact mutates Msgs and SystemPromptOverride but returns to the prompt without reaching this save block, because persistence only occurs after a successful LLM turn. If the user compacts a long session and then exits or the process is killed before sending another message, resuming silently restores the pre-compaction transcript and discards the summary. Synchronize and save the session immediately after /compact succeeds.
Useful? React with 👍 / 👎.
| pasclaw session delete <id> # remove the session file | ||
| ``` | ||
|
|
||
| Sessions live as one JSON file per id under `$PASCLAW_HOME/workspace/sessions/<id>.json`. The file carries the full `messages` array (role / content / name / tool_call_id / tool_calls), the model + provider + title in `meta`, and any `system_prompt_override` left behind by `/compact`. `pasclaw agent` (and `pasclaw tui`) save after each turn, so killing the process mid-conversation is safe — `pasclaw resume <id>` picks up exactly where it stopped. `/new` inside an interactive session spawns a new id; `/reset` clears history in place and keeps the same id. |
There was a problem hiding this comment.
Remove the unsupported TUI durability claim
The new documentation states that pasclaw tui saves after each turn, but the TUI path is not wired to PasClaw.Session.Store: Cmd_TUI_Run constructs TTUI without a session, and TTUI.HandleUserInput builds a fresh one-message array for every request. Users choosing the TUI based on this claim still lose history across turns and restarts. Either integrate sessions into the TUI or limit the documentation to pasclaw agent.
Useful? React with 👍 / 👎.
… + /compact persist Four Codex findings on the persistent-sessions PR — all legit, all fixed in place on PR #117. P1 — Default-persist interactive chats. Before: `pasclaw agent` without --session left Session=nil so every save was a no-op, which defeats the "history survives restart" promise the feature was supposed to deliver. After: RunInteractive always allocates a Session (auto-id when --session is empty) and prints the resume command up front, so the user can come back even without thinking about ids in advance. P1 — Reject path separators in session ids. Before: `pasclaw session export ../../../etc/passwd` would happily concat and dump the file (also delete / overwrite via the other subcommands). After: new IsSafeSessionId rejects `..`, `/`, `\`, leading dots, NULs, anything outside `[A-Za-z0-9._-]`; SessionPath returns '' for unsafe ids; Save raises EArgumentException; Load and Delete treat unsafe ids as "not found"; CLI's DoExport checks the empty path. NewSessionId output and hand-picked ids like `daily-2026-06-01` still pass. P2 — Atomic Save. Before: SaveToFile wrote directly to the final path, so a crash mid-write left a half-written JSON that Load couldn't parse — exactly the failure mode the feature was meant to prevent. After: write to `<id>.json.tmp` then RenameFile (with Windows pre-delete since MoveFile-without-overwrite isn't atomic there either). ListSessions now also skips stray `.tmp` leftovers via IsSafeSessionId so a crashed Save doesn't pollute the list. P2 — Persist /compact before returning to prompt. Before: /compact rewrote Msgs + SystemPromptOverride but didn't save, so a /quit before the next LLM turn lost the summary and resume replayed the full pre-compaction transcript. After: extracted a nested PersistSession helper, called from /compact (new), /reset (was already saving), and post-turn (was already saving). Docs — Removed the inaccurate "pasclaw tui save after each turn" claim from README; TUI doesn't wire to the session store yet. Called that out explicitly so a reader doesn't assume otherwise. Verified with a focused test (created, built, ran, removed) covering all four: unsafe-id rejection across every entry point, auto-id + roundtrip, .tmp-leftover skipped from ListSessions, repeated Save (the /compact replay path). https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Two user-reported bugs against PR FMXExpress#182's newest-first session sort, both in the TUI start/navigate path: Bug A -- sort drift when picking older sessions SelectSession used to call PersistSession on the outgoing session "to flush anything pending before the swap." But by the time you get there, every meaningful state change has already been persisted: PollLoopWorker's ApplyLoopResultTo saves after each turn, ApplyModelSelection saves after /model, and so on. Pure navigation had nothing to save -- but PersistSession's unconditional FSession.Touch bumped Meta.UpdatedAt anyway, so peeking at an older session re-promoted the one you LEFT to the top of the newest-first list. Dropped the Persist call. Added a comment explaining what's already persisted at each entry point so a future hand doesn't re-add it on the theory it might miss something. Bug B -- TUI launches with empty chat, mismatched highlight With no --session argument, the left pane highlighted the newest session but the chat pane was blank. TSession.Create('') auto- allocates a brand-new session id, so FSession pointed at a fresh empty in-memory record while FSelSessIdx tracked the newest persisted session at index 0. SessionId resolution in TTUI.Run now does: empty + sessions on disk -> resume the newest by UpdatedAt; empty + no sessions on disk -> fresh id (original PR FMXExpress#117 behavior); non-empty -> honour as-is. Pressing N still spawns a fresh session via StartNewSession -> SelectSession('').
Summary
Wire the
src/pkg/session/placeholder dir to actual durable storage — serialise the in-flight conversation to$PASCLAW_HOME/workspace/sessions/<id>.jsonafter every turn, so killingpasclaw agentmid-chat no longer drops context. openclaw-style/newvs/resetsplit, nanobot-style session ids, and a top-levelpasclaw resume <id>shortcut. ~600 LOC counting the CLI surface.TSessionclass + module helpers insrc/pkg/session/PasClaw.Session.Store.pas:Save/Load/ListSessions/DeleteSession,AutoTitlefrom first user message,MetaExists,TouchforUpdatedAt. Session id isyyyymmddTHHMMSS-<8 hex>— sortable and collision-safe.tool_calls+tool_call_idpairs round-trip through JSON intact, as does the/compactSystemPromptOverride.pasclaw session list / show / delete / exportCLI insrc/cmd/PasClaw.Cmd.Session.pas—listshows id/age/title columns,showtrims to the last 8 messages,exportprints raw JSON forjq,deleteremoves the file.pasclaw resume <id>top-level shortcut wired inCmd.Rootrewrites argv toagent --session <id>so the resume path uses the sameRunInteractiveloop as a fresh chat.--session <id>flag onpasclaw agent: missing id starts a fresh session at that id; existing id loads messages +SystemPromptOverrideand continues. Save runs after every turn (interactive only —-m "one-shot"skips save)./newspawns a new session id and clears history;/resetclears history in place and keeps the same id — matches openclaw's two-knob design.Test plan
make clean && makeclean (441563 lines, 0 errors)make smoke11/11 OKtool_use+tool_result+ assistant messages, save, free, reload, assert every field (role, content,tool_call_id,tool_calls[0].id/Func.Name,SystemPromptOverride,Model,Provider),ListSessionsincludes the id,DeleteSessionreturns true and removes it from the list — all 4 phases cleanpasclaw session listshows(no saved sessions)on a fresh workspacepasclaw session show foo→✗ no session named foopasclaw --helplists the newsessionandresumesubcommandspasclaw agent --session test-resumeround-trip — send a few messages, kill the process, resume, confirm history restoredGenerated by Claude Code