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/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/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/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/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/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/en/rfcs/2988-shared-workspace-scope-bindings.md b/docs/en/rfcs/2988-shared-workspace-scope-bindings.md new file mode 100644 index 0000000000..8dbe2a9235 --- /dev/null +++ b/docs/en/rfcs/2988-shared-workspace-scope-bindings.md @@ -0,0 +1,132 @@ +--- +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#2988](https://github.com/oceanbase/powercontext/pull/2988) +- 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; `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`). + +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 (expanding a leading `~` when applicable): + +```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 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) +``` + +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` 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). + +## 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 and session interaction + +`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`. + +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, 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, 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`. + +# 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 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` 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). + +# 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/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/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/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/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/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/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/docs/zh/rfcs/2988-shared-workspace-scope-bindings.md b/docs/zh/rfcs/2988-shared-workspace-scope-bindings.md new file mode 100644 index 0000000000..aa07361786 --- /dev/null +++ b/docs/zh/rfcs/2988-shared-workspace-scope-bindings.md @@ -0,0 +1,131 @@ +--- +title: "RFC 2988:跨宿主共享工作区 Scope 绑定" +description: "定义统一的本地工作区身份规则与共享绑定命名空间,使同一本地检出目录只需绑定一次即可在所有 PowerContext 宿主集成间生效,同时兼容既有按宿主隔离的旧绑定。" +--- + +- Proposal Name: `shared_workspace_scope_bindings` +- Start Date: 2026-12-02 +- 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 + +在不改动 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", )`,所有已升级宿主均会优先命中该共享绑定并覆盖旧的宿主级绑定。 +- 在宿主中清除工作区绑定会同时删除该检出目录的共享绑定与当前宿主的旧工作区绑定,避免清除后旧绑定重新生效;运行 `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`)。 + +遵循 [RFC 1345](1345_scope_organization_and_agent_integration.md) 约束,工作区键仅用于查找既有绑定,绝不直接派生或自动创建 `scope_id`。PowerContext MCP 服务端点永远不自行计算工作区键,由宿主层利用每次事件自带的工作目录解析并注入 `scope_id`。 + +# Reference-level explanation + +## 1. 规范化工作区身份 + +给定宿主为当前会话上报的目录 `dir`(存在前导 `~` 时先展开): + +```text +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` 在磁盘上不是已存在的目录,或其规范路径无法按严格 UTF-8 编码,则宿主在该位置不发送 `shared` 工作区键,其余候选键照常发送。 + +- 同一检出目录内的所有子目录共享同一个 `root`。在 Git 工作树之外,每个目录各自构成独立工作区。Git submodule 上报其自身工作树顶层,作为独立工作区处理。 +- 家目录与文件系统根目录守卫可防止用户在家目录执行 `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+ 标准库。 + +## 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`。 + +Codex 与 OpenCode 在未配置显式 Scope 时会将新会话首次解析出的 Scope 写入 `(host, "session", session_id)`。由于会话绑定排在工作区绑定之前,在会话中途修改工作区绑定不会改变已钉住的旧会话,新开启的会话将自动命中新的工作区绑定。 + +## 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`(与 `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`。 + +# 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 and boundaries + +- **多机或容器相同挂载路径边界**:工作区身份仅哈希本地检出目录规范路径,不引入机器 ID。当多台机器或多个 devcontainer 在完全相同的路径(例如 `/workspaces/app`)挂载仓库并连接同一个 PowerContext Server 时,它们会共享该路径对应的工作区绑定;不同路径仍保持独立。 +- **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 测试任务)。 + +# Future possibilities + +若未来运维场景需要在不设置进程级环境变量 `POWERCONTEXT__SCOPE_ID` 的前提下,仅针对单个检出目录为特定宿主指定独立覆盖绑定,可在 `("shared", "workspace", ...)` 之前引入新的键类型(例如 `kind = "workspace_override"`),无需迁移任何存量绑定。 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..e4f76a4cbd 100644 --- a/integrations/bub/src/powercontext_bub/_git_worktree.py +++ b/integrations/bub/src/powercontext_bub/_git_worktree.py @@ -22,11 +22,14 @@ from __future__ import annotations +import hashlib import os import subprocess +import sys 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 +39,111 @@ _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 _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) + + +def workspace_identity(path: str) -> str | None: + """Return the lowercase hex SHA-256 of the UTF-8 canonical real path of existing directory ``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() + + +def _guarded_git_top(cwd: str, top: str | None) -> str | None: + if top is None: + return None + top_real = real_workspace_path(top) + if top_real is None: + 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]]: + """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 (unless guarded by home/filesystem-root rules), + or ``cwd`` outside Git, so every host derives the same shared workspace key. When the shared guard blocks Git root + climbing in a linked worktree, the main-checkout fallback still preserves ``host_path`` with an empty + ``shared_root``. ``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 + raw_top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + top = _guarded_git_top(cwd, raw_top) + shared_own = top or cwd + host_own = (raw_top or cwd) if git_root else cwd + if raw_top is None: + return [(shared_own, host_own)] + main_root = _main_worktree_root(raw_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, raw_top, main_root) + if top is None: + return [(shared_own, host_own), ("", host_main)] if host_main is not None else [(shared_own, host_own)] + 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,22 +161,20 @@ 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: """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. @@ -76,7 +182,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): @@ -94,9 +201,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 +209,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..9b5371bdb1 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,47 @@ 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 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): + 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 | None: + if not workspace: + return None + identity = workspace_identity(str(Path(workspace).expanduser())) + if identity is None: + return None + return ScopeBindingKey( + integration=SHARED_WORKSPACE_INTEGRATION, + kind="workspace", + external_id=identity, + ) -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/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 103c5fbde9..e4f76a4cbd 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,14 @@ from __future__ import annotations +import hashlib import os import subprocess +import sys 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 +39,111 @@ _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 _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) + + +def workspace_identity(path: str) -> str | None: + """Return the lowercase hex SHA-256 of the UTF-8 canonical real path of existing directory ``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() + + +def _guarded_git_top(cwd: str, top: str | None) -> str | None: + if top is None: + return None + top_real = real_workspace_path(top) + if top_real is None: + 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]]: + """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 (unless guarded by home/filesystem-root rules), + or ``cwd`` outside Git, so every host derives the same shared workspace key. When the shared guard blocks Git root + climbing in a linked worktree, the main-checkout fallback still preserves ``host_path`` with an empty + ``shared_root``. ``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 + raw_top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + top = _guarded_git_top(cwd, raw_top) + shared_own = top or cwd + host_own = (raw_top or cwd) if git_root else cwd + if raw_top is None: + return [(shared_own, host_own)] + main_root = _main_worktree_root(raw_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, raw_top, main_root) + if top is None: + return [(shared_own, host_own), ("", host_main)] if host_main is not None else [(shared_own, host_own)] + 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,22 +161,20 @@ 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: """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. @@ -76,7 +182,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): @@ -94,9 +201,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 +209,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..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,3 +41,4 @@ class HostProfile: prompt_id_field: str diagnostics: DiagnosticThrottle bootstrap_state: BootstrapState + 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 2f4226108a..a81bfef59e 100644 --- a/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/scope_binding.py +++ b/integrations/claude-code/plugins/powercontext/powercontext_lifecycle/scope_binding.py @@ -31,7 +31,11 @@ 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 +137,84 @@ 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: 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 + 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 +226,19 @@ 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)): + 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 @@ -177,13 +250,25 @@ 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] + key = shared_workspace_key(shared_root) + if key is None: + raise ScopeBindingError + return key + - return _workspace_key(host, workspace_paths(cwd, git_root=True, timeout=_git_timeout(deadline))[0]) +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]: - external_id = sha256(os.fsencode(Path(path).resolve(strict=False))).hexdigest() + external_id = sha256(os.fsencode(Path(path).expanduser().resolve())).hexdigest() return {"integration": host.integration, "kind": "workspace", "external_id": external_id} 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/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 103c5fbde9..e4f76a4cbd 100644 --- a/integrations/codex/plugins/powercontext/powercontext_lifecycle/git_worktree.py +++ b/integrations/codex/plugins/powercontext/powercontext_lifecycle/git_worktree.py @@ -22,11 +22,14 @@ from __future__ import annotations +import hashlib import os import subprocess +import sys 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 +39,111 @@ _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 _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) + + +def workspace_identity(path: str) -> str | None: + """Return the lowercase hex SHA-256 of the UTF-8 canonical real path of existing directory ``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() + + +def _guarded_git_top(cwd: str, top: str | None) -> str | None: + if top is None: + return None + top_real = real_workspace_path(top) + if top_real is None: + 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]]: + """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 (unless guarded by home/filesystem-root rules), + or ``cwd`` outside Git, so every host derives the same shared workspace key. When the shared guard blocks Git root + climbing in a linked worktree, the main-checkout fallback still preserves ``host_path`` with an empty + ``shared_root``. ``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 + raw_top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + top = _guarded_git_top(cwd, raw_top) + shared_own = top or cwd + host_own = (raw_top or cwd) if git_root else cwd + if raw_top is None: + return [(shared_own, host_own)] + main_root = _main_worktree_root(raw_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, raw_top, main_root) + if top is None: + return [(shared_own, host_own), ("", host_main)] if host_main is not None else [(shared_own, host_own)] + 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,22 +161,20 @@ 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: """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. @@ -76,7 +182,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): @@ -94,9 +201,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 +209,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..c4ffae939b 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 = False diff --git a/integrations/codex/plugins/powercontext/powercontext_lifecycle/scope_binding.py b/integrations/codex/plugins/powercontext/powercontext_lifecycle/scope_binding.py index 2f4226108a..a81bfef59e 100644 --- a/integrations/codex/plugins/powercontext/powercontext_lifecycle/scope_binding.py +++ b/integrations/codex/plugins/powercontext/powercontext_lifecycle/scope_binding.py @@ -31,7 +31,11 @@ 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 +137,84 @@ 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: 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 + 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 +226,19 @@ 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)): + 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 @@ -177,13 +250,25 @@ 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] + key = shared_workspace_key(shared_root) + if key is None: + raise ScopeBindingError + return key + - return _workspace_key(host, workspace_paths(cwd, git_root=True, timeout=_git_timeout(deadline))[0]) +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]: - external_id = sha256(os.fsencode(Path(path).resolve(strict=False))).hexdigest() + external_id = sha256(os.fsencode(Path(path).expanduser().resolve())).hexdigest() return {"integration": host.integration, "kind": "workspace", "external_id": external_id} 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/dsh/plugins/powercontext/lib/index.js b/integrations/dsh/plugins/powercontext/lib/index.js index 58432c8f86..fa43b5520d 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 } 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,286 @@ 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 OS-canonical real path of an existing `directory`, or `undefined` when unavailable. */ +function realWorkspacePath(directory) { + if (!directory) return void 0; + let expanded = directory; + if (expanded === "~" || expanded.startsWith("~/") || expanded.startsWith("~\\")) { + const home = homedir(); + expanded = expanded === "~" ? home : join(home, expanded.slice(2)); + } + const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded; + try { + 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 UTF-8 canonical real path of an existing `directory`. */ +function workspaceIdentity(directory) { + const canonical = realWorkspacePath(directory); + if (canonical === void 0) return void 0; + if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?= SHARED_KEY_CACHE_LIMIT) { + const oldest = sharedKeys.keys().next().value; + if (oldest !== void 0) sharedKeys.delete(oldest); + } + sharedKeys.set(cwd, key$1); + return key$1; +} +function sharedWorkspaceBindingKey(cwd) { + if (!sharedKeys.has(cwd)) { + const [sharedRoot = cwd] = workspaceLocationsSync(cwd, false, GIT_TIMEOUT_MS)[0] ?? [cwd]; + const externalId = workspaceIdentity(sharedRoot); + return cacheSharedWorkspaceKey(cwd, externalId === void 0 ? void 0 : { + integration: SHARED_WORKSPACE_INTEGRATION, + kind: "workspace", + external_id: externalId + }); + } + return sharedKeys.get(cwd); +} +function legacyWorkspaceBindingKey(cwd) { + return { + integration: "dsh", + kind: "workspace", + external_id: createHash("sha256").update(resolve(cwd)).digest("hex") + }; +} +/** Return the workspace keys that resolution tries in order, shared before legacy at both checkout levels. */ +async function workspaceBindingKeys(cwd) { + const keys = []; + const locations = await workspaceLocations(cwd, false, GIT_TIMEOUT_MS); + let ownSharedKey; + for (const [index, [sharedRoot = cwd, hostPath]] of locations.entries()) { + const externalId = workspaceIdentity(sharedRoot); + if (externalId !== void 0) { + const sharedKey = { + integration: SHARED_WORKSPACE_INTEGRATION, + kind: "workspace", + external_id: externalId + }; + if (index === 0) ownSharedKey = sharedKey; + keys.push(sharedKey); + } + if (hostPath !== void 0) keys.push(legacyWorkspaceBindingKey(hostPath)); + } + cacheSharedWorkspaceKey(cwd, ownSharedKey); + return keys; +} +function formatScopeRouting(scopeId, cwd) { + const workspace = sessionCwd(cwd); + 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)}.`, + 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 +3229,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 +3695,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..1d8c418944 100644 --- a/integrations/dsh/plugins/powercontext/src/git-worktree.ts +++ b/integrations/dsh/plugins/powercontext/src/git-worktree.ts @@ -18,10 +18,14 @@ // Edit the source and run `make integration-lifecycle` instead. import { execFile, execFileSync } from 'node:child_process' -import { realpathSync } from 'node:fs' +import { createHash } from 'node:crypto' +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' +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,42 +54,144 @@ 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 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 = homedir() + expanded = expanded === '~' ? home : join(home, expanded.slice(2)) + } + const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded + try { + const resolved = realpathSync.native(input) + if (!statSync(resolved).isDirectory()) return undefined + return normalizeWindowsRealPath(resolved) + } catch { + return undefined + } +} + +/** 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 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 [rawTop = '', gitDir = '', common = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) + const top = guardedGitTop(directory, rawTop) + const sharedOwn = top || directory + const hostOwn = gitRoot ? (rawTop || directory) : directory + if (!rawTop) return [[sharedOwn, hostOwn]] + const mainRoot = mainWorktreeRoot(rawTop, 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] + 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, rawTop, mainRoot) + if (!top) return hostMain === undefined ? [[sharedOwn, hostOwn]] : [[sharedOwn, hostOwn], ['', hostMain]] + return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] +} + +/** 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 [rawTop = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) + const top = guardedGitTop(directory, rawTop) + const sharedOwn = top || directory + const hostOwn = gitRoot ? (rawTop || directory) : directory + if (!rawTop) return [[sharedOwn, hostOwn]] + const mainRoot = mainWorktreeRoot(rawTop, gitDir, common) + if (mainRoot === undefined) return [[sharedOwn, hostOwn]] + 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, rawTop, mainRoot) + if (!top) return hostMain === undefined ? [[sharedOwn, hostOwn]] : [[sharedOwn, hostOwn], ['', hostMain]] + 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 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 bare = gitOutputSync(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) - return bare.trim() === 'false' ? [first, main] : [first] + const result = [] + for (const [, hostPath] of workspaceLocationsSync(directory, gitRoot, timeout)) { + if (hostPath !== undefined) result.push(hostPath) + } + 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 { @@ -104,14 +210,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) diff --git a/integrations/dsh/plugins/powercontext/src/scope.ts b/integrations/dsh/plugins/powercontext/src/scope.ts index 1c2fdaa3e3..32576081a1 100644 --- a/integrations/dsh/plugins/powercontext/src/scope.ts +++ b/integrations/dsh/plugins/powercontext/src/scope.ts @@ -17,19 +17,55 @@ 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 +const SHARED_KEY_CACHE_LIMIT = 256 +const sharedKeys = new Map() -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 { +function cacheSharedWorkspaceKey(cwd: string, key: ScopeBindingKey | undefined): ScopeBindingKey | undefined { + if (sharedKeys.has(cwd)) { + sharedKeys.delete(cwd) + } else if (sharedKeys.size >= SHARED_KEY_CACHE_LIMIT) { + const oldest = sharedKeys.keys().next().value + if (oldest !== undefined) sharedKeys.delete(oldest) + } + sharedKeys.set(cwd, key) + return key +} + +export function sharedWorkspaceBindingKey(cwd: string): ScopeBindingKey | undefined { + if (!sharedKeys.has(cwd)) { + const [sharedRoot = cwd] = workspaceLocationsSync(cwd, false, GIT_TIMEOUT_MS)[0] ?? [cwd] + const externalId = workspaceIdentity(sharedRoot) + return cacheSharedWorkspaceKey( + cwd, + externalId === undefined + ? undefined + : { + integration: SHARED_WORKSPACE_INTEGRATION, + kind: 'workspace', + external_id: externalId, + }, + ) + } + return sharedKeys.get(cwd) +} + +export function legacyWorkspaceBindingKey(cwd: string): ScopeBindingKey { return { integration: 'dsh', kind: 'workspace', @@ -37,14 +73,31 @@ 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. */ +/** 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[] = [] + const locations = await workspaceLocations(cwd, false, GIT_TIMEOUT_MS) + let ownSharedKey: ScopeBindingKey | undefined + for (const [index, [sharedRoot = cwd, hostPath]] of locations.entries()) { + const externalId = workspaceIdentity(sharedRoot) + if (externalId !== undefined) { + const sharedKey: ScopeBindingKey = { + integration: SHARED_WORKSPACE_INTEGRATION, + kind: 'workspace', + external_id: externalId, + } + if (index === 0) ownSharedKey = sharedKey + keys.push(sharedKey) + } + if (hostPath !== undefined) keys.push(legacyWorkspaceBindingKey(hostPath)) + } + cacheSharedWorkspaceKey(cwd, ownSharedKey) + return keys } export function formatScopeRouting(scopeId: string, cwd?: string): string { const workspace = sessionCwd(cwd) - const bindingKey = workspace ? workspaceBindingKey(workspace) : undefined + const bindingKey = workspace ? sharedWorkspaceBindingKey(workspace) : undefined 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/tests/scope.spec.ts b/integrations/dsh/plugins/powercontext/tests/scope.spec.ts index 4692ece264..d12345f5c1 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 } { @@ -51,18 +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 - - 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(1) - expect(input.binding_keys[0]).toMatchObject({ integration: 'dsh', kind: 'workspace' }) - expect(input.binding_keys[0].external_id).not.toContain('/workspace') + 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, 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 () => { @@ -85,28 +91,34 @@ 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 }) } }) - 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') @@ -117,10 +129,64 @@ 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 { 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 }) + } + }) + + it('refreshes the advertised workspace key when resolution detects a new Git root', async () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), 'pc-dsh-git-init-'))) + try { + const project = join(root, 'project') + const api = join(project, 'packages', 'api') + mkdirSync(api, { recursive: true }) + const bindings = new Map() + const keyOf = (key: { integration: string; external_id: string }) => `${key.integration}:${key.external_id}` + const request = vi.fn(async (_operation: string, input: BindingInput) => ({ + value: { + scope_id: input.binding_keys.map(key => bindings.get(keyOf(key))).find(Boolean) ?? 'default', + }, + })) + + await expect(resolveScopeId({ request } as never, api)).resolves.toBe('default') + expect(formatScopeRouting('default', api)).toContain(pathHash(api)) + + execFileSync('git', ['init', '-q', project], { stdio: 'ignore' }) + await expect(resolveScopeId({ request } as never, api)).resolves.toBe('default') + const refreshed = formatScopeRouting('default', api) + expect(refreshed).toContain(pathHash(project)) + expect(refreshed).not.toContain(pathHash(api)) + + bindings.set(`shared:${pathHash(project)}`, 'project-scope') + await expect(resolveScopeId({ request } as never, api)).resolves.toBe('project-scope') + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) }) diff --git a/integrations/hermes/plugins/powercontext/git_worktree.py b/integrations/hermes/plugins/powercontext/git_worktree.py index 103c5fbde9..e4f76a4cbd 100644 --- a/integrations/hermes/plugins/powercontext/git_worktree.py +++ b/integrations/hermes/plugins/powercontext/git_worktree.py @@ -22,11 +22,14 @@ from __future__ import annotations +import hashlib import os import subprocess +import sys 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 +39,111 @@ _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 _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) + + +def workspace_identity(path: str) -> str | None: + """Return the lowercase hex SHA-256 of the UTF-8 canonical real path of existing directory ``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() + + +def _guarded_git_top(cwd: str, top: str | None) -> str | None: + if top is None: + return None + top_real = real_workspace_path(top) + if top_real is None: + 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]]: + """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 (unless guarded by home/filesystem-root rules), + or ``cwd`` outside Git, so every host derives the same shared workspace key. When the shared guard blocks Git root + climbing in a linked worktree, the main-checkout fallback still preserves ``host_path`` with an empty + ``shared_root``. ``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 + raw_top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + top = _guarded_git_top(cwd, raw_top) + shared_own = top or cwd + host_own = (raw_top or cwd) if git_root else cwd + if raw_top is None: + return [(shared_own, host_own)] + main_root = _main_worktree_root(raw_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, raw_top, main_root) + if top is None: + return [(shared_own, host_own), ("", host_main)] if host_main is not None else [(shared_own, host_own)] + 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,22 +161,20 @@ 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: """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. @@ -76,7 +182,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): @@ -94,9 +201,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 +209,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..18b82ef37c 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,17 @@ def _precompress_snapshot_after_capture( return captured_fingerprints +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": identity, + } + + 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 +689,45 @@ 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): + 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: - 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] + 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 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 + 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): + 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 +738,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/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..d9b6e17d24 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 @@ -32,24 +32,38 @@ try { const settings = loadSettings() const signal = AbortSignal.timeout(4000) if (action !== 'resolve') { - const key = workspaceKey(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 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 + let completed = 0 + 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 (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 + 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 + completed += 1 } - 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..f0567b8e6c 100644 --- a/integrations/kimi-code/plugins/powercontext/shared/git-worktree.mjs +++ b/integrations/kimi-code/plugins/powercontext/shared/git-worktree.mjs @@ -18,10 +18,14 @@ // Edit the source and run `make integration-lifecycle` instead. import { execFile, execFileSync } from 'node:child_process' -import { realpathSync } from 'node:fs' +import { createHash } from 'node:crypto' +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' +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,42 +54,144 @@ 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 OS-canonical real path of an existing `directory`, or `undefined` when unavailable. */ +export function realWorkspacePath(directory) { + if (!directory) return undefined + let expanded = directory + if (expanded === '~' || expanded.startsWith('~/') || expanded.startsWith('~\\')) { + const home = homedir() + expanded = expanded === '~' ? home : join(home, expanded.slice(2)) + } + const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded + try { + const resolved = realpathSync.native(input) + if (!statSync(resolved).isDirectory()) return undefined + return normalizeWindowsRealPath(resolved) + } catch { + return undefined + } +} + +/** 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 = [] @@ -591,34 +592,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..fda2906bbf 100644 --- a/integrations/lifecycle/git-worktree.ts +++ b/integrations/lifecycle/git-worktree.ts @@ -15,10 +15,14 @@ */ import { execFile, execFileSync } from 'node:child_process' -import { realpathSync } from 'node:fs' +import { createHash } from 'node:crypto' +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' +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,42 +51,144 @@ 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 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 = homedir() + expanded = expanded === '~' ? home : join(home, expanded.slice(2)) + } + const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded + try { + const resolved = realpathSync.native(input) + if (!statSync(resolved).isDirectory()) return undefined + return normalizeWindowsRealPath(resolved) + } catch { + return undefined + } +} + +/** 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 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 [rawTop = '', gitDir = '', common = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) + const top = guardedGitTop(directory, rawTop) + const sharedOwn = top || directory + const hostOwn = gitRoot ? (rawTop || directory) : directory + if (!rawTop) return [[sharedOwn, hostOwn]] + const mainRoot = mainWorktreeRoot(rawTop, 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] + 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, rawTop, mainRoot) + if (!top) return hostMain === undefined ? [[sharedOwn, hostOwn]] : [[sharedOwn, hostOwn], ['', hostMain]] + return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] +} + +/** 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 [rawTop = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) + const top = guardedGitTop(directory, rawTop) + const sharedOwn = top || directory + const hostOwn = gitRoot ? (rawTop || directory) : directory + if (!rawTop) return [[sharedOwn, hostOwn]] + const mainRoot = mainWorktreeRoot(rawTop, gitDir, common) + if (mainRoot === undefined) return [[sharedOwn, hostOwn]] + 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, rawTop, mainRoot) + if (!top) return hostMain === undefined ? [[sharedOwn, hostOwn]] : [[sharedOwn, hostOwn], ['', hostMain]] + 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 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 bare = gitOutputSync(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) - return bare.trim() === 'false' ? [first, main] : [first] + const result = [] + for (const [, hostPath] of workspaceLocationsSync(directory, gitRoot, timeout)) { + if (hostPath !== undefined) result.push(hostPath) + } + 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 { @@ -101,14 +207,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) diff --git a/integrations/opencode/plugins/powercontext/lib/index.js b/integrations/opencode/plugins/powercontext/lib/index.js index 10549e91fc..8cd6973c00 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"; @@ -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,28 +2519,89 @@ 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 OS-canonical real path of an existing `directory`, or `undefined` when unavailable. */ +function realWorkspacePath(directory) { + if (!directory) return void 0; + let expanded = directory; + if (expanded === "~" || expanded.startsWith("~/") || expanded.startsWith("~\\")) { + const home = homedir(); + expanded = expanded === "~" ? home : join(home, expanded.slice(2)); + } + const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded; + try { + 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 UTF-8 canonical real path of an existing `directory`. */ +function workspaceIdentity(directory) { + const canonical = realWorkspacePath(directory); + if (canonical === void 0) return void 0; + if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { +/** 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 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 = homedir() + expanded = expanded === '~' ? home : join(home, expanded.slice(2)) + } + const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded + try { + const resolved = realpathSync.native(input) + if (!statSync(resolved).isDirectory()) return undefined + return normalizeWindowsRealPath(resolved) + } catch { + return undefined + } +} + +/** 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 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 [rawTop = '', gitDir = '', common = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) + const top = guardedGitTop(directory, rawTop) + const sharedOwn = top || directory + const hostOwn = gitRoot ? (rawTop || directory) : directory + if (!rawTop) return [[sharedOwn, hostOwn]] + const mainRoot = mainWorktreeRoot(rawTop, 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] + 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, rawTop, mainRoot) + if (!top) return hostMain === undefined ? [[sharedOwn, hostOwn]] : [[sharedOwn, hostOwn], ['', hostMain]] + return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] +} + +/** 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 [rawTop = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) + const top = guardedGitTop(directory, rawTop) + const sharedOwn = top || directory + const hostOwn = gitRoot ? (rawTop || directory) : directory + if (!rawTop) return [[sharedOwn, hostOwn]] + const mainRoot = mainWorktreeRoot(rawTop, gitDir, common) + if (mainRoot === undefined) return [[sharedOwn, hostOwn]] + 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, rawTop, mainRoot) + if (!top) return hostMain === undefined ? [[sharedOwn, hostOwn]] : [[sharedOwn, hostOwn], ['', hostMain]] + 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 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 bare = gitOutputSync(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) - return bare.trim() === 'false' ? [first, main] : [first] + const result = [] + for (const [, hostPath] of workspaceLocationsSync(directory, gitRoot, timeout)) { + if (hostPath !== undefined) result.push(hostPath) + } + 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 { @@ -104,14 +210,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) diff --git a/integrations/opencode/plugins/powercontext/src/scope.ts b/integrations/opencode/plugins/powercontext/src/scope.ts index de6a371f0d..5fdbfff0ff 100644 --- a/integrations/opencode/plugins/powercontext/src/scope.ts +++ b/integrations/opencode/plugins/powercontext/src/scope.ts @@ -17,7 +17,11 @@ 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, +} from './git-worktree.ts' type ScopeBindingKey = { integration: string; kind: string; external_id: string } @@ -27,7 +31,7 @@ export function sessionBindingKey(sessionID: string): ScopeBindingKey { return { integration: 'opencode', kind: 'session', external_id: sessionID } } -export function workspaceBindingKey(cwd: string): ScopeBindingKey { +export function legacyWorkspaceBindingKey(cwd: string): ScopeBindingKey { return { integration: 'opencode', kind: 'workspace', @@ -35,9 +39,21 @@ 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. */ +/** 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)) { + 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 } 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..6a547916d3 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 } { @@ -43,23 +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: '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 () => { @@ -94,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', }) @@ -130,22 +136,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..a8416ecfdc 100644 --- a/integrations/opencode/plugins/powercontext/tests/tui.spec.tsx +++ b/integrations/opencode/plugins/powercontext/tests/tui.spec.tsx @@ -161,6 +161,7 @@ describe('PowerContextTuiPlugin', () => { external_id: 'session-1', }) 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 bd2ac88460..1d8c418944 100644 --- a/integrations/pi/plugins/powercontext/src/git-worktree.ts +++ b/integrations/pi/plugins/powercontext/src/git-worktree.ts @@ -18,10 +18,14 @@ // Edit the source and run `make integration-lifecycle` instead. import { execFile, execFileSync } from 'node:child_process' -import { realpathSync } from 'node:fs' +import { createHash } from 'node:crypto' +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' +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,42 +54,144 @@ 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 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 = homedir() + expanded = expanded === '~' ? home : join(home, expanded.slice(2)) + } + const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded + try { + const resolved = realpathSync.native(input) + if (!statSync(resolved).isDirectory()) return undefined + return normalizeWindowsRealPath(resolved) + } catch { + return undefined + } +} + +/** 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 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 [rawTop = '', gitDir = '', common = ''] = gitPaths(await gitOutput(directory, GIT_ARGUMENTS, timeout)) + const top = guardedGitTop(directory, rawTop) + const sharedOwn = top || directory + const hostOwn = gitRoot ? (rawTop || directory) : directory + if (!rawTop) return [[sharedOwn, hostOwn]] + const mainRoot = mainWorktreeRoot(rawTop, 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] + 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, rawTop, mainRoot) + if (!top) return hostMain === undefined ? [[sharedOwn, hostOwn]] : [[sharedOwn, hostOwn], ['', hostMain]] + return hostMain === undefined ? [[sharedOwn, hostOwn], [mainRoot]] : [[sharedOwn, hostOwn], [mainRoot, hostMain]] +} + +/** 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 [rawTop = '', gitDir = '', common = ''] = gitPaths(gitOutputSync(directory, GIT_ARGUMENTS, timeout)) + const top = guardedGitTop(directory, rawTop) + const sharedOwn = top || directory + const hostOwn = gitRoot ? (rawTop || directory) : directory + if (!rawTop) return [[sharedOwn, hostOwn]] + const mainRoot = mainWorktreeRoot(rawTop, gitDir, common) + if (mainRoot === undefined) return [[sharedOwn, hostOwn]] + 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, rawTop, mainRoot) + if (!top) return hostMain === undefined ? [[sharedOwn, hostOwn]] : [[sharedOwn, hostOwn], ['', hostMain]] + 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 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 bare = gitOutputSync(['-C', directory, '--git-dir', common, ...BARE_ARGUMENTS], deadline - Date.now()) - return bare.trim() === 'false' ? [first, main] : [first] + const result = [] + for (const [, hostPath] of workspaceLocationsSync(directory, gitRoot, timeout)) { + if (hostPath !== undefined) result.push(hostPath) + } + 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 { @@ -104,14 +210,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) diff --git a/integrations/pi/plugins/powercontext/src/scope.ts b/integrations/pi/plugins/powercontext/src/scope.ts index 86387bac1f..08bdce3fef 100644 --- a/integrations/pi/plugins/powercontext/src/scope.ts +++ b/integrations/pi/plugins/powercontext/src/scope.ts @@ -17,13 +17,17 @@ 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, +} 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 legacyWorkspaceBindingKey(cwd: string): ScopeBindingKey { return { integration: 'pi', kind: 'workspace', @@ -31,9 +35,21 @@ 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. */ +/** 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)) { + 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 } 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..abe2d7939f 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 } { @@ -43,18 +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(1) - expect(input.binding_keys[0]).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 () => { @@ -67,22 +73,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/workbuddy/plugins/powercontext/hooks/git_worktree.py b/integrations/workbuddy/plugins/powercontext/hooks/git_worktree.py index 103c5fbde9..e4f76a4cbd 100644 --- a/integrations/workbuddy/plugins/powercontext/hooks/git_worktree.py +++ b/integrations/workbuddy/plugins/powercontext/hooks/git_worktree.py @@ -22,11 +22,14 @@ from __future__ import annotations +import hashlib import os import subprocess +import sys 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 +39,111 @@ _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 _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) + + +def workspace_identity(path: str) -> str | None: + """Return the lowercase hex SHA-256 of the UTF-8 canonical real path of existing directory ``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() + + +def _guarded_git_top(cwd: str, top: str | None) -> str | None: + if top is None: + return None + top_real = real_workspace_path(top) + if top_real is None: + 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]]: + """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 (unless guarded by home/filesystem-root rules), + or ``cwd`` outside Git, so every host derives the same shared workspace key. When the shared guard blocks Git root + climbing in a linked worktree, the main-checkout fallback still preserves ``host_path`` with an empty + ``shared_root``. ``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 + raw_top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + top = _guarded_git_top(cwd, raw_top) + shared_own = top or cwd + host_own = (raw_top or cwd) if git_root else cwd + if raw_top is None: + return [(shared_own, host_own)] + main_root = _main_worktree_root(raw_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, raw_top, main_root) + if top is None: + return [(shared_own, host_own), ("", host_main)] if host_main is not None else [(shared_own, host_own)] + 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,22 +161,20 @@ 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: """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. @@ -76,7 +182,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): @@ -94,9 +201,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 +209,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..4209d015a7 100644 --- a/integrations/workbuddy/plugins/powercontext/scripts/workspace_scope.py +++ b/integrations/workbuddy/plugins/powercontext/scripts/workspace_scope.py @@ -18,12 +18,12 @@ from __future__ import annotations import argparse +import hashlib import json import os 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 +38,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 +188,92 @@ 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: 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 + 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)): + 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 @@ -214,16 +285,27 @@ 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] + key = _shared_workspace_key(shared_root) + if key is None: + raise ScopeBindingError + return key - return _workspace_key(workspace_paths(cwd, git_root=True, timeout=_git_timeout(deadline))[0]) + +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": sha256(os.fsencode(Path(path).resolve(strict=False))).hexdigest(), + "external_id": hashlib.sha256(os.fsencode(Path(path).expanduser().resolve())).hexdigest(), } @@ -376,9 +458,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 +471,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/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..dd96f9146a 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' @@ -42,26 +42,40 @@ 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 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 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 completed = 0 + 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 (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 || + !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 + completed += 1 } - 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..f0567b8e6c 100644 --- a/integrations/zcode/plugins/powercontext/shared/git-worktree.mjs +++ b/integrations/zcode/plugins/powercontext/shared/git-worktree.mjs @@ -18,10 +18,14 @@ // Edit the source and run `make integration-lifecycle` instead. import { execFile, execFileSync } from 'node:child_process' -import { realpathSync } from 'node:fs' +import { createHash } from 'node:crypto' +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' +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,42 +54,144 @@ 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 OS-canonical real path of an existing `directory`, or `undefined` when unavailable. */ +export function realWorkspacePath(directory) { + if (!directory) return undefined + let expanded = directory + if (expanded === '~' || expanded.startsWith('~/') || expanded.startsWith('~\\')) { + const home = homedir() + expanded = expanded === '~' ? home : join(home, expanded.slice(2)) + } + const input = isAbsolute(expanded) ? expanded : process.cwd() + sep + expanded + try { + const resolved = realpathSync.native(input) + if (!statSync(resolved).isDirectory()) return undefined + return normalizeWindowsRealPath(resolved) + } catch { + return undefined + } +} + +/** 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])|(? 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/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..64272acbd6 100644 --- a/src/powercontext/client/cli.py +++ b/src/powercontext/client/cli.py @@ -158,7 +158,12 @@ TopicMemoryProcessingStatus, TopicMemoryProcessingStatusRequest, ) -from powercontext_integration_lifecycle.git_worktree import workspace_paths +from powercontext_integration_lifecycle.git_worktree import ( + SHARED_WORKSPACE_INTEGRATION, + real_workspace_path, + workspace_identity, + workspace_locations, +) HELP_OPTION_NAMES = ("-h", "--help") _ClientResponse: TypeAlias = ( @@ -351,26 +356,118 @@ 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. - - 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 _legacy_host_workspace_external_id(path: str, integration: str) -> str: + expanded = os.path.expanduser(path) + if integration in _RESOLVED_CWD_WORKSPACE_INTEGRATIONS: + 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 _workspace_binding_keys(cwd: Path, integration: str) -> list[ScopeBindingKey]: + """Return the workspace keys that resolution tries in order, matching the host plugin's sequence.""" + + expanded = str(cwd.expanduser()) + if integration == SHARED_WORKSPACE_INTEGRATION: + shared_keys: list[ScopeBindingKey] = [] + for shared_root, _host_path in workspace_locations(expanded, 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" ) - # 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( + expanded, git_root=integration in _GIT_ROOT_WORKSPACE_INTEGRATIONS + ): + 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( + integration, + _BINDING_KIND_WORKSPACE, + _legacy_host_workspace_external_id(host_path, integration), + ) + ) + return keys + + +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", + ) + expanded = str(cwd.expanduser()) + if real_workspace_path(expanded) is None: + raise typer.BadParameter("Workspace directory does not exist.", param_hint="--cwd") # noqa: TRY003 + shared_root, _host_path = workspace_locations(expanded, git_root=True)[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 + return [_binding_key(SHARED_WORKSPACE_INTEGRATION, _BINDING_KIND_WORKSPACE, shared_id)] + + +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" + ) + expanded = str(cwd.expanduser()) + if real_workspace_path(expanded) is None: + raise typer.BadParameter("Workspace directory does not exist.", param_hint="--cwd") # noqa: TRY003 + shared_root, host_path = workspace_locations(expanded, 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( + *, + 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 + 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)] def _binding_key(integration: str, kind: str, external_id: str) -> ScopeBindingKey: @@ -503,12 +600,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 +619,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) - ) + 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))) @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', plus '' when --integration is given)." + ), + ] = 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..69812e63a5 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,27 @@ 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(), - ) - for path in workspace_paths(cwd, git_root=True) - ] + # 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): + shared_id = workspace_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=sha256(os.fsencode(Path(host_path).expanduser().resolve())).hexdigest(), + ) + ) + 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..08dca6eef8 100644 --- a/src/powercontext_integration_lifecycle/git_worktree.py +++ b/src/powercontext_integration_lifecycle/git_worktree.py @@ -19,11 +19,14 @@ from __future__ import annotations +import hashlib import os import subprocess +import sys 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 +36,111 @@ _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 _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) + + +def workspace_identity(path: str) -> str | None: + """Return the lowercase hex SHA-256 of the UTF-8 canonical real path of existing directory ``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() + + +def _guarded_git_top(cwd: str, top: str | None) -> str | None: + if top is None: + return None + top_real = real_workspace_path(top) + if top_real is None: + 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]]: + """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 (unless guarded by home/filesystem-root rules), + or ``cwd`` outside Git, so every host derives the same shared workspace key. When the shared guard blocks Git root + climbing in a linked worktree, the main-checkout fallback still preserves ``host_path`` with an empty + ``shared_root``. ``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 + raw_top, git_dir, common = _git_paths(_git_output(cwd, _ARGUMENTS, timeout)) + top = _guarded_git_top(cwd, raw_top) + shared_own = top or cwd + host_own = (raw_top or cwd) if git_root else cwd + if raw_top is None: + return [(shared_own, host_own)] + main_root = _main_worktree_root(raw_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, raw_top, main_root) + if top is None: + return [(shared_own, host_own), ("", host_main)] if host_main is not None else [(shared_own, host_own)] + 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,22 +158,20 @@ 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: """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. @@ -73,7 +179,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): @@ -91,9 +198,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 +206,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..9570421db9 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 = False diff --git a/src/powercontext_integration_lifecycle/scope_binding.py b/src/powercontext_integration_lifecycle/scope_binding.py index 68ccd241bd..caddc9eed6 100644 --- a/src/powercontext_integration_lifecycle/scope_binding.py +++ b/src/powercontext_integration_lifecycle/scope_binding.py @@ -28,7 +28,11 @@ 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 +134,84 @@ 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: 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 + 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 +223,19 @@ 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)): + 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 @@ -174,13 +247,25 @@ 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] + key = shared_workspace_key(shared_root) + if key is None: + raise ScopeBindingError + return key + - return _workspace_key(host, workspace_paths(cwd, git_root=True, timeout=_git_timeout(deadline))[0]) +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]: - external_id = sha256(os.fsencode(Path(path).resolve(strict=False))).hexdigest() + external_id = sha256(os.fsencode(Path(path).expanduser().resolve())).hexdigest() return {"integration": host.integration, "kind": "workspace", "external_id": external_id} 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..05c756661e 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,44 @@ 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/e2e/test_shared_workspace_scope_binding.py b/tests/e2e/test_shared_workspace_scope_binding.py new file mode 100644 index 0000000000..05b27a40cc --- /dev/null +++ b/tests/e2e/test_shared_workspace_scope_binding.py @@ -0,0 +1,406 @@ +# 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} + + # 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", + base_url, + "--json", + "scope", + "binding", + "clear", + "--cwd", + str(layout.worktree), + ], + ) + 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( + 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 + assert run_py_script(CLAUDE_SCRIPT, "--cwd", str(subdir)) == default_scope + assert _resolve_ts_hosts(node, base_url, subdir)["pi"] == legacy_pi_scope + + # 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", + 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 + swept_resolved = resolve_all_hosts(subdir) + assert set(swept_resolved.values()) == {default_scope}, swept_resolved + 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/fixtures/hook_characterization/claude-code.json b/tests/fixtures/hook_characterization/claude-code.json index b79058389d..5a82e768f8 100644 --- a/tests/fixtures/hook_characterization/claude-code.json +++ b/tests/fixtures/hook_characterization/claude-code.json @@ -407,6 +407,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -512,6 +517,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -633,6 +643,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -761,6 +776,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -946,6 +966,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -1055,6 +1080,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -1143,6 +1173,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -1241,6 +1276,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -1351,6 +1391,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -1453,6 +1498,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -1551,6 +1601,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -1636,6 +1691,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -1744,6 +1804,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -1852,6 +1917,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -1960,6 +2030,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -2068,6 +2143,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -2176,6 +2256,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -2284,6 +2369,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -2392,6 +2482,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -2517,6 +2612,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -2633,6 +2733,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -2735,6 +2840,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -2851,6 +2961,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -3019,6 +3134,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -3127,6 +3247,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -3235,6 +3360,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -3346,6 +3476,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -3497,6 +3632,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -3568,6 +3708,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -3639,6 +3784,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -3713,6 +3863,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -3784,6 +3939,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -3861,6 +4021,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -3963,6 +4128,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -4065,6 +4235,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -4136,6 +4311,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -4232,6 +4412,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -4336,6 +4521,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -4427,6 +4617,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -4501,6 +4696,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -4576,6 +4776,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -4664,6 +4869,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -4730,6 +4940,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -4833,6 +5048,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -4956,6 +5176,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -5040,6 +5265,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -5135,6 +5365,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -5212,6 +5447,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -5289,6 +5529,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -5365,6 +5610,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -5439,6 +5689,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -5502,6 +5757,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -5712,6 +5972,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", @@ -5805,6 +6070,11 @@ "integration": "claude-code", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "claude-code", diff --git a/tests/fixtures/hook_characterization/codex.json b/tests/fixtures/hook_characterization/codex.json index d6d46fdc3f..7018fbbbb8 100644 --- a/tests/fixtures/hook_characterization/codex.json +++ b/tests/fixtures/hook_characterization/codex.json @@ -435,6 +435,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -533,6 +538,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -638,6 +648,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -762,6 +777,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -871,6 +891,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -969,6 +994,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -1076,6 +1106,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -1184,6 +1219,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -1309,6 +1349,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -1421,6 +1466,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -1509,6 +1559,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -1593,6 +1648,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -1718,6 +1778,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -1888,6 +1953,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -1996,6 +2066,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -2104,6 +2179,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -2215,6 +2295,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -2380,6 +2465,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -2451,6 +2541,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -2522,6 +2617,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -2596,6 +2696,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -2667,6 +2772,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -2779,6 +2889,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -2897,6 +3012,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -2975,6 +3095,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -3044,6 +3169,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -3119,6 +3249,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -3228,6 +3363,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -3337,6 +3477,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -3452,6 +3597,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -3554,6 +3704,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -3620,6 +3775,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -3727,6 +3887,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -3868,6 +4033,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -4135,6 +4305,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -4231,6 +4406,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -4297,6 +4477,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -4396,6 +4581,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -4459,6 +4649,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -4522,6 +4717,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -4586,6 +4786,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -4675,6 +4880,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -4763,6 +4973,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", @@ -4850,6 +5065,11 @@ "integration": "codex", "kind": "session" }, + { + "external_id": "$WORKSPACE_KEY", + "integration": "shared", + "kind": "workspace" + }, { "external_id": "$WORKSPACE_KEY", "integration": "codex", 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..8e78d52dab 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,8 +218,11 @@ 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 = 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), ("opencode", "workspace", _workspace_external_id(workspace)), ] assert "scp_resolved" in output @@ -416,35 +420,193 @@ 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, 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(), + 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 external_ids(layout.checkout_sub) == [hashlib.sha256(os.fsencode(checkout)).hexdigest()] - assert len(external_ids(layout.bare_worktree)) == 1 + 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 = client_cli.workspace_identity(str(layout.checkout)) + assert checkout_id is not None + sub_id = hashlib.sha256(os.fsencode(layout.checkout_sub)).hexdigest() + client, set_output = _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, + ) + assert "scp_repo" in set_output + + # 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"], + ) + 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 + 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, + 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 + + # 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_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, + _descriptor(), + ["scope", "resolve", "--integration", "shared", "--cwd", str(layout.worktree_sub)], + ) + 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", worktree_id), + ("shared", checkout_id), + ] + + +def test_scope_binding_set_resolve_and_clear_expand_tilde_before_git_root_discovery( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + git = which("git") + assert git is not None + fake_home = tmp_path.resolve() + repo = fake_home / "pc-review" + sub = repo / "src" + sub.mkdir(parents=True) + subprocess.run([git, "init", "-q", str(repo)], check=True, timeout=10) + monkeypatch.setenv("HOME", str(fake_home)) + monkeypatch.setenv("USERPROFILE", str(fake_home)) + + repo_id = client_cli.workspace_identity(str(repo)) + assert repo_id is not None + tilde_sub = "~/pc-review/src" + + set_client, _ = _invoke( + monkeypatch, + ScopeBinding.model_validate({ + "key": {"integration": "shared", "kind": "workspace", "external_id": repo_id}, + "scope_id": "scp_tilde", + }), + ["scope", "binding", "set", "scp_tilde", "--cwd", tilde_sub], + ) + set_req = set_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", + repo_id, + ) + + abs_resolve, _ = _invoke( + monkeypatch, + _descriptor(), + ["scope", "resolve", "--integration", "codex", "--cwd", str(sub)], + ) + tilde_resolve, _ = _invoke( + monkeypatch, + _descriptor(), + ["scope", "resolve", "--integration", "codex", "--cwd", tilde_sub], + ) + abs_req = abs_resolve.calls[0] + tilde_req = tilde_resolve.calls[0] + assert isinstance(abs_req, ResolveScopeBindingRequest) + assert isinstance(tilde_req, ResolveScopeBindingRequest) + assert [(k.integration, k.external_id) for k in tilde_req.binding_keys] == [ + (k.integration, k.external_id) for k in abs_req.binding_keys + ] + assert abs_req.binding_keys[0].integration == "shared" + assert abs_req.binding_keys[0].external_id == repo_id + + clear_client, _ = _invoke( + monkeypatch, + ClearScopeBindingResponse(cleared=True), + ["scope", "binding", "clear", "--cwd", tilde_sub, "--integration", "codex"], + ) + clear_calls = [call for call in clear_client.calls if isinstance(call, ClearScopeBindingRequest)] + assert clear_calls[0].key.integration == "shared" + assert clear_calls[0].key.external_id == repo_id + assert clear_calls[1].key.integration == "codex" + assert clear_calls[1].key.external_id == hashlib.sha256(os.fsencode(repo.resolve())).hexdigest() def test_scope_resolve_rejects_unknown_workspace_rules(monkeypatch: pytest.MonkeyPatch) -> None: @@ -507,3 +669,11 @@ 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_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 "defaults to 'shared' with --cwd" in help_text diff --git a/tests/test_git_worktree.py b/tests/test_git_worktree.py index 959ee084ec..0ad50e7478 100644 --- a/tests/test_git_worktree.py +++ b/tests/test_git_worktree.py @@ -20,12 +20,19 @@ 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 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 +157,293 @@ 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, *, 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(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 json.loads(completed.stdout.strip()) + + +def test_python_and_javascript_derive_the_same_workspace_identity(layout: GitLayout, tmp_path: Path) -> None: + 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", str(link) + os.sep + "..", link / "missing"]) + 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)) + 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) + + 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. + 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: + 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, subDir, homeDir] = process.argv.slice(1);" + "const m = await import(helper);" + "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), str(fake_home)], + env=env, + text=True, + timeout=15, + ) + ) + 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: + 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)), + ] + + +def test_home_guard_preserves_legacy_main_checkout_fallback_in_linked_worktree( + layout: GitLayout, monkeypatch: pytest.MonkeyPatch +) -> None: + other_home = layout.outside + if os.name == "nt": + monkeypatch.setenv("HOME", str(other_home)) + monkeypatch.setenv("USERPROFILE", str(layout.worktree)) + else: + monkeypatch.setenv("HOME", str(layout.worktree)) + monkeypatch.setenv("USERPROFILE", str(other_home)) + + assert workspace_locations(str(layout.worktree_sub), git_root=True) == [ + (str(layout.worktree_sub), str(layout.worktree)), + ("", str(layout.checkout)), + ] + assert workspace_locations(str(layout.worktree_sub), git_root=False) == [ + (str(layout.worktree_sub), str(layout.worktree_sub)), + ("", str(layout.checkout_sub)), + ] + assert workspace_paths(str(layout.worktree_sub), git_root=True) == [str(layout.worktree), str(layout.checkout)] + assert workspace_paths(str(layout.worktree_sub), git_root=False) == [ + str(layout.worktree_sub), + str(layout.checkout_sub), + ] + + node = shutil.which("node") + if node is not None: + env = { + **os.environ, + "HOME": str(other_home if os.name == "nt" else layout.worktree), + "USERPROFILE": str(layout.worktree if os.name == "nt" else other_home), + } + script = ( + "const [helper, subDir] = process.argv.slice(1);" + "const m = await import(helper);" + "console.log(JSON.stringify({" + " locTrue: await m.workspaceLocations(subDir, true, 2000)," + " locTrueSync: m.workspaceLocationsSync(subDir, true, 2000)," + " locFalse: await m.workspaceLocations(subDir, false, 2000)," + " locFalseSync: m.workspaceLocationsSync(subDir, false, 2000)," + " pathsTrue: await m.workspacePaths(subDir, true, 2000)," + " pathsFalse: await m.workspacePaths(subDir, false, 2000)" + "}));" + ) + out = json.loads( + subprocess.check_output( + [node, "--input-type=module", "-e", script, JAVASCRIPT_HELPER.as_uri(), str(layout.worktree_sub)], + env=env, + text=True, + timeout=15, + ) + ) + + def _norm(pairs: list[list[str]]) -> list[list[str]]: + return [[os.path.normpath(p) if p else "" for p in pair] for pair in pairs] + + expected_true = [[str(layout.worktree_sub), str(layout.worktree)], ["", str(layout.checkout)]] + expected_false = [[str(layout.worktree_sub), str(layout.worktree_sub)], ["", str(layout.checkout_sub)]] + assert _norm(out["locTrue"]) == _norm(out["locTrueSync"]) == expected_true + assert _norm(out["locFalse"]) == _norm(out["locFalseSync"]) == expected_false + assert [os.path.normpath(p) for p in out["pathsTrue"]] == [str(layout.worktree), str(layout.checkout)] + assert [os.path.normpath(p) for p in out["pathsFalse"]] == [ + str(layout.worktree_sub), + str(layout.checkout_sub), + ] + + +def test_legacy_worktree_fallback_preserves_case_spelling_after_case_only_rename( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + if sys.platform != "darwin": + pytest.skip("case-only directory rename check applies to case-insensitive macOS filesystems") + git = shutil.which("git") + assert git is not None + root = tmp_path.resolve() + upper = root / "Checkout" + lower = root / "checkout" + worktree = root / "Worktree" + env = { + **os.environ, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_AUTHOR_NAME": "test", + "GIT_AUTHOR_EMAIL": "test@example.com", + "GIT_COMMITTER_NAME": "test", + "GIT_COMMITTER_EMAIL": "test@example.com", + } + monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1") + subprocess.run([git, "init", "-q", str(upper)], check=True, env=env, timeout=10) + subprocess.run( + [git, "-C", str(upper), "commit", "-q", "--allow-empty", "-m", "init"], check=True, env=env, timeout=10 + ) + subprocess.run([git, "-C", str(upper), "worktree", "add", "-q", str(worktree)], check=True, env=env, timeout=10) + (upper / "sub").mkdir() + worktree_sub = worktree / "sub" + worktree_sub.mkdir() + upper.rename(root / "Checkout-tmp") + (root / "Checkout-tmp").rename(lower) + if not upper.exists(): + pytest.skip("filesystem is case-sensitive") + + expected_legacy = [str(worktree_sub), str(upper / "sub")] + assert workspace_paths(str(worktree_sub), git_root=False) == expected_legacy + node = shutil.which("node") + if node is not None: + assert _javascript(worktree_sub, False) == expected_legacy + assert _javascript_identity(upper) == workspace_identity(str(lower)) 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), + )