Skip to content

fix(sessions): record queued input end causes and recover them across crashes - #200533

Merged
obviyus merged 26 commits into
mainfrom
fix/queued-input-end-cause
Nov 18, 2026
Merged

obviyus merged 26 commits into
mainfrom
fix/queued-input-end-cause

Conversation

@obviyus

@obviyus obviyus commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

An accepted (acknowledged) queued chat message could disappear without a trace:

  • It could be cancelled with no stored reason. History showed nothing, and retrying the same message ID could return a cached success although the message never ran.
  • A Gateway crash (SIGKILL) lost it. Recovery depended on a graceful-shutdown marker, so a crash before the acknowledgment, or between claiming the message and the turn taking it over, left neither a queued row nor a running turn. On restart nothing answered and nothing explained why.

This changes #185730's accepted SIGKILL loss for acknowledged queued input.

Fix

Recorded end causes

  • Store a closed end_cause (user-stop, delete, reset, revoked, restart-unrecoverable, overflow, policy-refused, failed) through the existing pending-input owner. One settlement owner classifies causes (an explicit Stop, delete, reset or revocation wins over a temporary outage), releases consumed custody and records terminal endings.
  • Temporary authority or dispatch outages: before the input is accepted (no acknowledgment sent; the caller gets the error), the row ends failed, as main cancels it today. After acceptance, the row stays queued and the failed attempt gives up its live ownership, so the existing owner (follow-up drain, mailbox, or startup replay) runs it once.
  • Read durable cancellation before cached success/abort responses; a queued retry reports in flight.
  • Chat shows one translated sentence per cause (for example "The Gateway restarted before this message ran. Send it again."). A message the user stopped shows no notice, as before (fix(ui): hide redundant cancellation notices after Stop #186073).
  • Channel redelivery under a fresh run ID still reclaims an attempt that ended failed, restart-unrecoverable, or with no recorded cause (fix(sessions): channel message never answered after its first attempt fails #193602). Explicit caller retries may reopen a cancelled row unless a final completion receipt exists or the user stopped it. One function (isRetryableSessionPendingInputEndCause) defines retryable endings for redelivery and Doctor repair; when Doctor merges two copies of one input, a deliberate ending in either copy wins.

Crash recovery

  • Store the already captured, authenticated sender source on the pending row (origin_source_json). Startup replays queued, unconsumed rows in FIFO order after running-root resume admission and revalidates current authority when work starts. A missing source ends as restart-unrecoverable. The column is cleared when custody ends. It is not the retired, untrusted recovery_intent_json envelope; historical v24 interruption is unchanged.
  • The transaction that appends the user message and consumes the pending row also writes the turn's existing lifecycle start fields, so restart recovery always finds the input as either a queued row or a running turn. No new table, scheduler or reconstruction machinery.
  • If replay defers because authority or dispatch is temporarily unavailable, the session keeps its older rows ahead of new input: the shared admission point (waitForAgentInputAdmission) runs that session's deferred replay once before admitting fresh input, and refuses fresh input with the same retryable error while it still defers. Other sessions are unaffected. No timer or retry loop.
  • Legacy queuedInputSources move from shutdown markers to their pending rows through the startup/Doctor rewrite owner. fix: preserve requester permissions when interrupted work resumes #200394's resumeAfterRestart.operatorSource (the interrupted root requester) is kept; a crash writes no marker, so source-less root recovery keeps the existing session-principal policy.

Agent schema 43 (one bump)

The agent database schema advances from 42 to 43 on SQLite and PostgreSQL through the existing versioned migration owners. It adds nullable end_cause and origin_source_json to session_pending_inputs and, in the same transaction, sets end_cause = 'user-stop' for older cancelled rows whose message carries __openclaw.pendingInputCancelledByUser: true or display: false (message bytes unchanged; dismissed rows stay hidden). Runtime readers use only end_cause.

Every pre-43 historical schema, including the schema-14 preflight, is derived without the two columns; PostgreSQL v42 predecessor DDL is unchanged. Older builds refuse schema 43; rollback needs the pre-upgrade backup and the matching binary. No schema-version bypass.

Pre-migration backup: session_pending_inputs is the agent schema's only AUTOINCREMENT table, and the scoped migration snapshot does not cover AUTOINCREMENT tables (shared sqlite_sequence), so Doctor takes its existing full-database backup for 42 → 43 wherever that table exists. Upgrades from stable 2026.11.4 already take a full backup (schema 30 has no scoped entry). For stores already on 42 this is a one-time copy about the size of the agent database (3.0 GB on one measured long-lived store). The migration inserts no rows, and no backup code changes.

User impact

  • A queued message survives a crash: it is answered once, or ends with a visible reason. Same-ID retries never start a second answer.
  • Cancelled messages explain why, in plain words, instead of looking successful.
  • During a startup access outage, new messages in an affected session get a "try again" error until its older messages have run; nothing runs out of order.

Accepted edges:

  • Explicit sessions.delete removes input rows and message bodies; the delete confirmation is the visible result.
  • Stop on 2026.11.4 and earlier wrote no marker; such rows stay generically cancelled and reclaimable by a same-content channel redelivery, as on main.
  • An accepted input whose path has no in-process retrier (direct agent execution after acknowledgment) and that hits a temporary outage stays visibly queued until the next Gateway start replays it.
  • The upgrade from 42 to 43 takes a full-database backup where session_pending_inputs exists (see Agent schema 43).
  • No exactly-once guarantee for external tool effects or provider billing.

Evidence

  • Head ed2c3b46d558, rebased on current main: format, lint and line caps pass; pnpm tsgo:core, all pnpm tsgo:core:test configurations and the script typecheck pass; all baseline ratchets and the import-cycle guard pass. Regression tests (each red on an earlier head) cover deferred replay ordering, the shared-store graceful-restart agent, pre-acceptance outages, an accepted follow-up that waits out an outage and then runs exactly once, a same-key attempt with a different run ID (refused), startup replay racing the follow-up drain (one run), a user Stop during an outage, and the original abort signal on cleanup. An internal stop is not recorded as user-stop; only a user-initiated Stop is. Only the recorder that confirmed a relinquish may re-attach its queued row; a fresh send, a redelivery or a row whose settlement failed cannot (the revoked-parent-after-stop test stays refused). Startup replay re-attaches only its exact durable row by input ID after a deferred outage.

  • Schema: reopening a main v42 PostgreSQL store failed before the migration (PostgreSQL schema drift detected against generated DDL) and now migrates to 43; 10 real PostgreSQL tests pass. The v14-to-v15 migration test failed with column definitions differ for session_pending_inputs before the historical-schema fix and passes now. Each review fix carries a regression test that failed before it.

  • Crash proof on head ed2c3b46d558: isolated source Gateway, Node inspector, real model, external SIGKILL at the exact breakpoint; plugins.allow=["openai"], plugins.slots.memory="none", cron.enabled=false. Baseline is main at 6747b1ec5ae3.

    Fault Main answers / queued model calls This PR answers / queued model calls Stored outcome
    Message row written, before acknowledgment 0 / 0 1 / 1 Answered; no pending row; session done
    Message claimed, before the turn took it over 0 / 0 1 / 0 (one running-turn recovery call) Answered; the message was already in the transcript and the row gone at the pause; session done

    Each produced exactly one answer and no extra model calls after a same-ID retry. Earlier runs on pre-43 head 975900737b4f covered a crash just after takeover (one answer, no duplicate) and mid-turn (one answer).

  • Upgrade from 2026.11.4 (schema 27), clean shutdown and SIGKILL: both reach schema 43 with both columns; a message still queued after the SIGKILL ends cancelled / restart-unrecoverable, shown in history and on same-ID retry, with zero model calls. Both this branch and pinned main fail their first start after that SIGKILL with a secrets/SQLite disk-I/O error and succeed on the second start; filed separately as First Gateway start after a SIGKILL'd 2026.11.4 fails with a secrets disk I/O error #200617. Doctor's Control UI build during that upgrade is Startup Doctor builds Control UI assets when gateway.controlUi.enabled is false #200618.

  • Chat notice before/after screenshots are in the PR comments.

No full release declaration proof or real PostgreSQL conformance suite is claimed beyond the tests above.

@clawsweeper

clawsweeper Bot commented Nov 17, 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 app: web-ui App: web-ui gateway Gateway runtime commands Command implementations agents Agent runtime and tooling size: XL labels Nov 17, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 17, 2026
@clawsweeper

clawsweeper Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR stores terminal causes for accepted chat inputs and exposes them in history and same-ID retry responses.

Example: A queued chat input with message ID chat-42 is stopped before execution.

  • Before: A retry can return cached success without explaining why the input never ran.
  • After: The retry returns chat-input-cancelled with endCause user-stop and instructions to send with a new ID.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The user problem is worth fixing, but demonstrated readmission failures and source-established recovery and upgrade defects make this revision unready.
Proof confidence 🦪 silver shellfish (2/6) The maintainer-authored PR is outside the contributor proof gate; supplied evidence describes owner tests and an earlier stacked upgrade, which does not establish compatibility of legacy retirement records or existing PostgreSQL storage.
Patch quality 🧂 unranked krab (1/6) 6 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: An accepted message can disappear from execution without an explanation, while retrying its ID appears successful.
Reason: Durable explanations have clear user value, and the maintainer-authored PR supplies direction for the behavior change.

Merge readiness

⛔ Blocked before merge - 8 items remain

Keep open: this maintainer-authored PR addresses a real accounting problem, but introduces retry, restart recovery, and PostgreSQL upgrade regressions that block merging.

Priority: P1
Reviewed head: 1844c01611e49311e7dedf2a98c16c6f07505459

Before merge

  • Preserve retryable failures without requiring a completion receipt (P1) - For a newly recorded cancelled/failed row, explicit retry now requires previous to exist, while channel reclaim accepts only legacy rows. Configuration readmission and failed completion commits can legitimately have no completion receipt, so their retryCancelled request now throws ownership ended; channel redelivery under a fresh run similarly conflicts. Exact-head CI shows the private-completion and session-event failures. Preserve these established retry paths while continuing to seal Stop and other intentional terminal causes.
  • Keep legacy Stop and dismissal markers as replay fences (P1) - A pre-upgrade cancelled row has no end_cause even when its message contains pendingInputCancelledByUser or display:false. Removing isSessionPendingInputRetiredByUser makes a byte-identical channel redelivery qualify for reclaim and rebind its run ID. In particular, a previously stopped, unconsumed message can execute after upgrade. Preserve the legacy marker exclusion or migrate those markers before allowing reclaim.
  • Retain restart scheduling custody across temporary admission failure (P1) - When restoring a captured sender throws GatewayOperatorAccessUnavailableError, this branch leaves the row queued and returns false, but continueSessionQueuedInputs discards that result and resolves normally. Its caller has already cleared resumeAfterRestart before invoking it. No retry is scheduled when authority returns, and later FIFO inputs are also abandoned; same-ID retries now report in_flight. Keep the unfinished cohort with the existing resume owner and retry it after recovery.
  • Provide a PostgreSQL upgrade path for end_cause (P1) - An existing PostgreSQL agent namespace lacks this column, but the PR changes generated canonical DDL without adding an upgrade operation. ensureSessionPendingInputsSchema explicitly returns for PostgreSQL, and engine migration runs only when the schema version changes. Same-version reopening therefore fails catalog verification against generated DDL; historical fromSchema definitions also inherit the new column. Install the additive field through the PostgreSQL schema owner while preserving accurate historical source definitions.
  • Exclude ownerless queued rows from ordinary pending history (P2) - The default SQL query now returns every unconsumed queued row, including crash-left rows with no live owner or captured restart cohort. The UI renders these as user messages without a terminal notice or dismissal action, although nothing will execute them. The memory backend retains the previous liveInputIds restriction, so the backends also disagree. Preserve the eligibility restriction unless the existing recovery owner has explicitly adopted or terminally classified the row.
  • Match the tool-hint assertion to its existing enum budget (P2) - The replacement expectation requires the full eight-value cause union, whose rendered text exceeds MAX_COMPACT_ENUM_CHARS=96. compactToolOutputHint therefore correctly emits endCause?: string, as the exact-head checks-node-changed-compact-large-38-2 failure confirms. Update this expectation to the bounded representation while retaining independent validation of the closed cause schema.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.
  • Explain or restore the original intent of Pending history eligibility - 9344233: Keep ownerless and crash-left input inert and outside normal history presentation; the later shared-predicate refactor preserved that restriction.

Findings

  • [P1] Preserve retryable failures without requiring a completion receipt — src/config/sessions/session-accessor.pending-inputs.ts:391-402
  • [P1] Keep legacy Stop and dismissal markers as replay fences — src/config/sessions/session-accessor.pending-inputs.ts:391-397
  • [P1] Retain restart scheduling custody across temporary admission failure — src/gateway/queued-chat-inputs.ts:185-189

Provenance

  • Pending history eligibility changes intended behavior without addressing why it exists (9344233: Keep ownerless and crash-left input inert and outside normal history presentation; the later shared-predicate refactor preserved that restriction.)

Tests

  • Missing end-to-end proof: Upgrade coverage must include legacy Stop/dismissal rows and an existing PostgreSQL namespace, and restart-outage coverage must show processing after recovery rather than only retained rows.
Agent review details

How this fits together

Gateway admission stages accepted messages in the pending-input owner, which coordinates transcript consumption, terminal settlement, database storage, and history presentation.

flowchart LR
A[Chat input] --> B[Gateway admission]
B --> C[Pending input owner]
C --> D[Session database]
C --> E[Agent dispatch]
D --> F[History and retry responses]
Loading

Technical review

Best possible solution:

Persist causes through the existing owner while preserving legitimate retries, legacy retirement fences, restart scheduling custody, and database upgrades.

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

Current-main storage and retry code establish the missing-cause path, and exact-head CI independently exposes several introduced regressions; no target code was executed during this read-only review.

Is this the best way to solve the issue?

Extending the current pending-input owner is the smallest appropriate design, but recording a failure must not erase retry contracts or substitute stored rows for runnable custody.

Full review comments:

  • [P1] Preserve retryable failures without requiring a completion receipt — src/config/sessions/session-accessor.pending-inputs.ts:391-402
    For a newly recorded cancelled/failed row, explicit retry now requires previous to exist, while channel reclaim accepts only legacy rows. Configuration readmission and failed completion commits can legitimately have no completion receipt, so their retryCancelled request now throws ownership ended; channel redelivery under a fresh run similarly conflicts. Exact-head CI shows the private-completion and session-event failures. Preserve these established retry paths while continuing to seal Stop and other intentional terminal causes.
    Confidence: 0.99
  • [P1] Keep legacy Stop and dismissal markers as replay fences — src/config/sessions/session-accessor.pending-inputs.ts:391-397
    A pre-upgrade cancelled row has no end_cause even when its message contains pendingInputCancelledByUser or display:false. Removing isSessionPendingInputRetiredByUser makes a byte-identical channel redelivery qualify for reclaim and rebind its run ID. In particular, a previously stopped, unconsumed message can execute after upgrade. Preserve the legacy marker exclusion or migrate those markers before allowing reclaim.
    Confidence: 0.99
  • [P1] Retain restart scheduling custody across temporary admission failure — src/gateway/queued-chat-inputs.ts:185-189
    When restoring a captured sender throws GatewayOperatorAccessUnavailableError, this branch leaves the row queued and returns false, but continueSessionQueuedInputs discards that result and resolves normally. Its caller has already cleared resumeAfterRestart before invoking it. No retry is scheduled when authority returns, and later FIFO inputs are also abandoned; same-ID retries now report in_flight. Keep the unfinished cohort with the existing resume owner and retry it after recovery.
    Confidence: 0.98
  • [P1] Provide a PostgreSQL upgrade path for end_cause — src/state/postgres-schema.generated/agent.postgres.sql:440
    An existing PostgreSQL agent namespace lacks this column, but the PR changes generated canonical DDL without adding an upgrade operation. ensureSessionPendingInputsSchema explicitly returns for PostgreSQL, and engine migration runs only when the schema version changes. Same-version reopening therefore fails catalog verification against generated DDL; historical fromSchema definitions also inherit the new column. Install the additive field through the PostgreSQL schema owner while preserving accurate historical source definitions.
    Confidence: 0.99
  • [P2] Exclude ownerless queued rows from ordinary pending history — src/config/sessions/session-pending-input-history.kernel.ts:32
    The default SQL query now returns every unconsumed queued row, including crash-left rows with no live owner or captured restart cohort. The UI renders these as user messages without a terminal notice or dismissal action, although nothing will execute them. The memory backend retains the previous liveInputIds restriction, so the backends also disagree. Preserve the eligibility restriction unless the existing recovery owner has explicitly adopted or terminally classified the row.
    Confidence: 0.99
  • [P2] Match the tool-hint assertion to its existing enum budget — src/agents/tools/sessions-history-tool.test.ts:219
    The replacement expectation requires the full eight-value cause union, whose rendered text exceeds MAX_COMPACT_ENUM_CHARS=96. compactToolOutputHint therefore correctly emits endCause?: string, as the exact-head checks-node-changed-compact-large-38-2 failure confirms. Update this expectation to the bounded representation while retaining independent validation of the closed cause schema.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Cancelled source-turn retry changes intended behavior with a stated reason (cb719fe: Recover a channel message after a pre-consumption failure without reopening Stop or dismissal.)
  • Direct Stop notices changes intended behavior with a stated reason (730b609: Keep stopped text without a redundant cancellation notice or Dismiss button.)
  • Consumed input settlement keeps the original intent (2031044: Acknowledge committed input retries without dispatching duplicate turns.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm exec vitest run src/config/sessions/session-accessor.pending-inputs.test.ts src/auto-reply/reply/dispatch-from-config.pending-restart.test.ts src/auto-reply/reply/session-event-config-readmission.test.ts src/gateway/server.private-completion.test.ts
  • pnpm exec vitest run src/config/sessions/session-pending-input-history.test.ts src/gateway/queued-chat-inputs.metadata.test.ts src/gateway/session-restart-resume.test.ts
  • pnpm exec vitest run src/state/openclaw-agent-pending-inputs-schema.test.ts src/state/openclaw-agent-db.test.ts src/agents/tools/sessions-history-tool.test.ts
  • pnpm tsgo:core
  • pnpm tsgo:core:test

What I checked:

Likely related people:

  • Vito Cappello: Raw commit cb719fe adds src/config/sessions/session-accessor.pending-inputs.ts:224 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: cb719feef55c; files: src/config/sessions/session-accessor.pending-inputs.ts)

PR surface

PR surface statistics unavailable: the file list is incomplete.

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add P1: Accepted-message accounting affects working chat, channel retry, and restart workflows.
  • add merge-risk: 🚨 compatibility: Existing PostgreSQL namespaces lack the newly required column and have no corresponding upgrade operation.
  • add merge-risk: 🚨 message-delivery: Failed input readmission and temporary restart outages can leave accepted messages permanently unprocessed.
  • add merge-risk: 🚨 session-state: Legacy retirement markers lose their replay fence, and ownerless queued rows enter ordinary history.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦪 silver shellfish and patch quality is 🧂 unranked krab.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P1: Accepted-message accounting affects working chat, channel retry, and restart workflows.
  • merge-risk: 🚨 message-delivery: Failed input readmission and temporary restart outages can leave accepted messages permanently unprocessed.
  • merge-risk: 🚨 session-state: Legacy retirement markers lose their replay fence, and ownerless queued rows enter ordinary history.
  • merge-risk: 🚨 compatibility: Existing PostgreSQL namespaces lack the newly required column and have no corresponding upgrade operation.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦪 silver shellfish and patch quality is 🧂 unranked krab.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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.

Reviewed November 17, 2026, 4:56 AM ET / 09:56 UTC.

@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Nov 17, 2026
@obviyus

obviyus commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Chat notice for a cancelled queued message, before (main) and after (this PR). Same synthetic stored rows on an isolated Gateway; this shows presentation, not how the cause is produced.

  • Gateway restart: main shows a generic "Cancelled before the agent started it" notice; this PR says the Gateway restarted before the message ran and asks to send it again.
  • Message could not start: generic notice on main; this PR says the message could not be started.
  • Stopped by the user: no notice and no Dismiss button, as on main (fix(ui): hide redundant cancellation notices after Stop #186073).

Before: generic notice after a Gateway restart

After: restart explanation with resend guidance

Before: generic notice when the message could not start

After: start-failure explanation

After: stopped message shows no notice

@obviyus
obviyus marked this pull request as draft November 17, 2026 13:44
@obviyus obviyus changed the title fix(sessions): record visible end causes for accepted chat input fix(sessions): record queued input end causes and recover them across crashes Nov 17, 2026
@obviyus
obviyus marked this pull request as ready for review November 17, 2026 14:50
- Record explicit terminal causes and separate consumed-owner release from finish.
- Keep temporary restart admission failures queued and return recorded cancellation on same-key retries.
- Declare nullable first-use storage and retain compatibility with older readers.
- Reclaim retryable channel failures while sealing legacy user retirement markers.
- End deferred graceful-restart inputs and keep crash-only history projection in the stacked replay change.
- Shipped Stop rows keep the marker under __openclaw; the fixture now uses that shape.
- Backfill legacy user retirement facts atomically with first-use end_cause installation.
- Normalize before startup, Doctor canonical repair, and offline port consumption; remove runtime marker readers.
- Preserve historical port descriptors and prove startup replay fences, history projection, repair, and port behavior.
- Migrate SQLite and PostgreSQL pending-input ending facts atomically and reserve original-source storage.
- Preserve exact predecessor layouts and replace first-use ending migration wiring with the existing versioned owners.
- Keep unmarked legacy cancellations unknown, matching main's retry semantics.
fuller-stack-dev added a commit that referenced this pull request Nov 19, 2026
 (#201590)

#200533 moved accepted queued input onto its pending rows, so the restart-resume marker no longer carries queuedInputIds. It keeps the interrupted requester as operatorSource, which restart resume revalidates. Assert that shape, and drop an unused journal field.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 19, 2026
…1002)

Apply hosted file-count bounds during weighted balancing instead of slicing already-balanced stripes into stranded tails. Preserve the 77-row hourly nondist cap, runner and worker limits, time budgets, and complete selected inventory.

The scheduled manifest reproduced 78 > 77 after inventory growth in openclaw#200967. Expanded GitHub/hybrid regressions and all 174 focused planner tests pass; Codex autoreview is clean. check:changed passes except unrelated main unused exports attributed to openclaw#200533, openclaw#193550, openclaw#198455, and openclaw#200817.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 19, 2026
…penclaw#200966)

* perf(agents): materialize selected rows for simple completions

* style: satisfy selected completion lint checks

* test: bind isolated registry measurement to concrete instances

* test: align participant custody with requester ownership

Follow openclaw#200952: Alice owns sessions she requests even when Bob supplies execution authority. Preserve autonomous agent ownership expectations. All 174 spawn-boundary, child-custody, and provenance tests pass; Codex scoped review is clean.

* fix: retain missing-session facts across database creation

Preserve first-chat authorization when catalog persistence opens the selected absent database. Keep session-row, lifecycle, routing, and source-revocation guards intact. The focused bisect identifies openclaw#197510 as the first failing first-chat authorization boundary; openclaw#199565 had repaired other cold-registration orderings.

The deterministic regression is red before this fix. All 66 owning tests and three complete real Gateway reload trials pass; Codex review is clean through P2. check:changed passes every check except nine unused exports reproduced identically on exact main parent 4dca39a and attributed to openclaw#200533, openclaw#198455, and openclaw#200817. Preserve peer cleanup scope in openclaw#201019.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 19, 2026
…claw#200533 (openclaw#201590)

openclaw#200533 moved accepted queued input onto its pending rows, so the restart-resume marker no longer carries queuedInputIds. It keeps the interrupted requester as operatorSource, which restart resume revalidates. Assert that shape, and drop an unused journal field.
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 19, 2026
…stage 2)

Catches the pure continuation candidate bc7e568 up to openclaw/openclaw
main 41bdde2 (fetched 2026-11-19T14:32:59Z),
2,996 upstream commits past the old merge base 401a1de. Merge commit only;
rerere disabled, so every resolution was made here.

80 conflicted paths (77 content, 3 modify/delete), each recorded with base,
ours and theirs blobs and its reason in the lane's stage2-conflicts.md:
- 8 take upstream whole: the openclaw#197153 pg16-smoke cherry-pick (6909b64) now
  ships upstream (ci.yml, ci-build-manifest, ci-workflow-planning test), the
  Control UI settings child moved onto runDistArtifactChild, the canary
  worker target and two active-facts migration tests.
- 3 deleted with upstream: session-fork and update-candidate-canary suites
  whose production paths upstream removed; cwd-split folded away (openclaw#198916),
  its one continuation case rehomed to attempt.continuation-tools.test.ts.
- One-owner cutovers where upstream now owns a fork extraction: the
  requester-origin projection and replacement-text helpers (openclaw#200533) replace
  the fork's byte-identical copies in user-turn-transcript.metadata.ts.
- Ports into fork-extracted owners: removalReason in the queued-start plan
  and collector-group sweep (openclaw#199868), the async prepared-pricing usage
  diagnostic, the announce flow types, and the session-delivery codec, which
  gains upstream's mediaCandidate kind, reviewedTaskId and their schemas
  (openclaw#198227), importing its retention type from the leaf types module.
- Transcript repair (openclaw#201304, post-b894): upstream's payload-free adapter
  kernel carries the fork's continue_delegate attachment redaction through a
  payload-adapter-only fact and a withBlock update.
- Reset cleanup: upstream's process and retained-send stops (openclaw#199079,
  openclaw#200326) with the fork's continuation-aware reason as the single input;
  the chat reset's retention adapter wraps upstream's stopSessionResetWork,
  the Gateway preemption keeps stopSessionResetSubagents as upstream does.
- Schema: upstream owns agent 42 (tool usage) and 43 (pending-input
  endings) and is at 43; 44 is unused upstream. Continuation's recipient
  authority moves 42 -> 44: version constants, step order, historical
  schemas, witness additive table and version set, backup scope, PostgreSQL
  ladder (V43 = current minus the authority table) and port descriptor.
  package.json schemaVersions state 40, agent 44.
- Generated outputs regenerated, never hand-merged: config baseline,
  gateway validators, postgres schema catalogs, worker-access inventory.
- Compile follow-through for upstream's delivery-union narrowing and its
  readSessionDelivery callers.

Refs openclaw#129388
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 19, 2026
…pted input relinquishes custody

O2, ported to the pure candidate (stage 2) from 8942242. Upstream's
relinquish (openclaw#200533, now merged) clears pendingInput and staging when an
accepted input meets a transient outage, while acceptedPendingInputId stays
so the same recorder can reattach the queued row. The fork's
delivery-ack replacement guard (replaceSessionDeliveryAckIds, inline in the
pure recorder) then read "not started", so a drain could replace the ack ids
of an input whose bytes were already committed. acceptedPendingInputId is
assigned once at the first commit and never cleared: the guard now counts it
first. Collected recorders set no accepted ID and keep their behaviour.

Regression (recorder boundary, real SQLite custody, upstream's
settleUserTurnPendingInput with accepted): "keeps managed delivery receipts
frozen after an accepted outage relinquishes custody", carried verbatim
from 8942242. Red on the merged head (expected true to be false at the
replacement), green with the operand; both transcript suites 57/57.

Refs openclaw#129388

Co-Authored-By: Claude Opus 5.5 <[email protected]>
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 19, 2026
…estart-custody pin

Upstream openclaw#200533 (703c82d) moved queued-input custody from the graceful
shutdown marker to the pending-input rows, so the marker is `{}` rather
than `{ queuedInputIds: [] }`. Case 3 of
subagent-registry.restart-terminal-custody (the root's resume input does
not stand in for a delegate's receipt) pinned the old shape: green at
chain head fa212db, red at ead2225, 11/11 here. The custody
assertions that follow are unchanged.

Carried to the pure candidate (stage 2): openclaw#200533 arrives with the 41bdde2
merge. On the merged head case 3 fails at the marker ({} vs
{ queuedInputIds: [] }); with this change it passes the marker and stops at
the separate upstream openclaw#201544 shutdown-outcome change (subagent-error vs
subagent-killed), which is held for 🌊's ruling and not changed here.

(cherry picked from commit 525e98d)
Refs openclaw#129388

Co-Authored-By: Claude Opus 5.5 <[email protected]>
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 19, 2026
…rk fixtures

Compile and behavior follow-through for upstream APIs the merge brought in,
each red on ddd0ec7 and green here:
- sessions-spawn-cloud: upstream's new paired-device case (openclaw#197469) mocks
  registerRun as void; the fork's registration returns ownership, so the mock
  returns a committed-row ownership (tsgo agents-tools TS2322; 16/16).
- finishPendingInput now takes an end cause (openclaw#200533): the fork's recorder
  case and transcript-events case pass "failed" (tsgo other TS2554).
- postcompaction-autocompaction: upstream's SessionMaintenanceRequest needs
  sourceTarget/sourceIdentities (prepareSessionMaintenanceRequest), so the
  command case prepares the request before scheduling (TS2739); the
  pressure-handoff report supplies the four subtrees upstream interns
  (openclaw#199748; 10 cases "snapshot is not an Object" without it, from chain
  47edd05); and the required-compaction-failure case crosses the 200k
  window with a new fitting-request case for openclaw#200714's fit-only preflight
  failure (from staging ead2225; red at 150k without it). 13/13.

(cherry picked from commit 47edd05)
Refs openclaw#129388

Co-Authored-By: Claude Opus 5.5 <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 19, 2026
Apply hosted file-count bounds during weighted balancing instead of slicing already-balanced stripes into stranded tails. Preserve the 77-row hourly nondist cap, runner and worker limits, time budgets, and complete selected inventory.

The scheduled manifest reproduced 78 > 77 after inventory growth in #200967. Expanded GitHub/hybrid regressions and all 174 focused planner tests pass; Codex autoreview is clean. check:changed passes except unrelated main unused exports attributed to #200533, #193550, #198455, and #200817.

Backport to beta.2 preparation; exact reviewed adapted patch. Focused parent proof: 35 tests; nine-file type-aware lint; 18-file format. Tooling typecheck retains the same two pre-existing cron UI errors as baseline. No release qualification.

(cherry picked from commit af50b8e)
(cherry picked from commit c7ccc5e)
Co-authored-by: Vincent Koc <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 19, 2026
…200966)

* perf(agents): materialize selected rows for simple completions

* style: satisfy selected completion lint checks

* test: bind isolated registry measurement to concrete instances

* test: align participant custody with requester ownership

Follow #200952: Alice owns sessions she requests even when Bob supplies execution authority. Preserve autonomous agent ownership expectations. All 174 spawn-boundary, child-custody, and provenance tests pass; Codex scoped review is clean.

* fix: retain missing-session facts across database creation

Preserve first-chat authorization when catalog persistence opens the selected absent database. Keep session-row, lifecycle, routing, and source-revocation guards intact. The focused bisect identifies #197510 as the first failing first-chat authorization boundary; #199565 had repaired other cold-registration orderings.

The deterministic regression is red before this fix. All 66 owning tests and three complete real Gateway reload trials pass; Codex review is clean through P2. check:changed passes every check except nine unused exports reproduced identically on exact main parent 97b03f7 and attributed to #200533, #198455, and #200817. Preserve peer cleanup scope in #201019.

(cherry picked from commit 8610cd6)

Co-authored-by: RomneyDa <[email protected]>
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 19, 2026
…admission at 44

Upstream's openclaw#200533 tests build a "version 42" store from the current
schema by dropping the 43 ending columns. In the fork the current schema
also carries recipient authority, so that store is upstream 42 plus
authority, which the bridge correctly refuses as an unrecognized
schema-42 shape. These fixtures now drop the authority table too
(upstream's 42 never had it), and the post-admission pins read 44:

- openclaw-agent-pending-inputs-schema (3 fixtures, 2 pin pairs)
- chat-pending-inputs, doctor-session-canonical-keys.completions
- session-tombstone-recovery (fork pin 43 -> 44)
- openclaw-agent-cold-navigation-migration: upstream openclaw#200533 moved the
  pending-input integrity scope onto step 43, so the fork's explicit
  crossing (kept off the authority step) now targets upstream's 43.

Red at 525e98d (7 + 5 + 1 cases), green here (5 files).

Carried to the pure candidate (stage 2) without session-tombstone-recovery
(that suite is composite-only and absent here). The pure tree has no
bridge: its SQLite admission is a contains-check, so upstream's
"42 = current minus endings" fixtures were admitted with the authority table
and only the 43 pins went red (4 cases in 3 files). Dropping the table
makes them upstream's real 42, so the authority step creates it on the way
to 44. The cold-navigation integrity case failed on the merged head (only
schema_meta checked on the explicit 38->39 crossing, since openclaw#200533 moved the
pending-input scope to 43). All 4 files green: 31/31 and 8/8.

(cherry picked from commit 465b2e5)
Refs openclaw#129388

Co-Authored-By: Claude Opus 5.5 <[email protected]>
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 19, 2026
…'s 42 and 43

The 41bdde2 merge moved continuation's recipient-authority step from 42
to 44: upstream owns 42 (tool usage, openclaw#197128) and 43 (pending-input
endings, openclaw#200533) and is at 43. The pins follow, in the pure tree's own
shape (no bridge):

- owner suite: fresh, v18, v24, derived upstream 32-38, current-schema and
  double-apply rows read 44; the derived upstream schemas also drop 42's
  tool usage and 43's endings; captured upstream rows now 39-43 (new
  fixtures openclaw-agent-schema-v42.sql = blob 43b1886 at 6691aca,
  the last schema-42 commit, and v43.sql = blob 2a6bb45 at 703c82d,
  unchanged through 41bdde2); the double-apply row starts from captured
  43; a new refusal row: a 43 holding upstream's 42 is refused by upstream's
  own check (session_pending_inputs) before any write.
- Doctor suite: upstream 37-43 -> 44 inside the declared scope, re-run
  no-op, exact restore; stores below 43 are staged before pending-input
  first use (upstream's 43 scope names that AUTOINCREMENT table, so a
  present one takes a full image instead).

Revert-proofs (temporary edits, restored byte-exact):
- authority step removed: 15/22 owner rows and 7/7 Doctor rows red
  ("missing table session_recipient_authority"); fresh, current-44,
  PG-separator and the three refusal rows stay green;
- AGENT_RECIPIENT_AUTHORITY_SCHEMA_VERSION left at 42: exactly the captured
  upstream 42 and 43 rows and the 43-based double-apply row go red, with
  the same missing-table refusal. Upstream's real 42/43 stores need 44.

Owner 22/22, Doctor 7/7.

Refs openclaw#129388

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-actions Bot pushed a commit to clawhaven/openclaw that referenced this pull request Nov 23, 2026
…penclaw#200966)

* perf(agents): materialize selected rows for simple completions

* style: satisfy selected completion lint checks

* test: bind isolated registry measurement to concrete instances

* test: align participant custody with requester ownership

Follow openclaw#200952: Alice owns sessions she requests even when Bob supplies execution authority. Preserve autonomous agent ownership expectations. All 174 spawn-boundary, child-custody, and provenance tests pass; Codex scoped review is clean.

* fix: retain missing-session facts across database creation

Preserve first-chat authorization when catalog persistence opens the selected absent database. Keep session-row, lifecycle, routing, and source-revocation guards intact. The focused bisect identifies openclaw#197510 as the first failing first-chat authorization boundary; openclaw#199565 had repaired other cold-registration orderings.

The deterministic regression is red before this fix. All 66 owning tests and three complete real Gateway reload trials pass; Codex review is clean through P2. check:changed passes every check except nine unused exports reproduced identically on exact main parent 97b03f7 and attributed to openclaw#200533, openclaw#198455, and openclaw#200817. Preserve peer cleanup scope in openclaw#201019.

(cherry picked from commit 8610cd6)
Release adaptation: approved 2026.11.7 models replay; see models-hook-safe-v2/REPORT.md.
Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
Release adaptation: extract the independent mixed-requester repair and its queue regression. Stable already strips display/owner flags but copies requester origin and the private owner capability. The wider saved-requester cutover needs the newer fixed-request and Cron occurrence authorities and the durable queue owner; do not replace the stable custody or restart contract.

Companions: #203468 and #203521 are separate selected start-grant repairs. #201334, #201377, #200533 and #202318 are missing full-cutover prerequisites; #203516, #202522 and #202520 are later distinct lifetime refactors, not needed by the isolated mixed-requester repair.

(cherry picked from commit 3ad2cce)

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit a26e1e7b02425b94d31c3e6bc6add8d417dc3fda)
maplel pushed a commit to maplel/openclaw that referenced this pull request Nov 24, 2026
)

* fix(plugins): portable plugin-state keys for PostgreSQL

Use an exclusive SQL lower bound for Doctor pagination instead of a NUL-suffixed cursor. Reject new NUL keys in test-only plugin-state fixtures while retaining legacy SQLite adoption reads.

Add real PostgreSQL Doctor regression coverage and register it in conformance and database-worker lanes. Refs openclaw#184862 openclaw#188642.

* test: account for rebased plugin-state coverage

* test(clickclack): import legacy revocations before adoption

(cherry picked from commit 395cac7)

Release adaptation: Only exclusive SQL lower bound in kernel and Doctor pagination; preserve legacy SQLite keys and public validation. Regression exercises real Doctor paging and inspected executed SQL bindings; no NUL-key fixture policy, schema or unrelated tests.

Follow-up dispositions: 8253356 fix: preserve child results after source lifecycle changes (openclaw#202708); f3f89c7 fix: show saved child results when completion delivery fails (openclaw#202664); c45faa8 fix: align CI tests with admitted tool calls (openclaw#202655); 5c9389a fix: make channels add report required plugin install failures (openclaw#202091); 52b9188 fix: show hosted model details in `models list` without a Gateway (openclaw#202490); d248a76 fix: show an outcome when kept child chats return no answer (openclaw#202423); 5148804 fix(discord): check a queued message's access again when its turn starts (openclaw#202330); 2470d62 fix: let setup use account models with a fresh catalog (openclaw#202019); 9fa0b92 fix: let PostgreSQL Gateways start with plugin-backed secrets (openclaw#201063); c180824 fix(plugins): Talk and plugin-loading requests fail on PostgreSQL Gateways (openclaw#201976); cb5cfb2 fix: keep a doubtful killed-update recovery on the repair path (openclaw#201361); 17c5fb0 fix(state): PostgreSQL state created before Template bootstrap deferral is refused as schema drift (openclaw#197425); b5c1277 fix: let resumed parents collect children stopped by restart (openclaw#201460); f920a7e chore(postgres): qualify cron completion during graceful shutdown (openclaw#201246); 1680f54 fix(openai): new ChatGPT subscription models missing until an OpenClaw release (openclaw#201130); 0d8820a fix(media): image descriptions use the ChatGPT OAuth route when OpenAI has no API key (openclaw#199299); ee3e16e test(agents): trim and fold low-value regression suites (openclaw#198916); b8029b4 test(agents): qualify PostgreSQL simple-completion acquisition (openclaw#200956); 703c82d fix(sessions): record queued input end causes and recover them across crashes (openclaw#200533); 23fca1a fix: let the next update continue after a killed update when nothing is left to repair (openclaw#200680); d565e17 fix(ci): retire deleted session fork test from inventory (openclaw#200611); 4cf12c6 chore(postgres): qualify prompt refresh and rebalance CI (openclaw#200488); d460273 fix(templates): release earlier Template-managed agents (openclaw#200303); ff75829 fix(update): --no-restart update fails when the Gateway restarts itself during Doctor's stop (openclaw#200181); 0b2ad60 chore(postgres): cover compaction watched-session prompts (openclaw#200117); b90c573 test: consolidate redundant coverage (198795 recut) (openclaw#198943); a042363 test: consolidate redundant coverage (198793, part 2) (openclaw#198936); 9bfad2b test: consolidate suites while retaining recovery owners (openclaw#198933); 4e9812c test: consolidate redundant coverage (198789, part 2) (openclaw#198932); 90814f5 fix(subagents): stops a finished sub-agent's chat being deleted before its parent reads the result; 799bc0b fix(ci): stabilize hourly fixtures and retire unused exports (openclaw#199851); e4a3093 perf(update): replace the candidate canary with a runtime contract check (openclaw#198268); a4cc2ad fix: undo cold-session compaction CPU and latency regressions (openclaw#199561); 55fec79 fix(agents): stop divergent mid-turn overflow recovery (openclaw#199636); 2c4413a fix: reduce Gateway stalls under filesystem pressure (openclaw#197510); 37d977f fix: output reducers are skipped in headless and Code Mode runs (openclaw#199434); c9ee264 fix(compaction): concurrent sessions wait for each other's summaries during compaction (openclaw#196550); 2471ddc feat: let agents review generated images before delivery (openclaw#198227); 21f7dc6 fix(github): publication fails with PostgreSQL session or state stores (openclaw#193749); 63d9e57 fix(ci): new PostgreSQL suites are omitted from conformance (openclaw#198390); 466a4b6 fix(telegram): steered answers quote the wrong input (openclaw#178124); 87b6f52 fix(delivery): resend routed Telegram finals after an ambiguous network failure (openclaw#192779); 68a839b fix: isolate held agent databases until explicit restoration (openclaw#198180); cff99b2 fix(agents): keep provider history append-only across runs (openclaw#197874); 8a328bf feat: add an opt-in usage-ranked tool index (openclaw#197128); 097e648 fix(ci): plan only executable infra tests (openclaw#197911); 76385fd fix(models): discovered models become "Unknown model" after restart or an ended sign-in (openclaw#197784); 89d4177 fix(plugin-state): guarded calls fail until Gateway restart after an unknown write outcome (openclaw#197790); baca36e fix(sessions): commit selected invitations with original messages (openclaw#184512); 699e538 fix(sessions): drain passive notices on sessions_send resumes; d6ded18 chore(ci): drop retired test-lines allocation records (2/3) (openclaw#197656); e0dd020 fix(agents): collect process results at suspended-run capacity; 4897740 feat(auth): preserve delegated OCE user profiles and permissions (openclaw#196856); 7197ce1 feat(templates): install bundled plugins through native management (openclaw#196349); 9c6ee9b feat: let Template automations start paused for onboarding (openclaw#196323); 79a6214 fix(message): retain local final replies in conversation history (openclaw#187795); caa978c feat(templates): open durable chat before verified setup (openclaw#196392); 78e73aa fix(sessions): cold PostgreSQL conversations fail after idle readers close (openclaw#189991); b6ed907 perf(sessions): persist active transcript facts for hydration (openclaw#193682); 1595dd2 feat(plugins): reauthorize accepted session work (openclaw#176886); b43ad0a fix(models): avoid reloading plugins on catalog refresh (openclaw#193903); 0947d02 fix(ci): avoid unrelated PostgreSQL runs and admit owned tests (openclaw#193870); 428ca7d feat(openclaw-id): add Gateway membership authority and publication behind the Labs flag (openclaw#192335); c718583 fix(update): repair refuses forever after a verified update fails a later step (openclaw#193132); 3f64174 fix: deliver background replies after a reload retires the turn registry (openclaw#193130); 982f3b1 fix(imessage): report Automation failures after Gateway updates (openclaw#186117); 31b28e9 fix(agents): wait for a peer OAuth refresh before failing request auth (openclaw#192906); cf50d4a feat(storage): support read-only PostgreSQL standby inspection (openclaw#192645); 82fd4e6 fix(agents): retain stale session target refusal reasons (openclaw#192681); 8ac4e19 fix(worktrees): reserve capacity on PostgreSQL (openclaw#192537); 718b349 fix: reduce session startup stalls under storage contention; 08f4a19 refactor(skills): move Skill Workshop into its bundled plugin (openclaw#192471); 837402a fix(clawrouter): keep upstream credit failures off the shared key (openclaw#192575); f38495f fix(plugins): reject late routing from canceled runs (openclaw#192492); dc5d61a improve(sessions): reduce unnecessary maintenance query rows (openclaw#192023); c4bf0dc fix(sessions): avoid extra maintenance scans for embedded archives (openclaw#184507); e44b3d6 fix(team-reports): recover after database connection loss (openclaw#192020); 991fb33 fix(logbook): recover after database connection loss (openclaw#192011); e6d0d2e fix(test): include omitted PostgreSQL conformance suites (openclaw#191962); da5ff0f fix(codex): reject native hooks from a previous run (openclaw#191788); 09f0b0b feat(plugins): add skill usage runtime for plugins (openclaw#191661); 00b2ff4 fix: parent sessions miss child approvals with a custom session store (openclaw#189827); be44b10 fix: stop completed session writes retaining request data (openclaw#191197); d40aa7c fix(sessions): replay creation requests across Gateway restarts (openclaw#190862); d894035 fix: await Doctor shared-state repair preparation (openclaw#190875); b515cc7 feat: fork threaded conversations with Telegram support (openclaw#190783); def6349 feat(plugins): plugins can run a hidden forked turn of a session with their own tools (openclaw#190950); d983e34 feat(plugins): plugin commands can continue the agent with a replacement prompt, on every channel (openclaw#190908); ea3f0b8 fix(ci): provision Node test prerequisites and retain Baseten routing (openclaw#191050); 29503e1 fix(update): Gateway stays stopped after the updater process dies mid-update (openclaw#188497); fc8c2d0 fix(update): preserve unfinished handoff artifacts (openclaw#190571); 7c26e8c fix(ci): cover PostgreSQL managed update handoffs (openclaw#190336); 4913d41 fix(ci): prevent truncated PostgreSQL target listings (openclaw#189509); 8925f62 fix(gateway): start restored PostgreSQL homes on the first attempt (openclaw#190291); 177fe32 feat(models): preserve inference capabilities in opt-in catalog v3 (openclaw#189678); 7faf32d feat: retain repository disk authority through recovery (openclaw#189106); a658df3 feat(database): capture externally quiesced SQLite migrations; 0f9e7f7 feat(database): capture exact SQLite migration capsules; 4fb684e feat(backup): add PostgreSQL local companion checkpoints; c89a101 fix(doctor): migrate auth profiles on PostgreSQL stores (openclaw#189639); 799de09 fix(ci): split oversized workspace and setup files (openclaw#189356); 21ee847 fix(acp): keep completed run conversations resumable (openclaw#189273); fce0e56 perf(sessions): open cold history without restoring archives (schema 39) (openclaw#188397)

Validation: Baseline1 NUL-binding assertion failure/21passing; candidate22/22passes (188693-green.log). Real SQLite Doctor path and generated SQL proved; no native PostgreSQL server execution claimed.

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 0895146d8c1493146f5c6461eee0b10c329bdd1e)
(cherry picked from commit f8ccaa70bc9773d6bbb569bc0e275eee0c544ead)
obviyus added a commit that referenced this pull request Nov 26, 2026
…hority (#203464, #203463) (#205757)

## Problem

Two issues reported possible admission gaps from static reads of `main`:

- #203464: a queued channel message could be silently lost after a Gateway restart, because native channel staging saves no operator recovery source and startup replay cancels such a row as `restart-unrecoverable`.
- #203463: a collected group batch could run with the last sender's owner rights when one message has no channel admission evidence (`resolveCollectedRun` in `src/auto-reply/reply/queue/drain.ts` returns the source run for unknown evidence).

Neither has a regression test for the reported scenario.

## Change

Test-only. Production code is unchanged (+0/−0).

1. `dispatch-from-config.pending-restart.test.ts`: a Discord message is staged by a native-shaped recorder (channel `observation` sender, channel source turn key, no operator source). The test runs Gateway shutdown preservation, then the real startup replay `continueSessionQueuedInputs`. The replay ends the row as `restart-unrecoverable` (as the issue says). Then the durable ingress redelivers the same message under a fresh run id: the recorder reclaims the cancelled row (`reclaimCancelledSourceTurn`, `isRetryableSessionPendingInputEndCause`), `dispatchReplyFromConfig` runs it through normal reply admission, and the transcript holds the message exactly once.
2. `queue.collect-sender-authority.test.ts` (new file; `queue.collect.test.ts` is at its line cap): in one group (collect mode, identity audit on), a guest message without admission evidence is queued, then an owner message with evidence. The guest text never runs in the owner's batch and never runs with `senderIsOwner: true`.

## Why no fix

- #203464: Discord, Telegram and the other durable-ingress channels keep the message in ingress custody until turn adoption (`docs/concepts/queue.md`, "Channel messages retained by durable ingress remain retryable…"; `ingress-monitor.test.ts` "defers a claimed event across restart drain…"). The Gateway replay refusal is not the end of the message: the redelivery reclaims the row (since #193602 and #200533, both before the issue). No OA2 PR changed this; the issue's chain stopped at the Gateway replay and missed the ingress redelivery.
- #203463: the collect storage key (`resolveFollowupAuthorizationKey`, `src/auto-reply/reply/queue/delivery-context.ts`) includes the requester principal, `senderId`, `senderE164` and `senderIsOwner` (since #122863 / #152460). An owner and a non-owner never share a collected claim, so the "return source" branch only sees items with the same sender and owner bit. Making that branch strip authority would remove owner tools from a single owner's batch when identity audit is off (no evidence is minted then), which is a UX regression with no security gain.

## Evidence

- Both tests pass on `main` `e4517b0ef2f4`.
- Red when the guarding code is removed (local mutation, reverted):
  - `resolveFollowupAuthorizationKey` returning a constant → #203463 test fails: `expected '[Queued messages while agent was busy…' not to contain 'owner message'`.
  - `isRetryableSessionPendingInputEndCause` without `restart-unrecoverable` → #203464 test fails: `Pending input idempotency key conflicts with the accepted input` (the redelivered message would be refused).
- One-admission E2E on the exact head `aa63024ad82d`: Q, R, S pass (`verdict.json` + `results.jsonl`: https://gist.github.com/obviyus/9dfe6c3b490daebc5442b456a46e10d1).

Closes #203463
Closes #203464

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 27, 2026
…hority (openclaw#203464, openclaw#203463) (openclaw#205757)

## Problem

Two issues reported possible admission gaps from static reads of `main`:

- openclaw#203464: a queued channel message could be silently lost after a Gateway restart, because native channel staging saves no operator recovery source and startup replay cancels such a row as `restart-unrecoverable`.
- openclaw#203463: a collected group batch could run with the last sender's owner rights when one message has no channel admission evidence (`resolveCollectedRun` in `src/auto-reply/reply/queue/drain.ts` returns the source run for unknown evidence).

Neither has a regression test for the reported scenario.

## Change

Test-only. Production code is unchanged (+0/−0).

1. `dispatch-from-config.pending-restart.test.ts`: a Discord message is staged by a native-shaped recorder (channel `observation` sender, channel source turn key, no operator source). The test runs Gateway shutdown preservation, then the real startup replay `continueSessionQueuedInputs`. The replay ends the row as `restart-unrecoverable` (as the issue says). Then the durable ingress redelivers the same message under a fresh run id: the recorder reclaims the cancelled row (`reclaimCancelledSourceTurn`, `isRetryableSessionPendingInputEndCause`), `dispatchReplyFromConfig` runs it through normal reply admission, and the transcript holds the message exactly once.
2. `queue.collect-sender-authority.test.ts` (new file; `queue.collect.test.ts` is at its line cap): in one group (collect mode, identity audit on), a guest message without admission evidence is queued, then an owner message with evidence. The guest text never runs in the owner's batch and never runs with `senderIsOwner: true`.

## Why no fix

- openclaw#203464: Discord, Telegram and the other durable-ingress channels keep the message in ingress custody until turn adoption (`docs/concepts/queue.md`, "Channel messages retained by durable ingress remain retryable…"; `ingress-monitor.test.ts` "defers a claimed event across restart drain…"). The Gateway replay refusal is not the end of the message: the redelivery reclaims the row (since openclaw#193602 and openclaw#200533, both before the issue). No OA2 PR changed this; the issue's chain stopped at the Gateway replay and missed the ingress redelivery.
- openclaw#203463: the collect storage key (`resolveFollowupAuthorizationKey`, `src/auto-reply/reply/queue/delivery-context.ts`) includes the requester principal, `senderId`, `senderE164` and `senderIsOwner` (since openclaw#122863 / openclaw#152460). An owner and a non-owner never share a collected claim, so the "return source" branch only sees items with the same sender and owner bit. Making that branch strip authority would remove owner tools from a single owner's batch when identity audit is off (no evidence is minted then), which is a UX regression with no security gain.

## Evidence

- Both tests pass on `main` `cb5ec7a5bab0`.
- Red when the guarding code is removed (local mutation, reverted):
  - `resolveFollowupAuthorizationKey` returning a constant → openclaw#203463 test fails: `expected '[Queued messages while agent was busy…' not to contain 'owner message'`.
  - `isRetryableSessionPendingInputEndCause` without `restart-unrecoverable` → openclaw#203464 test fails: `Pending input idempotency key conflicts with the accepted input` (the redelivered message would be refused).
- One-admission E2E on the exact head `aa63024ad82d`: Q, R, S pass (`verdict.json` + `results.jsonl`: https://gist.github.com/obviyus/9dfe6c3b490daebc5442b456a46e10d1).

Closes openclaw#203463
Closes openclaw#203464

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot added a commit that referenced this pull request Nov 28, 2026
…on retry

The submitted-input comparison discarded the pending row's disposition,
and a matching RAM fingerprint could replay success before reading the row.
Check the retained row before choosing a retry response so unconsumed
cancellation cannot look delivered. Report queued work as in flight only
with existing custody, without readmitting external retries.

Source commit: 703c82d
Source PR: #200533
Reference commit: 7edc997
Reference PR: #201399

Release adaptation: Hand-port only the read-only retry decision through the
existing SQLite and actor-memory snapshots. Use the schema-42 consumed link
and legacy Stop/dismissal flags instead of new end-cause columns. Do not port
crash replay, new abort-marker metadata, cancellation reopening, migrations,
or UI/protocol changes. Keep the exact graceful-replay admission bypass and
leave consumed, transcript, and completion idempotence intact.

Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts security-sensitive-changed size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant