Skip to content

fix: preserve unfinished output when an agent turn times out - #142236

Closed
destire-mio wants to merge 14 commits into
openclaw:mainfrom
destire-mio:fix/141839-timeout-history
Closed

destire-mio wants to merge 14 commits into
openclaw:mainfrom
destire-mio:fix/141839-timeout-history

Conversation

@destire-mio

@destire-mio destire-mio commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Latest update (2026-10-03): head 7717a5c merges main, fixes partial-output redaction/bounds, and clears conflicts. Current validation and remaining owner decision. Earlier exact-head evidence below is historical.

Related: #141839. Extends merged #142135.

What Problem This Solves

When a Gateway deadline stops a run with buffered assistant text, a later model request can lose that unfinished text. A successor can also read history while the timeout report is pending. Merged #142135 supplies the deadline terminal report and CLI persistence context; this PR addresses the remaining buffered-output and admission gaps.

Why This Change Was Made

Capture the buffer before abort cleanup and pass it through the existing terminal lifecycle owner. The existing SQLite report transaction stores the timeout statement and JSON-quoted unfinished output in one run-failed-before-reply custom message. Existing readers understand that record format. This PR adds no table, index, required field, schema version, replay exception, or backfill.

Wait for the same agent/session's timeout persistence before and after work admission. The second check covers a deadline observed while admission waits. Both waits run outside the session writer, allowing the terminal write to acquire it. If the observed write rejects, the pending successor receives the error before dispatch and releases its reservation, abort controller, and admission lease.

User Impact

The report states that a timed-out turn may have performed work; it makes no claim of completion, external success, or rollback. Existing assistant rows are retained. A partial assistant row does not suppress the timeout report. Normal completion, user cancellation, and ordinary failures retain their existing behavior. Transactional authority validation and per-run deduplication remain with the existing owner.

Evidence: schema-24 existing-database refresh (2026-09-30)

This refresh addresses Revision 10's existing-database proof gap on the unchanged published head 7952a8218c90802e572a3dca24e882a1c78534d3, tree c7b4cd2a40126044ab43fc2e6299c216113462ae. It supersedes the schema-23 compatibility scope of the historical runs below. No production or repository test bytes changed; no new commit or CI rerun was needed. The earlier exact-head CI failure and its bounded diagnosis remain as recorded below. Storage-owner acceptance of unfinished-text retention/visibility and failed-write recovery remains pending.

Pinned sources and real owner paths

  • Published old source: v2026.9.3, commit 1391f7cd2d40ab5bbcf2f5f831d3a64f520e72d7, annotated tag a69d657b4b74556017f2d0ef98b0c64aeabb3643, agent schema 19
  • Same-schema upstream source: this PR's main parent 5073ee41abfbe2cab02c0e58a12d4dcc27bcba18, agent schema 24; an untagged source snapshot, not a released-package claim
  • Candidate: the unchanged PR head/tree above, agent schema 24

Complete release and upstream source archives were materialized and compared with Git blob identities: 39,434 released-source files and 50,751 upstream files, zero mismatches. Each phase used a fresh Node process and isolated synthetic state. The release's actual session accessor created and closed the original SQLite database; SQLite backup captured the pre-upgrade recovery copy and migrated Gateway input. The candidate used withAgentDatabaseMaintenanceLease and migrateOpenClawAgentDatabaseForMaintenance, then the real report writer, session accessor, and SessionManager. No manual version-marker edits, extracted readers, replacement migration, or in-memory database were used.

Environment: Linux x64, Node 24.19.0. Workspace code resolves within each pinned source tree; external runtime dependencies reuse the existing installation (including Kysely 0.29.6, tsx 4.23.15, and fs-safe 0.21.2). The released source declares older versions of these dependencies. This proves the versioned source storage path, not an installed release package or its full dependency supply chain. Initial harness setup probes failed on missing mdast-util-from-markdown and ms; package-local links and the installed [email protected] resolved those setup errors before the recorded passing paths. The nine same-schema phases completed successfully before the first released-source setup failure; only the blocked upgrade lane was subsequently run again on fresh state.

Results

  1. Released existing database, 19 → 24: two existing sessions contained six transcript events, including long quoted Unicode text, and nonempty sessionDiffBaseline values. The unmigrated candidate read refused with a Doctor instruction. The real migration owner then published 24 in both PRAGMA user_version and schema_meta, retaining all original event IDs, sequence, creation timestamps, and decoded JSON hashes. Two long events changed physical representation from JSON text to Zstd while preserving decoded bytes. Full-entry reads reconstructed the exact baselines; raw read-only inspection confirmed that the baselines moved out of session_nodes.entry_json into session_entry_snapshots with unchanged values. Duplicate empty/partial timeout write requests produced exactly one report per run, increasing six events to eight.
  2. Rollback boundary: the real released schema-19 reader refused schema 24, leaving the checked transcript payloads unchanged. Restoring the pre-upgrade SQLite backup allowed that released writer to add two continuations; the current candidate migrated and reopened eight events with their original histories and baselines intact. Post-backup writes, including the two timeout reports, are absent after restore. No in-place downgrade is claimed.
  3. Same-schema roundtrip: upstream schema-24 writer creates six events → candidate writes two reports → upstream reader replays both reports and appends two ordinary continuations → candidate reopens ten events. Original physical/decoded payload hashes, IDs, sequence, timestamps, and baselines were preserved at every boundary.
  4. Real Gateway on the upgraded database: the unchanged six-scenario test started from the released seed migrated to schema 24. All six scenarios passed, and both original histories reached the next loopback provider request. Partial text and the timeout notice were replayed; report-write rejection produced zero successor provider requests. The backed-up Gateway output contained 42 events. Upstream schema-24 code read it and added two continuations; the candidate reopened 44 events. All 42 Gateway-output events retained their physical/decoded hashes and identity/order/timestamp fields through that roundtrip, including one report in each original empty/partial session. Both original baselines remained exact.

All 14 recorded SQLite snapshots reported integrity_check=ok, no foreign-key violations, and the expected owner and matching schema markers. The explicit baseline checker passed all 14. Hash preservation covers the checked transcript payloads/identity/order/time fields and fixture baselines, not every table or byte of a changing database file.

Recorded lane Phases Sum of phase wall times Outcome
Schema-24 upstream/candidate roundtrip 9 136.833 s All passed
Released database upgrade, refusal, backup restore and reopen 16 158.229 s Passed; exit 1 expected only for the two explicit version refusals
Gateway output → upstream read/write → candidate reopen 5 31.615 s All passed

Measured Gateway cost: test body 34.945 s, Vitest 111.24 s, wrapper 118.46 s, shell wall 120 s. The existing live-test SHA-256 remains 93cbe8936c4e01f9e8a0d4d8e9231e90c3e459fa18b1b5bf8b7a4bb93e3920a5. These are local current-tree runs; this opt-in released-database fixture has not been executed in hosted CI. Existing current-head fresh-fixture CI proof remains linked below.

Limitations: synthetic existing agent databases only; no installed CLI updater, shared-state migration, service restart, automatic package rollback, physical disk failure, or interrupted migration. Snapshot coverage here is one populated sessionDiffBaseline per session, not a complete schema-24 snapshot-edge-case suite. The existing six-scenario proof injects rejection before the report operation and establishes no successor provider I/O; it does not prove successful recovery of lost partial text after a failed write. This supplement makes no new storage-policy or recovery-contract decision.

Reproducing the refreshed run

Use the three full harness files retained in the historical appendix below, apply the following exact patch, and add check-snapshots.mjs below. Set releaseRoot, baseRoot, and candidateRoot to the pinned sources above, and gatewayMigratedSeedOutput to a new absolute SQLite output path. Use isolated dependencies/state. Run node run.mjs config.json all; this creates the upgraded seed before adding the direct timeout reports. For the separate Gateway pass:

OPENCLAW_VITEST_MAX_WORKERS=1 NODE_OPTIONS=--max-old-space-size=2048 \
OPENCLAW_TIMEOUT_HISTORY_PROOF_DATABASE=/absolute/path/to/gateway-input-schema24.sqlite \
OPENCLAW_TIMEOUT_HISTORY_PROOF_DATABASE_OUTPUT=/absolute/path/to/gateway-output-schema24.sqlite \
node scripts/run-vitest.mjs src/gateway/server-methods/chat.timeout-history-live-proof.test.ts

Use a distinct runName for the final node run.mjs config-gateway.json gateway-roundtrip, with gatewayOutput set to that output and gatewaySeedSnapshot set to the upgrade run's candidate-migrated.json. Run node check-snapshots.mjs runs/<runName> on each completed lane directory. The version assertions intentionally pin these configured roles to 19/24; the unused gateway-seed mode is not a released-schema-19 seeding command in this pinned harness.

Exact harness delta from the historical appendix
--- a/run.mjs
+++ b/run.mjs
@@ -67,9 +67,17 @@
   await fs.writeFile(path.join(evidenceRoot, `${label}.json`), JSON.stringify(result, null, 2) + "\n");
   assert.deepEqual(result.integrity, [{ integrity_check: "ok" }], `${label} integrity`);
   assert.deepEqual(result.foreignKeyViolations, [], `${label} foreign keys`);
+  const expectedVersion = /^(release-original-backup|candidate-refused-unmigrated|release-restored)$/.test(label) ? 19 : 24;
+  assert.equal(result.userVersion, expectedVersion, `${label} exact user_version`);
+  assert.equal(result.schemaMeta.length, 1, `${label} schema_meta row count`);
+  assert.equal(result.schemaMeta[0].schema_version, expectedVersion, `${label} exact metadata version`);
+  assert.equal(result.schemaMeta[0].role, "agent");
+  assert.equal(result.schemaMeta[0].agent_id, "main");
+  assert(result.rows.length >= 6, `${label} nonempty original history`);
   return result;
 }
 function preserve(before, after, physical) {
+  assert(before.rows.length >= 6, "preservation needs the six original events");
   for (const row of before.rows) {
     const found = after.rows.find((entry) => entry.sessionId === row.sessionId && entry.seq === row.seq);
     assert(found, `Missing original event ${row.sessionId}/${row.seq}`);
@@ -80,7 +88,12 @@
   }
 }
 function replay(result, timeouts, continuation = false) {
+  assert.deepEqual(result.rows.map((row) => row.scenario), ["empty-timeout", "partial-timeout"]);
   for (const row of result.rows) {
+    if (!result.mode.endsWith("gateway")) {
+      assert.equal(row.baselinePreserved, true);
+      assert.equal(row.eventCount, 3 + Number(timeouts) + Number(continuation));
+    }
     assert.equal(row.seedPresent, true);
     assert.equal(row.replayContainsSeed, true);
     assert.equal(row.reportCount, timeouts ? 1 : 0);
@@ -197,4 +210,3 @@
   await save();
   throw error;
 }
-
--- a/worker.mjs
+++ b/worker.mjs
@@ -21,6 +21,12 @@
   env: { ...process.env, OPENCLAW_STATE_DIR: stateDir },
 });
 const digest = (value) => createHash("sha256").update(value).digest("hex");
+const baselineFor = (scenario) => ({
+  version: 1,
+  sessionId: targetFor(scenario).sessionId,
+  root: "/synthetic/schema24-workspace",
+  files: [{ path: "proof/漢字-🙂.txt", fingerprint: "schema24-original-fingerprint" }],
+});
 
 await fs.mkdir(stateDir, { recursive: true });
 const agentDatabase = await fromSource("src/state/openclaw-agent-db.ts");
@@ -49,6 +55,7 @@
           // Keep this existing session inside the Gateway's current idle window.
           // Historical message timestamps remain old and are checked byte for byte.
           updatedAt: activeAt + index,
+          sessionDiffBaseline: baselineFor(scenario),
         });
         await accessor.appendTranscriptMessage(target, {
           cwd: stateDir,
@@ -113,6 +120,10 @@
     for (const scenario of scenarios) {
       const target = targetFor(scenario);
       const events = await accessor.loadTranscriptEvents(target);
+      const entry = await accessor.loadSessionEntry(target);
+      if (!mode.endsWith("gateway")) {
+        assert.deepEqual(entry?.sessionDiffBaseline, baselineFor(scenario));
+      }
       const messages = SessionManager.open(target, stateDir).buildSessionContext().messages;
       const reports = events.filter((event) => event.customType === "run-failed-before-reply");
       const replay = JSON.stringify(messages);
@@ -121,6 +132,7 @@
         sessionKey: target.sessionKey,
         sessionId: target.sessionId,
         eventCount: events.length,
+        baselinePreserved: JSON.stringify(entry?.sessionDiffBaseline) === JSON.stringify(baselineFor(scenario)),
         seedPresent: JSON.stringify(events).includes(seedMarker(scenario)),
         reportCount: reports.length,
         reports,
@@ -161,4 +173,3 @@
 };
 console.log(`DATABASE_COMPATIBILITY_RESULT ${JSON.stringify(result)}`);
 if (failure) process.exitCode = 1;
-
--- a/snapshot.mjs
+++ b/snapshot.mjs
@@ -9,6 +9,12 @@
 try {
   if (backupPath) await backup(database, backupPath);
   const columns = new Set(database.prepare("PRAGMA table_info(transcript_events)").all().map((row) => row.name));
+  const hasSnapshots = database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session_entry_snapshots'").get() !== undefined;
+  const nodes = database.prepare("SELECT session_key, entry_json FROM session_nodes ORDER BY session_key").all().map((row) => ({
+    sessionKey: row.session_key,
+    baselineInline: Object.hasOwn(JSON.parse(row.entry_json), "sessionDiffBaseline"),
+  }));
+  const snapshots = hasSnapshots ? database.prepare("SELECT * FROM session_entry_snapshots ORDER BY session_key, field").all() : [];
   const hash = (value) => createHash("sha256").update(value).digest("hex");
   const rows = database.prepare("SELECT * FROM transcript_events ORDER BY session_id, seq").all().map((row) => {
     const physical = row.event_json === null ? row.event_zstd : Buffer.from(row.event_json, "utf8");
@@ -36,9 +42,10 @@
     integrity: database.prepare("PRAGMA integrity_check").all(),
     foreignKeyViolations: database.prepare("PRAGMA foreign_key_check").all(),
     hasCompressedPayloadColumns: columns.has("event_zstd"),
+    nodes,
+    snapshots,
     rows,
   }, null, 2));
 } finally {
   database.close();
 }
-
import assert from "node:assert/strict";
import fs from "node:fs/promises";
import path from "node:path";

const root = process.argv[2];
assert(root);
let count = 0;
for (const filename of await fs.readdir(root)) {
  if (!filename.endsWith(".json") || filename === "results.json") continue;
  const result = JSON.parse(await fs.readFile(path.join(root, filename), "utf8"));
  if (!result.nodes) continue;
  for (const scenario of ["empty-timeout", "partial-timeout"]) {
    const key = `agent:main:timeout-proof-${scenario}`;
    const node = result.nodes.find((row) => row.sessionKey === key);
    assert(node, `${filename}: missing ${key}`);
    if (result.userVersion === 19) {
      assert.equal(node.baselineInline, true);
      assert.equal(result.snapshots.length, 0);
    } else {
      assert.equal(result.userVersion, 24);
      assert.equal(node.baselineInline, false);
      const row = result.snapshots.find((entry) => entry.session_key === key && entry.field === "sessionDiffBaseline");
      assert(row, `${filename}: missing separated baseline`);
      assert.deepEqual(JSON.parse(row.value_json), {
        version: 1,
        sessionId: `database-compatibility-${scenario}`,
        root: "/synthetic/schema24-workspace",
        files: [{ path: "proof/漢字-🙂.txt", fingerprint: "schema24-original-fingerprint" }],
      });
    }
  }
  count++;
}
assert(count > 0);
console.log(JSON.stringify({ snapshotsChecked: count, exactBaselinePreserved: true }));
Current artifact identities (SHA-256; SQLite binaries are not attached)
Artifact SHA-256
Released schema-19 backup d077c9ffe2675426223b914b0007347ebadba2ef4d8334aa02d57ac62e23c807
Migrated schema-24 Gateway input bb98af385efad6cb8ad193a938e78bbd97033c14b14fb04e97c1e414ab7105b9
Gateway schema-24 output 8040c25e2e0c1d3ba33cb7b30ac027229ca199d1f7d6e967655c12b585b40013
Final 44-event roundtrip 818e44271ea11b6685960c5dce2b1f16f45ed18cd2e9c16bc9a7cf44ec703490

Evidence: conflict resolution on 2026-09-30

Current head: 7952a8218c90802e572a3dca24e882a1c78534d3. This is a non-force merge of main 5073ee41abfbe2cab02c0e58a12d4dcc27bcba18 into the existing PR branch; the published tree was read back and matches the tested local tree c7b4cd2a40126044ab43fc2e6299c216113462ae. GitHub reports this head mergeable. The exact-head CI run completed with failure: 116 jobs succeeded, 23 were skipped, and one test shard failed (with the aggregate gate consequently failing). The earlier green run below does not validate this merge commit. The failure is chat.reset-visible-yield.test.ts / preserves real chat yield metadata and the held descendant's complete outcome, reporting requester did not resume in the failed shard. Bounded triage found the identical requester did not resume failure in an earlier, unrelated PR run on 2026-09-29. That job tested merge 97f4ced0a8a61d2d68bb9ac42c4834aa63e5aa7d (PR head 9f902836e59d86e5f419816fcb2b5786cc8518b1, then-main d8d0e9c990ea8006fdf8907d9e4972dbf452372b). Direct source reads at that tested merge show no timeoutPartialText and no waitForChatSessionTimeoutPersistence; its failing test blob, 3c940399e1800ede1576e10256fafa7614ecaf1d, exactly matches this branch. The same failure therefore occurs without this PR's timeout-history/admission changes.

A local replay of the failing isolated partition's eight files, using two workers as in CI, passed both chat.reset-visible-yield variants (reset 50.408 s, complete 14.257 s). The whole replay was 503 passed / 4 failed: four agent.test.ts yielded-orchestrator followup cases instead failed an announce call-count assertion; those four cases passed in the hosted run. This is bounded diagnostic evidence, not a repair or an all-green replay. Upstream #161691 addresses this test's per-step timer races and remains open; its proposed root cause is not independently established by this investigation. The current CI failure remains recorded and unresolved. No remote rerun, timeout increase, assertion weakening, or unrelated scheduler change was made.

The resolution preserves main's sessionEntryCurrent contract and receipt-write guard, ordinary-failure wording, and scheduler ownership. It retains this PR's timeout-specific report, captured unfinished text, and both same-agent/session persistence waits. The live proof now observes the real maintenance:dedupe job registered with GatewayScheduler instead of the retired setInterval hook; it still exercises real RPC admission, deadline handling, SQLite persistence, and the next loopback provider request.

Local validation used Linux x64, Node 24.19.0, and the repository-pinned pnpm 12.5.1:

  • Four focused files passed 97 tests (52 Gateway tests and 45 CLI-history tests), with 350 seconds total wrapper wall time. This run preceded only the behavior-equivalent void maintenance.sweep() annotation in the test.
  • The final committed live-test bytes passed a fresh standalone run: six scenarios, test body 30.126 seconds, Vitest 94.80 seconds, wrapper 100.05 seconds (101 seconds shell wall). Empty/partial timeout, user cancellation, normal completion, duplicate terminal events, and report-write rejection all passed. The next provider request contained the partial output and timeout notice; the waiting successor made zero provider requests after report-write rejection.
  • The current-head hosted live-proof job passed all six scenarios and recorded partialPreserved: true and successorProviderRequests: 0 after report-write rejection. Its live-test body took 16.910 seconds.
  • Full production core typecheck (node scripts/run-tsgo.mjs -p tsconfig.core.json --incremental --tsBuildInfoFile .artifacts/tsgo-cache/core.tsbuildinfo) passed. Type-aware lint passed for all 12 changed files using the unchanged lint rules and a task-local TypeScript root set limited to those files plus existing declarations. Formatting, conflict-marker, line-cap, max-lines, assertion-safety and diff checks passed. Independent code review found no actionable resolution defect.
  • Validation limits: the original broad core lint graph was killed by the local host twice, including a bounded-concurrency attempt. The native check:changed aggregate passed its preliminary guards but was stopped during the broad core-test graph-boundary scan to avoid duplicating large scans while completing final runtime proof. The aggregate and all-test typecheck are not claimed complete. The exact-head remote CI result and its unresolved failure are stated above.
  • The inherited main now declares agent schema 24. This PR adds no further schema change. The earlier copied released-database experiments below describe the schema-23 head; the new schema-24 refresh above now supplies current-tree upgrade, backup-restore, and roundtrip proof. Storage-contract maintainer acceptance remains pending.

Final live-test SHA-256: 93cbe8936c4e01f9e8a0d4d8e9231e90c3e459fa18b1b5bf8b7a4bb93e3920a5.

Historical evidence: previous head and hosted CI

The following original evidence is retained for provenance. References below to "current head", "current-head", and schema 23 describe the earlier 878114675c81e88c78e29d73a76cc0f530a80b8f candidate, not the merge commit above.

Current head: 878114675c81e88c78e29d73a76cc0f530a80b8f. The current-head CI run completed with success. The PR check snapshot contains 145 successful checks, 49 skipped checks, and one neutral CodeQL check; there are no failed or pending checks in that snapshot. Maintainer acceptance remains separate from CI.

The final local run passed 3 files / 52 tests using the production Gateway, its SQLite store, and a loopback HTTP provider capture. It used the migrated copy of the released source's existing database described below. The six cases cover empty timeout, partial timeout, user cancel, normal completion, duplicate terminal events, and report-persistence rejection. Original seed history reached the next provider request in both existing sessions.

The current-head live-test log exposes TIMEOUT_HISTORY_CASE captures of transcript rows and outgoing provider request bodies, plus TIMEOUT_CONCURRENT_ADMISSION and TIMEOUT_HISTORY_VERDICT. Hosted CI uses the default fresh fixture; the released-database copy and cross-version roundtrip are local evidence below.

The local run took place before the final test-only commit: its metadata names 98aab05bde7ffa9ff04af9b4062858f37afe0bba plus the test repairs. The production source is identical to current head, and all three recorded test-file SHA-256 hashes match current head. This is source-equivalent pre-commit proof; the linked hosted run is the committed-head execution.

The fixed five-second absence wait is removed. A scheduling callback identifies entry into the wait; it is not used as proof that admission awaits persistence. The decisive assertion rejects the actual report operation and observes GatewayClientRequestError, INVALID_REQUEST, the injected message, no successor registration, and zero successor provider requests. Counterfactuals that remove both admission awaits, or discard the persistence result and wait an unrelated one second, fail because the RPC returns started instead of rejecting. These are mutation results, not additional passing suites.

Targeted lint, formatting, line-cap and diff checks passed locally. The local full changed gate was incomplete in the sparse checkout; current hosted CI is the full remote result. The previously failing configuration fixture passes in this run, including the include-only case at 2.710 seconds. That passing replay is not a claimed root-cause repair of its earlier hook timeout.

Final local Gateway verdict and test-source identities
[
  {
    "scenario": "empty-timeout",
    "durableTimeoutReports": 1,
    "historyHasTimeout": true,
    "nextProviderRequestHasTimeout": true,
    "stopReasons": [
      "timeout"
    ]
  },
  {
    "scenario": "partial-timeout",
    "reportGateReached": true,
    "providerRequestBeforeReportRelease": false,
    "durableTimeoutReports": 1,
    "historyHasTimeout": true,
    "nextProviderRequestHasTimeout": true,
    "partialPreserved": true,
    "stopReasons": [
      "timeout"
    ]
  },
  {
    "scenario": "user-cancel",
    "durableTimeoutReports": 0,
    "historyHasTimeout": false,
    "nextProviderRequestHasTimeout": false,
    "stopReasons": [
      "rpc"
    ]
  },
  {
    "scenario": "normal",
    "durableTimeoutReports": 0,
    "historyHasTimeout": false,
    "nextProviderRequestHasTimeout": false,
    "stopReasons": [
      "stop"
    ]
  },
  {
    "scenario": "duplicate-timeout",
    "durableTimeoutReports": 1,
    "historyHasTimeout": true,
    "nextProviderRequestHasTimeout": true,
    "stopReasons": [
      "timeout"
    ]
  },
  {
    "scenario": "persistence-failure-timeout",
    "reportGateReached": true,
    "reportFailurePropagated": true,
    "durableTimeoutReports": 0,
    "successorProviderRequests": 0
  }
]
{
  "src/gateway/session-lifecycle-run-failure.test.ts": "f7d0bd24a2f3773f822ca8e975455f45f3bb19a16a0c10bfb01ef465d1e69a42",
  "src/gateway/server-methods/chat-send-session-binding.test.ts": "90de7898b8a5a1e4435fcf66a8fedd725932d96d2a18364c0d92442214c014e9",
  "src/gateway/server-methods/chat.timeout-history-live-proof.test.ts": "e95a4b1686db922dfc3e3d5a0035a7c3c2d5de32033e4580aaec4231863d1f72"
}

Measured test cost

The new file is src/gateway/server-methods/chat.timeout-history-live-proof.test.ts. Local environment: macOS arm64, Node 26.5.0, pnpm 12.4.2, OPENCLAW_VITEST_MAX_WORKERS=1. The measured command used the repository's ready-dependency wrapper allowed by AGENTS.md:

OPENCLAW_VITEST_MAX_WORKERS=1 \
OPENCLAW_TIMEOUT_HISTORY_PROOF_DATABASE=/absolute/path/to/gateway-input-migrated.sqlite \
node scripts/run-vitest.mjs src/gateway/server-methods/chat.timeout-history-live-proof.test.ts
Measurement Recorded result Scope
Local standalone file, wrapper wall 135.22 s One worker, current live-file bytes, six scenarios
Same standalone run, Vitest duration 124.71 s Includes transform/import/setup/teardown
Same standalone run, test body 63.130 s Reported by Vitest
Final local three-file run 356.548 s External process wall; 52 tests, not the new file alone
Same three-file run, Vitest duration 341.34 s New live test body: 82.001 s
Current-head CI, live test body 19.064 s Exact job log; checks-node-changed-compact-large-39
Current-head CI, containing job wall 931 s Multiple files plus setup; not attributed to this test

The local standalone command is the native wrapper above, not an execution of the literal pnpm test <file> --maxWorkers=1 spelling. The corresponding standard entrypoint is pnpm test src/gateway/server-methods/chat.timeout-history-live-proof.test.ts --maxWorkers=1.

This file exceeds the 30-second guide threshold. It shares one Gateway boot across six scenarios and exercises the real RPC → timeout owner → SQLite report → next HTTP request chain. Reducer/owner tests do not prove that the registered entrypoint calls those owners or that the provider receives their persisted result. The fixed absence delay was removed; the recorded cost still includes Gateway startup, module transforms, SQLite workers, and real transport completion. No claim is made that this is a sub-five-second unit test or a benchmark of production latency.

Storage contract and maintainer decision

The storage review checkpoint applies because the retained content and admission failure behavior change, despite an unchanged numeric schema. Maintainer acceptance is pending. The evidence below is submitted for that decision; contributor verification does not supply approval.

Please record whether these two behaviors are accepted:

  1. Retain JSON-quoted unfinished assistant output inside the visible, durable timeout report, and replay that report into later model context.
  2. Reject a successor that observes a failed timeout-report write before dispatch, with the error/cleanup/recovery limits below.
Contract topic Proposed behavior and boundary
Owner and canonical record The existing terminal lifecycle owner supplies authority; the existing report transaction commits one canonical custom record containing outcome and captured output. UI/model history are projections.
Alternatives considered Keeping text in memory loses it after cleanup/restart. Injecting a separate assistant row creates a partial/report inter-write window and encounters existing failed-assistant replay filtering. Dispatching while the report is pending permits stale next-turn context.
Retention and deletion The report follows existing transcript/session retention and compaction. There is no independent store or retention policy. Persisted report text can outlive the in-memory buffer.
Ordering and concurrency Matching agent/session admission waits outside the session writer before and after acquiring work admission. Existing authority validation and deduplication remain in force. Already-dispatched queued successors are outside this proof.
Failed write The test injects a rejected report operation before the underlying report write. The observed waiting RPC returns INVALID_REQUEST; no successor provider request starts. This is not a physical disk-failure or interrupted-commit experiment.
Cleanup and recovery The old run's registration is removed on settlement; the rejected successor releases its reservation/lease. Source inspection shows this is a wait on the observed run, not a permanent session lock. A later independent request uses normal admission after cleanup. No automatic report retry, durable recovery queue, restored partial buffer, or successful post-failure retry is claimed or added here.
Crash window A crash before the report commits can lose the in-memory output/outcome. Session status and transcript are not made one atomic transaction. Existing assistant rows are not rewritten.
Storage and latency One report per timed-out run; retained content grows with the JSON-quoted buffer plus a fixed label. Waiting successors incur the observed report-write latency. There is no production storage/latency benchmark or new per-report truncation policy in this PR.
Upgrade and rollback Existing agent DBs use the established schema migration owner. A schema-19 released reader refuses schema 23. Recovery to that release restores the pre-upgrade backup and excludes post-backup writes; same-schema main-parent readers can read/write the reports. No installed-updater or shared-state upgrade claim.

Credit and overlap

Report by @von8794. The original repair built on the unpublished ClawSweeper attempt in run 34187527730, which stopped on validation checkout-identity accounting; run 34190908565 completed planning only. @chelsealong's merged #142135 supplies the deadline-event gate, factual generic failure reporting, CLI write context/drain and UI visibility now present in the base. This PR adds buffered output inside the existing report and successor admission ordering. Neighboring #125977 concerns failed-assistant replay; this candidate does not modify replay-history.

Existing-database evidence appendix

The prior PR body described extracted-reader/in-memory checks. The following evidence supersedes that compatibility claim with real SQLite files and the real versioned accessors, migration owner, and SessionManager. It includes the harness source and recorded phase results so that review does not depend on a private local file link. Raw SQLite artifacts are retained locally; their hashes are provenance, not a claim that the binary files are attached here.

Scope and source identities

These are recorded runs on synthetic existing agent SQLite databases, created and closed by the selected old source before the candidate opens a copy. Each worker loads the version's actual source accessors, migration owner, report writer, and SessionManager in a fresh process with isolated state. No extracted-reader substitutes or in-memory transcript are used.

Role Source Agent schema
Published old source v2026.9.3, commit 1391f7cd2d40ab5bbcf2f5f831d3a64f520e72d7, annotated tag a69d657b4b74556017f2d0ef98b0c64aeabb3643 19
Same-schema previous source Untagged main parent 2d94121bb0ac7a4404e8a81fc00ffd735a89eac5; not a published-release claim 23
Candidate Runs recorded at 98aab05bde7ffa9ff04af9b4062858f37afe0bba plus test repairs; production is identical to 878114675c81e88c78e29d73a76cc0f530a80b8f 23

Runs: 2026-09-25 UTC, macOS arm64, Node 26.5.0. The final three delivery test hashes match the committed head. Materialized source files were compared with their Git blob identities: 11,891 released-source files and 15,121 main-parent files, zero mismatches. External runtime dependencies came from compatible existing installs; this is not validation of an installed release package or its entire dependency supply chain.

Recorded outcomes

  1. Copied released database, upgrade and backup restore. The released writer created two existing histories with six transcript events, including long Unicode/quoted text. The candidate refused unmigrated schema 19 with a Doctor instruction. Its real maintenance lease and migration owner upgraded the copy to schema 23. All six original events retained decoded JSON bytes, IDs, sequence and creation timestamps. Two long messages changed physical encoding from JSON text to zstd; their decoded JSON hashes stayed equal. Candidate requests for empty/partial timeout reports were each repeated twice and produced one report per run (six → eight events).
  2. Released-version rollback boundary. The schema-19 reader refused the schema-23 database and left the existing transcript payloads unchanged. Restoring the pre-upgrade SQLite backup let the released writer append two continuations; the candidate migrated and reopened that restored copy. This is backup restore, not in-place reverse migration. Writes made after the backup, including the two timeout reports, are absent from the restored copy.
  3. Same-schema roundtrip. Main-parent writer creates six events → candidate appends two reports → main-parent reader replays the reports and appends two ordinary messages → candidate reopens ten events. Existing physical payload hashes, decoded JSON hashes, IDs, sequence and creation timestamps match at each boundary.
  4. Actual Gateway connection. The migrated release seed, with its original six events and no timeout reports, was copied into the live Gateway test before startup. That run produced 42 transcript events across six scenarios, and both existing session histories reached the next actual loopback provider request. The main-parent source read the output and added two ordinary continuations; candidate reopened 44 events. Original six seed events and all 42 Gateway-output events retained their physical payload/decoded JSON hashes and identity/order/timestamp fields through this same-schema roundtrip. Each empty/partial session contained one timeout report; both readers replayed seed history, notice, and partial output where applicable.

All 15 recorded SQLite snapshots, including the released seed and the three lanes, reported integrity_check=ok and no foreign-key violations. Hash preservation refers to transcript payloads and the checked identity/order/time fields, not every table, metadata field, page, or byte in a changing SQLite file.

These runs do not exercise the installed CLI updater, shared-state upgrade, service restart, automatic package rollback, physical disk failure, or interrupted migration. The report-operation rejection is covered by the live Gateway test; successful retry or recovery of the lost partial after that failure is not established. Maintainer acceptance of the retained content and successor-failure behavior remains pending.

Phase records

The following tables are generated from the recorded results.json files. Exit 1 is expected only for the two explicit version-refusal phases. Seconds are per phase, not production latency benchmarks.

stable-upgrade-v2: 15 phases, 156.881 seconds
Phase Exit Seconds Expected refusal
release-original-backup 0 0.132 no
candidate-before-migration 1 19.601 yes
candidate-refused-unmigrated 0 0.085 no
candidate-owner-migration 0 14.447 no
candidate-migrated-read 0 18.331 no
candidate-migrated 0 0.096 no
candidate-migrated-timeouts 0 43.180 no
candidate-migrated-after-timeouts 0 0.131 no
release-downgrade-refusal 1 14.786 yes
after-release-refusal 0 0.089 no
release-backup-restore 0 13.351 no
release-restored 0 0.098 no
candidate-restored-migration 0 13.697 no
candidate-restored-reopen 0 18.747 no
candidate-restored-final 0 0.109 no
same-schema-v3: 9 phases, 105.321 seconds
Phase Exit Seconds Expected refusal
base-seed 0 25.067 no
base-original 0 0.094 no
candidate-existing-read 0 18.936 no
candidate-timeouts 0 33.738 no
candidate-after-timeouts 0 0.103 no
base-reader-writer 0 13.112 no
base-after-continuation 0 0.097 no
candidate-reopen 0 14.081 no
candidate-reopened 0 0.093 no
gateway-roundtrip-delivery: 5 phases, 35.974 seconds
Phase Exit Seconds Expected refusal
gateway-output 0 0.092 no
gateway-base-read-write 0 18.260 no
gateway-after-base 0 0.078 no
gateway-candidate-reopen 0 17.457 no
gateway-final 0 0.087 no

Binary artifact identities

These hashes identify the retained local artifacts; the binary database files are not attached to this PR text. The executable harness below makes the asserted path and comparisons inspectable.

Artifact SHA-256
Released seed (schema 19) cac8bb0ef968023177a94deaaa15a9982865ca5279445626b4b7afb4b2caffd2
Migrated seed (schema 23) e9954ecd4ea43084a79655c9ef30a569f6ff321f0c3117474aefb300f699ab5e
Final Gateway export (42 events) 57516dac067c82fbdc3be39d659e1e0fc15830d47be563d15c5931743146560b
Roundtrip output (44 events) 79235c1fccaa021673a80674fe2b2977616d59a3ef3fb3d4db9ece1ad01f7ba5

Reproduction setup

Save the three source blocks below together in a proof directory outside the source checkouts. Prepare separate complete checkouts at the three listed commits with compatible dependencies; candidateRoot should be current head. The scripts load source entrypoints through each checkout's own scripts/tsx.mjs. Use Node 26.5.0. Paths in this example are placeholders to replace with absolute paths on the review host.

{
  "node": "/absolute/path/to/node",
  "candidateRoot": "/absolute/path/to/candidate",
  "baseRoot": "/absolute/path/to/main-parent",
  "releaseRoot": "/absolute/path/to/release-2026.9.3",
  "runName": "fresh-review-run"
}

For the standalone same-schema and released-upgrade lanes, save that configuration as config.json and run node run.mjs config.json all. This creates old state, backups, phase logs, snapshots and results under runs/<runName>. Use a fresh runName for every execution; the harness is not intended to append to a completed fixture.

To connect a released seed to the Gateway as in the recorded delivery:

  1. Create a seed configuration using a fresh run name and baseRoot equal to the released checkout; run node run.mjs seed.json gateway-seed. It creates runs/<seedRun>/gateway-input.sqlite and gateway-seed.json.
  2. Create an upgrade configuration with another fresh run name, set releaseSeedDatabase and releaseSeedSnapshot to those absolute paths, and set gatewayMigratedSeedOutput to a new absolute output path. Run node run.mjs upgrade.json stable-upgrade. The migrated output is captured before timeout reports; its manifest is runs/<upgradeRun>/candidate-migrated.json.
  3. In the candidate checkout, run the live test with OPENCLAW_VITEST_MAX_WORKERS=1, OPENCLAW_TIMEOUT_HISTORY_PROOF_DATABASE set to that migrated output, and OPENCLAW_TIMEOUT_HISTORY_PROOF_DATABASE_OUTPUT set to a new absolute export path: node scripts/run-vitest.mjs src/gateway/server-methods/chat.timeout-history-live-proof.test.ts.
  4. Create a roundtrip configuration with a fresh run name and the main-parent checkout as baseRoot. Set gatewayOutput to the export from step 3 and gatewaySeedSnapshot to the manifest from step 2. Run node run.mjs roundtrip.json gateway-roundtrip.

The wrappers retain per-phase stdout/stderr, exit status, timing, SQLite manifests and results. Session activity is current to avoid replacing the seed through idle reset; historical message timestamps and payload bytes remain fixed and are checked. Seed state is synthetic; no existing user database or credentials are required.

Harness source used for the recorded runs

run.mjs — SHA-256 c4a1951fc654dcb25583443096891ea00debc243e4ec44272f04a457c26652f7
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";

const proofRoot = path.dirname(fileURLToPath(import.meta.url));
const [configPath, selection = "all"] = process.argv.slice(2);
assert(configPath, "Usage: node run.mjs config.json [all|same-schema|stable-upgrade|gateway-seed]");
const config = JSON.parse(await fs.readFile(configPath, "utf8"));
const evidenceRoot = path.join(proofRoot, "runs", config.runName);
await fs.mkdir(evidenceRoot, { recursive: true });
const evidence = { startedAt: new Date().toISOString(), config, selection, phases: [], checks: [] };
const save = () => fs.writeFile(path.join(evidenceRoot, "results.json"), JSON.stringify(evidence, null, 2) + "\n");

async function command(label, args, sourceRoot, stateDir, expectedFailure = false) {
  const homeDir = path.join(stateDir, "isolated-home");
  const tmpDir = path.join(stateDir, "tmp");
  await fs.mkdir(homeDir, { recursive: true });
  await fs.mkdir(tmpDir, { recursive: true });
  await fs.writeFile(path.join(stateDir, "openclaw.json"), '{"plugins":{"enabled":false}}\n');
  const started = performance.now();
  const child = spawn(config.node, args, {
    cwd: sourceRoot,
    env: {
      PATH: `${path.dirname(config.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,
      HOME: homeDir,
      TMPDIR: tmpDir,
      OPENCLAW_STATE_DIR: stateDir,
      OPENCLAW_CONFIG_PATH: path.join(stateDir, "openclaw.json"),
      OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
      OPENCLAW_SKIP_PROVIDERS: "1",
      OPENCLAW_SUPERVISOR_MODE: "external",
      NO_COLOR: "1",
    },
    stdio: ["ignore", "pipe", "pipe"],
  });
  let stdout = "";
  let stderr = "";
  child.stdout.on("data", (data) => { stdout += data; });
  child.stderr.on("data", (data) => { stderr += data; });
  const timer = setTimeout(() => child.kill("SIGTERM"), 120_000);
  const code = await new Promise((resolve, reject) => {
    child.once("error", reject);
    child.once("close", resolve);
  }).finally(() => clearTimeout(timer));
  await fs.writeFile(path.join(evidenceRoot, `${label}.stdout.log`), stdout);
  await fs.writeFile(path.join(evidenceRoot, `${label}.stderr.log`), stderr);
  const marker = stdout.split("\n").find((line) => line.startsWith("DATABASE_COMPATIBILITY_RESULT "));
  const result = marker ? JSON.parse(marker.slice("DATABASE_COMPATIBILITY_RESULT ".length)) : undefined;
  evidence.phases.push({ label, code, seconds: (performance.now() - started) / 1000, expectedFailure, result });
  await save();
  assert.equal(code === 0, !expectedFailure, `${label}: exit=${code}; ${JSON.stringify(result?.error)}; ${stderr.slice(-3000)}`);
  if (marker) assert.equal(result.ok, !expectedFailure, `${label}: ${JSON.stringify(result.error)}`);
  console.log(`${label}: ${expectedFailure ? "expected refusal" : "passed"}`);
  return result ?? JSON.parse(stdout);
}

async function worker(label, source, mode, stateDir, storePath, expectedFailure = false) {
  return command(label, [
    "--import", path.join(source, "scripts", "tsx.mjs"),
    path.join(proofRoot, "worker.mjs"), source, mode, stateDir, storePath,
  ], source, stateDir, expectedFailure);
}
async function snapshot(label, stateDir, storePath, backupPath) {
  const result = await command(label, [path.join(proofRoot, "snapshot.mjs"), storePath, ...(backupPath ? [backupPath] : [])], proofRoot, stateDir);
  await fs.writeFile(path.join(evidenceRoot, `${label}.json`), JSON.stringify(result, null, 2) + "\n");
  assert.deepEqual(result.integrity, [{ integrity_check: "ok" }], `${label} integrity`);
  assert.deepEqual(result.foreignKeyViolations, [], `${label} foreign keys`);
  return result;
}
function preserve(before, after, physical) {
  for (const row of before.rows) {
    const found = after.rows.find((entry) => entry.sessionId === row.sessionId && entry.seq === row.seq);
    assert(found, `Missing original event ${row.sessionId}/${row.seq}`);
    assert.equal(found.eventId, row.eventId);
    assert.equal(found.jsonSha256, row.jsonSha256, `Original JSON bytes changed for ${row.eventId}`);
    assert.equal(found.createdAt, row.createdAt);
    if (physical) assert.equal(found.physicalSha256, row.physicalSha256, `Physical payload changed for ${row.eventId}`);
  }
}
function replay(result, timeouts, continuation = false) {
  for (const row of result.rows) {
    assert.equal(row.seedPresent, true);
    assert.equal(row.replayContainsSeed, true);
    assert.equal(row.reportCount, timeouts ? 1 : 0);
    assert.equal(row.replayContainsTimeout, timeouts);
    assert.equal(row.replayContainsPartial, timeouts && row.scenario === "partial-timeout");
    assert.equal(row.replayContainsOldContinuation, continuation);
  }
}

try {
  if (selection === "gateway-seed") {
    const stateDir = path.join(evidenceRoot, "gateway-seed-state");
    const storePath = path.join(stateDir, "agents", "main", "agent", "openclaw-agent.sqlite");
    await fs.mkdir(path.dirname(storePath), { recursive: true });
    replay(await worker("gateway-seed-old-writer", config.baseRoot, "seed", stateDir, storePath), false);
    const backupPath = path.join(evidenceRoot, "gateway-input.sqlite");
    await snapshot("gateway-seed", stateDir, storePath, backupPath);
    evidence.gatewayInput = backupPath;
  }
  if (selection === "gateway-roundtrip") {
    assert(config.gatewayOutput, "gatewayOutput must name the consolidated DB from the real Gateway proof");
    const lane = path.join(evidenceRoot, "gateway-roundtrip");
    const oldState = path.join(lane, "base-state");
    const newState = path.join(lane, "candidate-state");
    const storePath = path.join(lane, "gateway-output.sqlite");
    await fs.mkdir(lane, { recursive: true });
    await fs.copyFile(config.gatewayOutput, storePath);
    const original = await snapshot("gateway-output", oldState, storePath);
    if (config.gatewaySeedSnapshot) {
      const seed = JSON.parse(await fs.readFile(config.gatewaySeedSnapshot, "utf8"));
      preserve(seed, original, seed.userVersion === original.userVersion);
    }
    replay(await worker("gateway-base-read-write", config.baseRoot, "old-append-gateway", oldState, storePath), true, true);
    const older = await snapshot("gateway-after-base", oldState, storePath);
    preserve(original, older, true);
    replay(await worker("gateway-candidate-reopen", config.candidateRoot, "read-gateway", newState, storePath), true, true);
    const reopened = await snapshot("gateway-final", newState, storePath);
    preserve(older, reopened, true);
    evidence.checks.push("real Gateway output -> old source reader/writer -> candidate source reopen; original transcript bytes and timeout reports preserved");
  }
  if (selection === "all" || selection === "same-schema") {
    const lane = path.join(evidenceRoot, "same-schema");
    const oldState = path.join(lane, "old-state");
    const newState = path.join(lane, "candidate-state");
    const storePath = path.join(lane, "session.sqlite");
    await fs.mkdir(lane, { recursive: true });
    replay(await worker("base-seed", config.baseRoot, "seed", oldState, storePath), false);
    const original = await snapshot("base-original", oldState, storePath);
    replay(await worker("candidate-existing-read", config.candidateRoot, "read", newState, storePath), false);
    replay(await worker("candidate-timeouts", config.candidateRoot, "write-timeouts", newState, storePath), true);
    const appended = await snapshot("candidate-after-timeouts", newState, storePath);
    assert.equal(appended.userVersion, original.userVersion);
    preserve(original, appended, true);
    replay(await worker("base-reader-writer", config.baseRoot, "old-append", oldState, storePath), true, true);
    const older = await snapshot("base-after-continuation", oldState, storePath);
    preserve(appended, older, true);
    replay(await worker("candidate-reopen", config.candidateRoot, "read", newState, storePath), true, true);
    const reopened = await snapshot("candidate-reopened", newState, storePath);
    preserve(older, reopened, true);
    evidence.checks.push("same-schema old writer -> candidate write -> old read/write -> candidate reopen; exact original bytes and both timeout reports preserved");
    await save();
  }
  if (selection === "all" || selection === "stable-upgrade") {
    const lane = path.join(evidenceRoot, "stable-upgrade");
    const oldState = path.join(lane, "release-state");
    const newState = path.join(lane, "candidate-state");
    const storePath = path.join(lane, "session.sqlite");
    const backupPath = path.join(lane, "before-upgrade.sqlite");
    await fs.mkdir(lane, { recursive: true });
    if (config.releaseSeedDatabase) {
      await fs.copyFile(config.releaseSeedDatabase, storePath);
    } else {
      replay(await worker("release-seed", config.releaseRoot, "seed", oldState, storePath), false);
    }
    const original = await snapshot("release-original-backup", oldState, storePath, backupPath);
    if (config.releaseSeedSnapshot) {
      preserve(JSON.parse(await fs.readFile(config.releaseSeedSnapshot, "utf8")), original, true);
    }
    const needsMigration = await worker("candidate-before-migration", config.candidateRoot, "read", newState, storePath, true);
    assert.match(needsMigration.error.message, /doctor --fix/);
    const beforeMigration = await snapshot("candidate-refused-unmigrated", newState, storePath);
    assert.equal(beforeMigration.userVersion, original.userVersion);
    preserve(original, beforeMigration, true);
    await worker("candidate-owner-migration", config.candidateRoot, "migrate", newState, storePath);
    replay(await worker("candidate-migrated-read", config.candidateRoot, "read", newState, storePath), false);
    const migrated = await snapshot("candidate-migrated", newState, storePath, config.gatewayMigratedSeedOutput);
    assert(migrated.userVersion > original.userVersion);
    preserve(original, migrated, false);
    replay(await worker("candidate-migrated-timeouts", config.candidateRoot, "write-timeouts", newState, storePath), true);
    const afterTimeout = await snapshot("candidate-migrated-after-timeouts", newState, storePath);
    preserve(original, afterTimeout, false);
    const refused = await worker("release-downgrade-refusal", config.releaseRoot, "read", oldState, storePath, true);
    assert.match(refused.error.message, /newer schema version/i);
    const afterRefusal = await snapshot("after-release-refusal", newState, storePath);
    preserve(afterTimeout, afterRefusal, true);
    const restoredPath = path.join(lane, "restored-session.sqlite");
    await fs.copyFile(backupPath, restoredPath);
    replay(await worker("release-backup-restore", config.releaseRoot, "old-append", oldState, restoredPath), false, true);
    const restored = await snapshot("release-restored", oldState, restoredPath);
    preserve(original, restored, true);
    await worker("candidate-restored-migration", config.candidateRoot, "migrate", newState, restoredPath);
    replay(await worker("candidate-restored-reopen", config.candidateRoot, "read", newState, restoredPath), false, true);
    const reopened = await snapshot("candidate-restored-final", newState, restoredPath);
    preserve(restored, reopened, false);
    evidence.checks.push("v2026.9.3 agent DB upgrade -> timeout write -> old reader refusal -> pre-upgrade backup restore -> candidate re-upgrade/reopen; original JSON bytes preserved");
  }
  evidence.completedAt = new Date().toISOString();
  evidence.ok = true;
  await save();
  console.log(`Evidence: ${path.join(evidenceRoot, "results.json")}`);
} catch (error) {
  evidence.ok = false;
  evidence.failure = { message: String(error?.message ?? error), stack: error?.stack };
  await save();
  throw error;
}
worker.mjs — SHA-256 c98ef5188be7b8450c2cbc4023679a29459d2088ba4ba2f9409bcded840cc0fd
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";

// Every invocation is a separate process loading a complete source revision.
// There are no extracted readers, in-memory databases, or replacement owners.
const [sourceRoot, mode, stateDir, storePath] = process.argv.slice(2);
assert(sourceRoot && mode && stateDir && storePath, "sourceRoot mode stateDir storePath required");
const fromSource = (name) => import(pathToFileURL(path.join(sourceRoot, name)).href);
const scenarios = ["empty-timeout", "partial-timeout"];
const NOTICE = "This turn timed out and may have performed work before it stopped.";
const PARTIAL = "DATABASE_COMPATIBILITY_PARTIAL_OUTPUT\nUnfinished history: 漢字🙂";
const seedMarker = (scenario) => `DATABASE_COMPATIBILITY_ORIGINAL_${scenario}`;
const targetFor = (scenario) => ({
  agentId: "main",
  sessionId: `database-compatibility-${scenario}`,
  sessionKey: `agent:main:timeout-proof-${scenario}`,
  storePath,
  env: { ...process.env, OPENCLAW_STATE_DIR: stateDir },
});
const digest = (value) => createHash("sha256").update(value).digest("hex");

await fs.mkdir(stateDir, { recursive: true });
const agentDatabase = await fromSource("src/state/openclaw-agent-db.ts");
const stateDatabase = await fromSource("src/state/openclaw-state-db.ts");
let outcome;
let failure;
try {
  if (mode === "migrate") {
    // This is Doctor's maintenance owner and its real lease/integrity scope.
    // It is deliberately reported as agent-store proof, not a full CLI update.
    await agentDatabase.withAgentDatabaseMaintenanceLease(
      { env: process.env },
      (maintenance) => agentDatabase.migrateOpenClawAgentDatabaseForMaintenance(
        { agentId: "main", pathname: storePath }, maintenance,
      ),
    );
    outcome = { mode, migrated: true };
  } else {
    const accessor = await fromSource("src/config/sessions/session-accessor.ts");
    if (mode === "seed") {
      const activeAt = Date.now();
      for (const [index, scenario] of scenarios.entries()) {
        const target = targetFor(scenario);
        await accessor.upsertSessionEntryCore(target, {
          sessionId: target.sessionId,
          // Keep this existing session inside the Gateway's current idle window.
          // Historical message timestamps remain old and are checked byte for byte.
          updatedAt: activeAt + index,
        });
        await accessor.appendTranscriptMessage(target, {
          cwd: stateDir,
          eventId: `database-compatibility-original-user-${scenario}`,
          now: 1_788_800_000_010 + index,
          message: {
            role: "user",
            content: `${seedMarker(scenario)}\n${"Keep exact history bytes: 汉字🙂 \"quoted\"\n".repeat(48)}`,
            timestamp: 1_788_800_000_010 + index,
          },
        });
        await accessor.appendTranscriptMessage(target, {
          cwd: stateDir,
          eventId: `database-compatibility-original-assistant-${scenario}`,
          now: 1_788_800_000_020 + index,
          message: {
            role: "assistant",
            content: [{ type: "text", text: `ORIGINAL_COMPLETED_REPLY_${scenario}` }],
            api: "openai-responses",
            provider: "database-compatibility",
            model: "synthetic",
            stopReason: "stop",
            timestamp: 1_788_800_000_020 + index,
            usage: {
              input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2,
              cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
            },
          },
        });
      }
    }
    if (mode === "write-timeouts") {
      const { recordGatewaySessionRunFailure } = await fromSource("src/sessions/session-run-error.ts");
      for (const scenario of scenarios) {
        const params = {
          target: targetFor(scenario),
          runId: `database-compatibility-${scenario}`,
          error: "timeout",
          status: "timeout",
          ...(scenario === "partial-timeout" ? { timeoutPartialText: PARTIAL } : {}),
        };
        await recordGatewaySessionRunFailure(params);
        await recordGatewaySessionRunFailure(params);
      }
    }
    if (mode === "old-append" || mode === "old-append-gateway") {
      for (const scenario of scenarios) {
        await accessor.appendTranscriptMessage(targetFor(scenario), {
          cwd: stateDir,
          eventId: `database-compatibility-old-continuation-${scenario}`,
          now: 1_788_800_000_030,
          message: {
            role: "user",
            content: `OLDER_WRITER_CONTINUATION_${scenario}`,
            timestamp: 1_788_800_000_030,
          },
        });
      }
    }
    const { SessionManager } = await fromSource("src/agents/sessions/session-manager.ts");
    const rows = [];
    for (const scenario of scenarios) {
      const target = targetFor(scenario);
      const events = await accessor.loadTranscriptEvents(target);
      const messages = SessionManager.open(target, stateDir).buildSessionContext().messages;
      const reports = events.filter((event) => event.customType === "run-failed-before-reply");
      const replay = JSON.stringify(messages);
      rows.push({
        scenario,
        sessionKey: target.sessionKey,
        sessionId: target.sessionId,
        eventCount: events.length,
        seedPresent: JSON.stringify(events).includes(seedMarker(scenario)),
        reportCount: reports.length,
        reports,
        replaySha256: digest(replay),
        replayContainsSeed: replay.includes(seedMarker(scenario)),
        replayContainsTimeout: replay.includes(NOTICE),
        replayContainsPartial: replay.includes(
          mode.endsWith("gateway") ? "TIMEOUT_PROOF_PARTIAL_OUTPUT" : "DATABASE_COMPATIBILITY_PARTIAL_OUTPUT",
        ),
        replayContainsOldContinuation: replay.includes(`OLDER_WRITER_CONTINUATION_${scenario}`),
      });
    }
    outcome = { mode, rows };
  }
} catch (error) {
  failure = { name: error?.name, message: String(error?.message ?? error), stack: error?.stack };
} finally {
  // Close the real owners before the coordinator reads or copies their SQLite files.
  try {
    await agentDatabase.closeOpenClawAgentDatabasesAsync();
    if (typeof stateDatabase.closeOpenClawStateDatabaseAsync === "function") {
      await stateDatabase.closeOpenClawStateDatabaseAsync();
    } else {
      // The published 2026.9.3 owner predates the asynchronous state close API.
      stateDatabase.closeOpenClawStateDatabase();
    }
  } catch (error) {
    failure ??= { name: error?.name, message: String(error?.message ?? error), stack: error?.stack };
  }
}
const result = {
  sourceRoot,
  version: JSON.parse(await fs.readFile(path.join(sourceRoot, "package.json"), "utf8")).version,
  node: process.version,
  mode,
  storePath,
  ...(failure ? { ok: false, error: failure } : { ok: true, ...outcome }),
};
console.log(`DATABASE_COMPATIBILITY_RESULT ${JSON.stringify(result)}`);
if (failure) process.exitCode = 1;
snapshot.mjs — SHA-256 ba5ab3a2daecb64404a55ca2663af2c93d8854c6b83d891c6fd7c9662f97c5bf
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { DatabaseSync, backup } from "node:sqlite";
import { zstdDecompressSync } from "node:zlib";

const [storePath, backupPath] = process.argv.slice(2);
assert(storePath, "storePath required");
const database = new DatabaseSync(storePath, { readOnly: true });
try {
  if (backupPath) await backup(database, backupPath);
  const columns = new Set(database.prepare("PRAGMA table_info(transcript_events)").all().map((row) => row.name));
  const hash = (value) => createHash("sha256").update(value).digest("hex");
  const rows = database.prepare("SELECT * FROM transcript_events ORDER BY session_id, seq").all().map((row) => {
    const physical = row.event_json === null ? row.event_zstd : Buffer.from(row.event_json, "utf8");
    const original = row.event_json === null ? zstdDecompressSync(row.event_zstd) : physical;
    const event = JSON.parse(original.toString("utf8"));
    return {
      sessionId: row.session_id,
      seq: row.seq,
      eventId: event.id,
      type: event.type,
      customType: event.customType,
      createdAt: row.created_at,
      encoding: row.event_json === null ? "zstd" : "json-text",
      jsonBytes: original.length,
      jsonSha256: hash(original),
      physicalSha256: hash(physical),
      partial: original.includes(Buffer.from("DATABASE_COMPATIBILITY_PARTIAL_OUTPUT")),
    };
  });
  console.log(JSON.stringify({
    storePath,
    backupPath,
    userVersion: database.prepare("PRAGMA user_version").get().user_version,
    schemaMeta: database.prepare("SELECT role, agent_id, schema_version, app_version FROM schema_meta").all(),
    integrity: database.prepare("PRAGMA integrity_check").all(),
    foreignKeyViolations: database.prepare("PRAGMA foreign_key_check").all(),
    hasCompressedPayloadColumns: columns.has("event_zstd"),
    rows,
  }, null, 2));
} finally {
  database.close();
}

@clawsweeper

clawsweeper Bot commented Sep 8, 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 gateway Gateway runtime agents Agent runtime and tooling size: L labels Sep 8, 2026
@destire-mio
destire-mio force-pushed the fix/141839-timeout-history branch from 7c86f83 to 8142928 Compare September 8, 2026 14:38
@destire-mio
destire-mio marked this pull request as ready for review September 8, 2026 14:38
@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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 8, 2026
@clawsweeper

clawsweeper Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

The PR retains bounded, redacted unfinished assistant output in timeout reports and waits for those reports before admitting subsequent turns.

Example: A turn streams "I updated config.json. Validation is unfinished." before its Gateway deadline expires.

  • Before: The next provider request can receive a timeout notice without the buffered output.
  • After: The next request receives the timeout notice and quoted unfinished output after persistence completes.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused implementation and real transport evidence are useful; readiness remains capped by the unresolved storage contract, and current CI failures could not be attributed from available annotations.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Recorded production Gateway RPC and real loopback HTTP captures exercise deadline cancellation, SQLite persistence, history replay, and successor requests; useful partial output survives while credentials are masked, and injected report rejection produces no successor provider I/O.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: After a deadline ends a turn, later conversation context can omit unfinished output describing work already attempted.
Reason: The user value is clear, but durable unfinished-text visibility and failed-save refusal need the storage acceptance required by repository policy.

Merge readiness

⛔ Blocked before merge - 1 item remains

This PR addresses a remaining timeout-history gap with useful production-boundary evidence; acceptance of its durable-output and failed-save behavior still requires a storage-owner decision.

Priority: P2
Reviewed head: 133ef0a5bfe8af1387c2bfa9d692441c28d9e981
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should bounded, redacted unfinished output be retained and replayed in timeout reports, with an observing successor refused when that report cannot be saved?
  • Recommendation: Accept the proposed contract: Record acceptance of the bounded report content, persistence ordering, and refusal of an observing successor after a failed save.
  • Why: These behaviors change visible durable content and successor failure semantics, and the available discussion expressly leaves storage-owner acceptance pending.

Before merge

  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

None.

Agent review details

How this fits together

Gateway deadline cancellation captures streamed output, the lifecycle owner persists its terminal report in SQLite, and history readers supply that report to clients and subsequent provider requests.

flowchart TD
  A[Provider stream] --> B[Gateway output buffer]
  B --> C[Deadline cancellation]
  C --> D[Lifecycle persistence owner]
  D --> E[SQLite transcript report]
  D --> F[Successor admission wait]
  E --> G[History and provider context]
  F --> G
Loading

Technical review

Best possible solution:

Retain unfinished output through the existing terminal report owner under an explicitly accepted storage and failed-save contract.

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

Current-main source shows that buffered timeout output is not passed into the durable report, and the supplied Gateway captures demonstrate the affected replay and admission paths; no target code was executed during this review.

Is this the best way to solve the issue?

Using one existing custom report and its persistence owner is a focused solution that preserves current transcript readers, deduplication, and authority checks.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 80347a9 adds src/sessions/session-run-error.ts:42 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 80347a9bb5eb; files: src/sessions/session-run-error.ts)
  • Advait Paliwal: Raw commit 14fb2c0 adds src/gateway/chat-abort.ts:95 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 14fb2c05b133; files: src/gateway/chat-abort.ts)

PR surface

Source +97, Tests +1116, Docs +12. Total +1225 across 24 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 14 119 22 +97
Tests 8 1147 31 +1116
Docs 2 13 1 +12
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 24 1279 54 +1225

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Deadline-ended turns can lose useful unfinished context, but the defect is limited to timeout persistence and successor admission.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • 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 (18 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-30T07:48:07.381Z sha 7952a82 :: blocked before merge. :: [P1] Redact buffered text before persisting the timeout report
  • reviewed 2026-10-03T16:38:05.975Z sha 7717a5c :: blocked before merge. :: [P2] Await owned completion instead of short real-time polls
  • reviewed 2026-10-03T17:00:10.324Z sha 9a06954 :: blocked before merge. :: none
  • reviewed 2026-10-09T17:25:44.005Z sha 5d94f2f :: blocked before merge. :: none
  • reviewed 2026-10-09T18:12:59.223Z sha a45a886 :: blocked before merge. :: none
  • reviewed 2026-10-13T16:29:47.773Z sha 5a50e71 :: blocked before merge. :: none
  • reviewed 2026-10-13T17:56:56.809Z sha 78568f2 :: blocked before merge. :: none
  • reviewed 2026-10-13T18:21:09.581Z sha 24c5784 :: blocked before merge. :: none

Reviewed October 13, 2026, 3:05 PM ET / 19:05 UTC (Revision 19).

@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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 8, 2026
@destire-mio
destire-mio force-pushed the fix/141839-timeout-history branch from 8142928 to 67ff6dc Compare September 9, 2026 04:16
@destire-mio destire-mio changed the title fix: preserve timeout outcomes and partial output in the next agent turn fix: preserve unfinished output when an agent turn times out Sep 9, 2026
Merge main at 2d94121. Capture unfinished timeout output on the run owner before cancellation, preserve terminal persistence authority, and retain successor admission waits outside the session writer.

Validation: formatting and non-type-aware lint passed for the 12 PR files. Full typecheck, build, and runtime regression tests were not run in this sparse checkout.
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed 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 25, 2026
@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 26, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 5, 2026
… the worktree reader (openclaw#164685)

* perf(state): carry admitted schema facts with database handles

Refresh freshness at read admission and after BEGIN while reusing
handle-owned facts for runtime schema checks. Validate canonical
triggers before exposing agent readers and classify shared-state
failures only after failed admission.

Focused runtime checks execute zero SQL statements, versus 30 with
the baseline owner. Preserve foreign-commit and snapshot semantics.
Full workload measurement and remote integration checks remain merge
preconditions after remote runner and fleet-capacity admission failed.

* perf(agents): run per-turn session-entry patches through the worker

Route audited writer claims, live-model-switch bookkeeping, and pending-final
preparation, settlement, and cleanup through the existing agent executor.
Preserve native opaque SDK callbacks and the excluded lifecycle and cron paths.

The paired isolated Gateway workload reduces native patch transactions from
8 to 2 per warmed turn and target-site SQL from 48 to 12. Overall main-thread
SQL averages 648.5 to 493.4 statements per warmed turn. Lifecycle persistence
remains follow-up work after openclaw#142236; cron preparation remains with openclaw#161105.

Local caller, settlement, error identity, import-boundary, cycle, and database
ratchet proof passes. Full build, changed checks, and released SDK diff remain
explicit merge preconditions under the maintainer's validation instruction.

* test(outbound): align recovery fixtures with queue state

Create and read producer-recovery sessions under the same explicit shared-state root as their delivery queue. Worker-backed pending-final settlement correctly rejects the previous fixture ownership mismatch. Preserve durable payloads and all existing assertions.

* fix(state): preserve worker handoffs during schema admission

Use the existing worker generation claim for maintenance metadata instead of
retaining a host read handle. Keep both live ownership checks around the
required transaction-entry freshness probe.

Consolidate shared-state cache initialization, refresh, and terminal failures
in its admission sibling and update the compiled-wrapper inventory. This
keeps the cache within the existing module-size limit without changing stored
schema or quarantine semantics.

Focused maintenance, ownership, schema, worker, wrapper, and quarantine proof
passed. Independent Codex review is clean through P2. Full landing validation
remains required before merge.

* test(agents): extract accounting persistence fixture

Keep the accounting persistence suite within its line cap by moving fixture construction into a dedicated test-support module. Preserve suite-owned state, immediate operation registration, and every test case and assertion.

* fix(state): keep retained handles free of schema probes

Refresh canonical readiness when it consumes schema facts. Retention only
holds native lifetime, so cold restore and other worker handoffs no longer
execute host SQLite before dispatch.

Protect foreign schema invalidation at the warm readiness fast path. Tighten
retained-reader budgets to the optimized counts, and require early missing-table
diagnosis before callbacks while preserving handle-cleanup assertions.

Validation: 93 focused tests, production types, state/config test types, and
independent review clean through P2.

* perf(agents): read worktree publication lookups in worker

Move publication preparation and per-turn tool availability through the existing worktree reader. Capture the physical store and session lifecycle before yielding, refresh availability facts, and preserve live effect guards and branch identity semantics.

* test(gateway): document publication reader mock isolation

Keep the SQL boundary fixture isolated from session storage, managed-worktree services, configuration, and credential state. Document those boundaries for the new first-party mock-export check.

No executable test code, assertions, timeouts, or production behavior changes. The mock-export check, formatter, reader tests, and scoped P2 review pass.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 5, 2026
…tory reader (openclaw#164747)

* perf(state): carry admitted schema facts with database handles

Refresh freshness at read admission and after BEGIN while reusing
handle-owned facts for runtime schema checks. Validate canonical
triggers before exposing agent readers and classify shared-state
failures only after failed admission.

Focused runtime checks execute zero SQL statements, versus 30 with
the baseline owner. Preserve foreign-commit and snapshot semantics.
Full workload measurement and remote integration checks remain merge
preconditions after remote runner and fleet-capacity admission failed.

* perf(agents): run per-turn session-entry patches through the worker

Route audited writer claims, live-model-switch bookkeeping, and pending-final
preparation, settlement, and cleanup through the existing agent executor.
Preserve native opaque SDK callbacks and the excluded lifecycle and cron paths.

The paired isolated Gateway workload reduces native patch transactions from
8 to 2 per warmed turn and target-site SQL from 48 to 12. Overall main-thread
SQL averages 648.5 to 493.4 statements per warmed turn. Lifecycle persistence
remains follow-up work after openclaw#142236; cron preparation remains with openclaw#161105.

Local caller, settlement, error identity, import-boundary, cycle, and database
ratchet proof passes. Full build, changed checks, and released SDK diff remain
explicit merge preconditions under the maintainer's validation instruction.

* test(outbound): align recovery fixtures with queue state

Create and read producer-recovery sessions under the same explicit shared-state root as their delivery queue. Worker-backed pending-final settlement correctly rejects the previous fixture ownership mismatch. Preserve durable payloads and all existing assertions.

* fix(state): preserve worker handoffs during schema admission

Use the existing worker generation claim for maintenance metadata instead of
retaining a host read handle. Keep both live ownership checks around the
required transaction-entry freshness probe.

Consolidate shared-state cache initialization, refresh, and terminal failures
in its admission sibling and update the compiled-wrapper inventory. This
keeps the cache within the existing module-size limit without changing stored
schema or quarantine semantics.

Focused maintenance, ownership, schema, worker, wrapper, and quarantine proof
passed. Independent Codex review is clean through P2. Full landing validation
remains required before merge.

* test(agents): extract accounting persistence fixture

Keep the accounting persistence suite within its line cap by moving fixture construction into a dedicated test-support module. Preserve suite-owned state, immediate operation registration, and every test case and assertion.

* fix(state): keep retained handles free of schema probes

Refresh canonical readiness when it consumes schema facts. Retention only
holds native lifetime, so cold restore and other worker handoffs no longer
execute host SQLite before dispatch.

Protect foreign schema invalidation at the warm readiness fast path. Tighten
retained-reader budgets to the optimized counts, and require early missing-table
diagnosis before callbacks while preserving handle-cleanup assertions.

Validation: 93 focused tests, production types, state/config test types, and
independent review clean through P2.

* perf(sessions): read transcript anchors and readiness through the history reader

* refactor(sessions): group history read request types
Preserve upstream session-worker and report-append changes while retaining
bounded, redacted timeout output and required persistence ordering.
Recognize the exact admitted writer before lifecycle-start publication.

Validation: 257 focused tests across 9 files; type-aware lint, formatting,
and scoped safety ratchets passed. Full core typecheck was limited by
local memory (exit 137). Independent review found no P0-P2 issues.
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed 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 Oct 9, 2026
Remove the retired per-agent default marker while preserving explicit
main-agent selection and all foreign-timeout isolation assertions.

Validation: Gateway-methods test typecheck, all 17 binding cases,
type-aware lint, formatting, and independent review passed.
@clawsweeper clawsweeper Bot added the status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. label Oct 9, 2026
Merge upstream main 32c8391 while retaining prompt-reaction and terminal-write ownership changes.
Use the retained diagnostic redaction owner for bounded timeout output, and wait for exact registration removal in session-binding test cleanup.

Validation: 46 lifecycle, 23 binding, and 47 CLI-history tests passed; core typecheck, scoped type-aware lint, and formatting passed.
@clawsweeper clawsweeper Bot removed merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Oct 13, 2026
Merge upstream main 050881c while preserving storage failure copy, unconditional terminal receipts, and async authorization cleanup.
Adapt timeout regression fixtures to the runtime configuration owner.

Validation: 124 focused tests passed in 292.69s; core typecheck, scoped type-aware lint, formatting, and independent source review passed.
@clawsweeper clawsweeper Bot removed the status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. label Oct 13, 2026
destire-mio and others added 4 commits October 14, 2026 02:10
Later terminal events can replace the tracked promise while the lifecycle owner queues their writes. Assert the retained dependency without assuming promise identity; keep the real RPC ordering, failed-save rejection, no-dispatch, and provider replay checks.

Reproduced the original CI assertion locally, then passed all six real-Gateway scenarios (44.16s wrapper). Scoped lint, formatting, and independent review passed.
The separate Gateway RPC timeout did not reproduce in the same two-file group: 43 tests passed with two workers and unchanged timeouts (189.78s). Its original CI cause remains unknown.
Reuse the canonical writer absence fact before opening a transaction. Keep matching writes, invalidation and rollback semantics unchanged; empty warmed matches save one transaction without delaying any durable effect.

Two Codex review rounds clean. Memory tests and static CI lanes passed; wrapper inventory failures reproduce identically on main 0ccaa45. Single post-merge harness pair follows.
Merge upstream main e52278f. Keep both persistence waits outside the session writer and preserve the new admission diagnostic scope and restart-recovery custody changes.
Group the core session target fields without changing their read order to retain the existing file line limit.

Validation: 125 focused tests passed (325.88s); final admission and real-Gateway proof rerun passed 24 tests (143.15s). Core typecheck, scoped lint, formatting, and independent source review passed.
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation extensions: memory-core Extension: memory-core labels Oct 13, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale after 7 days without qualifying human activity.
Without new human activity, Barnacle may close it as not planned 7 days after this message was posted. This is administrative inactivity cleanup, not a claim that the problem is fixed.
A human update restarts the inactivity clock; a new PR head also restarts it. A maintainer can add no-stale for a durable hold, or bad-barnacle to suppress Barnacle. Remove the hold when work can resume.

Copy link
Copy Markdown
Contributor Author

#171327 now keeps run-failed-before-reply notices visible in history but excludes them from later model requests, including older saved notices. That conflicts with this PR’s current partial-output replay contract.

Before rebasing, could a maintainer confirm the intended direction?

  • Retain bounded, redacted unfinished output only in visible history, preserving the current context exclusion; or
  • Use a separate, explicitly approved mechanism for unfinished output in later model context.

The storage-owner decision on refusing an observing successor after a failed report write also remains pending.

This PR is awaiting that design decision. Could a maintainer add no-stale while it is pending?

@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Oct 25, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale after 7 days without qualifying human activity.
Without new human activity, Barnacle may close it as not planned 7 days after this message was posted. This is administrative inactivity cleanup, not a claim that the problem is fixed.
A human update restarts the inactivity clock; a new PR head also restarts it. A maintainer can add no-stale for a durable hold, or bad-barnacle to suppress Barnacle. Remove the hold when work can resume.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Nov 1, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

@openclaw-barnacle openclaw-barnacle Bot closed this Nov 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: memory-core Extension: memory-core gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL stale Marked as stale due to inactivity

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants