Skip to content

feat(integrations): share workspace Scope bindings across hosts - #2988

Open
wycocoyu wants to merge 8 commits into
oceanbase:masterfrom
wycocoyu:feat/shared-workspace-scope-2879
Open

wycocoyu wants to merge 8 commits into
oceanbase:masterfrom
wycocoyu:feat/shared-workspace-scope-2879

Conversation

@wycocoyu

@wycocoyu wycocoyu commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Which issue or RFC does this PR close?

Closes #2879.
Implements RFC 2988-shared-workspace-scope-bindings.

Rationale for this change

Today, each workspace-aware host integration binds and resolves workspace Scopes under its own integration name (claude-code, codex, opencode, pi, dsh, workbuddy, zcode, kimi-code, hermes, bub), and derives workspace paths using three incompatible rules (git root + realpath, cwd + realpath, and cwd + path.resolve). Binding a repository checkout to a project Scope in one host leaves every other host on the same machine falling back to the Server default Scope (O(repositories × hosts) manual bindings).

In line with RFC 1345 (opaque Server-owned scope_ids, never derived from paths or Git remotes), this PR introduces a canonical cross-host workspace binding under the reserved integration name shared with zero Server schema, HTTP API, or persistence table changes.

What changes are included in this PR?

This Draft PR is organized in layered commits (bilingual RFC -> shared Python/TS lifecycle + CLI -> host integrations + cross-host E2E -> cross-platform identity, routing cache & CLI refinement) so the RFC can also be reviewed independently if preferred:

  • Bilingual RFC (docs/{en,zh}/rfcs/2988-shared-workspace-scope-bindings.md) & manifest guard (scripts/integration_manifest.py):
    • Specifies the canonical workspace identity rule, home-directory and filesystem-root guard, resolution precedence (up to 5 keys per resolve request), bind/clear semantics, and explicit platform/migration boundaries.
    • Reserves shared in scripts/integration_manifest.py so host manifests cannot claim it.
  • Cross-language workspace identity & Git worktree lifecycle (src/powercontext_integration_lifecycle/, integrations/lifecycle/git-worktree.ts):
    • Derives sha256(utf8(canonical_root)) for existing directories from the single existing git rev-parse call: aligns Python on macOS (fcntl.F_GETPATH) with Node.js fs.realpathSync.native across case-insensitive APFS and NFD/NFC paths, strips Windows \\?\ / \\?\UNC\ prefixes with uppercase drive letters, decodes Git stdout explicitly as UTF-8 (surrogateescape), skips spawning git when cwd is missing, and guards against $HOME / %USERPROFILE% (os.path.expanduser("~") / os.homedir()) and filesystem roots (_guarded_git_top / guardedGitTop).
    • Sets HostProfile.legacy_workspace_binding = False by default so newly added hosts emit only shared:workspace, while explicitly enabling legacy_workspace_binding = True for CLAUDE_CODE and CODEX and preserving byte-for-byte frozen legacy <host>:workspace derivations across existing workspace hosts.
    • Adds diagnose_scope_binding reporting matched_key, synced across generated copies via scripts/generate_integration_lifecycle.py.
  • All 10 existing workspace hosts, CLI, and session importer:
    • Updates claude-code, codex, workbuddy, hermes, bub, dsh (with per-cwd cached routing metadata and rebuilt integrations/dsh/plugins/powercontext/lib/), opencode (with rebuilt lib/), pi, kimi-code (preserving unknown status on partial multi-key unbind failures), and zcode (same partial-unbind unknown guard): binding writes shared:workspace, resolution queries session -> shared (own) -> legacy host (own) -> shared (main worktree) -> legacy host (main worktree) -> default, clearing removes both shared and the host's legacy key, and host diagnostics (--diagnose, doctor.ts, doctor.mjs) surface matched_key.
    • Updates powercontext scope resolve (supporting --integration shared and all 10 workspace hosts), adds --cwd to powercontext scope binding set (validating existing directories and rejecting non-shared --integration) and clear (requiring an existing directory and clearing shared by default, or shared plus <host> when --integration <host> is given), and updates powercontext import-sessions (session_import.py).
  • Bilingual integration docs & cross-host E2E tests (docs/{en,zh}/docs/integrations/, tests/):
    • Updates English and Chinese documentation across all 10 workspace-aware hosts.
    • Adds Python × Node.js parity tests (including APFS wrong-case, NFC/NFD, symlinks, Windows directory junctions, $HOME/%USERPROFILE% guard, and Windows path vectors) in tests/test_git_worktree.py, CLI --cwd / --help tests in tests/test_cli_scope.py, and real-Server + SQLite 10-host end-to-end tests in tests/e2e/test_shared_workspace_scope_binding.py.

Are there any user-facing changes?

  • Binding a workspace Scope in any supported host integration or via powercontext scope binding set <SCOPE_ID> --cwd <DIR> writes a canonical shared:workspace binding that applies across every workspace-aware host opening the same checkout (including subdirectories, symlinks, and linked Git worktrees without their own override). Active sessions that pin their Scope at startup (such as Codex and OpenCode) keep their current session Scope until a new session starts.
  • Existing pre-upgrade <host>:workspace bindings continue resolving without manual migration until superseded by a shared:workspace binding or cleared via host unbind / powercontext scope binding clear --cwd <DIR> --integration <HOST> (note: on non-UTF-8 Windows code pages such as cp936, Python's Git helper now decodes git rev-parse output as UTF-8 instead of ANSI, so a pre-upgrade binding created from a mojibake non-ASCII Git path requires rebinding once).
  • Host diagnostics (--diagnose in Claude Code / Codex / WorkBuddy, and doctor in DSH, Kimi Code, and ZCode) report matched_key.
  • No breaking changes to Server HTTP/MCP APIs, OpenAPI schemas, or persisted database tables.

How was this change tested?

  • Code quality, manifest, guidance, lifecycle sync, Ruff, and ty checks (verified locally on macOS arm64; macOS fcntl.F_GETPATH APFS case and NFD/NFC parity is verified locally on macOS, while automated CI exercises Linux and windows-latest once out of Draft):
    • make check (All checks passed!, 62 passed)
    • make contract-test (69 passed)
    • make harness-lint (All checks passed!)
  • Python unit, plugin contract, CLI, and real-Server E2E suites:
    • uv run python -m pytest -n auto tests/test_git_worktree.py tests/test_cli_scope.py tests/test_session_import.py tests/claude_code_plugin tests/codex_plugin tests/workbuddy_plugin tests/integrations tests/test_integration_manifest.py tests/test_cli_zcode.py tests/test_cli_workbuddy.py tests/e2e/test_shared_workspace_scope_binding.py tests/e2e/test_codex_service_chain.py tests/e2e/test_zcode_service_chain.py tests/e2e/test_bub_service_chain.py -q (1197 passed, 11 skipped)
  • JavaScript and TypeScript host unit, E2E, typecheck, and bundle suites:
    • pnpm --dir integrations/dsh/plugins/powercontext test (31 files, 1209 passed) and node --test integrations/dsh/plugins/dsh-pet/tests/adapter.test.mjs integrations/dsh/plugins/dsh-pet/tests/package.test.mjs (5 passed)
    • pnpm --dir integrations/opencode/plugins/powercontext test && pnpm --dir integrations/opencode/plugins/powercontext run typecheck (11 files, 175 passed)
    • pnpm --dir integrations/pi/plugins/powercontext test && pnpm --dir integrations/pi/plugins/powercontext run typecheck (18 files, 232 passed)
    • node --test integrations/zcode/plugins/powercontext/tests/*.test.mjs (116 passed, 1 skipped, 0 failed)
    • node --test --test-name-pattern="workspace|scope|doctor|worktree|binding|unbind" integrations/kimi-code/plugins/powercontext/tests/plugin.test.mjs (8 passed, 0 failed)

AI usage statement

Built, reviewed, and verified with assistance from Antigravity (Gemini) and Claude Code.

中文说明

本 PR 关联或关闭哪个 Issue / RFC?

Closes #2879。
实现 RFC 2988-shared-workspace-scope-bindings。

变更背景与原因

当前各工作区感知宿主集成在绑定与解析工作区 Scope 时均各自使用独立的 integration 名称(claude-code、codex、opencode、pi、dsh、workbuddy、zcode、kimi-code、hermes、bub),且工作区路径派生分成三套互不兼容的规则(Git 根目录 + realpath、cwd + realpath、cwd + path.resolve)。用户在任一宿主中将仓库检出绑定到项目 Scope 后,同一台机器上的其他宿主打开同一目录仍会回退到 Server 默认 Scope(手工维护成本为 O(仓库数 × 宿主数))。

遵循 RFC 1345(scope_id 由 Server 拥有且保持不透明,绝不从路径或 Git 远端地址自动派生),本 PR 在零 Server Schema、零 HTTP API、零持久化表结构改动的前提下,使用保留集成名 shared 引入跨宿主规范工作区绑定。

本 PR 包含哪些变更?

本 Draft PR 采用分层提交组织(中英文双语 RFC -> Python/TS 共享生命周期与 CLI -> 各宿主集成与跨宿主 E2E -> 跨平台路径归一、路由缓存与 CLI 精简收敛),便于按需先独立审阅 RFC:

  • 中英文双语 RFC(docs/{en,zh}/rfcs/2988-shared-workspace-scope-bindings.md)与能力清单校验(scripts/integration_manifest.py):
    • 定义规范工作区身份规则、家目录与文件系统根目录守卫、解析优先级(单次解析请求最多 5 个键)、绑定与清除语义以及跨平台与迁移边界说明。
    • 在 scripts/integration_manifest.py 中保留 shared,防止宿主清单占用该名称。
  • 跨语言工作区身份与 Git Worktree 生命周期(src/powercontext_integration_lifecycle/、integrations/lifecycle/git-worktree.ts):
    • 复用单次 git rev-parse 调用对已存在目录计算 sha256(utf8(canonical_root)):在 macOS 上通过 fcntl.F_GETPATH 使 Python 与 Node.js fs.realpathSync.native 在大小写不敏感 APFS 及 NFD/NFC 路径上逐字节一致,在 Windows 上统一剥离 \\?\ 与 \\?\UNC\ 前缀并大写盘符,Git 标准输出显式按 UTF-8(surrogateescape)解码,目录不存在时直接跳过 git 子进程派生,并按 os.path.expanduser("~") / os.homedir() 一致拦截 $HOME / %USERPROFILE% 及文件系统根目录(_guarded_git_top / guardedGitTop)。
    • 将 HostProfile.legacy_workspace_binding 默认值设为 False,使后续新接入宿主仅发送 shared:workspace;仅对 CLAUDE_CODE 与 CODEX 显式设为 True,并在存量工作区宿主中逐字节冻结原有的 <host>:workspace 派生逻辑。
    • 新增 diagnose_scope_binding 输出 matched_key,并通过 scripts/generate_integration_lifecycle.py 同步生成副本。
  • 全量 10 个存量工作区宿主、CLI 与会话导入器:
    • 统一更新 claude-code、codex、workbuddy、hermes、bub、dsh(按 cwd 缓存共享路由元数据并重编 integrations/dsh/plugins/powercontext/lib/)、opencode(含重编 lib/)、pi、kimi-code(多键解绑部分失败时保留 unknown 状态)与 zcode(同上保留部分解绑 unknown 状态):绑定只写 shared:workspace,解析按 session -> shared(当前检出)-> legacy host(当前检出)-> shared(主检出)-> legacy host(主检出)-> default 顺序查询,清除时一并移除 shared 与当前宿主旧键,且诊断入口(--diagnose、doctor.ts、doctor.mjs)统一展示 matched_key。
    • 更新 powercontext scope resolve(支持 --integration shared 及全部 10 个工作区宿主),为 powercontext scope binding set(校验目录存在并拒绝非 shared 的 --integration)与 clear(校验目录存在,默认清除 shared,指定 --integration <host> 时同时清除 shared 与 <host>)新增 --cwd 选项,并同步更新 powercontext import-sessions(session_import.py)。
  • 中英文文档与跨宿主端到端测试(docs/{en,zh}/docs/integrations/、tests/):
    • 同步更新全部 10 个工作区宿主的中英文用户文档。
    • 在 tests/test_git_worktree.py 新增 Python × Node.js 一致性测试(覆盖 APFS 大小写偏差、NFC/NFD、软链、Windows 目录联接 junction、$HOME/%USERPROFILE% 守卫与 Windows 路径向量),在 tests/test_cli_scope.py 新增 --cwd / --help 测试,并在 tests/e2e/test_shared_workspace_scope_binding.py 新增覆盖全部 10 个宿主的真实 Server + SQLite 端到端测试。

是否存在用户可见变更?

  • 在任一受支持宿主集成内执行工作区 Scope 绑定,或运行 powercontext scope binding set <SCOPE_ID> --cwd <DIR>,均会写入规范 shared:workspace 绑定,并在打开同一检出目录的所有工作区宿主(含子目录、软链及未单独覆盖绑定的关联 Git Worktree)中自动共享生效。启动时固定会话 Scope 的宿主(如 Codex 与 OpenCode)在已开启会话中保持原会话 Scope,新开会话采用新的工作区绑定。
  • 升级前已存在的 <host>:workspace 绑定无需手工迁移即可继续回退生效,直至被新的 shared:workspace 绑定覆盖,或通过宿主解绑 / powercontext scope binding clear --cwd <DIR> --integration <HOST> 清除(注:在非 UTF-8 代码页如 cp936 的 Windows 上,Python 的 Git 辅助函数现按 UTF-8 而非系统 ANSI 解码 git rev-parse 输出,此前由非 ASCII 乱码路径建立的旧绑定重新绑定一次即可)。
  • 宿主诊断入口(Claude Code / Codex / WorkBuddy 的 --diagnose,以及 DSH、Kimi Code、ZCode 的 doctor)新增展示 matched_key。
  • 服务端 HTTP/MCP API、OpenAPI Schema 与持久化数据库表结构均无破坏性变更。

测试与验证情况

  • 全仓代码质量、能力清单、指引 Skill、生命周期副本同步、Ruff 与 ty 类型检查(本机 macOS arm64 实测;macOS fcntl.F_GETPATH 的 APFS 大小写与 NFD/NFC 一致性已在 macOS 本机验证,CI 在脱离 Draft 后自动覆盖 Linux 与 windows-latest):
    • make check(All checks passed!,62 passed)
    • make contract-test(69 passed)
    • make harness-lint(All checks passed!)
  • Python 单元测试、插件契约、CLI 与真实 Server 端到端测试:
    • uv run python -m pytest -n auto tests/test_git_worktree.py tests/test_cli_scope.py tests/test_session_import.py tests/claude_code_plugin tests/codex_plugin tests/workbuddy_plugin tests/integrations tests/test_integration_manifest.py tests/test_cli_zcode.py tests/test_cli_workbuddy.py tests/e2e/test_shared_workspace_scope_binding.py tests/e2e/test_codex_service_chain.py tests/e2e/test_zcode_service_chain.py tests/e2e/test_bub_service_chain.py -q(1197 passed, 11 skipped)
  • JavaScript 与 TypeScript 宿主单测、端到端、类型检查与构建产物校验:
    • pnpm --dir integrations/dsh/plugins/powercontext test(31 files, 1209 passed)及 node --test integrations/dsh/plugins/dsh-pet/tests/adapter.test.mjs integrations/dsh/plugins/dsh-pet/tests/package.test.mjs(5 passed)
    • pnpm --dir integrations/opencode/plugins/powercontext test && pnpm --dir integrations/opencode/plugins/powercontext run typecheck(11 files, 175 passed)
    • pnpm --dir integrations/pi/plugins/powercontext test && pnpm --dir integrations/pi/plugins/powercontext run typecheck(18 files, 232 passed)
    • node --test integrations/zcode/plugins/powercontext/tests/*.test.mjs(116 passed, 1 skipped, 0 failed)
    • node --test --test-name-pattern="workspace|scope|doctor|worktree|binding|unbind" integrations/kimi-code/plugins/powercontext/tests/plugin.test.mjs(8 passed, 0 failed)

AI 使用声明

本 PR 在 Antigravity(Gemini)与 Claude Code 辅助下完成实现、审查与验证。

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

Reviewed aef8a44 and its merge with master d896b79. The shared-before-legacy lookup and dual-key clearing design are reasonable; no new database tables or Server API contract. Linux validation: 91 path/CLI/import/cross-host tests and 513 host tests passed; the real HTTP Server cross-host test also passed on the merged result. Node suites had one Kimi preparation failure (plus its parent), which did not reproduce in a focused rerun (77 passed). I have not established native Windows/macOS path parity or installed-host acceptance, and all 45 current CI checks are skipped while this remains a draft. Merge-readiness score: 58/100; holding approval pending that validation. Added CLI/interfaces are not the reason for withholding approval.

@wycocoyu

wycocoyu commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review! Keeping this PR in Draft for now while we run additional local and cross-platform (macOS/Windows) verification on installed hosts. We will mark it Ready for Review once validation is complete.

中文说明

感谢评审!本 PR 目前暂时保持 Draft 状态,我们还会继续在本地及跨平台(macOS/Windows)已安装宿主环境补充实测。待全部验证完成后,再转为 Ready for Review 请大家重新评审。

@hireview001 hireview001 added the module:core Core: PR changes under src/ label Dec 3, 2026
@hireview001

Copy link
Copy Markdown
Collaborator

The affected modules are Core. @hidb4ai, please coordinate follow-up. Core: @hidb4ai @frf12 @Fengzdadi @beatenevo. Please coordinate the review of the affected changes.

@wycocoyu

wycocoyu commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

@hidb4ai @frf12 @Fengzdadi @beatenevo

Additional local multi-host and linked-worktree validation is complete. This PR is now marked Ready for Review at aef8a4437 (cleanly mergeable with current master eb0a35498).

Additional Validation Completed

  1. Cross-host & linked-worktree workspace resolution: Verified powercontext scope binding set <scope_id> --cwd <repo> binds a single shared/workspace/<key> identity that resolves consistently across Antigravity, Codex, and Claude Code hooks from both the main checkout and linked Git worktrees (git worktree add).
  2. Two-way live recall across hosts: Verified live memory capture and recall between an Antigravity session and an interactive Codex CLI (v0.173.0) session running in a linked worktree of the same repository, including automatic session binding.
  3. Live daily soak (~4.5 hours on macOS): Verified workspace isolation in real daily usage — 15 new sessions automatically routed into the bound workspace Scope (60 captured prompts, 19 extracted atomic memories, background processing caught up with clean == dirty), while pre-existing session bindings preserved session precedence and unbound repositories continued falling back to Default.
  4. Validation boundary: Local live-host testing covered macOS (Antigravity, Codex, Claude Code hooks); Windows behavior remains covered by automated tests and CI.

Please review when convenient!

中文说明

@hidb4ai @frf12 @Fengzdadi @beatenevo

本机多宿主与关联 Git worktree 补充验证已完成,现将本 PR 在 aef8a4437 转为 Ready for Review(与当前 master eb0a35498 无合并冲突)。

补充验证结果

  1. 跨宿主与关联 worktree 工作区解析:实测 powercontext scope binding set <scope_id> --cwd <repo> 生成单一 shared/workspace/<key> 绑定,在主仓目录与关联 Git worktree(git worktree add)下,Antigravity、Codex 与 Claude Code Hook 均解析到同一目标 Scope。
  2. 跨宿主双向实时召回:在真实 Antigravity 会话与同仓关联 worktree 中运行的交互式 Codex CLI(v0.173.0)会话间,验证了记忆双向采集、召回及自动会话绑定闭环。
  3. 本机日用实测(macOS 约 4.5 小时):新绑定的工作区 Scope 自动接入 15 个新会话(采集 60 条 Prompt、稳定提取 19 条独立记忆、后台提取 clean == dirty),同时已有会话级绑定保持更高优先级,未绑定仓库继续回落至 Default,无跨仓串台。
  4. 验证边界说明:本机真机实测覆盖 macOS(Antigravity、Codex、Claude Code Hook),Windows 行为继续由自动化单测与 CI 覆盖。

烦请方便时复审!

@frf12 frf12 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed aef8a4437. The four inline comments describe reproduced binding/compatibility failures that need correction. Baseline comparisons used merge base 07f419041; the relevant implementation and fixture files are unchanged in current master eb0a35498.

CI also needs reconciliation: run 47307336643 fails the Python 3.11–3.14 unit jobs, with the 3.11 job reporting 100 failures concentrated in Hook request expectations. I independently ran test_hook_keeps_its_characterized_behavior[claude-code:session-start-without-bootstrap]: it passes on the baseline and fails on this head because the expected request omits the new shared key. Please update and review the affected fixtures for the intended behavior, then complete the skipped host and Windows checks.

Verification boundaries are stated in each finding; these reproductions do not establish installed-host or native Windows acceptance.

Comment thread src/powercontext/client/cli.py Outdated
Comment on lines +418 to +421
if real_workspace_path(str(cwd)) is None:
raise typer.BadParameter("Workspace directory does not exist.", param_hint="--cwd") # noqa: TRY003
shared_root, _host_path = workspace_locations(str(cwd), git_root=True)[0]
shared_id = workspace_identity(shared_root)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[P2] Expand the directory before discovering its Git root

For an existing Git repository ~/pc-review with a src subdirectory, bind an existing Scope with powercontext scope binding set <SCOPE_ID> --cwd '~/pc-review/src', then run powercontext scope resolve --integration codex --cwd "$HOME/pc-review/src" against the same Server. I reproduced a successful bind followed by resolution to the default Scope using the real CLI command and HTTP Server/SQLite; resolving with the literal tilde path instead finds the newly bound Scope.

The existence check expands ~, but workspace_locations receives the unexpanded string, skips Git discovery, and ultimately hashes the subdirectory. Normal absolute-path callers hash the repository root instead. Please normalize supported home-relative input before Git discovery so the accepted binding is readable through the normal host path. Master has no binding set --cwd option; this is a defect in the newly accepted input form, rather than a previously working command.


export function workspaceBindingKey(cwd: string): ScopeBindingKey {
export function sharedWorkspaceBindingKey(cwd: string): ScopeBindingKey | undefined {
if (!sharedKeys.has(cwd)) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[P2] Keep the advertised workspace key consistent with resolution

Start in a non-Git /project/packages/api, resolve the Scope and format its routing metadata, then run git init /project. The next resolution queries the shared key for /project, but this cwd-only cache still advertises the old shared key for packages/api. Saving a binding with that advertised key succeeds, yet subsequent resolution does not query it and continues returning the default Scope.

I reproduced this with real temporary directories/Git and the actual base/head resolver and formatter, using an in-memory binding map for the Server: master reads the advertised binding, while this head misses it. The actual caller refreshes resolution each turn, so the metadata needs to track the keys used by that resolution as well. Please refresh or invalidate the cached key when the effective workspace identity changes. This was a direct integration-code reproduction, not a live DSH session.

Comment on lines +128 to +129
if top is None:
return [(shared_own, host_own)]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[P2] Preserve legacy main-checkout candidates when the shared HOME guard applies

Use a linked worktree as the process's home directory, start in $HOME/sub, and retain only a pre-upgrade host binding for the main checkout. In an isolated real-Git layout, the master helper returns both the worktree and main-checkout paths; this head returns only the worktree path. The result is the same in Python and Node, including the cwd-keyed variants (Worktree/sub, Checkout/sub on master versus only Worktree/sub here).

The HOME guard makes top empty, and this return also drops the legacy fallback, so the existing main-checkout binding is no longer queried and resolution can fall back to Default. Please preserve the previous legacy candidates independently of the guard for shared identities, as the RFC's compatibility contract requires. The equivalent early returns in the TypeScript helper have the same behavior. Verification exercised the real helpers and Git layout, not a live host.

Comment thread integrations/lifecycle/git-worktree.ts Outdated
function realPath(path: string): string {
try {
return realpathSync(path)
return realpathSync.native(path)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[P2] Preserve the pre-RFC path spelling for legacy worktree fallbacks

On a case-insensitive macOS filesystem, create a main checkout named Checkout, add a linked Worktree, and save a legacy Pi/DSH/OpenCode binding for Checkout/sub. Rename the main directory to checkout (a temporary intermediate name can make the case-only rename explicit). Git's existing worktree pointer remains valid and still spells Checkout.

I reproduced this with real macOS directories, Git, and the original base/head helpers, without editing Git's internal files: master returns Checkout/sub as the fallback, but this head returns checkout/sub. Those hosts hash the returned spelling, so the legacy binding that master still finds is no longer queried. The Python helper retains the old spelling. Please keep legacy fallback derivation unchanged while applying OS-canonical paths to the new shared identity. The RFC explicitly promises byte-for-byte legacy compatibility; this reproduction covers path/key derivation, not complete host acceptance.

@wycocoyu

wycocoyu commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

@frf12 Thank you for the thorough review and exact reproductions! All four P2 findings and the hook characterization fixtures are fixed in f72019c33:

Summary of Fixes (f72019c33)

  1. Expand ~ before Git root discovery (src/powercontext/client/cli.py): Expanded cwd with str(cwd.expanduser()) before calling workspace_locations in _resolve_set_cwd_binding_target, _resolve_clear_cwd_binding_target, and _workspace_binding_keys, so --cwd '~/repo/src' discovers the Git root identically to "$HOME/repo/src". Added regression test test_scope_binding_set_resolve_and_clear_expand_tilde_before_git_root_discovery in tests/test_cli_scope.py.
  2. Keep DSH advertised workspace key synchronized with resolution (integrations/dsh/plugins/powercontext/src/scope.ts): Updated workspaceBindingKeys to refresh the bounded sharedKeys cache with the current turn's first-level shared key on every resolution (preserving repeated-format caching within a turn while updating immediately after git init or repo changes), and rebuilt integrations/dsh/plugins/powercontext/lib/index.js. Added regression test in integrations/dsh/plugins/powercontext/tests/scope.spec.ts.
  3. Preserve legacy main-checkout candidates under the shared HOME guard (src/powercontext_integration_lifecycle/git_worktree.py, integrations/lifecycle/git-worktree.ts, integrations/bub/src/powercontext_bub/scope.py): Computed main_root / host_main from raw_top independently of _guarded_git_top / guardedGitTop, returning ("", host_main) / ['', hostMain] when the shared guard blocks Git root climbing so legacy main-checkout bindings stay reachable without emitting a shared key for $HOME, and added an empty-string guard in Bub's _shared_workspace_key. Synced all host copies via scripts/generate_integration_lifecycle.py, rebuilt DSH/OpenCode bundles, and added Python + Node regression test test_home_guard_preserves_legacy_main_checkout_fallback_in_linked_worktree in tests/test_git_worktree.py.
  4. Preserve pre-RFC path spelling for legacy worktree fallbacks (integrations/lifecycle/git-worktree.ts): Restored realPath() to realpathSync(path) (keeping realpathSync.native(input) exclusively inside realWorkspacePath() for the new shared identity), matching master and Python's os.path.realpath on case-insensitive macOS filesystems. Added macOS case-only rename regression test test_legacy_worktree_fallback_preserves_case_spelling_after_case_only_rename in tests/test_git_worktree.py.
  5. Refreshed hook characterization fixtures (tests/fixtures/hook_characterization/{claude-code,codex}.json): Rewrote expectations via uv run python tests/test_hook_characterization.py and reviewed the complete diff (+490 / -0 lines: exactly 98 new {"external_id": "$WORKSPACE_KEY", "integration": "shared", "kind": "workspace"} entries).

Verification

  • uv run python scripts/generate_integration_lifecycle.py --check, uv run ruff check, uv run ruff format --check, uv run ty check → all exit 0
  • uv run python -m pytest -n auto --doctest-modules --ignore=tests/e2e -q → 11209 passed, 446 skipped (including all test_hook_characterization.py, test_session_start_shells.py, test_user_prompt_submit_shells.py, test_cli_scope.py, and test_git_worktree.py cases)
  • Direct powercontext_bub.scope smoke check verified _shared_workspace_key("") is None and workspace_binding_keys under a HOME-guarded linked worktree returns ["shared", "bub", "bub"]
  • pnpm --dir integrations/dsh/plugins/powercontext test, pnpm --dir integrations/opencode/plugins/powercontext test && typecheck, pnpm --dir integrations/pi/plugins/powercontext test && typecheck → 232 passed
  • node --test integrations/zcode/plugins/powercontext/tests/*.test.mjs integrations/kimi-code/plugins/powercontext/tests/*.test.mjs → 228 passed (only 1 macOS-local 127.0.0.2 EADDRNOTAVAIL loopback-alias check unrelated to workspace scope bindings)

Ready for CI re-run and your re-review!

中文说明

@frf12 非常感谢细致评审和精准复现!全部 4 条 P2 缺陷以及 Hook 特征测试快照均已在 f72019c33 修复:

修复摘要(f72019c33)

  1. Git 根目录探测前先展开 ~(src/powercontext/client/cli.py):在 _resolve_set_cwd_binding_target、_resolve_clear_cwd_binding_target 与 _workspace_binding_keys 中先执行 str(cwd.expanduser()) 再传入 workspace_locations,确保 --cwd '~/repo/src' 与 "$HOME/repo/src" 探测到同一 Git 根。在 tests/test_cli_scope.py 补齐回归用例 test_scope_binding_set_resolve_and_clear_expand_tilde_before_git_root_discovery。
  2. 保持 DSH 对外展示的 workspace key 与实际解析一致(integrations/dsh/plugins/powercontext/src/scope.ts):在 workspaceBindingKeys 每次解析后同步刷新有界缓存 sharedKeys 中的当前级 shared key(保留单轮内重复格式化缓存,同时在 git init 等仓库状态变化后立即对齐),并重建 integrations/dsh/plugins/powercontext/lib/index.js。在 integrations/dsh/plugins/powercontext/tests/scope.spec.ts 补齐回归用例。
  3. 在 HOME 守卫生效时保留旧版主仓回退候选(src/powercontext_integration_lifecycle/git_worktree.py、integrations/lifecycle/git-worktree.ts、integrations/bub/src/powercontext_bub/scope.py):基于 raw_top 独立计算 main_root 与 host_main,当共享守卫拦截 Git 根上溯时返回 ("", host_main) / ['', hostMain],保留旧版主仓回退且不为 $HOME 生成 shared key;同时在 Bub 的 _shared_workspace_key 增加空字符串保护。已通过 scripts/generate_integration_lifecycle.py 同步全部宿主副本、重建 DSH/OpenCode 产物,并在 tests/test_git_worktree.py 补齐 Python + Node 双端回归用例 test_home_guard_preserves_legacy_main_checkout_fallback_in_linked_worktree。
  4. 保留旧版 worktree 回退路径的 RFC 前大小写拼写(integrations/lifecycle/git-worktree.ts):将 realPath() 恢复为 realpathSync(path)(仅在新 shared 身份专用的 realWorkspacePath() 中使用 realpathSync.native(input)),在大小写不敏感的 macOS 文件系统上与 master 及 Python os.path.realpath 保持字节级一致。在 tests/test_git_worktree.py 补齐 macOS 仅改大小写重命名回归用例 test_legacy_worktree_fallback_preserves_case_spelling_after_case_only_rename。
  5. 刷新 Hook 特征测试快照(tests/fixtures/hook_characterization/{claude-code,codex}.json):运行 uv run python tests/test_hook_characterization.py 更新预期并逐行核验 diff(+490 / -0 行,全部为 98 处新增的 {"external_id": "$WORKSPACE_KEY", "integration": "shared", "kind": "workspace"} 条目)。

验证结果

  • uv run python scripts/generate_integration_lifecycle.py --check、uv run ruff check、uv run ruff format --check、uv run ty check → 全部退出码 0
  • uv run python -m pytest -n auto --doctest-modules --ignore=tests/e2e -q → 11209 passed, 446 skipped(涵盖全部 test_hook_characterization.py、test_session_start_shells.py、test_user_prompt_submit_shells.py、test_cli_scope.py 与 test_git_worktree.py)
  • 直接校验 powercontext_bub.scope 确认 _shared_workspace_key("") is None,且在 HOME 守卫关联 worktree 下 workspace_binding_keys 返回 ["shared", "bub", "bub"]
  • pnpm --dir integrations/dsh/plugins/powercontext test、pnpm --dir integrations/opencode/plugins/powercontext test && typecheck、pnpm --dir integrations/pi/plugins/powercontext test && typecheck → 232 passed
  • node --test integrations/zcode/plugins/powercontext/tests/*.test.mjs integrations/kimi-code/plugins/powercontext/tests/*.test.mjs → 228 passed(仅 macOS 本机无 127.0.0.2 环回别名 1 项环境差异,与 workspace scope 绑定无关)

CI 将自动重跑,烦请方便时复审!

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

module:core Core: PR changes under src/

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(integrations): use host-independent workspace Scope binding keys across hosts

4 participants