Skip to content

feat(clone): add native APFS, Btrfs, and ReFS directory cloning - #293

Merged
steipete merged 3 commits into
mainfrom
codex/native-directory-clone
Sep 13, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/native-directory-clone

Conversation

@steipete

@steipete steipete commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Consumers currently need separate native implementations to create copy-on-write directory trees on APFS, Btrfs, and ReFS. OpenClaw duplicates this platform code and makes per-file foreign-function calls on Windows.

Why This Change Was Made

Adds @openclaw/fs-safe/clone with cloneTree, createCloneSource, and a filesystem probe. APFS uses one native directory clone, Btrfs uses a subvolume snapshot without a subprocess, and ReFS uses a bounded native worker pool with 16 workers by default. A batched APFS metadata reader supports consumers that validate clone provenance.

The API requires immutable caller-owned sources and controlled destination namespaces. It pins directory descriptors, refuses overwrites and unsupported filesystems, preserves independent file data, and waits for admitted work before rejecting cancellation. ReFS rejects named streams and unsupported reparse types instead of silently dropping them. There is no byte-copy fallback or per-file durability sync.

User Impact

Applications can request a directory clone through one portable call and choose their own fallback. Btrfs sources must be subvolumes without nested subvolumes. APFS/Btrfs bulk operations may leave a complete destination after cancellation; recovery remains with the caller.

On a Windows ReFS Dev Drive, repeated raw cloning of 41,723 files had medians of 5.78 seconds with 8 workers and 4.26 seconds with 16 workers. Initial copies at every tested concurrency matched all file hashes. These are copy-only measurements, with observed timing variability; full worktree creation also incurs Git preparation costs.

Evidence

  • Independent autoreview: scoped clean at P0–P2.
  • ReFS public API tests: 14 passed, 3 platform/privilege skips.
  • Native ReFS regression passed with a 2 GiB + 4097 byte sparse file: shared physical extent, exact size/timestamps, independent writes, held-writer rejection, alternate-stream rejection, and cleanup.
  • Build, package/tarball contract check, docs examples, docs site, and 21 documentation tests passed.
  • Local full pnpm check: 7,476 passed, 36 failed, 1,228 skipped. The new API documentation omission was fixed and its tests passed afterward. Remaining failures are Windows symlink setup permissions and an existing test-hook mock issue; both categories were reproduced on unchanged main. Package validation was run separately and passed.
  • All checks passed at f62a5a6c4662801d6517650c46b6ff244e5e3532: CI, coverage, CodeQL, and benchmarks. Native CI executes Linux glibc/musl, macOS arm64, and Windows x64; the other release architectures are not execution claims here.
  • An earlier macOS Node 22 fallback job hit an unchanged archive test's 75 ms wall-clock assertion; one diagnostic rerun passed. New clone payload assertions used an unnecessarily expensive recursive Buffer comparison under coverage; exact Buffer.equals comparisons fixed that cost without changing payload coverage or timeouts. Final CI and coverage passed without retries.
  • OpenClaw integration against the built candidate: final restored-binding check passed all 15 backend/ReFS tests, including physical extent sharing and create/restore/template invalidation/cleanup.
  • OpenClaw Linux consumer validation: core typecheck and 78 tests across seven suites passed. Candidate declarations and subprocess imports used task-only aliases because this API is not published yet; these results do not claim a released dependency install. Windows service proof uses the real candidate native binding.

Captured APFS and Btrfs public-facade execution

The committed test/clone.test.ts imports cloneTree and createCloneSource from src/clone.ts and calls them against real filesystem fixtures. Data/metadata preservation, independent writes, source admission, and APFS clone provenance use the actual native binding. The separately named descriptor-lifetime test substitutes the native method and is not claimed as native cancellation proof.

Captured at the final head:

macOS APFS: pnpm test test/clone.test.ts
test/clone.test.ts (17 tests | 3 skipped) 66ms
Test Files 1 passed (1)
Tests 14 passed | 3 skipped (17)

Linux Btrfs loopback fixture:
FS_SAFE_CLONE_TEST_ROOT="$fixture/mount" pnpm test test/clone.test.ts
test/clone.test.ts (17 tests | 2 skipped) 87ms
Test Files 1 passed (1)
Tests 15 passed | 2 skipped (17)

APFS invocation/output and Btrfs fixture setup/invocation/output. Platform-specific tests skip on the other filesystems; Btrfs's ordinary-directory rejection executes on the mounted Btrfs fixture.

Captured ReFS public-API clone and native cancellation

fs-safe PR #293, checked out at f62a5a6. The built Windows clone API and native implementation are unchanged from the validated build. Run on the local ReFS Dev Drive with Node.js v26.8.2. No mocks or binding substitutions; no dependency operations or production edits.

The script waits up to 10 seconds for a real destination file matching source bytes while another source file is still absent, then aborts. It awaits rejection, verifies the partial destination is absent, immediately reuses that same path, compares every path and file hash, verifies independent writes, and checks that output metadata stays unchanged after a 1-second quiet interval.

Invocation (from the OpenClaw task workspace; paths contain no user identity):

node .local/fs-safe-public-proof.mjs 'D:\openclaw-refs-benchmark-jYp0ys\.templates\52f29ef5-5c83-40cc-9c0d-a55eb5c63e9b' 'D:\'

Captured output (exit 0):

API: built dist/clone.js; native ReFS binding; no mocks
Source: 41723 files, 566784361 bytes, 1977 directories
Cancellation: matching package.json observed at 32.4 ms while another source file was absent
Cancellation: exact caller reason returned at 38.6 ms; partial destination absent
Immediate same-path reuse: success in 5.516 s
Successful clone: all 41723 relative file paths and SHA-256 hashes match; all directories match
Independent write: clone package.json changed; source bytes unchanged
Post-settlement observation: file paths, lengths, modification times and directories unchanged after 1000 ms
Retained task-owned output: D:\fs-safe-public-proof-8Ih2zp

Proof script:

import fs from "node:fs";
import path from "node:path";
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { setTimeout as delay } from "node:timers/promises";
import { cloneTree, probeTreeClone } from "./fs-safe-clone/dist/clone.js";

const source = path.resolve(process.argv[2]);
const volume = path.resolve(process.argv[3]);
assert.equal(probeTreeClone(volume), "refs");

function inventory(root, hashes = true) {
  const files = new Map();
  const directories = [];
  let bytes = 0;
  function visit(relative) {
    for (const entry of fs.readdirSync(path.join(root, relative), { withFileTypes: true })) {
      const name = path.join(relative, entry.name);
      const pathname = path.join(root, name);
      if (entry.isDirectory()) {
        directories.push(name);
        visit(name);
      } else {
        assert.ok(entry.isFile(), `unexpected corpus entry type: ${name}`);
        const stat = fs.statSync(pathname, { bigint: true });
        files.set(name, hashes
          ? createHash("sha256").update(fs.readFileSync(pathname)).digest("hex")
          : `${stat.size}:${stat.mtimeNs}`);
        bytes += Number(stat.size);
      }
    }
  }
  visit("");
  return { files, directories: directories.sort(), bytes };
}

console.log("API: built dist/clone.js; native ReFS binding; no mocks");
const baseline = inventory(source);
console.log(`Source: ${baseline.files.size} files, ${baseline.bytes} bytes, ${baseline.directories.length} directories`);
const root = fs.mkdtempSync(path.join(volume, "fs-safe-public-proof-"));
const destination = path.join(root, "copy");
const controller = new AbortController();
const reason = new Error("proof: cancel after native destination file activity");
let settled = false;
const start = performance.now();
const pending = cloneTree(source, destination, { concurrency: 16, signal: controller.signal }).then(
  () => ({ status: "fulfilled" }),
  (error) => ({ status: "rejected", error }),
).finally(() => { settled = true; });
const deadline = performance.now() + 10_000;
const observedRelative = "package.json";
const observedSource = fs.readFileSync(path.join(source, observedRelative));
let missingBeforeAbort;
while (!settled && performance.now() < deadline) {
  const observedPath = path.join(destination, observedRelative);
  if (fs.existsSync(observedPath) && fs.readFileSync(observedPath).equals(observedSource)) {
    missingBeforeAbort = [...baseline.files.keys()].find((name) => !fs.existsSync(path.join(destination, name)));
    if (missingBeforeAbort !== undefined) break;
  }
  await delay(2);
}
if (settled || missingBeforeAbort === undefined) {
  if (!settled) controller.abort(new Error("proof observation deadline expired"));
  await pending;
  throw new Error("Did not observe native file activity before settlement; no cancellation proof recorded");
}
const observedMs = performance.now() - start;
controller.abort(reason);
const outcome = await pending;
assert.equal(outcome.status, "rejected");
assert.equal(outcome.error, reason);
assert.equal(fs.existsSync(destination), false);
console.log(`Cancellation: matching ${observedRelative} observed at ${observedMs.toFixed(1)} ms while another source file was absent`);
console.log(`Cancellation: exact caller reason returned at ${(performance.now() - start).toFixed(1)} ms; partial destination absent`);

// Reuse immediately after rejection, with no sleep or cleanup between the calls.
const reuseStart = performance.now();
await cloneTree(source, destination, { concurrency: 16 });
console.log(`Immediate same-path reuse: success in ${((performance.now() - reuseStart) / 1000).toFixed(3)} s`);
const copied = inventory(destination);
assert.deepEqual(copied.files, baseline.files);
assert.deepEqual(copied.directories, baseline.directories);
assert.equal(copied.bytes, baseline.bytes);
console.log(`Successful clone: all ${copied.files.size} relative file paths and SHA-256 hashes match; all directories match`);

fs.writeFileSync(path.join(destination, observedRelative), "proof-owned clone edit\n");
assert.deepEqual(fs.readFileSync(path.join(source, observedRelative)), observedSource);
assert.equal(fs.readFileSync(path.join(destination, observedRelative), "utf8"), "proof-owned clone edit\n");
console.log("Independent write: clone package.json changed; source bytes unchanged");
const beforeQuiet = inventory(destination, false);
await delay(1000);
assert.deepEqual(inventory(destination, false), beforeQuiet);
assert.deepEqual(fs.readdirSync(root), ["copy"]);
console.log("Post-settlement observation: file paths, lengths, modification times and directories unchanged after 1000 ms");
console.log(`Retained task-owned output: ${root}`);

Implementation references: Microsoft CopyOnWrite, MSBuild Artifacts, Apple clonefile contract, and Btrfs subvolume semantics. No source code was copied from those projects.

  • 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

@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 00:12
@steipete
steipete requested a review from a team as a code owner September 13, 2026 00:12
@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: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 13, 2026
@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed September 12, 2026, 8:28 PM ET / September 13, 2026, 00:28 UTC (Revision 2).

ClawSweeper review

What this changes

Adds a public directory-cloning API for APFS, Btrfs, and ReFS, batched APFS metadata reads, documentation, tests, benchmarks, and native CI coverage.

Merge readiness

⛔ Blocked before merge - 2 items remain

This remains useful work not implemented on current main. No blocking code defect was found, but the updated validation summaries do not resolve the previous request for captured real-behavior proof.

Priority: P2
Reviewed head: f62a5a6c4662801d6517650c46b6ff244e5e3532

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation is coherent and has focused coverage, while the unresolved runtime-proof request limits merge readiness.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: Needs real behavior proof before merge: the body reports useful real ReFS measurements and APFS/Btrfs CI results, but supplies no captured public-API invocation/output connecting src/clone.ts to those native outcomes; cancellation settlement is demonstrated only with a substituted native method. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: Needs real behavior proof before merge: the body reports useful real ReFS measurements and APFS/Btrfs CI results, but supplies no captured public-API invocation/output connecting src/clone.ts to those native outcomes; cancellation settlement is demonstrated only with a substituted native method. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
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 present. Applied filesystem-boundary, additive API, documentation, and changelog guidance; the read-only review contract precluded builds, tests, and another autoreview.
Distinct capability remains absent from main: The pinned main package has no clone subpath. Existing cloneFileExclusive and documented publication fallbacks operate on individual files, rather than providing directory cloning, Btrfs source preparation, or batched APFS metadata. The v0.9.0 source tree also lacks the new cloning modules. A bounded recent-PR search found no merged replacement for this capability.
Handle lifetime and ownership contract: The facade validates destination placement, uses shared staged-directory admission, retains descriptors until the native promise settles, and checks directory identities afterward. Documentation explicitly requires immutable sources and caller-controlled destination namespaces; these methods do not grant application authorization or sanitize cloned symlinks.
Findings None None.
Security None None.

How this fits together

fs-safe provides filesystem primitives for Node.js applications. The new cloning API accepts caller-owned absolute paths, retains directory handles during native work, and produces independent directory trees or a settled failure.

