Skip to content

Memory tiers with budgets, a nightly maintenance pass, backup/restore, and a cheap tier for background work - #606

Merged
FMXExpress merged 2 commits into
mainfrom
claude/keen-einstein-kPEMj
Oct 17, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/keen-einstein-kPEMj

Conversation

@FMXExpress

@FMXExpress FMXExpress commented Oct 17, 2026 •

Copy link
Copy Markdown
Owner

Why

The setups that keep running well for months share four habits: memory split into tiers with a hard cap on what loads every turn, a nightly maintenance loop, backups that can actually be restored, and most calls on a cheap model. PasClaw had parts of each. This PR builds the missing parts and fixes three doc/code mismatches found on the way.

1. Tier-1 memory is capped and split

  • The always-loaded files are now SOUL.md (optional), USER.md (optional), MEMORY.md, today's and yesterday's note, in that order, each cut at memory_core_budget_bytes (default 16 KB, 0 = no cap) on a line boundary, never inside a UTF-8 sequence. The model sees a note saying how many bytes were elided and that memory_search reaches them.
  • The memory rule in the system prompt carries the six-months test and names USER.md.
  • ClampToBudget is pure and tested, including 2-byte and 4-byte characters straddling the budget; injection order, the elided note and budget 0 are tested against a temp PASCLAW_HOME. Negative-tested by removing the clamp.

2. pasclaw maintain, the nightly loop

One pass: sweep expired facts and superseded facts older than maintenance.keep_superseded_days (new IFactStore.Sweep; the schema had the column and the index and never the sweep); size the tier-1 files against the budget; walk the last N days of sessions for turns, tool calls, failures with samples, tokens; list callable skills nothing invoked in unused_skill_days and pairs that look like the same skill twice; optionally ask the background model for a 200-word critique (--review); optionally back up (--backup); write memory/maintenance/<date>.md. --dry-run deletes nothing and calls nothing.

Schedule it with the reserved cron skill name:

pasclaw cron add nightly "0 3 * * *" @maintain

The gateway scheduler runs it in-process; the model's cron tool accepts the name. Reported, never deleted: skills and MEMORY.md lines stay the operator's call. Tested end to end against a temp home with a fact store, three sessions, four skills and an over-budget file; the sweep was negative-tested.

3. pasclaw backup / restore

  • Archive = the workspace (minus the WebView2 profile, SQLite journals, .git, the sessions search index, and the backup directory itself if it sits inside the workspace) + your real config.json + RESTORE.md naming the version, the file count and the exact restore command.
  • config.json goes in as is by default (backup.include_secrets: true), so a restore brings every connected API back. That makes the archive a credential and RESTORE.md says so. --redact (or include_secrets: false) writes config.redacted.json instead, every secret masked: providers[].api_key, mcp_servers[].env, gateway.token, web_search.api_key, and the webhook-style channels[].target and crons[].channel_target. The masking is one function, MaskConfigSecretsJSON, which the gateway's GET /v1/config now also uses, so the two cannot disagree.
  • Rotation 7 / 4 / 6 with borg's rule (newest of each of the last N days / ISO weeks / months that have one), never touches files it did not name, never prunes after a failed write. SelectBackupsToPrune is pure and tested on fixed dates.
  • Restore validates members, refuses an existing workspace without --force, overlays with it, writes config.json into a home that has none, and under --force keeps the old one as config.json.bak and replaces it. A redacted archive never writes config.json and prints the secrets to re-enter.
  • Tested: names, rotation, masking, packing, exclusions, both archive forms (the real key asserted present in one and absent in the other), restore round-trip (UTF-8 byte-identical), config written / left alone / replaced with .bak, nested destination excluded, unparseable config refused.

4. background_model and pasclaw route report

  • One key, falling back to fast_model, then the main model, now carries fact distillation (CLI, TUI, gateway), history compaction (TToolLoopConfig.CompactModel), the heartbeat, the goals judge and the maintenance review. A config with neither key behaves exactly as before.
  • It is applied only when the work runs on the default provider (BackgroundModelOn): a --provider override, or a request that picked another provider, keeps its own model, since the name belongs to the default provider. Unit-tested for entry name, kind, case and mismatch.
  • pasclaw route report [--since N] aggregates saved sessions by provider/model with token volume beside the cheap-tier settings. It states that a session counts under its last model, so the cheap share is a floor.

Doc fixes

  • docs/memory.md claimed SCARS.md is always injected. It never was; corrected, plus a new Tiers section.
  • docs/checkpoints.md said checkpoints are off by default. They are on; corrected.
  • docs/agent-features.md said the distiller is post-hoc; it runs per turn when enabled. That row, the tiered-memory row and the tier-aware-routing row now match the code.
  • New docs/maintenance.md, docs/backup.md; configuration.md, commands.md, cron.md and the docs index updated.

Config keys added

memory_core_budget_bytes, background_model, maintenance.{keep_superseded_days, unused_skill_days, review, backup}, backup.{dir, keep_daily, keep_weekly, keep_monthly, include_secrets}. All default to the previous behaviour, to off, or (for include_secrets) to on; round-trip tested, including an explicit 0 budget and an explicit include_secrets: false.

Review fixes (second commit)

Codex raised one P1 and three P2s; all addressed:

  • Channel/cron webhook targets leaked through the redaction (P1): now masked, in the shared function, so the gateway endpoint is fixed too. Per the operator's call, the default archive now carries the real config.json instead, with --redact for the masked form.
  • Background model handed to a non-default provider (P2): BackgroundModelOn guards on provider.
  • Budget cut inside a UTF-8 sequence (P2): steps back to a character boundary.
  • Backup directory inside the workspace recursed (P2): excluded from the walk.

Verification

  • Full make test on the rebased branch after the review fixes: 42 passes, 0 make errors (three new targets: test-memory-tiers, test-backup, test-maintain, plus the browser suite from Add PasClaw Browser: WebView2 tabs with an embedded agent per tab #604).
  • The built binary was run against a scratch home: maintain --dry-run, maintain, backup (default and --redact), backup list, restore --into (writes config.json), a refused second restore, restore --force (leaves config.json.bak), route report, cron add … @maintain.
  • New units are listed in src/pasclaw/PasClaw.dproj; the Delphi build is otherwise untouched (compiled blind, as always for this repo).

Not in this PR

Remote backup targets (the directory can be a mount), routing subagents and cron skills to the cheap tier, and automatic rewriting of an over-budget MEMORY.md (the report says what is over; moving lines out is a judgement call).

🤖 Generated with Claude Code

https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-17T05:24:12.407346Z 77b02e1 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: 77b02e182f

ℹ️ 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".

Item.Free;
end;

Result := Root.ToJSON;

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 Redact channel credentials before serializing backups

The masking pass serializes the object after covering only provider keys, MCP env, gateway tokens, and web-search keys. Configured channels[].target and crons[].channel_target values remain intact, even though Slack, Discord, Teams, and generic webhook URLs commonly contain bearer credentials. Consequently, pasclaw backup writes usable secrets into config.redacted.json while claiming secrets never enter the archive; mask these credential-bearing targets as well.

Useful? React with 👍 / 👎.

Comment thread src/cmd/PasClaw.Cmd.Agent.pas Outdated
Result.PruneOpts.MinCandidateTokens := Cfg.Prune.MinCandidateTokens;
Result.PruneOpts.PreviewChars := Cfg.Prune.PreviewChars;
Result.PruneOpts.Model := Cfg.PlanModel;
Result.CompactModel := BackgroundModelFor(Cfg);

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 Keep background models on their configured provider

When a CLI turn uses --provider (or another path supplies a provider different from default_provider), this assigns background_model/fast_model, which is documented as belonging to the default provider, to the existing turn provider. Once compaction triggers, that provider receives a model name from a different provider and can reject the request, interrupting the turn. The background model needs a matching provider instance, or this override should be skipped when the active provider differs.

Useful? React with 👍 / 👎.

Comment thread src/pkg/agent/PasClaw.Agent.Prompt.pas Outdated
Comment on lines +393 to +394
if Cut <= 1 then Cut := Budget;
Result := TrimRight(Copy(Body, 1, Cut));

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 Preserve UTF-8 boundaries when truncating long lines

If an over-budget memory file has no newline before the limit, Cut := Budget truncates the raw UTF-8 byte string at an arbitrary byte. A budget landing inside a multibyte character therefore injects malformed UTF-8 into every subsequent model request; this is especially likely for single-line JSON or prose containing non-ASCII text. Move the fallback cut backward to a valid UTF-8 boundary before copying.

Useful? React with 👍 / 👎.

Comment thread src/pkg/checkpoints/PasClaw.Backup.pas Outdated
Exit;
end;
try
Walk(WsDir, '', Files);

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 Exclude an in-workspace backup destination from the archive

When backup.dir or --to points anywhere under the workspace, this unrestricted walk includes all previously generated ZIPs in the next archive. Repeated backups then recursively embed retained backups and rapidly grow in size, potentially exhausting storage. Reject destinations beneath WsDir or explicitly exclude the destination subtree from the walk.

Useful? React with 👍 / 👎.

… cheap tier for background work

What the setups that stay good for months have in common, built in:

Tier-1 memory is capped and split. The always-loaded files -- SOUL.md,
USER.md (both new, optional), MEMORY.md, today's and yesterday's note --
are each cut at memory_core_budget_bytes (default 16 KB, 0 = no cap) on
a line boundary, with a note telling the model how much was elided and
that memory_search reaches it. The memory rule in the system prompt now
carries the six-months test: if it would not matter in six months with
no refresher it goes in a dated note or a fact with an expiry, not in
these files. ClampToBudget is pure and tested; the injection order,
the note, and budget 0 are tested against a temp PASCLAW_HOME.

pasclaw maintain is the nightly loop. One pass: sweep expired facts and
superseded facts older than maintenance.keep_superseded_days (the
schema had the expires column and the index and never the sweep --
IFactStore.Sweep, tested); size the tier-1 files against the budget;
walk the last N days of sessions for turns, tool calls, failures with
samples, tokens; list callable skills nothing invoked in
unused_skill_days and pairs that look like the same skill twice;
optionally ask the background model for a 200-word critique; optionally
back up; write memory/maintenance/<date>.md. Scheduled with the reserved
cron skill name @Maintain, which the gateway scheduler runs in-process
(and the model's cron tool accepts). Reported, never deleted: skills and
MEMORY.md lines are the operator's call. Tested end to end against a
temp home with a fact store, sessions, skills and an over-budget file;
the sweep was negative-tested.

pasclaw backup / restore. The archive holds the workspace (minus the
WebView2 profile, SQLite journals, .git), config.redacted.json with every
secret masked by the same function the gateway's GET /v1/config now
uses (MaskConfigSecretsJSON, factored out so the two cannot disagree),
and a RESTORE.md naming the version, the restore command and the secrets
to re-enter. Rotation keeps the newest archive of each of the last 7
days / 4 ISO weeks / 6 months that have one (borg's rule, so a machine
off for a fortnight does not delete its history), never touches files it
did not name, and never prunes after a failed write. Restore validates
members, refuses an existing workspace without --force, and never writes
config.json. Names, rotation, masking, packing, exclusions and the
round-trip are tested.

background_model. One key (falls back to fast_model, then the main
model) now carries fact distillation (CLI, TUI, gateway), history
compaction (TToolLoopConfig.CompactModel), the heartbeat, the goals
judge and the maintenance review. A config with neither key behaves
exactly as before. pasclaw route report aggregates saved sessions by
provider/model with token volume beside the cheap-tier settings, so the
split is visible; it says plainly that a session counts under its last
model, so the cheap share is a floor.

Docs: memory.md gains the three tiers, the six-months test and the
budget, and no longer claims SCARS.md is injected (it never was);
checkpoints.md no longer says off by default (it is on);
agent-features.md's distiller, tiered-memory and tier-aware-routing rows
match the code; new maintenance.md and backup.md; configuration.md,
commands.md, cron.md and the docs index updated.

Full make test: 41 passes, 0 make errors (three new targets:
test-memory-tiers, test-backup, test-maintain). The new commands were
also run against a scratch home from the built binary.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
@FMXExpress
FMXExpress force-pushed the claude/keen-einstein-kPEMj branch from 77b02e1 to 575871b Compare October 17, 2026 05:24
…stays on its provider, clean UTF-8 cuts, no recursive backups

Backups now include config.json by default. The review's P1 was right
that config.redacted.json still carried credentials -- channels[].target
and crons[].channel_target are webhook URLs with the token in them -- and
the operator's point was more right: a backup that breaks every
connected API on restore is not much of a backup. So backup.include_secrets
defaults to true, the archive carries the real config.json, RESTORE.md
says in so many words that the archive is a credential, and restore puts
config.json in place when the home has none (with --force it keeps the
old one as config.json.bak and replaces it). The redacted form is still
there for an archive that will sit somewhere shared: `pasclaw backup
--redact` or include_secrets: false, and that masking now covers the
channel and cron targets too, in MaskConfigSecretsJSON, so the gateway's
GET /v1/config stops leaking them as well. Both forms and the restore
paths are tested; the real key is asserted present in the one and absent
in the other.

background_model stays on its provider. BackgroundModelOn(Cfg, Active)
returns the cheap model only when the work runs on the default provider
-- the active name matching the default entry's name or its kind (what
ILLMProvider.GetName returns) -- and '' otherwise, so a --provider
override or a request that picked another provider keeps its own model
instead of being handed a name it cannot serve. The CLI passes
--provider, the TUI its new ProviderName, the gateway the loop
provider's GetName. Unit-tested for name, kind, case and mismatch.

ClampToBudget never cuts inside a UTF-8 sequence. When there is no
newline to cut at, the fallback steps back over continuation bytes so the
kept part ends on a whole character. Tested with a 2-byte and a 4-byte
character straddling the budget.

A backup destination inside the workspace is excluded from the walk, so
the second backup does not contain the first. Tested with two backups
into <workspace>/backups.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
@FMXExpress
FMXExpress merged commit 58d3151 into main Oct 17, 2026
FMXExpress pushed a commit that referenced this pull request Oct 17, 2026
Covers what landed since v0.1.4: the PasClaw Browser (#604) and the
memory tiers / nightly maintenance / backup-restore / background cheap
tier work (#606). VersionFallback, the installer default and its
documented value, and the .dproj FileVersion / ProductVersion / Release
all move together; `make lint-version` agrees. Changelog entries added
for both PRs in docs/changelog.md and the README mirror.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
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