Skip to content

fix(sandbox): escape terminal controls in explain reports - #176773

Closed
Alix-007 wants to merge 3 commits into
openclaw:mainfrom
Alix-007:alix/fix-sandbox-explain-controls-20261019
Closed

Alix-007 wants to merge 3 commits into
openclaw:mainfrom
Alix-007:alix/fix-sandbox-explain-controls-20261019

Conversation

@Alix-007

@Alix-007 Alix-007 commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: sandbox explain can clear terminal output or insert extra report lines when a configured workspace path contains control characters.

User Impact

User impact: operators can read effective sandbox paths safely. JSON paths and the effective sandbox/workspace configuration keep their original values.

Why This Change Was Made

Apply the existing terminal sanitizer in the central human-readable value renderer, before styling. JSON returns before this renderer, so consumers retain the original filesystem paths. No config/default, protocol/schema, permission/security-policy, dependency, compatibility, or migration changes.

Evidence

Current-head maintenance — October 26, 2026

  • Product head: 70b78d7a30dbe25fac1d7d7e4d900bc46536bf92; integrated main: 423ae422ef67159dd85c84c417f4a7ea304e131c; independently reviewed clean tree: ff73f7dad505a2fb267dcfb88d94204b3d9ec4b5. Ordinary merge, existing contributor history retained, no force-push.
  • Repair: retain both main's expanded session/channel-alias cases and this PR's terminal-sanitization regression. The production fix still only applies the existing sanitizer to the human value renderer; JSON returns before it.
  • Production entry: node <checkout>/openclaw.mjs sandbox explain [--json]; canonical owner: src/commands/sandbox-explain.ts, unmocked, from a normal pnpm build:runtime with a matching clean-head buildstamp. Node 26.12.1/Linux, isolated HOME/config/state. Build and CLI proof each exited 0; this is not a mocked command action or direct internal-function proof.
  • Same collector command: node proof-sandbox.mjs "$CHECKOUT" <red|green>; current run uses green. Complete collector and helper retained below; collector SHA-256 cd2663f6f7fd0de720e6bddbe30737f1a9996927d4de311c188d233e51e65df8 (only the helper import uses the task-local layout); helper SHA-256 9618fa1e6e0263e7ce22d485b7c1620a8db3cd0dee2ef11727c0d4253bace8cb. Scenario and all assertions are unchanged.
  • Before: RED on historical baseline e63269c: 4 unsafe terminal controls and 2 injected report lines from the same real POSIX directory scenario; all CLI processes exited 0. This unchanged collector/scenario baseline is reused with its original October 19 SHA and observations below, not relabeled as a new run.
  • After: GREEN on 70b78d7a30dbe25fac1d7d7e4d900bc46536bf92, freshly run at 2026-10-26T08:40:10.650Z: 0 unsafe controls and 0 injected lines; 2 visible escaped newlines; JSON retains both original paths, fs.stat reads the real directory, config bytes are unchanged, ordinary workspace succeeds. All three real CLI processes exit 0.
  • Recorder/readback: real child stdout/stderr/exit, independent config-file bytes, parsed JSON and fs.stat of the path returned by the CLI. Sanitized observed output is inline below.
  • Validation: OPENCLAW_VITEST_RUNTIME=node pnpm test src/commands/sandbox-explain.test.ts --maxWorkers=1: 19/19 PASS, retaining main's session/channel-alias and stored-delivery matrix plus the terminal regression. Targeted production/test tsgo, type-aware lint, format, main-relative line-cap ratchet, whitespace and independent P0-P3 source/test review PASS on the identical reviewed tree.
  • Measured test cost: Modified sandbox-explain.test.ts: 177.901 s wall for 19 cases, one worker, including cold transform/native runtime preparation; no broad test sweep. The test/type/lint/format results were obtained before the merge commit on the byte-identical tree above; runtime proof and ratchet were run after committing.
  • Scope: two files; production +2/-1 and tests +28/-0. Existing-solutions preflight reuses terminal-core sanitization. All central human-rendered path/policy consumers are covered by this owner; JSON returns before rendering. No config/default, protocol/schema, permission/security-policy, dependency, migration or compatibility changes.
  • Hosted CI: NOT YET OBSERVED for this new head at package preparation; follow-up comments record actual hosted results.
  • Not tested; cleanup and limitations: Linux real-filesystem and subprocess byte-boundary proof only. Docker/Podman/remote runtime launches, sandbox enforcement, rich PTY colors, Windows/macOS terminals and the full CI suite are not exercised. No production sessions, channels, model credentials or service configuration were loaded. Generated proof fixtures are retained outside the checkout for inspection; only those generated directories may be cleaned later.
Current-head normal-built CLI stdout/stderr and real filesystem readback
{
  "name": "sandbox-terminal",
  "phase": "green",
  "head": "70b78d7a30dbe25fac1d7d7e4d900bc46536bf92",
  "time": "2026-10-26T08:40:10.650Z",
  "root": "<isolated-fixture>",
  "runs": [
    {
      "label": "sandbox-explain",
      "args": [
        "sandbox",
        "explain"
      ],
      "code": 0,
      "stdout": "Effective sandbox:\n  agentId: main\n  sessionKey: agent:main:main\n  mainSessionKey: agent:main:main\n  runtime: direct\n  mode: off scope: agent\n  workspaceAccess: none workspaceRoot: <isolated-fixture>/state/sandboxes\n  effectiveHostWorkspaceRoot: <isolated-fixture>/café\\nFORGED/workspace\n  backend: docker runtimeWorkdir: <isolated-fixture>/café\\nFORGED/workspace workspaceSource: direct\n\nSandbox tool policy:\n  allow (default): exec, process, read, ls, write, edit, apply_patch, view_image, github_read, github_search, github_publish, sessions_list, sessions_history, sessions_search, sessions_send, sessions_spawn, sessions_yield, subagents, session_status, get_goal, create_goal, update_goal\n  deny  (default): browser, canvas, computer, mobile_ui, nodes, automations, gateway, feishu, googlechat, nostr, buzz, msteams, mattermost, nextcloud-talk, matrix, raft, a2a, line, zalo, clickclack, x, zalouser, sms, synology-chat, tlon, discord, imessage, irc, reef, signal, slack, telegram, twitch, whatsapp\n\nElevated:\n  enabled: true\n  channel: (unknown)\n  allowedByConfig: false\n\nFix-it:\n  - tools.sandbox.tools.allow\n  - tools.sandbox.tools.alsoAllow\n  - tools.sandbox.tools.deny\n  - agents.entries.*.tools.sandbox.tools.allow\n  - agents.entries.*.tools.sandbox.tools.alsoAllow\n  - agents.entries.*.tools.sandbox.tools.deny\n  - tools.elevated.enabled\n\nDocs: https://docs.openclaw.ai/sandbox\n\n",
      "stderr": ""
    },
    {
      "label": "raw-path-json-control",
      "args": [
        "sandbox",
        "explain",
        "--json"
      ],
      "code": 0,
      "stdout": "{\n  \"docsUrl\": \"https://docs.openclaw.ai/sandbox\",\n  \"agentId\": \"main\",\n  \"sessionKey\": \"agent:main:main\",\n  \"mainSessionKey\": \"agent:main:main\",\n  \"sandbox\": {\n    \"mode\": \"off\",\n    \"scope\": \"agent\",\n    \"backend\": \"docker\",\n    \"workspaceAccess\": \"none\",\n    \"workspaceRoot\": \"<isolated-fixture>/state/sandboxes\",\n    \"effectiveHostWorkspaceRoot\": \"<isolated-fixture>/café\\u001b[2J\\u0007\\nFORGED/workspace\",\n    \"runtimeWorkdir\": \"<isolated-fixture>/café\\u001b[2J\\u0007\\nFORGED/workspace\",\n    \"workspaceMounts\": [],\n    \"workspaceSource\": \"direct\",\n    \"sessionIsSandboxed\": false,\n    \"tools\": {\n      \"allow\": [\n        \"exec\",\n        \"process\",\n        \"read\",\n        \"ls\",\n        \"write\",\n        \"edit\",\n        \"apply_patch\",\n        \"view_image\",\n        \"github_read\",\n        \"github_search\",\n        \"github_publish\",\n        \"sessions_list\",\n        \"sessions_history\",\n        \"sessions_search\",\n        \"sessions_send\",\n        \"sessions_spawn\",\n        \"sessions_yield\",\n        \"subagents\",\n        \"session_status\",\n        \"get_goal\",\n        \"create_goal\",\n        \"update_goal\"\n      ],\n      \"deny\": [\n        \"browser\",\n        \"canvas\",\n        \"computer\",\n        \"mobile_ui\",\n        \"nodes\",\n        \"automations\",\n        \"gateway\",\n        \"feishu\",\n        \"googlechat\",\n        \"nostr\",\n        \"buzz\",\n        \"msteams\",\n        \"mattermost\",\n        \"nextcloud-talk\",\n        \"matrix\",\n        \"raft\",\n        \"a2a\",\n        \"line\",\n        \"zalo\",\n        \"clickclack\",\n        \"x\",\n        \"zalouser\",\n        \"sms\",\n        \"synology-chat\",\n        \"tlon\",\n        \"discord\",\n        \"imessage\",\n        \"irc\",\n        \"reef\",\n        \"signal\",\n        \"slack\",\n        \"telegram\",\n        \"twitch\",\n        \"whatsapp\"\n      ],\n      \"sources\": {\n        \"allow\": {\n          \"source\": \"default\",\n          \"key\": \"tools.sandbox.tools.allow\"\n        },\n        \"deny\": {\n          \"source\": \"default\",\n          \"key\": \"tools.sandbox.tools.deny\"\n        }\n      }\n    }\n  },\n  \"elevated\": {\n    \"enabled\": true,\n    \"allowedByConfig\": false,\n    \"alwaysAllowedByConfig\": false,\n    \"allowFrom\": {},\n    \"failures\": []\n  },\n  \"fixIt\": [\n    \"tools.sandbox.tools.allow\",\n    \"tools.sandbox.tools.alsoAllow\",\n    \"tools.sandbox.tools.deny\",\n    \"agents.entries.*.tools.sandbox.tools.allow\",\n    \"agents.entries.*.tools.sandbox.tools.alsoAllow\",\n    \"agents.entries.*.tools.sandbox.tools.deny\",\n    \"tools.elevated.enabled\"\n  ]\n}\n",
      "stderr": ""
    },
    {
      "label": "normal-workspace-control",
      "args": [
        "sandbox",
        "explain"
      ],
      "code": 0,
      "stdout": "Effective sandbox:\n  agentId: main\n  sessionKey: agent:main:main\n  mainSessionKey: agent:main:main\n  runtime: direct\n  mode: off scope: agent\n  workspaceAccess: none workspaceRoot: <isolated-fixture>/state/sandboxes\n  effectiveHostWorkspaceRoot: <isolated-fixture>/workspace\n  backend: docker runtimeWorkdir: <isolated-fixture>/workspace workspaceSource: direct\n\nSandbox tool policy:\n  allow (default): exec, process, read, ls, write, edit, apply_patch, view_image, github_read, github_search, github_publish, sessions_list, sessions_history, sessions_search, sessions_send, sessions_spawn, sessions_yield, subagents, session_status, get_goal, create_goal, update_goal\n  deny  (default): browser, canvas, computer, mobile_ui, nodes, automations, gateway, feishu, googlechat, nostr, buzz, msteams, mattermost, nextcloud-talk, matrix, raft, a2a, line, zalo, clickclack, x, zalouser, sms, synology-chat, tlon, discord, imessage, irc, reef, signal, slack, telegram, twitch, whatsapp\n\nElevated:\n  enabled: true\n  channel: (unknown)\n  allowedByConfig: false\n\nFix-it:\n  - tools.sandbox.tools.allow\n  - tools.sandbox.tools.alsoAllow\n  - tools.sandbox.tools.deny\n  - agents.entries.*.tools.sandbox.tools.allow\n  - agents.entries.*.tools.sandbox.tools.alsoAllow\n  - agents.entries.*.tools.sandbox.tools.deny\n  - tools.elevated.enabled\n\nDocs: https://docs.openclaw.ai/sandbox\n\n",
      "stderr": ""
    }
  ],
  "observations": [
    {
      "controls": 0,
      "forged": 0,
      "stdout": "Effective sandbox:\n  agentId: main\n  sessionKey: agent:main:main\n  mainSessionKey: agent:main:main\n  runtime: direct\n  mode: off scope: agent\n  workspaceAccess: none workspaceRoot: <isolated-fixture>/state/sandboxes\n  effectiveHostWorkspaceRoot: <isolated-fixture>/café\\nFORGED/workspace\n  backend: docker runtimeWorkdir: <isolated-fixture>/café\\nFORGED/workspace workspaceSource: direct\n\nSandbox tool policy:\n  allow (default): exec, process, read, ls, write, edit, apply_patch, view_image, github_read, github_search, github_publish, sessions_list, sessions_history, sessions_search, sessions_send, sessions_spawn, sessions_yield, subagents, session_status, get_goal, create_goal, update_goal\n  deny  (default): browser, canvas, computer, mobile_ui, nodes, automations, gateway, feishu, googlechat, nostr, buzz, msteams, mattermost, nextcloud-talk, matrix, raft, a2a, line, zalo, clickclack, x, zalouser, sms, synology-chat, tlon, discord, imessage, irc, reef, signal, slack, telegram, twitch, whatsapp\n\nElevated:\n  enabled: true\n  channel: (unknown)\n  allowedByConfig: false\n\nFix-it:\n  - tools.sandbox.tools.allow\n  - tools.sandbox.tools.alsoAllow\n  - tools.sandbox.tools.deny\n  - agents.entries.*.tools.sandbox.tools.allow\n  - agents.entries.*.tools.sandbox.tools.alsoAllow\n  - agents.entries.*.tools.sandbox.tools.deny\n  - tools.elevated.enabled\n\nDocs: https://docs.openclaw.ai/sandbox\n\n",
      "jsonPathsUnchanged": true,
      "realDirectoryReadback": true,
      "configBytesUnchanged": true,
      "configHash": "549f8fae7d2152fc7b4121bdb5dd9f00d3d22cad4c7ffc29d78969a5a9d2fad6",
      "legalWorkspaceControl": true
    }
  ],
  "result": "PASS",
  "rawReceiptSha256": "18bd3004a6f89fca9bda39345faf11a8930109e9d742058dae4ed2f49b07ef72",
  "buildStamp": {
    "builtAt": 1793003812148,
    "head": "70b78d7a30dbe25fac1d7d7e4d900bc46536bf92",
    "inputsClean": true,
    "inputSignature": "db08350500a23229c0efcb7becfa9826b2330cb6078daaa64c49d9d11d669b42"
  },
  "buildCommand": "pnpm build:runtime"
}

Historical baseline, collector and previous-head observations

Everything below retains its original SHA, timestamp and test counts; it is not the current-head run.

Normal-built CLI, Node 26.1.0 on Linux, isolated HOME/config/state, no external services or production credentials:

  • Base: e63269c28a22a6eec7c0758d54dc6dbe674e2886 (RED run 2026-10-19T01:09:29.619Z).
  • Product head: 2a30dc5cfb78889c02a308c1e93a68e6240b94ee (GREEN run 2026-10-19T01:37:37.219Z).
  • Production entry: node <checkout>/openclaw.mjs sandbox explain [--json]; canonical owner: src/commands/sandbox-explain.ts.
  • Recorder/readback: captured child stdout/stderr/exit plus config-file bytes and fs.stat of the path read back from JSON. Every child process exited 0 on both versions.
Actual CLI BASE controls / injected lines HEAD controls / injected lines
sandbox explain 4 / 2 0 / 0

The fixture creates a real POSIX directory with café\x1b[2J\x07\nFORGED in its name. HEAD prints visible café\nFORGED in the report; --json returns the unchanged path and fs.stat confirms it is the existing directory. No container needs to run to reproduce this display bug.

Controls: 0 unsafe controls and 0 injected lines; two visible escaped newlines; JSON retains both original paths and fs.stat confirms the actual directory; ordinary workspace remains readable; config bytes unchanged.

Focused regressions: OPENCLAW_VITEST_RUNTIME=node pnpm test src/commands/sandbox-explain.test.ts --maxWorkers=1 — 10/10 pass, exit 0; 103.19 s selected shard, 110.60 s including wrapper. Core and canonical commands-test type checks, explicit type-aware lint (including the modified test), format, line-cap ratchet, and independent adversarial review passed. The host's older glibc cannot load tsrs, so type checks used the documented OPENCLAW_TYPECHECKER=tsgo fallback.

Generated proof receipt
  • Scenario: sandbox explain safely displays configured workspace paths while JSON retains usable paths; ordinary Unicode, JSON values and stored config are preserved
  • Entry: node /openclaw.mjs sandbox explain [--json]; disputed owner ran unmocked: src/commands/sandbox-explain.ts
  • Same command on base e63269c and head 2a30dc5: node proof-sandbox.mjs <checkout> <red|green>
    • Before (base): RED human report emits four unsafe controls and two injected lines from a real POSIX workspace path
    • After (head): GREEN report emits 0 unsafe controls and 0 injected lines; all three real CLI processes exit 0
  • Readback (subprocess,config-file,disk): captured child stdout/stderr/exit plus config-file bytes and fs.stat of the path read back from JSON
  • Proof harness: complete collector and shared fixture source published in PR body; portable helper import path is the only local-layout adjustment
  • Control: 0 unsafe controls and 0 injected lines; two visible escaped newlines; JSON retains both original paths and fs.stat confirms the actual directory; ordinary workspace remains readable; config bytes unchanged
  • Other callers checked: all human value renderer consumers including workspace root, host workspace, runtime workdir, mount paths and tool policy; JSON returns before rendering; trusted headings and enums unchanged
  • Tests: OPENCLAW_VITEST_RUNTIME=node pnpm test src/commands/sandbox-explain.test.ts --maxWorkers=1: 10 pass, exit 0; core and canonical commands-test types, explicit type-aware lint, format, ratchet and independent P0-P3 adversarial review pass (measured cost: 103.19 s selected shard; 110.60 s including wrapper; cold preparation reported separately in local task log)
  • Not tested: Docker/Podman/remote runtime launches, sandbox enforcement, rich PTY colors, Windows/macOS terminals and full CI suite locally; real filesystem path proof is Linux-only
Reproduce the real CLI proof

Install the pinned dependencies in clean checkouts at the SHAs above, then build normally with pnpm build qaRuntime (used on BASE) or pnpm build cliStartup (used on HEAD; core CLI only). Save the two files below together outside the checkout. The same collector and scenario run on both versions:

node proof-sandbox.mjs <base-checkout> red
node proof-sandbox.mjs <head-checkout> green

Invocation form: node proof-sandbox.mjs <checkout> <red|green>. Only the helper import path is flattened for copying. The collector checks clean Git HEAD against the build stamp and records stdout, stderr, exit status, and readback in its printed temporary receipt directory.

proof-sandbox.mjs:

import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import {fixture} from './proof-cli-common.mjs';

const f = fixture('sandbox-terminal', process.argv[2], process.argv[3]);
const workspace = path.join(f.root,'café\x1b[2J\x07\nFORGED','workspace');
fs.mkdirSync(workspace,{recursive:true});
f.config.agents.entries.main.workspace = workspace;
f.config.agents.defaults.sandbox = {mode:'off'};
f.writeConfig();
const before = fs.readFileSync(f.configPath);
const report = f.run('sandbox-explain',['sandbox','explain']);
assert.equal(report.code,0,report.stderr);
const controls = (report.stdout.match(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g) ?? []).length;
const forged = (report.stdout.match(/\nFORGED/g) ?? []).length;
if (f.phase === 'red') {assert.ok(controls>0);assert.equal(forged,2);}
else {assert.equal(controls,0);assert.equal(forged,0);assert.equal((report.stdout.match(/café\\nFORGED/g) ?? []).length,2);}
const json = f.run('raw-path-json-control',['sandbox','explain','--json']);
assert.equal(json.code,0,json.stderr);
const payload = JSON.parse(json.stdout);
assert.equal(payload.sandbox.effectiveHostWorkspaceRoot,workspace);
assert.equal(payload.sandbox.runtimeWorkdir,workspace);
assert.equal(payload.sandbox.sessionIsSandboxed,false);
assert.ok(fs.statSync(payload.sandbox.runtimeWorkdir).isDirectory());
assert.ok(fs.readFileSync(f.configPath).equals(before));
f.config.agents.entries.main.workspace = path.join(f.root,'workspace');
f.writeConfig();
const normal = f.run('normal-workspace-control',['sandbox','explain']);
assert.equal(normal.code,0,normal.stderr);
assert.ok(normal.stdout.includes(`effectiveHostWorkspaceRoot: ${f.config.agents.entries.main.workspace}\n`));
assert.ok(normal.stdout.includes('runtime: direct'));
assert.equal((normal.stdout.match(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g) ?? []).length,0);
f.receipt.observations.push({controls,forged,stdout:report.stdout,jsonPathsUnchanged:true,realDirectoryReadback:true,configBytesUnchanged:true,configHash:f.hash(before),legalWorkspaceControl:true});
f.finish();

proof-cli-common.mjs:

import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {createHash} from 'node:crypto';
import {execFileSync, spawnSync} from 'node:child_process';

export function fixture(name, checkoutArg, phase) {
  assert.ok(['red', 'green'].includes(phase));
  const checkout = path.resolve(checkoutArg);
  const root = fs.mkdtempSync(path.join(os.tmpdir(), `alix-${name}-`));
  for (const leaf of ['home', 'state', 'workspace', 'tmp']) fs.mkdirSync(path.join(root, leaf));
  const hash = bytes => createHash('sha256').update(bytes).digest('hex');
  // Read-only containers receive a host Git attestation before the bind mount.
  const head = process.env.PROOF_CHECKED_HEAD ?? execFileSync('git', ['rev-parse', 'HEAD'], {cwd: checkout, encoding: 'utf8'}).trim();
  const status = process.env.PROOF_CHECKED_STATUS ?? execFileSync('git', ['status', '--porcelain'], {cwd: checkout, encoding: 'utf8'}).trim();
  assert.match(head, /^[a-f0-9]{40}$/);
  const stamp = JSON.parse(fs.readFileSync(path.join(checkout, 'dist/.buildstamp')));
  assert.equal(status, ''); assert.equal(stamp.head, head); assert.equal(stamp.inputsClean, true);
  const configPath = path.join(root, 'openclaw.json');
  const config = {agents: {ownership: 'explicit', defaults: {systemAgent: {agentId: 'main'}}, entries: {main: {workspace: path.join(root, 'workspace')}}}, tools: {profile: 'minimal'}, plugins: {allow: [], slots: {memory: 'none'}}, logging: {level: 'warn', consoleLevel: 'warn', file: path.join(root, 'runtime.log')}};
  const receipt = {name, phase, head, time: new Date().toISOString(), root, runs: [], observations: []};
  const save = () => fs.writeFileSync(path.join(root, 'receipt.json'), JSON.stringify(receipt, null, 2));
  const writeConfig = () => fs.writeFileSync(configPath, JSON.stringify(config), {mode: 0o600});
  writeConfig();
  const env = {PATH: `${path.dirname(process.execPath)}:/usr/bin:/bin`, HOME: path.join(root, 'home'), TMPDIR: path.join(root, 'tmp'), LANG: 'C.UTF-8', TZ: 'UTC', CI: '1', OPENCLAW_CONFIG_PATH: configPath, OPENCLAW_STATE_DIR: path.join(root, 'state'), OPENCLAW_NO_RESPAWN: '1', OPENCLAW_DISABLE_BONJOUR: '1'};
  function run(label, args) {
    const result = spawnSync(process.execPath, [path.join(checkout, 'openclaw.mjs'), ...args], {cwd: path.join(root, 'workspace'), env, encoding: 'utf8', timeout: 90000, maxBuffer: 4 * 1024 * 1024});
    const row = {label, args, code: result.status, stdout: result.stdout, stderr: result.stderr};
    receipt.runs.push(row); save();
    console.log(JSON.stringify({label, code: row.code}));
    assert.equal(result.error, undefined, 'Timeout/spawn errors are not product RED');
    assert.equal(result.signal, null);
    return row;
  }
  function finish() {receipt.result = 'PASS'; save(); console.log(JSON.stringify({result: 'PASS', receipt: path.join(root, 'receipt.json')}));}
  return {root, config, configPath, writeConfig, receipt, run, finish, hash, phase};
}
Scope and limitations

Two files; production/test LOC (added, removed):

28	0	src/commands/sandbox-explain.test.ts
2	1	src/commands/sandbox-explain.ts

Type-check reuse: the core and commands-test graphs passed at cc10221. The follow-up only renames a local fixture variable and expresses the same ESC/BEL exclusions as string assertions; production is byte-identical. Focused tests, explicit modified-test type-aware lint, formatting and ratchet were rerun; the normal CLI build and behavior proof were rerun at the final head.

Existing-solutions preflight: reused the canonical terminal-core sanitizer; no new abstraction. Sibling coverage: all human value renderer consumers including workspace root, host workspace, runtime workdir, mount paths and tool policy; JSON returns before rendering; trusted headings and enums unchanged.

Not tested: Docker/Podman/remote runtime launches, sandbox enforcement, rich PTY colors, Windows/macOS terminals and full CI suite locally; real filesystem path proof is Linux-only. Fixtures remain in their printed temporary directories for inspection; remove only those generated directories after inspecting them. No production data, existing sessions, channels or service configuration were loaded or changed.

@clawsweeper

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

@Alix-007
Alix-007 marked this pull request as ready for review October 19, 2026 01:43
@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations docker Docker and sandbox tooling size: XS labels Oct 19, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 19, 2026
@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR sanitizes human-readable sandbox explanation values before styling while preserving original JSON paths.

Example: A Linux workspace directory contains café followed by ESC[2J, BEL, a newline, and FORGED.

  • Before: Running sandbox explain emits terminal controls and inserts FORGED on another report line.
  • After: The report displays café\nFORGED safely, while --json preserves the actual filesystem path.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused owner-level repair with relevant shipped-CLI evidence, a meaningful regression, passing exact-head checks, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Current-head normal-built sandbox explain CLI output exercises the changed renderer on Linux with a real control-bearing directory: unsafe controls and injected lines are absent, JSON paths remain usable, config bytes remain unchanged, and an ordinary workspace succeeds.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A configured workspace path can clear terminal output or inject misleading lines into sandbox explain reports.
Reason: Safe diagnostic rendering provides clear user value while preserving configuration, JSON paths, ordinary text, and styling.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR provides a minimal fix for a current-main diagnostic rendering bug, with no actionable defects found and passing exact-head CI.

Priority: P2
Reviewed head: 70b78d7a30dbe25fac1d7d7e4d900bc46536bf92

Before merge

None.

Findings

None.

Agent review details

How this fits together

The sandbox explain CLI resolves configuration and session facts into a payload, then emits structured JSON or a styled terminal report.

flowchart TD
  A[CLI arguments] --> B[Sandbox explanation owner]
  C[Configuration and session facts] --> B
  B --> D[Original JSON payload]
  B --> E[Sanitized display values]
  E --> F[Styled terminal report]
Loading

Technical review

Best possible solution:

Apply the existing terminal sanitizer at the shared display renderer while retaining raw values for JSON and runtime use.

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

Current-main source exposes the raw-path rendering failure, and the contributor supplies matching built-CLI before/after observations; this read-only review executed no target code.

Is this the best way to solve the issue?

This is the smallest complete fix using existing owners: one sanitizer call protects shared display values, and one command regression checks text safety without changing JSON.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 820e3ce6b95a.

Provenance checked

  • Human-readable value renderer keeps the original intent (1bd5500: Add colored CLI output and documentation links through shared terminal formatting helpers.)
  • Shared terminal helper ownership keeps the original intent (de1dfab: Move shared terminal helpers into the terminal-core package.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Pinned introduced change: The introduced production change imports the existing sanitizer and applies it at the shared human-readable value renderer; the added regression checks terminal safety and JSON fidelity. (src/commands/sandbox-explain.ts:289, 70b78d7a30db)
  • Current-main defect remains: Current main passes configured workspace paths directly through colorize; JSON already returns before the human renderer. (src/commands/sandbox-explain.ts:288, 820e3ce6b95a)
  • Existing sanitizer contract: The canonical helper strips ANSI sequences, removes other control characters, and visibly escapes newlines, carriage returns, and tabs; its existing tests cover those behaviors. (packages/terminal-core/src/safe-text.ts:11, 70b78d7a30db)
  • Contributor supplied shipped CLI proof: The complete PR body includes current-head normal-built CLI output from isolated Linux state: zero unsafe controls or injected lines, unchanged JSON paths with filesystem readback, unchanged config bytes, and a normal-workspace control; the historical baseline records four controls and two injected lines. (70b78d7a30db)
  • Presentation provenance: The reviewed historical patch introduces the shared styled renderer to add colored CLI output and documentation links; sanitization preserves that architecture and styling intent. (src/commands/sandbox-explain.ts:289, 1bd55008325b)
  • Exact-head checks and mergeability: Live GitHub reads confirm the reviewed head is cleanly mergeable, openclaw/ci-gate succeeds, and dependency-review and security-sensitive-review statuses succeed; paginated checks show no failing required product check. (70b78d7a30db)

Likely related people:

  • Peter Steinberger: Raw commit 1bd5500 adds src/commands/sandbox-explain.ts:299 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1bd55008325b; files: src/commands/sandbox-explain.ts)

PR surface

Source +1, Tests +28. Total +29 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 2 1 +1
Tests 1 28 0 +28
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 30 1 +29

Labels

Label changes:

No label changes.

Label justifications:

  • P2: A valid configured path can corrupt an operator-facing diagnostic report, with limited scope and a focused repair.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 (1 earlier review cycle)
  • reviewed 2026-10-19T02:00:23.036Z sha 2a30dc5 :: needs maintainer review before merge. :: none

Reviewed October 26, 2026, 5:07 AM ET / 09:07 UTC (Revision 2).

@roboclaw-bot roboclaw-bot added the clawtributor-review Clawtributor pull request awaiting prioritized maintainer review label Oct 22, 2026
@Alix-007

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Updated head: 70b78d7a30dbe25fac1d7d7e4d900bc46536bf92. Resolved the merge conflict while retaining main's session/channel alias cases and the terminal regression. The updated Evidence includes a normal clean-head runtime build and three real CLI readbacks: zero unsafe controls or injected lines, unchanged JSON paths and config, real filesystem readback, and the ordinary-workspace control. All 19 focused tests pass.

Current-head evidence and inspectable output. Exact-head CI is green; targeted types, lint, format, line-cap check and independent source/publication reviews passed. Thank you for reviewing the updated revision.

@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

obviyus added a commit that referenced this pull request Oct 27, 2026
fix(cli): escape terminal controls in untrusted values through one owner

CLI human-readable output printed user-controlled values such as config paths, names, directories, binding descriptions, plugin metadata and dead-letter scopes without neutralizing terminal control sequences, so a crafted value could inject ANSI, OSC 8 or C1 sequences into the terminal. Earlier fixes wrapped one call site at a time. A single owner now does this: `terminalText` in terminal-core's safe-text escapes interpolated values before styling, and the display-only `displayPath` delegates to it. Raw path shortening, JSON output and the trusted styling of `renderTable` are unchanged, and the per-site wrapping is replaced.

This absorbs #184685, #184666, #184324, #184303, #176763, #176773 and #172873 by @Alix-007 and #184861 by @qingminglong, whose original commits are kept, and moves the earlier merged per-site fixes onto the same owner.

Evidence: built CLI in a secretless container, with ESC/CSI, OSC 8 and C1 sequences injected into values for eleven commands across eight families. Main printed the raw sequences; this change printed them neutralized, normal colored output and JSON values were unchanged, and dead-letter errors keep their stderr and JSON contracts. Raw-byte captures: #185927 (comment). Production +81.

Co-authored-by: Alix-007 <[email protected]>
Co-authored-by: qingminlong <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
@obviyus

obviyus commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

@shakkernerd: #185927 (2d2b465) landed a root-cause fix that routes the covered CLI report values through one terminalText owner, and it covers this PR's output sites. @Alix-007's commit from this PR is kept there with co-author credit. Leaving the close to you since it's assigned to you.

Rechecked against current main 7b31ab208c80123884bb3d67842331122e48d3d6: sandbox explain encodes configured display values with terminalText before theme styling. The site is fixed on main. This PR remains open for its assignee.

@roboclaw-bot roboclaw-bot added the clawtributors PR from a clawtributor label Oct 28, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 28, 2026
fix(cli): escape terminal controls in untrusted values through one owner

CLI human-readable output printed user-controlled values such as config paths, names, directories, binding descriptions, plugin metadata and dead-letter scopes without neutralizing terminal control sequences, so a crafted value could inject ANSI, OSC 8 or C1 sequences into the terminal. Earlier fixes wrapped one call site at a time. A single owner now does this: `terminalText` in terminal-core's safe-text escapes interpolated values before styling, and the display-only `displayPath` delegates to it. Raw path shortening, JSON output and the trusted styling of `renderTable` are unchanged, and the per-site wrapping is replaced.

This absorbs openclaw#184685, openclaw#184666, openclaw#184324, openclaw#184303, openclaw#176763, openclaw#176773 and openclaw#172873 by @Alix-007 and openclaw#184861 by @qingminglong, whose original commits are kept, and moves the earlier merged per-site fixes onto the same owner.

Evidence: built CLI in a secretless container, with ESC/CSI, OSC 8 and C1 sequences injected into values for eleven commands across eight families. Main printed the raw sequences; this change printed them neutralized, normal colored output and JSON values were unchanged, and dead-letter errors keep their stderr and JSON contracts. Raw-byte captures: openclaw#185927 (comment). Production +81.

Co-authored-by: Alix-007 <[email protected]>
Co-authored-by: qingminlong <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
@Alix-007

Copy link
Copy Markdown
Contributor Author

Thanks @obviyus for checking the sandbox output against the shared fix in #185927. Appreciate the follow-up!

@Alix-007

Alix-007 commented Nov 1, 2026

Copy link
Copy Markdown
Contributor Author

Hi @shakkernerd, could you take a look at the final disposition here when you have a chance? It's been open for over a week; #185927 already includes the fix with co-author credit. Thanks!

@Alix-007 Alix-007 closed this Nov 2, 2026
@Alix-007

Alix-007 commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Closing this as absorbed by the merged #185927, with contributor credit retained. Thanks @obviyus for integrating the fix, and @shakkernerd for taking a look!

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

Labels

clawtributor-review Clawtributor pull request awaiting prioritized maintainer review clawtributors PR from a clawtributor commands Command implementations docker Docker and sandbox tooling P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: XS status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants