Skip to content

feat(copy): add a synchronous guarded clone-capable file copy - #839

Merged
steipete merged 4 commits into
mainfrom
feat/sync-clone-copy
Oct 6, 2026
Merged

steipete merged 4 commits into
mainfrom
feat/sync-clone-copy

Conversation

@steipete

@steipete steipete commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Synchronous plugin module hooks cannot await Root.copyIn, and fd-to-fd byte copying cannot use APFS's name-creating clone operation. Add copyRootFileSync to @openclaw/fs-safe/advanced for openclaw/openclaw#161739. It retains the admitted source, creates an exclusive destination under its admitted root, and returns the owned destination descriptor for capture hashes and receipts.

The public surface is one function and two types:

function copyRootFileSync(options: CopyRootFileSyncOptions): CopiedRootFileSync;

// CopyRootFileSyncOptions
{
  source: { rootPath: string; absolutePath: string };
  destination: { rootPath: string; absolutePath: string };
  clone?: "auto" | "always" | "never"; // default: never, as with copyIn
  maxBytes?: number;
  mode?: number;
  preserveSourceMode?: boolean;
  sourceHardlinks?: "reject" | "allow";
}

// CopiedRootFileSync
{
  readonly fd: number;
  readonly path: string;
  readonly bytes: number;
  readonly method: "clone" | "copy-file-range" | "copy";
  readonly identity: Readonly<{ dev: bigint; ino: bigint }>;
  close(): void;
  [Symbol.dispose](): void;
}

Both roots and paths are absolute, parents must already exist, and the destination must be absent. Source identity is checked before and after copying. Destination identity and single-link status are checked through both its descriptor and name. Failure attempts identity-checked cleanup; replacements are preserved. This is direct exclusive creation, so callers should use a private capture directory; it does not promise atomic publication, crash durability, or a coherent snapshot of concurrent in-place edits.

The N-API source inspection revealed that only cloneFileExclusive was synchronous: copyFileExclusive and copyFileRangeExclusive returned async tasks. The new internal synchronous entry shares the existing bounded FileCopyTask engine, including APFS cloning, Linux FICLONE/copy_file_range, the #829/#835 capability classification, and its cleanup owner. Windows and native-disabled operation compose the existing synchronous descriptor copier with guarded creation and #824's dangling-leaf preflight. Mandatory cloning without that capability reports unsupported-platform.

OpenClaw migration

In plugin-source-file.ts, replace the descriptor-path copyFileSync optimization and descriptor byte loop inside copyPluginSourceFile with:

using copied = copyRootFileSync({
  source: { rootPath: boundary, absolutePath: source },
  destination: { rootPath: options.captureRoot, absolutePath: target },
  clone: "auto",
  maxBytes: options.expectedSize,
  sourceHardlinks: "allow",
  mode: options.mode,
  preserveSourceMode: true,
});
return options.hashCopiedContent ? hashPluginSourceDescriptor(copied.fd) : undefined;

Retain the existing too-large error translation. The copier now performs admission itself; the copy path no longer needs the surrounding withPluginSourceFile open. Hashing reads the owned output, including for the clone path, and descriptor disposal does not delete the successful capture.

In plugin-generation-file-capture.ts, pass captureRoot: directory, expectedSize: Number(stat.size), and mode: 0o600 | Number(stat.mode & 0o100n) for a new source. Keep copiedContent as receipt.file({ prepared: native?.content ?? copiedContent, ... }); the separate target-path chmod is absorbed by the copy. For the captured alias branch, call the same helper with source: captured, boundary: directory, and the existing capture's size/mode facts, rather than the later live source's metadata. Preserve the native materialization branch and the existing path/addition/receipt bookkeeping.

Validation

Rust workspace tests, Clippy, native/TypeScript builds, package and declaration checks, and 101 focused tests pass locally. Coverage includes byte, native clone and copy-range routes; the existing isolated seccomp FICLONE-EPERM test now uses the shared synchronous task preparation; maxBytes; source replacement; destination collisions; dangling Windows leaves; destination-parent substitution before fallback creation; and destination replacement/hardlink creation during mode finalization. The hosted macOS test requires method === "clone" on APFS and verifies matching clone IDs.

A preliminary local APFS run copied a synthetic 1 GiB file in 18.3 s with never, versus 254 ms with auto, which selected clone and shared the source's clone ID. The clone produced no measured decrease in available filesystem space. This was under concurrent test load, not an isolated performance comparison. The optional Tart image pull was cancelled after ten minutes without an allocated lease; cleanup confirmed no remaining lease or VM.

Rebased onto #838 after the native move work landed; the only conflict was the changelog, where both entries were retained. The final branch passes Codex autoreview at P0–P2. Full serial pnpm check passed 17,211 tests and the package/declaration gate; a separate pnpm pack:check also passed. The rebased Rust workspace tests, Clippy, native/TypeScript builds, and 101 focused tests passed again.

CI initially caught the missing benchmark registration and slow deep Buffer assertions under coverage. Both are fixed: 12 synchronous copy benchmark cases pass with native support off/required, and the focused native suite passes under V8 coverage using full byte equality through Buffer.equals. Earlier local parallel-check timeouts in unchanged suites disappeared under the repository's serial setting.

Final head: 930a18d50243d09245c6e52b3dd3b64c8528a3cd. All-OS CI, coverage, and CodeQL all passed on this exact head. No admin override or CodeQL rerun was needed. No release.

@clawsweeper

clawsweeper Bot commented Oct 6, 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.

@clawsweeper clawsweeper Bot added P2 Normal priority bug or improvement with limited blast radius. 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 Oct 6, 2026
@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed October 6, 2026, 4:00 AM ET / 08:00 UTC (Revision 3).

ClawSweeper review

What this changes

Adds a synchronous guarded file copy with optional native cloning, byte limits, identity checks, and an owned destination descriptor.

Merge readiness

⛔ Needs changes before merge - 2 items remain

The synchronous copy capability remains useful and is absent from current main. The export and benchmark findings are resolved, but the previously reported writable-descriptor contract mismatch remains.

Priority: P2
Reviewed head: 930a18d50243d09245c6e52b3dd3b64c8528a3cd

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation and coverage are useful, but the remaining documented descriptor guarantee is incorrect on APFS.
Proof confidence 🌊 off-meta tidepool Not applicable: Repository State identifies the author as MEMBER, so the ordinary external-contributor proof gate does not apply. The captured body reports the changed synchronous copy path selecting APFS cloning with matching clone IDs; no stored-data contract changes occur.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Repository State identifies the author as MEMBER, so the ordinary external-contributor proof gate does not apply. The captured body reports the changed synchronous copy path selecting APFS cloning with matching clone IDs; no stored-data contract changes occur.
Evidence reviewed 9 items Applicable repository policy: Read the complete root AGENTS.md. No nested AGENTS.md or maintainer-notes directory was found. Filesystem guards and alignment of public documentation with implementation informed the review.
Pinned introduction and scope: Inspected the introduced delta from pinned main to the original PR head across all 14 files. The native change exposes the existing bounded copy engine synchronously; workflow changes only extend existing test invocations.
Capability remains missing on main: Current main exports the borrowed synchronous descriptor copier and root-file admission helpers, but no synchronous root-admitting clone-capable copy. These existing primitives do not supply the requested combined capability. No same-repository merged replacement was established.
Findings 1 actionable finding [P2] Limit the descriptor promise to supported read access
Security None None.

How this fits together

fs-safe guards filesystem operations on untrusted paths. This helper admits source and destination roots, copies through retained descriptors, and returns the destination descriptor for capture reads or hashing.

flowchart TD
  A[Source and destination paths] --> B[Root and identity admission]
  B --> C[Retained source descriptor]
  C --> D{Native copying available}
  D --> E[Clone or native copy]
  D --> F[Guarded byte copy]
  E --> G[Verify identities and limits]
  F --> G
  G --> H[Owned destination descriptor]
Loading

Before merge

  • Limit the descriptor promise to supported read access (P2) - The previously reported contract mismatch remains: successful APFS cloning opens the payload with O_RDONLY in native/src/unix.rs and returns that descriptor unchanged. A caller relying on this writable guarantee gets EBADF from fs.writeSync, although byte-copy routes permit writes. Document readable access as the portable guarantee; the intended hashing use needs only reads.
  • Complete next step (P2) - Replace the readable/writable descriptor promise with a readable cross-platform guarantee.

Findings

  • [P2] Limit the descriptor promise to supported read access — docs/copy.md:222-225
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Production and test LOC Production +283/-12; tests and package smoke +303/-1 Production growth supports the synchronous admission wrapper and shared native entrypoint, with focused boundary coverage.

Technical review

Best possible solution:

Guarantee readable descriptor access across platforms while retaining the shared guarded clone and copy engine.

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

Yes, by source inspection: successful APFS cloning returns an O_RDONLY descriptor despite the writable guarantee. No runtime reproduction was executed.

Is this the best way to solve the issue?

Yes, composing existing admission and copy owners is a focused solution for synchronous hooks; the descriptor documentation must match the APFS implementation.

Full review comments:

  • [P2] Limit the descriptor promise to supported read access — docs/copy.md:222-225
    The previously reported contract mismatch remains: successful APFS cloning opens the payload with O_RDONLY in native/src/unix.rs and returns that descriptor unchanged. A caller relying on this writable guarantee gets EBADF from fs.writeSync, although byte-copy routes permit writes. Document readable access as the portable guarantee; the intended hashing use needs only reads.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 47fc59892b45.

Labels

Label changes:

  • remove merge-risk: 🚨 automation: Current PR review selected no merge-risk labels.

Label justifications:

  • P2: This is a bounded copy capability improvement with a remaining platform-specific public-contract defect.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: Repository State identifies the author as MEMBER, so the ordinary external-contributor proof gate does not apply. The captured body reports the changed synchronous copy path selecting APFS cloning with matching clone IDs; no stored-data contract changes occur.

Evidence

Acceptance criteria:

  • [P1] pnpm docs:check.
  • [P1] pnpm check.
  • [P1] git diff --check.

What I checked:

  • Applicable repository policy: Read the complete root AGENTS.md. No nested AGENTS.md or maintainer-notes directory was found. Filesystem guards and alignment of public documentation with implementation informed the review. (AGENTS.md:1, 930a18d50243)
  • Pinned introduction and scope: Inspected the introduced delta from pinned main to the original PR head across all 14 files. The native change exposes the existing bounded copy engine synchronously; workflow changes only extend existing test invocations. (native/src/file_copy.rs:331, 930a18d50243)
  • Capability remains missing on main: Current main exports the borrowed synchronous descriptor copier and root-file admission helpers, but no synchronous root-admitting clone-capable copy. These existing primitives do not supply the requested combined capability. No same-repository merged replacement was established. (src/advanced.ts:9, 47fc59892b45)
  • Previous benchmark and import findings resolved: The function and types are exported from advanced, documentation imports that subpath, and new auto/never benchmark cases prepare absent destinations, verify copied data, close descriptors, and remove outputs. Supplied exact-head benchmark checks passed. (benchmarks/core.mjs:418, 930a18d50243)
  • Remaining descriptor contract mismatch: docs/copy.md promises a readable/writable descriptor. The macOS clone owner opens payload with O_RDONLY and transfers that same descriptor through the native copy result and public helper; writeSync therefore fails with EBADF on successful APFS clones. (native/src/unix.rs:1118, 930a18d50243)
  • Guard and cleanup review: The helper retains source admission, verifies descriptor/name identity and destination single-link status, binds portable creation to the admitted parent, enforces byte limits, and preserves observed replacements during cleanup. The reviewed tests cover traversal, source swaps, destination swaps, hardlinks, limits, and native routes. No stored-data format changes are introduced. (src/copy-root-file-sync.ts:115, 930a18d50243)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Mohl: 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.

  • Document readable access as the cross-platform descriptor guarantee.

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-10-06T06:54:08.991Z sha a92a1b0 :: needs changes before merge. :: [P2] Align the documented import with an available export
  • reviewed 2026-10-06T07:24:12.968Z sha 31231be :: blocked before merge. :: [P2] Register benchmark coverage for the new export | [P2] Limit the descriptor promise to supported read access

@steipete
steipete marked this pull request as ready for review October 6, 2026 07:19
@steipete
steipete requested a review from a team as a code owner October 6, 2026 07:19
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 automation 🚨 Merging this PR could break CI, automerge, proof capture, label sync, or automation. label Oct 6, 2026
@steipete
steipete force-pushed the feat/sync-clone-copy branch from c285127 to 930a18d Compare October 6, 2026 07:47
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 automation 🚨 Merging this PR could break CI, automerge, proof capture, label sync, or automation. label Oct 6, 2026
@steipete
steipete merged commit 3bdcb00 into main Oct 6, 2026
48 checks passed
@steipete
steipete deleted the feat/sync-clone-copy branch October 6, 2026 08:08
steipete added a commit that referenced this pull request Oct 6, 2026
Bind fs-safe's own admitted source descriptor to an optional exact bigint expectedSourceIdentity before destination creation, and return the verified sourceIdentity for clone, copy-file-range, and byte copies. Preserve existing admission, copying, ownership, and end-of-copy checks when the option is omitted.

Close the source-identity gap between OpenClaw's caller pin and synchronous plugin capture copying. Follow-up to #839 for openclaw/openclaw#161739. Update documentation, installed-package declaration checks, regression tests, and the Unreleased changelog; regenerate the unchanged export-name API snapshot.

Validation: focused portable and native APFS tests; pnpm check (17,220 passed); pnpm pack:check; isolated Codex review clean at P0-P2; exact-head all-OS CI, coverage, CodeQL, and benchmarks. One Windows package-consumer PowerShell timeout passed on a targeted same-head retry. No release.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal priority bug or improvement with limited blast radius. 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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant