Repository navigation
feat(subagents): warn when live children share an explicit working directory - #197123
zeroaltitude wants to merge 37 commits into
Conversation
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]>
Co-Authored-By: Claude <[email protected]>
Co-Authored-By: Claude <[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]>
|
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 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 detailsBest 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:
Likely related people:
Codex review notes: model internal, reasoning medium; reviewed against 4c8668257a22. |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
…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]>
|
Review round reply — current head Before merge1. Add real behavior proof — partially addressed, and I am being explicit about what is still missing. Re-ran the committed harness at 20 assertions, exit 0. Real in that run: 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 2. Make directory assertions independent of temporary-root length [P2] — already fixed in The suites no longer assert the full absolute path. Both Findings[P2] TestsLow-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 Missing end-to-end proof. Outstanding, as described under item 1. Decision neededLeft for the area owner: whether explicit shared-directory collision summaries should become part of the core ValidationNo 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 Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude). |
|
@clawsweeper re-review |
|
🦞👀 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]>
|
Update at head Code finding. The P3 on the proof harness is fixed in Real behavior proof. The body's Evidence section now opens with a capture from an installed, long-running Gateway (systemd service, built
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, Not covered, and said so in the body: nobody typed Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude). |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Evidence update for the ACP half, no code change (head still The body now includes a capture of two real ACP children ( 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 Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude). |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
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.
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 listshowed 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
cwdthrough the sameresolveExplicitSpawnedCwd()contract native children already use.senderRestrictedisctx.inheritedToolPolicySource === "sender"at both owners, and both owners refuse anycwdthat is not the requester root for such a sender, so a restricted helper'sspawnedCwdis always the policy root and never a chosen directory.inheritedToolPolicySourceis a hotSessionEntryfield the advisory already reads, so no new field crosses a Gateway boundary and no protocolclosedObjectchanges.SessionEntry.acp.cwdwhen the ACP backend reported one,spawnedCwdotherwise — with canonical on-disk identity and a lexical fallback when a recorded directory no longer resolves.sharedCwdGroupId; all other rows are unchanged.sharedCwdGroupTotaland each group'srunCountpreserving exact counts even when display details are omitted. Order by stable keys before the caps apply, so identical live state always produces identical output.subagentstool and native/subagentstext.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
cwdto mark explicitness — breaks the restriction that put it there:prepare.tsresolves a session's run cwd fromspawnedCwd, so clearing it drops a restricted helper back toresolveAgentRunCwdand 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
collectswarm 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 parent9a861a7aebe18f897bce634f5232f740104916ea;3bc860565bechanges exactly one file — the committed proof harnessscripts/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
subagentstoolThis 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 head3bc860565be(git diff --quietper file; the latest commit changes only the proof script).From a Discord direct session, the agent spawned real children with the shipped
sessions_spawntool and then called the shippedsubagentstool withaction: "list". Children A and B were givencwd: /tmp/r3-shared-cwd/work, child Ccwd: /tmp/r3-shared-cwd/other, and six unrelated working children had nocwd(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
textfield of the same result, which is what the model reads: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_spawntool usingruntime: "acp"(the Claude Code ACP agent) andcwd: /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. Thesubagentslisting 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"}]}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 listslash command was not typed by a person during the capture (the tool'stextfield 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 ACPspawnedCwdfield 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
A real Gateway is started first, with isolated state
startGatewayServer()runs withbind: "loopback", a random token andcontrolUiEnabled: falseagainst a throwawayOPENCLAW_STATE_DIR/OPENCLAW_HOME/OPENCLAW_CONFIG_PATHunder/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, becausecreateSubagentControllerRead().prepare()has no admitted Gateway capability source. A passing run is itself evidence the Gateway is live.The shipped model-facing
subagentstool and the real/subagentscommandThe 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 archiveof the merge-base8408f1b57558d36d7bb21bf979a6275c46c20099, run from that tree, storing six session entries through the base release's ownupsertSessionEntryCore(): an owner session with ordinary settings (model,agentId,thinkLevel), two native children carryingspawnedCwd, two ACP children with nospawnedCwd(the gap this PR closes), and one lone native child. The base code materialized a real 692 KBopenclaw-agent.sqliteagent database (confirmed independently withnode:sqlite: six rows insession_nodeswith base-shapedentry_json). This head then opens those exact stored bytes:The last two assertions are the upgrade case: this head persists a new ACP child's
spawnedCwdinto 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 comparesdeepEqualto its pre-write snapshot. Nothing sensitive appears in the output to redact: throwaway state dir, no credentials, no private endpoints,/tmppaths only.Real vs stubbed in this round's proof
createSubagentsTool()andexecute("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.Round 1 — production readers and renderers, run out of process (earlier round)
Key lines of the real output (full run in the collapsed block below):
20 assertions, exit 0 at that head; 19 at the current head, where
3bc860565bedropped 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 writeracp-spawn.tscalls, given the exact creation patch that owner now builds) against a real on-disk session store under a tempOPENCLAW_HOME;readSubagentListSessionEntries()andbuildSubagentList()(the changed owner);handleSubagentsListAction()(the real/subagentstext 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:
src/agents/subagents/spawn/acp-spawn-policy.test-support.ts. So this is not live spawn-to-list proof.subagentstool object is not driven. Scenario 8 measures the model-visible payload by assembling the same fieldssrc/agents/tools/subagents-tool.tsemits foraction: "list", rather than callingcreateSubagentsTool().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.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.
3bc860565becompares throughexpectedSharedCwdPath()— 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: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 oxlint0 warnings / 0 errors;pnpm oxfmt --checkclean;git diff --checkclean;pnpm check:line-cap-ratchet"no new violations or over-cap growth";check-test-lines-ratchet.mts --base origin/main --no-merge-baseOK (6668555, ceiling 6668555);pnpm tsgo:scriptsexit 0.pnpm tsgo:core/tsgo:core:testwere not re-run: no TypeScript undersrc/orextensions/changed in this commit.Discrimination, two controls measured separately
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 failingcwdat both owners)acp-spawn.test.ts1 failed / 47 passed andsubagent-spawn.workspace.test.ts1 failed / 22 passed, in both cases the restricted-root enforcement caseControl 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
bbc24b971d4and are not re-measured at9a861a7ae.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.tssits at the oxlintmax-linescap of 1000 counted lines whoseorigin/mainbase is under the cap, socheck:line-cap-ratchettreats 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 longos.tmpdir()(macOS, a nested CI vitest temp root, a longTMPDIR) no longer fails a correct implementation. Exact grouping and count checks are retained, and a past-the-cap sibling-checkout case is covered. As of3bc860565bethe 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,aa0c15c8bfdandbbc24b971d4heads 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 merge26e8beb1c13; and the claim thatcheck: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)Full proof script —
scripts/proof-135480-subagent-shared-cwd-advisory.ts(ships in this PR's diff)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).