Skip to content

fix(cli): avoid writable session open during fallback - #156703

Merged
VACInc merged 5 commits into
openclaw:mainfrom
VACInc:fix/cli-fallback-readonly-session
Sep 27, 2026
Merged

VACInc merged 5 commits into
openclaw:mainfrom
VACInc:fix/cli-fallback-readonly-session

Conversation

@VACInc

@VACInc VACInc commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

Summary

High Level TLDR

CLI fallback can fail before producing a reply because its session metadata read opens a writable database. Read through the existing read-only worker, then recheck placement authority before executing the CLI.

What Problem This Solves

Fixes a reachable fallback failure when another connection holds a shared-state SQLite write transaction during a cold session read.

User Impact

A current session can reach CLI execution without this unnecessary writable-open contention. Replaced sessions and retired placement claims still abort before execution. This does not promise recovery from every database contention path or replay a whole turn.

Why This Change Was Made

The final delta against main contains three files: the canonical read-only worker call with placement revalidation; real SQLite contention, main/global session-key and retired-placement regressions; an updater output fixture repair. Current main independently includes the synchronized-frame TUI test repair; this PR has no TUI delta. Main was integrated while preserving the original contributor ancestry. The subagent admission and generated Workboard conflict resolutions take main's canonical implementations, leaving no net delta in either file. Main's newer media-task identity logic remains intact.

The updater fixture now owns unavailable-service observations and uses a per-case secure runtime directory. A verification run exposed that its synthetic service borrowed the operator's shared lifecycle lock, which another checkout legitimately held. Both preferred and Windows fallback temporary-directory paths now remain inside the fixture. Real lock acquisition, timeout budgets, recovery polling and report assertions are unchanged.

Root Cause

runCliFallbackCandidate rereads session metadata after placement admission. The previous loadSessionEntry call enters writable agent-database admission although it only needs a committed row. The regression closes the agent handle, opens a separate real shared-state SQLite connection with BEGIN IMMEDIATE, and observes the old accessor throw database is locked. The changed path uses withSessionEntryReadOnlyInWorker, propagates read errors, and revalidates settlement after the await.

The earlier Telegram incident had no first-throw stack. It supports the original report but does not establish that this accessor caused every observed contention error. Initial reply admission is separate from this later fallback reread.

Evidence

Real behavior proof

At pushed head 14b848aafbcccfb78c35288c6dfd8f5687e20975, on Linux with Node 24.19.0 and pnpm 12.5.0:

pnpm test src/auto-reply/reply/agent-runner-execution-cli-admission.test.ts --maxWorkers=1

Result: 13 passed, 53.24 seconds wrapper wall time, 51.18 seconds Vitest duration. The cold-contention case took 8.431 seconds; it needs real SQLite and the read-worker boundary because an accessor mock would hide the original defect. It returns one reply payload through executeAgentTurn and invokes the mocked CLI adapter once with the existing native binding. Retired placement and lifecycle revision changes abort before that invocation.

Negative control: restoring only the production candidate file from merge base 574927f256fa1a5355985b3d657d357abdd3fffb and running the cold-contention case fails: expected kind: "success" with reply payload, received kind: "final". The production file was restored afterward. No assertions or deadlines were weakened.

Isolated Gateway outcome on candidate 544af47211afba3df90760a58d07f347e6dd5312: A temporary CLI plugin was loaded normally and a real authenticated chat.send turn entered the real placement owner. At its callback boundary, the harness committed a newer session lifecycle revision, closed the agent handle, and held BEGIN IMMEDIATE on the shared-state database. It first verified that the old writable accessor throws database is locked, then let the unchanged candidate proceed under that lock.

The patched turn produced agent.wait { status: "error", stopReason: "superseded" }, one client chat event with state: "aborted" and stopReason: "superseded", and no invocation of the synthetic CLI executable. History contained the Gateway's own failure notice, not a model reply. The executable invocation marker stayed absent. The focused Gateway harness passed in 28.17 seconds. This is a safe stale-session abort through real Gateway RPC, not a claim of successful Telegram delivery.

Negative control used the same Gateway harness with only the candidate production file restored from pinned main 8d4d13c9e4e446b7ad72d3744ce52bcdc3100b9a: it failed with database is locked, without the expected superseded terminal outcome. The candidate file was restored and checkout verified clean. Initial harness attempts stopped at missing synthetic model/runtime registration; those attempts provide no product proof.

Verification

  • Published head: 794a477224066114b9b3e3aab75e36e24b5b0fba, tree e0add6b6297133990a45d1e5995dc00b2ef8f5f1, based on main da2bcd699bc. Remote head/tree verified. Contributor ancestry and trailers retained. The three changed files are byte-identical to the reviewed repair candidate.
  • Previous-head CI found four stale restart-status assertions introduced by main’s task retirement; incorporated the canonical main fix b459eb600f238d38f8b7156675e5868751f52c54. No product assertion was weakened in this PR. ClawSweeper cleared previous head cfe5361d967; exact new-head GitHub CI and refreshed review are pending. No readiness or complete current-head suite pass is claimed.
  • Independent repository-helper review of the repaired candidate completed scoped-clean at P3. Build and full static checks passed on predecessor 63c5d45; these are prior proof, not new-head CI.
  • On candidate 544af472: 86 focused cases across five files passed in three original-order runs (185.3s, 134.1s, 138.2s wall); another 33 worker ownership/invalidation cases passed in 25.84s. The updater scenario passed 20 targeted invocations after fixture isolation. CLI admission file: 13 cases, 53.24s wrapper wall; cold contention: 8.431s. CI timing will be recorded when available.
  • Earlier whole-repository testing was interrupted. One run recorded failures caused by missing pinned Chromium, Git 2.43 lacking --no-lazy-fetch, and a TUI assertion reading accumulated source-session output. Matching Chromium and Git 2.47.3 corrected the environment; current main contains the TUI owner fix. The affected 344 Docker-helper, 72 TUI and 30 browser cases then passed. A subsequent whole-suite run was also stopped; neither run is reported as a complete pass.
  • Sanitized real Gateway proof, negative control and reproducible harness. The production candidate source is unchanged after rebase.

What was not tested

No live Telegram delivery, real external CLI invocation, complete full-suite pass, final-candidate CI pass, Windows execution, or comparative runtime benchmark is claimed. The isolated regression uses real SQLite and production turn dispatch with a mocked CLI adapter; it does not prove channel delivery. No live Gateway was changed during this continuation.

Contributor credit

Work sessions

Implementation and discussion

@clawsweeper

clawsweeper Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 23, 2026
@clawsweeper

clawsweeper Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 27, 2026, 5:31 PM ET / 21:31 UTC (Revision 8).

ClawSweeper review

What this changes

Moves CLI fallback session reads to the existing read-only worker, rechecks placement before CLI execution, adds contention regressions, and isolates updater output test fixtures from shared service locks.

Merge readiness

✅ Ready for maintainer review

Current main still makes a writable session lookup during CLI fallback. The merged cold-admission repair addresses an earlier step, so this distinct fix remains useful. I found no blocking defect in the pinned patch.

Priority: P1
Reviewed head: 794a477224066114b9b3e3aab75e36e24b5b0fba

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The focused patch has a credible real-Gateway stale-session trace, a baseline negative control, and meaningful SQLite regressions; exact-head CI remains routine landing validation.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): An isolated authenticated Gateway chat.send used the production placement path and real SQLite contention; the after-fix trace showed a superseded abort before synthetic CLI invocation, while the stated main-file negative control hit the lock error. A direct fallback regression covers the current-session reply with a mocked CLI adapter. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): An isolated authenticated Gateway chat.send used the production placement path and real SQLite contention; the after-fix trace showed a superseded abort before synthetic CLI invocation, while the stated main-file negative control hit the lock error. A direct fallback regression covers the current-session reply with a mocked CLI adapter. No stored-data contract changes.
Evidence reviewed 9 items Pinned production change: The PR replaces the writable session lookup with a worker read, propagates read errors, and checks settlement again before using the entry.
Current main still needs the fix: The pinned main branch still calls the writable loadSessionEntry accessor after placement admission.
Worker and authority boundary: The existing reader retains its source across the asynchronous read and checks caller and source currency; placement settlement also checks that its claim remains live.
Findings None None.
Security None None.

How this fits together

An agent turn can select a CLI backend after fallback. The runner reads session metadata and placement authority before invoking that backend and returning a reply or a terminal abort.

flowchart LR
A[User turn] --> B[Fallback selection]
B --> C[Placement admission]
C --> D[Read-only session worker]
D --> E{Placement current?}
E -->|Yes| F[CLI backend and reply]
E -->|No| G[Superseded abort]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +10, Tests +132. Total +142 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 1 12 2 +10
Tests 2 135 3 +132
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 147 5 +142

Review metrics

Metric Value Why it matters
Production versus test growth production +10 net, test and test support +132 net The small production change is supported by a real SQLite contention regression and fixture isolation.
Focused test cost 53.24 s wrapper wall; 8.431 s contention case The PR body explains the above-budget test cost as necessary to exercise the real SQLite and worker boundary.

Technical review

Best possible solution:

Use the read-only session owner for fallback metadata and retain the live placement check before CLI execution, then land through the normal exact-head gates.

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

Yes. Current main still uses the writable accessor, and the supplied real-SQLite negative controls report its lock failure; I did not execute the case in this read-only checkout.

Is this the best way to solve the issue?

Yes. The existing read-only worker avoids the unnecessary writable admission, while settlement revalidation protects the added asynchronous gap.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Writable-open contention can stop an otherwise valid agent reply during CLI fallback.
  • merge-risk: 🚨 message-delivery: The changed session read gates CLI reply execution, so placement or read mistakes could suppress delivery despite passing ordinary checks.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): An isolated authenticated Gateway chat.send used the production placement path and real SQLite contention; the after-fix trace showed a superseded abort before synthetic CLI invocation, while the stated main-file negative control hit the lock error. A direct fallback regression covers the current-session reply with a mocked CLI adapter. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. An isolated authenticated Gateway chat.send used the production placement path and real SQLite contention; the after-fix trace showed a superseded abort before synthetic CLI invocation, while the stated main-file negative control hit the lock error. A direct fallback regression covers the current-session reply with a mocked CLI adapter. No stored-data contract changes.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Vito Cappello: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Vincent Koc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (7 earlier review cycles)
  • reviewed 2026-09-23T18:51:20.255Z sha 86b755a :: blocked before merge. :: none
  • reviewed 2026-09-26T02:04:36.244Z sha b75e41f :: blocked before merge. :: none
  • reviewed 2026-09-26T16:00:36.462Z sha b75e41f :: blocked before merge. :: none
  • reviewed 2026-09-27T16:25:59.900Z sha 75f8f69 :: blocked before merge. :: none
  • reviewed 2026-09-27T19:33:45.710Z sha 14b848a :: blocked before merge. :: none
  • reviewed 2026-09-27T19:51:30.621Z sha 14b848a :: blocked before merge. :: none
  • reviewed 2026-09-27T21:19:25.994Z sha cfe5361d967d09083b05e5c9dd73eebab7cbba92 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. label Sep 27, 2026
Preserve the author main merge. Read post-placement session metadata with the canonical read-only worker and revalidate settlement authority after the await. Exercise cold fallback reads with a real shared-state SQLite write transaction and retain main/global and retired-placement boundaries.

Keep expired schema admission distinct from recoverable resident-cache invalidation, fixing the reproduced current-head CI failure while retaining valid publication across ordinary read retirement. Give the updater output fixture its own unavailable service observations without weakening polling, timeout, report or mutation assertions.

Include the exact canonical generated Workboard Control UI asset-path refresh from Peter Steinberger commit 559b4f8. Normal asset generation reproduces these bytes after the already-merged protocol activity change; no browser source, styles, capabilities or permissions changed.

Co-authored-by: VACInc <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Jason (Json) <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot added cli CLI command changes agents Agent runtime and tooling plugin: workboard size: S and removed size: XS labels Sep 27, 2026
@VACInc

VACInc commented Sep 27, 2026

Copy link
Copy Markdown
Member Author

Updated head: cfe5361d967d09083b05e5c9dd73eebab7cbba92 (tree ff3eda0e1757ba8651668088e17750f47face0ec), rebased onto 97265123677f6141150202feefcb811793c3bd38 with contributor ancestry retained. The three remaining changed files are byte-identical to the reviewed repair candidate; current main supplies the TUI test repair. Exact-head CI is running.

The updated candidate retains main's canonical conflict resolutions and the original contributor ancestry. The read-only fallback and fixture-isolation repairs were reviewed with the repository P3 helper; final source review was scoped-clean.

The requested contended Gateway stale-session outcome is now observed on candidate 544af47211afba3df90760a58d07f347e6dd5312, with a real Gateway, authenticated chat.send, normal temporary CLI-plugin loading, real placement admission and real SQLite. The test decorates the existing placement owner's callback to arrange contention; it does not replace placement decisions, candidate execution, worker reads or Gateway terminal delivery.

Sanitized result:

{"placementCallbacks":1,"writableAccessorRejected":true,"candidateError":"AbortError: agent run superseded by a newer session writer","agentWait":{"status":"error","stopReason":"superseded"},"chatAbortEvents":1,"cliExecutableInvocations":0}

The patched harness passed in 28.17s. Gateway history also contains its own failure notice; this is a safe abort, not a successful model reply. Restoring only the candidate production file from main 8d4d13c9e4e446b7ad72d3744ce52bcdc3100b9a makes the same test fail with database is locked instead of superseded (42.28s). Candidate source was restored afterward.

Isolated proof harness (temporary, outside per-PR suites)

Save under .local/gateway-cli-contention.test.ts in a disposable checkout of the candidate. Run with the repository Vitest wrapper and the isolated Gateway config shown below. The fixture creates and closes its own Gateway and temporary state.

import { randomUUID } from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { expect, it, vi } from 'vitest';
import { testing as cliBackendsTesting } from '../src/agents/cli-backends.test-support.js';
import { loadSessionEntry, loadSessionEntryReadOnly, replaceSessionEntry } from '../src/config/sessions/session-accessor.js';
import { resolveSessionStorePathCore } from '../src/config/sessions/paths.js';
import { resolveSqliteScope } from '../src/config/sessions/session-accessor.sqlite-scope.js';
import { closeOpenClawAgentDatabaseByPathAsync } from '../src/state/openclaw-agent-db-lifecycle.js';
import { resolveOpenClawAgentSqlitePath } from '../src/state/openclaw-agent-db.paths.js';
import { resolveOpenClawStateSqlitePath } from '../src/state/openclaw-state-db.paths.js';
import { createGatewayConfigPath, setupGatewayTempHome, removeGatewayTempHome, resetGatewayTestState } from '../src/gateway/gateway.test-support.js';
import { startGatewayWithClient, disconnectGatewayClient } from '../src/gateway/test-helpers.e2e.js';
import { runQaGatewayFixture } from '../test/helpers/qa-gateway-cleanup.js';

const probe = vi.hoisted(() => ({ armed: false, installed: 0, entered: 0, writableRejected: false, error: '', revision: '' }));
vi.mock('../src/agents/session-placement-admission.js', async (importOriginal) => {
  const real = await importOriginal<typeof import('../src/agents/session-placement-admission.js')>();
  return {
    ...real,
    installSessionPlacementAdmissionProvider: (provider: Parameters<typeof real.installSessionPlacementAdmissionProvider>[0]) => { probe.installed++; return real.installSessionPlacementAdmissionProvider({
      ...provider,
      executeLocalTurn: (claim, runLocal, assertCurrent) => provider.executeLocalTurn(claim, async () => {
        if (!probe.armed || !claim.sessionKey?.includes('contention-proof')) return runLocal();
        probe.entered++;
        const target = {sessionKey: claim.sessionKey, agentId: claim.agentId ?? 'main', storePath: resolveSessionStorePathCore(undefined, {agentId: claim.agentId ?? 'main'})};
        const original = loadSessionEntryReadOnly(target);
        expect(original?.sessionId).toBe(claim.sessionId);
        probe.revision = randomUUID();
        await replaceSessionEntry(target, {...original!, lifecycleRevision: probe.revision});
        await closeOpenClawAgentDatabaseByPathAsync(resolveOpenClawAgentSqlitePath(resolveSqliteScope(target)));
        const holder = new DatabaseSync(resolveOpenClawStateSqlitePath());
        holder.exec('BEGIN IMMEDIATE');
        try {
          expect(() => loadSessionEntry(target)).toThrow(/database is locked/iu);
          probe.writableRejected = true;
          try { return await runLocal(); }
          catch (error) { probe.error = String(error); throw error; }
        } finally {
          if (holder.isTransaction) holder.exec('ROLLBACK');
          holder.close();
        }
      }, assertCurrent),
    }); },
  };
});

it('real Gateway rejects stale CLI session under cold shared-state write contention', async () => {
  resetGatewayTestState();
  const home = await setupGatewayTempHome({prefix: 'openclaw-cli-contention-proof-'});
  let gateway: Awaited<ReturnType<typeof startGatewayWithClient>> | undefined;
  const events: unknown[] = [];
  const token = randomUUID();
  const invoked = path.join(home.tempHome, 'cli-invoked');
  const executable = path.join(home.tempHome, 'synthetic-cli.cjs');
  await fs.writeFile(executable, `require('node:fs').writeFileSync(${JSON.stringify(invoked)},'invoked'); console.log('UNEXPECTED CLI REPLY');`);
  const pluginDir = path.join(home.tempHome, 'proof-fixture');
  await fs.mkdir(pluginDir);
  await fs.writeFile(path.join(pluginDir,'openclaw.plugin.json'),JSON.stringify({id:'proof-fixture',name:'Isolated CLI proof',cliBackends:['proof-cli'],activation:{onStartup:true},configSchema:{type:'object',additionalProperties:false,properties:{}},contracts:{cliBackends:['proof-cli']}}));
  await fs.writeFile(path.join(pluginDir,'index.js'),`export default {id:'proof-fixture',register(api){api.registerCliBackend({id:'proof-cli',modelProvider:'proof-cli',ownsNativeCompaction:false,config:{command:${JSON.stringify(process.execPath)},args:[${JSON.stringify(executable)}],output:'text',input:'arg',sessionMode:'none'}});}};`);
  await runQaGatewayFixture(async () => {
    gateway = await startGatewayWithClient({
      token,
      configPath: await createGatewayConfigPath(home.tempHome),
      cfg: {
        agents:{defaults:{workspace:home.workspaceDir,skipBootstrap:true,heartbeat:{every:'0m'},model:{primary:'proof-cli/proof'},models:{'proof-cli/proof':{agentRuntime:{id:'proof-cli'}}}}},
        gateway:{auth:{mode:'token',token}}, hooks:{enabled:false},
        plugins:{enabled:true,load:{paths:[pluginDir]},entries:{'proof-fixture':{enabled:true}}},
        models:{mode:'replace',providers:{'proof-cli':{baseUrl:'http://127.0.0.1:1/v1',api:'openai-responses',apiKey:'synthetic',models:[{id:'proof',name:'Proof',reasoning:false,input:['text'],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:32000,maxTokens:1024}]}}},
      },
      onEvent: (event) => { if (event.event === 'chat') events.push(event.payload); },
    });
    await gateway.server.startupSettled;
    console.log('PROBE_STARTED', JSON.stringify(probe));
    probe.armed = true;
    const sessionKey = `agent:main:contention-proof-${randomUUID()}`;
    const accepted = await gateway.client.request<{runId:string;status:string}>('chat.send',{sessionKey,message:'Return one reply.',deliver:false,idempotencyKey:randomUUID()},{expectFinal:false});
    expect(accepted.status).toBe('started');
    const terminal = await gateway.client.request('agent.wait',{runId:accepted.runId,timeoutMs:120000},{timeoutMs:125000});
    const history = await gateway.client.request<{messages:Array<{role:string;content:unknown}>}>('chat.history',{sessionKey,limit:100});
    console.log('CONTENTION_PROOF', JSON.stringify({probe,terminal,chatStates:events.map((event:any)=>({state:event.state,stopReason:event.stopReason}))}));
    expect(probe.entered).toBe(1);
    expect(probe.writableRejected).toBe(true);
    expect(probe.error).toMatch(/superseded/i);
    expect(terminal).toMatchObject({status:'error',stopReason:'superseded',error:'agent run superseded by a newer session writer'});
    expect(events.filter((event:any)=>event.state === 'aborted')).toEqual([expect.objectContaining({runId:accepted.runId,stopReason:'superseded'})]);
    const assistant = history.messages.filter(message=>message.role === 'assistant');
    expect(assistant).toHaveLength(1);
    expect(assistant[0]).toMatchObject({provider:'openclaw',model:'gateway-injected',content:[{type:'text',text:expect.stringContaining("OpenClaw couldn't produce or deliver a reply")} ]});
    expect(JSON.stringify(history.messages)).not.toContain('UNEXPECTED CLI REPLY');
    await expect(fs.stat(invoked)).rejects.toMatchObject({code:'ENOENT'});
  },
  async () => { if (gateway) await disconnectGatewayClient(gateway.client); },
  async () => { await gateway?.server.close({reason:'isolated contention proof complete'}); },
  () => { cliBackendsTesting.resetDepsForTest(); home.envSnapshot.restore(); resetGatewayTestState(); },
  () => removeGatewayTempHome(home.tempHome));
}, 180000);

.local/gateway-cli-contention.config.ts:

import { createGatewayServerIsolatedVitestConfig } from '../test/vitest/vitest.gateway-server-isolated.config.ts';
const config = createGatewayServerIsolatedVitestConfig();
export default {...config, test:{...config.test, include:['.local/gateway-cli-contention.test.ts'], passWithNoTests:false, maxWorkers:1}};
node scripts/run-vitest.mjs run --config .local/gateway-cli-contention.config.ts

@clawsweeper re-review

Please assess this exact head and the contended Gateway stale-session abort evidence above. Conflict resolution retains current main’s canonical subagent and generated asset changes. Review only; do not merge.

@clawsweeper

clawsweeper Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot removed agents Agent runtime and tooling plugin: workboard labels Sep 27, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 27, 2026
Integrate current main without rewriting contributor ancestry. Keep its
subagent admission failure propagation and generated Workboard assets.
Preserve the CLI worker read, settlement fence, and contention regression.

Keep updater output fixtures in their own secure runtime directory on
POSIX and Windows so synthetic service locks cannot contend with another
checkout or an operator service. Retain real lock and timeout behavior.

Co-authored-by: VACInc <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Jason (Json) <[email protected]>
@VACInc
VACInc force-pushed the fix/cli-fallback-readonly-session branch from cfe5361 to 794a477 Compare September 27, 2026 21:25
@VACInc

VACInc commented Sep 27, 2026

Copy link
Copy Markdown
Member Author

Rebased to current main; published head 794a477224066114b9b3e3aab75e36e24b5b0fba, tree e0add6b6297133990a45d1e5995dc00b2ef8f5f1.

CI run 36350918138 failed four cases in subagent-orphan-recovery.restart-integration.test.ts: the retired task projection expected running, while the current session owner correctly returned interrupted. Incorporated main’s exact fix b459eb600f238d38f8b7156675e5868751f52c54; the three PR files and the previously accepted Gateway proof remain unchanged. Fresh exact-head CI is pending.

@clawsweeper re-review

Review this exact head only; do not merge.

@clawsweeper

clawsweeper Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@VACInc
VACInc enabled auto-merge (squash) September 27, 2026 21:35
@VACInc
VACInc merged commit e200de9 into openclaw:main Sep 27, 2026
219 checks passed
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 28, 2026
* fix(cli): read fallback session state without writable open

* fix(cli): keep fallback replies working during state contention

Preserve the author main merge. Read post-placement session metadata with the canonical read-only worker and revalidate settlement authority after the await. Exercise cold fallback reads with a real shared-state SQLite write transaction and retain main/global and retired-placement boundaries.

Keep expired schema admission distinct from recoverable resident-cache invalidation, fixing the reproduced current-head CI failure while retaining valid publication across ordinary read retirement. Give the updater output fixture its own unavailable service observations without weakening polling, timeout, report or mutation assertions.

Include the exact canonical generated Workboard Control UI asset-path refresh from Peter Steinberger commit 4afb919. Normal asset generation reproduces these bytes after the already-merged protocol activity change; no browser source, styles, capabilities or permissions changed.

Co-authored-by: VACInc <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Jason (Json) <[email protected]>

---------

Co-authored-by: VACInc <[email protected]>
Co-authored-by: RoboClaw <[email protected]>
Co-authored-by: roboclaw-bot <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Jason (Json) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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.

2 participants