Skip to content

fix(backup): preserve configured agent state roots - #129773

Merged
steipete merged 2 commits into
mainfrom
steipete/goofy-raman-9831d5
Aug 26, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/goofy-raman-9831d5

Conversation

@steipete

@steipete steipete commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Closes #129730

What Problem This Solves

Fixes an issue where operators using agents.entries.*.agentDir outside the default state layout could create a backup that silently omitted durable agent state. A custom agent database covered incidentally by another source could also miss the normal agent-owned SQLite snapshot guarantees.

Why This Change Was Made

Backup planning now builds one configuration-derived ownership inventory for state, configured agent roots, and manifest-declared plugin resources. Archive creation, dry-run output, SQLite discovery and compaction, verification, restore containment, and Git/SQLite backup selection reuse that inventory instead of reconstructing the default agent layout.

Plugins can declare state- or agent-relative durable and regenerable roots through manifest metadata. The Codex plugin uses that generic contract for upstream-owned temporary roots; core contains no plugin IDs or provider-specific backup policy.

The archive stays schema version 1 and keeps its existing payload encoding. Additive paths.agentRoots metadata lets verification preserve exact custom-agent ownership while older archives remain supported.

AI-assisted implementation; maintainer reviewed the architecture, tests, generated diff, and final behavior.

User Impact

Operators can rely on full backups when agent state is configured outside <stateDir>/agents/<id>/agent. Custom agent databases retain committed WAL data, exclude sidecars and deleted-page remnants, validate the exact agent owner, and restore through the same verified archive flow as default-layout agents.

Regenerable plugin/runtime trees are excluded by their owner declarations without allowing an exclusion to remove canonical state or agent databases. Custom directories named tmp or .tmp remain durable unless an active owner explicitly declares them regenerable.

Evidence

  • Pre-fix reproduction: openclaw backup create --dry-run --json --no-include-workspace listed only the state asset while a configured external agentDir with durable data existed.
  • Post-rebase focused matrix: 216 tests passed. After addressing every ClawSweeper finding, the follow-up archive/command/plugin matrix passed 184 tests with one existing skip.
  • ClawSweeper findings resolved: canonical global role/integrity validation survives an enclosing agent root; invalid declarations from inactive workspace plugins remain inert; public nested-include precedence now matches runtime behavior.
  • node scripts/check-changed.mjs -- <touched paths> passed all selected formatting, typecheck, lint, architecture, metadata, and guard lanes.
  • pnpm check:docs passed.
  • pnpm build passed. The only ineffective-dynamic-import warnings were the pre-existing Control UI warnings for viewer-facepile.ts and lobster-pet.ts.
  • pnpm plugin-sdk:surface:check passed.
  • Fresh uncommitted autoreview after the review fixes reported no accepted/actionable findings.
  • Exact-head CI passed on run 32925661740, attempt 2. The first build-artifacts attempt hit the known three-byte Control UI gzip variance tracked in Control UI startup JS gzip budget is saturated (0 headroom) — needs deliberate re-baseline or startup-chunk diet #121497; the unchanged exact-head rerun passed.
  • Production LOC is positive because this adds a new generic ownership boundary and public plugin manifest contract; src/infra/backup-create.ts shrank by roughly 440 lines as duplicate filtering and SQLite policy moved to coherent owners.

Inventory configured agent directories as durable backup owners regardless of layout. Reuse the owner inventory for archive planning, SQLite snapshotting, verification, restore safety, and Git/SQLite backup selection.

Add manifest-first plugin backup resource declarations so regenerable runtime roots stay plugin-owned without provider IDs in core.

Closes #129730
@clawsweeper

clawsweeper Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime commands Command implementations docker Docker and sandbox tooling extensions: codex size: XL maintainer Maintainer-authored PR labels Aug 26, 2026
@steipete
steipete marked this pull request as ready for review August 26, 2026 02:20
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 26, 2026
@clawsweeper

clawsweeper Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 25, 2026, 11:47 PM ET / August 26, 2026, 03:47 UTC.

ClawSweeper review

What this changes

The PR inventories configured agent directories as durable backup roots and adds active-plugin manifest metadata for durable or regenerable backup resources.

Regression provenance

Possible regression — probable (reproduction; reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep open for maintainer review. The shared inventory appears to address the configured-agent backup omission across archive and SQLite paths, but the new Codex-specific regenerable exclusions lack the required direct upstream Codex source proof.

Priority: P1
Reviewed head: 923c89c03bdd6370bb1727e9d7744aa1af441674
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The core repair is well-covered, but the unresolved upstream Codex lifecycle contract prevents a higher-confidence merge assessment.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: This MEMBER-authored deterministic CLI/storage repair is exempt from the external-contributor proof gate; the PR supplies exact-head test and CI claims.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This MEMBER-authored deterministic CLI/storage repair is exempt from the external-contributor proof gate; the PR supplies exact-head test and CI claims.
Evidence reviewed 6 items Configured-agent ownership: The PR resolves every configured agent directory into a canonical backup root and database path, then feeds those roots into backup planning.
Canonical SQLite treatment: SQLite discovery recognizes configured agent database paths as canonical owners and applies owner validation during snapshot creation.
Manifest safety boundary: Plugin backup resources are considered only for effectively activated, loadable manifests; invalid inactive declarations remain inert.
Findings None None.
Security None None.

Live Verification

Command: pnpm test src/infra/backup-create.test.ts src/commands/backup-verify.test.ts

Result: FAIL (failed) — step 1 run pnpm test src/infra/backup-create.test.ts src/commands/backup-verify.test.ts: previous terminal command was still running after 30 seconds: "pnpm test src/infra/backup-create.test.ts src/commands/backup-verify.test.ts"

$ node --import tsx scripts/test-projects.mts src/infra/backup-create.test.ts src/commands/backup-verify.test.ts
[test] starting test/vitest/vitest.infra.config.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-129773-djTObN/target

Assertions:

  • FAIL expect_output: Test Files

How this fits together

Backup planning turns configuration and active plugin metadata into archive assets, SQLite snapshots, Git snapshots, verification rules, and restore containment checks. Configured agent roots feed this inventory so their session and credential database is handled as agent-owned state even outside the default state directory.

flowchart LR
  Config[Agent configuration] --> Inventory[Backup ownership inventory]
  Plugins[Active plugin manifests] --> Inventory
  Inventory --> Archive[Archive planner]
  Inventory --> Snapshot[SQLite and Git snapshots]
  Inventory --> Verify[Archive verification]
  Inventory --> Restore[Restore containment]
  Archive --> Backup[Verified backup]
  Snapshot --> Backup
Loading

Decision needed

Question Recommendation
Can the three Codex-home paths declared regenerable be accepted without direct upstream source proof of their lifecycle? Require upstream Codex proof: Inspect the exact upstream runtime paths and retain only exclusions proven to be regenerable.

Why: The repository policy requires direct sibling Codex inspection for this dependency-backed claim, and the current checkout cannot establish that contract.

Before merge

  • Resolve merge risk (P1) - If any declared Codex path holds durable upstream state, its new regenerable classification would silently omit it from backups.
  • Complete next step (P2) - The remaining blocker is direct upstream dependency-contract proof, not a narrow mechanical repair.
Agent review details

Security

None.

PR surface

Source +579, Tests +1038, Docs +124, Other -2. Total +1739 across 32 files.

View PR surface stats
Area Files Added Removed Net
Source 16 1214 635 +579
Tests 8 1077 39 +1038
Docs 6 180 56 +124
Config 0 0 0 0
Generated 0 0 0 0
Other 2 1 3 -2
Total 32 2472 733 +1739

Review metrics

Metric Value Why it matters
Production versus test delta production +1,213/-620 (net +593); tests/support +1,078/-54; docs +180/-56 Positive production growth introduces a generic ownership and manifest contract; the removed archive-planning code and broad test coverage partly absorb that expansion.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/commands/backup-restore.ts, migration/backfill/repair: src/commands/backup-shared.ts, serialized state: src/commands/backup-restore.test.ts, serialized state: src/infra/backup-create.test.ts, serialized state: src/plugins/manifest-backup-resources.test.ts, serialized state: src/snapshot/git-backup.test.ts, and 2 more. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #129730
Summary: This PR explicitly implements the configured custom-agent-directory backup fix reported by the canonical issue.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Prove Codex resource ownership (recommended)
    Verify each Codex path against upstream source before allowing it to be omitted from an operator backup.
  2. Pause the Codex exclusions
    Land no provider-specific omission until its upstream lifecycle contract can be inspected.

Technical review

Best possible solution:

Keep the generic inventory, but merge the Codex exclusions only after direct upstream source evidence confirms each declared path is recreatable and contains no durable state.

Do we have a high-confidence way to reproduce the issue?

Yes, source-reproducible: configure an external agentDir, add durable data, and run the documented backup dry-run path; the new resolver and focused tests target that exact boundary, though this read-only review did not execute it.

Is this the best way to solve the issue?

Unclear: one shared ownership inventory is the maintainable core repair, but the Codex-specific exclusions need direct upstream lifecycle proof before they are the best safe solution.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 345cfde43dc9.

Labels

Label justifications:

  • P1: The pre-fix behavior can silently omit configured agent state from a disaster-recovery backup.
  • merge-risk: 🚨 compatibility: The PR changes archive manifest metadata and backup selection for existing configured agent directories and active plugins.
  • merge-risk: 🚨 session-state: Configured agent databases hold session and auth state and are newly routed through canonical snapshot and verification logic.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This MEMBER-authored deterministic CLI/storage repair is exempt from the external-contributor proof gate; the PR supplies exact-head test and CI claims.

Evidence

What I checked:

Likely related people:

  • steipete: The available blame attributes the shared backup ownership implementation to this contributor; deeper local history is shallow. (role: feature introducer; confidence: medium; commits: 7ef19b0a652a, 923c89c03bdd; files: src/commands/backup-shared.ts, src/infra/backup-sqlite-snapshot.ts, src/plugins/manifest-backup-resources.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Inspect upstream Codex source for each declared regenerable path and record that it is recreated rather than durable.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (2 earlier review cycles)
  • reviewed 2026-08-26T02:30:08.199Z sha 7ef19b0 :: found issues before merge. :: [P1] Preserve canonical database roles under an enclosing agent root | [P1] Ignore invalid declarations from inactive workspace plugins | [P2] Describe nested include precedence accurately
  • reviewed 2026-08-26T03:20:07.699Z sha 923c89c :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 26, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Land-ready proof for exact head 923c89c03bdd6370bb1727e9d7744aa1af441674:

The first build-artifacts attempt exceeded the saturated Control UI startup gzip baseline by 3 bytes, matching the known nondeterminism tracked in #121497; the unchanged exact-head rerun passed. No product proof gaps remain for this deterministic CLI/storage repair.

@steipete

Copy link
Copy Markdown
Contributor Author

Direct upstream Codex ownership proof for the three backupResources exclusions, inspected at openai/codex 80e871309aec1ee2cc2fe58e4da61ccffc7ee3fd:

  • codex-home/tmp/arg0: Codex explicitly calls this a CODEX_HOME-scoped temp root, runs a stale-directory janitor, and creates per-session TempDir entries inside it. Source: https://github.com/openai/codex/blob/80e871309aec1ee2cc2fe58e4da61ccffc7ee3fd/codex-rs/arg0/src/lib.rs#L356-L375
  • codex-home/.tmp/plugins: Codex defines this as the curated plugins checkout, obtains it from the upstream repository/archive, stages a replacement, activates that checkout, and writes the fetched SHA. Source: https://github.com/openai/codex/blob/80e871309aec1ee2cc2fe58e4da61ccffc7ee3fd/codex-rs/core-plugins/src/startup_sync.rs#L31-L40 and https://github.com/openai/codex/blob/80e871309aec1ee2cc2fe58e4da61ccffc7ee3fd/codex-rs/core-plugins/src/startup_sync.rs#L185-L229
  • codex-home/.tmp/bundled-marketplaces: upstream Codex reserves this as its managed local marketplace root. Source: https://github.com/openai/codex/blob/80e871309aec1ee2cc2fe58e4da61ccffc7ee3fd/codex-rs/core-plugins/src/marketplace_policy.rs#L493-L503. The owning OpenClaw Codex plugin rebuilds that wrapper from the installed bundled marketplace source and atomically replaces only an owned prior wrapper:
    export function resolveCodexManagedBundledMarketplacePath(codexHome: string): string {
    return path.join(codexHome, ".tmp", "bundled-marketplaces", MARKETPLACE_NAME);
    }
    export async function ensureCodexManagedBundledMarketplace(params: {
    codexHome: string;
    ownershipRoot: string;
    appServerCommand?: string;
    candidates?: readonly MacOSDesktopCodexAppPathCandidate[];
    ownershipCandidates?: readonly MacOSDesktopCodexAppPathCandidate[];
    assertCurrent?: () => void;
    }): Promise<string | undefined> {
    const candidates = params.candidates ?? resolveMacOSDesktopCodexAppPathCandidates();
    const source = await resolveCodexManagedBundledMarketplaceSource({ ...params, candidates });
    if (!source) {
    return undefined;
    }
    const parentPath = path.dirname(resolveCodexManagedBundledMarketplacePath(params.codexHome));
    const targetPath = path.join(parentPath, MARKETPLACE_NAME);
    const parent = await prepareOwnedServiceParent({
    ownershipRoot: params.ownershipRoot,
    codexHome: params.codexHome,
    targetParent: parentPath,
    });
    const physicalTargetPath = path.join(parent.realPath, MARKETPLACE_NAME);
    await assertNotSymlink(physicalTargetPath, "managed bundled marketplace");
    const active = activeInstalls.get(physicalTargetPath);
    if (active) {
    if (active.sourcePath === source.bundledMarketplacePath) {
    return await active.promise;
    }
    await active.promise.catch(() => undefined);
    return await ensureCodexManagedBundledMarketplace(params);
    }
    const install = reconcileManagedWrapper({
    parent,
    physicalTargetPath,
    targetPath,
    source,
    ownershipCandidates: params.ownershipCandidates ?? candidates,
    assertCurrent: params.assertCurrent,
    });
    const activeEntry = { sourcePath: source.bundledMarketplacePath, promise: install };
    activeInstalls.set(physicalTargetPath, activeEntry);
    const clearActive = () => {
    if (activeInstalls.get(physicalTargetPath) === activeEntry) {
    activeInstalls.delete(physicalTargetPath);
    }
    };
    void install.then(clearActive, clearActive);
    return await install;
    }
    async function reconcileManagedWrapper(
    params: Parameters<typeof publishManagedWrapper>[0],
    ): Promise<string> {
    if (await wrapperMatches(params.physicalTargetPath, params.source.bundledMarketplacePath)) {
    return params.targetPath;
    }
    return await publishManagedWrapper(params);
    and
    const stagingPath = await fs.mkdtemp(path.join(parent.realPath, `.${MARKETPLACE_NAME}.staging-`));
    const backupPath = path.join(
    parent.realPath,
    `.${MARKETPLACE_NAME}.backup-${process.pid}-${Date.now()}`,
    );
    let backupCreated = false;
    try {
    const manifestParent = path.join(stagingPath, ".agents", "plugins");
    await fs.mkdir(manifestParent, { recursive: true, mode: 0o700 });
    await Promise.all([
    fs.symlink(
    path.join(source.bundledMarketplacePath, ".agents", "plugins", "marketplace.json"),
    path.join(manifestParent, "marketplace.json"),
    ),
    fs.symlink(
    path.join(source.bundledMarketplacePath, "plugins"),
    path.join(stagingPath, "plugins"),
    ),
    ]);
    await assertDirectoryIdentityStable(parent, "managed bundled marketplace parent");
    const existing = await fs.lstat(physicalTargetPath).catch((error: unknown) => {
    if (hasNodeErrorCode(error, "ENOENT")) {
    return undefined;
    }
    throw error;
    });
    if (existing && !existing.isDirectory()) {
    throw new Error(`Managed bundled marketplace must be a real directory: ${targetPath}`);
    }
    if (existing && !(await wrapperMatchesAnySource(physicalTargetPath, ownershipCandidates))) {
    throw new Error(
    `Refusing to replace an unowned bundled marketplace directory: ${targetPath}`,
    );
    }
    if (existing) {
    assertCurrent?.();
    await fs.rename(physicalTargetPath, backupPath);
    backupCreated = true;
    await assertDirectoryIdentityStable(parent, "managed bundled marketplace parent");
    }
    assertCurrent?.();
    await fs.rename(stagingPath, physicalTargetPath);
    await assertDirectoryIdentityStable(parent, "managed bundled marketplace parent");
    if (backupCreated) {
    await fs.rm(backupPath, { recursive: true });
    backupCreated = false;

These are generated/session-temporary owner roots, not durable Codex threads, config, authentication, or operator state. The manifest exclusions are therefore retained as declared.

@steipete
steipete merged commit 2f17d11 into main Aug 26, 2026
354 of 357 checks passed
@steipete
steipete deleted the steipete/goofy-raman-9831d5 branch August 26, 2026 04:13
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 26, 2026
* fix(backup): honor configured agent state roots

Inventory configured agent directories as durable backup owners regardless of layout. Reuse the owner inventory for archive planning, SQLite snapshotting, verification, restore safety, and Git/SQLite backup selection.

Add manifest-first plugin backup resource declarations so regenerable runtime roots stay plugin-owned without provider IDs in core.

Closes openclaw#129730

* fix(backup): preserve canonical ownership checks
vincentkoc added a commit that referenced this pull request Aug 26, 2026
* origin/main: (24 commits)
  fix(gateway): reject rootless session permission modes (#128149)
  docs(memory): document shipped turn-taint propagation for network tool output (#129837)
  fix(ui): pool reply-less wake activity into one chat rollup (#128442)
  fix(package): prevent installs from deleting validated runtime assets (#129724)
  fix(nodes): approve silent initial node surfaces and name the pending surface approval (#129795)
  fix(backup): preserve configured agent state roots (#129773)
  fix(ui): own chat history issuance with a closed state machine (#129776)
  fix(cron): preserve cancellation reason after late finalization (#129331)
  fix(cron): prevent run waits from failing after clock changes (#129805)
  fix(telegram): route commentary through one frozen progress owner (#128259)
  fix(release): start approved VCR mirror recovery jobs (#129829)
  test: complete current-plugin-metadata-snapshot mock factories (#129791)
  test(telegram): remove duplicate reaction case (#129848)
  fix(channels): honor supported account reply-threading policies (#129679)
  refactor(cli): deduplicate lazy subcommand registration (#129351)
  fix(ai): report interrupted local-model streams instead of empty success (#129794)
  refactor(cli): consolidate Gateway fallback and hook ownership (#129802)
  fix(qa): reject token confidence lanes without executed evidence (#129830)
  fix(tui): fence session state and delayed actions (#129810)
  fix(control-ui): keep task progress full width on hover (#129832)
  ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations docker Docker and sandbox tooling docs Improvements or additions to documentation extensions: codex gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: backup omits configured custom agent directories

1 participant