Skip to content

feat(root): add guarded file copies and clone strategies - #302

Merged
steipete merged 4 commits into
mainfrom
codex/fs-safe-root-copy
Sep 13, 2026
Merged

steipete merged 4 commits into
mainfrom
codex/fs-safe-root-copy

Conversation

@steipete

@steipete steipete commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Consumers cannot currently copy a file exclusively through Root.copyIn, copy directly from another guarded Root, or cancel an in-flight copy. They must buffer the entire file for Root.create or manage source admission, copying, permissions, and cleanup themselves. This affects worktree provisioning and workspace attachments in OpenClaw.

Why This Change Was Made

Extends the existing Root.copyIn owner with guarded source capabilities, completed-file exclusive publication, bounded positional reads, cancellation, and optional native file cloning. Copying uses the shared guarded write loop and existing staged-file lifecycle. File data remains independent between source and destination.

await destination.copyIn("config.json", {
  root: source,
  relativePath: "config.json",
}, {
  overwrite: false,
  clone: "auto",
  preserveSourceMode: true,
  signal,
});

The source capability needs only open and stat; callers can supply their existing read-only Root facade. An omitted sourceHardlinks option retains that Root's read default, while explicit allow/reject overrides remain effective. Source read policies and destination mutation policies stay with their respective Root owners, including final-symlink checks before publication.

Root.copyIn and copyTree from #301 share the CopyCloneMode policy and validation through a small module that does not load the tree runtime. Root keeps its guarded regular-file admission and publication contract; copyTree keeps its separate caller-owned immutable-tree and metadata contract. File cloning does not introduce Btrfs subvolume semantics into ordinary file copies.

User Impact

Existing pathname sources, replacement defaults, mode selection, and durability behavior remain supported. overwrite: false preserves existing files, including unreadable files, and publishes only completed contents. The native writer uses no-replace rename; the guarded Node fallback links the completed private stage and removes its temporary name in the same JavaScript turn. That fallback requires filesystem hardlink support and never links the source file to the destination.

clone accepts auto, always, or never. Root defaults to never, using ordinary positional reads and writes without explicit cloning or copy offload; tree copying retains its auto default. Automatic file copying may use native cloning or Linux copy offload before ordinary byte copying. APFS and supported Linux filesystems can clone files. Windows and older native bindings use bounded byte copying for never and auto; always reports unavailable cloning. Native binding configuration's separate require mode is unchanged. preserveSourceMode uses the admitted source descriptor; a numeric per-call mode or Root default takes precedence.

Cancellation waits for admitted work to settle before cleanup. A synchronous onDestinationPublished callback records the destination path and exact bigint device/inode identity before later checks can fail. Published destinations are preserved after cancellation or subsequent failure; the receipt records an outcome and does not authorize deleting later edits. Source identity is checked, while coherent snapshots still require the caller to keep source contents unchanged. Existing calls without new options must also account for post-publication source-verification failure rejecting with the completed destination retained. Archive merges remain incremental and never gain a separate rollback owner.

The native transfer retains close-on-exec descriptors, keeps ownership of failed-copy descriptors through settlement, and reports incomplete clone cleanup instead of hiding it behind automatic fallback. The existing Linux copy-range source-inspection failure also no longer leaves a newly created file. On Windows, file copies preserve their published destination when final permissions or synchronization fail; existing buffer and stream write cleanup behavior remains intact.

Evidence

  • The combined required-native selection passed every file-copy, tree-copy, clone, TAR-buffer, source-policy, authority, and publication case. Its sole failure was the unchanged append-authority test's expensive Buffer comparison. Full pnpm check likewise passed 8,896 tests with 101 skips and failed only that comparison. Replacing it with exact Buffer.equals preserved all dispatch, refusal, length, and content assertions; the same isolated command then passed all four tests. No timeouts, thresholds, retries, or expected failures changed.

  • Public Root.copyIn tests observe actual native transfer methods: never uses ordinary copying and APFS auto uses cloning. Strict always copying verifies APFS shared clone IDs, complete contents despite an advanced source offset, and independent subsequent writes. The Rust Linux matrix requires never to report ordinary copying, so copy-offload dispatch is covered on CI.

  • The combined current-main native addon and package builds passed. All 80 Rust workspace tests passed, including file strategies, source growth limits, descriptor ownership, and cancellation. Documentation examples, regenerated public API inventory, package checks, filesystem boundary checks, size limits, and whitespace checks passed.

  • A public-API run canceled an observed in-flight 256 MiB native copy and found no remaining temporary or destination entry after rejection:

    {"bytes":268435456,"observedRunningStage":true,"outcome":"canceled","remainingEntries":0}
  • Four Windows-writer permission/sync failure regressions reproduced a missing published destination before the repair and then passed with preserved receipts, data, and settled handles. Existing native and musl CI jobs explicitly run the copy, parent-policy, authority, dispatch, and publication suites; runner fanout is unchanged.

  • Source-swap coverage still requires path-mismatch and verifies the retained published inode, admitted bytes or later edit, replacement source, and moved original source. Guarded sources retain omitted hardlink defaults while explicit allow/reject overrides remain effective.

  • The copy matrix's 262,175-byte fixtures remain byte-identical. Seed filling and exact Buffer.equals assertions reduced the four focused coverage cases from 1,462–1,839 ms to 34–56 ms without changing timeouts or coverage thresholds.

  • Fresh independent reviews are clean through P2 for the full copy composition and Windows repair, source/default recovery corrections, unified file/tree policy, and the final one-line append comparison repair. Final exact-head cross-platform CI and coverage are green.

Related: #296, #297. No version bump or release is included.

  • Tests added or updated when behavior changed
  • Security and compatibility impact considered
  • CHANGELOG.md updated when release-relevant
  • No credentials, private paths, private hosts, or sensitive contents included

Current-main integration

Rebased onto #303 without changing any executable or test patch in this PR; the only conflict was release-note context. The combined source preserves structured Windows permission checks and encoded append handling. Focused copy, authority, encoded-append, and permission verification passed 187 tests with four platform skips; build, docs, package, boundary, and size checks passed. The previous exact copy head passed all 15 CI jobs, platform coverage and aggregate thresholds, CodeQL, and benchmarks. The rebased head passed its complete CI and coverage runs on the first attempt.

Maintainer decision: accept the documented publication-retention contract for existing and new copyIn calls. Completed destinations remain after late verification, cancellation, or metadata failure; caller-owned recovery must inspect current state before taking another action. Incremental archive merges follow that same contract. File and tree copying share CopyCloneMode and retain their separate admission, metadata, and publication responsibilities.

Final head 460217368a5ed841100b6eb2a427ec24739e067c passed all 15 CI jobs, every platform and aggregate coverage, CodeQL, and benchmarks, without retries or cancellations. Earlier macOS setup-only cancellations on the prior head were recovered before its checks passed; no source failure was attributed to those cancellations.

@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@steipete
steipete marked this pull request as ready for review September 13, 2026 03:20
@steipete
steipete requested a review from a team as a code owner September 13, 2026 03:20
@clawsweeper clawsweeper Bot added P2 Normal priority bug or improvement with limited blast radius. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. proof: sufficient Contributor real behavior proof is sufficient. 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 Sep 13, 2026
@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 13, 2026, 1:11 AM ET / 05:11 UTC (Revision 4).

ClawSweeper review

What this changes

Extends guarded file copying with Root sources, exclusive publication, cancellation, publication receipts, and optional native cloning.

Merge readiness

⛔ Blocked before merge - 3 items remain

This PR provides distinct functionality absent from current main. Earlier documentation and archive-test findings are resolved, and no new blocking code defect was found; the intentional recovery-contract change still needs maintainer acceptance.

Priority: P2
Reviewed head: 460217368a5ed841100b6eb2a427ec24739e067c
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent implementation with relevant real behavior evidence and resolved prior findings; compatibility acceptance remains a landing decision.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The captured public-API run observes an active 256 MiB native copy, cancels it, and records zero remaining entries after settlement, directly exercising the new transfer and cleanup owners; filesystem and policy regressions supplement that proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured public-API run observes an active 256 MiB native copy, cancels it, and records zero remaining entries after settlement, directly exercising the new transfer and cleanup owners; filesystem and policy regressions supplement that proof.
Evidence reviewed 8 items Applicable repository policy: Read the complete root AGENTS.md and CONTRIBUTING.md. No nested AGENTS.md or maintainer-notes directory was found. Public compatibility, guarded cleanup, documentation, and regression requirements informed this review.
Current main still lacks the requested options: Current main's RootCopyOptions only adds sourceHardlinks to the shared mutation options; its copyIn source remains a string. The merged tree-copy work at #301 has a separate immutable-tree contract and does not supersede guarded file copying.
Release comparison: Read v0.9.0's root implementation through the GitHub contents API after its local blob was unavailable. Its copyIn accepts a pathname and lacks the new exclusive-copy, cancellation, receipt, and clone options.
Findings None None.
Security None None.

How this fits together

fs-safe's Root API confines filesystem operations to a trusted directory. File copies admit a source descriptor, prepare independent destination data, and publish it through guarded native or JavaScript writers.

flowchart TD
  A[Path or source Root] --> B[Source admission and identity checks]
  B --> C[Bounded copy or native clone]
  C --> D[Private destination stage]
  D --> E[Authority and destination checks]
  E --> F[Atomic publication and receipt]
  F --> G[Preserve published destination]
  D --> H[Clean unpublished stage on failure]
Loading

Decision needed

Question Recommendation
Accept retaining completed destinations after post-publication copyIn failures for existing callers without new options? Accept the documented recovery contract: Retain completed publications and approve the documented requirement that callers inspect destination state after rejection.

Why: This deliberately changes an existing recovery contract; documentation and tests establish the behavior but cannot establish maintainer acceptance of the upgrade impact.

Before merge

  • Resolve merge risk (P1) - Existing callers can receive a source-verification rejection with a completed destination retained; recovery code that assumes rejection removed the destination may behave incorrectly after upgrading.
  • Complete next step (P2) - Obtain maintainer acceptance of the documented retained-destination recovery behavior for existing copyIn callers.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Production and test growth Production +781 lines; tests and API inventory +875 lines Net growth includes Rust tests counted separately; the new transfer strategies and publication lifecycle explain the production expansion.

Merge-risk options

Maintainer options:

  1. Approve retained-publication recovery (recommended)
    Accept the documented change for existing callers while retaining tests that preserve published bytes and later edits.
  2. Pause for a compatibility transition
    Defer landing if existing consumers require a migration or release boundary before adopting the new recovery contract.

Technical review

Best possible solution:

Keep completed publications protected from rollback deletion, with explicit maintainer acceptance and clear recovery guidance for existing callers.

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

Not applicable as a feature request; current main lacks the proposed options, and the supplied public-API cancellation output demonstrates the changed runtime path.

Is this the best way to solve the issue?

Yes, extending the existing guarded writer and sharing clone policy is a coherent solution; the intentional recovery change needs explicit acceptance.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 1aa2149e27f5.

Labels

Label justifications:

  • P2: This is a bounded filesystem-copy capability improvement without evidence of an urgent user-facing outage.
  • merge-risk: 🚨 compatibility: Existing copyIn callers must tolerate a retained completed destination after post-publication rejection.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; 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. Sufficient (live_output): The captured public-API run observes an active 256 MiB native copy, cancels it, and records zero remaining entries after settlement, directly exercising the new transfer and cleanup owners; filesystem and policy regressions supplement that proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured public-API run observes an active 256 MiB native copy, cancels it, and records zero remaining entries after settlement, directly exercising the new transfer and cleanup owners; filesystem and policy regressions supplement that proof.

Evidence

What I checked:

  • Applicable repository policy: Read the complete root AGENTS.md and CONTRIBUTING.md. No nested AGENTS.md or maintainer-notes directory was found. Public compatibility, guarded cleanup, documentation, and regression requirements informed this review. (AGENTS.md:1, 460217368a5e)
  • Current main still lacks the requested options: Current main's RootCopyOptions only adds sourceHardlinks to the shared mutation options; its copyIn source remains a string. The merged tree-copy work at feat(copy): unify tree copying and add XFS reflinks #301 has a separate immutable-tree contract and does not supersede guarded file copying. (src/root-options.ts:47, 1aa2149e27f5)
  • Release comparison: Read v0.9.0's root implementation through the GitHub contents API after its local blob was unavailable. Its copyIn accepts a pathname and lacks the new exclusive-copy, cancellation, receipt, and clone options. (src/root-impl.ts:127, 0fc5776a510d)
  • Intentional compatibility change: The introduced removal of post-publication destination cleanup applies to existing calls without new options. Documentation explicitly tells callers to inspect destination state after rejection, and archive coverage verifies preservation of both admitted bytes and later edits. (docs/root.md:201, 460217368a5e)
  • Publication and authority safeguards: Reviewed source admission, bounded positional reads, retained native descriptors, final authority and symlink checks, and cleanup ownership. Native publication records its outcome before observers run; cleanup preserves published destinations. Focused tests cover traversal, competing destinations, revocation after reads, source swaps, and Windows post-publication failures. (src/native-staged-file.ts:255, 460217368a5e)
  • Real behavior evidence: The complete supplied PR body, captured under sourceRevision 45dfa842d82d46814d2d7de006fc70322b00de6706a581b7b183210257d97efe, records a public-API native copy of 268435456 bytes, an observed running stage, cancellation, and zero remaining entries. This exercises the new native transfer and settled cleanup path; reported APFS independence checks and focused suites provide supplemental coverage.

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Record maintainer acceptance of retained completed destinations after post-publication failures for existing copyIn callers.

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 (3 earlier review cycles)
  • reviewed 2026-09-13T03:25:43.058Z sha dee07a2 :: blocked before merge. :: [P2] Document the three newly exported copy types | [P2] Reconcile archive coverage with retained copy publications
  • reviewed 2026-09-13T03:56:22.733Z sha f8e1920 :: blocked before merge. :: none
  • reviewed 2026-09-13T04:47:09.922Z sha e9ee8d7 :: blocked before merge. :: none

@steipete
steipete force-pushed the codex/fs-safe-root-copy branch from dee07a2 to f8e1920 Compare September 13, 2026 03:51
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed 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 Sep 13, 2026
@steipete
steipete force-pushed the codex/fs-safe-root-copy branch from f8e1920 to e9ee8d7 Compare September 13, 2026 04:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. P2 Normal priority bug or improvement with limited blast radius. proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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.

1 participant