Skip to content

fix: preserve OAuth inference and gateway rebuilds - #138696

Open
freeqaz-openai wants to merge 10 commits into
mainfrom
fix/runtime-inference-ui-rebuild
Open

freeqaz-openai wants to merge 10 commits into
mainfrom
fix/runtime-inference-ui-rebuild

Conversation

@freeqaz-openai

@freeqaz-openai freeqaz-openai commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Related: #138595

What Problem This Solves

Fixes OAuth profiles blocking native validation of compatible account-specific Codex models, rootful Docker creating undeletable skill mountpoints, and UI-only rebuilds without Git metadata reporting a false Gateway build mismatch. Inference errors retain their cause without repeated wrappers.

The sandbox repair now prepares the full required mount attachment chain. Preparing only the final overlay source left Docker creating intermediate attachments as root. A custom bind above the workdir also redirects the workspace mount itself. All necessary attachments now receive host-owned directories before startup.

Why This Change Was Made

The existing owner follows strict ancestors from protected overlays through effective binds, including workspace attachment. It reuses segment-aware containment, deepest-parent selection and protected-target filtering; custom binds win at the same workspace target. Duplicate relevant targets fail before writes; unrelated targets receive no preparation.

Generic source/target/network/security admission precedes custom-root writes. Docker/Podman creation/restart and browser creation/restart/auto-start use their resolved configurations and binds. Mount order, hashes/epochs, running reuse and read-only overlays stay unchanged. No framework, config option, schema or SDK surface is added. OAuth fallback remains limited to compatible first-party ChatGPT routes; Platform credentials and custom endpoints retain their behavior.

Current dependency and data-model check

Independent inspection at bcd5bad446eea7b136320acd2c927c3e1205c039 rechecked the official fs-safe 0.8.1 archive against this head’s lockfile: archive SHA256 effddeca2b5c8edddd0ac467169a4b7dc5b42f185556405b6c42b5c253f5f817, lock SHA256 f774aba43551e277ce53215eed45081f9ddaced986e6267b7bcb7411685b1817. All 543 extracted files match the archive. The directory helper used by mount preparation and the canonicalization function retain byte-identical operational code from 0.7.2. Their current source/types and consumers were personally inspected.

Existing executed 0.8.1 proof passes 13 published-export scenarios; four archive scenarios were also run against each version. Archive code is materially different: 0.8.1 preserves rejected hardlink destinations and finalizes directory permissions in those cases. Ordinary files remain overwriteable, merge is incremental, and new finalization errors may propagate. These are macOS/Node/native-off helper results; complete extraction, optional native binaries and a 0.8.1 installed Gateway were not proven. Exact 0.8.1 runnable proof supports a supplied official archive when registry access is unavailable. Historical installed Gateway/Docker evidence remains labeled 0.7.2.

Data-model check: no SQLite schema/version/table/index, serialized binding, mount hash/epoch or store-owner change. The production diff changes preparation/admission, the provider predicate, error text and UI-build identity normalization. Required directories can remain after later startup failure; preservation-first recovery and preparation beneath admitted ro binds follow the compatibility contract assessed below.

User Impact and Recovery Contract

Missing attachment directories are created as the Gateway user in the actual backing source, including under custom ro binds: ro restricts container access while host preparation creates required directories. Custom sources must exist and pass admission. Existing contents, modes and ownership are preserved. Required empty directories may remain after a later image/version/engine failure.

Files and all symlinks at required paths stop startup without replacement or target traversal. The recovery procedure covers pausing work, stopping containers, inspecting the selected source/attachment chain, moving the entry itself to an unused backup, and retrying. Bounded, escaped errors identify the relative suffix and containing container bind without host-source paths. Backups and symlink targets stay intact; other tools' data is not migrated. Compatibility decision: retain preservation-first recovery and host preparation under admitted ro binds. The technical readiness assessment accepts this bounded contract: replacing collisions or changing existing ownership would risk user data, while omitting preparation leaves rootful engines creating undeletable attachments. Container read-only enforcement is preserved.

Managed hooks and protected native startup are in #138595. Both PRs target main independently. No PR-specific dependency overrides are introduced.

Review and owner involvement

The final technical assessment recommends this scope for landing. The PR author freeqaz-openai is a verified active member of openclaw/openclaw-secops, satisfying the repository's listed-owner involvement rule. Live main rules require the passing CI gate and linear history; they do not require a separate independent approval. Existing review requests remain available. This assessment does not represent a newly submitted human approval or change the automated reviewer’s score.

Evidence and Source Attribution

Candidate: bcd5bad446eea7b136320acd2c927c3e1205c039. CI: normal CI passed, including the aggregate gate and both Windows lanes. Current-head checks report zero pending or failed checks. Earlier native and installed proofs retain their stated revisions.

The fixture correction passed fresh independent P0–P2 review with no actionable findings. A separate full-tree verification accepts the mechanical main integration. Matching formatting, whitespace and assertion-conservation checks pass. The published commit is signed and passed the normal commit hooks.

Current CI evidence

The actual tested merge is ad9af1d74a3ebfbec424219478a82d9f4ceee792, combining bcd5bad446eea7b136320acd2c927c3e1205c039 with main 3e4becea5e2ce38ede69e8ecf5302805ecbfc09c. The merged agent-end test is byte-identical to the reviewed fixture.

Coverage Result
Agent-end context: completed / aborted / refusal 3,437 / 1,239 / 1,249 ms, all pass
Codex target group 148 passed
Adjacent Codex lifecycle, deadline and settlement group 328 passed
Sibling spawn/authority group 895 passed; repaired setup case 9,606 ms
Session reclamation group 476 passed, with the original 500 ms heartbeat assertion

Hosted validation used Node 24.20.0, pnpm 12.3.4, and a successful frozen installation of fs-safe 0.8.1 and undici 8.10.2. These are observed current-run results. The earlier cold timings and test-order differences are retained in the work record; no isolated timing profile is claimed.

Mechanical main integration

The preceding fixture-correction head ba48c9eeb6352f6573b689c5bc9e58526a2c9216 passed full CI at test merge 7a0b5037be5a04c05fa90477fd7930de38ef3a1c. Main then advanced from 84b79be0d1f5556df5f4d131525c7a04f3b81db1 to e09a265b11112623addd4de2167ee6b34cd82719. The sole conflict was two explanatory comment lines at the existing 15-second sibling setup wait; the canonical main file was accepted and now drops out of the PR diff. An independent conservation check confirms that the refreshed tree differs from the preceding green CI merge only in the same 15 files changed by main, with every changed blob identical to main and all remaining files identical to the tested merge. The runtime-plan test correction is unchanged. Matching formatting and staged whitespace checks pass; this integration adds no custom production behavior.

Runtime-plan fixture correction

The agent-end context test now supplies the existing createCodexRuntimePlanFixture. Its nonempty skill_workshop tool otherwise falls back to provider discovery during startup. Supplying the prepared plan keeps this context test on the host-prepared tool-policy path already used by sibling fixtures. The change removes temporary agent-end phase diagnostics and preserves the controlled clock, startup readiness/error barrier, completed/aborted/refusal sequence, ten response iterations, and all eight assertions. No production code, product deadline, dependency, or workflow changes are added by this correction.

The matching change in upstream PR #139131, introduced by df715579, passed all 148 tests across 12 Codex files, with the first completed case taking 3,558 ms, at upstream head 62d0b82cddc743a854e570fe2ebc124bfded35c2. The actual job log establishes that result; the overall upstream run had an unrelated failure. This supported selecting the correction; this PR's own validation is recorded above.

Earlier diagnostics measured 139.7 seconds before turn/start on managed 023b95ef; general 0dd80d15 passed that case in 101.5 seconds against a 120-second limit. Those timings locate the delay but do not attribute its entire duration to provider discovery. Both fixture-correction heads and both refreshed heads passed their own normal CI; the corrected completed cases took about three seconds. These are observed CI results, not an isolated timing benchmark.

The accepted #139176 sibling-setup correction is now also present on main: a 15-second succeeded-status wait, preserving the original cleanup order and cancellation/authority assertions. Dedicated deadline and settlement tests remain unchanged. Broader product work is deferred to separate PRs.

Prior normal CI at 0dd80d15 passed, including both Windows lanes, on merge 34be574347860bab6c8c82efa39e636a269f7119 with main 707edba619a6244fb6a465f9c4b01a856994a29c. That run passed the 148 Codex, 895 sibling-spawn, and 476 reclamation group tests; it predates this fixture correction.

Local runtime/type checks remain unavailable because the configured registry policy blocks the required fs-safe 0.8.1 graph. Standard CI independently completed frozen installation with Node 24.20.0, pnpm 12.3.4, fs-safe 0.8.1, and undici 8.10.2. No registry or dependency-policy bypass is used.

The seven-layout proof below executes the corrected attachment-chain owner at b2683104. Earlier Docker, installed-package, UI, and dependency proofs retain their stated revisions and scope.

Final attachment-chain repair

Risk Current coverage and result
Intermediate attachments or the workspace attachment become root-owned Seven real rootful Docker layouts pass: default; ancestor rw; ancestor ro; adjacent deepest parents; single deep rw with default workdir; single deep ro with custom workdir; custom bind above workdir. All required attachments stay UID 1000; seven ordinary-user cleanups pass.
Tests miss a real redirected path The last three layouts failed on the prior candidate: each left two UID 0 directories and ordinary cleanup failed with EACCES, while overlays stayed read-only. Replaying the corrected owner makes all three pass. New chain regressions also failed before repair: 11 failed / 82 passed.
Preparation touches the wrong source or bypasses admission Boundary tests cover bind order, deepest/above-workdir chains, prefix boundaries, protected-target filtering, duplicate rejection, unrelated-source preservation and external/blocked-source or reserved-target rejection before writes.
Read-only protection changes Every real layout reads original skill sentinels and rejects writes to the skill overlay. Read-only parent flags remain present in inspected mounts. Existing files, symlinks, contents, modes and ownership are preserved.
Restart/browser uses a different bind collection Actual lifecycle-owner tests cover Docker/Podman creation/restart and browser-specific binds through creation/restart/auto-start, using a real-filesystem oracle before engine start. Engine boundaries in those tests are mocked; the seven-layout proof uses real Docker.
Collision recovery destroys data Current tests cover files and internal/external/dangling links. Separately attributed historical real-Docker recovery and the runnable published-helper matrix below verify preserved entries, targets, backups and successful retry.

The proof bundles actual resolution/preparation/mount-argument owners and security validation against published fs-safe 0.7.2 JavaScript. All 234 inputs stayed unchanged. Bundle SHA256: 1056e4adf47fe47855438ae7423e5d8192e85ad22880b8cd6a90a7e5b805e2fa. Execution completed exit 0; all containers/fixtures were absent without privileged fallback. Separate cleanup removed uploaded artifacts.

122 focused tests pass; 179 sibling tests pass, one skipped, across seven suites. Canonical changed checks pass, including typing, all three unused-export scans and lint. Final independent P0–P2 review completed scoped-clean with no actionable findings. The final test-only fixture refactor also passed all 37 affected tests, focused lint and formatting checks; production/proof inputs stayed unchanged.

Installed Gateway integration

Four installed Gateway → native Codex → OpenClaw sandbox-tool → Docker turns passed with official Codex 0.153.4: initial execution, project-hook injection, reuse after injection, and Gateway restart/reopen. Every turn validates a random value available at the worker's mount path, its actual tool callback, a workspace file and completed authenticated Gateway response. Inspected mounts retain read-only skills and network isolation.

The actual tool set contains only sandbox_exec/sandbox_process; stored bindings confirm native-tool restriction and protected native context. The same native thread and policy fingerprints survive reuse/reopen while restart replaces the native client/process. A separate native positive control executes user, project and the exact later-injected hook payload; after clearing those markers, all four Gateway turns run required managed hooks and suppress all three ordinary hooks.

This is a canonical combined-candidate installation of core plus the external plugin, not either PR's standalone package. Deterministic loopback provider, synthetic credentials, fs-safe 0.7.2; no real OAuth/hosted inference. An independent reviewer checked the receipts. Gateway/provider processes, all task containers, transfer jobs and temporary remote state are cleaned up. Artifact/source details follow below.

Dependency and data boundary

The published directory owner creates missing segments under an admitted root without replacing conflicts; source canonicalization is path calculation, not ACL attestation. No serialized data or database schema changes. Pinned integrity, source links and the unchanged runnable proof follow.

The actual GitHub test merge also consumes upstream fs-safe 0.8.1. Its official artifact matches that merge's lock integrity; the used directory/canonicalization operational closures are byte-identical to 0.7.2. All 13 published-export cases pass on 0.8.1, plus four archive scenarios run against each version. Archive implementation changes are kept separate from that equality: 0.8.1 improves hardlink-destination preservation and final directory permissions in the exercised cases. This does not relabel the installed 0.7.2 package as a 0.8.1 Gateway proof.

Historical evidence and limits

  • The initial four-layout candidate missed single-deep rw/ro and above-workdir attachments; the seven-layout proof supersedes it.
  • Default-workspace recovery at d7c4d438f7: 18 rejections → 18 recoveries including restart; backups/source/targets preserved; nine ordinary-user cleanups; 54 overlay writes rejected; no containers left. This 231-input proof did not cover custom attachment chains.
  • Original control at 7de91626ec: omitted preparation produced UID 0 directories and EACCES. Initial disposal failed without DAC_OVERRIDE; separate scoped cleanup succeeded. Prepared paths cleaned up normally.
  • Prior CI at 3d35e5b3 passed its aggregate gate, Windows suites and real-Gateway UI tests before this correction. It is not current-head CI.

The seven-layout matrix covers mount owners/rootful Docker. Installed Gateway/browser evidence belongs in the separate section; real Podman/rootless/Windows engines, SSH/OpenShell, hostile concurrent alias retargeting, Windows ACLs, native fs-safe binary equivalence and complete archive extraction are outside this matrix. Recovery requires paused work and stopped containers; existing root-owned data is preserved, not repaired.

Preserved inference, UI, and build evidence

Preserved earlier inference/UI owners passed 399 focused tests in 11 suites, 17 native-required archive tests, 76 lifecycle cases, full build, and types/lint/architecture checks. These results retain their original scope.

The UI unread failure reproduced under sixfold CPU throttling and passed after adding the missing initial-load wait, with every acknowledgement assertion retained. A separate exact-merge dashboard fixture failure passed after restoring its omitted session-resolution response. All three related UI tests pass together. Before/after build execution verifies that UI rebuilds without Git metadata retain runtime identity. Earlier d7 CI is also retained as historical evidence.

Installed candidate identity

Local union 16f96489d39dc7ea08be8c26518c13efaa02037c contains managed dab197ba3f2085642587dcc7257fa25814a3cc9d and general b268310405c25d893bae1f0b6d5dae69f5b5c26f production. All 37,913 staged source files stayed unchanged during canonical build/packaging. One later test-only fixture refactor is recorded separately; that test is absent from the tarballs.

Core SHA256 cff16a53a6de91ad40d8b36665f35e9f0cbaf480c4414ef9c44d833a5a4e69c3; external plugin c41090d5975f11a1b7c5c2ce85a37a74dfc492a1b1c4d998ce49a4c2fd7f5694; executed proof 119dd61bf0866cf74c0254e5d4b65850b2e949cfe32f0f0b80ee4981d8d9cf71. Installed parity verifies 9,782 core payload files and 74 plugin files; the documented package lifecycle removes its separate pending sentinel. Four completed responses and eight main-phase provider POSTs passed. The nonce proves routing/effect, not secrecy from a malicious Gateway.

fs-safe 0.8.1 published-export reproduction

This is the retained executed 0.8.1 script. Save it as fs-safe-contract-proof-0.8.1.mjs, then run node fs-safe-contract-proof-0.8.1.mjs /path/to/fs-safe-0.8.1.tgz with the official artifact. It verifies the entire SHA512 before extraction and does not install packages or run lifecycle hooks. Omitting the path downloads the official archive where registry policy permits. Node >=22 and tar are required. Expected result: 13 passing scenarios; the original execution used Node v26.8.1/macOS arm64/native off. This independently reproducible helper proof does not execute a Gateway or a full archive extraction.

Runnable 0.8.1 published-export script
// Node >=22; tar on PATH. No npm install or package lifecycle scripts.
// node fs-safe-contract-proof.mjs [path/to/fs-safe-0.8.1.tgz]
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { execFileSync } from 'node:child_process';
const url = 'https://registry.npmjs.org/@openclaw/fs-safe/-/fs-safe-0.8.1.tgz';
const integrity = 'sha512-I11v+xiet4RCE1G1bmWFLEMmd9nBnZMmKqHPT9gkqVtoqacY7GtFvpt1O7cffUDD6C2YlAt7Z5Z2Vlbq5rYxDg==';
const work = await fs.mkdtemp(path.join(process.cwd(), 'fs-safe-proof-'));
const archivePath = path.join(work, 'package.tgz');
const bytes = process.argv[2] ? await fs.readFile(process.argv[2]) : Buffer.from(await (await fetch(url)).arrayBuffer());
assert.equal('sha512-' + createHash('sha512').update(bytes).digest('base64'), integrity);
await fs.writeFile(archivePath, bytes);
// Extraction is allowed only after the entire artifact matches the pinned official hash.
execFileSync('tar', ['-xzf', archivePath, '-C', work]);
process.env.OPENCLAW_FS_SAFE_NATIVE = 'off';
process.env.FS_SAFE_NATIVE = 'off';
const load = name => import(pathToFileURL(path.join(work, 'package/dist', name + '.js')));
const config = await load('config');
config.configureFsSafeNative({ mode: 'off' });
const {ensureDirectoryWithinRoot: ensure, canonicalPathFromExistingAncestor: canonical} = await load('advanced');
const archive = await load('archive');
const results = [];
const check = async (name, run) => { await run(); results.push({ name, pass: true }); };
const fixture = async name => {
  const base = path.join(work, name), root = path.join(base, 'root'), outside = path.join(base, 'outside');
  await fs.mkdir(root, {recursive:true}); await fs.mkdir(outside);
  await fs.writeFile(path.join(outside, 'sentinel'), 'unchanged');
  return {base,root,outside};
};
const request = (root, requestedPath) => ensure({rootDir: root, requestedPath, scopeLabel: 'proof'});
for (const kind of ['file','inside-link','outside-link','dangling-link']) {
  for (const position of ['leaf','ancestor']) {
    await check(`directory ${kind} ${position}: reject, preserve collision, retry`, async () => {
      const {base,root,outside} = await fixture(`${kind}-${position}`);
      const collision = path.join(root,'collision'), saved = path.join(base,'preserved');
      const target = kind === 'inside-link' ? path.join(root,'target') : kind === 'outside-link' ? outside : path.join(base,'absent');
      if (kind === 'file') await fs.writeFile(collision, 'collision bytes');
      else { if (kind === 'inside-link') await fs.mkdir(target); await fs.symlink(target, collision); }
      const before = await fs.lstat(collision);
      const requested = position === 'leaf' ? 'collision' : 'collision/child';
      assert.equal((await request(root, requested)).ok, false);
      assert.equal((await fs.lstat(collision)).ino, before.ino);
      if (kind === 'file') assert.equal(await fs.readFile(collision, 'utf8'), 'collision bytes');
      else assert.equal(await fs.readlink(collision), target);
      await fs.rename(collision, saved); // fresh synthetic sibling; never overwrites a backup
      assert.equal((await fs.lstat(saved)).ino, before.ino);
      assert.equal((await request(root, requested)).ok, true);
      assert.equal((await fs.stat(path.join(root, requested))).isDirectory(), true);
      assert.equal(await fs.readFile(path.join(outside,'sentinel'),'utf8'), 'unchanged');
      assert.deepEqual(await fs.readdir(outside), ['sentinel']);
      if (kind === 'inside-link') assert.deepEqual(await fs.readdir(target), []);
      if (kind === 'dangling-link') await assert.rejects(fs.lstat(target), {code:'ENOENT'});
    });
  }
}
await check('directory normal create/reuse and lexical escape rejection', async () => {
  const {root,outside} = await fixture('normal');
  assert.equal((await request(root,'a/b')).ok,true);
  await fs.writeFile(path.join(root,'a/b/sentinel'),'retained');
  assert.equal((await request(root,'a/b')).ok,true);
  assert.equal(await fs.readFile(path.join(root,'a/b/sentinel'),'utf8'),'retained');
  for (const p of ['..', '../outside/new', outside, '.', '', 'x\0y']) assert.equal((await request(root,p)).ok,false);
  assert.deepEqual(await fs.readdir(outside), ['sentinel']);
});
await check('canonical existing symlink ancestor rejoins missing suffix without creating it', async () => {
  const {base,root} = await fixture('canonical');
  const alias=path.join(base,'alias'); await fs.symlink(root,alias);
  const missing=path.join(alias,'not','created');
  assert.equal(await canonical(missing),path.join(await fs.realpath(root),'not','created'));
  await assert.rejects(fs.lstat(path.join(root,'not')), {code:'ENOENT'});
});
await check('archive entry validation throws ArchiveSecurityError with entry-path code', async () => {
  for (const p of ['../escape','/absolute','C:/drive','a/../b','nul\0path']) {
    assert.throws(()=>archive.validateArchiveEntryPath(p), e=>e instanceof archive.ArchiveSecurityError && e.code==='entry-path');
  }
  assert.doesNotThrow(()=>archive.validateArchiveEntryPath('normal/file.txt'));
});
await check('archive destination rejects file and symlink with distinct stable codes', async () => {
  const {base,root,outside}=await fixture('archive-destination');
  const file=path.join(base,'file'), link=path.join(base,'link');
  await fs.writeFile(file,'file sentinel'); await fs.symlink(outside,link);
  for (const [p,code] of [[file,'destination-not-directory'],[link,'destination-symlink']])
    await assert.rejects(archive.prepareArchiveDestinationDir(p),e=>e instanceof archive.ArchiveSecurityError && e.code===code);
  assert.equal(await archive.prepareArchiveDestinationDir(root),await fs.realpath(root));
  assert.equal(await fs.readFile(file,'utf8'),'file sentinel');
  assert.deepEqual(await fs.readdir(outside),['sentinel']);
});
await check('archive output rejects symlink ancestor with destination-symlink-traversal', async () => {
  const {root,outside}=await fixture('archive-output');
  await fs.symlink(outside,path.join(root,'link'));
  await assert.rejects(archive.prepareArchiveOutputPath({destinationDir:root,destinationRealDir:await fs.realpath(root),relPath:'link/child',outPath:path.join(root,'link/child'),originalPath:'link/child',isDirectory:false}), e=>e instanceof archive.ArchiveSecurityError && e.code==='destination-symlink-traversal');
  assert.deepEqual(await fs.readdir(outside),['sentinel']);
});
const sourceHashes = {};
for (const file of ['advanced.js','root-paths.js','absolute-path.js','archive-errors.js','archive-entry.js','archive-staging.js'])
  sourceHashes[file] = createHash('sha256').update(await fs.readFile(path.join(work,'package/dist',file))).digest('hex');
console.log(JSON.stringify({node:process.version,platform:process.platform,arch:process.arch,package:'@openclaw/[email protected]',url,integrity,sha256:createHash('sha256').update(bytes).digest('hex'),nativeMode:'off',passed:results.length,results,sourceHashes},null,2));
// Only this process-created scratch directory is removed after all assertions pass.
await fs.rm(work,{recursive:true,force:true});

Published filesystem contracts and runnable proof

The links below were independently fetched and byte-compared with public source revision e9ab355341ecd47d3c5eeb523c5c8efd25587db9 (v0.7.2). Runtime claims come from the published JavaScript, not a reconstructed implementation.

  • Existing-segment checks use lstat and reject files/symlinks, including in-root and dangling links. Directory preparation validates containment and creates missing segments without replacing collisions.
  • Archive error class/codes, destination owner, and entry validator define the observed entry-path, destination-not-directory, destination-symlink, and destination-symlink-traversal codes.
  • Existing-ancestor canonicalization attempts realpath and rejoins a missing suffix. It calculates a path; it does not attest permissions or ACLs.
  • Fresh official metadata and tarball match the consumer lockfile integrity and all 320 JS/declaration files of the inspected published artifact. SHA512: sha512-Ls27+zwLKg7uomERaYeFFzKlhFH7A/T6PsQue/9JcLmJWS29041C/PcCaLH/r9Xajvk691EFkaNAq8lcKR75ew==; tarball SHA256: 94fc96188d7466485a10d2ad994e12568ac2844419c491aee88952b4d0db85ee.

Thirteen published-export scenarios passed on Node 26.8.1/macOS arm64 with native mode off: eight file/in-root-link/outside-link/dangling-link cases at leaf and ancestor positions, each rejecting, preserving, moving to a fresh backup, and retrying successfully; plus creation/reuse, traversal rejection, canonicalization, and structured archive errors. Outside targets/sentinels remain intact. This independent dependency check supports the helper contract; it does not substitute for the new consumer bind-selection proof.

Save the script below as fs-safe-contract-proof.mjs in an empty directory and run node fs-safe-contract-proof.mjs. It requires Node >=22 and tar, downloads only the official artifact, verifies its entire SHA512 before extraction, invokes published exports, prints JSON, and removes its own fixtures after success. Without registry access, use node fs-safe-contract-proof.mjs /path/to/fs-safe-0.7.2.tgz; the same hash check applies.

Standalone reproducible script
// Node >=22; tar on PATH. No npm install or package lifecycle scripts.
// node fs-safe-contract-proof.mjs [path/to/fs-safe-0.7.2.tgz]
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { execFileSync } from 'node:child_process';
const url = 'https://registry.npmjs.org/@openclaw/fs-safe/-/fs-safe-0.7.2.tgz';
const integrity = 'sha512-Ls27+zwLKg7uomERaYeFFzKlhFH7A/T6PsQue/9JcLmJWS29041C/PcCaLH/r9Xajvk691EFkaNAq8lcKR75ew==';
const work = await fs.mkdtemp(path.join(process.cwd(), 'fs-safe-proof-'));
const archivePath = path.join(work, 'package.tgz');
const bytes = process.argv[2] ? await fs.readFile(process.argv[2]) : Buffer.from(await (await fetch(url)).arrayBuffer());
assert.equal('sha512-' + createHash('sha512').update(bytes).digest('base64'), integrity);
await fs.writeFile(archivePath, bytes);
// Extraction is allowed only after the entire artifact matches the pinned official hash.
execFileSync('tar', ['-xzf', archivePath, '-C', work]);
process.env.OPENCLAW_FS_SAFE_NATIVE = 'off';
process.env.FS_SAFE_NATIVE = 'off';
const load = name => import(pathToFileURL(path.join(work, 'package/dist', name + '.js')));
const config = await load('config');
config.configureFsSafeNative({ mode: 'off' });
const {ensureDirectoryWithinRoot: ensure, canonicalPathFromExistingAncestor: canonical} = await load('advanced');
const archive = await load('archive');
const results = [];
const check = async (name, run) => { await run(); results.push({ name, pass: true }); };
const fixture = async name => {
  const base = path.join(work, name), root = path.join(base, 'root'), outside = path.join(base, 'outside');
  await fs.mkdir(root, {recursive:true}); await fs.mkdir(outside);
  await fs.writeFile(path.join(outside, 'sentinel'), 'unchanged');
  return {base,root,outside};
};
const request = (root, requestedPath) => ensure({rootDir: root, requestedPath, scopeLabel: 'proof'});
for (const kind of ['file','inside-link','outside-link','dangling-link']) {
  for (const position of ['leaf','ancestor']) {
    await check(`directory ${kind} ${position}: reject, preserve collision, retry`, async () => {
      const {base,root,outside} = await fixture(`${kind}-${position}`);
      const collision = path.join(root,'collision'), saved = path.join(base,'preserved');
      const target = kind === 'inside-link' ? path.join(root,'target') : kind === 'outside-link' ? outside : path.join(base,'absent');
      if (kind === 'file') await fs.writeFile(collision, 'collision bytes');
      else { if (kind === 'inside-link') await fs.mkdir(target); await fs.symlink(target, collision); }
      const before = await fs.lstat(collision);
      const requested = position === 'leaf' ? 'collision' : 'collision/child';
      assert.equal((await request(root, requested)).ok, false);
      assert.equal((await fs.lstat(collision)).ino, before.ino);
      if (kind === 'file') assert.equal(await fs.readFile(collision, 'utf8'), 'collision bytes');
      else assert.equal(await fs.readlink(collision), target);
      await fs.rename(collision, saved); // fresh synthetic sibling; never overwrites a backup
      assert.equal((await fs.lstat(saved)).ino, before.ino);
      assert.equal((await request(root, requested)).ok, true);
      assert.equal((await fs.stat(path.join(root, requested))).isDirectory(), true);
      assert.equal(await fs.readFile(path.join(outside,'sentinel'),'utf8'), 'unchanged');
      assert.deepEqual(await fs.readdir(outside), ['sentinel']);
      if (kind === 'inside-link') assert.deepEqual(await fs.readdir(target), []);
      if (kind === 'dangling-link') await assert.rejects(fs.lstat(target), {code:'ENOENT'});
    });
  }
}
await check('directory normal create/reuse and lexical escape rejection', async () => {
  const {root,outside} = await fixture('normal');
  assert.equal((await request(root,'a/b')).ok,true);
  await fs.writeFile(path.join(root,'a/b/sentinel'),'retained');
  assert.equal((await request(root,'a/b')).ok,true);
  assert.equal(await fs.readFile(path.join(root,'a/b/sentinel'),'utf8'),'retained');
  for (const p of ['..', '../outside/new', outside, '.', '', 'x\0y']) assert.equal((await request(root,p)).ok,false);
  assert.deepEqual(await fs.readdir(outside), ['sentinel']);
});
await check('canonical existing symlink ancestor rejoins missing suffix without creating it', async () => {
  const {base,root} = await fixture('canonical');
  const alias=path.join(base,'alias'); await fs.symlink(root,alias);
  const missing=path.join(alias,'not','created');
  assert.equal(await canonical(missing),path.join(await fs.realpath(root),'not','created'));
  await assert.rejects(fs.lstat(path.join(root,'not')), {code:'ENOENT'});
});
await check('archive entry validation throws ArchiveSecurityError with entry-path code', async () => {
  for (const p of ['../escape','/absolute','C:/drive','a/../b','nul\0path']) {
    assert.throws(()=>archive.validateArchiveEntryPath(p), e=>e instanceof archive.ArchiveSecurityError && e.code==='entry-path');
  }
  assert.doesNotThrow(()=>archive.validateArchiveEntryPath('normal/file.txt'));
});
await check('archive destination rejects file and symlink with distinct stable codes', async () => {
  const {base,root,outside}=await fixture('archive-destination');
  const file=path.join(base,'file'), link=path.join(base,'link');
  await fs.writeFile(file,'file sentinel'); await fs.symlink(outside,link);
  for (const [p,code] of [[file,'destination-not-directory'],[link,'destination-symlink']])
    await assert.rejects(archive.prepareArchiveDestinationDir(p),e=>e instanceof archive.ArchiveSecurityError && e.code===code);
  assert.equal(await archive.prepareArchiveDestinationDir(root),await fs.realpath(root));
  assert.equal(await fs.readFile(file,'utf8'),'file sentinel');
  assert.deepEqual(await fs.readdir(outside),['sentinel']);
});
await check('archive output rejects symlink ancestor with destination-symlink-traversal', async () => {
  const {root,outside}=await fixture('archive-output');
  await fs.symlink(outside,path.join(root,'link'));
  await assert.rejects(archive.prepareArchiveOutputPath({destinationDir:root,destinationRealDir:await fs.realpath(root),relPath:'link/child',outPath:path.join(root,'link/child'),originalPath:'link/child',isDirectory:false}), e=>e instanceof archive.ArchiveSecurityError && e.code==='destination-symlink-traversal');
  assert.deepEqual(await fs.readdir(outside),['sentinel']);
});
const sourceHashes = {};
for (const file of ['advanced.js','root-paths.js','absolute-path.js','archive-errors.js','archive-entry.js','archive-staging.js'])
  sourceHashes[file] = createHash('sha256').update(await fs.readFile(path.join(work,'package/dist',file))).digest('hex');
console.log(JSON.stringify({node:process.version,platform:process.platform,arch:process.arch,package:'@openclaw/[email protected]',url,integrity,sha256:createHash('sha256').update(bytes).digest('hex'),nativeMode:'off',passed:results.length,results,sourceHashes},null,2));
// Only this process-created scratch directory is removed after all assertions pass.
await fs.rm(work,{recursive:true,force:true});

@freeqaz-openai
freeqaz-openai requested a review from a team as a code owner September 4, 2026 23:30
@clawsweeper

clawsweeper Bot commented Sep 4, 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.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts agents Agent runtime and tooling extensions: openai size: L maintainer Maintainer-authored PR labels Sep 4, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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. labels Sep 4, 2026
@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

The branch lets OAuth-selected Codex models reach native validation, prepares sandbox skill mount directories, preserves Control UI build identity and inference causes, and adds tests and recovery documentation.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The branch has substantial real-path proof, but the host-write boundary and uncapped error path prevent a quality-ready rating.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦐 gold shrimp (3/6) Security review found an item that needs attention.

Merge readiness

⛔ Blocked before merge - 7 items remain

Keep this PR open. Current main has only partial overlap with its fixes, but the pinned branch has two actionable defects that prevent a merge-ready verdict.

Priority: P2
Reviewed head: bcd5bad446eea7b136320acd2c927c3e1205c039

Before merge

  • Add real behavior proof - Authority-chain proof required: Seven real rootful Docker layouts, four installed combined Gateway/Codex/Docker turns, and before/after UI build output support the allowed behavior. They do not show rejection before host I/O when an admitted custom bind source is retargeted to a forbidden root; no stored-data contract changes are introduced. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Keep the admitted bind source anchored through directory creation (P1) - Late discovery on the unchanged head: validation checks a custom bind’s canonical source, but this new realpath runs after that check. An in-root alias retargeted to a blocked or outside directory in the gap makes ensureDirectoryWithinRoot create the mountpoint under the new root without reapplying source policy, even if container startup later fails. Pin or revalidate the canonical source at the write boundary and prove the forbidden write is rejected.
  • Bound code-tagged inference errors after deduplication (P2) - Late discovery on the unchanged head: this return accepts any Error carrying the internal code and bypasses the 300-character cap below. A long tagged runtime error can therefore pass through the system-agent wrapper into the Gateway’s unavailable response without a bound. Preserve the single cause while applying a cap, and cover a long code-tagged error.
  • Resolve security concern: Bind-source retarget can escape the admitted host root - A workspace-controlled alias can be changed between canonical bind validation and the later realpath; fs-safe confines creation to the root it receives but does not check that the new root remains allowed.
  • Resolve merge risk - A custom bind-source alias can change after bind admission and before the new host directory write; the forbidden final effect has not been ruled out.
  • Resolve merge risk - Current main has replaced much of the sandbox mount owner and added workspace custody. Without a verified current-main merge result, the integration of this branch’s preparation path remains unverified.
  • Complete next step - Repair the bind-source host-write race and unbounded nested diagnostic, then verify the sandbox repair’s integration with current main before merge.

Findings

  • [P1] Keep the admitted bind source anchored through directory creation — src/agents/sandbox/workspace-mounts.ts:80-84
  • [P2] Bound code-tagged inference errors after deduplication — src/system-agent/inference-error.ts:15-16
  • [high] Bind-source retarget can escape the admitted host root — src/agents/sandbox/workspace-mounts.ts:80
Agent review details

How this fits together

The Gateway resolves an agent’s model and prepares sandbox mounts before Codex or a container runs. Inference errors and build identity then reach Gateway clients and the Control UI.

flowchart LR
 A[Auth profile and model] --> B[OpenAI provider routing]
 B --> C[Native Codex inference]
 D[Workspace and custom binds] --> E[Sandbox mount preparation]
 E --> F[Docker or browser container]
 C --> G[Gateway response and Control UI]
 F --> G
 H[UI build metadata] --> G
Loading

Technical review

Best possible solution:

Pin directory preparation to an admitted canonical host source, bound nested inference diagnostics, and integrate the mount-chain repair with current-main workspace custody while retaining preservation-first collision recovery.

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

Yes for the source-level OAuth and UI gaps; the PR also records historical before/after Docker controls. I did not execute a current-main reproduction in this read-only review.

Is this the best way to solve the issue?

No as submitted. The fixes sit in plausible owners, but host directory creation must retain the admitted source boundary and nested errors must retain a length cap.

Full review comments:

  • [P1] Keep the admitted bind source anchored through directory creation — src/agents/sandbox/workspace-mounts.ts:80-84
    Late discovery on the unchanged head: validation checks a custom bind’s canonical source, but this new realpath runs after that check. An in-root alias retargeted to a blocked or outside directory in the gap makes ensureDirectoryWithinRoot create the mountpoint under the new root without reapplying source policy, even if container startup later fails. Pin or revalidate the canonical source at the write boundary and prove the forbidden write is rejected.
    Confidence: 0.84
    Late finding: first raised on code an earlier review cycle already covered.
  • [P2] Bound code-tagged inference errors after deduplication — src/system-agent/inference-error.ts:15-16
    Late discovery on the unchanged head: this return accepts any Error carrying the internal code and bypasses the 300-character cap below. A long tagged runtime error can therefore pass through the system-agent wrapper into the Gateway’s unavailable response without a bound. Preserve the single cause while applying a cap, and cover a long code-tagged error.
    Confidence: 0.9
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is incorrect
Overall confidence: 0.84

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 800bf8e10e7c.

Merge-risk options

Maintainer options:

  1. Repair the host-write boundary (recommended)
    Keep the selected source anchored to its admission decision, prove a retargeted source cannot create directories outside allowed roots, and compose the repair with current main.
  2. Pause for sandbox integration
    Hold this branch if the newer mount owner cannot preserve its custom-bind fix without a broader rewrite.

Security

Needs attention: The new host directory write can resolve a custom bind source after its sandbox source-policy check.

Evidence

Security concerns:

  • [high] Bind-source retarget can escape the admitted host root — src/agents/sandbox/workspace-mounts.ts:80
    A workspace-controlled alias can be changed between canonical bind validation and the later realpath; fs-safe confines creation to the root it receives but does not check that the new root remains allowed.
    Confidence: 0.84

What I checked:

  • Introduced host write: The PR resolves each selected bind source again after admission, then asks fs-safe to create missing directories under that newly resolved root. (src/agents/sandbox/workspace-mounts.ts:80, bcd5bad446ee)
  • Admission boundary: Bind validation checks lexical and canonical sources against allowed and blocked paths before the later asynchronous preparation call; preparation does not repeat that source-policy check. (src/agents/sandbox/validate-sandbox-security.ts:363, bcd5bad446ee)
  • Filesystem dependency contract: The v0.8.1 helper rejects symlinks and files within the root it receives and creates missing segments there. It does not determine whether that root remains an allowed sandbox bind source. (src/root-paths.ts:227, 5872f54f62a7)
  • Unbounded nested diagnostic: The new early return accepts a code-tagged Error before the existing 300-character truncation; the Gateway returns the resulting message in its unavailable response. (src/system-agent/inference-error.ts:15, bcd5bad446ee)
  • Current-main necessity: Current main still excludes resolved OAuth profiles from the unlisted native Codex model path and still compares nullable stored UI commit identity directly with a possibly absent build commit. (extensions/openai/openai-chatgpt-provider.ts:323, 800bf8e10e7c)
  • Partial sandbox overlap on main: Main prepares a managed-worktree skill scaffold, but this branch also addresses attachment paths selected through custom ancestor binds. The current main sandbox owner has since been rewritten, and no pinned current-main test merge was available. (src/agents/sandbox/mount-plan.ts:45, 800bf8e10e7c)

PR surface

Source +117, Tests +678, Docs +43, Other 0. Total +838 across 18 files.

View PR surface stats
Area Files Added Removed Net
Source 6 132 15 +117
Tests 10 907 229 +678
Docs 1 43 0 +43
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 18 1083 245 +838

Review metrics

Metric Value Why it matters
Judged code growth production +117 net; tests/support about +485 substantive after fixture moves; docs +43 The production growth implements full attachment-chain preparation; its new host-write boundary needs review before merge.
Existing startup behavior 0 config keys added; 2 bind-startup behaviors changed Missing paths beneath admitted read-only binds are now prepared, while file or symlink collisions stop startup with documented recovery.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The PR addresses real but bounded provider, sandbox, and UI failures without evidence of a repository-wide emergency.
  • merge-risk: 🚨 compatibility: Existing custom-bind setups can encounter host preparation or preservation-first startup failures requiring operator recovery.
  • merge-risk: 🚨 security-boundary: The introduced filesystem write can use a bind source resolved after its allowed-root admission check.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

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

  • Add final-effect proof that retargeting an admitted bind source cannot create directories outside allowed roots before Docker starts.
  • Cap and test long code-tagged inference errors, then verify the sandbox repair against current main’s mount owner.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (16 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-05T15:01:20.244Z sha b268310 :: blocked before merge. :: none
  • reviewed 2026-09-05T15:42:26.684Z sha b268310 :: blocked before merge. :: none
  • reviewed 2026-09-05T16:03:48.852Z sha 98096bf :: blocked before merge. :: none
  • reviewed 2026-09-05T17:00:26.803Z sha 0dd80d1 :: blocked before merge. :: none
  • reviewed 2026-09-05T17:45:41.505Z sha ba48c9e :: blocked before merge. :: none
  • reviewed 2026-09-05T17:54:40.808Z sha bcd5bad :: blocked before merge. :: none
  • reviewed 2026-09-05T18:21:02.705Z sha bcd5bad :: blocked before merge. :: none
  • reviewed 2026-09-05T18:43:17.506Z sha bcd5bad :: blocked before merge. :: none

Reviewed September 25, 2026, 6:04 PM ET / 22:04 UTC (Revision 17).

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Sep 5, 2026
@openclaw-barnacle openclaw-barnacle Bot added the app: web-ui App: web-ui label Sep 5, 2026
@freeqaz-openai
freeqaz-openai force-pushed the fix/runtime-inference-ui-rebuild branch from e6c687a to 7de9162 Compare September 5, 2026 02:04
@freeqaz-openai
freeqaz-openai force-pushed the fix/runtime-inference-ui-rebuild branch from 7de9162 to d7c4d43 Compare September 5, 2026 03:09
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime labels Sep 5, 2026
@openclaw-barnacle openclaw-barnacle Bot added the docker Docker and sandbox tooling label Sep 5, 2026
Integrate the previously tested main revision and fix two CI fixtures.
Use the existing 15-second completion setup allowance from #139176,
keeping the cancellation scenario and succeeded assertion unchanged.
Give agent-end context fixtures the adjacent controlled-clock and
turn-start readiness pattern while preserving all terminal assertions.

No production code or dependency versions change in this follow-up.
Propagate attempts that settle before turn/start and report the last observed
fixture phase only on failure, preserving all terminal/context assertions.
Reuse the existing runtime-plan fixture so the synthetic workshop tool
does not trigger unrelated provider discovery during startup. Preserve
all context and terminal assertions, and remove the temporary timing
observations now that the startup path is identified.

Reuse the matching fixture correction from #139131.
Integrate main e09a265 after the completed PR CI run. Resolve the sibling
setup-wait comment overlap by taking the canonical main fixture; its
15-second wait and assertions remain unchanged.
@clawsweeper clawsweeper Bot added 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. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. labels Sep 26, 2026
@daniel-lxs

Copy link
Copy Markdown
Member

Hit this on a NixOS package of 2026.10.5. The package builds from the GitHub tag archive, which has no .git, and runs a standalone pnpm ui:build after pnpm build. The result is a dashboard 503 because the UI build ID no longer matches the runtime's.

Reproduced on main (d7349d9) from a git archive export, with no Git metadata and no build-ID env vars:

  • pnpm build: runtime and UI both 2026.10.8-2026-10-28T18-23-14.085Z
  • pnpm ui:build: UI becomes …18-39-03.956Z
  • Gateway GET / → 503 "Control UI assets could not be prepared". The Gateway's own UI rebuild goes through the same path and logs Control UI build completed but its identity is …18-48-45.468Z; expected …18-23-14.085Z.

With the equivalent one-line change in resolveUiBuildEnvironment (existing.commit !== (buildEnv.GIT_COMMIT ?? null)), the standalone rebuild keeps …18-23-14.085Z. The Gateway's self-rebuild then restores the matching ID, and GET / and the main script both return 200. I also added test cases for no commit on either side and a commit on only one side; they fail before the change and pass after it.

Main still has existing.commit !== buildEnv.GIT_COMMIT in scripts/ui.mts. Since this PR currently conflicts with main and bundles several unrelated fixes (OAuth inference, sandbox mounts, the fs-safe bump), would you be open to landing the UI build-ID part on its own? Happy to open a small PR for just that line and its test if that's easier for you.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui docker Docker and sandbox tooling docs Improvements or additions to documentation extensions: codex extensions: openai gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: XL 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.

2 participants