Skip to content

refactor(subagents): own descendant Stop cancellation - #206444

Merged
vincentkoc merged 1 commit into
mainfrom
refactor/gateway-subagent-owner-stop
Nov 27, 2026
Merged

vincentkoc merged 1 commit into
mainfrom
refactor/gateway-subagent-owner-stop

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

What Problem This Solves

The gateway owns descendant Stop orchestration and reads raw subagent rows to select yielded requester cancellation, even though that state belongs to the subagents runtime. This makes gateway, Talk, and the subagents tests depend on a gateway implementation for the same cancellation operation.

Related: #205482, #205940.

User Impact

No intended behavior change. Chat Stop, session Stop, Talk cancellation, native descendant cancellation, and cancellation error reporting retain their existing behavior.

Why This Change Was Made

Move the existing abortControlledSubagents operation into src/agents/subagents/cancel-descendants.ts and migrate all callers directly. The gateway retains only RPC error presentation. The moved function body is unchanged; both gateway re-exports are removed rather than kept as compatibility aliases.

Ownership map

Consumer Needed operation or fact Owner after this change
chat-abort-handler, chat-abort-exact-run, chat-abort-runtime, sessions-abort Cancel the admitted parent's registry, native, and exec descendants; return settled results subagents/cancel-descendants
chat-abort-runtime.types Descendant cancellation result contract Same operation's return type
chat-abort-descendants Present an incomplete cancellation as an RPC error Gateway, consuming the recorded result
Talk and the cancellation benchmark Invoke the same descendant cancellation operation subagents/cancel-descendants

Mechanical caller updates

  • src/talk/agent-run-control.runtime.ts: import path only.
  • test/subagent-progress-telegram-retirement.integration.test.ts: import path only.
  • src/agents/subagents/registry/subagent-control.worker.test.ts: import path only.
  • src/agents/subagents/announce/subagent-announce.requester-settle-cancel.test.ts: import path only, explicitly approved by the coordinator.
  • scripts/perf/agent-deletion-cancellation-measure.ts: type import and default owner path only. Historical baseline extraction instructions remain valid.
  • Gateway cancellation tests and type consumers: direct owner imports; existing assertions remain unchanged.

Scope and overlap

This is the descendant-cancellation slice of the gateway ownership campaign. Dormant-child cancellation and other gateway projections remain follow-ups; this PR does not change their semantics.

Open overlap: #205641 touches the old gateway owner and three abort callers. #206405 touches subagent-control.worker.test.ts; this PR changes only its import. No kill-owner, requester-custody, or announce implementation is changed.

Evidence

  • Base: 04a03bcb5eb42f6fc9af18b2a3f62015421a7291; candidate: 2737f4df8279.
  • The entire relocated function body compares byte-for-byte equal to the base.
  • Formatting and Node syntax checks passed for all 16 changed TypeScript files; git diff --check passed. The normal pre-commit hook passed.
  • The previously reported preserves routed native Stop authority … (consumed-session) case passed in the manual CI run; no fix to that case is claimed.
  • Existing cancellation assertions are preserved. No new tests or test-only seams were added for the relocation.
  • Focused Testbox attempt queued before tests ran. Its allocation was stopped and cleanup confirmed. Exact-head CI supplied the build, typecheck, lint, and dependency checks, which passed. That manual run completed with one failed test job. Normal ready-PR CI completed successfully on the same unchanged head, including its CI gate. This is current-head qualification; it does not prove the earlier shutdown failure was fixed.
  • The checks-node-changed job failed in gateway.compaction-hot-reload.e2e.test.ts during Gateway shutdown: PluginRuntimeCloseRetainedError, caused by Native worker execution owners have not joined. The native failure classifier reports unknown: no matching job on main. These shutdown sources are unchanged by the PR; baseline attribution is not yet established. A focused baseline/head comparison also queued on Testbox and was stopped before execution; no reproduction result is claimed. Failure log.
  • Local autoreview: P0–P2, base 04a03bcb5eb4, head 2737f4df8279, scoped-clean with no actionable findings. Runtime behavior remains deferred to CI.

Measurements

Counts use the same L6-owned gateway production scope before and after, excluding test/support files and L4’s session-restart-resume-* files. Direct registry/announce importers: 37 → 36. All subagent importers: 62 → 66, because four callers now import the named owner operation directly rather than through gateway re-exports. Subagent-mentioning lines: 1,194 → 1,176. Within the original campaign-listed L6 files only, those counts are 36 → 35, 59 → 59, and 911 → 893, respectively.

Within chat-abort-descendants.ts, raw requester/execution/wake decision lines: 4 → 0. Its cancellation function moves to its state owner; cyclomatic complexity is 48 → 48 for that unchanged operation. This is an ownership improvement, not a claim of algorithmic simplification.

Gateway production changes remove 296 lines and add 9; the complete PR is 2 production lines smaller, with no net test-line change. The two obsolete gateway exports have no remaining production consumers.

@vincentkoc vincentkoc self-assigned this Nov 27, 2026
@clawsweeper

clawsweeper Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: L labels Nov 27, 2026
@clawsweeper clawsweeper Bot added the P2 Normal backlog priority with limited blast radius. label Nov 27, 2026
@vincentkoc
vincentkoc marked this pull request as ready for review November 27, 2026 06:51
@vincentkoc
vincentkoc merged commit a9a7c7f into main Nov 27, 2026
317 of 319 checks passed
@vincentkoc
vincentkoc deleted the refactor/gateway-subagent-owner-stop branch November 27, 2026 07:20
@vincentkoc

Copy link
Copy Markdown
Member Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Nov 27, 2026
…restoration-ci-189390-20261127

* commit '6feeb50a3f14fbf0aa5167d342f186dc4d67fc18': (9846 commits)
  fix: stop 2026-11-17 main Git checkouts from half-switching on a schema update (#206341)
  refactor(codex): centralize native completion delivery (#206447)
  fix(subagents): finish claimed stops after session rotation (#206405)
  fix: let owners fork a chat with exec after a subagent or exec completion (#206483)
  test(cli): gate agent --local cold-start processes and workers (#206466)
  perf(ci): skip baseline inventory when line-cap debt is empty (#189909)
  refactor(test): share core process-result fixtures (#174149)
  refactor(ci): reuse canonical budget flag parsing (#189480)
  fix: recover Codex chats after oversized requests (#206475)
  fix(agents): skip the bootstrap ritual in one-shot runs (#206477)
  fix(test): preserve stack coordinates in redacted failure reports (#152384)
  fix(gateway): return consistent unavailable response guidance (#191933)
  fix: preserve emphasis in Markdown table row labels (#205349)
  fix(nextcloud-talk): keep webhook spool helpers private (#206470)
  perf(plugins): overlay native receipts once per visible root (#206464)
  fix: keep GitHub comment approvals alive and skip repeat approval on the session PR (#206129)
  perf(config): retain one snapshot for unchanged validation results (#206465)
  refactor(test): reuse canonical secret fixture cleanup (#189492)
  refactor(subagents): own descendant Stop cancellation (#206444)
  refactor(subagents): keep announce cleanup action type private (#206407)
  ...
obviyus added a commit that referenced this pull request Nov 27, 2026
…lowers their access (#206813)

## Problem

When the creator removes a person from a shared session, or lowers that person's access or role, work the person already started keeps running with the old access until it ends. #206747 removed the old version of this (an abort signal merged into every producer, `assertCurrent()` latches, and re-admission at restart against the current role), because each of these checked authority again from a different source.

Decision (Ayaan, 11-27, after a Fable 5.2 consult): "As soon as the permission is changed, whatever they started stops immediately, and whenever they send a new message, the new permissions are evaluated."

## Fix

There is one new function, `stopWorkStartedBy({ profileId, sessionKey?, stopReason })` in `src/gateway/chat-abort-stop-work.ts`. Only permission writers call it, and only after their write commits.

- **Which writers call it.** The writer itself decides that access was lost, by comparing the old value with the new one in the same write:
  - `session.members.remove`: stops that person's work in that session.
  - `session.members.setAccess` to a lower level (send > suggest > read): stops that person's work in that session. The writer already made this comparison for its reduction event.
  - `users.setRole`, when the new effective role drops an operator scope, an agent or a session permission: stops that person's work in all sessions. The effective role is resolved through `resolveOperatorRoleSelection`, so a GitHub-login assignment counts. Session permissions narrow only along their order: `none` < `view` < `suggest` < `write`, and `none` < `invited` < `write`. Within `invited`, a lower `maxInvitedAccess` (read < suggest < send) narrows; invited tool and permission limits apply to the next request. `invited` against `view`/`suggest`, and any unresolvable role, are not comparable, so they count as a loss. Promotions and equal writes stop nothing; `users-role.access-loss.test.ts` covers this. This adds one `resolveOperatorRoleSelection` reference to `users-role.ts` (`ADMISSION_FILES` 2 → 3). The role writer reads policy as data, which is its job.
- **How it finds work.** It filters the existing active-run map on the requester that admission recorded when the run started (`initiatingPersonalOperator.profileId`). Personal Stop uses the same equality. It does the same for the exec request owners of that person. It reads no role, membership or admission state, and the lint below enforces this. There is no new registry, no persisted state and no schema change.
- **What stops.**
  - Running turns stop through the ordinary exact-run Stop (`stopExactClientRun`). Partial text is kept and persisted, and descendant subagents stop through the owned Stop (#206444).
  - Commands (exec) that this person's requests own are cancelled.
  - Queued input is not touched here. Its own start is admitted again and refused, as before, and member removal still cancels durable queued participation rows in the store transaction.
  - Cron jobs stay, and each fire is admitted again.
- **What everyone in the session sees.** The stopped run uses the existing aborted Stop state with a new reason label, `access-removed` or `access-reduced`. Its partial reply stays and shows as "Interrupted". Then one timeline line appears per affected session: "Stopped N runs started by <name>: their access to this session changed." The line comes from `operator-refusal.ts` and is added as a Gateway-authored assistant message after the partial output. The person's next message gets the existing admission refusal.
  - **Decision (cut):** the brief also asked for a per-run notice addressed to the person ("Stopped: your access … changed. …"). The Control UI E2E showed that the aborted event reaches every viewer, so the **owner** saw "your access to this session changed. Ask the owner for access." That is a false notice. The event does not say who started the run, so the text cannot be targeted without a new protocol field. I dropped the per-run text. The timeline line names the person, so it is true for every viewer.
- **Lint.** `no-operator-permission-read` has a new `stop` check. The stop module fails if it references admission (`decideOperatorAdmission`, `prepareOperatorAdmission`, `decideTurnGrant`), any role-policy reader or a membership reader. A planted fixture proves it.
- **Docs.** The root `AGENTS.md` rule now says: "Check authority one time, when work starts. A writer that removes a named person's access stops the work that person started. All other changes apply to the next request." The `src/gateway/AGENTS.md` operator-admission section and `docs/concepts/multi-user.md` say the same thing.

### Accepted edges (named, no code)

- **Race (ms window).** Admission records the requester after awaited preparation (`retainGatewayOperatorRun` awaits the operator capture before it binds `initiatingPersonalOperator`, and the membership is read in an awaited prepare step). So a run admitted with the old access in the same instant as the write may not be recorded yet, and it finishes. Closing this gap would need fencing or generations, so I did not build it. The gap is named in the module comment.
  - A message accepted just before the write, but not yet running, is admitted again at its own start and refused. The test `never runs a message accepted just before a downgrade with the old access` covers this.
- **Config edits.** Config reload (`commands.ownerAllowFrom`, channel allowlists) and edits to role definitions stop nothing. They apply to the next request.
- **Other writers that already stop work.**
  - OpenClaw ID member removal already cancels the member's runs through `chat.abort` on their connections (`openclaw-id/removal-effects.ts`). I did not change it.
  - Visitor grant revocation already ends runs through the grant's run abort signal. I did not change it.
  - OpenClaw ID `set_role` goes through the canonical profile writer without a request context. I did not wire it.
- **Channel-started runs.** These are controller sources, not entries in the Gateway run map. They finish after a `users.setRole` downgrade, and the person's next channel message is admitted with the new role.
- **Owed rows (durable exec wakes).** These are not cancelled here. Every wake goes through admission and is refused while access is absent; this is the existing behavior (`server.participation-admission.test.ts`, re-admission under current invitation bounds). Cancelling a person's exec owners also stops new exit notices for those commands.
- **Removed person's view.** After a removal, the person's client shows the existing "Session … was not found" and still shows a stale Stop control. Their next message is refused (E2E screenshots). Clearing that stale control is UI work outside this PR.
- **Changed test:** `server.participation-admission.test.ts` expected the held child launch to be refused at its start with "Session not found" after the parent's invitation was removed. Now the removal stops the parent run Carol started, so the child launch ends with that stop. The test now asserts that the child failed, that the parent did not finish `ok`, and that the child made no calls.

Production code: about +200 lines (new module ~140, writers, text, lint), with no deletions. This is a new behavior that was asked for. The version it replaces was already deleted in #206747. Also drops the stale `MINT_FILES` entry for `session-sharing-authorization-async.ts` that #206747 left behind (it made `oxlint-boundary-guards` red on main).

## User impact

- Remove or downgrade an invited person: their running reply stops right away. Partial text is kept and marked "Interrupted", and their child agents and commands end. The session shows "Stopped N runs started by <name>: their access to this session changed."
- Lower a person's role: their running work stops in every session.
- Their next message is checked against the new access. Re-inviting them lets the next message run.
- Promotions and equal writes stop nothing.

## Evidence

- New `src/gateway/server.participation-access-loss.test.ts` runs on a real Gateway with a held streaming provider:
  1. Remove a member while 3 runs stream. Only that person's run in that session stops (`access-removed`, partial text in the aborted event and in the transcript, plus the timeline line). The same person's run in another session and the owner's run both complete. The person's next `chat.send` is refused, with no provider request.
  2. A message accepted just before a downgrade never completes, and the next message is refused.
  3. An equal `setAccess` write and a promotion to `administrator` stop nothing. A role downgrade stops the person's runs in two sessions (`access-reduced`).
- Lint fixture `stop-work-authority-read-violation.ts` (4 findings).
- Pre-push: one `ocx test` run of 83 files (touched tests plus direct importers of changed sources), plus `tsgo:core`, `tsgo:test`, oxfmt and oxlint on the changed files.
- E2E: Control UI on 85ee8dd (later commits change only the `users.setRole` comparison and its unit test); Q/R/S on the final head:
  - Q/R/S `one-admission-e2e`: all pass. R now checks the approved contract: a running turn stops with `access-reduced`. `verdict.json` and `results.jsonl` are in the comment.
  - Control UI, two browsers on a real Gateway: create and invite → the person streams → the owner removes them → the run stops with its partial reply marked "Interrupted", and the session shows "Stopped 1 run started by Carol: their access to this session changed." The person's next message is refused; after re-invite the next message completes; a send→read downgrade stops the run the same way. The owner sees no "your access" notice. Screenshots are in the comment.
  - Nits: the timeline line renders above the interrupted partial, because the partial keeps its run position. After a removal, the person's view still shows a stale Stop control next to "Session … not found".

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

## Problem

When the creator removes a person from a shared session, or lowers that person's access or role, work the person already started keeps running with the old access until it ends. openclaw#206747 removed the old version of this (an abort signal merged into every producer, `assertCurrent()` latches, and re-admission at restart against the current role), because each of these checked authority again from a different source.

Decision (Ayaan, 11-27, after a Fable 5.2 consult): "As soon as the permission is changed, whatever they started stops immediately, and whenever they send a new message, the new permissions are evaluated."

## Fix

There is one new function, `stopWorkStartedBy({ profileId, sessionKey?, stopReason })` in `src/gateway/chat-abort-stop-work.ts`. Only permission writers call it, and only after their write commits.

- **Which writers call it.** The writer itself decides that access was lost, by comparing the old value with the new one in the same write:
  - `session.members.remove`: stops that person's work in that session.
  - `session.members.setAccess` to a lower level (send > suggest > read): stops that person's work in that session. The writer already made this comparison for its reduction event.
  - `users.setRole`, when the new effective role drops an operator scope, an agent or a session permission: stops that person's work in all sessions. The effective role is resolved through `resolveOperatorRoleSelection`, so a GitHub-login assignment counts. Session permissions narrow only along their order: `none` < `view` < `suggest` < `write`, and `none` < `invited` < `write`. Within `invited`, a lower `maxInvitedAccess` (read < suggest < send) narrows; invited tool and permission limits apply to the next request. `invited` against `view`/`suggest`, and any unresolvable role, are not comparable, so they count as a loss. Promotions and equal writes stop nothing; `users-role.access-loss.test.ts` covers this. This adds one `resolveOperatorRoleSelection` reference to `users-role.ts` (`ADMISSION_FILES` 2 → 3). The role writer reads policy as data, which is its job.
- **How it finds work.** It filters the existing active-run map on the requester that admission recorded when the run started (`initiatingPersonalOperator.profileId`). Personal Stop uses the same equality. It does the same for the exec request owners of that person. It reads no role, membership or admission state, and the lint below enforces this. There is no new registry, no persisted state and no schema change.
- **What stops.**
  - Running turns stop through the ordinary exact-run Stop (`stopExactClientRun`). Partial text is kept and persisted, and descendant subagents stop through the owned Stop (openclaw#206444).
  - Commands (exec) that this person's requests own are cancelled.
  - Queued input is not touched here. Its own start is admitted again and refused, as before, and member removal still cancels durable queued participation rows in the store transaction.
  - Cron jobs stay, and each fire is admitted again.
- **What everyone in the session sees.** The stopped run uses the existing aborted Stop state with a new reason label, `access-removed` or `access-reduced`. Its partial reply stays and shows as "Interrupted". Then one timeline line appears per affected session: "Stopped N runs started by <name>: their access to this session changed." The line comes from `operator-refusal.ts` and is added as a Gateway-authored assistant message after the partial output. The person's next message gets the existing admission refusal.
  - **Decision (cut):** the brief also asked for a per-run notice addressed to the person ("Stopped: your access … changed. …"). The Control UI E2E showed that the aborted event reaches every viewer, so the **owner** saw "your access to this session changed. Ask the owner for access." That is a false notice. The event does not say who started the run, so the text cannot be targeted without a new protocol field. I dropped the per-run text. The timeline line names the person, so it is true for every viewer.
- **Lint.** `no-operator-permission-read` has a new `stop` check. The stop module fails if it references admission (`decideOperatorAdmission`, `prepareOperatorAdmission`, `decideTurnGrant`), any role-policy reader or a membership reader. A planted fixture proves it.
- **Docs.** The root `AGENTS.md` rule now says: "Check authority one time, when work starts. A writer that removes a named person's access stops the work that person started. All other changes apply to the next request." The `src/gateway/AGENTS.md` operator-admission section and `docs/concepts/multi-user.md` say the same thing.

### Accepted edges (named, no code)

- **Race (ms window).** Admission records the requester after awaited preparation (`retainGatewayOperatorRun` awaits the operator capture before it binds `initiatingPersonalOperator`, and the membership is read in an awaited prepare step). So a run admitted with the old access in the same instant as the write may not be recorded yet, and it finishes. Closing this gap would need fencing or generations, so I did not build it. The gap is named in the module comment.
  - A message accepted just before the write, but not yet running, is admitted again at its own start and refused. The test `never runs a message accepted just before a downgrade with the old access` covers this.
- **Config edits.** Config reload (`commands.ownerAllowFrom`, channel allowlists) and edits to role definitions stop nothing. They apply to the next request.
- **Other writers that already stop work.**
  - OpenClaw ID member removal already cancels the member's runs through `chat.abort` on their connections (`openclaw-id/removal-effects.ts`). I did not change it.
  - Visitor grant revocation already ends runs through the grant's run abort signal. I did not change it.
  - OpenClaw ID `set_role` goes through the canonical profile writer without a request context. I did not wire it.
- **Channel-started runs.** These are controller sources, not entries in the Gateway run map. They finish after a `users.setRole` downgrade, and the person's next channel message is admitted with the new role.
- **Owed rows (durable exec wakes).** These are not cancelled here. Every wake goes through admission and is refused while access is absent; this is the existing behavior (`server.participation-admission.test.ts`, re-admission under current invitation bounds). Cancelling a person's exec owners also stops new exit notices for those commands.
- **Removed person's view.** After a removal, the person's client shows the existing "Session … was not found" and still shows a stale Stop control. Their next message is refused (E2E screenshots). Clearing that stale control is UI work outside this PR.
- **Changed test:** `server.participation-admission.test.ts` expected the held child launch to be refused at its start with "Session not found" after the parent's invitation was removed. Now the removal stops the parent run Carol started, so the child launch ends with that stop. The test now asserts that the child failed, that the parent did not finish `ok`, and that the child made no calls.

Production code: about +200 lines (new module ~140, writers, text, lint), with no deletions. This is a new behavior that was asked for. The version it replaces was already deleted in openclaw#206747. Also drops the stale `MINT_FILES` entry for `session-sharing-authorization-async.ts` that openclaw#206747 left behind (it made `oxlint-boundary-guards` red on main).

## User impact

- Remove or downgrade an invited person: their running reply stops right away. Partial text is kept and marked "Interrupted", and their child agents and commands end. The session shows "Stopped N runs started by <name>: their access to this session changed."
- Lower a person's role: their running work stops in every session.
- Their next message is checked against the new access. Re-inviting them lets the next message run.
- Promotions and equal writes stop nothing.

## Evidence

- New `src/gateway/server.participation-access-loss.test.ts` runs on a real Gateway with a held streaming provider:
  1. Remove a member while 3 runs stream. Only that person's run in that session stops (`access-removed`, partial text in the aborted event and in the transcript, plus the timeline line). The same person's run in another session and the owner's run both complete. The person's next `chat.send` is refused, with no provider request.
  2. A message accepted just before a downgrade never completes, and the next message is refused.
  3. An equal `setAccess` write and a promotion to `administrator` stop nothing. A role downgrade stops the person's runs in two sessions (`access-reduced`).
- Lint fixture `stop-work-authority-read-violation.ts` (4 findings).
- Pre-push: one `ocx test` run of 83 files (touched tests plus direct importers of changed sources), plus `tsgo:core`, `tsgo:test`, oxfmt and oxlint on the changed files.
- E2E: Control UI on 85ee8dd (later commits change only the `users.setRole` comparison and its unit test); Q/R/S on the final head:
  - Q/R/S `one-admission-e2e`: all pass. R now checks the approved contract: a running turn stops with `access-reduced`. `verdict.json` and `results.jsonl` are in the comment.
  - Control UI, two browsers on a real Gateway: create and invite → the person streams → the owner removes them → the run stops with its partial reply marked "Interrupted", and the session shows "Stopped 1 run started by Carol: their access to this session changed." The person's next message is refused; after re-invite the next message completes; a send→read downgrade stops the run the same way. The owner sees no "your access" notice. Screenshots are in the comment.
  - Nits: the timeline line renders above the interrupted partial, because the partial keeps its run position. After a removal, the person's view still shows a stale Stop control next to "Session … not found".

Co-authored-by: Ayaan Zaidi <[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 gateway Gateway runtime P2 Normal backlog priority with limited blast radius. scripts Repository scripts size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant