Repository navigation
fix(acp): run session/new prompts in the requested cwd - #123585
Chinmayrawat15 wants to merge 14 commits into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs real behavior proof before merge. Reviewed September 18, 2026, 1:38 AM ET / 05:38 UTC (Revision 27). ClawSweeper reviewWhat this changesThe ACP bridge persists requested working directories through Gateway session creation, negotiates create-only directory handling, and suppresses unverified directory claims when loading existing sessions. Regression provenancePossible regression — suspected (reviewed change). No predecessor PR is attributed. Merge readiness⛔ Blocked before merge - 9 items remain The fix remains necessary on current main and the latest release. Keep this PR open: its fresh-session proof is useful, but adoption still changes an existing session’s filesystem permission boundary, and the branch remains conflict-marked. Priority: P1 Review scores
Verification
How this fits togetherThe ACP bridge connects editors and command-line clients to OpenClaw Gateway sessions. Gateway-owned session state determines the working directory and filesystem permissions used by subsequent agent turns. flowchart TD
A[Editor or ACP client] --> B[ACP session setup]
B --> C[Gateway capability check]
C --> D[Create or adopt session]
D --> E[Stored directory and permissions]
E --> F[Agent turn and filesystem tools]
E --> G[ACP directory claims]
Decision needed
Why: The patch intentionally replaces successful attachment with errors; the contributor discussion does not establish maintainer acceptance of that compatibility change. Before merge
Findings
Agent review detailsSecurityNeeds attention: Create-only cwd handling leaves an unintended persisted change to the adopted session’s filesystem confinement; no dependency or supply-chain changes were introduced. PR surfaceSource +117, Tests +302, Other +4. Total +423 across 20 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Use one Gateway-owned create/adopt decision that preserves an adopted session’s complete execution policy and reports only known runtime facts; capability negotiation warrants some growth, while cwd lookup can reuse the existing snapshot read. Do we have a high-confidence way to reproduce the issue? Yes, from source: current main records ACP cwd without passing it to Gateway-owned session state. On the proposed branch, adopting a workspace-mode session with a different requested directory preserves spawnedCwd but replaces sessionRoot; no runtime reproduction was executed during this read-only review. Is this the best way to solve the issue? Not yet. Persisting cwd at the Gateway owner is preferable to adding a competing chat.send override, but the create-only decision must preserve the coupled permission root and resolve attachment compatibility. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against ec7fed214284. LabelsLabel justifications:
EvidenceSecurity concerns:
What I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (26 earlier review cycles; latest 8 shown)
|
|
Rank-up move addressed — the PR body now carries the requested real-behavior proof. The ask was: "Add a redacted ACP stdio-to-isolated-Gateway transcript showing Harness is all real processes: built
The observed agent cwd is the decisive one. Pre-fix, the model receives two contradictory statements in the same turn — the bridge's message prefix says Two notes on the evidence, for transparency:
Remaining gap is stated in the PR body: @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Finding addressed: [P1] Provision non-existing explicit session keys — you were right, and the PR body is updated. My earlier guard treated "explicit route" as a proxy for "operator-owned session already exists". That assumption is wrong: The fix now branches on row existence rather than routing category, which covers both merge risks you listed:
Refreshed proof, as requested — same real harness (built
The default workspace appears in neither model payload, and the relative-cwd rejection still holds. Two things I want to flag rather than leave implicit:
Production LOC is +24 / −3 (tests +87), above the net-≤0 default. Naming it rather than burying it: the growth is the ownership boundary — distinguishing an absent row from an operator-owned one is the correctness requirement here, and collapsing it into a smaller guard reintroduces one of the two failure modes. The Full ACP suite: 182 files / 1442 tests green. autoreview clean on both revisions. @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Finding addressed: [P1] Make routed session creation atomic — you were right that a check-then-create cannot hold this invariant from outside the Gateway, and the decision has moved inside the mutation exactly as you described.
This resolves all three merge risks together. A missing explicit key still gets its cwd; an operator-owned row is safe with no probe window; and because the bridge no longer reasons about existence at all, the ACP-side probe and the duplicate snapshot branch are deleted rather than added to — I also reverted the The race is now proven deterministically. A Gateway test creates a session with one directory, then issues a second A companion test proves the flag still sets the directory on a genuinely new row. Refreshed proof. I re-ran the real ACP-stdio → isolated-Gateway harness against this build (not the previous one), covering both routes in one run: bridge-minted → Protocol follow-through: the field is additive and optional; I regenerated the Swift bindings ( On the two points about the SDK contract and LOC:
One non-green check, and it is not this change: @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Both findings answered. One is fixed; the second is the owner decision you asked for, and I have evidence that narrows it. [P1] Reject or synchronize an adopted session's cwd — fixedGood catch, and it is the original defect relocated rather than a new one: with the Gateway keeping an adopted row's directory, the bridge was still storing the requested cwd in its own session state, and both the visible The bridge now reads the authoritative value back instead of assuming its request won: const created = await this.gateway.request<{ entry?: { spawnedCwd?: string } }>("sessions.create", …);
const sessionCwd = normalizeOptionalString(created?.entry?.spawnedCwd) ?? params.cwd;The Gateway owns the run directory, so the bridge records what the turn will actually use. Fresh sessions are unaffected (the row reports the requested cwd back). New regression test, failing pre-fix for the right reason: [P1] Negotiate the new Gateway request field — owner decision, with precedentYou flagged this as requiring an owner decision, so I am not going to bump
So an optional additive request field on this schema has twice shipped without negotiation, and the older-Gateway exposure being described applies identically to I would rather state the residual risk plainly than argue it away: because the params object is closed, a Gateway built before this field would reject One thing I would push back on gently: dropping the field and returning to a caller-side probe would reintroduce the P1 race from the previous round, so "remove it" is not a safe resolution to this one. Also still standing, and not caused by this change: Full ACP suite 182 files / 1442 tests green; autoreview clean at 0.85. @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
The bridge decided whether a Gateway row existed by probing sessions.list and then calling sessions.create, so a row created between the probe and the write was adopted and had its owner's spawnedCwd overwritten by the bridge's cwd. sessions.create gains an opt-in cwdOnCreateOnly, applied where the mutation already knows whether it created the row. The bridge now calls create unconditionally with that flag, which removes the probe and the duplicate snapshot branch while making absence a Gateway-owned decision.
Additive optional field on SessionsCreateParams; existing clients decode unchanged.
When the Gateway adopts an existing session row it keeps that row's spawnedCwd, but the bridge stored the requested cwd in its own session state. The visible working-directory prefix and the provenance receipt are built from that state, so an adopted session told the model one directory while the turn ran in another. The bridge now reads spawnedCwd back from the create response and records that, falling back to the requested cwd when no entry is returned.
An adopted session key that carries no working directory runs in the agent workspace. The bridge fell back to the requested cwd in that case, so the visible directory prefix and provenance receipt claimed a directory the agent never used - the same contradiction this fix removes elsewhere. A create that passes a cwd always returns one for a new row, so a missing spawnedCwd identifies that case. session/new now fails with what to do instead. Shared translator test helpers model the sessions.create response the bridge reads, so partial mocks stop hiding this path behind a bare ok payload.
sessions.create params are a closed schema, so an ACP bridge that always sent cwdOnCreateOnly would make session/new fail outright against a Gateway built before the field, turning a bridge upgrade into a hard error. The Gateway now advertises sessions.create.cwdOnCreateOnly in its hello capabilities, the client retains the advertised set per connection, and the bridge sends the field only when it is offered. Against a Gateway without it the bridge still provisions its own minted keys, whose fresh ids cannot collide with an operator-owned row, and leaves explicitly routed keys alone rather than risk overwriting someone else's working directory.
The degraded path still started a session reporting the requested directory while the turn could use an adopted row's own directory or the agent workspace - the same contradiction this branch removes everywhere else. Routing an explicit key with a cwd to such a Gateway now fails with what to do instead. Bridge-minted keys are unaffected: nothing else can own a fresh id, so applying the directory there is safe.
… cwd Three related directory defects: Reset ran inside session-key resolution, before the capability gate and the create that carries the cwd. A requested reset could materialize a bare row that the create then adopted without a directory, and a routed request could be reset before being refused. Resolution no longer mutates; callers place their own reset, and session/new resets only after the row carries its cwd. loadSession and resumeSession stored the caller's cwd while attaching to a Gateway row that owns a different one, so prompt text and provenance could describe a directory the turn never used. Both now report the row's value. The client also drops server capabilities when the connection closes, so a reconnect onto an older Gateway cannot reuse the previous build's advertisement before its hello arrives.
An adopted Gateway session often records no directory - a session created without cwd, worktree, or project clears the field - so load and resume fell back to the caller's path and presented it as the runtime workspace through the prompt prefix and the provenance receipt. Sessions now carry whether their cwd is the directory Gateway will run in. Adoption keeps working and still reports the row's directory when it has one; when it does not, the bridge omits the claim instead of substituting the request. Refusing instead would have failed load and resume for ordinary sessions, which record no directory by design.
main deleted the cleanup-only store seam in openclaw#124043 because each test builds its own store. This branch predated that and its new cases still called it, which broke the merged result at both type-check and runtime.
`translator.lifecycle.test.ts` landed upstream after this branch was cut,
and its gateway mocks return a bare `{ ok: true }` for every unstubbed
method. `session/new` now reads `sessions.create`'s `entry.spawnedCwd`
back to decide whether the Gateway kept the requested directory, so a
mock that does not model that response looks exactly like an existing row
with no directory, and the bridge correctly refuses the request.
`acpGatewayDefaultResponse` already exists for this — its docstring asks
partial mocks to fall through to it so they keep modelling the responses
they do not stub. These mocks predate it. Routing all twelve through it
fixes the failure and stops the next unstubbed Gateway shape from
breaking the file the same way.
Test-only; no production behavior changes.
`sessions.create` now lstats the requested cwd and rejects one that is absent (openclaw#124909, "session permission modes with worktree-scoped defaults"), so the two cwdOnCreateOnly tests failed on the rebase with `cwd is unavailable: ENOENT` -- they passed fabricated /tmp paths. Switched to `tempDirs.make()`, the auto-cleanup helper the rest of this file already uses for real cwd cases. Also merged a duplicate import of `translator.test-helpers.js` that the rebase surfaced. No production change; the assertions are the same, against paths that exist.
77c11b6 to
6253b07
Compare
|
This pull request has been automatically marked as stale due to inactivity. |
|
This pull request has been automatically marked as stale due to inactivity. |
|
Closing due to inactivity. |
Closes #123557
AI-assisted contribution (Claude Code). I have read and understand the change.
What Problem This Solves
Fixes an issue where ACP clients that open a session with a specific working directory would have their agent run in the default workspace instead. An IDE extension, CLI wrapper, or automation script calls
session/newwithcwdset to a project directory, gets back a session whosesession.cwdcorrectly reports that directory, and then everyprompton that session executes in~/.openclaw/workspace.The confirming metadata is what makes this bite: the caller has positive evidence the session is scoped to their project, so files get read from and written to a directory the caller never intended.
The end-to-end capture below shows it precisely. On pre-fix code the model receives two contradictory statements in the same turn: the bridge's informational message prefix says
[Working directory: $ROOT/project], while the system prompt's own## Workspacesection saysWorking directory: $ROOT/workspace. The agent is told one thing and executes against the other.Why This Change Was Made
The requested directory was recorded only in the ACP bridge's in-memory session record. Nothing carried it to the Gateway: the bridge never creates a Gateway session,
chat.sendhas nocwdfield, and the Gateway therefore created the session lazily on the first prompt with no directory to work from. The agent turn resolves its cwd fromrequestedCwd ?? sessionEntry.spawnedCwd, andspawnedCwdwas never written.The fix records the fact at the boundary that owns it.
sessions.createalready accepts an absolutecwdand persists it asspawnedCwd, so the bridge now creates the Gateway session atsession/newand every later turn resolves it through the existing runtime path. Publicchat.sendis left alone — widening it with a competing per-requestcwdwould add a second source of truth for state the session entry already owns.Absence is decided by the Gateway, not the caller
Two earlier revisions of this PR got the ownership boundary wrong, and the fix for both is the same idea, so it is worth stating directly.
sessions.createappliesspawnedCwdeven when it adopts an existing row. So the bridge must not create over a session someone else owns — but it also cannot skip creation for explicitly routed keys, becauserequireExistingdefaults to false and an explicit_meta.sessionKey/--sessionroutes through unresolved, meaning the row may not exist at all. Deciding this from outside the Gateway is a check-then-create race: a row created between the bridge's probe and its write gets adopted, and the owner's directory is overwritten.So the decision moved to where the answer is already known.
sessions.creategains an opt-incwdOnCreateOnly, applied inside the same mutation that already computes whether it created the row — right next to the existing rule that adoption must not stamp new-row facts (provenance, visibility,projectId). The bridge now calls create unconditionally with that flag:This removes the ACP-side probe and its duplicate snapshot branch entirely; the bridge no longer reasons about session existence at all. Callers that omit the flag keep exactly the previous behavior.
The bridge reports the directory the turn will actually use
Because an adopted row keeps its own directory, the bridge must not keep assuming its request won — the visible
[Working directory: …]prefix and the provenance receipt are both built from ACP-side session state, so a mismatch there recreates the same false confirmation this PR removes.session/newnow reads the authoritative value back out of the create response and records that.That leaves one case where no honest directory exists to report: an adopted key whose row has no working directory at all. The turn will run in the agent workspace, so claiming the requested directory would be the original defect again. A create that passes a cwd always returns one for a new row, so a missing
spawnedCwdidentifies exactly that case, andsession/newfails with what to do instead rather than reporting a directory the agent will not use.Path authorization is unchanged.
sessions.createalready requires the cwd to be inside a configured agent workspace unless the caller holdsoperator.admin. The ACP bridge connects as a CLI-mode client, which getsoperator.adminby default, so the reported flow works; narrower deployments keep the Gateway's existing containment rule.session/newnow also rejects a relativecwd, matching the siblingsession/resumeand the ACP contract (NewSessionRequest.cwd: "The working directory for this session. Must be an absolute path.",@agentclientprotocol/sdkdist/schema/types.gen.d.ts:4649). Previously a relative path was silently accepted and quietly ignored — the capture below shows pre-fix code happily creating a session forrelative/project.Sibling surfaces:
session/loadandsession/resumeare adoption paths, not creation paths — they attach to a Gateway session that already exists and owns itsspawnedCwd, andresumeSessionalready requires that row viagetExistingSnapshot. They are intentionally unchanged.Older Gateways never see the new field
sessions.createparams are a closed schema, so unconditionally sendingcwdOnCreateOnlywould makesession/newfail outright against a Gateway built before it — turning a bridge upgrade into a hard error. The field is therefore capability-gated using the mechanism this repo already has: the Gateway advertisessessions.create.cwdOnCreateOnlyinHelloOk.features.capabilities(alongside entries likechat-send-routing-contract), the client retains the advertised set per connection, and the bridge sends the field only when it is offered. NoPROTOCOL_VERSIONchange.Against a Gateway that does not advertise it:
_meta.sessionKeyThe explicit-key route therefore keeps its pre-PR behavior against old Gateways — those callers keep the default-workspace bug until their Gateway updates — rather than risking someone else's state. Two consequences are deliberate and worth naming: the bridge reports the requested cwd on that degraded route even though the row may differ, and a reconnect onto a downgraded server uses the previous hello's capabilities until the new hello lands.
Protocol follow-through: the field is additive and optional, and the generated Swift bindings are regenerated in this PR (
Bool?with acwdOnCreateOnlycoding key), so existing clients decode unchanged. Kotlin anddist/protocol.schema.jsonneeded no changes. This does not reach model-visible prompt text — the agent-facing session tool schema is declared separately insrc/agents/tools/sessions-spawn-visible.ts, and no protocol-only field (emitCommandHooks,spawnDepth,catalogId,succeedsParent) appears in the prompt snapshots.Production LOC: +113 / −17 (tests +285/−14, generated Swift +5/−1), 15 files. That is well above the net-≤0 default for a bug fix and I am not going to present it as small. Roughly half is capability negotiation, which exists because shipping the field unconditionally breaks mixed-version pairings; the rest is the ownership boundary itself and the adoption-path repairs. Every increment traces to a review finding on this PR rather than scope I chose, and the one absorbing refactor available — moving absence into the Gateway mutation — was taken and removed the caller-side probe. Above the net-≤0 default, so naming it rather than burying it: the growth is a public protocol capability — opt-in create-if-absent semantics for a caller provisioning a key it may not own — plus the ACP contract assertion. Moving the decision into the Gateway is what let the ACP-side probe and duplicate snapshot branch be deleted rather than added to.
User Impact
ACP callers that scope a session to a project directory now actually get their agent running there — whether they let the bridge mint a session key or name one themselves with
_meta.sessionKey/--session. IDE extensions, CLI wrappers, and automation that passcwdtosession/newstop silently operating in~/.openclaw/workspace, which removes the risk of the agent creating or modifying files in the wrong directory whilesession.cwdreports the intended one. Sessions an operator already owns keep the directory they already had, with no window in which a concurrent creation could change it.session/listalso reports the real directory for bridge-created sessions.A relative
cwdonsession/newis now a clear error instead of being silently ignored.Evidence
1. Real-behavior proof — ACP stdio → isolated Gateway → agent turn
Harness, all real processes: the built
openclaw acpstdio bridge → a real Gateway on its own port with an isolatedOPENCLAW_STATE_DIR(never the operator's gateway) → the repo's own mock provider (scripts/e2e/mock-openai-server.mjs, wired through qa-labbuildQaGatewayConfigwithproviderMode: "mock-openai"). ACP JSON-RPC driven over real stdin/stdout. Re-run against the currentcwdOnCreateOnlybuild.Both routing modes, one run, each with its own directory and a real prompt turn:
spawnedCwd## Workspace→Working directory:agent:qa:acp-bridge:e90914c3…$ROOT/project-a✅$ROOT/project-a✅end_turn_meta.sessionKeyagent:qa:acp-explicit-proof$ROOT/project-b✅$ROOT/project-b✅end_turnThe default workspace appears in neither model payload (0 occurrences).
session/newwithcwd: "relative/project"was rejected:ACP session/new requires an absolute cwd.Before/after on the same harness, with only the ACP lifecycle reverted to pre-fix and the dist rebuilt:
session_nodes.entry_json.spawnedCwdNone$ROOT/projectWorking directory:$ROOT/workspace❌ default$ROOT/project✅ requestedsession/newwith a relative cwdWhat the model was actually told:
Real ACP stdio transcript (abridged):
Persisted rows, read out of the agent SQLite store after the run:
So the artifacts are not over-read: the Gateway's
[ws]log records only failed or slow responses (ok === false || durationMs >= DEFAULT_WS_SLOW_MS,src/gateway/ws-log.ts:395, threshold 50 ms), so it is not a complete RPC census — the persisted rows and model payloads above are the authoritative signal.$ROOTis a temporary directory; paths are otherwise unedited, and no credentials appear (the Gateway ran unconfigured against a local mock provider).2. Every directory-mismatch case is covered by a test that fails pre-fix
expected [ { method: 'sessions.list' } ] to deep equally contain { method: 'sessions.create' }expected '/tmp/my-project' to be '/tmp/owner-project'session/newrefusespromise resolved instead of rejectingsession/newrefusespromise resolved instead of rejectingsession/newstill succeedsThe shared translator test helper now models the
sessions.createresponse the bridge reads, instead of a bare{ ok: true }; partial mocks delegate to it. That stub had been hiding this path — six previously-passing tests only passed because they asserted against a Gateway shape that does not occur.3. The ownership race, proven deterministically
src/gateway/server.sessions.create.test.tscreates a session with one directory, then issues a secondsessions.createfor the same key with a different cwd andcwdOnCreateOnly: true— modelling the interleaving where the row already exists by the time the create lands. Removing the guard makes it fail for exactly the right reason:A companion test proves the flag still sets the directory on a genuinely new row.
4. Regression test fails before the fix, for the intended reason
The ACP tests assert the exact wire shape for both routing modes, including the flag, and that a rejected relative cwd creates nothing. The mock gateway returns a realistic
sessions.listpayload rather than a bare{ ok: true }.5. Owner-boundary and suite coverage
resolveSessionRuntimeCwd({ requestedCwd, sessionEntry })returnsrequestedCwd ?? sessionEntry.spawnedCwd(src/gateway/server-methods/agent-session-reset.ts:269), feeding the agent run'scwdatsrc/gateway/agent-turn/agent-run-execution-phase.ts:483.node scripts/run-vitest.mjs src/gateway/server.sessions.create.test.ts→ 91 passed.node scripts/run-vitest.mjs src/acp→ 182 files / 1451 tests passed.6. Gates
autoreview --engine claude --mode uncommitted: clean on every revision, "no accepted/actionable findings", clean on the final revision, TruffleHog clean.tsgo -p tsconfig.core.jsonexit 0;run-oxlint.mjsexit 0;oxfmt --checkclean;git diff --checkclean. The full protocol gate was run locally —check-protocol-registry,protocol-gen,protocol-gen-swift --check,protocol-gen-kotlin,check-protocol-since, and thegit diff --exit-codeover all four generated paths — and passes;checks-fast-bundled-protocolis green on the current head.Known non-green check:
check-lintis cancelled, not failed — itsconclusioniscancelledand its "Run check shard" step never completed. In the previous occurrence the log showed every lane reportingfinishedwith zero violations before the runner received a shutdown signal ([oxlint] FAILED (exit 143)= SIGTERM) while inoxlint:extensions, a lane this PR does not touch;mainwas independently red at the same time. Every lint lane covering these files passes locally. I cannot re-run workflows from a fork; happy to push a no-op commit if a maintainer would rather re-fire it.Proof gap, stated plainly:
pnpm check:changedroutes to Crabbox, which is unavailable from this machine (selected binary failed basic --version/--help sanity checks), so per AGENTS.md the gates above were run locally instead of remotely. The end-to-end run uses the repo's mock provider rather than a live model; the observation it supports — which directory the agent is given — is independent of the provider. This change is not UI-visible, so no screenshots apply.