Skip to content

refactor(gateway): wake restored processes and channel-owner work as their requester - #205129

Merged
obviyus merged 3 commits into
mainfrom
refactor/oa2-durable-source
Nov 25, 2026
Merged

obviyus merged 3 commits into
mainfrom
refactor/oa2-durable-source

Conversation

@obviyus

@obviyus obviyus commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

A background command that exits after a Gateway restart wakes its chat under the wrong person.

  • A durable process record (and the record of an ordinary wake-armed process the restart lost) saved no requester. At exit, the wake ran as the session principal:
    • A member's job in the owner's session finished with the owner's power.
    • An admin's job in another person's session failed with "Session principal has no current run authority".
  • A configured channel owner (commands.ownerAllowFrom, for example a Discord owner) recorded no source at all (captureQueuedOperatorRecoverySource returned nothing). After a restart, their owed or queued work lost the owner grant.

Fix

The fix follows the OA2 storage decision: store the requester's source on the work item and admit it again when the work starts.

  1. Durable process record. record_json now holds the requester's QueuedOperatorRecoverySource, for both durable and ordinary kinds.
    • The source comes from the target captured at exec start. Nothing is stored when capture is unavailable.
    • Incognito sessions still never write a row.
    • At exit, the restored process admits that source again (restoreGatewayQueuedOperatorRecovery, then captureSessionEventTargetForHost). This is the same function the restart replay of owed rows uses; captureOwedRequesterTarget now serves both paths.
    • The source is copied into the owed row's originFacts, so a second restart follows the same requester.
    • If the requester's access ended, the stored result is withheld with its cause (revoked). It stays visible in the chat as not run; it is never dropped.
  2. Channel owner. queuedSourceSchema gets { kind: "channel-owner", sender: { channelId, accountId, senderId } }. captureQueuedOperatorRecoverySource returns it for a configured channel owner. Restore runs decideChannelOwnerPrincipal(config, sender) again, then decideOperatorAdmission (live facts).
    • A sender no longer in ownerAllowFrom is refused, with a cause the user can see.
    • Same-process work keeps its live authority, as before.
    • Nothing is written to the session operatorSources store, so in a shared guild session a member's job never borrows the owner's grant.

Comments updated: bash-durable-process-store.ts:13, operator-run-recovery-source.ts:28, bash-process-durable-notify.ts, initializeDurableProcesses. Docs updated: docs/gateway/background-process.md, docs/reference/database-schemas/layout.md.

Decisions

  • Old rows: no migration. A process record or owed row written before this change has no source. It wakes as the session principal, as before, until it settles.
  • Deleted sessions: session delete does not remove durable process rows. Durable processes deliberately survive reset and delete (stopSessionExecProcesses), and the row is what lets the registry clean up the unit and its log. So the row stays until the process ends. Its stored source is never admitted: exit-time preparation disarms the wake when the session entry is gone or archived (prepareAdoptedDurableProcessNotification). Ordinary rows are removed, because delete stops ordinary processes and their exit deletes the row.
  • Wider capture: the channel-owner source reaches every existing capture point (owed rows, queue, subagent launch, environment provisioning, scheduled plugin commands). A Discord owner now gets the same answer there as the Control UI owner. This is the intended "same principal, same answer" rule (OA2 DESIGN §1).
  • Production lines: net positive (+142/−45 in src non-test). This PR adds approved stored-source behavior (storage decision, Fable 5.2 consult 2). The replay path in queued-chat-inputs.ts now shares captureOwedRequesterTarget instead of its own copy.
  • Admission lifetime (review rounds 1-2, fixed): a restored requester's admission is held until the wake and its one retry settle. wakeOwedExec now resolves at that point, and both restart callers release then. Before, a participant-limited source (chore: carry and enforce participant limits on admitted runs #204847) was released before the event queue retained it, and the retry reused a released target.

Evidence

  • New test src/gateway/owed-exec-requester.test.ts. All 5 cases fail on base 79e42e0877d9 and pass on head:
    • (a) a member's restored job in an owner session wakes as the member;
    • (b) an admin's restored job in another person's session wakes as the admin;
    • (c) a Discord owner's owed result after a restart, and a restored owner's job at exit, keep the owner grant;
    • (d) a removed owner's result ends cancelled/revoked, and a requester without session write gets the same visible cause;
    • (e) in the same guild session, a member's owed result wakes without the owner grant.
  • Matrix: E11 (durable exec wake) and channel-owner replay cells live in that file; the table test's comment points there.
  • Real isolated Gateway restart, real model (member-restart-proof.ts). admin@ owns the session, and worker@ (role worker: read + write, no admin) starts durable: true sleep 45. The Gateway restarts, the command exits, and the woken turn calls gateway config.get:
    • base 79e42e0877d9: the call returned the config; the wake ran with the session principal's (admin) owner grant;
    • head: "gateway needs the owner's authority, and this turn was not started by the owner. Do not retry gateway." The wake ran as the worker, with no refusal of the wake itself.
  • Live Discord QA bot (live channel driver, live model, real Gateway restart). The driver is the configured ownerAllowFrom owner. It checks that its own turn can call gateway config.get (owner grant), then starts durable: true sleep 75. The Gateway restarts, and the completion turn calls gateway config.get again:
    • base 79e42e0877d9: WAKE MEMBER: gateway needs the owner's authority, and this turn was not started by the owner.
    • head: WAKE OWNER.
  • One-admission E2E Q/R/S pass on each pushed head.

@clawsweeper

clawsweeper Bot commented Nov 25, 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 docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: M labels Nov 25, 2026
…their requester

Durable and lost ordinary process records store the requester's QueuedOperatorRecoverySource; the exit admits it again through restoreGatewayQueuedOperatorRecovery and copies it into the owed row. A refused requester's result is withheld with its cause.
A configured channel owner records a channel-owner source (sender only); restore re-runs decideChannelOwnerPrincipal and refuses a sender removed from commands.ownerAllowFrom. Older rows wake as the session principal.

Co-authored-by: obviyus <[email protected]>
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. impact:auth-provider Auth, provider routing, model choice, or SecretRef resolution may break. impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. labels Nov 25, 2026
@obviyus
obviyus force-pushed the refactor/oa2-durable-source branch from 6e7abc3 to 5c1626e Compare November 25, 2026 06:14
@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. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. 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 25, 2026
@clawsweeper

clawsweeper Bot commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR saves background-process requesters and configured channel-owner identities so restored work runs through requester admission.

Example: Discord owner 111 starts a durable command, then the Gateway restarts before it exits.

  • Before: The completion runs with the session principal's authority.
  • After: The completion restores sender discord:111 and checks current commands.ownerAllowFrom before running.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The direction is valuable, but completion-custody defects and absent runtime and upgrade proof prevent a pass.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A command finishing after restart can resume the conversation as a different person or lose the configured channel owner's authority.
Reason: The maintainer-authored direction restores requester parity using the existing persistence and admission boundaries.

Merge readiness

⛔ Blocked before merge - 4 items remain

Keep this PR open: the requester recovery correction is useful and maintainer-directed, but two introduced lifecycle defects need repair.

Reviewed head: 5c1626e9ce3b66fe1e5801bd7862d5eb1782de89

Before merge

  • [P2] Retain restored authority until the wake queue acquires custody (P2) - For an owed source containing a valid participationCeiling, restoreGatewayQueuedOperatorRecovery returns reference-counted authority from retainGatewayOperatorInvocation. This finally releases its only reference before the caller invokes wakeOwedExec. Capturing a SessionEventTarget does not retain authority, so the real event queue's subsequent authority.retain() throws "Operator invocation was released" and the completion never starts. Previously queued-input replay released admission after synchronous enqueue. Return custody with the target or perform enqueue before releasing it, and exercise the real queue in the regression test.
  • [P2] Preserve pending results during temporary admission outages (P2) - If requester restoration encounters a temporary pairing-store read failure or unavailable policy, admission throws GatewayOperatorAccessUnavailableError. resolvePendingInputEndCause intentionally returns undefined for that recoverable condition, but this fallback converts it to failed and withhold permanently cancels the saved result. Once access evaluation recovers, queued-input replay cannot resume it. Preserve the owed row for deferred recovery on unavailable admission; terminally withhold only errors with a terminal cause.
  • 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 Participant recovery custody - d2699a8: Recovered participant work retains its invitation limits and authority through a reference-counted invocation lifetime.

Findings

  • [P2] [P2] Retain restored authority until the wake queue acquires custody — src/agents/bash-tools.exec-notify.ts:286-287
  • [P2] [P2] Preserve pending results during temporary admission outages — src/agents/bash-tools.exec-notify.ts:431-435

Provenance

  • Participant recovery custody changes intended behavior without addressing why it exists (d2699a8: Recovered participant work retains its invitation limits and authority through a reference-counted invocation lifetime.)

Tests

  • Missing end-to-end proof: Provide redacted Gateway restart evidence showing requester-specific completion execution and revocation, plus a latest-stable upgrade preserving existing process records, settings, and data.
Agent review details

How this fits together

The process registry persists restart facts; exec notifications and queued-input recovery turn saved command results into conversation turns through operator admission.

flowchart TD
  A[Requester starts exec] --> B[Process registry]
  B --> C[Stored process and requester source]
  C --> D[Restored process exits]
  D --> E[Operator admission]
  E --> F[Conversation wake queue]
  E --> G[Visible withheld result]
Loading

Technical review

Best possible solution:

Keep saved-source recovery in the existing owners, retain admission through enqueue, and leave temporarily unavailable results pending for recovery.

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

Current-main source confirms that restored process records lack requester sources and configured channel owners cannot capture one; no product execution was performed during this read-only review.

Is this the best way to solve the issue?

Persisting requester facts and reusing admission is the smallest coherent approach, provided custody survives enqueue and temporary unavailability remains recoverable.

Full review comments:

  • [P2] [P2] Retain restored authority until the wake queue acquires custody — src/agents/bash-tools.exec-notify.ts:286-287
    For an owed source containing a valid participationCeiling, restoreGatewayQueuedOperatorRecovery returns reference-counted authority from retainGatewayOperatorInvocation. This finally releases its only reference before the caller invokes wakeOwedExec. Capturing a SessionEventTarget does not retain authority, so the real event queue's subsequent authority.retain() throws "Operator invocation was released" and the completion never starts. Previously queued-input replay released admission after synchronous enqueue. Return custody with the target or perform enqueue before releasing it, and exercise the real queue in the regression test.
    Confidence: 0.99
  • [P2] [P2] Preserve pending results during temporary admission outages — src/agents/bash-tools.exec-notify.ts:431-435
    If requester restoration encounters a temporary pairing-store read failure or unavailable policy, admission throws GatewayOperatorAccessUnavailableError. resolvePendingInputEndCause intentionally returns undefined for that recoverable condition, but this fallback converts it to failed and withhold permanently cancels the saved result. Once access evaluation recovers, queued-input replay cannot resume it. Preserve the owed row for deferred recovery on unavailable admission; terminally withhold only errors with a terminal cause.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Adopted durable processes and lost ordinary-process notices changes intended behavior with a stated reason (20c1a15: Durable adoption originally restored registry facts and delivered fresh input as the session principal; commit 68971b3 extended restart notices to lost ordinary commands.)
  • Configured channel-owner source capture changes intended behavior with a stated reason (e2a9a6d: The original channel admission change deliberately retained session-principal restart behavior and deferred a durable channel-owner source.)
  • Owed exec requester recovery keeps the original intent (b5af51a: Saved completions restore their requester through admission; adopted processes required a separate persistence change.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit 68971b3 adds src/agents/bash-process-durable.ts:38 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 68971b3c2a53; files: src/agents/bash-process-durable.ts)
  • Josh Lehman: Raw commit d2699a8 adds src/gateway/operator-run-recovery.ts:130 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: d2699a825ce7; files: src/gateway/operator-run-recovery.ts)
  • Peter Steinberger: Raw commit 20c1a15 adds src/agents/bash-process-durable.ts:36 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 20c1a15bb56d; files: src/agents/bash-process-durable.ts)

PR surface

Source +81, Tests +184, Docs +5. Total +270 across 14 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 9 116 35 +81
Tests 3 186 2 +184
Docs 2 14 9 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 316 46 +270

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 merge-risk: 🚨 message-delivery: Premature authority release can prevent restored completion turns, and transient admission failures can permanently suppress their saved results.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • merge-risk: 🚨 message-delivery: Premature authority release can prevent restored completion turns, and transient admission failures can permanently suppress their saved results.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • 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 25, 2026, 1:29 AM ET / 06:29 UTC.

obviyus and others added 2 commits November 25, 2026 12:04
…enqueued

The event queue retains the admitted authority when it takes the occurrence; releasing the admission before enqueue let a participant-limited source fail as released. captureOwedRequesterTarget now returns the release, and both callers release after wakeOwedExec.

Co-authored-by: obviyus <[email protected]>
…etry

wakeOwedExec resolves once its last attempt (including the one retry) settles; both restart callers release the admission then, so a participation-limited source is still retained when the retry enqueues.

Co-authored-by: obviyus <[email protected]>
@obviyus
obviyus merged commit 9a0d83b into main Nov 25, 2026
155 checks passed
@obviyus
obviyus deleted the refactor/oa2-durable-source branch November 25, 2026 07:07
@obviyus

obviyus commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as 9a0d83b.

  • Bug: a background command that exited after a Gateway restart woke its chat as the session principal, not the person who started it. A configured channel owner's saved work also lost the owner grant.
  • Fix: the durable or lost-process record keeps the requester's saved source. The exit admits that source again and copies it into the owed row. A configured channel owner is saved as its sender only and is checked again against commands.ownerAllowFrom. If the requester lost access, the result shows as not run, with its cause.
  • Proof: new test owed-exec-requester.test.ts (5 cases, all fail on base). A real Gateway restart: a member's durable job in an admin's session woke as the member. A live Discord QA bot run: the owner's durable completion after a restart kept the owner grant (base lost it). One-admission E2E Q/R/S pass.

obviyus added a commit that referenced this pull request Nov 25, 2026
… Talk reads grant.owner (OA2 PR 6i) (#205451)

## Problem

OA2 PR 6i (one admission owner, same person same answer).

- A verified channel sender listed in `commands.ownerAllowFrom` whose channel identity is also linked to a non-admin profile got that profile's grant, not the owner grant. The same owner over the Control UI (or unlinked in Discord) is the owner. In Discord, `/status`-class commands said "owner" (command-auth matches the owner list) while the run's owner-only tools were refused (they follow `grant.owner`).
- Talk decided its consult owner bit itself, from the socket's `operator.admin` scope (`talk/client-tool-authority.ts`).

## Fix

- `host-context-builder.ts`: `decideChannelOwnerPrincipal` runs first. A listed verified sender is the owner principal even when linked; an unlisted linked sender keeps its profile's grant, as before. The owner principal records `channelOwner`, so queued, restart and durable work re-admit it against the current owner list (`channel-owner` source, #205129).
- Talk: `resolveTalkAgentConsultAuthority(client)` reads `readGatewayRequestAdmission(client).grant.owner` (the admitted run's grant, else the connection's scopes grant). The local admin-scope check and the duplicate `scopes` argument are deleted (8 callers).
- Lint: `OWNER_PRODUCER_FILES` 16 → 15 (Talk leaves).
- Docs: `gateway/config-channels/commands.md`, `automation/cron-jobs/managing-jobs.md` state the listed-owner rule.

## Decisions (recorded, not asked)

- **Listed owner wins** (one-admission plan, #205232 follow-up (i)): the list is by definition the owners; same grant as the owner's Control UI turn. Sources saved before this change by a linked listed owner (linked-profile `channel` kind) still restore the profile until that work finishes; named, no code.
- **Talk tool context keeps command-auth's owner answer** (Fable 5.2 consult, pick A): `prepareTalkClientToolContext` passes along `resolveCommandAuthorization(...).senderIsOwner`, the same answer the person's `chat.send` turn gets (a Control UI profile id listed in `ownerAllowFrom` is a command owner there too). Removing it from Talk only would make Talk differ from chat. Command-auth's `ownerAllowFrom` match stays the producer for asserted-identity owners and pre-turn senders (#205232); `client-permission-parity` "configured ownership without admin" stays green unchanged.
- **Split (6j):** the plugin requester-owner continuation (`openclaw-plugin-tools`, `tool-factory-context`, `bindRequesterOwnerIdentity` and its `requesterOwner` chain through chat-send, cron creator admission and subagent requester custody, `scheduled-message-invocation`, `message-action-dispatch`, `execution-context-registry`, `openclaw-tools`) is ~15 production files plus tests, over the file cap with this PR. After this PR every verified listed owner carries `grant.owner`; the continuation remains only for asserted-identity owners, which 6j must decide.

## User impact

- A Discord/Telegram (any verified channel) owner listed in `commands.ownerAllowFrom` who also linked a member profile now gets owner-only tools, automation management and PR actions in the channel, the same as the owner in the Control UI.
- Talk: no change for real sockets (the grant from connection scopes equals the old admin check).

## Evidence

- Production (`src` + `scripts`, non-test): +16 / −19.
- Matrix cell `operator-admission.table.test.ts` "channel: listed-linked-owner" (real Gateway, real Discord identity declaration, real ingress and host context builder): **red on base `1bf2147f0a75`** (`owner: false, automations: "self", commands: "none"`), green on head.
- Pre-push: one `ocx test` call over 26 files (touched tests + importers of every changed source and test-support file, `OPENCLAW_NODE_TEST_PLAN_CONTINUE_ON_FAILURE=1`): all green except `gateway.sessions-send-provenance.e2e.test.ts` (collaborative steering refusal), which fails the same way on base `1bf2147f0a75` (not this change; no `ownerAllowFrom` in that test). `pnpm tsgo:core`, `pnpm tsgo:test`, oxlint and oxfmt clean. `pnpm check:changed`: only the main-owned parallels dead exports (`detectParallelsHostIp`, `listVmNames`) fail.
- E2E (one-admission run.sh Q/R/S) on the exact head: see comment.
- Live Discord QA bot: not run. The QA flow cannot create a linked member profile in its scratch Gateway (profiles come only from sign-in; `users.linkChannelIdentity` needs an existing non-owner profile). The matrix cell above runs the same Discord ingress path against a real Gateway.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 26, 2026
…their requester (openclaw#205129)

## Problem

A background command that exits after a Gateway restart wakes its chat under the wrong person.

- A durable process record (and the record of an ordinary wake-armed process the restart lost) saved no requester. At exit, the wake ran as the **session principal**:
  - A member's job in the owner's session finished with the owner's power.
  - An admin's job in another person's session failed with "Session principal has no current run authority".
- A configured channel owner (`commands.ownerAllowFrom`, for example a Discord owner) recorded no source at all (`captureQueuedOperatorRecoverySource` returned nothing). After a restart, their owed or queued work lost the owner grant.

## Fix

The fix follows the OA2 storage decision: store the requester's source on the work item and admit it again when the work starts.

1. **Durable process record.** `record_json` now holds the requester's `QueuedOperatorRecoverySource`, for both `durable` and `ordinary` kinds.
   - The source comes from the target captured at exec start. Nothing is stored when capture is `unavailable`.
   - Incognito sessions still never write a row.
   - At exit, the restored process admits that source again (`restoreGatewayQueuedOperatorRecovery`, then `captureSessionEventTargetForHost`). This is the same function the restart replay of owed rows uses; `captureOwedRequesterTarget` now serves both paths.
   - The source is copied into the owed row's `originFacts`, so a second restart follows the same requester.
   - If the requester's access ended, the stored result is withheld with its cause (`revoked`). It stays visible in the chat as not run; it is never dropped.
2. **Channel owner.** `queuedSourceSchema` gets `{ kind: "channel-owner", sender: { channelId, accountId, senderId } }`. `captureQueuedOperatorRecoverySource` returns it for a configured channel owner. Restore runs `decideChannelOwnerPrincipal(config, sender)` again, then `decideOperatorAdmission` (live facts).
   - A sender no longer in `ownerAllowFrom` is refused, with a cause the user can see.
   - Same-process work keeps its live authority, as before.
   - Nothing is written to the session `operatorSources` store, so in a shared guild session a member's job never borrows the owner's grant.

Comments updated: `bash-durable-process-store.ts:13`, `operator-run-recovery-source.ts:28`, `bash-process-durable-notify.ts`, `initializeDurableProcesses`. Docs updated: `docs/gateway/background-process.md`, `docs/reference/database-schemas/layout.md`.

## Decisions

- **Old rows:** no migration. A process record or owed row written before this change has no source. It wakes as the session principal, as before, until it settles.
- **Deleted sessions:** session delete does not remove durable process rows. Durable processes deliberately survive reset and delete (`stopSessionExecProcesses`), and the row is what lets the registry clean up the unit and its log. So the row stays until the process ends. Its stored source is never admitted: exit-time preparation disarms the wake when the session entry is gone or archived (`prepareAdoptedDurableProcessNotification`). Ordinary rows are removed, because delete stops ordinary processes and their exit deletes the row.
- **Wider capture:** the channel-owner source reaches every existing capture point (owed rows, queue, subagent launch, environment provisioning, scheduled plugin commands). A Discord owner now gets the same answer there as the Control UI owner. This is the intended "same principal, same answer" rule (OA2 DESIGN §1).
- **Production lines:** net positive (+142/−45 in `src` non-test). This PR adds approved stored-source behavior (storage decision, Fable 5.2 consult 2). The replay path in `queued-chat-inputs.ts` now shares `captureOwedRequesterTarget` instead of its own copy.
- **Admission lifetime (review rounds 1-2, fixed):** a restored requester's admission is held until the wake and its one retry settle. `wakeOwedExec` now resolves at that point, and both restart callers release then. Before, a participant-limited source (openclaw#204847) was released before the event queue retained it, and the retry reused a released target.

## Evidence

- New test `src/gateway/owed-exec-requester.test.ts`. All 5 cases fail on base `2719e6162d55` and pass on head:
  - (a) a member's restored job in an owner session wakes as the member;
  - (b) an admin's restored job in another person's session wakes as the admin;
  - (c) a Discord owner's owed result after a restart, and a restored owner's job at exit, keep the owner grant;
  - (d) a removed owner's result ends `cancelled`/`revoked`, and a requester without session write gets the same visible cause;
  - (e) in the same guild session, a member's owed result wakes without the owner grant.
- Matrix: E11 (durable exec wake) and channel-owner replay cells live in that file; the table test's comment points there.
- Real isolated Gateway restart, real model (`member-restart-proof.ts`). `admin@` owns the session, and `worker@` (role `worker`: read + write, no admin) starts `durable: true` `sleep 45`. The Gateway restarts, the command exits, and the woken turn calls `gateway config.get`:
  - base `2719e6162d55`: the call returned the config; the wake ran with the session principal's (admin) owner grant;
  - head: "gateway needs the owner's authority, and this turn was not started by the owner. Do not retry gateway." The wake ran as the worker, with no refusal of the wake itself.
- Live Discord QA bot (live channel driver, live model, real Gateway restart). The driver is the configured `ownerAllowFrom` owner. It checks that its own turn can call `gateway config.get` (owner grant), then starts `durable: true` `sleep 75`. The Gateway restarts, and the completion turn calls `gateway config.get` again:
  - base `2719e6162d55`: `WAKE MEMBER: gateway needs the owner's authority, and this turn was not started by the owner.`
  - head: `WAKE OWNER`.
- One-admission E2E Q/R/S pass on each pushed head.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 26, 2026
… Talk reads grant.owner (OA2 PR 6i) (openclaw#205451)

## Problem

OA2 PR 6i (one admission owner, same person same answer).

- A verified channel sender listed in `commands.ownerAllowFrom` whose channel identity is also linked to a non-admin profile got that profile's grant, not the owner grant. The same owner over the Control UI (or unlinked in Discord) is the owner. In Discord, `/status`-class commands said "owner" (command-auth matches the owner list) while the run's owner-only tools were refused (they follow `grant.owner`).
- Talk decided its consult owner bit itself, from the socket's `operator.admin` scope (`talk/client-tool-authority.ts`).

## Fix

- `host-context-builder.ts`: `decideChannelOwnerPrincipal` runs first. A listed verified sender is the owner principal even when linked; an unlisted linked sender keeps its profile's grant, as before. The owner principal records `channelOwner`, so queued, restart and durable work re-admit it against the current owner list (`channel-owner` source, openclaw#205129).
- Talk: `resolveTalkAgentConsultAuthority(client)` reads `readGatewayRequestAdmission(client).grant.owner` (the admitted run's grant, else the connection's scopes grant). The local admin-scope check and the duplicate `scopes` argument are deleted (8 callers).
- Lint: `OWNER_PRODUCER_FILES` 16 → 15 (Talk leaves).
- Docs: `gateway/config-channels/commands.md`, `automation/cron-jobs/managing-jobs.md` state the listed-owner rule.

## Decisions (recorded, not asked)

- **Listed owner wins** (one-admission plan, openclaw#205232 follow-up (i)): the list is by definition the owners; same grant as the owner's Control UI turn. Sources saved before this change by a linked listed owner (linked-profile `channel` kind) still restore the profile until that work finishes; named, no code.
- **Talk tool context keeps command-auth's owner answer** (Fable 5.2 consult, pick A): `prepareTalkClientToolContext` passes along `resolveCommandAuthorization(...).senderIsOwner`, the same answer the person's `chat.send` turn gets (a Control UI profile id listed in `ownerAllowFrom` is a command owner there too). Removing it from Talk only would make Talk differ from chat. Command-auth's `ownerAllowFrom` match stays the producer for asserted-identity owners and pre-turn senders (openclaw#205232); `client-permission-parity` "configured ownership without admin" stays green unchanged.
- **Split (6j):** the plugin requester-owner continuation (`openclaw-plugin-tools`, `tool-factory-context`, `bindRequesterOwnerIdentity` and its `requesterOwner` chain through chat-send, cron creator admission and subagent requester custody, `scheduled-message-invocation`, `message-action-dispatch`, `execution-context-registry`, `openclaw-tools`) is ~15 production files plus tests, over the file cap with this PR. After this PR every verified listed owner carries `grant.owner`; the continuation remains only for asserted-identity owners, which 6j must decide.

## User impact

- A Discord/Telegram (any verified channel) owner listed in `commands.ownerAllowFrom` who also linked a member profile now gets owner-only tools, automation management and PR actions in the channel, the same as the owner in the Control UI.
- Talk: no change for real sockets (the grant from connection scopes equals the old admin check).

## Evidence

- Production (`src` + `scripts`, non-test): +16 / −19.
- Matrix cell `operator-admission.table.test.ts` "channel: listed-linked-owner" (real Gateway, real Discord identity declaration, real ingress and host context builder): **red on base `9837ccd07e4d`** (`owner: false, automations: "self", commands: "none"`), green on head.
- Pre-push: one `ocx test` call over 26 files (touched tests + importers of every changed source and test-support file, `OPENCLAW_NODE_TEST_PLAN_CONTINUE_ON_FAILURE=1`): all green except `gateway.sessions-send-provenance.e2e.test.ts` (collaborative steering refusal), which fails the same way on base `9837ccd07e4d` (not this change; no `ownerAllowFrom` in that test). `pnpm tsgo:core`, `pnpm tsgo:test`, oxlint and oxfmt clean. `pnpm check:changed`: only the main-owned parallels dead exports (`detectParallelsHostIp`, `listVmNames`) fail.
- E2E (one-admission run.sh Q/R/S) on the exact head: see comment.
- Live Discord QA bot: not run. The QA flow cannot create a linked member profile in its scratch Gateway (profiles come only from sign-in; `users.linkChannelIdentity` needs an existing non-owner profile). The matrix cell above runs the same Discord ingress path against a real Gateway.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 28, 2026
A durable background exec (`durable: true`) completed only when its whole process group was empty. A command that leaves anything running (`nohup helper &`, `cmd &`) exited, but no exit was recorded and the promised wake never came. In a real incident a durable check script exited with code 2; its nohup'd helper kept the group alive, and the owner found out 9 hours later.

- macOS: the launchd wrapper's `drain()` waited for `kill(-pgid, 0)` to fail with ESRCH before it recorded the exit.
- Linux: units ran with `ExitType=cgroup`, which has the same rule.

Ordinary exec already completes when the root command exits and turns leftovers into tracked background sessions. Exec now has one definition of done.

- **macOS wrapper:** records the exit, the group id and the start time when the command itself exits. Stop and timeout still end the whole group (SIGTERM, then SIGKILL after the grace) before the wrapper records, as before. Verified on a real gui domain: launchd leaves the detached group alive at job exit and at `bootout`.
- **Linux unit:** `ExitType=cgroup` is removed. `SuccessExitStatus` lists every exit code and standard signal, because systemd stops (and kills) a unit whose main process fails. `ExecMainCode`/`ExecMainStatus` still carry the real code or signal; `reason` already comes from them. In `active/exited`, `RuntimeMaxSec` no longer applies, which matches ordinary exec (the timeout ends with the root).
- **Leftovers:** both supervisors report them (`survivors`): on Linux, the unit's `cgroup.procs`; on macOS, members of the recorded group that started before the recorded exit. A reused group id is never adopted. The durable `ManagedRun` now exposes `releasesOnRootExit` and `waitForExtinction`, so the existing `settleHostExecDescendants` → `adoptExecSurvivors` owner handles them as it does for ordinary exec:
  - the completion names `pid N (cmd) keeps running as background session …`;
  - `process list` shows them;
  - `process kill`, session reset and Gateway stop end them.

  Gateway-start adoption uses the same function.
- **Unit release:** the release never kills leftovers. On Linux, `cleanup` keeps a unit whose cgroup still holds processes. It is released at the record's retention end or at the next Gateway start. The wake and the recorded result no longer wait for `cleanup`.
- If the wrapper itself was killed, the registry now checks the root pid, not the group. A leftover no longer holds the "outcome unknown" report either.

Removed: the wrapper's wait-for-empty-group drain on natural exit, `ExitType=cgroup`, and the registry's group-alive gating of the supervisor-lost report. No schema, protocol or dependency change. The macOS status file is wrapper-private; old wrappers still running keep their old behavior until they finish.

- A durable command's exit wakes its session within seconds with its real exit code, even when it left processes running.
- Those processes keep running. The completion names them, and they behave like ordinary exec leftovers.
- Accepted asymmetry: leftovers of a durable command, like ordinary leftovers, stop at Gateway stop. Only the root command survives a restart. Keeping them across restarts would need a second owner (exempting them in `stopReleasedProcesses` plus re-adoption at boot).
- Accepted edge cases (named in the code):
  - On Linux, if leftovers outlive the 30-min completed record without a Gateway restart, the empty unit stays loaded (`active/exited`) until the user manager restarts.
  - A root killed by a real-time signal still fails the unit.
  - If leftovers cannot be listed, they keep running untracked.

- **Red on base, green on head** (`src/agents/bash-process-launchd.test.ts`, real wrapper and real processes, `sh -c 'sleep 600 & …; exit 3'`):
  - base: no exit recorded; the test timed out at 120 s;
  - head: exit code 3 recorded in under 1 s, the leftover alive and reported by `read()`.
- **Real E2E, macOS launchd** (scratch Gateway from `dist`, Node 24.22.1, real `openai/gpt-5.5`, isolated state). The agent started `sleep 600 & sleep 3; echo DURABLE_HEAD; exit 3` with `background: true, durable: true` and ended its turn. Results:
  - The wake arrived 4.5 s after `STARTED` (the command runs about 3 s): `Exec completed (salty-re, code 3, 5s): DURABLE_HEAD … pid 95391 (sleep 600) keeps running as background session fast-daisy:…`.
  - The agent replied `SEEN_DURABLE_HEAD 3`.
  - `process list` showed `fast-daisy:… running … sleep 600`, and `process kill` ended pid 95391.
  - No durable launchd job of the run remained. An earlier run also showed Gateway stop ending the leftover.
  - The live Gateway's launchd pid, the set of durable jobs and the live config hash are unchanged.
- **Real systemd 255 `--user` manager** (arm64 Ubuntu 24.04 container, the real `systemdDurableSupervisor`):
  - exit code 3 recorded 1.1 s after launch (the command sleeps 1 s), with `survivors: [sleep 600]` and the leftover alive;
  - `cleanup` keeps the unit while the leftover lives and releases it once empty;
  - stop and `timeoutSeconds` while the root runs still end the whole tree;
  - a root killed by SIGKILL keeps its leftover.
- Targeted tests on the touched files and every test that imports a changed source or `*.test-support.ts`: all pass except `bash-process-durable.test.ts` (ordinary-restart case). It fails with `FsSafeError: private Darwin creation requires native descriptor ACL inspection` and fails identically on the merge base `5750fb88fe02`.

Test lines: +39 −15.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit e80be91)

Release adaptation: Reuse stable truncateCommand for the live-process census and retain the two-second ordinary-exec survivor settle. Add a systemd regression for already-removed unit cleanup. The wrapper status additions remain private and require no database change.

Follow-ups: #205129 is a separate restored requester-authority refactor and is not required for root-exit completion.

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 docs Improvements or additions to documentation gateway Gateway runtime impact:auth-provider Auth, provider routing, model choice, or SecretRef resolution may break. impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. 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. size: M 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