Skip to content

feat(dsh): add handoff preflight and restricted launch foundation - #2602

Open
knqiufan wants to merge 15 commits into
masterfrom
codex/dsh-handoff-preflight
Open

knqiufan wants to merge 15 commits into
masterfrom
codex/dsh-handoff-preflight

Conversation

@knqiufan

@knqiufan knqiufan commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Implements the owner-local DSH Host flow for RFC #2528 and tracking issue #2514. It builds on delivery persistence from #2603 and Host wiring from #2604, and includes the exact receipt recovery and Codex Desktop adapter from #2651 and #2652.

  • Preflight binds the selected reply, working directory, target installation, Server, and Scope. It waits for an overlapping installer, rechecks at preparation dispatch, and verifies the binding again before launch.
  • The Host reclaims unreferenced terminal preflights at capacity, holds a macOS writer lease while delivery services are active, and persists launch attempts and exact receipt identities. A failed check still appears in the handoff omissions when its command contains credential options or exceeds the content limit.
  • Native launch checks the draft and working directory for credentials and records an ambiguous result until the owner explicitly retries the same package. The receiver hooks preserve the exact Scope and handoff identity.

Validation: make check, make js-test (869 plugin tests and 11 real Server E2E tests), make contract-test (69 tests), and make docs-test passed. The macOS Host route test verified lock acquisition, contention, and release on disposal. The Desktop protocol probe passed against the recorded SQLite Server wheel in anonymous loopback, static Bearer, HTTPS with explicit CA and base path, and enforced Provider modes. The Host route test uses a test Host composition and the real OS lock.

AI usage: OpenAI Codex assisted implementation and validation.

@hireview001 hireview001 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.

  • Resolve merge conflicts with the target branch.

}
const check = await adapter.checkIntegration(target, context.signal)
context.signal.throwIfAborted()
if (check.state === 'ready') return { state: 'completed' } as const

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.

[P2] Wait for the shared installer before accepting readiness

When one preflight is installing a shared configuration, another consented preflight can observe ready and pass validateForPrepare before that installer settles, even if it subsequently fails. Join the pending configuration installation before accepting readiness and propagate its final result.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The consented-install path is fixed in 63b716094541bd396dc91ff19bc0a286fc271bf1, but a fresh preflight still bypasses the pending installer. Reproduced through the service API: start A's install, let its integration probe become ready while installIntegration is still pending, then call create for B with a new request ID. B returns ready and validateForPrepare(B) succeeds; A subsequently returns failed. inspect (lines 273–288) and revalidate (lines 245–251) do not consult the shared installation. Please make these readiness gates wait for or reject the in-flight operation and honor its final result before permitting preparation or launch.

@hidb4ai hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Two P2 issues remain: fresh preflights can bypass an unsettled shared installer (reproduction added to the existing thread), and terminal preflight records permanently exhaust bookkeeping capacity.

Comment on lines +81 to +84
let count = 0
for (let item = directory.readSync(); item !== null; item = directory.readSync()) {
if (/^[0-9a-f]{64}\.json$/.test(item.name) && ++count >= this.maxRecords) {
throw new HandoffError('capacity_exceeded')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Allow terminal preflight bookkeeping to release capacity

Every preflight consumes a record permanently, including an installation the user declines. After creating and declining 512 preflights, the next PreflightService.create fails with capacity_exceeded; reconstructing the service over the same store still fails. Neither the store nor the Host routes provide expiry, deletion, or another reclamation path, so even a profile with no deliveries or pending work eventually loses handoff preparation until its private files are manually removed. Provide a supported way to reclaim terminal, unreferenced records while preserving active/unknown work and bindings still needed by saved deliveries.

* feat(dsh): persist and recover handoff deliveries

* feat(dsh): wire delivery preparation into the handoff host

* docs(dsh): describe the assembled handoff host

* fix(dsh): disclose failures when commands are omitted

* fix(dsh): recover deliveries with a kernel writer lock

* fix(dsh): recover deliveries with a kernel writer lock
@hidb4ai
hidb4ai requested a review from AlexStocks as a code owner November 13, 2026 08:53
const route = DESTINATIONS[target]
if (!route || !isAbsolute(cwd) || /[\x00-\x1f\x7f]/u.test(cwd) || typeof draft !== 'string' || !draft.trim()
|| /[\x00-\x08\x0b-\x1f\x7f]|[\uD800-\uDFFF]/u.test(draft)
|| Buffer.byteLength(draft) > 2_048 || hasSecretContent('capture_content_source', draft)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] 启动草稿的密钥筛查用了旧的标记串匹配:既会放过真实凭据,也会让正常草稿整单失败

nativeLaunchUrl 把 draft 交给 hasSecretContent('capture_content_source', draft)。该 operation 在 PAYLOAD_WRITES 里,因此实际走 containsSecretValue(string) → containsSecretMarker(),也就是对 SECRET_MARKERS = ['sk-', 'api_key', 'BEGIN PRIVATE'](src/secrets.ts:18)做区分大小写的子串匹配,而不是同文件里那套 SECRET_PATTERNS/containsSecret。

触发条件 A(误伤,更容易发生):草稿中出现 api_key、sk-、BEGIN PRIVATE 任一子串——例如用户选中的回复本身就写着"不要把 api_key 拼进 URL"或含 sk- 前缀的示例串。此时整次 launch 直接 400 payload_invalid。

触发条件 B(漏检):草稿含 Authorization: Bearer eyJ...、ghp_...、xoxb-...、-----BEGIN RSA PRIVATE KEY-----(注意标记是 BEGIN PRIVATE,RSA/EC 变体不含该子串)。这些都会通过检查,被 encodeURIComponent 拼进 codex://threads/new?prompt=… 后交给 /usr/bin/open。

实际影响:

  • A:用户拿到的是 payload_invalid → "The handoff request or package is invalid.",无法区分"草稿里有疑似密钥"和"请求格式错误";而草稿已经写进 delivery 记录、不可编辑,用户只能换一条回复重新 preflight,整条链路白走一遍。
  • B:凭据随 argv 进入本机进程表与启动服务日志。窗口很短(open 毫秒级退出),但这正是本方法存在筛查的目的;同样的自由文本在 recall 路径上是用 containsSecret(input.prompt, config.authorization) 拦的(lib/index.js:4085),两处判定强度不一致。

证据:src/handoff/native-launch.ts:43;src/secrets.ts:18(标记表)、62-64(子串匹配)、61(注释原文 "Detect secrets without rejecting ordinary words that merely contain a marker",即作者已知标记法不适合自由文本);编译产物 lib/index.js:7720 与 :4085 的对照。

修复方向:改用 containsSecret(draft, config.authorization)(该函数还会把配置里的 Bearer 实值整段抹掉),或先 scrubSecrets 再判定;并给"命中密钥"单独的 error code(而不是复用 payload_invalid),让 400 仍然可诊断。若确实希望保留当前的宽松语义,建议在 Docs 里写明启动草稿不做精确密钥筛查。

@hireview001 hireview001 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.

  • CI failed: CI result (failure).
  • CI failed: dsh-package (failure).
  • CI failed: cindy-package (failure).
  • CI failed: Main (failure). Failed steps: cindy-package / Build and test the standalone Cindy archive; dsh-package / Test DSH package; CI result / Require successful selected checks.

authority.requireLocal()
const assertInstaller = preflight.preparationInstallGuard(context, binding)
const live = await authority.sourceConnection(context, binding.source)
assertInstaller()

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.

[P2] Recheck the installer guard at Server dispatch

Returning from this async resolver yields to prepareCarrier's await resolve(...), allowing a concurrent consented installation to become pending after assertInstaller() succeeds but before handoff_current_work sends task content. Recheck the captured guard synchronously at the actual Server dispatch boundary so preparation cannot proceed while that installer is unsettled.

@AlexStocks AlexStocks added the 1.6.0 v1.6.0 release tracking label Nov 17, 2026
throw new HandoffError('integration_unavailable')
}
const acquired = spawnSync('/usr/bin/lockf', ['-t', '0', '3'], {
stdio: ['ignore', 'ignore', 'ignore', fd], env: { LANG: 'C' }, timeout: 1000, cwd: '/',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P1] /usr/bin/lockf 在 macOS 上不存在,lockWriter 必然失败,整个 handoff 服务在唯一支持平台上无法初始化

lockWriter 先用 process.platform !== "darwin" 把运行平台限定为 macOS,随后 spawnSync("/usr/bin/lockf", ...) —— 但 macOS 系统从不提供 lockf(它是 FreeBSD/util-linux 工具;在 macOS 15 上 /usr/bin/lockf 不存在)。spawnSync 对缺失二进制返回 status: null、error.code: "ENOENT",于是 acquired.status !== 0 恒为真,抛出 integration_unavailable。

影响路径:registerHandoffBridge 注册 /powercontext/targets|preflights|deliveries 后,options.services() 在首次请求时懒初始化并调用 lockWriter → 每次都抛错 → preflight/prepare/launch/delivery 全部 API 永远 503。而 requireLocal、planNativeLaunch、adapter qualification 都把非 darwin 平台拒之门外,因此不存在"lockf 可用的部署平台"。

测试掩盖:handoff.spec.ts、handoff-delivery.spec.ts 与 e2e handoff-host.spec.ts 全部直接调用 createHandoffServices 或注入 services: () => services!,从不执行 registerHandoffBridge 内的 services()/lockWriter 分支,所以全部测试通过也发现不了。

建议:改用进程内 fcntl(F_SETLK)(通过 native 绑定)或用 O_EXCL 锁文件 + 现有进程退出清理,并补一条走 registerHandoffBridge 真实 services() 路径的用例(真实调用 lockWriter)断言服务可初始化。

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Source-level follow-up for b29bc8ad: Apple's macOS 15.0 release manifest pins shell_cmds to 14a2692995de90c2fde0c3c1e639a8c7d9e2312d (shell_cmds-319.0.1). That release includes lockf in All_OSX, and its target inherits INSTALL_PATH = /usr/bin. Its implementation explicitly accepts the descriptor form used here (-t 0 3).

This evidence does not support the claim that macOS never provides this executable or that initialization necessarily fails on macOS 15. I have not exercised registerHandoffBridge on a real macOS host; that validation limit remains. A concrete reproduction on a supported macOS installation, including the OS version and the executable's presence/exit result, would be needed to establish this as a missing-binary P1.

@hireview001 hireview001 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.

  • Resolve merge conflicts with the target branch.

* feat(dsh): verify and recover exact handoff receipts

* test(desktop): qualify the receipt API contract

* fix(dsh): declare handoff connection identity tools

* feat(dsh): add the Codex Desktop handoff adapter (#2652)

* feat(dsh): add the Codex Desktop handoff adapter

* fix(dsh): ship Codex Desktop diagnostics in the default Host

* fix(dsh): recover Codex probes and isolate target discovery

@hireview001 hireview001 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.

.find(item => item.name === 'powercontext' && item.pluginId === plugin.pluginId)
if (!mcpServer || mcpServer.httpOrigin !== new URL(scope.endpoint).origin) throw new Error('MCP origin differs')
const hooks = await hookEvidence(observed.hooks, cwd, plugin, rootPath)
const receiveHandler = join(rootPath, 'hooks/dsh_handoff.py')

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.

[P2] Probe the receiver at its installed path

For an otherwise qualified Codex installation, this probe checks hooks/dsh_handoff.py, but the plugin ships the receiver as powercontext_lifecycle/dsh_handoff.py, causing resolveEnvironment to return integration_unavailable and preventing preflight from becoming ready. Validate and hash the receiver at its shipped path, and align the fixture with the installed layout.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Confirmed on a3ce48391a0f42feb407b9235679e89c306d0950 with a layout-corrected runtime fixture. With the checked-in receiver at powercontext_lifecycle/dsh_handoff.py, checkIntegration returns ready, but resolveEnvironment throws integration_unavailable. Copying the identical receiver bytes into the fixture-only hooks/dsh_handoff.py location makes the same observation pass. Please validate/hash the shipped lifecycle path and use the installed layout in the regression test. This reproduction uses a fixture app-server, not a real Desktop host.

@hidb4ai hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Two P2 issues remain: the Desktop runtime rejects the shipped receiver layout (reproduction added to the existing thread), and Codex doctor reports a complete profile when the newly required identity tool is missing.

capabilities = ["work_contract"]
[[toolsets.tools]]
id = "get_connection_identity"
capabilities = ["handoff"]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Include the identity tool in Codex doctor's full-profile check

This declares get_connection_identity as a required Handoff capability, but src/powercontext/cli/system.py::_CODEX_FULL_MCP_TOOLS still omits it. With every declared tool except this one, powercontext doctor codex --json exits 0 and reports mcp_full_profile.status = "ok", even though the new receiver procedure cannot perform its first required Server-identity check. The existing test_doctor_codex_requires_every_declared_capability_tool[get_connection_identity] reproduces the false healthy result and fails in this head's CI. Keep the packaged doctor checklist aligned with the added capability so this installation is reported as degraded.


def _source_record_response(value: RuntimeSourceRecord) -> SourceRecord:
return SourceRecord(
handoff_receipt=value.handoff_receipt,

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.

[P2] Complete the Source receipt-field rollout

create_subject_source still serializes runtime records with model_dump(), which excludes handoff_receipt. Its response therefore contains null, while fetching the same Source now returns false, breaking test_subject_key_projects_one_source_into_a_stable_user_root. Convert subject-source results through _source_record_response too. Also add the new field to the exact field expectation in test_source_and_artifact_api_round_trip; both assertions fail in every shard 1 job.

CI: View the failed check.

"restore_atomic_memory",
GET_ARTIFACT.operation_id,
GET_ARTIFACT_REVISION.operation_id,
GET_CONNECTION_IDENTITY.operation_id,

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.

[P2] Update the E2E MCP catalog for the new identity tool

Adding GET_CONNECTION_IDENTITY changes the exposed tool catalog, but test_mcp_projects_curated_tools_at_the_configured_server_path still expects the previous exact set. Its extra get_connection_identity entry fails every shard 0 job. Add the intended tool to that E2E expectation, as already done for the unit-level catalog test.

CI: View the failed check.

@AlexStocks AlexStocks added the 1.6.1 v1.6.1 release tracking label Nov 24, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

1.6.0 v1.6.0 release tracking 1.6.1 v1.6.1 release tracking

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants