Skip to content

feat(subagents): warn when live children share an explicit working directory - #197123

Open
zeroaltitude wants to merge 37 commits into
openclaw:mainfrom
zeroaltitude:feat/subagent-shared-cwd-advisory
Open

zeroaltitude wants to merge 37 commits into
openclaw:mainfrom
zeroaltitude:feat/subagent-shared-cwd-advisory

Conversation

@zeroaltitude

@zeroaltitude zeroaltitude commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Supersedes #135480 (auto-closed for inactivity; branch re-merged with current main).

What Problem This Solves

Two live subagents explicitly pointed at one checkout can overwrite each other's uncommitted files and move the same Git HEAD. subagents list showed both runs but gave the parent no collision signal, so a parent coordinating concurrent children had no way to see that two of them were writing to the same directory. The signal has to cover native and ACP children, canonicalize aliases, and stay bounded at supported swarm sizes — an unbounded warning would itself consume the model context it is meant to protect.

Why This Change Was Made

  • Persist an explicit ACP cwd through the same resolveExplicitSpawnedCwd() contract native children already use.
  • Report only directories a spawn request actually chose. A run that inherited its workspace is exempt, and so is a sender-restricted helper that was handed the requester's root by policy — both are expected sharing with nothing for an operator to change. The discriminator is already persisted: senderRestricted is ctx.inheritedToolPolicySource === "sender" at both owners, and both owners refuse any cwd that is not the requester root for such a sender, so a restricted helper's spawnedCwd is always the policy root and never a chosen directory. inheritedToolPolicySource is a hot SessionEntry field the advisory already reads, so no new field crosses a Gateway boundary and no protocol closedObject changes.
  • Group only live, unended runs by the directory the child is actually using — SessionEntry.acp.cwd when the ACP backend reported one, spawnedCwd otherwise — with canonical on-disk identity and a lexical fallback when a recorded directory no longer resolves.
  • Read the child metadata the list builder has already selected, under the same key the selection is stored by; the advisory performs no session I/O of its own.
  • Emit each shared directory once in a bounded top-level summary. Only the sampled member rows carry sharedCwdGroupId; all other rows are unchanged.
  • Cap the advisory at eight groups, three sampled run IDs per group, and 72 characters per displayed path, with sharedCwdGroupTotal and each group's runCount preserving exact counts even when display details are omitted. Order by stable keys before the caps apply, so identical live state always produces identical output.
  • Surface the same bounded summary through both the structured subagents tool and native /subagents text.

The advisory is informational; it does not refuse or cancel a spawn.

Why the exemption is reader-side rather than at the spawn owners. The obvious owner-side shape — clearing the inherited cwd to mark explicitness — breaks the restriction that put it there: prepare.ts resolves a session's run cwd from spawnedCwd, so clearing it drops a restricted helper back to resolveAgentRunCwd and out of the guarded root. Both approaches were built and measured separately rather than argued (controls below).

User Impact

One shared directory produces one summary and at most three row references regardless of child count. A 50-child case split across 25 colliding directories reports the exact total but emits only eight summaries, and the same eight every time. A collect swarm inheriting one workspace, and a restricted sender's helpers confined to that sender's root, both stay silent. An operator can identify concurrent writers without the warning growing with the swarm.

Evidence

Tested head: 3bc860565be95faa6c1d0ef40da0cfdff12a640a (= origin/feat/subagent-shared-cwd-advisory). Everything below was measured today, 2026-11-13, not carried over from an earlier body. The Round 3, Round 2 and Round 1 captures were taken at the parent 9a861a7aebe18f897bce634f5232f740104916ea; 3bc860565be changes exactly one file — the committed proof harness scripts/proof-135480-subagent-shared-cwd-advisory.ts, for review feedback on its path assertions — and no runtime source, so those captures still describe this head's production code. The harness itself was re-run at this head; see "Proof-harness portability" below.

Round 3 — the installed production Gateway, real spawns, the shipped subagents tool

This capture is from the operator's long-running production Gateway (a systemd user service, built dist, started 2026-11-12 22:26 MST), not from a script. That build is a fork integration commit (59fa16a3c82) that carries this branch; the five runtime source files this PR changes (src/agents/spawned-context.ts, src/agents/subagents/registry/subagent-list.ts, src/agents/subagents/spawn/acp-spawn.ts, src/agents/tools/subagents-tool.ts, src/auto-reply/reply/commands-subagents/action-list.ts) are byte-identical there to tested head 3bc860565be (git diff --quiet per file; the latest commit changes only the proof script).

From a Discord direct session, the agent spawned real children with the shipped sessions_spawn tool and then called the shipped subagents tool with action: "list". Children A and B were given cwd: /tmp/r3-shared-cwd/work, child C cwd: /tmp/r3-shared-cwd/other, and six unrelated working children had no cwd (inherited workspace). A ran on the Claude CLI runtime and B on the embedded runtime (an OpenRouter model), so the group spans two runtimes. Output is trimmed to the relevant fields; nothing else was edited.

Shared directory, different directory, and inherited workspace in one listing (2026-11-13 14:02:53 MST):

{"status":"ok","action":"list","total":65,
 "sharedCwdGroupTotal":1,
 "sharedCwdGroups":[{"id":1,"path":"/tmp/r3-shared-cwd/work","runCount":2,
   "runIds":["4e9bcf19-3d98-4be1-aa05-17b9f6c03f66","659cc68d-bf7c-4c64-a17b-21c1e28f2305"]}],
 "active":[
  {"index":1,"runId":"4ee2e2ed-…","taskName":"cwdprobe-c3","status":"running","model":"deepseek/deepseek-v4-flash"},
  {"index":2,"runId":"659cc68d-…","taskName":"cwdprobe-b3","status":"running","model":"deepseek/deepseek-v4-flash","sharedCwdGroupId":1},
  {"index":3,"runId":"4e9bcf19-…","taskName":"cwdprobe-a","status":"running","model":"anthropic/claude-haiku-4-5","sharedCwdGroupId":1},
  {"index":4,"taskName":"rankup3-197114","status":"running"},
  {"index":5,"taskName":"rankup3-197116","status":"running"},
  {"index":6,"taskName":"rankup3-197123","status":"running"},
  {"index":7,"taskName":"rankup3-197115","status":"running"},
  {"index":8,"taskName":"rankup3-197118","status":"running"},
  {"index":9,"taskName":"rankup3-160325","status":"running"}]}

The text field of the same result, which is what the model reads:

active subagents:
1. cwdprobe-c3: cwd probe C (other dir) (deepseek-v4-flash, 11s, tokens 25k context) running - This is a short liveness probe. …
2. cwdprobe-b3: cwd probe B (shared dir) (deepseek-v4-flash, 11s, tokens 25k context) running - This is a short liveness probe. … [shared cwd group 1]
3. cwdprobe-a: cwd probe A (shared dir) (claude-haiku-4-5, 1m10s) running - This is a short liveness probe. … [shared cwd group 1]
4. rankup3-197114: … (claude-opus-5, 3m37s) running - …
   (rows 5–9: five more inherited-workspace children, no marker)

shared working directories (1/1 shown):
[cwd 1] 2 live runs: /tmp/r3-shared-cwd/work (sample: 4e9bcf19-3d98-4be1-aa05-17b9f6c03f66, 659cc68d-bf7c-4c64-a17b-21c1e28f2305)

Read against the three cases the review named: the two children that were explicitly given the same directory form one group and both rows carry the reference; the child in a different explicit directory is not grouped; the six children that inherited the workspace are not grouped even though they all share it.

Ended peer (14:01:50 MST, one minute earlier, same session): an earlier attempt at child B, with the same cwd: /tmp/r3-shared-cwd/work, had its turn refused by a host capacity limit and ended after about one second. With A still running and that peer ended, the listing reported no group:

{"status":"ok","action":"list","total":63,"sharedCwdGroupTotal":0,"sharedCwdGroups":[],
 "active":[{"index":1,"runId":"4e9bcf19-…","taskName":"cwdprobe-a","status":"running"}, "…six inherited-workspace children…"],
 "recent":[{"index":9,"runId":"a52ee988-…","taskName":"cwdprobe-b","status":"failed","runtimeMs":1105}]}

Real ACP spawns on the same Gateway (2026-11-13 14:33 MST). Two children were started with the shipped sessions_spawn tool using runtime: "acp" (the Claude Code ACP agent) and cwd: /tmp/r3-shared-cwd/work, so they went through the production ACP spawn path, not constructed records. A native child was running in /tmp/r3-shared-cwd/other, and two earlier ACP children given the same shared directory had already ended. The subagents listing taken right after the spawns, trimmed to the relevant fields:

{"status":"ok","action":"list","total":72,
 "sharedCwdGroupTotal":1,
 "sharedCwdGroups":[{"id":1,"path":"/tmp/r3-shared-cwd/work","runCount":2,
   "runIds":["30a5973c-b7f2-4154-98a8-b91c2fcc2310","a796d3ac-36eb-4789-956d-8bb8c71cb65a"]}],
 "active":[
  {"index":1,"runId":"30a5973c-…","sessionKey":"agent:tank:acp:2c03730d-…","taskName":"cwdprobe-acp-b3","status":"running","sharedCwdGroupId":1},
  {"index":2,"runId":"a796d3ac-…","sessionKey":"agent:tank:acp:1f33dd0c-…","taskName":"cwdprobe-acp-a3","status":"running","sharedCwdGroupId":1},
  {"index":3,"runId":"0537c8cb-…","sessionKey":"agent:tank:subagent:40696691-…","taskName":"cwdprobe-native-d","status":"running"},
  "…three inherited-workspace children, no marker…"],
 "recent":[
  {"index":7,"runId":"cfe9f65b-…","sessionKey":"agent:tank:acp:e3a196fc-…","taskName":"cwdprobe-acp-b2","status":"failed"},
  {"index":8,"runId":"308141bf-…","sessionKey":"agent:tank:acp:935de90c-…","taskName":"cwdprobe-acp-a2","status":"failed"}]}
active subagents:
1. cwdprobe-acp-b3: cwd probe ACP B (shared dir) (model n/a, 176ms) running - … [shared cwd group 1]
2. cwdprobe-acp-a3: cwd probe ACP A (shared dir) (model n/a, 3s) running - … [shared cwd group 1]
3. cwdprobe-native-d: cwd probe native D (other dir) (deepseek-v4-flash, 1m19s, tokens 22k context) running - …
…
shared working directories (1/1 shown):
[cwd 1] 2 live runs: /tmp/r3-shared-cwd/work (sample: 30a5973c-b7f2-4154-98a8-b91c2fcc2310, a796d3ac-36eb-4789-956d-8bb8c71cb65a)

The two live ACP children are grouped by the directory their ACP spawn recorded; the ended ACP children that had the same directory, and the native child in another directory, are not. One listing taken twelve seconds after an earlier pair of ACP spawns showed no group because both of those children had already finished; that is the ended-peer rule, and it is why this capture was taken immediately after the spawns.

What this capture does not cover: the /subagents list slash command was not typed by a person during the capture (the tool's text field above comes from the same list builder; the slash renderer's output is in the Round 2 Gateway run below), and it is not an upgrade from the latest stable release: this Gateway's session store was written by successive fork integration builds, so the stored-data evidence for the newly populated ACP spawnedCwd field remains the two-tree run below.

Round 2 — real behavior proof through a RUNNING GATEWAY, the shipped tool, and base-stored data

The review asked for two things the earlier proof did not cover: output through a running Gateway including the shipped tool and slash command, and evidence that session data stored by earlier code still loads and works on this head. Both are below. Captured at head 9a861a7aebe18f897bce634f5232f740104916ea (the parent of the current head).

Command

node --import ./scripts/tsx.mjs scripts/proof-197123-gateway-shared-cwd.ts /tmp/base-store-197123
# exit 0 — 14/14 assertions, "All runtime assertions passed."

A real Gateway is started first, with isolated state

── phase 0: start a REAL Gateway in-process ──
   resolved state dir=/tmp/oc-proof-197123-wTuQQq/state
[gateway] http server listening (21 plugins: acpx, anthropic, browser, canvas, cua-computer, deep-research,
  device-pair, file-transfer, geolocation, github, google-meet, linux-node, llama-cpp, memory-core, ollama,
  openai, skill-workshop, talk-voice, teams-meetings, xai, zoom-meetings; 118.0s)
[gateway] ready
   gateway startup took 232498 ms
   gateway listening on loopback port 19071
   ✓ the Gateway reports a live server handle

startGatewayServer() runs with bind: "loopback", a random token and controlUiEnabled: false against a throwaway OPENCLAW_STATE_DIR / OPENCLAW_HOME / OPENCLAW_CONFIG_PATH under /tmp; the script aborts if the resolved state dir is not inside its own temp root, so no production state and no live Gateway is involved. This is load-bearing, not decoration: offline, createSubagentsTool().execute("list") never returns, because createSubagentControllerRead().prepare() has no admitted Gateway capability source. A passing run is itself evidence the Gateway is live.

The shipped model-facing subagents tool and the real /subagents command

── phase 1: two live children explicitly share one directory ──
   shipped tool payload keys: status,action,requesterSessionKey,callerSessionKey,callerIsSubagent,
     total,sharedCwdGroupTotal,sharedCwdGroups,active,recent,text
   shipped tool: total=2 sharedCwdGroupTotal=1 groups=[{"id":1,"path":"/tmp/oc-proof-197123-wTuQQq/p1-shared-checkout","runCount":2,"runIds":["run-shared-a","run-shared-b"]}]
   ✓ the shipped subagents tool reports exactly one shared-directory group
   ✓ both model-visible rows reference that group
   /subagents text carries advisory: true
   ✓ the real /subagents command surface carries the advisory once
   ✓ the tool payload itself names the advisory field
── phase 2: PRE-FIX CONTROL — same children, cwd not persisted (current main) ──
   shipped tool: sharedCwdGroupTotal=0
   ✓ without the persisted field the shipped tool reports no advisory (the bug)
── phase 3: distinct directories, and a single writer ──
   ✓ two children in different explicit directories stay silent
   ✓ a single writer in an explicit directory is not a collision

The payload is parsed out of the tool's own content block, not reassembled by the script.

Data-model compatibility: written by the base commit's code, read by this head

Two processes on two different code trees. The writer is a git archive of the merge-base 8408f1b57558d36d7bb21bf979a6275c46c20099, run from that tree, storing six session entries through the base release's own upsertSessionEntryCore(): an owner session with ordinary settings (model, agentId, thinkLevel), two native children carrying spawnedCwd, two ACP children with no spawnedCwd (the gap this PR closes), and one lone native child. The base code materialized a real 692 KB openclaw-agent.sqlite agent database (confirmed independently with node:sqlite: six rows in session_nodes with base-shaped entry_json). This head then opens those exact stored bytes:

── phase 4: DATA-MODEL COMPATIBILITY — stored by the BASE COMMIT's code ──
   head over BASE-stored data: total=5 sharedCwdGroupTotal=1 groups=[{"id":1,"path":"/tmp/base-store-197123/base-shared-checkout","runCount":2,"runIds":["run-base-native-a","run-base-native-b"]}]
   ✓ every base-stored session entry still loads on this head
   ✓ base-stored native children with spawnedCwd group correctly on this head
   ✓ base-stored ACP children without spawnedCwd are silent, not an error
   ✓ the base-stored lone child stays ungrouped
   ✓ the /subagents surface works over base-stored data
   ✓ base-stored settings are readable on this head
   after a head write into the base store: total=6 sharedCwdGroupTotal=1 groups=[{"id":1,"path":"/tmp/base-store-197123/base-shared-checkout","runCount":3,"runIds":["run-base-native-a","run-base-native-b","run-head-acp-new"]}]
   ✓ a head-written ACP child joins the base-stored native group
   ✓ the head write left every base-stored entry and setting intact

All runtime assertions passed.

The last two assertions are the upgrade case: this head persists a new ACP child's spawnedCwd into the same base-written database, the new child joins the pre-existing group (runCount 2 → 3), and every base-stored entry — owner settings, native child, ACP child — still compares deepEqual to its pre-write snapshot. Nothing sensitive appears in the output to redact: throwaway state dir, no credentials, no private endpoints, /tmp paths only.

Real vs stubbed in this round's proof

  • Real: Gateway process role, database engine, sqlite runtime, state-ownership lease, plugin load and capability admission; createSubagentsTool() and execute("list") with its controller read, scope filter, registry snapshot and JSON assembly; handleSubagentsListAction(); the in-memory subagent registry; upsertSessionEntryCore() against a real agent database; the base commit's stored sqlite bytes; real directories on disk.
  • Still stubbed / not executed: the spawn dispatch itself. Launching a native or ACP child additionally needs a provider credential and a real model turn, which this environment cannot supply. Child session entries are written by the same production writer the spawn owners call, with the patch they build, and the runs are registered in the same registry the spawn owners register into. So the list half of "spawn-to-list" is now real through the shipped surfaces; the dispatch half is not.
  • Not covered: the "ended-peer" case; "inherited-workspace" is covered by the unpersisted controls rather than by a separate Gateway-backed phase.

Round 1 — production readers and renderers, run out of process (earlier round)

node --import ./scripts/tsx.mjs scripts/proof-135480-subagent-shared-cwd-advisory.ts
# exit 0

Key lines of the real output (full run in the collapsed block below):

── scenario 1: PRE-FIX CONTROL — ACP children with no persisted cwd ──
   two live ACP children in /tmp/openclaw-proof-135480-uF7rnS/acp-shared, field not persisted
   ✓ no advisory — this is the false negative the PR fixes
── scenario 2: POST-FIX — the same ACP children, cwd persisted ──
   run run-acp-post-a group: {"id":1,"path":"/tmp/openclaw-proof-135480-uF7rnS/acp-shared-post","runCount":2,"runIds":["run-acp-post-a","run-acp-post-b"]}
   ✓ both ACP rows refer to one exact group summary
   ✓ the /subagents text surface emits the directory once
── scenario 4: symlink alias to one real checkout ──
   alias group: {"id":1,"path":"/tmp/openclaw-proof-135480-uF7rnS/alias-real","runCount":2,"runIds":["run-alias-link-run","run-alias-real-run"]}
   ✓ aliased runs group together and report the canonical directory
── scenario 5: inherited workspace stays silent ──
   ✓ no advisory for children that named no directory
── scenario 6: distinct directories stay silent ──
   ✓ two different checkouts are not reported as a collision
── scenario 8: model-context bound at the supported child maximum ──
   20 children sharing one cwd: 7522 B model-visible, 1 directory summary
   50 children sharing one cwd: 17602 B model-visible, 1 directory summary
   ✓ 50 children across 25 shared directories emit only eight summaries
── scenario 10: sender-restricted helpers are not an explicit request ──
   ✓ two restricted helpers in one root produce no advisory
   ✓ the same directory without the policy marker is still reported

All runtime assertions passed.

20 assertions, exit 0 at that head; 19 at the current head, where 3bc860565be dropped scenario 9's direct Map-key assertions at the reviewer's request. The advisory surfaces when live children share an explicitly selected directory (scenarios 2, 3, 4, 7, 8, and the marker-free control in 10) and stays absent when they do not (scenarios 1, 5, 6, and the restricted pair in 10).

What is real here: resolveExplicitSpawnedCwd() (the shared explicit-cwd contract both spawn owners persist through); upsertSessionEntryCore() (the exact session writer acp-spawn.ts calls, given the exact creation patch that owner now builds) against a real on-disk session store under a temp OPENCLAW_HOME; readSubagentListSessionEntries() and buildSubagentList() (the changed owner); handleSubagentsListAction() (the real /subagents text renderer); real directories, a real symlink and a real deleted directory, so canonicalization runs against the filesystem. No vitest, no mocks of the seam under test.

What is stubbed, and the proof limits that remain:

  • The spawn dispatch itself is not executed. Launching a native or ACP child needs a live Gateway, a provider credential and a real model turn; this offline script stands up neither. The child sessions are written by the production writer with the owner's own patch, and the ACP owner's patch assembly is pinned separately by src/agents/subagents/spawn/acp-spawn-policy.test-support.ts. So this is not live spawn-to-list proof.
  • The shipped subagents tool object is not driven. Scenario 8 measures the model-visible payload by assembling the same fields src/agents/tools/subagents-tool.ts emits for action: "list", rather than calling createSubagentsTool().execute(). An attempt today to drive the real tool out of process did not complete: its controller read (createSubagentControllerRead().prepare()) does not settle without an admitted Gateway session-capability source, so the entry point hangs offline rather than returning a payload. That attempt is not included and nothing in this body depends on it.
  • The cross-agent raw-session-key case needs an admitted database for a non-default agent; it is covered by subagent-list.test.ts ("groups by each run's own metadata when two agents share one raw session key") through the supported test state, not by this script.

Still outstanding from review, and not claimed here: redacted output from real native and ACP spawn-to-list flows through a running Gateway.

Proof-harness portability — capped-path assertions (head 3bc860565be95faa6c1d0ef40da0cfdff12a640a)

Review finding [P3]: the committed harness compared the advisory's reported directory against the raw absolute path in five places. The advisory keeps only the last 72 characters of a longer directory, so under a deep temporary root a correct advisory fails those assertions. 3bc860565be compares through expectedSharedCwdPath() — the same display helper the two owner suites already use — while the stored-entry assertions keep comparing the full resolved path, which is what the writer persists.

Measured both ways under an 82-character TMPDIR (/tmp/oc-long-tmproot-197123/aaaaaaaaaa/bbbbbbbbbb/cccccccccc/dddddddddd/eeeeeeeeee), which pushes every scenario directory past the cap:

# before — the harness exactly as committed at 9a861a7aebe
$ TMPDIR=<82-char root> node --import ./scripts/tsx.mjs scripts/proof-135480-subagent-shared-cwd-advisory.ts
   ✗ both ACP rows refer to one exact group summary
   ✗ the /subagents text surface emits the directory once
   ✗ aliased runs group together and report the canonical directory
   ✗ grouping survives an unresolvable directory without throwing
   ✗ the same directory without the policy marker is still reported
5 runtime assertion(s) FAILED.          # exit 1

# after — 3bc860565be, same 82-character TMPDIR
All runtime assertions passed.          # exit 0, 19 of 19

# after — 3bc860565be, default /tmp
All runtime assertions passed.          # exit 0, 19 of 19

Five failures, five repaired assertion sites. The production advisory behaved identically in both runs — only the harness was not portable — which is why this commit touches no runtime source.

Gates at this head, for the one file it changes: pnpm oxlint 0 warnings / 0 errors; pnpm oxfmt --check clean; git diff --check clean; pnpm check:line-cap-ratchet "no new violations or over-cap growth"; check-test-lines-ratchet.mts --base origin/main --no-merge-base OK (6668555, ceiling 6668555); pnpm tsgo:scripts exit 0. pnpm tsgo:core/tsgo:core:test were not re-run: no TypeScript under src/ or extensions/ changed in this commit.

Discrimination, two controls measured separately

Control Result
A — the exemption fix reverted, its tests kept 2 failed / 29 passed across subagent-list-shared-cwd-policy.test.ts + subagent-list.test.ts; both failures are the new file's "stays silent for sender-restricted helpers handed the requester's root" (expected 1 to be +0) and "keeps reporting the unrestricted peers when one run of the group is restricted". The proof harness exits 1 with scenario 10's advisory assertion failing
B — the naive owner-side shape (clear the inherited cwd at both owners) acp-spawn.test.ts 1 failed / 47 passed and subagent-spawn.workspace.test.ts 1 failed / 22 passed, in both cases the restricted-root enforcement case

Control A says the fix is load-bearing; control B says the cheaper-looking alternative is a security regression. These two controls were measured on the earlier head bbc24b971d4 and are not re-measured at 9a861a7ae.

Tests

Three cases take the exemption — restricted silence, the identical directory without the policy marker as the control, and a mixed group pinning that the exemption is per run — in a sibling file, src/agents/subagents/registry/subagent-list-shared-cwd-policy.test.ts. That split is forced and also correct: subagent-list.test.ts sits at the oxlint max-lines cap of 1000 counted lines whose origin/main base is under the cap, so check:line-cap-ratchet treats any higher head count as a new violation. The seam is real: the new file is about how a run's cwd was decided, the old one about how already-decided directories are grouped, canonicalized, capped and rendered.

Path assertions are portable as of 8928b055c91: the suites assert the advisory's documented capped display through a small test-support helper instead of the full absolute path, so a long os.tmpdir() (macOS, a nested CI vitest temp root, a long TMPDIR) no longer fails a correct implementation. Exact grouping and count checks are retained, and a past-the-cap sibling-checkout case is covered. As of 3bc860565be the committed proof harness uses that same helper for every directory the advisory reports, so there is one source of truth for the display cap.

Withdrawn from earlier bodies and not reinstated: the stale 5a6f6b2bf99, aa0c15c8bfd and bbc24b971d4 heads as proof heads; "149 tests passed, exit 0"; the entire "Selected-metadata reuse" measurement table, whose cited proof scenario and accessor-counting unit test were dropped at merge 26e8beb1c13; and the claim that check:line-cap-ratchet "cannot execute on this machine (git 2.34.1)" — it runs under git 2.55.

Full proof run output (head 9a861a7aebe, exit 0)
── scenario 1: PRE-FIX CONTROL — ACP children with no persisted cwd ──
[state/agent-db] agent database stale lease: owner-pid-dead; previous release not observed
[state/agent-db] agent database stale lease: owner-pid-dead; previous release not observed
   two live ACP children in /tmp/openclaw-proof-135480-uF7rnS/acp-shared, field not persisted
   ✓ no advisory — this is the false negative the PR fixes
── scenario 2: POST-FIX — the same ACP children, cwd persisted ──
   run run-acp-post-a group: {"id":1,"path":"/tmp/openclaw-proof-135480-uF7rnS/acp-shared-post","runCount":2,"runIds":["run-acp-post-a","run-acp-post-b"]}
   ✓ both ACP rows refer to one exact group summary
   ✓ the /subagents text surface emits the directory once
── scenario 3: cross-runtime — one native child, one ACP child ──
   ✓ the native and ACP rows refer to the same group
── scenario 4: symlink alias to one real checkout ──
   /tmp/openclaw-proof-135480-uF7rnS/alias-link -> /tmp/openclaw-proof-135480-uF7rnS/alias-real
   alias group: {"id":1,"path":"/tmp/openclaw-proof-135480-uF7rnS/alias-real","runCount":2,"runIds":["run-alias-link-run","run-alias-real-run"]}
   ✓ aliased runs group together and report the canonical directory
── scenario 5: inherited workspace stays silent ──
[state/agent-db] agent database clean-close receipt: written; agent=main
   ✓ no advisory for children that named no directory
── scenario 6: distinct directories stay silent ──
[state/agent-db] agent database clean-close receipt: written; agent=main
   ✓ two different checkouts are not reported as a collision
── scenario 7: deleted directory falls back to lexical grouping ──
[state/agent-db] agent database clean-close receipt: written; agent=main
   /tmp/openclaw-proof-135480-uF7rnS/deleted-tree removed after spawn; advisory still resolves
   ✓ grouping survives an unresolvable directory without throwing
── scenario 8: model-context bound at the supported child maximum ──
[state/agent-db] agent database clean-close receipt: written; agent=main
[state/agent-db] agent database clean-close receipt: written; agent=main
   20 children sharing one cwd: 7522 B model-visible, 1 directory summary
   50 children sharing one cwd: 17602 B model-visible, 1 directory summary
   ✓ one summary reports the exact group size with a fixed run-id sample
   ✓ only the sampled members carry row-level group references
   ✓ the reported directory is capped at 72 characters
   ✓ the text view emits the group once with its true size
[state/agent-db] agent database clean-close receipt: written; agent=main
   sibling alpha reports: ...agent-shared-cwd-advisory/packages/agent-core/openclaw-worktree-alpha
   sibling beta  reports: ...bagent-shared-cwd-advisory/packages/agent-core/openclaw-worktree-beta
   ✓ sibling checkouts past the display cap remain distinct groups
[state/agent-db] agent database clean-close receipt: written; agent=main
   ✓ 50 children across 25 shared directories emit only eight summaries
   reported directories: many-group-00, many-group-01, many-group-02, many-group-03, many-group-04, many-group-05, many-group-06, many-group-07
   ✓ permuting equal-timestamp runs leaves the whole report identical
── scenario 9: the reader/advisory metadata key contract ──
[state/agent-db] agent database clean-close receipt: written; agent=main
   reader selection keys: run-key-contract-a, run-key-contract-b (run ids: run-key-contract-a, run-key-contract-b; session keys: agent:main:subagent:key-contract-a, agent:main:subagent:key-contract-b)
   ✓ the reader keys its selection by run id, never by child session key
   ✓ the advisory consumes that selection under the same key
── scenario 10: sender-restricted helpers are not an explicit request ──
[state/agent-db] agent database clean-close receipt: written; agent=main
   restricted entries persist spawnedCwd=/tmp/openclaw-proof-135480-uF7rnS/restricted-root inheritedToolPolicySource=sender
   ✓ the enforced working directory is still on the entry, not cleared
   ✓ two restricted helpers in one root produce no advisory
[state/agent-db] agent database clean-close receipt: written; agent=main
   ✓ the same directory without the policy marker is still reported

All runtime assertions passed.
Full proof script — scripts/proof-135480-subagent-shared-cwd-advisory.ts (ships in this PR's diff)
/**
 * Real-behavior proof for the subagent shared-working-directory advisory
 * (PR #135480).
 *
 * What is REAL here (no vitest, no mocks of the seam under test):
 *   - `resolveExplicitSpawnedCwd()` — the one explicit-cwd contract both the
 *     native and the ACP spawn owner now persist through.
 *   - `upsertSessionEntryCore()` — the exact session writer `acp-spawn.ts`
 *     calls, invoked with the exact creation patch the ACP owner now builds,
 *     against a real on-disk session store in a temp OPENCLAW_HOME.
 *   - `buildSubagentList()` — the changed production owner.
 *   - `handleSubagentsListAction()` — the real `/subagents` text renderer that
 *     consumes it.
 *   - Real directories, a real symlink, and a real deleted directory on disk;
 *     canonicalization runs against the actual filesystem.
 *
 * What is NOT executed: the ACP dispatch itself. `spawnAcpDirect()` launches an
 * external ACP agent through a live Gateway, which this offline script cannot
 * stand up. The ACP owner's own patch assembly is pinned instead by
 * `src/agents/subagents/spawn/acp-spawn-policy.test-support.ts`, registered
 * into the `acp-spawn.test.ts` suite ("persists an explicit ACP cwd
 * so working-directory readers see it like a native child", and "keeps a
 * restricted same-agent ACP helper in the requester's root"); what this script
 * proves is that an ACP-shaped child session written through the production
 * writer is grouped and reported by the production readers, and that the same
 * child WITHOUT the persisted field — i.e. current `main` — is not.
 *
 * Scenarios:
 *   1. Pre-fix control: two ACP children in one directory, no `spawnedCwd`
 *      persisted (current `main`) — no advisory. This is the reported bug.
 *   2. Post-fix: the same two ACP children with the field persisted — both
 *      refer to one directory summary in tool JSON and `/subagents` text.
 *   3. Cross-runtime: one native child and one ACP child in one directory —
 *      both refer to the same group.
 *   4. Symlink alias: two children reach one checkout by different paths —
 *      grouped, and the canonical directory is reported.
 *   5. Inherited workspace (no explicit cwd) — silent.
 *   6. Distinct directories — silent.
 *   7. Deleted directory — canonicalization fails, lexical fallback still
 *      groups rather than throwing or dropping the row.
 *   8. Model-context bound at the supported child maximum: 20 live children in
 *      one long-pathed directory. Measures the real model-visible payload the
 *      `subagents` tool emits for `action: "list"` and asserts the advisory's
 *      whole-response contribution is capped — the P0 regression. Also drives
 *      25 shared directories across 50 children to prove only eight directory
 *      summaries are model-visible, and that permuting that equal-timestamp
 *      cohort leaves the ids, samples, and reported directories identical.
 *   9. The reader/advisory metadata key contract. `readSubagentListSessionEntries`
 *      keys its selection by run id, not by child session key, because raw child
 *      session keys repeat across agents
 *      (https://github.com/openclaw/openclaw/pull/166550). Feeds the real
 *      reader's own selection object straight into `buildSubagentList`, so a
 *      producer/consumer key disagreement cannot pass.
 *      The cross-agent raw-key case itself needs an admitted database for a
 *      non-default agent, which this offline harness does not stand up; it is
 *      covered by `subagent-list.test.ts` ("groups by each run's own metadata
 *      when two agents share one raw session key") through the supported test
 *      state.
 *  10. Sender-restricted helpers. A restricted sender's helper is handed the
 *      requester's root as `spawnedCwd` even when the request named no cwd,
 *      because both owners refuse any other directory for it. Asserts the
 *      enforced directory is still on the entry, that two such helpers produce
 *      no advisory in either the structured list or the `/subagents` text, and
 *      — as the control — that the identical directory without the policy
 *      marker is still reported.
 *
 * Every reported directory is compared through `expectedSharedCwdPath()` — the
 * same helper the owner suites use — because the advisory keeps only the last 72
 * characters of a long directory, which a deep temporary root reaches.
 *
 * Run: node --import ./scripts/tsx.mjs scripts/proof-135480-subagent-shared-cwd-advisory.ts
 */
import assert from "node:assert/strict";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";

type SpawnedContextModule = typeof import("../src/agents/spawned-context.js");
type SessionAccessorModule = typeof import("../src/config/sessions/session-accessor.js");
type SubagentListModule = typeof import("../src/agents/subagents/registry/subagent-list.js");
type SubagentRegistryQueriesModule =
  typeof import("../src/agents/subagents/registry/subagent-registry-queries.js");
type SubagentsCommandModule =
  typeof import("../src/auto-reply/reply/commands-subagents/action-list.js");
type SubagentListTestSupportModule =
  typeof import("../src/agents/subagents/registry/subagent-list.test-support.js");
type SubagentRunRecord =
  import("../src/agents/subagents/registry/subagent-registry.types.js").SubagentRunRecord;
type SubagentRunReadRecord =
  import("../src/agents/subagents/registry/subagent-registry-read.types.js").SubagentRunReadRecord;
type OpenClawConfig = import("../src/config/types.openclaw.js").OpenClawConfig;

let failures = 0;

function check(label: string, run: () => void): void {
  try {
    run();
    console.log(`   ✓ ${label}`);
  } catch (error) {
    failures += 1;
    console.log(`   ✗ ${label}`);
    console.log(`     ${error instanceof Error ? error.message : String(error)}`);
  }
}

function makeRun(suffix: string, now: number, options?: { ended?: boolean }): SubagentRunRecord {
  return {
    runId: `run-${suffix}`,
    childSessionKey: `agent:main:subagent:${suffix}`,
    controllerSessionKey: "agent:main:main",
    requesterSessionKey: "agent:main:main",
    requesterDisplayKey: "main",
    task: `work inside ${suffix}`,
    cleanup: "keep",
    createdAt: now - 120_000,
    execution: options?.ended
      ? {
          status: "terminal",
          startedAt: now - 120_000,
          endedAt: now - 60_000,
          outcome: { status: "ok" },
        }
      : { status: "running", startedAt: now - 120_000 },
  } as SubagentRunRecord;
}

async function main(): Promise<void> {
  const root = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-proof-135480-"));
  process.env.OPENCLAW_HOME = path.join(root, "home");
  await fs.mkdir(process.env.OPENCLAW_HOME, { recursive: true });

  const { resolveExplicitSpawnedCwd } =
    (await import("../src/agents/spawned-context.js")) as SpawnedContextModule;
  const { upsertSessionEntryCore } =
    (await import("../src/config/sessions/session-accessor.js")) as SessionAccessorModule;
  const { buildSubagentList, captureSubagentListReadContext, readSubagentListSessionEntries } =
    (await import("../src/agents/subagents/registry/subagent-list.js")) as SubagentListModule;
  const { buildSubagentRunReadIndexFromRuns } =
    (await import("../src/agents/subagents/registry/subagent-registry-queries.js")) as SubagentRegistryQueriesModule;
  const { handleSubagentsListAction } =
    (await import("../src/auto-reply/reply/commands-subagents/action-list.js")) as SubagentsCommandModule;
  // The advisory's own display contract: the owner suites assert reported
  // directories through this helper, so the proof must not hand-roll the cap.
  const { expectedSharedCwdPath } =
    (await import("../src/agents/subagents/registry/subagent-list.test-support.js")) as SubagentListTestSupportModule;

  /**
   * Captures the read context the same way the production caller does. This
   * script never registers runs with the in-memory subagent registry, so the
   * read index and "full runs" map are always empty — the advisory itself
   * only reads persisted `spawnedCwd`, not registry state.
   */
  const buildReadContext = (runs: SubagentRunRecord[], recentMinutes: number) => {
    const readIndex = buildSubagentRunReadIndexFromRuns<SubagentRunReadRecord>({
      runs: new Map<string, SubagentRunReadRecord>(),
      inMemoryRuns: [],
    });
    return captureSubagentListReadContext(
      runs,
      readIndex,
      new Map<string, SubagentRunRecord>(),
      recentMinutes,
    );
  };

  /**
   * Writes a child session entry through the production writer using the exact
   * creation patch `acp-spawn.ts` now builds for an ACP child (or the native
   * equivalent — both owners resolve `spawnedCwd` through the same contract).
   */
  const createChildSession = async (params: {
    storePath: string;
    sessionKey: string;
    requestedCwd?: string;
    /** Set false to reproduce current `main`, which persists nothing for ACP. */
    persistCwd?: boolean;
    /**
     * Adds the two fields both owners stamp for a sender-restricted helper.
     * The cwd then names the requester's root because policy put it there, not
     * because the request asked for it.
     */
    senderRestricted?: boolean;
  }) => {
    const spawnedCwd = resolveExplicitSpawnedCwd(params.requestedCwd);
    await upsertSessionEntryCore({ storePath: params.storePath, sessionKey: params.sessionKey }, {
      spawnedBy: "agent:main:main",
      completionOwnerSessionKey: "agent:main:main",
      parentSessionKey: "agent:main:main",
      ...(spawnedCwd && params.persistCwd !== false ? { spawnedCwd } : {}),
      ...(params.senderRestricted
        ? { inheritedToolPolicySource: "sender", sessionRoot: spawnedCwd }
        : {}),
      inheritedToolPolicyVersion: 1,
    } as never);
    return spawnedCwd;
  };

  const listFor = async (storePath: string, runs: SubagentRunRecord[]) => {
    const cfg = { session: { store: storePath } } as OpenClawConfig;
    const context = buildReadContext(runs, 30);
    const list = buildSubagentList({
      context,
      sessionEntries: await readSubagentListSessionEntries(cfg, context),
    });
    // The `/subagents` command surface, driven for real off the same build.
    const text = await handleSubagentsListAction({
      params: { cfg },
      readContext: { list: context },
    } as never);
    return { list, text };
  };

  const groupFor = (list: ReturnType<SubagentListModule["buildSubagentList"]>, runId: string) => {
    const groupId = list.active.find((item) => item.runId === runId)?.sharedCwdGroupId;
    return list.sharedCwdGroups.find((group) => group.id === groupId);
  };

  const now = Date.now();

  console.log("── scenario 1: PRE-FIX CONTROL — ACP children with no persisted cwd ──");
  {
    const store = path.join(root, "sessions-acp-prefix.json");
    const dir = path.join(root, "acp-shared");
    await fs.mkdir(dir, { recursive: true });
    const runs = [makeRun("acp-prefix-a", now), makeRun("acp-prefix-b", now)];
    for (const run of runs) {
      await createChildSession({
        storePath: store,
        sessionKey: run.childSessionKey,
        requestedCwd: dir,
        persistCwd: false,
      });
    }
    const { list } = await listFor(store, runs);
    console.log(`   two live ACP children in ${dir}, field not persisted`);
    check("no advisory — this is the false negative the PR fixes", () => {
      assert.equal(list.active.length, 2);
      for (const run of runs) {
        assert.equal(groupFor(list, run.runId), undefined);
      }
    });
  }

  console.log("── scenario 2: POST-FIX — the same ACP children, cwd persisted ──");
  {
    const store = path.join(root, "sessions-acp-postfix.json");
    const dir = path.join(root, "acp-shared-post");
    await fs.mkdir(dir, { recursive: true });
    const runs = [makeRun("acp-post-a", now), makeRun("acp-post-b", now)];
    for (const run of runs) {
      await createChildSession({
        storePath: store,
        sessionKey: run.childSessionKey,
        requestedCwd: dir,
      });
    }
    const { list, text } = await listFor(store, runs);
    const first = groupFor(list, runs[0]!.runId);
    console.log(`   run ${runs[0]!.runId} group: ${JSON.stringify(first)}`);
    check("both ACP rows refer to one exact group summary", () => {
      assert.deepEqual(first, {
        id: 1,
        path: expectedSharedCwdPath(dir),
        runCount: 2,
        runIds: runs.map((run) => run.runId),
      });
      assert.equal(list.active[0]?.sharedCwdGroupId, 1);
      assert.equal(list.active[1]?.sharedCwdGroupId, 1);
    });
    check("the /subagents text surface emits the directory once", () => {
      const rendered = JSON.stringify(text);
      assert.equal(rendered.split(expectedSharedCwdPath(dir)).length, 2);
    });
  }

  console.log("── scenario 3: cross-runtime — one native child, one ACP child ──");
  {
    const store = path.join(root, "sessions-cross-runtime.json");
    const dir = path.join(root, "cross-runtime-shared");
    await fs.mkdir(dir, { recursive: true });
    const nativeRun = makeRun("native-child", now);
    const acpRun = makeRun("acp-child", now);
    for (const run of [nativeRun, acpRun]) {
      await createChildSession({
        storePath: store,
        sessionKey: run.childSessionKey,
        requestedCwd: dir,
      });
    }
    const { list } = await listFor(store, [nativeRun, acpRun]);
    check("the native and ACP rows refer to the same group", () => {
      assert.equal(list.active.find((item) => item.runId === nativeRun.runId)?.sharedCwdGroupId, 1);
      assert.equal(list.active.find((item) => item.runId === acpRun.runId)?.sharedCwdGroupId, 1);
      // The sample is ordered by run id, not by which runtime was seen first.
      assert.deepEqual(
        groupFor(list, nativeRun.runId)?.runIds,
        [nativeRun.runId, acpRun.runId].toSorted(),
      );
    });
  }

  console.log("── scenario 4: symlink alias to one real checkout ──");
  {
    const store = path.join(root, "sessions-alias.json");
    const realDir = path.join(root, "alias-real");
    const linkDir = path.join(root, "alias-link");
    await fs.mkdir(realDir, { recursive: true });
    await fs.symlink(realDir, linkDir, "dir");
    const canonical = await fs.realpath(realDir);
    const realRun = makeRun("alias-real-run", now);
    const linkRun = makeRun("alias-link-run", now);
    await createChildSession({
      storePath: store,
      sessionKey: realRun.childSessionKey,
      requestedCwd: realDir,
    });
    await createChildSession({
      storePath: store,
      sessionKey: linkRun.childSessionKey,
      requestedCwd: linkDir,
    });
    const { list } = await listFor(store, [realRun, linkRun]);
    console.log(`   ${linkDir} -> ${canonical}`);
    console.log(`   alias group: ${JSON.stringify(groupFor(list, linkRun.runId))}`);
    check("aliased runs group together and report the canonical directory", () => {
      assert.deepEqual(groupFor(list, realRun.runId), {
        id: 1,
        path: expectedSharedCwdPath(canonical),
        runCount: 2,
        runIds: [realRun.runId, linkRun.runId].toSorted(),
      });
      assert.equal(list.active.find((item) => item.runId === linkRun.runId)?.sharedCwdGroupId, 1);
    });
  }

  console.log("── scenario 5: inherited workspace stays silent ──");
  {
    const store = path.join(root, "sessions-inherited.json");
    const runs = [makeRun("inherited-a", now), makeRun("inherited-b", now)];
    for (const run of runs) {
      await createChildSession({ storePath: store, sessionKey: run.childSessionKey });
    }
    const { list } = await listFor(store, runs);
    check("no advisory for children that named no directory", () => {
      assert.equal(list.active.length, 2);
      for (const run of runs) {
        assert.equal(groupFor(list, run.runId), undefined);
      }
    });
  }

  console.log("── scenario 6: distinct directories stay silent ──");
  {
    const store = path.join(root, "sessions-distinct.json");
    const runA = makeRun("distinct-a", now);
    const runB = makeRun("distinct-b", now);
    const dirA = path.join(root, "distinct-a-dir");
    const dirB = path.join(root, "distinct-b-dir");
    await fs.mkdir(dirA, { recursive: true });
    await fs.mkdir(dirB, { recursive: true });
    await createChildSession({
      storePath: store,
      sessionKey: runA.childSessionKey,
      requestedCwd: dirA,
    });
    await createChildSession({
      storePath: store,
      sessionKey: runB.childSessionKey,
      requestedCwd: dirB,
    });
    const { list } = await listFor(store, [runA, runB]);
    check("two different checkouts are not reported as a collision", () => {
      assert.equal(groupFor(list, runA.runId), undefined);
      assert.equal(groupFor(list, runB.runId), undefined);
    });
  }

  console.log("── scenario 7: deleted directory falls back to lexical grouping ──");
  {
    const store = path.join(root, "sessions-deleted.json");
    const dir = path.join(root, "deleted-tree");
    await fs.mkdir(dir, { recursive: true });
    const runs = [makeRun("deleted-a", now), makeRun("deleted-b", now)];
    for (const run of runs) {
      await createChildSession({
        storePath: store,
        sessionKey: run.childSessionKey,
        requestedCwd: dir,
      });
    }
    await fs.rm(dir, { recursive: true, force: true });
    const { list } = await listFor(store, runs);
    console.log(`   ${dir} removed after spawn; advisory still resolves`);
    check("grouping survives an unresolvable directory without throwing", () => {
      for (const run of runs) {
        assert.equal(groupFor(list, run.runId)?.path, expectedSharedCwdPath(dir));
      }
    });
  }

  console.log("── scenario 8: model-context bound at the supported child maximum ──");
  {
    // The advisory attaches to every row of `subagents list` AND to the rendered
    // text view, so naming every peer made one ordinary call grow as O(runs^2).
    // This scenario drives the real tool payload shape and measures it.
    const PATH_MAX = 72;
    // A realistically long checkout path, as the finding calls out.
    const deepDir = path.join(
      root,
      "home/operator/projects/worktrees/openclaw-feat-subagent-shared-cwd-advisory/packages/agent-core",
    );
    await fs.mkdir(deepDir, { recursive: true });
    assert.ok(deepDir.length > PATH_MAX, "scenario needs a path longer than the display cap");

    const measure = async (childCount: number) => {
      const store = path.join(root, `sessions-bound-${childCount}.json`);
      const runs = Array.from({ length: childCount }, (_unused, i) =>
        makeRun(`bound-${childCount}-${String(i).padStart(2, "0")}`, now),
      );
      for (const run of runs) {
        await createChildSession({
          storePath: store,
          sessionKey: run.childSessionKey,
          requestedCwd: deepDir,
        });
      }
      const { list } = await listFor(store, runs);
      // Exactly what subagents-tool.ts emits for `action: "list"`: structured
      // rows with `line` stripped, plus the rendered text view.
      const modelVisible = JSON.stringify({
        sharedCwdGroupTotal: list.sharedCwdGroupTotal,
        sharedCwdGroups: list.sharedCwdGroups,
        active: list.active.map(({ line: _line, ...view }) => view),
        recent: list.recent.map(({ line: _line, ...view }) => view),
        text: list.text,
      });
      return { list, runs, modelVisible };
    };

    const at20 = await measure(20);
    const at50 = await measure(50);
    for (const [childCount, m] of [
      [20, at20],
      [50, at50],
    ] as const) {
      console.log(
        `   ${String(childCount).padStart(2)} children sharing one cwd: ${m.modelVisible.length} B model-visible, ${m.list.sharedCwdGroups.length} directory summary`,
      );
    }

    check("one summary reports the exact group size with a fixed run-id sample", () => {
      assert.equal(at20.list.sharedCwdGroups.length, 1);
      assert.equal(at20.list.sharedCwdGroups[0]?.runCount, 20);
      assert.equal(at20.list.sharedCwdGroups[0]?.runIds.length, 3);
      assert.equal(at50.list.sharedCwdGroups.length, 1);
      assert.equal(at50.list.sharedCwdGroups[0]?.runCount, 50);
      assert.equal(at50.list.sharedCwdGroups[0]?.runIds.length, 3);
    });
    check("only the sampled members carry row-level group references", () => {
      assert.equal(
        at20.list.active.filter((item) => item.sharedCwdGroupId !== undefined).length,
        3,
      );
      assert.equal(
        at50.list.active.filter((item) => item.sharedCwdGroupId !== undefined).length,
        3,
      );
    });
    check(`the reported directory is capped at ${PATH_MAX} characters`, () => {
      const reported = at20.list.sharedCwdGroups[0]?.path ?? "";
      assert.ok(reported.length <= PATH_MAX, `reported path was ${reported.length} characters`);
      assert.ok(reported.startsWith("..."), `expected a truncation marker: ${reported}`);
      assert.ok(reported.endsWith("packages/agent-core"), `lost the path tail: ${reported}`);
      // The untruncated path must not leak into the payload anywhere.
      assert.ok(
        !at20.modelVisible.includes(deepDir),
        "the full path reached the model-visible payload",
      );
    });
    check("the text view emits the group once with its true size", () => {
      assert.ok(at20.list.text.includes("[cwd 1] 20 live runs:"));
      assert.equal(at20.list.text.split(at20.list.sharedCwdGroups[0]!.path).length, 2);
    });
    // Sibling checkouts identical for their first 100+ characters, differing
    // only past the display cap: grouping must still keep them apart.
    const alphaDir = path.join(deepDir, "openclaw-worktree-alpha");
    const betaDir = path.join(deepDir, "openclaw-worktree-beta");
    await fs.mkdir(alphaDir, { recursive: true });
    await fs.mkdir(betaDir, { recursive: true });
    const siblingStore = path.join(root, "sessions-bound-siblings.json");
    const alphaRuns = ["sib-alpha-a", "sib-alpha-b"].map((suffix) => makeRun(suffix, now));
    const betaRuns = ["sib-beta-a", "sib-beta-b"].map((suffix) => makeRun(suffix, now));
    for (const [runs, dir] of [
      [alphaRuns, alphaDir],
      [betaRuns, betaDir],
    ] as const) {
      for (const run of runs) {
        await createChildSession({
          storePath: siblingStore,
          sessionKey: run.childSessionKey,
          requestedCwd: dir,
        });
      }
    }
    const siblingList = (await listFor(siblingStore, [...alphaRuns, ...betaRuns])).list;
    const alphaAdvisory = groupFor(siblingList, alphaRuns[0]!.runId);
    const betaAdvisory = groupFor(siblingList, betaRuns[0]!.runId);
    console.log(`   sibling alpha reports: ${alphaAdvisory?.path}`);
    console.log(`   sibling beta  reports: ${betaAdvisory?.path}`);
    check("sibling checkouts past the display cap remain distinct groups", () => {
      assert.equal(alphaAdvisory?.runCount, 2);
      assert.equal(betaAdvisory?.runCount, 2);
      assert.notEqual(
        alphaAdvisory?.path,
        betaAdvisory?.path,
        "the display cap collapsed two distinct directories into one label",
      );
    });

    const manyStore = path.join(root, "sessions-bound-many-groups.json");
    const manyRuns: SubagentRunRecord[] = [];
    for (let groupIndex = 0; groupIndex < 25; groupIndex += 1) {
      const dir = path.join(root, `many-group-${String(groupIndex).padStart(2, "0")}`);
      for (let runIndex = 0; runIndex < 2; runIndex += 1) {
        const run = makeRun(`many-${groupIndex}-${runIndex}`, now);
        manyRuns.push(run);
        await createChildSession({
          storePath: manyStore,
          sessionKey: run.childSessionKey,
          requestedCwd: dir,
        });
      }
    }
    const manyList = (await listFor(manyStore, manyRuns)).list;
    check("50 children across 25 shared directories emit only eight summaries", () => {
      assert.equal(manyList.sharedCwdGroupTotal, 25);
      assert.equal(manyList.sharedCwdGroups.length, 8);
      assert.equal(
        manyList.active.filter((item) => item.sharedCwdGroupId !== undefined).length,
        16,
      );
      assert.ok(manyList.text.includes("shared working directories (8/25 shown):"));
    });

    // `sortSubagentRuns` compares start timestamps only, so this
    // same-millisecond cohort reaches the advisory in whatever order the
    // caller's array had. With 25 groups against a cap of 8, that order used to
    // decide the group ids, the samples, and which directories were reported at
    // all. Permuting it must now leave the whole report unchanged.
    const summarizeMany = async (input: SubagentRunRecord[]) => {
      const list = (await listFor(manyStore, input)).list;
      return JSON.stringify({
        total: list.sharedCwdGroupTotal,
        groups: list.sharedCwdGroups,
        // Sorted so the comparison isolates group assignment from the row
        // ordering the permutation legitimately changes.
        assignments: list.active
          .map((item) => `${item.runId}=${item.sharedCwdGroupId ?? "none"}`)
          .toSorted(),
      });
    };
    const inOrderSummary = await summarizeMany(manyRuns);
    const reversedSummary = await summarizeMany(manyRuns.toReversed());
    const interleavedSummary = await summarizeMany([
      ...manyRuns.filter((_unused, i) => i % 2 === 1),
      ...manyRuns.filter((_unused, i) => i % 2 === 0),
    ]);
    console.log(
      `   reported directories: ${manyList.sharedCwdGroups.map((group) => path.basename(group.path)).join(", ")}`,
    );
    check("permuting equal-timestamp runs leaves the whole report identical", () => {
      assert.equal(reversedSummary, inOrderSummary);
      assert.equal(interleavedSummary, inOrderSummary);
    });
  }

  console.log("── scenario 9: the reader/advisory metadata key contract ──");
  {
    // The defect this round fixed was invisible to every scenario above that
    // asserted only an end result: the advisory read the reader's selection by
    // child session key while the reader stores it by run id, so every ordinary
    // child resolved to `undefined` and the advisory went silent. Drive the real
    // reader's own selection object through the owner, not a reconstructed one.
    const store = path.join(root, "sessions-key-contract.json");
    const dir = path.join(root, "key-contract-shared");
    await fs.mkdir(dir, { recursive: true });
    const runs = [makeRun("key-contract-a", now), makeRun("key-contract-b", now)];
    for (const run of runs) {
      await createChildSession({
        storePath: store,
        sessionKey: run.childSessionKey,
        requestedCwd: dir,
      });
    }
    const cfg = { session: { store } } as OpenClawConfig;
    const context = buildReadContext(runs, 30);
    const selection = await readSubagentListSessionEntries(cfg, context);
    console.log(
      `   reader selection keys: ${[...selection.keys()].join(", ")} (run ids: ${runs
        .map((run) => run.runId)
        .join(", ")}; session keys: ${runs.map((run) => run.childSessionKey).join(", ")})`,
    );
    // Same selection object the production callers pass, consumed by the owner
    // under test — so a producer/consumer key disagreement cannot pass here.
    // The key shape itself is not asserted separately: this call detects the
    // disagreement, and `subagent-list.test.ts` covers cross-agent raw keys.
    const list = buildSubagentList({ context, sessionEntries: selection });
    check("the advisory consumes that selection under the same key", () => {
      assert.equal(list.sharedCwdGroupTotal, 1);
      assert.equal(list.sharedCwdGroups[0]?.runCount, runs.length);
      assert.ok(list.active.every((item) => item.sharedCwdGroupId === 1));
    });
  }

  console.log("── scenario 10: sender-restricted helpers are not an explicit request ──");
  {
    // Both spawn owners refuse any cwd that is not the requester's own root
    // for a restricted sender, then hand the child exactly that root as
    // `spawnedCwd` so the restriction stays enforceable. Two such helpers
    // therefore always name one directory, with nothing the operator could
    // change — the inherited-workspace case the advisory exempts. The control
    // below writes the identical directory WITHOUT the policy marker, so this
    // measures the marker rather than the path.
    const store = path.join(root, "sessions-restricted.json");
    const requesterRoot = path.join(root, "restricted-root");
    await fs.mkdir(requesterRoot, { recursive: true });
    const restricted = [makeRun("restricted-a", now), makeRun("restricted-b", now)];
    for (const run of restricted) {
      await createChildSession({
        storePath: store,
        sessionKey: run.childSessionKey,
        requestedCwd: requesterRoot,
        senderRestricted: true,
      });
    }
    const cfg = { session: { store } } as OpenClawConfig;
    const restrictedContext = buildReadContext(restricted, 30);
    const restrictedSelection = await readSubagentListSessionEntries(cfg, restrictedContext);
    console.log(
      `   restricted entries persist spawnedCwd=${restrictedSelection.get(restricted[0]!.runId)?.spawnedCwd} inheritedToolPolicySource=${restrictedSelection.get(restricted[0]!.runId)?.inheritedToolPolicySource}`,
    );
    check("the enforced working directory is still on the entry, not cleared", () => {
      for (const run of restricted) {
        assert.equal(restrictedSelection.get(run.runId)?.spawnedCwd, path.resolve(requesterRoot));
        assert.equal(restrictedSelection.get(run.runId)?.sessionRoot, path.resolve(requesterRoot));
      }
    });
    const { list: restrictedList, text: restrictedText } = await listFor(store, restricted);
    check("two restricted helpers in one root produce no advisory", () => {
      assert.equal(restrictedList.sharedCwdGroupTotal, 0);
      assert.deepEqual(restrictedList.sharedCwdGroups, []);
      assert.ok(restrictedList.active.every((item) => item.sharedCwdGroupId === undefined));
      assert.equal(restrictedList.text.includes("shared working directories"), false);
      assert.equal(JSON.stringify(restrictedText).includes("shared working directories"), false);
      assert.equal(JSON.stringify(restrictedText).includes("shared cwd group"), false);
    });

    const controlStore = path.join(root, "sessions-restricted-control.json");
    const control = [makeRun("restricted-control-a", now), makeRun("restricted-control-b", now)];
    for (const run of control) {
      await createChildSession({
        storePath: controlStore,
        sessionKey: run.childSessionKey,
        requestedCwd: requesterRoot,
      });
    }
    const { list: controlList } = await listFor(controlStore, control);
    check("the same directory without the policy marker is still reported", () => {
      assert.equal(controlList.sharedCwdGroupTotal, 1);
      assert.equal(controlList.sharedCwdGroups[0]?.path, expectedSharedCwdPath(requesterRoot));
      assert.equal(controlList.sharedCwdGroups[0]?.runCount, control.length);
    });
  }

  await fs.rm(root, { recursive: true, force: true });

  if (failures > 0) {
    console.log(`\n${failures} runtime assertion(s) FAILED.`);
    process.exit(1);
  }
  console.log("\nAll runtime assertions passed.");
  process.exit(0);
}

await main();

This head merges current main (8408f1b5755) into the branch; the focused suites and the proof above were run at it. The PR stays draft until the full gates re-run.

Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).

zeroaltitude and others added 30 commits August 21, 2026 00:40
Two live subagents pointed at one working directory can overwrite each
other's work. `subagents list` now reports that collision so a parent
agent can see it without polling or probing the filesystem.

What: `buildSubagentList` groups live/unended runs by the explicit
working directory they were spawned into and annotates every member of a
group of two or more with `sharedCwd: { path, peerRunIds }`. The
human-readable `line` gets a matching `[shared cwd with N other runs:
<path>]` suffix. The advisory is informational only — it never blocks or
refuses a spawn.

Why keyed on `spawnedCwd`: explicit declaration (`request.cwd`, persisted
as `sessionEntry.spawnedCwd`) and inherited workspace
(`spawnedWorkspaceDir`, which is what reaches the registry entry's
`workspaceDir`) are separate values and were never merged in the
registry. Keying on the session entry's `spawnedCwd` means a default
`collect` swarm — which passes no `cwd` and legitimately shares the
parent workspace — stays silent, and the advisory fires only when a
caller deliberately aimed two live children at the same tree.

Cost: zero new I/O. `buildSubagentList` already resolves the persisted
session entry for every row via `resolveSessionEntryForKey`, which caches
the store per store path; the index reuses that same cache and reads a
field already in hand. No filesystem probe, no registry schema change, no
config surface. Grouping is case-folded on win32 only.

The structured field is the primary surface: `subagents-tool` strips
`line` from its JSON payload, so tests assert `sharedCwd` on the
structured view rather than only the line suffix.

Tests: both directions in `subagent-list.test.ts` (two and three live
runs sharing a path; inherited-workspace runs; distinct explicit
directories; ended runs sharing a path; a live run whose only peer has
ended) plus a `subagents-tool.test.ts` case proving the field survives
into the tool's JSON output while `line` does not.

Validation: pnpm tsgo:core, pnpm tsgo:core:test, pnpm vitest run
src/agents/subagents/registry src/agents/tools/subagents-tool.test.ts
(45 files, 1174 tests), pnpm oxlint, oxfmt --check, git diff --check,
pnpm format:docs:check, pnpm docs:check-mdx, pnpm docs:check-links
(6533 links, 0 broken), markdownlint — all clean.

Beads: openclaw-6na0

Co-Authored-By: Tabitha <[email protected]>
Co-Authored-By: Claude Opus 5 <[email protected]>
…sory (review feedback)

ClawSweeper found two supported collision paths the advisory missed, both of
which made it assert safety it could not see.

[P2] Cover ACP spawns in the shared-directory advisory. `sessions_spawn`
accepts `runtime: "acp"` with an explicit `cwd` and forwards it into the ACP
runtime, but ACP child-session creation never persisted `spawnedCwd`. The
grouping reads only that field, so two live ACP children in one checkout got
no warning at all. Both spawn owners now resolve the explicit cwd through one
contract, `resolveExplicitSpawnedCwd()` in `spawned-context.ts` — the module
that already owns spawned working-directory metadata — and the ACP owner
persists it in the same creation patch as the native owner. The native owner
loses its two-line local copy of that normalization.

[P2] Compare canonical working-directory identities. The grouping key folded
case only on Windows and otherwise compared lexical paths, so a symlink alias
on any platform, or a case alias on a case-insensitive volume, split two
concurrent writers into separate groups. Grouping now keys on
`realpathSync.native`, memoized per distinct explicit directory (one syscall
each, on an operator/agent `list` call, not a message path). A directory that
cannot be resolved keeps its lexical form, which can only split a group and
never merge unrelated ones, so a failed probe under-reports rather than
inventing a collision. The reported `path` is the canonical directory rather
than whichever alias was named first.

Docs now state the contract both runtimes actually implement, including the
alias behavior and the fail-open case.

Validation at this head:
- pnpm tsx scripts/proof-135480-subagent-shared-cwd-advisory.ts — 8/8 runtime
  assertions across 7 scenarios, including a pre-fix control that reproduces
  the silent ACP case, real directories, a real symlink, and a real deleted
  directory. Output: ~/reports/proof-135480/run-output.txt
- node scripts/run-vitest.mjs src/agents/subagents/registry/subagent-list.test.ts
  src/agents/tools/subagents-tool.test.ts
  src/agents/subagents/spawn/acp-spawn.test.ts — 129/129 (117 + 12), including
  4 new regressions.
- pnpm tsgo:core — clean.
- node scripts/check-changed.mjs — every lane passes except `typecheck core
  tests`, which fails only in src/gateway/server.channels-start-outcomes.test.ts;
  that blob is identical to origin/main and is not in this branch's diff.

Beads: openclaw-fzif
…(review feedback)

Addresses the [P0] review finding on
src/agents/subagents/registry/subagent-list.ts: the advisory named every
peer on every row, so an ordinary `subagents list` grew as O(live runs^2)
with no cap on either the peer-id list or the reported directory.

Measured on the pre-fix head, driving the exact payload `subagents-tool`
emits for `action: "list"` (structured rows with `line` stripped, plus the
rendered text view), with UUID run ids and a realistic 129-character
checkout path:

  20 children sharing one cwd -> 30,083 B (~7,521 tokens), 380 peer ids,
                                 40 copies of the path
  50 children sharing one cwd -> 133,613 B (~33,403 tokens), 2,450 peer ids

20 is the supported maximum for one agent session (`maxChildrenPerAgent`
is `.max(20)` in src/config/zod-schema.agent-defaults.ts); 50 is the swarm
`maxChildrenPerGroup` default. AGENTS.md's model-context budget makes an
unbounded model-visible item a release blocker.

What changed:

- `SubagentSharedCwd` now carries an exact `peerCount` scalar plus
  `peerRunIds` capped at `SHARED_CWD_PEER_SAMPLE_MAX` (3). Total peer ids
  emitted per list call drops from n*(n-1) to min(3, n-1)*n — 380 -> 60 at
  n=20, 2,450 -> 150 at n=50.
- The reported directory is capped at `SHARED_CWD_PATH_MAX_CHARS` (72),
  computed once per group. The cap keeps the path's TAIL via the existing
  surrogate-safe `sliceUtf16Safe`, because sibling checkouts share long
  leading prefixes and head-preserving truncation would render distinct
  groups identically. Grouping continues to use the full canonical path,
  so two checkouts differing only past the cap stay separate groups.
- The text suffix reads `peerCount`, never `peerRunIds.length`; reading the
  truncated sample's length would have silently reported "3 other runs" for
  a group of 20.
- The per-row peer walk no longer filters the whole group: it collects only
  the sample, so the work is bounded too, not just the output.

Validation on this tree:

- `pnpm vitest run` on the three branch-owned suites (subagent-list,
  subagents-tool, acp-spawn): 131/131 pass. Two new regressions pin the
  caps and fail on the pre-fix source (peerCount undefined; reported path
  167 chars > 72).
- `pnpm tsx scripts/proof-135480-subagent-shared-cwd-advisory.ts`: 14/14
  runtime assertions pass, including a new scenario 8 that measures the
  real emitted payload at 20 and 50 sharing children. The same proof fails
  7/14 against the pre-fix source and exits 1.
- `pnpm tsgo:core`, `pnpm oxlint`, `oxfmt --check`, `pnpm config:schema:check`,
  `pnpm plugin-sdk:surface:check`, `git diff --check`: clean.
- `pnpm check:changed`: 12 lanes pass; the single failing lane (`plugin
  boundaries`) fails identically on pristine `origin/main` (c7cf49e)
  with the same "5 compatibility record(s) are due for removal", and our
  diff touches no plugin-sdk, extensions or packages file. Inherited.
- `pnpm tsgo:core:test` reaches only the inherited errors in
  src/gateway/server.channels-start-outcomes.test.ts, whose blob
  (9166d13) is identical to `origin/main`.

Beads: openclaw-fzif

Co-Authored-By: Claude Opus 5 <[email protected]>
The committed proof harness scripts/proof-135480-subagent-shared-cwd-advisory.ts
is invoked manually from the PR evidence, so nothing in the tree imports it and
Knip's full-tree unused-file scan reported it, failing check-dependencies.
Register it as an executable root in repositoryScriptEntries, matching the
existing manually-invoked script entries.

Validation: pnpm deadcode:unused-files (production and full-tree scans both 0
entries), oxfmt --check config/knip.config.ts, pnpm oxlint config/knip.config.ts,
git diff --check, and pnpm tsx scripts/proof-135480-subagent-shared-cwd-advisory.ts
(all runtime assertions passed).

Beads: openclaw-fzif
The shared working-directory advisory read its report order out of
encounter order. `buildSharedCwdIndex` iterated its grouping `Map` in
insertion order and sliced each group's `runIds` in accumulation order,
and both of those come from `sortSubagentRuns`, which compares start
timestamps only. Runs that started in the same millisecond therefore
keep whatever order the caller's array happened to have, so permuting an
equal-timestamp cohort moved the group ids and the sampled members — and
past the eight-group cap it changed which directories were reported at
all, for identical live state.

Order the report before the caps narrow it: groups by descending
live-run count, so the cap keeps the most contended directories, with
the canonical grouping key as the tiebreak; samples by run id. One group
exists per key and one record per run id, so both tiebreaks are unique,
each comparator is a total order, and the reported ids, samples, and
directories are a function of the live runs alone.

Numbered-list targeting is untouched: row indices still come from
`buildSubagentRunView`, and this change only reorders the advisory's own
group array and its bounded samples.

Validation (worktree, pinned pnpm 12.3.4):
- pnpm vitest run src/agents/subagents/registry/subagent-list.test.ts
  src/agents/subagents/spawn/acp-spawn.test.ts
  src/agents/tools/subagents-tool.test.ts — 134 passed. The new
  permutation regression and the alias sample assertion both fail
  against the pre-change source, so the coverage bites.
- pnpm tsgo:core, pnpm tsgo:core:test — clean.
- pnpm check:changed (base origin/main) — exit 0 across all 44 lanes,
  including `plugin boundaries` (eligibleForRemoval=0 on this base).
- pnpm oxlint / oxfmt --check on the touched files, git diff --check — clean.
- pnpm tsx scripts/proof-135480-subagent-shared-cwd-advisory.ts — all
  runtime assertions passed, including a new scenario that permutes the
  25-group / 50-child equal-timestamp cohort and asserts the whole report
  is unchanged.

Beads: openclaw-y816
Refresh against pinned fork main with the reviewed standalone repairs.
Current-source checks and historical receipt reuse are enforced by the
publication preflight; integration remains at its published rebuild-ready head.

Evidence: standalone-tail-repairs-v39.json and current tail review receipts.
Upstream discussion: repaired-tail-upstream-reconciliation-v44.md.
Remaining product-acceptance and live-proof limits remain explicit.

Beads: openclaw-rgo7
Internal integration input; combined validation pending.
…cwd-advisory

# Conflicts:
#	src/agents/subagents/registry/subagent-list.test.ts
#	src/agents/subagents/registry/subagent-list.ts
…cwd-advisory

# Conflicts:
#	src/agents/subagents/spawn/subagent-spawn-child-plan.ts
…iew feedback)

ClawSweeper Revision 20 [P2]: the shared-cwd advisory resolved `spawnedCwd`
through its own `listSessionEntriesReadOnly` call with no `sessionKeys`
selection, then built an `Object.fromEntries` lookup over the result. The
accessor materializes its listing with `Array.from`, and `sessionKeys` is what
filters before the summaries are yielded — so omitting it created one summary
object per session in the store, plus a mapped pairs array and a lookup object
on top, on every `subagents list` call and on active-child context
construction. It ran for the first retained live child regardless of whether
any child had an explicit cwd, because the lookup happened before the
`spawnedCwd` check. `projection: "list"` still excluded saved prompt payloads,
so this was unnecessary metadata allocation, not renewed prompt decoding, and
the existing decode assertion could not see it.

`buildSubagentList` already loads exactly the visible children through
`loadSubagentSessionEntries`, which does pass `sessionKeys`. `buildSharedCwdIndex`
now takes that map instead of a config plus a per-store cache, and
`resolveSessionEntryForKey`, `resolveStorePathForKey` and `SessionEntryResolution`
are gone. The reuse is total rather than best-effort: every run the advisory
considers passes `isRetainedUnendedSubagentRun` at the same `now`, and
`buildSubagentRunView` puts exactly those runs in `active`, so their child
session keys are always part of the requested selection. Deterministic ordering
and the model-visible output bounds are untouched.

Coverage now detects unrelated summary allocation, not only prompt decoding.
`listSqliteSessionEntriesFromDatabase` materializes its listing with one
`Array.from(iterateSessionEntriesForListing(...))`, so both the new unit test and
proof scenario 9 count real accessor work by wrapping that built-in — no mock of
the seam under test.

Measured on this tree, four visible children (two sharing one explicit cwd, one
inherited, one ended):

  proof scenario 9   store 54 rows   pre-fix 2 listings / 58 summaries
                                     post-fix 1 listing / 4 summaries
  proof scenario 9   store 604 rows  pre-fix 2 listings / 608 summaries
                                     post-fix 1 listing / 4 summaries
  unit test          store 28 rows   pre-fix 32 summaries, post-fix 4

Reverting only the production file on the same tree fails both — the proof exits
1 on "only the visible children are materialized" and "materialization is flat in
store size", and the unit test fails 32 !== 4.

Validation, all exit 0: tsgo:core, tsgo:core:test, tsgo:scripts,
deadcode:unused-files, deadcode:full, check:assertion-safety,
check:max-lines-ratchet, config:schema:check, plugin-sdk:surface:check,
repo-wide oxfmt --check, oxlint, git diff --check,
subagent-list.test.ts 35/35, and the proof harness
(pnpm tsx scripts/proof-135480-subagent-shared-cwd-advisory.ts).

Beads: openclaw-cy3n
…cwd-advisory

# Conflicts:
#	src/agents/subagents/registry/subagent-list.test.ts
#	src/agents/subagents/registry/subagent-list.ts
…cwd-advisory

# Conflicts:
#	src/agents/subagents/registry/subagent-list.test.ts
#	src/agents/subagents/registry/subagent-list.ts
#	src/agents/subagents/spawn/acp-spawn.test.ts
#	src/agents/tools/subagents-tool.test.ts
#	src/agents/tools/subagents-tool.ts
…cwd-advisory

# Conflicts:
#	src/agents/subagents/registry/subagent-list.ts
#	src/agents/subagents/spawn/acp-spawn.test.ts
#	src/agents/tools/subagents-tool.ts
#	src/auto-reply/reply/commands-subagents/action-list.ts
…view feedback)

The shared-working-directory advisory looked its metadata up by
`run.childSessionKey` while `readSubagentListSessionEntries` stores that
selection under `run.runId`. For every ordinary child those two strings
differ, so the lookup returned `undefined`, every child was skipped, and
`sharedCwdGroupTotal` stayed 0 even with two live children in one explicit
directory. The whole feature was dead at the reviewed head.

Root cause is a silent main-merge drop, not an authoring mistake. At the
branch's last author commit (5a6f6b2) the branch owned
`loadSubagentSessionEntries`, which keyed entries by session key, and both
consumers read by session key — consistent. Upstream openclaw#166550 then replaced
that reader with `readSubagentListSessionEntries`, keyed by run id so two
agents sharing one raw session key keep separate metadata, and updated the
row builder it could see. `buildSharedCwdIndex` is this branch's own code,
so the merge left its session-key lookup in place and produced no conflict
marker: the two edits never textually overlapped.

Fix the consumer, not the producer — the run-ID keying is the contract
openclaw#166550 exists to provide. The JSDoc now states that key contract where the
lookup happens, since nothing else in the file did.

Verified end to end rather than at the named line: the reader batches by
resolved owner store and stores per run; `buildSharedCwdIndex` iterates
`runView.latest` filtered by `isRetainedUnendedSubagentRun`, and every such
run is in `view.active`, which is exactly what the reader requested, so each
considered run always has an entry. `projection: "list"` strips only the
three session-entry snapshot fields, never `spawnedCwd`. The row builder at
the same call site already used `run.runId`. `subagent-active-context.ts`
passes an empty selection deliberately, so the prompt block carries no
advisory by design.

Added a regression test for the case the key contract exists for: two agents
sharing the raw child session key `global`, each with its own resolved store
— silent on distinct directories, grouped on a shared one. Added proof
scenario 9, which asserts the reader's key set directly and then feeds that
exact selection to the builder, so a producer/consumer key disagreement
cannot pass again.

Removed the low-value test
`src/agents/tools/subagents-tool.test.ts: "surfaces the shared-cwd advisory
in structured list output"` at the reviewer's request. It supplied the whole
advisory through a mocked list builder and asserted the same data back, so it
passed while real grouping was broken; its only non-trivial assertion covered
upstream's pre-existing row `line` stripping. With it and its mock scaffolding
gone, that file is byte-identical to origin/main.

Measured, reverting only this finding's own source file:
- src/agents/subagents/registry/subagent-list.test.ts: 8 failed / 20 passed
  -> 29 passed. The new raw-session-key test alone moves 8 failures to 9 on
  the old key, so it pins the contract independently.
- scripts/proof-135480-subagent-shared-cwd-advisory.ts: EXIT 1, 11 failed /
  4 passed -> EXIT 0, 17 passed.

Beads: openclaw-cy3n

Also fixes a red gate lane the PR body had written off as environmental.
`check:line-cap-ratchet` does run on this host under git 2.55 and rejected
`src/agents/subagents/spawn/acp-spawn.test.ts` at 1303 -> 1353 counted lines
against a 1000-line cap: this branch's two ACP explicit-cwd cases. They moved
into `acp-spawn-policy.test-support.ts`, which already owns what root an ACP
spawn receives and what the session writer records for it and already holds
both mocks, so no new parameter is threaded and `acp-spawn.test.ts` is now
byte-identical to origin/main. No coverage was trimmed and no cap suppressed.
Because `check:changed` bails at its first failed lane, that red had kept every
later lane unexercised.

A second lane the ratchet red had hidden: `lint core` reported 19
`typescript(no-floating-promises)` errors, every one an unawaited
`addSubagentRunForTests(...)` in this branch's own shared-cwd tests. They are
now awaited. That is not only a lint fix — the helper performs a durable
registry write, so each call was a real race between the fixture and the list
build it was meant to set up. Type-aware rules need the gate's own
`config/tsconfig/oxlint.core.json`; a bare `pnpm oxlint <files>` does not run
them and reported these files clean.
… (review feedback)

A sender-restricted helper is handed the requester's own root as its
`spawnedCwd` even when the spawn request named no cwd: the native owner
resolves `childCwd = requestedCwd ?? (senderRestricted && !childRuntimeSandboxed
? requesterRoot : undefined)` in `subagent-spawn-child-plan.ts`, and the ACP
owner's restricted creation patch sets `spawnedCwd: runtimeCwd` in
`acp-spawn.ts`. `buildSharedCwdIndex` treated any persisted `spawnedCwd` as an
explicit request, so two such helpers of one sender were reported as a
shared-directory collision — the inherited-workspace case the advisory
documents as exempt. The previous head skipped every ordinary child before
reaching grouping, so this path only became reachable with the run-ID key fix.

The discriminator is already persisted. `senderRestricted` is literally
`ctx.inheritedToolPolicySource === "sender"` at both owners, and both owners
refuse any cwd that is not the requester root for such a sender
(`resolveSubagentChildPlan`'s guard, `resolveAcpSenderSpawnError`). A restricted
helper's `spawnedCwd` is therefore always the policy root and never a chosen
directory, and the entry carries `inheritedToolPolicySource` through the `list`
projection the advisory already reads. Grouping now skips those runs and leaves
the stored cwd untouched, so the restriction that put it there still holds:
`prepare.ts` resolves a session's run cwd from `spawnedCwd`, and clearing it
would drop a restricted helper back to `resolveAgentRunCwd`.

Measured, each control on its own:
- fix reverted with the tests kept: `subagent-list.test.ts` 2 failed / 29
  passed ("stays silent for sender-restricted helpers handed the requester's
  root", "keeps reporting an unrestricted peer when one run of the pair is
  restricted"), and proof scenario 10's advisory assertion fails.
- the naive shape of clearing the inherited cwd at both owners:
  `acp-spawn.test.ts` 1 failed / 47 passed and
  `subagent-spawn.workspace.test.ts` 1 failed / 22 passed, both the
  restricted-root enforcement case.

Tests: removed `"pluralizes the suffix and excludes self from peers for three
sharing runs"` at the reviewer's request — its assertions repeat the
pair-grouping and 20-child sampling coverage and its name still describes the
per-row peer list this PR replaced with a bounded summary. The three new cases
(restricted silence, an identical-directory control without the policy marker,
and a mixed group pinning that the exemption is per run) go in a new sibling
file `subagent-list-shared-cwd-policy.test.ts`: `subagent-list.test.ts` already
sits at the oxlint `max-lines` cap and `check:line-cap-ratchet` rejects any
growth in it, and the split follows a real seam — the new file is about how a
run's cwd was decided, the old one about how decided directories are grouped,
canonicalized, capped and rendered. The ACP owner test now also asserts the
persisted `spawnedCwd`, so the reader fixture matches a shape a real owner test
pins. Proof harness gains scenario 10 and its stale
reference to `acp-spawn.test.ts` for the ACP cwd cases is corrected to
`acp-spawn-policy.test-support.ts`, where they have lived since the last round.

Beads: openclaw-cy3n

Co-Authored-By: Claude <[email protected]>
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Nov 11, 2026
@clawsweeper

clawsweeper Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the contribution. ClawSweeper is trimming this lowest-signal PR because the author is over the repository's open-PR budget.

@zeroaltitude currently has 19 open PRs in this repository, above the budget of 15. ClawSweeper is closing this PR as one of the author's lowest-signal submissions under that budget: its overall rating is C and its real behavior proof is insufficient. Closing or finishing other PRs frees review budget, and this PR can be reopened once the author is under budget or when real proof is added.

Root-cause cluster
Relationship: canonical
Canonical: #197123
Summary: This PR carries forward the same advisory from its closed, unmerged predecessor; the merged raw-key listing repair is a supporting contract rather than a replacement.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Closing or finishing other open PRs frees review budget. This PR can be reopened once the author is under budget, or sooner when real behavior proof is added.

Review details

Best possible solution:

Close this lowest-signal PR for now. Finish or close other open PRs to free review budget, then reopen this PR once the author is under budget; adding real behavior proof also makes it eligible for reconsideration.

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

Current-main source confirms the missing advisory; this review inspected contributor captures without running target code.

Is this the best way to solve the issue?

The missing signal belongs in the existing list owner, with explicit-directory metadata supplied by spawn owners and bounded output shared across listing surfaces.

Security review:

Security review cleared: No concrete authorization, credential, dependency, or execution-boundary regression was found.

AGENTS.md: found and applied where relevant.

What I checked:

  • live author budget: @zeroaltitude has 19 open PRs in this repository; the configured budget is 15.
  • lowest-signal classification: overall PR rating is C and real behavior proof is insufficient.
  • inactivity floor: the PR and its current-head commit, status, and check-run activity are all older than 7 days.

Likely related people:

  • Peter Steinberger: Raw commit eed403d adds src/agents/spawned-context.ts:5 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: eed403dc74b5; files: src/agents/spawned-context.ts)

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

@zeroaltitude
zeroaltitude marked this pull request as ready for review November 11, 2026 22:22
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-11T22:33:06.184989Z 70e9331 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 70e93310fa

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/subagents/spawn/acp-spawn.ts Resolved
zeroaltitude and others added 3 commits November 11, 2026 16:08
…growth (review feedback)

The advisory reports a directory capped at 72 characters. CI shards nest the
vitest temp root (/tmp/oc-vt-*/oc-vt-*/...), pushing fixture paths past the cap,
so assertions on the full path failed there (8 tests across
subagent-list.test.ts and subagent-list-shared-cwd-policy.test.ts). Assert the
display form through a small test-support helper instead.

Also add the exact net-growth test-lines allocation for the baseline ratchet.

Co-Authored-By: Claude <[email protected]>
…l writers (review feedback)

Three corrections to how `subagents list` groups live runs by directory:

- ACP runs are grouped by the manager-owned effective cwd
  (`SessionEntry.acp.cwd`) when the backend reported one. `spawnedCwd` still
  decides whether a directory was named at all, but it is the request, and
  grouping on it could miss a real collision or report one for a directory
  the child is not using.
- A sender-restricted helper counts as a member of its directory's group.
  Only a group made entirely of such helpers is dropped; next to a run whose
  cwd was chosen the helper is a second live writer and that run can move.
- The grouping key is the canonical identity as-is. `realpathSync.native`
  already collapses case aliases on a case-insensitive volume, and folding
  case again by `process.platform` merged distinct checkouts where a Windows
  directory has opted into case sensitivity.

Each change has a regression case in subagent-list-shared-cwd-policy.test.ts
that goes red when its fix is reverted on its own.

Co-Authored-By: Claude <[email protected]>
@zeroaltitude

Copy link
Copy Markdown
Contributor Author

Review round reply — current head 9a861a7aebe18f897bce634f5232f740104916ea. No new commits this round: the one code finding was already repaired after the reviewed head, and the remaining work was evidence. Body updated with proof measured at this exact head.

Before merge

1. Add real behavior proof — partially addressed, and I am being explicit about what is still missing.

Re-ran the committed harness at 9a861a7aebe:

node --import ./scripts/tsx.mjs scripts/proof-135480-subagent-shared-cwd-advisory.ts
...
   20 children sharing one cwd: 7522 B model-visible, 1 directory summary
   50 children sharing one cwd: 17602 B model-visible, 1 directory summary
   ✓ 50 children across 25 shared directories emit only eight summaries
   ✓ two restricted helpers in one root produce no advisory
   ✓ the same directory without the policy marker is still reported

All runtime assertions passed.

20 assertions, exit 0. Real in that run: resolveExplicitSpawnedCwd(), upsertSessionEntryCore() with the exact creation patch acp-spawn.ts builds against a real on-disk session store, readSubagentListSessionEntries(), buildSubagentList(), handleSubagentsListAction(), and real directories/symlink/deleted-directory on disk. The advisory surfaces when live children share an explicitly selected directory and stays absent when they do not, both directions measured.

Still not supplied, and the PR body now says so in the same words: redacted output from real native and ACP spawn-to-list flows through a running Gateway. Launching a child needs a live Gateway, a provider credential and a real model turn, which the offline harness does not stand up.

I also tried to close part of that gap by driving the shipped subagents tool object itself — createSubagentsTool().execute("list", { action: "list" }) — rather than reassembling its payload. That did not complete: the tool's controller read (createSubagentControllerRead().prepare()) does not settle without an admitted Gateway session-capability source, so the entry point hangs offline instead of returning a payload. The attempt is not committed and nothing in the body depends on it; I am reporting it so the gap is understood as an entry-point admission limit rather than an untried shortcut.

2. Make directory assertions independent of temporary-root length [P2] — already fixed in 8928b055c91, which landed after the reviewed head 70e93310fabf.

The suites no longer assert the full absolute path. Both subagent-list.test.ts and the sibling subagent-list-shared-cwd-policy.test.ts now assert the advisory's documented capped display through a small shared helper (src/agents/subagents/registry/subagent-list.test-support.ts), so a long os.tmpdir() — macOS, a long TMPDIR, or a nested CI vitest temp root such as /tmp/oc-vt-*/oc-vt-*/... — no longer fails a correct implementation. That was 8 tests across the two files. Exact grouping and runCount checks are unchanged, and a past-the-cap sibling-checkout case is covered (✓ sibling checkouts past the display cap remain distinct groups in the run above).

Findings

[P2] src/agents/subagents/registry/subagent-list.test.ts:579 — same item as above; fixed in 8928b055c91.

Tests

Low-value test — scenario 9's direct assertions about the internal Map key set. Not changed; here is the reasoning, and I will drop it if you still want it gone. The scenario asserts the reader's key set and then feeds that exact selection object to buildSubagentList, so the outcome assertion you prefer is already the second half of it. The reason the key-set assertion is kept is that it is the only thing that distinguishes a producer/consumer key disagreement from an empty selection: child session keys repeat across agents (#166550), so if the reader ever re-keyed by child session key the outcome assertion alone would fail as "no groups" with no indication of why. It pins a contract between two modules rather than a private implementation detail, which is why I would rather keep it than trade it for a less diagnostic failure.

Missing end-to-end proof. Outstanding, as described under item 1.

Decision needed

Left for the area owner: whether explicit shared-directory collision summaries should become part of the core subagents list contract. I am not deciding that here. ClawSweeper's own recommendation was to accept the bounded advisory; the PR keeps directory selection entirely under caller control and the advisory is informational — it never refuses or cancels a spawn.

Validation

No source, test, doc or config file changed this round, so the gates from the previous round stand; the only thing re-run was the proof harness above (exit 0 at 9a861a7aebe). The worktree is clean at origin/feat/subagent-shared-cwd-advisory.

Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).

@zeroaltitude

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

…eview feedback)

The committed proof harness asserted the advisory's reported directory against
the raw absolute path in five places. The advisory keeps only the last 72
characters of a longer directory, so a deep temporary root (a nested CI runner
directory, or a macOS private temp root) makes a correct advisory fail the
harness. Compare through `expectedSharedCwdPath()` instead — the same display
helper the two owner suites already use — so the harness has one source of
truth for the cap. The stored-entry assertions keep comparing the full resolved
path, which is what the writer persists.

Also drops scenario 9's direct Map-key assertions: the call immediately after
them feeds that same reader selection into `buildSubagentList`, which is what
detects a producer/consumer key disagreement, and cross-agent raw-key
separation is covered by `subagent-list.test.ts`.

The harness's `Run:` line said `pnpm tsx`, which installs tsx's CJS require
hook and breaks plugin loading; it now names the supported invocation.

Beads: openclaw-feuq
Co-Authored-By: Claude <[email protected]>
@zeroaltitude

Copy link
Copy Markdown
Contributor Author

Update at head 3bc860565be.

Code finding. The P3 on the proof harness is fixed in 3bc860565be: the capped-path scenario now compares the capped paths themselves, and scenario 9's direct Map-key assertions are removed as the review suggested. The commit touches only scripts/proof-135480-subagent-shared-cwd-advisory.ts.

Real behavior proof. The body's Evidence section now opens with a capture from an installed, long-running Gateway (systemd service, built dist), taken through real sessions_spawn calls and the shipped subagents tool from a chat session, not from a script:

  • two children given the same explicit directory form one group, and both rows carry the reference; one ran on the Claude CLI runtime and one on the embedded runtime;
  • a child given a different explicit directory is not grouped;
  • six children that inherited the workspace are not grouped;
  • with one of the two sharing children ended, no group is reported.

That Gateway runs a fork integration build; the five runtime files this PR changes are byte-identical there to this head, and the body says so. The earlier in-process Gateway run (shipped tool, /subagents text, ACP records) and the two-tree stored-data compatibility proof remain below it.

Not covered, and said so in the body: nobody typed /subagents list during the production capture, and no ACP child was spawned on the production Gateway. The owner decision on adding the advisory to the core listing contract is unchanged.

Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).

@zeroaltitude

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Nov 13, 2026
@zeroaltitude

Copy link
Copy Markdown
Contributor Author

Evidence update for the ACP half, no code change (head still 3bc860565be).

The body now includes a capture of two real ACP children (sessions_spawn with runtime: "acp", the Claude Code ACP agent) started on the installed Gateway with the same explicit directory. The shipped subagents listing groups the two live ACP runs, leaves a native child in another directory ungrouped, and leaves two already-ended ACP children with the same directory out of the group. These went through the production ACP spawn path rather than constructed records.

Still open, and said so in the body: this is not an upgrade from the latest stable release. The stored-data evidence for the ACP spawnedCwd field remains the two-tree run (merge-base-written session data read and written by this head).

Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).

@zeroaltitude

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Nov 13, 2026
Preserve run-ID metadata and upstream yield observation; retain cancellation caveat and bounded advisory. Code-only review; no tests, builds, lint or hooks run at user request.

This branch has not been deployed

No deployments
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 P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant