Skip to content

feat(managed-agent): reliably close workspace-bound sessions - #13135

Merged
doudouOUC merged 11 commits into
mainfrom
codex/workspace-session-reliable-close
Oct 2, 2026
Merged

doudouOUC merged 11 commits into
mainfrom
codex/workspace-session-reliable-close

Conversation

@doudouOUC

@doudouOUC doudouOUC commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator

What this PR does

Enables reliable close for idle Workspace-bound hosted-workspace-files/1 Sessions through the existing public and WebShell lifecycle operations. The creator with current read access receives an idempotent 202 admission; the Session becomes CLOSED and the operation completed only after the original resources are settled. Active, cancelling, or approval-waiting Turns return 409 turn_active.

Persists a permanent admission fence, releases saved Runtime Sessions and the original holder, and retires the exact local worker with durable stop evidence. Cleanup continues after ACL or mount changes. Unknown execution or worker identity remains CLOSING with recovery_blocked and a stable failure code. History, committed Artifacts and Workspace files remain available, and another Session's shared holder is preserved.

Why it's needed

Workspace-bound close previously returned 409 workspace_unavailable. Delayed background warm can outlive a text-only Turn, and a replacement Harness's 404 or an expired writer lease cannot prove the original worker stopped. Close now requires durable cleanup evidence before confirming completion and does not replay tools or acquire replacement resources.

Reviewer Test Plan

How to verify

  1. On a deployment with durable local-process support, create an idle files-profile Session, run a file Turn, and close through either public or WebShell. Expect 202, then completed/CLOSED, retained history/Artifacts/files, and the original worker stopped. Repeat the same actor/key through either surface and expect the original operation.
  2. Attempt close with an active or approval-waiting Turn, a readable non-creator, and an unreadable actor. Expect 409, 403, and 404 respectively, without accepting cleanup.
  3. Race close with late warm, a new writer, Turn admission, and Action response. New admissions must be fenced; an existing writer must still settle/seal, and a pending renewal must prevent premature completion.
  4. Exercise lost release/stop replies and claim takeover. Cleanup must use the original generation, preserve another Session's holder, and block on unverifiable identity or UNKNOWN execution without provisioning or replaying work.
  5. Close an unstarted binding whose handle, lease and attestation have not been saved, with either an empty durable directory or an existing INTENT. Expect normal retirement and a persisted drain receipt without launching a worker. A missing registration for a previously saved handle must still block.

Evidence (Before & After)

Before: the baseline public lifecycle contract refused bound close with 409 workspace_unavailable. The global CLI could not reach the Hosted Harness path, so baseline verification used the existing HTTP/store/Broker contracts.

After: integration with main 49b6c900 independently reproduced a duplicate V30 startup failure, then passed after moving the provisional close migration to V31 without changing its SQL (renumbered to V32 post-merge by #13223). The integration snapshot passed 128 targeted Java tests and 8 real MySQL tests, including incremental schema upgrade, writer races and deletion serialization. Harness 171, Hook 70, Workspace 137 and assembly 10 passed in their targeted runs; formatting-only Harness wrapping was separately checked for AST equality and four affected cases. The unstarted empty-store close regression was independently red before the local INTENT retirement repair; the repaired candidate passed63 Broker tests plus17 public lifecycle/store/coordinator tests with Checkstyle0, and a private mutation made exactly the two empty-store cases error while both existing-INTENT cases passed. Final commit d7c5c5e passed build/typecheck/bundle. Separate reports distinguish the exact candidate, native fixtures, real POSIX worker stop with injected host identity, initial failures and retained historical Linux CI. Current-head Hosted CI has completed successfully; its normal acceptance is separate from the full physical recovery matrix. The complete physical Linux stop/crash/reboot matrix remains untested locally. The maintainer separately reproduced startup checksum mismatches for databases recording earlier PR close migrations as either V28 or V30; these are external upgrade tests, not local runs. No UI button or TUI change is included.

External current-head evidence: the maintainer’s round-2 report confirms R4-1 closes on a real Linux/container/MySQL8.4.7 stack and rechecks both close surfaces, refusals, delayed warm, a neighbouring Session and selected worker/Spring shutdown cases. These are the maintainer’s runs, not a local full recovery-matrix claim. Current-head Linux CI also ran HostedPublicWorkspaceIT3/3 with zero failures/errors/skips; this normal acceptance does not resolve F1.

Tested on

OS Status
🍏 macOS ✅ Local build, focused tests, MySQL concurrency, POSIX stop, and existing Hosted E2E
🪟 Windows ⚠️ Not tested
🐧 Linux ⚠️ Production durable close acceptance and physical recovery matrix not executed locally

Environment

Fresh integration verification: macOS arm64, JDK 23, Maven 3.9.11, isolated frozen workspace dependencies, H2 in MySQL mode and an owned MySQL 8.4.11 server. Earlier deployment environments are recorded in their original reports.

Risk & Scope

  • Main risk or tradeoff: completion depends on precise original-resource identity and database-time claims. Missing proof intentionally leaves the Session CLOSING for recovery instead of confirming an uncertain stop. Maintainer F1 remains an open pre-admission policy choice for already known unverifiable namespaces; this repair does not choose that policy or weaken post-admission stop proof.
  • Not validated / out of scope: production Linux host/boot/PID namespace checks and the complete physical crash/reboot matrix remain unexecuted on this macOS host. Shell, MCP, archive/delete, and a new WebShell close button are excluded. Public Artifact reads from upstream feat(managed-agent): project durable tool results to WebShell #13037 are retained, including committed content after close; Artifact reading remains available without a RuntimeWarmer, with bound close capability false.
  • Breaking changes / migration notes: adds the V32 database migration for permanent fences and drain receipts after main's V28/V29 Hook admission, V30 tool-output retention, and V31 workspace recovery bundle migrations, with the close SQL bytes unchanged. It merged as V31 and was renumbered to V32 by fix(managed-agent): renumber session-close migration to V32 #13223 after feat(managed-agent): Add offline W1b recovery bundles #13138 claimed V31 on main first. Optional session_close / sessionClose defaults false for unsupported deployments; bound session_lifecycle remains false. Existing routes and lifecycle operation contracts are retained. Earlier PR builds that recorded the provisional close migration as V28 or V30 cannot directly upgrade: the maintainer reproduced Flyway checksum mismatches for V28 and V30. Those development databases require recreation or an explicit schema migration/repair before upgrade; this PR provides no automatic repair of provisional schema or history. A database with main’s V30 migrated to V31 successfully in that rig.

Complete, synchronized designs: English · 简体中文.

Linked Issues

Related to #12380. Aligns lifecycle operation behavior with #12867 and the Harness recovery boundary with #12740; this slice does not close those broader proposals.

中文说明

本 PR 的改动

通过现有 public 和 WebShell lifecycle operation,为空闲的 Workspace 绑定 hosted-workspace-files/1 Session 开放可靠 close。当前有读权限的创建者获得幂等的 202 接纳;只有原资源完成结算,Session 才变为 CLOSED、operation 才变为 completed。活跃、取消中或等待审批的 Turn 返回 409 turn_active。

持久保存永久准入栅栏,释放保存的 Runtime Sessions 和原 holder,并通过持久停机证明退休精确的原 local worker。ACL 或挂载变化后仍继续清理。执行结果或 worker 身份不明时保持 CLOSING,返回 recovery_blocked 和稳定 failure code。保留历史、已提交 Artifacts 与 Workspace 文件,并保护其他 Session 在共享存储上的 holder。

为什么需要

Workspace 绑定 close 原先返回 409 workspace_unavailable。延迟后台 warm 可能在纯文本 Turn 结束后继续运行;替换后的 Harness 返回 404 或 writer 租约过期,都不能证明原 worker 已停止。现在只有持久清理证据充分才确认完成,不重放工具,也不获取替代资源。

审阅者测试计划

如何验证

  1. 在支持持久 local-process 的部署创建空闲文件 profile Session,执行文件 Turn,然后通过 public 或 WebShell close。应返回 202,随后 completed/CLOSED,保留历史、Artifacts 和文件,原 worker 已停止。同 actor/key 经任一入口重试应返回原 operation。
  2. 分别以活跃或待审批 Turn、可读非创建者、不可读 actor 请求 close。应分别返回 409、403、404,不接纳清理。
  3. 将 close 与延迟 warm、新 writer、Turn 准入及 Action response 并发。新准入必须被栅栏阻止;已有 writer 仍可结算/seal,未提交的续租必须阻止提前完成。
  4. 验证 release/stop 响应丢失和 claim 接管。清理必须沿用原 generation,保留其他 Session 的 holder;身份不可验证或 execution 为 UNKNOWN 时保持阻塞,不能 provision 或重放工作。
  5. 对尚未保存 handle、lease 和 attestation 的未启动 binding 执行 close,分别覆盖持久目录为空和已有 INTENT。应正常退休并持久保存 drain receipt,不能启动 worker。已保存 handle 却缺少 registration 时仍应阻塞。

证据(改动前后)

改动前:基线 public lifecycle 契约以 409 workspace_unavailable 拒绝绑定 close。全局 CLI 无法进入 Hosted Harness 路径,因此基线验证使用既有 HTTP/store/Broker 契约。

改动后:与主干 49b6c900 集成时,独立复现了重复 V30 的启动失败;将临时 close 迁移顺延为 V31、保持 SQL 字节不变后通过(合并后由 #13223 再次顺延为 V32)。集成快照通过定向 Java 128 项和真实 MySQL 8 项,包括增量 schema 升级、writer 并发与删除串行化。Harness 171、Hook 70、Workspace 137、共享装配 10 在各自定向运行中通过;Harness 仅换行的格式调整另做 AST 等价检查和受影响的 4 个用例验证。从未启动且目录为空的 close 回归在 local INTENT 退休修复前独立复现失败;修复候选通过 Broker 63 项及公开 lifecycle/store/coordinator 17 项,Checkstyle 违规为零;私有故障注入恰好让两个空目录用例失败,两个已有 INTENT 用例通过。最终提交 d7c5c5e 通过 build/typecheck/bundle。独立报告区分精确候选、原生 fixture、注入测试主机身份的真实 POSIX worker 停机、首败及历史 Linux CI;当前 HEAD 的 Hosted CI 已通过,正常验收与完整物理恢复矩阵分开记录。完整物理 Linux 停机/崩溃/重启矩阵仍未在本地验证。维护者另复现了早期 PR close 迁移记为 V28 或 V30 的数据库启动时发生 checksum mismatch;这些是第三方升级测试,不能记为本地运行。本 PR 不含 UI 按钮或 TUI 改动。

当前 HEAD 的第三方证据:维护者第 2 轮报告确认 R4-1 在真实 Linux/容器/MySQL8.4.7 栈完成关闭,并重跑两种 close 入口、准入拒绝、延迟 warm、相邻 Session 及部分 worker/Spring 停机场景。这些运行来自维护者,不能作为本地完整恢复矩阵通过的声明。当前 HEAD 的 Linux CI 另实际运行 HostedPublicWorkspaceIT3/3,failure/error/skip 均为零;正常验收不解决 F1。

已测试平台

OS 状态
🍏 macOS ✅ 本地构建、定向测试、MySQL 并发、POSIX 停机与既有 Hosted E2E
🪟 Windows ⚠️ 未测试
🐧 Linux ⚠️ 本地未执行生产持久 close 验收和物理恢复矩阵

环境

本次主干集成验证:macOS arm64、JDK 23、Maven 3.9.11、隔离的冻结 workspace 依赖、MySQL mode 的 H2,以及独立 MySQL 8.4.11 server。此前部署环境保留在各自原始报告中。

风险与范围

  • 主要风险或取舍:完成依赖精确的原资源身份与数据库时间 claim。证明不足时保持 CLOSING,等待恢复,不能确认不确定的停机。维护者 F1 对已知不可验证的命名空间仍有接纳前策略待决定;本次修复不选择该策略,也不放宽接纳后的停机证明。
  • 未验证及范围外:当前 macOS 未执行生产 Linux host/boot/PID namespace 检查和完整物理崩溃/重启矩阵。Shell、MCP、archive/delete 和新增 WebShell close 按钮不在本切片范围内。保留上游 feat(managed-agent): project durable tool results to WebShell #13037 的公开 Artifact 读取,包括 close 后的已提交内容;没有 RuntimeWarmer 时仍可读取 Artifact,绑定 close capability 为 false。
  • 兼容性与迁移:在主干 V28/V29 Hook admission、V30 工具输出保留及 V31 workspace recovery bundle 迁移之后,以 V32 增加永久栅栏和 drain receipt,close SQL 字节不变。合并时为 V31,因 feat(managed-agent): Add offline W1b recovery bundles #13138 先占用主干的 V31,由 fix(managed-agent): renumber session-close migration to V32 #13223 重编号为 V32。可选 session_close / sessionClose 在不支持的部署缺省 false;绑定会话的 session_lifecycle 保持 false。沿用既有路由与 lifecycle operation 契约。已将早期 PR close 迁移记录为 V28 或 V30 的数据库不能直接升级:维护者分别复现了 V28 和 V30 的 Flyway checksum mismatch。这些开发数据库升级前需要重建,或显式迁移/修复 schema;本 PR 不自动修复临时 schema 或历史。该装置中,主干 V30 数据库升级 V31 成功。

完整且同步的设计:English · 简体中文。

关联 Issue

关联 #12380。与 #12867 对齐 lifecycle operation 行为,与 #12740 对齐 Harness 恢复边界;本切片不关闭这些更大范围的 proposal。

@doudouOUC

Copy link
Copy Markdown
Collaborator Author

E2E and regression verification report

Verified commit: aa23bce47b76ff3d1d37884241a0a0a798d24cac, rebased onto 937ed13a1. Environment: macOS 26.6.2 arm64, Node.js 22.14.0, Java 21.0.12.1, Maven 3.9.16, and disposable MySQL 8.4.

Baseline

The global qwen 0.24.6 Hosted Harness attempt exited with “the Broker-backed session loop is not implemented,” so it cannot reach this Java public lifecycle path. The existing HTTP/store/Broker fallback tests established the pre-change 409 workspace_unavailable refusal for bound close. An ordinary CLI exit was not treated as close coverage.

Post-change results

Verification Actual result
Build, typecheck, and bundle after rebase PASS
CLI Harness, Hosted MCP, Managed MCP, provider-worker, and publication regression suites 250 passed across 5 files
Broker close/service/durable-process/recovery suites 207 passed; checkstyle passed
Upstream provider transport regression 18 passed
Managed close/lifecycle/journal/Workspace suites plus upstream publication/configuration/MCP-record regressions 87 passed; checkstyle passed
Real MySQL Broker contracts 6 passed, zero skipped
Real MySQL close concurrency/takeover contracts 4 passed, zero skipped
Real Hosted files/approval E2E with the local bundle 2 passed
New production durable close acceptance E2E 1 skipped on macOS; Linux-only

The tests exercise public/WebShell idempotent admission, creator/read permission checks, active/approval refusal, original-writer settlement, deferred warm fencing, exact-generation release, lost release/stop replies, expired claims, uncertain execution/identity, revoked ACL, and preservation of another Session's shared holder. Independent verification reproduced the old unusable-worker claim re-entry and the uncommitted writer-renewal race before their repairs; dedicated regressions now pass. The definitive-versus-transient release test preserves the original logical Session and verifies blocked versus retry behavior.

The SQL tests use independent connections to an owned temporary MySQL server/datadir and fresh loopback port, then shut down and remove that fixture. They do not use the existing database or user credentials. Actual POSIX workers are stopped by the durable-provider tests, with injected test host identity on macOS. The Hosted files/approval cases use deterministic model fixtures and temporary Workspace directories.

Limits and Linux acceptance

This is not a production Linux durable-close pass. The new acceptance test compiles but was actually skipped on this host; trusted /proc, host/boot/PID namespace identity, reboot, and the full physical recovery fault matrix remain unexecuted. Two SQL-store instances sharing a JVM establish SQL serialization/takeover, not a full two-service process-crash proof. Public Artifacts are not yet implemented, so retention assertions cover history, managed resources, and real Workspace files.

On Linux, build/bundle first, then run the durable acceptance fixture with Node.js 22+:

mvn -f packages/sdk-java/managed-agent-server/pom.xml \
  -Dtest=HostedPublicWorkspaceIT#durableCloseStopsOriginalWorkersAndRetainsHistoryAndFiles \
  -Dnode.executable=<absolute-node-22+> \
  -Dqwen.cli.entry=<absolute-dist/cli.js> test

Expected acceptance: close returns 202 then completed/CLOSED only after the original PID exited, registration is RETIRED, the drain receipt is durable, original logical Sessions/holder are released, and retained history/files are readable. Repeating the same key must return the same operation. Teardown checks only the fixture's saved worker identities.

Two clean full self-audit passes and the final independent read-only review found no unresolved Critical. The feature diff is unchanged by rebase; the platform limits above remain explicit.

@doudouOUC
doudouOUC marked this pull request as ready for review October 1, 2026 02:59
@doudouOUC
doudouOUC enabled auto-merge October 1, 2026 02:59
@doudouOUC doudouOUC self-assigned this Oct 1, 2026
@doudouOUC

Copy link
Copy Markdown
Collaborator Author

[codex] Agreed with the blocking executor finding in Stage 2 and the changes-requested review. Fixed in 8b1b5cdd26001d640d9eda80f579f23fb7771e1f: durable stop now uses the existing provisioner executor. The new regression occupies the common pool, confirms resource lookup still works, and requires drain to return a matching receipt and retire the original registration before unrelated work is released. It failed on the previous production code and passes with the fix.

Review item Decision
Blocking worker shutdown on the common pool Fixed in 8b1b5cdd26001d640d9eda80f579f23fb7771e1f with a red/green availability regression.
ACTION_RESPONSE scheduling across application/database clocks Valid follow-up, deferred from this close fix. Admission/recovery scan remain application-clock based while shared claims use database time; clock skew can delay delivery. This round does not claim that alignment is fixed.
Ignored now argument; repeated database-time helper and null/range validation Deferred maintenance/API cleanup. Database time remains authoritative for lifecycle leases.
Duplicate idle validation; fixed placeholder count Deferred simplification; current error precedence and all 37 binding parameter positions are correct.
Byte-exact SQL idiom; locking versus ordinary drain read helper Deferred clarity work; directed lookup remains byte-exact and admission retains the placement transaction lock.
Unsupported-deployment negative capability coverage; unbound capability clarification Deferred coverage/documentation follow-up. Default-false/refusal behavior is unchanged, and unbound Sessions can advertise both close and aggregate lifecycle support.
Size/public-capability awareness Acknowledged. The additive capability keys and current slice remain the accepted scope.

Validation: npm run build, npm run typecheck, and npm run bundle passed on the pushed commit. Independent runtime-broker verification passed 67 distinct cases across the common-pool saturation regression, durable-process tests, standard provisioner tests (the initially skipped real-worker case was separately enabled with the built local bundle and passed), and Harness drain tests. Checkstyle passed. Two clean self-audit passes covered the incremental diff. No flaky reruns were used.

I also downloaded SDK Java run 36807213197 and inspected the actual Hosted Public Workspace JUnit XML for aa23bce47b76ff3d1d37884241a0a0a798d24cac: all three cases passed with zero skips, including the Linux durable-close acceptance. That updates the earlier local-only report; the complete physical reboot/crash matrix remains unverified. There are no inline review threads to resolve (0/0); the blocking review needs reevaluation on this new commit.

中文:已修复停机任务占用公共线程池的问题,并通过修复前失败、修复后通过的回归验证。其他非阻塞建议逐项记录为后续事项,尤其保留 Action response 调度时钟偏差的已知限制。Linux CI 的真实停机验收已实际通过,但完整物理崩溃与重启矩阵仍未验证。

@wenshao

wenshao commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator

@qwen-code /resolve

Main's WebShell artifact projection (#13037) and this branch's session
close capability both extended WebShellSessionCapabilities, so the
record, the OpenAPI schema, the generated WebShell client, and the
contract assertion now carry artifacts and sessionClose together.
@qwen-code-dev-bot

Copy link
Copy Markdown
Collaborator

Qwen Code resolved the merge conflicts and pushed the branch update.

Root cause

main took #13037 (6310dd38d5) while this branch was open: it added an artifacts capability flag exactly where this PR added sessionClose. 5 files conflicted, one hunk each: the WebShellSessionCapabilities record, its OpenAPI schema, the generated WebShell client, and the contract assertion pinning that JSON.

Semantic, not adjacent

Both sides edited the same record and call site; fields were unioned:

public record WebShellSessionCapabilities(boolean tasks, boolean artifacts, boolean actions,
        boolean sessionClose) {
    public WebShellSessionCapabilities(boolean tasks, boolean artifacts, boolean actions) {
        this(tasks, artifacts, actions, false);
    }
}
new WebShellSessionCapabilities(true, hasArtifacts(session), hasActions(session),
        supportsClose(session)));

artifacts keeps main's slot; sessionClose is appended last, as this PR appended session_close to SessionCapabilities. The 3-arg shim defaults sessionClose=false, mirroring the PR's shim there (neither has a caller). Assertion: {"tasks":true,"artifacts":false,"actions":false,"sessionClose":true} — right for that fixture: no workspace, so hasArtifacts is false and supportsClose short-circuits true.

Load-bearing

  • recordsMatchTheirSchemas diffs record components against non-planned schema properties both ways; the two sets are verified equal here.
  • managed-agent-api.test.ts needs committed TS byte-identical to renderManagedAgentApi(). The generator drops planned properties and otherwise preserves JSON property order, so my JSON ordering fixes the TS order.
  • Four positional booleans — a transposition still compiles.

Not verified — needs a follow-up commit

Duplicate Flyway version 26. #13037 added V26__managed_tool_result_projection.sql, this PR V26__workspace_session_close.sql; both now sit in db/migration/, and Flyway rejects two migrations at one version. Neither filename is referenced anywhere, so the fix is renaming the PR's file to V27__. I did not do it — that file never conflicted, and only conflicted files are in scope here. It fails before any test I resolved runs: WorkspaceStorageGuardTest runs Flyway…migrate() on H2, and flyway is enabled at startup.

No build, typecheck, lint, or tests were run.

中文说明

根因:main 在本分支开出后合入 #13037(6310dd38d5),它新增 artifacts 能力位,正是本 PR 新增 sessionClose 之处。5 个文件各冲突一处:该 record、其 OpenAPI schema、生成的客户端、固定该 JSON 的断言。

语义冲突:双方改同一 record 与调用点,字段取并集(见上)。artifacts 保留 main 的位置,sessionClose 追加末尾,与 PR 在 SessionCapabilities 追加 session_close 一致;三参构造器默认 sessionClose=false,两者均无调用方(PR 原有)。

关键约束:recordsMatchTheirSchemas 双向比对 record 字段与非 planned schema 属性,两侧集合已校验相等。managed-agent-api.test.ts 要求提交的 TS 与 renderManagedAgentApi() 逐字节一致;生成器剔除 planned 属性、其余保持 JSON 属性顺序,故 JSON 排序决定 TS 顺序。四个参数均按位置传 boolean,写错仍能编译。

未验证,需后续提交:Flyway 版本 26 重复。#13037 加了 V26__managed_tool_result_projection.sql,本 PR 加了 V26__workspace_session_close.sql,现同处 db/migration/,Flyway 不允许同版本两个迁移。两文件名均无引用,修法是把本 PR 文件改名为 V27__。我没有改:该文件未冲突,本任务只允许改冲突文件。它会先于我解决的任何测试失败——WorkspaceStorageGuardTest 在 H2 上执行 Flyway…migrate(),启动时 flyway 亦启用。

未运行构建、类型检查、lint 或测试。

@doudouOUC

Copy link
Copy Markdown
Collaborator Author

[codex] Follow-up to the resolve request and bot resolution: pushed 3862b2f404ff370b6c69f4fd2ec4b670118897b5 as a fast-forward follow-up to the bot's 47fd356, preserving its update. The final tree is byte-identical to independently reviewed and verified candidate 6d948df8; no concurrent work was overwritten.

Item Action
Upstream Artifact / close capability collision Preserved both capabilities and the regenerated client; bound aggregate lifecycle stays false.
Duplicate Flyway V26 reported by the bot Fixed: close is V27 after upstream V26 projection. Fresh MySQL migration and an upgrade containing original Artifact sentinel rows both passed; repeated migration is idempotent.
Standalone Artifact context fails without RuntimeWarmer Independently reproduced 19 setup errors. Fixed optional injection; the same 44 Managed cases pass, including public/WebShell close=false while artifacts=true when no warmer exists.
CLOSED history and original Artifact content Retained; actual full/range content, original descriptors, current read policy and streaming revocation regressions passed.
Prior executor blocker The existing 8b1b5cdd fix is preserved. Common-pool saturation, durable stop and real worker exit checks pass. Other prior deferrals remain in the earlier response; this update does not claim to fix Action response clock alignment.
Bilingual design and PR evidence Synchronized with V27, upstream Artifact reads and the precise Linux validation limits.

Validation: the exact pushed commit passed npm run build && npm run typecheck && npm run bundle. Focused TypeScript coverage passed 118 cases (Harness 79, WebShell API/client/projector/build artifact 39); independent Java/MySQL/Hosted verification passed 123 distinct JUnit cases with zero failures and one actual Linux-only skip. Both Maven checkstyle checks, focused ESLint/Prettier and generated-client equality passed. Additional probes verified capability composition, migration retention and an actual local-bundle worker: the exact saved PID exited, registration was RETIRED, and the drain receipt matched on retry. Two clean self-audit passes and independent full-diff review found no unresolved Critical. The final history adjustment retained the verified source tree; execution SHAs and red/green logs are recorded locally.

No CI reruns were used. There are no inline review threads to resolve (0/0). New-head CI and reevaluation of the old changes-requested review remain pending. The current Hosted run passed files/approval flows and skipped production Linux durable close on macOS. Earlier normal-close Linux acceptance passed specifically at aa23bce; it is not verification of this new HEAD. The complete physical Linux crash/reboot matrix remains unexecuted.

中文:已保留机器人的并发更新,在其提交上补齐 V27 迁移并修复 Artifact 独立 context 缺少 RuntimeWarmer 时无法启动的问题。无 warmer 时仍可读取 Artifact,绑定 close 能力保持 false;支持持久停机时两组能力可以同时开启。修复前 19 项错误、修复后 44 项 Managed 全绿的证据均保留。定向 TS 118 项、Java/MySQL/Hosted 123 项通过,Linux 条件用例实际跳过 1 项;真实 worker 停机、迁移保留与最终提交构建门禁通过。当前无 inline 线程(0/0),等待新 HEAD 的 CI 和审查重新评估;完整物理 Linux 崩溃/重启矩阵仍未验证。

@doudouOUC

Copy link
Copy Markdown
Collaborator Author

[codex] Review repair batch pushed as 63e840cedf87fa54cf80c826112b8cc77272cff4 (fix commit 45dde01da, upstream integration 63e840c).

Fixed both independently reproduced Critical findings: close MySQL tests now own private schemas, and fence probes avoid cross-tenant InnoDB gap locks while preserving late-fence visibility under REPEATABLE READ. The unsupported-instance takeover now reports a stable recovery-blocked result rather than repeatedly appearing RUNNING. Small contract, portable fixture and timing corrections are included.

Integrated current main (private Managed ACP, hosted file history and recovery-claim renewal), preserving both sides of the Harness tests and forwarding close methods through the shared repository test double. Independent incremental and TS/Java integration reviews found no further actionable defect in those reviewed scopes; this is not a whole-PR approval.

Disposition Finding Action / reasoning
fixed R1-39 Each close test now creates/drops its own schema from the existing mysql.url. All four close cases followed by the legacy upgrade pass on owned MySQL 8.4; restoring the shared URL fails the actual legacy backfill assertion.
fixed R1-2 The drain probe is nonlocking, with all admission placement guards retained. Immutable tenant discovery moved outside the execution transaction so the post-lock probe sees a newly committed fence under REPEATABLE READ. Cross-tenant completion and queued-admission rejection pass; restoring FOR UPDATE or only dropping it without moving the first read goes red.
deferred R1-4 The earlier busy guard already rejects this prompt, so no new work enters during close. Removing the redundant error branch and asserting the observed busy code are cleanup/coverage followups; changing phase semantics to manufacture a second code is outside this repair.
deferred R1-22 Confirmed the shorter constructors have no in-tree callers; production uses full records. They conservatively default optional fields, so there is no current lost capability/receipt. Compatibility API cleanup is recorded for followup.
fixed R1-54 Corrected the javadoc: legacy unbound drain only retires warm admission; bound close uses the durable fence and harness-level drain.
fixed R1-27 Clarified both capability contracts: they describe deployment support, while creator/read authorization remains enforced at close admission. No close UI is added in this slice; actor-specific capability projections remain a separate API choice.
deferred R1-21 Defaults are identical (60s lease, 20s renewal), and current renewal is safe. Wiring the existing interval consistently is a configuration followup; shortening renewal cadence does not itself shorten crash takeover, which depends on lease expiry.
deferred R1-16 The coordinator already preserves workspace_close_execution_unsettled. An additional classification/recovery assertion is useful negative coverage, recorded for followup; the current branch is not missing the production guard.
deferred R1-33 Confirmed the log overstates a backoff retry when claim validity is lost. Persistence still remains fenced and recovery waits for DB lease expiry. Distinguishing discarded, blocked and rescheduled log messages is an observability followup.
declined R1-6 Keeping the conservative latch: a failed renewal observation delays completion but cannot falsely finish or replay tools. SQL-fenced completion despite uncertainty is an availability tradeoff; no current correctness failure warrants removing this safety check.
fixed R1-5 Unsupported takeover now uses RECOVERY_BLOCKED with workspace_close_identity_unverified and leaves the accepted Session CLOSING. A real-store regression passes; isolated original coordinator code stays RUNNING without the required failure status and goes red.
deferred R1-19 The only in-tree store overrides renewal with DB fencing. Changing the default false to a thrown exception would be caught at the same validity latch and have the same behavior; a future unsupported-store policy is needed rather than this proposed one-line substitute.
fixed R1-9 Documented session_inactive on both Action-response 409 contracts and regenerated the client. Existing matching idempotent responses still replay first. Error-code unification is deferred; rejecting new responses after closing remains the intended gate, including legacy Sessions.
deferred R1-58 Confirmed potential overhead on unbound/missing rows. Bound public-Session-before-journal ordering is required to serialize close. Any nonlocking precheck optimization needs its own immutability and real DB race evidence; retaining the admission fence in this repair.
deferred R1-7 Confirmed the binding/generation holder query is not indexed by storage_key. It currently gives the correct exact-generation refusal. A storage-key-directed rewrite and scale measurements are performance followup, without broadening schema/query changes now.
fixed R1-8 Updated canonical close admission/completion prose for supported bound close, creator/read authorization, original-resource cleanup proof, recovery_blocked and retained content. Unsupported close still uses the actual workspace_unavailable code; archive/delete descriptions remain unchanged.
fixed R1-18 POSIX initial permissions are now applied only by the Linux-only durable-close case; ordinary files/approval setup uses portable directory creation. Local Hosted files/approval passed; Windows Hosted execution is not claimed.
declined R1-37 At the latest reviewed tree, ManagedArtifactApiIntegrationTest already asserts close=false on both surfaces for a bound Session without RuntimeWarmer. The positive unbound assertions are intentional. A separately wired false-support warmer is additional negative coverage, recorded for followup.
fixed R1-36 While fixing the short timing window, added DB-time samples around retry and asserted available_at is within those samples plus the requested relative delay. The skewed application clock still cannot drive delivery; no narrow wall-clock tolerance was added.
fixed R1-17 Replaced the 500ms real-time window with a long relative deadline and retained explicit expiry setup. The test now also verifies persisted DB-time deadline translation before changing available_at.
deferred R1-15 Confirmed the Turn refusal is workspace_unavailable before status validation; this leg witnesses shared Session-lock serialization, not a CLOSING-specific Turn gate. Additional bound Turn support is out of scope; narrowing the test claim is a followup.
deferred R1-40 Confirmed the cancelled/empty-options fixture makes the count a retained invariant rather than an independent admission witness; the adjacent session_inactive assertion is status-sensitive. A valid ACTIVE response control is followup. Moving an INSERT before a throw in the same transaction still rolls it back, so that proposed count mutation is not an unsafe-commit witness.
deferred R1-42 The bound unavailable-Harness exemption and live-writer check are implemented. A stale boot-id fixture would strengthen recovery coverage; missing coverage is nonblocking. Ordinary IllegalStateException retries, rather than becoming permanent identity blocking.
deferred R1-53 Confirmed original hasHolder is already false after fixture release; the rival-holder assertion remains meaningful. A direct stop-with-original-holder negative test is followup. Normal release also nulls binding/generation, so deleting only the holder_key predicate does not isolate the proposed mutation.
fixed R1-44 Immutable binding/tenant discovery is now outside the admission transaction. The first consistent fence read is after placement lock, preserving late-fence visibility and avoiding the described earlier receipt snapshot; receipt uniqueness/winner fallback remains.
deferred R1-45 The tenant guard deliberately serializes same-tenant fence and admission. Restricting it for other isolation classes is a measured performance followup; this repair removes cross-tenant gap coupling without weakening the placement lock.
deferred R1-12 Confirmed early post-claim throws can leave the claim until DB expiry; subsequent attempts re-read state, so this is bounded takeover delay, not lost cleanup proof. Claimed-state revalidation and quiet cleanup on all early exceptions are robustness followup.
deferred R1-60 Confirmed cleanup I/O can cause one incidental retry after RELEASED/receipt commit. The next drain short-circuits the proven terminal state; it is not a permanent client failure. Using the existing quiet cleanup helper plus a fault-injection test is followup.
deferred R1-46 Confirmed busy control can be reported as identity blocking. BLOCKED CLOSE is explicitly re-scanned, so it resumes after the control settles and cannot falsely stop/complete. Exempting runtime_session_busy from the identity remap with a held-control regression is a classification followup.
deferred R1-51 Confirmed the refusal fixture changes both isolation and digest. Production checks both and validates the exact registration. Splitting single-invalid-field negative fixtures is useful defense-in-depth coverage, recorded for followup.
fixed R1-29 The held transaction now persists the fence before unlocking, so every queued warm/Session/execution admission must reject and the old receipt still replays. Actual MySQL mutation controls fail when placement locking is removed or the old pre-lock read view survives a plain-only fence fix.
deferred R1-28 Confirmed the backdated lease also changes sameOperation relative to the expected snapshot. Rereading the expired row would isolate the existing liveness guard; ownership/generation fencing is currently present. Recording the focused test-strengthening followup.
deferred R1-30 Production coordinator always writes the persistent fence before drain, and Broker rejects unfenced drain. A ready/unfenced negative fixture would pin this destructive-entry guard more directly; no current bypass is present.
deferred R1-31 Negative handle-mismatch receipt coverage is useful. The claimed arbitrary-registration trust is not present: real local-store lookup checks the full original request/seed identity even when the SQL handle is missing, as required for INTENT/response-loss recovery. Preserving that valid retirement path.
deferred R1-56 Confirmed missing isolated refusal-state cases; production unsupported/state/managed-context checks are present and loss-evidenced records also cannot become DRAINING. Current proven-loss recovery composition test is meaningful. Further negative fixtures are followup.
deferred R1-14 The exact observation identity guard is present; adding an opt-in mismatch/UNKNOWN fake is useful coverage followup. Refusal occurs before Session release transition, so the expected state must match the actual saved initial state rather than unconditionally RELEASING.
deferred R1-55 A completed-false transport fixture would pin retry classification. Deleting that mapping still leaves an active RELEASING Session, and the later active-session count prevents stop/receipt; the suggested unsafe-stop mutation consequence is false. Followup should assert release-failed classification and successful retry.

Counts: 12 fixed, 23 deferred with explicit followup reasoning, 2 declined after checking current code. Each inline thread is replied to individually; replied threads are then resolved.

Validation on the integrated tree:

  • Required root build, typecheck and bundle passed on the final commit; configured formatting/lint tasks passed.
  • Broker selected tests: 210 cases, zero failures/errors, one platform skip; durable local-process tests: 37 passed, including real POSIX worker stop using the injected test host identity. Managed Server selected tests: 70 passed.
  • Private frozen test-script verification on owned MySQL 8.4.11: all four close cases followed by the staged legacy upgrade, plus both Broker fence races, passed. Unsupported coordinator also passed. Prior four actual Critical mutants and original coordinator fail at their intended assertions; six corresponding source snapshots remain identical after integration. This is actual JUnit-method test-script evidence, not a full Failsafe job claim.
  • Hosted files/approval end-to-end cases passed against the final local bundle (2 passed, 1 durable production-Linux close skip on macOS).
  • Full physical Linux stop/crash/reboot matrix and Windows Hosted execution remain unverified. Earlier normal-close Linux CI is historical evidence only; new-HEAD CI is pending.

Final CLI integration: the two tool-turn/file-history files passed (140 cases); the Harness file passed all 98 cases on its focused rerun. The initial batch had one socket-hang-up failure in an unchanged SSE/replay test; its isolated case and the complete file both passed without source changes. Core file-history tests: 54 passed. A Hosted invocation with an incorrect local Node path was discarded as setup error, then corrected before the actual 2-case green run.

@doudouOUC

Copy link
Copy Markdown
Collaborator Author

@qwen-code /triage

@doudouOUC

Copy link
Copy Markdown
Collaborator Author

[codex] Review repair batch at 89579db

Bound the original-binding drain so a hung stop/reconcile/release cannot renew forever, retained placement exclusion while stop proof is pending or fails, and made idle close ignore expired orphan approvals using database time. Trusted same-host reboot proof now produces an original drain receipt for an already drained binding; foreign/missing/untrusted identities and still-active logical Sessions retain the documented fail-closed boundary. Closing prompt errors and best-effort claim cleanup are also covered.

Finding Action Reason
R2-1 fixed The whole original-binding drain now has the existing four-lease deadline, a named retryable timeout, stopped renewal and best-effort claim cleanup. Regressions hang stop, reconcile and release separately, then prove second-broker takeover and that late callbacks cannot retire the binding.
R2-2 partially-fixed Trusted same-host reboot proof is now accepted by stopDrained for an already drained binding and persists the original drain receipt without signalling another boot PID or inventing JOURNAL_LOST. INTENT/LAUNCHING/REGISTERED, untrusted/foreign identities and missing registration are covered. The broader premise is not established: cross-host missing registration still blocks even without the fence, and existing proven LOST/operator recovery remains available. Still-active logical Sessions continue to require release/holder proof; automatic general recovery is outside this slice and is explicitly documented.
R2-3 fixed DRAINING now remains a placement exclusion in both the JDBC scan and shared in-memory predicate throughout pending and failed stop, rather than restoring the guard only after failure. Both repository regressions refuse a rival on the original storage, allow unrelated storage, and permit the rival only after a persisted stop receipt and RELEASED.
R2-4 fixed Close checks requested Action expiresAt using database time and the same future-only boundary as decision admission. Future approvals still return turn_active; expired/missing-expiry orphan rows permit idle close and remain in history. API/H2 and actual MySQL with a deliberately skewed application clock pass.
R1-4 fixed Moved the closing guard ahead of the busy guard after identity validation, and asserted hosted_session_closing during pending seal. The full98-case Harness suite passes.
R1-6 declined Retaining conservative claim validity after an uncertain renewal. A transient DB error can delay completion until the persisted lease expires, but cannot falsely finish or replay tools. Removing the latch changes an availability/safety choice; renewal diagnostics remain a followup.
R1-7 deferred Confirmed the holder query is not indexed by storage_key and returns the exact original generation correctly. Storage-key lookup and scale measurements remain a performance followup already recorded in the prior repair summary.
R1-15 deferred Confirmed bound Turn admission already returns workspace_unavailable while ACTIVE as well as CLOSING. This assertion proves serialization/no new row, not the status-specific gate; that limitation remains recorded. A newly supported bound Turn path and its matrix belong to their own slice.
R1-16 deferred The producer and coordinator currently preserve workspace_close_execution_unsettled correctly. Dedicated classification/mutation coverage is useful followup; no missing production guard was established.
R1-22 deferred Confirmed in-tree consumers use full-arity records; shorter compatibility constructors default optional fields conservatively. No current caller loses capability or failure evidence. Compatibility API cleanup stays recorded as followup.
R1-33 deferred Confirmed the warning overstates backoff in blocked/discarded cases; persistence and lease fencing remain correct. Separate blocked/discarded/rescheduled messages and renewal diagnostics remain an observability followup.
R1-45 deferred Keeping the tenant placement lock required to serialize admission with the permanent close fence; admission-scale profiling and narrower locking are followup. The repeated R1-44 snapshot assertion no longer applies: immutable binding discovery occurs outside the transaction before its placement lock, as fixed and MySQL mutation-checked in the previous batch.
R1-51 deferred Confirmed the combined negative profile fixture does not pin every disjunct independently; production still refuses other profiles/isolation classes. Independent profile-axis mutation coverage remains followup; this batch adds trusted/untrusted/foreign/missing startup identity regressions for the actual repair.
R1-60 fixed Both drain cleanup sites now use releaseOperationQuietly. A regression injects cleanup connection failure after the stop receipt and RELEASED are persisted, requires successful close, then proves idempotent replay does not stop again.
R2-5 deferred The terminal-row pagination and missing ordering index are valid performance concerns and remain followup with real-engine scale evidence. One Session per Turn is not the current identity contract: runtimeSessionId is reused. Changing the shared enumeration contract/schema is beyond this correctness batch.
R2-6 deferred Recorded the missing guard/renewal/remap mutation coverage for followup. Existing production checks remain present and fail closed; absence of a deletion-sensitive test alone does not establish a correctness defect. Current regressions add bounded renewal/claim takeover and precise placement proof coverage.
R2-7 declined The accepted design explicitly requires durable admission retirement before signalling the original process, so moving RETIRED after exit would reopen crash/relaunch risk. RETIRED is not the physical close proof: stopDrained rechecks exact process absence and a separate drain receipt is required for RELEASED. Generic maintenance skips close-fenced normal retirements; no JOURNAL_LOST is manufactured by this close path.
R2-8 deferred A child spawned by a custom worker can outlive its parent; recorded process-group/descendant identity cleanup for the Shell/MCP slice. Public close in this PR is enabled only for idle hosted-workspace-files/1, and Shell/MCP close remains disabled. A volatile descendants snapshot would also lose proof after a parent-exit crash, so this needs a durable design; this PR does not claim process-tree shutdown.
R2-9 declined An already acquired writer may renew during CLOSING to finish settlement and seal, explicitly required by the accepted plan. Only new acquire is rejected. The test first acquires while ACTIVE then closes and renews that original generation, so the scenario is reachable; adding the proposed renewal status gate would break intended cleanup.
R2-10 deferred Agreed that the100ms discriminator can be weakened by connection/scheduling delay; the existing real-MySQL race is useful but not a scheduler-independent lock-wait proof. Record an engine-specific positive waiter oracle and delayed-mutant coverage as followup, without changing production locks or claiming that stronger evidence here.
R2-11 deferred Partially addressed: approval fixtures now have production-shaped IDs and future expiry with expired/missing-expiry controls; drained-stop fixtures cover trusted/untrusted/foreign boot identities and missing registration. Remaining holder/profile/observation/admission negatives and the Hosted post-turn registry fixture are recorded for followup. The in-flight provision test correctly witnesses claim exclusion first and never-attested recovery after failure; no claim that its final stop retired an attested worker.

Validation: focused Broker234cases (19drain+40durable-local+137service+38recovery), Managed42, CLI98 and actual disposable MySQL close5 all pass, with Java Checkstyle and TS formatting/lint. Exact committed npm run build && npm run typecheck && npm run bundle passed; fresh-bundle Hosted acceptance passed2cases with1explicit macOS skip. Independent original-vs-candidate admission/protocol verification passes. Broker probes pass bounded2412ms timeout/claim takeover/late callback, pending and failed placement exclusion in JDBC and memory, and7 identity/active-Session boundary cases; restoring original timeout, shared placement predicate, JDBC scan, or reboot provider code makes the relevant control red. The independent local review found no new correctness defect within the incremental diff; this is not full-PR maintainer approval.

Limits: boot identity regressions are simulated; actual POSIX worker stop is exercised with test host identity. The full physical Linux close/crash/reboot matrix remains unexecuted. Shell/MCP and general recovery orchestration stay out of scope. Prior green Linux CI is evidence for the previous HEAD, not this new commit. The issue-comment triage job failed on external model API ETIMEDOUT/ENETUNREACH; no source change or old-HEAD rerun is used to hide that infrastructure failure.

This is approximately the fourth external feedback batch; further rounds will prioritize Critical fixes as required by AGENTS.md. All deferrals are explicitly recorded above.

@doudouOUC

Copy link
Copy Markdown
Collaborator Author

[codex] CI/upstream compatibility follow-up pushed in 5c46e7a62a18384b99155d0641263ece5cc871cf.

Disposition Result
Fixed The lint job rejected the stale branch workflow before running lint. Merged main through a7deb01bc; the latest lint-gate change is now an ancestor of this HEAD. No infrastructure failure was patched or blindly retried.
Fixed The upstream Turn takeover routes could admit a recovered continuation/cancellation while daemon close waited for lease return, or resume stale authorization after the attachment was removed. Both routes now reject local closing admissions and recheck exact attachment identity, closing/busy state, and active work after authorization. Six deterministic concurrent schedules cover both endpoints; independent old-code controls reproduce the failure and model execution, and the repaired controls reject it.
Preserved Public close still rejects an active Turn. This fixes the daemon attachment boundary without adding active-Turn close, Shell/MCP close, or recovery orchestration. Both close designs are synchronized.
Review hygiene The preceding feedback batch's 21/21 threads remain replied and resolved; the pre-push snapshot has 0 unresolved threads. Existing replies were not duplicated. See the full feedback dispositions.

Validation on the committed candidate: final npm run build && npm run typecheck && npm run bundle passed, as did focused CLI 180/180, Core managed journal/harness 638/638, WebShell approval 79/79, Java close/lifecycle/connector/coordinator/writer/header 44/44, SDK client 19/19, and CI helper 16/16 tests. Java checkstyle and commit-hook lint/format passed. Two clean self-audit passes and independent integration review found no further confirmed defect within the merge boundary. The exact committed patch matches the independently reviewed candidate. The initial broad CLI run's single timing failure is retained in local records; its isolated unchanged cases and an independent frozen baseline run passed, and the final repaired five-file run passed all 180 tests.

Fresh-bundle Hosted Workspace E2E passed both portable cases (2 passed, 1 Linux-only close case skipped on macOS). An independent fresh-bundle check also confirmed authenticated health/capabilities and clean owned-process shutdown. Full physical Linux worker-stop, reboot and crash matrices remain unexecuted; simulated identity or HTTP barriers are not physical fault coverage. No remote flaky retry was used. New CI runs will validate this pushed HEAD.

@doudouOUC

Copy link
Copy Markdown
Collaborator Author

Review follow-up and main synchronization, commit 6c6e584 (reviewed previous HEAD 5c46e7a62; candidate tree 0c0f8c819).

Resolved the conflict with main's Hosted Hooks H2 changes while retaining closing/attachment/active-owner guards and the upstream Hook tests. Validation exposed a real deployment blocker: both branches used Flyway V27. The unchanged close migration now follows upstream Hook records as V28, with matching English/Chinese design updates. H2 and disposable MySQL initialize/validate all 28 migrations; the test fixture also now awaits the upstream asynchronous server factory.

Independent review and reproduction did not substantiate either new Critical as an in-scope correctness fix: an active recovery owner returns its original lease on settlement (a rejected competitor must not return it), while absent/foreign startup identity is required to remain CLOSING/recovery_blocked until original-resource stop evidence exists. No receipt was fabricated and the permanent close fence remains. After approximately five feedback batches, noncritical work is recorded below for followup rather than widening this files-only close slice.

Review item Decision Verified reason / recorded followup
R3-1 declined The files/1 MCP route rejects with hosted_mcp_unavailable before becoming busy. Independent HTTP probes on reviewed 5c46e7a and the merged tree show a competing recovery gets hosted_turn_active, its same-key retry keeps the original watermark, and the legitimate owner completes and returns its original Runtime lease. Releasing from the refused competitor could return a lease that the active owner still uses. Close already awaits handback. No permanent leak was reproduced; no blanket handback was added.
R2-2 declined Missing registration, foreign host or UNKNOWN execution intentionally remains CLOSING/recovery_blocked under the accepted original-resource proof contract. Rescan still retries blocked operations; restored original-host identity, a trusted same-host reboot with the original registration, a persisted stop receipt or already established matching loss/stop evidence can permit progress. Unreachability alone is not a stop receipt. Removing the permanent fence or treating missing identity as RELEASED would violate this slice; general operator/remote-stop orchestration remains a followup.
R3-2 deferred A dedicated authorization-versus-competing-owner regression would strengthen coverage; the active-owner guard exists and the independent probes already execute its refusal and normal owner handback. Keep a permanent collocated case as nonblocking followup after approximately five review batches.
R3-3 deferred Pin the retained expired Action state, not just its row count, in a followup. Current close does not change that state and the DB-time expiry gate is present; no incorrect Action mutation was found.
R3-4 deferred Add UNKNOWN and one-at-a-time original handle/runtime/lease/epoch/endpoint mismatch fixtures as nonblocking test work. Current uncached release checks each identity before any release or stop; accepting-only fixtures do not establish an unsafe path.
R3-5 deferred The missing-binding exception is diagnostically remapped to an execution conflict today, but still refuses all effects. A precise admission-closed classification regression is a valid noncritical followup; no unsafe admission was established.
R3-6 deferred A narrow immutable tenant lookup can avoid duplicate full binding decode. Keep it outside the admission transaction so the first consistent fence read follows the placement lock; an inside-transaction early snapshot would restore the fixed repeatable-read bug. Defer this performance change.
R3-7 deferred Add drain_receipt_json to raw reference schema.sql and a direct-DDL fixture in a followup. Inspected supported initialization paths use JdbcRuntimeBrokerSchema or Flyway, both install it; no failing supported raw-DDL-only production caller was found.
R3-8 deferred Add unsupported-stop and non-RELEASED LOST/operator/FAILED refusal fixtures. The production exclusion is present; the existing proven-loss fixture intentionally verifies cleanup composition after RELEASED. Missing negative coverage remains nonblocking.
R3-9 deferred Pin previously stored Action same-key replay after CLOSING and fresh-key refusal. Current production replay precedes the ACTIVE gate and already implements this ordering; this is a test followup.
R3-10 deferred Add a gated coordinator cleanup with an actual renewal tick and lost-claim control as followup. Renewal and database-time/generation completion fencing exist; current short tests do not directly witness the scheduler tick.
R1-6 deferred Distinct renewal-abandon logging and a carefully proven renewal retry policy are followups. Current conservative valid=false abandons completion and expires into rescan, preserving claim safety; it is not permanent loss or unsafe completion.
R1-7 deferred Resolve the saved storage key or add an index to the exact binding/generation holder barrier, with a positive-holder fixture. Keep the barrier; the current COUNT is correct but could be cheaper.
R1-15 deferred Keep this MySQL Turn result described as Session-row serialization, not a CLOSING-specific witness: a bound queued Turn is refused as workspace_unavailable before the ACTIVE gate. A suitable public Turn path witness is followup; the existing E2E report already records this limit.
R1-16 deferred Add a public operation failure_code assertion for execution-unsettled remapping as followup. The current remap exists; the present injected test covers identity-unverified only.
R1-22 deferred Removing unused compatibility overloads is noncritical cleanup. Actual canonical production constructors populate close capability/failure_code; these are not dead optional fields.
R1-33 deferred Distinguish persisted retry/block from abandoned-claim warning text in a followup. valid=false correctly prevents all store mutations; the warning is misleading diagnostics rather than unsafe completion.
R1-45 deferred Narrower placement locking is a throughput followup requiring a fresh lock/fence proof. The earlier cross-tenant missing-fence gap-lock premise is stale: current fence reads are nonlocking and immutable tenant lookup is outside the transaction. Current tenant serialization preserves correctness.
R1-51 deferred Split invalid digest and invalid isolation into independent negative tests. Both production checks exist; current public close enumeration is Session-isolated and no reachable shared-worker stop was established.
R2-5 deferred Filter inactive Runtime Session history and align the paging index if scale warrants. Current bounded pagination skips terminal rows and releases all original active Sessions correctly; this is noncritical performance work.
R2-6 deferred Add separate negative controls for holder, renewal tick, failure-code remap, required fence and blocked-operation admission. The inspected production gates exist; missing test coverage alone is nonblocking.
R2-7 declined Retirement before signalling is explicitly required: it is the durable tombstone preventing a late original launch. It is not the stop receipt. Exact process absence must still be confirmed before returning and persisting RuntimeDrainReceipt, and fenced normal close skips fabricated JOURNAL_LOST recovery. Moving retirement after the kill would weaken the accepted protocol.
R2-8 deferred Process-group/descendant shutdown needs a separate durable identity design before enabling child-spawning Shell/MCP profiles. This public close slice advertises only file operations and rejects MCP configuration; no in-scope persistent child was established. A child snapshot alone is not crash-safe original-resource proof.
R2-9 declined Existing writer renewal during CLOSING is intentionally allowed for settlement and seal by the user plan and both designs. The MySQL fixture acquires while ACTIVE, then closes and renews that exact writer. New acquisition is Session-row gated; adding an ACTIVE condition to renewal would break required cleanup.
R2-10 deferred A bounded positive database-wait witness would strengthen the 100 ms negative timeout against slow connection scheduling. The actual FOR UPDATE remains; local mutation evidence does not justify claiming deterministic detection under every CI delay. Record this test strengthening as followup.
R2-11 deferred Retain only unsupported-provider, false-release, identity-mismatch and precise startup-state fixture gaps. Foreign/missing registration cases and production-shaped approval IDs/expiry already exist; mount invalidation intentionally verifies cleanup after configuration changes. Those stale premises should not be reverted.

Validation on the unchanged candidate tree: CLI 283 pass; core writer/hooks 153 pass plus 10 platform skips; core Harness/recovery 121 pass; Broker Java 254 pass; Managed Java 85 pass; both Java checkstyle checks pass; disposable MySQL close concurrency 5 pass. HostedPublicWorkspaceIT executes 2 passes and skips the Linux-only durable-close case on macOS. Independent actual HTTP recovery-owner probes pass 4/4 on both the reviewed HEAD and merged candidate; the other 165 candidate cases in that private probe run were skipped, not claimed executed. Fresh owned bundled-daemon authenticated health/capabilities and orderly shutdown pass. Two clean self-audit passes and an independent close/Hooks composition review completed. Post-commit build/typecheck/bundle passed before push; precommit formatting/lint passed without altering the reviewed tree.

Preserved validation limit: the complete physical Linux worker-stop, reboot and close crash matrix remains unexecuted. Previous-HEAD Linux normal-close CI is evidence only for that specific normal path; it is not a substitute for the full matrix. Current HEAD CI will be checked after push; local green checks do not imply new GitHub CI is already green.


本轮已同步 main 的 Hosted Hooks H2,保留 close/attachment/运行 owner 的准入栅栏及双方测试。实际复现的部署阻塞是两份 V27 迁移重复;close 原 SQL 已移至 V28,中英文设计同步,H2 和真实临时 MySQL 均验证 28 个迁移。两条 Critical 复核后均未采纳:运行 owner 有正常释放路径,竞争请求不能抢先归还其租约;缺失或外部主机身份必须按既定契约保持 CLOSING/recovery_blocked,等待原资源的停机证明。另两项与退休先于信号、原 writer 关闭期间续租有关的建议也保留原设计;22 项窄范围的非阻塞建议逐条记录在上表,后续处理。

本轮定向 TS/Java、真实 MySQL close 并发、实际 Hosted E2E 可运行部分、独立 HTTP 复现、双轮自审、独立合并审查以及提交后的 build/typecheck/bundle 均通过。macOS 的 Linux 持久 close 用例实际跳过,完整物理 Linux 停机/重启/崩溃矩阵仍未执行,不能报告为通过。继续每小时处理该开放 PR;不自动合并或改变 draft。

@qqqys qqqys left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

COMMENT — reviewed at head d7c5c5e50ebb74ea2bb4aea1fdf37b8bbaa8fd82. One new Critical that blocks merging, one round-4 Critical confirmed fixed, and one round-4 Critical I could not confirm fixed.

New Critical: this branch's migration version collides with what landed on main an hour ago

main now carries V31__workspace_recovery_bundle.sql. It arrived when #13138 merged at 2026-10-02T10:06:46Z. This head still ships V31__workspace_session_close.sql, and its tree contains no workspace_recovery_bundle migration, so the branch has not absorbed main since that merge.

Once both are on main, the module ships two different migrations declaring version 31. Flyway rejects that at startup rather than choosing one, so managed-agent-server will not boot on any deployment that runs its migrations. Nothing warns anyone beforehand: the two files have different names, so there is no git conflict, and every CI lane on this PR ran against a base that predates the other V31 — the 30 green checks here include the MySQL integration legs, and none of them can see it.

Live state at the time of writing, both locations:

  • main SQL: … V28__managed_hook_admission_index, V30__managed_tool_output_retention, V31__workspace_recovery_bundle
  • main Java: V15__managed_event_identity, V29__managed_hook_admission_backfill
  • this head SQL: … V28, V30, V31__workspace_session_close

The fix is a re-sync plus a renumber to the next free version in both locations, which is V32. Two notes from this PR's own history. The branch has already been renumbered once for exactly this reason — 0b9ad071e5 "avoid close migration collision", and 6c6e58441a "sync main and sequence close migration" before it — so this is the second collision in two days and the version will keep moving until it lands; a merge-queue slot or a rebase immediately before merge is what actually ends the cycle. And the round-4 Suggestion R4-2 already records that the description's deployment-facing migration note contradicts the migration the diff ships, so the renumber should correct the description in both languages at the same time rather than leaving a third version number in the body.

R4-1 confirmed fixed — a binding that never attested a resource can now be closed

stopDrained no longer opens the durable registration with a hard-coded create = false. It derives the intent from the binding's own evidence:

boolean createIntent = binding.getResourceHandle() == null && binding.getLease() == null
        && binding.getAttestationGeneration() == 0;
return CompletableFuture.supplyAsync(() -> store.locked(binding.getRequest(),
        binding.getProvisionSeed(), binding.getResourceHandle(), createIntent, (resource, registration) -> { …

so the state the finding named — a committed binding row with resourceHandle == null after an IOException in validate(directory, true) or Files.createFile(lockPath), or a broker death between the committed findOrCreate insert and the registration creation — creates an intent registration instead of throwing the non-retryable blocked(). The callback then lets that registration through all three of its refusals: the first blocked() is carved out for registration.pid() == 0 when the state is INTENT or RETIRED, the second is guarded by !neverStarted, and the workspace_close_stop_unconfirmed 503 is guarded by !neverStarted as well, where neverStarted = registration.pid() == 0. The intent is retired with resource.save(registration.withState(RETIRED)) and a real RuntimeDrainReceipt is returned, so the drain settles and the binding can leave DRAINING — which is what unblocks the requireRecoverablePlacement refusal the finding pointed at. Requiring all three of handle, lease and attestation generation to be empty before treating a binding as never-started is the right narrowness: a binding that attested anything takes the evidence path instead.

R2-2 not confirmed fixed — the foreign-host arm still throws before the callback runs

The finding's narrowed claim is that the same-host reboot trigger is fixed but a foreign-host or missing-registration identity change still cannot complete a fenced drain. At this head the reboot arm is handled (originalBootStopped = trustedRebootRecovery && store.rebooted(registration)) and the never-attested arm is handled by createIntent above. The remaining arm is not visibly addressed by this diff: when the binding did attest a resource, createIntent is false, so store.locked is called with create=false, and on a node that does not hold the local registration the store reads registration == null and throws the non-retryable blocked() — before any of the new originalBootStopped / neverStarted logic can run, because all of it lives inside the callback.

I am recording this as unconfirmed rather than asserting it, because closing it needs three things I could not trace in this pass: what LocalRuntimeStore.locked does on a missing registration when create is false, whether recoverBinding's fence short-circuit still removes the recovery route while isHarnessDraining is true, and whether qwen_runtime_harness_drain still has no production DELETE. The finding itself narrowed in the author's favour this round — WorkspaceOperatorRecoveryStore.canPrepare admits a DRAINING binding, so a supported operator exit exists — which turns "uncloseable absent manual SQL" into "uncloseable without an operator recovery flow". Whether that residual is still Critical is a call for the reviewer who filed it or for a maintainer; it is not mine to make from a partial trace.

The earlier Criticals (R1-39, R1-2, R2-1, R2-3, R2-4, R3-1) are marked fixed in the later ledgers and I did not re-verify them at this head.

Scope of this pass

I read the migration set on both refs and in both locations, stopDrained in full, the two round-4 Critical texts, and the CI state. I did not scan the rest of the 49-file diff — RuntimeBrokerService.java (+169), ManagedAgentStore.java (+101), JdbcRuntimeBindingRepository.java (+102), the session-lifecycle coordinator and service, hosted-harness-session.ts (+19), the OpenAPI and generated web-shell client changes, or the ~1,700 lines of new tests.

CI at this head

No check failed: 30 succeeded, review-pr was still running, and two route runs were cancelled, which is workflow plumbing. The maintainer approval on record was submitted at 09:33, before #13138 merged at 10:06, so it could not have observed the version collision; that is a statement about timing, not about the approval's judgement on anything else.

@doudouOUC
doudouOUC dismissed a stale review October 2, 2026 10:26

Already have 2 approves,3ks

@chiga0 chiga0 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review — feat(managed-agent): reliably close workspace-bound sessions

Tier: Deep (DB schema migration, concurrency lifecycle protocol, hard-to-reverse)

Scope

Reviewed: V31 migration, SessionLifecycleCoordinator, SessionLifecycleService, ManagedAgentStore, WorkspaceRuntimeProvisioner, RuntimeBrokerService, LocalProcessRuntimeProvisioner, OpenAPI spec, WorkspaceSessionCloseTest, ManagedSessionOperationStoreTest.
Not reviewed: docs/design/ (docs-only), Windows platform behaviour (no host).


Findings

Minor — redundant validateOperationStart call in beginLifecycle (ManagedAgentStore.java)

For new workspace-close admissions where session.workspace() != null && "ACTIVE".equals(session.status()), validateOperationStart(session, kind) is called twice — once before requireNoOpenOperation and once unconditionally after it — executing hasActiveTurn() and hasDecidableAction() twice. No functional impact; two redundant DB queries per new admission. Carry-forward or address in a follow-up.


Cleared concerns

Item Verdict
error_code missing from V31 migration ✅ Column already exists since V24
V31 migration conflicts ✅ SQL bytes unchanged from provisional V30; clean
lifecycleDatabaseTime() correctness ✅ TZ-agnostic epoch-ms; correct
Concurrency (lease renewal, generation CAS) ✅ Design is sound
Auth ordering (creator-only, current-read check) ✅ Intentional per design

Cross-check against existing reviews

Reviewed wenshao's three real-environment runs (rounds 1–3, Linux/container/MySQL 8.4.7):

  • Normal close on both surfaces, refusals, race with delayed warm, crash takeover, neighbouring Session — all pass at head ✅
  • F1 (container restart → new PID/time namespaces): accepted close never completes; Session stays CLOSING; Workspace storage blocked. Confirmed by wenshao; acknowledged by author as an open pre-admission policy decision out of scope for this PR.

F1 is the one remaining policy question explicitly flagged by the maintainer. The code is correct for the stated scope; F1 is a deliberate fail-closed choice the project leads must decide.


No confirmed blocking code defects. Approving on the code-correctness dimension; the F1 admission policy remains a project-level decision.

Reviewed with AI assistance.

@doudouOUC
doudouOUC added this pull request to the merge queue Oct 2, 2026
Merged via the queue into main with commit 9478f28 Oct 2, 2026
182 of 185 checks passed
@doudouOUC
doudouOUC deleted the codex/workspace-session-reliable-close branch October 2, 2026 10:49
@doudouOUC
doudouOUC restored the codex/workspace-session-reliable-close branch October 2, 2026 11:07
@doudouOUC
doudouOUC deleted the codex/workspace-session-reliable-close branch October 2, 2026 11:08
@wenshao

wenshao commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

Follow-up on this review — the merge raced it (#13135 merged at 10:46Z at d7c5c5e5, after #13138 took V31 at 10:06Z), so the new Critical materialized on main.

V31 collision — confirmed live on main, hotfix open

A main checkout at 9478f28731 reproduces exactly what the review predicted: org.flywaydb.core.api.FlywayException: Found more than one migration with version 31, offenders V31__workspace_recovery_bundle.sql and V31__workspace_session_close.sql — any managed-agent-server boot or test context that runs migrations now aborts. Hotfix #13223 renumbers the close migration to V32 with its SQL bytes unchanged, updates the close design doc in both languages to the final sequence (…V30 → V31 recovery bundle → V32 session close), and fixes a cross-feature drift the renumber exposes: #13138's recovery-bundle tests complete a leased DELETE whose fixture row has no lease_until, which the close flow's database-time lease-freshness check (completeOperation) refuses — a state production never produces, since every LEASED row goes through claimOperation. The fixture now carries a far-future lease; deleting it makes those eight tests red again. Full module suite (mvn test, 435 tests) and checkstyle:check pass on the hotfix branch. This PR's description is updated in both languages to point at the shipped V32, closing out R4-2's version-trail note as well.

R2-2 — the three open questions, answered at the merged code

All three traces resolve in the finding's favour, so the residual stands as narrowed:

  1. LocalRuntimeStore.locked with create=false, registration missing throws the non-retryable 409 runtime_broker_recovery_blocked before the callback runs, at two points: if the node's local store has no lock inode for the seed (LocalRuntimeStore.java, the !create guard in the lock-creation branch), or a lock exists but the registration JSON does not (registration == null guard right after). Both fire before operation.run(...), so the new originalBootStopped / neverStarted logic in LocalProcessRuntimeProvisioner.stopDrained is unreachable on this arm — the attested-binding foreign-host drain cannot complete.
  2. recoverBinding while isHarnessDraining is true — the short-circuit is still there, twice: pre-claim and post-claim both return the saved record unchanged for non-LOST session-isolation bindings (RuntimeBrokerService.java, recoverBinding), so the automated recovery route stays removed while the fence stands.
  3. qwen_runtime_harness_drain has no production DELETE — confirmed. JdbcRuntimeBindingRepository only INSERTs (markHarnessDraining) and SELECTs (isHarnessDraining) that table; clearing a fence is manual SQL.

The mitigating observation also checks out: WorkspaceOperatorRecoveryStore.canPrepare admits DRAINING (alongside READY/RECOVERY_BLOCKED/LOST) when no stop evidence exists, so a supported operator exit exists — but if that flow drives the drain on a node that does not hold the binding's local registration, it terminates at the same locked() wall as (1), leaving the binding in DRAINING behind a permanent fence. Whether that residual remains Critical is, as the review framed it, the original reviewer's or a maintainer's call.

R4-1

Agreed with confirmed-fixed — nothing further there.

yiliang114 pushed a commit to LubabaKhalid/qwen-code that referenced this pull request Oct 2, 2026
…3223)

Main carries both V31__workspace_recovery_bundle from QwenLM#13138 and
V31__workspace_session_close from the merged QwenLM#13135, so Flyway aborts at
startup with 'Found more than one migration with version 31' and every
managed-agent-server migration (and the deployments running them) fails.
Renumber the close migration to V32 with its SQL bytes unchanged and
update the close design doc in both languages to record the sequence.

The merged close flow also completes lifecycle operations only while the
claim lease is fresh in database time. The recovery-bundle tests added
by QwenLM#13138 complete a leased DELETE whose fixture row has no lease_until,
which production never produces, so give the fixture a far-future lease.
yiliang114 pushed a commit that referenced this pull request Oct 2, 2026
…und Turn

WorkspaceSessionCloseMySqlIT (#13135) was written before this PR, when a
bound Session refused every later Turn with workspace_unavailable. With
Workspace files enabled this PR admits the creator's later Turns, so the
Turn queued behind the close now reaches the Session status and answers
session_not_active, which is what the test means to show: the close commits
before the queued admission inspects the Session.
qqqys pushed a commit to qqqys/qwen-code that referenced this pull request Oct 8, 2026
…enLM#13163)

* feat(managed-agent): admit later Turns of a Workspace-bound Session for its creator

G0 admits only the initial file-tool Turn created with a Workspace-bound
Session; every later public submit is refused with workspace_unavailable,
so a Hosted Session cannot hold a conversation.

Admit a later Turn when the deployment's Workspace-files opt-in is on
and the submitter created the Session. Execution already authorizes
each Turn against the creator's Workspace grants
(WorkspaceExecutionStore.authorize), so letting another actor submit
would run tools under the creator's authority; every other actor keeps
the existing refusal (404 without read access, 409 otherwise). The
store admits a bound Session's later Turn only under the same opt-in.
Cancel, rename, lifecycle and cwd operations stay gated.

- ManagedWorkspaceRegistry.createdSession looks up the creator in
  managed_workspace_create_command.
- HostedPublicWorkspaceIT: a reader who is not the creator is refused;
  the creator's second Turn runs write, edit and read again through the
  real Broker and worker and completes.
- ManagedWorkspaceAdmissionTest: the enabled store admits the later
  Turn and the creator lookup distinguishes actors and tenants.
- The Workspace-binding capability description (contract and generated
  WebShell types), the README and both G0 design documents describe the
  new boundary. The contract version is left for QwenLM#13101, which takes
  1.25.

Not built or run locally.

* feat(web-shell): let the creator send later Turns to a bound Session

The server now admits later Turns from a Workspace-bound Session's
creator, but the Managed panel still hid the composer for every bound
Session and the Java provider forced canSend to false.

- WebShellSessionCapabilities gains workspaceTurns, computed per Session
  and caller with the same rule the submit path enforces (opt-in on,
  caller can read, caller created the Session). The contract and the
  generated WebShell types describe it.
- The Java provider sends for a bound Session only when the service
  reports workspaceTurns, and reports it in the summary only when true.
- The Managed panel shows the composer for such a Session; cancel stays
  hidden for bound Sessions.
- HostedPublicWorkspaceIT checks the capability per caller through the
  WebShell route; the contract test's WebShell capability shape and
  provider/page tests cover the client.

* feat(managed-agent): let the bound Session creator cancel a running Turn

Later Turns of a Workspace-bound Session could be submitted by the
creator but not cancelled: the service and store refused the cancel,
and the coordinator skipped bound Sessions entirely.

Apply the same rule to cancellation. The creator, with the Workspace-
files opt-in on, may cancel; the coordinator then cancels through the
Hosted Harness like any other Turn, which aborts the Turn and settles
its Runtime calls through their original identities. Other actors and
deployments without the opt-in keep the existing refusal, and the
coordinator still leaves a bound Session alone without the opt-in.

- HarnessCoordinatorTest: without the opt-in only the opt-in is read;
  with it, the bound Turn is cancelled through the Harness.
- HostedPublicWorkspaceIT: a later Turn is held in the model call; a
  reader's cancel is refused, the creator's cancel is accepted, and the
  Turn ends CANCELLED with no tool execution.
- WebShell reports canCancel for such a Session when workspaceTurns is
  set, so the Managed panel shows Cancel.
- Contract text, generated types, README and both G0 design documents
  now keep only lifecycle operations gated.

* feat(managed-agent): let the bound Session creator rename it

Rename of a Workspace-bound Session answered 409 until a role source
decided who may change it (D4 4.9). QwenLM#12867 settled the first version:
the Session's creator is its only owner. Rename changes only the title
through the Hosted Harness and touches no Runtime, so apply the same
creator rule under the Workspace-files opt-in; the store admits only a
RENAME mutation of a bound Session, and only under the opt-in.

Close, archive, delete and unarchive stay gated: the embedded Broker's
drain only stops warming a closed Session and has no Harness-level
teardown yet, so closing a bound Session would leave its worker and any
held Workspace lease behind.

HostedPublicWorkspaceIT: a reader's rename is refused; the creator's
rename returns the new title.

* style(web-shell): keep the workspaceTurns expression on one line as Prettier prints it

* test(managed-agent): read the renamed title from the public Session metadata

PublicSession carries its title under metadata.title; the rename
assertion read a top-level title and saw an empty string although the
rename returned 200.

* fix(web-shell): match the generated optional workspaceTurns capability

* test(managed-agent): keep the approval run out of the later-Turn checks

* docs(managed-agent): Align G0 gating statements with creator later-Turn admission

The G0 section and Prerequisites still published the pre-follow-up gate
("later submit/cancel remain gated"), contradicting the boundary
paragraph this PR adds; state the creator's submit/cancel/rename
admission and keep close/archive/delete/unarchive and cwd gated. Scope
the follow-up's refusal precisely: requireLegacyWorkspace answers
workspace_unavailable only when the actor can read the Workspace, and
session_not_found otherwise. Apply the same two corrections to the
bilingual design doc and note the follow-up's composer UI change.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmuoob5v90j

* chore(managed-agent): Bump the public API contract to 1.27.0

The deferral resolved: QwenLM#13101 merged and took 1.25.0, and QwenLM#13117 took
1.26.0. Record this PR's contract change per the version-history
convention: creator later-Turn admission and the workspaceTurns
capability.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmuoob5v90j

* fix(web-shell): hide execution-unavailable banner line when creator can send later Turns

The workspace-binding banner always stated that message execution is
unavailable, contradicting the composer this PR enables for the creator
of a bound Session with workspaceTurns capability. Gate the third
banner paragraph on !capabilities.workspaceTurns so the page no longer
states both. Pin both branches in ManagedSessionsPage tests.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmuoqgbnv0l

* test(sdk-java): pin bound-Session admission clauses with negative controls

Three of the four clauses this PR adds to bound-Session admission could
be deleted with the suite staying green:

- ManagedWorkspaceRegistry.createdSession's session_id column: create a
  second bound Session by actor-b under a distinct idempotency key and
  assert createdSession(tenant, actor-a, otherSession) is false, so the
  lookup must match this Session, not any Session the actor created.
- maySubmitWorkspaceTurn's harness.isWorkspaceFilesAvailable() clause:
  assert the bound-session web-shell GET reports
  capabilities.workspaceTurns == false while the opt-in is off.
- boundRenameAllowed's kind conjunct: assert beginSessionMutation with
  UNARCHIVE on the enabled store throws workspace_unavailable, and add
  the positive insertCancelCommand control so the cancel path stays
  open for bound Sessions under the opt-in.

Each new assertion was verified to go red under the corresponding
mutation (session_id dropped, flag clause dropped, kind conjunct
dropped, cancel conjunct dropped) and the suite returns green with the
sources restored.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmuoqgbnv0l

* test(sdk-java): exercise later Turns under approval-mode=default and pin canRead

HostedPublicWorkspaceIT changes:

- register() now grants the reader in both runs (can_create only in the
  files run), removing the access-table primary-key collision that
  forced the approvals run to skip the later-Turn block.
- The approvals run now drives a later Turn through answerActions and
  asserts it completes, so a later Turn admitted under
  approval-mode=default is covered; the cancel/rename probes keep their
  held model reply and stay in the files run to fit the method timeout.
- proof.txt is reset to a sentinel just before the later-Turn submit, so
  the post-Turn "after" assertion can fail if the later Turn's write and
  edit stop reaching the bound root (R1-13).
- After the rename check, revoking the creator's read grant asserts
  submit, cancel and PATCH all answer 404 session_not_found, pinning
  the canRead clause of maySubmitWorkspaceTurn (R1-12 clause 3).
- Model-request counts become 16 (approvals) / 18 (files) and the
  approvals run now answers 8 actions across the two Turns.

Compile-verified via mvn test-compile. Execution requires the bundled
dist/cli.js plus a MySQL/hosted-Harness stack, which this environment
cannot provide; behavior was traced against requireSubmitter /
requireLegacyWorkspace / boundRenameAllowed and the fixture request
model, and CI remains the executor.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmuoqgbnv0l

* fix(sdk-java): align bound-Session later-Turn admission with the execution authority

Round-2 review of QwenLM#13112 found the admission predicate certifying Turns
that execution can never run. maySubmitWorkspaceTurn now also requires the
predicates the cited authority fixes at creation (Session ACTIVE, the
qwen-code agent, the frozen execution profile refs) and the creator's
can_create on an ACTIVE registry, read through the same grant row shape;
a can_read-revoked creator still falls through to the documented 404.
Cancellation attaches passively so an abort no longer depends on the
physical mount still verifying. renameSession answers a non-retryable
refusal with its own status and code instead of a transient 503.
requireSubmitter loads the Session once per call, and the session read
paths skip the canRead probe their entry already established. The OpenAPI
contract, README and both design docs now state the creator admission,
its grants qualifier and the still-gated lifecycle/cwd operations
consistently, and the generated WebShell types are regenerated from the
corrected contract. Tests pin the bound rename admission, the two
empty-creation profile escapes and the can_create-revoked arm.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(sdk-java): cancel a live bound Turn through its running attachment

26de98c made the live cancel attach passively. A passive attach reloads
the Session in the Hosted Harness instead of reusing the running Turn's
attachment, so the abort never reached the Turn and HostedPublicWorkspaceIT
timed out with the Turn still CANCELLING. Restore the ordinary attach for
the live path; cancellation recovery, which has no live attachment, keeps
attaching passively. Cancelling under a refused Workspace authorization
stays a follow-up.

* fix(managed-agent): stop a bound Turn under refused authorization

Follow-ups to QwenLM#13112 from its round-4 verification (QwenLM#13162).

Cancelling aborts work that is already running, so it no longer needs the
grants that admit new work: the creator who can still read the Workspace
may cancel while can_create is revoked, the Workspace is draining or it was
re-registered. A live cancel reuses the running Turn's attachment and runs
no Workspace authorization; only without one does it fall back to the
existing attach. A cancel the Harness did not take is re-sent with backoff
while the Turn is still CANCELLING, since the running dispatcher checks
CANCELLING only once.

Admission of new work now also requires the Workspace generation and
storage the Session was bound to, so a re-registration refuses submit and
rename synchronously, before any command row is written. Tests pin the
opt-in clause, the creator cancel under revocation and re-registration, the
live-attachment path and the resend, and the IT cancels a running Turn after
revoking the grant and draining the Workspace.

* fix(managed-agent): fail the Turn when a cancel attach is refused

The bound-Session cancel path attaches through the strict 3-arg createOrLoad.
When the Workspace authority, or the storage guard behind it, refused that
attach, the RuntimeException fell into the catch that promises recovery: no
harness.cancel was issued for a cancel the API had already answered 202 for,
no sweeper re-claims a Turn whose lease the live consumer keeps renewing, and
the Turn ran on and settled COMPLETED. Settle the Turn with the refusal's own
code instead of dropping the cancel silently.

Addresses review thread R2-1 (PRRT_kwDOPB-92c6n-tVW).

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmupkgkl21b

* fix(managed-agent): retire a refused rename command instead of wedging rename

The permanent-refusal branch in renameSession rethrew a 4xx after
beginSessionMutation had already written a PENDING RENAME_SESSION row. Nothing
retires that row, so every later rename with a fresh key died in
requireNoOpenOperation with session_operation_active for the Session's life.
abandonSessionMutation deletes the still-PENDING row before the refusal is
answered, so the Session accepts the next rename again.

Addresses review thread R3-1 (PRRT_kwDOPB-92c6n-tVl).

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmupkgkl21b

* refactor(managed-agent): drop the dead read-grant operand and fix the published rule

maySubmitWorkspaceTurn's canRead operand, readGranted flag and 2-arg/3-arg
overload pair cannot change any result: findReadable already joins the same
access row with can_read = TRUE, and createdSession still runs first so an
actor id the registry key cannot encode keeps answering false instead of
throwing. The README's later-Turn rule now names the create grant and the
registry's ACTIVE state, as the OpenAPI capability text already does.

Addresses review threads R1-8 (PRRT_kwDOPB-92c6n-tVt) and R1-5
(PRRT_kwDOPB-92c6n-tV0, PRRT_kwDOPB-92c6n-tV-).

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmupkgkl21b

* refactor(managed-agent): cancel an admitted Turn without attaching

bindHarness compares the given boot with the Session's bound boot, and an
admitted Turn's boot is already bound, so the attach in cancelAdmittedTurn
only recomputed it while re-running the Workspace authorization. Pass the
bound boot instead and drop liveAttachment; harness.cancel already reuses
the running Turn's attachment. Re-send at a fixed two-second interval
instead of a backoff table.

* docs(managed-agent): state the full later-Turn admission rule and narrow the bound-Session notice

The published rule on createSession, webShellCreateSession and the
workspaceTurns description omitted the caller's live read and create
grants and the registry's ACTIVE state, so the public surface could not
discover the rule maySubmitWorkspaceTurn actually applies; the public
descriptions now also say there is no per-caller flag there and callers
must handle 409 workspace_unavailable. The bound-Session notice claimed
message execution "is not available in this service yet", which is false
for every per-caller refusal (not the creator, grant revoked, Workspace
draining) while the deployment serves the creator fine; narrow the copy
to "You cannot send messages in this Session" so it is true for both
causes. The webShellCreationIsMetadataOnlyUntilExecutionIsWired comment
claimed to pin the isWorkspaceFilesAvailable clause though its 3-arg
registration's drifted profile refs make the refusal over-determined;
say so instead.

Addresses review threads R3-4 (PRRT_kwDOPB-92c6n-tWn), R3-6
(PRRT_kwDOPB-92c6n-tWw) and the R3-2 comment anchor
(PRRT_kwDOPB-92c6n-tWZ).

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(managed-agent): deliver cancellation through the running owner

* fix(ci): bound hosted browser dependency installation

* fix(ci): record the ci.yml growth in the workflow size baseline

The hosted-browser install step adds two lines to ci.yml, taking it to
147136 bytes: 4110 over the recorded 143026 and 14 past the 4096-byte
allowance, which is why "Check workflow file size" failed. Most of that
growth is main-side drift the allowance had been absorbing, but this PR
touches the file, so the ratchet's stale-baseline leniency does not apply
and the number has to move in the same PR. The growth is real — a bounded
apt/Playwright install — so bump the entry instead of shrinking the
workflow.

Verified locally: .github/scripts/check-workflow-size.sh exits 0 against
base a7deb01, and scripts/tests/workflow-size.test.js passes 220/220.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-conflict/jmupvw3d00b

* fix(ci): reserve browser smoke time after slow dependency downloads

* fix(ci): keep time for smoke after slow hosted installs

* test(web-shell): wait for step expansion before selecting next group

* test(ci): align hosted browser timeout contract

* fix(managed-agent): retry transient cancel-attach refusals instead of settling the Turn

The cancelAdmittedTurn catch settled the Turn permanently for every
RuntimeException out of createOrLoad, so a transient blip (a retryable
broker refusal, a daemon 5xx, a store error) terminally failed an
already-admitted, still-executing Turn whose Harness side kept running.
Rethrow anything that is not a non-retryable RuntimeBrokerException so
the Turn stays CANCELLING and the dispatch sweep re-attempts the cancel,
the pre-existing recovery path. Only a permanent refusal still settles
the Turn, under its own broker code.

That classification makes cancelRefusalCode's non-broker fallback
unreachable — a RuntimeBrokerException code is non-null by constructor
invariant — so the helper is removed rather than tested as dead code.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmuq5w6bb0f

* fix(managed-agent): retire the rename command row on every answered failure

A rename answered without completing retired its PENDING command row only
for non-retryable broker refusals; every other failure family (a daemon
4xx/5xx, the connector's approval-mode IllegalStateException) left the row
PENDING forever, and requireNoOpenOperation then wedged every later
lifecycle change of the Session with 409 session_operation_active. Retire
the row for any RuntimeException and keep the retryable/permanent split
only for choosing the answered status.

The freed key also stayed poisoned: the requested event the abandoned
attempt published has a source_key derived from the key, so a same-key
re-attempt collided on UNIQUE (tenant_id, session_id, source_key) and
answered 500. beginSessionMutation now skips re-appending an already
published requested event, matching the no-event replay it replaces.

Two existing tests pinned the wedge (a 409 for a different key after an
answered failure, and a replay header on the same-key retry); they now
assert admission and a fresh, non-replay re-attempt.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmuq5w6bb0f

* docs(managed-agent): qualify Workspace cancel contract

* docs(web-shell): scope Session creation capabilities

* docs(managed-agent): state the retired-rename-command contract in the README

Two README passages still described behavior this PR changed. The lifecycle paragraph promised a failed rename leaves a resumable PENDING command, but abandonSessionMutation now deletes that row, so a same-key retry is a fresh attempt answered replayed=false and the requested event the abandoned attempt published is not re-appended. The W1a paragraph still denied the public next-turn admission that the G0 section and the v1.28 OpenAPI note now describe; narrow it to the creator's later Turns under the opt-in and keep the resume clause.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmuqn1gku0t

* test(managed-agent): pin the command half of requireNoOpenOperation

allowsOneLifecycleChangeAtATime held the suite's only witness for the PENDING-command conjunct, and this PR replaced those four lines because they pinned the wedge the retirement removes. Deleting the conjunct from requireNoOpenOperation now survives the whole module suite, so build a PENDING command row through the store and assert a close and a delete both answer 409 session_operation_active while no operation row is open.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmuqn1gku0t

* test(web-shell): pin the bound-Session Cancel control at the page level

This PR moved the Cancel button inside the composer <form> and made that
form's visibility depend on `!summary?.workspace || workspaceTurns`. No
page-level fixture was both bound and cancellable (0 of 23), so neither
half of that composition was observable here: reverting the form gate, or
re-adding `!summary.workspace` to the Cancel condition, left every case
in the file green while a bound Session's creator lost the ability to
stop a Turn they had just started.

Adds one case mirroring the unbound cancel test. Measured both mutants:
reverting the gate to `!summary?.workspace` and adding `!summary.workspace`
to the Cancel condition each turn this case red (1 failed / 33 skipped)
while the unmutated tree passes 34/34.

Refs review finding R1-10.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmuqp6mdb01

* fix(managed-agent): answer same-key retries from the record, retire rows on any permanent rename failure

- submitTurn/renameSession: look up the recorded admission before the
  Workspace-admission gate, so a same-key retry of an admitted submit or a
  completed rename is answered with the recorded outcome even after a
  re-registration / revoked grant / DRAINING flip the gate off (R1-7). A
  PENDING rename row still falls through to beginSessionMutation, which
  answers it as replayed and re-drives the unfinished mutation.
- renameSession: classify the retire-on-refusal branch by permanence, not
  by exception type — the connector's approval-mode IllegalStateException
  and permanent (<500) DaemonHttpException wedge the PENDING row exactly
  like a non-retryable broker refusal (R1-16).
- OpenAPI: workspaceTurns is served on every response, so move it into
  WebShellSessionCapabilities.required (R1-5).

Tests are written but not executed locally (no JDK 21/Maven on this host);
the three new ManagedWorkspaceAdmissionTest cases go red without their fix
by construction.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(managed-agent): clear rename admission when harness is disabled

* fix(managed-agent): repair the two red required lanes on this head

Both failures are this PR's own, not the base's:

- ManagedAgentService.renameSession called CommandRecord.commandStatus(),
  which does not exist; the record's component is status. This is the sole
  cause of both Java lane failures (maven-compiler-plugin:compile,
  "cannot find symbol / method commandStatus()"), and lines 304 and 363 of
  the same file already use the correct "COMPLETED".equals(command.status())
  idiom.
- WebShellSessionCapabilities.workspaceTurns moved into the OpenAPI required
  array, but the generated TypeScript mirror was not regenerated, so the
  contract-drift guard in managed-agent-api.test.ts failed
  (expected `workspaceTurns: boolean;`, checked-in `workspaceTurns?: boolean;`).
  Regenerated with `node scripts/generate-managed-agent-api.mjs`; the only
  line that changed is the one the guard reported.

Verified locally: managed-agent-api.test.ts 2/2 pass,
java-managed-agent-provider.test.ts + ManagedSessionsPage.test.tsx 53/53 pass,
eslint clean on the regenerated file. The Java edit could not be compiled
here (no JDK 21 / Maven on this host); it is a single symbol-name correction
read off the record declaration in this tree.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmuqtgxwd07

* test(managed-agent): expect the closed Session status for a queued bound Turn

WorkspaceSessionCloseMySqlIT (QwenLM#13135) was written before this PR, when a
bound Session refused every later Turn with workspace_unavailable. With
Workspace files enabled this PR admits the creator's later Turns, so the
Turn queued behind the close now reaches the Session status and answers
session_not_active, which is what the test means to show: the close commits
before the queued admission inspects the Session.

* test(managed-agent): read the renamed Session title from metadata

The public Session body projects the Session title into metadata.title
(ManagedAgentService.publicSession); PublicSession has no title
component, so the three rename assertions written against title() broke
testCompile and reddened both Java lanes on this head.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-conflict/jmur1oq2c0i

* fix(managed-agent): restore admission error precedence in CI

* fix(managed-agent): keep the Workspace refusal ahead of the Harness gate

Both red required Java lanes fail the same six assertions on MySQL 8.4 and
MariaDB (run 37022561191, jobs 110889014145 / 110889014257). Both causes are
in this branch's production code; main has not touched packages/sdk-java since
the merge base b3dda46.

- submitTurn ran requireHarness() ahead of requireSubmitter(), so a Session the
  Workspace refuses was answered with 503 hosted_harness_disabled instead of
  409 workspace_unavailable whenever the Harness is not configured. That is the
  four ManagedWorkspaceAdmissionTest failures
  (revocationHidesBoundSessionAndBlocksRetry:372,
  emptyBoundCreationOutsideTheProfileIsNotAdmittedForLaterTurns:663,
  creatorCancelsWithoutTheGrantsThatAdmitNewWork:1028,
  reRegistrationRefusesLaterWorkBeforeAnyCommandIsWritten:1055). Restore the
  order cancelTurn and renameSession already use, keeping the same-key replay
  lookup ahead of both gates so R1-7 still holds.

- renameSession classified every IllegalStateException as a permanent failure,
  retiring the PENDING command row and answering 409 session_mutation_refused.
  Only the attach path is permanent: that is where QwenHostedHarnessConnector
  refuses an unconfirmed Session approval mode (lines 133 and 364). An
  IllegalStateException out of harness.rename() is an unreachable Harness, and
  main pins it as a transient 503 hosted_harness_unavailable whose row a
  same-key retry re-drives (ManagedSessionLifecycleTest
  .allowsOneLifecycleChangeAtATime:382, ManagedAgentServerIntegrationTest
  .retriesAPendingRenameWithTheSameIdempotencyKey:660, both through the
  failNextRename fixture at ManagedAgentServerIntegrationTest:1744). Track
  whether the attach returned and narrow the arm to that call site, which keeps
  permanentNonBrokerRenameFailureRetiresItsCommandRow green without widening
  the transient path.

Not compiled or executed here: this host has no mvn and only JDK 1.8
(`which mvn` empty, `java -version` = 1.8.0_322, no ~/.m2), while the lanes run
JDK 21 with surefire/failsafe. The change is confined to two statements and
their guard; CI is the verifier.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-conflict/jmur4wgp80n

* fix(runtime-broker): close drained lost workspace bindings

* docs(managed-agent): state the cancel rule and refusal codes the code enforces

The public createSession description bound cancel to the submit-grade
conditions that requireCanceller deliberately does not check (create
grant, ACTIVE registry row, active undeleted frozen-profile Session), so
an integrator gating its Cancel control on them would withhold a cancel
the server accepts and could not abort a runaway Turn on a draining or
re-registered Workspace. Split the sentence: submit and rename keep the
submit-grade rule, now also naming the generation/storage conjunct, and
cancel states the narrower creator-plus-Workspace-read rule. Name the
404 session_not_found that requireLegacyWorkspace answers when the caller
lost Workspace read, next to the 409 already documented.

Drop the rename promise from webShellCreateSession - the WebShell surface
exposes no rename route, rename is updateSession on Public Sessions only -
re-landing the removal already made at 7720f6d. Add the ACTIVE
registry-state conjunct to the workspaceTurns capability so it matches
maySubmitWorkspaceTurn and the "same rule" claim beside it.

The generated WebShell mirror is updated to match; the generator imports
openapi-typescript, which is unavailable without node_modules here.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmurtwo5e1r

* fix(managed-agent): answer bound replays only to the creator and keep Cancel reachable

R3-1: submit and rename now check the creator's durable creation receipt
before the replay lookup, so a reader who did not create a bound Session
neither replays the creator's admission nor learns which keys exist. The
receipt survives revocation, draining and re-registration, so the creator's
own same-key retry still replays.

R3-2: cancel is no longer tied to workspaceTurns in the WebShell provider,
and the Cancel button renders outside the composer when the composer is
hidden. Send keeps its gate; the server refuses a cancel from anyone else.

R3-3, R3-4: scope the published cancel claim to a resident attachment
(after a restart or takeover the owner re-attaches through Workspace
execution authority and the Turn may stay cancelling while it refuses), and
align the README's G0 twin with the later-Turn rule.

* fix(managed-agent): keep a retired rename from reverting a newer title

completeSessionMutation accepts a FAILED receipt so a same-key sibling that
entered the Harness before the retirement can still complete. Nothing
ordered that completion: while the receipt was FAILED, requireNoOpenOperation
no longer saw it, so a rename under a fresh key could begin and complete,
and the late sibling then overwrote that newer title with a 200 and a second
session.updated event.

Refuse to complete a FAILED receipt when a mutation of the same kind
completed after its requested event, answering 409
session_mutation_superseded. Mutation commands on a Session begin one at a
time, so event sequence ids order this strictly where millisecond
timestamps could tie. A same-key request sent after the newer rename
revives the receipt to PENDING and still applies, so the newest request
wins as before.

Reported on QwenLM#13112 (ManagedAgentStore.java:565 review thread).

* style(web-shell): format the bound Cancel page test with Prettier

* style(web-shell): apply prettier to ManagedSessionsPage.test.tsx

The Lint & Static job failed on `node scripts/lint.js --prettier` with
"Code style issues found in 1 file" for
packages/web-shell/client/components/managed/ManagedSessionsPage.test.tsx.
Reformat that one expectation so the branch matches the repo prettier style.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-conflict/jmus7hcqa2c

* fix(managed-agent): recover cold-cache cancels without new-work grants

* docs(managed-agent): include storage in both capability descriptions

* refactor(managed-agent): delete the review-minted dead surface and its duplicate

Closes four open review findings by deletion only; the diff shrinks by 92
lines and no production behavior changes.

- R2-3: both convenience constructors on WebShellSessionCapabilities had
  zero call sites. The only construction is the canonical 8-arg call in
  ManagedAgentService.webShellSession; the contract test touches the record
  through .class for schema naming. The 2-arg overload also took
  (tasks, actions) while the record's components run (tasks, artifacts,
  actions), so it silently mapped its second argument to `actions`.
- R2-4: isSessionCreator was a one-line wrapper over createdSession with
  the two String parameters reversed, leaving two public registry methods
  that differ only in argument order on a creator-identity authorization
  check. Deleted the wrapper; its single caller in
  ManagedAgentStore.requireWorkspaceCreator now calls createdSession with
  the declared (tenantId, actorId, sessionId) order. Equivalent by
  construction: the wrapper body was that same call.
- R2-5 and R2-6: aRenameFailureThatIsNotABrokerRefusalStillRetiresItsCommand
  and permanentNonBrokerRenameFailureRetiresItsCommandRow both pin the same
  single branch -- renameSession's catch fall-through to
  abandonSessionMutation plus dependencyUnavailable("hosted_harness_unavailable")
  -- with the same three assertions. They were distinct while the catch still
  classified DaemonHttpException(<500) and IllegalStateException separately;
  retiring the row on every answered failure collapsed them. The deleted twin
  also stubbed its DaemonHttpException double with a bare mock(), so
  getStatusCode() returned 0 rather than the documented 4xx, and its
  TransactionTemplate wrapper mirrors no production contract (renameSession
  carries no @transactional). The surviving test uses the shared
  boundSession/boundServiceWith helpers, which build the identical
  workspaceFilesEnabled configuration and the identical bound Session.
  The two imports only that test used are removed, as checkstyle enforces
  UnusedImports for this module.

Not compiled or executed here: this host has no mvn and only JDK 1.8. Every
removed member was grepped to zero remaining references across the module,
and no surviving import was left unused. The Java lanes on the pre-push head
52704a9 are green and are the verifier.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmusjmlf72u

* fix(managed-agent): dedupe by dropping this PR's own added test, not main's

Corrects 8d98903, which deleted the wrong twin.

aRenameFailureThatIsNotABrokerRefusalStillRetiresItsCommand is pre-existing
main coverage: it sits at line 776 of ManagedWorkspaceAdmissionTest.java both
at this PR's merge base 2a6879e and on origin/main, introduced by QwenLM#13112
(2b15eac), which is an ancestor of the merge base. Removing it made this
PR delete 80 lines of unrelated main test coverage.

permanentNonBrokerRenameFailureRetiresItsCommandRow is the twin this PR added,
and it is the one that duplicates main's test: both drive the same single
branch (renameSession's catch fall-through to abandonSessionMutation plus
dependencyUnavailable("hosted_harness_unavailable")) with the same three
assertions. They were only distinct while the catch classified
DaemonHttpException(<500) and IllegalStateException separately; retiring the
row on every answered failure collapsed them.

So the deletion moves to the PR's own addition. The test file's diff against
the merge base is now 233 insertions and zero deletions instead of 291/80.
The two imports 8d98903 removed (DaemonHttpException, Mockito.mock) are
restored, as main's test still uses both; no import is left unused, which this
module's checkstyle enforces.

The R2-3 (unused WebShellSessionCapabilities constructors) and R2-4
(isSessionCreator wrapper with reversed String parameters) deletions from
8d98903 are unchanged and unaffected.

Not compiled or executed here: this host has no mvn and only JDK 1.8. The
removed method was grepped to zero remaining references and the deletion is
brace-balanced; the Java lanes are the verifier.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmusjmlf72u

* fix(serve): retain passive recovery leases on refusal

* fix(managed-agent): keep the re-registration guard on the page twin

The page refactor on main rewired webShellSession(session, actorId) to
the batch assembler, whose maySubmitWorkspaceTurn twin answers the
creator submit gate from the batched grant read alone. That read carried
no binding stamp, so a re-registered Workspace kept advertising
workspace_turns on the page and on the single-session path while the
singular gate still refused the submit through bindingCurrent.

Carry workspace_generation and storage_id in the batch grant read and
compare them with the Session's recorded binding, so the twin answers the
same rule without a per-row registry query: the grant batch stays the one
managed_workspace_registry read the page budget asserts.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-conflict/jmutypl6357

* fix(managed-agent): keep the Session lifecycle term on cancel admission

requireCanceller hand-copied only the workspace and files disjuncts of
maySubmitShape, dropping the Session lifecycle term that main enforced
through requireSubmitter. A cancel on a CLOSED, ARCHIVED or DELETED bound
Session answered 202 and wrote a CANCEL command where main answered 409
workspace_unavailable and wrote nothing.

Cite maySubmitShape instead: it restores the lifecycle term and removes the
duplication. The grant and registry terms stay out of the cancel rule, so
the creator can still cancel while can_create is revoked, the Workspace is
draining or it was re-registered.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmuu9s91d5p

* fix(managed-agent): record a passive adoption stranded by a concurrent teardown

The resident passive-load path answered its two post-await exits without
noteOwedAdoption, even though onPassiveRuntimeAcquired had already recorded
the adopted Runtime lease. close() admits a concurrent DELETE here: its guard
is only active/mcpBusy/mcpRecovering/hooksBusy, none of which a parked passive
recovery sets, and the route allows a missing client id. Its releaseLeaseNow
then runs while runtimeLeaseHeld is still undefined, so it releases nothing,
the acquire resolves afterwards, and the adopted Runtime Session is left
unreachable from every route with nothing named on stderr.

Record the strand on both exits rather than releasing it: a release persists
the record as RELEASED and every retried acquire of the same identity then
conflicts with 409 runtime_session_not_acquirable.

Also drain refusedAdoptions on both resident drive-redrive success exits,
matching the resident passive success exit and the record's own contract that
the next successful load of the id drains it. Without the drain a later
genuinely stranded adoption is suppressed by the has(sessionId) latch.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmuug7qaz61

* fix(managed-agent): fence every resident reattach and keep its refusal retryable

The resident split answered a redriven load from the same resident connection
as a passive one, but only the passive branch revalidated the store identity.
Hoist that fence above both branches so a foreign tenant or Workspace stays
hidden and a drifted Session Store address is refused on either path.

A 404 is settled as a terminal Turn failure by the only caller, which would
drop an admitted cancellation on the storage-drift refusal; answer the
retryable conflict instead.

The drive branch also resumed from its recovery await with no post-await
revalidation, so a teardown admitted during the await answered 200 with the
detached Session's clientId and left the acquired lease unreachable. Mirror
the passive branch's fences there and record the owed adoption.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmuva7z827l

* fix(managed-agent): fence the parked passive recovery against teardown

The resident passive load publishes its adopted Runtime lease onto the
route-reachable Session the moment broker.acquire() resolves, while the
recovery is still reading execution states. close() fenced only
active/mcpBusy/mcpRecovering/hooksBusy, none of which a parked passive
recovery set, and DELETE /session/:id resolves with a missing client id
allowed, so a teardown landing in that window released a lease that was still
mid-adoption. The release persists the record RELEASED, and
RuntimeBrokerService.acquireNewSession answers 409 runtime_session_not_acquirable
for any stored state that is neither READY nor ACQUIRING, so every later cold
takeover and every cancel-path status/cancel for that parked Turn failed and the
Workspace stayed pinned.

Hold close()'s own fence for the whole recovery rather than recording the strand
afterwards: the teardown is refused with 409 hosted_turn_active, nothing is
released mid-adoption, and the adopted lease goes back with the teardown the
fence lets through. The pre-diff teardown released nothing but left the adoption
unreachable from every route; the fence removes that window too, so the two
post-await exits no longer carry a false comment.

Also states the deployment's Workspace-files opt-in in the README's authoritative
cancel rule: requireCanceller reaches maySubmitShape, which returns false the
moment harness.isWorkspaceFilesAvailable() is false, before falling through to
requireLegacyWorkspace, which answers workspace_unavailable for a bound Session.
The other contract artifacts already state the condition.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-closeout/jmuvp83ny8e

* fix(managed-agent): preserve concurrent recovery and rename ordering

Count all pending passive recovery requests before permitting teardown.
Persist the newest mutation attempt boundary so a failing sibling does not reject its successful retry.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(test): import Mockito times in coordinator tests

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(serve): preserve live cancellation reattachment

Skip ownerless cancellation settlement while the original Turn still runs, so a cold Java attachment can reattach passively and cancel that owner.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(serve): restore resident recovery outcomes

Preserve terminal decline reasons and reattach requested approvals. Settle payable terminal projections without retrying settled file history, and refuse a cancellation attachment removed during settlement.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(managed-agent): retry transient approval mount failures

Use delivery-time mount verification for action responses and recover cold approval attachments passively after rechecking new-work authority. Preserve shared acquire verdicts and permanent workspace refusals.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(managed-agent): renumber the mutation-attempt migration to V51

main published V48__workspace_storage_migration.sql plus V49/V50 while this
branch was open, and the merge that pulled them in left two files claiming
version 48, so scripts/check-flyway-migrations.js fails the "Flyway migration
version uniqueness" gate. V51 is the next free version across both migration
locations (SQL and BaseJavaMigration, whose highest is V29). Nothing refers to
the file by name or version: the code and tests only use the
mutation_attempt_sequence column, and Flyway applies every migration in the
location, so the renumber only moves this ALTER after main's V48-V50.

Verified locally with the same command the gate runs:
  node scripts/check-flyway-migrations.js packages/sdk-java/managed-agent-server \
    packages/sdk-java/runtime-broker packages/sdk-java/qwencode
before: "2 migrations claim version 48" (rc=1); after: "51 migrations, all
versions unique" (rc=0).

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-conflict/jmuy7yk8zcm

* test(managed-agent): expect the V51 mutation-attempt migration in the upgrade IT

WorkspaceMigrationMySqlIT.upgradesCurrentMainWithoutChangingAppliedMigrations
pins every migration applied after the V47 baseline, so renumbering
V48__managed_mutation_attempt_sequence.sql to V51 left that expectation one
version short and the MariaDB failsafe job failed 1 of 58 tests.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Patrol-Run: qwen-pr-conflict/jmuya3q1ncp

* test(managed-agent): keep Hosted fixture ports distinct

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(managed-agent): retry operator-reversible refusals on the action-response path

A revoked creation grant or a registry that left ACTIVE is
operator-mutable state, not the structural verdict the terminal exit
promises: stamping the committed approval decision FAILED over it
certifies a confirmation the Harness never saw, and restoring the grant
cannot recover it. The passive attachment authority now splits its
verdict into structural, grant-only, and authorized; only the
action-response delivery maps the grant-only refusal to a retryable
workspace_unavailable so the delivery machine re-arms while recovery
waits for the operator. Every other caller — creation, passive load,
cancellation — keeps the previous terminal refusal.

* fix(cli): refuse a resident inapplicable redrive while a prompt slot is active

The helper re-validated registration and closing after its awaits but
never that the Session was still idle, and the latch clear removed the
only incidentally closing guard: a files/rewind admitted inside the
window had its prompt slot overwritten by the settle projection and its
AbortController dropped while /status reported the Session idle. Add
the third post-await re-validation the continue and managed-runtime
cancel routes already perform, answering the session-scoped refusal
before the projection can run.

* test(managed-agent): pin V52 after renumbering the mutation-attempt migration

* fix(managed-agent): preserve approval retries during cold attachment

* test(managed-agent): pin the legacy receipt rewrite and the acquire verdict control

- Wrap the two raw jdbc receipt mutations in exactly-one-row assertions
  so a 0-row arm can no longer collapse onto the tested path.

- Add the positive acquire-path control after the action-response probe
  retry proves its retryable refusal: the same mount must still authorize
  without a verdict change.

Review threads on the 2026-10-07 automated closeout round.

* test(sdk-java): allow heartbeat recovery time after refused detach

Keep the confirmed-detach observation at 200ms, but allow rejected detach responses two seconds to demonstrate continued HTTP heartbeats on macOS.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* test(hosted): pin teardown and pending rename recovery guards

Add HTTP-level deletion and closing interleavings for resident inapplicable recovery, and a public-store pending rename witness. Keep the inherited main heartbeat deadline fix unchanged.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

---------

Co-authored-by: yiliang114 <jinjing.zzj@gmail.com>
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Co-authored-by: yiliang114 <yiliang114@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants