Skip to content

Persistent session management — durable conversations across restarts - #117

Merged
FMXExpress merged 2 commits into
mainfrom
claude/persistent-sessions
Jun 1, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/persistent-sessions

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Wire the src/pkg/session/ placeholder dir to actual durable storage — serialise the in-flight conversation to $PASCLAW_HOME/workspace/sessions/<id>.json after every turn, so killing pasclaw agent mid-chat no longer drops context. openclaw-style /new vs /reset split, nanobot-style session ids, and a top-level pasclaw resume <id> shortcut. ~600 LOC counting the CLI surface.

  • TSession class + module helpers in src/pkg/session/PasClaw.Session.Store.pas: Save / Load / ListSessions / DeleteSession, AutoTitle from first user message, MetaExists, Touch for UpdatedAt. Session id is yyyymmddTHHMMSS-<8 hex> — sortable and collision-safe. tool_calls + tool_call_id pairs round-trip through JSON intact, as does the /compact SystemPromptOverride.
  • 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 for 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 uses 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 — -m "one-shot" skips save).
  • /new spawns a new session id and clears history; /reset clears history in place and keeps the same id — matches openclaw's two-knob design.

Test plan

  • make clean && make clean (441563 lines, 0 errors)
  • make smoke 11/11 OK
  • Focused end-to-end roundtrip test (built + ran, then removed): create session with user + assistant-with-tool_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), ListSessions includes the id, DeleteSession returns true and removes it from the list — all 4 phases clean
  • pasclaw session list shows (no saved sessions) on a fresh workspace
  • pasclaw session show foo → ✗ no session named foo
  • pasclaw --help lists the new session and resume subcommands
  • Manual: live pasclaw agent --session test-resume round-trip — send a few messages, kill the process, resume, confirm history restored

Generated by Claude Code

…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

@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: 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".

Comment thread src/cmd/PasClaw.Cmd.Agent.pas Outdated
{ 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment on lines +126 to +129
function SessionPath(const Id: string): string;
begin
Result := JoinPath(SessionsDir, Id + '.json');
end;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment on lines +271 to +273
S.Text := Root.ToJSON;
S.SaveToFile(SessionPath(Meta.Id));
FExists := True;

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 Save session files atomically

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 👍 / 👎.

Comment thread src/cmd/PasClaw.Cmd.Agent.pas Outdated
Comment on lines +512 to +515
{ 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

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 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 👍 / 👎.

Comment thread README.md Outdated
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.

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 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
@FMXExpress
FMXExpress merged commit afbe8ed into main Jun 1, 2026
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
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('').
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