flowchart TD
  A[Caller-owned source and destination] --> B[Validate paths and pin directories]
  B --> C{Supported filesystem}
  C --> D[APFS clone or Btrfs snapshot]
  C --> E[Parallel ReFS file clones]
  C --> F[Unsupported error]
  D --> G[Wait for native work and verify identity]
  E --> G
  G --> H[Independent tree or settled failure]
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: Needs real behavior proof before merge: the body reports useful real ReFS measurements and APFS/Btrfs CI results, but supplies no captured public-API invocation/output connecting src/clone.ts to those native outcomes; cancellation settlement is demonstrated only with a substituted native method. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Complete next step (P2) - Attach captured public-API cloning output and native cancellation-settlement evidence. Terminal screenshots or recordings are welcome; copied output and logs also count. Redact private paths, hosts, credentials, and other private details. Updating the PR body should trigger re-review; otherwise ask a maintainer to comment @clawsweeper re-review.
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Production and test growth Runtime source +1,095 lines; test code +448; API fixture +14 The production growth implements three native filesystem backends and their public facade; counts separate the embedded Rust tests from runtime code.

Technical review

Best possible solution:

Keep the additive cloning API and its explicit ownership contract, supported by observable native preservation and cancellation-settlement evidence.

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

Not applicable: this PR adds a capability rather than repairing an established failure; no definite introduced bug was identified.

Is this the best way to solve the issue?

Yes, the additive subpath and shared directory guards provide a coherent implementation without replacing existing publication behavior; runtime proof remains incomplete.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 18f4156e654d.

Labels

Label justifications:

  • P2: This is a bounded new filesystem capability with no demonstrated urgent regression in existing users' workflows.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: Needs real behavior proof before merge: the body reports useful real ReFS measurements and APFS/Btrfs CI results, but supplies no captured public-API invocation/output connecting src/clone.ts to those native outcomes; cancellation settlement is demonstrated only with a substituted native method. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

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 present. Applied filesystem-boundary, additive API, documentation, and changelog guidance; the read-only review contract precluded builds, tests, and another autoreview. (AGENTS.md:22, f62a5a6c4662)
  • Distinct capability remains absent from main: The pinned main package has no clone subpath. Existing cloneFileExclusive and documented publication fallbacks operate on individual files, rather than providing directory cloning, Btrfs source preparation, or batched APFS metadata. The v0.9.0 source tree also lacks the new cloning modules. A bounded recent-PR search found no merged replacement for this capability. (native/src/fast_file.rs:27, 18f4156e654d)
  • Handle lifetime and ownership contract: The facade validates destination placement, uses shared staged-directory admission, retains descriptors until the native promise settles, and checks directory identities afterward. Documentation explicitly requires immutable sources and caller-controlled destination namespaces; these methods do not grant application authorization or sanitize cloned symlinks. (src/clone.ts:54, f62a5a6c4662)
  • Native safety and supply-chain inspection: ReFS opens enumerated children relative to retained handles, checks identities, rejects named streams and unsupported reparse types, creates destinations exclusively, and joins workers before returning. Existing Windows callers retain their original sharing flags. CI adds an ephemeral Btrfs fixture without broadening workflow permissions; the Cargo change enables a feature on an existing dependency. (native/src/clone_windows.rs:266, f62a5a6c4662)
  • Updated proof and review continuity: The captured context, sourceRevision 255c8c8ac20b78cb0942ee2633c088f82809e39ef4998fbbda095ec0c8cfbc78, contains useful ReFS timings, sparse-file observations, APFS/Btrfs CI claims, and OpenClaw integration results. The full live body matched that snapshot and contained no captured invocation/output or runtime artifact. The earlier review requested public-API proof including cancellation settlement. The latest commit changes byte assertions only; production cloning files are unchanged from the earlier reviewed head. (test/clone.test.ts:98, f62a5a6c4662)
  • Cancellation coverage boundary: The cancellation-settlement test replaces the native clone method with a JavaScript implementation. It verifies facade descriptor lifetime but cannot establish actual native worker or bulk-operation settlement after cancellation. The real filesystem tests cover preservation, independent writes, exclusivity, symlinks, and platform-specific rejection. (test/clone.test.ts:111, f62a5a6c4662)

Likely related people:

  • Peter Steinberger: Raw commit d733275 adds src/staged-directory.ts:44 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: d73327569edf; files: src/staged-directory.ts)

Rank-up moves

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

  • Attach redacted public-API runtime output supporting the claimed native backends and showing cancellation settles before cleanup.

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 (1 earlier review cycle)
  • reviewed 2026-09-13T00:17:47.227Z sha fae2274 :: needs real behavior proof before merge. :: none

@steipete
steipete merged commit 0b40e52 into main Sep 13, 2026
28 checks passed
@vincentkoc
vincentkoc deleted the codex/native-directory-clone branch September 25, 2026 11:15
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: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant