From 84f1d43ea7395b0d5f07b00b2a7dc3ca26323d70 Mon Sep 17 00:00:00 2001 From: wycocoyu <180249289+wycocoyu@users.noreply.github.com> Date: Wed, 2 Dec 2026 08:55:10 -0800 Subject: [PATCH 1/7] docs(rfc): define shared workspace Scope bindings --- .../0000-shared-workspace-scope-bindings.md | 117 ++++++++++++++++++ .../0000-shared-workspace-scope-bindings.md | 117 ++++++++++++++++++ 2 files changed, 234 insertions(+) create mode 100644 docs/en/rfcs/0000-shared-workspace-scope-bindings.md create mode 100644 docs/zh/rfcs/0000-shared-workspace-scope-bindings.md diff --git a/docs/en/rfcs/0000-shared-workspace-scope-bindings.md b/docs/en/rfcs/0000-shared-workspace-scope-bindings.md new file mode 100644 index 0000000000..3f16ce863a --- /dev/null +++ b/docs/en/rfcs/0000-shared-workspace-scope-bindings.md @@ -0,0 +1,117 @@ +--- +title: "RFC 0000: Shared workspace Scope bindings" +description: "One canonical checkout identity and a shared binding namespace so binding a local workspace once applies across every PowerContext host integration while keeping existing per-host bindings compatible." +--- + +- Proposal Name: `shared_workspace_scope_bindings` +- Start Date: 2026-12-02 +- RFC PR: [oceanbase/powercontext#0000](https://github.com/oceanbase/powercontext/pull/0000) +- Tracking Issue: [oceanbase/powercontext#2879](https://github.com/oceanbase/powercontext/issues/2879) + +# Summary + +Host plugins and CLI tools share durable workspace Scope bindings across integrations on the same local checkout without changing the Server, HTTP API, or database schema. Every directory-aware host computes one canonical checkout identity (the real path of the Git top level, or of the working directory outside Git, normalized across platforms and hashed with SHA-256) and stores workspace bindings under the reserved integration name `shared`. Resolution tries the shared workspace key ahead of each host's existing per-integration workspace key at both the current checkout and, in a linked Git worktree, its main checkout. + +# Motivation + +Today, every host integration puts its own `integration` identifier inside `ScopeBindingKey` when reading or writing workspace bindings, and hosts derive the hashed path in three incompatible ways: + +| Host group | Hashed directory | Symbolic links | +| --- | --- | --- | +| Claude Code, Codex, WorkBuddy, ZCode | Git top level, or working directory outside Git | Resolved | +| Kimi Code, Hermes, Bub | Working directory | Resolved | +| DSH, OpenCode, Pi | Working directory | Preserved (`path.resolve`) | + +When a user creates an isolated Scope for a repository and binds it in one host, opening the same checkout in another host misses that binding and silently falls back to the Server's default Scope. Recalled context is lost across hosts, captured prompts land in the default Scope instead of the repository Scope, and keeping `M` repositories isolated across `N` installed hosts requires `M * N` manual bindings. + +# Guide-level explanation + +Binding a local repository checkout to a Scope applies to every PowerContext host on that machine: + +```bash +powercontext scope binding set scp_repo --cwd /path/to/repo +``` + +Binding from any host's workspace helper writes the same shared binding. Opening `/path/to/repo`, a subdirectory `/path/to/repo/packages/api`, a symbolic link to that checkout, or a linked Git worktree of that checkout in Claude Code, Codex, OpenCode, Pi, DSH, Kimi Code, ZCode, WorkBuddy, Hermes, or Bub resolves `scp_repo`. + +Existing deployments need no migration: + +- Before a checkout receives a shared binding, each host continues resolving its existing per-host binding. +- Binding the checkout once writes `("shared", "workspace", )`, which takes precedence over older per-host workspace bindings in every updated host. +- Clearing a workspace binding from a host removes both the shared binding and that host's legacy workspace binding for the checkout so the old per-host binding does not reappear. +- A host that intentionally needs a separate Scope overrides resolution with its explicit Scope setting (for example `POWERCONTEXT_CODEX_SCOPE_ID`) or a session binding. +- Scope diagnostics probe candidate keys with `allow_default=false` and report which key matched (`shared`, the host's own workspace key, or `session`) so operators can tell when another host's legacy binding is still active. + +As required by [RFC 1345](1345_scope_organization_and_agent_integration.md), a workspace key only looks up an existing binding and never derives or creates a `scope_id`. + +# Reference-level explanation + +## 1. Canonical workspace identity + +Given the session directory `dir` reported by the host: + +```text +root = `git rev-parse --show-toplevel` in dir, or dir itself when not in a Git work tree +path = real path of root (absolute, symbolic links resolved; on Windows, strip non-UNC `\\?\` and uppercase `[A-Za-z]:`) +id = lowercase hex SHA-256 of UTF-8(path) +``` + +- Subdirectories of a checkout share the checkout's `root`. Outside Git, each directory is its own workspace. +- On Windows, resolving symbolic links and normalizing extended-length `\\?\C:\...` prefixes and drive-letter casing to uppercase `C:\...` ensures Python and Node.js hash identical bytes for the same directory. +- When `root` contains a trailing segment that does not exist yet, both runtimes resolve symbolic links on the deepest existing ancestor and join the remaining relative segments before hashing. +- The shared lifecycle helpers (`src/powercontext_integration_lifecycle/git_worktree.py` and `integrations/lifecycle/git-worktree.ts`) compute both the shared checkout roots and the host's legacy paths from the single Git invocation introduced in [PR #2875](https://github.com/oceanbase/powercontext/pull/2875), starting no extra Git subprocesses. + +## 2. Reserved `shared` namespace + +Shared workspace bindings use: + +```json +{"integration": "shared", "kind": "workspace", "external_id": ""} +``` + +`ScopeBindingKey.integration` is already an unconstrained non-empty string (`1..128` characters) on the Server. `shared` is reserved and rejected as a host integration identifier in the host registry and capability manifest checks. + +## 3. Resolution order + +`POST /v1/scope-bindings/resolve` evaluates `explicit_scope_id`, then `binding_keys` in order, then the Server default Scope: + +1. Explicit Scope configuration (`explicit_scope_id`). +2. Session binding: `(host, "session", session_id)` when the host supplies a session ID. +3. Current checkout shared binding: `("shared", "workspace", shared_id_own)`. +4. Current checkout host binding: `(host, "workspace", legacy_id_own)` (omitted by newly introduced hosts that have no legacy bindings). +5. Linked worktree main checkout shared binding: `("shared", "workspace", shared_id_main)`. +6. Linked worktree main checkout host binding: `(host, "workspace", legacy_id_main)`. +7. Server default Scope (`allow_default=true`). + +Nearer locations win over main-checkout fallbacks (preserving #2875), and `shared` wins over legacy per-host keys at the same location so one new bind unifies every host immediately. Because Server resolution is unchanged, a matched binding whose target Scope was deleted still stops resolution with `409 scope_binding_target_missing`. + +## 4. Bind, clear, CLI, and diagnostics + +- **Bind**: Host workspace helpers and `powercontext scope binding set --cwd ` write `("shared", "workspace", shared_id_own)`. In a linked worktree, this binds the worktree itself. +- **Clear**: Host workspace helpers remove `("shared", "workspace", shared_id_own)` and `(host, "workspace", legacy_id_own)`, reporting `cleared=true` when either existed. `powercontext scope binding clear --cwd ` clears the shared key by default, or both the shared key and ``'s legacy key when `--integration ` is supplied. +- **CLI resolution**: `powercontext scope resolve` supports `--integration shared` as well as all workspace-capable host names (`claude-code`, `codex`, `dsh`, `hermes`, `kimi-code`, `opencode`, `pi`, `workbuddy`, `zcode`, `bub`), emitting the exact key sequence that host sends. +- **Diagnostics**: Host doctor and Scope diagnostic scripts (never per-turn hooks) probe `binding_keys` one at a time with `allow_default=false` to report the winning key's `integration` and `kind`. + +# Drawbacks + +- A single `POST /v1/scope-bindings/resolve` payload carries up to five `binding_keys` (one session key plus up to four workspace keys in a linked worktree) instead of up to three, adding at most two primary-key lookups on a cache-free miss. +- Another host's legacy binding remains stored until overwritten or explicitly cleared for that host, though it is shadowed whenever a shared binding exists. + +# Rationale and alternatives + +- **Git remote URL as workspace identity**: Rejected. Directories outside Git or without remotes have none, repositories can configure multiple remotes or URL spellings, and two local clones intentionally bound to separate Scopes would collide. +- **Fanning out writes across installed hosts**: Rejected. Host path derivations still disagree across subdirectories and symbolic links, and any host installed later would miss earlier bindings. +- **Server-side wildcard over `integration`**: Rejected. Ignoring `integration` on the Server alters the contract of existing stored keys, creates ambiguity when two hosts previously bound different Scopes, and still fails when hosts hash different paths. + +# Prior art + +- [RFC 1345](1345_scope_organization_and_agent_integration.md) defines Server-owned opaque `scope_id` values and lookup-only external `ScopeBindingKey` records. +- [PR #2875](https://github.com/oceanbase/powercontext/pull/2875) established ordered `binding_keys` fallback from a linked Git worktree to its main checkout across Python and TypeScript lifecycle helpers without Server changes. + +# Unresolved questions + +None. + +# Future possibilities + +If an operator needs a persistent per-host Scope override for a single checkout without setting a process-wide `POWERCONTEXT__SCOPE_ID` environment variable, a dedicated key `kind` (for example `workspace_override`) placed ahead of `("shared", "workspace", ...)` can be added without migrating stored bindings. diff --git a/docs/zh/rfcs/0000-shared-workspace-scope-bindings.md b/docs/zh/rfcs/0000-shared-workspace-scope-bindings.md new file mode 100644 index 0000000000..393dcda2fb --- /dev/null +++ b/docs/zh/rfcs/0000-shared-workspace-scope-bindings.md @@ -0,0 +1,117 @@ +--- +title: "RFC 0000:跨宿主共享工作区 Scope 绑定" +description: "定义统一的本地工作区身份规则与共享绑定命名空间,使同一本地检出目录只需绑定一次即可在所有 PowerContext 宿主集成间生效,同时兼容既有按宿主隔离的旧绑定。" +--- + +- Proposal Name: `shared_workspace_scope_bindings` +- Start Date: 2026-12-02 +- RFC PR: [oceanbase/powercontext#0000](https://github.com/oceanbase/powercontext/pull/0000) +- Tracking Issue: [oceanbase/powercontext#2879](https://github.com/oceanbase/powercontext/issues/2879) + +# Summary + +在不改动 Server、HTTP API 和数据库表结构的前提下,使各宿主插件与 CLI 工具在同一本地检出目录上共享持久工作区 Scope 绑定。所有支持目录绑定的宿主统一计算同一规范化检出身份(取 Git 顶层目录或非 Git 工作树下的当前目录,解析真实物理路径并跨平台规范化后计算 SHA-256),并将工作区绑定写入保留集成名 `shared`。解析时在当前检出目录及链接 Git 工作树(linked worktree)的主检出目录两个层级上,均优先尝试共享工作区键,再回退宿主既有的私有工作区键。 + +# Motivation + +当前各宿主集成在读写工作区绑定时均将自身的 `integration` 名称写入 `ScopeBindingKey`,且不同宿主采用了三套互不兼容的路径哈希计算方式: + +| 宿主分组 | 参与哈希的目录 | 符号链接处理 | +| --- | --- | --- | +| Claude Code、Codex、WorkBuddy、ZCode | Git 顶层目录,非 Git 下为当前目录 | 解析为真实路径 | +| Kimi Code、Hermes、Bub | 当前工作目录 | 解析为真实路径 | +| DSH、OpenCode、Pi | 当前工作目录 | 保留原路径(`path.resolve`) | + +当用户为某个代码仓创建独立 Scope 并在一个宿主中完成绑定后,换用另一个宿主打开同一检出目录会无法命中该绑定,进而静默回退到 Server 的默认 Scope。这不仅导致跨宿主切换时丢失已积累的项目记忆、将新采集的对话错误写入默认 Scope,还迫使用户为 `M` 个仓库和 `N` 个宿主重复执行 `M * N` 次手工绑定。 + +# Guide-level explanation + +将本地仓库检出目录绑定到指定 Scope 后,本机所有 PowerContext 宿主集成立即共享该绑定: + +```bash +powercontext scope binding set scp_repo --cwd /path/to/repo +``` + +通过任意宿主自带的工作区绑定脚本执行绑定同样会写入该共享绑定。随后无论在 Claude Code、Codex、OpenCode、Pi、DSH、Kimi Code、ZCode、WorkBuddy、Hermes 还是 Bub 中打开 `/path/to/repo`、子目录 `/path/to/repo/packages/api`、指向该目录的符号链接或该仓库的链接 Git 工作树,均会统一解析到 `scp_repo`。 + +存量环境无需执行数据迁移: + +- 在某个检出目录写入共享绑定之前,各宿主继续命中各自原有的宿主工作区绑定。 +- 在该检出目录重新绑定一次即会写入 `("shared", "workspace", )`,所有已升级宿主均会优先命中该共享绑定并覆盖旧的宿主级绑定。 +- 在宿主中清除工作区绑定会同时删除该检出目录的共享绑定与当前宿主的旧工作区绑定,避免清除后旧绑定重新生效。 +- 若某个宿主确实需要使用独立 Scope,可通过显式 Scope 配置(例如 `POWERCONTEXT_CODEX_SCOPE_ID`)或会话级绑定覆盖。 +- 各宿主 Scope 诊断工具以 `allow_default=false` 逐键探测候选绑定键,并报告实际命中的键来源(`shared`、宿主自有工作区键或 `session`),便于排查其他宿主遗留绑定仍在生效的情况。 + +遵循 [RFC 1345](1345_scope_organization_and_agent_integration.md) 约束,工作区键仅用于查找既有绑定,绝不直接派生或自动创建 `scope_id`。 + +# Reference-level explanation + +## 1. 规范化工作区身份 + +给定宿主为当前会话上报的目录 `dir`: + +```text +root = 在 dir 中执行 `git rev-parse --show-toplevel` 的结果,不在 Git 工作树内时取 dir 自身 +path = root 的真实物理路径(绝对路径且解析符号链接;Windows 下剥离非 UNC 的 `\\?\` 前缀并将盘符 `[A-Za-z]:` 统一为大写) +id = UTF-8(path) 的小写十六进制 SHA-256 +``` + +- 同一检出目录内的所有子目录共享同一个 `root`。在 Git 工作树之外,每个目录各自构成独立工作区。 +- 在 Windows 下,解析符号链接并将扩展路径前缀 `\\?\C:\...` 与盘符大小写统一规范化为大写 `C:\...`,保证 Python 与 Node.js 对同一目录产出完全一致的字节序列与哈希。 +- 当 `root` 末尾包含尚未创建的子路径时,两种运行时均先解析最深已存在祖先目录的符号链接,再拼接剩余相对路径段进行哈希。 +- 共享生命周期辅助模块(`src/powercontext_integration_lifecycle/git_worktree.py` 与 `integrations/lifecycle/git-worktree.ts`)复用 [PR #2875](https://github.com/oceanbase/powercontext/pull/2875) 的单次 Git 调用同时派生共享检出根路径与宿主旧兼容路径,不额外启动 Git 子进程。 + +## 2. 保留命名空间 `shared` + +共享工作区绑定使用以下键结构: + +```json +{"integration": "shared", "kind": "workspace", "external_id": ""} +``` + +Server 端 `ScopeBindingKey.integration` 本身为非空自由字符串(`1..128` 字符)。宿主注册表与能力清单校验将 `shared` 列为保留名,禁止任何宿主集成使用该名称。 + +## 3. 解析顺序 + +`POST /v1/scope-bindings/resolve` 依次评估 `explicit_scope_id`、有序 `binding_keys` 与 Server 默认 Scope: + +1. 显式 Scope 配置(`explicit_scope_id`)。 +2. 会话绑定:当宿主提供会话 ID 时发送 `(host, "session", session_id)`。 +3. 当前检出目录共享绑定:`("shared", "workspace", shared_id_own)`。 +4. 当前检出目录宿主绑定:`(host, "workspace", legacy_id_own)`(无历史兼容包袱的新增宿主可省略此项)。 +5. 链接工作树所属主检出目录共享绑定:`("shared", "workspace", shared_id_main)`。 +6. 链接工作树所属主检出目录宿主绑定:`(host, "workspace", legacy_id_main)`。 +7. Server 默认 Scope(`allow_default=true`)。 + +更近的位置优先于主检出目录回退(保持 #2875 语义),同一位置下 `shared` 优先于宿主旧私有键,从而保证重新绑定一次即可统一所有宿主。由于 Server 解析逻辑保持不变,若命中的绑定所指向的目标 Scope 已被删除,解析仍按契约停止并返回 `409 scope_binding_target_missing`。 + +## 4. 绑定、清除、CLI 与诊断 + +- **绑定(Bind)**:各宿主工作区脚本与 `powercontext scope binding set --cwd ` 统一写入 `("shared", "workspace", shared_id_own)`。在链接工作树中执行时绑定该工作树自身。 +- **清除(Clear)**:各宿主工作区脚本同时清除 `("shared", "workspace", shared_id_own)` 与 `(host, "workspace", legacy_id_own)`,任一存在即返回 `cleared=true`。`powercontext scope binding clear --cwd ` 默认清除共享键;当显式传入 `--integration ` 时一并清除共享键与 `` 的旧工作区键。 +- **CLI 解析**:`powercontext scope resolve` 支持 `--integration shared` 及全部支持工作区绑定的宿主名(`claude-code`、`codex`、`dsh`、`hermes`、`kimi-code`、`opencode`、`pi`、`workbuddy`、`zcode`、`bub`),输出与对应宿主完全一致的键序列。 +- **诊断(Diagnostics)**:宿主 doctor 与 Scope 诊断脚本(仅限诊断命令,不在每轮对话 Hook 中执行)通过 `allow_default=false` 逐键探测 `binding_keys`,直接报告实际命中键的 `integration` 与 `kind`。 + +# Drawbacks + +- 单次 `POST /v1/scope-bindings/resolve` 请求最多携带 5 个 `binding_keys`(1 个会话键加链接工作树下最多 4 个工作区键),较此前最多 3 个键在全部未命中时至多增加 2 次主键查询。 +- 其他宿主的旧私有绑定在未被该宿主清除前仍保留在存储中,但在存在共享绑定时会被自然遮蔽。 + +# Rationale and alternatives + +- **使用 Git 远端 URL 作为工作区身份**:不采用。非 Git 目录或无远端仓库没有 URL,同一仓库可能存在多个远端或不同 URL 写法,且同一机器上刻意绑定到不同 Scope 的两个本地克隆目录会发生冲突。 +- **绑定时向本机所有已安装宿主逐一扇出写入**:不采用。不同宿主的子目录与符号链接派生结果依然不一致,且后续新安装的宿主仍会漏掉此前建立的绑定。 +- **由 Server 在查询工作区键时忽略 `integration` 字段**:不采用。这会改变存量数据的键契约,在不同宿主曾绑定不同 Scope 时产生歧义,且无法解决各宿主路径哈希不一致的问题。 + +# Prior art + +- [RFC 1345](1345_scope_organization_and_agent_integration.md) 定义了 Server 拥有的不透明 `scope_id` 以及仅用于查找绑定的外部 `ScopeBindingKey`。 +- [PR #2875](https://github.com/oceanbase/powercontext/pull/2875) 在不改动 Server 的前提下,通过 Python 与 TypeScript 共享生命周期辅助模块实现了链接 Git 工作树向主检出目录的有序 `binding_keys` 回退。 + +# Unresolved questions + +无。 + +# Future possibilities + +若未来运维场景需要在不设置进程级环境变量 `POWERCONTEXT__SCOPE_ID` 的前提下,仅针对单个检出目录为特定宿主指定独立覆盖绑定,可在 `("shared", "workspace", ...)` 之前引入新的键类型(例如 `kind = "workspace_override"`),无需迁移任何存量绑定。 From c5fbc45793113d25e89cb8c470377ffcfa2a64c8 Mon Sep 17 00:00:00 2001 From: wycocoyu <180249289+wycocoyu@users.noreply.github.com> Date: Wed, 2 Dec 2026 08:55:10 -0800 Subject: [PATCH 2/7] feat(integrations): share workspace Scope bindings across Python hosts and CLI --- docs/en/docs/integrations/claude-code.md | 10 +- docs/en/docs/integrations/codex.md | 11 +- docs/en/docs/integrations/hermes.md | 12 +- docs/en/docs/integrations/workbuddy.md | 8 +- docs/zh/docs/integrations/claude-code.md | 2 +- docs/zh/docs/integrations/codex.md | 2 +- docs/zh/docs/integrations/hermes.md | 7 +- docs/zh/docs/integrations/workbuddy.md | 2 +- e2e/bub/tests/test_bub_scope_binding.py | 35 ++-- integrations/bub/README.md | 8 +- .../bub/src/powercontext_bub/_git_worktree.py | 88 ++++++++-- .../bub/src/powercontext_bub/scope.py | 38 +++- .../powercontext_lifecycle/git_worktree.py | 88 ++++++++-- .../powercontext_lifecycle/host_profile.py | 1 + .../powercontext_lifecycle/scope_binding.py | 90 ++++++++-- .../powercontext/scripts/workspace_scope.py | 25 ++- .../powercontext_lifecycle/git_worktree.py | 88 ++++++++-- .../powercontext_lifecycle/host_profile.py | 1 + .../powercontext_lifecycle/scope_binding.py | 90 ++++++++-- .../powercontext/scripts/scope_binding.py | 21 ++- .../plugins/powercontext/git_worktree.py | 88 ++++++++-- .../hermes/plugins/powercontext/provider.py | 36 ++-- .../powercontext/hooks/git_worktree.py | 88 ++++++++-- .../powercontext/scripts/workspace_scope.py | 95 ++++++++-- scripts/integration_manifest.py | 7 + src/powercontext/client/cli.py | 163 ++++++++++++++---- src/powercontext/client/session_import.py | 32 +++- .../git_worktree.py | 88 ++++++++-- .../host_profile.py | 1 + .../scope_binding.py | 90 ++++++++-- tests/claude_code_plugin/test_contract.py | 43 ++++- tests/codex_plugin/test_contract.py | 10 +- tests/codex_plugin/test_scope_binding.py | 72 ++++++-- tests/e2e/test_bub_service_chain.py | 3 +- tests/git_worktree_support.py | 22 +++ tests/integrations/test_hermes_provider.py | 18 +- tests/test_cli_scope.py | 91 ++++++++-- tests/test_session_import.py | 20 ++- tests/workbuddy_plugin/test_scope_binding.py | 29 +++- 39 files changed, 1306 insertions(+), 317 deletions(-) diff --git a/docs/en/docs/integrations/claude-code.md b/docs/en/docs/integrations/claude-code.md index 93b4aa8763..08b75a3171 100644 --- a/docs/en/docs/integrations/claude-code.md +++ b/docs/en/docs/integrations/claude-code.md @@ -150,10 +150,12 @@ python3 "${CLAUDE_PLUGIN_ROOT}/scripts/workspace_scope.py" \ The resolver hashes the workspace path only as an external binding key. It never generates a Scope ID from a Git remote or directory. Set an explicit Scope only when that separation or sharing is deliberate. -The workspace is the Git root, so the binding covers the checkout's subdirectories. A linked Git worktree that has no -workspace binding of its own uses its main checkout's binding, so a session started in such a worktree shares the -checkout's Scope. Bind inside the worktree to give it a separate Scope. Binding and clearing there change only the -worktree's own binding. +The workspace is the Git root, so the binding covers the checkout's subdirectories and uses the cross-host `shared` +workspace key (ahead of any legacy `claude-code` workspace key). Binding a checkout once therefore applies across every +PowerContext host on the machine, and clearing removes both the shared binding and Claude Code's legacy workspace +binding. A linked Git worktree that has no workspace binding of its own uses its main checkout's binding, so a session +started in such a worktree shares the checkout's Scope. Bind inside the worktree to give it a separate Scope. Binding +and clearing there change only the worktree's own binding. ## Use explicit Memory and Handoff operations diff --git a/docs/en/docs/integrations/codex.md b/docs/en/docs/integrations/codex.md index 3a841703a3..2768524960 100644 --- a/docs/en/docs/integrations/codex.md +++ b/docs/en/docs/integrations/codex.md @@ -163,10 +163,13 @@ uv run --frozen --quiet --project "$PLUGIN_ROOT" python "$PLUGIN_ROOT/scripts/sc `$PLUGIN_ROOT` is the installed Codex plugin root, the same value the hooks use. In an ordinary terminal, replace it with that directory, such as `powercontext/powercontext/` in the plugin cache or -`integrations/codex/plugins/powercontext` in this repository. The command stores a binding with -`integration=codex` and `kind=workspace`. Its external id is the SHA-256 of the Git root path. It does not create a -Scope, and it does not derive a `scope_id` from the path, remote, or branch. Run the script again without -`--bind-scope` to print the Scope resolved for that directory. `--clear-scope` removes only that workspace binding. +`integrations/codex/plugins/powercontext` in this repository. The command stores a cross-host workspace binding with +`integration=shared` and `kind=workspace` (resolved ahead of any legacy `integration=codex` binding), so binding a +checkout once applies across every PowerContext host on the machine. Its external id is the SHA-256 of the real Git +root path. It does not create a Scope, and it does not derive a `scope_id` from the path, remote, or branch. Run the +script again without `--bind-scope` to print the Scope resolved for that directory, or pass `--diagnose` to inspect +which binding key matched. `--clear-scope` removes both the shared workspace binding and Codex's legacy workspace +binding for that checkout. `POWERCONTEXT_CODEX_SCOPE_ID` still takes precedence. A Session that already started keeps the Session binding written at startup. A new Session in that Git root uses the workspace binding when no explicit variable and no earlier Session diff --git a/docs/en/docs/integrations/hermes.md b/docs/en/docs/integrations/hermes.md index 653be18b23..824ed4a0e5 100644 --- a/docs/en/docs/integrations/hermes.md +++ b/docs/en/docs/integrations/hermes.md @@ -62,11 +62,13 @@ commands. Hermes 0.20.4 does not provide enough invocation context to route gate companion rejects gateway invocations; use the provider's Hermes tools in gateway sessions. The provider uses `http://127.0.0.1:8000` by default. The Server resolves an explicit Scope first, then durable session -and workspace bindings, and finally its default Scope. Hermes hashes the workspace path only as an external binding -key; it does not generate Scope IDs from profiles, users, repositories, or directories. In a linked Git worktree that -has no workspace binding of its own, resolution uses the binding of the same directory in the main checkout, so a -checkout's binding also covers its linked worktrees. A binding made in the worktree takes precedence, and binding or -clearing there changes only the worktree's own binding. +bindings, the checkout's cross-host `shared` workspace binding (real Git root path) ahead of Hermes's legacy directory +binding, and finally its default Scope. Hermes hashes the workspace path only as an external binding key; it does not +generate Scope IDs from profiles, users, repositories, or directories. Binding a checkout writes the `shared` workspace +key so every PowerContext host shares the Scope, while clearing removes both the shared binding and Hermes's legacy +binding. In a linked Git worktree that has no workspace binding of its own, resolution uses the main checkout's +binding; a binding made in the worktree takes precedence, and binding or clearing there changes only the worktree's own +binding. ## Configure the connection diff --git a/docs/en/docs/integrations/workbuddy.md b/docs/en/docs/integrations/workbuddy.md index 7884e4e2fc..3cc930a897 100644 --- a/docs/en/docs/integrations/workbuddy.md +++ b/docs/en/docs/integrations/workbuddy.md @@ -252,9 +252,11 @@ Later WorkBuddy sessions in the same workspace reuse that Scope. The `powerconte operation persists the workspace binding in PowerContext. The workspace path is hashed only as an external binding key; the plugin never derives a Scope ID from it. -The workspace is the Git root. A linked Git worktree that has no workspace binding of its own uses its main checkout's -binding, so a checkout's binding also covers its linked worktrees. Bind inside the worktree to give it a separate -Scope; binding and clearing there change only the worktree's own binding. +The workspace is the Git root and writes the cross-host `shared` workspace key (resolved ahead of any legacy `workbuddy` +workspace key), so binding a checkout once applies across every PowerContext host on the machine and clearing removes +both the shared binding and WorkBuddy's legacy binding. A linked Git worktree that has no workspace binding of its own +uses its main checkout's binding, so a checkout's binding also covers its linked worktrees. Bind inside the worktree to +give it a separate Scope; binding and clearing there change only the worktree's own binding. ## Connect to an authenticated local Server diff --git a/docs/zh/docs/integrations/claude-code.md b/docs/zh/docs/integrations/claude-code.md index 1398080274..5fc0cd6304 100644 --- a/docs/zh/docs/integrations/claude-code.md +++ b/docs/zh/docs/integrations/claude-code.md @@ -137,7 +137,7 @@ python3 "${CLAUDE_PLUGIN_ROOT}/scripts/workspace_scope.py" \ resolver 只把 workspace 路径哈希用作外部 binding key,不会根据 Git remote 或目录生成 Scope ID。只有确实需要 主动隔离或共享时,才设置显式 Scope。 -workspace 指 Git 根目录,因此这条绑定也覆盖 checkout 的子目录。没有自己 workspace binding 的 linked Git worktree, +workspace 指 Git 根目录,因此这条绑定覆盖 checkout 的子目录,并写入跨宿主的 `shared` workspace 键(解析时优先于任何旧的 `claude-code` workspace 键)。对同一 checkout 绑定一次即可在本机所有 PowerContext 宿主间生效,执行清除则会一并移除该共享绑定与 Claude Code 的旧 workspace 绑定。没有自己 workspace binding 的 linked Git worktree, 会使用其主 checkout 的绑定,所以在这类 worktree 中启动的会话与 checkout 共用同一个 Scope。 要让 worktree 使用单独的 Scope,在 worktree 内执行绑定;在那里绑定或清除,只会改动该 worktree 自己的绑定。 diff --git a/docs/zh/docs/integrations/codex.md b/docs/zh/docs/integrations/codex.md index b81f2ddc58..a924488416 100644 --- a/docs/zh/docs/integrations/codex.md +++ b/docs/zh/docs/integrations/codex.md @@ -139,7 +139,7 @@ uv run --frozen --quiet --project "$PLUGIN_ROOT" python "$PLUGIN_ROOT/scripts/sc --cwd "$PWD" --bind-scope "SCOPE_ID" ``` -`$PLUGIN_ROOT` 是已安装 Codex 插件的根目录,与 Hook 使用的变量相同。在普通终端里把它换成实际目录,例如插件缓存中的 `powercontext/powercontext/`,或本仓库的 `integrations/codex/plugins/powercontext`。命令写入 `integration=codex`、`kind=workspace` 的绑定,外部身份是 Git 根路径的 SHA-256。它不创建 Scope,也不从路径、远程地址或分支生成 `scope_id`。去掉 `--bind-scope` 再执行一次,可以打印该目录当前解析到的编号。`--clear-scope` 只删除这条 workspace binding,不删除 Scope 里的内容。 +`$PLUGIN_ROOT` 是已安装 Codex 插件的根目录,与 Hook 使用的变量相同。在普通终端里把它换成实际目录,例如插件缓存中的 `powercontext/powercontext/`,或本仓库的 `integrations/codex/plugins/powercontext`。命令写入跨宿主共享的 `integration=shared`、`kind=workspace` 绑定(解析时优先于任何旧的 `integration=codex` 绑定),因此对同一 checkout 绑定一次即可在本机所有 PowerContext 宿主间生效,外部身份是真实 Git 根路径的 SHA-256。它不创建 Scope,也不从路径、远程地址或分支生成 `scope_id`。去掉 `--bind-scope` 再执行一次可以打印该目录当前解析到的编号,传入 `--diagnose` 可查看具体命中的绑定键。`--clear-scope` 会同时删除该 checkout 的共享 workspace 绑定与 Codex 的旧 workspace 绑定,不删除 Scope 里的内容。 `POWERCONTEXT_CODEX_SCOPE_ID` 仍然优先于这条登记。已经开着的会话保持启动时写下的 Session binding;在该 Git 根新开一场会话后,没有显式变量、也没有更早的 Session binding 时,会使用这条 workspace binding。没有自己 workspace binding 的 linked Git worktree 会使用其主 checkout 的绑定,所以 checkout 的绑定也覆盖它的 linked worktree。要让 worktree 使用单独的 Scope,在 worktree 内执行绑定;在那里绑定或清除,只会改动该 worktree 自己的绑定。记录中的 worktree 仍然存在时,`powercontext session import` 也遵循同一规则。MCP 的 `set_scope_binding` 只改当前会话,不能代替这条命令。 diff --git a/docs/zh/docs/integrations/hermes.md b/docs/zh/docs/integrations/hermes.md index cdd13b6ae4..aa6b08cbe0 100644 --- a/docs/zh/docs/integrations/hermes.md +++ b/docs/zh/docs/integrations/hermes.md @@ -59,11 +59,8 @@ Memory、Handoff、Experience、Skill、审核、统计、trace 和 Scope 命令 slash command 提供足够的调用上下文,因此该插件会拒绝 gateway 调用;gateway 会话应使用 provider 提供的 Hermes tools。 -provider 默认连接 `http://127.0.0.1:8000`。Server 依次解析显式 Scope、持久 session binding、持久 workspace -binding 和默认 Scope。Hermes 只把 workspace 路径哈希用作外部 binding key,不会根据 profile、user、repository -或目录生成 Scope ID。在没有自己 workspace binding 的 linked Git worktree 中,解析会使用主 checkout 中同一目录的绑定, -所以 checkout 的绑定也覆盖它的 linked worktree。在 worktree 中建立的绑定优先;在那里绑定或清除, -只会改动该 worktree 自己的绑定。 +provider 默认连接 `http://127.0.0.1:8000`。Server 依次解析显式 Scope、持久 session binding、当前 checkout 的跨宿主 `shared` workspace 绑定(真实 Git 根路径,优先于 Hermes 旧目录绑定)和默认 Scope。Hermes 只把 workspace 路径哈希用作外部 binding key,不会根据 profile、user、repository +或目录生成 Scope ID。执行绑定会写入 `shared` 工作区键使本机所有 PowerContext 宿主共用该 Scope,执行清除则会一并移除共享绑定与 Hermes 的旧绑定。在没有自己 workspace binding 的 linked Git worktree 中,解析会回退使用主 checkout 的绑定;在 worktree 中建立的绑定优先,在那里绑定或清除只会改动该 worktree 自己的绑定。 ## 配置连接 diff --git a/docs/zh/docs/integrations/workbuddy.md b/docs/zh/docs/integrations/workbuddy.md index 026ed2cce1..0c68c18e2d 100644 --- a/docs/zh/docs/integrations/workbuddy.md +++ b/docs/zh/docs/integrations/workbuddy.md @@ -223,7 +223,7 @@ Server 按以下顺序为 WorkBuddy 解析 Scope: 同一工作区后续开启的新 WorkBuddy 会话会复用同一个 Scope。`powercontext-project-context` Skill 的 `--bind-scope` 操作会在 PowerContext 中持久化 workspace binding。插件只把 workspace 路径哈希用作外部 binding key,不会据此生成 Scope ID。 -workspace 指 Git 根目录。没有自己 workspace binding 的 linked Git worktree 会使用其主 checkout 的绑定, +workspace 指 Git 根目录并写入跨宿主的 `shared` workspace 键(解析时优先于任何旧的 `workbuddy` workspace 键),因此对同一 checkout 绑定一次即可在本机所有 PowerContext 宿主间生效,执行清除则会一并移除共享绑定与 WorkBuddy 的旧绑定。没有自己 workspace binding 的 linked Git worktree 会使用其主 checkout 的绑定, 所以 checkout 的绑定也覆盖它的 linked worktree。要让 worktree 使用单独的 Scope,在 worktree 内执行绑定; 在那里绑定或清除,只会改动该 worktree 自己的绑定。 diff --git a/e2e/bub/tests/test_bub_scope_binding.py b/e2e/bub/tests/test_bub_scope_binding.py index 4e2b40a2de..044df58b0b 100644 --- a/e2e/bub/tests/test_bub_scope_binding.py +++ b/e2e/bub/tests/test_bub_scope_binding.py @@ -113,33 +113,38 @@ def test_a_linked_worktree_falls_back_to_the_same_directory_in_its_checkout(monk (worktree / "sub").mkdir() git_calls: list[str] = [] - workspace_paths = scope_module.workspace_paths + workspace_locations = scope_module.workspace_locations - def recording_workspace_paths(cwd: str, **options: Any) -> list[str]: + def recording_workspace_locations(cwd: str, **options: Any) -> list[tuple[str, str | None]]: git_calls.append(cwd) - return workspace_paths(cwd, **options) + return workspace_locations(cwd, **options) - monkeypatch.setattr(scope_module, "workspace_paths", recording_workspace_paths) + monkeypatch.setattr(scope_module, "workspace_locations", recording_workspace_locations) - def external_ids(plugin: PowerContextPlugin) -> list[str]: + def key_pairs(plugin: PowerContextPlugin) -> list[tuple[str, str]]: state = plugin.load_state(message=None, session_id="session-1") - return [key.external_id for key in state[STATE_KEY]["binding_keys"]] - - worktree_ids = [ - hashlib.sha256(str(worktree / "sub").encode()).hexdigest(), - hashlib.sha256(str(checkout / "sub").encode()).hexdigest(), + return [(key.integration, key.external_id) for key in state[STATE_KEY]["binding_keys"]] + + worktree_root_id = hashlib.sha256(str(worktree).encode()).hexdigest() + worktree_sub_id = hashlib.sha256(str(worktree / "sub").encode()).hexdigest() + checkout_root_id = hashlib.sha256(str(checkout).encode()).hexdigest() + checkout_sub_id = hashlib.sha256(str(checkout / "sub").encode()).hexdigest() + expected_worktree = [ + ("shared", worktree_root_id), + ("bub", worktree_sub_id), + ("shared", checkout_root_id), + ("bub", checkout_sub_id), ] - # The worktree's own key is still the hash of its resolved directory, so it wins over the checkout's key. in_worktree = _plugin(monkeypatch, worktree / "sub", scope_id=None) - assert external_ids(in_worktree) == worktree_ids - assert external_ids(in_worktree) == worktree_ids - assert external_ids(_plugin(monkeypatch, checkout / "sub", scope_id=None)) == [worktree_ids[1]] + assert key_pairs(in_worktree) == expected_worktree + assert key_pairs(in_worktree) == expected_worktree + assert key_pairs(_plugin(monkeypatch, checkout / "sub", scope_id=None)) == expected_worktree[2:] # Later turns in the same workspace reuse the keys rather than ask Git again. assert git_calls == [str(worktree / "sub"), str(checkout / "sub")] # With an explicit Scope, the Server ignores the keys, so the plugin asks Git nothing. git_calls.clear() - assert external_ids(_plugin(monkeypatch, worktree / "sub")) == worktree_ids[:1] + assert key_pairs(_plugin(monkeypatch, worktree / "sub")) == [("bub", worktree_sub_id)] assert git_calls == [] diff --git a/integrations/bub/README.md b/integrations/bub/README.md index 86367504dc..de867afeab 100644 --- a/integrations/bub/README.md +++ b/integrations/bub/README.md @@ -53,9 +53,11 @@ constructor values, host environment, common `POWERCONTEXT_CLIENT_SERVER_URL` / Saved consent applies only to its saved Server URL and is not reused when the URL changes. The plugin never derives a Scope ID from the current directory, Git metadata, or a workspace path. It asks the Server -to resolve the configured explicit Scope first, then an opaque stable binding key derived from Bub's workspace identity, -then, in a linked Git worktree, the key of the same directory in the main checkout, and finally the Server default. A -checkout's binding therefore also covers its linked worktrees until a worktree has a binding of its own. Only the real Scope returned by the Server is cached and used for recall, capture, and +to resolve the configured explicit Scope first, then the cross-host `shared` workspace key of the checkout's Git root +ahead of Bub's legacy directory key, then, in a linked Git worktree, the `shared` and legacy keys of the main checkout, +and finally the Server default. Binding a checkout in any host or through `powercontext scope binding set --cwd` +therefore applies to Bub as well, and a checkout's binding covers its linked worktrees until a worktree has a binding of +its own. Only the real Scope returned by the Server is cached and used for recall, capture, and tools. The recall query is the user's text, trimmed, with recognized credentials, such as `api_key=…` assignments, Bearer diff --git a/integrations/bub/src/powercontext_bub/_git_worktree.py b/integrations/bub/src/powercontext_bub/_git_worktree.py index 103c5fbde9..721e66c091 100644 --- a/integrations/bub/src/powercontext_bub/_git_worktree.py +++ b/integrations/bub/src/powercontext_bub/_git_worktree.py @@ -22,11 +22,13 @@ from __future__ import annotations +import hashlib import os import subprocess import time from shutil import which +SHARED_WORKSPACE_INTEGRATION = "shared" # --path-format applies to the options after it, so the top level stays exactly what --show-toplevel alone prints. # It needs Git 2.31 or later. _ARGUMENTS = ("rev-parse", "--show-toplevel", "--path-format=absolute", "--git-dir", "--git-common-dir") @@ -36,6 +38,65 @@ _BARE_ARGUMENTS = ("rev-parse", "--is-bare-repository") +def normalize_windows_real_path(path: str, *, windows: bool = os.name == "nt") -> str: + """Normalize extended-length prefixes and drive-letter casing so Python and Node.js hash identical Windows paths.""" + + if not windows: + return path + resolved = path + if resolved[:8].upper() == "\\\\?\\UNC\\": + resolved = "\\\\" + resolved[8:] + elif ( + len(resolved) >= 6 + and resolved[:4] == "\\\\?\\" + and resolved[4].isascii() + and resolved[4].isalpha() + and resolved[5] == ":" + ): + resolved = resolved[4:] + if len(resolved) >= 2 and resolved[0].isascii() and resolved[0].isalpha() and resolved[1] == ":": + resolved = resolved[0].upper() + resolved[1:] + return resolved + + +def real_workspace_path(path: str) -> str: + """Return the canonical real path of ``path`` with symbolic links resolved and Windows drive prefixes normalized.""" + + return normalize_windows_real_path(os.path.realpath(path)) + + +def workspace_identity(path: str) -> str: + """Return the lowercase hex SHA-256 of the canonical real path of ``path``.""" + + if os.name == "nt": + return hashlib.sha256(real_workspace_path(path).encode("utf-8", errors="surrogatepass")).hexdigest() + return hashlib.sha256(os.fsencode(real_workspace_path(path))).hexdigest() + + +def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[tuple[str, str | None]]: + """Return ``(shared_root, host_path)`` pairs for ``cwd`` and, in a linked worktree, its main checkout. + + ``shared_root`` is always the Git top level when inside a work tree, or ``cwd`` outside Git, so every host derives + the same shared workspace key. ``host_path`` preserves each host's legacy path rule (the Git top level when + ``git_root`` is true, otherwise ``cwd`` and its counterpart subdirectory in the main checkout) from the same Git + invocation, or ``None`` when the main-checkout counterpart is unavailable or links back to ``cwd``. + """ + + deadline = time.monotonic() + timeout + top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + shared_own = top or cwd + host_own = shared_own if git_root else cwd + main_root = _main_worktree_root(top, git_dir, common) + if main_root is None or common is None: + return [(shared_own, host_own)] + # An unknown answer leaves the second path out, as for a bare repository. + bare = _git_output(cwd, ("--git-dir", common, *_BARE_ARGUMENTS), deadline - time.monotonic()) + if bare.strip() != "false": + return [(shared_own, host_own)] + host_main = main_root if git_root else _main_worktree_subdir(cwd, top, main_root) + return [(shared_own, host_own), (main_root, host_main)] + + def workspace_paths(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[str]: """Return the paths whose workspace bindings apply to ``cwd``, the worktree's own first. @@ -53,15 +114,11 @@ def workspace_paths(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[s is the same directory as ``cwd`` is left out. Both Git calls together stay within ``timeout``. """ - deadline = time.monotonic() + timeout - top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) - first = (top or cwd) if git_root else cwd - main = _main_worktree_path(cwd, top, git_dir, common, git_root=git_root) - if main is None or common is None: - return [first] - # An unknown answer leaves the second path out, as for a bare repository. - bare = _git_output(cwd, ("--git-dir", common, *_BARE_ARGUMENTS), deadline - time.monotonic()) - return [first, main] if bare.strip() == "false" else [first] + return [ + host_path + for _shared, host_path in workspace_locations(cwd, git_root=git_root, timeout=timeout) + if host_path is not None + ] def _git_output(cwd: str, arguments: tuple[str, ...], timeout: float) -> str: @@ -94,9 +151,7 @@ def _git_paths(stdout: str) -> tuple[str | None, str | None, str | None]: return head.strip() or None, git_dir or None, common or None -def _main_worktree_path( - cwd: str, top: str | None, git_dir: str | None, common: str | None, *, git_root: bool -) -> str | None: +def _main_worktree_root(top: str | None, git_dir: str | None, common: str | None) -> str | None: if top is None or git_dir is None or common is None or not (os.path.isabs(git_dir) and os.path.isabs(common)): return None common_directory = os.path.realpath(common) @@ -104,10 +159,13 @@ def _main_worktree_path( return None main_root = os.path.dirname(common_directory) worktree_root = os.path.realpath(top) - if main_root == worktree_root: + return None if main_root == worktree_root else main_root + + +def _main_worktree_subdir(cwd: str, top: str | None, main_root: str) -> str | None: + if top is None: return None - if git_root: - return main_root + worktree_root = os.path.realpath(top) try: position = os.path.relpath(os.path.realpath(cwd), worktree_root) except ValueError: diff --git a/integrations/bub/src/powercontext_bub/scope.py b/integrations/bub/src/powercontext_bub/scope.py index 69c846bd44..8b07b2767b 100644 --- a/integrations/bub/src/powercontext_bub/scope.py +++ b/integrations/bub/src/powercontext_bub/scope.py @@ -22,7 +22,7 @@ from powercontext.client import PowerContextClient from powercontext.http import ResolveScopeBindingRequest, ScopeBindingKey -from ._git_worktree import workspace_paths +from ._git_worktree import SHARED_WORKSPACE_INTEGRATION, workspace_identity, workspace_locations def workspace_binding_key(workspace: str | Path | None) -> ScopeBindingKey | None: @@ -30,27 +30,49 @@ def workspace_binding_key(workspace: str | Path | None) -> ScopeBindingKey | Non if workspace is None: return None - return _workspace_key(workspace) + return _legacy_workspace_key(workspace) + + +def shared_workspace_binding_key(workspace: str | Path | None) -> ScopeBindingKey | None: + """Return the cross-host shared binding key for the checkout containing ``workspace``.""" + + if workspace is None: + return None + shared_root, _host_path = workspace_locations(str(Path(workspace).expanduser()), git_root=False)[0] + return _shared_workspace_key(shared_root) def workspace_binding_keys(workspace: str | Path | None) -> list[ScopeBindingKey]: """Return the workspace keys that resolution tries in order. - They are the workspace's own and, in a linked Git worktree, the same directory's in the main checkout, so a binding - made there applies until the worktree has its own. + At both the current checkout and a linked Git worktree's main checkout, the shared checkout key precedes Bub's + legacy directory key. """ if workspace is None: return [] - return [_workspace_key(path) for path in workspace_paths(str(Path(workspace).expanduser()), git_root=False)] + keys: list[ScopeBindingKey] = [] + for shared_root, host_path in workspace_locations(str(Path(workspace).expanduser()), git_root=False): + keys.append(_shared_workspace_key(shared_root)) + if host_path is not None: + keys.append(_legacy_workspace_key(host_path)) + return keys + + +def _shared_workspace_key(workspace: str | Path) -> ScopeBindingKey: + return ScopeBindingKey( + integration=SHARED_WORKSPACE_INTEGRATION, + kind="workspace", + external_id=workspace_identity(str(Path(workspace).expanduser())), + ) -def _workspace_key(workspace: str | Path) -> ScopeBindingKey: - workspace_identity = str(Path(workspace).expanduser().resolve()) +def _legacy_workspace_key(workspace: str | Path) -> ScopeBindingKey: + workspace_identity_str = str(Path(workspace).expanduser().resolve()) return ScopeBindingKey( integration="bub", kind="workspace", - external_id=hashlib.sha256(workspace_identity.encode()).hexdigest(), + external_id=hashlib.sha256(workspace_identity_str.encode()).hexdigest(), ) diff --git a/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/git_worktree.py b/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/git_worktree.py index 103c5fbde9..721e66c091 100644 --- a/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/git_worktree.py +++ b/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/git_worktree.py @@ -22,11 +22,13 @@ from __future__ import annotations +import hashlib import os import subprocess import time from shutil import which +SHARED_WORKSPACE_INTEGRATION = "shared" # --path-format applies to the options after it, so the top level stays exactly what --show-toplevel alone prints. # It needs Git 2.31 or later. _ARGUMENTS = ("rev-parse", "--show-toplevel", "--path-format=absolute", "--git-dir", "--git-common-dir") @@ -36,6 +38,65 @@ _BARE_ARGUMENTS = ("rev-parse", "--is-bare-repository") +def normalize_windows_real_path(path: str, *, windows: bool = os.name == "nt") -> str: + """Normalize extended-length prefixes and drive-letter casing so Python and Node.js hash identical Windows paths.""" + + if not windows: + return path + resolved = path + if resolved[:8].upper() == "\\\\?\\UNC\\": + resolved = "\\\\" + resolved[8:] + elif ( + len(resolved) >= 6 + and resolved[:4] == "\\\\?\\" + and resolved[4].isascii() + and resolved[4].isalpha() + and resolved[5] == ":" + ): + resolved = resolved[4:] + if len(resolved) >= 2 and resolved[0].isascii() and resolved[0].isalpha() and resolved[1] == ":": + resolved = resolved[0].upper() + resolved[1:] + return resolved + + +def real_workspace_path(path: str) -> str: + """Return the canonical real path of ``path`` with symbolic links resolved and Windows drive prefixes normalized.""" + + return normalize_windows_real_path(os.path.realpath(path)) + + +def workspace_identity(path: str) -> str: + """Return the lowercase hex SHA-256 of the canonical real path of ``path``.""" + + if os.name == "nt": + return hashlib.sha256(real_workspace_path(path).encode("utf-8", errors="surrogatepass")).hexdigest() + return hashlib.sha256(os.fsencode(real_workspace_path(path))).hexdigest() + + +def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[tuple[str, str | None]]: + """Return ``(shared_root, host_path)`` pairs for ``cwd`` and, in a linked worktree, its main checkout. + + ``shared_root`` is always the Git top level when inside a work tree, or ``cwd`` outside Git, so every host derives + the same shared workspace key. ``host_path`` preserves each host's legacy path rule (the Git top level when + ``git_root`` is true, otherwise ``cwd`` and its counterpart subdirectory in the main checkout) from the same Git + invocation, or ``None`` when the main-checkout counterpart is unavailable or links back to ``cwd``. + """ + + deadline = time.monotonic() + timeout + top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + shared_own = top or cwd + host_own = shared_own if git_root else cwd + main_root = _main_worktree_root(top, git_dir, common) + if main_root is None or common is None: + return [(shared_own, host_own)] + # An unknown answer leaves the second path out, as for a bare repository. + bare = _git_output(cwd, ("--git-dir", common, *_BARE_ARGUMENTS), deadline - time.monotonic()) + if bare.strip() != "false": + return [(shared_own, host_own)] + host_main = main_root if git_root else _main_worktree_subdir(cwd, top, main_root) + return [(shared_own, host_own), (main_root, host_main)] + + def workspace_paths(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[str]: """Return the paths whose workspace bindings apply to ``cwd``, the worktree's own first. @@ -53,15 +114,11 @@ def workspace_paths(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[s is the same directory as ``cwd`` is left out. Both Git calls together stay within ``timeout``. """ - deadline = time.monotonic() + timeout - top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) - first = (top or cwd) if git_root else cwd - main = _main_worktree_path(cwd, top, git_dir, common, git_root=git_root) - if main is None or common is None: - return [first] - # An unknown answer leaves the second path out, as for a bare repository. - bare = _git_output(cwd, ("--git-dir", common, *_BARE_ARGUMENTS), deadline - time.monotonic()) - return [first, main] if bare.strip() == "false" else [first] + return [ + host_path + for _shared, host_path in workspace_locations(cwd, git_root=git_root, timeout=timeout) + if host_path is not None + ] def _git_output(cwd: str, arguments: tuple[str, ...], timeout: float) -> str: @@ -94,9 +151,7 @@ def _git_paths(stdout: str) -> tuple[str | None, str | None, str | None]: return head.strip() or None, git_dir or None, common or None -def _main_worktree_path( - cwd: str, top: str | None, git_dir: str | None, common: str | None, *, git_root: bool -) -> str | None: +def _main_worktree_root(top: str | None, git_dir: str | None, common: str | None) -> str | None: if top is None or git_dir is None or common is None or not (os.path.isabs(git_dir) and os.path.isabs(common)): return None common_directory = os.path.realpath(common) @@ -104,10 +159,13 @@ def _main_worktree_path( return None main_root = os.path.dirname(common_directory) worktree_root = os.path.realpath(top) - if main_root == worktree_root: + return None if main_root == worktree_root else main_root + + +def _main_worktree_subdir(cwd: str, top: str | None, main_root: str) -> str | None: + if top is None: return None - if git_root: - return main_root + worktree_root = os.path.realpath(top) try: position = os.path.relpath(os.path.realpath(cwd), worktree_root) except ValueError: diff --git a/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/host_profile.py b/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/host_profile.py index 79d036a991..93749182b0 100644 --- a/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/host_profile.py +++ b/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/host_profile.py @@ -41,3 +41,4 @@ class HostProfile: prompt_id_field: str diagnostics: DiagnosticThrottle bootstrap_state: BootstrapState + legacy_workspace_binding: bool = True diff --git a/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/scope_binding.py b/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/scope_binding.py index 2f4226108a..a45a721abd 100644 --- a/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/scope_binding.py +++ b/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/scope_binding.py @@ -20,18 +20,15 @@ from __future__ import annotations import json -import os from collections.abc import Mapping from dataclasses import dataclass, field -from hashlib import sha256 from http.client import HTTPException -from pathlib import Path from time import monotonic from typing import Any, Protocol from urllib.error import HTTPError from urllib.request import Request -from .git_worktree import workspace_paths +from .git_worktree import SHARED_WORKSPACE_INTEGRATION, workspace_identity, workspace_locations from .host_profile import HostProfile from .scope_binding_errors import ( ScopeBindingError, @@ -133,19 +130,69 @@ def clear_scope_binding( settings: ScopeBindingSettings, deadline: float, ) -> bool: - """Remove the durable workspace binding from the Scope service.""" + """Remove the shared workspace binding and, when enabled, this host's legacy workspace binding.""" + + shared_root, host_path = workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline))[0] + keys = [shared_workspace_key(shared_root)] + if host.legacy_workspace_binding and host_path is not None: + keys.append(_workspace_key(host, host_path)) + cleared_any = False + for key in keys: + response = _request_json( + "/v1/scope-bindings/clear", + {"key": key}, + host=host, + settings=settings, + deadline=deadline, + ) + cleared = response.get("cleared") + if not isinstance(cleared, bool): + raise ScopeBindingError + cleared_any = cleared_any or cleared + return cleared_any + +def diagnose_scope_binding( + host: HostProfile, + cwd: str, + *, + session_id: str | None, + settings: ScopeBindingSettings, + deadline: float, +) -> dict[str, Any]: + """Resolve the active Scope and identify which candidate binding key matched (for diagnostics, never hooks).""" + + if settings.scope_id is not None: + scope_id = resolve_scope_id(host, cwd, session_id=session_id, settings=settings, deadline=deadline) + return {"scope_id": scope_id, "source": "explicit", "matched_key": None} + for key in binding_keys(host, cwd, session_id=session_id, deadline=deadline): + try: + response = _request_json( + "/v1/scope-bindings/resolve", + {"explicit_scope_id": None, "binding_keys": [key], "allow_default": False}, + host=host, + settings=settings, + deadline=deadline, + ) + except ScopeBindingStatusError as error: + if error.status == 404 and error.code == "scope_not_found": + continue + raise + scope_id = response.get("scope_id") + if not isinstance(scope_id, str) or not scope_id.strip() or scope_id != scope_id.strip(): + raise ScopeBindingError + return {"scope_id": scope_id, "source": "binding", "matched_key": key} response = _request_json( - "/v1/scope-bindings/clear", - {"key": workspace_binding_key(host, cwd, deadline=deadline)}, + "/v1/scope-bindings/resolve", + {"explicit_scope_id": None, "binding_keys": [], "allow_default": True}, host=host, settings=settings, deadline=deadline, ) - cleared = response.get("cleared") - if not isinstance(cleared, bool): + scope_id = response.get("scope_id") + if not isinstance(scope_id, str) or not scope_id.strip() or scope_id != scope_id.strip(): raise ScopeBindingError - return cleared + return {"scope_id": scope_id, "source": "default", "matched_key": None} def binding_keys( @@ -157,15 +204,17 @@ def binding_keys( ) -> list[dict[str, str]]: """Return the keys that resolution tries in order. - They are the session's, the workspace's, and, in a linked worktree, its main checkout's. + At each checkout level (the current checkout first, then a linked worktree's main checkout), the shared workspace + key precedes this host's legacy workspace key. """ keys: list[dict[str, str]] = [] if session_id is not None: keys.append(session_binding_key(host, session_id)) - keys.extend( - _workspace_key(host, path) for path in workspace_paths(cwd, git_root=True, timeout=_git_timeout(deadline)) - ) + for shared_root, host_path in workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline)): + keys.append(shared_workspace_key(shared_root)) + if host.legacy_workspace_binding and host_path is not None: + keys.append(_workspace_key(host, host_path)) return keys @@ -177,14 +226,19 @@ def session_binding_key(host: HostProfile, session_id: str) -> dict[str, str]: def workspace_binding_key(host: HostProfile, cwd: str, *, deadline: float | None = None) -> dict[str, str]: - """Return the key of the workspace's own Git top level, the only key that binding and clearing write.""" + """Return the shared key of the workspace's own Git top level, the key that binding writes.""" + + del host + shared_root, _host_path = workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline))[0] + return shared_workspace_key(shared_root) + - return _workspace_key(host, workspace_paths(cwd, git_root=True, timeout=_git_timeout(deadline))[0]) +def shared_workspace_key(path: str) -> dict[str, str]: + return {"integration": SHARED_WORKSPACE_INTEGRATION, "kind": "workspace", "external_id": workspace_identity(path)} def _workspace_key(host: HostProfile, path: str) -> dict[str, str]: - external_id = sha256(os.fsencode(Path(path).resolve(strict=False))).hexdigest() - return {"integration": host.integration, "kind": "workspace", "external_id": external_id} + return {"integration": host.integration, "kind": "workspace", "external_id": workspace_identity(path)} def _request_json( diff --git a/integrations/claude-code/plugins/powercontext/scripts/workspace_scope.py b/integrations/claude-code/plugins/powercontext/scripts/workspace_scope.py index 11ad225b39..a78406f23e 100644 --- a/integrations/claude-code/plugins/powercontext/scripts/workspace_scope.py +++ b/integrations/claude-code/plugins/powercontext/scripts/workspace_scope.py @@ -18,6 +18,7 @@ from __future__ import annotations import argparse +import json import os import sys from collections.abc import Sequence @@ -29,15 +30,22 @@ from claude_code_host import CLAUDE_CODE # noqa: E402 from claude_code_settings import ClaudeCodePluginSettings # noqa: E402 -from powercontext_lifecycle.scope_binding import bind_scope, clear_scope_binding, resolve_scope_id # noqa: E402 +from powercontext_lifecycle.scope_binding import ( # noqa: E402 + bind_scope, + clear_scope_binding, + diagnose_scope_binding, + resolve_scope_id, +) def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser() parser.add_argument("--cwd", default=os.getcwd()) + parser.add_argument("--session-id") action = parser.add_mutually_exclusive_group() action.add_argument("--bind-scope", metavar="SCOPE_ID") action.add_argument("--clear-scope", action="store_true") + action.add_argument("--diagnose", action="store_true") arguments = parser.parse_args(argv) loaded = ClaudeCodePluginSettings.from_environment() settings = loaded.scope_binding_settings() @@ -47,7 +55,20 @@ def main(argv: Sequence[str] | None = None) -> int: return 0 if arguments.clear_scope: clear_scope_binding(CLAUDE_CODE, arguments.cwd, settings=settings, deadline=deadline) - print(resolve_scope_id(CLAUDE_CODE, arguments.cwd, session_id=None, settings=settings, deadline=deadline)) + if arguments.diagnose: + print( + json.dumps( + diagnose_scope_binding( + CLAUDE_CODE, arguments.cwd, session_id=arguments.session_id, settings=settings, deadline=deadline + ) + ) + ) + return 0 + print( + resolve_scope_id( + CLAUDE_CODE, arguments.cwd, session_id=arguments.session_id, settings=settings, deadline=deadline + ) + ) return 0 diff --git a/integrations/codex/plugins/powercontext/powercontext_lifecycle/git_worktree.py b/integrations/codex/plugins/powercontext/powercontext_lifecycle/git_worktree.py index 103c5fbde9..721e66c091 100644 --- a/integrations/codex/plugins/powercontext/powercontext_lifecycle/git_worktree.py +++ b/integrations/codex/plugins/powercontext/powercontext_lifecycle/git_worktree.py @@ -22,11 +22,13 @@ from __future__ import annotations +import hashlib import os import subprocess import time from shutil import which +SHARED_WORKSPACE_INTEGRATION = "shared" # --path-format applies to the options after it, so the top level stays exactly what --show-toplevel alone prints. # It needs Git 2.31 or later. _ARGUMENTS = ("rev-parse", "--show-toplevel", "--path-format=absolute", "--git-dir", "--git-common-dir") @@ -36,6 +38,65 @@ _BARE_ARGUMENTS = ("rev-parse", "--is-bare-repository") +def normalize_windows_real_path(path: str, *, windows: bool = os.name == "nt") -> str: + """Normalize extended-length prefixes and drive-letter casing so Python and Node.js hash identical Windows paths.""" + + if not windows: + return path + resolved = path + if resolved[:8].upper() == "\\\\?\\UNC\\": + resolved = "\\\\" + resolved[8:] + elif ( + len(resolved) >= 6 + and resolved[:4] == "\\\\?\\" + and resolved[4].isascii() + and resolved[4].isalpha() + and resolved[5] == ":" + ): + resolved = resolved[4:] + if len(resolved) >= 2 and resolved[0].isascii() and resolved[0].isalpha() and resolved[1] == ":": + resolved = resolved[0].upper() + resolved[1:] + return resolved + + +def real_workspace_path(path: str) -> str: + """Return the canonical real path of ``path`` with symbolic links resolved and Windows drive prefixes normalized.""" + + return normalize_windows_real_path(os.path.realpath(path)) + + +def workspace_identity(path: str) -> str: + """Return the lowercase hex SHA-256 of the canonical real path of ``path``.""" + + if os.name == "nt": + return hashlib.sha256(real_workspace_path(path).encode("utf-8", errors="surrogatepass")).hexdigest() + return hashlib.sha256(os.fsencode(real_workspace_path(path))).hexdigest() + + +def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[tuple[str, str | None]]: + """Return ``(shared_root, host_path)`` pairs for ``cwd`` and, in a linked worktree, its main checkout. + + ``shared_root`` is always the Git top level when inside a work tree, or ``cwd`` outside Git, so every host derives + the same shared workspace key. ``host_path`` preserves each host's legacy path rule (the Git top level when + ``git_root`` is true, otherwise ``cwd`` and its counterpart subdirectory in the main checkout) from the same Git + invocation, or ``None`` when the main-checkout counterpart is unavailable or links back to ``cwd``. + """ + + deadline = time.monotonic() + timeout + top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + shared_own = top or cwd + host_own = shared_own if git_root else cwd + main_root = _main_worktree_root(top, git_dir, common) + if main_root is None or common is None: + return [(shared_own, host_own)] + # An unknown answer leaves the second path out, as for a bare repository. + bare = _git_output(cwd, ("--git-dir", common, *_BARE_ARGUMENTS), deadline - time.monotonic()) + if bare.strip() != "false": + return [(shared_own, host_own)] + host_main = main_root if git_root else _main_worktree_subdir(cwd, top, main_root) + return [(shared_own, host_own), (main_root, host_main)] + + def workspace_paths(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[str]: """Return the paths whose workspace bindings apply to ``cwd``, the worktree's own first. @@ -53,15 +114,11 @@ def workspace_paths(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[s is the same directory as ``cwd`` is left out. Both Git calls together stay within ``timeout``. """ - deadline = time.monotonic() + timeout - top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) - first = (top or cwd) if git_root else cwd - main = _main_worktree_path(cwd, top, git_dir, common, git_root=git_root) - if main is None or common is None: - return [first] - # An unknown answer leaves the second path out, as for a bare repository. - bare = _git_output(cwd, ("--git-dir", common, *_BARE_ARGUMENTS), deadline - time.monotonic()) - return [first, main] if bare.strip() == "false" else [first] + return [ + host_path + for _shared, host_path in workspace_locations(cwd, git_root=git_root, timeout=timeout) + if host_path is not None + ] def _git_output(cwd: str, arguments: tuple[str, ...], timeout: float) -> str: @@ -94,9 +151,7 @@ def _git_paths(stdout: str) -> tuple[str | None, str | None, str | None]: return head.strip() or None, git_dir or None, common or None -def _main_worktree_path( - cwd: str, top: str | None, git_dir: str | None, common: str | None, *, git_root: bool -) -> str | None: +def _main_worktree_root(top: str | None, git_dir: str | None, common: str | None) -> str | None: if top is None or git_dir is None or common is None or not (os.path.isabs(git_dir) and os.path.isabs(common)): return None common_directory = os.path.realpath(common) @@ -104,10 +159,13 @@ def _main_worktree_path( return None main_root = os.path.dirname(common_directory) worktree_root = os.path.realpath(top) - if main_root == worktree_root: + return None if main_root == worktree_root else main_root + + +def _main_worktree_subdir(cwd: str, top: str | None, main_root: str) -> str | None: + if top is None: return None - if git_root: - return main_root + worktree_root = os.path.realpath(top) try: position = os.path.relpath(os.path.realpath(cwd), worktree_root) except ValueError: diff --git a/integrations/codex/plugins/powercontext/powercontext_lifecycle/host_profile.py b/integrations/codex/plugins/powercontext/powercontext_lifecycle/host_profile.py index 79d036a991..93749182b0 100644 --- a/integrations/codex/plugins/powercontext/powercontext_lifecycle/host_profile.py +++ b/integrations/codex/plugins/powercontext/powercontext_lifecycle/host_profile.py @@ -41,3 +41,4 @@ class HostProfile: prompt_id_field: str diagnostics: DiagnosticThrottle bootstrap_state: BootstrapState + legacy_workspace_binding: bool = True diff --git a/integrations/codex/plugins/powercontext/powercontext_lifecycle/scope_binding.py b/integrations/codex/plugins/powercontext/powercontext_lifecycle/scope_binding.py index 2f4226108a..a45a721abd 100644 --- a/integrations/codex/plugins/powercontext/powercontext_lifecycle/scope_binding.py +++ b/integrations/codex/plugins/powercontext/powercontext_lifecycle/scope_binding.py @@ -20,18 +20,15 @@ from __future__ import annotations import json -import os from collections.abc import Mapping from dataclasses import dataclass, field -from hashlib import sha256 from http.client import HTTPException -from pathlib import Path from time import monotonic from typing import Any, Protocol from urllib.error import HTTPError from urllib.request import Request -from .git_worktree import workspace_paths +from .git_worktree import SHARED_WORKSPACE_INTEGRATION, workspace_identity, workspace_locations from .host_profile import HostProfile from .scope_binding_errors import ( ScopeBindingError, @@ -133,19 +130,69 @@ def clear_scope_binding( settings: ScopeBindingSettings, deadline: float, ) -> bool: - """Remove the durable workspace binding from the Scope service.""" + """Remove the shared workspace binding and, when enabled, this host's legacy workspace binding.""" + + shared_root, host_path = workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline))[0] + keys = [shared_workspace_key(shared_root)] + if host.legacy_workspace_binding and host_path is not None: + keys.append(_workspace_key(host, host_path)) + cleared_any = False + for key in keys: + response = _request_json( + "/v1/scope-bindings/clear", + {"key": key}, + host=host, + settings=settings, + deadline=deadline, + ) + cleared = response.get("cleared") + if not isinstance(cleared, bool): + raise ScopeBindingError + cleared_any = cleared_any or cleared + return cleared_any + +def diagnose_scope_binding( + host: HostProfile, + cwd: str, + *, + session_id: str | None, + settings: ScopeBindingSettings, + deadline: float, +) -> dict[str, Any]: + """Resolve the active Scope and identify which candidate binding key matched (for diagnostics, never hooks).""" + + if settings.scope_id is not None: + scope_id = resolve_scope_id(host, cwd, session_id=session_id, settings=settings, deadline=deadline) + return {"scope_id": scope_id, "source": "explicit", "matched_key": None} + for key in binding_keys(host, cwd, session_id=session_id, deadline=deadline): + try: + response = _request_json( + "/v1/scope-bindings/resolve", + {"explicit_scope_id": None, "binding_keys": [key], "allow_default": False}, + host=host, + settings=settings, + deadline=deadline, + ) + except ScopeBindingStatusError as error: + if error.status == 404 and error.code == "scope_not_found": + continue + raise + scope_id = response.get("scope_id") + if not isinstance(scope_id, str) or not scope_id.strip() or scope_id != scope_id.strip(): + raise ScopeBindingError + return {"scope_id": scope_id, "source": "binding", "matched_key": key} response = _request_json( - "/v1/scope-bindings/clear", - {"key": workspace_binding_key(host, cwd, deadline=deadline)}, + "/v1/scope-bindings/resolve", + {"explicit_scope_id": None, "binding_keys": [], "allow_default": True}, host=host, settings=settings, deadline=deadline, ) - cleared = response.get("cleared") - if not isinstance(cleared, bool): + scope_id = response.get("scope_id") + if not isinstance(scope_id, str) or not scope_id.strip() or scope_id != scope_id.strip(): raise ScopeBindingError - return cleared + return {"scope_id": scope_id, "source": "default", "matched_key": None} def binding_keys( @@ -157,15 +204,17 @@ def binding_keys( ) -> list[dict[str, str]]: """Return the keys that resolution tries in order. - They are the session's, the workspace's, and, in a linked worktree, its main checkout's. + At each checkout level (the current checkout first, then a linked worktree's main checkout), the shared workspace + key precedes this host's legacy workspace key. """ keys: list[dict[str, str]] = [] if session_id is not None: keys.append(session_binding_key(host, session_id)) - keys.extend( - _workspace_key(host, path) for path in workspace_paths(cwd, git_root=True, timeout=_git_timeout(deadline)) - ) + for shared_root, host_path in workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline)): + keys.append(shared_workspace_key(shared_root)) + if host.legacy_workspace_binding and host_path is not None: + keys.append(_workspace_key(host, host_path)) return keys @@ -177,14 +226,19 @@ def session_binding_key(host: HostProfile, session_id: str) -> dict[str, str]: def workspace_binding_key(host: HostProfile, cwd: str, *, deadline: float | None = None) -> dict[str, str]: - """Return the key of the workspace's own Git top level, the only key that binding and clearing write.""" + """Return the shared key of the workspace's own Git top level, the key that binding writes.""" + + del host + shared_root, _host_path = workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline))[0] + return shared_workspace_key(shared_root) + - return _workspace_key(host, workspace_paths(cwd, git_root=True, timeout=_git_timeout(deadline))[0]) +def shared_workspace_key(path: str) -> dict[str, str]: + return {"integration": SHARED_WORKSPACE_INTEGRATION, "kind": "workspace", "external_id": workspace_identity(path)} def _workspace_key(host: HostProfile, path: str) -> dict[str, str]: - external_id = sha256(os.fsencode(Path(path).resolve(strict=False))).hexdigest() - return {"integration": host.integration, "kind": "workspace", "external_id": external_id} + return {"integration": host.integration, "kind": "workspace", "external_id": workspace_identity(path)} def _request_json( diff --git a/integrations/codex/plugins/powercontext/scripts/scope_binding.py b/integrations/codex/plugins/powercontext/scripts/scope_binding.py index 317223814a..1e9e0ba1b7 100644 --- a/integrations/codex/plugins/powercontext/scripts/scope_binding.py +++ b/integrations/codex/plugins/powercontext/scripts/scope_binding.py @@ -18,6 +18,7 @@ from __future__ import annotations import argparse +import json import os import sys from collections.abc import Sequence @@ -28,16 +29,23 @@ sys.path.insert(0, str(_PLUGIN_ROOT)) from codex_host import CODEX # noqa: E402 -from powercontext_lifecycle.scope_binding import bind_scope, clear_scope_binding, resolve_scope_id # noqa: E402 +from powercontext_lifecycle.scope_binding import ( # noqa: E402 + bind_scope, + clear_scope_binding, + diagnose_scope_binding, + resolve_scope_id, +) from settings import CodexPluginSettings # noqa: E402 def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser() parser.add_argument("--cwd", default=os.getcwd()) + parser.add_argument("--session-id") action = parser.add_mutually_exclusive_group() action.add_argument("--bind-scope", metavar="SCOPE_ID") action.add_argument("--clear-scope", action="store_true") + action.add_argument("--diagnose", action="store_true") arguments = parser.parse_args(argv) loaded = CodexPluginSettings() settings = loaded.scope_binding_settings() @@ -47,7 +55,16 @@ def main(argv: Sequence[str] | None = None) -> int: return 0 if arguments.clear_scope: clear_scope_binding(CODEX, arguments.cwd, settings=settings, deadline=deadline) - print(resolve_scope_id(CODEX, arguments.cwd, session_id=None, settings=settings, deadline=deadline)) + if arguments.diagnose: + print( + json.dumps( + diagnose_scope_binding( + CODEX, arguments.cwd, session_id=arguments.session_id, settings=settings, deadline=deadline + ) + ) + ) + return 0 + print(resolve_scope_id(CODEX, arguments.cwd, session_id=arguments.session_id, settings=settings, deadline=deadline)) return 0 diff --git a/integrations/hermes/plugins/powercontext/git_worktree.py b/integrations/hermes/plugins/powercontext/git_worktree.py index 103c5fbde9..721e66c091 100644 --- a/integrations/hermes/plugins/powercontext/git_worktree.py +++ b/integrations/hermes/plugins/powercontext/git_worktree.py @@ -22,11 +22,13 @@ from __future__ import annotations +import hashlib import os import subprocess import time from shutil import which +SHARED_WORKSPACE_INTEGRATION = "shared" # --path-format applies to the options after it, so the top level stays exactly what --show-toplevel alone prints. # It needs Git 2.31 or later. _ARGUMENTS = ("rev-parse", "--show-toplevel", "--path-format=absolute", "--git-dir", "--git-common-dir") @@ -36,6 +38,65 @@ _BARE_ARGUMENTS = ("rev-parse", "--is-bare-repository") +def normalize_windows_real_path(path: str, *, windows: bool = os.name == "nt") -> str: + """Normalize extended-length prefixes and drive-letter casing so Python and Node.js hash identical Windows paths.""" + + if not windows: + return path + resolved = path + if resolved[:8].upper() == "\\\\?\\UNC\\": + resolved = "\\\\" + resolved[8:] + elif ( + len(resolved) >= 6 + and resolved[:4] == "\\\\?\\" + and resolved[4].isascii() + and resolved[4].isalpha() + and resolved[5] == ":" + ): + resolved = resolved[4:] + if len(resolved) >= 2 and resolved[0].isascii() and resolved[0].isalpha() and resolved[1] == ":": + resolved = resolved[0].upper() + resolved[1:] + return resolved + + +def real_workspace_path(path: str) -> str: + """Return the canonical real path of ``path`` with symbolic links resolved and Windows drive prefixes normalized.""" + + return normalize_windows_real_path(os.path.realpath(path)) + + +def workspace_identity(path: str) -> str: + """Return the lowercase hex SHA-256 of the canonical real path of ``path``.""" + + if os.name == "nt": + return hashlib.sha256(real_workspace_path(path).encode("utf-8", errors="surrogatepass")).hexdigest() + return hashlib.sha256(os.fsencode(real_workspace_path(path))).hexdigest() + + +def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[tuple[str, str | None]]: + """Return ``(shared_root, host_path)`` pairs for ``cwd`` and, in a linked worktree, its main checkout. + + ``shared_root`` is always the Git top level when inside a work tree, or ``cwd`` outside Git, so every host derives + the same shared workspace key. ``host_path`` preserves each host's legacy path rule (the Git top level when + ``git_root`` is true, otherwise ``cwd`` and its counterpart subdirectory in the main checkout) from the same Git + invocation, or ``None`` when the main-checkout counterpart is unavailable or links back to ``cwd``. + """ + + deadline = time.monotonic() + timeout + top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + shared_own = top or cwd + host_own = shared_own if git_root else cwd + main_root = _main_worktree_root(top, git_dir, common) + if main_root is None or common is None: + return [(shared_own, host_own)] + # An unknown answer leaves the second path out, as for a bare repository. + bare = _git_output(cwd, ("--git-dir", common, *_BARE_ARGUMENTS), deadline - time.monotonic()) + if bare.strip() != "false": + return [(shared_own, host_own)] + host_main = main_root if git_root else _main_worktree_subdir(cwd, top, main_root) + return [(shared_own, host_own), (main_root, host_main)] + + def workspace_paths(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[str]: """Return the paths whose workspace bindings apply to ``cwd``, the worktree's own first. @@ -53,15 +114,11 @@ def workspace_paths(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[s is the same directory as ``cwd`` is left out. Both Git calls together stay within ``timeout``. """ - deadline = time.monotonic() + timeout - top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) - first = (top or cwd) if git_root else cwd - main = _main_worktree_path(cwd, top, git_dir, common, git_root=git_root) - if main is None or common is None: - return [first] - # An unknown answer leaves the second path out, as for a bare repository. - bare = _git_output(cwd, ("--git-dir", common, *_BARE_ARGUMENTS), deadline - time.monotonic()) - return [first, main] if bare.strip() == "false" else [first] + return [ + host_path + for _shared, host_path in workspace_locations(cwd, git_root=git_root, timeout=timeout) + if host_path is not None + ] def _git_output(cwd: str, arguments: tuple[str, ...], timeout: float) -> str: @@ -94,9 +151,7 @@ def _git_paths(stdout: str) -> tuple[str | None, str | None, str | None]: return head.strip() or None, git_dir or None, common or None -def _main_worktree_path( - cwd: str, top: str | None, git_dir: str | None, common: str | None, *, git_root: bool -) -> str | None: +def _main_worktree_root(top: str | None, git_dir: str | None, common: str | None) -> str | None: if top is None or git_dir is None or common is None or not (os.path.isabs(git_dir) and os.path.isabs(common)): return None common_directory = os.path.realpath(common) @@ -104,10 +159,13 @@ def _main_worktree_path( return None main_root = os.path.dirname(common_directory) worktree_root = os.path.realpath(top) - if main_root == worktree_root: + return None if main_root == worktree_root else main_root + + +def _main_worktree_subdir(cwd: str, top: str | None, main_root: str) -> str | None: + if top is None: return None - if git_root: - return main_root + worktree_root = os.path.realpath(top) try: position = os.path.relpath(os.path.realpath(cwd), worktree_root) except ValueError: diff --git a/integrations/hermes/plugins/powercontext/provider.py b/integrations/hermes/plugins/powercontext/provider.py index 5bd30477ba..6f7879b3a1 100644 --- a/integrations/hermes/plugins/powercontext/provider.py +++ b/integrations/hermes/plugins/powercontext/provider.py @@ -37,7 +37,7 @@ PowerContextInvalidResponseError, PowerContextTransportError, ) -from .git_worktree import workspace_paths +from .git_worktree import SHARED_WORKSPACE_INTEGRATION, workspace_identity, workspace_locations from .helpers import ( CAPTURE_COVERAGE_KEY, capture_coverage, @@ -208,6 +208,14 @@ def _precompress_snapshot_after_capture( return captured_fingerprints +def _shared_workspace_binding_key(path: str) -> dict[str, str]: + return { + "integration": SHARED_WORKSPACE_INTEGRATION, + "kind": "workspace", + "external_id": workspace_identity(path), + } + + def _workspace_binding_key(path: str) -> dict[str, str]: workspace_id = hashlib.sha256(os.fsencode(Path(path).resolve(strict=False))).hexdigest() return {"integration": "hermes", "kind": "workspace", "external_id": workspace_id} @@ -678,28 +686,36 @@ def _switch_scope(self, scope_id: str) -> None: def _scope_binding_keys(self) -> list[dict[str, str]]: """Return the keys that resolution tries in order. - They are the session's, the workspace's, and, in a linked Git worktree, the same directory's in the main - checkout. + At both the current checkout and a linked worktree's main checkout, the shared workspace key precedes Hermes's + own legacy workspace key. """ keys = [] if self._session_id: keys.append({"integration": "hermes", "kind": "session", "external_id": self._session_id}) - keys.extend(_workspace_binding_key(path) for path in workspace_paths(self._scope_binding_cwd, git_root=False)) + for shared_root, host_path in workspace_locations(self._scope_binding_cwd, git_root=False): + keys.append(_shared_workspace_binding_key(shared_root)) + if host_path is not None: + keys.append(_workspace_binding_key(host_path)) return keys def _bind_workspace_scope(self, scope_id: str) -> None: - response = self._client.set_scope_binding(_workspace_binding_key(self._scope_binding_cwd), scope_id) + shared_root, _host_path = workspace_locations(self._scope_binding_cwd, git_root=False)[0] + response = self._client.set_scope_binding(_shared_workspace_binding_key(shared_root), scope_id) if response.get("scope_id") != scope_id: raise InvalidScopeBindingError self._bound_scope_id = scope_id self._switch_scope(scope_id) def _clear_workspace_scope(self) -> bool: - response = self._client.clear_scope_binding(_workspace_binding_key(self._scope_binding_cwd)) - cleared = response.get("cleared") - if not isinstance(cleared, bool): - raise InvalidScopeBindingError + shared_root, _host_path = workspace_locations(self._scope_binding_cwd, git_root=False)[0] + cleared_any = False + for key in (_shared_workspace_binding_key(shared_root), _workspace_binding_key(self._scope_binding_cwd)): + response = self._client.clear_scope_binding(key) + cleared = response.get("cleared") + if not isinstance(cleared, bool): + raise InvalidScopeBindingError + cleared_any = cleared_any or cleared resolved = self._client.resolve_scope_binding( explicit_scope_id=self._explicit_scope_id, binding_keys=self._scope_binding_keys(), @@ -710,7 +726,7 @@ def _clear_workspace_scope(self) -> bool: self._bound_scope_id = "" self._default_scope_id = scope_id self._switch_scope(scope_id) - return cleared + return cleared_any def _load_memory_map(self) -> dict[str, dict[str, Any]]: if self._memory_map_path is None: diff --git a/integrations/workbuddy/plugins/powercontext/hooks/git_worktree.py b/integrations/workbuddy/plugins/powercontext/hooks/git_worktree.py index 103c5fbde9..721e66c091 100644 --- a/integrations/workbuddy/plugins/powercontext/hooks/git_worktree.py +++ b/integrations/workbuddy/plugins/powercontext/hooks/git_worktree.py @@ -22,11 +22,13 @@ from __future__ import annotations +import hashlib import os import subprocess import time from shutil import which +SHARED_WORKSPACE_INTEGRATION = "shared" # --path-format applies to the options after it, so the top level stays exactly what --show-toplevel alone prints. # It needs Git 2.31 or later. _ARGUMENTS = ("rev-parse", "--show-toplevel", "--path-format=absolute", "--git-dir", "--git-common-dir") @@ -36,6 +38,65 @@ _BARE_ARGUMENTS = ("rev-parse", "--is-bare-repository") +def normalize_windows_real_path(path: str, *, windows: bool = os.name == "nt") -> str: + """Normalize extended-length prefixes and drive-letter casing so Python and Node.js hash identical Windows paths.""" + + if not windows: + return path + resolved = path + if resolved[:8].upper() == "\\\\?\\UNC\\": + resolved = "\\\\" + resolved[8:] + elif ( + len(resolved) >= 6 + and resolved[:4] == "\\\\?\\" + and resolved[4].isascii() + and resolved[4].isalpha() + and resolved[5] == ":" + ): + resolved = resolved[4:] + if len(resolved) >= 2 and resolved[0].isascii() and resolved[0].isalpha() and resolved[1] == ":": + resolved = resolved[0].upper() + resolved[1:] + return resolved + + +def real_workspace_path(path: str) -> str: + """Return the canonical real path of ``path`` with symbolic links resolved and Windows drive prefixes normalized.""" + + return normalize_windows_real_path(os.path.realpath(path)) + + +def workspace_identity(path: str) -> str: + """Return the lowercase hex SHA-256 of the canonical real path of ``path``.""" + + if os.name == "nt": + return hashlib.sha256(real_workspace_path(path).encode("utf-8", errors="surrogatepass")).hexdigest() + return hashlib.sha256(os.fsencode(real_workspace_path(path))).hexdigest() + + +def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[tuple[str, str | None]]: + """Return ``(shared_root, host_path)`` pairs for ``cwd`` and, in a linked worktree, its main checkout. + + ``shared_root`` is always the Git top level when inside a work tree, or ``cwd`` outside Git, so every host derives + the same shared workspace key. ``host_path`` preserves each host's legacy path rule (the Git top level when + ``git_root`` is true, otherwise ``cwd`` and its counterpart subdirectory in the main checkout) from the same Git + invocation, or ``None`` when the main-checkout counterpart is unavailable or links back to ``cwd``. + """ + + deadline = time.monotonic() + timeout + top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + shared_own = top or cwd + host_own = shared_own if git_root else cwd + main_root = _main_worktree_root(top, git_dir, common) + if main_root is None or common is None: + return [(shared_own, host_own)] + # An unknown answer leaves the second path out, as for a bare repository. + bare = _git_output(cwd, ("--git-dir", common, *_BARE_ARGUMENTS), deadline - time.monotonic()) + if bare.strip() != "false": + return [(shared_own, host_own)] + host_main = main_root if git_root else _main_worktree_subdir(cwd, top, main_root) + return [(shared_own, host_own), (main_root, host_main)] + + def workspace_paths(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[str]: """Return the paths whose workspace bindings apply to ``cwd``, the worktree's own first. @@ -53,15 +114,11 @@ def workspace_paths(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[s is the same directory as ``cwd`` is left out. Both Git calls together stay within ``timeout``. """ - deadline = time.monotonic() + timeout - top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) - first = (top or cwd) if git_root else cwd - main = _main_worktree_path(cwd, top, git_dir, common, git_root=git_root) - if main is None or common is None: - return [first] - # An unknown answer leaves the second path out, as for a bare repository. - bare = _git_output(cwd, ("--git-dir", common, *_BARE_ARGUMENTS), deadline - time.monotonic()) - return [first, main] if bare.strip() == "false" else [first] + return [ + host_path + for _shared, host_path in workspace_locations(cwd, git_root=git_root, timeout=timeout) + if host_path is not None + ] def _git_output(cwd: str, arguments: tuple[str, ...], timeout: float) -> str: @@ -94,9 +151,7 @@ def _git_paths(stdout: str) -> tuple[str | None, str | None, str | None]: return head.strip() or None, git_dir or None, common or None -def _main_worktree_path( - cwd: str, top: str | None, git_dir: str | None, common: str | None, *, git_root: bool -) -> str | None: +def _main_worktree_root(top: str | None, git_dir: str | None, common: str | None) -> str | None: if top is None or git_dir is None or common is None or not (os.path.isabs(git_dir) and os.path.isabs(common)): return None common_directory = os.path.realpath(common) @@ -104,10 +159,13 @@ def _main_worktree_path( return None main_root = os.path.dirname(common_directory) worktree_root = os.path.realpath(top) - if main_root == worktree_root: + return None if main_root == worktree_root else main_root + + +def _main_worktree_subdir(cwd: str, top: str | None, main_root: str) -> str | None: + if top is None: return None - if git_root: - return main_root + worktree_root = os.path.realpath(top) try: position = os.path.relpath(os.path.realpath(cwd), worktree_root) except ValueError: diff --git a/integrations/workbuddy/plugins/powercontext/scripts/workspace_scope.py b/integrations/workbuddy/plugins/powercontext/scripts/workspace_scope.py index aaf46c7af7..beb26514be 100644 --- a/integrations/workbuddy/plugins/powercontext/scripts/workspace_scope.py +++ b/integrations/workbuddy/plugins/powercontext/scripts/workspace_scope.py @@ -23,7 +23,6 @@ import sys import threading from collections.abc import Mapping, Sequence -from hashlib import sha256 from http.client import HTTPException from pathlib import Path from time import monotonic @@ -38,7 +37,11 @@ sys.path.insert(0, str(_PLUGIN_ROOT / "hooks")) sys.path.insert(0, str(_PLUGIN_ROOT)) -from git_worktree import workspace_paths # noqa: E402 +from git_worktree import ( # noqa: E402 + SHARED_WORKSPACE_INTEGRATION, + workspace_identity, + workspace_locations, +) from workbuddy_settings import WorkBuddyPluginSettings # noqa: E402 _MAX_RESPONSE_BYTES = 1_048_576 @@ -184,25 +187,75 @@ def clear_scope_binding( settings: ScopeBindingSettings, deadline: float, ) -> bool: - """Remove the durable workspace binding from the Scope service.""" + """Remove the shared workspace binding and WorkBuddy's legacy workspace binding.""" + + shared_root, host_path = workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline))[0] + keys = [_shared_workspace_key(shared_root)] + if host_path is not None: + keys.append(_workspace_key(host_path)) + cleared_any = False + for key in keys: + response = _request_json( + "/v1/scope-bindings/clear", + {"key": key}, + settings=settings, + deadline=deadline, + ) + cleared = response.get("cleared") + if not isinstance(cleared, bool): + raise ScopeBindingError + cleared_any = cleared_any or cleared + return cleared_any + + +def diagnose_scope_binding( + cwd: str, + *, + session_id: str | None, + settings: ScopeBindingSettings, + deadline: float, +) -> dict[str, Any]: + """Resolve the active Scope and identify which candidate binding key matched.""" + if settings.scope_id is not None: + scope_id = resolve_scope_id(cwd, session_id=session_id, settings=settings, deadline=deadline) + return {"scope_id": scope_id, "source": "explicit", "matched_key": None} + for key in binding_keys(cwd, session_id=session_id, deadline=deadline): + try: + response = _request_json( + "/v1/scope-bindings/resolve", + {"explicit_scope_id": None, "binding_keys": [key], "allow_default": False}, + settings=settings, + deadline=deadline, + ) + except ScopeBindingStatusError as error: + if error.status == 404 and error.code == "scope_not_found": + continue + raise + scope_id = response.get("scope_id") + if not isinstance(scope_id, str) or not scope_id.strip() or scope_id != scope_id.strip(): + raise ScopeBindingError + return {"scope_id": scope_id, "source": "binding", "matched_key": key} response = _request_json( - "/v1/scope-bindings/clear", - {"key": workspace_binding_key(cwd, deadline=deadline)}, + "/v1/scope-bindings/resolve", + {"explicit_scope_id": None, "binding_keys": [], "allow_default": True}, settings=settings, deadline=deadline, ) - cleared = response.get("cleared") - if not isinstance(cleared, bool): + scope_id = response.get("scope_id") + if not isinstance(scope_id, str) or not scope_id.strip() or scope_id != scope_id.strip(): raise ScopeBindingError - return cleared + return {"scope_id": scope_id, "source": "default", "matched_key": None} def binding_keys(cwd: str, *, session_id: str | None, deadline: float | None = None) -> list[dict[str, str]]: keys: list[dict[str, str]] = [] if session_id is not None: keys.append(session_binding_key(session_id)) - keys.extend(_workspace_key(path) for path in workspace_paths(cwd, git_root=True, timeout=_git_timeout(deadline))) + for shared_root, host_path in workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline)): + keys.append(_shared_workspace_key(shared_root)) + if host_path is not None: + keys.append(_workspace_key(host_path)) return keys @@ -214,16 +267,21 @@ def session_binding_key(session_id: str) -> dict[str, str]: def workspace_binding_key(cwd: str, *, deadline: float | None = None) -> dict[str, str]: - """Return the key of the workspace's own Git top level, the only key that binding and clearing write.""" + """Return the shared key of the workspace's own Git top level, the key that binding writes.""" + + shared_root, _host_path = workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline))[0] + return _shared_workspace_key(shared_root) - return _workspace_key(workspace_paths(cwd, git_root=True, timeout=_git_timeout(deadline))[0]) + +def _shared_workspace_key(path: str) -> dict[str, str]: + return {"integration": SHARED_WORKSPACE_INTEGRATION, "kind": "workspace", "external_id": workspace_identity(path)} def _workspace_key(path: str) -> dict[str, str]: return { "integration": "workbuddy", "kind": "workspace", - "external_id": sha256(os.fsencode(Path(path).resolve(strict=False))).hexdigest(), + "external_id": workspace_identity(path), } @@ -376,9 +434,11 @@ def _read_bounded(response: _Response, *, deadline: float) -> bytes: def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser() parser.add_argument("--cwd", default=os.getcwd()) + parser.add_argument("--session-id") action = parser.add_mutually_exclusive_group() action.add_argument("--bind-scope", metavar="SCOPE_ID") action.add_argument("--clear-scope", action="store_true") + action.add_argument("--diagnose", action="store_true") arguments = parser.parse_args(argv) settings = WorkBuddyPluginSettings.from_environment() deadline = monotonic() + settings.http_budget_seconds @@ -387,7 +447,16 @@ def main(argv: Sequence[str] | None = None) -> int: return 0 if arguments.clear_scope: clear_scope_binding(arguments.cwd, settings=settings, deadline=deadline) - print(resolve_scope_id(arguments.cwd, session_id=None, settings=settings, deadline=deadline)) + if arguments.diagnose: + print( + json.dumps( + diagnose_scope_binding( + arguments.cwd, session_id=arguments.session_id, settings=settings, deadline=deadline + ) + ) + ) + return 0 + print(resolve_scope_id(arguments.cwd, session_id=arguments.session_id, settings=settings, deadline=deadline)) return 0 diff --git a/scripts/integration_manifest.py b/scripts/integration_manifest.py index 2c08da92f2..0453bc36e4 100644 --- a/scripts/integration_manifest.py +++ b/scripts/integration_manifest.py @@ -264,6 +264,13 @@ class IntegrationDeclaration(BaseModel): proposal: str | None = None rationale: str | None = None + @field_validator("id") + @classmethod + def reject_reserved_id(cls, value: str) -> str: + if value == "shared": + raise ValueError("'shared' is reserved for cross-host workspace Scope bindings") + return value + @field_validator("capabilities", "profiles", "toolsets") @classmethod def validate_unique_values(cls, values: tuple[StrEnum | str, ...]) -> tuple[StrEnum | str, ...]: diff --git a/src/powercontext/client/cli.py b/src/powercontext/client/cli.py index aa4bd14081..d4812e6f16 100644 --- a/src/powercontext/client/cli.py +++ b/src/powercontext/client/cli.py @@ -158,7 +158,11 @@ TopicMemoryProcessingStatus, TopicMemoryProcessingStatusRequest, ) -from powercontext_integration_lifecycle.git_worktree import workspace_paths +from powercontext_integration_lifecycle.git_worktree import ( + SHARED_WORKSPACE_INTEGRATION, + workspace_identity, + workspace_locations, +) HELP_OPTION_NAMES = ("-h", "--help") _ClientResponse: TypeAlias = ( @@ -351,26 +355,94 @@ def list_dreams( _BINDING_KIND_SESSION = "session" _BINDING_KIND_WORKSPACE = "workspace" _DEFAULT_BINDING_INTEGRATION = "opencode" +_GIT_ROOT_WORKSPACE_INTEGRATIONS = frozenset({"claude-code", "codex", "workbuddy", "zcode"}) +_REALPATH_CWD_WORKSPACE_INTEGRATIONS = frozenset({"bub", "hermes", "kimi-code"}) +_RESOLVED_CWD_WORKSPACE_INTEGRATIONS = frozenset({"dsh", "opencode", "pi"}) +_HOST_WORKSPACE_INTEGRATIONS = ( + _GIT_ROOT_WORKSPACE_INTEGRATIONS | _REALPATH_CWD_WORKSPACE_INTEGRATIONS | _RESOLVED_CWD_WORKSPACE_INTEGRATIONS +) -def _workspace_binding_external_ids(cwd: Path, integration: str) -> list[str]: - """Return the workspace identities that the integration's plugin resolves, its own first. +def _legacy_host_workspace_external_id(path: str, integration: str) -> str: + if integration in _RESOLVED_CWD_WORKSPACE_INTEGRATIONS: + # Node hosts that key path.resolve preserve symbolic links. + return hashlib.sha256(os.path.abspath(path).encode("utf-8")).hexdigest() + return workspace_identity(path) - In a linked Git worktree, the identity of the main checkout follows, as the plugins send it. - """ - if integration not in {"codex", "claude-code", "hermes", "kimi-code", "opencode", "pi"}: +def _workspace_binding_keys(cwd: Path, integration: str) -> list[ScopeBindingKey]: + """Return the workspace keys that resolution tries in order, matching the host plugin's sequence.""" + + if integration == SHARED_WORKSPACE_INTEGRATION: + return [ + _binding_key(SHARED_WORKSPACE_INTEGRATION, _BINDING_KIND_WORKSPACE, workspace_identity(shared_root)) + for shared_root, _host_path in workspace_locations(str(cwd), git_root=True) + ] + if integration not in _HOST_WORKSPACE_INTEGRATIONS: raise typer.BadParameter( # noqa: TRY003 - user-facing CLI validation. "Unsupported workspace integration; use an explicit binding key instead.", param_hint="--integration" ) - # Claude Code and Codex bind the Git top level, including when invoked from a subdirectory. - paths = workspace_paths(str(cwd), git_root=integration in {"codex", "claude-code"}) - if integration in {"opencode", "pi"}: - # Node hosts use path.resolve without resolving symlinks. - identities = [os.path.abspath(path).encode("utf-8") for path in paths] - else: - identities = [os.fsencode(Path(path).resolve(strict=False)) for path in paths] - return [hashlib.sha256(identity).hexdigest() for identity in identities] + keys: list[ScopeBindingKey] = [] + for shared_root, host_path in workspace_locations( + str(cwd), git_root=integration in _GIT_ROOT_WORKSPACE_INTEGRATIONS + ): + keys.append( + _binding_key(SHARED_WORKSPACE_INTEGRATION, _BINDING_KIND_WORKSPACE, workspace_identity(shared_root)) + ) + if host_path is not None: + keys.append( + _binding_key( + integration, + _BINDING_KIND_WORKSPACE, + _legacy_host_workspace_external_id(host_path, integration), + ) + ) + return keys + + +def _resolve_cli_binding_target( + *, + kind: str | None, + external_id: str | None, + cwd: Path | None, + integration: str | None, + for_clear: bool = False, +) -> list[ScopeBindingKey]: + if cwd is not None and external_id is not None: + raise typer.BadParameter("--cwd and --external-id cannot be used together") # noqa: TRY003 + if cwd is not None: + if kind is not None and kind != _BINDING_KIND_WORKSPACE: + raise typer.BadParameter("--cwd only applies to --kind workspace") # noqa: TRY003 + target_integration = SHARED_WORKSPACE_INTEGRATION if integration is None else integration + if ( + target_integration != SHARED_WORKSPACE_INTEGRATION + and target_integration not in _HOST_WORKSPACE_INTEGRATIONS + ): + raise typer.BadParameter( # noqa: TRY003 + "Unsupported workspace integration; use --external-id instead.", param_hint="--integration" + ) + shared_root, host_path = workspace_locations( + str(cwd), + git_root=target_integration == SHARED_WORKSPACE_INTEGRATION + or target_integration in _GIT_ROOT_WORKSPACE_INTEGRATIONS, + )[0] + shared_key = _binding_key( + SHARED_WORKSPACE_INTEGRATION, _BINDING_KIND_WORKSPACE, workspace_identity(shared_root) + ) + if target_integration == SHARED_WORKSPACE_INTEGRATION: + return [shared_key] + resolved_host_path = host_path if host_path is not None else str(cwd) + host_key = _binding_key( + target_integration, + _BINDING_KIND_WORKSPACE, + _legacy_host_workspace_external_id(resolved_host_path, target_integration), + ) + return [shared_key, host_key] if for_clear else [host_key] + if kind is None: + raise typer.BadParameter("Missing option '--kind' (or pass '--cwd' for a workspace binding).") # noqa: TRY003 + if external_id is None: + raise typer.BadParameter("Missing option '--external-id' (or pass '--cwd' for a workspace binding).") # noqa: TRY003 + return [_binding_key(integration or _DEFAULT_BINDING_INTEGRATION, kind, external_id)] def _binding_key(integration: str, kind: str, external_id: str) -> ScopeBindingKey: @@ -503,12 +575,13 @@ def resolve_scope( binding_keys = [] if scope_id is None: if session_id is not None and session_id.strip(): + if integration == SHARED_WORKSPACE_INTEGRATION: + raise typer.BadParameter( # noqa: TRY003 + "--session-id requires a host --integration rather than 'shared'.", param_hint="--integration" + ) binding_keys.append(_binding_key(integration, _BINDING_KIND_SESSION, session_id.strip())) workspace = cwd if cwd is not None else Path.cwd() - binding_keys.extend( - _binding_key(integration, _BINDING_KIND_WORKSPACE, external_id) - for external_id in _workspace_binding_external_ids(workspace, integration) - ) + binding_keys.extend(_workspace_binding_keys(workspace, integration)) request = ResolveScopeBindingRequest( explicit_scope_id=scope_id, binding_keys=binding_keys, @@ -521,29 +594,57 @@ def resolve_scope( def set_scope_binding( context: typer.Context, scope_id: Annotated[str, typer.Argument(help="Exact Scope ID to bind.")], - kind: Annotated[str, typer.Option(help="Binding kind, e.g. session or workspace.")], - external_id: Annotated[str, typer.Option(help="Integration-specific identity, e.g. a session or path hash.")], - integration: Annotated[str, typer.Option(help="Binding integration name.")] = _DEFAULT_BINDING_INTEGRATION, + kind: Annotated[str | None, typer.Option(help="Binding kind, e.g. session or workspace.")] = None, + external_id: Annotated[ + str | None, typer.Option(help="Integration-specific identity, e.g. a session or path hash.") + ] = None, + cwd: Annotated[ + Path | None, typer.Option(help="Workspace directory to bind using the shared checkout identity.") + ] = None, + integration: Annotated[ + str | None, + typer.Option(help="Binding integration name (defaults to 'shared' with --cwd, else 'opencode')."), + ] = None, ) -> None: - """Bind one external integration identity to a Scope.""" + """Bind one external integration identity or local workspace checkout to a Scope.""" - request = SetScopeBindingRequest( - root=ScopeBinding(key=_binding_key(integration, kind, external_id), scope_id=scope_id) - ) + key = _resolve_cli_binding_target(kind=kind, external_id=external_id, cwd=cwd, integration=integration)[0] + request = SetScopeBindingRequest(root=ScopeBinding(key=key, scope_id=scope_id)) asyncio.run(_execute(context, lambda client: client.set_scope_binding(request))) @scope_binding_app.command("clear") def clear_scope_binding( context: typer.Context, - kind: Annotated[str, typer.Option(help="Binding kind, e.g. session or workspace.")], - external_id: Annotated[str, typer.Option(help="Integration-specific identity, e.g. a session or path hash.")], - integration: Annotated[str, typer.Option(help="Binding integration name.")] = _DEFAULT_BINDING_INTEGRATION, + kind: Annotated[str | None, typer.Option(help="Binding kind, e.g. session or workspace.")] = None, + external_id: Annotated[ + str | None, typer.Option(help="Integration-specific identity, e.g. a session or path hash.") + ] = None, + cwd: Annotated[ + Path | None, + typer.Option( + help="Workspace directory to clear (clears shared and, when --integration names a host, its own)." + ), + ] = None, + integration: Annotated[ + str | None, + typer.Option(help="Binding integration name (defaults to 'shared' with --cwd, else 'opencode')."), + ] = None, ) -> None: - """Clear one external integration binding.""" + """Clear one external integration or local workspace binding.""" - request = ClearScopeBindingRequest(key=_binding_key(integration, kind, external_id)) - asyncio.run(_execute(context, lambda client: client.clear_scope_binding(request))) + keys = _resolve_cli_binding_target( + kind=kind, external_id=external_id, cwd=cwd, integration=integration, for_clear=True + ) + + async def operation(client: PowerContextClient) -> ClearScopeBindingResponse: + cleared = False + for key in keys: + response = await client.clear_scope_binding(ClearScopeBindingRequest(key=key)) + cleared = cleared or response.cleared + return ClearScopeBindingResponse(cleared=cleared) + + asyncio.run(_execute(context, operation)) @dataclass(frozen=True, slots=True) diff --git a/src/powercontext/client/session_import.py b/src/powercontext/client/session_import.py index b1c8b7e430..af8eae5cbe 100644 --- a/src/powercontext/client/session_import.py +++ b/src/powercontext/client/session_import.py @@ -34,7 +34,11 @@ ScopeDescriptor, ) from powercontext.redaction import redact_known_secrets -from powercontext_integration_lifecycle.git_worktree import workspace_paths +from powercontext_integration_lifecycle.git_worktree import ( + SHARED_WORKSPACE_INTEGRATION, + workspace_identity, + workspace_locations, +) SUPPORTED_SESSION_IMPORT_HOSTS = ("codex",) _MAX_CONTENT_LENGTH = 200_000 @@ -567,15 +571,25 @@ def _session_binding_keys(session_id: str | None) -> tuple[ScopeBindingKey, ...] def _workspace_binding_keys(cwd: str) -> list[ScopeBindingKey]: - # Codex keys the Git top level; in a linked worktree that still exists, its main checkout's key follows. - return [ - ScopeBindingKey( - integration="codex", - kind="workspace", - external_id=sha256(os.fsencode(Path(path).resolve(strict=False))).hexdigest(), + # Try the shared workspace key ahead of Codex's own key at both the checkout and, in a linked worktree, its main. + keys: list[ScopeBindingKey] = [] + for shared_root, host_path in workspace_locations(cwd, git_root=True): + keys.append( + ScopeBindingKey( + integration=SHARED_WORKSPACE_INTEGRATION, + kind="workspace", + external_id=workspace_identity(shared_root), + ) ) - for path in workspace_paths(cwd, git_root=True) - ] + if host_path is not None: + keys.append( + ScopeBindingKey( + integration="codex", + kind="workspace", + external_id=workspace_identity(host_path), + ) + ) + return keys def _metadata(prompt: ImportedPrompt) -> dict[str, object]: diff --git a/src/powercontext_integration_lifecycle/git_worktree.py b/src/powercontext_integration_lifecycle/git_worktree.py index 7027ec8768..bd1ab0d129 100644 --- a/src/powercontext_integration_lifecycle/git_worktree.py +++ b/src/powercontext_integration_lifecycle/git_worktree.py @@ -19,11 +19,13 @@ from __future__ import annotations +import hashlib import os import subprocess import time from shutil import which +SHARED_WORKSPACE_INTEGRATION = "shared" # --path-format applies to the options after it, so the top level stays exactly what --show-toplevel alone prints. # It needs Git 2.31 or later. _ARGUMENTS = ("rev-parse", "--show-toplevel", "--path-format=absolute", "--git-dir", "--git-common-dir") @@ -33,6 +35,65 @@ _BARE_ARGUMENTS = ("rev-parse", "--is-bare-repository") +def normalize_windows_real_path(path: str, *, windows: bool = os.name == "nt") -> str: + """Normalize extended-length prefixes and drive-letter casing so Python and Node.js hash identical Windows paths.""" + + if not windows: + return path + resolved = path + if resolved[:8].upper() == "\\\\?\\UNC\\": + resolved = "\\\\" + resolved[8:] + elif ( + len(resolved) >= 6 + and resolved[:4] == "\\\\?\\" + and resolved[4].isascii() + and resolved[4].isalpha() + and resolved[5] == ":" + ): + resolved = resolved[4:] + if len(resolved) >= 2 and resolved[0].isascii() and resolved[0].isalpha() and resolved[1] == ":": + resolved = resolved[0].upper() + resolved[1:] + return resolved + + +def real_workspace_path(path: str) -> str: + """Return the canonical real path of ``path`` with symbolic links resolved and Windows drive prefixes normalized.""" + + return normalize_windows_real_path(os.path.realpath(path)) + + +def workspace_identity(path: str) -> str: + """Return the lowercase hex SHA-256 of the canonical real path of ``path``.""" + + if os.name == "nt": + return hashlib.sha256(real_workspace_path(path).encode("utf-8", errors="surrogatepass")).hexdigest() + return hashlib.sha256(os.fsencode(real_workspace_path(path))).hexdigest() + + +def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[tuple[str, str | None]]: + """Return ``(shared_root, host_path)`` pairs for ``cwd`` and, in a linked worktree, its main checkout. + + ``shared_root`` is always the Git top level when inside a work tree, or ``cwd`` outside Git, so every host derives + the same shared workspace key. ``host_path`` preserves each host's legacy path rule (the Git top level when + ``git_root`` is true, otherwise ``cwd`` and its counterpart subdirectory in the main checkout) from the same Git + invocation, or ``None`` when the main-checkout counterpart is unavailable or links back to ``cwd``. + """ + + deadline = time.monotonic() + timeout + top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + shared_own = top or cwd + host_own = shared_own if git_root else cwd + main_root = _main_worktree_root(top, git_dir, common) + if main_root is None or common is None: + return [(shared_own, host_own)] + # An unknown answer leaves the second path out, as for a bare repository. + bare = _git_output(cwd, ("--git-dir", common, *_BARE_ARGUMENTS), deadline - time.monotonic()) + if bare.strip() != "false": + return [(shared_own, host_own)] + host_main = main_root if git_root else _main_worktree_subdir(cwd, top, main_root) + return [(shared_own, host_own), (main_root, host_main)] + + def workspace_paths(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[str]: """Return the paths whose workspace bindings apply to ``cwd``, the worktree's own first. @@ -50,15 +111,11 @@ def workspace_paths(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[s is the same directory as ``cwd`` is left out. Both Git calls together stay within ``timeout``. """ - deadline = time.monotonic() + timeout - top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) - first = (top or cwd) if git_root else cwd - main = _main_worktree_path(cwd, top, git_dir, common, git_root=git_root) - if main is None or common is None: - return [first] - # An unknown answer leaves the second path out, as for a bare repository. - bare = _git_output(cwd, ("--git-dir", common, *_BARE_ARGUMENTS), deadline - time.monotonic()) - return [first, main] if bare.strip() == "false" else [first] + return [ + host_path + for _shared, host_path in workspace_locations(cwd, git_root=git_root, timeout=timeout) + if host_path is not None + ] def _git_output(cwd: str, arguments: tuple[str, ...], timeout: float) -> str: @@ -91,9 +148,7 @@ def _git_paths(stdout: str) -> tuple[str | None, str | None, str | None]: return head.strip() or None, git_dir or None, common or None -def _main_worktree_path( - cwd: str, top: str | None, git_dir: str | None, common: str | None, *, git_root: bool -) -> str | None: +def _main_worktree_root(top: str | None, git_dir: str | None, common: str | None) -> str | None: if top is None or git_dir is None or common is None or not (os.path.isabs(git_dir) and os.path.isabs(common)): return None common_directory = os.path.realpath(common) @@ -101,10 +156,13 @@ def _main_worktree_path( return None main_root = os.path.dirname(common_directory) worktree_root = os.path.realpath(top) - if main_root == worktree_root: + return None if main_root == worktree_root else main_root + + +def _main_worktree_subdir(cwd: str, top: str | None, main_root: str) -> str | None: + if top is None: return None - if git_root: - return main_root + worktree_root = os.path.realpath(top) try: position = os.path.relpath(os.path.realpath(cwd), worktree_root) except ValueError: diff --git a/src/powercontext_integration_lifecycle/host_profile.py b/src/powercontext_integration_lifecycle/host_profile.py index d274ee0323..6619108a5b 100644 --- a/src/powercontext_integration_lifecycle/host_profile.py +++ b/src/powercontext_integration_lifecycle/host_profile.py @@ -38,3 +38,4 @@ class HostProfile: prompt_id_field: str diagnostics: DiagnosticThrottle bootstrap_state: BootstrapState + legacy_workspace_binding: bool = True diff --git a/src/powercontext_integration_lifecycle/scope_binding.py b/src/powercontext_integration_lifecycle/scope_binding.py index 68ccd241bd..530ed4786b 100644 --- a/src/powercontext_integration_lifecycle/scope_binding.py +++ b/src/powercontext_integration_lifecycle/scope_binding.py @@ -17,18 +17,15 @@ from __future__ import annotations import json -import os from collections.abc import Mapping from dataclasses import dataclass, field -from hashlib import sha256 from http.client import HTTPException -from pathlib import Path from time import monotonic from typing import Any, Protocol from urllib.error import HTTPError from urllib.request import Request -from .git_worktree import workspace_paths +from .git_worktree import SHARED_WORKSPACE_INTEGRATION, workspace_identity, workspace_locations from .host_profile import HostProfile from .scope_binding_errors import ( ScopeBindingError, @@ -130,19 +127,69 @@ def clear_scope_binding( settings: ScopeBindingSettings, deadline: float, ) -> bool: - """Remove the durable workspace binding from the Scope service.""" + """Remove the shared workspace binding and, when enabled, this host's legacy workspace binding.""" + + shared_root, host_path = workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline))[0] + keys = [shared_workspace_key(shared_root)] + if host.legacy_workspace_binding and host_path is not None: + keys.append(_workspace_key(host, host_path)) + cleared_any = False + for key in keys: + response = _request_json( + "/v1/scope-bindings/clear", + {"key": key}, + host=host, + settings=settings, + deadline=deadline, + ) + cleared = response.get("cleared") + if not isinstance(cleared, bool): + raise ScopeBindingError + cleared_any = cleared_any or cleared + return cleared_any + +def diagnose_scope_binding( + host: HostProfile, + cwd: str, + *, + session_id: str | None, + settings: ScopeBindingSettings, + deadline: float, +) -> dict[str, Any]: + """Resolve the active Scope and identify which candidate binding key matched (for diagnostics, never hooks).""" + + if settings.scope_id is not None: + scope_id = resolve_scope_id(host, cwd, session_id=session_id, settings=settings, deadline=deadline) + return {"scope_id": scope_id, "source": "explicit", "matched_key": None} + for key in binding_keys(host, cwd, session_id=session_id, deadline=deadline): + try: + response = _request_json( + "/v1/scope-bindings/resolve", + {"explicit_scope_id": None, "binding_keys": [key], "allow_default": False}, + host=host, + settings=settings, + deadline=deadline, + ) + except ScopeBindingStatusError as error: + if error.status == 404 and error.code == "scope_not_found": + continue + raise + scope_id = response.get("scope_id") + if not isinstance(scope_id, str) or not scope_id.strip() or scope_id != scope_id.strip(): + raise ScopeBindingError + return {"scope_id": scope_id, "source": "binding", "matched_key": key} response = _request_json( - "/v1/scope-bindings/clear", - {"key": workspace_binding_key(host, cwd, deadline=deadline)}, + "/v1/scope-bindings/resolve", + {"explicit_scope_id": None, "binding_keys": [], "allow_default": True}, host=host, settings=settings, deadline=deadline, ) - cleared = response.get("cleared") - if not isinstance(cleared, bool): + scope_id = response.get("scope_id") + if not isinstance(scope_id, str) or not scope_id.strip() or scope_id != scope_id.strip(): raise ScopeBindingError - return cleared + return {"scope_id": scope_id, "source": "default", "matched_key": None} def binding_keys( @@ -154,15 +201,17 @@ def binding_keys( ) -> list[dict[str, str]]: """Return the keys that resolution tries in order. - They are the session's, the workspace's, and, in a linked worktree, its main checkout's. + At each checkout level (the current checkout first, then a linked worktree's main checkout), the shared workspace + key precedes this host's legacy workspace key. """ keys: list[dict[str, str]] = [] if session_id is not None: keys.append(session_binding_key(host, session_id)) - keys.extend( - _workspace_key(host, path) for path in workspace_paths(cwd, git_root=True, timeout=_git_timeout(deadline)) - ) + for shared_root, host_path in workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline)): + keys.append(shared_workspace_key(shared_root)) + if host.legacy_workspace_binding and host_path is not None: + keys.append(_workspace_key(host, host_path)) return keys @@ -174,14 +223,19 @@ def session_binding_key(host: HostProfile, session_id: str) -> dict[str, str]: def workspace_binding_key(host: HostProfile, cwd: str, *, deadline: float | None = None) -> dict[str, str]: - """Return the key of the workspace's own Git top level, the only key that binding and clearing write.""" + """Return the shared key of the workspace's own Git top level, the key that binding writes.""" + + del host + shared_root, _host_path = workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline))[0] + return shared_workspace_key(shared_root) + - return _workspace_key(host, workspace_paths(cwd, git_root=True, timeout=_git_timeout(deadline))[0]) +def shared_workspace_key(path: str) -> dict[str, str]: + return {"integration": SHARED_WORKSPACE_INTEGRATION, "kind": "workspace", "external_id": workspace_identity(path)} def _workspace_key(host: HostProfile, path: str) -> dict[str, str]: - external_id = sha256(os.fsencode(Path(path).resolve(strict=False))).hexdigest() - return {"integration": host.integration, "kind": "workspace", "external_id": external_id} + return {"integration": host.integration, "kind": "workspace", "external_id": workspace_identity(path)} def _request_json( diff --git a/tests/claude_code_plugin/test_contract.py b/tests/claude_code_plugin/test_contract.py index 2c814c27e2..c66b117a8d 100644 --- a/tests/claude_code_plugin/test_contract.py +++ b/tests/claude_code_plugin/test_contract.py @@ -27,7 +27,12 @@ import pytest -from tests.git_worktree_support import ScopeBindings, check_worktree_fallback, make_git_layout +from tests.git_worktree_support import ( + ScopeBindings, + check_shared_workspace_precedence, + check_worktree_fallback, + make_git_layout, +) REPOSITORY_ROOT = Path(__file__).resolve().parents[2] PLUGIN_ROOT = REPOSITORY_ROOT / "integrations" / "claude-code" / "plugins" / "powercontext" @@ -188,10 +193,17 @@ def request(path, payload, *, host, settings, deadline, method="POST"): assert requests[0][0] == "/v1/scope-bindings/resolve" assert requests[0][1]["explicit_scope_id"] == resolved binding_keys = cast(list[dict[str, Any]], requests[0][1]["binding_keys"]) - assert [key["kind"] for key in binding_keys] == ["session", "workspace"] + assert [key["kind"] for key in binding_keys] == ["session", "workspace", "workspace"] + assert [key["integration"] for key in binding_keys] == [ + host_name := scope_module.CLAUDE_CODE.integration, + "shared", + host_name, + ] assert binding_keys[0]["external_id"] == "session-1" - assert binding_keys[1]["external_id"] != str(tmp_path) + assert binding_keys[1]["external_id"] == binding_keys[2]["external_id"] != str(tmp_path) assert requests[1][0] == "/v1/scope-bindings" + put_key = cast(dict[str, Any], requests[1][1]["key"]) + assert put_key["integration"] == "shared" assert requests[1][2] == "PUT" @@ -224,16 +236,29 @@ def request(path, payload, *, host, settings, deadline, method="POST"): bind=lambda cwd, scope_id: scope_binding_client.bind_scope(host, str(cwd), scope_id, **options), clear=lambda cwd: scope_binding_client.clear_scope_binding(host, str(cwd), **options), ) - # The first workspace key is still the hash of the resolved Git top level, so existing bindings keep matching. + worktree_id = hashlib.sha256(os.fsencode(layout.worktree)).hexdigest() + checkout_id = hashlib.sha256(os.fsencode(layout.checkout)).hexdigest() keys = scope_binding_client.binding_keys(host, str(layout.worktree_sub), session_id="session-a") - assert [key["external_id"] for key in keys] == [ - "session-a", - hashlib.sha256(os.fsencode(layout.worktree)).hexdigest(), - hashlib.sha256(os.fsencode(layout.checkout)).hexdigest(), + assert keys == [ + {"integration": host.integration, "kind": "session", "external_id": "session-a"}, + {"integration": "shared", "kind": "workspace", "external_id": worktree_id}, + {"integration": host.integration, "kind": "workspace", "external_id": worktree_id}, + {"integration": "shared", "kind": "workspace", "external_id": checkout_id}, + {"integration": host.integration, "kind": "workspace", "external_id": checkout_id}, ] assert scope_binding_client.binding_keys(host, str(layout.checkout_sub), session_id=None) == [ - {"integration": host.integration, "kind": "workspace", "external_id": keys[2]["external_id"]} + {"integration": "shared", "kind": "workspace", "external_id": checkout_id}, + {"integration": host.integration, "kind": "workspace", "external_id": checkout_id}, ] + bindings.scopes.clear() + check_shared_workspace_precedence( + bindings=bindings, + checkout=layout.checkout_sub, + legacy_key={"integration": host.integration, "kind": "workspace", "external_id": checkout_id}, + resolve=lambda cwd: scope_binding_client.resolve_scope_id(host, str(cwd), session_id=None, **options), + bind=lambda cwd, scope_id: scope_binding_client.bind_scope(host, str(cwd), scope_id, **options), + clear=lambda cwd: scope_binding_client.clear_scope_binding(host, str(cwd), **options), + ) @pytest.mark.parametrize( diff --git a/tests/codex_plugin/test_contract.py b/tests/codex_plugin/test_contract.py index 246f816f3a..1d30ed30d5 100644 --- a/tests/codex_plugin/test_contract.py +++ b/tests/codex_plugin/test_contract.py @@ -43,7 +43,7 @@ def post(path, payload, *, host, settings, deadline, method="POST"): return {"scope_id": "scp_00000000000000000000000000"} monkeypatch.setattr(scope_binding_client, "_request_json", post) - monkeypatch.setattr(scope_binding_client, "workspace_paths", lambda cwd, **_kwargs: [cwd]) + monkeypatch.setattr(scope_binding_client, "workspace_locations", lambda cwd, **_kwargs: [(cwd, cwd)]) resolved = scope_binding_client.resolve_scope_id( scope_module.CODEX, @@ -57,9 +57,13 @@ def post(path, payload, *, host, settings, deadline, method="POST"): assert resolved == "scp_00000000000000000000000000" assert requests[0][0] == "/v1/scope-bindings/resolve" binding_keys = cast(list[dict[str, Any]], requests[0][1]["binding_keys"]) - assert [key["kind"] for key in binding_keys] == ["session", "workspace"] + assert [(key["integration"], key["kind"]) for key in binding_keys] == [ + ("codex", "session"), + ("shared", "workspace"), + ("codex", "workspace"), + ] assert binding_keys[0]["external_id"] == "session-1" - assert binding_keys[1]["external_id"] != str(tmp_path) + assert binding_keys[1]["external_id"] == binding_keys[2]["external_id"] != str(tmp_path) assert not binding_keys[1]["external_id"].startswith("scp_") assert requests[1] == ( "/v1/scope-bindings", diff --git a/tests/codex_plugin/test_scope_binding.py b/tests/codex_plugin/test_scope_binding.py index 2789687d31..25a6eed6f9 100644 --- a/tests/codex_plugin/test_scope_binding.py +++ b/tests/codex_plugin/test_scope_binding.py @@ -35,7 +35,12 @@ from powercontext.http._generated import operations as generated_operations from powercontext.server.app import create_app from powercontext.server.mcp import create_mcp_server -from tests.git_worktree_support import ScopeBindings, check_worktree_fallback, make_git_layout +from tests.git_worktree_support import ( + ScopeBindings, + check_shared_workspace_precedence, + check_worktree_fallback, + make_git_layout, +) def _operations_with_scope_mode(scope_mode: str) -> frozenset[str]: @@ -646,7 +651,7 @@ def request(path, payload, *, host, settings, deadline, method="POST"): assert bound == "scp_project_a" assert requests == [("/v1/scope-bindings", {"key": key, "scope_id": "scp_project_a"}, "PUT")] - assert key["integration"] == "codex" + assert key["integration"] == "shared" assert key["kind"] == "workspace" assert key["external_id"] != str(tmp_path) @@ -680,16 +685,29 @@ def request(path, payload, *, host, settings, deadline, method="POST"): bind=lambda cwd, scope_id: scope_binding_client.bind_scope(host, str(cwd), scope_id, **options), clear=lambda cwd: scope_binding_client.clear_scope_binding(host, str(cwd), **options), ) - # The first workspace key is still the hash of the resolved Git top level, so existing bindings keep matching. + worktree_id = hashlib.sha256(os.fsencode(layout.worktree)).hexdigest() + checkout_id = hashlib.sha256(os.fsencode(layout.checkout)).hexdigest() keys = scope_binding_client.binding_keys(host, str(layout.worktree_sub), session_id="session-a") - assert [key["external_id"] for key in keys] == [ - "session-a", - hashlib.sha256(os.fsencode(layout.worktree)).hexdigest(), - hashlib.sha256(os.fsencode(layout.checkout)).hexdigest(), + assert keys == [ + {"integration": host.integration, "kind": "session", "external_id": "session-a"}, + {"integration": "shared", "kind": "workspace", "external_id": worktree_id}, + {"integration": host.integration, "kind": "workspace", "external_id": worktree_id}, + {"integration": "shared", "kind": "workspace", "external_id": checkout_id}, + {"integration": host.integration, "kind": "workspace", "external_id": checkout_id}, ] assert scope_binding_client.binding_keys(host, str(layout.checkout_sub), session_id=None) == [ - {"integration": host.integration, "kind": "workspace", "external_id": keys[2]["external_id"]} + {"integration": "shared", "kind": "workspace", "external_id": checkout_id}, + {"integration": host.integration, "kind": "workspace", "external_id": checkout_id}, ] + bindings.scopes.clear() + check_shared_workspace_precedence( + bindings=bindings, + checkout=layout.checkout_sub, + legacy_key={"integration": host.integration, "kind": "workspace", "external_id": checkout_id}, + resolve=lambda cwd: scope_binding_client.resolve_scope_id(host, str(cwd), session_id=None, **options), + bind=lambda cwd, scope_id: scope_binding_client.bind_scope(host, str(cwd), scope_id, **options), + clear=lambda cwd: scope_binding_client.clear_scope_binding(host, str(cwd), **options), + ) def test_bind_scope_rejects_a_different_server_scope( @@ -710,7 +728,7 @@ def request(path, payload, *, host, settings, deadline, method="POST"): ) -def test_clear_scope_binding_removes_only_the_workspace_key( +def test_clear_scope_binding_removes_shared_and_host_workspace_keys( scope_module: ModuleType, scope_binding_client: ModuleType, monkeypatch: pytest.MonkeyPatch, @@ -720,7 +738,7 @@ def test_clear_scope_binding_removes_only_the_workspace_key( def request(path, payload, *, host, settings, deadline, method="POST"): requests.append((path, payload)) - return {"cleared": True} + return {"cleared": payload["key"]["integration"] == "codex"} monkeypatch.setattr(scope_binding_client, "_request_json", request) settings = scope_module.CodexPluginSettings().scope_binding_settings() @@ -728,10 +746,40 @@ def request(path, payload, *, host, settings, deadline, method="POST"): cleared = scope_binding_client.clear_scope_binding( scope_module.CODEX, str(tmp_path), settings=settings, deadline=float("inf") ) - key = scope_binding_client.workspace_binding_key(scope_module.CODEX, str(tmp_path)) + shared_key = scope_binding_client.workspace_binding_key(scope_module.CODEX, str(tmp_path)) + legacy_key = {"integration": "codex", "kind": "workspace", "external_id": shared_key["external_id"]} assert cleared is True - assert requests == [("/v1/scope-bindings/clear", {"key": key})] + assert requests == [ + ("/v1/scope-bindings/clear", {"key": shared_key}), + ("/v1/scope-bindings/clear", {"key": legacy_key}), + ] + + +def test_diagnose_scope_binding_identifies_the_matching_key( + scope_module: ModuleType, + scope_binding_client: ModuleType, + monkeypatch: pytest.MonkeyPatch, + tmp_path, +) -> None: + shared_key = scope_binding_client.workspace_binding_key(scope_module.CODEX, str(tmp_path)) + legacy_key = {"integration": "codex", "kind": "workspace", "external_id": shared_key["external_id"]} + + def request(path, payload, *, host, settings, deadline, method="POST"): + keys = payload["binding_keys"] + if keys == [legacy_key]: + return {"scope_id": "scp_legacy"} + if not payload.get("allow_default", True): + raise scope_binding_client.ScopeBindingStatusError(404, path, "scope_not_found") + return {"scope_id": "scp_default"} + + monkeypatch.setattr(scope_binding_client, "_request_json", request) + settings = scope_module.CodexPluginSettings().scope_binding_settings() + + report = scope_binding_client.diagnose_scope_binding( + scope_module.CODEX, str(tmp_path), session_id=None, settings=settings, deadline=float("inf") + ) + assert report == {"scope_id": "scp_legacy", "source": "binding", "matched_key": legacy_key} def test_cli_bind_scope_prints_the_bound_scope_id( diff --git a/tests/e2e/test_bub_service_chain.py b/tests/e2e/test_bub_service_chain.py index d0aa059827..df15cf61e6 100644 --- a/tests/e2e/test_bub_service_chain.py +++ b/tests/e2e/test_bub_service_chain.py @@ -118,7 +118,8 @@ def bind(self, start: int, scope_id: str) -> None: """Bind the workspace key that one Bub turn presented to `scope_id`, as an operator would.""" resolved = self.calls("/v1/scope-bindings/resolve", start) assert resolved, "bub_scope_resolution_missing" - (key,) = resolved[0]["request"]["binding_keys"] + key, *_ = resolved[0]["request"]["binding_keys"] + assert key["integration"] == "shared" self.server.put("/v1/scope-bindings", json={"key": key, "scope_id": scope_id}).raise_for_status() def remember(self, scope_id: str, text: str) -> None: diff --git a/tests/git_worktree_support.py b/tests/git_worktree_support.py index 5ca8b7c907..976e10b2b4 100644 --- a/tests/git_worktree_support.py +++ b/tests/git_worktree_support.py @@ -165,3 +165,25 @@ def check_worktree_fallback( clear(worktree) assert resolve(worktree) == "checkout-scope" assert resolve(checkout) == "checkout-scope" + + +def check_shared_workspace_precedence( + *, + bindings: ScopeBindings, + checkout: Path, + legacy_key: BindingKey, + resolve: Callable[[Path], str], + bind: Callable[[Path, str], object], + clear: Callable[[Path], object], +) -> None: + """Verify legacy fallback before a shared bind, shared precedence after it, and dual-key clearing.""" + + bindings.set(legacy_key, "legacy-host-scope") + assert resolve(checkout) == "legacy-host-scope" + + bind(checkout, "shared-scope") + assert resolve(checkout) == "shared-scope" + + assert clear(checkout) is True + assert resolve(checkout) == "default" + assert clear(checkout) is False diff --git a/tests/integrations/test_hermes_provider.py b/tests/integrations/test_hermes_provider.py index c91f37880e..f1a9660516 100644 --- a/tests/integrations/test_hermes_provider.py +++ b/tests/integrations/test_hermes_provider.py @@ -1699,8 +1699,11 @@ def test_scope_resolution_uses_session_workspace_and_server_default(tmp_path, he status = json.loads(provider.handle_slash_command("scope status")) assert status["active_scope_id"] == client.default_scope_id - assert [key["kind"] for key in client.resolved_binding_keys] == ["session", "workspace"] - assert all(key["integration"] == "hermes" for key in client.resolved_binding_keys) + assert [(key["integration"], key["kind"]) for key in client.resolved_binding_keys] == [ + ("hermes", "session"), + ("shared", "workspace"), + ("hermes", "workspace"), + ] provider.shutdown() @@ -1736,11 +1739,12 @@ def command(cwd: Path, text: str) -> dict[str, Any]: ) with provider_in(layout.worktree_sub): pass - # The first workspace key is still the hash of the resolved working directory, so existing bindings keep matching. - assert [key["external_id"] for key in client.resolved_binding_keys] == [ - "session-1", - hashlib.sha256(os.fsencode(layout.worktree_sub)).hexdigest(), - hashlib.sha256(os.fsencode(layout.checkout_sub)).hexdigest(), + assert [(key["integration"], key["external_id"]) for key in client.resolved_binding_keys] == [ + ("hermes", "session-1"), + ("shared", hashlib.sha256(os.fsencode(layout.worktree)).hexdigest()), + ("hermes", hashlib.sha256(os.fsencode(layout.worktree_sub)).hexdigest()), + ("shared", hashlib.sha256(os.fsencode(layout.checkout)).hexdigest()), + ("hermes", hashlib.sha256(os.fsencode(layout.checkout_sub)).hexdigest()), ] diff --git a/tests/test_cli_scope.py b/tests/test_cli_scope.py index c21448efca..c9126e475f 100644 --- a/tests/test_cli_scope.py +++ b/tests/test_cli_scope.py @@ -217,8 +217,10 @@ def test_scope_resolve_mirrors_the_plugin_binding_keys(monkeypatch: pytest.Monke assert isinstance(request, ResolveScopeBindingRequest) assert request.allow_default is False assert request.explicit_scope_id is None + shared_id = hashlib.sha256(os.fsencode(workspace.resolve())).hexdigest() assert [(key.integration, key.kind, key.external_id) for key in request.binding_keys] == [ ("opencode", "session", "ses_1"), + ("shared", "workspace", shared_id), ("opencode", "workspace", _workspace_external_id(workspace)), ] assert "scp_resolved" in output @@ -416,35 +418,98 @@ def test_scope_resolve_non_git_symlink_matches_host_rules( ) request = client.calls[0] assert isinstance(request, ResolveScopeBindingRequest) - expected = os.path.abspath(link) if integration in {"opencode", "pi"} else str(directory.resolve()) - assert request.binding_keys[0].external_id == hashlib.sha256(os.fsencode(expected)).hexdigest() + resolved_id = hashlib.sha256(os.fsencode(directory.resolve())).hexdigest() + expected_host = os.path.abspath(link) if integration in {"opencode", "pi", "dsh"} else str(directory.resolve()) + assert [(key.integration, key.external_id) for key in request.binding_keys] == [ + ("shared", resolved_id), + (integration, hashlib.sha256(os.fsencode(expected_host)).hexdigest()), + ] -@pytest.mark.parametrize("integration", ["opencode", "pi", "hermes", "kimi-code", "codex", "claude-code"]) +@pytest.mark.parametrize( + "integration", + ["opencode", "pi", "dsh", "hermes", "kimi-code", "bub", "codex", "claude-code", "workbuddy", "zcode"], +) def test_scope_resolve_in_a_linked_worktree_falls_back_to_the_main_checkouts_key( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, integration: str, ) -> None: layout = make_git_layout(tmp_path, monkeypatch) - git_root = integration in {"codex", "claude-code"} + git_root = integration in {"codex", "claude-code", "workbuddy", "zcode"} - def external_ids(cwd: Path) -> list[str]: + def resolved_pairs(cwd: Path) -> list[tuple[str, str]]: client, _ = _invoke( monkeypatch, _descriptor(), ["scope", "resolve", "--integration", integration, "--cwd", str(cwd)] ) request = client.calls[0] assert isinstance(request, ResolveScopeBindingRequest) - return [key.external_id for key in request.binding_keys] + return [(key.integration, key.external_id) for key in request.binding_keys] + + worktree_root_id = hashlib.sha256(os.fsencode(layout.worktree)).hexdigest() + checkout_root_id = hashlib.sha256(os.fsencode(layout.checkout)).hexdigest() + worktree_host, checkout_host = ( + (layout.worktree, layout.checkout) if git_root else (layout.worktree_sub, layout.checkout_sub) + ) + assert resolved_pairs(layout.worktree_sub) == [ + ("shared", worktree_root_id), + (integration, hashlib.sha256(os.fsencode(worktree_host)).hexdigest()), + ("shared", checkout_root_id), + (integration, hashlib.sha256(os.fsencode(checkout_host)).hexdigest()), + ] + assert resolved_pairs(layout.checkout_sub) == [ + ("shared", checkout_root_id), + (integration, hashlib.sha256(os.fsencode(checkout_host)).hexdigest()), + ] + assert len(resolved_pairs(layout.bare_worktree)) == 2 + + +def test_scope_binding_set_and_clear_with_cwd_manage_shared_and_host_keys( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + layout = make_git_layout(tmp_path, monkeypatch) + checkout_id = hashlib.sha256(os.fsencode(layout.checkout)).hexdigest() + sub_id = hashlib.sha256(os.fsencode(layout.checkout_sub)).hexdigest() + client, _ = _invoke( + monkeypatch, + ScopeBinding.model_validate({ + "key": {"integration": "shared", "kind": "workspace", "external_id": checkout_id}, + "scope_id": "scp_repo", + }), + ["scope", "binding", "set", "scp_repo", "--cwd", str(layout.checkout_sub)], + ) + set_req = client.calls[0] + assert isinstance(set_req, SetScopeBindingRequest) + assert (set_req.root.key.integration, set_req.root.key.kind, set_req.root.key.external_id) == ( + "shared", + "workspace", + checkout_id, + ) - worktree, checkout = (layout.worktree, layout.checkout) if git_root else (layout.worktree_sub, layout.checkout_sub) - # The worktree's own key comes first and is the one the plugin binds; the main checkout's key follows. - assert external_ids(layout.worktree_sub) == [ - hashlib.sha256(os.fsencode(worktree)).hexdigest(), - hashlib.sha256(os.fsencode(checkout)).hexdigest(), + clear_client, output = _invoke( + monkeypatch, + ClearScopeBindingResponse(cleared=True), + ["scope", "binding", "clear", "--cwd", str(layout.checkout_sub), "--integration", "opencode"], + ) + clear_calls = [call for call in clear_client.calls if isinstance(call, ClearScopeBindingRequest)] + assert len(clear_calls) == len(clear_client.calls) + assert [(call.key.integration, call.key.external_id) for call in clear_calls] == [ + ("shared", checkout_id), + ("opencode", sub_id), + ] + assert "Binding cleared." in output + + shared_resolve, _ = _invoke( + monkeypatch, + _descriptor(), + ["scope", "resolve", "--integration", "shared", "--cwd", str(layout.worktree_sub)], + ) + resolve_req = shared_resolve.calls[0] + assert isinstance(resolve_req, ResolveScopeBindingRequest) + assert [(k.integration, k.external_id) for k in resolve_req.binding_keys] == [ + ("shared", hashlib.sha256(os.fsencode(layout.worktree)).hexdigest()), + ("shared", checkout_id), ] - assert external_ids(layout.checkout_sub) == [hashlib.sha256(os.fsencode(checkout)).hexdigest()] - assert len(external_ids(layout.bare_worktree)) == 1 def test_scope_resolve_rejects_unknown_workspace_rules(monkeypatch: pytest.MonkeyPatch) -> None: diff --git a/tests/test_session_import.py b/tests/test_session_import.py index 26b2e99ee9..babc04f672 100644 --- a/tests/test_session_import.py +++ b/tests/test_session_import.py @@ -190,7 +190,11 @@ def test_import_sessions_resolves_scope_and_captures_sources(tmp_path: Path, mon ) assert len(client.resolve_scope_requests) == 1 assert client.resolve_scope_requests[0].allow_default is False - assert [key.kind for key in client.resolve_scope_requests[0].binding_keys] == ["session", "workspace"] + assert [(key.integration, key.kind) for key in client.resolve_scope_requests[0].binding_keys] == [ + ("codex", "session"), + ("shared", "workspace"), + ("codex", "workspace"), + ] assert len(client.capture_requests) == 1 assert client.capture_requests[0].source_id.startswith("codex-user-prompt:") assert client.capture_requests[0].content == "[REDACTED]" @@ -343,12 +347,18 @@ async def resolve_scope_binding(self, request: Any) -> ScopeDescriptor: result = _run(import_sessions(client, host="codex", destination_id=_DESTINATION_ID, codex_home=codex_home)) assert result.imported == 1 - # The worktree's own key, the hash of its Git top level as before, comes first, so its own binding would win. - assert [key.external_id for key in client.resolve_scope_requests[0].binding_keys] == [ - hashlib.sha256(os.fsencode(layout.worktree)).hexdigest(), - checkout_key, + worktree_key = hashlib.sha256(os.fsencode(layout.worktree)).hexdigest() + assert [(key.integration, key.external_id) for key in client.resolve_scope_requests[0].binding_keys] == [ + ("shared", worktree_key), + ("codex", worktree_key), + ("shared", checkout_key), + ("codex", checkout_key), ] assert client.capture_requests[0].scope_id == "checkout-scope" + bindings.set({"integration": "shared", "kind": "workspace", "external_id": checkout_key}, "shared-checkout-scope") + client_shared = BoundClient() + _run(import_sessions(client_shared, host="codex", destination_id=_DESTINATION_ID, codex_home=codex_home)) + assert client_shared.capture_requests[0].scope_id == "shared-checkout-scope" def test_import_sessions_uses_live_hook_source_identity(tmp_path: Path) -> None: diff --git a/tests/workbuddy_plugin/test_scope_binding.py b/tests/workbuddy_plugin/test_scope_binding.py index 150ab24910..4bf93ff18e 100644 --- a/tests/workbuddy_plugin/test_scope_binding.py +++ b/tests/workbuddy_plugin/test_scope_binding.py @@ -30,7 +30,12 @@ import pytest -from tests.git_worktree_support import ScopeBindings, check_worktree_fallback, make_git_layout +from tests.git_worktree_support import ( + ScopeBindings, + check_shared_workspace_precedence, + check_worktree_fallback, + make_git_layout, +) _SCOPE_BODY = json.dumps({"scope_id": "scope-1"}).encode() _DRIP_INTERVAL_SECONDS = 0.05 @@ -226,7 +231,7 @@ def slow_git(*_args: Any, **kwargs: Any) -> subprocess.CompletedProcess[str]: text=True, ) - git_worktree = sys.modules[scope_module.workspace_paths.__module__] + git_worktree = sys.modules[scope_module.workspace_locations.__module__] monkeypatch.setattr(git_worktree, "which", lambda _name: sys.executable) monkeypatch.setattr(git_worktree.subprocess, "run", slow_git) settings = _settings(scope_module, "http://127.0.0.1:1") @@ -270,9 +275,21 @@ def request(path, payload, *, settings, deadline, method="POST"): bind=lambda cwd, scope_id: scope_module.bind_scope(str(cwd), scope_id, **options), clear=lambda cwd: scope_module.clear_scope_binding(str(cwd), **options), ) - # The first workspace key is still the hash of the resolved Git top level, so existing bindings keep matching. + worktree_id = hashlib.sha256(os.fsencode(layout.worktree)).hexdigest() + checkout_id = hashlib.sha256(os.fsencode(layout.checkout)).hexdigest() keys = scope_module.binding_keys(str(layout.worktree_sub), session_id=None) - assert [key["external_id"] for key in keys] == [ - hashlib.sha256(os.fsencode(layout.worktree)).hexdigest(), - hashlib.sha256(os.fsencode(layout.checkout)).hexdigest(), + assert keys == [ + {"integration": "shared", "kind": "workspace", "external_id": worktree_id}, + {"integration": "workbuddy", "kind": "workspace", "external_id": worktree_id}, + {"integration": "shared", "kind": "workspace", "external_id": checkout_id}, + {"integration": "workbuddy", "kind": "workspace", "external_id": checkout_id}, ] + bindings.scopes.clear() + check_shared_workspace_precedence( + bindings=bindings, + checkout=layout.checkout_sub, + legacy_key={"integration": "workbuddy", "kind": "workspace", "external_id": checkout_id}, + resolve=lambda cwd: scope_module.resolve_scope_id(str(cwd), session_id=None, **options), + bind=lambda cwd, scope_id: scope_module.bind_scope(str(cwd), scope_id, **options), + clear=lambda cwd: scope_module.clear_scope_binding(str(cwd), **options), + ) From fc9ce4fe64b914f14751a59dea3aba6df0f0dfc1 Mon Sep 17 00:00:00 2001 From: wycocoyu <180249289+wycocoyu@users.noreply.github.com> Date: Wed, 2 Dec 2026 08:55:10 -0800 Subject: [PATCH 3/7] feat(integrations): adopt shared workspace Scope bindings across JS and TS hosts --- docs/en/docs/integrations/dsh.md | 12 +- docs/en/docs/integrations/kimi-code.md | 4 +- docs/en/docs/integrations/opencode.md | 11 +- docs/en/docs/integrations/pi.md | 11 +- docs/en/docs/integrations/zcode.md | 12 +- docs/zh/docs/integrations/dsh.md | 6 +- docs/zh/docs/integrations/kimi-code.md | 4 +- docs/zh/docs/integrations/opencode.md | 6 +- docs/zh/docs/integrations/pi.md | 6 +- docs/zh/docs/integrations/zcode.md | 4 +- .../dsh/plugins/powercontext/lib/index.js | 402 ++++++++++++------ .../dsh/plugins/powercontext/src/doctor.ts | 36 +- .../plugins/powercontext/src/git-worktree.ts | 113 ++++- .../dsh/plugins/powercontext/src/scope.ts | 37 +- .../plugins/powercontext/tests/scope.spec.ts | 24 +- .../plugins/powercontext/scripts/doctor.mjs | 22 +- .../plugins/powercontext/scripts/scope.mjs | 35 +- .../powercontext/shared/git-worktree.mjs | 113 ++++- .../plugins/powercontext/shared/runtime.mjs | 31 +- .../powercontext/tests/plugin.test.mjs | 30 +- integrations/lifecycle/git-worktree.ts | 113 ++++- .../plugins/powercontext/lib/index.js | 83 +++- .../opencode/plugins/powercontext/lib/tui.js | 83 +++- .../plugins/powercontext/src/git-worktree.ts | 113 ++++- .../plugins/powercontext/src/scope.ts | 35 +- .../plugins/powercontext/tests/scope.spec.ts | 26 +- .../plugins/powercontext/tests/tui.spec.tsx | 3 +- .../plugins/powercontext/src/git-worktree.ts | 113 ++++- .../pi/plugins/powercontext/src/scope.ts | 35 +- .../plugins/powercontext/tests/scope.spec.ts | 23 +- .../plugins/powercontext/scripts/doctor.mjs | 23 +- .../plugins/powercontext/scripts/scope.mjs | 41 +- .../powercontext/shared/git-worktree.mjs | 113 ++++- .../plugins/powercontext/shared/scope.mjs | 28 +- .../powercontext/tests/plugin.test.mjs | 5 +- .../plugins/powercontext/tests/scope.test.mjs | 29 +- .../test_shared_workspace_scope_binding.py | 389 +++++++++++++++++ tests/e2e/test_zcode_service_chain.py | 13 +- tests/test_git_worktree.py | 98 ++++- 39 files changed, 1871 insertions(+), 414 deletions(-) create mode 100644 tests/e2e/test_shared_workspace_scope_binding.py diff --git a/docs/en/docs/integrations/dsh.md b/docs/en/docs/integrations/dsh.md index da363d32e6..400bbeaae6 100644 --- a/docs/en/docs/integrations/dsh.md +++ b/docs/en/docs/integrations/dsh.md @@ -488,12 +488,12 @@ the complete `handoff` member, then pass that exact value to `mcp__powercontext_ `selection: "prepared"`. No preliminary Source capture is needed. In the separate low-level capture/activate/finalize flow, pass activation's top-level `draft` to finalization and transfer the complete native finalization result unchanged. -The plugin resolves one Server-owned Scope in this order: `POWERCONTEXT_DSH_SCOPE_ID`, a durable binding for the -session workspace, then the Server default. The workspace path is hashed only as an external binding key. A missing -workspace therefore uses the Server default instead of the Harness process directory. In a linked Git worktree that -has no workspace binding of its own, the binding of the same directory in the main checkout applies, so a checkout's -binding also covers its linked worktrees. That fallback comes from the real path that Git reports, so it matches a -checkout binding made from a path without symlinks. +The plugin resolves one Server-owned Scope in this order: `POWERCONTEXT_DSH_SCOPE_ID`, the checkout's cross-host +`shared` workspace binding (real Git root path) ahead of DSH's legacy directory binding, then the Server default. The +workspace path is hashed only as an external binding key. A missing workspace therefore uses the Server default instead +of the Harness process directory. Binding a checkout once through `powercontext scope binding set --cwd ` +or another host's workspace helper applies in DSH across subdirectories and symlinks, and in a linked Git worktree that +has no workspace binding of its own, the main checkout's binding applies. The plugin calls `POST /v1/context/prepare` once before the model analyzes the prompt, unless prompt recall is off. Explicit `remember_memory` calls do not require a model. diff --git a/docs/en/docs/integrations/kimi-code.md b/docs/en/docs/integrations/kimi-code.md index 62fac39143..2719d280a9 100644 --- a/docs/en/docs/integrations/kimi-code.md +++ b/docs/en/docs/integrations/kimi-code.md @@ -72,11 +72,11 @@ Open a new Kimi session after changing the installation mode. An explicit `--sco The Hook, Scope script and doctor use the same Server resolution: explicit Scope, then the workspace binding, then the Server default. A missing or broken binding target fails resolution without client fallback or Scope creation. Explicit Scope resolution does not require a workspace key: `scope.mjs resolve` may omit `--cwd` in that mode. Workspace-mode resolution and all bind/unbind operations require an absolute working directory. -The binding key uses integration `kimi-code`, kind `workspace`, and SHA-256 of the absolute working directory after native real-path resolution; it contains no raw path. Existing directories share a binding across symlink/junction aliases and case variants recognized by the filesystem. On POSIX, symlinks are followed before interpreting subsequent `..` components; Windows uses its native path semantics. Use the Kimi session's working directory; subdirectories retain separate identities, without Git-root discovery. In a linked Git worktree, resolution tries the key of the same directory in the main checkout after the worktree's own key, so a checkout's binding also covers its linked worktrees until a worktree is bound itself; bind and unbind still write only the worktree's own key. If real-path resolution fails, the key uses the lexically normalized absolute path. Bind existing, accessible directories and bind again if their resolved identity changes. Session bindings are outside this integration's scope. +Workspace binding writes use the cross-host integration `shared`, kind `workspace`, and SHA-256 of the Git root's real path (or the working directory outside Git); resolution tries that `shared` key ahead of any legacy `kimi-code` directory key at both the current checkout and, in a linked Git worktree, its main checkout, while `unbind` removes both the `shared` key and Kimi's legacy key. It contains no raw path. Existing checkouts share a binding across subdirectories, symlink/junction aliases, and every PowerContext host on the machine; outside Git, subdirectories retain separate identities. On POSIX, symlinks are followed before interpreting subsequent `..` components; Windows normalizes drive-letter casing and extended-length prefixes after real-path resolution. In a linked Git worktree, a checkout's binding covers its linked worktrees until a worktree is bound itself; bind and unbind there change only the worktree's own keys. If real-path resolution fails on a missing trailing segment, symlinks on the deepest existing ancestor are resolved first. Bind existing, accessible directories and bind again if their resolved identity changes. Session bindings are outside this integration's scope. Bind/unbind changes only that workspace's Server-owned binding. The JSON result keeps `binding` separate from subsequent resolution: a saved binding may be masked by an explicit Scope (`bound_scope_is_current: false`), or remain saved when resolution fails. An unconfirmed write stays `unknown` and is not retried automatically. Resolve again before claiming the active Scope changed. -For native MCP operations, use this request's Hook binding metadata or a successful read-only Scope-script result for the actual workspace; never infer a Scope from historical content. Doctor reports the current Scope ID and selection strategy (`explicit` or `workspace_or_default`); the latter does not assert which fallback matched. +For native MCP operations, use this request's Hook binding metadata or a successful read-only Scope-script result for the actual workspace; never infer a Scope from historical content. Doctor reports the current Scope ID, selection strategy (`explicit` or `workspace_or_default`), and `matched_key` (`shared:workspace`, `kimi-code:workspace`, or `default`). ## Select a workflow profile diff --git a/docs/en/docs/integrations/opencode.md b/docs/en/docs/integrations/opencode.md index 76ebbacba5..396ac09d19 100644 --- a/docs/en/docs/integrations/opencode.md +++ b/docs/en/docs/integrations/opencode.md @@ -66,11 +66,12 @@ export POWERCONTEXT_OPENCODE_CAPTURE_PROMPTS=true opencode ``` -Each OpenCode session resolves an explicit `POWERCONTEXT_OPENCODE_SCOPE_ID`, its durable Session binding, its -workspace binding, then the Server default. The resolved Scope is fixed to the Session so resume keeps the same -boundary. In a linked Git worktree that has no workspace binding of its own, the binding of the same directory in the -main checkout applies, so a checkout's binding also covers its linked worktrees. That fallback comes from the real path -that Git reports, so it matches a checkout binding made from a path without symlinks. Set the explicit variable only to an existing Server-owned Scope. +Each OpenCode session resolves an explicit `POWERCONTEXT_OPENCODE_SCOPE_ID`, its durable Session binding, the +checkout's cross-host `shared` workspace binding (real Git root path) ahead of OpenCode's legacy directory binding, +then the Server default. The resolved Scope is fixed to the Session so resume keeps the same boundary. Binding a +checkout once through `powercontext scope binding set --cwd ` or another host's workspace helper +applies in OpenCode across subdirectories and symlinks, and in a linked Git worktree that has no workspace binding of +its own, the main checkout's binding applies. Set the explicit variable only to an existing Server-owned Scope. For a Server using bearer authentication, supply its token while running setup, through the complete header in `POWERCONTEXT_OPENCODE_AUTHORIZATION` or the token in `POWERCONTEXT_CLIENT_API_TOKEN`: diff --git a/docs/en/docs/integrations/pi.md b/docs/en/docs/integrations/pi.md index 5a4c4d9c10..121ea12f93 100644 --- a/docs/en/docs/integrations/pi.md +++ b/docs/en/docs/integrations/pi.md @@ -46,11 +46,12 @@ Eligible user prompts are captured separately as Content Sources. The package ne transcript. Recall, capture, and boundary flushing fail open: an unavailable Server, timeout, redirect, or invalid response leaves Pi's prompt unchanged and never blocks ordinary work. -The package resolves one Server-owned Scope in this order: `POWERCONTEXT_PI_SCOPE_ID`, a durable binding for the -workspace, then the Server default. The workspace path is hashed only as an external binding key; it never becomes a -Scope ID. In a linked Git worktree that has no workspace binding of its own, the binding of the same directory in the -main checkout applies, so a checkout's binding also covers its linked worktrees. That fallback comes from the real path -that Git reports, so it matches a checkout binding made from a path without symlinks. Keep the explicit variable unset unless the host must force one existing Scope. +The package resolves one Server-owned Scope in this order: `POWERCONTEXT_PI_SCOPE_ID`, the checkout's cross-host +`shared` workspace binding (real Git root path) ahead of Pi's legacy directory binding, then the Server default. The +workspace path is hashed only as an external binding key; it never becomes a Scope ID. Binding a checkout once through +`powercontext scope binding set --cwd ` or another host's workspace helper applies in Pi across +subdirectories and symlinks, and in a linked Git worktree that has no workspace binding of its own, the main checkout's +binding applies. Keep the explicit variable unset unless the host must force one existing Scope. With these capabilities enabled, Pi satisfies the repository's Full core integration profile. diff --git a/docs/en/docs/integrations/zcode.md b/docs/en/docs/integrations/zcode.md index 55fae46bb0..4e7f982f93 100644 --- a/docs/en/docs/integrations/zcode.md +++ b/docs/en/docs/integrations/zcode.md @@ -388,11 +388,13 @@ The plugin reaches the same PowerContext Server through two paths: `PreparedHandoff` to follow-up tools exactly, without omitting or inventing fields. Resolved content is marked `untrusted_history` and should be checked against the current project state. -The Hook selects a Scope through `POWERCONTEXT_ZCODE_SCOPE_ID`, then current session binding, workspace binding, and -finally the Server default. A canonical Git-root or workspace path is hashed into an external binding key; the path -itself is not a Scope ID. A linked Git worktree that has no workspace binding of its own uses its main checkout's -binding, so a checkout's binding also covers its linked worktrees. Bind inside the worktree to give it a separate -Scope; `bind` and `unbind` there change only the worktree's own binding. For a remote workspace, set `POWERCONTEXT_ZCODE_REMOTE_WORKSPACE=true` and an existing +The Hook selects a Scope through `POWERCONTEXT_ZCODE_SCOPE_ID`, then current session binding, the checkout's cross-host +`shared` workspace binding (ahead of any legacy `zcode` workspace binding), and finally the Server default. A canonical +Git-root or workspace path is hashed into an external binding key; the path itself is not a Scope ID. Binding a checkout +writes the `shared` key so every PowerContext host shares the Scope, while `unbind` removes both the `shared` key and +ZCode's legacy key. A linked Git worktree that has no workspace binding of its own uses its main checkout's binding, so +a checkout's binding also covers its linked worktrees. Bind inside the worktree to give it a separate Scope; `bind` and +`unbind` there change only the worktree's own binding. For a remote workspace, set `POWERCONTEXT_ZCODE_REMOTE_WORKSPACE=true` and an existing `POWERCONTEXT_ZCODE_SCOPE_ID` before launching ZCode, so the Hook skips local path inference. MCP tools still need the correct Scope when called. diff --git a/docs/zh/docs/integrations/dsh.md b/docs/zh/docs/integrations/dsh.md index 955e272b45..de9a37323a 100644 --- a/docs/zh/docs/integrations/dsh.md +++ b/docs/zh/docs/integrations/dsh.md @@ -406,11 +406,9 @@ profile 契约之外的 Server MCP 工具。插件不会注册 Pi/Hermes 风格 独立的底层 capture/activate/finalize 流程则把 activation 顶层的 `draft` 交给 finalization,完整保留并传递原生 finalization 结果,不额外包装或只提取其中的内容。 -插件按 `POWERCONTEXT_DSH_SCOPE_ID`、session workspace 持久 binding、Server 默认 Scope 的顺序解析一个由 +插件按 `POWERCONTEXT_DSH_SCOPE_ID`、当前 checkout 的跨宿主 `shared` workspace 绑定(真实 Git 根路径,优先于 DSH 旧目录绑定)、Server 默认 Scope 的顺序解析一个由 Server 管理的 Scope。workspace 路径只会哈希为外部 binding key。缺少 workspace 时使用 Server 默认 Scope, -不会把 Harness 进程目录作为 Scope。在没有自己 workspace binding 的 linked Git worktree 中, -解析会使用主 checkout 中同一目录的绑定,所以 checkout 的绑定也覆盖它的 linked worktree。这个回退来自 Git 报告的真实路径, -因此只有 checkout 的绑定建立时所用路径不含符号链接,才能匹配。 +不会把 Harness 进程目录作为 Scope。通过 `powercontext scope binding set --cwd ` 或其他宿主脚本绑定一次 checkout,即可在 DSH 的各子目录与符号链接路径下生效;在没有自己 workspace binding 的 linked Git worktree 中,主 checkout 的绑定同样会自动回退生效。 插件在模型分析提示词前只调用一次 `POST /v1/context/prepare`,关闭提示词召回时不调用。显式 `remember_memory` 不需要模型。 diff --git a/docs/zh/docs/integrations/kimi-code.md b/docs/zh/docs/integrations/kimi-code.md index 08bf2b5cff..13ed39b4f9 100644 --- a/docs/zh/docs/integrations/kimi-code.md +++ b/docs/zh/docs/integrations/kimi-code.md @@ -72,11 +72,11 @@ node "/plugins/managed/powercontext/scripts/scope.mjs" unbind --cwd / Hook、Scope 脚本和 doctor 共用 Server 的解析顺序:显式 Scope、工作区绑定、Server 默认 Scope。绑定目标缺失或不可用时解析失败,客户端不自行回退或创建 Scope。显式 Scope 解析不要求工作区键,该模式下 `scope.mjs resolve` 可以省略 `--cwd`。工作区模式的解析和所有 bind/unbind 操作均要求绝对工作目录。 -绑定键使用 integration `kimi-code`、kind `workspace`,external_id 为绝对工作目录经原生真实路径解析后的 SHA-256,不含原始路径。对于已有目录,symlink/junction 别名和文件系统认可的大小写变体共用绑定。POSIX 先跟随符号链接,再解释后续 `..` 分量;Windows 遵循原生路径语义。请使用 Kimi 会话实际提交的工作目录;子目录保留独立身份,不查找 Git 根目录。在 linked Git worktree 中,解析先尝试 worktree 自己的键,再尝试主 checkout 中同一目录的键,所以在 worktree 自己绑定之前,checkout 的绑定也覆盖它;bind 和 unbind 仍只写 worktree 自己的键。真实路径解析失败时,使用词法规范化后的绝对路径。请绑定已存在且可访问的目录;解析身份变化后需要重新绑定。本接入不提供 session binding。 +工作区绑定写入跨宿主的 integration `shared`、kind `workspace`,external_id 为 Git 根目录(非 Git 下为工作目录)真实物理路径的 SHA-256;解析时在当前 checkout 与 linked Git worktree 的主 checkout 两个层级上均优先尝试 `shared` 键,再回退旧的 `kimi-code` 目录键,`unbind` 则同时清除 `shared` 键与 Kimi 的旧键,键内不含原始路径。同一 Git 仓库的各子目录、symlink/junction 别名与本机所有 PowerContext 宿主共用同一绑定;在非 Git 目录下,子目录保留独立身份。POSIX 先跟随符号链接再解释后续 `..` 分量,Windows 在真实路径解析后统一规范化盘符大小写与扩展路径前缀。在 linked Git worktree 中,worktree 自己绑定前继承主 checkout 的绑定,在 worktree 内执行 bind 和 unbind 只改动该 worktree 自己的键。若末尾子目录尚未存在,先解析最深已存在祖先目录的符号链接。请绑定已存在且可访问的目录;解析身份变化后需要重新绑定。本接入不提供 session binding。 bind/unbind 只修改该工作区在 Server 上的绑定。JSON 将 `binding` 写入结果与后续解析分开:绑定保存成功后仍可能被显式 Scope 遮盖(`bound_scope_is_current: false`),或在后续解析失败时继续保留。无法确认的写入为 `unknown`,不自动重试;重新 resolve 成功后才能宣称当前 Scope 已切换。 -原生 MCP 操作使用本轮 Hook 的 binding metadata,或实际工作区的 Scope 脚本只读解析结果,不从历史内容推断 Scope。doctor 显示当前 Scope ID 与解析策略(`explicit` 或 `workspace_or_default`),后者不表示已确认具体命中了工作区绑定还是默认值。 +原生 MCP 操作使用本轮 Hook 的 binding metadata,或实际工作区的 Scope 脚本只读解析结果,不从历史内容推断 Scope。doctor 显示当前 Scope ID、解析策略(`explicit` 或 `workspace_or_default`)以及 `matched_key`(`shared:workspace`、`kimi-code:workspace` 或 `default`)。 ## 选择工作流 profile diff --git a/docs/zh/docs/integrations/opencode.md b/docs/zh/docs/integrations/opencode.md index 8cd0ec574c..1d087fa2d5 100644 --- a/docs/zh/docs/integrations/opencode.md +++ b/docs/zh/docs/integrations/opencode.md @@ -60,11 +60,9 @@ export POWERCONTEXT_OPENCODE_CAPTURE_PROMPTS=true opencode ``` -每个 OpenCode session 按显式的 `POWERCONTEXT_OPENCODE_SCOPE_ID`、持久 Session binding、workspace binding、 +每个 OpenCode session 按显式的 `POWERCONTEXT_OPENCODE_SCOPE_ID`、持久 Session binding、当前 checkout 的跨宿主 `shared` workspace 绑定(真实 Git 根路径,优先于 OpenCode 旧目录绑定)、 Server 默认 Scope 的顺序解析。解析结果会固定到 Session,resume 时继续使用同一边界。显式变量只能指向一个 -已存在且由 Server 管理的 Scope。在没有自己 workspace binding 的 linked Git worktree 中, -解析会使用主 checkout 中同一目录的绑定,所以 checkout 的绑定也覆盖它的 linked worktree。这个回退来自 Git 报告的真实路径, -因此只有 checkout 的绑定建立时所用路径不含符号链接,才能匹配。 +已存在且由 Server 管理的 Scope。通过 `powercontext scope binding set --cwd ` 或其他宿主脚本绑定一次 checkout,即可在 OpenCode 的各子目录与符号链接路径下生效;在没有自己 workspace binding 的 linked Git worktree 中,主 checkout 的绑定同样会自动回退生效。 Server 启用 Bearer 鉴权时,在运行 setup 时提供其 token: 把完整请求头写入 `POWERCONTEXT_OPENCODE_AUTHORIZATION`,或把 token 写入 `POWERCONTEXT_CLIENT_API_TOKEN`。 diff --git a/docs/zh/docs/integrations/pi.md b/docs/zh/docs/integrations/pi.md index d7baa75289..da23ea6de9 100644 --- a/docs/zh/docs/integrations/pi.md +++ b/docs/zh/docs/integrations/pi.md @@ -45,11 +45,9 @@ Pi 开始 agent turn 前,package 会以默认 8000-byte 预算调用一次 `PO 符合条件的用户提示词会被独立采集为 Content Source。package 不会同步完整 Pi transcript。Server 不可用、超时、 重定向或响应不符合契约时,召回、采集和边界 flush 都会正常降级:Pi 的 prompt 不变,普通工作不会被阻塞。 -package 按 `POWERCONTEXT_PI_SCOPE_ID`、workspace 持久 binding、Server 默认 Scope 的顺序解析一个由 Server +package 按 `POWERCONTEXT_PI_SCOPE_ID`、当前 checkout 的跨宿主 `shared` workspace 绑定(真实 Git 根路径,优先于 Pi 旧目录绑定)、Server 默认 Scope 的顺序解析一个由 Server 管理的 Scope。workspace 路径只会哈希为外部 binding key,不会成为 Scope ID。仅在宿主必须固定到某个已有 -Scope 时设置显式变量。在没有自己 workspace binding 的 linked Git worktree 中, -解析会使用主 checkout 中同一目录的绑定,所以 checkout 的绑定也覆盖它的 linked worktree。这个回退来自 Git 报告的真实路径, -因此只有 checkout 的绑定建立时所用路径不含符号链接,才能匹配。 +Scope 时设置显式变量。通过 `powercontext scope binding set --cwd ` 或其他宿主脚本绑定一次 checkout,即可在 Pi 的各子目录与符号链接路径下生效;在没有自己 workspace binding 的 linked Git worktree 中,主 checkout 的绑定同样会自动回退生效。 启用这些能力后,Pi 已满足仓库定义的 Full 核心接入 profile。 diff --git a/docs/zh/docs/integrations/zcode.md b/docs/zh/docs/integrations/zcode.md index bd1ab4678a..94be39293f 100644 --- a/docs/zh/docs/integrations/zcode.md +++ b/docs/zh/docs/integrations/zcode.md @@ -336,8 +336,8 @@ TLS 握手失败,因此远端端口的直接 HTTPS 接入尚未验收。 `remember_memory`。首次 Handoff 的 `base` 和 `generation` 可以为 `null`,后续工具应原样传递 `PreparedHandoff`,不要省略或编造字段。读取结果标记为 `untrusted_history`,需结合当前项目状态核实。 -Hook 按 `POWERCONTEXT_ZCODE_SCOPE_ID`、当前 session binding、workspace binding、Server 默认 Scope -解析 Scope。workspace 使用 Git 根目录或工作目录的规范化路径哈希作为 binding key;路径本身不是 Scope ID。 +Hook 按 `POWERCONTEXT_ZCODE_SCOPE_ID`、当前 session binding、当前 checkout 的跨宿主 `shared` workspace 绑定(优先于旧的 `zcode` workspace 绑定)、Server 默认 Scope +解析 Scope。workspace 使用 Git 根目录或工作目录的规范化路径哈希作为 binding key;路径本身不是 Scope ID。执行 `bind` 会写入 `shared` 键使本机所有 PowerContext 宿主共用该 Scope,`unbind` 则同时清除 `shared` 键与 ZCode 的旧键。 没有自己 workspace binding 的 linked Git worktree 会使用其主 checkout 的绑定, 所以 checkout 的绑定也覆盖它的 linked worktree。要让 worktree 使用单独的 Scope,在 worktree 内执行绑定; 在那里执行 `bind` 和 `unbind`,只会改动该 worktree 自己的绑定。 diff --git a/integrations/dsh/plugins/powercontext/lib/index.js b/integrations/dsh/plugins/powercontext/lib/index.js index 58432c8f86..4fd3576705 100644 --- a/integrations/dsh/plugins/powercontext/lib/index.js +++ b/integrations/dsh/plugins/powercontext/lib/index.js @@ -20,7 +20,7 @@ import { fileURLToPath, pathToFileURL } from "node:url"; import { homedir } from "node:os"; import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { createHash, randomUUID } from "node:crypto"; -import { execFile } from "node:child_process"; +import { execFile, execFileSync } from "node:child_process"; import { promisify } from "node:util"; import { createServer, request } from "node:http"; import { request as request$1 } from "node:https"; @@ -2616,6 +2616,246 @@ function boundedRecallQuery(prompt) { return characters.slice(start).join("").trim(); } +//#endregion +//#region src/git-worktree.ts +const SHARED_WORKSPACE_INTEGRATION = "shared"; +const GIT_ARGUMENTS = [ + "rev-parse", + "--show-toplevel", + "--path-format=absolute", + "--git-dir", + "--git-common-dir" +]; +const UNKNOWN_FORMAT = "\n--path-format=absolute"; +const BARE_ARGUMENTS = ["rev-parse", "--is-bare-repository"]; +const runGit = promisify(execFile); +/** +* Return the paths whose workspace bindings apply to `directory`, the worktree's own first. +* +* The first path is the one the host has always keyed: with `gitRoot`, the Git top level as Git prints it, or +* `directory` outside a work tree; otherwise `directory` itself. In a linked worktree of a non-bare repository, a +* second path follows from the main worktree: its root with `gitRoot`, otherwise the path at `directory`'s position in +* it. Each host keys both paths the way it keys the first, so the second matches a binding made in the main checkout, +* and resolves them in this order, so the worktree's own binding wins. Binding and clearing use only the first. +* +* A linked worktree's Git directory differs from the common directory, and its main worktree is the parent of the +* common directory when that directory is named `.git` and Git confirms that the repository is not bare. A main +* checkout, including one whose Git directory is separate, gets no second path, and neither do bare repositories, +* including one in a directory named `.git`, and submodules. A linked worktree of a checkout with a separate Git +* directory falls back to the parent of that directory, since Git records no other main worktree. A second path that +* is the same directory as `directory` is left out. Both Git calls together stay within `timeout`. +*/ +/** Normalize Windows extended-length prefixes and drive-letter casing so Python and Node.js hash identical paths. */ +function normalizeWindowsRealPath(value, win32) { + if (!(win32 === void 0 ? process.platform === "win32" : win32)) return value; + let resolved = value; + if (resolved.slice(0, 8).toUpperCase() === "\\\\?\\UNC\\") resolved = "\\\\" + resolved.slice(8); + else if (resolved.slice(0, 4) === "\\\\?\\" && /^[A-Za-z]:/u.test(resolved.slice(4, 6))) resolved = resolved.slice(4); + if (/^[a-z]:/u.test(resolved)) resolved = resolved.slice(0, 1).toUpperCase() + resolved.slice(1); + return resolved; +} +/** Return the canonical real path of `directory` with symbolic links resolved on existing ancestors. */ +function realWorkspacePath(directory) { + const input = isAbsolute(directory) ? directory : process.cwd() + sep + directory; + try { + return normalizeWindowsRealPath(realpathSync.native(input)); + } catch {} + const target = resolve(directory); + let current = target; + const suffix = []; + while (true) { + const parent = dirname(current); + if (parent === current) return normalizeWindowsRealPath(target); + suffix.unshift(basename(current)); + current = parent; + try { + return normalizeWindowsRealPath(join(realpathSync.native(current), ...suffix)); + } catch {} + } +} +/** Return the lowercase hex SHA-256 of the canonical real path of `directory`. */ +function workspaceIdentity(directory) { + return createHash("sha256").update(realWorkspacePath(directory), "utf8").digest("hex"); +} +/** +* Return `[sharedRoot, hostPath]` pairs for `directory` and, in a linked worktree, its main checkout. +* +* `sharedRoot` is always the Git top level inside a work tree, or `directory` outside Git. `hostPath` preserves the +* host's legacy rule from the same Git invocation, and is omitted when the main-checkout counterpart is unavailable or +* links back to `directory`. +*/ +async function workspaceLocations(directory, gitRoot, timeout) { + const deadline = Date.now() + timeout; + const [top = "", gitDir = "", common = ""] = gitPaths(await gitOutput([ + "-C", + directory, + ...GIT_ARGUMENTS + ], timeout)); + const sharedOwn = top || directory; + const hostOwn = gitRoot ? sharedOwn : directory; + const mainRoot = mainWorktreeRoot(top, gitDir, common); + if (mainRoot === void 0) return [[sharedOwn, hostOwn]]; + if ((await gitOutput([ + "-C", + directory, + "--git-dir", + common, + ...BARE_ARGUMENTS + ], deadline - Date.now())).trim() !== "false") return [[sharedOwn, hostOwn]]; + const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot); + return hostMain === void 0 ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]]; +} +/** Return what `workspaceLocations` returns, for hosts whose hooks compute their keys synchronously. */ +function workspaceLocationsSync(directory, gitRoot, timeout) { + const deadline = Date.now() + timeout; + const [top = "", gitDir = "", common = ""] = gitPaths(gitOutputSync([ + "-C", + directory, + ...GIT_ARGUMENTS + ], timeout)); + const sharedOwn = top || directory; + const hostOwn = gitRoot ? sharedOwn : directory; + const mainRoot = mainWorktreeRoot(top, gitDir, common); + if (mainRoot === void 0) return [[sharedOwn, hostOwn]]; + if (gitOutputSync([ + "-C", + directory, + "--git-dir", + common, + ...BARE_ARGUMENTS + ], deadline - Date.now()).trim() !== "false") return [[sharedOwn, hostOwn]]; + const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot); + return hostMain === void 0 ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]]; +} +async function gitOutput(args, timeout) { + if (timeout <= 0) return ""; + try { + return (await runGit("git", args, { + encoding: "utf8", + timeout, + windowsHide: true + })).stdout; + } catch { + return ""; + } +} +function gitOutputSync(args, timeout) { + if (timeout <= 0) return ""; + try { + return execFileSync("git", args, { + encoding: "utf8", + timeout, + windowsHide: true, + stdio: [ + "ignore", + "pipe", + "ignore" + ] + }); + } catch { + return ""; + } +} +function gitPaths(output) { + const lines = output.replace(/\r\n/gu, "\n").replace(/\n+$/u, ""); + const commonSplit = lines.lastIndexOf("\n"); + const rest = commonSplit < 0 ? "" : lines.slice(0, commonSplit); + const gitDirSplit = rest.lastIndexOf("\n"); + const head = gitDirSplit < 0 ? "" : rest.slice(0, gitDirSplit); + if (head.endsWith(UNKNOWN_FORMAT)) return [ + head.slice(0, -23).trim(), + "", + "" + ]; + return [ + head.trim(), + rest.slice(gitDirSplit + 1), + lines.slice(commonSplit + 1) + ]; +} +function mainWorktreeRoot(top, gitDir, common) { + if (!top || !gitDir || !common || !isAbsolute(gitDir) || !isAbsolute(common)) return void 0; + const commonDirectory = realPath(common); + if (realPath(gitDir) === commonDirectory || basename(commonDirectory) !== ".git") return void 0; + const mainRoot = dirname(commonDirectory); + return mainRoot === realPath(top) ? void 0 : mainRoot; +} +function mainWorktreeSubdir(directory, top, mainRoot) { + if (!top) return void 0; + const position = relative(realPath(top), realPath(directory)); + if (position === ".." || position.startsWith(".." + sep) || isAbsolute(position)) return void 0; + const main = join(mainRoot, position); + return realPath(main) === realPath(directory) ? void 0 : main; +} +function realPath(path) { + try { + return realpathSync.native(path); + } catch { + return resolve(path); + } +} + +//#endregion +//#region src/scope.ts +const UNSCOPED_MESSAGE = "PowerContext could not resolve the current Scope."; +const GIT_TIMEOUT_MS = 500; +function sessionCwd(cwd) { + const value = cwd?.trim(); + return value ? value : void 0; +} +function sharedWorkspaceBindingKey(cwd) { + const [sharedRoot = cwd] = workspaceLocationsSync(cwd, false, GIT_TIMEOUT_MS)[0] ?? [cwd]; + return { + integration: SHARED_WORKSPACE_INTEGRATION, + kind: "workspace", + external_id: workspaceIdentity(sharedRoot) + }; +} +function legacyWorkspaceBindingKey(cwd) { + return { + integration: "dsh", + kind: "workspace", + external_id: createHash("sha256").update(resolve(cwd)).digest("hex") + }; +} +function workspaceBindingKey(cwd) { + return sharedWorkspaceBindingKey(cwd); +} +/** Return the workspace keys that resolution tries in order, shared before legacy at both checkout levels. */ +async function workspaceBindingKeys(cwd) { + const keys = []; + for (const [sharedRoot = cwd, hostPath] of await workspaceLocations(cwd, false, GIT_TIMEOUT_MS)) { + keys.push({ + integration: SHARED_WORKSPACE_INTEGRATION, + kind: "workspace", + external_id: workspaceIdentity(sharedRoot) + }); + if (hostPath !== void 0) keys.push(legacyWorkspaceBindingKey(hostPath)); + } + return keys; +} +function formatScopeRouting(scopeId, cwd) { + const workspace = sessionCwd(cwd); + const bindingKey = workspace ? workspaceBindingKey(workspace) : void 0; + return [ + "PowerContext host Scope routing is authoritative for this DSH session.", + `Use exactly this scope_id for every mcp__powercontext__ operation that accepts one: ${JSON.stringify(scopeId)}.`, + bindingKey ? `The workspace binding key already used by the host is ${JSON.stringify(bindingKey)}.` : "No workspace binding key is available for this session.", + "Do not call mcp__powercontext__resolve_scope_binding with allow_default=true to select another Scope.", + "If this routing metadata is unavailable, report the Scope as unavailable instead of guessing an identifier." + ].join("\n"); +} +async function resolveScopeId(client, cwd, configuredScopeId, signal, allowDefault = true) { + const workspace = sessionCwd(cwd); + const value = (await client.request("resolve_scope_binding", { + explicit_scope_id: configuredScopeId, + ...allowDefault ? {} : { allow_default: false }, + binding_keys: workspace ? await workspaceBindingKeys(workspace) : [] + }, signal)).value; + const scopeId = value && typeof value === "object" ? value.scope_id : void 0; + return typeof scopeId === "string" && scopeId.trim() ? scopeId : void 0; +} + //#endregion //#region src/doctor.ts const CORE_OPERATIONS = [ @@ -2949,7 +3189,28 @@ async function diagnoseServer(runtime, cwd, signal, toolCatalog, toolScope) { let scopeId; checks.scope = await probe("resolve_scope_binding", async () => { scopeId = await runtime.resolveScope(cwd, signal); - return scopeId ? check("resolve_scope_binding", "scope_resolved", "The Server resolved the current session Scope.", void 0, "ok") : check("resolve_scope_binding", "unscoped", "Scope resolution returned no usable Scope.", "Check the explicit Scope override, workspace binding and Server default Scope. Doctor does not create bindings."); + if (!scopeId) return check("resolve_scope_binding", "unscoped", "Scope resolution returned no usable Scope.", "Check the explicit Scope override, workspace binding and Server default Scope. Doctor does not create bindings."); + const workspace = sessionCwd(cwd); + let matchedKey = runtime.config.scopeId ? "explicit" : "default"; + if (!runtime.config.scopeId && workspace) for (const candidate of await workspaceBindingKeys(workspace)) try { + const single = await runtime.client.request("resolve_scope_binding", { + explicit_scope_id: void 0, + allow_default: false, + binding_keys: [candidate] + }, signal); + if (record$1(single.value) && typeof single.value.scope_id === "string" ? single.value.scope_id.trim() : "") { + matchedKey = `${candidate.integration}:${candidate.kind}`; + break; + } + } catch (error) { + if (error instanceof ServerResponseError && error.statusCode === 404 && error.code === "scope_not_found") continue; + matchedKey = void 0; + break; + } + return { + ...check("resolve_scope_binding", "scope_resolved", "The Server resolved the current session Scope.", void 0, "ok"), + ...matchedKey ? { matched_key: matchedKey } : {} + }; }); checks.prepare = scopeId ? await probe("prepare_context", async () => { const response = await runtime.client.request("prepare_context", { @@ -3394,143 +3655,6 @@ async function reportDirectFailure(runtime, event, error) { return toToolResult(error); } -//#endregion -//#region src/git-worktree.ts -const GIT_ARGUMENTS = [ - "rev-parse", - "--show-toplevel", - "--path-format=absolute", - "--git-dir", - "--git-common-dir" -]; -const UNKNOWN_FORMAT = "\n--path-format=absolute"; -const BARE_ARGUMENTS = ["rev-parse", "--is-bare-repository"]; -const runGit = promisify(execFile); -/** -* Return the paths whose workspace bindings apply to `directory`, the worktree's own first. -* -* The first path is the one the host has always keyed: with `gitRoot`, the Git top level as Git prints it, or -* `directory` outside a work tree; otherwise `directory` itself. In a linked worktree of a non-bare repository, a -* second path follows from the main worktree: its root with `gitRoot`, otherwise the path at `directory`'s position in -* it. Each host keys both paths the way it keys the first, so the second matches a binding made in the main checkout, -* and resolves them in this order, so the worktree's own binding wins. Binding and clearing use only the first. -* -* A linked worktree's Git directory differs from the common directory, and its main worktree is the parent of the -* common directory when that directory is named `.git` and Git confirms that the repository is not bare. A main -* checkout, including one whose Git directory is separate, gets no second path, and neither do bare repositories, -* including one in a directory named `.git`, and submodules. A linked worktree of a checkout with a separate Git -* directory falls back to the parent of that directory, since Git records no other main worktree. A second path that -* is the same directory as `directory` is left out. Both Git calls together stay within `timeout`. -*/ -async function workspacePaths(directory, gitRoot, timeout) { - const deadline = Date.now() + timeout; - const [top = "", gitDir = "", common = ""] = gitPaths(await gitOutput([ - "-C", - directory, - ...GIT_ARGUMENTS - ], timeout)); - const first = gitRoot && top ? top : directory; - const main = mainPath(directory, top, gitDir, common, gitRoot); - if (main === void 0) return [first]; - return (await gitOutput([ - "-C", - directory, - "--git-dir", - common, - ...BARE_ARGUMENTS - ], deadline - Date.now())).trim() === "false" ? [first, main] : [first]; -} -async function gitOutput(args, timeout) { - if (timeout <= 0) return ""; - try { - return (await runGit("git", args, { - encoding: "utf8", - timeout, - windowsHide: true - })).stdout; - } catch { - return ""; - } -} -function gitPaths(output) { - const lines = output.replace(/\r\n/gu, "\n").replace(/\n+$/u, ""); - const commonSplit = lines.lastIndexOf("\n"); - const rest = commonSplit < 0 ? "" : lines.slice(0, commonSplit); - const gitDirSplit = rest.lastIndexOf("\n"); - const head = gitDirSplit < 0 ? "" : rest.slice(0, gitDirSplit); - if (head.endsWith(UNKNOWN_FORMAT)) return [ - head.slice(0, -23).trim(), - "", - "" - ]; - return [ - head.trim(), - rest.slice(gitDirSplit + 1), - lines.slice(commonSplit + 1) - ]; -} -function mainPath(directory, top, gitDir, common, gitRoot) { - if (!top || !gitDir || !common || !isAbsolute(gitDir) || !isAbsolute(common)) return void 0; - const commonDirectory = realPath(common); - if (realPath(gitDir) === commonDirectory || basename(commonDirectory) !== ".git") return void 0; - const mainRoot = dirname(commonDirectory); - const worktreeRoot = realPath(top); - if (mainRoot === worktreeRoot) return void 0; - if (gitRoot) return mainRoot; - const position = relative(worktreeRoot, realPath(directory)); - if (position === ".." || position.startsWith(".." + sep) || isAbsolute(position)) return void 0; - const main = join(mainRoot, position); - return realPath(main) === realPath(directory) ? void 0 : main; -} -function realPath(path) { - try { - return realpathSync(path); - } catch { - return resolve(path); - } -} - -//#endregion -//#region src/scope.ts -const UNSCOPED_MESSAGE = "PowerContext could not resolve the current Scope."; -const GIT_TIMEOUT_MS = 500; -function sessionCwd(cwd) { - const value = cwd?.trim(); - return value ? value : void 0; -} -function workspaceBindingKey(cwd) { - return { - integration: "dsh", - kind: "workspace", - external_id: createHash("sha256").update(resolve(cwd)).digest("hex") - }; -} -/** Return the workspace keys that resolution tries in order, with a linked worktree's main checkout after its own. */ -async function workspaceBindingKeys(cwd) { - return (await workspacePaths(cwd, false, GIT_TIMEOUT_MS)).map(workspaceBindingKey); -} -function formatScopeRouting(scopeId, cwd) { - const workspace = sessionCwd(cwd); - const bindingKey = workspace ? workspaceBindingKey(workspace) : void 0; - return [ - "PowerContext host Scope routing is authoritative for this DSH session.", - `Use exactly this scope_id for every mcp__powercontext__ operation that accepts one: ${JSON.stringify(scopeId)}.`, - bindingKey ? `The workspace binding key already used by the host is ${JSON.stringify(bindingKey)}.` : "No workspace binding key is available for this session.", - "Do not call mcp__powercontext__resolve_scope_binding with allow_default=true to select another Scope.", - "If this routing metadata is unavailable, report the Scope as unavailable instead of guessing an identifier." - ].join("\n"); -} -async function resolveScopeId(client, cwd, configuredScopeId, signal, allowDefault = true) { - const workspace = sessionCwd(cwd); - const value = (await client.request("resolve_scope_binding", { - explicit_scope_id: configuredScopeId, - ...allowDefault ? {} : { allow_default: false }, - binding_keys: workspace ? await workspaceBindingKeys(workspace) : [] - }, signal)).value; - const scopeId = value && typeof value === "object" ? value.scope_id : void 0; - return typeof scopeId === "string" && scopeId.trim() ? scopeId : void 0; -} - //#endregion //#region src/status.ts const STATUS_SESSION_LIMIT = 64; diff --git a/integrations/dsh/plugins/powercontext/src/doctor.ts b/integrations/dsh/plugins/powercontext/src/doctor.ts index 764c78ee80..31a8000761 100644 --- a/integrations/dsh/plugins/powercontext/src/doctor.ts +++ b/integrations/dsh/plugins/powercontext/src/doctor.ts @@ -23,6 +23,7 @@ import { authenticationRejection, bodyFailureDetails, type BodyFailureDetails, I import type { PluginRuntime } from './invoke.ts' import { OPERATIONS, type OperationId } from './operations.generated.ts' import { PREPARED_CONTEXT_SCHEMA, validatePreparedContext } from './prepared-context.ts' +import { sessionCwd, workspaceBindingKeys } from './scope.ts' export interface DoctorCheck extends BodyFailureDetails { state: 'ok' | 'failed' | 'degraded' | 'skipped' @@ -36,6 +37,7 @@ export interface DoctorCheck extends BodyFailureDetails { dependencies?: Record operations?: string[] tools?: string[] + matched_key?: string } const CORE_OPERATIONS: OperationId[] = [ @@ -361,9 +363,39 @@ export async function diagnoseServer( let scopeId: string | undefined checks.scope = await probe('resolve_scope_binding', async () => { scopeId = await runtime.resolveScope(cwd, signal) - return scopeId ? check('resolve_scope_binding', 'scope_resolved', 'The Server resolved the current session Scope.', undefined, 'ok') - : check('resolve_scope_binding', 'unscoped', 'Scope resolution returned no usable Scope.', + if (!scopeId) { + return check('resolve_scope_binding', 'unscoped', 'Scope resolution returned no usable Scope.', 'Check the explicit Scope override, workspace binding and Server default Scope. Doctor does not create bindings.') + } + const workspace = sessionCwd(cwd) + let matchedKey: string | undefined = runtime.config.scopeId ? 'explicit' : 'default' + if (!runtime.config.scopeId && workspace) { + for (const candidate of await workspaceBindingKeys(workspace)) { + try { + const single = await runtime.client.request('resolve_scope_binding', { + explicit_scope_id: undefined, + allow_default: false, + binding_keys: [candidate], + }, signal) + const singleScope = record(single.value) && typeof single.value.scope_id === 'string' + ? single.value.scope_id.trim() : '' + if (singleScope) { + matchedKey = `${candidate.integration}:${candidate.kind}` + break + } + } catch (error) { + if (error instanceof ServerResponseError && error.statusCode === 404 && error.code === 'scope_not_found') { + continue + } + matchedKey = undefined + break + } + } + } + return { + ...check('resolve_scope_binding', 'scope_resolved', 'The Server resolved the current session Scope.', undefined, 'ok'), + ...(matchedKey ? { matched_key: matchedKey } : {}), + } }) checks.prepare = scopeId ? await probe('prepare_context', async () => { const response = await runtime.client.request('prepare_context', { diff --git a/integrations/dsh/plugins/powercontext/src/git-worktree.ts b/integrations/dsh/plugins/powercontext/src/git-worktree.ts index bd2ac88460..a39ee55956 100644 --- a/integrations/dsh/plugins/powercontext/src/git-worktree.ts +++ b/integrations/dsh/plugins/powercontext/src/git-worktree.ts @@ -18,10 +18,13 @@ // Edit the source and run `make integration-lifecycle` instead. import { execFile, execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' import { realpathSync } from 'node:fs' import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { promisify } from 'node:util' +export const SHARED_WORKSPACE_INTEGRATION = 'shared' + // Find the paths whose workspace bindings apply to a directory, so a linked Git worktree falls back to its checkout. // src/powercontext_integration_lifecycle/git_worktree.py applies the same rule for the Python hosts. // @@ -50,26 +53,102 @@ const runGit = promisify(execFile) * directory falls back to the parent of that directory, since Git records no other main worktree. A second path that * is the same directory as `directory` is left out. Both Git calls together stay within `timeout`. */ -export async function workspacePaths(directory: string, gitRoot: boolean, timeout: number): Promise { +/** Normalize Windows extended-length prefixes and drive-letter casing so Python and Node.js hash identical paths. */ +export function normalizeWindowsRealPath(value: string, win32?: boolean): string { + const active = win32 === undefined ? process.platform === 'win32' : win32 + if (!active) return value + let resolved = value + if (resolved.slice(0, 8).toUpperCase() === '\\\\?\\UNC\\') { + resolved = '\\\\' + resolved.slice(8) + } else if (resolved.slice(0, 4) === '\\\\?\\' && /^[A-Za-z]:/u.test(resolved.slice(4, 6))) { + resolved = resolved.slice(4) + } + if (/^[a-z]:/u.test(resolved)) { + resolved = resolved.slice(0, 1).toUpperCase() + resolved.slice(1) + } + return resolved +} + +/** Return the canonical real path of `directory` with symbolic links resolved on existing ancestors. */ +export function realWorkspacePath(directory: string): string { + const input = isAbsolute(directory) ? directory : process.cwd() + sep + directory + try { + return normalizeWindowsRealPath(realpathSync.native(input)) + } catch { + // Resolve symbolic links on the deepest existing ancestor, matching Python's os.path.realpath. + } + const target = resolve(directory) + let current = target + const suffix = [] + while (true) { + const parent = dirname(current) + if (parent === current) return normalizeWindowsRealPath(target) + suffix.unshift(basename(current)) + current = parent + try { + const resolvedAncestor = realpathSync.native(current) + return normalizeWindowsRealPath(join(resolvedAncestor, ...suffix)) + } catch { + // Keep walking up until an existing directory is found. + } + } +} + +/** Return the lowercase hex SHA-256 of the canonical real path of `directory`. */ +export function workspaceIdentity(directory: string): string { + return createHash('sha256').update(realWorkspacePath(directory), 'utf8').digest('hex') +} + +/** + * Return `[sharedRoot, hostPath]` pairs for `directory` and, in a linked worktree, its main checkout. + * + * `sharedRoot` is always the Git top level inside a work tree, or `directory` outside Git. `hostPath` preserves the + * host's legacy rule from the same Git invocation, and is omitted when the main-checkout counterpart is unavailable or + * links back to `directory`. + */ +export async function workspaceLocations(directory: string, gitRoot: boolean, timeout: number): Promise { const deadline = Date.now() + timeout const [top = '', gitDir = '', common = ''] = gitPaths(await gitOutput(['-C', directory, ...GIT_ARGUMENTS], timeout)) - const first = gitRoot && top ? top : directory - const main = mainPath(directory, top, gitDir, common, gitRoot) - if (main === undefined) return [first] + const sharedOwn = top || directory + const hostOwn = gitRoot ? sharedOwn : directory + const mainRoot = mainWorktreeRoot(top, gitDir, common) + if (mainRoot === undefined) return [[sharedOwn, hostOwn]] // An unknown answer leaves the second path out, as for a bare repository. const bare = await gitOutput(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) - return bare.trim() === 'false' ? [first, main] : [first] + if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] + const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) + return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] } -/** Return what `workspacePaths` returns, for hosts whose hooks compute their keys synchronously. */ -export function workspacePathsSync(directory: string, gitRoot: boolean, timeout: number): string[] { +/** Return what `workspaceLocations` returns, for hosts whose hooks compute their keys synchronously. */ +export function workspaceLocationsSync(directory: string, gitRoot: boolean, timeout: number): string[][] { const deadline = Date.now() + timeout const [top = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(['-C', directory, ...GIT_ARGUMENTS], timeout)) - const first = gitRoot && top ? top : directory - const main = mainPath(directory, top, gitDir, common, gitRoot) - if (main === undefined) return [first] + const sharedOwn = top || directory + const hostOwn = gitRoot ? sharedOwn : directory + const mainRoot = mainWorktreeRoot(top, gitDir, common) + if (mainRoot === undefined) return [[sharedOwn, hostOwn]] const bare = gitOutputSync(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) - return bare.trim() === 'false' ? [first, main] : [first] + if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] + const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) + return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] +} + +export async function workspacePaths(directory: string, gitRoot: boolean, timeout: number): Promise { + const result = [] + for (const [, hostPath] of await workspaceLocations(directory, gitRoot, timeout)) { + if (hostPath !== undefined) result.push(hostPath) + } + return result +} + +/** Return what `workspacePaths` returns, for hosts whose hooks compute their keys synchronously. */ +export function workspacePathsSync(directory: string, gitRoot: boolean, timeout: number): string[] { + const result = [] + for (const [, hostPath] of workspaceLocationsSync(directory, gitRoot, timeout)) { + if (hostPath !== undefined) result.push(hostPath) + } + return result } // Return what Git prints, or an empty string when it fails or time is up. @@ -104,14 +183,18 @@ function gitPaths(output: string): string[] { return [head.trim(), rest.slice(gitDirSplit + 1), lines.slice(commonSplit + 1)] } -function mainPath(directory: string, top: string, gitDir: string, common: string, gitRoot: boolean): string | undefined { +function mainWorktreeRoot(top: string, gitDir: string, common: string): string | undefined { if (!top || !gitDir || !common || !isAbsolute(gitDir) || !isAbsolute(common)) return undefined const commonDirectory = realPath(common) if (realPath(gitDir) === commonDirectory || basename(commonDirectory) !== '.git') return undefined const mainRoot = dirname(commonDirectory) const worktreeRoot = realPath(top) - if (mainRoot === worktreeRoot) return undefined - if (gitRoot) return mainRoot + return mainRoot === worktreeRoot ? undefined : mainRoot +} + +function mainWorktreeSubdir(directory: string, top: string, mainRoot: string): string | undefined { + if (!top) return undefined + const worktreeRoot = realPath(top) const position = relative(worktreeRoot, realPath(directory)) if (position === '..' || position.startsWith('..' + sep) || isAbsolute(position)) return undefined const main = join(mainRoot, position) @@ -121,7 +204,7 @@ function mainPath(directory: string, top: string, gitDir: string, common: string function realPath(path: string): string { try { - return realpathSync(path) + return realpathSync.native(path) } catch { return resolve(path) } diff --git a/integrations/dsh/plugins/powercontext/src/scope.ts b/integrations/dsh/plugins/powercontext/src/scope.ts index 1c2fdaa3e3..8e82f4e233 100644 --- a/integrations/dsh/plugins/powercontext/src/scope.ts +++ b/integrations/dsh/plugins/powercontext/src/scope.ts @@ -17,19 +17,33 @@ import { createHash } from 'node:crypto' import { resolve } from 'node:path' import type { PowerContextClient } from './client.ts' -import { workspacePaths } from './git-worktree.ts' +import { + SHARED_WORKSPACE_INTEGRATION, + workspaceIdentity, + workspaceLocations, + workspaceLocationsSync, +} from './git-worktree.ts' export const UNSCOPED_MESSAGE = 'PowerContext could not resolve the current Scope.' const GIT_TIMEOUT_MS = 500 -type ScopeBindingKey = { integration: string; kind: string; external_id: string } +export type ScopeBindingKey = { integration: string; kind: string; external_id: string } export function sessionCwd(cwd: string | undefined): string | undefined { const value = cwd?.trim() return value ? value : undefined } -export function workspaceBindingKey(cwd: string): ScopeBindingKey { +export function sharedWorkspaceBindingKey(cwd: string): ScopeBindingKey { + const [sharedRoot = cwd] = workspaceLocationsSync(cwd, false, GIT_TIMEOUT_MS)[0] ?? [cwd] + return { + integration: SHARED_WORKSPACE_INTEGRATION, + kind: 'workspace', + external_id: workspaceIdentity(sharedRoot), + } +} + +export function legacyWorkspaceBindingKey(cwd: string): ScopeBindingKey { return { integration: 'dsh', kind: 'workspace', @@ -37,9 +51,22 @@ export function workspaceBindingKey(cwd: string): ScopeBindingKey { } } -/** Return the workspace keys that resolution tries in order, with a linked worktree's main checkout after its own. */ +export function workspaceBindingKey(cwd: string): ScopeBindingKey { + return sharedWorkspaceBindingKey(cwd) +} + +/** Return the workspace keys that resolution tries in order, shared before legacy at both checkout levels. */ export async function workspaceBindingKeys(cwd: string): Promise { - return (await workspacePaths(cwd, false, GIT_TIMEOUT_MS)).map(workspaceBindingKey) + const keys: ScopeBindingKey[] = [] + for (const [sharedRoot = cwd, hostPath] of await workspaceLocations(cwd, false, GIT_TIMEOUT_MS)) { + keys.push({ + integration: SHARED_WORKSPACE_INTEGRATION, + kind: 'workspace', + external_id: workspaceIdentity(sharedRoot), + }) + if (hostPath !== undefined) keys.push(legacyWorkspaceBindingKey(hostPath)) + } + return keys } export function formatScopeRouting(scopeId: string, cwd?: string): string { diff --git a/integrations/dsh/plugins/powercontext/tests/scope.spec.ts b/integrations/dsh/plugins/powercontext/tests/scope.spec.ts index 4692ece264..a95be0e677 100644 --- a/integrations/dsh/plugins/powercontext/tests/scope.spec.ts +++ b/integrations/dsh/plugins/powercontext/tests/scope.spec.ts @@ -22,7 +22,7 @@ import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' import { formatScopeRouting, resolveScopeId } from '../src/scope.ts' -type BindingInput = { binding_keys: { external_id: string }[] } +type BindingInput = { binding_keys: { integration: string; kind: string; external_id: string }[] } // A checkout and a linked worktree of it, each with the same subdirectory, under a real temporary directory. function gitLayout(): { root: string; checkout: string; worktree: string } { @@ -60,8 +60,9 @@ describe('Scope binding', () => { const [operation, input] = request.mock.calls[0] expect(operation).toBe('resolve_scope_binding') expect(input.explicit_scope_id).toBe('explicit-scope') - expect(input.binding_keys).toHaveLength(1) - expect(input.binding_keys[0]).toMatchObject({ integration: 'dsh', kind: 'workspace' }) + expect(input.binding_keys).toHaveLength(2) + expect(input.binding_keys[0]).toMatchObject({ integration: 'shared', kind: 'workspace' }) + expect(input.binding_keys[1]).toMatchObject({ integration: 'dsh', kind: 'workspace' }) expect(input.binding_keys[0].external_id).not.toContain('/workspace') }) @@ -85,22 +86,28 @@ describe('Scope binding', () => { try { const checkoutSub = join(checkout, 'sub') const worktreeSub = join(worktree, 'sub') - const bindings = new Map([[pathHash(checkoutSub), 'checkout-scope']]) + const keyOf = (integration: string, id: string) => `${integration}:${id}` + const bindings = new Map([[keyOf('dsh', pathHash(checkoutSub)), 'checkout-scope']]) const request = vi.fn(async (_operation: string, input: BindingInput) => ({ - value: { scope_id: input.binding_keys.map(key => bindings.get(key.external_id)).find(Boolean) ?? 'default' }, + value: { + scope_id: input.binding_keys.map(key => bindings.get(keyOf(key.integration, key.external_id))).find(Boolean) ?? 'default', + }, })) const resolveIn = (cwd: string) => resolveScopeId({ request } as never, cwd) await expect(resolveIn(worktreeSub)).resolves.toBe('checkout-scope') - // The first key is still the hash of path.resolve(cwd), so bindings made before keep matching. expect(request.mock.calls[0]?.[1].binding_keys).toEqual([ + { integration: 'shared', kind: 'workspace', external_id: pathHash(worktree) }, { integration: 'dsh', kind: 'workspace', external_id: pathHash(worktreeSub) }, + { integration: 'shared', kind: 'workspace', external_id: pathHash(checkout) }, { integration: 'dsh', kind: 'workspace', external_id: pathHash(checkoutSub) }, ]) - bindings.set(pathHash(worktreeSub), 'worktree-scope') + bindings.set(keyOf('dsh', pathHash(worktreeSub)), 'worktree-scope') await expect(resolveIn(worktreeSub)).resolves.toBe('worktree-scope') + bindings.set(keyOf('shared', pathHash(worktree)), 'shared-worktree-scope') + await expect(resolveIn(worktreeSub)).resolves.toBe('shared-worktree-scope') await expect(resolveIn(checkoutSub)).resolves.toBe('checkout-scope') - expect(request.mock.calls.at(-1)?.[1].binding_keys).toHaveLength(1) + expect(request.mock.calls.at(-1)?.[1].binding_keys).toHaveLength(2) } finally { rmSync(root, { recursive: true, force: true }) } @@ -117,6 +124,7 @@ describe('Scope binding', () => { const request = vi.fn().mockResolvedValue({ value: { scope_id: 'default' } }) await resolveScopeId({ request } as never, checkout) expect(request.mock.calls[0]?.[1].binding_keys).toEqual([ + { integration: 'shared', kind: 'workspace', external_id: pathHash(checkout) }, { integration: 'dsh', kind: 'workspace', external_id: pathHash(checkout) }, ]) } finally { diff --git a/integrations/kimi-code/plugins/powercontext/scripts/doctor.mjs b/integrations/kimi-code/plugins/powercontext/scripts/doctor.mjs index 030465cbb6..03eaa0823b 100644 --- a/integrations/kimi-code/plugins/powercontext/scripts/doctor.mjs +++ b/integrations/kimi-code/plugins/powercontext/scripts/doctor.mjs @@ -14,7 +14,7 @@ * limitations under the License. */ -import { Failure, loadSettings, profileTools, request, resolveScope } from '../shared/runtime.mjs' +import { Failure, isScopeId, loadSettings, profileTools, request, resolveScope, workspaceKeys } from '../shared/runtime.mjs' import { discoverTools } from '../shared/mcp.mjs' import { parseArgs } from 'node:util' import { queryObservations } from '../shared/observations.mjs' @@ -42,8 +42,26 @@ if (settings) { } catch (error) { checks.server = result(error) } try { const scopeId = await resolveScope(settings, AbortSignal.timeout(1500), input) + let matchedKey = settings.scopeId ? 'explicit' : 'default' + if (!settings.scopeId) { + for (const candidate of workspaceKeys(input.cwd)) { + try { + const { status, value } = await request(settings, 'POST', '/v1/scope-bindings/resolve', + { explicit_scope_id: null, binding_keys: [candidate], allow_default: false }, AbortSignal.timeout(1500)) + if (status === 200 && isScopeId(value.scope_id)) { + matchedKey = `${candidate.integration}:${candidate.kind}` + break + } + } catch (error) { + if (error.httpStatus === 404) continue + matchedKey = undefined + break + } + } + } checks.scope = { status: 'ok', detail: 'Current Scope is accessible.', - checks: { scope_id: scopeId, selection: settings.scopeId ? 'explicit' : 'workspace_or_default' } } + checks: { scope_id: scopeId, selection: settings.scopeId ? 'explicit' : 'workspace_or_default', + ...(matchedKey ? { matched_key: matchedKey } : {}) } } } catch (error) { checks.scope = result(error) } if (values.mcp) { try { checks.mcp_discovery = await discoverTools(settings, profileTools(settings.profile)) } diff --git a/integrations/kimi-code/plugins/powercontext/scripts/scope.mjs b/integrations/kimi-code/plugins/powercontext/scripts/scope.mjs index 9e37b71886..e9305f409d 100644 --- a/integrations/kimi-code/plugins/powercontext/scripts/scope.mjs +++ b/integrations/kimi-code/plugins/powercontext/scripts/scope.mjs @@ -15,7 +15,7 @@ */ import { parseArgs } from 'node:util' -import { Failure, isScopeId, loadSettings, request, resolveScope, workspaceKey } from '../shared/runtime.mjs' +import { Failure, isScopeId, legacyWorkspaceKey, loadSettings, request, resolveScope, workspaceKey } from '../shared/runtime.mjs' const schema = 'powercontext.kimi-code.scope-result.v1' let binding @@ -33,23 +33,28 @@ try { const signal = AbortSignal.timeout(4000) if (action !== 'resolve') { const key = workspaceKey(input.cwd) + const keys = action === 'bind' ? [key] : [key, legacyWorkspaceKey(input.cwd)] binding = { action, status: 'unknown' } - let response - try { - response = await request(settings, action === 'bind' ? 'PUT' : 'POST', - action === 'bind' ? '/v1/scope-bindings' : '/v1/scope-bindings/clear', - { key, ...(action === 'bind' ? { scope_id: target } : {}) }, signal) - } catch (error) { - if (error.httpStatus >= 400 && error.httpStatus < 500) binding.status = 'rejected' - else if (error instanceof Failure && !error.requestSent) binding.status = 'not_sent' - throw error + let clearedAny = false + for (const currentKey of keys) { + let response + try { + response = await request(settings, action === 'bind' ? 'PUT' : 'POST', + action === 'bind' ? '/v1/scope-bindings' : '/v1/scope-bindings/clear', + { key: currentKey, ...(action === 'bind' ? { scope_id: target } : {}) }, signal) + } catch (error) { + if (error.httpStatus >= 400 && error.httpStatus < 500) binding.status = 'rejected' + else if (error instanceof Failure && !error.requestSent) binding.status = 'not_sent' + throw error + } + const { status, value } = response + if (status !== 200 || (action === 'bind' ? value.scope_id !== target || !value.key || + Object.entries(currentKey).some(([name, expected]) => value.key[name] !== expected) : + typeof value.cleared !== 'boolean')) throw new Failure('binding_not_confirmed') + if (action !== 'bind') clearedAny = clearedAny || value.cleared } - const { status, value } = response - if (status !== 200 || (action === 'bind' ? value.scope_id !== target || !value.key || - Object.entries(key).some(([name, expected]) => value.key[name] !== expected) : - typeof value.cleared !== 'boolean')) throw new Failure('binding_not_confirmed') binding = action === 'bind' ? { action, status: 'saved', scope_id: target } : - { action, status: value.cleared ? 'cleared' : 'absent', cleared: value.cleared } + { action, status: clearedAny ? 'cleared' : 'absent', cleared: clearedAny } } const scopeId = await resolveScope(settings, signal, input) console.log(JSON.stringify({ schema, status: 'resolved', scope_id: scopeId, diff --git a/integrations/kimi-code/plugins/powercontext/shared/git-worktree.mjs b/integrations/kimi-code/plugins/powercontext/shared/git-worktree.mjs index 4975e5293a..6b5e9d5259 100644 --- a/integrations/kimi-code/plugins/powercontext/shared/git-worktree.mjs +++ b/integrations/kimi-code/plugins/powercontext/shared/git-worktree.mjs @@ -18,10 +18,13 @@ // Edit the source and run `make integration-lifecycle` instead. import { execFile, execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' import { realpathSync } from 'node:fs' import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { promisify } from 'node:util' +export const SHARED_WORKSPACE_INTEGRATION = 'shared' + // Find the paths whose workspace bindings apply to a directory, so a linked Git worktree falls back to its checkout. // src/powercontext_integration_lifecycle/git_worktree.py applies the same rule for the Python hosts. // @@ -50,26 +53,102 @@ const runGit = promisify(execFile) * directory falls back to the parent of that directory, since Git records no other main worktree. A second path that * is the same directory as `directory` is left out. Both Git calls together stay within `timeout`. */ -export async function workspacePaths(directory, gitRoot, timeout) { +/** Normalize Windows extended-length prefixes and drive-letter casing so Python and Node.js hash identical paths. */ +export function normalizeWindowsRealPath(value, win32) { + const active = win32 === undefined ? process.platform === 'win32' : win32 + if (!active) return value + let resolved = value + if (resolved.slice(0, 8).toUpperCase() === '\\\\?\\UNC\\') { + resolved = '\\\\' + resolved.slice(8) + } else if (resolved.slice(0, 4) === '\\\\?\\' && /^[A-Za-z]:/u.test(resolved.slice(4, 6))) { + resolved = resolved.slice(4) + } + if (/^[a-z]:/u.test(resolved)) { + resolved = resolved.slice(0, 1).toUpperCase() + resolved.slice(1) + } + return resolved +} + +/** Return the canonical real path of `directory` with symbolic links resolved on existing ancestors. */ +export function realWorkspacePath(directory) { + const input = isAbsolute(directory) ? directory : process.cwd() + sep + directory + try { + return normalizeWindowsRealPath(realpathSync.native(input)) + } catch { + // Resolve symbolic links on the deepest existing ancestor, matching Python's os.path.realpath. + } + const target = resolve(directory) + let current = target + const suffix = [] + while (true) { + const parent = dirname(current) + if (parent === current) return normalizeWindowsRealPath(target) + suffix.unshift(basename(current)) + current = parent + try { + const resolvedAncestor = realpathSync.native(current) + return normalizeWindowsRealPath(join(resolvedAncestor, ...suffix)) + } catch { + // Keep walking up until an existing directory is found. + } + } +} + +/** Return the lowercase hex SHA-256 of the canonical real path of `directory`. */ +export function workspaceIdentity(directory) { + return createHash('sha256').update(realWorkspacePath(directory), 'utf8').digest('hex') +} + +/** + * Return `[sharedRoot, hostPath]` pairs for `directory` and, in a linked worktree, its main checkout. + * + * `sharedRoot` is always the Git top level inside a work tree, or `directory` outside Git. `hostPath` preserves the + * host's legacy rule from the same Git invocation, and is omitted when the main-checkout counterpart is unavailable or + * links back to `directory`. + */ +export async function workspaceLocations(directory, gitRoot, timeout) { const deadline = Date.now() + timeout const [top = '', gitDir = '', common = ''] = gitPaths(await gitOutput(['-C', directory, ...GIT_ARGUMENTS], timeout)) - const first = gitRoot && top ? top : directory - const main = mainPath(directory, top, gitDir, common, gitRoot) - if (main === undefined) return [first] + const sharedOwn = top || directory + const hostOwn = gitRoot ? sharedOwn : directory + const mainRoot = mainWorktreeRoot(top, gitDir, common) + if (mainRoot === undefined) return [[sharedOwn, hostOwn]] // An unknown answer leaves the second path out, as for a bare repository. const bare = await gitOutput(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) - return bare.trim() === 'false' ? [first, main] : [first] + if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] + const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) + return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] } -/** Return what `workspacePaths` returns, for hosts whose hooks compute their keys synchronously. */ -export function workspacePathsSync(directory, gitRoot, timeout) { +/** Return what `workspaceLocations` returns, for hosts whose hooks compute their keys synchronously. */ +export function workspaceLocationsSync(directory, gitRoot, timeout) { const deadline = Date.now() + timeout const [top = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(['-C', directory, ...GIT_ARGUMENTS], timeout)) - const first = gitRoot && top ? top : directory - const main = mainPath(directory, top, gitDir, common, gitRoot) - if (main === undefined) return [first] + const sharedOwn = top || directory + const hostOwn = gitRoot ? sharedOwn : directory + const mainRoot = mainWorktreeRoot(top, gitDir, common) + if (mainRoot === undefined) return [[sharedOwn, hostOwn]] const bare = gitOutputSync(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) - return bare.trim() === 'false' ? [first, main] : [first] + if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] + const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) + return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] +} + +export async function workspacePaths(directory, gitRoot, timeout) { + const result = [] + for (const [, hostPath] of await workspaceLocations(directory, gitRoot, timeout)) { + if (hostPath !== undefined) result.push(hostPath) + } + return result +} + +/** Return what `workspacePaths` returns, for hosts whose hooks compute their keys synchronously. */ +export function workspacePathsSync(directory, gitRoot, timeout) { + const result = [] + for (const [, hostPath] of workspaceLocationsSync(directory, gitRoot, timeout)) { + if (hostPath !== undefined) result.push(hostPath) + } + return result } // Return what Git prints, or an empty string when it fails or time is up. @@ -104,14 +183,18 @@ function gitPaths(output) { return [head.trim(), rest.slice(gitDirSplit + 1), lines.slice(commonSplit + 1)] } -function mainPath(directory, top, gitDir, common, gitRoot) { +function mainWorktreeRoot(top, gitDir, common) { if (!top || !gitDir || !common || !isAbsolute(gitDir) || !isAbsolute(common)) return undefined const commonDirectory = realPath(common) if (realPath(gitDir) === commonDirectory || basename(commonDirectory) !== '.git') return undefined const mainRoot = dirname(commonDirectory) const worktreeRoot = realPath(top) - if (mainRoot === worktreeRoot) return undefined - if (gitRoot) return mainRoot + return mainRoot === worktreeRoot ? undefined : mainRoot +} + +function mainWorktreeSubdir(directory, top, mainRoot) { + if (!top) return undefined + const worktreeRoot = realPath(top) const position = relative(worktreeRoot, realPath(directory)) if (position === '..' || position.startsWith('..' + sep) || isAbsolute(position)) return undefined const main = join(mainRoot, position) @@ -121,7 +204,7 @@ function mainPath(directory, top, gitDir, common, gitRoot) { function realPath(path) { try { - return realpathSync(path) + return realpathSync.native(path) } catch { return resolve(path) } diff --git a/integrations/kimi-code/plugins/powercontext/shared/runtime.mjs b/integrations/kimi-code/plugins/powercontext/shared/runtime.mjs index 0de1ad4840..5c27d322b8 100644 --- a/integrations/kimi-code/plugins/powercontext/shared/runtime.mjs +++ b/integrations/kimi-code/plugins/powercontext/shared/runtime.mjs @@ -19,7 +19,11 @@ import { createHash } from 'node:crypto' import { isAbsolute, resolve } from 'node:path' import { isIP } from 'node:net' import { fileURLToPath } from 'node:url' -import { workspacePathsSync } from './git-worktree.mjs' +import { + SHARED_WORKSPACE_INTEGRATION, + workspaceIdentity, + workspaceLocationsSync, +} from './git-worktree.mjs' export const MAX_CONTEXT_BYTES = 8000 export const TOKEN_ENV = 'POWERCONTEXT_KIMI_TOKEN' @@ -120,18 +124,35 @@ export function isScopeId(value) { return typeof value === 'string' && [...value].length <= 256 && /[^\p{White_Space}\u001c-\u001f]/u.test(value) } -export function workspaceKey(cwd) { +function requireAbsoluteWorkspace(cwd) { if (typeof cwd !== 'string' || !isAbsolute(cwd)) throw new Failure('workspace_required') +} + +export function legacyWorkspaceKey(cwd) { + requireAbsoluteWorkspace(cwd) let directory try { directory = realpathSync.native(cwd) } catch { directory = resolve(cwd) } return { integration: 'kimi-code', kind: 'workspace', external_id: createHash('sha256').update(directory).digest('hex') } } -// Resolution tries the workspace's own key, then, in a linked Git worktree, the same directory's in the main checkout. -// Binding and clearing write only workspaceKey. +export function workspaceKey(cwd) { + requireAbsoluteWorkspace(cwd) + const [sharedRoot = cwd] = workspaceLocationsSync(cwd, false, GIT_TIMEOUT_MS)[0] ?? [cwd] + return { integration: SHARED_WORKSPACE_INTEGRATION, kind: 'workspace', + external_id: workspaceIdentity(sharedRoot) } +} + +// Resolution tries shared before Kimi's legacy key at both the checkout and, in a linked worktree, its main checkout. +// Binding writes only workspaceKey (shared); clearing removes both workspaceKey and legacyWorkspaceKey. export function workspaceKeys(cwd) { - return [workspaceKey(cwd), ...workspacePathsSync(cwd, false, GIT_TIMEOUT_MS).slice(1).map(workspaceKey)] + requireAbsoluteWorkspace(cwd) + const keys = [] + for (const [sharedRoot = cwd, hostPath] of workspaceLocationsSync(cwd, false, GIT_TIMEOUT_MS)) { + keys.push({ integration: SHARED_WORKSPACE_INTEGRATION, kind: 'workspace', external_id: workspaceIdentity(sharedRoot) }) + if (hostPath !== undefined) keys.push(legacyWorkspaceKey(hostPath)) + } + return keys } export async function resolveScope(settings, signal, input = {}) { diff --git a/integrations/kimi-code/plugins/powercontext/tests/plugin.test.mjs b/integrations/kimi-code/plugins/powercontext/tests/plugin.test.mjs index 299810a07b..c97d4bb8fa 100644 --- a/integrations/kimi-code/plugins/powercontext/tests/plugin.test.mjs +++ b/integrations/kimi-code/plugins/powercontext/tests/plugin.test.mjs @@ -591,34 +591,48 @@ async function gitLayout(parent) { await git('-C', checkout, 'worktree', 'add', '-q', worktree) await mkdir(join(checkout, 'sub')) await mkdir(join(worktree, 'sub')) - return { checkout: join(checkout, 'sub'), worktree: join(worktree, 'sub') } + return { checkoutRoot: checkout, worktreeRoot: worktree, checkout: join(checkout, 'sub'), worktree: join(worktree, 'sub') } } test('a linked Git worktree uses its checkout binding until it binds its own', async t => { const bindings = new Map() + const keyOf = key => `${key.integration}:${key.external_id}` function reply(res, value) { res.writeHead(200); res.end(JSON.stringify(value)) } const f = await fixture(t, { - '/v1/scope-bindings': (_req, res, body) => { bindings.set(body.key.external_id, body.scope_id); reply(res, body) }, - '/v1/scope-bindings/clear': (_req, res, body) => reply(res, { cleared: bindings.delete(body.key.external_id) }), - '/v1/scope-bindings/resolve': (_req, res, body) => reply(res, { scope_id: body.explicit_scope_id ?? - body.binding_keys.map(key => bindings.get(key.external_id)).find(Boolean) ?? 'scope-default' }), + '/v1/scope-bindings': (_req, res, body) => { bindings.set(keyOf(body.key), body.scope_id); reply(res, body) }, + '/v1/scope-bindings/clear': (_req, res, body) => reply(res, { cleared: bindings.delete(keyOf(body.key)) }), + '/v1/scope-bindings/resolve': (_req, res, body) => { + const scopeId = body.explicit_scope_id ?? body.binding_keys.map(key => bindings.get(keyOf(key))).find(Boolean) + if (!scopeId && body.allow_default === false) { res.writeHead(404); res.end('{"error":{"code":"scope_not_found"}}'); return } + reply(res, { scope_id: scopeId ?? 'scope-default' }) + }, }, { scope_id: null }) - const { checkout, worktree } = await gitLayout(join(f.workspace, '..', 'git')) + const { checkoutRoot, worktreeRoot, checkout, worktree } = await gitLayout(join(f.workspace, '..', 'git')) const hash = path => createHash('sha256').update(path).digest('hex') + bindings.set(`kimi-code:${hash(checkout)}`, 'legacy-checkout-scope') + assert.equal((await f.scope('resolve', undefined, worktree)).scope_id, 'legacy-checkout-scope') + assert.equal((await f.doctor(worktree)).checks.scope.checks.matched_key, 'kimi-code:workspace') assert.equal((await f.scope('bind', 'scope-checkout', checkout)).binding.status, 'saved') assert.equal((await f.scope('resolve', undefined, worktree)).scope_id, 'scope-checkout') + assert.equal((await f.doctor(worktree)).checks.scope.checks.matched_key, 'shared:workspace') const result = await f.invoke({ cwd: worktree, session_id: 'session-test', hook_event_name: 'UserPromptSubmit', prompt }) assert.equal(result.stderr, '') assert.equal(f.captures.at(-1).scope_id, 'scope-checkout') - // The first key is still the hash of the real working directory, so bindings made before keep matching. const resolved = f.requests.filter(item => item.path === '/v1/scope-bindings/resolve').at(-1) - assert.deepEqual(resolved.body.binding_keys.map(key => key.external_id), [hash(worktree), hash(checkout)]) + assert.deepEqual(resolved.body.binding_keys, [ + { integration: 'shared', kind: 'workspace', external_id: hash(worktreeRoot) }, + { integration: 'kimi-code', kind: 'workspace', external_id: hash(worktree) }, + { integration: 'shared', kind: 'workspace', external_id: hash(checkoutRoot) }, + { integration: 'kimi-code', kind: 'workspace', external_id: hash(checkout) }, + ]) assert.equal((await f.scope('bind', 'scope-worktree', worktree)).binding.status, 'saved') assert.equal((await f.scope('resolve', undefined, worktree)).scope_id, 'scope-worktree') assert.equal((await f.scope('resolve', undefined, checkout)).scope_id, 'scope-checkout') assert.equal((await f.scope('unbind', undefined, worktree)).binding.status, 'cleared') assert.equal((await f.scope('resolve', undefined, worktree)).scope_id, 'scope-checkout') assert.equal((await f.scope('resolve', undefined, checkout)).scope_id, 'scope-checkout') + assert.equal((await f.scope('unbind', undefined, checkout)).binding.status, 'cleared') + assert.equal((await f.scope('resolve', undefined, checkout)).scope_id, 'scope-default') }) test('a confirmed binding survives later resolution failure and failed resolution never captures', async t => { diff --git a/integrations/lifecycle/git-worktree.ts b/integrations/lifecycle/git-worktree.ts index 3a27935880..8dadd64803 100644 --- a/integrations/lifecycle/git-worktree.ts +++ b/integrations/lifecycle/git-worktree.ts @@ -15,10 +15,13 @@ */ import { execFile, execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' import { realpathSync } from 'node:fs' import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { promisify } from 'node:util' +export const SHARED_WORKSPACE_INTEGRATION = 'shared' + // Find the paths whose workspace bindings apply to a directory, so a linked Git worktree falls back to its checkout. // src/powercontext_integration_lifecycle/git_worktree.py applies the same rule for the Python hosts. // @@ -47,26 +50,102 @@ const runGit = promisify(execFile) * directory falls back to the parent of that directory, since Git records no other main worktree. A second path that * is the same directory as `directory` is left out. Both Git calls together stay within `timeout`. */ -export async function workspacePaths(directory: string, gitRoot: boolean, timeout: number): Promise { +/** Normalize Windows extended-length prefixes and drive-letter casing so Python and Node.js hash identical paths. */ +export function normalizeWindowsRealPath(value: string, win32?: boolean): string { + const active = win32 === undefined ? process.platform === 'win32' : win32 + if (!active) return value + let resolved = value + if (resolved.slice(0, 8).toUpperCase() === '\\\\?\\UNC\\') { + resolved = '\\\\' + resolved.slice(8) + } else if (resolved.slice(0, 4) === '\\\\?\\' && /^[A-Za-z]:/u.test(resolved.slice(4, 6))) { + resolved = resolved.slice(4) + } + if (/^[a-z]:/u.test(resolved)) { + resolved = resolved.slice(0, 1).toUpperCase() + resolved.slice(1) + } + return resolved +} + +/** Return the canonical real path of `directory` with symbolic links resolved on existing ancestors. */ +export function realWorkspacePath(directory: string): string { + const input = isAbsolute(directory) ? directory : process.cwd() + sep + directory + try { + return normalizeWindowsRealPath(realpathSync.native(input)) + } catch { + // Resolve symbolic links on the deepest existing ancestor, matching Python's os.path.realpath. + } + const target = resolve(directory) + let current = target + const suffix = [] + while (true) { + const parent = dirname(current) + if (parent === current) return normalizeWindowsRealPath(target) + suffix.unshift(basename(current)) + current = parent + try { + const resolvedAncestor = realpathSync.native(current) + return normalizeWindowsRealPath(join(resolvedAncestor, ...suffix)) + } catch { + // Keep walking up until an existing directory is found. + } + } +} + +/** Return the lowercase hex SHA-256 of the canonical real path of `directory`. */ +export function workspaceIdentity(directory: string): string { + return createHash('sha256').update(realWorkspacePath(directory), 'utf8').digest('hex') +} + +/** + * Return `[sharedRoot, hostPath]` pairs for `directory` and, in a linked worktree, its main checkout. + * + * `sharedRoot` is always the Git top level inside a work tree, or `directory` outside Git. `hostPath` preserves the + * host's legacy rule from the same Git invocation, and is omitted when the main-checkout counterpart is unavailable or + * links back to `directory`. + */ +export async function workspaceLocations(directory: string, gitRoot: boolean, timeout: number): Promise { const deadline = Date.now() + timeout const [top = '', gitDir = '', common = ''] = gitPaths(await gitOutput(['-C', directory, ...GIT_ARGUMENTS], timeout)) - const first = gitRoot && top ? top : directory - const main = mainPath(directory, top, gitDir, common, gitRoot) - if (main === undefined) return [first] + const sharedOwn = top || directory + const hostOwn = gitRoot ? sharedOwn : directory + const mainRoot = mainWorktreeRoot(top, gitDir, common) + if (mainRoot === undefined) return [[sharedOwn, hostOwn]] // An unknown answer leaves the second path out, as for a bare repository. const bare = await gitOutput(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) - return bare.trim() === 'false' ? [first, main] : [first] + if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] + const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) + return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] } -/** Return what `workspacePaths` returns, for hosts whose hooks compute their keys synchronously. */ -export function workspacePathsSync(directory: string, gitRoot: boolean, timeout: number): string[] { +/** Return what `workspaceLocations` returns, for hosts whose hooks compute their keys synchronously. */ +export function workspaceLocationsSync(directory: string, gitRoot: boolean, timeout: number): string[][] { const deadline = Date.now() + timeout const [top = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(['-C', directory, ...GIT_ARGUMENTS], timeout)) - const first = gitRoot && top ? top : directory - const main = mainPath(directory, top, gitDir, common, gitRoot) - if (main === undefined) return [first] + const sharedOwn = top || directory + const hostOwn = gitRoot ? sharedOwn : directory + const mainRoot = mainWorktreeRoot(top, gitDir, common) + if (mainRoot === undefined) return [[sharedOwn, hostOwn]] const bare = gitOutputSync(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) - return bare.trim() === 'false' ? [first, main] : [first] + if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] + const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) + return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] +} + +export async function workspacePaths(directory: string, gitRoot: boolean, timeout: number): Promise { + const result = [] + for (const [, hostPath] of await workspaceLocations(directory, gitRoot, timeout)) { + if (hostPath !== undefined) result.push(hostPath) + } + return result +} + +/** Return what `workspacePaths` returns, for hosts whose hooks compute their keys synchronously. */ +export function workspacePathsSync(directory: string, gitRoot: boolean, timeout: number): string[] { + const result = [] + for (const [, hostPath] of workspaceLocationsSync(directory, gitRoot, timeout)) { + if (hostPath !== undefined) result.push(hostPath) + } + return result } // Return what Git prints, or an empty string when it fails or time is up. @@ -101,14 +180,18 @@ function gitPaths(output: string): string[] { return [head.trim(), rest.slice(gitDirSplit + 1), lines.slice(commonSplit + 1)] } -function mainPath(directory: string, top: string, gitDir: string, common: string, gitRoot: boolean): string | undefined { +function mainWorktreeRoot(top: string, gitDir: string, common: string): string | undefined { if (!top || !gitDir || !common || !isAbsolute(gitDir) || !isAbsolute(common)) return undefined const commonDirectory = realPath(common) if (realPath(gitDir) === commonDirectory || basename(commonDirectory) !== '.git') return undefined const mainRoot = dirname(commonDirectory) const worktreeRoot = realPath(top) - if (mainRoot === worktreeRoot) return undefined - if (gitRoot) return mainRoot + return mainRoot === worktreeRoot ? undefined : mainRoot +} + +function mainWorktreeSubdir(directory: string, top: string, mainRoot: string): string | undefined { + if (!top) return undefined + const worktreeRoot = realPath(top) const position = relative(worktreeRoot, realPath(directory)) if (position === '..' || position.startsWith('..' + sep) || isAbsolute(position)) return undefined const main = join(mainRoot, position) @@ -118,7 +201,7 @@ function mainPath(directory: string, top: string, gitDir: string, common: string function realPath(path: string): string { try { - return realpathSync(path) + return realpathSync.native(path) } catch { return resolve(path) } diff --git a/integrations/opencode/plugins/powercontext/lib/index.js b/integrations/opencode/plugins/powercontext/lib/index.js index 10549e91fc..2a62d5fcf8 100644 --- a/integrations/opencode/plugins/powercontext/lib/index.js +++ b/integrations/opencode/plugins/powercontext/lib/index.js @@ -2492,6 +2492,7 @@ function boundedRecallQuery(prompt) { //#endregion //#region src/git-worktree.ts +const SHARED_WORKSPACE_INTEGRATION = "shared"; const GIT_ARGUMENTS = [ "rev-parse", "--show-toplevel", @@ -2518,23 +2519,65 @@ const runGit = promisify(execFile); * directory falls back to the parent of that directory, since Git records no other main worktree. A second path that * is the same directory as `directory` is left out. Both Git calls together stay within `timeout`. */ -async function workspacePaths(directory, gitRoot, timeout) { +/** Normalize Windows extended-length prefixes and drive-letter casing so Python and Node.js hash identical paths. */ +function normalizeWindowsRealPath(value, win32) { + if (!(win32 === void 0 ? process.platform === "win32" : win32)) return value; + let resolved = value; + if (resolved.slice(0, 8).toUpperCase() === "\\\\?\\UNC\\") resolved = "\\\\" + resolved.slice(8); + else if (resolved.slice(0, 4) === "\\\\?\\" && /^[A-Za-z]:/u.test(resolved.slice(4, 6))) resolved = resolved.slice(4); + if (/^[a-z]:/u.test(resolved)) resolved = resolved.slice(0, 1).toUpperCase() + resolved.slice(1); + return resolved; +} +/** Return the canonical real path of `directory` with symbolic links resolved on existing ancestors. */ +function realWorkspacePath(directory) { + const input = isAbsolute(directory) ? directory : process.cwd() + sep + directory; + try { + return normalizeWindowsRealPath(realpathSync.native(input)); + } catch {} + const target = resolve(directory); + let current = target; + const suffix = []; + while (true) { + const parent = dirname(current); + if (parent === current) return normalizeWindowsRealPath(target); + suffix.unshift(basename(current)); + current = parent; + try { + return normalizeWindowsRealPath(join(realpathSync.native(current), ...suffix)); + } catch {} + } +} +/** Return the lowercase hex SHA-256 of the canonical real path of `directory`. */ +function workspaceIdentity(directory) { + return createHash("sha256").update(realWorkspacePath(directory), "utf8").digest("hex"); +} +/** +* Return `[sharedRoot, hostPath]` pairs for `directory` and, in a linked worktree, its main checkout. +* +* `sharedRoot` is always the Git top level inside a work tree, or `directory` outside Git. `hostPath` preserves the +* host's legacy rule from the same Git invocation, and is omitted when the main-checkout counterpart is unavailable or +* links back to `directory`. +*/ +async function workspaceLocations(directory, gitRoot, timeout) { const deadline = Date.now() + timeout; const [top = "", gitDir = "", common = ""] = gitPaths(await gitOutput([ "-C", directory, ...GIT_ARGUMENTS ], timeout)); - const first = gitRoot && top ? top : directory; - const main = mainPath(directory, top, gitDir, common, gitRoot); - if (main === void 0) return [first]; - return (await gitOutput([ + const sharedOwn = top || directory; + const hostOwn = gitRoot ? sharedOwn : directory; + const mainRoot = mainWorktreeRoot(top, gitDir, common); + if (mainRoot === void 0) return [[sharedOwn, hostOwn]]; + if ((await gitOutput([ "-C", directory, "--git-dir", common, ...BARE_ARGUMENTS - ], deadline - Date.now())).trim() === "false" ? [first, main] : [first]; + ], deadline - Date.now())).trim() !== "false") return [[sharedOwn, hostOwn]]; + const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot); + return hostMain === void 0 ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]]; } async function gitOutput(args, timeout) { if (timeout <= 0) return ""; @@ -2565,22 +2608,23 @@ function gitPaths(output) { lines.slice(commonSplit + 1) ]; } -function mainPath(directory, top, gitDir, common, gitRoot) { +function mainWorktreeRoot(top, gitDir, common) { if (!top || !gitDir || !common || !isAbsolute(gitDir) || !isAbsolute(common)) return void 0; const commonDirectory = realPath(common); if (realPath(gitDir) === commonDirectory || basename(commonDirectory) !== ".git") return void 0; const mainRoot = dirname(commonDirectory); - const worktreeRoot = realPath(top); - if (mainRoot === worktreeRoot) return void 0; - if (gitRoot) return mainRoot; - const position = relative(worktreeRoot, realPath(directory)); + return mainRoot === realPath(top) ? void 0 : mainRoot; +} +function mainWorktreeSubdir(directory, top, mainRoot) { + if (!top) return void 0; + const position = relative(realPath(top), realPath(directory)); if (position === ".." || position.startsWith(".." + sep) || isAbsolute(position)) return void 0; const main = join(mainRoot, position); return realPath(main) === realPath(directory) ? void 0 : main; } function realPath(path) { try { - return realpathSync(path); + return realpathSync.native(path); } catch { return resolve(path); } @@ -2596,16 +2640,25 @@ function sessionBindingKey(sessionID) { external_id: sessionID }; } -function workspaceBindingKey(cwd) { +function legacyWorkspaceBindingKey(cwd) { return { integration: "opencode", kind: "workspace", external_id: createHash("sha256").update(resolve(cwd)).digest("hex") }; } -/** Return the workspace keys that resolution tries in order, with a linked worktree's main checkout after its own. */ +/** Return the workspace keys that resolution tries in order, shared before legacy at both checkout levels. */ async function workspaceBindingKeys(cwd) { - return (await workspacePaths(cwd, false, GIT_TIMEOUT_MS)).map(workspaceBindingKey); + const keys = []; + for (const [sharedRoot = cwd, hostPath] of await workspaceLocations(cwd, false, GIT_TIMEOUT_MS)) { + keys.push({ + integration: SHARED_WORKSPACE_INTEGRATION, + kind: "workspace", + external_id: workspaceIdentity(sharedRoot) + }); + if (hostPath !== void 0) keys.push(legacyWorkspaceBindingKey(hostPath)); + } + return keys; } async function resolveScopeId(client, input, signal) { const sessionID = input.sessionID?.trim(); diff --git a/integrations/opencode/plugins/powercontext/lib/tui.js b/integrations/opencode/plugins/powercontext/lib/tui.js index 921e7a05ad..b9f87ffd15 100644 --- a/integrations/opencode/plugins/powercontext/lib/tui.js +++ b/integrations/opencode/plugins/powercontext/lib/tui.js @@ -2578,6 +2578,7 @@ function resolveConfig(env = process.env) { //#endregion //#region src/git-worktree.ts +const SHARED_WORKSPACE_INTEGRATION = "shared"; const GIT_ARGUMENTS = [ "rev-parse", "--show-toplevel", @@ -2604,23 +2605,65 @@ const runGit = promisify(execFile); * directory falls back to the parent of that directory, since Git records no other main worktree. A second path that * is the same directory as `directory` is left out. Both Git calls together stay within `timeout`. */ -async function workspacePaths(directory, gitRoot, timeout) { +/** Normalize Windows extended-length prefixes and drive-letter casing so Python and Node.js hash identical paths. */ +function normalizeWindowsRealPath(value, win32) { + if (!(win32 === void 0 ? process.platform === "win32" : win32)) return value; + let resolved = value; + if (resolved.slice(0, 8).toUpperCase() === "\\\\?\\UNC\\") resolved = "\\\\" + resolved.slice(8); + else if (resolved.slice(0, 4) === "\\\\?\\" && /^[A-Za-z]:/u.test(resolved.slice(4, 6))) resolved = resolved.slice(4); + if (/^[a-z]:/u.test(resolved)) resolved = resolved.slice(0, 1).toUpperCase() + resolved.slice(1); + return resolved; +} +/** Return the canonical real path of `directory` with symbolic links resolved on existing ancestors. */ +function realWorkspacePath(directory) { + const input = isAbsolute(directory) ? directory : process.cwd() + sep + directory; + try { + return normalizeWindowsRealPath(realpathSync.native(input)); + } catch {} + const target = resolve(directory); + let current = target; + const suffix = []; + while (true) { + const parent = dirname(current); + if (parent === current) return normalizeWindowsRealPath(target); + suffix.unshift(basename(current)); + current = parent; + try { + return normalizeWindowsRealPath(join(realpathSync.native(current), ...suffix)); + } catch {} + } +} +/** Return the lowercase hex SHA-256 of the canonical real path of `directory`. */ +function workspaceIdentity(directory) { + return createHash("sha256").update(realWorkspacePath(directory), "utf8").digest("hex"); +} +/** +* Return `[sharedRoot, hostPath]` pairs for `directory` and, in a linked worktree, its main checkout. +* +* `sharedRoot` is always the Git top level inside a work tree, or `directory` outside Git. `hostPath` preserves the +* host's legacy rule from the same Git invocation, and is omitted when the main-checkout counterpart is unavailable or +* links back to `directory`. +*/ +async function workspaceLocations(directory, gitRoot, timeout) { const deadline = Date.now() + timeout; const [top = "", gitDir = "", common = ""] = gitPaths(await gitOutput([ "-C", directory, ...GIT_ARGUMENTS ], timeout)); - const first = gitRoot && top ? top : directory; - const main = mainPath(directory, top, gitDir, common, gitRoot); - if (main === void 0) return [first]; - return (await gitOutput([ + const sharedOwn = top || directory; + const hostOwn = gitRoot ? sharedOwn : directory; + const mainRoot = mainWorktreeRoot(top, gitDir, common); + if (mainRoot === void 0) return [[sharedOwn, hostOwn]]; + if ((await gitOutput([ "-C", directory, "--git-dir", common, ...BARE_ARGUMENTS - ], deadline - Date.now())).trim() === "false" ? [first, main] : [first]; + ], deadline - Date.now())).trim() !== "false") return [[sharedOwn, hostOwn]]; + const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot); + return hostMain === void 0 ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]]; } async function gitOutput(args, timeout) { if (timeout <= 0) return ""; @@ -2651,22 +2694,23 @@ function gitPaths(output) { lines.slice(commonSplit + 1) ]; } -function mainPath(directory, top, gitDir, common, gitRoot) { +function mainWorktreeRoot(top, gitDir, common) { if (!top || !gitDir || !common || !isAbsolute(gitDir) || !isAbsolute(common)) return void 0; const commonDirectory = realPath(common); if (realPath(gitDir) === commonDirectory || basename(commonDirectory) !== ".git") return void 0; const mainRoot = dirname(commonDirectory); - const worktreeRoot = realPath(top); - if (mainRoot === worktreeRoot) return void 0; - if (gitRoot) return mainRoot; - const position = relative(worktreeRoot, realPath(directory)); + return mainRoot === realPath(top) ? void 0 : mainRoot; +} +function mainWorktreeSubdir(directory, top, mainRoot) { + if (!top) return void 0; + const position = relative(realPath(top), realPath(directory)); if (position === ".." || position.startsWith(".." + sep) || isAbsolute(position)) return void 0; const main = join(mainRoot, position); return realPath(main) === realPath(directory) ? void 0 : main; } function realPath(path) { try { - return realpathSync(path); + return realpathSync.native(path); } catch { return resolve(path); } @@ -2682,16 +2726,25 @@ function sessionBindingKey(sessionID) { external_id: sessionID }; } -function workspaceBindingKey(cwd) { +function legacyWorkspaceBindingKey(cwd) { return { integration: "opencode", kind: "workspace", external_id: createHash("sha256").update(resolve(cwd)).digest("hex") }; } -/** Return the workspace keys that resolution tries in order, with a linked worktree's main checkout after its own. */ +/** Return the workspace keys that resolution tries in order, shared before legacy at both checkout levels. */ async function workspaceBindingKeys(cwd) { - return (await workspacePaths(cwd, false, GIT_TIMEOUT_MS)).map(workspaceBindingKey); + const keys = []; + for (const [sharedRoot = cwd, hostPath] of await workspaceLocations(cwd, false, GIT_TIMEOUT_MS)) { + keys.push({ + integration: SHARED_WORKSPACE_INTEGRATION, + kind: "workspace", + external_id: workspaceIdentity(sharedRoot) + }); + if (hostPath !== void 0) keys.push(legacyWorkspaceBindingKey(hostPath)); + } + return keys; } async function resolveScopeId(client, input, signal) { const sessionID = input.sessionID?.trim(); diff --git a/integrations/opencode/plugins/powercontext/src/git-worktree.ts b/integrations/opencode/plugins/powercontext/src/git-worktree.ts index bd2ac88460..a39ee55956 100644 --- a/integrations/opencode/plugins/powercontext/src/git-worktree.ts +++ b/integrations/opencode/plugins/powercontext/src/git-worktree.ts @@ -18,10 +18,13 @@ // Edit the source and run `make integration-lifecycle` instead. import { execFile, execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' import { realpathSync } from 'node:fs' import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { promisify } from 'node:util' +export const SHARED_WORKSPACE_INTEGRATION = 'shared' + // Find the paths whose workspace bindings apply to a directory, so a linked Git worktree falls back to its checkout. // src/powercontext_integration_lifecycle/git_worktree.py applies the same rule for the Python hosts. // @@ -50,26 +53,102 @@ const runGit = promisify(execFile) * directory falls back to the parent of that directory, since Git records no other main worktree. A second path that * is the same directory as `directory` is left out. Both Git calls together stay within `timeout`. */ -export async function workspacePaths(directory: string, gitRoot: boolean, timeout: number): Promise { +/** Normalize Windows extended-length prefixes and drive-letter casing so Python and Node.js hash identical paths. */ +export function normalizeWindowsRealPath(value: string, win32?: boolean): string { + const active = win32 === undefined ? process.platform === 'win32' : win32 + if (!active) return value + let resolved = value + if (resolved.slice(0, 8).toUpperCase() === '\\\\?\\UNC\\') { + resolved = '\\\\' + resolved.slice(8) + } else if (resolved.slice(0, 4) === '\\\\?\\' && /^[A-Za-z]:/u.test(resolved.slice(4, 6))) { + resolved = resolved.slice(4) + } + if (/^[a-z]:/u.test(resolved)) { + resolved = resolved.slice(0, 1).toUpperCase() + resolved.slice(1) + } + return resolved +} + +/** Return the canonical real path of `directory` with symbolic links resolved on existing ancestors. */ +export function realWorkspacePath(directory: string): string { + const input = isAbsolute(directory) ? directory : process.cwd() + sep + directory + try { + return normalizeWindowsRealPath(realpathSync.native(input)) + } catch { + // Resolve symbolic links on the deepest existing ancestor, matching Python's os.path.realpath. + } + const target = resolve(directory) + let current = target + const suffix = [] + while (true) { + const parent = dirname(current) + if (parent === current) return normalizeWindowsRealPath(target) + suffix.unshift(basename(current)) + current = parent + try { + const resolvedAncestor = realpathSync.native(current) + return normalizeWindowsRealPath(join(resolvedAncestor, ...suffix)) + } catch { + // Keep walking up until an existing directory is found. + } + } +} + +/** Return the lowercase hex SHA-256 of the canonical real path of `directory`. */ +export function workspaceIdentity(directory: string): string { + return createHash('sha256').update(realWorkspacePath(directory), 'utf8').digest('hex') +} + +/** + * Return `[sharedRoot, hostPath]` pairs for `directory` and, in a linked worktree, its main checkout. + * + * `sharedRoot` is always the Git top level inside a work tree, or `directory` outside Git. `hostPath` preserves the + * host's legacy rule from the same Git invocation, and is omitted when the main-checkout counterpart is unavailable or + * links back to `directory`. + */ +export async function workspaceLocations(directory: string, gitRoot: boolean, timeout: number): Promise { const deadline = Date.now() + timeout const [top = '', gitDir = '', common = ''] = gitPaths(await gitOutput(['-C', directory, ...GIT_ARGUMENTS], timeout)) - const first = gitRoot && top ? top : directory - const main = mainPath(directory, top, gitDir, common, gitRoot) - if (main === undefined) return [first] + const sharedOwn = top || directory + const hostOwn = gitRoot ? sharedOwn : directory + const mainRoot = mainWorktreeRoot(top, gitDir, common) + if (mainRoot === undefined) return [[sharedOwn, hostOwn]] // An unknown answer leaves the second path out, as for a bare repository. const bare = await gitOutput(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) - return bare.trim() === 'false' ? [first, main] : [first] + if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] + const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) + return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] } -/** Return what `workspacePaths` returns, for hosts whose hooks compute their keys synchronously. */ -export function workspacePathsSync(directory: string, gitRoot: boolean, timeout: number): string[] { +/** Return what `workspaceLocations` returns, for hosts whose hooks compute their keys synchronously. */ +export function workspaceLocationsSync(directory: string, gitRoot: boolean, timeout: number): string[][] { const deadline = Date.now() + timeout const [top = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(['-C', directory, ...GIT_ARGUMENTS], timeout)) - const first = gitRoot && top ? top : directory - const main = mainPath(directory, top, gitDir, common, gitRoot) - if (main === undefined) return [first] + const sharedOwn = top || directory + const hostOwn = gitRoot ? sharedOwn : directory + const mainRoot = mainWorktreeRoot(top, gitDir, common) + if (mainRoot === undefined) return [[sharedOwn, hostOwn]] const bare = gitOutputSync(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) - return bare.trim() === 'false' ? [first, main] : [first] + if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] + const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) + return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] +} + +export async function workspacePaths(directory: string, gitRoot: boolean, timeout: number): Promise { + const result = [] + for (const [, hostPath] of await workspaceLocations(directory, gitRoot, timeout)) { + if (hostPath !== undefined) result.push(hostPath) + } + return result +} + +/** Return what `workspacePaths` returns, for hosts whose hooks compute their keys synchronously. */ +export function workspacePathsSync(directory: string, gitRoot: boolean, timeout: number): string[] { + const result = [] + for (const [, hostPath] of workspaceLocationsSync(directory, gitRoot, timeout)) { + if (hostPath !== undefined) result.push(hostPath) + } + return result } // Return what Git prints, or an empty string when it fails or time is up. @@ -104,14 +183,18 @@ function gitPaths(output: string): string[] { return [head.trim(), rest.slice(gitDirSplit + 1), lines.slice(commonSplit + 1)] } -function mainPath(directory: string, top: string, gitDir: string, common: string, gitRoot: boolean): string | undefined { +function mainWorktreeRoot(top: string, gitDir: string, common: string): string | undefined { if (!top || !gitDir || !common || !isAbsolute(gitDir) || !isAbsolute(common)) return undefined const commonDirectory = realPath(common) if (realPath(gitDir) === commonDirectory || basename(commonDirectory) !== '.git') return undefined const mainRoot = dirname(commonDirectory) const worktreeRoot = realPath(top) - if (mainRoot === worktreeRoot) return undefined - if (gitRoot) return mainRoot + return mainRoot === worktreeRoot ? undefined : mainRoot +} + +function mainWorktreeSubdir(directory: string, top: string, mainRoot: string): string | undefined { + if (!top) return undefined + const worktreeRoot = realPath(top) const position = relative(worktreeRoot, realPath(directory)) if (position === '..' || position.startsWith('..' + sep) || isAbsolute(position)) return undefined const main = join(mainRoot, position) @@ -121,7 +204,7 @@ function mainPath(directory: string, top: string, gitDir: string, common: string function realPath(path: string): string { try { - return realpathSync(path) + return realpathSync.native(path) } catch { return resolve(path) } diff --git a/integrations/opencode/plugins/powercontext/src/scope.ts b/integrations/opencode/plugins/powercontext/src/scope.ts index de6a371f0d..aa6af0cf75 100644 --- a/integrations/opencode/plugins/powercontext/src/scope.ts +++ b/integrations/opencode/plugins/powercontext/src/scope.ts @@ -17,7 +17,12 @@ import { createHash } from 'node:crypto' import { resolve } from 'node:path' import type { PowerContextClient } from './client.ts' -import { workspacePaths } from './git-worktree.ts' +import { + SHARED_WORKSPACE_INTEGRATION, + workspaceIdentity, + workspaceLocations, + workspaceLocationsSync, +} from './git-worktree.ts' type ScopeBindingKey = { integration: string; kind: string; external_id: string } @@ -27,7 +32,16 @@ export function sessionBindingKey(sessionID: string): ScopeBindingKey { return { integration: 'opencode', kind: 'session', external_id: sessionID } } -export function workspaceBindingKey(cwd: string): ScopeBindingKey { +export function sharedWorkspaceBindingKey(cwd: string): ScopeBindingKey { + const [sharedRoot = cwd] = workspaceLocationsSync(cwd, false, GIT_TIMEOUT_MS)[0] ?? [cwd] + return { + integration: SHARED_WORKSPACE_INTEGRATION, + kind: 'workspace', + external_id: workspaceIdentity(sharedRoot), + } +} + +export function legacyWorkspaceBindingKey(cwd: string): ScopeBindingKey { return { integration: 'opencode', kind: 'workspace', @@ -35,9 +49,22 @@ export function workspaceBindingKey(cwd: string): ScopeBindingKey { } } -/** Return the workspace keys that resolution tries in order, with a linked worktree's main checkout after its own. */ +export function workspaceBindingKey(cwd: string): ScopeBindingKey { + return sharedWorkspaceBindingKey(cwd) +} + +/** Return the workspace keys that resolution tries in order, shared before legacy at both checkout levels. */ export async function workspaceBindingKeys(cwd: string): Promise { - return (await workspacePaths(cwd, false, GIT_TIMEOUT_MS)).map(workspaceBindingKey) + const keys: ScopeBindingKey[] = [] + for (const [sharedRoot = cwd, hostPath] of await workspaceLocations(cwd, false, GIT_TIMEOUT_MS)) { + keys.push({ + integration: SHARED_WORKSPACE_INTEGRATION, + kind: 'workspace', + external_id: workspaceIdentity(sharedRoot), + }) + if (hostPath !== undefined) keys.push(legacyWorkspaceBindingKey(hostPath)) + } + return keys } export async function resolveScopeId( diff --git a/integrations/opencode/plugins/powercontext/tests/scope.spec.ts b/integrations/opencode/plugins/powercontext/tests/scope.spec.ts index 5ee5c2b3b3..c5bd846cd2 100644 --- a/integrations/opencode/plugins/powercontext/tests/scope.spec.ts +++ b/integrations/opencode/plugins/powercontext/tests/scope.spec.ts @@ -22,7 +22,7 @@ import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' import { resolveScopeId } from '../src/scope.ts' -type BindingInput = { binding_keys: { external_id: string }[] } +type BindingInput = { binding_keys: { integration: string; kind: string; external_id: string }[] } // A checkout and a linked worktree of it, each with the same subdirectory, under a real temporary directory. function gitLayout(): { root: string; checkout: string; worktree: string } { @@ -58,7 +58,8 @@ describe('Scope binding', () => { expect(operation).toBe('resolve_scope_binding') expect(input.explicit_scope_id).toBe('explicit-scope') expect(input.binding_keys[0]).toEqual({ integration: 'opencode', kind: 'session', external_id: 'session-a' }) - expect(input.binding_keys[1]).toMatchObject({ integration: 'opencode', kind: 'workspace' }) + expect(input.binding_keys[1]).toMatchObject({ integration: 'shared', kind: 'workspace' }) + expect(input.binding_keys[2]).toMatchObject({ integration: 'opencode', kind: 'workspace' }) expect(input.binding_keys[1].external_id).not.toContain('/workspace/powercontext') }) @@ -106,8 +107,9 @@ describe('Scope binding', () => { expect(firstCall).toBeDefined() if (!firstCall) throw new Error('resolve_scope_binding was not called') const input = firstCall[1] - expect(input.binding_keys).toHaveLength(1) - expect(input.binding_keys[0]).toMatchObject({ integration: 'opencode', kind: 'workspace' }) + expect(input.binding_keys).toHaveLength(2) + expect(input.binding_keys[0]).toMatchObject({ integration: 'shared', kind: 'workspace' }) + expect(input.binding_keys[1]).toMatchObject({ integration: 'opencode', kind: 'workspace' }) expect(input.binding_keys[0].external_id).toHaveLength(64) }) @@ -130,22 +132,28 @@ describe('Scope binding', () => { try { const checkoutSub = join(checkout, 'sub') const worktreeSub = join(worktree, 'sub') - const bindings = new Map([[pathHash(checkoutSub), 'checkout-scope']]) + const keyOf = (integration: string, id: string) => `${integration}:${id}` + const bindings = new Map([[keyOf('opencode', pathHash(checkoutSub)), 'checkout-scope']]) const request = vi.fn(async (_operation: string, input: BindingInput) => ({ - value: { scope_id: input.binding_keys.map(key => bindings.get(key.external_id)).find(Boolean) ?? 'default' }, + value: { + scope_id: input.binding_keys.map(key => bindings.get(keyOf(key.integration, key.external_id))).find(Boolean) ?? 'default', + }, })) const resolveIn = (cwd: string) => resolveScopeId({ request } as never, { cwd }) await expect(resolveIn(worktreeSub)).resolves.toBe('checkout-scope') - // The first key is still the hash of path.resolve(cwd), so bindings made before keep matching. expect(request.mock.calls[0]?.[1].binding_keys).toEqual([ + { integration: 'shared', kind: 'workspace', external_id: pathHash(worktree) }, { integration: 'opencode', kind: 'workspace', external_id: pathHash(worktreeSub) }, + { integration: 'shared', kind: 'workspace', external_id: pathHash(checkout) }, { integration: 'opencode', kind: 'workspace', external_id: pathHash(checkoutSub) }, ]) - bindings.set(pathHash(worktreeSub), 'worktree-scope') + bindings.set(keyOf('opencode', pathHash(worktreeSub)), 'worktree-scope') await expect(resolveIn(worktreeSub)).resolves.toBe('worktree-scope') + bindings.set(keyOf('shared', pathHash(worktree)), 'shared-worktree-scope') + await expect(resolveIn(worktreeSub)).resolves.toBe('shared-worktree-scope') await expect(resolveIn(checkoutSub)).resolves.toBe('checkout-scope') - expect(request.mock.calls.at(-1)?.[1].binding_keys).toHaveLength(1) + expect(request.mock.calls.at(-1)?.[1].binding_keys).toHaveLength(2) } finally { rmSync(root, { recursive: true, force: true }) } diff --git a/integrations/opencode/plugins/powercontext/tests/tui.spec.tsx b/integrations/opencode/plugins/powercontext/tests/tui.spec.tsx index f8bdf51425..0b39215599 100644 --- a/integrations/opencode/plugins/powercontext/tests/tui.spec.tsx +++ b/integrations/opencode/plugins/powercontext/tests/tui.spec.tsx @@ -160,7 +160,8 @@ describe('PowerContextTuiPlugin', () => { kind: 'session', external_id: 'session-1', }) - expect(resolveCalls[0]?.body.binding_keys[1]).toMatchObject({ integration: 'opencode', kind: 'workspace' }) + expect(resolveCalls[0]?.body.binding_keys[1]).toMatchObject({ integration: 'shared', kind: 'workspace' }) + expect(resolveCalls[0]?.body.binding_keys[2]).toMatchObject({ integration: 'opencode', kind: 'workspace' }) expect(dialog.setSize).toHaveBeenCalledWith('large') }) diff --git a/integrations/pi/plugins/powercontext/src/git-worktree.ts b/integrations/pi/plugins/powercontext/src/git-worktree.ts index bd2ac88460..a39ee55956 100644 --- a/integrations/pi/plugins/powercontext/src/git-worktree.ts +++ b/integrations/pi/plugins/powercontext/src/git-worktree.ts @@ -18,10 +18,13 @@ // Edit the source and run `make integration-lifecycle` instead. import { execFile, execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' import { realpathSync } from 'node:fs' import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { promisify } from 'node:util' +export const SHARED_WORKSPACE_INTEGRATION = 'shared' + // Find the paths whose workspace bindings apply to a directory, so a linked Git worktree falls back to its checkout. // src/powercontext_integration_lifecycle/git_worktree.py applies the same rule for the Python hosts. // @@ -50,26 +53,102 @@ const runGit = promisify(execFile) * directory falls back to the parent of that directory, since Git records no other main worktree. A second path that * is the same directory as `directory` is left out. Both Git calls together stay within `timeout`. */ -export async function workspacePaths(directory: string, gitRoot: boolean, timeout: number): Promise { +/** Normalize Windows extended-length prefixes and drive-letter casing so Python and Node.js hash identical paths. */ +export function normalizeWindowsRealPath(value: string, win32?: boolean): string { + const active = win32 === undefined ? process.platform === 'win32' : win32 + if (!active) return value + let resolved = value + if (resolved.slice(0, 8).toUpperCase() === '\\\\?\\UNC\\') { + resolved = '\\\\' + resolved.slice(8) + } else if (resolved.slice(0, 4) === '\\\\?\\' && /^[A-Za-z]:/u.test(resolved.slice(4, 6))) { + resolved = resolved.slice(4) + } + if (/^[a-z]:/u.test(resolved)) { + resolved = resolved.slice(0, 1).toUpperCase() + resolved.slice(1) + } + return resolved +} + +/** Return the canonical real path of `directory` with symbolic links resolved on existing ancestors. */ +export function realWorkspacePath(directory: string): string { + const input = isAbsolute(directory) ? directory : process.cwd() + sep + directory + try { + return normalizeWindowsRealPath(realpathSync.native(input)) + } catch { + // Resolve symbolic links on the deepest existing ancestor, matching Python's os.path.realpath. + } + const target = resolve(directory) + let current = target + const suffix = [] + while (true) { + const parent = dirname(current) + if (parent === current) return normalizeWindowsRealPath(target) + suffix.unshift(basename(current)) + current = parent + try { + const resolvedAncestor = realpathSync.native(current) + return normalizeWindowsRealPath(join(resolvedAncestor, ...suffix)) + } catch { + // Keep walking up until an existing directory is found. + } + } +} + +/** Return the lowercase hex SHA-256 of the canonical real path of `directory`. */ +export function workspaceIdentity(directory: string): string { + return createHash('sha256').update(realWorkspacePath(directory), 'utf8').digest('hex') +} + +/** + * Return `[sharedRoot, hostPath]` pairs for `directory` and, in a linked worktree, its main checkout. + * + * `sharedRoot` is always the Git top level inside a work tree, or `directory` outside Git. `hostPath` preserves the + * host's legacy rule from the same Git invocation, and is omitted when the main-checkout counterpart is unavailable or + * links back to `directory`. + */ +export async function workspaceLocations(directory: string, gitRoot: boolean, timeout: number): Promise { const deadline = Date.now() + timeout const [top = '', gitDir = '', common = ''] = gitPaths(await gitOutput(['-C', directory, ...GIT_ARGUMENTS], timeout)) - const first = gitRoot && top ? top : directory - const main = mainPath(directory, top, gitDir, common, gitRoot) - if (main === undefined) return [first] + const sharedOwn = top || directory + const hostOwn = gitRoot ? sharedOwn : directory + const mainRoot = mainWorktreeRoot(top, gitDir, common) + if (mainRoot === undefined) return [[sharedOwn, hostOwn]] // An unknown answer leaves the second path out, as for a bare repository. const bare = await gitOutput(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) - return bare.trim() === 'false' ? [first, main] : [first] + if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] + const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) + return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] } -/** Return what `workspacePaths` returns, for hosts whose hooks compute their keys synchronously. */ -export function workspacePathsSync(directory: string, gitRoot: boolean, timeout: number): string[] { +/** Return what `workspaceLocations` returns, for hosts whose hooks compute their keys synchronously. */ +export function workspaceLocationsSync(directory: string, gitRoot: boolean, timeout: number): string[][] { const deadline = Date.now() + timeout const [top = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(['-C', directory, ...GIT_ARGUMENTS], timeout)) - const first = gitRoot && top ? top : directory - const main = mainPath(directory, top, gitDir, common, gitRoot) - if (main === undefined) return [first] + const sharedOwn = top || directory + const hostOwn = gitRoot ? sharedOwn : directory + const mainRoot = mainWorktreeRoot(top, gitDir, common) + if (mainRoot === undefined) return [[sharedOwn, hostOwn]] const bare = gitOutputSync(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) - return bare.trim() === 'false' ? [first, main] : [first] + if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] + const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) + return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] +} + +export async function workspacePaths(directory: string, gitRoot: boolean, timeout: number): Promise { + const result = [] + for (const [, hostPath] of await workspaceLocations(directory, gitRoot, timeout)) { + if (hostPath !== undefined) result.push(hostPath) + } + return result +} + +/** Return what `workspacePaths` returns, for hosts whose hooks compute their keys synchronously. */ +export function workspacePathsSync(directory: string, gitRoot: boolean, timeout: number): string[] { + const result = [] + for (const [, hostPath] of workspaceLocationsSync(directory, gitRoot, timeout)) { + if (hostPath !== undefined) result.push(hostPath) + } + return result } // Return what Git prints, or an empty string when it fails or time is up. @@ -104,14 +183,18 @@ function gitPaths(output: string): string[] { return [head.trim(), rest.slice(gitDirSplit + 1), lines.slice(commonSplit + 1)] } -function mainPath(directory: string, top: string, gitDir: string, common: string, gitRoot: boolean): string | undefined { +function mainWorktreeRoot(top: string, gitDir: string, common: string): string | undefined { if (!top || !gitDir || !common || !isAbsolute(gitDir) || !isAbsolute(common)) return undefined const commonDirectory = realPath(common) if (realPath(gitDir) === commonDirectory || basename(commonDirectory) !== '.git') return undefined const mainRoot = dirname(commonDirectory) const worktreeRoot = realPath(top) - if (mainRoot === worktreeRoot) return undefined - if (gitRoot) return mainRoot + return mainRoot === worktreeRoot ? undefined : mainRoot +} + +function mainWorktreeSubdir(directory: string, top: string, mainRoot: string): string | undefined { + if (!top) return undefined + const worktreeRoot = realPath(top) const position = relative(worktreeRoot, realPath(directory)) if (position === '..' || position.startsWith('..' + sep) || isAbsolute(position)) return undefined const main = join(mainRoot, position) @@ -121,7 +204,7 @@ function mainPath(directory: string, top: string, gitDir: string, common: string function realPath(path: string): string { try { - return realpathSync(path) + return realpathSync.native(path) } catch { return resolve(path) } diff --git a/integrations/pi/plugins/powercontext/src/scope.ts b/integrations/pi/plugins/powercontext/src/scope.ts index 86387bac1f..124124c147 100644 --- a/integrations/pi/plugins/powercontext/src/scope.ts +++ b/integrations/pi/plugins/powercontext/src/scope.ts @@ -17,13 +17,27 @@ import { createHash } from 'node:crypto' import { resolve } from 'node:path' import type { PowerContextClient } from './client.ts' -import { workspacePaths } from './git-worktree.ts' +import { + SHARED_WORKSPACE_INTEGRATION, + workspaceIdentity, + workspaceLocations, + workspaceLocationsSync, +} from './git-worktree.ts' type ScopeBindingKey = { integration: string; kind: string; external_id: string } const GIT_TIMEOUT_MS = 500 -export function workspaceBindingKey(cwd: string): ScopeBindingKey { +export function sharedWorkspaceBindingKey(cwd: string): ScopeBindingKey { + const [sharedRoot = cwd] = workspaceLocationsSync(cwd, false, GIT_TIMEOUT_MS)[0] ?? [cwd] + return { + integration: SHARED_WORKSPACE_INTEGRATION, + kind: 'workspace', + external_id: workspaceIdentity(sharedRoot), + } +} + +export function legacyWorkspaceBindingKey(cwd: string): ScopeBindingKey { return { integration: 'pi', kind: 'workspace', @@ -31,9 +45,22 @@ export function workspaceBindingKey(cwd: string): ScopeBindingKey { } } -/** Return the workspace keys that resolution tries in order, with a linked worktree's main checkout after its own. */ +export function workspaceBindingKey(cwd: string): ScopeBindingKey { + return sharedWorkspaceBindingKey(cwd) +} + +/** Return the workspace keys that resolution tries in order, shared before legacy at both checkout levels. */ export async function workspaceBindingKeys(cwd: string): Promise { - return (await workspacePaths(cwd, false, GIT_TIMEOUT_MS)).map(workspaceBindingKey) + const keys: ScopeBindingKey[] = [] + for (const [sharedRoot = cwd, hostPath] of await workspaceLocations(cwd, false, GIT_TIMEOUT_MS)) { + keys.push({ + integration: SHARED_WORKSPACE_INTEGRATION, + kind: 'workspace', + external_id: workspaceIdentity(sharedRoot), + }) + if (hostPath !== undefined) keys.push(legacyWorkspaceBindingKey(hostPath)) + } + return keys } export async function resolveScopeId( diff --git a/integrations/pi/plugins/powercontext/tests/scope.spec.ts b/integrations/pi/plugins/powercontext/tests/scope.spec.ts index 8db339bb6d..3c429a67b4 100644 --- a/integrations/pi/plugins/powercontext/tests/scope.spec.ts +++ b/integrations/pi/plugins/powercontext/tests/scope.spec.ts @@ -22,7 +22,7 @@ import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' import { resolveScopeId } from '../src/scope.ts' -type BindingInput = { binding_keys: { external_id: string }[] } +type BindingInput = { binding_keys: { integration: string; kind: string; external_id: string }[] } // A checkout and a linked worktree of it, each with the same subdirectory, under a real temporary directory. function gitLayout(): { root: string; checkout: string; worktree: string } { @@ -52,8 +52,9 @@ describe('Scope binding', () => { const [operation, input] = request.mock.calls[0] expect(operation).toBe('resolve_scope_binding') expect(input.explicit_scope_id).toBe('explicit-scope') - expect(input.binding_keys).toHaveLength(1) - expect(input.binding_keys[0]).toMatchObject({ integration: 'pi', kind: 'workspace' }) + expect(input.binding_keys).toHaveLength(2) + expect(input.binding_keys[0]).toMatchObject({ integration: 'shared', kind: 'workspace' }) + expect(input.binding_keys[1]).toMatchObject({ integration: 'pi', kind: 'workspace' }) expect(input.binding_keys[0].external_id).not.toContain('/workspace/powercontext') }) @@ -67,22 +68,28 @@ describe('Scope binding', () => { try { const checkoutSub = join(checkout, 'sub') const worktreeSub = join(worktree, 'sub') - const bindings = new Map([[pathHash(checkoutSub), 'checkout-scope']]) + const keyOf = (integration: string, id: string) => `${integration}:${id}` + const bindings = new Map([[keyOf('pi', pathHash(checkoutSub)), 'checkout-scope']]) const request = vi.fn(async (_operation: string, input: BindingInput) => ({ - value: { scope_id: input.binding_keys.map(key => bindings.get(key.external_id)).find(Boolean) ?? 'default' }, + value: { + scope_id: input.binding_keys.map(key => bindings.get(keyOf(key.integration, key.external_id))).find(Boolean) ?? 'default', + }, })) const resolveIn = (cwd: string) => resolveScopeId({ request } as never, cwd) await expect(resolveIn(worktreeSub)).resolves.toBe('checkout-scope') - // The first key is still the hash of path.resolve(cwd), so bindings made before keep matching. expect(request.mock.calls[0]?.[1].binding_keys).toEqual([ + { integration: 'shared', kind: 'workspace', external_id: pathHash(worktree) }, { integration: 'pi', kind: 'workspace', external_id: pathHash(worktreeSub) }, + { integration: 'shared', kind: 'workspace', external_id: pathHash(checkout) }, { integration: 'pi', kind: 'workspace', external_id: pathHash(checkoutSub) }, ]) - bindings.set(pathHash(worktreeSub), 'worktree-scope') + bindings.set(keyOf('pi', pathHash(worktreeSub)), 'worktree-scope') await expect(resolveIn(worktreeSub)).resolves.toBe('worktree-scope') + bindings.set(keyOf('shared', pathHash(worktree)), 'shared-worktree-scope') + await expect(resolveIn(worktreeSub)).resolves.toBe('shared-worktree-scope') await expect(resolveIn(checkoutSub)).resolves.toBe('checkout-scope') - expect(request.mock.calls.at(-1)?.[1].binding_keys).toHaveLength(1) + expect(request.mock.calls.at(-1)?.[1].binding_keys).toHaveLength(2) } finally { rmSync(root, { recursive: true, force: true }) } diff --git a/integrations/zcode/plugins/powercontext/scripts/doctor.mjs b/integrations/zcode/plugins/powercontext/scripts/doctor.mjs index 47f77d2f75..fceb72b8de 100644 --- a/integrations/zcode/plugins/powercontext/scripts/doctor.mjs +++ b/integrations/zcode/plugins/powercontext/scripts/doctor.mjs @@ -16,7 +16,7 @@ import { parseArgs } from 'node:util' import { queryObservations } from '../shared/observations.mjs' -import { resolveScope } from '../shared/scope.mjs' +import { isScopeId, resolveScope } from '../shared/scope.mjs' import { loadSettings } from '../shared/settings.mjs' import { failureCode, HOOK_BUDGET_MS, request } from '../shared/transport.mjs' @@ -43,8 +43,27 @@ try { let scope try { scope = await resolveScope(input, settings, signal) + let matchedKey = settings.explicitScopeId ? 'explicit' : 'default' + if (!settings.explicitScopeId && !settings.remoteWorkspace) { + for (const candidate of scope.keys) { + try { + const single = await request(settings, 'POST', '/v1/scope-bindings/resolve', { + explicit_scope_id: null, binding_keys: [candidate], allow_default: false, + }, signal) + if (single.status === 200 && isScopeId(single.body.scope_id)) { + matchedKey = `${candidate.integration}:${candidate.kind}` + break + } + } catch (error) { + if (error?.message === 'http_404') continue + matchedKey = undefined + break + } + } + } checks.scope_probe = { status: 'ok', code: 'resolved', scope_id: scope.scopeId, - session_key_used: scope.keys.some(key => key.kind === 'session') } + session_key_used: scope.keys.some(key => key.kind === 'session'), + ...(matchedKey ? { matched_key: matchedKey } : {}) } } catch (error) { checks.scope_probe = { status: 'failed', code: failureCode(error) } } if (values.prepare && scope) { try { diff --git a/integrations/zcode/plugins/powercontext/scripts/scope.mjs b/integrations/zcode/plugins/powercontext/scripts/scope.mjs index e6e0082982..c33aeb6c6c 100644 --- a/integrations/zcode/plugins/powercontext/scripts/scope.mjs +++ b/integrations/zcode/plugins/powercontext/scripts/scope.mjs @@ -17,7 +17,7 @@ import { isAbsolute } from 'node:path' import { parseArgs } from 'node:util' import { loadSettings, nonempty } from '../shared/settings.mjs' -import { isScopeId, resolveScope, sessionIdentity, workspaceKey } from '../shared/scope.mjs' +import { isScopeId, legacyWorkspaceKey, resolveScope, sessionIdentity, workspaceKey } from '../shared/scope.mjs' import { failureCode, HOOK_BUDGET_MS, request, serverOrigin } from '../shared/transport.mjs' const schema = 'powercontext.zcode.scope-result.v1' @@ -43,25 +43,32 @@ try { if (action !== 'resolve') { if (settings.remoteWorkspace) throw new Error('remote_binding_disabled') const key = workspaceKey(cwd) + const keys = action === 'bind' ? [key] : [key, legacyWorkspaceKey(cwd)] const target = args.values['scope-id'] binding = { action, status: 'unknown' } - let response - try { - response = await request(settings, action === 'bind' ? 'PUT' : 'POST', - action === 'bind' ? '/v1/scope-bindings' : '/v1/scope-bindings/clear', { - key, ...(action === 'bind' ? { scope_id: target } : {}), - }, signal) - } catch (error) { - if (/^http_4\d\d$/u.test(error?.message ?? '')) binding.status = 'rejected' - throw error + let clearedAny = false + let savedScopeId + for (const currentKey of keys) { + let response + try { + response = await request(settings, action === 'bind' ? 'PUT' : 'POST', + action === 'bind' ? '/v1/scope-bindings' : '/v1/scope-bindings/clear', { + key: currentKey, ...(action === 'bind' ? { scope_id: target } : {}), + }, signal) + } catch (error) { + if (/^http_4\d\d$/u.test(error?.message ?? '')) binding.status = 'rejected' + throw error + } + if (response.status !== 200 || action === 'bind' && (response.body.scope_id !== target || + !response.body.key || Object.entries(currentKey).some(([name, value]) => response.body.key[name] !== value)) || + action === 'unbind' && typeof response.body.cleared !== 'boolean') { + throw new Error('binding_not_confirmed') + } + if (action === 'bind') savedScopeId = response.body.scope_id + else clearedAny = clearedAny || response.body.cleared } - if (response.status !== 200 || action === 'bind' && (response.body.scope_id !== target || - !response.body.key || Object.entries(key).some(([name, value]) => response.body.key[name] !== value)) || - action === 'unbind' && typeof response.body.cleared !== 'boolean') { - throw new Error('binding_not_confirmed') - } - binding = action === 'bind' ? { action, status: 'saved', scope_id: response.body.scope_id } : { - action, status: response.body.cleared ? 'cleared' : 'absent', cleared: response.body.cleared, + binding = action === 'bind' ? { action, status: 'saved', scope_id: savedScopeId } : { + action, status: clearedAny ? 'cleared' : 'absent', cleared: clearedAny, } } const { scopeId, keys } = await resolveScope(input, settings, signal) diff --git a/integrations/zcode/plugins/powercontext/shared/git-worktree.mjs b/integrations/zcode/plugins/powercontext/shared/git-worktree.mjs index 4975e5293a..6b5e9d5259 100644 --- a/integrations/zcode/plugins/powercontext/shared/git-worktree.mjs +++ b/integrations/zcode/plugins/powercontext/shared/git-worktree.mjs @@ -18,10 +18,13 @@ // Edit the source and run `make integration-lifecycle` instead. import { execFile, execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' import { realpathSync } from 'node:fs' import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { promisify } from 'node:util' +export const SHARED_WORKSPACE_INTEGRATION = 'shared' + // Find the paths whose workspace bindings apply to a directory, so a linked Git worktree falls back to its checkout. // src/powercontext_integration_lifecycle/git_worktree.py applies the same rule for the Python hosts. // @@ -50,26 +53,102 @@ const runGit = promisify(execFile) * directory falls back to the parent of that directory, since Git records no other main worktree. A second path that * is the same directory as `directory` is left out. Both Git calls together stay within `timeout`. */ -export async function workspacePaths(directory, gitRoot, timeout) { +/** Normalize Windows extended-length prefixes and drive-letter casing so Python and Node.js hash identical paths. */ +export function normalizeWindowsRealPath(value, win32) { + const active = win32 === undefined ? process.platform === 'win32' : win32 + if (!active) return value + let resolved = value + if (resolved.slice(0, 8).toUpperCase() === '\\\\?\\UNC\\') { + resolved = '\\\\' + resolved.slice(8) + } else if (resolved.slice(0, 4) === '\\\\?\\' && /^[A-Za-z]:/u.test(resolved.slice(4, 6))) { + resolved = resolved.slice(4) + } + if (/^[a-z]:/u.test(resolved)) { + resolved = resolved.slice(0, 1).toUpperCase() + resolved.slice(1) + } + return resolved +} + +/** Return the canonical real path of `directory` with symbolic links resolved on existing ancestors. */ +export function realWorkspacePath(directory) { + const input = isAbsolute(directory) ? directory : process.cwd() + sep + directory + try { + return normalizeWindowsRealPath(realpathSync.native(input)) + } catch { + // Resolve symbolic links on the deepest existing ancestor, matching Python's os.path.realpath. + } + const target = resolve(directory) + let current = target + const suffix = [] + while (true) { + const parent = dirname(current) + if (parent === current) return normalizeWindowsRealPath(target) + suffix.unshift(basename(current)) + current = parent + try { + const resolvedAncestor = realpathSync.native(current) + return normalizeWindowsRealPath(join(resolvedAncestor, ...suffix)) + } catch { + // Keep walking up until an existing directory is found. + } + } +} + +/** Return the lowercase hex SHA-256 of the canonical real path of `directory`. */ +export function workspaceIdentity(directory) { + return createHash('sha256').update(realWorkspacePath(directory), 'utf8').digest('hex') +} + +/** + * Return `[sharedRoot, hostPath]` pairs for `directory` and, in a linked worktree, its main checkout. + * + * `sharedRoot` is always the Git top level inside a work tree, or `directory` outside Git. `hostPath` preserves the + * host's legacy rule from the same Git invocation, and is omitted when the main-checkout counterpart is unavailable or + * links back to `directory`. + */ +export async function workspaceLocations(directory, gitRoot, timeout) { const deadline = Date.now() + timeout const [top = '', gitDir = '', common = ''] = gitPaths(await gitOutput(['-C', directory, ...GIT_ARGUMENTS], timeout)) - const first = gitRoot && top ? top : directory - const main = mainPath(directory, top, gitDir, common, gitRoot) - if (main === undefined) return [first] + const sharedOwn = top || directory + const hostOwn = gitRoot ? sharedOwn : directory + const mainRoot = mainWorktreeRoot(top, gitDir, common) + if (mainRoot === undefined) return [[sharedOwn, hostOwn]] // An unknown answer leaves the second path out, as for a bare repository. const bare = await gitOutput(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) - return bare.trim() === 'false' ? [first, main] : [first] + if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] + const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) + return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] } -/** Return what `workspacePaths` returns, for hosts whose hooks compute their keys synchronously. */ -export function workspacePathsSync(directory, gitRoot, timeout) { +/** Return what `workspaceLocations` returns, for hosts whose hooks compute their keys synchronously. */ +export function workspaceLocationsSync(directory, gitRoot, timeout) { const deadline = Date.now() + timeout const [top = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(['-C', directory, ...GIT_ARGUMENTS], timeout)) - const first = gitRoot && top ? top : directory - const main = mainPath(directory, top, gitDir, common, gitRoot) - if (main === undefined) return [first] + const sharedOwn = top || directory + const hostOwn = gitRoot ? sharedOwn : directory + const mainRoot = mainWorktreeRoot(top, gitDir, common) + if (mainRoot === undefined) return [[sharedOwn, hostOwn]] const bare = gitOutputSync(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) - return bare.trim() === 'false' ? [first, main] : [first] + if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] + const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) + return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] +} + +export async function workspacePaths(directory, gitRoot, timeout) { + const result = [] + for (const [, hostPath] of await workspaceLocations(directory, gitRoot, timeout)) { + if (hostPath !== undefined) result.push(hostPath) + } + return result +} + +/** Return what `workspacePaths` returns, for hosts whose hooks compute their keys synchronously. */ +export function workspacePathsSync(directory, gitRoot, timeout) { + const result = [] + for (const [, hostPath] of workspaceLocationsSync(directory, gitRoot, timeout)) { + if (hostPath !== undefined) result.push(hostPath) + } + return result } // Return what Git prints, or an empty string when it fails or time is up. @@ -104,14 +183,18 @@ function gitPaths(output) { return [head.trim(), rest.slice(gitDirSplit + 1), lines.slice(commonSplit + 1)] } -function mainPath(directory, top, gitDir, common, gitRoot) { +function mainWorktreeRoot(top, gitDir, common) { if (!top || !gitDir || !common || !isAbsolute(gitDir) || !isAbsolute(common)) return undefined const commonDirectory = realPath(common) if (realPath(gitDir) === commonDirectory || basename(commonDirectory) !== '.git') return undefined const mainRoot = dirname(commonDirectory) const worktreeRoot = realPath(top) - if (mainRoot === worktreeRoot) return undefined - if (gitRoot) return mainRoot + return mainRoot === worktreeRoot ? undefined : mainRoot +} + +function mainWorktreeSubdir(directory, top, mainRoot) { + if (!top) return undefined + const worktreeRoot = realPath(top) const position = relative(worktreeRoot, realPath(directory)) if (position === '..' || position.startsWith('..' + sep) || isAbsolute(position)) return undefined const main = join(mainRoot, position) @@ -121,7 +204,7 @@ function mainPath(directory, top, gitDir, common, gitRoot) { function realPath(path) { try { - return realpathSync(path) + return realpathSync.native(path) } catch { return resolve(path) } diff --git a/integrations/zcode/plugins/powercontext/shared/scope.mjs b/integrations/zcode/plugins/powercontext/shared/scope.mjs index 4ca55eb069..3e3ff366fd 100644 --- a/integrations/zcode/plugins/powercontext/shared/scope.mjs +++ b/integrations/zcode/plugins/powercontext/shared/scope.mjs @@ -15,9 +15,12 @@ */ import { createHash } from 'node:crypto' -import { realpathSync } from 'node:fs' import { resolve } from 'node:path' -import { workspacePathsSync } from './git-worktree.mjs' +import { + SHARED_WORKSPACE_INTEGRATION, + workspaceIdentity, + workspacePathsSync, +} from './git-worktree.mjs' import { nonempty } from './settings.mjs' import { request } from './transport.mjs' @@ -41,23 +44,20 @@ export function sessionIdentity(input) { // The Git top level, and, in a linked worktree, its main checkout's root after it. function workspaces(cwd) { const directory = resolve(cwd) - const [root, main] = workspacePathsSync(directory, true, 500) - const own = realPath(root) ?? realPath(directory) ?? directory - // The helper returns the main checkout's root as a real path. - return main === undefined ? [own] : [own, main] -} - -function realPath(path) { - try { return realpathSync(path) } catch { return undefined } + return workspacePathsSync(directory, true, 500) } export function currentWorkspace(cwd) { return workspaces(cwd)[0] } -// Binding and clearing write only this key. +// Binding writes the shared key; clearing removes both the shared key and ZCode's legacy key. export function workspaceKey(cwd) { - return { integration: 'zcode', kind: 'workspace', external_id: sha256(currentWorkspace(cwd)) } + return { integration: SHARED_WORKSPACE_INTEGRATION, kind: 'workspace', external_id: workspaceIdentity(currentWorkspace(cwd)) } +} + +export function legacyWorkspaceKey(cwd) { + return { integration: 'zcode', kind: 'workspace', external_id: workspaceIdentity(currentWorkspace(cwd)) } } export function bindingKeys(input, settings) { @@ -67,7 +67,9 @@ export function bindingKeys(input, settings) { if (sessionId) keys.push({ integration: 'zcode', kind: 'session', external_id: sessionId }) if (nonempty(input.cwd)) { for (const workspace of workspaces(input.cwd)) { - keys.push({ integration: 'zcode', kind: 'workspace', external_id: sha256(workspace) }) + const externalId = workspaceIdentity(workspace) + keys.push({ integration: SHARED_WORKSPACE_INTEGRATION, kind: 'workspace', external_id: externalId }) + keys.push({ integration: 'zcode', kind: 'workspace', external_id: externalId }) } } return keys diff --git a/integrations/zcode/plugins/powercontext/tests/plugin.test.mjs b/integrations/zcode/plugins/powercontext/tests/plugin.test.mjs index 181b2a65f6..0f585b4d05 100644 --- a/integrations/zcode/plugins/powercontext/tests/plugin.test.mjs +++ b/integrations/zcode/plugins/powercontext/tests/plugin.test.mjs @@ -173,7 +173,10 @@ test('hook resolves Scope, injects prepared context and captures one Source', as assert.deepEqual(requests.map(request => request.path), [ '/v1/scope-bindings/resolve', '/v1/context/prepare', '/v1/sources/content', ]) - assert.deepEqual(requests[0].body.binding_keys.map(key => key.kind), ['session', 'workspace']) + assert.deepEqual( + requests[0].body.binding_keys.map(key => `${key.integration}:${key.kind}`), + ['zcode:session', 'shared:workspace', 'zcode:workspace'], + ) assert.equal(requests[1].body.scope_id, 'scope-test') assert.equal(requests[2].body.scope_id, 'scope-test') assert.match(requests[2].body.source_id, /^zcode-user-prompt:[0-9a-f]{64}$/) diff --git a/integrations/zcode/plugins/powercontext/tests/scope.test.mjs b/integrations/zcode/plugins/powercontext/tests/scope.test.mjs index 072ab5e464..eeff778354 100644 --- a/integrations/zcode/plugins/powercontext/tests/scope.test.mjs +++ b/integrations/zcode/plugins/powercontext/tests/scope.test.mjs @@ -44,11 +44,11 @@ function run(script, args, env, input) { } test('installed Scope resolver agrees with Hook and keeps binding writes distinct from effective Scope', async () => { - const root = await mkdtemp(join(tmpdir(), 'pc-zcode-scope-')) + const root = await realpath(await mkdtemp(join(tmpdir(), 'pc-zcode-scope-'))) const bindings = new Map() const seen = [] let failResolve = false - const keyOf = key => `${key.kind}:${key.external_id}` + const keyOf = key => `${key.integration}:${key.kind}:${key.external_id}` const server = createServer(async (req, res) => { let raw = '' for await (const chunk of req) raw += chunk @@ -58,7 +58,7 @@ test('installed Scope resolver agrees with Hook and keeps binding writes distinc if (req.url === '/v1/scope-bindings' && req.method === 'PUT') { bindings.set(keyOf(body.key), body.scope_id) // JSON property order is not part of the binding contract. - res.end(JSON.stringify({ scope_id: body.scope_id, key: { external_id: body.key.external_id, kind: body.key.kind, integration: 'zcode' } })) + res.end(JSON.stringify({ scope_id: body.scope_id, key: { external_id: body.key.external_id, kind: body.key.kind, integration: body.key.integration } })) } else if (req.url === '/v1/scope-bindings/clear' && req.method === 'POST') { res.end(JSON.stringify({ cleared: bindings.delete(keyOf(body.key)) })) } else if (req.url === '/v1/scope-bindings/resolve') { @@ -83,10 +83,11 @@ test('installed Scope resolver agrees with Hook and keeps binding writes distinc assert.equal(result.stderr, '') return { ...result, body: JSON.parse(result.stdout) } } - bindings.set('session:session-one', 'session-scope') + bindings.set('zcode:session:session-one', 'session-scope') const bound = await scope('bind', {}, ['--scope-id', 'workspace-scope']) assert.equal(bound.code, 0) assert.equal(bound.body.binding.status, 'saved') + assert.equal(seen[0].body.key.integration, 'shared') assert.equal(bound.body.scope_id, 'session-scope') assert.equal(bound.body.bound_scope_is_current, false) const resolvedRequest = seen.at(-1).body @@ -133,19 +134,20 @@ test('a linked Git worktree uses its checkout binding until it binds its own', a const root = await realpath(await mkdtemp(join(tmpdir(), 'pc-zcode-worktree-'))) const bindings = new Map() const resolved = [] + const keyOf = key => `${key.integration}:${key.external_id}` const server = createServer(async (req, res) => { let raw = '' for await (const chunk of req) raw += chunk const body = JSON.parse(raw) res.setHeader('Content-Type', 'application/json') if (req.url === '/v1/scope-bindings' && req.method === 'PUT') { - bindings.set(body.key.external_id, body.scope_id) + bindings.set(keyOf(body.key), body.scope_id) res.end(JSON.stringify(body)) } else if (req.url === '/v1/scope-bindings/clear') { - res.end(JSON.stringify({ cleared: bindings.delete(body.key.external_id) })) + res.end(JSON.stringify({ cleared: bindings.delete(keyOf(body.key)) })) } else if (req.url === '/v1/scope-bindings/resolve') { resolved.push(body.binding_keys) - res.end(JSON.stringify({ scope_id: body.binding_keys.map(key => bindings.get(key.external_id)).find(Boolean) ?? 'default' })) + res.end(JSON.stringify({ scope_id: body.binding_keys.map(key => bindings.get(keyOf(key))).find(Boolean) ?? 'default' })) } else { res.statusCode = 404; res.end('{}') } }) try { @@ -166,16 +168,23 @@ test('a linked Git worktree uses its checkout binding until it binds its own', a } const hash = path => createHash('sha256').update(path).digest('hex') + bindings.set(`zcode:${hash(checkout)}`, 'legacy-checkout-scope') + assert.equal((await scope('resolve', join(worktree, 'sub'))).scope_id, 'legacy-checkout-scope') assert.equal((await scope('bind', checkout, ['--scope-id', 'checkout-scope'])).binding.status, 'saved') assert.equal((await scope('resolve', join(worktree, 'sub'))).scope_id, 'checkout-scope') - // ZCode still keys the real Git top level first, so bindings made before keep matching. - assert.deepEqual(resolved.at(-1).map(key => key.external_id), [hash(worktree), hash(checkout)]) + assert.deepEqual(resolved.at(-1), [ + { integration: 'shared', kind: 'workspace', external_id: hash(worktree) }, + { integration: 'zcode', kind: 'workspace', external_id: hash(worktree) }, + { integration: 'shared', kind: 'workspace', external_id: hash(checkout) }, + { integration: 'zcode', kind: 'workspace', external_id: hash(checkout) }, + ]) assert.equal((await scope('bind', join(worktree, 'sub'), ['--scope-id', 'worktree-scope'])).binding.status, 'saved') assert.equal((await scope('resolve', worktree)).scope_id, 'worktree-scope') assert.equal((await scope('resolve', checkout)).scope_id, 'checkout-scope') assert.equal((await scope('unbind', worktree)).binding.status, 'cleared') assert.equal((await scope('resolve', worktree)).scope_id, 'checkout-scope') - assert.equal((await scope('resolve', checkout)).scope_id, 'checkout-scope') + assert.equal((await scope('unbind', checkout)).binding.status, 'cleared') + assert.equal((await scope('resolve', checkout)).scope_id, 'default') } finally { await new Promise(resolve => server.close(resolve)) await rm(root, { recursive: true, force: true }) diff --git a/tests/e2e/test_shared_workspace_scope_binding.py b/tests/e2e/test_shared_workspace_scope_binding.py new file mode 100644 index 0000000000..f91747e8f0 --- /dev/null +++ b/tests/e2e/test_shared_workspace_scope_binding.py @@ -0,0 +1,389 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Cross-host workspace Scope binding resolution, legacy fallback, and dual-key clearing against a real Server.""" + +from __future__ import annotations + +import asyncio +import hashlib +import importlib.util +import json +import os +import shutil +import socket +import subprocess +import sys +import threading +import types +from pathlib import Path +from typing import Any +from uuid import uuid4 + +import httpx +import pytest +import uvicorn +from typer.testing import CliRunner + +from powercontext.builtin.persistence.sqlite import SQLiteConfig +from powercontext.cli.app import create_cli +from powercontext.client import PowerContextClient +from powercontext.server.factory import create_server_app +from powercontext.server.settings import McpConfig, ServerSettings +from tests.e2e.server_startup import wait_for_server_startup +from tests.git_worktree_support import make_git_layout + +PROJECT_ROOT = Path(__file__).resolve().parents[2] +CLAUDE_SCRIPT = PROJECT_ROOT / "integrations/claude-code/plugins/powercontext/scripts/workspace_scope.py" +CODEX_PLUGIN = PROJECT_ROOT / "integrations/codex/plugins/powercontext" +WORKBUDDY_SCRIPT = PROJECT_ROOT / "integrations/workbuddy/plugins/powercontext/scripts/workspace_scope.py" +ZCODE_PLUGIN = PROJECT_ROOT / "integrations/zcode/plugins/powercontext" +KIMI_PLUGIN = PROJECT_ROOT / "integrations/kimi-code/plugins/powercontext" +DSH_SCOPE = PROJECT_ROOT / "integrations/dsh/plugins/powercontext/src/scope.ts" +OPENCODE_SCOPE = PROJECT_ROOT / "integrations/opencode/plugins/powercontext/src/scope.ts" +PI_SCOPE = PROJECT_ROOT / "integrations/pi/plugins/powercontext/src/scope.ts" +HERMES_PACKAGE = PROJECT_ROOT / "integrations/hermes/plugins/powercontext" +BUB_SRC = PROJECT_ROOT / "integrations/bub/src" + + +def _load_package_module(package_name: str, package_dir: Path, module_name: str) -> Any: + full_name = f"{package_name}.{module_name}" + if package_name not in sys.modules: + pkg_mod = types.ModuleType(package_name) + pkg_mod.__path__ = [str(package_dir)] + pkg_mod.__package__ = package_name + sys.modules[package_name] = pkg_mod + spec = importlib.util.spec_from_file_location(full_name, package_dir / f"{module_name}.py") + assert spec is not None and spec.loader is not None + mod = importlib.util.module_from_spec(spec) + sys.modules[full_name] = mod + spec.loader.exec_module(mod) + return mod + + +def _resolve_ts_hosts(node: str, base_url: str, cwd: Path) -> dict[str, str]: + script = """ +const [baseUrl, cwd, dshUri, opencodeUri, piUri] = process.argv.slice(1); +const client = { + async request(operation, payload) { + if (operation !== 'resolve_scope_binding') throw new Error(operation); + const res = await fetch(baseUrl + '/v1/scope-bindings/resolve', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload), + }); + return { status: res.status, value: await res.json() }; + }, +}; +const dsh = await import(dshUri); +const opencode = await import(opencodeUri); +const pi = await import(piUri); +console.log(JSON.stringify({ + dsh: await dsh.resolveScopeId(client, cwd), + opencode: await opencode.resolveScopeId(client, { cwd }), + pi: await pi.resolveScopeId(client, cwd), +})); +""" + completed = subprocess.run( + [ + node, + "--input-type=module", + "-e", + script, + base_url, + str(cwd), + DSH_SCOPE.as_uri(), + OPENCODE_SCOPE.as_uri(), + PI_SCOPE.as_uri(), + ], + capture_output=True, + text=True, + check=True, + timeout=15, + ) + return json.loads(completed.stdout) + + +def test_shared_workspace_binding_resolves_across_all_hosts_and_preserves_legacy_bindings( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + node = shutil.which("node") + if node is None: + pytest.skip("Node.js is required to exercise JS and TS workspace Scope resolvers") + + layout = make_git_layout(tmp_path / "git", monkeypatch) + subdir = layout.checkout / "packages" / "web" + subdir.mkdir(parents=True) + worktree_subdir = layout.worktree / "packages" / "web" + worktree_subdir.mkdir(parents=True) + symlink_root = tmp_path / "repo-link" + symlink_root.symlink_to(layout.checkout, target_is_directory=True) + symlink_subdir = symlink_root / "packages" / "web" + + app = create_server_app( + settings=ServerSettings( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'shared-scope.db'}"), + mcp=McpConfig(enabled=False), + ) + ) + listener = socket.socket() + listener.bind(("127.0.0.1", 0)) + host, port = listener.getsockname() + base_url = f"http://{host}:{port}" + server = uvicorn.Server(uvicorn.Config(app, log_level="critical", lifespan="on")) + thread = threading.Thread(target=server.run, kwargs={"sockets": [listener]}, daemon=True) + thread.start() + + codex_copy = tmp_path / "codex-plugin" + shutil.copytree(CODEX_PLUGIN, codex_copy) + codex_mcp = json.loads((codex_copy / ".mcp.json").read_text(encoding="utf-8")) + codex_mcp["mcpServers"]["powercontext"]["url"] = f"{base_url}/mcp" + (codex_copy / ".mcp.json").write_text(json.dumps(codex_mcp), encoding="utf-8") + codex_script = codex_copy / "scripts/scope_binding.py" + + kimi_copy = tmp_path / "kimi-plugin" + shutil.copytree(KIMI_PLUGIN, kimi_copy) + (kimi_copy / "powercontext.json").write_text( + json.dumps({"server_url": base_url, "scope_id": None, "capture_prompts": True, "use_token": False}), + encoding="utf-8", + ) + + env = { + key: value + for key, value in os.environ.items() + if not key.startswith("POWERCONTEXT_") and not key.upper().endswith("_PROXY") + } + env.update( + NO_PROXY="127.0.0.1,localhost,::1", + POWERCONTEXT_CLIENT_CONFIG_FILE=str(tmp_path / "clients.json"), + CLAUDE_CONFIG_DIR=str(tmp_path / "claude-config"), + CODEX_HOME=str(tmp_path / "codex-home"), + WORKBUDDY_HOME=str(tmp_path / "workbuddy-home"), + ZCODE_PLUGIN_DATA=str(tmp_path / "zcode-data"), + POWERCONTEXT_CLAUDE_SERVER_URL=base_url, + POWERCONTEXT_WORKBUDDY_SERVER_URL=base_url, + POWERCONTEXT_ZCODE_SERVER_URL=base_url, + ) + + hermes_provider_mod = _load_package_module("_test_hermes_e2e_pkg", HERMES_PACKAGE, "provider") + bub_scope_mod = _load_package_module("powercontext_bub", BUB_SRC / "powercontext_bub", "scope") + + def create_scope(http: httpx.Client, title: str) -> str: + response = http.post( + "/v1/scopes", + json={"title": title, "summary": "Cross-host workspace binding test", "idempotency_key": title}, + ) + response.raise_for_status() + return response.json()["scope_id"] + + def run_py_script(script: Path, *args: str) -> str: + completed = subprocess.run( + [sys.executable, str(script), *args], + env=env, + capture_output=True, + text=True, + check=True, + timeout=15, + ) + return completed.stdout.strip() + + def run_zcode_scope(action: str, cwd: Path, *extra: str) -> dict[str, Any]: + completed = subprocess.run( + [node, str(ZCODE_PLUGIN / "scripts/scope.mjs"), action, "--cwd", str(cwd), *extra], + env=env, + capture_output=True, + text=True, + check=True, + timeout=15, + ) + return json.loads(completed.stdout) + + def run_kimi_scope(action: str, cwd: Path, *extra: str) -> dict[str, Any]: + completed = subprocess.run( + [node, str(kimi_copy / "scripts/scope.mjs"), action, "--cwd", str(cwd), *extra], + env=env, + capture_output=True, + text=True, + check=True, + timeout=15, + ) + return json.loads(completed.stdout) + + def resolve_bub_and_hermes(cwd: Path) -> tuple[str, str]: + async def _bub() -> str: + async with PowerContextClient(base_url=base_url) as client: + return await bub_scope_mod.resolve_scope_id( + client, + explicit_scope_id=None, + binding_keys=bub_scope_mod.workspace_binding_keys(cwd), + ) + + provider = hermes_provider_mod.PowerContextMemoryProvider(config={"base_url": base_url}) + provider.initialize( + f"hermes-{uuid4().hex}", + hermes_home=str(tmp_path / "hermes-home"), + cwd=str(cwd), + ) + hermes_scope = provider._scope_id + assert isinstance(hermes_scope, str) + return asyncio.run(_bub()), hermes_scope + + def resolve_all_hosts(cwd: Path) -> dict[str, str]: + ts_results = _resolve_ts_hosts(node, base_url, cwd) + bub_id, hermes_id = resolve_bub_and_hermes(cwd) + cli_res = CliRunner().invoke( + create_cli(), + ["--server-url", base_url, "--json", "scope", "resolve", "--integration", "opencode", "--cwd", str(cwd)], + ) + assert cli_res.exit_code == 0, cli_res.output + cli_doc = json.loads(cli_res.output) + return { + "claude-code": run_py_script(CLAUDE_SCRIPT, "--cwd", str(cwd)), + "codex": run_py_script(codex_script, "--cwd", str(cwd)), + "workbuddy": run_py_script(WORKBUDDY_SCRIPT, "--cwd", str(cwd)), + "zcode": run_zcode_scope("resolve", cwd)["scope_id"], + "kimi-code": run_kimi_scope("resolve", cwd)["scope_id"], + "bub": bub_id, + "hermes": hermes_id, + "cli-opencode": cli_doc["scope_id"], + **ts_results, + } + + try: + wait_for_server_startup(server, thread) + with httpx.Client(base_url=base_url, timeout=10) as http: + default_scope = http.post("/v1/scope-bindings/resolve", json={"binding_keys": []}).json()["scope_id"] + main_scope = create_scope(http, "shared-main") + worktree_scope = create_scope(http, "shared-worktree") + legacy_pi_scope = create_scope(http, "legacy-pi-subdir") + legacy_claude_scope = create_scope(http, "legacy-claude-root") + + # 1. Seed pre-existing per-host legacy bindings and confirm backward compatibility. + pi_legacy_id = hashlib.sha256(os.path.abspath(subdir).encode()).hexdigest() + claude_legacy_id = hashlib.sha256(os.fsencode(layout.checkout.resolve())).hexdigest() + http.put( + "/v1/scope-bindings", + json={ + "key": {"integration": "pi", "kind": "workspace", "external_id": pi_legacy_id}, + "scope_id": legacy_pi_scope, + }, + ).raise_for_status() + http.put( + "/v1/scope-bindings", + json={ + "key": {"integration": "claude-code", "kind": "workspace", "external_id": claude_legacy_id}, + "scope_id": legacy_claude_scope, + }, + ).raise_for_status() + + assert _resolve_ts_hosts(node, base_url, subdir)["pi"] == legacy_pi_scope + claude_diag_legacy = json.loads(run_py_script(CLAUDE_SCRIPT, "--cwd", str(subdir), "--diagnose")) + assert claude_diag_legacy["scope_id"] == legacy_claude_scope + assert claude_diag_legacy["matched_key"] == { + "integration": "claude-code", + "kind": "workspace", + "external_id": claude_legacy_id, + } + + # 2. Bind once via Codex from a symlinked subdirectory; every host resolves main_scope everywhere. + assert run_py_script(codex_script, "--cwd", str(symlink_subdir), "--bind-scope", main_scope) == main_scope + + for target_dir in (layout.checkout, subdir, symlink_subdir, worktree_subdir): + resolved = resolve_all_hosts(target_dir) + assert set(resolved.values()) == {main_scope}, (target_dir, resolved) + + # Verify diagnostics report shared:workspace as the winning key. + codex_diag = json.loads(run_py_script(codex_script, "--cwd", str(subdir), "--diagnose")) + assert codex_diag["scope_id"] == main_scope + assert codex_diag["source"] == "binding" + assert codex_diag["matched_key"]["integration"] == "shared" + + zcode_doc = json.loads( + subprocess.run( + [node, str(ZCODE_PLUGIN / "scripts/doctor.mjs")], + cwd=subdir, + env=env, + capture_output=True, + text=True, + check=True, + timeout=15, + ).stdout + ) + assert zcode_doc["checks"]["scope_probe"]["matched_key"] == "shared:workspace" + + kimi_doc = json.loads( + subprocess.run( + [node, str(kimi_copy / "scripts/doctor.mjs"), "--cwd", str(subdir)], + env=env, + capture_output=True, + text=True, + check=True, + timeout=15, + ).stdout + ) + assert kimi_doc["checks"]["scope"]["checks"]["matched_key"] == "shared:workspace" + + # 3. A linked worktree's own shared binding overrides the main checkout across all hosts. + assert run_zcode_scope("bind", worktree_subdir, "--scope-id", worktree_scope)["scope_id"] == worktree_scope + assert set(resolve_all_hosts(worktree_subdir).values()) == {worktree_scope} + assert set(resolve_all_hosts(subdir).values()) == {main_scope} + + # 4. Dual-key clear removes both shared:workspace and the invoking host's legacy workspace key. + clear_claude = CliRunner().invoke( + create_cli(), + [ + "--server-url", + base_url, + "--json", + "scope", + "binding", + "clear", + "--integration", + "claude-code", + "--cwd", + str(subdir), + ], + ) + assert clear_claude.exit_code == 0, clear_claude.output + assert json.loads(clear_claude.output)["cleared"] is True + + # Claude Code's legacy root binding was cleared alongside shared:workspace, so it falls back to default. + assert run_py_script(CLAUDE_SCRIPT, "--cwd", str(subdir)) == default_scope + # Pi's subdir legacy binding was preserved until cleared by Pi / CLI --integration pi. + assert _resolve_ts_hosts(node, base_url, subdir)["pi"] == legacy_pi_scope + + clear_pi = CliRunner().invoke( + create_cli(), + [ + "--server-url", + base_url, + "--json", + "scope", + "binding", + "clear", + "--integration", + "pi", + "--cwd", + str(subdir), + ], + ) + assert clear_pi.exit_code == 0, clear_pi.output + assert json.loads(clear_pi.output)["cleared"] is True + assert _resolve_ts_hosts(node, base_url, subdir)["pi"] == default_scope + finally: + server.should_exit = True + thread.join(timeout=10) + listener.close() + assert not thread.is_alive() diff --git a/tests/e2e/test_zcode_service_chain.py b/tests/e2e/test_zcode_service_chain.py index b43df50a1b..6b539bee0e 100644 --- a/tests/e2e/test_zcode_service_chain.py +++ b/tests/e2e/test_zcode_service_chain.py @@ -324,8 +324,19 @@ def _exercise_scope_bindings( if unbinding["status"] == "resolved": assert unbinding["scope_id"] == session_scope, unbinding _wait_for_workspace_binding(client, binding_mutations, None) - assert [path for path, _ in binding_mutations] == ["/v1/scope-bindings", "/v1/scope-bindings/clear"] + expected_paths = ( + ["/v1/scope-bindings", "/v1/scope-bindings/clear"] + if binding_delay + else ["/v1/scope-bindings", "/v1/scope-bindings/clear", "/v1/scope-bindings/clear"] + ) + assert [path for path, _ in binding_mutations] == expected_paths + assert binding_mutations[0][1]["key"]["integration"] == "shared" assert binding_mutations[0][1]["key"] == binding_mutations[1][1]["key"] + if not binding_delay: + assert binding_mutations[2][1]["key"] == { + **binding_mutations[0][1]["key"], + "integration": "zcode", + } def _wait_for_processed_memory(client: httpx.Client, scope_id: str, text: str) -> dict[str, Any]: diff --git a/tests/test_git_worktree.py b/tests/test_git_worktree.py index 959ee084ec..fe0984b37a 100644 --- a/tests/test_git_worktree.py +++ b/tests/test_git_worktree.py @@ -25,7 +25,12 @@ import pytest -from powercontext_integration_lifecycle.git_worktree import workspace_paths +from powercontext_integration_lifecycle.git_worktree import ( + normalize_windows_real_path, + workspace_identity, + workspace_locations, + workspace_paths, +) from tests.git_worktree_support import GitLayout, fake_old_git, make_git_layout ROOT = Path(__file__).resolve().parents[1] @@ -150,3 +155,94 @@ def test_git_without_path_format_keeps_the_top_level_and_adds_nothing( assert helper(layout.worktree_sub, True) == [str(layout.worktree)] assert helper(layout.worktree_sub, False) == [str(layout.worktree_sub)] + + +def _javascript_identity(directory: Path) -> str: + node = shutil.which("node") + if node is None: + pytest.skip("Node.js is not installed") + script = ( + "const [helper, directory] = process.argv.slice(1);" + "const { workspaceIdentity } = await import(helper);" + "console.log(workspaceIdentity(directory));" + ) + completed = subprocess.run( + [node, "--input-type=module", "-e", script, JAVASCRIPT_HELPER.as_uri(), str(directory)], + check=True, + capture_output=True, + text=True, + timeout=30, + ) + return completed.stdout.strip() + + +def test_python_and_javascript_derive_the_same_workspace_identity(layout: GitLayout, tmp_path: Path) -> None: + targets = [ + layout.checkout, + layout.checkout_sub, + layout.worktree, + layout.worktree_sub, + layout.outside, + layout.outside / "missing" / "nested", + ] + link = tmp_path / "checkout-link" + try: + link.symlink_to(layout.checkout, target_is_directory=True) + targets.extend([link, link / "sub", link / "missing"]) + except OSError: + if os.name != "nt": + raise + for target in targets: + py_id = workspace_identity(str(target)) + js_id = _javascript_identity(target) + assert py_id == js_id, f"mismatch for {target}: {py_id} != {js_id}" + + +def test_python_and_javascript_normalize_windows_drive_and_extended_prefixes() -> None: + node = shutil.which("node") + if node is None: + pytest.skip("Node.js is not installed") + vectors = [ + r"c:\Users\dev\repo", + r"C:\Users\dev\repo", + r"\\?\c:\Users\dev\repo", + r"\\?\C:\Users\dev\repo", + r"\\?\UNC\server\share\repo", + r"\\?\unc\server\share\repo", + ] + script = ( + "const [helper, raw] = process.argv.slice(1);" + "const { normalizeWindowsRealPath } = await import(helper);" + "console.log(JSON.stringify(JSON.parse(raw).map(v => normalizeWindowsRealPath(v, true))));" + ) + completed = subprocess.run( + [node, "--input-type=module", "-e", script, JAVASCRIPT_HELPER.as_uri(), json.dumps(vectors)], + check=True, + capture_output=True, + text=True, + timeout=30, + ) + js_values = json.loads(completed.stdout) + py_values = [normalize_windows_real_path(v, windows=True) for v in vectors] + assert ( + py_values + == js_values + == [ + r"C:\Users\dev\repo", + r"C:\Users\dev\repo", + r"C:\Users\dev\repo", + r"C:\Users\dev\repo", + r"\\server\share\repo", + r"\\server\share\repo", + ] + ) + + +def test_workspace_locations_pair_shared_roots_with_legacy_host_paths(layout: GitLayout) -> None: + assert workspace_locations(str(layout.worktree_sub), git_root=False) == [ + (str(layout.worktree), str(layout.worktree_sub)), + (str(layout.checkout), str(layout.checkout_sub)), + ] + assert workspace_locations(str(layout.checkout_sub), git_root=False) == [ + (str(layout.checkout), str(layout.checkout_sub)), + ] From 5863d39adfce204ff4dccb24c72da7c3037981a0 Mon Sep 17 00:00:00 2001 From: wycocoyu <180249289+wycocoyu@users.noreply.github.com> Date: Wed, 2 Dec 2026 08:58:09 -0800 Subject: [PATCH 4/7] docs(rfc): assign RFC number #2988 --- ...pe-bindings.md => 2988-shared-workspace-scope-bindings.md} | 4 ++-- ...pe-bindings.md => 2988-shared-workspace-scope-bindings.md} | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) rename docs/en/rfcs/{0000-shared-workspace-scope-bindings.md => 2988-shared-workspace-scope-bindings.md} (98%) rename docs/zh/rfcs/{0000-shared-workspace-scope-bindings.md => 2988-shared-workspace-scope-bindings.md} (98%) diff --git a/docs/en/rfcs/0000-shared-workspace-scope-bindings.md b/docs/en/rfcs/2988-shared-workspace-scope-bindings.md similarity index 98% rename from docs/en/rfcs/0000-shared-workspace-scope-bindings.md rename to docs/en/rfcs/2988-shared-workspace-scope-bindings.md index 3f16ce863a..661e42251e 100644 --- a/docs/en/rfcs/0000-shared-workspace-scope-bindings.md +++ b/docs/en/rfcs/2988-shared-workspace-scope-bindings.md @@ -1,11 +1,11 @@ --- -title: "RFC 0000: Shared workspace Scope bindings" +title: "RFC 2988: Shared workspace Scope bindings" description: "One canonical checkout identity and a shared binding namespace so binding a local workspace once applies across every PowerContext host integration while keeping existing per-host bindings compatible." --- - Proposal Name: `shared_workspace_scope_bindings` - Start Date: 2026-12-02 -- RFC PR: [oceanbase/powercontext#0000](https://github.com/oceanbase/powercontext/pull/0000) +- RFC PR: [oceanbase/powercontext#2988](https://github.com/oceanbase/powercontext/pull/2988) - Tracking Issue: [oceanbase/powercontext#2879](https://github.com/oceanbase/powercontext/issues/2879) # Summary diff --git a/docs/zh/rfcs/0000-shared-workspace-scope-bindings.md b/docs/zh/rfcs/2988-shared-workspace-scope-bindings.md similarity index 98% rename from docs/zh/rfcs/0000-shared-workspace-scope-bindings.md rename to docs/zh/rfcs/2988-shared-workspace-scope-bindings.md index 393dcda2fb..549db7f55d 100644 --- a/docs/zh/rfcs/0000-shared-workspace-scope-bindings.md +++ b/docs/zh/rfcs/2988-shared-workspace-scope-bindings.md @@ -1,11 +1,11 @@ --- -title: "RFC 0000:跨宿主共享工作区 Scope 绑定" +title: "RFC 2988:跨宿主共享工作区 Scope 绑定" description: "定义统一的本地工作区身份规则与共享绑定命名空间,使同一本地检出目录只需绑定一次即可在所有 PowerContext 宿主集成间生效,同时兼容既有按宿主隔离的旧绑定。" --- - Proposal Name: `shared_workspace_scope_bindings` - Start Date: 2026-12-02 -- RFC PR: [oceanbase/powercontext#0000](https://github.com/oceanbase/powercontext/pull/0000) +- RFC PR: [oceanbase/powercontext#2988](https://github.com/oceanbase/powercontext/pull/2988) - Tracking Issue: [oceanbase/powercontext#2879](https://github.com/oceanbase/powercontext/issues/2879) # Summary From bca7502b64fb165546d08f957f4465934fae05a1 Mon Sep 17 00:00:00 2001 From: wycocoyu <180249289+wycocoyu@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:23:24 -0800 Subject: [PATCH 5/7] feat(integrations): harden cross-platform workspace identity and CLI clearing --- .../2988-shared-workspace-scope-bindings.md | 52 +++-- .../2988-shared-workspace-scope-bindings.md | 52 +++-- .../bub/src/powercontext_bub/_git_worktree.py | 98 +++++++-- .../bub/src/powercontext_bub/scope.py | 11 +- .../plugins/powercontext/claude_code_host.py | 1 + .../powercontext_lifecycle/git_worktree.py | 98 +++++++-- .../powercontext_lifecycle/host_profile.py | 2 +- .../powercontext_lifecycle/scope_binding.py | 59 +++++- .../codex/plugins/powercontext/codex_host.py | 1 + .../powercontext_lifecycle/git_worktree.py | 98 +++++++-- .../powercontext_lifecycle/host_profile.py | 2 +- .../powercontext_lifecycle/scope_binding.py | 59 +++++- .../dsh/plugins/powercontext/lib/index.js | 142 ++++++++----- .../dsh/plugins/powercontext/src/doctor.ts | 5 + .../plugins/powercontext/src/git-worktree.ts | 118 +++++++---- .../dsh/plugins/powercontext/src/scope.ts | 21 +- .../plugins/powercontext/tests/scope.spec.ts | 29 +-- .../plugins/powercontext/git_worktree.py | 98 +++++++-- .../hermes/plugins/powercontext/provider.py | 22 +- .../plugins/powercontext/scripts/doctor.mjs | 7 +- .../plugins/powercontext/scripts/scope.mjs | 9 +- .../powercontext/shared/git-worktree.mjs | 116 ++++++---- .../plugins/powercontext/shared/runtime.mjs | 16 +- .../powercontext/tests/plugin.test.mjs | 1 + integrations/lifecycle/git-worktree.ts | 118 +++++++---- .../plugins/powercontext/lib/index.js | 99 ++++++--- .../opencode/plugins/powercontext/lib/tui.js | 99 ++++++--- .../plugins/powercontext/src/git-worktree.ts | 118 +++++++---- .../plugins/powercontext/src/scope.ts | 21 +- .../plugins/powercontext/tests/scope.spec.ts | 50 +++-- .../plugins/powercontext/tests/tui.spec.tsx | 4 +- .../plugins/powercontext/src/git-worktree.ts | 118 +++++++---- .../pi/plugins/powercontext/src/scope.ts | 21 +- .../plugins/powercontext/tests/scope.spec.ts | 29 +-- .../powercontext/hooks/git_worktree.py | 98 +++++++-- .../powercontext/scripts/workspace_scope.py | 50 ++++- .../plugins/powercontext/scripts/doctor.mjs | 9 +- .../plugins/powercontext/scripts/scope.mjs | 9 +- .../powercontext/shared/git-worktree.mjs | 116 ++++++---- .../plugins/powercontext/shared/scope.mjs | 41 ++-- src/powercontext/client/cli.py | 200 ++++++++++++++---- src/powercontext/client/session_import.py | 50 ++++- .../git_worktree.py | 98 +++++++-- .../host_profile.py | 2 +- .../scope_binding.py | 59 +++++- tests/codex_plugin/test_scope_binding.py | 8 +- .../test_shared_workspace_scope_binding.py | 34 ++- tests/test_cli_scope.py | 63 +++++- tests/test_git_worktree.py | 91 +++++++- 49 files changed, 2035 insertions(+), 687 deletions(-) diff --git a/docs/en/rfcs/2988-shared-workspace-scope-bindings.md b/docs/en/rfcs/2988-shared-workspace-scope-bindings.md index 661e42251e..ddb442fa3b 100644 --- a/docs/en/rfcs/2988-shared-workspace-scope-bindings.md +++ b/docs/en/rfcs/2988-shared-workspace-scope-bindings.md @@ -38,28 +38,38 @@ Existing deployments need no migration: - Before a checkout receives a shared binding, each host continues resolving its existing per-host binding. - Binding the checkout once writes `("shared", "workspace", )`, which takes precedence over older per-host workspace bindings in every updated host. -- Clearing a workspace binding from a host removes both the shared binding and that host's legacy workspace binding for the checkout so the old per-host binding does not reappear. +- Clearing a workspace binding from a host removes both the shared binding and that host's legacy workspace binding for the checkout so the old per-host binding does not reappear; `powercontext scope binding clear --cwd /path/to/repo` clears the shared key and every derivable legacy per-host workspace key across all supported hosts. +- Hosts that pin a resolved Scope to the session at startup (Codex and OpenCode) keep an active session on its existing Scope when a workspace binding changes mid-session; new sessions pick up the workspace binding. - A host that intentionally needs a separate Scope overrides resolution with its explicit Scope setting (for example `POWERCONTEXT_CODEX_SCOPE_ID`) or a session binding. -- Scope diagnostics probe candidate keys with `allow_default=false` and report which key matched (`shared`, the host's own workspace key, or `session`) so operators can tell when another host's legacy binding is still active. +- Scope diagnostics probe candidate keys with `allow_default=false` and report which key matched (`shared`, the host's own workspace key, or `session`) together with the resolved workspace root and its source (`git_root`, `directory`, or `home_guard`). -As required by [RFC 1345](1345_scope_organization_and_agent_integration.md), a workspace key only looks up an existing binding and never derives or creates a `scope_id`. +As required by [RFC 1345](1345_scope_organization_and_agent_integration.md), a workspace key only looks up an existing binding and never derives or creates a `scope_id`. PowerContext MCP endpoints never compute workspace keys; host hooks and plugins resolve and supply `scope_id` from each event's working directory. # Reference-level explanation ## 1. Canonical workspace identity -Given the session directory `dir` reported by the host: +Given the session directory `dir` reported by the host (expanding a leading `~` when applicable): ```text -root = `git rev-parse --show-toplevel` in dir, or dir itself when not in a Git work tree -path = real path of root (absolute, symbolic links resolved; on Windows, strip non-UNC `\\?\` and uppercase `[A-Za-z]:`) -id = lowercase hex SHA-256 of UTF-8(path) +top = `git rev-parse --show-toplevel` in dir (decoded as UTF-8 in both Python and Node.js) +root = top, except when Git produces no output, or when top != dir and top's canonical path is + the user's home directory, an ancestor of the home directory, or a filesystem root + (in which case root falls back to dir) +path = OS-canonical real path of existing directory root: + - Node.js: `fs.realpathSync.native(root)` (directory verified via `statSync`) + - Python: `os.path.realpath(root)` (plus `fcntl.F_GETPATH` on macOS so case-insensitive + APFS casing and NFD/NFC normalization match `realpathSync.native`) + - Windows: strip leading `\\?\` and convert `\\?\UNC\` to `\\`; uppercase `[A-Za-z]:` +id = lowercase hex SHA-256 of strict UTF-8(path) ``` -- Subdirectories of a checkout share the checkout's `root`. Outside Git, each directory is its own workspace. -- On Windows, resolving symbolic links and normalizing extended-length `\\?\C:\...` prefixes and drive-letter casing to uppercase `C:\...` ensures Python and Node.js hash identical bytes for the same directory. -- When `root` contains a trailing segment that does not exist yet, both runtimes resolve symbolic links on the deepest existing ancestor and join the remaining relative segments before hashing. -- The shared lifecycle helpers (`src/powercontext_integration_lifecycle/git_worktree.py` and `integrations/lifecycle/git-worktree.ts`) compute both the shared checkout roots and the host's legacy paths from the single Git invocation introduced in [PR #2875](https://github.com/oceanbase/powercontext/pull/2875), starting no extra Git subprocesses. +If `root` does not exist on disk as a directory or its canonical path cannot be strictly encoded as UTF-8, the host omits the `shared` workspace key for that location while still sending any remaining candidate keys. + +- Subdirectories of a checkout share the checkout's `root`. Outside Git, each directory is its own workspace. Git submodules report their own worktree top level and remain independent workspaces. +- Guarding `$HOME`, ancestors of `$HOME`, and filesystem roots prevents a dotfiles repository initialized in `$HOME` (or a stray `.git` at `/`) from collapsing unrelated subdirectories onto one workspace identity. +- Legacy per-host `:workspace` derivations are frozen byte-for-byte to each host's pre-RFC implementation (`HostProfile.legacy_workspace_binding` defaults to `False` and is enabled only on pre-existing hosts). +- The shared lifecycle helpers (`src/powercontext_integration_lifecycle/git_worktree.py` and `integrations/lifecycle/git-worktree.ts`) compute both the shared checkout roots and the host's legacy paths from the single Git invocation introduced in [PR #2875](https://github.com/oceanbase/powercontext/pull/2875), starting no extra Git subprocesses ( Python 3.9+ standard library compatible). ## 2. Reserved `shared` namespace @@ -71,7 +81,7 @@ Shared workspace bindings use: `ScopeBindingKey.integration` is already an unconstrained non-empty string (`1..128` characters) on the Server. `shared` is reserved and rejected as a host integration identifier in the host registry and capability manifest checks. -## 3. Resolution order +## 3. Resolution order and session interaction `POST /v1/scope-bindings/resolve` evaluates `explicit_scope_id`, then `binding_keys` in order, then the Server default Scope: @@ -85,12 +95,15 @@ Shared workspace bindings use: Nearer locations win over main-checkout fallbacks (preserving #2875), and `shared` wins over legacy per-host keys at the same location so one new bind unifies every host immediately. Because Server resolution is unchanged, a matched binding whose target Scope was deleted still stops resolution with `409 scope_binding_target_missing`. -## 4. Bind, clear, CLI, and diagnostics +Codex and OpenCode persist the Scope resolved at session start to `(host, "session", session_id)` when no explicit Scope is configured. Because session bindings precede workspace bindings, binding a workspace mid-session leaves already-pinned sessions on their original Scope and applies to newly started sessions. + +## 4. Bind, clear, CLI, offline maintenance, and diagnostics -- **Bind**: Host workspace helpers and `powercontext scope binding set --cwd ` write `("shared", "workspace", shared_id_own)`. In a linked worktree, this binds the worktree itself. -- **Clear**: Host workspace helpers remove `("shared", "workspace", shared_id_own)` and `(host, "workspace", legacy_id_own)`, reporting `cleared=true` when either existed. `powercontext scope binding clear --cwd ` clears the shared key by default, or both the shared key and ``'s legacy key when `--integration ` is supplied. +- **Bind**: Host workspace helpers write `("shared", "workspace", shared_id_own)` for an existing directory. `powercontext scope binding set --cwd ` validates that `` exists, rejects non-`shared` `--integration` flags, writes the `shared` binding, and prints the resolved workspace root in human output. +- **Clear**: Host workspace helpers remove `("shared", "workspace", shared_id_own)` and `(host, "workspace", legacy_id_own)`, reporting `cleared=true` when either existed. `powercontext scope binding clear --cwd ` clears `shared` plus every derivable legacy `:workspace` key across all 10 existing workspace hosts when `--integration` is omitted (`--integration shared` clears only `shared`; `--integration ` clears `shared` and ``). +- **Offline maintenance for removed directories**: When `` has already been removed from disk (for example after `git worktree remove`), `powercontext scope binding clear --cwd ` and `powercontext import-sessions` derive a best-effort canonical path from the deepest existing ancestor so stale bindings can still be cleared and historical Codex sessions imported. - **CLI resolution**: `powercontext scope resolve` supports `--integration shared` as well as all workspace-capable host names (`claude-code`, `codex`, `dsh`, `hermes`, `kimi-code`, `opencode`, `pi`, `workbuddy`, `zcode`, `bub`), emitting the exact key sequence that host sends. -- **Diagnostics**: Host doctor and Scope diagnostic scripts (never per-turn hooks) probe `binding_keys` one at a time with `allow_default=false` to report the winning key's `integration` and `kind`. +- **Diagnostics**: Host doctor and Scope diagnostic scripts (never per-turn hooks) probe `binding_keys` one at a time with `allow_default=false` to report `matched_key`, `resolved_root`, and `root_source`. # Drawbacks @@ -108,9 +121,12 @@ Nearer locations win over main-checkout fallbacks (preserving #2875), and `share - [RFC 1345](1345_scope_organization_and_agent_integration.md) defines Server-owned opaque `scope_id` values and lookup-only external `ScopeBindingKey` records. - [PR #2875](https://github.com/oceanbase/powercontext/pull/2875) established ordered `binding_keys` fallback from a linked Git worktree to its main checkout across Python and TypeScript lifecycle helpers without Server changes. -# Unresolved questions +# Unresolved questions and boundaries -None. +- **Identical container or devcontainer paths across machines**: Workspace identity hashes the canonical local checkout path without a machine identifier. Two machines or devcontainers mounting a repository at the exact same path (such as `/workspaces/app`) and sharing one PowerContext Server share that binding; separate paths on different machines remain distinct checkouts. +- **Git unavailable, timed out, or refused (`safe.directory`)**: When Git cannot report a top level within the helper budget, `root` falls back to `dir` (`root_source = "directory"` in diagnostics) rather than failing closed. +- **Legacy subdirectory bindings on cwd-keyed hosts**: `powercontext scope binding clear --cwd ` derives legacy keys for `` and its Git top level; a pre-RFC binding created from an arbitrary nested subdirectory in a cwd-keyed host (`dsh`, `opencode`, `pi`, `kimi-code`, `hermes`, `bub`) must be cleared with `--cwd` pointing at that subdirectory if no shared binding shadows it. +- **Native Windows runner verification**: Python `ntpath.realpath` and Node `fs.realpathSync.native` both delegate to `GetFinalPathNameByHandleW`; cross-runtime path-vector parity is exercised in CI on `windows-latest`. # Future possibilities diff --git a/docs/zh/rfcs/2988-shared-workspace-scope-bindings.md b/docs/zh/rfcs/2988-shared-workspace-scope-bindings.md index 549db7f55d..4027bea6e0 100644 --- a/docs/zh/rfcs/2988-shared-workspace-scope-bindings.md +++ b/docs/zh/rfcs/2988-shared-workspace-scope-bindings.md @@ -38,28 +38,36 @@ powercontext scope binding set scp_repo --cwd /path/to/repo - 在某个检出目录写入共享绑定之前,各宿主继续命中各自原有的宿主工作区绑定。 - 在该检出目录重新绑定一次即会写入 `("shared", "workspace", )`,所有已升级宿主均会优先命中该共享绑定并覆盖旧的宿主级绑定。 -- 在宿主中清除工作区绑定会同时删除该检出目录的共享绑定与当前宿主的旧工作区绑定,避免清除后旧绑定重新生效。 +- 在宿主中清除工作区绑定会同时删除该检出目录的共享绑定与当前宿主的旧工作区绑定,避免清除后旧绑定重新生效;运行 `powercontext scope binding clear --cwd /path/to/repo` 默认一并清除共享键及该目录可推导出的全部存量宿主旧工作区键。 +- 在会话启动时自动钉住已解析 Scope 的宿主(Codex 与 OpenCode)在会话中途修改工作区绑定时,已开启的活跃会话保持原 Scope,新启动会话采用新的工作区绑定。 - 若某个宿主确实需要使用独立 Scope,可通过显式 Scope 配置(例如 `POWERCONTEXT_CODEX_SCOPE_ID`)或会话级绑定覆盖。 -- 各宿主 Scope 诊断工具以 `allow_default=false` 逐键探测候选绑定键,并报告实际命中的键来源(`shared`、宿主自有工作区键或 `session`),便于排查其他宿主遗留绑定仍在生效的情况。 +- 各宿主 Scope 诊断工具以 `allow_default=false` 逐键探测候选绑定键,并同时报告命中的键来源(`shared`、宿主自有工作区键或 `session`)以及实际采用的规范化根路径与来源(`git_root`、`directory` 或 `home_guard`)。 -遵循 [RFC 1345](1345_scope_organization_and_agent_integration.md) 约束,工作区键仅用于查找既有绑定,绝不直接派生或自动创建 `scope_id`。 +遵循 [RFC 1345](1345_scope_organization_and_agent_integration.md) 约束,工作区键仅用于查找既有绑定,绝不直接派生或自动创建 `scope_id`。PowerContext MCP 服务端点永远不自行计算工作区键,由宿主层利用每次事件自带的工作目录解析并注入 `scope_id`。 # Reference-level explanation ## 1. 规范化工作区身份 -给定宿主为当前会话上报的目录 `dir`: +给定宿主为当前会话上报的目录 `dir`(存在前导 `~` 时先展开): ```text -root = 在 dir 中执行 `git rev-parse --show-toplevel` 的结果,不在 Git 工作树内时取 dir 自身 -path = root 的真实物理路径(绝对路径且解析符号链接;Windows 下剥离非 UNC 的 `\\?\` 前缀并将盘符 `[A-Za-z]:` 统一为大写) -id = UTF-8(path) 的小写十六进制 SHA-256 +top = 在 dir 中执行 `git rev-parse --show-toplevel` 的输出(Python 与 Node.js 均按 UTF-8 解码) +root = top;但若 Git 无输出,或当 top != dir 且 top 的规范路径等于用户家目录、家目录的祖先或文件系统根目录时, + root 回退为 dir 自身 +path = 已存在目录 root 的操作系统规范路径: + - Node.js:`fs.realpathSync.native(root)`(并通过 `statSync` 确认为目录) + - Python: `os.path.realpath(root)`(在 macOS 上进一步通过 `fcntl.F_GETPATH` 获取内核规范大小写与 NFD/NFC 形式,与 `realpathSync.native` 保持逐字节一致) + - Windows:剥离前导 `\\?\` 并将 `\\?\UNC\` 转为 `\\`,盘符 `[A-Za-z]:` 统一为大写 +id = 严格 UTF-8(path) 字节序列的小写十六进制 SHA-256 ``` -- 同一检出目录内的所有子目录共享同一个 `root`。在 Git 工作树之外,每个目录各自构成独立工作区。 -- 在 Windows 下,解析符号链接并将扩展路径前缀 `\\?\C:\...` 与盘符大小写统一规范化为大写 `C:\...`,保证 Python 与 Node.js 对同一目录产出完全一致的字节序列与哈希。 -- 当 `root` 末尾包含尚未创建的子路径时,两种运行时均先解析最深已存在祖先目录的符号链接,再拼接剩余相对路径段进行哈希。 -- 共享生命周期辅助模块(`src/powercontext_integration_lifecycle/git_worktree.py` 与 `integrations/lifecycle/git-worktree.ts`)复用 [PR #2875](https://github.com/oceanbase/powercontext/pull/2875) 的单次 Git 调用同时派生共享检出根路径与宿主旧兼容路径,不额外启动 Git 子进程。 +若 `root` 在磁盘上不是已存在的目录,或其规范路径无法按严格 UTF-8 编码,则宿主在该位置不发送 `shared` 工作区键,其余候选键照常发送。 + +- 同一检出目录内的所有子目录共享同一个 `root`。在 Git 工作树之外,每个目录各自构成独立工作区。Git submodule 上报其自身工作树顶层,作为独立工作区处理。 +- 家目录、家目录祖先及文件系统根目录守卫可防止用户在家目录执行 `git init`(如管理 dotfiles)或根目录存在残留 `.git` 时,将家目录下所有无关非仓库目录折叠为同一工作区。 +- 存量宿主的旧 `:workspace` 派生逻辑按本 RFC 之前的实现逐字节冻结(`HostProfile.legacy_workspace_binding` 默认设为 `False`,仅在既有宿主中显式开启)。 +- 共享生命周期辅助模块(`src/powercontext_integration_lifecycle/git_worktree.py` 与 `integrations/lifecycle/git-worktree.ts`)复用 [PR #2875](https://github.com/oceanbase/powercontext/pull/2875) 的单次 Git 调用同时派生共享检出根路径与宿主旧兼容路径,不额外启动 Git 子进程,并兼容 Python 3.9+ 标准库。 ## 2. 保留命名空间 `shared` @@ -71,26 +79,29 @@ id = UTF-8(path) 的小写十六进制 SHA-256 Server 端 `ScopeBindingKey.integration` 本身为非空自由字符串(`1..128` 字符)。宿主注册表与能力清单校验将 `shared` 列为保留名,禁止任何宿主集成使用该名称。 -## 3. 解析顺序 +## 3. 解析顺序与会话交互 `POST /v1/scope-bindings/resolve` 依次评估 `explicit_scope_id`、有序 `binding_keys` 与 Server 默认 Scope: 1. 显式 Scope 配置(`explicit_scope_id`)。 2. 会话绑定:当宿主提供会话 ID 时发送 `(host, "session", session_id)`。 3. 当前检出目录共享绑定:`("shared", "workspace", shared_id_own)`。 -4. 当前检出目录宿主绑定:`(host, "workspace", legacy_id_own)`(无历史兼容包袱的新增宿主可省略此项)。 +4. 当前检出目录宿主绑定:`(host, "workspace", legacy_id_own)`(无历史兼容包袱的新增宿主省略此项)。 5. 链接工作树所属主检出目录共享绑定:`("shared", "workspace", shared_id_main)`。 6. 链接工作树所属主检出目录宿主绑定:`(host, "workspace", legacy_id_main)`。 7. Server 默认 Scope(`allow_default=true`)。 更近的位置优先于主检出目录回退(保持 #2875 语义),同一位置下 `shared` 优先于宿主旧私有键,从而保证重新绑定一次即可统一所有宿主。由于 Server 解析逻辑保持不变,若命中的绑定所指向的目标 Scope 已被删除,解析仍按契约停止并返回 `409 scope_binding_target_missing`。 -## 4. 绑定、清除、CLI 与诊断 +Codex 与 OpenCode 在未配置显式 Scope 时会将新会话首次解析出的 Scope 写入 `(host, "session", session_id)`。由于会话绑定排在工作区绑定之前,在会话中途修改工作区绑定不会改变已钉住的旧会话,新开启的会话将自动命中新的工作区绑定。 + +## 4. 绑定、清除、CLI、离线维护与诊断 -- **绑定(Bind)**:各宿主工作区脚本与 `powercontext scope binding set --cwd ` 统一写入 `("shared", "workspace", shared_id_own)`。在链接工作树中执行时绑定该工作树自身。 -- **清除(Clear)**:各宿主工作区脚本同时清除 `("shared", "workspace", shared_id_own)` 与 `(host, "workspace", legacy_id_own)`,任一存在即返回 `cleared=true`。`powercontext scope binding clear --cwd ` 默认清除共享键;当显式传入 `--integration ` 时一并清除共享键与 `` 的旧工作区键。 +- **绑定(Bind)**:各宿主工作区脚本对已存在目录写入 `("shared", "workspace", shared_id_own)`。`powercontext scope binding set --cwd ` 校验 `` 存在、拒绝非 `shared` 的 `--integration` 参数,写入共享绑定并在人类可读输出中打印采用的根路径。 +- **清除(Clear)**:各宿主工作区脚本同时清除 `("shared", "workspace", shared_id_own)` 与 `(host, "workspace", legacy_id_own)`,任一存在即返回 `cleared=true`。`powercontext scope binding clear --cwd ` 在未指定 `--integration` 时默认清除 `shared` 及全部 10 个存量宿主在该目录可推导出的旧工作区键(`--integration shared` 仅清 `shared`,`--integration ` 清 `shared` 与 ``)。 +- **已删除目录的离线维护**:当 `` 已从磁盘删除(例如已执行 `git worktree remove`)时,`powercontext scope binding clear --cwd ` 与 `powercontext import-sessions` 通过最深已存在祖先目录尽力推导规范路径,使残留绑定仍可被清除、已删工作树的历史 Codex 会话仍可导入。 - **CLI 解析**:`powercontext scope resolve` 支持 `--integration shared` 及全部支持工作区绑定的宿主名(`claude-code`、`codex`、`dsh`、`hermes`、`kimi-code`、`opencode`、`pi`、`workbuddy`、`zcode`、`bub`),输出与对应宿主完全一致的键序列。 -- **诊断(Diagnostics)**:宿主 doctor 与 Scope 诊断脚本(仅限诊断命令,不在每轮对话 Hook 中执行)通过 `allow_default=false` 逐键探测 `binding_keys`,直接报告实际命中键的 `integration` 与 `kind`。 +- **诊断(Diagnostics)**:宿主 doctor 与 Scope 诊断脚本(仅限诊断命令,不在每轮对话 Hook 中执行)通过 `allow_default=false` 逐键探测 `binding_keys`,报告 `matched_key`、`resolved_root` 与 `root_source`。 # Drawbacks @@ -108,9 +119,12 @@ Server 端 `ScopeBindingKey.integration` 本身为非空自由字符串(`1..12 - [RFC 1345](1345_scope_organization_and_agent_integration.md) 定义了 Server 拥有的不透明 `scope_id` 以及仅用于查找绑定的外部 `ScopeBindingKey`。 - [PR #2875](https://github.com/oceanbase/powercontext/pull/2875) 在不改动 Server 的前提下,通过 Python 与 TypeScript 共享生命周期辅助模块实现了链接 Git 工作树向主检出目录的有序 `binding_keys` 回退。 -# Unresolved questions +# Unresolved questions and boundaries -无。 +- **多机或容器相同挂载路径边界**:工作区身份仅哈希本地检出目录规范路径,不引入机器 ID。当多台机器或多个 devcontainer 在完全相同的路径(例如 `/workspaces/app`)挂载仓库并连接同一个 PowerContext Server 时,它们会共享该路径对应的工作区绑定;不同路径仍保持独立。 +- **Git 未安装、超时或 `safe.directory` 拒绝**:当 Git 在超时预算内无法返回顶层目录时,`root` 安全回退为 `dir`(诊断中 `root_source = "directory"`),不会阻断会话请求。 +- **按 `cwd` 派生宿主的子目录遗留绑定**:`powercontext scope binding clear --cwd ` 会清除 `` 及其 Git 顶层对应的旧键;若升级前曾在 `dsh`、`opencode`、`pi`、`kimi-code`、`hermes` 或 `bub` 的某个深层子目录单独创建过旧绑定且当前不存在遮蔽它的共享绑定,则需对该子目录传入 `--cwd` 予以清除。 +- **Windows 原生环境校验**:Python `ntpath.realpath` 与 Node `fs.realpathSync.native` 底层均调用 `GetFinalPathNameByHandleW`,跨运行时路径向量一致性在 CI 的 `windows-latest` 任务中持续验证。 # Future possibilities diff --git a/integrations/bub/src/powercontext_bub/_git_worktree.py b/integrations/bub/src/powercontext_bub/_git_worktree.py index 721e66c091..65f6747778 100644 --- a/integrations/bub/src/powercontext_bub/_git_worktree.py +++ b/integrations/bub/src/powercontext_bub/_git_worktree.py @@ -25,6 +25,7 @@ import hashlib import os import subprocess +import sys import time from shutil import which @@ -59,33 +60,95 @@ def normalize_windows_real_path(path: str, *, windows: bool = os.name == "nt") - return resolved -def real_workspace_path(path: str) -> str: - """Return the canonical real path of ``path`` with symbolic links resolved and Windows drive prefixes normalized.""" +def _darwin_canonical_path(path: str) -> str: + if sys.platform != "darwin": + return path + import fcntl + + fd = os.open(path, os.O_RDONLY) + try: + raw = fcntl.fcntl(fd, fcntl.F_GETPATH, b"\x00" * 1024) + finally: + os.close(fd) + return os.fsdecode(raw.split(b"\x00", 1)[0]) + + +def real_workspace_path(path: str) -> str | None: + """Return the OS-canonical real path of an existing directory ``path``, or ``None`` when unavailable.""" + + expanded = os.path.expanduser(path) + if not expanded or not os.path.isdir(expanded): + return None + try: + resolved = _darwin_canonical_path(os.path.realpath(expanded)) + except OSError: + return None + if not os.path.isdir(resolved): + return None + return normalize_windows_real_path(resolved) - return normalize_windows_real_path(os.path.realpath(path)) +def workspace_identity(path: str) -> str | None: + """Return the lowercase hex SHA-256 of the UTF-8 canonical real path of existing directory ``path``.""" -def workspace_identity(path: str) -> str: - """Return the lowercase hex SHA-256 of the canonical real path of ``path``.""" + canonical = real_workspace_path(path) + if canonical is None: + return None + try: + encoded = canonical.encode("utf-8") + except UnicodeEncodeError: + return None + return hashlib.sha256(encoded).hexdigest() - if os.name == "nt": - return hashlib.sha256(real_workspace_path(path).encode("utf-8", errors="surrogatepass")).hexdigest() - return hashlib.sha256(os.fsencode(real_workspace_path(path))).hexdigest() + +def _guarded_git_top(cwd: str, top: str | None) -> tuple[str | None, str]: + if top is None: + return None, "directory" + top_real = real_workspace_path(top) + if top_real is None: + return None, "directory" + cwd_real = real_workspace_path(cwd) + if cwd_real is not None and cwd_real == top_real: + return top, "git_root" + if os.path.dirname(top_real) == top_real: + return None, "home_guard" + home_real = real_workspace_path("~") + if home_real is not None: + current = home_real + while True: + if current == top_real: + return None, "home_guard" + parent = os.path.dirname(current) + if parent == current: + break + current = parent + return top, "git_root" + + +def describe_workspace_root(cwd: str, *, timeout: float = 2.0) -> tuple[str | None, str]: + """Return ``(canonical_root, root_source)`` for diagnostics and operator CLI output.""" + + raw_top, _git_dir, _common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + effective_top, source = _guarded_git_top(cwd, raw_top) + return real_workspace_path(effective_top or cwd), source def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[tuple[str, str | None]]: """Return ``(shared_root, host_path)`` pairs for ``cwd`` and, in a linked worktree, its main checkout. - ``shared_root`` is always the Git top level when inside a work tree, or ``cwd`` outside Git, so every host derives - the same shared workspace key. ``host_path`` preserves each host's legacy path rule (the Git top level when - ``git_root`` is true, otherwise ``cwd`` and its counterpart subdirectory in the main checkout) from the same Git - invocation, or ``None`` when the main-checkout counterpart is unavailable or links back to ``cwd``. + ``shared_root`` is always the Git top level when inside a work tree (unless guarded by home/filesystem-root rules), + or ``cwd`` outside Git, so every host derives the same shared workspace key. ``host_path`` preserves each host's + legacy path rule from the same Git invocation, or ``None`` when the main-checkout counterpart is unavailable or + links back to ``cwd``. """ deadline = time.monotonic() + timeout - top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + raw_top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + top, _source = _guarded_git_top(cwd, raw_top) shared_own = top or cwd - host_own = shared_own if git_root else cwd + host_own = (raw_top or cwd) if git_root else cwd + if top is None: + return [(shared_own, host_own)] main_root = _main_worktree_root(top, git_dir, common) if main_root is None or common is None: return [(shared_own, host_own)] @@ -124,8 +187,10 @@ def workspace_paths(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[s def _git_output(cwd: str, arguments: tuple[str, ...], timeout: float) -> str: """Return what Git prints for ``arguments`` in ``cwd``, or an empty string when it fails or time is up.""" + if timeout <= 0 or not cwd or not os.path.isdir(cwd): + return "" executable = which("git") - if executable is None or timeout <= 0: + if executable is None: return "" try: completed = subprocess.run( # noqa: S603 - git executable and arguments are integration-owned. @@ -133,7 +198,8 @@ def _git_output(cwd: str, arguments: tuple[str, ...], timeout: float) -> str: cwd=cwd, check=True, capture_output=True, - text=True, + encoding="utf-8", + errors="surrogateescape", timeout=timeout, ) except (OSError, subprocess.SubprocessError): diff --git a/integrations/bub/src/powercontext_bub/scope.py b/integrations/bub/src/powercontext_bub/scope.py index 8b07b2767b..f41101b712 100644 --- a/integrations/bub/src/powercontext_bub/scope.py +++ b/integrations/bub/src/powercontext_bub/scope.py @@ -53,17 +53,22 @@ def workspace_binding_keys(workspace: str | Path | None) -> list[ScopeBindingKey return [] keys: list[ScopeBindingKey] = [] for shared_root, host_path in workspace_locations(str(Path(workspace).expanduser()), git_root=False): - keys.append(_shared_workspace_key(shared_root)) + shared_key = _shared_workspace_key(shared_root) + if shared_key is not None: + keys.append(shared_key) if host_path is not None: keys.append(_legacy_workspace_key(host_path)) return keys -def _shared_workspace_key(workspace: str | Path) -> ScopeBindingKey: +def _shared_workspace_key(workspace: str | Path) -> ScopeBindingKey | None: + identity = workspace_identity(str(Path(workspace).expanduser())) + if identity is None: + return None return ScopeBindingKey( integration=SHARED_WORKSPACE_INTEGRATION, kind="workspace", - external_id=workspace_identity(str(Path(workspace).expanduser())), + external_id=identity, ) diff --git a/integrations/claude-code/plugins/powercontext/claude_code_host.py b/integrations/claude-code/plugins/powercontext/claude_code_host.py index b4bb448ee0..8ea285bf29 100644 --- a/integrations/claude-code/plugins/powercontext/claude_code_host.py +++ b/integrations/claude-code/plugins/powercontext/claude_code_host.py @@ -28,4 +28,5 @@ directory_variable="POWERCONTEXT_CLAUDE_BOOTSTRAP_STATE_DIR", plugin_data_variable="CLAUDE_PLUGIN_DATA", ), + legacy_workspace_binding=True, ) diff --git a/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/git_worktree.py b/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/git_worktree.py index 721e66c091..65f6747778 100644 --- a/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/git_worktree.py +++ b/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/git_worktree.py @@ -25,6 +25,7 @@ import hashlib import os import subprocess +import sys import time from shutil import which @@ -59,33 +60,95 @@ def normalize_windows_real_path(path: str, *, windows: bool = os.name == "nt") - return resolved -def real_workspace_path(path: str) -> str: - """Return the canonical real path of ``path`` with symbolic links resolved and Windows drive prefixes normalized.""" +def _darwin_canonical_path(path: str) -> str: + if sys.platform != "darwin": + return path + import fcntl + + fd = os.open(path, os.O_RDONLY) + try: + raw = fcntl.fcntl(fd, fcntl.F_GETPATH, b"\x00" * 1024) + finally: + os.close(fd) + return os.fsdecode(raw.split(b"\x00", 1)[0]) + + +def real_workspace_path(path: str) -> str | None: + """Return the OS-canonical real path of an existing directory ``path``, or ``None`` when unavailable.""" + + expanded = os.path.expanduser(path) + if not expanded or not os.path.isdir(expanded): + return None + try: + resolved = _darwin_canonical_path(os.path.realpath(expanded)) + except OSError: + return None + if not os.path.isdir(resolved): + return None + return normalize_windows_real_path(resolved) - return normalize_windows_real_path(os.path.realpath(path)) +def workspace_identity(path: str) -> str | None: + """Return the lowercase hex SHA-256 of the UTF-8 canonical real path of existing directory ``path``.""" -def workspace_identity(path: str) -> str: - """Return the lowercase hex SHA-256 of the canonical real path of ``path``.""" + canonical = real_workspace_path(path) + if canonical is None: + return None + try: + encoded = canonical.encode("utf-8") + except UnicodeEncodeError: + return None + return hashlib.sha256(encoded).hexdigest() - if os.name == "nt": - return hashlib.sha256(real_workspace_path(path).encode("utf-8", errors="surrogatepass")).hexdigest() - return hashlib.sha256(os.fsencode(real_workspace_path(path))).hexdigest() + +def _guarded_git_top(cwd: str, top: str | None) -> tuple[str | None, str]: + if top is None: + return None, "directory" + top_real = real_workspace_path(top) + if top_real is None: + return None, "directory" + cwd_real = real_workspace_path(cwd) + if cwd_real is not None and cwd_real == top_real: + return top, "git_root" + if os.path.dirname(top_real) == top_real: + return None, "home_guard" + home_real = real_workspace_path("~") + if home_real is not None: + current = home_real + while True: + if current == top_real: + return None, "home_guard" + parent = os.path.dirname(current) + if parent == current: + break + current = parent + return top, "git_root" + + +def describe_workspace_root(cwd: str, *, timeout: float = 2.0) -> tuple[str | None, str]: + """Return ``(canonical_root, root_source)`` for diagnostics and operator CLI output.""" + + raw_top, _git_dir, _common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + effective_top, source = _guarded_git_top(cwd, raw_top) + return real_workspace_path(effective_top or cwd), source def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[tuple[str, str | None]]: """Return ``(shared_root, host_path)`` pairs for ``cwd`` and, in a linked worktree, its main checkout. - ``shared_root`` is always the Git top level when inside a work tree, or ``cwd`` outside Git, so every host derives - the same shared workspace key. ``host_path`` preserves each host's legacy path rule (the Git top level when - ``git_root`` is true, otherwise ``cwd`` and its counterpart subdirectory in the main checkout) from the same Git - invocation, or ``None`` when the main-checkout counterpart is unavailable or links back to ``cwd``. + ``shared_root`` is always the Git top level when inside a work tree (unless guarded by home/filesystem-root rules), + or ``cwd`` outside Git, so every host derives the same shared workspace key. ``host_path`` preserves each host's + legacy path rule from the same Git invocation, or ``None`` when the main-checkout counterpart is unavailable or + links back to ``cwd``. """ deadline = time.monotonic() + timeout - top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + raw_top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + top, _source = _guarded_git_top(cwd, raw_top) shared_own = top or cwd - host_own = shared_own if git_root else cwd + host_own = (raw_top or cwd) if git_root else cwd + if top is None: + return [(shared_own, host_own)] main_root = _main_worktree_root(top, git_dir, common) if main_root is None or common is None: return [(shared_own, host_own)] @@ -124,8 +187,10 @@ def workspace_paths(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[s def _git_output(cwd: str, arguments: tuple[str, ...], timeout: float) -> str: """Return what Git prints for ``arguments`` in ``cwd``, or an empty string when it fails or time is up.""" + if timeout <= 0 or not cwd or not os.path.isdir(cwd): + return "" executable = which("git") - if executable is None or timeout <= 0: + if executable is None: return "" try: completed = subprocess.run( # noqa: S603 - git executable and arguments are integration-owned. @@ -133,7 +198,8 @@ def _git_output(cwd: str, arguments: tuple[str, ...], timeout: float) -> str: cwd=cwd, check=True, capture_output=True, - text=True, + encoding="utf-8", + errors="surrogateescape", timeout=timeout, ) except (OSError, subprocess.SubprocessError): diff --git a/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/host_profile.py b/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/host_profile.py index 93749182b0..c4ffae939b 100644 --- a/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/host_profile.py +++ b/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/host_profile.py @@ -41,4 +41,4 @@ class HostProfile: prompt_id_field: str diagnostics: DiagnosticThrottle bootstrap_state: BootstrapState - legacy_workspace_binding: bool = True + legacy_workspace_binding: bool = False diff --git a/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/scope_binding.py b/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/scope_binding.py index a45a721abd..7342e113b4 100644 --- a/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/scope_binding.py +++ b/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/scope_binding.py @@ -20,15 +20,23 @@ from __future__ import annotations import json +import os from collections.abc import Mapping from dataclasses import dataclass, field +from hashlib import sha256 from http.client import HTTPException +from pathlib import Path from time import monotonic from typing import Any, Protocol from urllib.error import HTTPError from urllib.request import Request -from .git_worktree import SHARED_WORKSPACE_INTEGRATION, workspace_identity, workspace_locations +from .git_worktree import ( + SHARED_WORKSPACE_INTEGRATION, + describe_workspace_root, + workspace_identity, + workspace_locations, +) from .host_profile import HostProfile from .scope_binding_errors import ( ScopeBindingError, @@ -133,7 +141,10 @@ def clear_scope_binding( """Remove the shared workspace binding and, when enabled, this host's legacy workspace binding.""" shared_root, host_path = workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline))[0] - keys = [shared_workspace_key(shared_root)] + keys: list[dict[str, str]] = [] + shared_key = shared_workspace_key(shared_root) + if shared_key is not None: + keys.append(shared_key) if host.legacy_workspace_binding and host_path is not None: keys.append(_workspace_key(host, host_path)) cleared_any = False @@ -162,9 +173,16 @@ def diagnose_scope_binding( ) -> dict[str, Any]: """Resolve the active Scope and identify which candidate binding key matched (for diagnostics, never hooks).""" + resolved_root, root_source = describe_workspace_root(cwd, timeout=_git_timeout(deadline)) if settings.scope_id is not None: scope_id = resolve_scope_id(host, cwd, session_id=session_id, settings=settings, deadline=deadline) - return {"scope_id": scope_id, "source": "explicit", "matched_key": None} + return { + "scope_id": scope_id, + "source": "explicit", + "matched_key": None, + "resolved_root": resolved_root, + "root_source": root_source, + } for key in binding_keys(host, cwd, session_id=session_id, deadline=deadline): try: response = _request_json( @@ -181,7 +199,13 @@ def diagnose_scope_binding( scope_id = response.get("scope_id") if not isinstance(scope_id, str) or not scope_id.strip() or scope_id != scope_id.strip(): raise ScopeBindingError - return {"scope_id": scope_id, "source": "binding", "matched_key": key} + return { + "scope_id": scope_id, + "source": "binding", + "matched_key": key, + "resolved_root": resolved_root, + "root_source": root_source, + } response = _request_json( "/v1/scope-bindings/resolve", {"explicit_scope_id": None, "binding_keys": [], "allow_default": True}, @@ -192,7 +216,13 @@ def diagnose_scope_binding( scope_id = response.get("scope_id") if not isinstance(scope_id, str) or not scope_id.strip() or scope_id != scope_id.strip(): raise ScopeBindingError - return {"scope_id": scope_id, "source": "default", "matched_key": None} + return { + "scope_id": scope_id, + "source": "default", + "matched_key": None, + "resolved_root": resolved_root, + "root_source": root_source, + } def binding_keys( @@ -212,7 +242,9 @@ def binding_keys( if session_id is not None: keys.append(session_binding_key(host, session_id)) for shared_root, host_path in workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline)): - keys.append(shared_workspace_key(shared_root)) + shared_key = shared_workspace_key(shared_root) + if shared_key is not None: + keys.append(shared_key) if host.legacy_workspace_binding and host_path is not None: keys.append(_workspace_key(host, host_path)) return keys @@ -230,15 +262,22 @@ def workspace_binding_key(host: HostProfile, cwd: str, *, deadline: float | None del host shared_root, _host_path = workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline))[0] - return shared_workspace_key(shared_root) + key = shared_workspace_key(shared_root) + if key is None: + raise ScopeBindingError + return key -def shared_workspace_key(path: str) -> dict[str, str]: - return {"integration": SHARED_WORKSPACE_INTEGRATION, "kind": "workspace", "external_id": workspace_identity(path)} +def shared_workspace_key(path: str) -> dict[str, str] | None: + identity = workspace_identity(path) + if identity is None: + return None + return {"integration": SHARED_WORKSPACE_INTEGRATION, "kind": "workspace", "external_id": identity} def _workspace_key(host: HostProfile, path: str) -> dict[str, str]: - return {"integration": host.integration, "kind": "workspace", "external_id": workspace_identity(path)} + external_id = sha256(os.fsencode(Path(path).expanduser().resolve())).hexdigest() + return {"integration": host.integration, "kind": "workspace", "external_id": external_id} def _request_json( diff --git a/integrations/codex/plugins/powercontext/codex_host.py b/integrations/codex/plugins/powercontext/codex_host.py index 82901c9a60..37a1e21aeb 100644 --- a/integrations/codex/plugins/powercontext/codex_host.py +++ b/integrations/codex/plugins/powercontext/codex_host.py @@ -29,4 +29,5 @@ directory_variable="POWERCONTEXT_BOOTSTRAP_STATE_DIR", plugin_data_variable="PLUGIN_DATA", ), + legacy_workspace_binding=True, ) diff --git a/integrations/codex/plugins/powercontext/powercontext_lifecycle/git_worktree.py b/integrations/codex/plugins/powercontext/powercontext_lifecycle/git_worktree.py index 721e66c091..65f6747778 100644 --- a/integrations/codex/plugins/powercontext/powercontext_lifecycle/git_worktree.py +++ b/integrations/codex/plugins/powercontext/powercontext_lifecycle/git_worktree.py @@ -25,6 +25,7 @@ import hashlib import os import subprocess +import sys import time from shutil import which @@ -59,33 +60,95 @@ def normalize_windows_real_path(path: str, *, windows: bool = os.name == "nt") - return resolved -def real_workspace_path(path: str) -> str: - """Return the canonical real path of ``path`` with symbolic links resolved and Windows drive prefixes normalized.""" +def _darwin_canonical_path(path: str) -> str: + if sys.platform != "darwin": + return path + import fcntl + + fd = os.open(path, os.O_RDONLY) + try: + raw = fcntl.fcntl(fd, fcntl.F_GETPATH, b"\x00" * 1024) + finally: + os.close(fd) + return os.fsdecode(raw.split(b"\x00", 1)[0]) + + +def real_workspace_path(path: str) -> str | None: + """Return the OS-canonical real path of an existing directory ``path``, or ``None`` when unavailable.""" + + expanded = os.path.expanduser(path) + if not expanded or not os.path.isdir(expanded): + return None + try: + resolved = _darwin_canonical_path(os.path.realpath(expanded)) + except OSError: + return None + if not os.path.isdir(resolved): + return None + return normalize_windows_real_path(resolved) - return normalize_windows_real_path(os.path.realpath(path)) +def workspace_identity(path: str) -> str | None: + """Return the lowercase hex SHA-256 of the UTF-8 canonical real path of existing directory ``path``.""" -def workspace_identity(path: str) -> str: - """Return the lowercase hex SHA-256 of the canonical real path of ``path``.""" + canonical = real_workspace_path(path) + if canonical is None: + return None + try: + encoded = canonical.encode("utf-8") + except UnicodeEncodeError: + return None + return hashlib.sha256(encoded).hexdigest() - if os.name == "nt": - return hashlib.sha256(real_workspace_path(path).encode("utf-8", errors="surrogatepass")).hexdigest() - return hashlib.sha256(os.fsencode(real_workspace_path(path))).hexdigest() + +def _guarded_git_top(cwd: str, top: str | None) -> tuple[str | None, str]: + if top is None: + return None, "directory" + top_real = real_workspace_path(top) + if top_real is None: + return None, "directory" + cwd_real = real_workspace_path(cwd) + if cwd_real is not None and cwd_real == top_real: + return top, "git_root" + if os.path.dirname(top_real) == top_real: + return None, "home_guard" + home_real = real_workspace_path("~") + if home_real is not None: + current = home_real + while True: + if current == top_real: + return None, "home_guard" + parent = os.path.dirname(current) + if parent == current: + break + current = parent + return top, "git_root" + + +def describe_workspace_root(cwd: str, *, timeout: float = 2.0) -> tuple[str | None, str]: + """Return ``(canonical_root, root_source)`` for diagnostics and operator CLI output.""" + + raw_top, _git_dir, _common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + effective_top, source = _guarded_git_top(cwd, raw_top) + return real_workspace_path(effective_top or cwd), source def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[tuple[str, str | None]]: """Return ``(shared_root, host_path)`` pairs for ``cwd`` and, in a linked worktree, its main checkout. - ``shared_root`` is always the Git top level when inside a work tree, or ``cwd`` outside Git, so every host derives - the same shared workspace key. ``host_path`` preserves each host's legacy path rule (the Git top level when - ``git_root`` is true, otherwise ``cwd`` and its counterpart subdirectory in the main checkout) from the same Git - invocation, or ``None`` when the main-checkout counterpart is unavailable or links back to ``cwd``. + ``shared_root`` is always the Git top level when inside a work tree (unless guarded by home/filesystem-root rules), + or ``cwd`` outside Git, so every host derives the same shared workspace key. ``host_path`` preserves each host's + legacy path rule from the same Git invocation, or ``None`` when the main-checkout counterpart is unavailable or + links back to ``cwd``. """ deadline = time.monotonic() + timeout - top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + raw_top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + top, _source = _guarded_git_top(cwd, raw_top) shared_own = top or cwd - host_own = shared_own if git_root else cwd + host_own = (raw_top or cwd) if git_root else cwd + if top is None: + return [(shared_own, host_own)] main_root = _main_worktree_root(top, git_dir, common) if main_root is None or common is None: return [(shared_own, host_own)] @@ -124,8 +187,10 @@ def workspace_paths(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[s def _git_output(cwd: str, arguments: tuple[str, ...], timeout: float) -> str: """Return what Git prints for ``arguments`` in ``cwd``, or an empty string when it fails or time is up.""" + if timeout <= 0 or not cwd or not os.path.isdir(cwd): + return "" executable = which("git") - if executable is None or timeout <= 0: + if executable is None: return "" try: completed = subprocess.run( # noqa: S603 - git executable and arguments are integration-owned. @@ -133,7 +198,8 @@ def _git_output(cwd: str, arguments: tuple[str, ...], timeout: float) -> str: cwd=cwd, check=True, capture_output=True, - text=True, + encoding="utf-8", + errors="surrogateescape", timeout=timeout, ) except (OSError, subprocess.SubprocessError): diff --git a/integrations/codex/plugins/powercontext/powercontext_lifecycle/host_profile.py b/integrations/codex/plugins/powercontext/powercontext_lifecycle/host_profile.py index 93749182b0..c4ffae939b 100644 --- a/integrations/codex/plugins/powercontext/powercontext_lifecycle/host_profile.py +++ b/integrations/codex/plugins/powercontext/powercontext_lifecycle/host_profile.py @@ -41,4 +41,4 @@ class HostProfile: prompt_id_field: str diagnostics: DiagnosticThrottle bootstrap_state: BootstrapState - legacy_workspace_binding: bool = True + legacy_workspace_binding: bool = False diff --git a/integrations/codex/plugins/powercontext/powercontext_lifecycle/scope_binding.py b/integrations/codex/plugins/powercontext/powercontext_lifecycle/scope_binding.py index a45a721abd..7342e113b4 100644 --- a/integrations/codex/plugins/powercontext/powercontext_lifecycle/scope_binding.py +++ b/integrations/codex/plugins/powercontext/powercontext_lifecycle/scope_binding.py @@ -20,15 +20,23 @@ from __future__ import annotations import json +import os from collections.abc import Mapping from dataclasses import dataclass, field +from hashlib import sha256 from http.client import HTTPException +from pathlib import Path from time import monotonic from typing import Any, Protocol from urllib.error import HTTPError from urllib.request import Request -from .git_worktree import SHARED_WORKSPACE_INTEGRATION, workspace_identity, workspace_locations +from .git_worktree import ( + SHARED_WORKSPACE_INTEGRATION, + describe_workspace_root, + workspace_identity, + workspace_locations, +) from .host_profile import HostProfile from .scope_binding_errors import ( ScopeBindingError, @@ -133,7 +141,10 @@ def clear_scope_binding( """Remove the shared workspace binding and, when enabled, this host's legacy workspace binding.""" shared_root, host_path = workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline))[0] - keys = [shared_workspace_key(shared_root)] + keys: list[dict[str, str]] = [] + shared_key = shared_workspace_key(shared_root) + if shared_key is not None: + keys.append(shared_key) if host.legacy_workspace_binding and host_path is not None: keys.append(_workspace_key(host, host_path)) cleared_any = False @@ -162,9 +173,16 @@ def diagnose_scope_binding( ) -> dict[str, Any]: """Resolve the active Scope and identify which candidate binding key matched (for diagnostics, never hooks).""" + resolved_root, root_source = describe_workspace_root(cwd, timeout=_git_timeout(deadline)) if settings.scope_id is not None: scope_id = resolve_scope_id(host, cwd, session_id=session_id, settings=settings, deadline=deadline) - return {"scope_id": scope_id, "source": "explicit", "matched_key": None} + return { + "scope_id": scope_id, + "source": "explicit", + "matched_key": None, + "resolved_root": resolved_root, + "root_source": root_source, + } for key in binding_keys(host, cwd, session_id=session_id, deadline=deadline): try: response = _request_json( @@ -181,7 +199,13 @@ def diagnose_scope_binding( scope_id = response.get("scope_id") if not isinstance(scope_id, str) or not scope_id.strip() or scope_id != scope_id.strip(): raise ScopeBindingError - return {"scope_id": scope_id, "source": "binding", "matched_key": key} + return { + "scope_id": scope_id, + "source": "binding", + "matched_key": key, + "resolved_root": resolved_root, + "root_source": root_source, + } response = _request_json( "/v1/scope-bindings/resolve", {"explicit_scope_id": None, "binding_keys": [], "allow_default": True}, @@ -192,7 +216,13 @@ def diagnose_scope_binding( scope_id = response.get("scope_id") if not isinstance(scope_id, str) or not scope_id.strip() or scope_id != scope_id.strip(): raise ScopeBindingError - return {"scope_id": scope_id, "source": "default", "matched_key": None} + return { + "scope_id": scope_id, + "source": "default", + "matched_key": None, + "resolved_root": resolved_root, + "root_source": root_source, + } def binding_keys( @@ -212,7 +242,9 @@ def binding_keys( if session_id is not None: keys.append(session_binding_key(host, session_id)) for shared_root, host_path in workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline)): - keys.append(shared_workspace_key(shared_root)) + shared_key = shared_workspace_key(shared_root) + if shared_key is not None: + keys.append(shared_key) if host.legacy_workspace_binding and host_path is not None: keys.append(_workspace_key(host, host_path)) return keys @@ -230,15 +262,22 @@ def workspace_binding_key(host: HostProfile, cwd: str, *, deadline: float | None del host shared_root, _host_path = workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline))[0] - return shared_workspace_key(shared_root) + key = shared_workspace_key(shared_root) + if key is None: + raise ScopeBindingError + return key -def shared_workspace_key(path: str) -> dict[str, str]: - return {"integration": SHARED_WORKSPACE_INTEGRATION, "kind": "workspace", "external_id": workspace_identity(path)} +def shared_workspace_key(path: str) -> dict[str, str] | None: + identity = workspace_identity(path) + if identity is None: + return None + return {"integration": SHARED_WORKSPACE_INTEGRATION, "kind": "workspace", "external_id": identity} def _workspace_key(host: HostProfile, path: str) -> dict[str, str]: - return {"integration": host.integration, "kind": "workspace", "external_id": workspace_identity(path)} + external_id = sha256(os.fsencode(Path(path).expanduser().resolve())).hexdigest() + return {"integration": host.integration, "kind": "workspace", "external_id": external_id} def _request_json( diff --git a/integrations/dsh/plugins/powercontext/lib/index.js b/integrations/dsh/plugins/powercontext/lib/index.js index 4fd3576705..7f007d0d0e 100644 --- a/integrations/dsh/plugins/powercontext/lib/index.js +++ b/integrations/dsh/plugins/powercontext/lib/index.js @@ -15,12 +15,12 @@ */ import { createRequire } from "node:module"; -import { lstatSync, readFileSync, realpathSync } from "node:fs"; +import { lstatSync, readFileSync, realpathSync, statSync } from "node:fs"; import { fileURLToPath, pathToFileURL } from "node:url"; import { homedir } from "node:os"; import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; -import { createHash, randomUUID } from "node:crypto"; import { execFile, execFileSync } from "node:child_process"; +import { createHash, randomUUID } from "node:crypto"; import { promisify } from "node:util"; import { createServer, request } from "node:http"; import { request as request$1 } from "node:https"; @@ -2654,50 +2654,72 @@ function normalizeWindowsRealPath(value, win32) { if (/^[a-z]:/u.test(resolved)) resolved = resolved.slice(0, 1).toUpperCase() + resolved.slice(1); return resolved; } -/** Return the canonical real path of `directory` with symbolic links resolved on existing ancestors. */ +/** Return the OS-canonical real path of an existing `directory`, or `undefined` when unavailable. */ function realWorkspacePath(directory) { - const input = isAbsolute(directory) ? directory : process.cwd() + sep + directory; + if (!directory) return void 0; + let expanded = directory; + if (expanded === "~" || expanded.startsWith("~/") || expanded.startsWith("~\\")) { + const home = process.env.HOME || process.env.USERPROFILE || homedir(); + expanded = expanded === "~" ? home : join(home, expanded.slice(2)); + } + const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded; try { - return normalizeWindowsRealPath(realpathSync.native(input)); - } catch {} - const target = resolve(directory); - let current = target; - const suffix = []; - while (true) { - const parent = dirname(current); - if (parent === current) return normalizeWindowsRealPath(target); - suffix.unshift(basename(current)); - current = parent; - try { - return normalizeWindowsRealPath(join(realpathSync.native(current), ...suffix)); - } catch {} + const resolved = realpathSync.native(input); + if (!statSync(resolved).isDirectory()) return void 0; + return normalizeWindowsRealPath(resolved); + } catch { + return; } } -/** Return the lowercase hex SHA-256 of the canonical real path of `directory`. */ +/** Return the lowercase hex SHA-256 of the UTF-8 canonical real path of an existing `directory`. */ function workspaceIdentity(directory) { - return createHash("sha256").update(realWorkspacePath(directory), "utf8").digest("hex"); + const canonical = realWorkspacePath(directory); + if (canonical === void 0) return void 0; + if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { diff --git a/integrations/dsh/plugins/powercontext/src/doctor.ts b/integrations/dsh/plugins/powercontext/src/doctor.ts index 31a8000761..4bc9c14adb 100644 --- a/integrations/dsh/plugins/powercontext/src/doctor.ts +++ b/integrations/dsh/plugins/powercontext/src/doctor.ts @@ -23,6 +23,7 @@ import { authenticationRejection, bodyFailureDetails, type BodyFailureDetails, I import type { PluginRuntime } from './invoke.ts' import { OPERATIONS, type OperationId } from './operations.generated.ts' import { PREPARED_CONTEXT_SCHEMA, validatePreparedContext } from './prepared-context.ts' +import { describeWorkspaceRoot } from './git-worktree.ts' import { sessionCwd, workspaceBindingKeys } from './scope.ts' export interface DoctorCheck extends BodyFailureDetails { @@ -368,6 +369,9 @@ export async function diagnoseServer( 'Check the explicit Scope override, workspace binding and Server default Scope. Doctor does not create bindings.') } const workspace = sessionCwd(cwd) + const [resolvedRoot = '', rootSource = 'directory'] = workspace + ? await describeWorkspaceRoot(workspace, 500) + : ['', 'none'] let matchedKey: string | undefined = runtime.config.scopeId ? 'explicit' : 'default' if (!runtime.config.scopeId && workspace) { for (const candidate of await workspaceBindingKeys(workspace)) { @@ -395,6 +399,7 @@ export async function diagnoseServer( return { ...check('resolve_scope_binding', 'scope_resolved', 'The Server resolved the current session Scope.', undefined, 'ok'), ...(matchedKey ? { matched_key: matchedKey } : {}), + ...(workspace ? { resolved_root: resolvedRoot || null, root_source: rootSource } : {}), } }) checks.prepare = scopeId ? await probe('prepare_context', async () => { diff --git a/integrations/dsh/plugins/powercontext/src/git-worktree.ts b/integrations/dsh/plugins/powercontext/src/git-worktree.ts index a39ee55956..fb5d5f12e4 100644 --- a/integrations/dsh/plugins/powercontext/src/git-worktree.ts +++ b/integrations/dsh/plugins/powercontext/src/git-worktree.ts @@ -19,7 +19,8 @@ import { execFile, execFileSync } from 'node:child_process' import { createHash } from 'node:crypto' -import { realpathSync } from 'node:fs' +import { realpathSync, statSync } from 'node:fs' +import { homedir } from 'node:os' import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { promisify } from 'node:util' @@ -69,52 +70,84 @@ export function normalizeWindowsRealPath(value: string, win32?: boolean): string return resolved } -/** Return the canonical real path of `directory` with symbolic links resolved on existing ancestors. */ -export function realWorkspacePath(directory: string): string { - const input = isAbsolute(directory) ? directory : process.cwd() + sep + directory +/** Return the OS-canonical real path of an existing `directory`, or `undefined` when unavailable. */ +export function realWorkspacePath(directory: string): string | undefined { + if (!directory) return undefined + let expanded = directory + if (expanded === '~' || expanded.startsWith('~/') || expanded.startsWith('~\\')) { + const home = process.env.HOME || process.env.USERPROFILE || homedir() + expanded = expanded === '~' ? home : join(home, expanded.slice(2)) + } + const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded try { - return normalizeWindowsRealPath(realpathSync.native(input)) + const resolved = realpathSync.native(input) + if (!statSync(resolved).isDirectory()) return undefined + return normalizeWindowsRealPath(resolved) } catch { - // Resolve symbolic links on the deepest existing ancestor, matching Python's os.path.realpath. + return undefined } - const target = resolve(directory) - let current = target - const suffix = [] - while (true) { - const parent = dirname(current) - if (parent === current) return normalizeWindowsRealPath(target) - suffix.unshift(basename(current)) - current = parent - try { - const resolvedAncestor = realpathSync.native(current) - return normalizeWindowsRealPath(join(resolvedAncestor, ...suffix)) - } catch { - // Keep walking up until an existing directory is found. +} + +/** Return the lowercase hex SHA-256 of the UTF-8 canonical real path of an existing `directory`. */ +export function workspaceIdentity(directory: string): string | undefined { + const canonical = realWorkspacePath(directory) + if (canonical === undefined) return undefined + if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { + const [rawTop = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) + const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) + return [realWorkspacePath(top || directory) ?? '', source] } -/** Return the lowercase hex SHA-256 of the canonical real path of `directory`. */ -export function workspaceIdentity(directory: string): string { - return createHash('sha256').update(realWorkspacePath(directory), 'utf8').digest('hex') +/** Synchronous counterpart of `describeWorkspaceRoot`. */ +export function describeWorkspaceRootSync(directory: string, timeout: number): string[] { + const [rawTop = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) + const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) + return [realWorkspacePath(top || directory) ?? '', source] } /** * Return `[sharedRoot, hostPath]` pairs for `directory` and, in a linked worktree, its main checkout. * - * `sharedRoot` is always the Git top level inside a work tree, or `directory` outside Git. `hostPath` preserves the - * host's legacy rule from the same Git invocation, and is omitted when the main-checkout counterpart is unavailable or - * links back to `directory`. + * `sharedRoot` is always the Git top level inside a work tree (unless guarded by home/filesystem-root rules), or + * `directory` outside Git. `hostPath` preserves the host's legacy rule from the same Git invocation, and is omitted + * when the main-checkout counterpart is unavailable or links back to `directory`. */ export async function workspaceLocations(directory: string, gitRoot: boolean, timeout: number): Promise { const deadline = Date.now() + timeout - const [top = '', gitDir = '', common = ''] = gitPaths(await gitOutput(['-C', directory, ...GIT_ARGUMENTS], timeout)) + const [rawTop = '', gitDir = '', common = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) + const [top = ''] = guardedGitTop(directory, rawTop) const sharedOwn = top || directory - const hostOwn = gitRoot ? sharedOwn : directory + const hostOwn = gitRoot ? (rawTop || directory) : directory + if (!top) return [[sharedOwn, hostOwn]] const mainRoot = mainWorktreeRoot(top, gitDir, common) if (mainRoot === undefined) return [[sharedOwn, hostOwn]] // An unknown answer leaves the second path out, as for a bare repository. - const bare = await gitOutput(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) + const bare = await gitOutput(directory, ['--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] @@ -123,12 +156,14 @@ export async function workspaceLocations(directory: string, gitRoot: boolean, ti /** Return what `workspaceLocations` returns, for hosts whose hooks compute their keys synchronously. */ export function workspaceLocationsSync(directory: string, gitRoot: boolean, timeout: number): string[][] { const deadline = Date.now() + timeout - const [top = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(['-C', directory, ...GIT_ARGUMENTS], timeout)) + const [rawTop = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) + const [top = ''] = guardedGitTop(directory, rawTop) const sharedOwn = top || directory - const hostOwn = gitRoot ? sharedOwn : directory + const hostOwn = gitRoot ? (rawTop || directory) : directory + if (!top) return [[sharedOwn, hostOwn]] const mainRoot = mainWorktreeRoot(top, gitDir, common) if (mainRoot === undefined) return [[sharedOwn, hostOwn]] - const bare = gitOutputSync(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) + const bare = gitOutputSync(directory, ['--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] @@ -151,20 +186,29 @@ export function workspacePathsSync(directory: string, gitRoot: boolean, timeout: return result } +function existingDirectory(directory: string): boolean { + if (!directory) return false + try { + return statSync(directory, { throwIfNoEntry: false })?.isDirectory() === true + } catch { + return false + } +} + // Return what Git prints, or an empty string when it fails or time is up. -async function gitOutput(args: string[], timeout: number): Promise { - if (timeout <= 0) return '' +async function gitOutput(directory: string, args: string[], timeout: number): Promise { + if (timeout <= 0 || !existingDirectory(directory)) return '' try { - return (await runGit('git', args, { encoding: 'utf8', timeout, windowsHide: true })).stdout + return (await runGit('git', ['-C', directory, ...args], { encoding: 'utf8', timeout, windowsHide: true })).stdout } catch { return '' } } -function gitOutputSync(args: string[], timeout: number): string { - if (timeout <= 0) return '' +function gitOutputSync(directory: string, args: string[], timeout: number): string { + if (timeout <= 0 || !existingDirectory(directory)) return '' try { - return execFileSync('git', args, { + return execFileSync('git', ['-C', directory, ...args], { encoding: 'utf8', timeout, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'], }) } catch { diff --git a/integrations/dsh/plugins/powercontext/src/scope.ts b/integrations/dsh/plugins/powercontext/src/scope.ts index 8e82f4e233..ca85ca3697 100644 --- a/integrations/dsh/plugins/powercontext/src/scope.ts +++ b/integrations/dsh/plugins/powercontext/src/scope.ts @@ -34,12 +34,14 @@ export function sessionCwd(cwd: string | undefined): string | undefined { return value ? value : undefined } -export function sharedWorkspaceBindingKey(cwd: string): ScopeBindingKey { +export function sharedWorkspaceBindingKey(cwd: string): ScopeBindingKey | undefined { const [sharedRoot = cwd] = workspaceLocationsSync(cwd, false, GIT_TIMEOUT_MS)[0] ?? [cwd] + const externalId = workspaceIdentity(sharedRoot) + if (externalId === undefined) return undefined return { integration: SHARED_WORKSPACE_INTEGRATION, kind: 'workspace', - external_id: workspaceIdentity(sharedRoot), + external_id: externalId, } } @@ -51,7 +53,7 @@ export function legacyWorkspaceBindingKey(cwd: string): ScopeBindingKey { } } -export function workspaceBindingKey(cwd: string): ScopeBindingKey { +export function workspaceBindingKey(cwd: string): ScopeBindingKey | undefined { return sharedWorkspaceBindingKey(cwd) } @@ -59,11 +61,14 @@ export function workspaceBindingKey(cwd: string): ScopeBindingKey { export async function workspaceBindingKeys(cwd: string): Promise { const keys: ScopeBindingKey[] = [] for (const [sharedRoot = cwd, hostPath] of await workspaceLocations(cwd, false, GIT_TIMEOUT_MS)) { - keys.push({ - integration: SHARED_WORKSPACE_INTEGRATION, - kind: 'workspace', - external_id: workspaceIdentity(sharedRoot), - }) + const externalId = workspaceIdentity(sharedRoot) + if (externalId !== undefined) { + keys.push({ + integration: SHARED_WORKSPACE_INTEGRATION, + kind: 'workspace', + external_id: externalId, + }) + } if (hostPath !== undefined) keys.push(legacyWorkspaceBindingKey(hostPath)) } return keys diff --git a/integrations/dsh/plugins/powercontext/tests/scope.spec.ts b/integrations/dsh/plugins/powercontext/tests/scope.spec.ts index a95be0e677..58f5c5c925 100644 --- a/integrations/dsh/plugins/powercontext/tests/scope.spec.ts +++ b/integrations/dsh/plugins/powercontext/tests/scope.spec.ts @@ -51,19 +51,24 @@ describe('Scope binding', () => { }) it('delegates explicit, durable, and default precedence to the Server', async () => { - const request = vi.fn().mockResolvedValue({ value: { scope_id: 'scp_00000000000000000000000000' } }) - const client = { request } as never + const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pc-dsh-scope-'))) + try { + const request = vi.fn().mockResolvedValue({ value: { scope_id: 'scp_00000000000000000000000000' } }) + const client = { request } as never - await expect(resolveScopeId(client, '/workspace', 'explicit-scope')).resolves.toBe( - 'scp_00000000000000000000000000', - ) - const [operation, input] = request.mock.calls[0] - expect(operation).toBe('resolve_scope_binding') - expect(input.explicit_scope_id).toBe('explicit-scope') - expect(input.binding_keys).toHaveLength(2) - expect(input.binding_keys[0]).toMatchObject({ integration: 'shared', kind: 'workspace' }) - expect(input.binding_keys[1]).toMatchObject({ integration: 'dsh', kind: 'workspace' }) - expect(input.binding_keys[0].external_id).not.toContain('/workspace') + await expect(resolveScopeId(client, dir, 'explicit-scope')).resolves.toBe( + 'scp_00000000000000000000000000', + ) + const [operation, input] = request.mock.calls[0] + expect(operation).toBe('resolve_scope_binding') + expect(input.explicit_scope_id).toBe('explicit-scope') + expect(input.binding_keys).toHaveLength(2) + expect(input.binding_keys[0]).toMatchObject({ integration: 'shared', kind: 'workspace' }) + expect(input.binding_keys[1]).toMatchObject({ integration: 'dsh', kind: 'workspace' }) + expect(input.binding_keys[0].external_id).not.toContain(dir) + } finally { + rmSync(dir, { recursive: true, force: true }) + } }) it('allows companion callers to refuse an implicit default Scope', async () => { diff --git a/integrations/hermes/plugins/powercontext/git_worktree.py b/integrations/hermes/plugins/powercontext/git_worktree.py index 721e66c091..65f6747778 100644 --- a/integrations/hermes/plugins/powercontext/git_worktree.py +++ b/integrations/hermes/plugins/powercontext/git_worktree.py @@ -25,6 +25,7 @@ import hashlib import os import subprocess +import sys import time from shutil import which @@ -59,33 +60,95 @@ def normalize_windows_real_path(path: str, *, windows: bool = os.name == "nt") - return resolved -def real_workspace_path(path: str) -> str: - """Return the canonical real path of ``path`` with symbolic links resolved and Windows drive prefixes normalized.""" +def _darwin_canonical_path(path: str) -> str: + if sys.platform != "darwin": + return path + import fcntl + + fd = os.open(path, os.O_RDONLY) + try: + raw = fcntl.fcntl(fd, fcntl.F_GETPATH, b"\x00" * 1024) + finally: + os.close(fd) + return os.fsdecode(raw.split(b"\x00", 1)[0]) + + +def real_workspace_path(path: str) -> str | None: + """Return the OS-canonical real path of an existing directory ``path``, or ``None`` when unavailable.""" + + expanded = os.path.expanduser(path) + if not expanded or not os.path.isdir(expanded): + return None + try: + resolved = _darwin_canonical_path(os.path.realpath(expanded)) + except OSError: + return None + if not os.path.isdir(resolved): + return None + return normalize_windows_real_path(resolved) - return normalize_windows_real_path(os.path.realpath(path)) +def workspace_identity(path: str) -> str | None: + """Return the lowercase hex SHA-256 of the UTF-8 canonical real path of existing directory ``path``.""" -def workspace_identity(path: str) -> str: - """Return the lowercase hex SHA-256 of the canonical real path of ``path``.""" + canonical = real_workspace_path(path) + if canonical is None: + return None + try: + encoded = canonical.encode("utf-8") + except UnicodeEncodeError: + return None + return hashlib.sha256(encoded).hexdigest() - if os.name == "nt": - return hashlib.sha256(real_workspace_path(path).encode("utf-8", errors="surrogatepass")).hexdigest() - return hashlib.sha256(os.fsencode(real_workspace_path(path))).hexdigest() + +def _guarded_git_top(cwd: str, top: str | None) -> tuple[str | None, str]: + if top is None: + return None, "directory" + top_real = real_workspace_path(top) + if top_real is None: + return None, "directory" + cwd_real = real_workspace_path(cwd) + if cwd_real is not None and cwd_real == top_real: + return top, "git_root" + if os.path.dirname(top_real) == top_real: + return None, "home_guard" + home_real = real_workspace_path("~") + if home_real is not None: + current = home_real + while True: + if current == top_real: + return None, "home_guard" + parent = os.path.dirname(current) + if parent == current: + break + current = parent + return top, "git_root" + + +def describe_workspace_root(cwd: str, *, timeout: float = 2.0) -> tuple[str | None, str]: + """Return ``(canonical_root, root_source)`` for diagnostics and operator CLI output.""" + + raw_top, _git_dir, _common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + effective_top, source = _guarded_git_top(cwd, raw_top) + return real_workspace_path(effective_top or cwd), source def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[tuple[str, str | None]]: """Return ``(shared_root, host_path)`` pairs for ``cwd`` and, in a linked worktree, its main checkout. - ``shared_root`` is always the Git top level when inside a work tree, or ``cwd`` outside Git, so every host derives - the same shared workspace key. ``host_path`` preserves each host's legacy path rule (the Git top level when - ``git_root`` is true, otherwise ``cwd`` and its counterpart subdirectory in the main checkout) from the same Git - invocation, or ``None`` when the main-checkout counterpart is unavailable or links back to ``cwd``. + ``shared_root`` is always the Git top level when inside a work tree (unless guarded by home/filesystem-root rules), + or ``cwd`` outside Git, so every host derives the same shared workspace key. ``host_path`` preserves each host's + legacy path rule from the same Git invocation, or ``None`` when the main-checkout counterpart is unavailable or + links back to ``cwd``. """ deadline = time.monotonic() + timeout - top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + raw_top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + top, _source = _guarded_git_top(cwd, raw_top) shared_own = top or cwd - host_own = shared_own if git_root else cwd + host_own = (raw_top or cwd) if git_root else cwd + if top is None: + return [(shared_own, host_own)] main_root = _main_worktree_root(top, git_dir, common) if main_root is None or common is None: return [(shared_own, host_own)] @@ -124,8 +187,10 @@ def workspace_paths(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[s def _git_output(cwd: str, arguments: tuple[str, ...], timeout: float) -> str: """Return what Git prints for ``arguments`` in ``cwd``, or an empty string when it fails or time is up.""" + if timeout <= 0 or not cwd or not os.path.isdir(cwd): + return "" executable = which("git") - if executable is None or timeout <= 0: + if executable is None: return "" try: completed = subprocess.run( # noqa: S603 - git executable and arguments are integration-owned. @@ -133,7 +198,8 @@ def _git_output(cwd: str, arguments: tuple[str, ...], timeout: float) -> str: cwd=cwd, check=True, capture_output=True, - text=True, + encoding="utf-8", + errors="surrogateescape", timeout=timeout, ) except (OSError, subprocess.SubprocessError): diff --git a/integrations/hermes/plugins/powercontext/provider.py b/integrations/hermes/plugins/powercontext/provider.py index 6f7879b3a1..18b82ef37c 100644 --- a/integrations/hermes/plugins/powercontext/provider.py +++ b/integrations/hermes/plugins/powercontext/provider.py @@ -208,11 +208,14 @@ def _precompress_snapshot_after_capture( return captured_fingerprints -def _shared_workspace_binding_key(path: str) -> dict[str, str]: +def _shared_workspace_binding_key(path: str) -> dict[str, str] | None: + identity = workspace_identity(path) + if identity is None: + return None return { "integration": SHARED_WORKSPACE_INTEGRATION, "kind": "workspace", - "external_id": workspace_identity(path), + "external_id": identity, } @@ -694,14 +697,19 @@ def _scope_binding_keys(self) -> list[dict[str, str]]: if self._session_id: keys.append({"integration": "hermes", "kind": "session", "external_id": self._session_id}) for shared_root, host_path in workspace_locations(self._scope_binding_cwd, git_root=False): - keys.append(_shared_workspace_binding_key(shared_root)) + shared_key = _shared_workspace_binding_key(shared_root) + if shared_key is not None: + keys.append(shared_key) if host_path is not None: keys.append(_workspace_binding_key(host_path)) return keys def _bind_workspace_scope(self, scope_id: str) -> None: shared_root, _host_path = workspace_locations(self._scope_binding_cwd, git_root=False)[0] - response = self._client.set_scope_binding(_shared_workspace_binding_key(shared_root), scope_id) + shared_key = _shared_workspace_binding_key(shared_root) + if shared_key is None: + raise InvalidScopeBindingError + response = self._client.set_scope_binding(shared_key, scope_id) if response.get("scope_id") != scope_id: raise InvalidScopeBindingError self._bound_scope_id = scope_id @@ -710,7 +718,11 @@ def _bind_workspace_scope(self, scope_id: str) -> None: def _clear_workspace_scope(self) -> bool: shared_root, _host_path = workspace_locations(self._scope_binding_cwd, git_root=False)[0] cleared_any = False - for key in (_shared_workspace_binding_key(shared_root), _workspace_binding_key(self._scope_binding_cwd)): + shared_key = _shared_workspace_binding_key(shared_root) + keys_to_clear = [ + key for key in (shared_key, _workspace_binding_key(self._scope_binding_cwd)) if key is not None + ] + for key in keys_to_clear: response = self._client.clear_scope_binding(key) cleared = response.get("cleared") if not isinstance(cleared, bool): diff --git a/integrations/kimi-code/plugins/powercontext/scripts/doctor.mjs b/integrations/kimi-code/plugins/powercontext/scripts/doctor.mjs index 03eaa0823b..a0257f9d40 100644 --- a/integrations/kimi-code/plugins/powercontext/scripts/doctor.mjs +++ b/integrations/kimi-code/plugins/powercontext/scripts/doctor.mjs @@ -14,7 +14,7 @@ * limitations under the License. */ -import { Failure, isScopeId, loadSettings, profileTools, request, resolveScope, workspaceKeys } from '../shared/runtime.mjs' +import { describeWorkspace, Failure, isScopeId, loadSettings, profileTools, request, resolveScope, workspaceKeys } from '../shared/runtime.mjs' import { discoverTools } from '../shared/mcp.mjs' import { parseArgs } from 'node:util' import { queryObservations } from '../shared/observations.mjs' @@ -59,9 +59,12 @@ if (settings) { } } } + const [resolvedRoot = '', rootSource = 'directory'] = describeWorkspace(input.cwd) checks.scope = { status: 'ok', detail: 'Current Scope is accessible.', checks: { scope_id: scopeId, selection: settings.scopeId ? 'explicit' : 'workspace_or_default', - ...(matchedKey ? { matched_key: matchedKey } : {}) } } + ...(matchedKey ? { matched_key: matchedKey } : {}), + ...(resolvedRoot ? { resolved_root: resolvedRoot } : {}), + root_source: rootSource } } } catch (error) { checks.scope = result(error) } if (values.mcp) { try { checks.mcp_discovery = await discoverTools(settings, profileTools(settings.profile)) } diff --git a/integrations/kimi-code/plugins/powercontext/scripts/scope.mjs b/integrations/kimi-code/plugins/powercontext/scripts/scope.mjs index e9305f409d..208cec48c6 100644 --- a/integrations/kimi-code/plugins/powercontext/scripts/scope.mjs +++ b/integrations/kimi-code/plugins/powercontext/scripts/scope.mjs @@ -32,8 +32,13 @@ try { const settings = loadSettings() const signal = AbortSignal.timeout(4000) if (action !== 'resolve') { - const key = workspaceKey(input.cwd) - const keys = action === 'bind' ? [key] : [key, legacyWorkspaceKey(input.cwd)] + const key = action === 'bind' ? workspaceKey(input.cwd) : (() => { + try { return workspaceKey(input.cwd) } catch { return undefined } + })() + const keys = action === 'bind' ? [key] : [ + ...(key ? [key] : []), + legacyWorkspaceKey(input.cwd), + ] binding = { action, status: 'unknown' } let clearedAny = false for (const currentKey of keys) { diff --git a/integrations/kimi-code/plugins/powercontext/shared/git-worktree.mjs b/integrations/kimi-code/plugins/powercontext/shared/git-worktree.mjs index 6b5e9d5259..0a029f5261 100644 --- a/integrations/kimi-code/plugins/powercontext/shared/git-worktree.mjs +++ b/integrations/kimi-code/plugins/powercontext/shared/git-worktree.mjs @@ -19,7 +19,8 @@ import { execFile, execFileSync } from 'node:child_process' import { createHash } from 'node:crypto' -import { realpathSync } from 'node:fs' +import { realpathSync, statSync } from 'node:fs' +import { homedir } from 'node:os' import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { promisify } from 'node:util' @@ -69,52 +70,84 @@ export function normalizeWindowsRealPath(value, win32) { return resolved } -/** Return the canonical real path of `directory` with symbolic links resolved on existing ancestors. */ +/** Return the OS-canonical real path of an existing `directory`, or `undefined` when unavailable. */ export function realWorkspacePath(directory) { - const input = isAbsolute(directory) ? directory : process.cwd() + sep + directory + if (!directory) return undefined + let expanded = directory + if (expanded === '~' || expanded.startsWith('~/') || expanded.startsWith('~\\')) { + const home = process.env.HOME || process.env.USERPROFILE || homedir() + expanded = expanded === '~' ? home : join(home, expanded.slice(2)) + } + const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded try { - return normalizeWindowsRealPath(realpathSync.native(input)) + const resolved = realpathSync.native(input) + if (!statSync(resolved).isDirectory()) return undefined + return normalizeWindowsRealPath(resolved) } catch { - // Resolve symbolic links on the deepest existing ancestor, matching Python's os.path.realpath. + return undefined } - const target = resolve(directory) - let current = target - const suffix = [] - while (true) { - const parent = dirname(current) - if (parent === current) return normalizeWindowsRealPath(target) - suffix.unshift(basename(current)) - current = parent - try { - const resolvedAncestor = realpathSync.native(current) - return normalizeWindowsRealPath(join(resolvedAncestor, ...suffix)) - } catch { - // Keep walking up until an existing directory is found. +} + +/** Return the lowercase hex SHA-256 of the UTF-8 canonical real path of an existing `directory`. */ +export function workspaceIdentity(directory) { + const canonical = realWorkspacePath(directory) + if (canonical === undefined) return undefined + if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? !path.includes('tests') }) const captures = [] const requests = [] diff --git a/integrations/lifecycle/git-worktree.ts b/integrations/lifecycle/git-worktree.ts index 8dadd64803..bddfac1f5c 100644 --- a/integrations/lifecycle/git-worktree.ts +++ b/integrations/lifecycle/git-worktree.ts @@ -16,7 +16,8 @@ import { execFile, execFileSync } from 'node:child_process' import { createHash } from 'node:crypto' -import { realpathSync } from 'node:fs' +import { realpathSync, statSync } from 'node:fs' +import { homedir } from 'node:os' import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { promisify } from 'node:util' @@ -66,52 +67,84 @@ export function normalizeWindowsRealPath(value: string, win32?: boolean): string return resolved } -/** Return the canonical real path of `directory` with symbolic links resolved on existing ancestors. */ -export function realWorkspacePath(directory: string): string { - const input = isAbsolute(directory) ? directory : process.cwd() + sep + directory +/** Return the OS-canonical real path of an existing `directory`, or `undefined` when unavailable. */ +export function realWorkspacePath(directory: string): string | undefined { + if (!directory) return undefined + let expanded = directory + if (expanded === '~' || expanded.startsWith('~/') || expanded.startsWith('~\\')) { + const home = process.env.HOME || process.env.USERPROFILE || homedir() + expanded = expanded === '~' ? home : join(home, expanded.slice(2)) + } + const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded try { - return normalizeWindowsRealPath(realpathSync.native(input)) + const resolved = realpathSync.native(input) + if (!statSync(resolved).isDirectory()) return undefined + return normalizeWindowsRealPath(resolved) } catch { - // Resolve symbolic links on the deepest existing ancestor, matching Python's os.path.realpath. + return undefined } - const target = resolve(directory) - let current = target - const suffix = [] - while (true) { - const parent = dirname(current) - if (parent === current) return normalizeWindowsRealPath(target) - suffix.unshift(basename(current)) - current = parent - try { - const resolvedAncestor = realpathSync.native(current) - return normalizeWindowsRealPath(join(resolvedAncestor, ...suffix)) - } catch { - // Keep walking up until an existing directory is found. +} + +/** Return the lowercase hex SHA-256 of the UTF-8 canonical real path of an existing `directory`. */ +export function workspaceIdentity(directory: string): string | undefined { + const canonical = realWorkspacePath(directory) + if (canonical === undefined) return undefined + if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { + const [rawTop = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) + const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) + return [realWorkspacePath(top || directory) ?? '', source] } -/** Return the lowercase hex SHA-256 of the canonical real path of `directory`. */ -export function workspaceIdentity(directory: string): string { - return createHash('sha256').update(realWorkspacePath(directory), 'utf8').digest('hex') +/** Synchronous counterpart of `describeWorkspaceRoot`. */ +export function describeWorkspaceRootSync(directory: string, timeout: number): string[] { + const [rawTop = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) + const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) + return [realWorkspacePath(top || directory) ?? '', source] } /** * Return `[sharedRoot, hostPath]` pairs for `directory` and, in a linked worktree, its main checkout. * - * `sharedRoot` is always the Git top level inside a work tree, or `directory` outside Git. `hostPath` preserves the - * host's legacy rule from the same Git invocation, and is omitted when the main-checkout counterpart is unavailable or - * links back to `directory`. + * `sharedRoot` is always the Git top level inside a work tree (unless guarded by home/filesystem-root rules), or + * `directory` outside Git. `hostPath` preserves the host's legacy rule from the same Git invocation, and is omitted + * when the main-checkout counterpart is unavailable or links back to `directory`. */ export async function workspaceLocations(directory: string, gitRoot: boolean, timeout: number): Promise { const deadline = Date.now() + timeout - const [top = '', gitDir = '', common = ''] = gitPaths(await gitOutput(['-C', directory, ...GIT_ARGUMENTS], timeout)) + const [rawTop = '', gitDir = '', common = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) + const [top = ''] = guardedGitTop(directory, rawTop) const sharedOwn = top || directory - const hostOwn = gitRoot ? sharedOwn : directory + const hostOwn = gitRoot ? (rawTop || directory) : directory + if (!top) return [[sharedOwn, hostOwn]] const mainRoot = mainWorktreeRoot(top, gitDir, common) if (mainRoot === undefined) return [[sharedOwn, hostOwn]] // An unknown answer leaves the second path out, as for a bare repository. - const bare = await gitOutput(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) + const bare = await gitOutput(directory, ['--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] @@ -120,12 +153,14 @@ export async function workspaceLocations(directory: string, gitRoot: boolean, ti /** Return what `workspaceLocations` returns, for hosts whose hooks compute their keys synchronously. */ export function workspaceLocationsSync(directory: string, gitRoot: boolean, timeout: number): string[][] { const deadline = Date.now() + timeout - const [top = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(['-C', directory, ...GIT_ARGUMENTS], timeout)) + const [rawTop = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) + const [top = ''] = guardedGitTop(directory, rawTop) const sharedOwn = top || directory - const hostOwn = gitRoot ? sharedOwn : directory + const hostOwn = gitRoot ? (rawTop || directory) : directory + if (!top) return [[sharedOwn, hostOwn]] const mainRoot = mainWorktreeRoot(top, gitDir, common) if (mainRoot === undefined) return [[sharedOwn, hostOwn]] - const bare = gitOutputSync(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) + const bare = gitOutputSync(directory, ['--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] @@ -148,20 +183,29 @@ export function workspacePathsSync(directory: string, gitRoot: boolean, timeout: return result } +function existingDirectory(directory: string): boolean { + if (!directory) return false + try { + return statSync(directory, { throwIfNoEntry: false })?.isDirectory() === true + } catch { + return false + } +} + // Return what Git prints, or an empty string when it fails or time is up. -async function gitOutput(args: string[], timeout: number): Promise { - if (timeout <= 0) return '' +async function gitOutput(directory: string, args: string[], timeout: number): Promise { + if (timeout <= 0 || !existingDirectory(directory)) return '' try { - return (await runGit('git', args, { encoding: 'utf8', timeout, windowsHide: true })).stdout + return (await runGit('git', ['-C', directory, ...args], { encoding: 'utf8', timeout, windowsHide: true })).stdout } catch { return '' } } -function gitOutputSync(args: string[], timeout: number): string { - if (timeout <= 0) return '' +function gitOutputSync(directory: string, args: string[], timeout: number): string { + if (timeout <= 0 || !existingDirectory(directory)) return '' try { - return execFileSync('git', args, { + return execFileSync('git', ['-C', directory, ...args], { encoding: 'utf8', timeout, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'], }) } catch { diff --git a/integrations/opencode/plugins/powercontext/lib/index.js b/integrations/opencode/plugins/powercontext/lib/index.js index 2a62d5fcf8..132c3fb2ca 100644 --- a/integrations/opencode/plugins/powercontext/lib/index.js +++ b/integrations/opencode/plugins/powercontext/lib/index.js @@ -16,7 +16,7 @@ import { createHash } from "node:crypto"; import { writeFile } from "node:fs/promises"; import { tool } from "@opencode-ai/plugin"; -import { lstatSync, readFileSync, realpathSync } from "node:fs"; +import { lstatSync, readFileSync, realpathSync, statSync } from "node:fs"; import { homedir } from "node:os"; import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { execFile } from "node:child_process"; @@ -2528,50 +2528,66 @@ function normalizeWindowsRealPath(value, win32) { if (/^[a-z]:/u.test(resolved)) resolved = resolved.slice(0, 1).toUpperCase() + resolved.slice(1); return resolved; } -/** Return the canonical real path of `directory` with symbolic links resolved on existing ancestors. */ +/** Return the OS-canonical real path of an existing `directory`, or `undefined` when unavailable. */ function realWorkspacePath(directory) { - const input = isAbsolute(directory) ? directory : process.cwd() + sep + directory; + if (!directory) return void 0; + let expanded = directory; + if (expanded === "~" || expanded.startsWith("~/") || expanded.startsWith("~\\")) { + const home = process.env.HOME || process.env.USERPROFILE || homedir(); + expanded = expanded === "~" ? home : join(home, expanded.slice(2)); + } + const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded; try { - return normalizeWindowsRealPath(realpathSync.native(input)); - } catch {} - const target = resolve(directory); - let current = target; - const suffix = []; - while (true) { - const parent = dirname(current); - if (parent === current) return normalizeWindowsRealPath(target); - suffix.unshift(basename(current)); - current = parent; - try { - return normalizeWindowsRealPath(join(realpathSync.native(current), ...suffix)); - } catch {} + const resolved = realpathSync.native(input); + if (!statSync(resolved).isDirectory()) return void 0; + return normalizeWindowsRealPath(resolved); + } catch { + return; } } -/** Return the lowercase hex SHA-256 of the canonical real path of `directory`. */ +/** Return the lowercase hex SHA-256 of the UTF-8 canonical real path of an existing `directory`. */ function workspaceIdentity(directory) { - return createHash("sha256").update(realWorkspacePath(directory), "utf8").digest("hex"); + const canonical = realWorkspacePath(directory); + if (canonical === void 0) return void 0; + if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { + const [rawTop = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) + const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) + return [realWorkspacePath(top || directory) ?? '', source] } -/** Return the lowercase hex SHA-256 of the canonical real path of `directory`. */ -export function workspaceIdentity(directory: string): string { - return createHash('sha256').update(realWorkspacePath(directory), 'utf8').digest('hex') +/** Synchronous counterpart of `describeWorkspaceRoot`. */ +export function describeWorkspaceRootSync(directory: string, timeout: number): string[] { + const [rawTop = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) + const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) + return [realWorkspacePath(top || directory) ?? '', source] } /** * Return `[sharedRoot, hostPath]` pairs for `directory` and, in a linked worktree, its main checkout. * - * `sharedRoot` is always the Git top level inside a work tree, or `directory` outside Git. `hostPath` preserves the - * host's legacy rule from the same Git invocation, and is omitted when the main-checkout counterpart is unavailable or - * links back to `directory`. + * `sharedRoot` is always the Git top level inside a work tree (unless guarded by home/filesystem-root rules), or + * `directory` outside Git. `hostPath` preserves the host's legacy rule from the same Git invocation, and is omitted + * when the main-checkout counterpart is unavailable or links back to `directory`. */ export async function workspaceLocations(directory: string, gitRoot: boolean, timeout: number): Promise { const deadline = Date.now() + timeout - const [top = '', gitDir = '', common = ''] = gitPaths(await gitOutput(['-C', directory, ...GIT_ARGUMENTS], timeout)) + const [rawTop = '', gitDir = '', common = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) + const [top = ''] = guardedGitTop(directory, rawTop) const sharedOwn = top || directory - const hostOwn = gitRoot ? sharedOwn : directory + const hostOwn = gitRoot ? (rawTop || directory) : directory + if (!top) return [[sharedOwn, hostOwn]] const mainRoot = mainWorktreeRoot(top, gitDir, common) if (mainRoot === undefined) return [[sharedOwn, hostOwn]] // An unknown answer leaves the second path out, as for a bare repository. - const bare = await gitOutput(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) + const bare = await gitOutput(directory, ['--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] @@ -123,12 +156,14 @@ export async function workspaceLocations(directory: string, gitRoot: boolean, ti /** Return what `workspaceLocations` returns, for hosts whose hooks compute their keys synchronously. */ export function workspaceLocationsSync(directory: string, gitRoot: boolean, timeout: number): string[][] { const deadline = Date.now() + timeout - const [top = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(['-C', directory, ...GIT_ARGUMENTS], timeout)) + const [rawTop = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) + const [top = ''] = guardedGitTop(directory, rawTop) const sharedOwn = top || directory - const hostOwn = gitRoot ? sharedOwn : directory + const hostOwn = gitRoot ? (rawTop || directory) : directory + if (!top) return [[sharedOwn, hostOwn]] const mainRoot = mainWorktreeRoot(top, gitDir, common) if (mainRoot === undefined) return [[sharedOwn, hostOwn]] - const bare = gitOutputSync(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) + const bare = gitOutputSync(directory, ['--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] @@ -151,20 +186,29 @@ export function workspacePathsSync(directory: string, gitRoot: boolean, timeout: return result } +function existingDirectory(directory: string): boolean { + if (!directory) return false + try { + return statSync(directory, { throwIfNoEntry: false })?.isDirectory() === true + } catch { + return false + } +} + // Return what Git prints, or an empty string when it fails or time is up. -async function gitOutput(args: string[], timeout: number): Promise { - if (timeout <= 0) return '' +async function gitOutput(directory: string, args: string[], timeout: number): Promise { + if (timeout <= 0 || !existingDirectory(directory)) return '' try { - return (await runGit('git', args, { encoding: 'utf8', timeout, windowsHide: true })).stdout + return (await runGit('git', ['-C', directory, ...args], { encoding: 'utf8', timeout, windowsHide: true })).stdout } catch { return '' } } -function gitOutputSync(args: string[], timeout: number): string { - if (timeout <= 0) return '' +function gitOutputSync(directory: string, args: string[], timeout: number): string { + if (timeout <= 0 || !existingDirectory(directory)) return '' try { - return execFileSync('git', args, { + return execFileSync('git', ['-C', directory, ...args], { encoding: 'utf8', timeout, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'], }) } catch { diff --git a/integrations/opencode/plugins/powercontext/src/scope.ts b/integrations/opencode/plugins/powercontext/src/scope.ts index aa6af0cf75..ec4824bc8f 100644 --- a/integrations/opencode/plugins/powercontext/src/scope.ts +++ b/integrations/opencode/plugins/powercontext/src/scope.ts @@ -32,12 +32,14 @@ export function sessionBindingKey(sessionID: string): ScopeBindingKey { return { integration: 'opencode', kind: 'session', external_id: sessionID } } -export function sharedWorkspaceBindingKey(cwd: string): ScopeBindingKey { +export function sharedWorkspaceBindingKey(cwd: string): ScopeBindingKey | undefined { const [sharedRoot = cwd] = workspaceLocationsSync(cwd, false, GIT_TIMEOUT_MS)[0] ?? [cwd] + const externalId = workspaceIdentity(sharedRoot) + if (externalId === undefined) return undefined return { integration: SHARED_WORKSPACE_INTEGRATION, kind: 'workspace', - external_id: workspaceIdentity(sharedRoot), + external_id: externalId, } } @@ -49,7 +51,7 @@ export function legacyWorkspaceBindingKey(cwd: string): ScopeBindingKey { } } -export function workspaceBindingKey(cwd: string): ScopeBindingKey { +export function workspaceBindingKey(cwd: string): ScopeBindingKey | undefined { return sharedWorkspaceBindingKey(cwd) } @@ -57,11 +59,14 @@ export function workspaceBindingKey(cwd: string): ScopeBindingKey { export async function workspaceBindingKeys(cwd: string): Promise { const keys: ScopeBindingKey[] = [] for (const [sharedRoot = cwd, hostPath] of await workspaceLocations(cwd, false, GIT_TIMEOUT_MS)) { - keys.push({ - integration: SHARED_WORKSPACE_INTEGRATION, - kind: 'workspace', - external_id: workspaceIdentity(sharedRoot), - }) + const externalId = workspaceIdentity(sharedRoot) + if (externalId !== undefined) { + keys.push({ + integration: SHARED_WORKSPACE_INTEGRATION, + kind: 'workspace', + external_id: externalId, + }) + } if (hostPath !== undefined) keys.push(legacyWorkspaceBindingKey(hostPath)) } return keys diff --git a/integrations/opencode/plugins/powercontext/tests/scope.spec.ts b/integrations/opencode/plugins/powercontext/tests/scope.spec.ts index c5bd846cd2..6a547916d3 100644 --- a/integrations/opencode/plugins/powercontext/tests/scope.spec.ts +++ b/integrations/opencode/plugins/powercontext/tests/scope.spec.ts @@ -43,24 +43,29 @@ const pathHash = (path: string) => createHash('sha256').update(path).digest('hex describe('Scope binding', () => { it('resolves session, workspace, and default precedence on the Server', async () => { - const request = vi.fn().mockResolvedValue({ value: { scope_id: 'scp_00000000000000000000000000' } }) - const client = { request } as never - - await expect(resolveScopeId(client, { - cwd: '/workspace/powercontext', - sessionID: 'session-a', - configuredScopeId: 'explicit-scope', - })).resolves.toBe('scp_00000000000000000000000000') - const firstCall = request.mock.calls[0] - expect(firstCall).toBeDefined() - if (!firstCall) throw new Error('resolve_scope_binding was not called') - const [operation, input] = firstCall - expect(operation).toBe('resolve_scope_binding') - expect(input.explicit_scope_id).toBe('explicit-scope') - expect(input.binding_keys[0]).toEqual({ integration: 'opencode', kind: 'session', external_id: 'session-a' }) - expect(input.binding_keys[1]).toMatchObject({ integration: 'shared', kind: 'workspace' }) - expect(input.binding_keys[2]).toMatchObject({ integration: 'opencode', kind: 'workspace' }) - expect(input.binding_keys[1].external_id).not.toContain('/workspace/powercontext') + const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pc-opencode-scope-'))) + try { + const request = vi.fn().mockResolvedValue({ value: { scope_id: 'scp_00000000000000000000000000' } }) + const client = { request } as never + + await expect(resolveScopeId(client, { + cwd: dir, + sessionID: 'session-a', + configuredScopeId: 'explicit-scope', + })).resolves.toBe('scp_00000000000000000000000000') + const firstCall = request.mock.calls[0] + expect(firstCall).toBeDefined() + if (!firstCall) throw new Error('resolve_scope_binding was not called') + const [operation, input] = firstCall + expect(operation).toBe('resolve_scope_binding') + expect(input.explicit_scope_id).toBe('explicit-scope') + expect(input.binding_keys[0]).toEqual({ integration: 'opencode', kind: 'session', external_id: 'session-a' }) + expect(input.binding_keys[1]).toMatchObject({ integration: 'shared', kind: 'workspace' }) + expect(input.binding_keys[2]).toMatchObject({ integration: 'opencode', kind: 'workspace' }) + expect(input.binding_keys[1].external_id).not.toContain(dir) + } finally { + rmSync(dir, { recursive: true, force: true }) + } }) it('fixes a new session to its resolved Scope', async () => { @@ -95,11 +100,11 @@ describe('Scope binding', () => { ]) }) - it('sends only the workspace key on a route without a session', async () => { + it('sends only the legacy workspace key when a synthetic path does not exist on disk', async () => { const request = vi.fn().mockResolvedValue({ value: { scope_id: 'scope-a' } }) await resolveScopeId({ request } as never, { - cwd: '/workspace/powercontext', + cwd: '/workspace/powercontext-nonexistent-2879', configuredScopeId: 'explicit-scope', }) @@ -107,9 +112,8 @@ describe('Scope binding', () => { expect(firstCall).toBeDefined() if (!firstCall) throw new Error('resolve_scope_binding was not called') const input = firstCall[1] - expect(input.binding_keys).toHaveLength(2) - expect(input.binding_keys[0]).toMatchObject({ integration: 'shared', kind: 'workspace' }) - expect(input.binding_keys[1]).toMatchObject({ integration: 'opencode', kind: 'workspace' }) + expect(input.binding_keys).toHaveLength(1) + expect(input.binding_keys[0]).toMatchObject({ integration: 'opencode', kind: 'workspace' }) expect(input.binding_keys[0].external_id).toHaveLength(64) }) diff --git a/integrations/opencode/plugins/powercontext/tests/tui.spec.tsx b/integrations/opencode/plugins/powercontext/tests/tui.spec.tsx index 0b39215599..a8416ecfdc 100644 --- a/integrations/opencode/plugins/powercontext/tests/tui.spec.tsx +++ b/integrations/opencode/plugins/powercontext/tests/tui.spec.tsx @@ -160,8 +160,8 @@ describe('PowerContextTuiPlugin', () => { kind: 'session', external_id: 'session-1', }) - expect(resolveCalls[0]?.body.binding_keys[1]).toMatchObject({ integration: 'shared', kind: 'workspace' }) - expect(resolveCalls[0]?.body.binding_keys[2]).toMatchObject({ integration: 'opencode', kind: 'workspace' }) + expect(resolveCalls[0]?.body.binding_keys[1]).toMatchObject({ integration: 'opencode', kind: 'workspace' }) + expect(resolveCalls[0]?.body.binding_keys).toHaveLength(2) expect(dialog.setSize).toHaveBeenCalledWith('large') }) diff --git a/integrations/pi/plugins/powercontext/src/git-worktree.ts b/integrations/pi/plugins/powercontext/src/git-worktree.ts index a39ee55956..fb5d5f12e4 100644 --- a/integrations/pi/plugins/powercontext/src/git-worktree.ts +++ b/integrations/pi/plugins/powercontext/src/git-worktree.ts @@ -19,7 +19,8 @@ import { execFile, execFileSync } from 'node:child_process' import { createHash } from 'node:crypto' -import { realpathSync } from 'node:fs' +import { realpathSync, statSync } from 'node:fs' +import { homedir } from 'node:os' import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { promisify } from 'node:util' @@ -69,52 +70,84 @@ export function normalizeWindowsRealPath(value: string, win32?: boolean): string return resolved } -/** Return the canonical real path of `directory` with symbolic links resolved on existing ancestors. */ -export function realWorkspacePath(directory: string): string { - const input = isAbsolute(directory) ? directory : process.cwd() + sep + directory +/** Return the OS-canonical real path of an existing `directory`, or `undefined` when unavailable. */ +export function realWorkspacePath(directory: string): string | undefined { + if (!directory) return undefined + let expanded = directory + if (expanded === '~' || expanded.startsWith('~/') || expanded.startsWith('~\\')) { + const home = process.env.HOME || process.env.USERPROFILE || homedir() + expanded = expanded === '~' ? home : join(home, expanded.slice(2)) + } + const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded try { - return normalizeWindowsRealPath(realpathSync.native(input)) + const resolved = realpathSync.native(input) + if (!statSync(resolved).isDirectory()) return undefined + return normalizeWindowsRealPath(resolved) } catch { - // Resolve symbolic links on the deepest existing ancestor, matching Python's os.path.realpath. + return undefined } - const target = resolve(directory) - let current = target - const suffix = [] - while (true) { - const parent = dirname(current) - if (parent === current) return normalizeWindowsRealPath(target) - suffix.unshift(basename(current)) - current = parent - try { - const resolvedAncestor = realpathSync.native(current) - return normalizeWindowsRealPath(join(resolvedAncestor, ...suffix)) - } catch { - // Keep walking up until an existing directory is found. +} + +/** Return the lowercase hex SHA-256 of the UTF-8 canonical real path of an existing `directory`. */ +export function workspaceIdentity(directory: string): string | undefined { + const canonical = realWorkspacePath(directory) + if (canonical === undefined) return undefined + if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { + const [rawTop = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) + const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) + return [realWorkspacePath(top || directory) ?? '', source] } -/** Return the lowercase hex SHA-256 of the canonical real path of `directory`. */ -export function workspaceIdentity(directory: string): string { - return createHash('sha256').update(realWorkspacePath(directory), 'utf8').digest('hex') +/** Synchronous counterpart of `describeWorkspaceRoot`. */ +export function describeWorkspaceRootSync(directory: string, timeout: number): string[] { + const [rawTop = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) + const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) + return [realWorkspacePath(top || directory) ?? '', source] } /** * Return `[sharedRoot, hostPath]` pairs for `directory` and, in a linked worktree, its main checkout. * - * `sharedRoot` is always the Git top level inside a work tree, or `directory` outside Git. `hostPath` preserves the - * host's legacy rule from the same Git invocation, and is omitted when the main-checkout counterpart is unavailable or - * links back to `directory`. + * `sharedRoot` is always the Git top level inside a work tree (unless guarded by home/filesystem-root rules), or + * `directory` outside Git. `hostPath` preserves the host's legacy rule from the same Git invocation, and is omitted + * when the main-checkout counterpart is unavailable or links back to `directory`. */ export async function workspaceLocations(directory: string, gitRoot: boolean, timeout: number): Promise { const deadline = Date.now() + timeout - const [top = '', gitDir = '', common = ''] = gitPaths(await gitOutput(['-C', directory, ...GIT_ARGUMENTS], timeout)) + const [rawTop = '', gitDir = '', common = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) + const [top = ''] = guardedGitTop(directory, rawTop) const sharedOwn = top || directory - const hostOwn = gitRoot ? sharedOwn : directory + const hostOwn = gitRoot ? (rawTop || directory) : directory + if (!top) return [[sharedOwn, hostOwn]] const mainRoot = mainWorktreeRoot(top, gitDir, common) if (mainRoot === undefined) return [[sharedOwn, hostOwn]] // An unknown answer leaves the second path out, as for a bare repository. - const bare = await gitOutput(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) + const bare = await gitOutput(directory, ['--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] @@ -123,12 +156,14 @@ export async function workspaceLocations(directory: string, gitRoot: boolean, ti /** Return what `workspaceLocations` returns, for hosts whose hooks compute their keys synchronously. */ export function workspaceLocationsSync(directory: string, gitRoot: boolean, timeout: number): string[][] { const deadline = Date.now() + timeout - const [top = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(['-C', directory, ...GIT_ARGUMENTS], timeout)) + const [rawTop = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) + const [top = ''] = guardedGitTop(directory, rawTop) const sharedOwn = top || directory - const hostOwn = gitRoot ? sharedOwn : directory + const hostOwn = gitRoot ? (rawTop || directory) : directory + if (!top) return [[sharedOwn, hostOwn]] const mainRoot = mainWorktreeRoot(top, gitDir, common) if (mainRoot === undefined) return [[sharedOwn, hostOwn]] - const bare = gitOutputSync(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) + const bare = gitOutputSync(directory, ['--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) if (bare.trim() !== 'false') return [[sharedOwn, hostOwn]] const hostMain = gitRoot ? mainRoot : mainWorktreeSubdir(directory, top, mainRoot) return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] @@ -151,20 +186,29 @@ export function workspacePathsSync(directory: string, gitRoot: boolean, timeout: return result } +function existingDirectory(directory: string): boolean { + if (!directory) return false + try { + return statSync(directory, { throwIfNoEntry: false })?.isDirectory() === true + } catch { + return false + } +} + // Return what Git prints, or an empty string when it fails or time is up. -async function gitOutput(args: string[], timeout: number): Promise { - if (timeout <= 0) return '' +async function gitOutput(directory: string, args: string[], timeout: number): Promise { + if (timeout <= 0 || !existingDirectory(directory)) return '' try { - return (await runGit('git', args, { encoding: 'utf8', timeout, windowsHide: true })).stdout + return (await runGit('git', ['-C', directory, ...args], { encoding: 'utf8', timeout, windowsHide: true })).stdout } catch { return '' } } -function gitOutputSync(args: string[], timeout: number): string { - if (timeout <= 0) return '' +function gitOutputSync(directory: string, args: string[], timeout: number): string { + if (timeout <= 0 || !existingDirectory(directory)) return '' try { - return execFileSync('git', args, { + return execFileSync('git', ['-C', directory, ...args], { encoding: 'utf8', timeout, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'], }) } catch { diff --git a/integrations/pi/plugins/powercontext/src/scope.ts b/integrations/pi/plugins/powercontext/src/scope.ts index 124124c147..57aa1cf954 100644 --- a/integrations/pi/plugins/powercontext/src/scope.ts +++ b/integrations/pi/plugins/powercontext/src/scope.ts @@ -28,12 +28,14 @@ type ScopeBindingKey = { integration: string; kind: string; external_id: string const GIT_TIMEOUT_MS = 500 -export function sharedWorkspaceBindingKey(cwd: string): ScopeBindingKey { +export function sharedWorkspaceBindingKey(cwd: string): ScopeBindingKey | undefined { const [sharedRoot = cwd] = workspaceLocationsSync(cwd, false, GIT_TIMEOUT_MS)[0] ?? [cwd] + const externalId = workspaceIdentity(sharedRoot) + if (externalId === undefined) return undefined return { integration: SHARED_WORKSPACE_INTEGRATION, kind: 'workspace', - external_id: workspaceIdentity(sharedRoot), + external_id: externalId, } } @@ -45,7 +47,7 @@ export function legacyWorkspaceBindingKey(cwd: string): ScopeBindingKey { } } -export function workspaceBindingKey(cwd: string): ScopeBindingKey { +export function workspaceBindingKey(cwd: string): ScopeBindingKey | undefined { return sharedWorkspaceBindingKey(cwd) } @@ -53,11 +55,14 @@ export function workspaceBindingKey(cwd: string): ScopeBindingKey { export async function workspaceBindingKeys(cwd: string): Promise { const keys: ScopeBindingKey[] = [] for (const [sharedRoot = cwd, hostPath] of await workspaceLocations(cwd, false, GIT_TIMEOUT_MS)) { - keys.push({ - integration: SHARED_WORKSPACE_INTEGRATION, - kind: 'workspace', - external_id: workspaceIdentity(sharedRoot), - }) + const externalId = workspaceIdentity(sharedRoot) + if (externalId !== undefined) { + keys.push({ + integration: SHARED_WORKSPACE_INTEGRATION, + kind: 'workspace', + external_id: externalId, + }) + } if (hostPath !== undefined) keys.push(legacyWorkspaceBindingKey(hostPath)) } return keys diff --git a/integrations/pi/plugins/powercontext/tests/scope.spec.ts b/integrations/pi/plugins/powercontext/tests/scope.spec.ts index 3c429a67b4..abe2d7939f 100644 --- a/integrations/pi/plugins/powercontext/tests/scope.spec.ts +++ b/integrations/pi/plugins/powercontext/tests/scope.spec.ts @@ -43,19 +43,24 @@ const pathHash = (path: string) => createHash('sha256').update(path).digest('hex describe('Scope binding', () => { it('resolves explicit, durable, and default precedence on the Server', async () => { - const request = vi.fn().mockResolvedValue({ value: { scope_id: 'scp_00000000000000000000000000' } }) - const client = { request } as never + const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pc-pi-scope-'))) + try { + const request = vi.fn().mockResolvedValue({ value: { scope_id: 'scp_00000000000000000000000000' } }) + const client = { request } as never - await expect(resolveScopeId(client, '/workspace/powercontext', 'explicit-scope')).resolves.toBe( - 'scp_00000000000000000000000000', - ) - const [operation, input] = request.mock.calls[0] - expect(operation).toBe('resolve_scope_binding') - expect(input.explicit_scope_id).toBe('explicit-scope') - expect(input.binding_keys).toHaveLength(2) - expect(input.binding_keys[0]).toMatchObject({ integration: 'shared', kind: 'workspace' }) - expect(input.binding_keys[1]).toMatchObject({ integration: 'pi', kind: 'workspace' }) - expect(input.binding_keys[0].external_id).not.toContain('/workspace/powercontext') + await expect(resolveScopeId(client, dir, 'explicit-scope')).resolves.toBe( + 'scp_00000000000000000000000000', + ) + const [operation, input] = request.mock.calls[0] + expect(operation).toBe('resolve_scope_binding') + expect(input.explicit_scope_id).toBe('explicit-scope') + expect(input.binding_keys).toHaveLength(2) + expect(input.binding_keys[0]).toMatchObject({ integration: 'shared', kind: 'workspace' }) + expect(input.binding_keys[1]).toMatchObject({ integration: 'pi', kind: 'workspace' }) + expect(input.binding_keys[0].external_id).not.toContain(dir) + } finally { + rmSync(dir, { recursive: true, force: true }) + } }) it('rejects an invalid resolver response', async () => { diff --git a/integrations/workbuddy/plugins/powercontext/hooks/git_worktree.py b/integrations/workbuddy/plugins/powercontext/hooks/git_worktree.py index 721e66c091..65f6747778 100644 --- a/integrations/workbuddy/plugins/powercontext/hooks/git_worktree.py +++ b/integrations/workbuddy/plugins/powercontext/hooks/git_worktree.py @@ -25,6 +25,7 @@ import hashlib import os import subprocess +import sys import time from shutil import which @@ -59,33 +60,95 @@ def normalize_windows_real_path(path: str, *, windows: bool = os.name == "nt") - return resolved -def real_workspace_path(path: str) -> str: - """Return the canonical real path of ``path`` with symbolic links resolved and Windows drive prefixes normalized.""" +def _darwin_canonical_path(path: str) -> str: + if sys.platform != "darwin": + return path + import fcntl + + fd = os.open(path, os.O_RDONLY) + try: + raw = fcntl.fcntl(fd, fcntl.F_GETPATH, b"\x00" * 1024) + finally: + os.close(fd) + return os.fsdecode(raw.split(b"\x00", 1)[0]) + + +def real_workspace_path(path: str) -> str | None: + """Return the OS-canonical real path of an existing directory ``path``, or ``None`` when unavailable.""" + + expanded = os.path.expanduser(path) + if not expanded or not os.path.isdir(expanded): + return None + try: + resolved = _darwin_canonical_path(os.path.realpath(expanded)) + except OSError: + return None + if not os.path.isdir(resolved): + return None + return normalize_windows_real_path(resolved) - return normalize_windows_real_path(os.path.realpath(path)) +def workspace_identity(path: str) -> str | None: + """Return the lowercase hex SHA-256 of the UTF-8 canonical real path of existing directory ``path``.""" -def workspace_identity(path: str) -> str: - """Return the lowercase hex SHA-256 of the canonical real path of ``path``.""" + canonical = real_workspace_path(path) + if canonical is None: + return None + try: + encoded = canonical.encode("utf-8") + except UnicodeEncodeError: + return None + return hashlib.sha256(encoded).hexdigest() - if os.name == "nt": - return hashlib.sha256(real_workspace_path(path).encode("utf-8", errors="surrogatepass")).hexdigest() - return hashlib.sha256(os.fsencode(real_workspace_path(path))).hexdigest() + +def _guarded_git_top(cwd: str, top: str | None) -> tuple[str | None, str]: + if top is None: + return None, "directory" + top_real = real_workspace_path(top) + if top_real is None: + return None, "directory" + cwd_real = real_workspace_path(cwd) + if cwd_real is not None and cwd_real == top_real: + return top, "git_root" + if os.path.dirname(top_real) == top_real: + return None, "home_guard" + home_real = real_workspace_path("~") + if home_real is not None: + current = home_real + while True: + if current == top_real: + return None, "home_guard" + parent = os.path.dirname(current) + if parent == current: + break + current = parent + return top, "git_root" + + +def describe_workspace_root(cwd: str, *, timeout: float = 2.0) -> tuple[str | None, str]: + """Return ``(canonical_root, root_source)`` for diagnostics and operator CLI output.""" + + raw_top, _git_dir, _common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + effective_top, source = _guarded_git_top(cwd, raw_top) + return real_workspace_path(effective_top or cwd), source def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[tuple[str, str | None]]: """Return ``(shared_root, host_path)`` pairs for ``cwd`` and, in a linked worktree, its main checkout. - ``shared_root`` is always the Git top level when inside a work tree, or ``cwd`` outside Git, so every host derives - the same shared workspace key. ``host_path`` preserves each host's legacy path rule (the Git top level when - ``git_root`` is true, otherwise ``cwd`` and its counterpart subdirectory in the main checkout) from the same Git - invocation, or ``None`` when the main-checkout counterpart is unavailable or links back to ``cwd``. + ``shared_root`` is always the Git top level when inside a work tree (unless guarded by home/filesystem-root rules), + or ``cwd`` outside Git, so every host derives the same shared workspace key. ``host_path`` preserves each host's + legacy path rule from the same Git invocation, or ``None`` when the main-checkout counterpart is unavailable or + links back to ``cwd``. """ deadline = time.monotonic() + timeout - top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + raw_top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + top, _source = _guarded_git_top(cwd, raw_top) shared_own = top or cwd - host_own = shared_own if git_root else cwd + host_own = (raw_top or cwd) if git_root else cwd + if top is None: + return [(shared_own, host_own)] main_root = _main_worktree_root(top, git_dir, common) if main_root is None or common is None: return [(shared_own, host_own)] @@ -124,8 +187,10 @@ def workspace_paths(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[s def _git_output(cwd: str, arguments: tuple[str, ...], timeout: float) -> str: """Return what Git prints for ``arguments`` in ``cwd``, or an empty string when it fails or time is up.""" + if timeout <= 0 or not cwd or not os.path.isdir(cwd): + return "" executable = which("git") - if executable is None or timeout <= 0: + if executable is None: return "" try: completed = subprocess.run( # noqa: S603 - git executable and arguments are integration-owned. @@ -133,7 +198,8 @@ def _git_output(cwd: str, arguments: tuple[str, ...], timeout: float) -> str: cwd=cwd, check=True, capture_output=True, - text=True, + encoding="utf-8", + errors="surrogateescape", timeout=timeout, ) except (OSError, subprocess.SubprocessError): diff --git a/integrations/workbuddy/plugins/powercontext/scripts/workspace_scope.py b/integrations/workbuddy/plugins/powercontext/scripts/workspace_scope.py index beb26514be..246737ab3a 100644 --- a/integrations/workbuddy/plugins/powercontext/scripts/workspace_scope.py +++ b/integrations/workbuddy/plugins/powercontext/scripts/workspace_scope.py @@ -18,6 +18,7 @@ from __future__ import annotations import argparse +import hashlib import json import os import sys @@ -39,6 +40,7 @@ from git_worktree import ( # noqa: E402 SHARED_WORKSPACE_INTEGRATION, + describe_workspace_root, workspace_identity, workspace_locations, ) @@ -190,7 +192,10 @@ def clear_scope_binding( """Remove the shared workspace binding and WorkBuddy's legacy workspace binding.""" shared_root, host_path = workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline))[0] - keys = [_shared_workspace_key(shared_root)] + keys: list[dict[str, str]] = [] + shared_key = _shared_workspace_key(shared_root) + if shared_key is not None: + keys.append(shared_key) if host_path is not None: keys.append(_workspace_key(host_path)) cleared_any = False @@ -217,9 +222,16 @@ def diagnose_scope_binding( ) -> dict[str, Any]: """Resolve the active Scope and identify which candidate binding key matched.""" + resolved_root, root_source = describe_workspace_root(cwd, timeout=_git_timeout(deadline)) if settings.scope_id is not None: scope_id = resolve_scope_id(cwd, session_id=session_id, settings=settings, deadline=deadline) - return {"scope_id": scope_id, "source": "explicit", "matched_key": None} + return { + "scope_id": scope_id, + "source": "explicit", + "matched_key": None, + "resolved_root": resolved_root, + "root_source": root_source, + } for key in binding_keys(cwd, session_id=session_id, deadline=deadline): try: response = _request_json( @@ -235,7 +247,13 @@ def diagnose_scope_binding( scope_id = response.get("scope_id") if not isinstance(scope_id, str) or not scope_id.strip() or scope_id != scope_id.strip(): raise ScopeBindingError - return {"scope_id": scope_id, "source": "binding", "matched_key": key} + return { + "scope_id": scope_id, + "source": "binding", + "matched_key": key, + "resolved_root": resolved_root, + "root_source": root_source, + } response = _request_json( "/v1/scope-bindings/resolve", {"explicit_scope_id": None, "binding_keys": [], "allow_default": True}, @@ -245,7 +263,13 @@ def diagnose_scope_binding( scope_id = response.get("scope_id") if not isinstance(scope_id, str) or not scope_id.strip() or scope_id != scope_id.strip(): raise ScopeBindingError - return {"scope_id": scope_id, "source": "default", "matched_key": None} + return { + "scope_id": scope_id, + "source": "default", + "matched_key": None, + "resolved_root": resolved_root, + "root_source": root_source, + } def binding_keys(cwd: str, *, session_id: str | None, deadline: float | None = None) -> list[dict[str, str]]: @@ -253,7 +277,9 @@ def binding_keys(cwd: str, *, session_id: str | None, deadline: float | None = N if session_id is not None: keys.append(session_binding_key(session_id)) for shared_root, host_path in workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline)): - keys.append(_shared_workspace_key(shared_root)) + shared_key = _shared_workspace_key(shared_root) + if shared_key is not None: + keys.append(shared_key) if host_path is not None: keys.append(_workspace_key(host_path)) return keys @@ -270,18 +296,24 @@ def workspace_binding_key(cwd: str, *, deadline: float | None = None) -> dict[st """Return the shared key of the workspace's own Git top level, the key that binding writes.""" shared_root, _host_path = workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline))[0] - return _shared_workspace_key(shared_root) + key = _shared_workspace_key(shared_root) + if key is None: + raise ScopeBindingError + return key -def _shared_workspace_key(path: str) -> dict[str, str]: - return {"integration": SHARED_WORKSPACE_INTEGRATION, "kind": "workspace", "external_id": workspace_identity(path)} +def _shared_workspace_key(path: str) -> dict[str, str] | None: + identity = workspace_identity(path) + if identity is None: + return None + return {"integration": SHARED_WORKSPACE_INTEGRATION, "kind": "workspace", "external_id": identity} def _workspace_key(path: str) -> dict[str, str]: return { "integration": "workbuddy", "kind": "workspace", - "external_id": workspace_identity(path), + "external_id": hashlib.sha256(os.fsencode(Path(path).expanduser().resolve())).hexdigest(), } diff --git a/integrations/zcode/plugins/powercontext/scripts/doctor.mjs b/integrations/zcode/plugins/powercontext/scripts/doctor.mjs index fceb72b8de..71d81f0c5f 100644 --- a/integrations/zcode/plugins/powercontext/scripts/doctor.mjs +++ b/integrations/zcode/plugins/powercontext/scripts/doctor.mjs @@ -16,7 +16,7 @@ import { parseArgs } from 'node:util' import { queryObservations } from '../shared/observations.mjs' -import { isScopeId, resolveScope } from '../shared/scope.mjs' +import { describeWorkspace, isScopeId, resolveScope } from '../shared/scope.mjs' import { loadSettings } from '../shared/settings.mjs' import { failureCode, HOOK_BUDGET_MS, request } from '../shared/transport.mjs' @@ -61,9 +61,14 @@ try { } } } + const [resolvedRoot = '', rootSource = 'directory'] = settings.remoteWorkspace + ? ['', 'remote'] + : describeWorkspace(input.cwd) checks.scope_probe = { status: 'ok', code: 'resolved', scope_id: scope.scopeId, session_key_used: scope.keys.some(key => key.kind === 'session'), - ...(matchedKey ? { matched_key: matchedKey } : {}) } + ...(matchedKey ? { matched_key: matchedKey } : {}), + ...(resolvedRoot ? { resolved_root: resolvedRoot } : {}), + root_source: rootSource } } catch (error) { checks.scope_probe = { status: 'failed', code: failureCode(error) } } if (values.prepare && scope) { try { diff --git a/integrations/zcode/plugins/powercontext/scripts/scope.mjs b/integrations/zcode/plugins/powercontext/scripts/scope.mjs index c33aeb6c6c..64fb8b6cf7 100644 --- a/integrations/zcode/plugins/powercontext/scripts/scope.mjs +++ b/integrations/zcode/plugins/powercontext/scripts/scope.mjs @@ -42,8 +42,13 @@ try { const signal = AbortSignal.timeout(HOOK_BUDGET_MS) if (action !== 'resolve') { if (settings.remoteWorkspace) throw new Error('remote_binding_disabled') - const key = workspaceKey(cwd) - const keys = action === 'bind' ? [key] : [key, legacyWorkspaceKey(cwd)] + const sharedKey = action === 'bind' ? workspaceKey(cwd) : (() => { + try { return workspaceKey(cwd) } catch { return undefined } + })() + const keys = action === 'bind' ? [sharedKey] : [ + ...(sharedKey ? [sharedKey] : []), + legacyWorkspaceKey(cwd), + ] const target = args.values['scope-id'] binding = { action, status: 'unknown' } let clearedAny = false diff --git a/integrations/zcode/plugins/powercontext/shared/git-worktree.mjs b/integrations/zcode/plugins/powercontext/shared/git-worktree.mjs index 6b5e9d5259..0a029f5261 100644 --- a/integrations/zcode/plugins/powercontext/shared/git-worktree.mjs +++ b/integrations/zcode/plugins/powercontext/shared/git-worktree.mjs @@ -19,7 +19,8 @@ import { execFile, execFileSync } from 'node:child_process' import { createHash } from 'node:crypto' -import { realpathSync } from 'node:fs' +import { realpathSync, statSync } from 'node:fs' +import { homedir } from 'node:os' import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { promisify } from 'node:util' @@ -69,52 +70,84 @@ export function normalizeWindowsRealPath(value, win32) { return resolved } -/** Return the canonical real path of `directory` with symbolic links resolved on existing ancestors. */ +/** Return the OS-canonical real path of an existing `directory`, or `undefined` when unavailable. */ export function realWorkspacePath(directory) { - const input = isAbsolute(directory) ? directory : process.cwd() + sep + directory + if (!directory) return undefined + let expanded = directory + if (expanded === '~' || expanded.startsWith('~/') || expanded.startsWith('~\\')) { + const home = process.env.HOME || process.env.USERPROFILE || homedir() + expanded = expanded === '~' ? home : join(home, expanded.slice(2)) + } + const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded try { - return normalizeWindowsRealPath(realpathSync.native(input)) + const resolved = realpathSync.native(input) + if (!statSync(resolved).isDirectory()) return undefined + return normalizeWindowsRealPath(resolved) } catch { - // Resolve symbolic links on the deepest existing ancestor, matching Python's os.path.realpath. + return undefined } - const target = resolve(directory) - let current = target - const suffix = [] - while (true) { - const parent = dirname(current) - if (parent === current) return normalizeWindowsRealPath(target) - suffix.unshift(basename(current)) - current = parent - try { - const resolvedAncestor = realpathSync.native(current) - return normalizeWindowsRealPath(join(resolvedAncestor, ...suffix)) - } catch { - // Keep walking up until an existing directory is found. +} + +/** Return the lowercase hex SHA-256 of the UTF-8 canonical real path of an existing `directory`. */ +export function workspaceIdentity(directory) { + const canonical = realWorkspacePath(directory) + if (canonical === undefined) return undefined + if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? tuple[str, bool]: + """Resolve ``path`` on disk when it exists, or canonicalize its deepest existing ancestor for offline cleanup.""" + + existing = real_workspace_path(path) + if existing is not None: + return existing, True + current = os.path.realpath(os.path.expanduser(path)) + tail: list[str] = [] + while True: + if os.path.isdir(current): + try: + canon = _darwin_canonical_path(current) + except OSError: + canon = current + combined = os.path.join(canon, *tail) if tail else canon + return normalize_windows_real_path(combined), False + parent = os.path.dirname(current) + if parent == current: + combined = os.path.join(current, *tail) if tail else current + return normalize_windows_real_path(combined), False + tail.insert(0, os.path.basename(current)) + current = parent + + +def _best_effort_workspace_identity(path: str) -> tuple[str | None, str, bool]: + canonical, exists = _best_effort_canonical_path(path) + try: + digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest() + except UnicodeEncodeError: + return None, canonical, exists + return digest, canonical, exists + + def _legacy_host_workspace_external_id(path: str, integration: str) -> str: + expanded = os.path.expanduser(path) if integration in _RESOLVED_CWD_WORKSPACE_INTEGRATIONS: - # Node hosts that key path.resolve preserve symbolic links. - return hashlib.sha256(os.path.abspath(path).encode("utf-8")).hexdigest() - return workspace_identity(path) + return hashlib.sha256(os.path.abspath(expanded).encode("utf-8")).hexdigest() + if integration == "kimi-code": + existing = real_workspace_path(expanded) + target = existing if existing is not None else os.path.abspath(expanded) + return hashlib.sha256(target.encode("utf-8")).hexdigest() + if integration in {"bub", "zcode"}: + return hashlib.sha256(str(Path(expanded).resolve()).encode("utf-8")).hexdigest() + return hashlib.sha256(os.fsencode(Path(expanded).resolve())).hexdigest() + + +def _legacy_host_clear_external_ids(path: str, integration: str) -> list[str]: + ids = [_legacy_host_workspace_external_id(path, integration)] + if integration not in _RESOLVED_CWD_WORKSPACE_INTEGRATIONS: + canon, _exists = _best_effort_canonical_path(path) + try: + canon_id = hashlib.sha256(canon.encode("utf-8")).hexdigest() + except UnicodeEncodeError: + canon_id = None + if canon_id is not None and canon_id not in ids: + ids.append(canon_id) + return ids def _workspace_binding_keys(cwd: Path, integration: str) -> list[ScopeBindingKey]: """Return the workspace keys that resolution tries in order, matching the host plugin's sequence.""" if integration == SHARED_WORKSPACE_INTEGRATION: - return [ - _binding_key(SHARED_WORKSPACE_INTEGRATION, _BINDING_KIND_WORKSPACE, workspace_identity(shared_root)) - for shared_root, _host_path in workspace_locations(str(cwd), git_root=True) - ] + shared_keys: list[ScopeBindingKey] = [] + for shared_root, _host_path in workspace_locations(str(cwd), git_root=True): + shared_id = workspace_identity(shared_root) + if shared_id is not None: + shared_keys.append(_binding_key(SHARED_WORKSPACE_INTEGRATION, _BINDING_KIND_WORKSPACE, shared_id)) + return shared_keys if integration not in _HOST_WORKSPACE_INTEGRATIONS: raise typer.BadParameter( # noqa: TRY003 - user-facing CLI validation. "Unsupported workspace integration; use an explicit binding key instead.", param_hint="--integration" @@ -386,9 +444,9 @@ def _workspace_binding_keys(cwd: Path, integration: str) -> list[ScopeBindingKey for shared_root, host_path in workspace_locations( str(cwd), git_root=integration in _GIT_ROOT_WORKSPACE_INTEGRATIONS ): - keys.append( - _binding_key(SHARED_WORKSPACE_INTEGRATION, _BINDING_KIND_WORKSPACE, workspace_identity(shared_root)) - ) + shared_id = workspace_identity(shared_root) + if shared_id is not None: + keys.append(_binding_key(SHARED_WORKSPACE_INTEGRATION, _BINDING_KIND_WORKSPACE, shared_id)) if host_path is not None: keys.append( _binding_key( @@ -400,6 +458,73 @@ def _workspace_binding_keys(cwd: Path, integration: str) -> list[ScopeBindingKey return keys +def _resolve_set_cwd_binding_target( + cwd: Path, + integration: str | None, +) -> tuple[list[ScopeBindingKey], str | None, str | None, bool]: + if integration is not None and integration != SHARED_WORKSPACE_INTEGRATION: + raise typer.BadParameter( # noqa: TRY003 + "--cwd always writes the 'shared' workspace binding; omit --integration.", + param_hint="--integration", + ) + if real_workspace_path(str(cwd)) is None: + raise typer.BadParameter( # noqa: TRY003 + "Workspace directory does not exist.", + param_hint="--cwd", + ) + resolved_root, root_source = describe_workspace_root(str(cwd)) + shared_root, _host_path = workspace_locations(str(cwd), git_root=True)[0] + shared_id = workspace_identity(shared_root) + if shared_id is None: + raise typer.BadParameter( # noqa: TRY003 + "Workspace path cannot be encoded as UTF-8.", + param_hint="--cwd", + ) + return ( + [_binding_key(SHARED_WORKSPACE_INTEGRATION, _BINDING_KIND_WORKSPACE, shared_id)], + resolved_root, + root_source, + True, + ) + + +def _resolve_clear_cwd_binding_target( + cwd: Path, + integration: str | None, +) -> tuple[list[ScopeBindingKey], str | None, str | None, bool]: + if ( + integration is not None + and integration != SHARED_WORKSPACE_INTEGRATION + and integration not in _HOST_WORKSPACE_INTEGRATIONS + ): + raise typer.BadParameter( # noqa: TRY003 + "Unsupported workspace integration; use --external-id instead.", param_hint="--integration" + ) + existing_root, root_source = describe_workspace_root(str(cwd)) + if existing_root is not None: + shared_root, _ = workspace_locations(str(cwd), git_root=True)[0] + shared_id = workspace_identity(shared_root) + canonical_root = existing_root + exists = True + else: + shared_id, canonical_root, exists = _best_effort_workspace_identity(str(cwd)) + root_source = "missing_directory" + clear_keys = ( + [_binding_key(SHARED_WORKSPACE_INTEGRATION, _BINDING_KIND_WORKSPACE, shared_id)] + if shared_id is not None + else [] + ) + if integration == SHARED_WORKSPACE_INTEGRATION: + return clear_keys, canonical_root, root_source, exists + target_hosts = sorted(_HOST_WORKSPACE_INTEGRATIONS) if integration is None else [integration] + git_root_host_path = workspace_locations(str(cwd), git_root=True)[0][1] if exists else str(cwd) + for host_name in target_hosts: + host_dir = (git_root_host_path or str(cwd)) if host_name in _GIT_ROOT_WORKSPACE_INTEGRATIONS else str(cwd) + for legacy_id in _legacy_host_clear_external_ids(host_dir, host_name): + clear_keys.append(_binding_key(host_name, _BINDING_KIND_WORKSPACE, legacy_id)) + return clear_keys, canonical_root, root_source, exists + + def _resolve_cli_binding_target( *, kind: str | None, @@ -407,42 +532,20 @@ def _resolve_cli_binding_target( cwd: Path | None, integration: str | None, for_clear: bool = False, -) -> list[ScopeBindingKey]: +) -> tuple[list[ScopeBindingKey], str | None, str | None, bool]: if cwd is not None and external_id is not None: raise typer.BadParameter("--cwd and --external-id cannot be used together") # noqa: TRY003 if cwd is not None: if kind is not None and kind != _BINDING_KIND_WORKSPACE: raise typer.BadParameter("--cwd only applies to --kind workspace") # noqa: TRY003 - target_integration = SHARED_WORKSPACE_INTEGRATION if integration is None else integration - if ( - target_integration != SHARED_WORKSPACE_INTEGRATION - and target_integration not in _HOST_WORKSPACE_INTEGRATIONS - ): - raise typer.BadParameter( # noqa: TRY003 - "Unsupported workspace integration; use --external-id instead.", param_hint="--integration" - ) - shared_root, host_path = workspace_locations( - str(cwd), - git_root=target_integration == SHARED_WORKSPACE_INTEGRATION - or target_integration in _GIT_ROOT_WORKSPACE_INTEGRATIONS, - )[0] - shared_key = _binding_key( - SHARED_WORKSPACE_INTEGRATION, _BINDING_KIND_WORKSPACE, workspace_identity(shared_root) - ) - if target_integration == SHARED_WORKSPACE_INTEGRATION: - return [shared_key] - resolved_host_path = host_path if host_path is not None else str(cwd) - host_key = _binding_key( - target_integration, - _BINDING_KIND_WORKSPACE, - _legacy_host_workspace_external_id(resolved_host_path, target_integration), - ) - return [shared_key, host_key] if for_clear else [host_key] + if for_clear: + return _resolve_clear_cwd_binding_target(cwd, integration) + return _resolve_set_cwd_binding_target(cwd, integration) if kind is None: raise typer.BadParameter("Missing option '--kind' (or pass '--cwd' for a workspace binding).") # noqa: TRY003 if external_id is None: raise typer.BadParameter("Missing option '--external-id' (or pass '--cwd' for a workspace binding).") # noqa: TRY003 - return [_binding_key(integration or _DEFAULT_BINDING_INTEGRATION, kind, external_id)] + return [_binding_key(integration or _DEFAULT_BINDING_INTEGRATION, kind, external_id)], None, None, True def _binding_key(integration: str, kind: str, external_id: str) -> ScopeBindingKey: @@ -608,9 +711,16 @@ def set_scope_binding( ) -> None: """Bind one external integration identity or local workspace checkout to a Scope.""" - key = _resolve_cli_binding_target(kind=kind, external_id=external_id, cwd=cwd, integration=integration)[0] - request = SetScopeBindingRequest(root=ScopeBinding(key=key, scope_id=scope_id)) + keys, resolved_root, root_source, _exists = _resolve_cli_binding_target( + kind=kind, external_id=external_id, cwd=cwd, integration=integration + ) + request = SetScopeBindingRequest(root=ScopeBinding(key=keys[0], scope_id=scope_id)) asyncio.run(_execute(context, lambda client: client.set_scope_binding(request))) + if cwd is not None and not _options(context).json_output and resolved_root is not None: + typer.echo(f"Workspace root: {resolved_root} ({root_source})") + typer.echo( + "Note: active sessions that pin their Scope at startup (such as Codex and OpenCode) keep their current Scope until a new session starts." + ) @scope_binding_app.command("clear") @@ -633,18 +743,28 @@ def clear_scope_binding( ) -> None: """Clear one external integration or local workspace binding.""" - keys = _resolve_cli_binding_target( + keys, resolved_root, root_source, exists = _resolve_cli_binding_target( kind=kind, external_id=external_id, cwd=cwd, integration=integration, for_clear=True ) + cleared_integrations: list[str] = [] async def operation(client: PowerContextClient) -> ClearScopeBindingResponse: cleared = False for key in keys: response = await client.clear_scope_binding(ClearScopeBindingRequest(key=key)) + if response.cleared and key.integration not in cleared_integrations: + cleared_integrations.append(key.integration) cleared = cleared or response.cleared return ClearScopeBindingResponse(cleared=cleared) asyncio.run(_execute(context, operation)) + if cwd is not None and not _options(context).json_output and resolved_root is not None: + if exists: + typer.echo(f"Workspace root: {resolved_root} ({root_source})") + else: + typer.echo(f"Workspace root: {resolved_root} (directory missing; derived from input spelling)") + if cleared_integrations: + typer.echo(f"Cleared workspace bindings: {', '.join(cleared_integrations)}") @dataclass(frozen=True, slots=True) diff --git a/src/powercontext/client/session_import.py b/src/powercontext/client/session_import.py index af8eae5cbe..11ed90ac21 100644 --- a/src/powercontext/client/session_import.py +++ b/src/powercontext/client/session_import.py @@ -36,6 +36,9 @@ from powercontext.redaction import redact_known_secrets from powercontext_integration_lifecycle.git_worktree import ( SHARED_WORKSPACE_INTEGRATION, + _darwin_canonical_path, + normalize_windows_real_path, + real_workspace_path, workspace_identity, workspace_locations, ) @@ -570,23 +573,52 @@ def _session_binding_keys(session_id: str | None) -> tuple[ScopeBindingKey, ...] return (ScopeBindingKey(integration="codex", kind="session", external_id=value),) +def _offline_shared_identity(path: str) -> str | None: + online = workspace_identity(path) + if online is not None: + return online + current = os.path.realpath(os.path.expanduser(path)) + tail: list[str] = [] + while True: + if os.path.isdir(current): + try: + canon = _darwin_canonical_path(current) + except OSError: + canon = current + resolved = normalize_windows_real_path(os.path.join(canon, *tail) if tail else canon) + break + parent = os.path.dirname(current) + if parent == current: + resolved = normalize_windows_real_path(os.path.join(current, *tail) if tail else current) + break + tail.insert(0, os.path.basename(current)) + current = parent + try: + return sha256(resolved.encode("utf-8")).hexdigest() + except UnicodeEncodeError: + return None + + def _workspace_binding_keys(cwd: str) -> list[ScopeBindingKey]: - # Try the shared workspace key ahead of Codex's own key at both the checkout and, in a linked worktree, its main. + # Try the shared workspace key ahead of Codex's legacy key at both the checkout and, in a linked worktree, its main. keys: list[ScopeBindingKey] = [] - for shared_root, host_path in workspace_locations(cwd, git_root=True): - keys.append( - ScopeBindingKey( - integration=SHARED_WORKSPACE_INTEGRATION, - kind="workspace", - external_id=workspace_identity(shared_root), + locations = workspace_locations(cwd, git_root=True) if real_workspace_path(cwd) is not None else [(cwd, cwd)] + for shared_root, host_path in locations: + shared_id = _offline_shared_identity(shared_root) + if shared_id is not None: + keys.append( + ScopeBindingKey( + integration=SHARED_WORKSPACE_INTEGRATION, + kind="workspace", + external_id=shared_id, + ) ) - ) if host_path is not None: keys.append( ScopeBindingKey( integration="codex", kind="workspace", - external_id=workspace_identity(host_path), + external_id=sha256(os.fsencode(Path(host_path).expanduser().resolve())).hexdigest(), ) ) return keys diff --git a/src/powercontext_integration_lifecycle/git_worktree.py b/src/powercontext_integration_lifecycle/git_worktree.py index bd1ab0d129..adbfa465bc 100644 --- a/src/powercontext_integration_lifecycle/git_worktree.py +++ b/src/powercontext_integration_lifecycle/git_worktree.py @@ -22,6 +22,7 @@ import hashlib import os import subprocess +import sys import time from shutil import which @@ -56,33 +57,95 @@ def normalize_windows_real_path(path: str, *, windows: bool = os.name == "nt") - return resolved -def real_workspace_path(path: str) -> str: - """Return the canonical real path of ``path`` with symbolic links resolved and Windows drive prefixes normalized.""" +def _darwin_canonical_path(path: str) -> str: + if sys.platform != "darwin": + return path + import fcntl + + fd = os.open(path, os.O_RDONLY) + try: + raw = fcntl.fcntl(fd, fcntl.F_GETPATH, b"\x00" * 1024) + finally: + os.close(fd) + return os.fsdecode(raw.split(b"\x00", 1)[0]) + + +def real_workspace_path(path: str) -> str | None: + """Return the OS-canonical real path of an existing directory ``path``, or ``None`` when unavailable.""" + + expanded = os.path.expanduser(path) + if not expanded or not os.path.isdir(expanded): + return None + try: + resolved = _darwin_canonical_path(os.path.realpath(expanded)) + except OSError: + return None + if not os.path.isdir(resolved): + return None + return normalize_windows_real_path(resolved) - return normalize_windows_real_path(os.path.realpath(path)) +def workspace_identity(path: str) -> str | None: + """Return the lowercase hex SHA-256 of the UTF-8 canonical real path of existing directory ``path``.""" -def workspace_identity(path: str) -> str: - """Return the lowercase hex SHA-256 of the canonical real path of ``path``.""" + canonical = real_workspace_path(path) + if canonical is None: + return None + try: + encoded = canonical.encode("utf-8") + except UnicodeEncodeError: + return None + return hashlib.sha256(encoded).hexdigest() - if os.name == "nt": - return hashlib.sha256(real_workspace_path(path).encode("utf-8", errors="surrogatepass")).hexdigest() - return hashlib.sha256(os.fsencode(real_workspace_path(path))).hexdigest() + +def _guarded_git_top(cwd: str, top: str | None) -> tuple[str | None, str]: + if top is None: + return None, "directory" + top_real = real_workspace_path(top) + if top_real is None: + return None, "directory" + cwd_real = real_workspace_path(cwd) + if cwd_real is not None and cwd_real == top_real: + return top, "git_root" + if os.path.dirname(top_real) == top_real: + return None, "home_guard" + home_real = real_workspace_path("~") + if home_real is not None: + current = home_real + while True: + if current == top_real: + return None, "home_guard" + parent = os.path.dirname(current) + if parent == current: + break + current = parent + return top, "git_root" + + +def describe_workspace_root(cwd: str, *, timeout: float = 2.0) -> tuple[str | None, str]: + """Return ``(canonical_root, root_source)`` for diagnostics and operator CLI output.""" + + raw_top, _git_dir, _common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + effective_top, source = _guarded_git_top(cwd, raw_top) + return real_workspace_path(effective_top or cwd), source def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[tuple[str, str | None]]: """Return ``(shared_root, host_path)`` pairs for ``cwd`` and, in a linked worktree, its main checkout. - ``shared_root`` is always the Git top level when inside a work tree, or ``cwd`` outside Git, so every host derives - the same shared workspace key. ``host_path`` preserves each host's legacy path rule (the Git top level when - ``git_root`` is true, otherwise ``cwd`` and its counterpart subdirectory in the main checkout) from the same Git - invocation, or ``None`` when the main-checkout counterpart is unavailable or links back to ``cwd``. + ``shared_root`` is always the Git top level when inside a work tree (unless guarded by home/filesystem-root rules), + or ``cwd`` outside Git, so every host derives the same shared workspace key. ``host_path`` preserves each host's + legacy path rule from the same Git invocation, or ``None`` when the main-checkout counterpart is unavailable or + links back to ``cwd``. """ deadline = time.monotonic() + timeout - top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + raw_top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + top, _source = _guarded_git_top(cwd, raw_top) shared_own = top or cwd - host_own = shared_own if git_root else cwd + host_own = (raw_top or cwd) if git_root else cwd + if top is None: + return [(shared_own, host_own)] main_root = _main_worktree_root(top, git_dir, common) if main_root is None or common is None: return [(shared_own, host_own)] @@ -121,8 +184,10 @@ def workspace_paths(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[s def _git_output(cwd: str, arguments: tuple[str, ...], timeout: float) -> str: """Return what Git prints for ``arguments`` in ``cwd``, or an empty string when it fails or time is up.""" + if timeout <= 0 or not cwd or not os.path.isdir(cwd): + return "" executable = which("git") - if executable is None or timeout <= 0: + if executable is None: return "" try: completed = subprocess.run( # noqa: S603 - git executable and arguments are integration-owned. @@ -130,7 +195,8 @@ def _git_output(cwd: str, arguments: tuple[str, ...], timeout: float) -> str: cwd=cwd, check=True, capture_output=True, - text=True, + encoding="utf-8", + errors="surrogateescape", timeout=timeout, ) except (OSError, subprocess.SubprocessError): diff --git a/src/powercontext_integration_lifecycle/host_profile.py b/src/powercontext_integration_lifecycle/host_profile.py index 6619108a5b..9570421db9 100644 --- a/src/powercontext_integration_lifecycle/host_profile.py +++ b/src/powercontext_integration_lifecycle/host_profile.py @@ -38,4 +38,4 @@ class HostProfile: prompt_id_field: str diagnostics: DiagnosticThrottle bootstrap_state: BootstrapState - legacy_workspace_binding: bool = True + legacy_workspace_binding: bool = False diff --git a/src/powercontext_integration_lifecycle/scope_binding.py b/src/powercontext_integration_lifecycle/scope_binding.py index 530ed4786b..81caab35c8 100644 --- a/src/powercontext_integration_lifecycle/scope_binding.py +++ b/src/powercontext_integration_lifecycle/scope_binding.py @@ -17,15 +17,23 @@ from __future__ import annotations import json +import os from collections.abc import Mapping from dataclasses import dataclass, field +from hashlib import sha256 from http.client import HTTPException +from pathlib import Path from time import monotonic from typing import Any, Protocol from urllib.error import HTTPError from urllib.request import Request -from .git_worktree import SHARED_WORKSPACE_INTEGRATION, workspace_identity, workspace_locations +from .git_worktree import ( + SHARED_WORKSPACE_INTEGRATION, + describe_workspace_root, + workspace_identity, + workspace_locations, +) from .host_profile import HostProfile from .scope_binding_errors import ( ScopeBindingError, @@ -130,7 +138,10 @@ def clear_scope_binding( """Remove the shared workspace binding and, when enabled, this host's legacy workspace binding.""" shared_root, host_path = workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline))[0] - keys = [shared_workspace_key(shared_root)] + keys: list[dict[str, str]] = [] + shared_key = shared_workspace_key(shared_root) + if shared_key is not None: + keys.append(shared_key) if host.legacy_workspace_binding and host_path is not None: keys.append(_workspace_key(host, host_path)) cleared_any = False @@ -159,9 +170,16 @@ def diagnose_scope_binding( ) -> dict[str, Any]: """Resolve the active Scope and identify which candidate binding key matched (for diagnostics, never hooks).""" + resolved_root, root_source = describe_workspace_root(cwd, timeout=_git_timeout(deadline)) if settings.scope_id is not None: scope_id = resolve_scope_id(host, cwd, session_id=session_id, settings=settings, deadline=deadline) - return {"scope_id": scope_id, "source": "explicit", "matched_key": None} + return { + "scope_id": scope_id, + "source": "explicit", + "matched_key": None, + "resolved_root": resolved_root, + "root_source": root_source, + } for key in binding_keys(host, cwd, session_id=session_id, deadline=deadline): try: response = _request_json( @@ -178,7 +196,13 @@ def diagnose_scope_binding( scope_id = response.get("scope_id") if not isinstance(scope_id, str) or not scope_id.strip() or scope_id != scope_id.strip(): raise ScopeBindingError - return {"scope_id": scope_id, "source": "binding", "matched_key": key} + return { + "scope_id": scope_id, + "source": "binding", + "matched_key": key, + "resolved_root": resolved_root, + "root_source": root_source, + } response = _request_json( "/v1/scope-bindings/resolve", {"explicit_scope_id": None, "binding_keys": [], "allow_default": True}, @@ -189,7 +213,13 @@ def diagnose_scope_binding( scope_id = response.get("scope_id") if not isinstance(scope_id, str) or not scope_id.strip() or scope_id != scope_id.strip(): raise ScopeBindingError - return {"scope_id": scope_id, "source": "default", "matched_key": None} + return { + "scope_id": scope_id, + "source": "default", + "matched_key": None, + "resolved_root": resolved_root, + "root_source": root_source, + } def binding_keys( @@ -209,7 +239,9 @@ def binding_keys( if session_id is not None: keys.append(session_binding_key(host, session_id)) for shared_root, host_path in workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline)): - keys.append(shared_workspace_key(shared_root)) + shared_key = shared_workspace_key(shared_root) + if shared_key is not None: + keys.append(shared_key) if host.legacy_workspace_binding and host_path is not None: keys.append(_workspace_key(host, host_path)) return keys @@ -227,15 +259,22 @@ def workspace_binding_key(host: HostProfile, cwd: str, *, deadline: float | None del host shared_root, _host_path = workspace_locations(cwd, git_root=True, timeout=_git_timeout(deadline))[0] - return shared_workspace_key(shared_root) + key = shared_workspace_key(shared_root) + if key is None: + raise ScopeBindingError + return key -def shared_workspace_key(path: str) -> dict[str, str]: - return {"integration": SHARED_WORKSPACE_INTEGRATION, "kind": "workspace", "external_id": workspace_identity(path)} +def shared_workspace_key(path: str) -> dict[str, str] | None: + identity = workspace_identity(path) + if identity is None: + return None + return {"integration": SHARED_WORKSPACE_INTEGRATION, "kind": "workspace", "external_id": identity} def _workspace_key(host: HostProfile, path: str) -> dict[str, str]: - return {"integration": host.integration, "kind": "workspace", "external_id": workspace_identity(path)} + external_id = sha256(os.fsencode(Path(path).expanduser().resolve())).hexdigest() + return {"integration": host.integration, "kind": "workspace", "external_id": external_id} def _request_json( diff --git a/tests/codex_plugin/test_scope_binding.py b/tests/codex_plugin/test_scope_binding.py index 25a6eed6f9..268e7cac28 100644 --- a/tests/codex_plugin/test_scope_binding.py +++ b/tests/codex_plugin/test_scope_binding.py @@ -779,7 +779,13 @@ def request(path, payload, *, host, settings, deadline, method="POST"): report = scope_binding_client.diagnose_scope_binding( scope_module.CODEX, str(tmp_path), session_id=None, settings=settings, deadline=float("inf") ) - assert report == {"scope_id": "scp_legacy", "source": "binding", "matched_key": legacy_key} + assert report == { + "scope_id": "scp_legacy", + "source": "binding", + "matched_key": legacy_key, + "resolved_root": scope_binding_client.describe_workspace_root(str(tmp_path))[0], + "root_source": "directory", + } def test_cli_bind_scope_prints_the_bound_scope_id( diff --git a/tests/e2e/test_shared_workspace_scope_binding.py b/tests/e2e/test_shared_workspace_scope_binding.py index f91747e8f0..aa166b96ed 100644 --- a/tests/e2e/test_shared_workspace_scope_binding.py +++ b/tests/e2e/test_shared_workspace_scope_binding.py @@ -322,6 +322,7 @@ def resolve_all_hosts(cwd: Path) -> dict[str, str]: ).stdout ) assert zcode_doc["checks"]["scope_probe"]["matched_key"] == "shared:workspace" + assert zcode_doc["checks"]["scope_probe"]["root_source"] == "git_root" kimi_doc = json.loads( subprocess.run( @@ -334,13 +335,32 @@ def resolve_all_hosts(cwd: Path) -> dict[str, str]: ).stdout ) assert kimi_doc["checks"]["scope"]["checks"]["matched_key"] == "shared:workspace" + assert kimi_doc["checks"]["scope"]["checks"]["root_source"] == "git_root" # 3. A linked worktree's own shared binding overrides the main checkout across all hosts. assert run_zcode_scope("bind", worktree_subdir, "--scope-id", worktree_scope)["scope_id"] == worktree_scope assert set(resolve_all_hosts(worktree_subdir).values()) == {worktree_scope} assert set(resolve_all_hosts(subdir).values()) == {main_scope} - # 4. Dual-key clear removes both shared:workspace and the invoking host's legacy workspace key. + # Removing the linked worktree directory from disk still lets offline CLI clear --cwd remove its binding. + shutil.rmtree(layout.worktree) + clear_deleted_wt = CliRunner().invoke( + create_cli(), + [ + "--server-url", + base_url, + "--json", + "scope", + "binding", + "clear", + "--cwd", + str(layout.worktree), + ], + ) + assert clear_deleted_wt.exit_code == 0, clear_deleted_wt.output + assert json.loads(clear_deleted_wt.output)["cleared"] is True + + # 4. Scoped clear (--integration claude-code) clears shared + claude-code while preserving Pi's subdir legacy key. clear_claude = CliRunner().invoke( create_cli(), [ @@ -358,13 +378,11 @@ def resolve_all_hosts(cwd: Path) -> dict[str, str]: ) assert clear_claude.exit_code == 0, clear_claude.output assert json.loads(clear_claude.output)["cleared"] is True - - # Claude Code's legacy root binding was cleared alongside shared:workspace, so it falls back to default. assert run_py_script(CLAUDE_SCRIPT, "--cwd", str(subdir)) == default_scope - # Pi's subdir legacy binding was preserved until cleared by Pi / CLI --integration pi. assert _resolve_ts_hosts(node, base_url, subdir)["pi"] == legacy_pi_scope - clear_pi = CliRunner().invoke( + # 5. Default clear --cwd (no --integration) sweeps shared + all 10 legacy host keys at subdir. + clear_all_subdir = CliRunner().invoke( create_cli(), [ "--server-url", @@ -373,14 +391,12 @@ def resolve_all_hosts(cwd: Path) -> dict[str, str]: "scope", "binding", "clear", - "--integration", - "pi", "--cwd", str(subdir), ], ) - assert clear_pi.exit_code == 0, clear_pi.output - assert json.loads(clear_pi.output)["cleared"] is True + assert clear_all_subdir.exit_code == 0, clear_all_subdir.output + assert json.loads(clear_all_subdir.output)["cleared"] is True assert _resolve_ts_hosts(node, base_url, subdir)["pi"] == default_scope finally: server.should_exit = True diff --git a/tests/test_cli_scope.py b/tests/test_cli_scope.py index c9126e475f..81544090bb 100644 --- a/tests/test_cli_scope.py +++ b/tests/test_cli_scope.py @@ -200,6 +200,7 @@ def test_scope_create_sends_wellformed_external_references(monkeypatch: pytest.M def test_scope_resolve_mirrors_the_plugin_binding_keys(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: workspace = tmp_path / "worktree" + workspace.mkdir() client, output = _invoke( monkeypatch, _descriptor("scp_resolved"), @@ -217,7 +218,8 @@ def test_scope_resolve_mirrors_the_plugin_binding_keys(monkeypatch: pytest.Monke assert isinstance(request, ResolveScopeBindingRequest) assert request.allow_default is False assert request.explicit_scope_id is None - shared_id = hashlib.sha256(os.fsencode(workspace.resolve())).hexdigest() + shared_id = client_cli.workspace_identity(str(workspace)) + assert shared_id is not None assert [(key.integration, key.kind, key.external_id) for key in request.binding_keys] == [ ("opencode", "session", "ses_1"), ("shared", "workspace", shared_id), @@ -468,9 +470,10 @@ def test_scope_binding_set_and_clear_with_cwd_manage_shared_and_host_keys( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: layout = make_git_layout(tmp_path, monkeypatch) - checkout_id = hashlib.sha256(os.fsencode(layout.checkout)).hexdigest() + checkout_id = client_cli.workspace_identity(str(layout.checkout)) + assert checkout_id is not None sub_id = hashlib.sha256(os.fsencode(layout.checkout_sub)).hexdigest() - client, _ = _invoke( + client, set_output = _invoke( monkeypatch, ScopeBinding.model_validate({ "key": {"integration": "shared", "kind": "workspace", "external_id": checkout_id}, @@ -485,6 +488,19 @@ def test_scope_binding_set_and_clear_with_cwd_manage_shared_and_host_keys( "workspace", checkout_id, ) + assert "Workspace root:" in set_output + + # Rejects non-shared --integration and non-existent --cwd on set. + bad_host = CliRunner().invoke( + create_cli([]), + ["scope", "binding", "set", "scp_repo", "--cwd", str(layout.checkout_sub), "--integration", "codex"], + ) + assert bad_host.exit_code != 0 + missing_set = CliRunner().invoke( + create_cli([]), + ["scope", "binding", "set", "scp_repo", "--cwd", str(tmp_path / "does-not-exist")], + ) + assert missing_set.exit_code != 0 clear_client, output = _invoke( monkeypatch, @@ -499,6 +515,43 @@ def test_scope_binding_set_and_clear_with_cwd_manage_shared_and_host_keys( ] assert "Binding cleared." in output + # Default clear --cwd without --integration clears shared plus all 10 legacy host integrations. + clear_all_client, _ = _invoke( + monkeypatch, + ClearScopeBindingResponse(cleared=True), + ["scope", "binding", "clear", "--cwd", str(layout.checkout_sub)], + ) + clear_all_calls = [call for call in clear_all_client.calls if isinstance(call, ClearScopeBindingRequest)] + cleared_names = {call.key.integration for call in clear_all_calls} + assert cleared_names == { + "shared", + "bub", + "claude-code", + "codex", + "dsh", + "hermes", + "kimi-code", + "opencode", + "pi", + "workbuddy", + "zcode", + } + + # Deleting a directory still allows offline clear --cwd to derive and clear its shared key. + ephemeral = tmp_path / "ephemeral-worktree" + ephemeral.mkdir() + ephemeral_id = client_cli.workspace_identity(str(ephemeral)) + assert ephemeral_id is not None + ephemeral.rmdir() + deleted_clear_client, deleted_out = _invoke( + monkeypatch, + ClearScopeBindingResponse(cleared=True), + ["scope", "binding", "clear", "--cwd", str(ephemeral), "--integration", "shared"], + ) + deleted_calls = [call for call in deleted_clear_client.calls if isinstance(call, ClearScopeBindingRequest)] + assert [(call.key.integration, call.key.external_id) for call in deleted_calls] == [("shared", ephemeral_id)] + assert "directory missing" in deleted_out + shared_resolve, _ = _invoke( monkeypatch, _descriptor(), @@ -506,8 +559,10 @@ def test_scope_binding_set_and_clear_with_cwd_manage_shared_and_host_keys( ) resolve_req = shared_resolve.calls[0] assert isinstance(resolve_req, ResolveScopeBindingRequest) + worktree_id = client_cli.workspace_identity(str(layout.worktree)) + assert worktree_id is not None assert [(k.integration, k.external_id) for k in resolve_req.binding_keys] == [ - ("shared", hashlib.sha256(os.fsencode(layout.worktree)).hexdigest()), + ("shared", worktree_id), ("shared", checkout_id), ] diff --git a/tests/test_git_worktree.py b/tests/test_git_worktree.py index fe0984b37a..dff3060029 100644 --- a/tests/test_git_worktree.py +++ b/tests/test_git_worktree.py @@ -20,13 +20,17 @@ import os import shutil import subprocess +import sys +import unicodedata from collections.abc import Callable from pathlib import Path import pytest from powercontext_integration_lifecycle.git_worktree import ( + describe_workspace_root, normalize_windows_real_path, + real_workspace_path, workspace_identity, workspace_locations, workspace_paths, @@ -157,46 +161,123 @@ def test_git_without_path_format_keeps_the_top_level_and_adds_nothing( assert helper(layout.worktree_sub, False) == [str(layout.worktree_sub)] -def _javascript_identity(directory: Path) -> str: +def _javascript_identity(directory: Path | str, *, env: dict[str, str] | None = None) -> str | None: node = shutil.which("node") if node is None: pytest.skip("Node.js is not installed") script = ( "const [helper, directory] = process.argv.slice(1);" "const { workspaceIdentity } = await import(helper);" - "console.log(workspaceIdentity(directory));" + "console.log(JSON.stringify(workspaceIdentity(directory) ?? null));" ) completed = subprocess.run( [node, "--input-type=module", "-e", script, JAVASCRIPT_HELPER.as_uri(), str(directory)], + env=env, check=True, capture_output=True, text=True, timeout=30, ) - return completed.stdout.strip() + return json.loads(completed.stdout.strip()) def test_python_and_javascript_derive_the_same_workspace_identity(layout: GitLayout, tmp_path: Path) -> None: - targets = [ + unicode_dir = tmp_path / "中文仓库" / "子目录" + unicode_dir.mkdir(parents=True) + case_dir = tmp_path / "CaseRepo" / "sub" + case_dir.mkdir(parents=True) + nfd_dir = tmp_path / unicodedata.normalize("NFD", "café") + nfd_dir.mkdir(exist_ok=True) + file_path = tmp_path / "plain-file.txt" + file_path.write_text("not a directory", encoding="utf-8") + + targets: list[Path | str] = [ layout.checkout, layout.checkout_sub, layout.worktree, layout.worktree_sub, layout.outside, + str(layout.outside) + os.sep, + unicode_dir, + case_dir, + nfd_dir, + tmp_path / unicodedata.normalize("NFC", "café"), layout.outside / "missing" / "nested", + file_path, ] + if sys.platform in {"darwin", "win32"}: + targets.append(tmp_path / "caserepo" / "SUB") + link = tmp_path / "checkout-link" + sibling = tmp_path / "sibling-dir" + sibling.mkdir() try: link.symlink_to(layout.checkout, target_is_directory=True) - targets.extend([link, link / "sub", link / "missing"]) + targets.extend([link, link / "sub", str(link) + os.sep + "..", link / "missing"]) except OSError: if os.name != "nt": raise + for target in targets: py_id = workspace_identity(str(target)) js_id = _javascript_identity(target) assert py_id == js_id, f"mismatch for {target}: {py_id} != {js_id}" + assert workspace_identity(str(layout.outside / "missing" / "nested")) is None + assert workspace_identity(str(file_path)) is None + if sys.platform in {"darwin", "win32"} and (tmp_path / "caserepo" / "SUB").is_dir(): + assert workspace_identity(str(tmp_path / "caserepo" / "SUB")) == workspace_identity(str(case_dir)) + if sys.platform == "darwin": + assert workspace_identity(str(tmp_path / unicodedata.normalize("NFC", "café"))) == workspace_identity( + str(nfd_dir) + ) + + +def test_home_directory_git_repository_does_not_collapse_subdirectories( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + git = shutil.which("git") + assert git is not None + fake_home = tmp_path / "fakehome" + unrelated = fake_home / "projects" / "notes" + unrelated.mkdir(parents=True) + subprocess.run([git, "init", "-q", str(fake_home)], check=True, timeout=10) + + monkeypatch.setenv("HOME", str(fake_home)) + monkeypatch.setenv("USERPROFILE", str(fake_home)) + + # Subdirectories under a git-initialized $HOME fall back to the directory itself for shared identity. + py_locations = workspace_locations(str(unrelated), git_root=False) + assert py_locations == [(str(unrelated), str(unrelated))] + resolved_root, source = describe_workspace_root(str(unrelated)) + assert resolved_root == real_workspace_path(str(unrelated)) + assert source == "home_guard" + + # Opening $HOME itself still resolves $HOME. + home_root, home_source = describe_workspace_root(str(fake_home)) + assert home_root == real_workspace_path(str(fake_home)) + assert home_source == "git_root" + + node = shutil.which("node") + if node is not None: + env = {**os.environ, "HOME": str(fake_home), "USERPROFILE": str(fake_home)} + script = ( + "const [helper, dir] = process.argv.slice(1);" + "const m = await import(helper);" + "console.log(JSON.stringify({ locs: m.workspaceLocationsSync(dir, false, 2000)," + " desc: m.describeWorkspaceRootSync(dir, 2000) }));" + ) + out = json.loads( + subprocess.check_output( + [node, "--input-type=module", "-e", script, JAVASCRIPT_HELPER.as_uri(), str(unrelated)], + env=env, + text=True, + timeout=15, + ) + ) + assert out["locs"] == [[str(unrelated), str(unrelated)]] + assert out["desc"] == [resolved_root, "home_guard"] + def test_python_and_javascript_normalize_windows_drive_and_extended_prefixes() -> None: node = shutil.which("node") From c3435eb5d0435615c89955c623693edb2fbfb361 Mon Sep 17 00:00:00 2001 From: wycocoyu <180249289+wycocoyu@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:19:41 -0800 Subject: [PATCH 6/7] fix(integrations): refine routing cache, home resolution, and RFC boundaries --- .../2988-shared-workspace-scope-bindings.md | 6 +- .../2988-shared-workspace-scope-bindings.md | 6 +- .../bub/src/powercontext_bub/scope.py | 9 --- .../dsh/plugins/powercontext/lib/index.js | 33 ++++++----- .../plugins/powercontext/src/git-worktree.ts | 4 +- .../dsh/plugins/powercontext/src/scope.ts | 33 +++++++---- .../plugins/powercontext/tests/scope.spec.ts | 25 +++++++- .../plugins/powercontext/scripts/scope.mjs | 8 ++- .../powercontext/shared/git-worktree.mjs | 4 +- .../powercontext/tests/plugin.test.mjs | 14 +++++ integrations/lifecycle/git-worktree.ts | 4 +- .../plugins/powercontext/lib/index.js | 4 +- .../opencode/plugins/powercontext/lib/tui.js | 4 +- .../plugins/powercontext/src/git-worktree.ts | 4 +- .../plugins/powercontext/src/scope.ts | 16 ----- .../plugins/powercontext/src/git-worktree.ts | 4 +- .../pi/plugins/powercontext/src/scope.ts | 16 ----- .../plugins/powercontext/scripts/scope.mjs | 4 +- .../powercontext/shared/git-worktree.mjs | 4 +- .../plugins/powercontext/tests/scope.test.mjs | 33 +++++++++++ src/powercontext/client/cli.py | 58 +++++-------------- src/powercontext/client/session_import.py | 45 +++++++------- .../test_shared_workspace_scope_binding.py | 47 ++++++++++++++- tests/test_cli_scope.py | 9 +++ tests/test_git_worktree.py | 22 ++++++- 25 files changed, 252 insertions(+), 164 deletions(-) diff --git a/docs/en/rfcs/2988-shared-workspace-scope-bindings.md b/docs/en/rfcs/2988-shared-workspace-scope-bindings.md index ddb442fa3b..2579835cca 100644 --- a/docs/en/rfcs/2988-shared-workspace-scope-bindings.md +++ b/docs/en/rfcs/2988-shared-workspace-scope-bindings.md @@ -68,7 +68,7 @@ If `root` does not exist on disk as a directory or its canonical path cannot be - Subdirectories of a checkout share the checkout's `root`. Outside Git, each directory is its own workspace. Git submodules report their own worktree top level and remain independent workspaces. - Guarding `$HOME`, ancestors of `$HOME`, and filesystem roots prevents a dotfiles repository initialized in `$HOME` (or a stray `.git` at `/`) from collapsing unrelated subdirectories onto one workspace identity. -- Legacy per-host `:workspace` derivations are frozen byte-for-byte to each host's pre-RFC implementation (`HostProfile.legacy_workspace_binding` defaults to `False` and is enabled only on pre-existing hosts). +- Legacy per-host `:workspace` derivations are frozen byte-for-byte to each host's pre-RFC implementation (`HostProfile.legacy_workspace_binding` defaults to `False` and is enabled only on pre-existing hosts). One intentional exception applies on non-UTF-8 Windows code pages (such as `cp936`): Python's Git helper now decodes `git rev-parse` output explicitly as UTF-8 instead of the system ANSI code page so non-ASCII Git paths no longer corrupt or raise `UnicodeDecodeError`; a pre-RFC binding created from a mojibake path on such a checkout requires rebinding once. - The shared lifecycle helpers (`src/powercontext_integration_lifecycle/git_worktree.py` and `integrations/lifecycle/git-worktree.ts`) compute both the shared checkout roots and the host's legacy paths from the single Git invocation introduced in [PR #2875](https://github.com/oceanbase/powercontext/pull/2875), starting no extra Git subprocesses ( Python 3.9+ standard library compatible). ## 2. Reserved `shared` namespace @@ -126,7 +126,9 @@ Codex and OpenCode persist the Scope resolved at session start to `(host, "sessi - **Identical container or devcontainer paths across machines**: Workspace identity hashes the canonical local checkout path without a machine identifier. Two machines or devcontainers mounting a repository at the exact same path (such as `/workspaces/app`) and sharing one PowerContext Server share that binding; separate paths on different machines remain distinct checkouts. - **Git unavailable, timed out, or refused (`safe.directory`)**: When Git cannot report a top level within the helper budget, `root` falls back to `dir` (`root_source = "directory"` in diagnostics) rather than failing closed. - **Legacy subdirectory bindings on cwd-keyed hosts**: `powercontext scope binding clear --cwd ` derives legacy keys for `` and its Git top level; a pre-RFC binding created from an arbitrary nested subdirectory in a cwd-keyed host (`dsh`, `opencode`, `pi`, `kimi-code`, `hermes`, `bub`) must be cleared with `--cwd` pointing at that subdirectory if no shared binding shadows it. -- **Native Windows runner verification**: Python `ntpath.realpath` and Node `fs.realpathSync.native` both delegate to `GetFinalPathNameByHandleW`; cross-runtime path-vector parity is exercised in CI on `windows-latest`. +- **Removed subdirectories inside a live checkout**: When `` itself no longer exists on disk, offline `clear --cwd ` and `import-sessions` derive the canonical path from ``'s deepest existing ancestor without walking into a surrounding Git top level (which would risk clearing a live main checkout's binding when removing a nested worktree such as `/.worktrees/wt`). To clear a live checkout's shared binding, pass the checkout root or any existing directory inside it. +- **Windows long-path policy (`LongPathsEnabled=0`)**: On Windows systems with `LongPathsEnabled=0` (the OS default), Python's standard Win32 directory checks fail on workspace root paths of `MAX_PATH` (~260 characters) or longer when passed without an extended `\\?\` prefix, causing Python hosts and CLI `--cwd` to omit the `shared` key while Node.js (`libuv`) still resolves it. Checkouts whose root path stays under `MAX_PATH` are unaffected. +- **Platform verification coverage**: On Windows, Python `ntpath.realpath` and Node `fs.realpathSync.native` both delegate to `GetFinalPathNameByHandleW`; cross-runtime path, junction, and home-guard parity is exercised in CI on Linux and `windows-latest`. macOS `fcntl.F_GETPATH` APFS case and NFD/NFC parity is verified on macOS development hosts (CI does not run a dedicated macOS Python test job). # Future possibilities diff --git a/docs/zh/rfcs/2988-shared-workspace-scope-bindings.md b/docs/zh/rfcs/2988-shared-workspace-scope-bindings.md index 4027bea6e0..9b4bbdc9f0 100644 --- a/docs/zh/rfcs/2988-shared-workspace-scope-bindings.md +++ b/docs/zh/rfcs/2988-shared-workspace-scope-bindings.md @@ -66,7 +66,7 @@ id = 严格 UTF-8(path) 字节序列的小写十六进制 SHA-256 - 同一检出目录内的所有子目录共享同一个 `root`。在 Git 工作树之外,每个目录各自构成独立工作区。Git submodule 上报其自身工作树顶层,作为独立工作区处理。 - 家目录、家目录祖先及文件系统根目录守卫可防止用户在家目录执行 `git init`(如管理 dotfiles)或根目录存在残留 `.git` 时,将家目录下所有无关非仓库目录折叠为同一工作区。 -- 存量宿主的旧 `:workspace` 派生逻辑按本 RFC 之前的实现逐字节冻结(`HostProfile.legacy_workspace_binding` 默认设为 `False`,仅在既有宿主中显式开启)。 +- 存量宿主的旧 `:workspace` 派生逻辑按本 RFC 之前的实现逐字节冻结(`HostProfile.legacy_workspace_binding` 默认设为 `False`,仅在既有宿主中显式开启)。唯一有意例外位于非 UTF-8 代码页(如 `cp936`)的 Windows 环境:Python 的 Git 辅助函数现显式按 UTF-8 解码 `git rev-parse` 输出而不再使用系统 ANSI 代码页,避免非 ASCII Git 路径乱码或抛出 `UnicodeDecodeError`;此前在这类路径上由乱码字符串生成的旧绑定重新绑定一次即可。 - 共享生命周期辅助模块(`src/powercontext_integration_lifecycle/git_worktree.py` 与 `integrations/lifecycle/git-worktree.ts`)复用 [PR #2875](https://github.com/oceanbase/powercontext/pull/2875) 的单次 Git 调用同时派生共享检出根路径与宿主旧兼容路径,不额外启动 Git 子进程,并兼容 Python 3.9+ 标准库。 ## 2. 保留命名空间 `shared` @@ -124,7 +124,9 @@ Codex 与 OpenCode 在未配置显式 Scope 时会将新会话首次解析出的 - **多机或容器相同挂载路径边界**:工作区身份仅哈希本地检出目录规范路径,不引入机器 ID。当多台机器或多个 devcontainer 在完全相同的路径(例如 `/workspaces/app`)挂载仓库并连接同一个 PowerContext Server 时,它们会共享该路径对应的工作区绑定;不同路径仍保持独立。 - **Git 未安装、超时或 `safe.directory` 拒绝**:当 Git 在超时预算内无法返回顶层目录时,`root` 安全回退为 `dir`(诊断中 `root_source = "directory"`),不会阻断会话请求。 - **按 `cwd` 派生宿主的子目录遗留绑定**:`powercontext scope binding clear --cwd ` 会清除 `` 及其 Git 顶层对应的旧键;若升级前曾在 `dsh`、`opencode`、`pi`、`kimi-code`、`hermes` 或 `bub` 的某个深层子目录单独创建过旧绑定且当前不存在遮蔽它的共享绑定,则需对该子目录传入 `--cwd` 予以清除。 -- **Windows 原生环境校验**:Python `ntpath.realpath` 与 Node `fs.realpathSync.native` 底层均调用 `GetFinalPathNameByHandleW`,跨运行时路径向量一致性在 CI 的 `windows-latest` 任务中持续验证。 +- **存活检出内已删除子目录的离线推导**:当 `` 本身已不存在时,离线 `clear --cwd ` 与 `import-sessions` 按最深已存在祖先拼接原相对尾部推导,不会继续向上探测外层 Git 顶层(否则当已删除的嵌套工作树位于 `/.worktrees/wt` 时会误删主检出目录的共享绑定)。如需清除存活检出目录的共享绑定,请对检出根目录或其中任一存活子目录执行 `clear --cwd`。 +- **Windows 长路径策略(`LongPathsEnabled=0`)**:在未开启长路径支持(Windows 默认 `LongPathsEnabled=0`)的系统上,当工作区根路径本身达到或超过 `MAX_PATH`(约 260 字符)且未携带 `\\?\` 前缀时,Python 标准库目录检查会失败并省略 `shared` 键,而 Node.js(`libuv`)仍能解析;根路径短于 `MAX_PATH` 的常规检出不受影响。 +- **跨平台验证覆盖范围**:在 Windows 上,Python `ntpath.realpath` 与 Node `fs.realpathSync.native` 底层均调用 `GetFinalPathNameByHandleW`,跨运行时路径、目录联接(junction)与家目录守卫一致性在 CI 的 Linux 与 `windows-latest` 任务中持续验证;macOS `fcntl.F_GETPATH` 的 APFS 大小写与 NFD/NFC 一致性已在 macOS 本机验证(CI 未单独配置 macOS Python 测试任务)。 # Future possibilities diff --git a/integrations/bub/src/powercontext_bub/scope.py b/integrations/bub/src/powercontext_bub/scope.py index f41101b712..5a107bd022 100644 --- a/integrations/bub/src/powercontext_bub/scope.py +++ b/integrations/bub/src/powercontext_bub/scope.py @@ -33,15 +33,6 @@ def workspace_binding_key(workspace: str | Path | None) -> ScopeBindingKey | Non return _legacy_workspace_key(workspace) -def shared_workspace_binding_key(workspace: str | Path | None) -> ScopeBindingKey | None: - """Return the cross-host shared binding key for the checkout containing ``workspace``.""" - - if workspace is None: - return None - shared_root, _host_path = workspace_locations(str(Path(workspace).expanduser()), git_root=False)[0] - return _shared_workspace_key(shared_root) - - def workspace_binding_keys(workspace: str | Path | None) -> list[ScopeBindingKey]: """Return the workspace keys that resolution tries in order. diff --git a/integrations/dsh/plugins/powercontext/lib/index.js b/integrations/dsh/plugins/powercontext/lib/index.js index 7f007d0d0e..f5ed5aaba8 100644 --- a/integrations/dsh/plugins/powercontext/lib/index.js +++ b/integrations/dsh/plugins/powercontext/lib/index.js @@ -2659,7 +2659,7 @@ function realWorkspacePath(directory) { if (!directory) return void 0; let expanded = directory; if (expanded === "~" || expanded.startsWith("~/") || expanded.startsWith("~\\")) { - const home = process.env.HOME || process.env.USERPROFILE || homedir(); + const home = homedir(); expanded = expanded === "~" ? home : join(home, expanded.slice(2)); } const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded; @@ -2685,7 +2685,7 @@ function guardedGitTop(directory, top) { const dirReal = realWorkspacePath(directory); if (dirReal !== void 0 && dirReal === topReal) return [top, "git_root"]; if (dirname(topReal) === topReal) return ["", "home_guard"]; - const homeReal = realWorkspacePath(process.env.HOME || process.env.USERPROFILE || homedir()); + const homeReal = realWorkspacePath(homedir()); if (homeReal !== void 0) { let current = homeReal; while (true) { @@ -2833,19 +2833,27 @@ function realPath(path) { //#region src/scope.ts const UNSCOPED_MESSAGE = "PowerContext could not resolve the current Scope."; const GIT_TIMEOUT_MS = 500; +const SHARED_KEY_CACHE_LIMIT = 256; +const sharedKeys = /* @__PURE__ */ new Map(); function sessionCwd(cwd) { const value = cwd?.trim(); return value ? value : void 0; } function sharedWorkspaceBindingKey(cwd) { - const [sharedRoot = cwd] = workspaceLocationsSync(cwd, false, GIT_TIMEOUT_MS)[0] ?? [cwd]; - const externalId = workspaceIdentity(sharedRoot); - if (externalId === void 0) return void 0; - return { - integration: SHARED_WORKSPACE_INTEGRATION, - kind: "workspace", - external_id: externalId - }; + if (!sharedKeys.has(cwd)) { + if (sharedKeys.size >= SHARED_KEY_CACHE_LIMIT) { + const oldest = sharedKeys.keys().next().value; + if (oldest !== void 0) sharedKeys.delete(oldest); + } + const [sharedRoot = cwd] = workspaceLocationsSync(cwd, false, GIT_TIMEOUT_MS)[0] ?? [cwd]; + const externalId = workspaceIdentity(sharedRoot); + sharedKeys.set(cwd, externalId === void 0 ? void 0 : { + integration: SHARED_WORKSPACE_INTEGRATION, + kind: "workspace", + external_id: externalId + }); + } + return sharedKeys.get(cwd); } function legacyWorkspaceBindingKey(cwd) { return { @@ -2854,9 +2862,6 @@ function legacyWorkspaceBindingKey(cwd) { external_id: createHash("sha256").update(resolve(cwd)).digest("hex") }; } -function workspaceBindingKey(cwd) { - return sharedWorkspaceBindingKey(cwd); -} /** Return the workspace keys that resolution tries in order, shared before legacy at both checkout levels. */ async function workspaceBindingKeys(cwd) { const keys = []; @@ -2873,7 +2878,7 @@ async function workspaceBindingKeys(cwd) { } function formatScopeRouting(scopeId, cwd) { const workspace = sessionCwd(cwd); - const bindingKey = workspace ? workspaceBindingKey(workspace) : void 0; + const bindingKey = workspace ? sharedWorkspaceBindingKey(workspace) : void 0; return [ "PowerContext host Scope routing is authoritative for this DSH session.", `Use exactly this scope_id for every mcp__powercontext__ operation that accepts one: ${JSON.stringify(scopeId)}.`, diff --git a/integrations/dsh/plugins/powercontext/src/git-worktree.ts b/integrations/dsh/plugins/powercontext/src/git-worktree.ts index fb5d5f12e4..cbab6ff2e1 100644 --- a/integrations/dsh/plugins/powercontext/src/git-worktree.ts +++ b/integrations/dsh/plugins/powercontext/src/git-worktree.ts @@ -75,7 +75,7 @@ export function realWorkspacePath(directory: string): string | undefined { if (!directory) return undefined let expanded = directory if (expanded === '~' || expanded.startsWith('~/') || expanded.startsWith('~\\')) { - const home = process.env.HOME || process.env.USERPROFILE || homedir() + const home = homedir() expanded = expanded === '~' ? home : join(home, expanded.slice(2)) } const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded @@ -103,7 +103,7 @@ function guardedGitTop(directory: string, top: string): string[] { const dirReal = realWorkspacePath(directory) if (dirReal !== undefined && dirReal === topReal) return [top, 'git_root'] if (dirname(topReal) === topReal) return ['', 'home_guard'] - const homeReal = realWorkspacePath(process.env.HOME || process.env.USERPROFILE || homedir()) + const homeReal = realWorkspacePath(homedir()) if (homeReal !== undefined) { let current = homeReal while (true) { diff --git a/integrations/dsh/plugins/powercontext/src/scope.ts b/integrations/dsh/plugins/powercontext/src/scope.ts index ca85ca3697..a812169c2f 100644 --- a/integrations/dsh/plugins/powercontext/src/scope.ts +++ b/integrations/dsh/plugins/powercontext/src/scope.ts @@ -26,6 +26,8 @@ import { export const UNSCOPED_MESSAGE = 'PowerContext could not resolve the current Scope.' const GIT_TIMEOUT_MS = 500 +const SHARED_KEY_CACHE_LIMIT = 256 +const sharedKeys = new Map() export type ScopeBindingKey = { integration: string; kind: string; external_id: string } @@ -35,14 +37,25 @@ export function sessionCwd(cwd: string | undefined): string | undefined { } export function sharedWorkspaceBindingKey(cwd: string): ScopeBindingKey | undefined { - const [sharedRoot = cwd] = workspaceLocationsSync(cwd, false, GIT_TIMEOUT_MS)[0] ?? [cwd] - const externalId = workspaceIdentity(sharedRoot) - if (externalId === undefined) return undefined - return { - integration: SHARED_WORKSPACE_INTEGRATION, - kind: 'workspace', - external_id: externalId, + if (!sharedKeys.has(cwd)) { + if (sharedKeys.size >= SHARED_KEY_CACHE_LIMIT) { + const oldest = sharedKeys.keys().next().value + if (oldest !== undefined) sharedKeys.delete(oldest) + } + const [sharedRoot = cwd] = workspaceLocationsSync(cwd, false, GIT_TIMEOUT_MS)[0] ?? [cwd] + const externalId = workspaceIdentity(sharedRoot) + sharedKeys.set( + cwd, + externalId === undefined + ? undefined + : { + integration: SHARED_WORKSPACE_INTEGRATION, + kind: 'workspace', + external_id: externalId, + }, + ) } + return sharedKeys.get(cwd) } export function legacyWorkspaceBindingKey(cwd: string): ScopeBindingKey { @@ -53,10 +66,6 @@ export function legacyWorkspaceBindingKey(cwd: string): ScopeBindingKey { } } -export function workspaceBindingKey(cwd: string): ScopeBindingKey | undefined { - return sharedWorkspaceBindingKey(cwd) -} - /** Return the workspace keys that resolution tries in order, shared before legacy at both checkout levels. */ export async function workspaceBindingKeys(cwd: string): Promise { const keys: ScopeBindingKey[] = [] @@ -76,7 +85,7 @@ export async function workspaceBindingKeys(cwd: string): Promise { } }) - it('sends only its own key from a checkout whose Git directory is separate', async () => { + it('sends only its own key from a checkout whose Git directory is separate', async () => { const root = realpathSync(mkdtempSync(join(tmpdir(), 'pc-separate-'))) try { const checkout = join(root, 'checkout') @@ -136,4 +136,27 @@ describe('Scope binding', () => { rmSync(root, { recursive: true, force: true }) } }) + + it('caches the shared workspace key across repeated routing formatting for the same cwd', () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), 'pc-dsh-git-cache-'))) + try { + const checkout = join(root, 'checkout') + const cachedSub = join(checkout, 'cached-sub') + const uncachedSub = join(checkout, 'uncached-sub') + execFileSync('git', ['init', '-q', checkout], { stdio: 'ignore' }) + mkdirSync(cachedSub) + mkdirSync(uncachedSub) + + const first = formatScopeRouting('scope-a', cachedSub) + expect(first).toContain(pathHash(checkout)) + + rmSync(join(checkout, '.git'), { recursive: true, force: true }) + const second = formatScopeRouting('scope-b', cachedSub) + const freshAfterRemoval = formatScopeRouting('scope-b', uncachedSub) + expect(second).toContain(pathHash(checkout)) + expect(freshAfterRemoval).toContain(pathHash(uncachedSub)) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) }) diff --git a/integrations/kimi-code/plugins/powercontext/scripts/scope.mjs b/integrations/kimi-code/plugins/powercontext/scripts/scope.mjs index 208cec48c6..d9b6e17d24 100644 --- a/integrations/kimi-code/plugins/powercontext/scripts/scope.mjs +++ b/integrations/kimi-code/plugins/powercontext/scripts/scope.mjs @@ -41,6 +41,7 @@ try { ] binding = { action, status: 'unknown' } let clearedAny = false + let completed = 0 for (const currentKey of keys) { let response try { @@ -48,8 +49,10 @@ try { action === 'bind' ? '/v1/scope-bindings' : '/v1/scope-bindings/clear', { key: currentKey, ...(action === 'bind' ? { scope_id: target } : {}) }, signal) } catch (error) { - if (error.httpStatus >= 400 && error.httpStatus < 500) binding.status = 'rejected' - else if (error instanceof Failure && !error.requestSent) binding.status = 'not_sent' + if (completed === 0) { + if (error.httpStatus >= 400 && error.httpStatus < 500) binding.status = 'rejected' + else if (error instanceof Failure && !error.requestSent) binding.status = 'not_sent' + } throw error } const { status, value } = response @@ -57,6 +60,7 @@ try { Object.entries(currentKey).some(([name, expected]) => value.key[name] !== expected) : typeof value.cleared !== 'boolean')) throw new Failure('binding_not_confirmed') if (action !== 'bind') clearedAny = clearedAny || value.cleared + completed += 1 } binding = action === 'bind' ? { action, status: 'saved', scope_id: target } : { action, status: clearedAny ? 'cleared' : 'absent', cleared: clearedAny } diff --git a/integrations/kimi-code/plugins/powercontext/shared/git-worktree.mjs b/integrations/kimi-code/plugins/powercontext/shared/git-worktree.mjs index 0a029f5261..ea079ae47a 100644 --- a/integrations/kimi-code/plugins/powercontext/shared/git-worktree.mjs +++ b/integrations/kimi-code/plugins/powercontext/shared/git-worktree.mjs @@ -75,7 +75,7 @@ export function realWorkspacePath(directory) { if (!directory) return undefined let expanded = directory if (expanded === '~' || expanded.startsWith('~/') || expanded.startsWith('~\\')) { - const home = process.env.HOME || process.env.USERPROFILE || homedir() + const home = homedir() expanded = expanded === '~' ? home : join(home, expanded.slice(2)) } const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded @@ -103,7 +103,7 @@ function guardedGitTop(directory, top) { const dirReal = realWorkspacePath(directory) if (dirReal !== undefined && dirReal === topReal) return [top, 'git_root'] if (dirname(topReal) === topReal) return ['', 'home_guard'] - const homeReal = realWorkspacePath(process.env.HOME || process.env.USERPROFILE || homedir()) + const homeReal = realWorkspacePath(homedir()) if (homeReal !== undefined) { let current = homeReal while (true) { diff --git a/integrations/kimi-code/plugins/powercontext/tests/plugin.test.mjs b/integrations/kimi-code/plugins/powercontext/tests/plugin.test.mjs index a5a6eee849..878e885372 100644 --- a/integrations/kimi-code/plugins/powercontext/tests/plugin.test.mjs +++ b/integrations/kimi-code/plugins/powercontext/tests/plugin.test.mjs @@ -665,3 +665,17 @@ test('an unconfirmed binding write stays unknown without retry and invalid works assert.equal(result.status, 'failed') assert.equal(f.requests.filter(item => item.path === '/v1/scope-bindings').length, 1) }) + +test('a partial unbind failure after clearing shared keeps binding status unknown instead of rejected', async t => { + let clears = 0 + const f = await fixture(t, { + '/v1/scope-bindings/clear': (_req, res) => { + clears += 1 + if (clears === 1) { res.writeHead(200); res.end('{"cleared":true}'); return } + res.writeHead(429); res.end('{"error":{"code":"rate_limited"}}') + }, + }, { scope_id: null }) + const result = await f.scope('unbind') + assert.equal(result.status, 'failed') + assert.equal(result.binding.status, 'unknown') +}) diff --git a/integrations/lifecycle/git-worktree.ts b/integrations/lifecycle/git-worktree.ts index bddfac1f5c..73f9d73d33 100644 --- a/integrations/lifecycle/git-worktree.ts +++ b/integrations/lifecycle/git-worktree.ts @@ -72,7 +72,7 @@ export function realWorkspacePath(directory: string): string | undefined { if (!directory) return undefined let expanded = directory if (expanded === '~' || expanded.startsWith('~/') || expanded.startsWith('~\\')) { - const home = process.env.HOME || process.env.USERPROFILE || homedir() + const home = homedir() expanded = expanded === '~' ? home : join(home, expanded.slice(2)) } const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded @@ -100,7 +100,7 @@ function guardedGitTop(directory: string, top: string): string[] { const dirReal = realWorkspacePath(directory) if (dirReal !== undefined && dirReal === topReal) return [top, 'git_root'] if (dirname(topReal) === topReal) return ['', 'home_guard'] - const homeReal = realWorkspacePath(process.env.HOME || process.env.USERPROFILE || homedir()) + const homeReal = realWorkspacePath(homedir()) if (homeReal !== undefined) { let current = homeReal while (true) { diff --git a/integrations/opencode/plugins/powercontext/lib/index.js b/integrations/opencode/plugins/powercontext/lib/index.js index 132c3fb2ca..aec3151d00 100644 --- a/integrations/opencode/plugins/powercontext/lib/index.js +++ b/integrations/opencode/plugins/powercontext/lib/index.js @@ -2533,7 +2533,7 @@ function realWorkspacePath(directory) { if (!directory) return void 0; let expanded = directory; if (expanded === "~" || expanded.startsWith("~/") || expanded.startsWith("~\\")) { - const home = process.env.HOME || process.env.USERPROFILE || homedir(); + const home = homedir(); expanded = expanded === "~" ? home : join(home, expanded.slice(2)); } const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded; @@ -2559,7 +2559,7 @@ function guardedGitTop(directory, top) { const dirReal = realWorkspacePath(directory); if (dirReal !== void 0 && dirReal === topReal) return [top, "git_root"]; if (dirname(topReal) === topReal) return ["", "home_guard"]; - const homeReal = realWorkspacePath(process.env.HOME || process.env.USERPROFILE || homedir()); + const homeReal = realWorkspacePath(homedir()); if (homeReal !== void 0) { let current = homeReal; while (true) { diff --git a/integrations/opencode/plugins/powercontext/lib/tui.js b/integrations/opencode/plugins/powercontext/lib/tui.js index 840621c525..363c29ed17 100644 --- a/integrations/opencode/plugins/powercontext/lib/tui.js +++ b/integrations/opencode/plugins/powercontext/lib/tui.js @@ -2619,7 +2619,7 @@ function realWorkspacePath(directory) { if (!directory) return void 0; let expanded = directory; if (expanded === "~" || expanded.startsWith("~/") || expanded.startsWith("~\\")) { - const home = process.env.HOME || process.env.USERPROFILE || homedir(); + const home = homedir(); expanded = expanded === "~" ? home : join(home, expanded.slice(2)); } const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded; @@ -2645,7 +2645,7 @@ function guardedGitTop(directory, top) { const dirReal = realWorkspacePath(directory); if (dirReal !== void 0 && dirReal === topReal) return [top, "git_root"]; if (dirname(topReal) === topReal) return ["", "home_guard"]; - const homeReal = realWorkspacePath(process.env.HOME || process.env.USERPROFILE || homedir()); + const homeReal = realWorkspacePath(homedir()); if (homeReal !== void 0) { let current = homeReal; while (true) { diff --git a/integrations/opencode/plugins/powercontext/src/git-worktree.ts b/integrations/opencode/plugins/powercontext/src/git-worktree.ts index fb5d5f12e4..cbab6ff2e1 100644 --- a/integrations/opencode/plugins/powercontext/src/git-worktree.ts +++ b/integrations/opencode/plugins/powercontext/src/git-worktree.ts @@ -75,7 +75,7 @@ export function realWorkspacePath(directory: string): string | undefined { if (!directory) return undefined let expanded = directory if (expanded === '~' || expanded.startsWith('~/') || expanded.startsWith('~\\')) { - const home = process.env.HOME || process.env.USERPROFILE || homedir() + const home = homedir() expanded = expanded === '~' ? home : join(home, expanded.slice(2)) } const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded @@ -103,7 +103,7 @@ function guardedGitTop(directory: string, top: string): string[] { const dirReal = realWorkspacePath(directory) if (dirReal !== undefined && dirReal === topReal) return [top, 'git_root'] if (dirname(topReal) === topReal) return ['', 'home_guard'] - const homeReal = realWorkspacePath(process.env.HOME || process.env.USERPROFILE || homedir()) + const homeReal = realWorkspacePath(homedir()) if (homeReal !== undefined) { let current = homeReal while (true) { diff --git a/integrations/opencode/plugins/powercontext/src/scope.ts b/integrations/opencode/plugins/powercontext/src/scope.ts index ec4824bc8f..5fdbfff0ff 100644 --- a/integrations/opencode/plugins/powercontext/src/scope.ts +++ b/integrations/opencode/plugins/powercontext/src/scope.ts @@ -21,7 +21,6 @@ import { SHARED_WORKSPACE_INTEGRATION, workspaceIdentity, workspaceLocations, - workspaceLocationsSync, } from './git-worktree.ts' type ScopeBindingKey = { integration: string; kind: string; external_id: string } @@ -32,17 +31,6 @@ export function sessionBindingKey(sessionID: string): ScopeBindingKey { return { integration: 'opencode', kind: 'session', external_id: sessionID } } -export function sharedWorkspaceBindingKey(cwd: string): ScopeBindingKey | undefined { - const [sharedRoot = cwd] = workspaceLocationsSync(cwd, false, GIT_TIMEOUT_MS)[0] ?? [cwd] - const externalId = workspaceIdentity(sharedRoot) - if (externalId === undefined) return undefined - return { - integration: SHARED_WORKSPACE_INTEGRATION, - kind: 'workspace', - external_id: externalId, - } -} - export function legacyWorkspaceBindingKey(cwd: string): ScopeBindingKey { return { integration: 'opencode', @@ -51,10 +39,6 @@ export function legacyWorkspaceBindingKey(cwd: string): ScopeBindingKey { } } -export function workspaceBindingKey(cwd: string): ScopeBindingKey | undefined { - return sharedWorkspaceBindingKey(cwd) -} - /** Return the workspace keys that resolution tries in order, shared before legacy at both checkout levels. */ export async function workspaceBindingKeys(cwd: string): Promise { const keys: ScopeBindingKey[] = [] diff --git a/integrations/pi/plugins/powercontext/src/git-worktree.ts b/integrations/pi/plugins/powercontext/src/git-worktree.ts index fb5d5f12e4..cbab6ff2e1 100644 --- a/integrations/pi/plugins/powercontext/src/git-worktree.ts +++ b/integrations/pi/plugins/powercontext/src/git-worktree.ts @@ -75,7 +75,7 @@ export function realWorkspacePath(directory: string): string | undefined { if (!directory) return undefined let expanded = directory if (expanded === '~' || expanded.startsWith('~/') || expanded.startsWith('~\\')) { - const home = process.env.HOME || process.env.USERPROFILE || homedir() + const home = homedir() expanded = expanded === '~' ? home : join(home, expanded.slice(2)) } const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded @@ -103,7 +103,7 @@ function guardedGitTop(directory: string, top: string): string[] { const dirReal = realWorkspacePath(directory) if (dirReal !== undefined && dirReal === topReal) return [top, 'git_root'] if (dirname(topReal) === topReal) return ['', 'home_guard'] - const homeReal = realWorkspacePath(process.env.HOME || process.env.USERPROFILE || homedir()) + const homeReal = realWorkspacePath(homedir()) if (homeReal !== undefined) { let current = homeReal while (true) { diff --git a/integrations/pi/plugins/powercontext/src/scope.ts b/integrations/pi/plugins/powercontext/src/scope.ts index 57aa1cf954..08bdce3fef 100644 --- a/integrations/pi/plugins/powercontext/src/scope.ts +++ b/integrations/pi/plugins/powercontext/src/scope.ts @@ -21,24 +21,12 @@ import { SHARED_WORKSPACE_INTEGRATION, workspaceIdentity, workspaceLocations, - workspaceLocationsSync, } from './git-worktree.ts' type ScopeBindingKey = { integration: string; kind: string; external_id: string } const GIT_TIMEOUT_MS = 500 -export function sharedWorkspaceBindingKey(cwd: string): ScopeBindingKey | undefined { - const [sharedRoot = cwd] = workspaceLocationsSync(cwd, false, GIT_TIMEOUT_MS)[0] ?? [cwd] - const externalId = workspaceIdentity(sharedRoot) - if (externalId === undefined) return undefined - return { - integration: SHARED_WORKSPACE_INTEGRATION, - kind: 'workspace', - external_id: externalId, - } -} - export function legacyWorkspaceBindingKey(cwd: string): ScopeBindingKey { return { integration: 'pi', @@ -47,10 +35,6 @@ export function legacyWorkspaceBindingKey(cwd: string): ScopeBindingKey { } } -export function workspaceBindingKey(cwd: string): ScopeBindingKey | undefined { - return sharedWorkspaceBindingKey(cwd) -} - /** Return the workspace keys that resolution tries in order, shared before legacy at both checkout levels. */ export async function workspaceBindingKeys(cwd: string): Promise { const keys: ScopeBindingKey[] = [] diff --git a/integrations/zcode/plugins/powercontext/scripts/scope.mjs b/integrations/zcode/plugins/powercontext/scripts/scope.mjs index 64fb8b6cf7..dd96f9146a 100644 --- a/integrations/zcode/plugins/powercontext/scripts/scope.mjs +++ b/integrations/zcode/plugins/powercontext/scripts/scope.mjs @@ -52,6 +52,7 @@ try { const target = args.values['scope-id'] binding = { action, status: 'unknown' } let clearedAny = false + let completed = 0 let savedScopeId for (const currentKey of keys) { let response @@ -61,7 +62,7 @@ try { key: currentKey, ...(action === 'bind' ? { scope_id: target } : {}), }, signal) } catch (error) { - if (/^http_4\d\d$/u.test(error?.message ?? '')) binding.status = 'rejected' + if (completed === 0 && /^http_4\d\d$/u.test(error?.message ?? '')) binding.status = 'rejected' throw error } if (response.status !== 200 || action === 'bind' && (response.body.scope_id !== target || @@ -71,6 +72,7 @@ try { } if (action === 'bind') savedScopeId = response.body.scope_id else clearedAny = clearedAny || response.body.cleared + completed += 1 } binding = action === 'bind' ? { action, status: 'saved', scope_id: savedScopeId } : { action, status: clearedAny ? 'cleared' : 'absent', cleared: clearedAny, diff --git a/integrations/zcode/plugins/powercontext/shared/git-worktree.mjs b/integrations/zcode/plugins/powercontext/shared/git-worktree.mjs index 0a029f5261..ea079ae47a 100644 --- a/integrations/zcode/plugins/powercontext/shared/git-worktree.mjs +++ b/integrations/zcode/plugins/powercontext/shared/git-worktree.mjs @@ -75,7 +75,7 @@ export function realWorkspacePath(directory) { if (!directory) return undefined let expanded = directory if (expanded === '~' || expanded.startsWith('~/') || expanded.startsWith('~\\')) { - const home = process.env.HOME || process.env.USERPROFILE || homedir() + const home = homedir() expanded = expanded === '~' ? home : join(home, expanded.slice(2)) } const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded @@ -103,7 +103,7 @@ function guardedGitTop(directory, top) { const dirReal = realWorkspacePath(directory) if (dirReal !== undefined && dirReal === topReal) return [top, 'git_root'] if (dirname(topReal) === topReal) return ['', 'home_guard'] - const homeReal = realWorkspacePath(process.env.HOME || process.env.USERPROFILE || homedir()) + const homeReal = realWorkspacePath(homedir()) if (homeReal !== undefined) { let current = homeReal while (true) { diff --git a/integrations/zcode/plugins/powercontext/tests/scope.test.mjs b/integrations/zcode/plugins/powercontext/tests/scope.test.mjs index eeff778354..b64911625a 100644 --- a/integrations/zcode/plugins/powercontext/tests/scope.test.mjs +++ b/integrations/zcode/plugins/powercontext/tests/scope.test.mjs @@ -190,3 +190,36 @@ test('a linked Git worktree uses its checkout binding until it binds its own', a await rm(root, { recursive: true, force: true }) } }) + +test('a partial unbind failure after clearing shared keeps binding status unknown instead of rejected', async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), 'pc-zcode-partial-'))) + let clears = 0 + const server = createServer(async (req, res) => { + for await (const _chunk of req) { /* drain */ } + res.setHeader('Content-Type', 'application/json') + if (req.url === '/v1/scope-bindings/clear') { + clears += 1 + if (clears === 1) { res.end('{"cleared":true}'); return } + res.statusCode = 429 + res.end('{"error":{"code":"rate_limited"}}') + return + } + res.end('{"scope_id":"default"}') + }) + try { + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + const installed = join(root, 'plugin') + await cp(plugin, installed, { recursive: true, filter: path => !path.includes('node_modules') }) + await writeFile(join(installed, 'powercontext.json'), JSON.stringify({ + server_url: `http://127.0.0.1:${server.address().port}`, capture_prompts: false, + })) + const cwd = join(root, 'workspace') + await mkdir(cwd) + const result = await run(join(installed, 'scripts', 'scope.mjs'), ['unbind', '--cwd', cwd], {}) + assert.equal(result.code, 1) + assert.equal(JSON.parse(result.stdout).binding.status, 'unknown') + } finally { + await new Promise(resolve => server.close(resolve)) + await rm(root, { recursive: true, force: true }) + } +}) diff --git a/src/powercontext/client/cli.py b/src/powercontext/client/cli.py index da8f2894c5..f77306fa63 100644 --- a/src/powercontext/client/cli.py +++ b/src/powercontext/client/cli.py @@ -54,6 +54,7 @@ SUPPORTED_SESSION_IMPORT_HOSTS, SessionImportError, SessionImportResult, + best_effort_workspace_identity, ) from powercontext.client.session_import import ( import_sessions as run_session_import, @@ -160,9 +161,7 @@ ) from powercontext_integration_lifecycle.git_worktree import ( SHARED_WORKSPACE_INTEGRATION, - _darwin_canonical_path, describe_workspace_root, - normalize_windows_real_path, real_workspace_path, workspace_identity, workspace_locations, @@ -367,39 +366,6 @@ def list_dreams( ) -def _best_effort_canonical_path(path: str) -> tuple[str, bool]: - """Resolve ``path`` on disk when it exists, or canonicalize its deepest existing ancestor for offline cleanup.""" - - existing = real_workspace_path(path) - if existing is not None: - return existing, True - current = os.path.realpath(os.path.expanduser(path)) - tail: list[str] = [] - while True: - if os.path.isdir(current): - try: - canon = _darwin_canonical_path(current) - except OSError: - canon = current - combined = os.path.join(canon, *tail) if tail else canon - return normalize_windows_real_path(combined), False - parent = os.path.dirname(current) - if parent == current: - combined = os.path.join(current, *tail) if tail else current - return normalize_windows_real_path(combined), False - tail.insert(0, os.path.basename(current)) - current = parent - - -def _best_effort_workspace_identity(path: str) -> tuple[str | None, str, bool]: - canonical, exists = _best_effort_canonical_path(path) - try: - digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest() - except UnicodeEncodeError: - return None, canonical, exists - return digest, canonical, exists - - def _legacy_host_workspace_external_id(path: str, integration: str) -> str: expanded = os.path.expanduser(path) if integration in _RESOLVED_CWD_WORKSPACE_INTEGRATIONS: @@ -415,12 +381,12 @@ def _legacy_host_workspace_external_id(path: str, integration: str) -> str: def _legacy_host_clear_external_ids(path: str, integration: str) -> list[str]: ids = [_legacy_host_workspace_external_id(path, integration)] + if integration == "zcode": + lexical_id = hashlib.sha256(os.path.abspath(os.path.expanduser(path)).encode("utf-8")).hexdigest() + if lexical_id not in ids: + ids.append(lexical_id) if integration not in _RESOLVED_CWD_WORKSPACE_INTEGRATIONS: - canon, _exists = _best_effort_canonical_path(path) - try: - canon_id = hashlib.sha256(canon.encode("utf-8")).hexdigest() - except UnicodeEncodeError: - canon_id = None + canon_id, _canon, _exists = best_effort_workspace_identity(path) if canon_id is not None and canon_id not in ids: ids.append(canon_id) return ids @@ -507,7 +473,7 @@ def _resolve_clear_cwd_binding_target( canonical_root = existing_root exists = True else: - shared_id, canonical_root, exists = _best_effort_workspace_identity(str(cwd)) + shared_id, canonical_root, exists = best_effort_workspace_identity(str(cwd)) root_source = "missing_directory" clear_keys = ( [_binding_key(SHARED_WORKSPACE_INTEGRATION, _BINDING_KIND_WORKSPACE, shared_id)] @@ -733,12 +699,18 @@ def clear_scope_binding( cwd: Annotated[ Path | None, typer.Option( - help="Workspace directory to clear (clears shared and, when --integration names a host, its own)." + help=( + "Workspace directory to clear. Without --integration, clears the shared binding and every derivable " + "legacy host workspace binding. Pass --integration shared for shared only, or --integration " + "for shared and that host's." + ) ), ] = None, integration: Annotated[ str | None, - typer.Option(help="Binding integration name (defaults to 'shared' with --cwd, else 'opencode')."), + typer.Option( + help="Binding integration name. With --cwd, narrows what is cleared; without --cwd, defaults to 'opencode'." + ), ] = None, ) -> None: """Clear one external integration or local workspace binding.""" diff --git a/src/powercontext/client/session_import.py b/src/powercontext/client/session_import.py index 11ed90ac21..5e3d1be6b2 100644 --- a/src/powercontext/client/session_import.py +++ b/src/powercontext/client/session_import.py @@ -36,10 +36,8 @@ from powercontext.redaction import redact_known_secrets from powercontext_integration_lifecycle.git_worktree import ( SHARED_WORKSPACE_INTEGRATION, - _darwin_canonical_path, normalize_windows_real_path, real_workspace_path, - workspace_identity, workspace_locations, ) @@ -573,30 +571,27 @@ def _session_binding_keys(session_id: str | None) -> tuple[ScopeBindingKey, ...] return (ScopeBindingKey(integration="codex", kind="session", external_id=value),) -def _offline_shared_identity(path: str) -> str | None: - online = workspace_identity(path) - if online is not None: - return online - current = os.path.realpath(os.path.expanduser(path)) - tail: list[str] = [] - while True: - if os.path.isdir(current): - try: - canon = _darwin_canonical_path(current) - except OSError: - canon = current - resolved = normalize_windows_real_path(os.path.join(canon, *tail) if tail else canon) - break - parent = os.path.dirname(current) - if parent == current: - resolved = normalize_windows_real_path(os.path.join(current, *tail) if tail else current) - break - tail.insert(0, os.path.basename(current)) - current = parent +def best_effort_workspace_identity(path: str) -> tuple[str | None, str, bool]: + """Return ``(shared_identity, canonical_path, exists)`` for ``path``. + + When ``path`` has been removed from disk, canonicalize its deepest existing ancestor and preserve the missing tail + so offline maintenance (``scope binding clear --cwd`` and ``import-sessions``) can still address the binding. + """ + + canonical = real_workspace_path(path) + exists = canonical is not None + if canonical is None: + current = os.path.realpath(os.path.expanduser(path)) + tail: list[str] = [] + while not os.path.isdir(current) and os.path.dirname(current) != current: + tail.insert(0, os.path.basename(current)) + current = os.path.dirname(current) + base = real_workspace_path(current) or current + canonical = normalize_windows_real_path(os.path.join(base, *tail) if tail else base) try: - return sha256(resolved.encode("utf-8")).hexdigest() + return sha256(canonical.encode("utf-8")).hexdigest(), canonical, exists except UnicodeEncodeError: - return None + return None, canonical, exists def _workspace_binding_keys(cwd: str) -> list[ScopeBindingKey]: @@ -604,7 +599,7 @@ def _workspace_binding_keys(cwd: str) -> list[ScopeBindingKey]: keys: list[ScopeBindingKey] = [] locations = workspace_locations(cwd, git_root=True) if real_workspace_path(cwd) is not None else [(cwd, cwd)] for shared_root, host_path in locations: - shared_id = _offline_shared_identity(shared_root) + shared_id, _canonical, _exists = best_effort_workspace_identity(shared_root) if shared_id is not None: keys.append( ScopeBindingKey( diff --git a/tests/e2e/test_shared_workspace_scope_binding.py b/tests/e2e/test_shared_workspace_scope_binding.py index aa166b96ed..be0f3a408e 100644 --- a/tests/e2e/test_shared_workspace_scope_binding.py +++ b/tests/e2e/test_shared_workspace_scope_binding.py @@ -115,6 +115,44 @@ def _resolve_ts_hosts(node: str, base_url: str, cwd: Path) -> dict[str, str]: return json.loads(completed.stdout) +def _seed_all_legacy_bindings(http: httpx.Client, checkout: Path, subdir: Path) -> None: + git_root_id = hashlib.sha256(os.fsencode(checkout.resolve())).hexdigest() + zcode_root_id = hashlib.sha256(str(checkout.resolve()).encode("utf-8")).hexdigest() + realpath_sub_id = hashlib.sha256(os.fsencode(subdir.resolve())).hexdigest() + bub_sub_id = hashlib.sha256(str(subdir.resolve()).encode("utf-8")).hexdigest() + kimi_sub_id = hashlib.sha256(os.path.realpath(subdir).encode("utf-8")).hexdigest() + resolved_sub_id = hashlib.sha256(os.path.abspath(subdir).encode("utf-8")).hexdigest() + legacy_seeds = { + "claude-code": git_root_id, + "codex": git_root_id, + "workbuddy": git_root_id, + "zcode": zcode_root_id, + "hermes": realpath_sub_id, + "bub": bub_sub_id, + "kimi-code": kimi_sub_id, + "dsh": resolved_sub_id, + "opencode": resolved_sub_id, + "pi": resolved_sub_id, + } + for host_name, ext_id in legacy_seeds.items(): + scope_resp = http.post( + "/v1/scopes", + json={ + "title": f"legacy-seed-{host_name}", + "summary": "Legacy workspace binding seed", + "idempotency_key": f"legacy-seed-{host_name}", + }, + ) + scope_resp.raise_for_status() + http.put( + "/v1/scope-bindings", + json={ + "key": {"integration": host_name, "kind": "workspace", "external_id": ext_id}, + "scope_id": scope_resp.json()["scope_id"], + }, + ).raise_for_status() + + def test_shared_workspace_binding_resolves_across_all_hosts_and_preserves_legacy_bindings( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, @@ -381,7 +419,11 @@ def resolve_all_hosts(cwd: Path) -> dict[str, str]: assert run_py_script(CLAUDE_SCRIPT, "--cwd", str(subdir)) == default_scope assert _resolve_ts_hosts(node, base_url, subdir)["pi"] == legacy_pi_scope - # 5. Default clear --cwd (no --integration) sweeps shared + all 10 legacy host keys at subdir. + # 5. Seed legacy bindings for all 10 workspace hosts and verify default clear --cwd sweeps every one. + _seed_all_legacy_bindings(http, layout.checkout, subdir) + seeded_resolved = resolve_all_hosts(subdir) + assert default_scope not in set(seeded_resolved.values()), seeded_resolved + clear_all_subdir = CliRunner().invoke( create_cli(), [ @@ -397,7 +439,8 @@ def resolve_all_hosts(cwd: Path) -> dict[str, str]: ) assert clear_all_subdir.exit_code == 0, clear_all_subdir.output assert json.loads(clear_all_subdir.output)["cleared"] is True - assert _resolve_ts_hosts(node, base_url, subdir)["pi"] == default_scope + swept_resolved = resolve_all_hosts(subdir) + assert set(swept_resolved.values()) == {default_scope}, swept_resolved finally: server.should_exit = True thread.join(timeout=10) diff --git a/tests/test_cli_scope.py b/tests/test_cli_scope.py index 81544090bb..2ac79ffdbf 100644 --- a/tests/test_cli_scope.py +++ b/tests/test_cli_scope.py @@ -627,3 +627,12 @@ def test_scope_list_forwards_query_with_field(monkeypatch: pytest.MonkeyPatch) - ], ) assert client.calls[0] == {"query": "Example", "query_field": "title", "limit": 50, "cursor": None} + + +def test_scope_binding_clear_help_describes_default_legacy_sweep() -> None: + result = CliRunner().invoke(create_cli([]), ["scope", "binding", "clear", "--help"]) + assert result.exit_code == 0 + cleaned = unstyle(result.output).replace("│", " ") + help_text = " ".join(cleaned.split()) + assert "every derivable legacy host workspace binding" in help_text + assert "defaults to 'shared' with --cwd" not in help_text diff --git a/tests/test_git_worktree.py b/tests/test_git_worktree.py index dff3060029..680e96f23b 100644 --- a/tests/test_git_worktree.py +++ b/tests/test_git_worktree.py @@ -217,6 +217,12 @@ def test_python_and_javascript_derive_the_same_workspace_identity(layout: GitLay except OSError: if os.name != "nt": raise + if os.name == "nt": + import _winapi + + junction = tmp_path / "checkout-junction" + _winapi.CreateJunction(str(layout.checkout), str(junction)) + targets.extend([junction, junction / "sub", str(junction) + os.sep + "..", junction / "missing"]) for target in targets: py_id = workspace_identity(str(target)) @@ -243,8 +249,14 @@ def test_home_directory_git_repository_does_not_collapse_subdirectories( unrelated.mkdir(parents=True) subprocess.run([git, "init", "-q", str(fake_home)], check=True, timeout=10) - monkeypatch.setenv("HOME", str(fake_home)) - monkeypatch.setenv("USERPROFILE", str(fake_home)) + other_home = tmp_path / "msys-home" + other_home.mkdir() + if os.name == "nt": + monkeypatch.setenv("HOME", str(other_home)) + monkeypatch.setenv("USERPROFILE", str(fake_home)) + else: + monkeypatch.setenv("HOME", str(fake_home)) + monkeypatch.setenv("USERPROFILE", str(other_home)) # Subdirectories under a git-initialized $HOME fall back to the directory itself for shared identity. py_locations = workspace_locations(str(unrelated), git_root=False) @@ -260,7 +272,11 @@ def test_home_directory_git_repository_does_not_collapse_subdirectories( node = shutil.which("node") if node is not None: - env = {**os.environ, "HOME": str(fake_home), "USERPROFILE": str(fake_home)} + env = { + **os.environ, + "HOME": str(other_home if os.name == "nt" else fake_home), + "USERPROFILE": str(fake_home if os.name == "nt" else other_home), + } script = ( "const [helper, dir] = process.argv.slice(1);" "const m = await import(helper);" From aef8a4437a19efaf1d1a0efaffb62a08f15be488 Mon Sep 17 00:00:00 2001 From: wycocoyu <180249289+wycocoyu@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:08:53 -0800 Subject: [PATCH 7/7] refactor(integrations): simplify workspace clearing and diagnostics --- .../2988-shared-workspace-scope-bindings.md | 25 ++-- .../2988-shared-workspace-scope-bindings.md | 22 ++-- .../bub/src/powercontext_bub/_git_worktree.py | 37 ++---- .../powercontext_lifecycle/git_worktree.py | 37 ++---- .../powercontext_lifecycle/scope_binding.py | 8 -- .../powercontext_lifecycle/git_worktree.py | 37 ++---- .../powercontext_lifecycle/scope_binding.py | 8 -- .../dsh/plugins/powercontext/lib/index.js | 39 ++---- .../dsh/plugins/powercontext/src/doctor.ts | 5 - .../plugins/powercontext/src/git-worktree.ts | 43 ++----- .../plugins/powercontext/git_worktree.py | 37 ++---- .../plugins/powercontext/scripts/doctor.mjs | 7 +- .../powercontext/shared/git-worktree.mjs | 41 ++---- .../plugins/powercontext/shared/runtime.mjs | 6 - .../powercontext/tests/plugin.test.mjs | 14 -- integrations/lifecycle/git-worktree.ts | 43 ++----- .../plugins/powercontext/lib/index.js | 22 +--- .../opencode/plugins/powercontext/lib/tui.js | 22 +--- .../plugins/powercontext/src/git-worktree.ts | 43 ++----- .../plugins/powercontext/src/git-worktree.ts | 43 ++----- .../powercontext/hooks/git_worktree.py | 37 ++---- .../powercontext/scripts/workspace_scope.py | 8 -- .../plugins/powercontext/scripts/doctor.mjs | 9 +- .../powercontext/shared/git-worktree.mjs | 41 ++---- .../plugins/powercontext/shared/scope.mjs | 5 - .../plugins/powercontext/tests/scope.test.mjs | 33 ----- src/powercontext/client/cli.py | 120 ++++-------------- src/powercontext/client/session_import.py | 31 +---- .../git_worktree.py | 37 ++---- .../scope_binding.py | 8 -- tests/codex_plugin/test_scope_binding.py | 2 - .../test_shared_workspace_scope_binding.py | 64 ++-------- tests/test_cli_scope.py | 50 ++------ tests/test_git_worktree.py | 31 ++--- 34 files changed, 226 insertions(+), 789 deletions(-) diff --git a/docs/en/rfcs/2988-shared-workspace-scope-bindings.md b/docs/en/rfcs/2988-shared-workspace-scope-bindings.md index 2579835cca..8dbe2a9235 100644 --- a/docs/en/rfcs/2988-shared-workspace-scope-bindings.md +++ b/docs/en/rfcs/2988-shared-workspace-scope-bindings.md @@ -38,10 +38,10 @@ Existing deployments need no migration: - Before a checkout receives a shared binding, each host continues resolving its existing per-host binding. - Binding the checkout once writes `("shared", "workspace", )`, which takes precedence over older per-host workspace bindings in every updated host. -- Clearing a workspace binding from a host removes both the shared binding and that host's legacy workspace binding for the checkout so the old per-host binding does not reappear; `powercontext scope binding clear --cwd /path/to/repo` clears the shared key and every derivable legacy per-host workspace key across all supported hosts. +- Clearing a workspace binding from a host removes both the shared binding and that host's legacy workspace binding for the checkout so the old per-host binding does not reappear; `powercontext scope binding clear --cwd /path/to/repo` clears `shared` by default, or `shared` plus a specific host's legacy workspace binding when `--integration ` is supplied. - Hosts that pin a resolved Scope to the session at startup (Codex and OpenCode) keep an active session on its existing Scope when a workspace binding changes mid-session; new sessions pick up the workspace binding. - A host that intentionally needs a separate Scope overrides resolution with its explicit Scope setting (for example `POWERCONTEXT_CODEX_SCOPE_ID`) or a session binding. -- Scope diagnostics probe candidate keys with `allow_default=false` and report which key matched (`shared`, the host's own workspace key, or `session`) together with the resolved workspace root and its source (`git_root`, `directory`, or `home_guard`). +- Scope diagnostics probe candidate keys with `allow_default=false` and report which key matched (`shared`, the host's own workspace key, or `session`). As required by [RFC 1345](1345_scope_organization_and_agent_integration.md), a workspace key only looks up an existing binding and never derives or creates a `scope_id`. PowerContext MCP endpoints never compute workspace keys; host hooks and plugins resolve and supply `scope_id` from each event's working directory. @@ -54,8 +54,7 @@ Given the session directory `dir` reported by the host (expanding a leading `~` ```text top = `git rev-parse --show-toplevel` in dir (decoded as UTF-8 in both Python and Node.js) root = top, except when Git produces no output, or when top != dir and top's canonical path is - the user's home directory, an ancestor of the home directory, or a filesystem root - (in which case root falls back to dir) + the user's home directory or a filesystem root (in which case root falls back to dir) path = OS-canonical real path of existing directory root: - Node.js: `fs.realpathSync.native(root)` (directory verified via `statSync`) - Python: `os.path.realpath(root)` (plus `fcntl.F_GETPATH` on macOS so case-insensitive @@ -67,9 +66,9 @@ id = lowercase hex SHA-256 of strict UTF-8(path) If `root` does not exist on disk as a directory or its canonical path cannot be strictly encoded as UTF-8, the host omits the `shared` workspace key for that location while still sending any remaining candidate keys. - Subdirectories of a checkout share the checkout's `root`. Outside Git, each directory is its own workspace. Git submodules report their own worktree top level and remain independent workspaces. -- Guarding `$HOME`, ancestors of `$HOME`, and filesystem roots prevents a dotfiles repository initialized in `$HOME` (or a stray `.git` at `/`) from collapsing unrelated subdirectories onto one workspace identity. +- Guarding `$HOME` and filesystem roots prevents a dotfiles repository initialized in `$HOME` (or a stray `.git` at `/`) from collapsing unrelated subdirectories onto one workspace identity. - Legacy per-host `:workspace` derivations are frozen byte-for-byte to each host's pre-RFC implementation (`HostProfile.legacy_workspace_binding` defaults to `False` and is enabled only on pre-existing hosts). One intentional exception applies on non-UTF-8 Windows code pages (such as `cp936`): Python's Git helper now decodes `git rev-parse` output explicitly as UTF-8 instead of the system ANSI code page so non-ASCII Git paths no longer corrupt or raise `UnicodeDecodeError`; a pre-RFC binding created from a mojibake path on such a checkout requires rebinding once. -- The shared lifecycle helpers (`src/powercontext_integration_lifecycle/git_worktree.py` and `integrations/lifecycle/git-worktree.ts`) compute both the shared checkout roots and the host's legacy paths from the single Git invocation introduced in [PR #2875](https://github.com/oceanbase/powercontext/pull/2875), starting no extra Git subprocesses ( Python 3.9+ standard library compatible). +- The shared lifecycle helpers (`src/powercontext_integration_lifecycle/git_worktree.py` and `integrations/lifecycle/git-worktree.ts`) compute both the shared checkout roots and the host's legacy paths from the single Git invocation introduced in [PR #2875](https://github.com/oceanbase/powercontext/pull/2875), starting no extra Git subprocesses (Python 3.9+ standard library compatible). ## 2. Reserved `shared` namespace @@ -97,13 +96,12 @@ Nearer locations win over main-checkout fallbacks (preserving #2875), and `share Codex and OpenCode persist the Scope resolved at session start to `(host, "session", session_id)` when no explicit Scope is configured. Because session bindings precede workspace bindings, binding a workspace mid-session leaves already-pinned sessions on their original Scope and applies to newly started sessions. -## 4. Bind, clear, CLI, offline maintenance, and diagnostics +## 4. Bind, clear, CLI, and diagnostics -- **Bind**: Host workspace helpers write `("shared", "workspace", shared_id_own)` for an existing directory. `powercontext scope binding set --cwd ` validates that `` exists, rejects non-`shared` `--integration` flags, writes the `shared` binding, and prints the resolved workspace root in human output. -- **Clear**: Host workspace helpers remove `("shared", "workspace", shared_id_own)` and `(host, "workspace", legacy_id_own)`, reporting `cleared=true` when either existed. `powercontext scope binding clear --cwd ` clears `shared` plus every derivable legacy `:workspace` key across all 10 existing workspace hosts when `--integration` is omitted (`--integration shared` clears only `shared`; `--integration ` clears `shared` and ``). -- **Offline maintenance for removed directories**: When `` has already been removed from disk (for example after `git worktree remove`), `powercontext scope binding clear --cwd ` and `powercontext import-sessions` derive a best-effort canonical path from the deepest existing ancestor so stale bindings can still be cleared and historical Codex sessions imported. +- **Bind**: Host workspace helpers write `("shared", "workspace", shared_id_own)` for an existing directory. `powercontext scope binding set --cwd ` validates that `` exists, rejects non-`shared` `--integration` flags, and writes the `shared` binding. +- **Clear**: Host workspace helpers remove `("shared", "workspace", shared_id_own)` and `(host, "workspace", legacy_id_own)`, reporting `cleared=true` when either existed. `powercontext scope binding clear --cwd ` requires `` to exist and clears `shared` by default (symmetric with `set --cwd`), or clears `shared` plus `` when `--integration ` is passed. - **CLI resolution**: `powercontext scope resolve` supports `--integration shared` as well as all workspace-capable host names (`claude-code`, `codex`, `dsh`, `hermes`, `kimi-code`, `opencode`, `pi`, `workbuddy`, `zcode`, `bub`), emitting the exact key sequence that host sends. -- **Diagnostics**: Host doctor and Scope diagnostic scripts (never per-turn hooks) probe `binding_keys` one at a time with `allow_default=false` to report `matched_key`, `resolved_root`, and `root_source`. +- **Diagnostics**: Host doctor and Scope diagnostic scripts (never per-turn hooks) probe `binding_keys` one at a time with `allow_default=false` to report `matched_key`. # Drawbacks @@ -124,9 +122,8 @@ Codex and OpenCode persist the Scope resolved at session start to `(host, "sessi # Unresolved questions and boundaries - **Identical container or devcontainer paths across machines**: Workspace identity hashes the canonical local checkout path without a machine identifier. Two machines or devcontainers mounting a repository at the exact same path (such as `/workspaces/app`) and sharing one PowerContext Server share that binding; separate paths on different machines remain distinct checkouts. -- **Git unavailable, timed out, or refused (`safe.directory`)**: When Git cannot report a top level within the helper budget, `root` falls back to `dir` (`root_source = "directory"` in diagnostics) rather than failing closed. -- **Legacy subdirectory bindings on cwd-keyed hosts**: `powercontext scope binding clear --cwd ` derives legacy keys for `` and its Git top level; a pre-RFC binding created from an arbitrary nested subdirectory in a cwd-keyed host (`dsh`, `opencode`, `pi`, `kimi-code`, `hermes`, `bub`) must be cleared with `--cwd` pointing at that subdirectory if no shared binding shadows it. -- **Removed subdirectories inside a live checkout**: When `` itself no longer exists on disk, offline `clear --cwd ` and `import-sessions` derive the canonical path from ``'s deepest existing ancestor without walking into a surrounding Git top level (which would risk clearing a live main checkout's binding when removing a nested worktree such as `/.worktrees/wt`). To clear a live checkout's shared binding, pass the checkout root or any existing directory inside it. +- **Git unavailable, timed out, or refused (`safe.directory`)**: When Git cannot report a top level within the helper budget, `root` falls back to `dir` rather than failing closed. +- **Legacy per-host workspace bindings**: Clearing a pre-RFC `:workspace` binding from the CLI uses `powercontext scope binding clear --cwd --integration ` (pointing `--cwd` at the bound subdirectory for cwd-keyed hosts `dsh`, `opencode`, `pi`, `kimi-code`, `hermes`, and `bub` if no shared binding shadows it). Because `--cwd` requires an existing directory, clearing a binding after its directory has been deleted uses `--kind workspace --external-id `. - **Windows long-path policy (`LongPathsEnabled=0`)**: On Windows systems with `LongPathsEnabled=0` (the OS default), Python's standard Win32 directory checks fail on workspace root paths of `MAX_PATH` (~260 characters) or longer when passed without an extended `\\?\` prefix, causing Python hosts and CLI `--cwd` to omit the `shared` key while Node.js (`libuv`) still resolves it. Checkouts whose root path stays under `MAX_PATH` are unaffected. - **Platform verification coverage**: On Windows, Python `ntpath.realpath` and Node `fs.realpathSync.native` both delegate to `GetFinalPathNameByHandleW`; cross-runtime path, junction, and home-guard parity is exercised in CI on Linux and `windows-latest`. macOS `fcntl.F_GETPATH` APFS case and NFD/NFC parity is verified on macOS development hosts (CI does not run a dedicated macOS Python test job). diff --git a/docs/zh/rfcs/2988-shared-workspace-scope-bindings.md b/docs/zh/rfcs/2988-shared-workspace-scope-bindings.md index 9b4bbdc9f0..aa07361786 100644 --- a/docs/zh/rfcs/2988-shared-workspace-scope-bindings.md +++ b/docs/zh/rfcs/2988-shared-workspace-scope-bindings.md @@ -38,10 +38,10 @@ powercontext scope binding set scp_repo --cwd /path/to/repo - 在某个检出目录写入共享绑定之前,各宿主继续命中各自原有的宿主工作区绑定。 - 在该检出目录重新绑定一次即会写入 `("shared", "workspace", )`,所有已升级宿主均会优先命中该共享绑定并覆盖旧的宿主级绑定。 -- 在宿主中清除工作区绑定会同时删除该检出目录的共享绑定与当前宿主的旧工作区绑定,避免清除后旧绑定重新生效;运行 `powercontext scope binding clear --cwd /path/to/repo` 默认一并清除共享键及该目录可推导出的全部存量宿主旧工作区键。 +- 在宿主中清除工作区绑定会同时删除该检出目录的共享绑定与当前宿主的旧工作区绑定,避免清除后旧绑定重新生效;运行 `powercontext scope binding clear --cwd /path/to/repo` 默认清除 `shared` 共享绑定,传入 `--integration ` 时同时清除 `shared` 与指定宿主的旧工作区绑定。 - 在会话启动时自动钉住已解析 Scope 的宿主(Codex 与 OpenCode)在会话中途修改工作区绑定时,已开启的活跃会话保持原 Scope,新启动会话采用新的工作区绑定。 - 若某个宿主确实需要使用独立 Scope,可通过显式 Scope 配置(例如 `POWERCONTEXT_CODEX_SCOPE_ID`)或会话级绑定覆盖。 -- 各宿主 Scope 诊断工具以 `allow_default=false` 逐键探测候选绑定键,并同时报告命中的键来源(`shared`、宿主自有工作区键或 `session`)以及实际采用的规范化根路径与来源(`git_root`、`directory` 或 `home_guard`)。 +- 各宿主 Scope 诊断工具以 `allow_default=false` 逐键探测候选绑定键,并报告实际命中的键来源(`shared`、宿主自有工作区键或 `session`)。 遵循 [RFC 1345](1345_scope_organization_and_agent_integration.md) 约束,工作区键仅用于查找既有绑定,绝不直接派生或自动创建 `scope_id`。PowerContext MCP 服务端点永远不自行计算工作区键,由宿主层利用每次事件自带的工作目录解析并注入 `scope_id`。 @@ -53,7 +53,7 @@ powercontext scope binding set scp_repo --cwd /path/to/repo ```text top = 在 dir 中执行 `git rev-parse --show-toplevel` 的输出(Python 与 Node.js 均按 UTF-8 解码) -root = top;但若 Git 无输出,或当 top != dir 且 top 的规范路径等于用户家目录、家目录的祖先或文件系统根目录时, +root = top;但若 Git 无输出,或当 top != dir 且 top 的规范路径等于用户家目录或文件系统根目录时, root 回退为 dir 自身 path = 已存在目录 root 的操作系统规范路径: - Node.js:`fs.realpathSync.native(root)`(并通过 `statSync` 确认为目录) @@ -65,7 +65,7 @@ id = 严格 UTF-8(path) 字节序列的小写十六进制 SHA-256 若 `root` 在磁盘上不是已存在的目录,或其规范路径无法按严格 UTF-8 编码,则宿主在该位置不发送 `shared` 工作区键,其余候选键照常发送。 - 同一检出目录内的所有子目录共享同一个 `root`。在 Git 工作树之外,每个目录各自构成独立工作区。Git submodule 上报其自身工作树顶层,作为独立工作区处理。 -- 家目录、家目录祖先及文件系统根目录守卫可防止用户在家目录执行 `git init`(如管理 dotfiles)或根目录存在残留 `.git` 时,将家目录下所有无关非仓库目录折叠为同一工作区。 +- 家目录与文件系统根目录守卫可防止用户在家目录执行 `git init`(如管理 dotfiles)或根目录存在残留 `.git` 时,将家目录下所有无关非仓库目录折叠为同一工作区。 - 存量宿主的旧 `:workspace` 派生逻辑按本 RFC 之前的实现逐字节冻结(`HostProfile.legacy_workspace_binding` 默认设为 `False`,仅在既有宿主中显式开启)。唯一有意例外位于非 UTF-8 代码页(如 `cp936`)的 Windows 环境:Python 的 Git 辅助函数现显式按 UTF-8 解码 `git rev-parse` 输出而不再使用系统 ANSI 代码页,避免非 ASCII Git 路径乱码或抛出 `UnicodeDecodeError`;此前在这类路径上由乱码字符串生成的旧绑定重新绑定一次即可。 - 共享生命周期辅助模块(`src/powercontext_integration_lifecycle/git_worktree.py` 与 `integrations/lifecycle/git-worktree.ts`)复用 [PR #2875](https://github.com/oceanbase/powercontext/pull/2875) 的单次 Git 调用同时派生共享检出根路径与宿主旧兼容路径,不额外启动 Git 子进程,并兼容 Python 3.9+ 标准库。 @@ -95,13 +95,12 @@ Server 端 `ScopeBindingKey.integration` 本身为非空自由字符串(`1..12 Codex 与 OpenCode 在未配置显式 Scope 时会将新会话首次解析出的 Scope 写入 `(host, "session", session_id)`。由于会话绑定排在工作区绑定之前,在会话中途修改工作区绑定不会改变已钉住的旧会话,新开启的会话将自动命中新的工作区绑定。 -## 4. 绑定、清除、CLI、离线维护与诊断 +## 4. 绑定、清除、CLI 与诊断 -- **绑定(Bind)**:各宿主工作区脚本对已存在目录写入 `("shared", "workspace", shared_id_own)`。`powercontext scope binding set --cwd ` 校验 `` 存在、拒绝非 `shared` 的 `--integration` 参数,写入共享绑定并在人类可读输出中打印采用的根路径。 -- **清除(Clear)**:各宿主工作区脚本同时清除 `("shared", "workspace", shared_id_own)` 与 `(host, "workspace", legacy_id_own)`,任一存在即返回 `cleared=true`。`powercontext scope binding clear --cwd ` 在未指定 `--integration` 时默认清除 `shared` 及全部 10 个存量宿主在该目录可推导出的旧工作区键(`--integration shared` 仅清 `shared`,`--integration ` 清 `shared` 与 ``)。 -- **已删除目录的离线维护**:当 `` 已从磁盘删除(例如已执行 `git worktree remove`)时,`powercontext scope binding clear --cwd ` 与 `powercontext import-sessions` 通过最深已存在祖先目录尽力推导规范路径,使残留绑定仍可被清除、已删工作树的历史 Codex 会话仍可导入。 +- **绑定(Bind)**:各宿主工作区脚本对已存在目录写入 `("shared", "workspace", shared_id_own)`。`powercontext scope binding set --cwd ` 校验 `` 存在、拒绝非 `shared` 的 `--integration` 参数并写入共享绑定。 +- **清除(Clear)**:各宿主工作区脚本同时清除 `("shared", "workspace", shared_id_own)` 与 `(host, "workspace", legacy_id_own)`,任一存在即返回 `cleared=true`。`powercontext scope binding clear --cwd ` 要求 `` 存在,未指定 `--integration` 时默认清除 `shared`(与 `set --cwd` 对称),指定 `--integration ` 时同时清除 `shared` 与 ``。 - **CLI 解析**:`powercontext scope resolve` 支持 `--integration shared` 及全部支持工作区绑定的宿主名(`claude-code`、`codex`、`dsh`、`hermes`、`kimi-code`、`opencode`、`pi`、`workbuddy`、`zcode`、`bub`),输出与对应宿主完全一致的键序列。 -- **诊断(Diagnostics)**:宿主 doctor 与 Scope 诊断脚本(仅限诊断命令,不在每轮对话 Hook 中执行)通过 `allow_default=false` 逐键探测 `binding_keys`,报告 `matched_key`、`resolved_root` 与 `root_source`。 +- **诊断(Diagnostics)**:宿主 doctor 与 Scope 诊断脚本(仅限诊断命令,不在每轮对话 Hook 中执行)通过 `allow_default=false` 逐键探测 `binding_keys`,报告 `matched_key`。 # Drawbacks @@ -122,9 +121,8 @@ Codex 与 OpenCode 在未配置显式 Scope 时会将新会话首次解析出的 # Unresolved questions and boundaries - **多机或容器相同挂载路径边界**:工作区身份仅哈希本地检出目录规范路径,不引入机器 ID。当多台机器或多个 devcontainer 在完全相同的路径(例如 `/workspaces/app`)挂载仓库并连接同一个 PowerContext Server 时,它们会共享该路径对应的工作区绑定;不同路径仍保持独立。 -- **Git 未安装、超时或 `safe.directory` 拒绝**:当 Git 在超时预算内无法返回顶层目录时,`root` 安全回退为 `dir`(诊断中 `root_source = "directory"`),不会阻断会话请求。 -- **按 `cwd` 派生宿主的子目录遗留绑定**:`powercontext scope binding clear --cwd ` 会清除 `` 及其 Git 顶层对应的旧键;若升级前曾在 `dsh`、`opencode`、`pi`、`kimi-code`、`hermes` 或 `bub` 的某个深层子目录单独创建过旧绑定且当前不存在遮蔽它的共享绑定,则需对该子目录传入 `--cwd` 予以清除。 -- **存活检出内已删除子目录的离线推导**:当 `` 本身已不存在时,离线 `clear --cwd ` 与 `import-sessions` 按最深已存在祖先拼接原相对尾部推导,不会继续向上探测外层 Git 顶层(否则当已删除的嵌套工作树位于 `/.worktrees/wt` 时会误删主检出目录的共享绑定)。如需清除存活检出目录的共享绑定,请对检出根目录或其中任一存活子目录执行 `clear --cwd`。 +- **Git 未安装、超时或 `safe.directory` 拒绝**:当 Git 在超时预算内无法返回顶层目录时,`root` 安全回退为 `dir`,不会阻断会话请求。 +- **存量宿主私有工作区绑定的清除**:通过 CLI 清除本 RFC 之前的 `:workspace` 绑定时,使用 `powercontext scope binding clear --cwd --integration `(对于 `dsh`、`opencode`、`pi`、`kimi-code`、`hermes`、`bub` 等按当前目录派生的宿主,若无遮蔽它的共享绑定,需对曾绑定的对应目录传入 `--cwd`)。由于 `--cwd` 要求目录存在,目录从磁盘删除后的残留绑定通过 `--kind workspace --external-id ` 清除。 - **Windows 长路径策略(`LongPathsEnabled=0`)**:在未开启长路径支持(Windows 默认 `LongPathsEnabled=0`)的系统上,当工作区根路径本身达到或超过 `MAX_PATH`(约 260 字符)且未携带 `\\?\` 前缀时,Python 标准库目录检查会失败并省略 `shared` 键,而 Node.js(`libuv`)仍能解析;根路径短于 `MAX_PATH` 的常规检出不受影响。 - **跨平台验证覆盖范围**:在 Windows 上,Python `ntpath.realpath` 与 Node `fs.realpathSync.native` 底层均调用 `GetFinalPathNameByHandleW`,跨运行时路径、目录联接(junction)与家目录守卫一致性在 CI 的 Linux 与 `windows-latest` 任务中持续验证;macOS `fcntl.F_GETPATH` 的 APFS 大小写与 NFD/NFC 一致性已在 macOS 本机验证(CI 未单独配置 macOS Python 测试任务)。 diff --git a/integrations/bub/src/powercontext_bub/_git_worktree.py b/integrations/bub/src/powercontext_bub/_git_worktree.py index 65f6747778..e246e51474 100644 --- a/integrations/bub/src/powercontext_bub/_git_worktree.py +++ b/integrations/bub/src/powercontext_bub/_git_worktree.py @@ -101,36 +101,17 @@ def workspace_identity(path: str) -> str | None: return hashlib.sha256(encoded).hexdigest() -def _guarded_git_top(cwd: str, top: str | None) -> tuple[str | None, str]: +def _guarded_git_top(cwd: str, top: str | None) -> str | None: if top is None: - return None, "directory" + return None top_real = real_workspace_path(top) if top_real is None: - return None, "directory" - cwd_real = real_workspace_path(cwd) - if cwd_real is not None and cwd_real == top_real: - return top, "git_root" - if os.path.dirname(top_real) == top_real: - return None, "home_guard" - home_real = real_workspace_path("~") - if home_real is not None: - current = home_real - while True: - if current == top_real: - return None, "home_guard" - parent = os.path.dirname(current) - if parent == current: - break - current = parent - return top, "git_root" - - -def describe_workspace_root(cwd: str, *, timeout: float = 2.0) -> tuple[str | None, str]: - """Return ``(canonical_root, root_source)`` for diagnostics and operator CLI output.""" - - raw_top, _git_dir, _common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) - effective_top, source = _guarded_git_top(cwd, raw_top) - return real_workspace_path(effective_top or cwd), source + return None + if top_real != real_workspace_path(cwd) and ( + os.path.dirname(top_real) == top_real or top_real == real_workspace_path("~") + ): + return None + return top def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[tuple[str, str | None]]: @@ -144,7 +125,7 @@ def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> li deadline = time.monotonic() + timeout raw_top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) - top, _source = _guarded_git_top(cwd, raw_top) + top = _guarded_git_top(cwd, raw_top) shared_own = top or cwd host_own = (raw_top or cwd) if git_root else cwd if top is None: diff --git a/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/git_worktree.py b/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/git_worktree.py index 65f6747778..e246e51474 100644 --- a/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/git_worktree.py +++ b/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/git_worktree.py @@ -101,36 +101,17 @@ def workspace_identity(path: str) -> str | None: return hashlib.sha256(encoded).hexdigest() -def _guarded_git_top(cwd: str, top: str | None) -> tuple[str | None, str]: +def _guarded_git_top(cwd: str, top: str | None) -> str | None: if top is None: - return None, "directory" + return None top_real = real_workspace_path(top) if top_real is None: - return None, "directory" - cwd_real = real_workspace_path(cwd) - if cwd_real is not None and cwd_real == top_real: - return top, "git_root" - if os.path.dirname(top_real) == top_real: - return None, "home_guard" - home_real = real_workspace_path("~") - if home_real is not None: - current = home_real - while True: - if current == top_real: - return None, "home_guard" - parent = os.path.dirname(current) - if parent == current: - break - current = parent - return top, "git_root" - - -def describe_workspace_root(cwd: str, *, timeout: float = 2.0) -> tuple[str | None, str]: - """Return ``(canonical_root, root_source)`` for diagnostics and operator CLI output.""" - - raw_top, _git_dir, _common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) - effective_top, source = _guarded_git_top(cwd, raw_top) - return real_workspace_path(effective_top or cwd), source + return None + if top_real != real_workspace_path(cwd) and ( + os.path.dirname(top_real) == top_real or top_real == real_workspace_path("~") + ): + return None + return top def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[tuple[str, str | None]]: @@ -144,7 +125,7 @@ def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> li deadline = time.monotonic() + timeout raw_top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) - top, _source = _guarded_git_top(cwd, raw_top) + top = _guarded_git_top(cwd, raw_top) shared_own = top or cwd host_own = (raw_top or cwd) if git_root else cwd if top is None: diff --git a/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/scope_binding.py b/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/scope_binding.py index 7342e113b4..a81bfef59e 100644 --- a/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/scope_binding.py +++ b/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/scope_binding.py @@ -33,7 +33,6 @@ from .git_worktree import ( SHARED_WORKSPACE_INTEGRATION, - describe_workspace_root, workspace_identity, workspace_locations, ) @@ -173,15 +172,12 @@ def diagnose_scope_binding( ) -> dict[str, Any]: """Resolve the active Scope and identify which candidate binding key matched (for diagnostics, never hooks).""" - resolved_root, root_source = describe_workspace_root(cwd, timeout=_git_timeout(deadline)) if settings.scope_id is not None: scope_id = resolve_scope_id(host, cwd, session_id=session_id, settings=settings, deadline=deadline) return { "scope_id": scope_id, "source": "explicit", "matched_key": None, - "resolved_root": resolved_root, - "root_source": root_source, } for key in binding_keys(host, cwd, session_id=session_id, deadline=deadline): try: @@ -203,8 +199,6 @@ def diagnose_scope_binding( "scope_id": scope_id, "source": "binding", "matched_key": key, - "resolved_root": resolved_root, - "root_source": root_source, } response = _request_json( "/v1/scope-bindings/resolve", @@ -220,8 +214,6 @@ def diagnose_scope_binding( "scope_id": scope_id, "source": "default", "matched_key": None, - "resolved_root": resolved_root, - "root_source": root_source, } diff --git a/integrations/codex/plugins/powercontext/powercontext_lifecycle/git_worktree.py b/integrations/codex/plugins/powercontext/powercontext_lifecycle/git_worktree.py index 65f6747778..e246e51474 100644 --- a/integrations/codex/plugins/powercontext/powercontext_lifecycle/git_worktree.py +++ b/integrations/codex/plugins/powercontext/powercontext_lifecycle/git_worktree.py @@ -101,36 +101,17 @@ def workspace_identity(path: str) -> str | None: return hashlib.sha256(encoded).hexdigest() -def _guarded_git_top(cwd: str, top: str | None) -> tuple[str | None, str]: +def _guarded_git_top(cwd: str, top: str | None) -> str | None: if top is None: - return None, "directory" + return None top_real = real_workspace_path(top) if top_real is None: - return None, "directory" - cwd_real = real_workspace_path(cwd) - if cwd_real is not None and cwd_real == top_real: - return top, "git_root" - if os.path.dirname(top_real) == top_real: - return None, "home_guard" - home_real = real_workspace_path("~") - if home_real is not None: - current = home_real - while True: - if current == top_real: - return None, "home_guard" - parent = os.path.dirname(current) - if parent == current: - break - current = parent - return top, "git_root" - - -def describe_workspace_root(cwd: str, *, timeout: float = 2.0) -> tuple[str | None, str]: - """Return ``(canonical_root, root_source)`` for diagnostics and operator CLI output.""" - - raw_top, _git_dir, _common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) - effective_top, source = _guarded_git_top(cwd, raw_top) - return real_workspace_path(effective_top or cwd), source + return None + if top_real != real_workspace_path(cwd) and ( + os.path.dirname(top_real) == top_real or top_real == real_workspace_path("~") + ): + return None + return top def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[tuple[str, str | None]]: @@ -144,7 +125,7 @@ def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> li deadline = time.monotonic() + timeout raw_top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) - top, _source = _guarded_git_top(cwd, raw_top) + top = _guarded_git_top(cwd, raw_top) shared_own = top or cwd host_own = (raw_top or cwd) if git_root else cwd if top is None: diff --git a/integrations/codex/plugins/powercontext/powercontext_lifecycle/scope_binding.py b/integrations/codex/plugins/powercontext/powercontext_lifecycle/scope_binding.py index 7342e113b4..a81bfef59e 100644 --- a/integrations/codex/plugins/powercontext/powercontext_lifecycle/scope_binding.py +++ b/integrations/codex/plugins/powercontext/powercontext_lifecycle/scope_binding.py @@ -33,7 +33,6 @@ from .git_worktree import ( SHARED_WORKSPACE_INTEGRATION, - describe_workspace_root, workspace_identity, workspace_locations, ) @@ -173,15 +172,12 @@ def diagnose_scope_binding( ) -> dict[str, Any]: """Resolve the active Scope and identify which candidate binding key matched (for diagnostics, never hooks).""" - resolved_root, root_source = describe_workspace_root(cwd, timeout=_git_timeout(deadline)) if settings.scope_id is not None: scope_id = resolve_scope_id(host, cwd, session_id=session_id, settings=settings, deadline=deadline) return { "scope_id": scope_id, "source": "explicit", "matched_key": None, - "resolved_root": resolved_root, - "root_source": root_source, } for key in binding_keys(host, cwd, session_id=session_id, deadline=deadline): try: @@ -203,8 +199,6 @@ def diagnose_scope_binding( "scope_id": scope_id, "source": "binding", "matched_key": key, - "resolved_root": resolved_root, - "root_source": root_source, } response = _request_json( "/v1/scope-bindings/resolve", @@ -220,8 +214,6 @@ def diagnose_scope_binding( "scope_id": scope_id, "source": "default", "matched_key": None, - "resolved_root": resolved_root, - "root_source": root_source, } diff --git a/integrations/dsh/plugins/powercontext/lib/index.js b/integrations/dsh/plugins/powercontext/lib/index.js index f5ed5aaba8..d78fbf4dd3 100644 --- a/integrations/dsh/plugins/powercontext/lib/index.js +++ b/integrations/dsh/plugins/powercontext/lib/index.js @@ -19,8 +19,8 @@ import { lstatSync, readFileSync, realpathSync, statSync } from "node:fs"; import { fileURLToPath, pathToFileURL } from "node:url"; import { homedir } from "node:os"; import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; -import { execFile, execFileSync } from "node:child_process"; import { createHash, randomUUID } from "node:crypto"; +import { execFile, execFileSync } from "node:child_process"; import { promisify } from "node:util"; import { createServer, request } from "node:http"; import { request as request$1 } from "node:https"; @@ -2679,29 +2679,11 @@ function workspaceIdentity(directory) { return createHash("sha256").update(canonical, "utf8").digest("hex"); } function guardedGitTop(directory, top) { - if (!top) return ["", "directory"]; + if (!top) return ""; const topReal = realWorkspacePath(top); - if (topReal === void 0) return ["", "directory"]; - const dirReal = realWorkspacePath(directory); - if (dirReal !== void 0 && dirReal === topReal) return [top, "git_root"]; - if (dirname(topReal) === topReal) return ["", "home_guard"]; - const homeReal = realWorkspacePath(homedir()); - if (homeReal !== void 0) { - let current = homeReal; - while (true) { - if (current === topReal) return ["", "home_guard"]; - const parent = dirname(current); - if (parent === current) break; - current = parent; - } - } - return [top, "git_root"]; -} -/** Return `[canonicalRootOrEmpty, rootSource]` for diagnostics. */ -async function describeWorkspaceRoot(directory, timeout) { - const [rawTop = ""] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)); - const [top = "", source = "directory"] = guardedGitTop(directory, rawTop); - return [realWorkspacePath(top || directory) ?? "", source]; + if (topReal === void 0) return ""; + if (topReal !== realWorkspacePath(directory) && (dirname(topReal) === topReal || topReal === realWorkspacePath(homedir()))) return ""; + return top; } /** * Return `[sharedRoot, hostPath]` pairs for `directory` and, in a linked worktree, its main checkout. @@ -2713,7 +2695,7 @@ async function describeWorkspaceRoot(directory, timeout) { async function workspaceLocations(directory, gitRoot, timeout) { const deadline = Date.now() + timeout; const [rawTop = "", gitDir = "", common = ""] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)); - const [top = ""] = guardedGitTop(directory, rawTop); + const top = guardedGitTop(directory, rawTop); const sharedOwn = top || directory; const hostOwn = gitRoot ? rawTop || directory : directory; if (!top) return [[sharedOwn, hostOwn]]; @@ -2731,7 +2713,7 @@ async function workspaceLocations(directory, gitRoot, timeout) { function workspaceLocationsSync(directory, gitRoot, timeout) { const deadline = Date.now() + timeout; const [rawTop = "", gitDir = "", common = ""] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)); - const [top = ""] = guardedGitTop(directory, rawTop); + const top = guardedGitTop(directory, rawTop); const sharedOwn = top || directory; const hostOwn = gitRoot ? rawTop || directory : directory; if (!top) return [[sharedOwn, hostOwn]]; @@ -3233,7 +3215,6 @@ async function diagnoseServer(runtime, cwd, signal, toolCatalog, toolScope) { scopeId = await runtime.resolveScope(cwd, signal); if (!scopeId) return check("resolve_scope_binding", "unscoped", "Scope resolution returned no usable Scope.", "Check the explicit Scope override, workspace binding and Server default Scope. Doctor does not create bindings."); const workspace = sessionCwd(cwd); - const [resolvedRoot = "", rootSource = "directory"] = workspace ? await describeWorkspaceRoot(workspace, 500) : ["", "none"]; let matchedKey = runtime.config.scopeId ? "explicit" : "default"; if (!runtime.config.scopeId && workspace) for (const candidate of await workspaceBindingKeys(workspace)) try { const single = await runtime.client.request("resolve_scope_binding", { @@ -3252,11 +3233,7 @@ async function diagnoseServer(runtime, cwd, signal, toolCatalog, toolScope) { } return { ...check("resolve_scope_binding", "scope_resolved", "The Server resolved the current session Scope.", void 0, "ok"), - ...matchedKey ? { matched_key: matchedKey } : {}, - ...workspace ? { - resolved_root: resolvedRoot || null, - root_source: rootSource - } : {} + ...matchedKey ? { matched_key: matchedKey } : {} }; }); checks.prepare = scopeId ? await probe("prepare_context", async () => { diff --git a/integrations/dsh/plugins/powercontext/src/doctor.ts b/integrations/dsh/plugins/powercontext/src/doctor.ts index 4bc9c14adb..31a8000761 100644 --- a/integrations/dsh/plugins/powercontext/src/doctor.ts +++ b/integrations/dsh/plugins/powercontext/src/doctor.ts @@ -23,7 +23,6 @@ import { authenticationRejection, bodyFailureDetails, type BodyFailureDetails, I import type { PluginRuntime } from './invoke.ts' import { OPERATIONS, type OperationId } from './operations.generated.ts' import { PREPARED_CONTEXT_SCHEMA, validatePreparedContext } from './prepared-context.ts' -import { describeWorkspaceRoot } from './git-worktree.ts' import { sessionCwd, workspaceBindingKeys } from './scope.ts' export interface DoctorCheck extends BodyFailureDetails { @@ -369,9 +368,6 @@ export async function diagnoseServer( 'Check the explicit Scope override, workspace binding and Server default Scope. Doctor does not create bindings.') } const workspace = sessionCwd(cwd) - const [resolvedRoot = '', rootSource = 'directory'] = workspace - ? await describeWorkspaceRoot(workspace, 500) - : ['', 'none'] let matchedKey: string | undefined = runtime.config.scopeId ? 'explicit' : 'default' if (!runtime.config.scopeId && workspace) { for (const candidate of await workspaceBindingKeys(workspace)) { @@ -399,7 +395,6 @@ export async function diagnoseServer( return { ...check('resolve_scope_binding', 'scope_resolved', 'The Server resolved the current session Scope.', undefined, 'ok'), ...(matchedKey ? { matched_key: matchedKey } : {}), - ...(workspace ? { resolved_root: resolvedRoot || null, root_source: rootSource } : {}), } }) checks.prepare = scopeId ? await probe('prepare_context', async () => { diff --git a/integrations/dsh/plugins/powercontext/src/git-worktree.ts b/integrations/dsh/plugins/powercontext/src/git-worktree.ts index cbab6ff2e1..6d74315495 100644 --- a/integrations/dsh/plugins/powercontext/src/git-worktree.ts +++ b/integrations/dsh/plugins/powercontext/src/git-worktree.ts @@ -96,38 +96,17 @@ export function workspaceIdentity(directory: string): string | undefined { return createHash('sha256').update(canonical, 'utf8').digest('hex') } -function guardedGitTop(directory: string, top: string): string[] { - if (!top) return ['', 'directory'] +function guardedGitTop(directory: string, top: string): string { + if (!top) return '' const topReal = realWorkspacePath(top) - if (topReal === undefined) return ['', 'directory'] - const dirReal = realWorkspacePath(directory) - if (dirReal !== undefined && dirReal === topReal) return [top, 'git_root'] - if (dirname(topReal) === topReal) return ['', 'home_guard'] - const homeReal = realWorkspacePath(homedir()) - if (homeReal !== undefined) { - let current = homeReal - while (true) { - if (current === topReal) return ['', 'home_guard'] - const parent = dirname(current) - if (parent === current) break - current = parent - } + if (topReal === undefined) return '' + if ( + topReal !== realWorkspacePath(directory) && + (dirname(topReal) === topReal || topReal === realWorkspacePath(homedir())) + ) { + return '' } - return [top, 'git_root'] -} - -/** Return `[canonicalRootOrEmpty, rootSource]` for diagnostics. */ -export async function describeWorkspaceRoot(directory: string, timeout: number): Promise { - const [rawTop = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) - const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) - return [realWorkspacePath(top || directory) ?? '', source] -} - -/** Synchronous counterpart of `describeWorkspaceRoot`. */ -export function describeWorkspaceRootSync(directory: string, timeout: number): string[] { - const [rawTop = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) - const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) - return [realWorkspacePath(top || directory) ?? '', source] + return top } /** @@ -140,7 +119,7 @@ export function describeWorkspaceRootSync(directory: string, timeout: number): s export async function workspaceLocations(directory: string, gitRoot: boolean, timeout: number): Promise { const deadline = Date.now() + timeout const [rawTop = '', gitDir = '', common = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) - const [top = ''] = guardedGitTop(directory, rawTop) + const top = guardedGitTop(directory, rawTop) const sharedOwn = top || directory const hostOwn = gitRoot ? (rawTop || directory) : directory if (!top) return [[sharedOwn, hostOwn]] @@ -157,7 +136,7 @@ export async function workspaceLocations(directory: string, gitRoot: boolean, ti export function workspaceLocationsSync(directory: string, gitRoot: boolean, timeout: number): string[][] { const deadline = Date.now() + timeout const [rawTop = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) - const [top = ''] = guardedGitTop(directory, rawTop) + const top = guardedGitTop(directory, rawTop) const sharedOwn = top || directory const hostOwn = gitRoot ? (rawTop || directory) : directory if (!top) return [[sharedOwn, hostOwn]] diff --git a/integrations/hermes/plugins/powercontext/git_worktree.py b/integrations/hermes/plugins/powercontext/git_worktree.py index 65f6747778..e246e51474 100644 --- a/integrations/hermes/plugins/powercontext/git_worktree.py +++ b/integrations/hermes/plugins/powercontext/git_worktree.py @@ -101,36 +101,17 @@ def workspace_identity(path: str) -> str | None: return hashlib.sha256(encoded).hexdigest() -def _guarded_git_top(cwd: str, top: str | None) -> tuple[str | None, str]: +def _guarded_git_top(cwd: str, top: str | None) -> str | None: if top is None: - return None, "directory" + return None top_real = real_workspace_path(top) if top_real is None: - return None, "directory" - cwd_real = real_workspace_path(cwd) - if cwd_real is not None and cwd_real == top_real: - return top, "git_root" - if os.path.dirname(top_real) == top_real: - return None, "home_guard" - home_real = real_workspace_path("~") - if home_real is not None: - current = home_real - while True: - if current == top_real: - return None, "home_guard" - parent = os.path.dirname(current) - if parent == current: - break - current = parent - return top, "git_root" - - -def describe_workspace_root(cwd: str, *, timeout: float = 2.0) -> tuple[str | None, str]: - """Return ``(canonical_root, root_source)`` for diagnostics and operator CLI output.""" - - raw_top, _git_dir, _common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) - effective_top, source = _guarded_git_top(cwd, raw_top) - return real_workspace_path(effective_top or cwd), source + return None + if top_real != real_workspace_path(cwd) and ( + os.path.dirname(top_real) == top_real or top_real == real_workspace_path("~") + ): + return None + return top def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[tuple[str, str | None]]: @@ -144,7 +125,7 @@ def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> li deadline = time.monotonic() + timeout raw_top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) - top, _source = _guarded_git_top(cwd, raw_top) + top = _guarded_git_top(cwd, raw_top) shared_own = top or cwd host_own = (raw_top or cwd) if git_root else cwd if top is None: diff --git a/integrations/kimi-code/plugins/powercontext/scripts/doctor.mjs b/integrations/kimi-code/plugins/powercontext/scripts/doctor.mjs index a0257f9d40..03eaa0823b 100644 --- a/integrations/kimi-code/plugins/powercontext/scripts/doctor.mjs +++ b/integrations/kimi-code/plugins/powercontext/scripts/doctor.mjs @@ -14,7 +14,7 @@ * limitations under the License. */ -import { describeWorkspace, Failure, isScopeId, loadSettings, profileTools, request, resolveScope, workspaceKeys } from '../shared/runtime.mjs' +import { Failure, isScopeId, loadSettings, profileTools, request, resolveScope, workspaceKeys } from '../shared/runtime.mjs' import { discoverTools } from '../shared/mcp.mjs' import { parseArgs } from 'node:util' import { queryObservations } from '../shared/observations.mjs' @@ -59,12 +59,9 @@ if (settings) { } } } - const [resolvedRoot = '', rootSource = 'directory'] = describeWorkspace(input.cwd) checks.scope = { status: 'ok', detail: 'Current Scope is accessible.', checks: { scope_id: scopeId, selection: settings.scopeId ? 'explicit' : 'workspace_or_default', - ...(matchedKey ? { matched_key: matchedKey } : {}), - ...(resolvedRoot ? { resolved_root: resolvedRoot } : {}), - root_source: rootSource } } + ...(matchedKey ? { matched_key: matchedKey } : {}) } } } catch (error) { checks.scope = result(error) } if (values.mcp) { try { checks.mcp_discovery = await discoverTools(settings, profileTools(settings.profile)) } diff --git a/integrations/kimi-code/plugins/powercontext/shared/git-worktree.mjs b/integrations/kimi-code/plugins/powercontext/shared/git-worktree.mjs index ea079ae47a..9ca9ae4cc8 100644 --- a/integrations/kimi-code/plugins/powercontext/shared/git-worktree.mjs +++ b/integrations/kimi-code/plugins/powercontext/shared/git-worktree.mjs @@ -97,37 +97,16 @@ export function workspaceIdentity(directory) { } function guardedGitTop(directory, top) { - if (!top) return ['', 'directory'] + if (!top) return '' const topReal = realWorkspacePath(top) - if (topReal === undefined) return ['', 'directory'] - const dirReal = realWorkspacePath(directory) - if (dirReal !== undefined && dirReal === topReal) return [top, 'git_root'] - if (dirname(topReal) === topReal) return ['', 'home_guard'] - const homeReal = realWorkspacePath(homedir()) - if (homeReal !== undefined) { - let current = homeReal - while (true) { - if (current === topReal) return ['', 'home_guard'] - const parent = dirname(current) - if (parent === current) break - current = parent - } + if (topReal === undefined) return '' + if ( + topReal !== realWorkspacePath(directory) && + (dirname(topReal) === topReal || topReal === realWorkspacePath(homedir())) + ) { + return '' } - return [top, 'git_root'] -} - -/** Return `[canonicalRootOrEmpty, rootSource]` for diagnostics. */ -export async function describeWorkspaceRoot(directory, timeout) { - const [rawTop = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) - const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) - return [realWorkspacePath(top || directory) ?? '', source] -} - -/** Synchronous counterpart of `describeWorkspaceRoot`. */ -export function describeWorkspaceRootSync(directory, timeout) { - const [rawTop = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) - const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) - return [realWorkspacePath(top || directory) ?? '', source] + return top } /** @@ -140,7 +119,7 @@ export function describeWorkspaceRootSync(directory, timeout) { export async function workspaceLocations(directory, gitRoot, timeout) { const deadline = Date.now() + timeout const [rawTop = '', gitDir = '', common = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) - const [top = ''] = guardedGitTop(directory, rawTop) + const top = guardedGitTop(directory, rawTop) const sharedOwn = top || directory const hostOwn = gitRoot ? (rawTop || directory) : directory if (!top) return [[sharedOwn, hostOwn]] @@ -157,7 +136,7 @@ export async function workspaceLocations(directory, gitRoot, timeout) { export function workspaceLocationsSync(directory, gitRoot, timeout) { const deadline = Date.now() + timeout const [rawTop = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) - const [top = ''] = guardedGitTop(directory, rawTop) + const top = guardedGitTop(directory, rawTop) const sharedOwn = top || directory const hostOwn = gitRoot ? (rawTop || directory) : directory if (!top) return [[sharedOwn, hostOwn]] diff --git a/integrations/kimi-code/plugins/powercontext/shared/runtime.mjs b/integrations/kimi-code/plugins/powercontext/shared/runtime.mjs index 647526fb92..57313228eb 100644 --- a/integrations/kimi-code/plugins/powercontext/shared/runtime.mjs +++ b/integrations/kimi-code/plugins/powercontext/shared/runtime.mjs @@ -20,7 +20,6 @@ import { isAbsolute, resolve } from 'node:path' import { isIP } from 'node:net' import { fileURLToPath } from 'node:url' import { - describeWorkspaceRootSync, SHARED_WORKSPACE_INTEGRATION, workspaceIdentity, workspaceLocationsSync, @@ -145,11 +144,6 @@ export function workspaceKey(cwd) { return { integration: SHARED_WORKSPACE_INTEGRATION, kind: 'workspace', external_id: externalId } } -export function describeWorkspace(cwd) { - requireAbsoluteWorkspace(cwd) - return describeWorkspaceRootSync(cwd, GIT_TIMEOUT_MS) -} - // Resolution tries shared before Kimi's legacy key at both the checkout and, in a linked worktree, its main checkout. // Binding writes only workspaceKey (shared); clearing removes both workspaceKey and legacyWorkspaceKey. export function workspaceKeys(cwd) { diff --git a/integrations/kimi-code/plugins/powercontext/tests/plugin.test.mjs b/integrations/kimi-code/plugins/powercontext/tests/plugin.test.mjs index 878e885372..a5a6eee849 100644 --- a/integrations/kimi-code/plugins/powercontext/tests/plugin.test.mjs +++ b/integrations/kimi-code/plugins/powercontext/tests/plugin.test.mjs @@ -665,17 +665,3 @@ test('an unconfirmed binding write stays unknown without retry and invalid works assert.equal(result.status, 'failed') assert.equal(f.requests.filter(item => item.path === '/v1/scope-bindings').length, 1) }) - -test('a partial unbind failure after clearing shared keeps binding status unknown instead of rejected', async t => { - let clears = 0 - const f = await fixture(t, { - '/v1/scope-bindings/clear': (_req, res) => { - clears += 1 - if (clears === 1) { res.writeHead(200); res.end('{"cleared":true}'); return } - res.writeHead(429); res.end('{"error":{"code":"rate_limited"}}') - }, - }, { scope_id: null }) - const result = await f.scope('unbind') - assert.equal(result.status, 'failed') - assert.equal(result.binding.status, 'unknown') -}) diff --git a/integrations/lifecycle/git-worktree.ts b/integrations/lifecycle/git-worktree.ts index 73f9d73d33..543fe8f608 100644 --- a/integrations/lifecycle/git-worktree.ts +++ b/integrations/lifecycle/git-worktree.ts @@ -93,38 +93,17 @@ export function workspaceIdentity(directory: string): string | undefined { return createHash('sha256').update(canonical, 'utf8').digest('hex') } -function guardedGitTop(directory: string, top: string): string[] { - if (!top) return ['', 'directory'] +function guardedGitTop(directory: string, top: string): string { + if (!top) return '' const topReal = realWorkspacePath(top) - if (topReal === undefined) return ['', 'directory'] - const dirReal = realWorkspacePath(directory) - if (dirReal !== undefined && dirReal === topReal) return [top, 'git_root'] - if (dirname(topReal) === topReal) return ['', 'home_guard'] - const homeReal = realWorkspacePath(homedir()) - if (homeReal !== undefined) { - let current = homeReal - while (true) { - if (current === topReal) return ['', 'home_guard'] - const parent = dirname(current) - if (parent === current) break - current = parent - } + if (topReal === undefined) return '' + if ( + topReal !== realWorkspacePath(directory) && + (dirname(topReal) === topReal || topReal === realWorkspacePath(homedir())) + ) { + return '' } - return [top, 'git_root'] -} - -/** Return `[canonicalRootOrEmpty, rootSource]` for diagnostics. */ -export async function describeWorkspaceRoot(directory: string, timeout: number): Promise { - const [rawTop = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) - const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) - return [realWorkspacePath(top || directory) ?? '', source] -} - -/** Synchronous counterpart of `describeWorkspaceRoot`. */ -export function describeWorkspaceRootSync(directory: string, timeout: number): string[] { - const [rawTop = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) - const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) - return [realWorkspacePath(top || directory) ?? '', source] + return top } /** @@ -137,7 +116,7 @@ export function describeWorkspaceRootSync(directory: string, timeout: number): s export async function workspaceLocations(directory: string, gitRoot: boolean, timeout: number): Promise { const deadline = Date.now() + timeout const [rawTop = '', gitDir = '', common = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) - const [top = ''] = guardedGitTop(directory, rawTop) + const top = guardedGitTop(directory, rawTop) const sharedOwn = top || directory const hostOwn = gitRoot ? (rawTop || directory) : directory if (!top) return [[sharedOwn, hostOwn]] @@ -154,7 +133,7 @@ export async function workspaceLocations(directory: string, gitRoot: boolean, ti export function workspaceLocationsSync(directory: string, gitRoot: boolean, timeout: number): string[][] { const deadline = Date.now() + timeout const [rawTop = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) - const [top = ''] = guardedGitTop(directory, rawTop) + const top = guardedGitTop(directory, rawTop) const sharedOwn = top || directory const hostOwn = gitRoot ? (rawTop || directory) : directory if (!top) return [[sharedOwn, hostOwn]] diff --git a/integrations/opencode/plugins/powercontext/lib/index.js b/integrations/opencode/plugins/powercontext/lib/index.js index aec3151d00..2d17f18b66 100644 --- a/integrations/opencode/plugins/powercontext/lib/index.js +++ b/integrations/opencode/plugins/powercontext/lib/index.js @@ -2553,23 +2553,11 @@ function workspaceIdentity(directory) { return createHash("sha256").update(canonical, "utf8").digest("hex"); } function guardedGitTop(directory, top) { - if (!top) return ["", "directory"]; + if (!top) return ""; const topReal = realWorkspacePath(top); - if (topReal === void 0) return ["", "directory"]; - const dirReal = realWorkspacePath(directory); - if (dirReal !== void 0 && dirReal === topReal) return [top, "git_root"]; - if (dirname(topReal) === topReal) return ["", "home_guard"]; - const homeReal = realWorkspacePath(homedir()); - if (homeReal !== void 0) { - let current = homeReal; - while (true) { - if (current === topReal) return ["", "home_guard"]; - const parent = dirname(current); - if (parent === current) break; - current = parent; - } - } - return [top, "git_root"]; + if (topReal === void 0) return ""; + if (topReal !== realWorkspacePath(directory) && (dirname(topReal) === topReal || topReal === realWorkspacePath(homedir()))) return ""; + return top; } /** * Return `[sharedRoot, hostPath]` pairs for `directory` and, in a linked worktree, its main checkout. @@ -2581,7 +2569,7 @@ function guardedGitTop(directory, top) { async function workspaceLocations(directory, gitRoot, timeout) { const deadline = Date.now() + timeout; const [rawTop = "", gitDir = "", common = ""] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)); - const [top = ""] = guardedGitTop(directory, rawTop); + const top = guardedGitTop(directory, rawTop); const sharedOwn = top || directory; const hostOwn = gitRoot ? rawTop || directory : directory; if (!top) return [[sharedOwn, hostOwn]]; diff --git a/integrations/opencode/plugins/powercontext/lib/tui.js b/integrations/opencode/plugins/powercontext/lib/tui.js index 363c29ed17..ff539c0425 100644 --- a/integrations/opencode/plugins/powercontext/lib/tui.js +++ b/integrations/opencode/plugins/powercontext/lib/tui.js @@ -2639,23 +2639,11 @@ function workspaceIdentity(directory) { return createHash("sha256").update(canonical, "utf8").digest("hex"); } function guardedGitTop(directory, top) { - if (!top) return ["", "directory"]; + if (!top) return ""; const topReal = realWorkspacePath(top); - if (topReal === void 0) return ["", "directory"]; - const dirReal = realWorkspacePath(directory); - if (dirReal !== void 0 && dirReal === topReal) return [top, "git_root"]; - if (dirname(topReal) === topReal) return ["", "home_guard"]; - const homeReal = realWorkspacePath(homedir()); - if (homeReal !== void 0) { - let current = homeReal; - while (true) { - if (current === topReal) return ["", "home_guard"]; - const parent = dirname(current); - if (parent === current) break; - current = parent; - } - } - return [top, "git_root"]; + if (topReal === void 0) return ""; + if (topReal !== realWorkspacePath(directory) && (dirname(topReal) === topReal || topReal === realWorkspacePath(homedir()))) return ""; + return top; } /** * Return `[sharedRoot, hostPath]` pairs for `directory` and, in a linked worktree, its main checkout. @@ -2667,7 +2655,7 @@ function guardedGitTop(directory, top) { async function workspaceLocations(directory, gitRoot, timeout) { const deadline = Date.now() + timeout; const [rawTop = "", gitDir = "", common = ""] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)); - const [top = ""] = guardedGitTop(directory, rawTop); + const top = guardedGitTop(directory, rawTop); const sharedOwn = top || directory; const hostOwn = gitRoot ? rawTop || directory : directory; if (!top) return [[sharedOwn, hostOwn]]; diff --git a/integrations/opencode/plugins/powercontext/src/git-worktree.ts b/integrations/opencode/plugins/powercontext/src/git-worktree.ts index cbab6ff2e1..6d74315495 100644 --- a/integrations/opencode/plugins/powercontext/src/git-worktree.ts +++ b/integrations/opencode/plugins/powercontext/src/git-worktree.ts @@ -96,38 +96,17 @@ export function workspaceIdentity(directory: string): string | undefined { return createHash('sha256').update(canonical, 'utf8').digest('hex') } -function guardedGitTop(directory: string, top: string): string[] { - if (!top) return ['', 'directory'] +function guardedGitTop(directory: string, top: string): string { + if (!top) return '' const topReal = realWorkspacePath(top) - if (topReal === undefined) return ['', 'directory'] - const dirReal = realWorkspacePath(directory) - if (dirReal !== undefined && dirReal === topReal) return [top, 'git_root'] - if (dirname(topReal) === topReal) return ['', 'home_guard'] - const homeReal = realWorkspacePath(homedir()) - if (homeReal !== undefined) { - let current = homeReal - while (true) { - if (current === topReal) return ['', 'home_guard'] - const parent = dirname(current) - if (parent === current) break - current = parent - } + if (topReal === undefined) return '' + if ( + topReal !== realWorkspacePath(directory) && + (dirname(topReal) === topReal || topReal === realWorkspacePath(homedir())) + ) { + return '' } - return [top, 'git_root'] -} - -/** Return `[canonicalRootOrEmpty, rootSource]` for diagnostics. */ -export async function describeWorkspaceRoot(directory: string, timeout: number): Promise { - const [rawTop = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) - const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) - return [realWorkspacePath(top || directory) ?? '', source] -} - -/** Synchronous counterpart of `describeWorkspaceRoot`. */ -export function describeWorkspaceRootSync(directory: string, timeout: number): string[] { - const [rawTop = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) - const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) - return [realWorkspacePath(top || directory) ?? '', source] + return top } /** @@ -140,7 +119,7 @@ export function describeWorkspaceRootSync(directory: string, timeout: number): s export async function workspaceLocations(directory: string, gitRoot: boolean, timeout: number): Promise { const deadline = Date.now() + timeout const [rawTop = '', gitDir = '', common = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) - const [top = ''] = guardedGitTop(directory, rawTop) + const top = guardedGitTop(directory, rawTop) const sharedOwn = top || directory const hostOwn = gitRoot ? (rawTop || directory) : directory if (!top) return [[sharedOwn, hostOwn]] @@ -157,7 +136,7 @@ export async function workspaceLocations(directory: string, gitRoot: boolean, ti export function workspaceLocationsSync(directory: string, gitRoot: boolean, timeout: number): string[][] { const deadline = Date.now() + timeout const [rawTop = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) - const [top = ''] = guardedGitTop(directory, rawTop) + const top = guardedGitTop(directory, rawTop) const sharedOwn = top || directory const hostOwn = gitRoot ? (rawTop || directory) : directory if (!top) return [[sharedOwn, hostOwn]] diff --git a/integrations/pi/plugins/powercontext/src/git-worktree.ts b/integrations/pi/plugins/powercontext/src/git-worktree.ts index cbab6ff2e1..6d74315495 100644 --- a/integrations/pi/plugins/powercontext/src/git-worktree.ts +++ b/integrations/pi/plugins/powercontext/src/git-worktree.ts @@ -96,38 +96,17 @@ export function workspaceIdentity(directory: string): string | undefined { return createHash('sha256').update(canonical, 'utf8').digest('hex') } -function guardedGitTop(directory: string, top: string): string[] { - if (!top) return ['', 'directory'] +function guardedGitTop(directory: string, top: string): string { + if (!top) return '' const topReal = realWorkspacePath(top) - if (topReal === undefined) return ['', 'directory'] - const dirReal = realWorkspacePath(directory) - if (dirReal !== undefined && dirReal === topReal) return [top, 'git_root'] - if (dirname(topReal) === topReal) return ['', 'home_guard'] - const homeReal = realWorkspacePath(homedir()) - if (homeReal !== undefined) { - let current = homeReal - while (true) { - if (current === topReal) return ['', 'home_guard'] - const parent = dirname(current) - if (parent === current) break - current = parent - } + if (topReal === undefined) return '' + if ( + topReal !== realWorkspacePath(directory) && + (dirname(topReal) === topReal || topReal === realWorkspacePath(homedir())) + ) { + return '' } - return [top, 'git_root'] -} - -/** Return `[canonicalRootOrEmpty, rootSource]` for diagnostics. */ -export async function describeWorkspaceRoot(directory: string, timeout: number): Promise { - const [rawTop = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) - const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) - return [realWorkspacePath(top || directory) ?? '', source] -} - -/** Synchronous counterpart of `describeWorkspaceRoot`. */ -export function describeWorkspaceRootSync(directory: string, timeout: number): string[] { - const [rawTop = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) - const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) - return [realWorkspacePath(top || directory) ?? '', source] + return top } /** @@ -140,7 +119,7 @@ export function describeWorkspaceRootSync(directory: string, timeout: number): s export async function workspaceLocations(directory: string, gitRoot: boolean, timeout: number): Promise { const deadline = Date.now() + timeout const [rawTop = '', gitDir = '', common = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) - const [top = ''] = guardedGitTop(directory, rawTop) + const top = guardedGitTop(directory, rawTop) const sharedOwn = top || directory const hostOwn = gitRoot ? (rawTop || directory) : directory if (!top) return [[sharedOwn, hostOwn]] @@ -157,7 +136,7 @@ export async function workspaceLocations(directory: string, gitRoot: boolean, ti export function workspaceLocationsSync(directory: string, gitRoot: boolean, timeout: number): string[][] { const deadline = Date.now() + timeout const [rawTop = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) - const [top = ''] = guardedGitTop(directory, rawTop) + const top = guardedGitTop(directory, rawTop) const sharedOwn = top || directory const hostOwn = gitRoot ? (rawTop || directory) : directory if (!top) return [[sharedOwn, hostOwn]] diff --git a/integrations/workbuddy/plugins/powercontext/hooks/git_worktree.py b/integrations/workbuddy/plugins/powercontext/hooks/git_worktree.py index 65f6747778..e246e51474 100644 --- a/integrations/workbuddy/plugins/powercontext/hooks/git_worktree.py +++ b/integrations/workbuddy/plugins/powercontext/hooks/git_worktree.py @@ -101,36 +101,17 @@ def workspace_identity(path: str) -> str | None: return hashlib.sha256(encoded).hexdigest() -def _guarded_git_top(cwd: str, top: str | None) -> tuple[str | None, str]: +def _guarded_git_top(cwd: str, top: str | None) -> str | None: if top is None: - return None, "directory" + return None top_real = real_workspace_path(top) if top_real is None: - return None, "directory" - cwd_real = real_workspace_path(cwd) - if cwd_real is not None and cwd_real == top_real: - return top, "git_root" - if os.path.dirname(top_real) == top_real: - return None, "home_guard" - home_real = real_workspace_path("~") - if home_real is not None: - current = home_real - while True: - if current == top_real: - return None, "home_guard" - parent = os.path.dirname(current) - if parent == current: - break - current = parent - return top, "git_root" - - -def describe_workspace_root(cwd: str, *, timeout: float = 2.0) -> tuple[str | None, str]: - """Return ``(canonical_root, root_source)`` for diagnostics and operator CLI output.""" - - raw_top, _git_dir, _common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) - effective_top, source = _guarded_git_top(cwd, raw_top) - return real_workspace_path(effective_top or cwd), source + return None + if top_real != real_workspace_path(cwd) and ( + os.path.dirname(top_real) == top_real or top_real == real_workspace_path("~") + ): + return None + return top def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[tuple[str, str | None]]: @@ -144,7 +125,7 @@ def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> li deadline = time.monotonic() + timeout raw_top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) - top, _source = _guarded_git_top(cwd, raw_top) + top = _guarded_git_top(cwd, raw_top) shared_own = top or cwd host_own = (raw_top or cwd) if git_root else cwd if top is None: diff --git a/integrations/workbuddy/plugins/powercontext/scripts/workspace_scope.py b/integrations/workbuddy/plugins/powercontext/scripts/workspace_scope.py index 246737ab3a..4209d015a7 100644 --- a/integrations/workbuddy/plugins/powercontext/scripts/workspace_scope.py +++ b/integrations/workbuddy/plugins/powercontext/scripts/workspace_scope.py @@ -40,7 +40,6 @@ from git_worktree import ( # noqa: E402 SHARED_WORKSPACE_INTEGRATION, - describe_workspace_root, workspace_identity, workspace_locations, ) @@ -222,15 +221,12 @@ def diagnose_scope_binding( ) -> dict[str, Any]: """Resolve the active Scope and identify which candidate binding key matched.""" - resolved_root, root_source = describe_workspace_root(cwd, timeout=_git_timeout(deadline)) if settings.scope_id is not None: scope_id = resolve_scope_id(cwd, session_id=session_id, settings=settings, deadline=deadline) return { "scope_id": scope_id, "source": "explicit", "matched_key": None, - "resolved_root": resolved_root, - "root_source": root_source, } for key in binding_keys(cwd, session_id=session_id, deadline=deadline): try: @@ -251,8 +247,6 @@ def diagnose_scope_binding( "scope_id": scope_id, "source": "binding", "matched_key": key, - "resolved_root": resolved_root, - "root_source": root_source, } response = _request_json( "/v1/scope-bindings/resolve", @@ -267,8 +261,6 @@ def diagnose_scope_binding( "scope_id": scope_id, "source": "default", "matched_key": None, - "resolved_root": resolved_root, - "root_source": root_source, } diff --git a/integrations/zcode/plugins/powercontext/scripts/doctor.mjs b/integrations/zcode/plugins/powercontext/scripts/doctor.mjs index 71d81f0c5f..fceb72b8de 100644 --- a/integrations/zcode/plugins/powercontext/scripts/doctor.mjs +++ b/integrations/zcode/plugins/powercontext/scripts/doctor.mjs @@ -16,7 +16,7 @@ import { parseArgs } from 'node:util' import { queryObservations } from '../shared/observations.mjs' -import { describeWorkspace, isScopeId, resolveScope } from '../shared/scope.mjs' +import { isScopeId, resolveScope } from '../shared/scope.mjs' import { loadSettings } from '../shared/settings.mjs' import { failureCode, HOOK_BUDGET_MS, request } from '../shared/transport.mjs' @@ -61,14 +61,9 @@ try { } } } - const [resolvedRoot = '', rootSource = 'directory'] = settings.remoteWorkspace - ? ['', 'remote'] - : describeWorkspace(input.cwd) checks.scope_probe = { status: 'ok', code: 'resolved', scope_id: scope.scopeId, session_key_used: scope.keys.some(key => key.kind === 'session'), - ...(matchedKey ? { matched_key: matchedKey } : {}), - ...(resolvedRoot ? { resolved_root: resolvedRoot } : {}), - root_source: rootSource } + ...(matchedKey ? { matched_key: matchedKey } : {}) } } catch (error) { checks.scope_probe = { status: 'failed', code: failureCode(error) } } if (values.prepare && scope) { try { diff --git a/integrations/zcode/plugins/powercontext/shared/git-worktree.mjs b/integrations/zcode/plugins/powercontext/shared/git-worktree.mjs index ea079ae47a..9ca9ae4cc8 100644 --- a/integrations/zcode/plugins/powercontext/shared/git-worktree.mjs +++ b/integrations/zcode/plugins/powercontext/shared/git-worktree.mjs @@ -97,37 +97,16 @@ export function workspaceIdentity(directory) { } function guardedGitTop(directory, top) { - if (!top) return ['', 'directory'] + if (!top) return '' const topReal = realWorkspacePath(top) - if (topReal === undefined) return ['', 'directory'] - const dirReal = realWorkspacePath(directory) - if (dirReal !== undefined && dirReal === topReal) return [top, 'git_root'] - if (dirname(topReal) === topReal) return ['', 'home_guard'] - const homeReal = realWorkspacePath(homedir()) - if (homeReal !== undefined) { - let current = homeReal - while (true) { - if (current === topReal) return ['', 'home_guard'] - const parent = dirname(current) - if (parent === current) break - current = parent - } + if (topReal === undefined) return '' + if ( + topReal !== realWorkspacePath(directory) && + (dirname(topReal) === topReal || topReal === realWorkspacePath(homedir())) + ) { + return '' } - return [top, 'git_root'] -} - -/** Return `[canonicalRootOrEmpty, rootSource]` for diagnostics. */ -export async function describeWorkspaceRoot(directory, timeout) { - const [rawTop = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) - const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) - return [realWorkspacePath(top || directory) ?? '', source] -} - -/** Synchronous counterpart of `describeWorkspaceRoot`. */ -export function describeWorkspaceRootSync(directory, timeout) { - const [rawTop = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) - const [top = '', source = 'directory'] = guardedGitTop(directory, rawTop) - return [realWorkspacePath(top || directory) ?? '', source] + return top } /** @@ -140,7 +119,7 @@ export function describeWorkspaceRootSync(directory, timeout) { export async function workspaceLocations(directory, gitRoot, timeout) { const deadline = Date.now() + timeout const [rawTop = '', gitDir = '', common = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) - const [top = ''] = guardedGitTop(directory, rawTop) + const top = guardedGitTop(directory, rawTop) const sharedOwn = top || directory const hostOwn = gitRoot ? (rawTop || directory) : directory if (!top) return [[sharedOwn, hostOwn]] @@ -157,7 +136,7 @@ export async function workspaceLocations(directory, gitRoot, timeout) { export function workspaceLocationsSync(directory, gitRoot, timeout) { const deadline = Date.now() + timeout const [rawTop = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) - const [top = ''] = guardedGitTop(directory, rawTop) + const top = guardedGitTop(directory, rawTop) const sharedOwn = top || directory const hostOwn = gitRoot ? (rawTop || directory) : directory if (!top) return [[sharedOwn, hostOwn]] diff --git a/integrations/zcode/plugins/powercontext/shared/scope.mjs b/integrations/zcode/plugins/powercontext/shared/scope.mjs index 8a7a8c93f5..4250e88fbd 100644 --- a/integrations/zcode/plugins/powercontext/shared/scope.mjs +++ b/integrations/zcode/plugins/powercontext/shared/scope.mjs @@ -18,7 +18,6 @@ import { createHash } from 'node:crypto' import { realpathSync } from 'node:fs' import { resolve } from 'node:path' import { - describeWorkspaceRootSync, SHARED_WORKSPACE_INTEGRATION, workspaceIdentity, workspaceLocationsSync, @@ -53,10 +52,6 @@ export function currentWorkspace(cwd) { return legacyPath(sharedRoot) } -export function describeWorkspace(cwd) { - return describeWorkspaceRootSync(resolve(cwd), 500) -} - // Binding writes the shared key; clearing removes both the shared key and ZCode's legacy key. export function workspaceKey(cwd) { const directory = resolve(cwd) diff --git a/integrations/zcode/plugins/powercontext/tests/scope.test.mjs b/integrations/zcode/plugins/powercontext/tests/scope.test.mjs index b64911625a..eeff778354 100644 --- a/integrations/zcode/plugins/powercontext/tests/scope.test.mjs +++ b/integrations/zcode/plugins/powercontext/tests/scope.test.mjs @@ -190,36 +190,3 @@ test('a linked Git worktree uses its checkout binding until it binds its own', a await rm(root, { recursive: true, force: true }) } }) - -test('a partial unbind failure after clearing shared keeps binding status unknown instead of rejected', async () => { - const root = await realpath(await mkdtemp(join(tmpdir(), 'pc-zcode-partial-'))) - let clears = 0 - const server = createServer(async (req, res) => { - for await (const _chunk of req) { /* drain */ } - res.setHeader('Content-Type', 'application/json') - if (req.url === '/v1/scope-bindings/clear') { - clears += 1 - if (clears === 1) { res.end('{"cleared":true}'); return } - res.statusCode = 429 - res.end('{"error":{"code":"rate_limited"}}') - return - } - res.end('{"scope_id":"default"}') - }) - try { - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) - const installed = join(root, 'plugin') - await cp(plugin, installed, { recursive: true, filter: path => !path.includes('node_modules') }) - await writeFile(join(installed, 'powercontext.json'), JSON.stringify({ - server_url: `http://127.0.0.1:${server.address().port}`, capture_prompts: false, - })) - const cwd = join(root, 'workspace') - await mkdir(cwd) - const result = await run(join(installed, 'scripts', 'scope.mjs'), ['unbind', '--cwd', cwd], {}) - assert.equal(result.code, 1) - assert.equal(JSON.parse(result.stdout).binding.status, 'unknown') - } finally { - await new Promise(resolve => server.close(resolve)) - await rm(root, { recursive: true, force: true }) - } -}) diff --git a/src/powercontext/client/cli.py b/src/powercontext/client/cli.py index f77306fa63..37cdb6bed6 100644 --- a/src/powercontext/client/cli.py +++ b/src/powercontext/client/cli.py @@ -54,7 +54,6 @@ SUPPORTED_SESSION_IMPORT_HOSTS, SessionImportError, SessionImportResult, - best_effort_workspace_identity, ) from powercontext.client.session_import import ( import_sessions as run_session_import, @@ -161,7 +160,6 @@ ) from powercontext_integration_lifecycle.git_worktree import ( SHARED_WORKSPACE_INTEGRATION, - describe_workspace_root, real_workspace_path, workspace_identity, workspace_locations, @@ -379,19 +377,6 @@ def _legacy_host_workspace_external_id(path: str, integration: str) -> str: return hashlib.sha256(os.fsencode(Path(expanded).resolve())).hexdigest() -def _legacy_host_clear_external_ids(path: str, integration: str) -> list[str]: - ids = [_legacy_host_workspace_external_id(path, integration)] - if integration == "zcode": - lexical_id = hashlib.sha256(os.path.abspath(os.path.expanduser(path)).encode("utf-8")).hexdigest() - if lexical_id not in ids: - ids.append(lexical_id) - if integration not in _RESOLVED_CWD_WORKSPACE_INTEGRATIONS: - canon_id, _canon, _exists = best_effort_workspace_identity(path) - if canon_id is not None and canon_id not in ids: - ids.append(canon_id) - return ids - - def _workspace_binding_keys(cwd: Path, integration: str) -> list[ScopeBindingKey]: """Return the workspace keys that resolution tries in order, matching the host plugin's sequence.""" @@ -424,71 +409,39 @@ def _workspace_binding_keys(cwd: Path, integration: str) -> list[ScopeBindingKey return keys -def _resolve_set_cwd_binding_target( - cwd: Path, - integration: str | None, -) -> tuple[list[ScopeBindingKey], str | None, str | None, bool]: +def _resolve_set_cwd_binding_target(cwd: Path, integration: str | None) -> list[ScopeBindingKey]: if integration is not None and integration != SHARED_WORKSPACE_INTEGRATION: raise typer.BadParameter( # noqa: TRY003 "--cwd always writes the 'shared' workspace binding; omit --integration.", param_hint="--integration", ) if real_workspace_path(str(cwd)) is None: - raise typer.BadParameter( # noqa: TRY003 - "Workspace directory does not exist.", - param_hint="--cwd", - ) - resolved_root, root_source = describe_workspace_root(str(cwd)) + 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) if shared_id is None: - raise typer.BadParameter( # noqa: TRY003 - "Workspace path cannot be encoded as UTF-8.", - param_hint="--cwd", - ) - return ( - [_binding_key(SHARED_WORKSPACE_INTEGRATION, _BINDING_KIND_WORKSPACE, shared_id)], - resolved_root, - root_source, - True, - ) + raise typer.BadParameter("Workspace path cannot be encoded as UTF-8.", param_hint="--cwd") # noqa: TRY003 + return [_binding_key(SHARED_WORKSPACE_INTEGRATION, _BINDING_KIND_WORKSPACE, shared_id)] -def _resolve_clear_cwd_binding_target( - cwd: Path, - integration: str | None, -) -> tuple[list[ScopeBindingKey], str | None, str | None, bool]: - if ( - integration is not None - and integration != SHARED_WORKSPACE_INTEGRATION - and integration not in _HOST_WORKSPACE_INTEGRATIONS - ): +def _resolve_clear_cwd_binding_target(cwd: Path, integration: str | None) -> list[ScopeBindingKey]: + target = integration or SHARED_WORKSPACE_INTEGRATION + if target != SHARED_WORKSPACE_INTEGRATION and target not in _HOST_WORKSPACE_INTEGRATIONS: raise typer.BadParameter( # noqa: TRY003 "Unsupported workspace integration; use --external-id instead.", param_hint="--integration" ) - existing_root, root_source = describe_workspace_root(str(cwd)) - if existing_root is not None: - shared_root, _ = workspace_locations(str(cwd), git_root=True)[0] - shared_id = workspace_identity(shared_root) - canonical_root = existing_root - exists = True - else: - shared_id, canonical_root, exists = best_effort_workspace_identity(str(cwd)) - root_source = "missing_directory" - clear_keys = ( - [_binding_key(SHARED_WORKSPACE_INTEGRATION, _BINDING_KIND_WORKSPACE, shared_id)] - if shared_id is not None - else [] - ) - if integration == SHARED_WORKSPACE_INTEGRATION: - return clear_keys, canonical_root, root_source, exists - target_hosts = sorted(_HOST_WORKSPACE_INTEGRATIONS) if integration is None else [integration] - git_root_host_path = workspace_locations(str(cwd), git_root=True)[0][1] if exists else str(cwd) - for host_name in target_hosts: - host_dir = (git_root_host_path or str(cwd)) if host_name in _GIT_ROOT_WORKSPACE_INTEGRATIONS else str(cwd) - for legacy_id in _legacy_host_clear_external_ids(host_dir, host_name): - clear_keys.append(_binding_key(host_name, _BINDING_KIND_WORKSPACE, legacy_id)) - return clear_keys, canonical_root, root_source, exists + 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=target in _GIT_ROOT_WORKSPACE_INTEGRATIONS)[0] + shared_id = workspace_identity(shared_root) + if shared_id is None: + raise typer.BadParameter("Workspace path cannot be encoded as UTF-8.", param_hint="--cwd") # noqa: TRY003 + keys = [_binding_key(SHARED_WORKSPACE_INTEGRATION, _BINDING_KIND_WORKSPACE, shared_id)] + if target != SHARED_WORKSPACE_INTEGRATION and host_path is not None: + keys.append( + _binding_key(target, _BINDING_KIND_WORKSPACE, _legacy_host_workspace_external_id(host_path, target)) + ) + return keys def _resolve_cli_binding_target( @@ -498,7 +451,7 @@ def _resolve_cli_binding_target( cwd: Path | None, integration: str | None, for_clear: bool = False, -) -> tuple[list[ScopeBindingKey], str | None, str | None, bool]: +) -> list[ScopeBindingKey]: if cwd is not None and external_id is not None: raise typer.BadParameter("--cwd and --external-id cannot be used together") # noqa: TRY003 if cwd is not None: @@ -511,7 +464,7 @@ def _resolve_cli_binding_target( raise typer.BadParameter("Missing option '--kind' (or pass '--cwd' for a workspace binding).") # noqa: TRY003 if external_id is None: raise typer.BadParameter("Missing option '--external-id' (or pass '--cwd' for a workspace binding).") # noqa: TRY003 - return [_binding_key(integration or _DEFAULT_BINDING_INTEGRATION, kind, external_id)], None, None, True + return [_binding_key(integration or _DEFAULT_BINDING_INTEGRATION, kind, external_id)] def _binding_key(integration: str, kind: str, external_id: str) -> ScopeBindingKey: @@ -677,16 +630,9 @@ def set_scope_binding( ) -> None: """Bind one external integration identity or local workspace checkout to a Scope.""" - keys, resolved_root, root_source, _exists = _resolve_cli_binding_target( - kind=kind, external_id=external_id, cwd=cwd, integration=integration - ) + keys = _resolve_cli_binding_target(kind=kind, external_id=external_id, cwd=cwd, integration=integration) request = SetScopeBindingRequest(root=ScopeBinding(key=keys[0], scope_id=scope_id)) asyncio.run(_execute(context, lambda client: client.set_scope_binding(request))) - if cwd is not None and not _options(context).json_output and resolved_root is not None: - typer.echo(f"Workspace root: {resolved_root} ({root_source})") - typer.echo( - "Note: active sessions that pin their Scope at startup (such as Codex and OpenCode) keep their current Scope until a new session starts." - ) @scope_binding_app.command("clear") @@ -699,44 +645,28 @@ def clear_scope_binding( cwd: Annotated[ Path | None, typer.Option( - help=( - "Workspace directory to clear. Without --integration, clears the shared binding and every derivable " - "legacy host workspace binding. Pass --integration shared for shared only, or --integration " - "for shared and that host's." - ) + help="Workspace directory to clear (clears 'shared', plus '' when --integration is given)." ), ] = None, integration: Annotated[ str | None, - typer.Option( - help="Binding integration name. With --cwd, narrows what is cleared; without --cwd, defaults to 'opencode'." - ), + typer.Option(help="Binding integration name (defaults to 'shared' with --cwd, else 'opencode')."), ] = None, ) -> None: """Clear one external integration or local workspace binding.""" - keys, resolved_root, root_source, exists = _resolve_cli_binding_target( + keys = _resolve_cli_binding_target( kind=kind, external_id=external_id, cwd=cwd, integration=integration, for_clear=True ) - cleared_integrations: list[str] = [] async def operation(client: PowerContextClient) -> ClearScopeBindingResponse: cleared = False for key in keys: response = await client.clear_scope_binding(ClearScopeBindingRequest(key=key)) - if response.cleared and key.integration not in cleared_integrations: - cleared_integrations.append(key.integration) cleared = cleared or response.cleared return ClearScopeBindingResponse(cleared=cleared) asyncio.run(_execute(context, operation)) - if cwd is not None and not _options(context).json_output and resolved_root is not None: - if exists: - typer.echo(f"Workspace root: {resolved_root} ({root_source})") - else: - typer.echo(f"Workspace root: {resolved_root} (directory missing; derived from input spelling)") - if cleared_integrations: - typer.echo(f"Cleared workspace bindings: {', '.join(cleared_integrations)}") @dataclass(frozen=True, slots=True) diff --git a/src/powercontext/client/session_import.py b/src/powercontext/client/session_import.py index 5e3d1be6b2..69812e63a5 100644 --- a/src/powercontext/client/session_import.py +++ b/src/powercontext/client/session_import.py @@ -36,8 +36,7 @@ from powercontext.redaction import redact_known_secrets from powercontext_integration_lifecycle.git_worktree import ( SHARED_WORKSPACE_INTEGRATION, - normalize_windows_real_path, - real_workspace_path, + workspace_identity, workspace_locations, ) @@ -571,35 +570,11 @@ def _session_binding_keys(session_id: str | None) -> tuple[ScopeBindingKey, ...] return (ScopeBindingKey(integration="codex", kind="session", external_id=value),) -def best_effort_workspace_identity(path: str) -> tuple[str | None, str, bool]: - """Return ``(shared_identity, canonical_path, exists)`` for ``path``. - - When ``path`` has been removed from disk, canonicalize its deepest existing ancestor and preserve the missing tail - so offline maintenance (``scope binding clear --cwd`` and ``import-sessions``) can still address the binding. - """ - - canonical = real_workspace_path(path) - exists = canonical is not None - if canonical is None: - current = os.path.realpath(os.path.expanduser(path)) - tail: list[str] = [] - while not os.path.isdir(current) and os.path.dirname(current) != current: - tail.insert(0, os.path.basename(current)) - current = os.path.dirname(current) - base = real_workspace_path(current) or current - canonical = normalize_windows_real_path(os.path.join(base, *tail) if tail else base) - try: - return sha256(canonical.encode("utf-8")).hexdigest(), canonical, exists - except UnicodeEncodeError: - return None, canonical, exists - - def _workspace_binding_keys(cwd: str) -> list[ScopeBindingKey]: # Try the shared workspace key ahead of Codex's legacy key at both the checkout and, in a linked worktree, its main. keys: list[ScopeBindingKey] = [] - locations = workspace_locations(cwd, git_root=True) if real_workspace_path(cwd) is not None else [(cwd, cwd)] - for shared_root, host_path in locations: - shared_id, _canonical, _exists = best_effort_workspace_identity(shared_root) + for shared_root, host_path in workspace_locations(cwd, git_root=True): + shared_id = workspace_identity(shared_root) if shared_id is not None: keys.append( ScopeBindingKey( diff --git a/src/powercontext_integration_lifecycle/git_worktree.py b/src/powercontext_integration_lifecycle/git_worktree.py index adbfa465bc..bfd27c7778 100644 --- a/src/powercontext_integration_lifecycle/git_worktree.py +++ b/src/powercontext_integration_lifecycle/git_worktree.py @@ -98,36 +98,17 @@ def workspace_identity(path: str) -> str | None: return hashlib.sha256(encoded).hexdigest() -def _guarded_git_top(cwd: str, top: str | None) -> tuple[str | None, str]: +def _guarded_git_top(cwd: str, top: str | None) -> str | None: if top is None: - return None, "directory" + return None top_real = real_workspace_path(top) if top_real is None: - return None, "directory" - cwd_real = real_workspace_path(cwd) - if cwd_real is not None and cwd_real == top_real: - return top, "git_root" - if os.path.dirname(top_real) == top_real: - return None, "home_guard" - home_real = real_workspace_path("~") - if home_real is not None: - current = home_real - while True: - if current == top_real: - return None, "home_guard" - parent = os.path.dirname(current) - if parent == current: - break - current = parent - return top, "git_root" - - -def describe_workspace_root(cwd: str, *, timeout: float = 2.0) -> tuple[str | None, str]: - """Return ``(canonical_root, root_source)`` for diagnostics and operator CLI output.""" - - raw_top, _git_dir, _common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) - effective_top, source = _guarded_git_top(cwd, raw_top) - return real_workspace_path(effective_top or cwd), source + return None + if top_real != real_workspace_path(cwd) and ( + os.path.dirname(top_real) == top_real or top_real == real_workspace_path("~") + ): + return None + return top def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> list[tuple[str, str | None]]: @@ -141,7 +122,7 @@ def workspace_locations(cwd: str, *, git_root: bool, timeout: float = 2.0) -> li deadline = time.monotonic() + timeout raw_top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) - top, _source = _guarded_git_top(cwd, raw_top) + top = _guarded_git_top(cwd, raw_top) shared_own = top or cwd host_own = (raw_top or cwd) if git_root else cwd if top is None: diff --git a/src/powercontext_integration_lifecycle/scope_binding.py b/src/powercontext_integration_lifecycle/scope_binding.py index 81caab35c8..caddc9eed6 100644 --- a/src/powercontext_integration_lifecycle/scope_binding.py +++ b/src/powercontext_integration_lifecycle/scope_binding.py @@ -30,7 +30,6 @@ from .git_worktree import ( SHARED_WORKSPACE_INTEGRATION, - describe_workspace_root, workspace_identity, workspace_locations, ) @@ -170,15 +169,12 @@ def diagnose_scope_binding( ) -> dict[str, Any]: """Resolve the active Scope and identify which candidate binding key matched (for diagnostics, never hooks).""" - resolved_root, root_source = describe_workspace_root(cwd, timeout=_git_timeout(deadline)) if settings.scope_id is not None: scope_id = resolve_scope_id(host, cwd, session_id=session_id, settings=settings, deadline=deadline) return { "scope_id": scope_id, "source": "explicit", "matched_key": None, - "resolved_root": resolved_root, - "root_source": root_source, } for key in binding_keys(host, cwd, session_id=session_id, deadline=deadline): try: @@ -200,8 +196,6 @@ def diagnose_scope_binding( "scope_id": scope_id, "source": "binding", "matched_key": key, - "resolved_root": resolved_root, - "root_source": root_source, } response = _request_json( "/v1/scope-bindings/resolve", @@ -217,8 +211,6 @@ def diagnose_scope_binding( "scope_id": scope_id, "source": "default", "matched_key": None, - "resolved_root": resolved_root, - "root_source": root_source, } diff --git a/tests/codex_plugin/test_scope_binding.py b/tests/codex_plugin/test_scope_binding.py index 268e7cac28..05c756661e 100644 --- a/tests/codex_plugin/test_scope_binding.py +++ b/tests/codex_plugin/test_scope_binding.py @@ -783,8 +783,6 @@ def request(path, payload, *, host, settings, deadline, method="POST"): "scope_id": "scp_legacy", "source": "binding", "matched_key": legacy_key, - "resolved_root": scope_binding_client.describe_workspace_root(str(tmp_path))[0], - "root_source": "directory", } diff --git a/tests/e2e/test_shared_workspace_scope_binding.py b/tests/e2e/test_shared_workspace_scope_binding.py index be0f3a408e..05b27a40cc 100644 --- a/tests/e2e/test_shared_workspace_scope_binding.py +++ b/tests/e2e/test_shared_workspace_scope_binding.py @@ -115,44 +115,6 @@ def _resolve_ts_hosts(node: str, base_url: str, cwd: Path) -> dict[str, str]: return json.loads(completed.stdout) -def _seed_all_legacy_bindings(http: httpx.Client, checkout: Path, subdir: Path) -> None: - git_root_id = hashlib.sha256(os.fsencode(checkout.resolve())).hexdigest() - zcode_root_id = hashlib.sha256(str(checkout.resolve()).encode("utf-8")).hexdigest() - realpath_sub_id = hashlib.sha256(os.fsencode(subdir.resolve())).hexdigest() - bub_sub_id = hashlib.sha256(str(subdir.resolve()).encode("utf-8")).hexdigest() - kimi_sub_id = hashlib.sha256(os.path.realpath(subdir).encode("utf-8")).hexdigest() - resolved_sub_id = hashlib.sha256(os.path.abspath(subdir).encode("utf-8")).hexdigest() - legacy_seeds = { - "claude-code": git_root_id, - "codex": git_root_id, - "workbuddy": git_root_id, - "zcode": zcode_root_id, - "hermes": realpath_sub_id, - "bub": bub_sub_id, - "kimi-code": kimi_sub_id, - "dsh": resolved_sub_id, - "opencode": resolved_sub_id, - "pi": resolved_sub_id, - } - for host_name, ext_id in legacy_seeds.items(): - scope_resp = http.post( - "/v1/scopes", - json={ - "title": f"legacy-seed-{host_name}", - "summary": "Legacy workspace binding seed", - "idempotency_key": f"legacy-seed-{host_name}", - }, - ) - scope_resp.raise_for_status() - http.put( - "/v1/scope-bindings", - json={ - "key": {"integration": host_name, "kind": "workspace", "external_id": ext_id}, - "scope_id": scope_resp.json()["scope_id"], - }, - ).raise_for_status() - - def test_shared_workspace_binding_resolves_across_all_hosts_and_preserves_legacy_bindings( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, @@ -360,7 +322,6 @@ def resolve_all_hosts(cwd: Path) -> dict[str, str]: ).stdout ) assert zcode_doc["checks"]["scope_probe"]["matched_key"] == "shared:workspace" - assert zcode_doc["checks"]["scope_probe"]["root_source"] == "git_root" kimi_doc = json.loads( subprocess.run( @@ -373,16 +334,14 @@ def resolve_all_hosts(cwd: Path) -> dict[str, str]: ).stdout ) assert kimi_doc["checks"]["scope"]["checks"]["matched_key"] == "shared:workspace" - assert kimi_doc["checks"]["scope"]["checks"]["root_source"] == "git_root" # 3. A linked worktree's own shared binding overrides the main checkout across all hosts. assert run_zcode_scope("bind", worktree_subdir, "--scope-id", worktree_scope)["scope_id"] == worktree_scope assert set(resolve_all_hosts(worktree_subdir).values()) == {worktree_scope} assert set(resolve_all_hosts(subdir).values()) == {main_scope} - # Removing the linked worktree directory from disk still lets offline CLI clear --cwd remove its binding. - shutil.rmtree(layout.worktree) - clear_deleted_wt = CliRunner().invoke( + # Default CLI clear --cwd removes the worktree's shared binding so it falls back to main_scope again. + clear_wt = CliRunner().invoke( create_cli(), [ "--server-url", @@ -395,8 +354,9 @@ def resolve_all_hosts(cwd: Path) -> dict[str, str]: str(layout.worktree), ], ) - assert clear_deleted_wt.exit_code == 0, clear_deleted_wt.output - assert json.loads(clear_deleted_wt.output)["cleared"] is True + assert clear_wt.exit_code == 0, clear_wt.output + assert json.loads(clear_wt.output)["cleared"] is True + assert set(resolve_all_hosts(worktree_subdir).values()) == {main_scope} # 4. Scoped clear (--integration claude-code) clears shared + claude-code while preserving Pi's subdir legacy key. clear_claude = CliRunner().invoke( @@ -419,12 +379,8 @@ def resolve_all_hosts(cwd: Path) -> dict[str, str]: assert run_py_script(CLAUDE_SCRIPT, "--cwd", str(subdir)) == default_scope assert _resolve_ts_hosts(node, base_url, subdir)["pi"] == legacy_pi_scope - # 5. Seed legacy bindings for all 10 workspace hosts and verify default clear --cwd sweeps every one. - _seed_all_legacy_bindings(http, layout.checkout, subdir) - seeded_resolved = resolve_all_hosts(subdir) - assert default_scope not in set(seeded_resolved.values()), seeded_resolved - - clear_all_subdir = CliRunner().invoke( + # 5. Scoped clear (--integration pi) clears Pi's subdir legacy key so every host returns to default_scope. + clear_pi = CliRunner().invoke( create_cli(), [ "--server-url", @@ -433,12 +389,14 @@ def resolve_all_hosts(cwd: Path) -> dict[str, str]: "scope", "binding", "clear", + "--integration", + "pi", "--cwd", str(subdir), ], ) - assert clear_all_subdir.exit_code == 0, clear_all_subdir.output - assert json.loads(clear_all_subdir.output)["cleared"] is True + assert clear_pi.exit_code == 0, clear_pi.output + assert json.loads(clear_pi.output)["cleared"] is True swept_resolved = resolve_all_hosts(subdir) assert set(swept_resolved.values()) == {default_scope}, swept_resolved finally: diff --git a/tests/test_cli_scope.py b/tests/test_cli_scope.py index 2ac79ffdbf..c7a0fabee2 100644 --- a/tests/test_cli_scope.py +++ b/tests/test_cli_scope.py @@ -488,9 +488,9 @@ def test_scope_binding_set_and_clear_with_cwd_manage_shared_and_host_keys( "workspace", checkout_id, ) - assert "Workspace root:" in set_output + assert "scp_repo" in set_output - # Rejects non-shared --integration and non-existent --cwd on set. + # Rejects non-shared --integration and non-existent --cwd on set and clear. bad_host = CliRunner().invoke( create_cli([]), ["scope", "binding", "set", "scp_repo", "--cwd", str(layout.checkout_sub), "--integration", "codex"], @@ -501,6 +501,11 @@ def test_scope_binding_set_and_clear_with_cwd_manage_shared_and_host_keys( ["scope", "binding", "set", "scp_repo", "--cwd", str(tmp_path / "does-not-exist")], ) assert missing_set.exit_code != 0 + missing_clear = CliRunner().invoke( + create_cli([]), + ["scope", "binding", "clear", "--cwd", str(tmp_path / "does-not-exist")], + ) + assert missing_clear.exit_code != 0 clear_client, output = _invoke( monkeypatch, @@ -515,42 +520,14 @@ def test_scope_binding_set_and_clear_with_cwd_manage_shared_and_host_keys( ] assert "Binding cleared." in output - # Default clear --cwd without --integration clears shared plus all 10 legacy host integrations. - clear_all_client, _ = _invoke( + # Default clear --cwd without --integration clears only the shared binding (symmetric with set --cwd). + clear_shared_client, _ = _invoke( monkeypatch, ClearScopeBindingResponse(cleared=True), ["scope", "binding", "clear", "--cwd", str(layout.checkout_sub)], ) - clear_all_calls = [call for call in clear_all_client.calls if isinstance(call, ClearScopeBindingRequest)] - cleared_names = {call.key.integration for call in clear_all_calls} - assert cleared_names == { - "shared", - "bub", - "claude-code", - "codex", - "dsh", - "hermes", - "kimi-code", - "opencode", - "pi", - "workbuddy", - "zcode", - } - - # Deleting a directory still allows offline clear --cwd to derive and clear its shared key. - ephemeral = tmp_path / "ephemeral-worktree" - ephemeral.mkdir() - ephemeral_id = client_cli.workspace_identity(str(ephemeral)) - assert ephemeral_id is not None - ephemeral.rmdir() - deleted_clear_client, deleted_out = _invoke( - monkeypatch, - ClearScopeBindingResponse(cleared=True), - ["scope", "binding", "clear", "--cwd", str(ephemeral), "--integration", "shared"], - ) - deleted_calls = [call for call in deleted_clear_client.calls if isinstance(call, ClearScopeBindingRequest)] - assert [(call.key.integration, call.key.external_id) for call in deleted_calls] == [("shared", ephemeral_id)] - assert "directory missing" in deleted_out + clear_shared_calls = [call for call in clear_shared_client.calls if isinstance(call, ClearScopeBindingRequest)] + assert [(call.key.integration, call.key.external_id) for call in clear_shared_calls] == [("shared", checkout_id)] shared_resolve, _ = _invoke( monkeypatch, @@ -629,10 +606,9 @@ def test_scope_list_forwards_query_with_field(monkeypatch: pytest.MonkeyPatch) - assert client.calls[0] == {"query": "Example", "query_field": "title", "limit": 50, "cursor": None} -def test_scope_binding_clear_help_describes_default_legacy_sweep() -> None: +def test_scope_binding_clear_help_describes_shared_default() -> None: result = CliRunner().invoke(create_cli([]), ["scope", "binding", "clear", "--help"]) assert result.exit_code == 0 cleaned = unstyle(result.output).replace("│", " ") help_text = " ".join(cleaned.split()) - assert "every derivable legacy host workspace binding" in help_text - assert "defaults to 'shared' with --cwd" not in help_text + assert "defaults to 'shared' with --cwd" in help_text diff --git a/tests/test_git_worktree.py b/tests/test_git_worktree.py index 680e96f23b..fecc94f763 100644 --- a/tests/test_git_worktree.py +++ b/tests/test_git_worktree.py @@ -28,9 +28,7 @@ import pytest from powercontext_integration_lifecycle.git_worktree import ( - describe_workspace_root, normalize_windows_real_path, - real_workspace_path, workspace_identity, workspace_locations, workspace_paths, @@ -259,16 +257,9 @@ def test_home_directory_git_repository_does_not_collapse_subdirectories( monkeypatch.setenv("USERPROFILE", str(other_home)) # Subdirectories under a git-initialized $HOME fall back to the directory itself for shared identity. - py_locations = workspace_locations(str(unrelated), git_root=False) - assert py_locations == [(str(unrelated), str(unrelated))] - resolved_root, source = describe_workspace_root(str(unrelated)) - assert resolved_root == real_workspace_path(str(unrelated)) - assert source == "home_guard" - - # Opening $HOME itself still resolves $HOME. - home_root, home_source = describe_workspace_root(str(fake_home)) - assert home_root == real_workspace_path(str(fake_home)) - assert home_source == "git_root" + assert workspace_locations(str(unrelated), git_root=False) == [(str(unrelated), str(unrelated))] + assert workspace_locations(str(unrelated), git_root=True) == [(str(unrelated), str(fake_home))] + assert workspace_locations(str(fake_home), git_root=True) == [(str(fake_home), str(fake_home))] node = shutil.which("node") if node is not None: @@ -278,21 +269,25 @@ def test_home_directory_git_repository_does_not_collapse_subdirectories( "USERPROFILE": str(fake_home if os.name == "nt" else other_home), } script = ( - "const [helper, dir] = process.argv.slice(1);" + "const [helper, subDir, homeDir] = process.argv.slice(1);" "const m = await import(helper);" - "console.log(JSON.stringify({ locs: m.workspaceLocationsSync(dir, false, 2000)," - " desc: m.describeWorkspaceRootSync(dir, 2000) }));" + "console.log(JSON.stringify({" + " subFalse: m.workspaceLocationsSync(subDir, false, 2000)," + " subTrue: m.workspaceLocationsSync(subDir, true, 2000)," + " homeTrue: m.workspaceLocationsSync(homeDir, true, 2000)" + "}));" ) out = json.loads( subprocess.check_output( - [node, "--input-type=module", "-e", script, JAVASCRIPT_HELPER.as_uri(), str(unrelated)], + [node, "--input-type=module", "-e", script, JAVASCRIPT_HELPER.as_uri(), str(unrelated), str(fake_home)], env=env, text=True, timeout=15, ) ) - assert out["locs"] == [[str(unrelated), str(unrelated)]] - assert out["desc"] == [resolved_root, "home_guard"] + assert [[os.path.normpath(p) for p in pair] for pair in out["subFalse"]] == [[str(unrelated), str(unrelated)]] + assert [[os.path.normpath(p) for p in pair] for pair in out["subTrue"]] == [[str(unrelated), str(fake_home)]] + assert [[os.path.normpath(p) for p in pair] for pair in out["homeTrue"]] == [[str(fake_home), str(fake_home)]] def test_python_and_javascript_normalize_windows_drive_and_extended_prefixes() -> None: