Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Fix uninstall cleanup to preserve existing configuration (#4290)
mike-inkeep6aab7a6af1bf
diff --git a/.changeset/safe-uninstall-reset.md b/.changeset/safe-uninstall-reset.mdnew file mode 100644index 000000000..62f204898--- /dev/null+++ b/.changeset/safe-uninstall-reset.md@@ -0,0 +1,14 @@+---+"@inkeep/open-knowledge": minor+"@inkeep/open-knowledge-desktop": minor+---++Make uninstall preserve symlinked configuration files and ignore rules for shared editor settings. Wait for servers to exit before deleting their state, retain enough state to retry incomplete cleanup, and report unresolved integrations as failures. On macOS, finish desktop cleanup after the application exits so shutdown cannot recreate its settings. When removing an agent connection in Settings, preserve the reason for a cleanup failure in the OpenKnowledge log. Honor custom Pi agent directories when removing project trust, and distinguish configuration read failures from invalid syntax during init.++Scripts using `ok deinit` or `ok uninstall` should handle exit code `1` when integration cleanup remains unresolved. With `--yes --json`, those items now appear in `failed[]` instead of `skipped[]`; repair the reported problem and retry. `skipped[]` still covers intentionally preserved entries, including another tool's configuration and dangling shell, editor, or launch config symlinks. A dangling Pi bridge reports a failure. Cleanup also fails for an unreadable, dangling, or cyclic trust store when an owned bridge or recorded grant requires checking it. Bridge setup and cleanup refuse project paths they cannot resolve or access. For a missing project, cleanup checks records under the supplied path and the missing suffix appended to the nearest accessible ancestor's current real path, following healthy directory aliases only for that additional lookup. With no bridge or record at either path, the project is already absent. Known records or an unresolvable or inaccessible ancestor require repairing the project path before retrying. This lookup cannot recover historical symlink targets. Setup also refuses a symlink target that differs from the real directory shown in its approval prompt, before changing the bridge or trust settings. With neither a bridge nor a record and a verifiable project path, the store is unrelated and is not inspected.++For callers of the exported JavaScript API, `probePiBridgeState()` can now return `project: 'unavailable'` with an error. Narrow to `project === 'ready'` before reading `bridge`, `trust`, `bridgeLoadable`, `canonicalCwd`, or `otherExtensions`. `otherExtensions` contains quoted display names with control characters escaped, not raw filenames. `ensurePiBridge()` can now return `bridge: 'refused-project-path'` when the project path cannot be verified or differs from the approved directory; handle that refusal before using the bridge. Custom `EditorMcpTarget` objects with `format: 'file'` must provide a `projectConfigPath` function.++Pi trust updates coordinate with Pi's own file lock and preserve symlinked stores. New trust changes record the previous folder decision so cleanup can restore it, using the real project directory even when opened through a symlink. Every grant made before this release lacks an ownership record and is preserved, including grants made by OpenKnowledge; there is no automatic backfill. Older entries under non-canonical project spellings, such as symlink paths, are also preserved and named when found. Pi does not use those literal keys, and cleanup does not move them to the real-path key. Interrupted setup records also preserve trust because completion cannot be verified, and retries do not reconcile them while the folder remains trusted. To remove an unrecorded or non-canonical grant manually, close Pi and remove only the project's exact-folder key from its `trust.json`; the cleanup message names an entry's key and file when it can inspect that entry. If the project path is already unavailable when cleanup starts and ownership records can be read, cleanup names those records and recorded store locations without claiming those grants still exist. If a later project-path check fails, the affected trust store is left pending with guidance to repair the path and retry. For manual cleanup using a record, inspect the intended destination and restore the previous decision only if you choose to undo a current true entry; remove that key only when there was no previous entry. Once the project's `.ok/` directory is gone, `ok deinit` reports nothing to remove; use that manual cleanup for any retained entries. Other entries, parent-folder decisions, and Pi's global trust default remain intact and may still confer trust.++When other Pi resources still need folder trust, cleanup lists up to three resources and the remaining count, and relinquishes its ownership record where one exists. Removing the retained grant manually may stop Pi from loading those resources. Later cleanup runs will not revoke that grant, even after those resources are removed. When a bridge or record requires trust cleanup, OpenKnowledge checks the currently configured store and saved locations for recorded grants, including custom Pi directories. It reports retained exact keys it finds, including the supplied project spelling when it differs from the real path. Unknown historical stores and aliases are not searched or inferred. Broken trust files also block bridge setup until repaired. The Pi-compatible directory lock coordinates with Pi at the configured path; the separate OpenKnowledge lock coordinates its own writers across symlinks to the same destination.diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex b9da3bb06..4af3d73ac 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -4989,6 +4989,11 @@ Homepage: https://facebook.github.io/react/Copyright (c) 2013-present, Facebook, Inc.+### `[email protected]`+Homepage: https://github.com/moxystudio/node-proper-lockfile++Copyright (c) 2018 Made With MOXY Lda <[email protected]>+### `[email protected]`Homepage: https://github.com/wooorm/property-information@@ -5315,6 +5320,11 @@ Homepage: https://github.com/sindresorhus/restore-cursorCopyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)+### `[email protected]`+Homepage: https://github.com/tim-kos/node-retry++Copyright (c) 2011: Tim Koschützki ([email protected]) Felix Geisendörfer ([email protected])+### `[email protected]`Homepage: https://github.com/mcollina/reusify#readme@@ -6280,15 +6290,15 @@ Homepage: https://github.com/wesleytodd/setprototypeofCopyright (c) 2015, Wes Todd-### `[email protected]`+### `[email protected]`Homepage: https://github.com/tapjs/signal-exit-Copyright (c) 2015-2023 Benjamin Coe, Isaac Z. Schlueter, and Contributors+Copyright (c) 2015, Contributors-### `[email protected]`+### `[email protected]`Homepage: https://github.com/tapjs/signal-exit-Copyright (c) 2015, Contributors+Copyright (c) 2015-2023 Benjamin Coe, Isaac Z. Schlueter, and Contributors### `[email protected]`Homepage: https://github.com/mcollina/split2diff --git a/docs/content/integrations/pi.mdx b/docs/content/integrations/pi.mdxindex d38bbb8ec..16781f639 100644--- a/docs/content/integrations/pi.mdx+++ b/docs/content/integrations/pi.mdx@@ -17,7 +17,7 @@ These files are managed by OpenKnowledge. Running `ok init` again refreshes them## Trust the project-Make sure Pi trusts the project folder. Pi does not load project-local extensions or skills from `.pi/` until the project is trusted. When you first run pi in the project, accept the trust prompt. See Pi's [project trust documentation](https://pi.dev/docs/latest/security#project-trust) for more details.+Make sure Pi trusts the project folder. Pi does not load project-local extensions or skills from `.pi/` until the project is trusted. When you first run pi in the project, accept the trust prompt. When you use Pi inside OpenKnowledge, accepting its bridge setup prompt also grants folder trust. See [Pi folder trust](../reference/what-open-knowledge-writes.mdx#pi-folder-trust) for the trust file, `PI_CODING_AGENT_DIR`, and cleanup requirements. See Pi's [project trust documentation](https://pi.dev/docs/latest/security#project-trust) for more details.## Verifydiff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdxindex 94b257fa9..e8e041d2c 100644--- a/docs/content/reference/cli.mdx+++ b/docs/content/reference/cli.mdx@@ -39,7 +39,7 @@ ok initIn a sub-folder of a git repo, `ok init` sets the project up at the git root — one `.ok/` per repo — and the whole repo becomes the content scope. Pass `--content-dir <dir>` to limit content to one folder (`ok init --content-dir .` scopes it to the folder you run in); the choice is saved as `content.dir` in `.ok/config.yml`. For scripts, `--json` prints a structured JSON summary. `ok init` also installs the user-global `open-knowledge-discovery` skill, the same one the desktop's first launch sets up; `--skills discovery,write-skill` adds the authoring skill, and `--no-skills` installs none on that run. `open-knowledge-write-skill` is otherwise one click away in **Settings → Skills Studio**.<Callout type="info" title="If an editor shows “left unchanged”">- When an editor's config can't be parsed safely — it's not valid JSON/TOML, has two MCP server blocks, or is unusually large — OpenKnowledge leaves the file **byte-for-byte untouched** and prints `left unchanged (<reason>)` instead of registering. It never rewrites or resets a config it can't fully understand. Fix the underlying config (the editor itself usually reports the parse error) and re-run `ok init`.+ OpenKnowledge prints `left unchanged (<reason>)` when it cannot safely read or update an editor's config. This can mean a permission problem, a path that is not a regular file, invalid JSON/TOML/YAML, duplicate MCP server blocks, or an unusually large file. The config stays **byte-for-byte untouched**. Follow the printed reason and then re-run `ok init`. Correct permissions or the path for an access failure, or repair syntax for a parse failure. For `no format-preserving writer available`, reinstall OpenKnowledge to restore its TOML writer, or add the MCP entry manually as described in the [Codex integration guide](/docs/integrations/codex#verify).</Callout>Once you have initialized your project, launch the app in your browser:@@ -152,12 +152,16 @@ The rest of the CLI exists mostly for tooling and automation. Your AI editor spa## Remove OpenKnowledge-`ok deinit` reverses `ok init` for one project: it removes the project's `.ok/` directory, its editor MCP entries, git-exclude lines, and shadow repo, leaving your markdown untouched.+`ok deinit [path]` reverses `ok init` for one project (the current project when `path` is omitted): it removes the project's `.ok/` directory, OpenKnowledge's editor MCP entries, its own git-exclude lines, and shadow repo, leaving your markdown untouched. Shared editor settings and their symlinks are preserved; ignore rules for shared config files stay while those files still exist.-`ok uninstall` removes OpenKnowledge from the whole machine — running servers, credentials, the PATH shim, its own editor MCP entries, skill bundles, app data, and `~/.ok`. Your markdown content stays, and your global skills in your editors' skill dirs (`~/.agents/skills`, `~/.claude/skills`, and the like) are never touched. It never deletes the CLI binary itself; it ends by printing the removal command (`npm uninstall -g @inkeep/open-knowledge` for the install above).+`ok uninstall` removes the global footprint — running servers, credentials, the PATH shim, OpenKnowledge's editor MCP entries and bundled skills, app data, and `~/.ok` (keeping authored skills in `~/.ok/skills` unless you pass `--purge-content`). Your markdown and other skills in your editors' skill directories stay. An interactive run lets you select projects to deinitialize; `--yes` removes only the global footprint unless you also pass `--all-projects`, which covers current, recent, and discovered running projects. The CLI binary stays installed; the command ends by printing how to remove it (`npm uninstall -g @inkeep/open-knowledge` for the install above).++Both `ok deinit` and `ok uninstall` wait for servers to exit before deleting their state. If a server cannot be safely stopped or an integration cannot be cleaned up, the command reports the problem and retains state needed for repair and retry. Applied cleanup exits `1` when anything remains unresolved. With `--yes --json`, inspect `failed[]` for those items and their reasons; `skipped[]` covers intentionally preserved entries. Repair the reported problem and rerun the command.++`ok deinit` needs the project's `.ok/` directory; once that directory is gone, it reports nothing to remove. Remove any retained Pi trust entry manually using its reported exact key and file, as described in [installation details](./what-open-knowledge-writes.mdx#pi-folder-trust).Both commands print their plan and ask before acting; `--dry-run` previews without changing anything. Once `ok uninstall` has finished successfully, an interactive run also asks one optional question about why you're leaving — you can skip it, and `--yes`, `--json`, and non-interactive runs never ask. Anything you do answer is [sent to us](/docs/reference/what-open-knowledge-writes#what-leaves-your-machine).-On the macOS desktop app, **App menu → Uninstall OpenKnowledge…** covers both steps from one flow: it optionally deinitializes your projects, removes the global footprint, shows the same optional "why are you leaving?" screen once removal succeeds, and then guides you through dragging the app to the Trash.+On the macOS desktop app, **App menu → Uninstall OpenKnowledge…** lets you choose projects to deinitialize, confirm removal, and answer or skip the optional "why are you leaving?" screen. The app then quits before cleanup starts, so shutdown cannot recreate its settings. A separate macOS dialog reports the result: successful cleanup guides you through dragging the app to the Trash; incomplete cleanup points to a retained log so you can repair the problem and retry.To remove the desktop app on the other platforms: on **Windows**, uninstall OpenKnowledge from **Settings → Apps → Installed apps**; on **Linux**, remove the package with your package manager (`sudo apt remove openknowledge` on Debian/Ubuntu, `sudo dnf remove OpenKnowledge` on Fedora/RHEL). Run `ok uninstall` first if you also want the rest of the footprint cleaned up — it works the same on every platform.diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex 93454b46d..ddb65dcc3 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -169,7 +169,7 @@ Installing `@inkeep/open-knowledge` from npm (or invoking it with `npx`) drops t### `ok init`-`ok init` turns a folder into an OpenKnowledge project. It scaffolds the project's `.ok/` directory, and — unless you pass `--no-mcp` — registers the `open-knowledge` MCP server with the AI editors it detects. The MCP registration is **surgical**: it touches only the entry named `open-knowledge` and leaves your other settings, comments, and formatting byte-for-byte intact (if a config can't be parsed safely, it's left untouched and reported).+`ok init` turns a folder into an OpenKnowledge project. It scaffolds the project's `.ok/` directory, and — unless you pass `--no-mcp` — registers the `open-knowledge` MCP server with the AI editors it detects. The MCP registration is **surgical**: it touches only the entry named `open-knowledge` and leaves your other settings, comments, and formatting byte-for-byte intact (if a config cannot be read or updated safely, it is left untouched and the reason is reported; follow that reason when repairing permissions, the path, or syntax. If it reports `no format-preserving writer available`, reinstall OpenKnowledge to restore its TOML writer or configure the integration manually).| Path | What it is | Scope || --- | --- | --- |@@ -212,7 +212,7 @@ With `--scope user` or `both` (the default), `ok init` also registers the `open-The install is **non-fatal** (`ok init` still exits 0 if it fails), **version-gated** (a no-op when the current version is already installed), and needs **no network access**. Skip it for one run with `ok init --no-skills`, or choose individual bundles with `--skills <ids>`. Skipping records nothing and removes nothing, so skills already on the machine are left alone. An installed bundle is remembered in `~/.ok/skill-state.yml` and honored by every later install path; to turn the built-in skills off for good, decline at the first-launch prompt or uninstall from **Settings → Skills Studio**, either of which records a durable machine-wide choice. `ok repair-skills` re-runs it.-Pi is the exception: it has no user-level MCP config (it has no MCP support at all), so its integration is only ever the project-scoped bridge extension above.+Pi has no user-level MCP config. `ok init` writes its project-scoped bridge extension; using Pi inside OpenKnowledge can also add a [folder trust grant](#pi-folder-trust), whose location respects `PI_CODING_AGENT_DIR`.On Windows, Claude Desktop and OpenCode configs live under `%APPDATA%\Claude\` and `%APPDATA%\opencode\`, and the MCP entry is a PowerShell launcher.@@ -278,6 +278,31 @@ Disable both with `OK_RECLAIM_DISABLE=1`. `ok start` does not touch skill files;</Tabs>+## Pi folder trust++When you use Pi inside OpenKnowledge and accept its bridge setup prompt, OpenKnowledge also grants Pi trust in the project folder. This applies to both the desktop app and the web app served by `ok start`; `ok init` writes the project bridge without adding this trust grant.++| Path | What it is | Scope |+| --- | --- | --- |+| `~/.pi/agent/trust.json` (or `$PI_CODING_AGENT_DIR/trust.json`) | Pi's trust store. Bridge setup can add an exact-folder trust decision so Pi can load the OpenKnowledge bridge | In-project or Outside-project (follows the trust destination) |+| `~/.ok/pi-trust/` | Records the previous decision and trust-store path when OpenKnowledge changes a folder's trust. An interrupted, unconfirmed change is not treated as proven ownership | Outside-project (home dir) |+| `<configured trust path>.lock` | Temporary directory lock shared with Pi while accessing its trust store | In-project or Outside-project (follows the configured Pi directory) |+| `<resolved trust target>.ok.lock` | Temporary OpenKnowledge lock coordinating access through different symlinks. For a linked trust file, this sits beside its destination | In-project or Outside-project (follows the trust destination) |++Pi's directory lock coordinates with Pi itself at the configured path. The separate OpenKnowledge lock uses the resolved destination so OpenKnowledge processes using different symlinks also coordinate. Pi's store and locks normally live outside the project; a custom configuration or symlink can place them inside it.++New Pi trust checks, grants, and ownership records use the real project directory, even when the project was opened through a symlink. The setup prompt shows that directory; if the symlink points elsewhere when setup begins, OpenKnowledge refuses the change and asks you to reopen the intended project and approve it again. OpenKnowledge also refuses a project path it cannot resolve or access, instead of falling back to an unverified spelling.++`ok deinit`, project cleanup selected during `ok uninstall`, and removing the Pi connection in Settings reverse recorded OpenKnowledge trust changes when the current exact-folder value still matches the recorded grant and no other Pi resources need it. Cleanup restores the previous exact-folder decision, or removes the entry if none existed. Other projects' entries, parent-folder decisions, and Pi's global trust default are preserved; a folder may still be trusted through those settings.++Every Pi trust grant made before ownership recording was introduced lacks a record and is preserved, including grants made by OpenKnowledge. There is no automatic backfill. Older entries under a non-canonical project spelling, such as a symlink path, are also preserved and named when found. Pi does not use those literal keys, and cleanup does not move them to the real-path key. An interrupted setup can leave a pending record that does not prove the trust write completed; setup and cleanup do not reconcile it while the folder remains trusted. To remove an unrecorded or non-canonical grant manually, close Pi and remove only the project's exact-folder key from its `trust.json`, leaving the other entries intact. The cleanup message names an entry's exact key and file when it can inspect that entry. If the project path is already unavailable when cleanup starts and ownership records can be read, cleanup names those records and their recorded locations without checking current trust decisions. If a later project-path check fails, the affected trust store is left pending with guidance to repair the path and retry. For manual cleanup using a record, inspect the intended destination and restore the recorded previous decision only if you choose to undo a current true entry, removing that key only when there was no previous entry. Parent-folder and global trust settings can still apply; see [Pi's project trust rules](https://pi.dev/docs/latest/security#project-trust).++Trust is also kept when other project resources need it, including Pi settings, extensions, skills, prompts, themes, system prompts, and inherited project skills. Cleanup lists up to three of those resources, reports how many more remain, and relinquishes its ownership record where one exists: later cleanup runs will not revoke that grant even if those resources are removed. Manage the retained decision in Pi or remove the exact-folder key manually as described above. Removing the grant may stop Pi from loading those resources. OpenKnowledge's own skill namespace is managed separately in the current project; ancestor skill roots remain outside that project's cleanup and can still require trust.++Bridge setup requires a project directory it can resolve and access, and refuses unreadable trust files or broken or cyclic trust-file symlinks. Cleanup reports a failure if a project path or required trust check cannot be verified, retains retry information, and tells you what to repair. For a missing project, cleanup checks for ownership records under both the supplied path and the missing path appended to its nearest resolvable, accessible ancestor's real path. Healthy directory aliases are followed for this additional record lookup only; it cannot recover a deleted symlink's former target or an ancestor's historical target. With no bridge or record at either checked path, cleanup treats the project as already absent. A record at either path, or an ancestor that cannot be resolved or accessed, requires repairing the project path before retrying. With neither a bridge nor a record and a verifiable project path, cleanup treats the trust store as unrelated and does not inspect it.++`PI_CODING_AGENT_DIR` changes the trust-store directory; it does not relocate the project's `.pi/extensions/open-knowledge.ts` bridge. When a bridge or record requires trust cleanup, OpenKnowledge checks the currently configured store as well as saved locations for recorded grants, even if the environment setting has changed. It reports retained exact keys it finds, including the supplied project spelling when it differs from the real path. It does not search arbitrary Pi directories or infer unknown historical aliases for older, unrecorded entries.+## Opt-outs in one place| To skip… | Do this |@@ -291,7 +316,7 @@ Disable both with `OK_RECLAIM_DISABLE=1`. `ok start` does not touch skill files;| Local diagnostic logs and telemetry | `telemetry.localSink.enabled: false` in config || Auto-starting the MCP server | `OK_MCP_AUTOSTART=0` |-To review the footprint after the fact, `ok diagnose` reports what's on disk (and the desktop `path-install.json` records exactly which shell/`PATH` changes were made). To reverse it, `ok deinit` removes OpenKnowledge from one project and `ok uninstall` removes it from the whole machine — both keep your markdown content, and your global skills in your editors' skill dirs (`~/.agents/skills`, `~/.claude/skills`, and the like) are never touched, and both take `--dry-run` to preview. See the [CLI reference](./cli.mdx) for the full semantics.+To review the footprint after the fact, `ok diagnose` reports what's on disk (and the desktop `path-install.json` records exactly which shell/`PATH` changes were made). To reverse it, `ok deinit` removes OpenKnowledge from one project and `ok uninstall` removes the global footprint, with optional project cleanup. Both keep your markdown and authored skills by default; OpenKnowledge's bundled skills are removed. Shared configs and their symlinks are preserved, and incomplete cleanup reports a failure while retaining state needed to retry. Both commands take `--dry-run` to preview. See the [CLI reference](./cli.mdx#remove-openknowledge) for project selection and scripting behavior.In the desktop app you don't need the CLI for finer control, and the split follows what each thing is. **Settings → Agent connections** lists every agent OpenKnowledge can wire up, grouped by how you reach it — In app, Terminal, External apps. Each row says whether OpenKnowledge can reach that agent's tools and offers the one action that fits: **Add MCP & skill** when nothing is set up, **Manage** when something is, and **Remove** when files are still on disk for a tool you have turned off or uninstalled. A tool that is not on this machine offers **Install** instead, or **How to set up** when OpenKnowledge has no download link for it; neither writes anything. Both scopes are chosen in the same place: the dialog behind those actions groups what it writes under *This project* and *This machine*, so a project-scoped MCP config and a user-global one sit side by side, each naming the file it touches. *Skills* live on their own page at both scopes: **Settings → Skills Studio** carries the skills OpenKnowledge ships (user scope) or the project's own skill (project scope), each with an explicit Install/Uninstall button behind a confirmation naming every path it touches, plus the folders your AI tools read skills from. Removal keeps the guest discipline you would expect: only entries OpenKnowledge recognizably wrote are removed, and anything you customized is left intact.@@ -305,7 +330,7 @@ None of your content, by default. Everything above is written to your own disk.| --- | --- | --- || Diagnostic bundle | Only when you run `ok diagnose bundle` (you can inspect it first). On macOS it also carries the crash reports the OS recorded for this app and its helper processes (listed above), which are machine-wide rather than project-scoped; only this app's are collected, never another application's, though a report of ours still names the processes it was running alongside, and the summary printed before the zip is written says what that search found even when the answer is nothing | Wherever you send it || In-app bug report | Only when you click **Send** in the desktop app's **Help → Report a bug…** dialog, or the `Cmd+Shift+D` / `Ctrl+Shift+D` shortcut that opens the same dialog — it builds a secret-redacted zip you can reveal and inspect first, and nothing is sent without that explicit click. The zip carries a picture of the app window unless you uncheck **Screenshot** in that dialog, and the preview there is the picture that would be sent. A report reached through a surface you opened only to get to the reporter — the command palette, the Help popover, or the Windows and Linux menu bar — waits for that surface to close first, and carries no marker, because the row it would point at has already gone. Every other report you start yourself photographs the screen as it is, so an open menu or another person's document visible at the time is in the picture, and carries a marker drawn where your pointer was, since a screenshot never includes the cursor. No marker is drawn either if the pointer has not moved since the window loaded, or has since left the window. The invitation that appears on its own after a crash is the exception to all of this: it carries no picture at all. After a crash, the same dialog adds an **off-by-default** "Include crash dump" checkbox: a crash dump is a memory snapshot that can contain document content and can't be redacted, and it is only ever attached when you check that box. On macOS the zip also carries the update helper's install log (listed above), which is machine-wide rather than project-scoped; the zip's own README names it and says where it came from. At the **Detailed diagnostics** level — pre-checked on the invitation that follows a crash — it additionally carries the crash reports macOS itself recorded for this app and its helpers (also listed above), which are machine-wide for the same reason and named in the same README; only this app's are collected, never another application's, though a report of ours still names the processes it was running alongside, and the zip always says what that search found even when the answer is nothing. The zip also carries a short send history of the bug reports previously generated on this machine — when each was generated and whether sending it succeeded — which is what makes a report that failed to send diagnosable at all. That history is machine-wide too, so it names the other projects you have filed reports from; it carries no document content, and the README names it the same way | By default, Send makes no network request — it opens a prefilled email draft to [email protected] that you send yourself, naming the zip to attach. Only when an operator has configured a bug-report intake endpoint ([`OK_BUG_REPORT_INTAKE_URL`](./configuration.mdx#environment-variables)) does Send upload the zip there, falling back to the same email draft if the upload fails |-| Uninstall feedback | Only after an uninstall has already succeeded, and only if you pick a reason, type a note, or give an email address on the optional "Before you go" screen (desktop app) or prompt (`ok uninstall`). Skipping it, `--yes`, `--json`, and any non-interactive run send nothing | `openknowledge.ai/api/feedback` — the reason you picked, your note, your email address if you gave one, plus the app version and platform. It files one ticket for the team; nothing from your notes is included |+| Uninstall feedback | Only if you answer the optional "Before you go" screen or prompt. The macOS desktop asks after you confirm removal, before the app quits and cleanup starts; feedback can be sent even if cleanup later fails. Interactive `ok uninstall` asks only after successful cleanup. Skipping sends nothing; CLI runs with `--yes`, `--json`, or non-interactive input never ask | `openknowledge.ai/api/feedback` — the reason you picked, your note, your email address if you gave one, plus the app version and platform. It files one ticket for the team; nothing from your notes is included || Semantic search embeddings | Only when you enable [semantic search](./configuration.mdx#semantic-search) **and** set a key — off by default | Your configured embeddings provider (OpenAI by default) || GitHub sync / share | When you sync, clone, publish, or share | GitHub || Update check | Automatically — on launch and periodically while the desktop app runs | OpenKnowledge update service (`openknowledge.ai/updates`), which redirects to GitHub; sends the app version and channel |diff --git a/packages/app/src/components/acp/ThreadView.composed.dom.test.tsx b/packages/app/src/components/acp/ThreadView.composed.dom.test.tsxindex 39720c6fe..a72e216b9 100644--- a/packages/app/src/components/acp/ThreadView.composed.dom.test.tsx+++ b/packages/app/src/components/acp/ThreadView.composed.dom.test.tsx@@ -165,6 +165,94 @@ function transcriptRows(): [string, string][] {const noticeCards = (): HTMLElement[] => screen.queryAllByTestId('agent-thread-agent-notice');+describe('composed Pi bridge status and consent', () => {+ const bridgePath = '/opened-project/.pi/extensions/open-knowledge.ts';+ const canonicalCwd = '/real-project';+ const request: ThreadEvent = {+ kind: 'pi_bridge_consent_request',+ requestId: 'pi-request',+ agentName: 'Pi',+ cwd: canonicalCwd,+ bridgePath,+ ts: 1,+ };++ test.each([false, true])(+ 'an unavailable project names the folder and preserves its remedy, after consent: %s',+ (afterConsent) => {+ render(<ThreadView info={openThread()} />);+ const detail = 'Restore /opened-project or its link target, then retry';+ const events: ThreadEvent[] = afterConsent+ ? [+ request,+ {+ kind: 'pi_bridge_consent_resolved',+ requestId: 'pi-request',+ decision: 'granted',+ ts: 2,+ },+ ]+ : [];+ events.push({+ kind: 'pi_bridge_status',+ ...(afterConsent ? { requestId: 'pi-request' } : {}),+ state: 'project-path-unavailable',+ bridgePath,+ detail,+ ts: 3,+ });+ pushEvents(events, 0);++ const cards = screen.getAllByTestId('agent-thread-pi-bridge');+ expect(cards).toHaveLength(1);+ expect(cards[0].textContent).toContain(+ 'Open Knowledge tools are unavailable because the project folder is missing, inaccessible, or has changed. Check its location and permissions, then retry.',+ );+ expect(cards[0].textContent).toContain(detail);+ expect(cards[0].textContent).not.toContain('something is already at');+ expect(within(cards[0]).queryByRole('button', { name: 'Approve' })).toBeNull();+ },+ );++ test('consent displays the canonical trust key beside the opened bridge path', async () => {+ render(<ThreadView info={openThread()} />);+ pushEvent(request, 0);++ const card = screen.getByTestId('agent-thread-pi-bridge');+ expect(card.textContent).toContain(`extension to ${bridgePath}`);+ expect(card.textContent).toContain(`It also marks ${canonicalCwd} as trusted`);+ await userEvent.click(within(card).getByRole('button', { name: 'Approve' }));+ expect(socket.sent.map((frame) => JSON.parse(frame))).toContainEqual({+ op: 'pi_bridge_consent_response',+ threadId,+ requestId: 'pi-request',+ outcome: { kind: 'granted' },+ });+ });++ test('consent renders quoted and escaped extension names literally', () => {+ render(<ThreadView info={openThread()} />);+ pushEvent(+ {+ ...request,+ otherExtensions: [+ '"helper.ts. No other extensions are present.ts"',+ '"hidden\\u200b.ts"',+ '"prettier.ts, tailwind.ts, eslint.ts"',+ '"quoted\\"name.ts"',+ '"safe\\u202e.ts"',+ ],+ },+ 0,+ );++ const card = screen.getByTestId('agent-thread-pi-bridge');+ expect(card.textContent).toContain(+ 'same trust would let Pi run: "helper.ts. No other extensions are present.ts", "hidden\\u200b.ts", "prettier.ts, tailwind.ts, eslint.ts", "quoted\\"name.ts", "safe\\u202e.ts".',+ );+ });+});+describe('composed transcript: a Codex warning becomes a warning card', () => {test.each(fixture.candidates.map((candidate) => [candidate.name, candidate] as const))('candidate %s arrives over the socket and draws one runtime-warning row',diff --git a/packages/app/src/components/acp/ThreadView.tsx b/packages/app/src/components/acp/ThreadView.tsxindex 3a2c545cb..9b1b741c3 100644--- a/packages/app/src/components/acp/ThreadView.tsx+++ b/packages/app/src/components/acp/ThreadView.tsx@@ -2999,9 +2999,11 @@ function PiBridgeOutcomeRow({? t`Open Knowledge tools are unavailable: a file Open Knowledge didn't write is already at ${bridgePath}.`: outcome.state === 'unreadable-file'? t`Open Knowledge tools are unavailable: something is already at ${bridgePath} but couldn't be read, so Open Knowledge left it alone.`- : outcome.state === 'trust-failed'- ? t`Wrote the Open Knowledge extension, but couldn't mark the folder trusted, so it won't load. This thread has no Open Knowledge tools.`- : t`Couldn't write the Open Knowledge extension. This thread has no Open Knowledge tools.`}+ : outcome.state === 'project-path-unavailable'+ ? t`Open Knowledge tools are unavailable because the project folder is missing, inaccessible, or has changed. Check its location and permissions, then retry.`+ : outcome.state === 'trust-failed'+ ? t`Wrote the Open Knowledge extension, but couldn't mark the folder trusted, so it won't load. This thread has no Open Knowledge tools.`+ : t`Couldn't write the Open Knowledge extension. This thread has no Open Knowledge tools.`}</span></div>{outcome.detail !== null ? (diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.jsonindex c84b4c2b1..1f72f9859 100644--- a/packages/app/src/locales/ar/messages.json+++ b/packages/app/src/locales/ar/messages.json@@ -3716,7 +3716,6 @@"ciozf1": ["المهارة موجودة بالفعل في المشروع"],"cjtjry": ["تنقّل في سجل تنقّل OpenKnowledge إلى الخلف."],"cklVjM": ["الخط الزمني"],- "clJ3qM": ["تم."],"cn1sLi": ["تعذّر ربط أدوات OpenKnowledge بـ Claude Code. يرجى المحاولة مرة أخرى."],"cnGeoo": ["حذف"],"cqQyPB": ["اسم المجلد"],@@ -3908,6 +3907,9 @@"e8zRrb": ["إظهار الملفات"],"e8zYa8": ["تعذّر فتح ", ["shareBranch"], " في شجرة عمل. أعد المحاولة."],"e9sHSO": ["تابع من حيث توقفت"],+ "eBGWcy": [+ "أدوات Open Knowledge غير متاحة لأن مجلد المشروع مفقود أو يتعذر الوصول إليه أو تغيّر. تحقق من موقعه وأذوناته، ثم أعد المحاولة."+ ],"eBIT9h": ["فشل اللصق.", ["restoreSuffix"]],"eCDwNN": [[@@ -5952,7 +5954,6 @@"yQE2r9": ["يجري التحميل"],"yQyglE": ["لا توجد مستندات مطابقة"],"yR5LHI": ["أدخل قيمة ست عشرية من 6 خانات مثل #1A2B3C"],- "yU_9ur": ["للقيام به."],"yUxR-Q": ["توسيع ", ["keyName"]],"yWSvcf": ["جذر المحتوى"],"yWWThY": ["مرجع الأصل"],diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.poindex eddad0da4..6d17d13c9 100644--- a/packages/app/src/locales/ar/messages.po+++ b/packages/app/src/locales/ar/messages.po@@ -5026,10 +5026,6 @@ msgstr "تم"msgid "Done"msgstr "تم"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "Done."-msgstr "تم."-#: src/components/ui/tag-pill-input.tsxmsgid "Double-click to edit"msgstr "انقر نقرًا مزدوجًا للتحرير"@@ -9497,6 +9493,10 @@ msgstr "يقوم Open Knowledge بإعادة كتابة ملفات index.md هذmsgid "Open Knowledge tools are available in this thread."msgstr "أدوات Open Knowledge متاحة في هذه السلسلة."+#: src/components/acp/ThreadView.tsx+msgid "Open Knowledge tools are unavailable because the project folder is missing, inaccessible, or has changed. Check its location and permissions, then retry."+msgstr "أدوات Open Knowledge غير متاحة لأن مجلد المشروع مفقود أو يتعذر الوصول إليه أو تغيّر. تحقق من موقعه وأذوناته، ثم أعد المحاولة."+#: src/components/acp/ThreadView.tsxmsgid "Open Knowledge tools are unavailable: a file Open Knowledge didn't write is already at {bridgePath}."msgstr "أدوات Open Knowledge غير متاحة: يوجد بالفعل في {bridgePath} ملف لم تكتبه Open Knowledge."@@ -14334,10 +14334,6 @@ msgstr "العنوان"msgid "To do"msgstr "للقيام به"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "To do."-msgstr "للقيام به."-#: src/lib/keyboard-shortcuts.tsmsgid "Toggle a bullet list."msgstr "بدّل القائمة النقطية."diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.jsonindex f42b85ef2..6780c34e2 100644--- a/packages/app/src/locales/bn/messages.json+++ b/packages/app/src/locales/bn/messages.json@@ -3150,7 +3150,6 @@"ciozf1": ["ইতিমধ্যে প্রকল্পে দক্ষতা"],"cjtjry": ["OpenKnowledge-এর নেভিগেশন ইতিহাসে পিছনে যান।"],"cklVjM": ["কালানুক্রম"],- "clJ3qM": ["সম্পন্ন।"],"cn1sLi": ["OpenKnowledge টুলগুলো Claude Code-এর সঙ্গে যুক্ত করা যায়নি। অনুগ্রহ করে আবার চেষ্টা করুন।"],"cnGeoo": ["মুছুন"],"cqQyPB": ["ফোল্ডারের নাম"],@@ -3274,6 +3273,9 @@"e8zRrb": ["Files দেখান"],"e8zYa8": [["shareBranch"], " কোনো ওয়ার্কট্রিতে খোলা যায়নি। আবার চেষ্টা করুন।"],"e9sHSO": ["যেখানে ছেড়েছিলেন সেখান থেকেই শুরু করুন"],+ "eBGWcy": [+ "Open Knowledge-এর টুলগুলো উপলব্ধ নেই, কারণ প্রোজেক্ট ফোল্ডারটি নেই, সেটিতে প্রবেশ করা যাচ্ছে না অথবা সেটি বদলে গেছে। ফোল্ডারের অবস্থান ও অনুমতি পরীক্ষা করে আবার চেষ্টা করুন।"+ ],"eBIT9h": ["পেস্ট ব্যর্থ।", ["restoreSuffix"]],"eCDwNN": [["total", "plural", { "one": ["#", " সমস্যা"], "other": ["#", " সমস্যা"] }]],"eCOktA": ["এই এজেন্টের সাথে ইতিমধ্যেই একটি চ্যাট শুরু হচ্ছে — একটু পরে আবার চেষ্টা করুন।"],@@ -5020,7 +5022,6 @@"yQE2r9": ["লোড হচ্ছে"],"yQyglE": ["মিলে যাওয়া কোনো নথি নেই"],"yR5LHI": ["#1A2B3C-এর মতো ৬-অঙ্কের হেক্স দিন"],- "yU_9ur": ["করণীয়।"],"yUxR-Q": [["keyName"], " মেলে ধরুন"],"yWSvcf": ["বিষয়বস্তুর রুট"],"yWWThY": ["সম্পদ রেফারেন্স"],diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.poindex b64e0c9d1..92385d7d0 100644--- a/packages/app/src/locales/bn/messages.po+++ b/packages/app/src/locales/bn/messages.po@@ -5022,10 +5022,6 @@ msgstr "সম্পন্ন"msgid "Done"msgstr "সম্পন্ন"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "Done."-msgstr "সম্পন্ন।"-#: src/components/ui/tag-pill-input.tsxmsgid "Double-click to edit"msgstr "সম্পাদনা করতে ডাবল-ক্লিক করুন"@@ -9493,6 +9489,10 @@ msgstr "Open Knowledge এই index.md ফাইলগুলিকে দস্msgid "Open Knowledge tools are available in this thread."msgstr "এই থ্রেডে Open Knowledge টুল উপলব্ধ।"+#: src/components/acp/ThreadView.tsx+msgid "Open Knowledge tools are unavailable because the project folder is missing, inaccessible, or has changed. Check its location and permissions, then retry."+msgstr "Open Knowledge-এর টুলগুলো উপলব্ধ নেই, কারণ প্রোজেক্ট ফোল্ডারটি নেই, সেটিতে প্রবেশ করা যাচ্ছে না অথবা সেটি বদলে গেছে। ফোল্ডারের অবস্থান ও অনুমতি পরীক্ষা করে আবার চেষ্টা করুন।"+#: src/components/acp/ThreadView.tsxmsgid "Open Knowledge tools are unavailable: a file Open Knowledge didn't write is already at {bridgePath}."msgstr "Open Knowledge টুল উপলব্ধ নয়: {bridgePath}-এ ইতিমধ্যেই এমন একটি ফাইল আছে যা Open Knowledge লেখেনি।"@@ -14330,10 +14330,6 @@ msgstr "শিরোনাম"msgid "To do"msgstr "করণীয়"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "To do."-msgstr "করণীয়।"-#: src/lib/keyboard-shortcuts.tsmsgid "Toggle a bullet list."msgstr "বুলেট তালিকা চালু বা বন্ধ করুন।"diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex a56666993..ff0041224 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -3230,7 +3230,6 @@"ciozf1": ["Skill already in project"],"cjtjry": ["Traverse OpenKnowledge navigation history backward."],"cklVjM": ["Timeline"],- "clJ3qM": ["Done."],"cn1sLi": ["Couldn't connect OpenKnowledge tools to Claude Code. Please try again."],"cnGeoo": ["Delete"],"cqQyPB": ["Folder name"],@@ -3369,6 +3368,9 @@"e8zRrb": ["Show Files"],"e8zYa8": ["Could not open ", ["shareBranch"], " in a worktree. Try again."],"e9sHSO": ["Pick up where you left off"],+ "eBGWcy": [+ "Open Knowledge tools are unavailable because the project folder is missing, inaccessible, or has changed. Check its location and permissions, then retry."+ ],"eBIT9h": ["Paste failed.", ["restoreSuffix"]],"eCDwNN": [["total", "plural", { "one": ["#", " problem"], "other": ["#", " problems"] }]],"eCOktA": ["Already starting a chat with this agent — try again in a moment."],@@ -5202,7 +5204,6 @@"yQE2r9": ["Loading"],"yQyglE": ["No matching docs"],"yR5LHI": ["Enter a 6-digit hex like #1A2B3C"],- "yU_9ur": ["To do."],"yUxR-Q": ["Expand ", ["keyName"]],"yWSvcf": ["Content root"],"yWWThY": ["Asset reference"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 4ab4b5f58..ed547d828 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -5026,10 +5026,6 @@ msgstr "done"msgid "Done"msgstr "Done"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "Done."-msgstr "Done."-#: src/components/ui/tag-pill-input.tsxmsgid "Double-click to edit"msgstr "Double-click to edit"@@ -9497,6 +9493,10 @@ msgstr "Open Knowledge rewrites these index.md files as documents change, so manmsgid "Open Knowledge tools are available in this thread."msgstr "Open Knowledge tools are available in this thread."+#: src/components/acp/ThreadView.tsx+msgid "Open Knowledge tools are unavailable because the project folder is missing, inaccessible, or has changed. Check its location and permissions, then retry."+msgstr "Open Knowledge tools are unavailable because the project folder is missing, inaccessible, or has changed. Check its location and permissions, then retry."+#: src/components/acp/ThreadView.tsxmsgid "Open Knowledge tools are unavailable: a file Open Knowledge didn't write is already at {bridgePath}."msgstr "Open Knowledge tools are unavailable: a file Open Knowledge didn't write is already at {bridgePath}."@@ -14334,10 +14334,6 @@ msgstr "Title"msgid "To do"msgstr "To do"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "To do."-msgstr "To do."-#: src/lib/keyboard-shortcuts.tsmsgid "Toggle a bullet list."msgstr "Toggle a bullet list."diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.jsonindex 78ec1810a..c6421e4a2 100644--- a/packages/app/src/locales/es/messages.json+++ b/packages/app/src/locales/es/messages.json@@ -3761,7 +3761,6 @@"ciozf1": ["La habilidad ya está en el proyecto"],"cjtjry": ["Retrocede por el historial de navegación de OpenKnowledge."],"cklVjM": ["Cronología"],- "clJ3qM": ["Listo."],"cn1sLi": ["No se pudieron conectar las herramientas de OpenKnowledge con Claude Code. Inténtalo de nuevo."],@@ -3929,6 +3928,9 @@"e8zRrb": ["Mostrar Archivos"],"e8zYa8": ["No se pudo abrir ", ["shareBranch"], " en un worktree. Inténtalo de nuevo."],"e9sHSO": ["Continúa donde lo dejaste"],+ "eBGWcy": [+ "Las herramientas de Open Knowledge no están disponibles porque la carpeta del proyecto no existe, no es accesible o ha cambiado. Comprueba su ubicación y permisos y vuelve a intentarlo."+ ],"eBIT9h": ["Falló el pegado.", ["restoreSuffix"]],"eCDwNN": [[@@ -5980,7 +5982,6 @@"yQE2r9": ["Cargando"],"yQyglE": ["Ningún documento coincide"],"yR5LHI": ["Escribe un valor hexadecimal de 6 dígitos, como #1A2B3C"],- "yU_9ur": ["Por hacer."],"yUxR-Q": ["Expandir ", ["keyName"]],"yWSvcf": ["Raíz del contenido"],"yWWThY": ["Referencia al recurso"],diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.poindex f56028382..eff1b5975 100644--- a/packages/app/src/locales/es/messages.po+++ b/packages/app/src/locales/es/messages.po@@ -5026,10 +5026,6 @@ msgstr "listo"msgid "Done"msgstr "Listo"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "Done."-msgstr "Listo."-#: src/components/ui/tag-pill-input.tsxmsgid "Double-click to edit"msgstr "Haz doble clic para editar"@@ -9497,6 +9493,10 @@ msgstr "Open Knowledge reescribe estos archivos index.md a medida que cambian lomsgid "Open Knowledge tools are available in this thread."msgstr "Las herramientas de Open Knowledge están disponibles en este hilo."+#: src/components/acp/ThreadView.tsx+msgid "Open Knowledge tools are unavailable because the project folder is missing, inaccessible, or has changed. Check its location and permissions, then retry."+msgstr "Las herramientas de Open Knowledge no están disponibles porque la carpeta del proyecto no existe, no es accesible o ha cambiado. Comprueba su ubicación y permisos y vuelve a intentarlo."+#: src/components/acp/ThreadView.tsxmsgid "Open Knowledge tools are unavailable: a file Open Knowledge didn't write is already at {bridgePath}."msgstr "Las herramientas de Open Knowledge no están disponibles: ya hay en {bridgePath} un archivo que Open Knowledge no escribió."@@ -14334,10 +14334,6 @@ msgstr "Título"msgid "To do"msgstr "Por hacer"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "To do."-msgstr "Por hacer."-#: src/lib/keyboard-shortcuts.tsmsgid "Toggle a bullet list."msgstr "Activa o desactiva una lista con viñetas."diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.jsonindex 7a9895d4d..0e0be874f 100644--- a/packages/app/src/locales/fr/messages.json+++ b/packages/app/src/locales/fr/messages.json@@ -3807,7 +3807,6 @@"ciozf1": ["Compétence déjà en projet"],"cjtjry": ["Recule dans l'historique de navigation d'OpenKnowledge."],"cklVjM": ["Chronologie"],- "clJ3qM": ["Terminé."],"cn1sLi": ["Impossible de connecter les outils OpenKnowledge à Claude Code. Veuillez réessayer."],@@ -3968,6 +3967,9 @@"e8zRrb": ["Afficher les fichiers"],"e8zYa8": ["Impossible d'ouvrir ", ["shareBranch"], " dans un worktree. Réessayez."],"e9sHSO": ["Reprenez là où vous vous étiez arrêté"],+ "eBGWcy": [+ "Les outils Open Knowledge ne sont pas disponibles, car le dossier du projet est introuvable, inaccessible ou a changé. Vérifiez son emplacement et ses autorisations, puis réessayez."+ ],"eBIT9h": ["Échec du collage.", ["restoreSuffix"]],"eCDwNN": [[@@ -6058,7 +6060,6 @@"yQE2r9": ["Chargement"],"yQyglE": ["Aucun document correspondant"],"yR5LHI": ["Saisissez une valeur hexadécimale à 6 chiffres, par ex. #1A2B3C"],- "yU_9ur": ["À faire."],"yUxR-Q": ["Développer ", ["keyName"]],"yWSvcf": ["Racine du contenu"],"yWWThY": ["Référence de ressource"],diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.poindex e12742f14..361c413d2 100644--- a/packages/app/src/locales/fr/messages.po+++ b/packages/app/src/locales/fr/messages.po@@ -5026,10 +5026,6 @@ msgstr "terminé"msgid "Done"msgstr "Terminé"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "Done."-msgstr "Terminé."-#: src/components/ui/tag-pill-input.tsxmsgid "Double-click to edit"msgstr "Double-cliquez pour modifier"@@ -9497,6 +9493,10 @@ msgstr "Open Knowledge réécrit ces fichiers index.md à mesure que les documenmsgid "Open Knowledge tools are available in this thread."msgstr "Les outils Open Knowledge sont disponibles dans ce fil."+#: src/components/acp/ThreadView.tsx+msgid "Open Knowledge tools are unavailable because the project folder is missing, inaccessible, or has changed. Check its location and permissions, then retry."+msgstr "Les outils Open Knowledge ne sont pas disponibles, car le dossier du projet est introuvable, inaccessible ou a changé. Vérifiez son emplacement et ses autorisations, puis réessayez."+#: src/components/acp/ThreadView.tsxmsgid "Open Knowledge tools are unavailable: a file Open Knowledge didn't write is already at {bridgePath}."msgstr "Les outils Open Knowledge ne sont pas disponibles : un fichier qu'Open Knowledge n'a pas écrit se trouve déjà à {bridgePath}."@@ -14334,10 +14334,6 @@ msgstr "Titre"msgid "To do"msgstr "À faire"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "To do."-msgstr "À faire."-#: src/lib/keyboard-shortcuts.tsmsgid "Toggle a bullet list."msgstr "Bascule une liste à puces."diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.jsonindex bf0d88b25..eca506c4e 100644--- a/packages/app/src/locales/hi/messages.json+++ b/packages/app/src/locales/hi/messages.json@@ -3141,7 +3141,6 @@"ciozf1": ["कौशल पहले से ही परियोजना में है"],"cjtjry": ["OpenKnowledge के नेविगेशन इतिहास में पीछे जाएँ।"],"cklVjM": ["समयरेखा"],- "clJ3qM": ["पूर्ण।"],"cn1sLi": ["OpenKnowledge टूल को Claude Code से नहीं जोड़ा जा सका। कृपया फिर कोशिश करें।"],"cnGeoo": ["हटाएँ"],"cqQyPB": ["फ़ोल्डर का नाम"],@@ -3265,6 +3264,9 @@"e8zRrb": ["Files दिखाएँ"],"e8zYa8": [["shareBranch"], " को किसी वर्कट्री में नहीं खोला जा सका। फिर कोशिश करें।"],"e9sHSO": ["जहाँ छोड़ा था वहीं से शुरू करें"],+ "eBGWcy": [+ "Open Knowledge के टूल उपलब्ध नहीं हैं क्योंकि प्रोजेक्ट फ़ोल्डर मौजूद नहीं है, उस तक पहुँच नहीं है या वह बदल गया है। उसका स्थान और अनुमतियाँ जाँचें, फिर दोबारा कोशिश करें।"+ ],"eBIT9h": ["चिपकाना विफल।", ["restoreSuffix"]],"eCDwNN": [["total", "plural", { "one": ["#", " समस्या"], "other": ["#", " समस्याएँ"] }]],"eCOktA": ["इस एजेंट के साथ पहले से ही एक चैट शुरू हो रही है — कुछ ही देर में फिर कोशिश करें।"],@@ -5014,7 +5016,6 @@"yQE2r9": ["लोड हो रहा है"],"yQyglE": ["कोई मेल खाता दस्तावेज़ नहीं"],"yR5LHI": ["#1A2B3C जैसा 6-अंकों का हेक्स मान डालें"],- "yU_9ur": ["करना है।"],"yUxR-Q": [["keyName"], " फैलाएँ"],"yWSvcf": ["सामग्री रूट"],"yWWThY": ["एसेट संदर्भ"],diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.poindex 0ba21504f..07c3d0ba7 100644--- a/packages/app/src/locales/hi/messages.po+++ b/packages/app/src/locales/hi/messages.po@@ -5022,10 +5022,6 @@ msgstr "पूर्ण"msgid "Done"msgstr "पूर्ण"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "Done."-msgstr "पूर्ण।"-#: src/components/ui/tag-pill-input.tsxmsgid "Double-click to edit"msgstr "संपादित करने के लिए डबल-क्लिक करें"@@ -9493,6 +9489,10 @@ msgstr "दस्तावेज़ बदलने पर Open Knowledge इनmsgid "Open Knowledge tools are available in this thread."msgstr "इस थ्रेड में Open Knowledge टूल उपलब्ध हैं।"+#: src/components/acp/ThreadView.tsx+msgid "Open Knowledge tools are unavailable because the project folder is missing, inaccessible, or has changed. Check its location and permissions, then retry."+msgstr "Open Knowledge के टूल उपलब्ध नहीं हैं क्योंकि प्रोजेक्ट फ़ोल्डर मौजूद नहीं है, उस तक पहुँच नहीं है या वह बदल गया है। उसका स्थान और अनुमतियाँ जाँचें, फिर दोबारा कोशिश करें।"+#: src/components/acp/ThreadView.tsxmsgid "Open Knowledge tools are unavailable: a file Open Knowledge didn't write is already at {bridgePath}."msgstr "Open Knowledge टूल उपलब्ध नहीं हैं: {bridgePath} पर पहले से ऐसी फ़ाइल मौजूद है जिसे Open Knowledge ने नहीं लिखा।"@@ -14330,10 +14330,6 @@ msgstr "शीर्षक"msgid "To do"msgstr "करना है"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "To do."-msgstr "करना है।"-#: src/lib/keyboard-shortcuts.tsmsgid "Toggle a bullet list."msgstr "बुलेट सूची चालू या बंद करें।"diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.jsonindex 565584b78..251718036 100644--- a/packages/app/src/locales/id/messages.json+++ b/packages/app/src/locales/id/messages.json@@ -3262,7 +3262,6 @@"ciozf1": ["Keterampilan sudah ada dalam proyek"],"cjtjry": ["Menyusuri riwayat navigasi OpenKnowledge ke belakang."],"cklVjM": ["Lini masa"],- "clJ3qM": ["Selesai."],"cn1sLi": ["Alat OpenKnowledge tidak bisa dihubungkan ke Claude Code. Silakan coba lagi."],"cnGeoo": ["Hapus"],"cqQyPB": ["Nama folder"],@@ -3381,6 +3380,9 @@"e8zRrb": ["Tampilkan Berkas"],"e8zYa8": [["shareBranch"], " tidak dapat dibuka di worktree. Coba lagi."],"e9sHSO": ["Lanjutkan dari tempat Anda berhenti"],+ "eBGWcy": [+ "Alat Open Knowledge tidak tersedia karena folder proyek tidak ada, tidak dapat diakses, atau telah berubah. Periksa lokasi dan izinnya, lalu coba lagi."+ ],"eBIT9h": ["Penempelan gagal.", ["restoreSuffix"]],"eCDwNN": [["total", "plural", { "other": ["#", " masalah"] }]],"eCOktA": ["Obrolan dengan agen ini sudah mulai dibuka — coba lagi sebentar lagi."],@@ -5198,7 +5200,6 @@"yQE2r9": ["Memuat"],"yQyglE": ["Tidak ada dokumen yang cocok"],"yR5LHI": ["Masukkan nilai heksa 6 digit seperti #1A2B3C"],- "yU_9ur": ["Akan dikerjakan."],"yUxR-Q": ["Bentangkan ", ["keyName"]],"yWSvcf": ["Akar konten"],"yWWThY": ["Referensi aset"],diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.poindex d7eff73e5..23529897f 100644--- a/packages/app/src/locales/id/messages.po+++ b/packages/app/src/locales/id/messages.po@@ -5022,10 +5022,6 @@ msgstr "selesai"msgid "Done"msgstr "Selesai"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "Done."-msgstr "Selesai."-#: src/components/ui/tag-pill-input.tsxmsgid "Double-click to edit"msgstr "Klik dua kali untuk menyunting"@@ -9493,6 +9489,10 @@ msgstr "Open Knowledge menulis ulang file index.md ini seiring perubahan dokumenmsgid "Open Knowledge tools are available in this thread."msgstr "Alat Open Knowledge tersedia di utas ini."+#: src/components/acp/ThreadView.tsx+msgid "Open Knowledge tools are unavailable because the project folder is missing, inaccessible, or has changed. Check its location and permissions, then retry."+msgstr "Alat Open Knowledge tidak tersedia karena folder proyek tidak ada, tidak dapat diakses, atau telah berubah. Periksa lokasi dan izinnya, lalu coba lagi."+#: src/components/acp/ThreadView.tsxmsgid "Open Knowledge tools are unavailable: a file Open Knowledge didn't write is already at {bridgePath}."msgstr "Alat Open Knowledge tidak tersedia: sudah ada berkas di {bridgePath} yang tidak ditulis Open Knowledge."@@ -14330,10 +14330,6 @@ msgstr "Judul"msgid "To do"msgstr "Akan dikerjakan"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "To do."-msgstr "Akan dikerjakan."-#: src/lib/keyboard-shortcuts.tsmsgid "Toggle a bullet list."msgstr "Menyalakan atau mematikan daftar berpoin."diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.jsonindex 88e57a3b9..4197bbfd3 100644--- a/packages/app/src/locales/ko/messages.json+++ b/packages/app/src/locales/ko/messages.json@@ -3120,7 +3120,6 @@"ciozf1": ["이미 프로젝트에 있는 스킬"],"cjtjry": ["OpenKnowledge 탐색 기록을 뒤로 이동합니다."],"cklVjM": ["타임라인"],- "clJ3qM": ["완료"],"cn1sLi": ["OpenKnowledge 도구와 Claude Code 연결 실패. 다시 시도하세요."],"cnGeoo": ["삭제"],"cqQyPB": ["폴더 이름"],@@ -3239,6 +3238,9 @@"e8zRrb": ["파일 보기"],"e8zYa8": ["워크트리에서 ", ["shareBranch"], " 브랜치 열기에 실패했습니다. 다시 시도하세요."],"e9sHSO": ["중단한 지점부터 계속"],+ "eBGWcy": [+ "프로젝트 폴더가 없거나, 접근할 수 없거나, 변경되어 Open Knowledge 도구를 사용할 수 없습니다. 위치와 권한을 확인한 후 다시 시도하세요."+ ],"eBIT9h": ["붙여넣기에 실패했습니다.", ["restoreSuffix"]],"eCDwNN": [["total", "plural", { "other": ["#", "개 문제"] }]],"eCOktA": ["이 에이전트와의 채팅을 이미 시작하는 중입니다. 잠시 후 다시 시도하세요."],@@ -4965,7 +4967,6 @@"yQE2r9": ["로드 중"],"yQyglE": ["일치하는 문서 없음"],"yR5LHI": ["6자리 16진수 입력, 예: #1A2B3C"],- "yU_9ur": ["할 일"],"yUxR-Q": [["keyName"], " 펼치기"],"yWSvcf": ["콘텐츠 루트"],"yWWThY": ["에셋 참조"],diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.poindex 41d4c5a16..8e53b0c47 100644--- a/packages/app/src/locales/ko/messages.po+++ b/packages/app/src/locales/ko/messages.po@@ -5026,10 +5026,6 @@ msgstr "완료"msgid "Done"msgstr "완료"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "Done."-msgstr "완료"-#: src/components/ui/tag-pill-input.tsxmsgid "Double-click to edit"msgstr "편집하려면 두 번 클릭"@@ -9497,6 +9493,10 @@ msgstr "문서가 변경되면 Open Knowledge가 index.md 파일을 다시 작msgid "Open Knowledge tools are available in this thread."msgstr "이 스레드에서 Open Knowledge 도구를 사용할 수 있습니다."+#: src/components/acp/ThreadView.tsx+msgid "Open Knowledge tools are unavailable because the project folder is missing, inaccessible, or has changed. Check its location and permissions, then retry."+msgstr "프로젝트 폴더가 없거나, 접근할 수 없거나, 변경되어 Open Knowledge 도구를 사용할 수 없습니다. 위치와 권한을 확인한 후 다시 시도하세요."+#: src/components/acp/ThreadView.tsxmsgid "Open Knowledge tools are unavailable: a file Open Knowledge didn't write is already at {bridgePath}."msgstr "Open Knowledge 도구를 사용할 수 없습니다. {bridgePath}에 Open Knowledge가 작성하지 않은 파일이 이미 있습니다."@@ -14334,10 +14334,6 @@ msgstr "제목"msgid "To do"msgstr "할 일"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "To do."-msgstr "할 일"-#: src/lib/keyboard-shortcuts.tsmsgid "Toggle a bullet list."msgstr "글머리 기호 목록을 전환합니다."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 4af318d9f..80f651009 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -3230,7 +3230,6 @@"ciozf1": ["Śķĩĺĺ àĺŕēàďŷ ĩń ƥŕōĴēćţ"],"cjtjry": ["Ţŕàvēŕśē ŌƥēńĶńōŵĺēďĝē ńàvĩĝàţĩōń ĥĩśţōŕŷ ƀàćķŵàŕď."],"cklVjM": ["Ţĩḿēĺĩńē"],- "clJ3qM": ["Ďōńē."],"cn1sLi": ["Ćōũĺďń'ţ ćōńńēćţ ŌƥēńĶńōŵĺēďĝē ţōōĺś ţō Ćĺàũďē Ćōďē. Ƥĺēàśē ţŕŷ àĝàĩń."],"cnGeoo": ["Ďēĺēţē"],"cqQyPB": ["Ƒōĺďēŕ ńàḿē"],@@ -3369,6 +3368,9 @@"e8zRrb": ["Śĥōŵ Ƒĩĺēś"],"e8zYa8": ["Ćōũĺď ńōţ ōƥēń ", ["shareBranch"], " ĩń à ŵōŕķţŕēē. Ţŕŷ àĝàĩń."],"e9sHSO": ["Ƥĩćķ ũƥ ŵĥēŕē ŷōũ ĺēƒţ ōƒƒ"],+ "eBGWcy": [+ "Ōƥēń Ķńōŵĺēďĝē ţōōĺś àŕē ũńàvàĩĺàƀĺē ƀēćàũśē ţĥē ƥŕōĴēćţ ƒōĺďēŕ ĩś ḿĩśśĩńĝ, ĩńàććēśśĩƀĺē, ōŕ ĥàś ćĥàńĝēď. Ćĥēćķ ĩţś ĺōćàţĩōń àńď ƥēŕḿĩśśĩōńś, ţĥēń ŕēţŕŷ."+ ],"eBIT9h": ["Ƥàśţē ƒàĩĺēď.", ["restoreSuffix"]],"eCDwNN": [["total", "plural", { "one": ["#", " ƥŕōƀĺēḿ"], "other": ["#", " ƥŕōƀĺēḿś"] }]],"eCOktA": ["Àĺŕēàďŷ śţàŕţĩńĝ à ćĥàţ ŵĩţĥ ţĥĩś àĝēńţ — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ."],@@ -5202,7 +5204,6 @@"yQE2r9": ["Ĺōàďĩńĝ"],"yQyglE": ["Ńō ḿàţćĥĩńĝ ďōćś"],"yR5LHI": ["Ēńţēŕ à 6-ďĩĝĩţ ĥēx ĺĩķē #1À2ß3Ć"],- "yU_9ur": ["Ţō ďō."],"yUxR-Q": ["Ēxƥàńď ", ["keyName"]],"yWSvcf": ["Ćōńţēńţ ŕōōţ"],"yWWThY": ["Àśśēţ ŕēƒēŕēńćē"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 6cf182288..9b5147101 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -5022,10 +5022,6 @@ msgstr ""msgid "Done"msgstr ""-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "Done."-msgstr ""-#: src/components/ui/tag-pill-input.tsxmsgid "Double-click to edit"msgstr ""@@ -9493,6 +9489,10 @@ msgstr ""msgid "Open Knowledge tools are available in this thread."msgstr ""+#: src/components/acp/ThreadView.tsx+msgid "Open Knowledge tools are unavailable because the project folder is missing, inaccessible, or has changed. Check its location and permissions, then retry."+msgstr ""+#: src/components/acp/ThreadView.tsxmsgid "Open Knowledge tools are unavailable: a file Open Knowledge didn't write is already at {bridgePath}."msgstr ""@@ -14330,10 +14330,6 @@ msgstr ""msgid "To do"msgstr ""-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "To do."-msgstr ""-#: src/lib/keyboard-shortcuts.tsmsgid "Toggle a bullet list."msgstr ""diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.jsonindex 55c11cf41..6afc32d78 100644--- a/packages/app/src/locales/pt-BR/messages.json+++ b/packages/app/src/locales/pt-BR/messages.json@@ -3687,7 +3687,6 @@"ciozf1": ["Habilidade já em projeto"],"cjtjry": ["Volta pelo histórico de navegação do OpenKnowledge."],"cklVjM": ["Linha do tempo"],- "clJ3qM": ["Concluído."],"cn1sLi": ["Não deu para conectar as ferramentas do OpenKnowledge ao Claude Code. Tente de novo."],@@ -3850,6 +3849,9 @@"e8zRrb": ["Mostrar Arquivos"],"e8zYa8": ["Não foi possível abrir ", ["shareBranch"], " em um worktree. Tente de novo."],"e9sHSO": ["Continue de onde parou"],+ "eBGWcy": [+ "As ferramentas do Open Knowledge estão indisponíveis porque a pasta do projeto não existe, está inacessível ou foi alterada. Verifique a localização e as permissões e tente novamente."+ ],"eBIT9h": ["Falha ao colar.", ["restoreSuffix"]],"eCDwNN": [[@@ -5872,7 +5874,6 @@"yQE2r9": ["Carregando"],"yQyglE": ["Nenhum documento corresponde"],"yR5LHI": ["Digite um valor hexadecimal de 6 dígitos, como #1A2B3C"],- "yU_9ur": ["A fazer."],"yUxR-Q": ["Expandir ", ["keyName"]],"yWSvcf": ["Raiz do conteúdo"],"yWWThY": ["Referência de recurso"],diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.poindex 9a55b5c01..5c5d5d84c 100644--- a/packages/app/src/locales/pt-BR/messages.po+++ b/packages/app/src/locales/pt-BR/messages.po@@ -5022,10 +5022,6 @@ msgstr "pronto"msgid "Done"msgstr "Concluído"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "Done."-msgstr "Concluído."-#: src/components/ui/tag-pill-input.tsxmsgid "Double-click to edit"msgstr "Clique duas vezes para editar"@@ -9493,6 +9489,10 @@ msgstr "Open Knowledge reescreve esses arquivos index.md conforme os documentosmsgid "Open Knowledge tools are available in this thread."msgstr "As ferramentas do Open Knowledge estão disponíveis nesta conversa."+#: src/components/acp/ThreadView.tsx+msgid "Open Knowledge tools are unavailable because the project folder is missing, inaccessible, or has changed. Check its location and permissions, then retry."+msgstr "As ferramentas do Open Knowledge estão indisponíveis porque a pasta do projeto não existe, está inacessível ou foi alterada. Verifique a localização e as permissões e tente novamente."+#: src/components/acp/ThreadView.tsxmsgid "Open Knowledge tools are unavailable: a file Open Knowledge didn't write is already at {bridgePath}."msgstr "As ferramentas do Open Knowledge estão indisponíveis: já existe em {bridgePath} um arquivo que o Open Knowledge não escreveu."@@ -14330,10 +14330,6 @@ msgstr "Título"msgid "To do"msgstr "A fazer"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "To do."-msgstr "A fazer."-#: src/lib/keyboard-shortcuts.tsmsgid "Toggle a bullet list."msgstr "Liga ou desliga uma lista com marcadores."diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.jsonindex ecfa0f9cf..f5e6e1a96 100644--- a/packages/app/src/locales/ur/messages.json+++ b/packages/app/src/locales/ur/messages.json@@ -3309,7 +3309,6 @@"ciozf1": ["پروجیکٹ میں پہلے سے ہی مہارت"],"cjtjry": ["OpenKnowledge کی نیویگیشن تاریخ میں پیچھے جائیں۔"],"cklVjM": ["ٹائم لائن"],- "clJ3qM": ["مکمل۔"],"cn1sLi": ["OpenKnowledge کے ٹولز Claude Code سے منسلک نہیں ہو سکے۔ براہِ کرم دوبارہ کوشش کریں۔"],@@ -3448,6 +3447,9 @@"e8zRrb": ["فائلیں دکھائیں"],"e8zYa8": [["shareBranch"], " کسی ورک ٹری میں نہیں کھل سکا۔ دوبارہ کوشش کریں۔"],"e9sHSO": ["جہاں چھوڑا تھا وہیں سے شروع کریں"],+ "eBGWcy": [+ "Open Knowledge کے ٹولز دستیاب نہیں ہیں کیونکہ پروجیکٹ فولڈر موجود نہیں، اس تک رسائی ممکن نہیں یا وہ تبدیل ہو گیا ہے۔ اس کا مقام اور اجازتیں چیک کریں، پھر دوبارہ کوشش کریں۔"+ ],"eBIT9h": ["چسپاں کرنا ناکام رہا۔", ["restoreSuffix"]],"eCDwNN": [["total", "plural", { "one": ["#", " مسئلہ"], "other": ["#", " مسائل"] }]],"eCOktA": ["اس ایجنٹ کے ساتھ پہلے ہی چیٹ شروع ہو رہی ہے — تھوڑی دیر بعد دوبارہ کوشش کریں۔"],@@ -5279,7 +5281,6 @@"yQE2r9": ["لوڈ ہو رہا ہے"],"yQyglE": ["کوئی مماثل دستاویز نہیں"],"yR5LHI": ["#1A2B3C جیسی 6 ہندسوں کی ہیکس قدر درج کریں"],- "yU_9ur": ["کرنا ہے۔"],"yUxR-Q": [["keyName"], " پھیلائیں"],"yWSvcf": ["مواد کی جڑ"],"yWWThY": ["اثاثے کا حوالہ"],diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.poindex cb574bc9f..10f3d624f 100644--- a/packages/app/src/locales/ur/messages.po+++ b/packages/app/src/locales/ur/messages.po@@ -5026,10 +5026,6 @@ msgstr "مکمل"msgid "Done"msgstr "مکمل"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "Done."-msgstr "مکمل۔"-#: src/components/ui/tag-pill-input.tsxmsgid "Double-click to edit"msgstr "ترمیم کے لیے ڈبل کلک کریں"@@ -9497,6 +9493,10 @@ msgstr "Open Knowledge ان index.md فائلوں کو دوبارہ لکھتاmsgid "Open Knowledge tools are available in this thread."msgstr "اس تھریڈ میں Open Knowledge ٹولز دستیاب ہیں۔"+#: src/components/acp/ThreadView.tsx+msgid "Open Knowledge tools are unavailable because the project folder is missing, inaccessible, or has changed. Check its location and permissions, then retry."+msgstr "Open Knowledge کے ٹولز دستیاب نہیں ہیں کیونکہ پروجیکٹ فولڈر موجود نہیں، اس تک رسائی ممکن نہیں یا وہ تبدیل ہو گیا ہے۔ اس کا مقام اور اجازتیں چیک کریں، پھر دوبارہ کوشش کریں۔"+#: src/components/acp/ThreadView.tsxmsgid "Open Knowledge tools are unavailable: a file Open Knowledge didn't write is already at {bridgePath}."msgstr "Open Knowledge ٹولز دستیاب نہیں: {bridgePath} پر پہلے سے ایسی فائل موجود ہے جو Open Knowledge نے نہیں لکھی۔"@@ -14334,10 +14334,6 @@ msgstr "عنوان"msgid "To do"msgstr "کرنا ہے"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "To do."-msgstr "کرنا ہے۔"-#: src/lib/keyboard-shortcuts.tsmsgid "Toggle a bullet list."msgstr "بلٹ فہرست بدلیں۔"diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.jsonindex 4cf04e049..9d04f2837 100644--- a/packages/app/src/locales/zh-Hans/messages.json+++ b/packages/app/src/locales/zh-Hans/messages.json@@ -2833,7 +2833,6 @@"ciozf1": ["项目中已有的技能"],"cjtjry": ["在 OpenKnowledge 的导航历史中后退。"],"cklVjM": ["时间线"],- "clJ3qM": ["完成。"],"cn1sLi": ["无法把 OpenKnowledge 工具连接到 Claude Code。请重试。"],"cnGeoo": ["删除"],"cqQyPB": ["文件夹名"],@@ -2939,6 +2938,9 @@"e8zRrb": ["显示「文件」"],"e8zYa8": ["无法在 worktree 中打开 ", ["shareBranch"], "。请重试。"],"e9sHSO": ["从上次的位置继续"],+ "eBGWcy": [+ "Open Knowledge 工具不可用,因为项目文件夹缺失、无法访问或已更改。请检查其位置和权限,然后重试。"+ ],"eBIT9h": ["粘贴失败。", ["restoreSuffix"]],"eCDwNN": [["total", "plural", { "other": ["#", " 个问题"] }]],"eCOktA": ["已经在与该智能体开启对话了,请稍后再试。"],@@ -4511,7 +4513,6 @@"yQE2r9": ["正在加载"],"yQyglE": ["没有匹配的文档"],"yR5LHI": ["请输入 6 位十六进制值,例如 #1A2B3C"],- "yU_9ur": ["待办。"],"yUxR-Q": ["展开 ", ["keyName"]],"yWSvcf": ["内容根目录"],"yWWThY": ["资源引用"],diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.poindex 19cd6c674..ca16fc6a4 100644--- a/packages/app/src/locales/zh-Hans/messages.po+++ b/packages/app/src/locales/zh-Hans/messages.po@@ -5026,10 +5026,6 @@ msgstr "完成"msgid "Done"msgstr "完成"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "Done."-msgstr "完成。"-#: src/components/ui/tag-pill-input.tsxmsgid "Double-click to edit"msgstr "双击进行编辑"@@ -9497,6 +9493,10 @@ msgstr "当文档更改时,Open Knowledge 会重写这些 index.md 文件,msgid "Open Knowledge tools are available in this thread."msgstr "此线程中已可使用 Open Knowledge 工具。"+#: src/components/acp/ThreadView.tsx+msgid "Open Knowledge tools are unavailable because the project folder is missing, inaccessible, or has changed. Check its location and permissions, then retry."+msgstr "Open Knowledge 工具不可用,因为项目文件夹缺失、无法访问或已更改。请检查其位置和权限,然后重试。"+#: src/components/acp/ThreadView.tsxmsgid "Open Knowledge tools are unavailable: a file Open Knowledge didn't write is already at {bridgePath}."msgstr "Open Knowledge 工具不可用:{bridgePath} 处已存在一个并非 Open Knowledge 写入的文件。"@@ -14334,10 +14334,6 @@ msgstr "标题"msgid "To do"msgstr "待办"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "To do."-msgstr "待办。"-#: src/lib/keyboard-shortcuts.tsmsgid "Toggle a bullet list."msgstr "切换无序列表。"diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.jsonindex f967d5942..d2a6a1cbe 100644--- a/packages/app/src/locales/zh-Hant/messages.json+++ b/packages/app/src/locales/zh-Hant/messages.json@@ -2857,7 +2857,6 @@"ciozf1": ["專案中已有的技能"],"cjtjry": ["在 OpenKnowledge 的導覽記錄中往回走。"],"cklVjM": ["時間軸"],- "clJ3qM": ["完成。"],"cn1sLi": ["無法把 OpenKnowledge 工具連接到 Claude Code。請再試一次。"],"cnGeoo": ["刪除"],"cqQyPB": ["資料夾名稱"],@@ -2963,6 +2962,9 @@"e8zRrb": ["顯示「檔案」"],"e8zYa8": ["無法在 worktree 中開啟 ", ["shareBranch"], "。請再試一次。"],"e9sHSO": ["從上次停下的地方繼續"],+ "eBGWcy": [+ "Open Knowledge 工具無法使用,因為專案資料夾遺失、無法存取或已變更。請檢查其位置和權限,然後重試。"+ ],"eBIT9h": ["貼上失敗。", ["restoreSuffix"]],"eCDwNN": [["total", "plural", { "other": ["#", " 個問題"] }]],"eCOktA": ["已經在與該代理開啟對話了,請稍後再試。"],@@ -4543,7 +4545,6 @@"yQE2r9": ["正在載入"],"yQyglE": ["沒有相符的文件"],"yR5LHI": ["請輸入 6 位十六進位值,例如 #1A2B3C"],- "yU_9ur": ["待辦。"],"yUxR-Q": ["展開 ", ["keyName"]],"yWSvcf": ["內容根目錄"],"yWWThY": ["資產參照"],diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.poindex 015a0362b..ea5de2e7f 100644--- a/packages/app/src/locales/zh-Hant/messages.po+++ b/packages/app/src/locales/zh-Hant/messages.po@@ -5026,10 +5026,6 @@ msgstr "完成"msgid "Done"msgstr "完成"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "Done."-msgstr "完成。"-#: src/components/ui/tag-pill-input.tsxmsgid "Double-click to edit"msgstr "按兩下即可編輯"@@ -9497,6 +9493,10 @@ msgstr "當文件變更時,Open Knowledge 會重寫這些 index.md 文件,msgid "Open Knowledge tools are available in this thread."msgstr "此執行緒中已可使用 Open Knowledge 工具。"+#: src/components/acp/ThreadView.tsx+msgid "Open Knowledge tools are unavailable because the project folder is missing, inaccessible, or has changed. Check its location and permissions, then retry."+msgstr "Open Knowledge 工具無法使用,因為專案資料夾遺失、無法存取或已變更。請檢查其位置和權限,然後重試。"+#: src/components/acp/ThreadView.tsxmsgid "Open Knowledge tools are unavailable: a file Open Knowledge didn't write is already at {bridgePath}."msgstr "Open Knowledge 工具無法使用:{bridgePath} 已存在一個並非 Open Knowledge 寫入的檔案。"@@ -14334,10 +14334,6 @@ msgstr "標題"msgid "To do"msgstr "待辦"-#: src/uninstall/UninstallNoticeScreen.tsx-msgid "To do."-msgstr "待辦。"-#: src/lib/keyboard-shortcuts.tsmsgid "Toggle a bullet list."msgstr "切換項目符號清單。"diff --git a/packages/app/src/uninstall/UninstallApp.tsx b/packages/app/src/uninstall/UninstallApp.tsxindex 0999d880a..b7d93cb42 100644--- a/packages/app/src/uninstall/UninstallApp.tsx+++ b/packages/app/src/uninstall/UninstallApp.tsx@@ -47,7 +47,6 @@ export function UninstallApp() {notice={screen.notice}onConfirm={() => sendUninstallIntent({ kind: 'notice-confirm' })}onCancel={() => sendUninstallIntent({ kind: 'notice-cancel' })}- onRevealLog={() => sendUninstallIntent({ kind: 'notice-reveal-log' })}/>);default: {diff --git a/packages/app/src/uninstall/UninstallNoticeScreen.dom.test.tsx b/packages/app/src/uninstall/UninstallNoticeScreen.dom.test.tsxindex 172e06dbb..30d2b3a63 100644--- a/packages/app/src/uninstall/UninstallNoticeScreen.dom.test.tsx+++ b/packages/app/src/uninstall/UninstallNoticeScreen.dom.test.tsx@@ -8,39 +8,13 @@ const CONFIRM_NOTICE: UninstallNoticeSpec = {title: 'Uninstall OpenKnowledge?',paragraphs: ['This removes OpenKnowledge’s settings and integrations from your Mac, but keeps your markdown content and authored skills.',- 'When cleanup finishes, OpenKnowledge will help you remove the app itself, then quit.',+ 'OpenKnowledge will quit before cleanup starts. A dialog will show the result and help you remove the app itself.',],confirmLabel: 'Uninstall OpenKnowledge',cancelLabel: 'Cancel',danger: true,};-const COMPLETION_NOTICE: UninstallNoticeSpec = {- title: 'OpenKnowledge files were removed',- subtitle: "Almost done. Here's what happened and what's left.",- paragraphs: [],- checklist: [- {- label: 'Kept your content',- detail: 'Markdown files and authored skills were left untouched.',- done: true,- },- {- label: 'Removed OpenKnowledge files',- detail: 'Cleaned up, including from 2 projects.',- done: true,- },- {- label: 'Move OpenKnowledge.app to the Trash',- detail:- 'Reveal in Finder shows the app and quits OpenKnowledge, so you can drag it to the Trash.',- done: false,- },- ],- logRevealLabel: 'Cleanup log',- confirmLabel: 'Reveal in Finder',-};-const FAILURE_NOTICE: UninstallNoticeSpec = {title: 'Cleanup didn’t finish',paragraphs: ['Some files may not have been removed — details below.'],@@ -52,16 +26,8 @@ const FAILURE_NOTICE: UninstallNoticeSpec = {function renderNotice(notice: UninstallNoticeSpec) {const onConfirm = vi.fn();const onCancel = vi.fn();- const onRevealLog = vi.fn();- render(- <UninstallNoticeScreen- notice={notice}- onConfirm={onConfirm}- onCancel={onCancel}- onRevealLog={onRevealLog}- />,- );- return { onConfirm, onCancel, onRevealLog, user: userEvent.setup() };+ render(<UninstallNoticeScreen notice={notice} onConfirm={onConfirm} onCancel={onCancel} />);+ return { onConfirm, onCancel, user: userEvent.setup() };}describe('uninstall notice screen', () => {@@ -87,9 +53,9 @@ describe('uninstall notice screen', () => {});test('confirm holds focus on a single-button notice, where there is nothing else to choose', () => {- renderNotice(COMPLETION_NOTICE);+ renderNotice(FAILURE_NOTICE);- expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Reveal in Finder' }));+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Continue' }));});test('Escape cancels a two-button notice', async () => {@@ -102,7 +68,7 @@ describe('uninstall notice screen', () => {});test('Escape confirms a single-button notice', async () => {- const { user, onConfirm, onCancel } = renderNotice(COMPLETION_NOTICE);+ const { user, onConfirm, onCancel } = renderNotice(FAILURE_NOTICE);await user.keyboard('{Escape}');@@ -110,34 +76,6 @@ describe('uninstall notice screen', () => {expect(onCancel).not.toHaveBeenCalled();});- test('recaps what was kept and removed, and what the user still has to do', () => {- renderNotice(COMPLETION_NOTICE);-- expect(screen.getByText("Almost done. Here's what happened and what's left.")).toBeDefined();- for (const item of COMPLETION_NOTICE.checklist ?? []) {- expect(screen.getByText(item.label)).toBeDefined();- if (item.detail !== undefined) expect(screen.getByText(item.detail)).toBeDefined();- }-- expect(screen.getAllByText('Done.')).toHaveLength(2);- expect(screen.getAllByText('To do.')).toHaveLength(1);- });-- test('revealing the log leaves the notice up', async () => {- const { user, onConfirm, onRevealLog } = renderNotice(COMPLETION_NOTICE);-- await user.click(screen.getByRole('button', { name: 'Cleanup log' }));-- expect(onRevealLog).toHaveBeenCalledTimes(1);- expect(onConfirm).not.toHaveBeenCalled();- });-- test('offers no log reveal when there is no log to reveal', () => {- renderNotice(CONFIRM_NOTICE);-- expect(screen.queryByRole('button', { name: 'Cleanup log' })).toBeNull();- });-test('shows the cleanup detail and where the full log was written', () => {renderNotice(FAILURE_NOTICE);diff --git a/packages/app/src/uninstall/UninstallNoticeScreen.tsx b/packages/app/src/uninstall/UninstallNoticeScreen.tsxindex 293959cbf..9f16b43b8 100644--- a/packages/app/src/uninstall/UninstallNoticeScreen.tsx+++ b/packages/app/src/uninstall/UninstallNoticeScreen.tsx@@ -1,66 +1,15 @@-// oxlint-disable ok/no-physical-direction-utility -- pre-rule backlog — physical margin/padding/inset utilities predate the rule; drain by swapping ml/mr → ms/me, pl/pr → ps/pe, left/right → start/end, then deleting this line. See https://github.com/inkeep/open-knowledge/blob/main/lint-plugins/ok-rules/README.md#no-physical-direction-utility--import type {- UninstallNoticeChecklistItem,- UninstallNoticeScreen as UninstallNoticeSpec,-} from '@inkeep/open-knowledge-core';-import { Trans, useLingui } from '@lingui/react/macro';-import { Check } from 'lucide-react';+import type { UninstallNoticeScreen as UninstallNoticeSpec } from '@inkeep/open-knowledge-core';+import { useLingui } from '@lingui/react/macro';import { useEffect, useId } from 'react';import { Button } from '@/components/ui/button';-import { cn } from '@/lib/utils';interface UninstallNoticeScreenProps {notice: UninstallNoticeSpec;onConfirm: () => void;onCancel: () => void;- onRevealLog: () => void;}-function NoticeChecklist({ items }: { items: readonly UninstallNoticeChecklistItem[] }) {- return (- <ol className="mb-1.5">- {items.map((item, index) => (- <li key={item.label} className="relative pb-5 pl-[30px] last:pb-1">- {index < items.length - 1 && (- <span- aria-hidden="true"- className="absolute top-[22px] bottom-0.5 left-[9px] w-0.5 bg-border"- />- )}- {}- <span- aria-hidden="true"- className={cn(- 'absolute top-px left-0 inline-flex size-5 items-center justify-center rounded-full',- item.done- ? 'bg-primary/15 text-primary'- : 'border-[1.5px] border-muted-foreground/50',- )}- >- {item.done && <Check className="size-3" />}- </span>- <span className="sr-only">- {item.done ? <Trans>Done.</Trans> : <Trans>To do.</Trans>}- </span>- <span className="block">- <span className="font-medium">{item.label}</span>- {item.detail !== undefined && (- <span className="mt-0.5 block text-muted-foreground leading-snug">{item.detail}</span>- )}- </span>- </li>- ))}- </ol>- );-}--export function UninstallNoticeScreen({- notice,- onConfirm,- onCancel,- onRevealLog,-}: UninstallNoticeScreenProps) {+export function UninstallNoticeScreen({ notice, onConfirm, onCancel }: UninstallNoticeScreenProps) {const { t } = useLingui();const titleId = useId();const bodyId = useId();@@ -85,13 +34,10 @@ export function UninstallNoticeScreen({aria-describedby={bodyId}className="flex h-dvh flex-col bg-background text-foreground">- <header className="shrink-0 space-y-4 px-6 pt-5 pb-3.5">+ <header className="shrink-0 px-6 pt-5 pb-3.5"><h1 id={titleId} className="font-medium text-base leading-none">{notice.title}</h1>- {notice.subtitle !== undefined && (- <p className="text-muted-foreground text-sm leading-snug">{notice.subtitle}</p>- )}</header><div id={bodyId} className="flex min-h-0 flex-1 flex-col px-6 pt-1 pb-4 text-sm">@@ -100,7 +46,6 @@ export function UninstallNoticeScreen({{text}</p>))}- {notice.checklist !== undefined && <NoticeChecklist items={notice.checklist} />}{notice.log !== undefined && (<sectionaria-label={t`Cleanup log`}@@ -118,19 +63,6 @@ export function UninstallNoticeScreen({{notice.footnote}</p>)}- {notice.logRevealLabel !== undefined && (- <p className="mt-0.5">- <Button- type="button"- variant="link-muted"- size="xs"- className="h-auto px-0 underline underline-offset-2"- onClick={onRevealLog}- >- {notice.logRevealLabel}- </Button>- </p>- )}</div><footer className="flex items-center justify-end gap-2.5 border-border border-t bg-muted/50 px-6 pt-3.5 pb-4">diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 496094b30..f959c0281 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -70,6 +70,7 @@"jsonc-parser": "^3.3.1","picocolors": "^1.1.1","pino": "^10.3.1",+ "proper-lockfile": "^4.1.2","simple-git": "^3.36.0","smol-toml": "^1.6.1","yaml": "^2.7.1",@@ -86,6 +87,7 @@"@inkeep/open-knowledge-native-config": "workspace:*","@inkeep/open-knowledge-server": "workspace:*","@types/node": "^24.7.0",+ "@types/proper-lockfile": "^4.1.4","@types/yazl": "^3.3.1","ajv": "^8.18.0","ajv-formats": "^3.0.1",diff --git a/packages/cli/src/commands/deinit.test.ts b/packages/cli/src/commands/deinit.test.tsindex d6b9ef06e..b0203b6d2 100644--- a/packages/cli/src/commands/deinit.test.ts+++ b/packages/cli/src/commands/deinit.test.ts@@ -14,6 +14,7 @@ import { MCP_SERVER_NAME } from '@inkeep/open-knowledge-server';import { describe, expect, test, vi } from 'vitest';import { deinitCommand, runDeinit } from './deinit.ts';import { buildManagedServerEntry } from './editors.ts';+import { ensurePiBridge } from './pi-acp-bridge.ts';const OWN_ENTRY = buildManagedServerEntry({ mode: 'published' });@@ -29,7 +30,7 @@ function seedHome(): string {function seedProject(home: string = seedHome()): string {const dir = mkdtempSync(join(home, 'ok-deinit-'));write(join(dir, '.ok', 'config.yml'), 'content:\n dir: .\n');- write(join(dir, '.ok', 'local', 'server.lock'), '{}');+ mkdirSync(join(dir, '.ok', 'local'), { recursive: true });write(join(dir, '.okignore'), 'secret.md\n');write(join(dir, '.mcp.json'),@@ -41,6 +42,45 @@ function seedProject(home: string = seedHome()): string {}describe('runDeinit', () => {+ test.each([false, true])(+ 'cleans the configured Pi trust directory and preserves other grants (injected home=%s)',+ async (injectedHome) => {+ const home = seedHome();+ const cwd = seedProject(home);+ const agentDir = join(home, 'custom-pi');+ const trustPath = join(agentDir, 'trust.json');+ const defaultTrustPath = join(home, '.pi', 'agent', 'trust.json');+ const unrelated = join(home, 'other-project');+ const env = { PI_CODING_AGENT_DIR: agentDir };+ const defaultTrust = `${JSON.stringify({ [cwd]: true })}\n`;+ try {+ write(defaultTrustPath, defaultTrust);+ write(trustPath, JSON.stringify({ [unrelated]: true }));+ await ensurePiBridge(cwd, { mode: 'published' }, home, env);+ if (!injectedHome) {+ vi.stubEnv('HOME', home);+ vi.stubEnv('USERPROFILE', home);+ vi.stubEnv('PI_CODING_AGENT_DIR', agentDir);+ }+ const result = await runDeinit({+ cwd,+ ...(injectedHome ? { home, env } : {}),+ yes: true,+ probeClients: async () => null,+ runRemovalDeps: { stopServer: async () => ({ stopped: 0, failed: [] }) },+ });+ expect(result.status).toBe('done');+ expect(existsSync(join(cwd, '.pi', 'extensions', 'open-knowledge.ts'))).toBe(false);+ expect(JSON.parse(readFileSync(trustPath, 'utf8'))).toEqual({ [unrelated]: true });+ expect(readFileSync(defaultTrustPath, 'utf8')).toBe(defaultTrust);+ expect(readFileSync(join(cwd, 'notes.md'), 'utf8')).toBe('# my notes\n');+ } finally {+ vi.unstubAllEnvs();+ rmSync(home, { recursive: true, force: true });+ }+ },+ );+test('no-op with a clear message when the dir is not an OK project', async () => {const dir = mkdtempSync(join(seedHome(), 'ok-deinit-'));try {@@ -311,3 +351,99 @@ describe('runDeinit attached-client disclosure', () => {}});});++test('keeps project state after incomplete config cleanup so a repaired config can be retried', async () => {+ const home = seedHome();+ const project = seedProject(home);+ const configPath = join(project, '.cursor', 'mcp.json');+ try {+ write(configPath, '{broken config');+ const opts = {+ cwd: project,+ home,+ yes: true,+ probeClients: async () => null,+ runRemovalDeps: { stopServer: async () => ({ stopped: 0, failed: [] }) },+ };+ const first = await runDeinit(opts);+ expect(first.status).toBe('failed');+ expect(existsSync(join(project, '.ok', 'config.yml'))).toBe(true);+ write(configPath, JSON.stringify({ mcpServers: { [MCP_SERVER_NAME]: OWN_ENTRY } }));+ const second = await runDeinit(opts);+ expect(second.status).toBe('done');+ expect(existsSync(join(project, '.ok'))).toBe(false);+ expect(readFileSync(configPath, 'utf-8')).not.toContain(MCP_SERVER_NAME);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+});++test('reports an unreadable Git pointer and completes after it is repaired', async () => {+ const home = seedHome();+ const project = seedProject(home);+ const gitDir = join(home, 'actual-git-dir');+ try {+ write(join(project, '.git'), 'broken pointer');+ write(join(gitDir, 'HEAD'), 'ref: refs/heads/main\n');+ write(join(gitDir, 'info', 'exclude'), '.ok/\n.mcp.json\nprivate.env\n');+ write(join(gitDir, 'ok', 'state'), 'derived state');+ const opts = {+ cwd: project,+ home,+ yes: true,+ probeClients: async () => null,+ runRemovalDeps: { stopServer: async () => ({ stopped: 0, failed: [] }) },+ };+ const first = await runDeinit(opts);+ expect(first.status).toBe('failed');+ expect(first.exitCode).toBe(1);+ expect(first.message).toContain('repair the .git pointer');+ expect(first.message).toContain('restore a valid gitdir: <path> line');+ expect(first.message).toContain('run git worktree repair from the main repository');+ expect(first.message).toContain(join(project, '.git'));+ expect(existsSync(join(project, '.ok', 'config.yml'))).toBe(true);+ expect(readFileSync(join(gitDir, 'info', 'exclude'), 'utf8')).toBe(+ '.ok/\n.mcp.json\nprivate.env\n',+ );+ const json = JSON.parse((await runDeinit({ ...opts, json: true })).message);+ expect(json.failed).toContainEqual(+ expect.objectContaining({+ kind: 'git-exclude',+ detail: expect.stringContaining('repair the .git pointer'),+ }),+ );+ write(join(project, '.git'), `gitdir: ${gitDir}\n`);+ const retry = await runDeinit(opts);+ expect(retry.status).toBe('done');+ expect(retry.exitCode).toBe(0);+ expect(existsSync(join(project, '.ok'))).toBe(false);+ expect(existsSync(join(gitDir, 'ok'))).toBe(false);+ expect(readFileSync(join(gitDir, 'info', 'exclude'), 'utf8')).toBe('.mcp.json\nprivate.env\n');+ expect(readFileSync(join(project, '.git'), 'utf8')).toBe(`gitdir: ${gitDir}\n`);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+});++test('keeps project state when a later skill removal fails', async () => {+ const home = seedHome();+ const project = seedProject(home);+ const outside = join(home, 'outside');+ try {+ mkdirSync(join(outside, 'skills', 'open-knowledge'), { recursive: true });+ rmSync(join(project, '.claude'), { recursive: true, force: true });+ symlinkSync(outside, join(project, '.claude'));+ const result = await runDeinit({+ cwd: project,+ home,+ yes: true,+ probeClients: async () => null,+ runRemovalDeps: { stopServer: async () => ({ stopped: 0, failed: [] }) },+ });+ expect(result.status).toBe('failed');+ expect(existsSync(join(project, '.ok', 'config.yml'))).toBe(true);+ expect(existsSync(join(outside, 'skills', 'open-knowledge'))).toBe(true);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+});diff --git a/packages/cli/src/commands/deinit.ts b/packages/cli/src/commands/deinit.tsindex a01c4cad4..eb8327bc4 100644--- a/packages/cli/src/commands/deinit.ts+++ b/packages/cli/src/commands/deinit.ts@@ -21,6 +21,7 @@ import {export interface DeinitOptions {cwd?: string;home?: string;+ env?: NodeJS.ProcessEnv;yes?: boolean;dryRun?: boolean;json?: boolean;@@ -95,7 +96,10 @@ export async function runDeinit(opts: DeinitOptions = {}): Promise<DeinitResult>}}- const outcome = await runRemoval(plan, opts.runRemovalDeps);+ const outcome = await runRemoval(plan, {+ env: opts.env ?? (opts.home === undefined ? process.env : {}),+ ...opts.runRemovalDeps,+ });return {status: outcome.failed.length > 0 ? 'failed' : 'done',message: opts.jsondiff --git a/packages/cli/src/commands/editors.ts b/packages/cli/src/commands/editors.tsindex 5ef129791..4b85e8987 100644--- a/packages/cli/src/commands/editors.ts+++ b/packages/cli/src/commands/editors.ts@@ -532,6 +532,7 @@ interface EditorMcpTargetBase {interface ManagedFileEditorTarget extends EditorMcpTargetBase {format: 'file';+ projectConfigPath: (cwd: string) => string;buildEntry?: undefined;}@@ -559,7 +560,7 @@ export function editorConfigPathDisplay(target: EditorMcpTarget, home: string):return abs.startsWith(`${home}/`) ? `~${abs.slice(home.length)}` : abs;}-export const EDITOR_TARGETS: Record<EditorId, EditorMcpTarget> = {+export const EDITOR_TARGETS: Record<EditorId, EditorMcpTarget> & { pi: ManagedFileEditorTarget } = {claude: {id: 'claude',label: EDITOR_LABELS.claude,diff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.tsindex 331d9e1d3..f2ed869f1 100644--- a/packages/cli/src/commands/init.test.ts+++ b/packages/cli/src/commands/init.test.ts@@ -1,5 +1,6 @@import { execFileSync } from 'node:child_process';import {+ chmodSync,existsSync,lstatSync,mkdirSync,@@ -328,11 +329,59 @@ describe('runInit', () => {expect(readFileSync(claudeConfigPath(), 'utf-8')).toBe(original);const output = formatInitResult(result, testDir);- expect(output).toContain('left unchanged (config not readable)');+ expect(output).toContain('left unchanged (config could not be parsed)');expect(existsSync(join(testDir, OK_DIR, 'config.yml'))).toBe(true);});+ it.each(['claude', 'codex', 'hermes'] as const)(+ 'reports a %s config directory without changing its contents',+ async (editorId) => {+ const configPath = EDITOR_TARGETS[editorId].configPath(testDir, fakeHome);+ mkdirSync(configPath, { recursive: true });+ const childPath = join(configPath, 'keep.txt');+ writeFileSync(childPath, 'keep this file');++ const result = await runInitForTest({ editors: [editorId] });++ expect(result.editors).toMatchObject([+ { editorId, action: 'declined', declineReason: 'not-a-file' },+ ]);+ expect(formatInitResult(result, testDir)).toContain(+ 'left unchanged (config path is not a regular file)',+ );+ expect(lstatSync(configPath).isDirectory()).toBe(true);+ expect(readFileSync(childPath, 'utf-8')).toBe('keep this file');+ },+ );++ it.skipIf(process.platform === 'win32' || process.getuid?.() === 0).each([+ ['claude', '{"mcpServers":{}}\n'],+ ['codex', '[mcp_servers]\n'],+ ['hermes', 'mcp_servers: {}\n'],+ ] as const)(+ 'reports unreadable %s config permissions without changing its bytes',+ async (editorId, raw) => {+ const configPath = EDITOR_TARGETS[editorId].configPath(testDir, fakeHome);+ mkdirSync(dirname(configPath), { recursive: true });+ writeFileSync(configPath, raw);+ chmodSync(configPath, 0o000);+ try {+ const result = await runInitForTest({ editors: [editorId] });++ expect(result.editors).toMatchObject([+ { editorId, action: 'declined', declineReason: 'permission-denied' },+ ]);+ expect(formatInitResult(result, testDir)).toContain(+ 'left unchanged (permission denied; check file and parent-directory permissions)',+ );+ } finally {+ chmodSync(configPath, 0o600);+ }+ expect(readFileSync(configPath, 'utf-8')).toBe(raw);+ },+ );+describe('Cursor', () => {it('writes ~/.cursor/mcp.json with mcpServers key', async () => {mkdirSync(dirname(cursorConfigPath()), { recursive: true });@@ -2604,6 +2653,26 @@ describe('classifyExistingMcpEntry', () => {});});+ it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(+ 'reports an unreadable file as permission denied rather than malformed JSON',+ () => {+ const path = resolveCursorConfigPath({ home: fakeHome });+ mkdirSync(dirname(path), { recursive: true });+ const raw = '{"mcpServers":{}}';+ writeFileSync(path, raw);+ chmodSync(path, 0o000);+ try {+ expect(classifyExistingMcpEntry(EDITOR_TARGETS.cursor, '', fakeHome)).toEqual({+ kind: 'decline',+ reason: 'permission-denied',+ });+ } finally {+ chmodSync(path, 0o600);+ }+ expect(readFileSync(path, 'utf8')).toBe(raw);+ },+ );+it('absent when configPath throws (platform-mismatched target)', () => {Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });expect(classifyExistingMcpEntry(EDITOR_TARGETS['claude-desktop'], '', fakeHome)).toEqual({diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex df84e106a..6ab4bdb87 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -71,6 +71,10 @@ import {type TrackedRefusal,} from '../sharing/git-exclude.ts';import { accent, dim, error, info, success, warning } from '../ui/colors.ts';+import {+ type ConfigFileDeclineReason,+ configFileDeclineReason,+} from '../utils/config-file-error.ts';import { isObject } from '../utils/is-object.ts';import {ALL_EDITOR_IDS,@@ -164,7 +168,7 @@ function detectJsonIndent(body: string): { insertSpaces: boolean; tabSize: numbetype JsonUpsertOutcome =| { kind: 'written' | 'overwritten' | 'unchanged' }- | { kind: 'declined'; reason: McpDeclineReason };+ | { kind: 'declined'; reason: McpWriteDeclineReason };export function serverMapPath(topLevelKey: string,@@ -213,7 +217,7 @@ function upsertJsonMcpConfig(raw = readFileSync(configPath, 'utf-8');} catch (err) {debugNativeLoadFailure('json config read failed', err);- return { kind: 'declined', reason: 'unparseable' };+ return { kind: 'declined', reason: configFileDeclineReason(err) };}if (raw.trim() === '') {if (pruneOnly) return { kind: 'unchanged' };@@ -274,7 +278,7 @@ function upsertJsonMcpConfig(type TomlUpsertOutcome =| { kind: 'written' | 'overwritten' | 'unchanged' }- | { kind: 'declined'; reason: McpDeclineReason };+ | { kind: 'declined'; reason: McpWriteDeclineReason };function upsertTomlMcpConfig(engine: TomlConfigEngine,@@ -291,7 +295,7 @@ function upsertTomlMcpConfig(raw = readFileSync(configPath, 'utf-8');} catch (err) {debugNativeLoadFailure('toml config read failed', err);- return { kind: 'declined', reason: 'unparseable' };+ return { kind: 'declined', reason: configFileDeclineReason(err) };}}const blank = raw.trim() === '';@@ -376,7 +380,7 @@ function tomlWritePlan(type YamlUpsertOutcome =| { kind: 'written' | 'overwritten' | 'unchanged' }- | { kind: 'declined'; reason: McpDeclineReason };+ | { kind: 'declined'; reason: McpWriteDeclineReason };function upsertYamlMcpConfig(configPath: string,@@ -392,7 +396,7 @@ function upsertYamlMcpConfig(raw = readFileSync(configPath, 'utf-8');} catch (err) {debugNativeLoadFailure('yaml config read failed', err);- return { kind: 'declined', reason: 'unparseable' };+ return { kind: 'declined', reason: configFileDeclineReason(err) };}}if (raw.trim() === '') {@@ -551,7 +555,7 @@ export interface EditorMcpResult {configPath: string;serverName: string;error?: string;- declineReason?: McpDeclineReason;+ declineReason?: McpWriteDeclineReason;configScope?: 'project';}@@ -808,7 +812,7 @@ export function writeEditorMcpConfig(const captured: {action: 'written' | 'overwritten' | 'unchanged' | 'declined';- declineReason?: McpDeclineReason;+ declineReason?: McpWriteDeclineReason;} = { action: 'written' };let lockErr: Error | undefined;try {@@ -1025,18 +1029,22 @@ export function readExistingMcpEntry(return classified.kind === 'present' ? classified.entry : null;}-export type McpDeclineReason =+export type McpConfigDeclineReason =+ | ConfigFileDeclineReason| 'unparseable'| 'duplicate-container'| 'oversize'- | 'no-native-writer'- | McpLauncherDeclineReason;+ | 'no-native-writer';++export type McpDeclineReason = McpConfigDeclineReason | McpLauncherDeclineReason;++type McpWriteDeclineReason = Exclude<McpConfigDeclineReason, 'missing-symlink-target'>;export type McpEntryClassification =| { kind: 'absent' }| { kind: 'no-entry' }| { kind: 'present'; entry: Record<string, unknown> }- | { kind: 'decline'; reason: McpDeclineReason };+ | { kind: 'decline'; reason: McpConfigDeclineReason };function classifyContainer(config: Record<string, unknown>,@@ -1069,15 +1077,15 @@ export function classifyExistingMcpEntry(if (statSync(configPath).size > JSON_CONFIG_MAX_BYTES) {return { kind: 'decline', reason: 'oversize' };}- } catch {- return { kind: 'decline', reason: 'unparseable' };+ } catch (error) {+ return { kind: 'decline', reason: configFileDeclineReason(error) };}let raw: string;try {raw = readFileSync(configPath, 'utf-8');- } catch {- return { kind: 'decline', reason: 'unparseable' };+ } catch (error) {+ return { kind: 'decline', reason: configFileDeclineReason(error) };}if (raw.trim() === '') {return { kind: 'absent' };@@ -1461,16 +1469,32 @@ function summarizeApplied(};}-function declineReasonLabel(reason: McpDeclineReason | undefined): string {+function declineReasonLabel(reason: McpWriteDeclineReason | undefined): string {switch (reason) {+ case 'permission-denied':+ return 'permission denied; check file and parent-directory permissions';+ case 'unresolved-symlink':+ return 'could not resolve the path or symlink; check permissions and symlink cycles';+ case 'not-a-file':+ return 'config path is not a regular file';+ case 'disappeared':+ return 'config disappeared while being read; retry to check its current state';+ case 'unreadable':+ return 'could not read the config file; check that the path is accessible';+ case 'unparseable':+ return 'config could not be parsed';case 'oversize':return 'config too large to edit safely';case 'duplicate-container':return 'duplicate server block';case 'no-native-writer':return 'no format-preserving writer available';- default:+ case undefined:return 'config not readable';+ default: {+ const exhaustive: never = reason;+ throw new Error(`unhandled MCP decline reason: ${exhaustive}`);+ }}}diff --git a/packages/cli/src/commands/launch-json-removal.test.ts b/packages/cli/src/commands/launch-json-removal.test.tsindex d581d6bf3..0c4ca3927 100644--- a/packages/cli/src/commands/launch-json-removal.test.ts+++ b/packages/cli/src/commands/launch-json-removal.test.ts@@ -1,4 +1,15 @@-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import {+ existsSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readlinkSync,+ renameSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { describe, expect, test } from 'vitest';@@ -171,3 +182,54 @@ describe('removeOwnLaunchEntry', () => {}});});++describe('removeOwnLaunchEntry — symlinks', () => {+ test.skipIf(process.platform === 'win32')(+ 'preserves a symlink and edits the destination launch configuration',+ () => {+ const dir = project();+ try {+ const p = writeLaunch(dir, {+ configurations: [+ { name: 'My App', type: 'node' },+ {+ name: LAUNCH_CONFIG_NAME,+ runtimeExecutable: 'npx',+ runtimeArgs: ['-y', '@inkeep/open-knowledge', 'ui'],+ },+ ],+ });+ const target = join(dir, 'dotfiles-launch.json');+ renameSync(p, target);+ symlinkSync('../dotfiles-launch.json', p);+ expect(removeOwnLaunchEntry(dir).kind).toBe('removed');+ expect(lstatSync(p).isSymbolicLink()).toBe(true);+ expect(readlinkSync(p)).toBe('../dotfiles-launch.json');+ expect(JSON.parse(readFileSync(target, 'utf8')).configurations).toEqual([+ { name: 'My App', type: 'node' },+ ]);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ },+ );++ test.skipIf(process.platform === 'win32').each(['dangling', 'cycle'])(+ 'declines a %s launch symlink without removing it',+ (kind) => {+ const dir = project();+ try {+ const p = join(dir, '.claude', 'launch.json');+ symlinkSync(kind === 'cycle' ? 'launch.json' : 'missing.json', p);+ expect(removeOwnLaunchEntry(dir)).toEqual({+ kind: 'declined',+ reason: kind === 'cycle' ? 'unresolved-symlink' : 'missing-symlink-target',+ });+ expect(lstatSync(p).isSymbolicLink()).toBe(true);+ expect(existsSync(join(dir, '.claude', 'missing.json'))).toBe(false);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ },+ );+});diff --git a/packages/cli/src/commands/launch-json-removal.ts b/packages/cli/src/commands/launch-json-removal.tsindex fcce94b53..7feb4282a 100644--- a/packages/cli/src/commands/launch-json-removal.ts+++ b/packages/cli/src/commands/launch-json-removal.ts@@ -1,4 +1,4 @@-import { existsSync, readFileSync } from 'node:fs';+import { readFileSync } from 'node:fs';import { join } from 'node:path';import { atomicWriteFileSync } from '@inkeep/open-knowledge-core/server';import {@@ -7,14 +7,19 @@ import {type ParseError as JsoncParseError,parseTree,} from 'jsonc-parser';+import {+ type ConfigFileDeclineReason,+ configFileDeclineReason,+} from '../utils/config-file-error.ts';import { isObject } from '../utils/is-object.ts';import { LAUNCH_CONFIG_NAME } from './init.ts';import { existingFileMode, surgicalJsonDelete } from './jsonc-surgical.ts';+import { resolveRemovalFilePath } from './removal-file-path.ts';export type LaunchRemoveOutcome =| { kind: 'removed' }| { kind: 'not-present' }- | { kind: 'declined' };+ | { kind: 'declined'; reason: ConfigFileDeclineReason | 'unparseable' };const JSONC_PARSE_OPTIONS = { allowTrailingComma: true, disallowComments: false };@@ -26,20 +31,22 @@ function isBenignBomError(error: JsoncParseError, raw: string): boolean {}export function removeOwnLaunchEntry(projectRoot: string): LaunchRemoveOutcome {- const configPath = join(projectRoot, '.claude', 'launch.json');- if (!existsSync(configPath)) return { kind: 'not-present' };+ const resolved = resolveRemovalFilePath(join(projectRoot, '.claude', 'launch.json'));+ if (resolved.kind !== 'ready') return resolved;+ const configPath = resolved.path;let raw: string;try {raw = readFileSync(configPath, 'utf-8');- } catch {- return { kind: 'declined' };+ } catch (error) {+ return { kind: 'declined', reason: configFileDeclineReason(error) };}const errors: JsoncParseError[] = [];const tree: JsoncNode | undefined = parseTree(raw, errors, JSONC_PARSE_OPTIONS) ?? undefined;- if (errors.some((e) => !isBenignBomError(e, raw))) return { kind: 'declined' };- if (tree?.type !== 'object') return { kind: 'declined' };+ if (errors.some((e) => !isBenignBomError(e, raw)))+ return { kind: 'declined', reason: 'unparseable' };+ if (tree?.type !== 'object') return { kind: 'declined', reason: 'unparseable' };const root = getNodeValue(tree) as Record<string, unknown>;const configs = root.configurations;diff --git a/packages/cli/src/commands/mcp-config-removal.test.ts b/packages/cli/src/commands/mcp-config-removal.test.tsindex ae31abf3e..29d6c16a9 100644--- a/packages/cli/src/commands/mcp-config-removal.test.ts+++ b/packages/cli/src/commands/mcp-config-removal.test.ts@@ -1,4 +1,16 @@-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import {+ existsSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readlinkSync,+ realpathSync,+ rmSync,+ statSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { MCP_SERVER_NAME } from '@inkeep/open-knowledge-server';@@ -14,9 +26,10 @@ import {PI_EXTENSION_OWNERSHIP_MARKER,} from './editors.ts';import { removeOwnMcpEntry } from './mcp-config-removal.ts';+import { ensurePiBridge } from './pi-acp-bridge.ts';function tmp(): string {- return mkdtempSync(join(tmpdir(), 'ok-mcp-remove-'));+ return realpathSync(mkdtempSync(join(tmpdir(), 'ok-mcp-remove-')));}const OWN_ENTRY = buildManagedServerEntry({ mode: 'published' });@@ -253,7 +266,7 @@ describe('removeOwnMcpEntry — TOML (Codex)', () => {}});- test('declines when the format-preserving native engine is unavailable', () => {+ test('declines without the native writer, then accepts manual entry removal on retry', () => {const dir = tmp();try {const configPath = join(dir, 'config.toml');@@ -266,6 +279,12 @@ describe('removeOwnMcpEntry — TOML (Codex)', () => {expect(outcome.kind).toBe('declined');if (outcome.kind === 'declined') expect(outcome.reason).toBe('no-native-writer');expect(readFileSync(configPath, 'utf-8')).toBe(raw);+ const repaired = '# user config\n[mcp_servers.other]\ncommand = "node"\n';+ writeFileSync(configPath, repaired);+ expect(removeOwnMcpEntry(EDITOR_TARGETS.codex, dir, undefined, configPath)).toEqual({+ kind: 'not-present',+ });+ expect(readFileSync(configPath, 'utf8')).toBe(repaired);} finally {setTomlConfigEngineForTesting(null);}@@ -282,6 +301,108 @@ describe('removeOwnMcpEntry — Pi managed extension file', () => {return p;};+ test('retains the bridge after trust cleanup fails and removes both on retry', async () => {+ const dir = tmp();+ const home = join(dir, 'home');+ const project = join(dir, 'project');+ try {+ const configPath = piConfigPath(project);+ const trustPath = join(home, '.pi', 'agent', 'trust.json');+ mkdirSync(join(project, '.pi', 'extensions'), { recursive: true });+ mkdirSync(join(home, '.pi', 'agent'), { recursive: true });+ const bridge = buildPiExtensionSource();+ expect((await ensurePiBridge(project, { mode: 'published' }, home)).trust).toBe('added');+ writeFileSync(trustPath, '{malformed trust');++ expect(() => removeOwnMcpEntry(EDITOR_TARGETS.pi, project, home, configPath)).toThrow(+ 'bridge file was left untouched',+ );+ expect(readFileSync(configPath, 'utf8')).toBe(bridge);+ expect(readFileSync(trustPath, 'utf8')).toBe('{malformed trust');++ const otherProject = join(dir, 'other-project');+ writeFileSync(trustPath, JSON.stringify({ [project]: true, [otherProject]: true }));+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, project, home, configPath)).toEqual({+ kind: 'removed',+ trust: 'removed',+ });+ expect(existsSync(configPath)).toBe(false);+ expect(JSON.parse(readFileSync(trustPath, 'utf8'))).toEqual({ [otherProject]: true });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('cleans a recorded grant even when its bridge was already removed', async () => {+ const dir = tmp();+ const home = join(dir, 'home');+ const project = join(dir, 'project');+ try {+ mkdirSync(project, { recursive: true });+ const configPath = piConfigPath(project);+ expect((await ensurePiBridge(project, { mode: 'published' }, home)).trust).toBe('added');+ rmSync(configPath);++ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, project, home, configPath)).toEqual({+ kind: 'removed',+ trust: 'removed',+ });+ expect(JSON.parse(readFileSync(join(home, '.pi', 'agent', 'trust.json'), 'utf8'))).toEqual(+ {},+ );+ expect(existsSync(configPath)).toBe(false);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('leaves unrecorded Pi trust alone when there is no bridge to remove', () => {+ const dir = tmp();+ const home = join(dir, 'home');+ const project = join(dir, 'project');+ try {+ const trustPath = join(home, '.pi', 'agent', 'trust.json');+ mkdirSync(join(home, '.pi', 'agent'), { recursive: true });+ const before = '{unrelated unreadable trust config';+ writeFileSync(trustPath, before);++ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, project, home, piConfigPath(project))).toEqual({+ kind: 'not-present',+ });+ expect(readFileSync(trustPath, 'utf8')).toBe(before);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('keeps shared Pi trust while removing the bridge before other extensions', () => {+ const dir = tmp();+ const home = join(dir, 'home');+ const project = join(dir, 'project');+ try {+ const configPath = piConfigPath(project);+ const otherPath = join(project, '.pi', 'extensions', 'other.ts');+ const trustPath = join(home, '.pi', 'agent', 'trust.json');+ mkdirSync(join(project, '.pi', 'extensions'), { recursive: true });+ mkdirSync(join(home, '.pi', 'agent'), { recursive: true });+ writeFileSync(configPath, buildPiExtensionSource());+ writeFileSync(otherPath, 'export default function extension() {}');+ const trust = JSON.stringify({ [project]: true });+ writeFileSync(trustPath, trust);++ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, project, home, configPath)).toEqual({+ kind: 'removed',+ trust: 'kept-shared',+ trustDetail: expect.any(String),+ });+ expect(existsSync(configPath)).toBe(false);+ expect(existsSync(otherPath)).toBe(true);+ expect(readFileSync(trustPath, 'utf8')).toBe(trust);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+test('removes OK’s own bridge file (current version)', () => {const dir = tmp();try {@@ -343,3 +464,106 @@ describe('removeOwnMcpEntry — Pi managed extension file', () => {}});});++describe('removeOwnMcpEntry — symlinks', () => {+ test.skipIf(process.platform === 'win32')(+ 'preserves an unreadable configuration target and its symlink',+ () => {+ const dir = tmp();+ try {+ const configPath = join(dir, 'config.json');+ const targetPath = join(dir, 'target.json');+ const raw = '{ malformed user settings ]';+ writeFileSync(targetPath, raw);+ symlinkSync('target.json', configPath);+ expect(removeOwnMcpEntry(EDITOR_TARGETS.claude, dir, undefined, configPath)).toEqual({+ kind: 'declined',+ reason: 'unparseable',+ });+ expect(lstatSync(configPath).isSymbolicLink()).toBe(true);+ expect(readFileSync(targetPath, 'utf8')).toBe(raw);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ },+ );++ test.skipIf(process.platform === 'win32')(+ 'unlinks a managed extension file without deleting its symlink destination',+ () => {+ const dir = tmp();+ try {+ const configPath = join(dir, 'extension.ts');+ const targetPath = join(dir, 'target.ts');+ const raw = buildPiExtensionSource();+ writeFileSync(targetPath, raw);+ symlinkSync('target.ts', configPath);+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, dir, undefined, configPath).kind).toBe(+ 'removed',+ );+ expect(existsSync(configPath)).toBe(false);+ expect(readFileSync(targetPath, 'utf8')).toBe(raw);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ },+ );++ test.skipIf(process.platform === 'win32').each(['claude', 'hermes', 'codex'] as const)(+ 'preserves the %s config symlink chain and edits only its destination',+ (editorId) => {+ const dir = tmp();+ try {+ const configPath = join(dir, 'config');+ const targetPath = join(dir, 'dotfiles-config');+ const chain = (OWN_ENTRY.args as string[])[2];+ const raw =+ editorId === 'codex'+ ? `# user configuration\n[mcp_servers.other]\ncommand = "node"\n\n[mcp_servers.${MCP_SERVER_NAME}]\ncommand = "/bin/sh"\nargs = ["-l", "-c", ${JSON.stringify(chain)}]\n`+ : editorId === 'hermes'+ ? `# user configuration\nmcp_servers:\n other:\n command: node\n ${MCP_SERVER_NAME}: ${JSON.stringify(OWN_ENTRY)}\n`+ : `{\n // user configuration\n "mcpServers": {"other": {"command": "node"}, "${MCP_SERVER_NAME}": ${JSON.stringify(OWN_ENTRY)}}\n}\n`;+ writeFileSync(targetPath, raw, { mode: 0o640 });+ symlinkSync('dotfiles-config', join(dir, 'intermediate'));+ symlinkSync('intermediate', configPath);++ expect(removeOwnMcpEntry(EDITOR_TARGETS[editorId], dir, undefined, configPath).kind).toBe(+ 'removed',+ );+ expect(lstatSync(configPath).isSymbolicLink()).toBe(true);+ expect(readlinkSync(configPath)).toBe('intermediate');+ expect(lstatSync(join(dir, 'intermediate')).isSymbolicLink()).toBe(true);+ const after = readFileSync(targetPath, 'utf8');+ expect(after).toContain('user configuration');+ expect(after).toContain('other');+ expect(after).not.toContain(MCP_SERVER_NAME);+ expect(statSync(targetPath).mode & 0o777).toBe(0o640);+ expect(removeOwnMcpEntry(EDITOR_TARGETS[editorId], dir, undefined, configPath).kind).toBe(+ 'not-present',+ );+ expect(readFileSync(targetPath, 'utf8')).toBe(after);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ },+ );++ test.skipIf(process.platform === 'win32').each(['dangling', 'cycle'])(+ 'declines a %s config symlink without removing it',+ (kind) => {+ const dir = tmp();+ try {+ const configPath = join(dir, 'config.json');+ symlinkSync(kind === 'cycle' ? 'config.json' : 'missing.json', configPath);+ expect(removeOwnMcpEntry(EDITOR_TARGETS.claude, dir, undefined, configPath)).toEqual({+ kind: 'declined',+ reason: kind === 'cycle' ? 'unresolved-symlink' : 'missing-symlink-target',+ });+ expect(lstatSync(configPath).isSymbolicLink()).toBe(true);+ expect(existsSync(join(dir, 'missing.json'))).toBe(false);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ },+ );+});diff --git a/packages/cli/src/commands/mcp-config-removal.ts b/packages/cli/src/commands/mcp-config-removal.tsindex dc20c954b..7adf5cdb1 100644--- a/packages/cli/src/commands/mcp-config-removal.ts+++ b/packages/cli/src/commands/mcp-config-removal.ts@@ -3,20 +3,28 @@ import { atomicWriteFileSync } from '@inkeep/open-knowledge-core/server';import { parseDocument } from 'yaml';import { isOwnPiManagedFileEntry } from '../integrations/pi-extension.ts';import { getTomlConfigEngine } from '../native/toml-config-engine.ts';+import { configFileDeclineReason } from '../utils/config-file-error.ts';import { type EditorMcpTarget, isEntryUpToDate, isOwnManagedEntry } from './editors.ts';-import { classifyExistingMcpEntry, type McpDeclineReason, serverMapPath } from './init.ts';+import { classifyExistingMcpEntry, type McpConfigDeclineReason, serverMapPath } from './init.ts';import { existingFileMode, isCrlfDominant, surgicalJsonDelete } from './jsonc-surgical.ts';import { type PiTrustRemoveAction, removePiTrustEntry } from './pi-acp-bridge.ts';+import { resolveRemovalFilePath } from './removal-file-path.ts';-export type McpRemoveOutcome =+type McpTrustRemoval =| {- kind: 'removed';- trust?: PiTrustRemoveAction;- trustError?: string;+ trust?: Extract<PiTrustRemoveAction, 'removed' | 'not-present'>;+ trustDetail?: never;}+ | {+ trust: Extract<PiTrustRemoveAction, 'kept-shared' | 'kept-unowned'>;+ trustDetail: string;+ };++export type McpRemoveOutcome =+ | ({ kind: 'removed' } & McpTrustRemoval)| { kind: 'not-present' }| { kind: 'left-foreign' }- | { kind: 'declined'; reason: McpDeclineReason };+ | { kind: 'declined'; reason: McpConfigDeclineReason };function isRemovableOwnEntry(entry: unknown): boolean {return isEntryUpToDate(entry) || isOwnManagedEntry(entry) || isOwnPiManagedFileEntry(entry);@@ -24,16 +32,69 @@ function isRemovableOwnEntry(entry: unknown): boolean {const JSON_CONFIG_MAX_BYTES = 10 * 1024 * 1024;+function cleanupPiTrust(+ cwd: string,+ home: string | undefined,+ env: NodeJS.ProcessEnv | undefined,+ recordedOnly = false,+): McpTrustRemoval {+ const trust = removePiTrustEntry(cwd, home, env, { recordedOnly });+ switch (trust.action) {+ case 'removed':+ case 'not-present':+ return { trust: trust.action };+ case 'kept-shared':+ case 'kept-unowned':+ return { trust: trust.action, trustDetail: trust.detail };+ case 'failed':+ case 'refused-unreadable':+ case 'kept-unverified': {+ const retained = recordedOnly+ ? 'Trust cleanup remains incomplete'+ : 'The bridge file was left untouched';+ throw new Error(+ `Pi trust cleanup failed (${trust.action}):\n${trust.error}\n${retained} so cleanup can be retried.`,+ );+ }+ default: {+ const exhaustive: never = trust;+ throw new Error(`unhandled Pi trust cleanup result: ${exhaustive}`);+ }+ }+}++function cleanupAbsentPiBridge(+ target: EditorMcpTarget,+ cwd: string,+ home: string | undefined,+ env: NodeJS.ProcessEnv | undefined,+): McpRemoveOutcome {+ if (target.id !== 'pi') return { kind: 'not-present' };+ const trust = cleanupPiTrust(cwd, home, env, true);+ return trust.trust === 'not-present' ? { kind: 'not-present' } : { kind: 'removed', ...trust };+}+export function removeOwnMcpEntry(target: EditorMcpTarget,cwd: string,home?: string,configPathOverride?: string,+ env?: NodeJS.ProcessEnv,): McpRemoveOutcome {- const classified = classifyExistingMcpEntry(target, cwd, home, configPathOverride);- if (classified.kind === 'absent' || classified.kind === 'no-entry') {+ let configPath: string;+ try {+ configPath = configPathOverride ?? target.configPath(cwd, home);+ } catch {return { kind: 'not-present' };}+ const resolved = resolveRemovalFilePath(configPath);+ if (resolved.kind === 'not-present') return cleanupAbsentPiBridge(target, cwd, home, env);+ if (resolved.kind === 'declined') return resolved;++ const classified = classifyExistingMcpEntry(target, cwd, home, resolved.path);+ if (classified.kind === 'absent' || classified.kind === 'no-entry') {+ return cleanupAbsentPiBridge(target, cwd, home, env);+ }if (classified.kind === 'decline') {return { kind: 'declined', reason: classified.reason };}@@ -41,27 +102,31 @@ export function removeOwnMcpEntry(return { kind: 'left-foreign' };}- let configPath: string;- try {- configPath = configPathOverride ?? target.configPath(cwd, home);- } catch {- return { kind: 'not-present' };- }const serverName = target.serverName(cwd);if (target.format === 'file') {- rmSync(configPath, { force: true });- const trust = removePiTrustEntry(cwd, home);+ const trust = cleanupPiTrust(cwd, home, env);+ try {+ rmSync(configPath, { force: true });+ } catch (error) {+ if (!trust.trustDetail) throw error;+ throw new Error(+ `${error instanceof Error ? error.message : String(error)}\n${trust.trustDetail}`,+ {+ cause: error,+ },+ );+ }return {kind: 'removed',- trust: trust.action,- ...(trust.error !== undefined ? { trustError: trust.error } : {}),+ ...trust,};}- if (target.format === 'toml') return removeTomlEntry(configPath, serverName);- if (target.format === 'yaml') return removeYamlEntry(configPath, target.topLevelKey, serverName);- return removeJsonEntry(configPath, target.topLevelKey, target.serverMapSubKey, serverName);+ if (target.format === 'toml') return removeTomlEntry(resolved.path, serverName);+ if (target.format === 'yaml')+ return removeYamlEntry(resolved.path, target.topLevelKey, serverName);+ return removeJsonEntry(resolved.path, target.topLevelKey, target.serverMapSubKey, serverName);}function removeJsonEntry(@@ -73,8 +138,8 @@ function removeJsonEntry(let raw: string;try {raw = readFileSync(configPath, 'utf-8');- } catch {- return { kind: 'declined', reason: 'unparseable' };+ } catch (error) {+ return { kind: 'declined', reason: configFileDeclineReason(error) };}if (Buffer.byteLength(raw, 'utf-8') > JSON_CONFIG_MAX_BYTES) {return { kind: 'declined', reason: 'oversize' };@@ -96,8 +161,8 @@ function removeYamlEntry(let raw: string;try {raw = readFileSync(configPath, 'utf-8');- } catch {- return { kind: 'declined', reason: 'unparseable' };+ } catch (error) {+ return { kind: 'declined', reason: configFileDeclineReason(error) };}if (Buffer.byteLength(raw, 'utf-8') > JSON_CONFIG_MAX_BYTES) {return { kind: 'declined', reason: 'oversize' };@@ -143,8 +208,8 @@ function removeTomlEntry(configPath: string, serverName: string): McpRemoveOutcolet raw: string;try {raw = readFileSync(configPath, 'utf-8');- } catch {- return { kind: 'declined', reason: 'unparseable' };+ } catch (error) {+ return { kind: 'declined', reason: configFileDeclineReason(error) };}const hasBom = raw.charCodeAt(0) === 0xfeff;diff --git a/packages/cli/src/commands/pi-acp-bridge.test.ts b/packages/cli/src/commands/pi-acp-bridge.test.tsindex 5cdb15855..0031c60a2 100644--- a/packages/cli/src/commands/pi-acp-bridge.test.ts+++ b/packages/cli/src/commands/pi-acp-bridge.test.ts@@ -1,31 +1,50 @@import {chmodSync,+ existsSync,+ lstatSync,mkdirSync,mkdtempSync,+ readdirSync,readFileSync,+ readlinkSync,+ realpathSync,+ renameSync,rmSync,statSync,+ symlinkSync,+ unlinkSync,utimesSync,writeFileSync,} from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';-import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import lockfile from 'proper-lockfile';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import { buildPiExtensionSource, isOwnPiExtensionSource } from '../integrations/pi-extension.ts';-import { PI_EXTENSION_OWNERSHIP_MARKER } from './editors.ts';+import { EDITOR_TARGETS, PI_EXTENSION_OWNERSHIP_MARKER } from './editors.ts';+import { removeOwnMcpEntry } from './mcp-config-removal.ts';import { ensurePiBridge, probePiBridgeState, removePiTrustEntry } from './pi-acp-bridge.ts';+import { commitPiTrustGrant, listPiTrustGrants, preparePiTrustGrant } from './pi-trust-grants.ts';+import { withPiTrustLockSync } from './pi-trust-lock.ts';let dirs: string[] = [];function tmp(): string {- const d = mkdtempSync(join(tmpdir(), 'pi-acp-bridge-'));+ const d = realpathSync(mkdtempSync(join(tmpdir(), 'pi-acp-bridge-')));dirs.push(d);return d;}afterEach(() => {+ vi.restoreAllMocks();for (const d of dirs) rmSync(d, { recursive: true, force: true });dirs = [];});+function probeReadyPiBridgeState(...args: Parameters<typeof probePiBridgeState>) {+ const state = probePiBridgeState(...args);+ if (state.project !== 'ready') throw new Error(state.error);+ return state;+}+const bridgePathIn = (cwd: string) => join(cwd, '.pi', 'extensions', 'open-knowledge.ts');const trustPathIn = (home: string) => join(home, '.pi', 'agent', 'trust.json');@@ -54,8 +73,10 @@ describe('probePiBridgeState', () => {test('reports absent bridge + untrusted folder when nothing exists', async () => {const cwd = tmp();const home = tmp();- expect(probePiBridgeState(cwd, home)).toEqual({+ expect(probeReadyPiBridgeState(cwd, home)).toEqual({cwd,+ project: 'ready',+ canonicalCwd: cwd,otherExtensions: [],bridgePath: bridgePathIn(cwd),trustPath: trustPathIn(home),@@ -65,11 +86,43 @@ describe('probePiBridgeState', () => {});});+ test('escapes extension names for display after filtering and sorting without changing files', () => {+ const cwd = tmp();+ const home = tmp();+ const extensionDir = dirname(bridgePathIn(cwd));+ const names = [+ 'safe\u202e.ts',+ 'hidden\u200b.ts',+ 'zeta.ts',+ 'prettier.ts, tailwind.ts, eslint.ts',+ 'helper.ts. No other extensions are present.ts',+ ...(process.platform === 'win32' ? [] : ['quoted"name.ts']),+ ];+ for (const name of names) write(join(extensionDir, name), `User extension ${name}`);+ write(bridgePathIn(cwd), buildPiExtensionSource({ mode: 'published' }));+ write(join(extensionDir, 'notes.txt'), 'not an extension');++ expect(probeReadyPiBridgeState(cwd, home).otherExtensions).toEqual([+ '"helper.ts. No other extensions are present.ts"',+ '"hidden\\u200b.ts"',+ '"prettier.ts, tailwind.ts, eslint.ts"',+ ...(process.platform === 'win32' ? [] : ['"quoted\\"name.ts"']),+ '"safe\\u202e.ts"',+ '"zeta.ts"',+ ]);+ expect(readdirSync(extensionDir).sort()).toEqual(+ [...names, 'open-knowledge.ts', 'notes.txt'].sort(),+ );+ for (const name of names)+ expect(readFileSync(join(extensionDir, name), 'utf8')).toBe(`User extension ${name}`);+ expect(existsSync(trustPathIn(home))).toBe(false);+ });+test('normalizes the cwd it reports and keys trust on', async () => {const cwd = tmp();const home = tmp();write(trustPathIn(home), JSON.stringify({ [cwd]: true }));- const state = probePiBridgeState(`${cwd}/./`, home);+ const state = probeReadyPiBridgeState(`${cwd}/./`, home);expect(state.cwd).toBe(cwd);expect(state.trust).toBe('trusted');});@@ -79,7 +132,7 @@ describe('probePiBridgeState', () => {const home = tmp();write(bridgePathIn(cwd), buildPiExtensionSource({ mode: 'published' }));write(trustPathIn(home), JSON.stringify({ [cwd]: true }, null, 2));- const state = probePiBridgeState(cwd, home);+ const state = probeReadyPiBridgeState(cwd, home);expect(state.bridge).toBe('own-current');expect(state.trust).toBe('trusted');expect(state.bridgeLoadable).toBe(true);@@ -93,13 +146,13 @@ describe('probePiBridgeState', () => {await withDevArgv(async () =>write(bridgePathIn(cwd), buildPiExtensionSource({ mode: 'dev' })),);- expect(probePiBridgeState(cwd, home)).toMatchObject({+ expect(probeReadyPiBridgeState(cwd, home)).toMatchObject({bridge: 'own-stale',bridgeLoadable: true,});write(bridgePathIn(cwd), `${PI_EXTENSION_OWNERSHIP_MARKER}-v0\n// legacy body\n`);- expect(probePiBridgeState(cwd, home)).toMatchObject({+ expect(probeReadyPiBridgeState(cwd, home)).toMatchObject({bridge: 'own-stale',bridgeLoadable: true,});@@ -110,7 +163,7 @@ describe('probePiBridgeState', () => {const home = tmp();write(bridgePathIn(cwd), 'export default function mine() {}\n');write(trustPathIn(home), JSON.stringify({ [cwd]: true }));- const state = probePiBridgeState(cwd, home);+ const state = probeReadyPiBridgeState(cwd, home);expect(state.bridge).toBe('foreign');expect(state.bridgeLoadable).toBe(false);});@@ -119,7 +172,7 @@ describe('probePiBridgeState', () => {const cwd = tmp();const home = tmp();write(bridgePathIn(cwd), ' \n');- expect(probePiBridgeState(cwd, home).bridge).toBe('absent');+ expect(probeReadyPiBridgeState(cwd, home).bridge).toBe('absent');});test('trust states: missing entry, explicit false, corrupt, non-object', async () => {@@ -127,19 +180,19 @@ describe('probePiBridgeState', () => {const home = tmp();write(trustPathIn(home), JSON.stringify({ '/somewhere/else': true }));- expect(probePiBridgeState(cwd, home).trust).toBe('untrusted');+ expect(probeReadyPiBridgeState(cwd, home).trust).toBe('untrusted');write(trustPathIn(home), JSON.stringify({ [cwd]: false }));- expect(probePiBridgeState(cwd, home).trust).toBe('untrusted');+ expect(probeReadyPiBridgeState(cwd, home).trust).toBe('untrusted');write(trustPathIn(home), '{not json');- expect(probePiBridgeState(cwd, home).trust).toBe('unreadable');+ expect(probeReadyPiBridgeState(cwd, home).trust).toBe('unreadable');write(trustPathIn(home), JSON.stringify([cwd]));- expect(probePiBridgeState(cwd, home).trust).toBe('unreadable');+ expect(probeReadyPiBridgeState(cwd, home).trust).toBe('unreadable');write(trustPathIn(home), '');- expect(probePiBridgeState(cwd, home).trust).toBe('untrusted');+ expect(probeReadyPiBridgeState(cwd, home).trust).toBe('untrusted');});describe('with PI_CODING_AGENT_DIR set on the machine', () => {@@ -156,14 +209,40 @@ describe('probePiBridgeState', () => {const cwd = tmp();const home = tmp();write(trustPathIn(home), JSON.stringify({ [cwd]: true }));- const state = probePiBridgeState(cwd, home);+ const state = probeReadyPiBridgeState(cwd, home);expect(state.trustPath).toBe(trustPathIn(home));expect(state.trust).toBe('trusted');});test('without an injected home the env override is honored', async () => {const cwd = tmp();- expect(probePiBridgeState(cwd).trustPath).toBe('/nonexistent/pi-agent-dir/trust.json');+ expect(probeReadyPiBridgeState(cwd).trustPath).toBe('/nonexistent/pi-agent-dir/trust.json');+ });++ test('an explicit environment selects the same trust store for ensure, probe and removal', async () => {+ const cwd = tmp();+ const home = tmp();+ const agentDir = tmp();+ const env = { PI_CODING_AGENT_DIR: agentDir };+ const trustPath = join(agentDir, 'trust.json');+ const unrelated = tmp();+ const defaultTrust = `${JSON.stringify({ [cwd]: true })}\n`;+ write(trustPathIn(home), defaultTrust);+ write(trustPath, JSON.stringify({ [unrelated]: true }));++ expect(await ensurePiBridge(cwd, { mode: 'published' }, home, env)).toMatchObject({+ ok: true,+ trustPath,+ trust: 'added',+ });+ expect(probeReadyPiBridgeState(cwd, home, env)).toMatchObject({+ trustPath,+ bridgeLoadable: true,+ });+ expect(removePiTrustEntry(cwd, home, env).action).toBe('removed');+ expect(probeReadyPiBridgeState(cwd, home, env).trust).toBe('untrusted');+ expect(JSON.parse(readFileSync(trustPath, 'utf8'))).toEqual({ [unrelated]: true });+ expect(readFileSync(trustPathIn(home), 'utf8')).toBe(defaultTrust);});});});@@ -185,7 +264,7 @@ describe('ensurePiBridge', () => {buildPiExtensionSource({ mode: 'published' }),);expect(JSON.parse(readFileSync(trustPathIn(home), 'utf-8'))).toEqual({ [cwd]: true });- expect(probePiBridgeState(cwd, home).bridgeLoadable).toBe(true);+ expect(probeReadyPiBridgeState(cwd, home).bridgeLoadable).toBe(true);});test('defaults to the published shape `ok init` writes', async () => {@@ -226,11 +305,13 @@ describe('ensurePiBridge', () => {await ensurePiBridge(cwd, { mode: 'published' }, home);const bridgeMtime = freezeMtime(bridgePathIn(cwd));const trustMtime = freezeMtime(trustPathIn(home));+ const receipts = listPiTrustGrants(home, cwd);const second = await ensurePiBridge(cwd, { mode: 'published' }, home);expect(second).toMatchObject({ ok: true, bridge: 'unchanged', trust: 'already-trusted' });expect(statSync(bridgePathIn(cwd)).mtimeMs).toBe(bridgeMtime);expect(statSync(trustPathIn(home)).mtimeMs).toBe(trustMtime);+ expect(listPiTrustGrants(home, cwd)).toEqual(receipts);});test('refreshes an own stale bridge, including a mode flip', async () => {@@ -328,7 +409,1481 @@ describe('ensurePiBridge', () => {});});+describe.skipIf(process.platform === 'win32')('symlinked Pi trust stores', () => {+ function fixture() {+ const cwd = tmp();+ const home = tmp();+ const target = join(tmp(), 'trust.json');+ const trustPath = trustPathIn(home);+ const entries = { other: true, settings: { nested: ['preserve', 42] } };+ write(target, `${JSON.stringify(entries, null, 2)}\n`);+ chmodSync(target, 0o640);+ mkdirSync(dirname(trustPath), { recursive: true });+ symlinkSync(target, trustPath);+ return { cwd, home, target, trustPath, entries };+ }++ test('adds trust through the link and preserves the target mode and unrelated entries', async () => {+ const { cwd, home, target, trustPath, entries } = fixture();++ expect(await ensurePiBridge(cwd, { mode: 'published' }, home)).toMatchObject({+ ok: true,+ trust: 'added',+ trustPath,+ });++ expect(lstatSync(trustPath).isSymbolicLink()).toBe(true);+ expect(readlinkSync(trustPath)).toBe(target);+ expect(statSync(target).mode & 0o777).toBe(0o640);+ expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual({ ...entries, [cwd]: true });+ expect(probeReadyPiBridgeState(cwd, home)).toMatchObject({ trustPath, bridgeLoadable: true });+ });++ test('preserves pre-existing trust and its symlink while removing the bridge', async () => {+ const { cwd, home, target, trustPath, entries } = fixture();+ write(target, `${JSON.stringify({ ...entries, [cwd]: true }, null, 2)}\n`);+ expect((await ensurePiBridge(cwd, { mode: 'published' }, home)).trust).toBe('already-trusted');++ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toEqual({+ kind: 'removed',+ trust: 'kept-unowned',+ trustDetail: expect.any(String),+ });++ expect(lstatSync(trustPath).isSymbolicLink()).toBe(true);+ expect(readlinkSync(trustPath)).toBe(target);+ expect(readFileSync(target, 'utf8')).toBe(+ `${JSON.stringify({ ...entries, [cwd]: true }, null, 2)}\n`,+ );+ expect(statSync(target).mode & 0o777).toBe(0o640);+ expect(existsSync(bridgePathIn(cwd))).toBe(false);+ expect(probeReadyPiBridgeState(cwd, home).trust).toBe('trusted');+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ });++ test.each([+ ['missing', 'the symlink target is missing', 'restore the target or correct the symlink'],+ ['cycle', 'the path or symlink could not be resolved', 'repair any symlink cycle'],+ ['malformed', 'the file is not a valid JSON object', 'repair its JSON'],+ ] as const)(+ 'refuses a %s trust target without deleting the bridge and succeeds after repair',+ async (problem, cause, remedy) => {+ const { cwd, home, target, trustPath, entries } = fixture();+ const trusted = `${JSON.stringify({ ...entries, [cwd]: true }, null, 2)}\n`;+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ const bridge = readFileSync(bridgePathIn(cwd), 'utf8');+ if (problem === 'missing') unlinkSync(target);+ if (problem === 'malformed') write(target, '{ broken json');+ if (problem === 'cycle') {+ unlinkSync(trustPath);+ symlinkSync(trustPath, trustPath);+ }+ const link = readlinkSync(trustPath);+ const targetBytes = problem === 'missing' ? undefined : readFileSync(target, 'utf8');++ expect(probeReadyPiBridgeState(cwd, home).trust).toBe('unreadable');+ const result = await ensurePiBridge(cwd, { mode: 'published' }, home);+ expect(result).toMatchObject({+ ok: false,+ trust: 'refused-unreadable',+ });+ expect(result.error).toContain(cause);+ expect(result.error).toContain(remedy);+ expect(result.error).toContain(trustPath);+ expect(result.error).not.toMatch(/missing-symlink-target|unresolved-symlink/);+ expect(() => removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toThrow(+ cause,+ );+ expect(readFileSync(bridgePathIn(cwd), 'utf8')).toBe(bridge);+ expect(lstatSync(trustPath).isSymbolicLink()).toBe(true);+ expect(readlinkSync(trustPath)).toBe(link);+ if (targetBytes === undefined) expect(existsSync(target)).toBe(false);+ else expect(readFileSync(target, 'utf8')).toBe(targetBytes);++ if (problem === 'cycle') {+ unlinkSync(trustPath);+ symlinkSync(target, trustPath);+ }+ write(target, trusted);+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd)).kind).toBe(+ 'removed',+ );+ expect(readlinkSync(trustPath)).toBe(target);+ expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual(entries);+ expect(existsSync(bridgePathIn(cwd))).toBe(false);+ },+ );++ test.skipIf(process.getuid?.() === 0)(+ 'preserves an unreadable target and its bridge until permissions are repaired',+ async () => {+ const { cwd, home, target, trustPath, entries } = fixture();+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ const before = readFileSync(target, 'utf8');+ const bridge = readFileSync(bridgePathIn(cwd), 'utf8');+ chmodSync(target, 0o000);+ try {+ expect(probeReadyPiBridgeState(cwd, home).trust).toBe('unreadable');+ const result = await ensurePiBridge(cwd, { mode: 'published' }, home);+ expect(result).toMatchObject({+ ok: false,+ trust: 'refused-unreadable',+ });+ expect(result.error).toContain('permission denied');+ expect(result.error).toContain('check file and parent-directory permissions');+ expect(result.error).not.toMatch(/JSON|permission-denied/);+ expect(() => removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toThrow(+ 'permission denied; check file and parent-directory permissions',+ );+ expect(readFileSync(bridgePathIn(cwd), 'utf8')).toBe(bridge);+ expect(readlinkSync(trustPath)).toBe(target);+ } finally {+ chmodSync(target, 0o640);+ }+ expect(readFileSync(target, 'utf8')).toBe(before);+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd)).kind).toBe(+ 'removed',+ );+ expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual(entries);+ expect(statSync(target).mode & 0o777).toBe(0o640);+ },+ );++ test.each([false, true])(+ 'waits for the canonical target lock and rejects a retargeted link (retarget=%s)',+ async (retarget) => {+ const { cwd, home, target, trustPath, entries } = fixture();+ const canonicalLock = `${realpathSync(target)}.ok.lock`;+ const otherTarget = join(tmp(), 'trust.json');+ const before = readFileSync(target, 'utf8');+ const otherBytes = '{"untouched": true}\n';+ write(otherTarget, otherBytes);+ write(canonicalLock, 'held');+ const pending = ensurePiBridge(cwd, { mode: 'published' }, home);+ try {+ expect(+ await Promise.race([+ pending.then(() => 'finished'),+ new Promise<string>((resolve) => setTimeout(() => resolve('waiting'), 75)),+ ]),+ ).toBe('waiting');+ expect(readFileSync(target, 'utf8')).toBe(before);+ if (retarget) {+ unlinkSync(trustPath);+ symlinkSync(otherTarget, trustPath);+ }+ } finally {+ unlinkSync(canonicalLock);+ await pending;+ }+ const result = await pending;+ if (retarget) {+ expect(result).toMatchObject({ ok: false, trust: 'refused-unreadable' });+ expect(result.error).toContain('path changed while waiting for its lock');+ expect(result.error).toContain('retry to check its current state');+ expect(result.error).not.toContain('permissions');+ expect(readFileSync(target, 'utf8')).toBe(before);+ expect(readFileSync(otherTarget, 'utf8')).toBe(otherBytes);+ expect(readlinkSync(trustPath)).toBe(otherTarget);+ } else {+ expect(result).toMatchObject({ ok: true, trust: 'added' });+ expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual({ ...entries, [cwd]: true });+ expect(readlinkSync(trustPath)).toBe(target);+ }+ },+ );++ test('creates and removes trust through a symlinked ancestor without replacing the directory link', async () => {+ const cwd = tmp();+ const other = tmp();+ const home = tmp();+ const realPiDir = tmp();+ const piLink = join(home, '.pi');+ const target = join(realPiDir, 'agent', 'trust.json');+ const settings = join(realPiDir, 'settings.json');+ write(settings, '{"keep": "these settings"}\n');+ symlinkSync(realPiDir, piLink, 'dir');++ expect(existsSync(target)).toBe(false);+ expect((await ensurePiBridge(cwd, { mode: 'published' }, home)).ok).toBe(true);+ expect((await ensurePiBridge(other, { mode: 'published' }, home)).ok).toBe(true);+ expect(probeReadyPiBridgeState(cwd, home).bridgeLoadable).toBe(true);+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toEqual({+ kind: 'removed',+ trust: 'removed',+ });++ expect(lstatSync(piLink).isSymbolicLink()).toBe(true);+ expect(readlinkSync(piLink)).toBe(realPiDir);+ expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual({ [other]: true });+ expect(readFileSync(settings, 'utf8')).toBe('{"keep": "these settings"}\n');+ });++ test('refuses a dangling ancestor and succeeds after the directory target is restored', async () => {+ const cwd = tmp();+ const home = tmp();+ const realPiDir = join(tmp(), 'missing-pi');+ const piLink = join(home, '.pi');+ symlinkSync(realPiDir, piLink, 'dir');++ const first = await ensurePiBridge(cwd, { mode: 'published' }, home);+ expect(first).toMatchObject({ ok: false, trust: 'refused-unreadable' });+ expect(first.error).toContain('the symlink target is missing');+ expect(first.error).toContain('restore the target or correct the symlink');+ expect(probeReadyPiBridgeState(cwd, home).trust).toBe('unreadable');+ expect(() => removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toThrow(+ 'the symlink target is missing',+ );+ expect(readlinkSync(piLink)).toBe(realPiDir);+ expect(existsSync(realPiDir)).toBe(false);+ expect(existsSync(bridgePathIn(cwd))).toBe(true);++ mkdirSync(realPiDir);+ expect((await ensurePiBridge(cwd, { mode: 'published' }, home)).ok).toBe(true);+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd)).kind).toBe('removed');+ expect(readlinkSync(piLink)).toBe(realPiDir);+ expect(JSON.parse(readFileSync(join(realPiDir, 'agent', 'trust.json'), 'utf8'))).toEqual({});+ });+});++describe('owned Pi trust grants', () => {+ test('restores an explicit refusal after a consented grant is removed', async () => {+ const cwd = tmp();+ const home = tmp();+ const trustPath = trustPathIn(home);+ const previous = { [dirname(cwd)]: true, [cwd]: false, other: true };+ write(trustPath, `${JSON.stringify(previous, null, 2)}\n`);++ expect((await ensurePiBridge(cwd, { mode: 'published' }, home)).ok).toBe(true);+ expect(listPiTrustGrants(home, cwd)).toMatchObject([+ { record: { state: 'committed', previous: { present: true, value: false } } },+ ]);+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toEqual({+ kind: 'removed',+ trust: 'removed',+ });++ expect(JSON.parse(readFileSync(trustPath, 'utf8'))).toEqual(previous);+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ expect(existsSync(bridgePathIn(cwd))).toBe(false);+ });++ test('preserves a pending grant whose successful ownership was never recorded', () => {+ const cwd = tmp();+ const home = tmp();+ const trustPath = trustPathIn(home);+ const before = `${JSON.stringify({ [cwd]: true, other: true })}\n`;+ write(trustPath, before);+ write(bridgePathIn(cwd), buildPiExtensionSource({ mode: 'published' }));+ const canonicalPath = realpathSync(trustPath);+ withPiTrustLockSync(trustPath, canonicalPath, () => {+ preparePiTrustGrant(home, cwd, trustPath, canonicalPath, { present: false });+ });++ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toEqual({+ kind: 'removed',+ trust: 'kept-unowned',+ trustDetail: expect.any(String),+ });++ expect(readFileSync(trustPath, 'utf8')).toBe(before);+ expect(listPiTrustGrants(home, cwd)).toMatchObject([{ record: { state: 'pending' } }]);+ expect(existsSync(bridgePathIn(cwd))).toBe(false);+ });++ test('reconciles every recorded custom store without the original environment override', async () => {+ const cwd = tmp();+ const home = tmp();+ const agentDirs = [tmp(), tmp()] as const;+ const defaultTrust = `${JSON.stringify({ [cwd]: true, defaultStore: true })}\n`;+ write(trustPathIn(home), defaultTrust);+ for (const agentDir of agentDirs) {+ write(join(agentDir, 'trust.json'), '{"other":true}\n');+ expect(+ (await ensurePiBridge(cwd, { mode: 'published' }, home, { PI_CODING_AGENT_DIR: agentDir }))+ .ok,+ ).toBe(true);+ }+ expect(listPiTrustGrants(home, cwd)).toHaveLength(2);++ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toEqual({+ kind: 'removed',+ trust: 'kept-unowned',+ trustDetail: expect.stringContaining(trustPathIn(home)),+ });++ for (const agentDir of agentDirs) {+ expect(JSON.parse(readFileSync(join(agentDir, 'trust.json'), 'utf8'))).toEqual({+ other: true,+ });+ }+ expect(readFileSync(trustPathIn(home), 'utf8')).toBe(defaultTrust);+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ });++ test('keeps a grant used by project prompts and relinquishes its ownership record', async () => {+ const cwd = tmp();+ const home = tmp();+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ const before = readFileSync(trustPathIn(home), 'utf8');+ const promptPath = join(cwd, '.pi', 'prompts', 'review.md');+ write(promptPath, 'User-authored prompt\n');++ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toEqual({+ kind: 'removed',+ trust: 'kept-shared',+ trustDetail: expect.any(String),+ });++ expect(readFileSync(trustPathIn(home), 'utf8')).toBe(before);+ expect(readFileSync(promptPath, 'utf8')).toBe('User-authored prompt\n');+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ rmSync(dirname(promptPath), { recursive: true });+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toEqual({+ kind: 'not-present',+ });+ expect(readFileSync(trustPathIn(home), 'utf8')).toBe(before);+ });++ test('cleans independent recorded stores while retaining a failed store and the bridge for retry', async () => {+ const cwd = tmp();+ const home = tmp();+ const agentDirs = [tmp(), tmp()] as const;+ for (const agentDir of agentDirs) {+ write(join(agentDir, 'trust.json'), '{"other":true}\n');+ await ensurePiBridge(cwd, { mode: 'published' }, home, { PI_CODING_AGENT_DIR: agentDir });+ }+ const failedPath = join(agentDirs[0], 'trust.json');+ const repairedBytes = readFileSync(failedPath, 'utf8');+ write(failedPath, '{broken trust');++ expect(() => removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toThrow(+ 'repair its JSON, then retry',+ );+ expect(readFileSync(failedPath, 'utf8')).toBe('{broken trust');+ expect(JSON.parse(readFileSync(join(agentDirs[1], 'trust.json'), 'utf8'))).toEqual({+ other: true,+ });+ expect(existsSync(bridgePathIn(cwd))).toBe(true);+ expect(listPiTrustGrants(home, cwd)).toMatchObject([+ { record: { configuredTrustPath: failedPath } },+ ]);++ write(failedPath, repairedBytes);+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toEqual({+ kind: 'removed',+ trust: 'removed',+ });+ expect(JSON.parse(readFileSync(failedPath, 'utf8'))).toEqual({ other: true });+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ });++ test('retains shared-trust handoff guidance when the Pi lock cannot be released', async () => {+ const cwd = tmp();+ const home = tmp();+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ const promptPath = join(cwd, '.pi', 'prompts', 'review.md');+ write(promptPath, 'User-authored prompt\n');+ const trustPath = trustPathIn(home);+ const before = readFileSync(trustPath, 'utf8');+ const originalLockSync = lockfile.lockSync;+ const unexpectedFile = join(`${trustPath}.lock`, 'keep.txt');+ vi.spyOn(lockfile, 'lockSync').mockImplementation((path, options) => {+ const release = originalLockSync(path, options);+ return () => {+ writeFileSync(unexpectedFile, 'preserve this file');+ release();+ };+ });++ const result = removePiTrustEntry(cwd, home);++ expect(result.action).toBe('failed');+ expect(result.error).toContain('ENOTEMPTY');+ expect(result.error).toContain(dirname(promptPath));+ expect(result.error).toContain('To remove this grant manually');+ expect(result.error).toContain('OpenKnowledge has relinquished this grant');+ expect(readFileSync(trustPath, 'utf8')).toBe(before);+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ expect(existsSync(bridgePathIn(cwd))).toBe(true);+ expect(readFileSync(unexpectedFile, 'utf8')).toBe('preserve this file');+ });++ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(+ 'retains neutral shared-trust guidance when its ownership record cannot be removed',+ async () => {+ const cwd = tmp();+ const home = tmp();+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ const promptPath = join(cwd, '.pi', 'prompts', 'review.md');+ write(promptPath, 'User-authored prompt\n');+ const [receipt] = listPiTrustGrants(home, cwd);+ if (!receipt) throw new Error('expected committed receipt');+ chmodSync(dirname(receipt.path), 0o500);+ try {+ const result = removePiTrustEntry(cwd, home);+ expect(result.action).toBe('failed');+ expect(result.error).toContain(dirname(promptPath));+ expect(result.error).toContain('To remove this grant manually');+ expect(result.error).toContain('may stop Pi from loading');+ expect(result.error).not.toContain('has relinquished');+ expect(result.error).toContain(+ 'check receipt and parent-directory permissions, then retry',+ );+ expect(result.error).not.toContain('retry to check its current state');+ expect(listPiTrustGrants(home, cwd)).toEqual([receipt]);+ expect(existsSync(bridgePathIn(cwd))).toBe(true);+ } finally {+ chmodSync(dirname(receipt.path), 0o700);+ }+ },+ );++ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(+ 'adds retry guidance after a trust write loses directory access without losing its receipt',+ async () => {+ const cwd = tmp();+ const home = tmp();+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ const trustPath = trustPathIn(home);+ const trustDirectory = dirname(trustPath);+ const before = readFileSync(trustPath, 'utf8');+ const receipts = listPiTrustGrants(home, cwd);+ const originalLockSync = lockfile.lockSync;+ vi.spyOn(lockfile, 'lockSync').mockImplementationOnce((path, options) => {+ const release = originalLockSync(path, options);+ chmodSync(trustDirectory, 0o555);+ return () => {+ chmodSync(trustDirectory, 0o700);+ release();+ };+ });++ try {+ const result = removePiTrustEntry(cwd, home);++ expect(result.action).toBe('failed');+ expect(result.error).toContain('EACCES');+ expect(result.error).toContain('retry to check its current state');+ expect(readFileSync(trustPath, 'utf8')).toBe(before);+ expect(listPiTrustGrants(home, cwd)).toEqual(receipts);+ expect(existsSync(bridgePathIn(cwd))).toBe(true);+ } finally {+ chmodSync(trustDirectory, 0o700);+ }++ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toMatchObject({+ kind: 'removed',+ trust: 'removed',+ });+ expect(JSON.parse(readFileSync(trustPath, 'utf8'))).toEqual({});+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ },+ );++ test.skipIf(process.platform === 'win32')(+ 'preserves both stores when a recorded symlink is retargeted until the link is repaired',+ async () => {+ const cwd = tmp();+ const home = tmp();+ const trustPath = trustPathIn(home);+ const firstTarget = join(tmp(), 'first.json');+ const otherTarget = join(tmp(), 'other.json');+ write(firstTarget, '{"other":true}\n');+ write(otherTarget, `${JSON.stringify({ [cwd]: true, unrelated: true })}\n`);+ mkdirSync(dirname(trustPath), { recursive: true });+ symlinkSync(firstTarget, trustPath);+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ const firstBytes = readFileSync(firstTarget, 'utf8');+ const otherBytes = readFileSync(otherTarget, 'utf8');+ unlinkSync(trustPath);+ symlinkSync(otherTarget, trustPath);++ expect(() => removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toThrow(+ 'restore the intended file location or symlink, then retry',+ );+ expect(readlinkSync(trustPath)).toBe(otherTarget);+ expect(readFileSync(firstTarget, 'utf8')).toBe(firstBytes);+ expect(readFileSync(otherTarget, 'utf8')).toBe(otherBytes);+ expect(existsSync(bridgePathIn(cwd))).toBe(true);+ expect(listPiTrustGrants(home, cwd)).toHaveLength(1);++ unlinkSync(trustPath);+ symlinkSync(firstTarget, trustPath);+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd)).kind).toBe(+ 'removed',+ );+ expect(readlinkSync(trustPath)).toBe(firstTarget);+ expect(JSON.parse(readFileSync(firstTarget, 'utf8'))).toEqual({ other: true });+ expect(readFileSync(otherTarget, 'utf8')).toBe(otherBytes);+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ },+ );++ test('forgets stale ownership after the user changes a granted decision', async () => {+ const cwd = tmp();+ const home = tmp();+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ const before = `${JSON.stringify({ [cwd]: false, other: true })}\n`;+ write(trustPathIn(home), before);++ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toEqual({+ kind: 'removed',+ trust: 'not-present',+ });++ expect(readFileSync(trustPathIn(home), 'utf8')).toBe(before);+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ });++ test('does not grant trust when its ownership record cannot be prepared', async () => {+ const cwd = tmp();+ const home = tmp();+ const trustPath = trustPathIn(home);+ const before = '{"other":true}\n';+ write(trustPath, before);+ write(join(home, '.ok', 'pi-trust'), 'not a directory');++ const result = await ensurePiBridge(cwd, { mode: 'published' }, home);++ expect(result).toMatchObject({ ok: false, trust: 'failed' });+ expect(result.error).toContain('Pi trust receipt at');+ expect(result.error).toContain('then retry');+ expect(readFileSync(trustPath, 'utf8')).toBe(before);+ expect(existsSync(bridgePathIn(cwd))).toBe(true);+ });++ test('preserves the bridge and grant if an existing ownership record cannot be read', async () => {+ const cwd = tmp();+ const home = tmp();+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ const [receipt] = listPiTrustGrants(home, cwd);+ expect(receipt).toBeDefined();+ if (!receipt) throw new Error('expected committed Pi trust receipt');+ const recordBytes = readFileSync(receipt.path, 'utf8');+ const trustBytes = readFileSync(trustPathIn(home), 'utf8');+ write(receipt.path, '{broken record');++ expect(() => removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toThrow(+ 'Pi trust receipt at',+ );+ expect(existsSync(bridgePathIn(cwd))).toBe(true);+ expect(readFileSync(trustPathIn(home), 'utf8')).toBe(trustBytes);+ expect(readFileSync(receipt.path, 'utf8')).toBe('{broken record');++ write(receipt.path, recordBytes);+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd)).kind).toBe('removed');+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ });++ test('does not inspect unrelated Pi state when only recorded grants are requested', () => {+ const cwd = join(tmp(), 'no-project');+ const home = tmp();+ write(trustPathIn(home), '{unrelated unreadable trust');++ expect(removePiTrustEntry(cwd, home, undefined, { recordedOnly: true })).toEqual({+ action: 'not-present',+ });+ });++ test('forgets a recorded grant whose ordinary trust file was already deleted', async () => {+ const cwd = tmp();+ const home = tmp();+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ unlinkSync(trustPathIn(home));++ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toEqual({+ kind: 'removed',+ trust: 'not-present',+ });+ expect(existsSync(trustPathIn(home))).toBe(false);+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ });++ test('retains the receipt and bridge when its recorded trust directory is unavailable', async () => {+ const cwd = tmp();+ const home = tmp();+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ rmSync(dirname(trustPathIn(home)), { recursive: true });++ expect(() => removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toThrow(+ 'Restore access to its parent directory or mounted drive, then retry',+ );+ expect(existsSync(dirname(trustPathIn(home)))).toBe(false);+ expect(existsSync(bridgePathIn(cwd))).toBe(true);+ expect(listPiTrustGrants(home, cwd)).toHaveLength(1);+ });+});++describe('canonical Pi project identity', () => {+ test.each([false, true])(+ 'requires the project identity approved before setup (retarget=%s)',+ async (retarget) => {+ const approvedProject = tmp();+ const otherProject = tmp();+ const home = tmp();+ const alias = join(tmp(), 'project-link');+ symlinkSync(approvedProject, alias, process.platform === 'win32' ? 'junction' : 'dir');+ const before = '{"unrelated":false}\n';+ write(trustPathIn(home), before);+ const approved = probeReadyPiBridgeState(alias, home).canonicalCwd;+ if (retarget) {+ unlinkSync(alias);+ symlinkSync(otherProject, alias, process.platform === 'win32' ? 'junction' : 'dir');+ }++ const result = await ensurePiBridge(alias, { mode: 'published' }, home, undefined, approved);++ if (retarget) {+ expect(result).toMatchObject({+ ok: false,+ bridge: 'refused-project-path',+ trust: 'skipped',+ });+ expect(result.error).toContain(approvedProject);+ expect(result.error).toContain(otherProject);+ expect(result.error).toContain(+ 'Reopen the intended project and approve the Pi integration again',+ );+ expect(readFileSync(trustPathIn(home), 'utf8')).toBe(before);+ expect(existsSync(bridgePathIn(approvedProject))).toBe(false);+ expect(existsSync(bridgePathIn(otherProject))).toBe(false);+ expect(listPiTrustGrants(home, approvedProject)).toEqual([]);+ expect(listPiTrustGrants(home, otherProject)).toEqual([]);+ } else {+ expect(result).toMatchObject({ ok: true, bridge: 'written', trust: 'added' });+ expect(JSON.parse(readFileSync(trustPathIn(home), 'utf8'))).toEqual({+ unrelated: false,+ [approvedProject]: true,+ });+ expect(existsSync(bridgePathIn(approvedProject))).toBe(true);+ expect(existsSync(bridgePathIn(otherProject))).toBe(false);+ expect(listPiTrustGrants(home, approvedProject)).toMatchObject([+ { record: { cwd: approvedProject, state: 'committed' } },+ ]);+ }+ },+ );++ test.each([false, true])(+ 'discloses an unowned alias key alongside canonical trust (%s)',+ (canonicalGrant) => {+ const cwd = tmp();+ const home = tmp();+ const alias = join(tmp(), 'project-link');+ symlinkSync(cwd, alias, process.platform === 'win32' ? 'junction' : 'dir');+ const trustPath = trustPathIn(home);+ const before = JSON.stringify({+ [alias]: true,+ ...(canonicalGrant ? { [cwd]: true } : {}),+ unrelated: false,+ });+ write(trustPath, before);+ write(bridgePathIn(alias), buildPiExtensionSource({ mode: 'published' }));+ const lockSpy = vi.spyOn(lockfile, 'lockSync');++ const result = removeOwnMcpEntry(EDITOR_TARGETS.pi, alias, home, bridgePathIn(alias));++ expect(result).toMatchObject({ kind: 'removed', trust: 'kept-unowned' });+ expect(result).toHaveProperty('trustDetail', expect.stringContaining(JSON.stringify(alias)));+ expect(result).toHaveProperty('trustDetail', expect.stringContaining(trustPath));+ expect(result).toHaveProperty(+ 'trustDetail',+ expect.stringContaining('Pi uses the real project directory instead of this key'),+ );+ if (canonicalGrant)+ expect(result).toHaveProperty('trustDetail', expect.stringContaining(JSON.stringify(cwd)));+ expect(lockSpy).toHaveBeenCalledTimes(1);+ expect(readFileSync(trustPath, 'utf8')).toBe(before);+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ expect(listPiTrustGrants(home, alias)).toEqual([]);+ expect(existsSync(bridgePathIn(cwd))).toBe(false);+ },+ );++ test.each([false, true])(+ 'refuses an unresolved project alias before a recorded-only no-op (ancestor=%s)',+ async (ancestor) => {+ const target = tmp();+ const cwd = ancestor ? join(target, 'project') : target;+ mkdirSync(cwd, { recursive: true });+ const home = tmp();+ const alias = join(tmp(), 'project-link');+ const opened = ancestor ? join(alias, 'project') : alias;+ symlinkSync(target, alias, process.platform === 'win32' ? 'junction' : 'dir');+ await ensurePiBridge(opened, { mode: 'published' }, home);+ const before = readFileSync(trustPathIn(home), 'utf8');+ rmSync(bridgePathIn(cwd));+ unlinkSync(alias);+ symlinkSync(join(tmp(), 'missing'), alias, process.platform === 'win32' ? 'junction' : 'dir');++ expect(removePiTrustEntry(opened, home, undefined, { recordedOnly: true })).toMatchObject({+ action: 'kept-unverified',+ error: expect.stringContaining('restore the directory or symlink'),+ });+ expect(readFileSync(trustPathIn(home), 'utf8')).toBe(before);+ expect(listPiTrustGrants(home, cwd)).toHaveLength(1);++ unlinkSync(alias);+ symlinkSync(target, alias, process.platform === 'win32' ? 'junction' : 'dir');+ expect(+ removeOwnMcpEntry(EDITOR_TARGETS.pi, opened, home, bridgePathIn(opened)),+ ).toMatchObject({ kind: 'removed', trust: 'removed' });+ expect(JSON.parse(readFileSync(trustPathIn(home), 'utf8'))).toEqual({});+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ },+ );++ test('preserves a canonical receipt when a missing project lies under a healthy directory alias', async () => {+ const parent = tmp();+ const cwd = join(parent, 'project');+ mkdirSync(cwd);+ const home = tmp();+ const alias = join(tmp(), 'parent-link');+ symlinkSync(parent, alias, process.platform === 'win32' ? 'junction' : 'dir');+ const opened = join(alias, 'project');+ await ensurePiBridge(opened, { mode: 'published' }, home);+ const before = readFileSync(trustPathIn(home), 'utf8');+ const moved = join(parent, 'moved-project');+ renameSync(cwd, moved);++ expect(realpathSync(alias)).toBe(parent);+ const result = removePiTrustEntry(opened, home, undefined, { recordedOnly: true });+ expect(result.action).toBe('kept-unverified');+ expect(result.error).toContain('could not be resolved or accessed');+ expect(result.error).toContain('current trust decisions were not checked');+ expect(result.error).toContain(`key ${JSON.stringify(cwd)}`);+ expect(result.error).toContain(`configured store ${JSON.stringify(trustPathIn(home))}`);+ expect(result.error).not.toContain('cleanup was left pending');+ expect(readFileSync(trustPathIn(home), 'utf8')).toBe(before);+ expect(listPiTrustGrants(home, cwd)).toHaveLength(1);+ expect(existsSync(bridgePathIn(moved))).toBe(true);++ renameSync(moved, cwd);+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, opened, home, bridgePathIn(opened))).toMatchObject({+ kind: 'removed',+ trust: 'removed',+ });+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ });++ test.each(['true', 'false', 'absent', 'missing-store', 'pending'] as const)(+ 'discloses retained records without inferring current trust for an unresolved project (%s)',+ (state) => {+ const parent = tmp();+ const cwd = join(parent, 'project');+ mkdirSync(cwd);+ const home = tmp();+ const alias = join(tmp(), 'parent-link');+ symlinkSync(parent, alias, process.platform === 'win32' ? 'junction' : 'dir');+ const opened = join(alias, 'project');+ const storeDir = tmp();+ const configuredDir = join(tmp(), 'store-link');+ symlinkSync(storeDir, configuredDir, process.platform === 'win32' ? 'junction' : 'dir');+ const configured = join(configuredDir, 'trust.json');+ const canonical = join(storeDir, 'trust.json');+ const otherStore = join(tmp(), 'other-trust.json');+ const before = `${JSON.stringify({+ ...(state === 'absent' ? {} : { [cwd]: state !== 'false' }),+ unrelated: false,+ })}\n`;+ if (state !== 'missing-store') write(canonical, before);+ write(otherStore, '{"unrelated":{"preserve":true}}\n');+ const prepared = preparePiTrustGrant(home, cwd, configured, canonical, {+ present: true,+ value: false,+ });+ const receipt = state === 'pending' ? prepared : commitPiTrustGrant(home, prepared);+ const otherReceipt = preparePiTrustGrant(home, opened, otherStore, otherStore, {+ present: false,+ });+ write(bridgePathIn(cwd), buildPiExtensionSource({ mode: 'published' }));+ const bridgeBefore = readFileSync(bridgePathIn(cwd), 'utf8');+ const receiptBefore = readFileSync(receipt.path, 'utf8');+ const otherReceiptBefore = readFileSync(otherReceipt.path, 'utf8');+ const moved = join(parent, 'moved-project');+ renameSync(cwd, moved);+ const lockSpy = vi.spyOn(lockfile, 'lockSync');++ const result = removePiTrustEntry(opened, home, undefined, { recordedOnly: true });++ expect(result.action).toBe('kept-unverified');+ expect(result.error).toContain('current trust decisions were not checked');+ for (const kept of [receipt, otherReceipt]) {+ expect(result.error?.split('\n')).toContain(+ `key ${JSON.stringify(kept.record.cwd)}; configured store ${JSON.stringify(kept.record.configuredTrustPath)}; recorded destination ${JSON.stringify(kept.record.canonicalTrustPath)}; ownership record ${JSON.stringify(kept.path)} (${kept.record.state})`,+ );+ }+ expect(result.error).toContain('A pending record does not prove setup completed');+ expect(result.error).toContain('restore the recorded previous value');+ expect(result.error).toContain('remove that key only when no previous entry was recorded');+ expect(result.error).toContain('Preserve other current decisions');+ expect(result.error).not.toContain('the grant is still in place');+ expect(lockSpy).not.toHaveBeenCalled();+ expect(readFileSync(receipt.path, 'utf8')).toBe(receiptBefore);+ expect(readFileSync(otherReceipt.path, 'utf8')).toBe(otherReceiptBefore);+ expect(readFileSync(otherStore, 'utf8')).toBe('{"unrelated":{"preserve":true}}\n');+ expect(readFileSync(bridgePathIn(moved), 'utf8')).toBe(bridgeBefore);+ expect(existsSync(cwd)).toBe(false);+ if (state === 'missing-store') expect(existsSync(canonical)).toBe(false);+ else expect(readFileSync(canonical, 'utf8')).toBe(before);+ },+ );++ test('does not claim retained ownership records for an unresolved unrecorded project', () => {+ const cwd = join(tmp(), 'missing-project');+ const home = tmp();+ const trustPath = trustPathIn(home);+ write(trustPath, '{unrelated invalid config');++ const result = removePiTrustEntry(cwd, home);++ expect(result.action).toBe('kept-unverified');+ expect(result.error).toContain('restore the directory or symlink');+ expect(result.error).not.toContain('kept these Pi trust ownership records');+ expect(readFileSync(trustPath, 'utf8')).toBe('{unrelated invalid config');+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ expect(existsSync(cwd)).toBe(false);+ });++ test('treats a missing child under a healthy alias as absent when neither current spelling has records', () => {+ const parent = tmp();+ const home = tmp();+ const alias = join(tmp(), 'parent-link');+ symlinkSync(parent, alias, process.platform === 'win32' ? 'junction' : 'dir');+ const opened = join(alias, 'deleted', 'project');+ write(trustPathIn(home), '{unrelated invalid trust');++ expect(removePiTrustEntry(opened, home, undefined, { recordedOnly: true })).toEqual({+ action: 'not-present',+ });+ expect(readFileSync(trustPathIn(home), 'utf8')).toBe('{unrelated invalid trust');+ expect(existsSync(join(parent, 'deleted'))).toBe(false);+ expect(lstatSync(alias).isSymbolicLink()).toBe(true);+ });++ test('refuses a missing project whose existing ancestor is a file', () => {+ const parent = join(tmp(), 'not-a-directory');+ const home = tmp();+ write(parent, 'preserve');+ expect(+ removePiTrustEntry(join(parent, 'project'), home, undefined, { recordedOnly: true }),+ ).toMatchObject({+ action: 'kept-unverified',+ error: expect.stringContaining('could not be resolved or accessed'),+ });+ expect(readFileSync(parent, 'utf8')).toBe('preserve');+ });++ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(+ 'refuses inaccessible ancestry while checking a missing project',+ () => {+ const parent = tmp();+ const home = tmp();+ const opened = join(parent, 'missing');+ chmodSync(parent, 0o000);+ try {+ const result = removePiTrustEntry(opened, home, undefined, { recordedOnly: true });+ expect(result.action).toBe('kept-unverified');+ expect(result.error).toContain('check its permissions');+ expect(result.error).toContain('cleanup was left pending');+ expect(result.error).toContain('Retry once the project path can be resolved');+ } finally {+ chmodSync(parent, 0o700);+ }+ expect(removePiTrustEntry(opened, home, undefined, { recordedOnly: true })).toEqual({+ action: 'not-present',+ });+ },+ );++ test('keeps a plainly missing unrecorded project quiet without inspecting the ambient store', () => {+ const cwd = join(tmp(), 'removed-project');+ const home = tmp();+ write(trustPathIn(home), '{unrelated invalid config');+ expect(removePiTrustEntry(cwd, home, undefined, { recordedOnly: true })).toEqual({+ action: 'not-present',+ });+ expect(readFileSync(trustPathIn(home), 'utf8')).toBe('{unrelated invalid config');+ });++ test.each([false, true])(+ 'discloses ambient unowned trust while cleaning a recorded custom store (bridge absent=%s)',+ async (absentBridge) => {+ const cwd = tmp();+ const home = tmp();+ const custom = tmp();+ await ensurePiBridge(cwd, { mode: 'published' }, home, { PI_CODING_AGENT_DIR: custom });+ const before = JSON.stringify({ [cwd]: true, other: false });+ write(trustPathIn(home), before);+ if (absentBridge) rmSync(bridgePathIn(cwd));++ const result = removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd));++ expect(result).toMatchObject({ kind: 'removed', trust: 'kept-unowned' });+ expect(result).toHaveProperty('trustDetail', expect.stringContaining(trustPathIn(home)));+ expect(result).toHaveProperty('trustDetail', expect.stringContaining(JSON.stringify(cwd)));+ expect(readFileSync(trustPathIn(home), 'utf8')).toBe(before);+ expect(JSON.parse(readFileSync(join(custom, 'trust.json'), 'utf8'))).toEqual({});+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ expect(existsSync(bridgePathIn(cwd))).toBe(false);+ },+ );++ test.skipIf(process.platform === 'win32')(+ 'preserves a known pending receipt when the ambient path aliases its recorded store',+ () => {+ const cwd = tmp();+ const home = tmp();+ const trustPath = trustPathIn(home);+ const configured = join(tmp(), 'trust.json');+ const before = JSON.stringify({ [cwd]: true, other: false });+ write(trustPath, before);+ symlinkSync(trustPath, configured);+ write(bridgePathIn(cwd), buildPiExtensionSource({ mode: 'published' }));+ withPiTrustLockSync(configured, realpathSync(trustPath), () => {+ preparePiTrustGrant(home, cwd, configured, realpathSync(trustPath), { present: false });+ });+ const lockSpy = vi.spyOn(lockfile, 'lockSync');++ const result = removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd));++ expect(result).toMatchObject({ kind: 'removed', trust: 'kept-unowned' });+ expect(result).toHaveProperty(+ 'trustDetail',+ expect.stringContaining('ownership record is pending'),+ );+ expect(result).toHaveProperty('trustDetail', expect.stringContaining(configured));+ expect(result).toHaveProperty('trustDetail', expect.stringContaining(trustPath));+ expect(lockSpy.mock.calls.map(([, options]) => options?.lockfilePath)).toEqual([+ `${configured}.lock`,+ `${trustPath}.lock`,+ ]);+ expect(listPiTrustGrants(home, cwd)).toMatchObject([+ { record: { state: 'pending', configuredTrustPath: configured } },+ ]);+ expect(readFileSync(trustPath, 'utf8')).toBe(before);+ expect(existsSync(bridgePathIn(cwd))).toBe(false);+ expect(lstatSync(configured).isSymbolicLink()).toBe(true);+ },+ );++ test('does not convert disclosure into removal when a new ownership record appears under the lock', () => {+ const cwd = tmp();+ const home = tmp();+ const trustPath = trustPathIn(home);+ write(trustPath, '{}');+ write(bridgePathIn(cwd), buildPiExtensionSource({ mode: 'published' }));+ const originalLockSync = lockfile.lockSync;+ vi.spyOn(lockfile, 'lockSync').mockImplementation((path, options) => {+ const release = originalLockSync(path, options);+ const pending = preparePiTrustGrant(home, cwd, trustPath, realpathSync(trustPath), {+ present: false,+ });+ writeFileSync(trustPath, JSON.stringify({ [cwd]: true }));+ commitPiTrustGrant(home, pending);+ return release;+ });++ expect(removePiTrustEntry(cwd, home)).toMatchObject({+ action: 'failed',+ error: expect.stringContaining('ownership record changed during cleanup'),+ });+ expect(JSON.parse(readFileSync(trustPath, 'utf8'))).toEqual({ [cwd]: true });+ expect(listPiTrustGrants(home, cwd)).toHaveLength(1);+ expect(existsSync(bridgePathIn(cwd))).toBe(true);+ vi.restoreAllMocks();+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toMatchObject({+ kind: 'removed',+ trust: 'removed',+ });+ });++ test.each([false, true])(+ 'preserves the project recheck refusal through lock release (release fails=%s)',+ async (releaseFails) => {+ const cwd = tmp();+ const other = tmp();+ const home = tmp();+ const alias = join(tmp(), 'project-link');+ symlinkSync(cwd, alias, process.platform === 'win32' ? 'junction' : 'dir');+ await ensurePiBridge(alias, { mode: 'published' }, home);+ const trustPath = trustPathIn(home);+ const before = readFileSync(trustPath, 'utf8');+ const originalLockSync = lockfile.lockSync;+ vi.spyOn(lockfile, 'lockSync').mockImplementation((path, options) => {+ const release = originalLockSync(path, options);+ unlinkSync(alias);+ symlinkSync(other, alias, process.platform === 'win32' ? 'junction' : 'dir');+ return () => {+ if (releaseFails) writeFileSync(join(`${trustPath}.lock`, 'keep.txt'), 'preserve');+ release();+ };+ });++ const result = removePiTrustEntry(alias, home);++ expect(result.action).toBe(releaseFails ? 'failed' : 'kept-unverified');+ expect(result.error).toContain('changed while waiting for its trust lock');+ if (releaseFails) expect(result.error).toContain('ENOTEMPTY');+ expect(readFileSync(trustPath, 'utf8')).toBe(before);+ expect(listPiTrustGrants(home, cwd)).toHaveLength(1);+ expect(existsSync(bridgePathIn(cwd))).toBe(true);+ expect(existsSync(bridgePathIn(other))).toBe(false);++ vi.restoreAllMocks();+ if (releaseFails) rmSync(`${trustPath}.lock`, { recursive: true });+ unlinkSync(alias);+ symlinkSync(cwd, alias, process.platform === 'win32' ? 'junction' : 'dir');+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, alias, home, bridgePathIn(alias))).toMatchObject({+ kind: 'removed',+ trust: 'removed',+ });+ },+ );++ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(+ 'cleans a searchable project without requiring permission to list its root',+ async () => {+ const cwd = tmp();+ const home = tmp();+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ chmodSync(cwd, 0o111);+ try {+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toMatchObject({+ kind: 'removed',+ trust: 'removed',+ });+ expect(JSON.parse(readFileSync(trustPathIn(home), 'utf8'))).toEqual({});+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ expect(existsSync(bridgePathIn(cwd))).toBe(false);+ } finally {+ chmodSync(cwd, 0o700);+ }+ },+ );++ test.each(['alias', 'canonical'] as const)(+ 'uses canonical trust and receipts when setup starts through the %s path',+ async (setupPath) => {+ const cwd = tmp();+ const home = tmp();+ const alias = join(tmp(), 'project-link');+ symlinkSync(cwd, alias, process.platform === 'win32' ? 'junction' : 'dir');++ expect(+ (await ensurePiBridge(setupPath === 'alias' ? alias : cwd, { mode: 'published' }, home)).ok,+ ).toBe(true);+ expect(JSON.parse(readFileSync(trustPathIn(home), 'utf8'))).toEqual({ [cwd]: true });+ expect(listPiTrustGrants(home, cwd)).toMatchObject([{ record: { cwd } }]);+ expect(listPiTrustGrants(home, alias)).toEqual([]);+ expect(probeReadyPiBridgeState(alias, home)).toMatchObject({+ project: 'ready',+ canonicalCwd: cwd,+ bridgeLoadable: true,+ });+ expect(probeReadyPiBridgeState(cwd, home).bridgeLoadable).toBe(true);++ const cleanupPath = setupPath === 'alias' ? cwd : alias;+ expect(+ removeOwnMcpEntry(EDITOR_TARGETS.pi, cleanupPath, home, bridgePathIn(cleanupPath)),+ ).toMatchObject({ kind: 'removed', trust: 'removed' });+ expect(JSON.parse(readFileSync(trustPathIn(home), 'utf8'))).toEqual({});+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ expect(existsSync(bridgePathIn(cwd))).toBe(false);+ expect(lstatSync(alias).isSymbolicLink()).toBe(true);+ expect(realpathSync(alias)).toBe(cwd);+ },+ );++ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(+ 'discloses canonical trust after a sibling alias receipt cannot be forgotten',+ () => {+ const cwd = tmp();+ const home = tmp();+ const alias = join(tmp(), 'project-link');+ symlinkSync(cwd, alias, 'dir');+ const trustPath = trustPathIn(home);+ write(trustPath, JSON.stringify({ [cwd]: true, [alias]: true, unrelated: false }));+ write(bridgePathIn(cwd), buildPiExtensionSource({ mode: 'published' }));+ withPiTrustLockSync(trustPath, realpathSync(trustPath), () => {+ commitPiTrustGrant(+ home,+ preparePiTrustGrant(home, alias, trustPath, realpathSync(trustPath), { present: false }),+ );+ });+ const [receipt] = listPiTrustGrants(home, alias);+ if (!receipt) throw new Error('expected alias receipt');+ chmodSync(dirname(receipt.path), 0o500);+ try {+ const result = removePiTrustEntry(alias, home);+ expect(result.action).toBe('failed');+ expect(result.error).toContain(`Pi trust entry ${JSON.stringify(alias)}`);+ expect(result.error).toContain(`remove only the ${JSON.stringify(cwd)} entry`);+ expect(result.error).toContain(trustPath);+ expect(JSON.parse(readFileSync(trustPath, 'utf8'))).toEqual({+ [cwd]: true,+ unrelated: false,+ });+ expect(listPiTrustGrants(home, alias)).toEqual([receipt]);+ expect(existsSync(bridgePathIn(cwd))).toBe(true);+ } finally {+ chmodSync(dirname(receipt.path), 0o700);+ }+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, alias, home, bridgePathIn(alias))).toMatchObject({+ kind: 'removed',+ trust: 'kept-unowned',+ });+ expect(listPiTrustGrants(home, alias)).toEqual([]);+ },+ );++ function twoRecordedKeys() {+ const cwd = tmp();+ const home = tmp();+ const alias = join(tmp(), 'project-link');+ symlinkSync(cwd, alias, process.platform === 'win32' ? 'junction' : 'dir');+ const trustPath = trustPathIn(home);+ write(+ trustPath,+ `${JSON.stringify({ [cwd]: true, [alias]: true, unrelated: { keep: 'yes' } })}\n`,+ );+ write(bridgePathIn(cwd), buildPiExtensionSource({ mode: 'published' }));+ withPiTrustLockSync(trustPath, realpathSync(trustPath), () => {+ commitPiTrustGrant(+ home,+ preparePiTrustGrant(home, cwd, trustPath, realpathSync(trustPath), {+ present: true,+ value: false,+ }),+ );+ commitPiTrustGrant(+ home,+ preparePiTrustGrant(home, alias, trustPath, realpathSync(trustPath), { present: false }),+ );+ });+ const [receipt] = listPiTrustGrants(home, cwd);+ if (!receipt) throw new Error('expected canonical receipt');+ return { cwd, home, alias, trustPath, receipt };+ }++ test('restores one recorded decision and removes another in the same store without resurrecting either grant', () => {+ const { cwd, home, alias, trustPath } = twoRecordedKeys();+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, alias, home, bridgePathIn(alias))).toMatchObject({+ kind: 'removed',+ trust: 'removed',+ });+ expect(JSON.parse(readFileSync(trustPath, 'utf8'))).toEqual({+ [cwd]: false,+ unrelated: { keep: 'yes' },+ });+ expect(readFileSync(trustPath, 'utf8').endsWith('\n')).toBe(true);+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ expect(listPiTrustGrants(home, alias)).toEqual([]);+ expect(existsSync(bridgePathIn(cwd))).toBe(false);+ });++ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(+ 'preserves the first completed decision when its receipt deletion fails and the next key succeeds',+ () => {+ const { cwd, home, alias, trustPath, receipt } = twoRecordedKeys();+ chmodSync(dirname(receipt.path), 0o500);+ try {+ const result = removePiTrustEntry(alias, home);+ expect(result.action).toBe('failed');+ expect(result.error).toContain(`Pi trust entry ${JSON.stringify(cwd)}`);+ expect(JSON.parse(readFileSync(trustPath, 'utf8'))).toEqual({+ [cwd]: false,+ unrelated: { keep: 'yes' },+ });+ expect(listPiTrustGrants(home, cwd)).toEqual([receipt]);+ expect(listPiTrustGrants(home, alias)).toEqual([]);+ expect(existsSync(bridgePathIn(cwd))).toBe(true);+ } finally {+ chmodSync(dirname(receipt.path), 0o700);+ }+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, alias, home, bridgePathIn(alias))).toMatchObject({+ kind: 'removed',+ trust: 'not-present',+ });+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ expect(JSON.parse(readFileSync(trustPath, 'utf8'))).toEqual({+ [cwd]: false,+ unrelated: { keep: 'yes' },+ });+ },+ );++ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0).each([false, true])(+ 'discloses a committed record retained through an accessible inspection path (shared=%s)',+ async (shared) => {+ const cwd = tmp();+ const home = tmp();+ const configuredDir = tmp();+ const configured = join(configuredDir, 'trust.json');+ const trustPath = trustPathIn(home);+ write(trustPath, '{"unrelated":false}\n');+ symlinkSync(trustPath, configured);+ await ensurePiBridge(cwd, { mode: 'published' }, home, {+ PI_CODING_AGENT_DIR: configuredDir,+ });+ if (shared) write(join(cwd, '.pi', 'prompts', 'user.txt'), 'keep this prompt');+ const before = readFileSync(trustPath, 'utf8');+ const bridgeBefore = readFileSync(bridgePathIn(cwd), 'utf8');+ const receipts = listPiTrustGrants(home, cwd);+ chmodSync(configuredDir, 0o500);+ try {+ const result = removePiTrustEntry(cwd, home);+ expect(result.action).toBe('failed');+ expect(result.error).toContain(+ shared+ ? 'OpenKnowledge kept the existing ownership record; cleanup of its recorded location remains incomplete.'+ : `OpenKnowledge must reconcile its recorded location at ${configured} before removing it.`,+ );+ expect(result.error).toContain(`remove only the ${JSON.stringify(cwd)} entry`);+ expect(result.error).not.toContain('has relinquished');+ expect(readFileSync(trustPath, 'utf8')).toBe(before);+ expect(readFileSync(bridgePathIn(cwd), 'utf8')).toBe(bridgeBefore);+ expect(listPiTrustGrants(home, cwd)).toEqual(receipts);+ } finally {+ chmodSync(configuredDir, 0o700);+ }+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toMatchObject({+ kind: 'removed',+ trust: shared ? 'kept-shared' : 'removed',+ });+ expect(JSON.parse(readFileSync(trustPath, 'utf8'))).toEqual({+ unrelated: false,+ ...(shared ? { [cwd]: true } : {}),+ });+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ expect(existsSync(bridgePathIn(cwd))).toBe(false);+ expect(lstatSync(configured).isSymbolicLink()).toBe(true);+ },+ );++ test.each(['pending', 'committed'] as const)(+ 'preserves canonical trust while handling a %s legacy alias receipt',+ (state) => {+ const cwd = tmp();+ const home = tmp();+ const alias = join(tmp(), 'project-link');+ symlinkSync(cwd, alias, process.platform === 'win32' ? 'junction' : 'dir');+ const trustPath = trustPathIn(home);+ write(trustPath, JSON.stringify({ [cwd]: true, [alias]: true, unrelated: false }));+ write(bridgePathIn(alias), buildPiExtensionSource({ mode: 'published' }));+ withPiTrustLockSync(trustPath, realpathSync(trustPath), () => {+ const pending = preparePiTrustGrant(home, alias, trustPath, realpathSync(trustPath), {+ present: false,+ });+ if (state === 'committed') commitPiTrustGrant(home, pending);+ });++ const lockSpy = vi.spyOn(lockfile, 'lockSync');+ const outcome = removeOwnMcpEntry(EDITOR_TARGETS.pi, alias, home, bridgePathIn(alias));+ expect(lockSpy).toHaveBeenCalledTimes(1);++ expect(outcome).toMatchObject({ kind: 'removed', trust: 'kept-unowned' });+ expect(outcome).toHaveProperty('trustDetail', expect.stringContaining(JSON.stringify(cwd)));+ expect(JSON.parse(readFileSync(trustPath, 'utf8'))).toEqual({+ [cwd]: true,+ ...(state === 'pending' ? { [alias]: true } : {}),+ unrelated: false,+ });+ expect(listPiTrustGrants(home, alias)).toHaveLength(state === 'pending' ? 1 : 0);+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ expect(existsSync(bridgePathIn(cwd))).toBe(false);+ },+ );++ test('does not transfer legacy alias ownership to a different target after the alias is repointed', () => {+ const original = tmp();+ const current = tmp();+ const home = tmp();+ const alias = join(tmp(), 'project-link');+ symlinkSync(original, alias, process.platform === 'win32' ? 'junction' : 'dir');+ const trustPath = trustPathIn(home);+ write(trustPath, JSON.stringify({ [original]: true, [current]: true, [alias]: true }));+ write(bridgePathIn(original), buildPiExtensionSource({ mode: 'published' }));+ write(bridgePathIn(current), buildPiExtensionSource({ mode: 'published' }));+ withPiTrustLockSync(trustPath, realpathSync(trustPath), () => {+ const pending = preparePiTrustGrant(home, alias, trustPath, realpathSync(trustPath), {+ present: false,+ });+ commitPiTrustGrant(home, pending);+ });+ unlinkSync(alias);+ symlinkSync(current, alias, process.platform === 'win32' ? 'junction' : 'dir');++ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, alias, home, bridgePathIn(alias))).toMatchObject({+ kind: 'removed',+ trust: 'kept-unowned',+ });+ expect(JSON.parse(readFileSync(trustPath, 'utf8'))).toEqual({+ [original]: true,+ [current]: true,+ });+ expect(existsSync(bridgePathIn(original))).toBe(true);+ expect(listPiTrustGrants(home, alias)).toEqual([]);+ });++ test('refuses missing or broken project paths without changing the real project grant or bridge', async () => {+ const cwd = tmp();+ const home = tmp();+ const alias = join(tmp(), 'project-link');+ symlinkSync(cwd, alias, process.platform === 'win32' ? 'junction' : 'dir');+ await ensurePiBridge(alias, { mode: 'published' }, home);+ const before = readFileSync(trustPathIn(home), 'utf8');+ unlinkSync(alias);+ symlinkSync(+ join(tmp(), 'missing-project'),+ alias,+ process.platform === 'win32' ? 'junction' : 'dir',+ );++ expect(await ensurePiBridge(alias, { mode: 'published' }, home)).toMatchObject({+ ok: false,+ bridge: 'refused-project-path',+ trust: 'skipped',+ });+ expect(removePiTrustEntry(alias, home)).toMatchObject({+ action: 'kept-unverified',+ error: expect.stringContaining('restore the directory or symlink'),+ });+ expect(probePiBridgeState(alias, home)).toEqual({+ cwd: alias,+ bridgePath: bridgePathIn(alias),+ trustPath: trustPathIn(home),+ project: 'unavailable',+ error: expect.stringContaining('restore the directory or symlink'),+ });+ expect(readFileSync(trustPathIn(home), 'utf8')).toBe(before);+ expect(listPiTrustGrants(home, cwd)).toHaveLength(1);+ expect(existsSync(bridgePathIn(cwd))).toBe(true);+ });++ test('refuses a project alias that changes while setup waits for the trust lock', async () => {+ const original = tmp();+ const other = tmp();+ const home = tmp();+ const alias = join(tmp(), 'project-link');+ symlinkSync(original, alias, process.platform === 'win32' ? 'junction' : 'dir');+ const trustPath = trustPathIn(home);+ const before = '{"unrelated":true}\n';+ write(trustPath, before);+ const canonicalLock = `${realpathSync(trustPath)}.ok.lock`;+ write(canonicalLock, 'held');+ const pending = ensurePiBridge(alias, { mode: 'published' }, home);+ try {+ expect(+ await Promise.race([+ pending.then(() => 'finished'),+ new Promise<string>((resolve) => setTimeout(() => resolve('waiting'), 75)),+ ]),+ ).toBe('waiting');+ unlinkSync(alias);+ symlinkSync(other, alias, process.platform === 'win32' ? 'junction' : 'dir');+ } finally {+ unlinkSync(canonicalLock);+ await pending;+ }++ expect(await pending).toMatchObject({+ ok: false,+ trust: 'refused-unreadable',+ error: expect.stringContaining('changed while waiting for its trust lock'),+ });+ expect(readFileSync(trustPath, 'utf8')).toBe(before);+ expect(listPiTrustGrants(home, original)).toEqual([]);+ expect(listPiTrustGrants(home, other)).toEqual([]);+ expect(existsSync(bridgePathIn(other))).toBe(false);+ });++ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(+ 'refuses an unreadable project through the result contract and permits repair and retry',+ async () => {+ const cwd = tmp();+ const home = tmp();+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ const before = readFileSync(trustPathIn(home), 'utf8');+ chmodSync(cwd, 0o000);+ try {+ expect(await ensurePiBridge(cwd, { mode: 'published' }, home)).toMatchObject({+ ok: false,+ bridge: 'refused-project-path',+ trust: 'skipped',+ });+ expect(removePiTrustEntry(cwd, home)).toMatchObject({+ action: 'kept-unverified',+ error: expect.stringContaining('check its permissions'),+ });+ expect(readFileSync(trustPathIn(home), 'utf8')).toBe(before);+ expect(listPiTrustGrants(home, cwd)).toHaveLength(1);+ } finally {+ chmodSync(cwd, 0o700);+ }+ expect(existsSync(bridgePathIn(cwd))).toBe(true);+ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toMatchObject({+ kind: 'removed',+ trust: 'removed',+ });+ },+ );+});+describe('folder-scoped trust', () => {+ test('does not recreate a plain trust file that disappeared while waiting for the lock', async () => {+ const cwd = tmp();+ const home = tmp();+ const trustPath = trustPathIn(home);+ write(trustPath, '{"other": true}\n');+ const canonicalLock = `${realpathSync(trustPath)}.ok.lock`;+ write(canonicalLock, 'held');+ const pending = ensurePiBridge(cwd, { mode: 'published' }, home);+ try {+ expect(+ await Promise.race([+ pending.then(() => 'finished'),+ new Promise<string>((resolve) => setTimeout(() => resolve('waiting'), 75)),+ ]),+ ).toBe('waiting');+ unlinkSync(trustPath);+ } finally {+ unlinkSync(canonicalLock);+ await pending;+ }++ const result = await pending;+ expect(result).toMatchObject({ ok: false, trust: 'refused-unreadable' });+ expect(result.error).toContain('path changed while waiting for its lock');+ expect(result.error).toContain('retry to check its current state');+ expect(result.error).not.toContain('permissions');+ expect(existsSync(trustPath)).toBe(false);+ expect(existsSync(bridgePathIn(cwd))).toBe(true);+ });++ test.each([false, null, 'unknown', { future: 'decision' }] as const)(+ 'removes the bridge without rewriting a non-grant trust decision (%j)',+ (decision) => {+ const cwd = tmp();+ const home = tmp();+ const trustPath = trustPathIn(home);+ const before = `${JSON.stringify({ [dirname(cwd)]: true, [cwd]: decision, other: true })}\n`;+ write(trustPath, before);+ write(bridgePathIn(cwd), buildPiExtensionSource({ mode: 'published' }));+ const mtime = freezeMtime(trustPath);++ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePathIn(cwd))).toEqual({+ kind: 'removed',+ trust: 'not-present',+ });++ expect(readFileSync(trustPath, 'utf8')).toBe(before);+ expect(statSync(trustPath).mtimeMs).toBe(mtime);+ expect(existsSync(bridgePathIn(cwd))).toBe(false);+ },+ );+test('the probe names the other extensions the trust grant would cover', async () => {const cwd = tmp();const home = tmp();@@ -337,17 +1892,17 @@ describe('folder-scoped trust', () => {write(join(dirname(bridgePathIn(cwd)), 'alpha.ts'), '// someone else');write(join(dirname(bridgePathIn(cwd)), 'notes.md'), 'hi');await ensurePiBridge(cwd, { mode: 'published' }, home);- expect(probePiBridgeState(cwd, home).otherExtensions).toEqual(['alpha.ts', 'zeta.ts']);+ expect(probeReadyPiBridgeState(cwd, home).otherExtensions).toEqual(['"alpha.ts"', '"zeta.ts"']);});test('removing the bridge revokes the trust entry it added', async () => {const cwd = tmp();const home = tmp();await ensurePiBridge(cwd, { mode: 'published' }, home);- expect(probePiBridgeState(cwd, home).trust).toBe('trusted');+ expect(probeReadyPiBridgeState(cwd, home).trust).toBe('trusted');rmSync(bridgePathIn(cwd), { force: true });expect(removePiTrustEntry(cwd, home).action).toBe('removed');- expect(probePiBridgeState(cwd, home).trust).toBe('untrusted');+ expect(probeReadyPiBridgeState(cwd, home).trust).toBe('untrusted');});test('an entry another extension still depends on is kept', async () => {@@ -357,7 +1912,7 @@ describe('folder-scoped trust', () => {write(join(dirname(bridgePathIn(cwd)), 'theirs.ts'), '// someone else');rmSync(bridgePathIn(cwd), { force: true });expect(removePiTrustEntry(cwd, home).action).toBe('kept-shared');- expect(probePiBridgeState(cwd, home).trust).toBe('trusted');+ expect(probeReadyPiBridgeState(cwd, home).trust).toBe('trusted');});test('an unreadable extensions folder is kept, not treated as verified empty', async () => {@@ -369,7 +1924,7 @@ describe('folder-scoped trust', () => {chmodSync(extDir, 0o000);try {expect(removePiTrustEntry(cwd, home).action).toBe('kept-unverified');- expect(probePiBridgeState(cwd, home).trust).toBe('trusted');+ expect(probeReadyPiBridgeState(cwd, home).trust).toBe('trusted');} finally {chmodSync(extDir, 0o755);}@@ -407,6 +1962,6 @@ describe('folder-scoped trust', () => {await ensurePiBridge(other, { mode: 'published' }, home);rmSync(bridgePathIn(cwd), { force: true });expect(removePiTrustEntry(cwd, home).action).toBe('removed');- expect(probePiBridgeState(other, home).trust).toBe('trusted');+ expect(probeReadyPiBridgeState(other, home).trust).toBe('trusted');});});diff --git a/packages/cli/src/commands/pi-acp-bridge.ts b/packages/cli/src/commands/pi-acp-bridge.tsindex ed9b23080..7cb0748ba 100644--- a/packages/cli/src/commands/pi-acp-bridge.ts+++ b/packages/cli/src/commands/pi-acp-bridge.ts@@ -1,15 +1,27 @@-import { existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs';+import {+ accessSync,+ constants,+ lstatSync,+ mkdirSync,+ readdirSync,+ readFileSync,+ realpathSync,+ statSync,+} from 'node:fs';+import { homedir } from 'node:os';import { basename, dirname, join, resolve } from 'node:path';import type {PiBridgeWriteAction,PiTrustWriteAction,} from '@inkeep/open-knowledge-core/acp/thread-protocol';-import {- atomicWriteFileSync,- withFileLock,- withFileLockSync,-} from '@inkeep/open-knowledge-core/server';+import { atomicWriteFileSync } from '@inkeep/open-knowledge-core/server';import { buildPiExtensionSource, isOwnPiManagedFileEntry } from '../integrations/pi-extension.ts';+import {+ type ConfigFileDeclineReason,+ configFileDeclineDetail,+ configFileDeclineReason,+} from '../utils/config-file-error.ts';+import { escapeDisplayPath } from '../utils/escape-display-path.ts';import { isObject } from '../utils/is-object.ts';import {EDITOR_TARGETS,@@ -19,6 +31,17 @@ import {} from './editors.ts';import { classifyExistingMcpEntry, writeEditorMcpConfig } from './init.ts';import { existingFileMode } from './jsonc-surgical.ts';+import {+ commitPiTrustGrant,+ forgetPiTrustGrant,+ listPiTrustGrants,+ type PiTrustGrantReceipt,+ PiTrustReceiptError,+ preparePiTrustGrant,+} from './pi-trust-grants.ts';+import { withPiTrustLock, withPiTrustLockSync } from './pi-trust-lock.ts';+import { inspectPiTrustResources } from './pi-trust-resources.ts';+import { resolveRemovalFilePath } from './removal-file-path.ts';const PI_TRUST_FILENAME = 'trust.json';@@ -26,25 +49,30 @@ export type PiBridgeFileState = 'absent' | 'own-current' | 'own-stale' | 'foreigexport type PiTrustState = 'trusted' | 'untrusted' | 'unreadable';-export interface PiBridgeState {+export type PiBridgeState = {cwd: string;bridgePath: string;trustPath: string;- bridge: PiBridgeFileState;- trust: PiTrustState;- bridgeLoadable: boolean;- otherExtensions: readonly string[];-}+} & (+ | { project: 'unavailable'; error: string }+ | {+ project: 'ready';+ canonicalCwd: string;+ bridge: PiBridgeFileState;+ trust: PiTrustState;+ bridgeLoadable: boolean;+ otherExtensions: readonly string[];+ }+);export type { PiBridgeWriteAction, PiTrustWriteAction };-export type PiTrustRemoveAction =- | 'removed'- | 'not-present'- | 'kept-shared'- | 'kept-unverified'- | 'refused-unreadable'- | 'failed';+type PiTrustRemoveResult =+ | { action: 'removed' | 'not-present'; error?: never; detail?: never }+ | { action: 'kept-shared' | 'kept-unowned'; detail: string; error?: never }+ | { action: 'kept-unverified' | 'refused-unreadable' | 'failed'; error: string; detail?: never };++export type PiTrustRemoveAction = PiTrustRemoveResult['action'];export interface EnsurePiBridgeResult {ok: boolean;@@ -59,21 +87,56 @@ export interface EnsurePiBridgeResult {function resolvePiPaths(cwd: string,home?: string,+ env?: NodeJS.ProcessEnv,): {cwd: string;bridgePath: string;trustPath: string;} {const normalizedCwd = resolve(cwd);- const agentDir =- home === undefined ? resolvePiAgentDirPath() : resolvePiAgentDirPath({ home, env: {} });+ const agentDir = resolvePiAgentDirPath({+ home,+ env: env ?? (home === undefined ? process.env : {}),+ });return {cwd: normalizedCwd,- bridgePath: EDITOR_TARGETS.pi.projectConfigPath?.(normalizedCwd) ?? '',+ bridgePath: EDITOR_TARGETS.pi.projectConfigPath(normalizedCwd),trustPath: join(agentDir, PI_TRUST_FILENAME),};}+type PiProjectPath = { path: string; canonical: string };++function resolvePiProjectPath(+ path: string,+): { kind: 'ready'; project: PiProjectPath } | { kind: 'refused'; error: string } {+ try {+ const canonical = realpathSync(path);+ if (!statSync(canonical).isDirectory()) {+ return {+ kind: 'refused',+ error: `Pi project path ${escapeDisplayPath(path)} is not a directory; restore the intended project directory, then retry`,+ };+ }+ accessSync(canonical, constants.X_OK);+ return { kind: 'ready', project: { path, canonical } };+ } catch (error) {+ return {+ kind: 'refused',+ error: `Pi project directory ${escapeDisplayPath(path)} could not be resolved or accessed: ${escapeDisplayPath(error instanceof Error ? error.message : String(error))}; restore the directory or symlink and check its permissions, then retry`,+ };+ }+}++function recheckPiProjectPath(project: PiProjectPath): string | undefined {+ const checked = resolvePiProjectPath(project.path);+ if (checked.kind === 'refused') return checked.error;+ if (checked.project.canonical !== project.canonical) {+ return `Pi project path ${escapeDisplayPath(project.path)} changed while waiting for its trust lock; restore the intended project location, then retry`;+ }+ return undefined;+}+function classifyPiBridgeFile(cwd: string,bridgePath: string,@@ -90,28 +153,36 @@ function classifyPiBridgeFile(return { state: 'foreign', text };}+type PiTrustReadResult =+ | {+ state: 'trusted' | 'untrusted';+ entries: Record<string, unknown>;+ trailingNewline: boolean;+ }+ | { state: 'unreadable'; reason: ReturnType<typeof configFileDeclineReason> | 'invalid-json' };+function readPiTrust(- trustPath: string,+ file: Extract<PiTrustFilePath, { path: string }>,cwd: string,-): { state: PiTrustState; entries: Record<string, unknown> | null; trailingNewline: boolean } {+): PiTrustReadResult {let raw: string;try {- raw = readFileSync(trustPath, 'utf-8');+ raw = readFileSync(file.path, 'utf-8');} catch (err) {const code = (err as NodeJS.ErrnoException).code;- if (code === 'ENOENT' || code === 'ENOTDIR') {+ if (file.kind === 'missing' && code === 'ENOENT') {return { state: 'untrusted', entries: {}, trailingNewline: false };}- return { state: 'unreadable', entries: null, trailingNewline: false };+ return { state: 'unreadable', reason: configFileDeclineReason(err) };}if (raw.trim() === '') return { state: 'untrusted', entries: {}, trailingNewline: false };let parsed: unknown;try {parsed = JSON.parse(raw);} catch {- return { state: 'unreadable', entries: null, trailingNewline: false };+ return { state: 'unreadable', reason: 'invalid-json' };}- if (!isObject(parsed)) return { state: 'unreadable', entries: null, trailingNewline: false };+ if (!isObject(parsed)) return { state: 'unreadable', reason: 'invalid-json' };return {state: parsed[cwd] === true ? 'trusted' : 'untrusted',entries: parsed,@@ -119,35 +190,134 @@ function readPiTrust(};}-export function probePiBridgeState(cwd: string, home?: string): PiBridgeState {- const paths = resolvePiPaths(cwd, home);+type PiTrustFilePath =+ | { kind: 'ready' | 'missing'; path: string }+ | { kind: 'refused'; error: string };++type PiTrustRefusalReason =+ | ConfigFileDeclineReason+ | 'invalid-json'+ | 'path-changed'+ | 'unavailable-root';++function piTrustRefusalDetail(reason: PiTrustRefusalReason): string {+ switch (reason) {+ case 'invalid-json':+ return 'the file is not a valid JSON object; repair its JSON, then retry';+ case 'path-changed':+ return 'the path changed while waiting for its lock; retry to check its current state';+ case 'unavailable-root':+ return 'the filesystem root is unavailable; reconnect the drive or network share, then retry';+ default:+ return configFileDeclineDetail(reason);+ }+}++function refusedTrustPath(+ trustPath: string,+ reason: PiTrustRefusalReason,+): Extract<PiTrustFilePath, { kind: 'refused' }> {+ return {+ kind: 'refused',+ error: `trust store ${escapeDisplayPath(trustPath)}: ${piTrustRefusalDetail(reason)}`,+ };+}++function resolvePiTrustFilePath(trustPath: string): PiTrustFilePath {+ const resolved = resolveRemovalFilePath(trustPath);+ try {+ switch (resolved.kind) {+ case 'declined':+ return refusedTrustPath(trustPath, resolved.reason);+ case 'ready':+ return { kind: 'ready', path: realpathSync(resolved.path) };+ case 'not-present':+ break;+ default: {+ const exhaustive: never = resolved;+ throw new Error(`unhandled trust file resolution: ${exhaustive}`);+ }+ }+ let parent = dirname(trustPath);+ const suffix = [basename(trustPath)];+ let parentEntry = lstatSync(parent, { throwIfNoEntry: false });+ while (!parentEntry) {+ const ancestor = dirname(parent);+ if (ancestor === parent) return refusedTrustPath(trustPath, 'unavailable-root');+ suffix.unshift(basename(parent));+ parent = ancestor;+ parentEntry = lstatSync(parent, { throwIfNoEntry: false });+ }+ try {+ return { kind: 'missing', path: join(realpathSync(parent), ...suffix) };+ } catch (error) {+ return refusedTrustPath(+ trustPath,+ parentEntry.isSymbolicLink() && (error as NodeJS.ErrnoException).code === 'ENOENT'+ ? 'missing-symlink-target'+ : configFileDeclineReason(error),+ );+ }+ } catch (error) {+ return refusedTrustPath(trustPath, configFileDeclineReason(error));+ }+}++function recheckPiTrustFilePath(+ trustPath: string,+ previous: Extract<PiTrustFilePath, { path: string }>,+): PiTrustFilePath {+ const current = resolvePiTrustFilePath(trustPath);+ if (current.kind === 'refused') return current;+ if (current.path !== previous.path || (previous.kind === 'ready' && current.kind === 'missing')) {+ return refusedTrustPath(trustPath, 'path-changed');+ }+ return current;+}++export function probePiBridgeState(+ cwd: string,+ home?: string,+ env?: NodeJS.ProcessEnv,+): PiBridgeState {+ const paths = resolvePiPaths(cwd, home, env);+ const project = resolvePiProjectPath(paths.cwd);+ if (project.kind === 'refused') {+ return { ...paths, project: 'unavailable', error: project.error };+ }const bridge = classifyPiBridgeFile(paths.cwd, paths.bridgePath, home).state;- const trust = readPiTrust(paths.trustPath, paths.cwd).state;+ const trustFile = resolvePiTrustFilePath(paths.trustPath);+ const trust =+ trustFile.kind === 'refused'+ ? 'unreadable'+ : trustFile.kind === 'missing'+ ? 'untrusted'+ : readPiTrust(trustFile, project.project.canonical).state;return {...paths,+ project: 'ready',+ canonicalCwd: project.project.canonical,bridge,trust,bridgeLoadable: (bridge === 'own-current' || bridge === 'own-stale') && trust === 'trusted',- otherExtensions: listOtherPiExtensions(paths.bridgePath).names,+ otherExtensions: listOtherPiExtensions(paths.bridgePath).displayNames,};}function listOtherPiExtensions(bridgePath: string): {- names: readonly string[];- verified: boolean;+ displayNames: readonly string[];} {const dir = dirname(bridgePath);const own = basename(bridgePath);try {return {- names: readdirSync(dir)+ displayNames: readdirSync(dir).filter((name) => name !== own && name.endsWith('.ts'))- .sort(),- verified: true,+ .sort()+ .map((name) => escapeDisplayPath(JSON.stringify(name))),};- } catch (err) {- const code = (err as NodeJS.ErrnoException).code;- return { names: [], verified: code === 'ENOENT' || code === 'ENOTDIR' };+ } catch {+ return { displayNames: [] };}}@@ -155,8 +325,29 @@ export async function ensurePiBridge(cwd: string,options: McpInstallOptions = { mode: 'published' },home?: string,+ env?: NodeJS.ProcessEnv,+ approvedCanonicalCwd?: string,): Promise<EnsurePiBridgeResult> {- const base = resolvePiPaths(cwd, home);+ const base = resolvePiPaths(cwd, home, env);+ const project = resolvePiProjectPath(base.cwd);+ if (project.kind === 'refused') {+ return {+ ...base,+ ok: false,+ bridge: 'refused-project-path',+ trust: 'skipped',+ error: project.error,+ };+ }+ if (approvedCanonicalCwd !== undefined && project.project.canonical !== approvedCanonicalCwd) {+ return {+ ...base,+ ok: false,+ bridge: 'refused-project-path',+ trust: 'skipped',+ error: `The approved Pi project directory ${escapeDisplayPath(approvedCanonicalCwd)} no longer matches the current directory ${escapeDisplayPath(project.project.canonical)}. Reopen the intended project and approve the Pi integration again; no bridge or trust settings were changed.`,+ };+ }const existing = classifyPiBridgeFile(base.cwd, base.bridgePath, home);if (existing.state === 'foreign') {@@ -193,12 +384,15 @@ export async function ensurePiBridge(ok: false,bridge: 'failed',trust: 'skipped',- error: result.error ?? `bridge write ${result.action}`,+ error:+ result.error !== undefined+ ? escapeDisplayPath(result.error)+ : `bridge write ${result.action}`,};}}- const trust = await addPiTrustEntry(base.trustPath, base.cwd);+ const trust = await addPiTrustEntry(base.trustPath, project.project, home ?? homedir());return {...base,ok: trust.action === 'already-trusted' || trust.action === 'added',@@ -210,73 +404,407 @@ export async function ensurePiBridge(async function addPiTrustEntry(trustPath: string,- cwd: string,+ project: PiProjectPath,+ home: string,): Promise<{ action: PiTrustWriteAction; error?: string }> {+ const cwd = project.canonical;+ const resolved = resolvePiTrustFilePath(trustPath);+ if (resolved.kind === 'refused') return { action: 'refused-unreadable', error: resolved.error };try {- mkdirSync(dirname(trustPath), { recursive: true });+ mkdirSync(dirname(resolved.path), { recursive: true });} catch (err) {- return { action: 'failed', error: err instanceof Error ? err.message : String(err) };+ return {+ action: 'failed',+ error: escapeDisplayPath(err instanceof Error ? err.message : String(err)),+ };}- const captured: { action: PiTrustWriteAction } = { action: 'added' };+ const captured: { action: PiTrustWriteAction; error?: string } = { action: 'added' };try {- await withFileLock(`${trustPath}.lock`, async () => {- const current = readPiTrust(trustPath, cwd);+ await withPiTrustLock(trustPath, resolved.path, () => {+ const projectError = recheckPiProjectPath(project);+ if (projectError) {+ captured.action = 'refused-unreadable';+ captured.error = projectError;+ return;+ }+ const checked = recheckPiTrustFilePath(trustPath, resolved);+ if (checked.kind === 'refused') {+ captured.action = 'refused-unreadable';+ captured.error = checked.error;+ return;+ }+ const current = readPiTrust(checked, cwd);if (current.state === 'trusted') {captured.action = 'already-trusted';return;}- if (current.entries === null) {+ if (current.state === 'unreadable') {captured.action = 'refused-unreadable';+ captured.error = refusedTrustPath(trustPath, current.reason).error;return;}+ const receipt = accessPiTrustReceipts(home, () => {+ const previousReceipt = listPiTrustGrants(home, cwd).find(+ (grant) => grant.record.canonicalTrustPath === checked.path,+ );+ if (previousReceipt) forgetPiTrustGrant(home, previousReceipt);+ return preparePiTrustGrant(+ home,+ cwd,+ trustPath,+ checked.path,+ Object.hasOwn(current.entries, cwd)+ ? { present: true, value: current.entries[cwd] }+ : { present: false },+ );+ });const next = { ...current.entries, [cwd]: true };const serialized = JSON.stringify(next, null, 2) + (current.trailingNewline ? '\n' : '');- const mode = existingFileMode(trustPath);- atomicWriteFileSync(trustPath, serialized, mode !== undefined ? { mode } : undefined);+ const mode = existingFileMode(checked.path);+ atomicWriteFileSync(checked.path, serialized, mode !== undefined ? { mode } : undefined);+ accessPiTrustReceipts(home, () => commitPiTrustGrant(home, receipt));captured.action = 'added';});} catch (err) {- return { action: 'failed', error: err instanceof Error ? err.message : String(err) };+ return {+ action: 'failed',+ error: escapeDisplayPath(err instanceof Error ? err.message : String(err)),+ };}- return captured.action === 'refused-unreadable'- ? { action: 'refused-unreadable', error: 'trust store is not a readable JSON object' }- : { action: captured.action };+ return captured;+}++function missingPiProjectPathCandidate(path: string): string | undefined {+ const suffix: string[] = [];+ let inspecting = path;+ try {+ while (true) {+ const entry = lstatSync(inspecting, { throwIfNoEntry: false });+ if (entry) {+ if (suffix.length === 0) return undefined;+ const ancestor = realpathSync(inspecting);+ if (!statSync(ancestor).isDirectory()) return undefined;+ accessSync(ancestor, constants.X_OK);+ return join(ancestor, ...suffix);+ }+ const parent = dirname(inspecting);+ if (parent === inspecting) return undefined;+ suffix.unshift(basename(inspecting));+ inspecting = parent;+ }+ } catch {+ return undefined;+ }+}++type PiTrustRemovalKey = {+ cwd: string;+ mode: 'recorded' | 'inspect';+ receipt?: PiTrustGrantReceipt;+};++type PiTrustRemovalStore = {+ trustPath: string;+ resolved: Extract<PiTrustFilePath, { path: string }>;+ keys: Map<string, PiTrustRemovalKey>;+};++function aggregatePiTrustRemoval(outcomes: readonly PiTrustRemoveResult[]): PiTrustRemoveResult {+ const priority = {+ 'not-present': 0,+ removed: 1,+ 'kept-unowned': 2,+ 'kept-shared': 3,+ 'kept-unverified': 4,+ 'refused-unreadable': 5,+ failed: 6,+ } satisfies Record<PiTrustRemoveAction, number>;+ const outcome = outcomes.reduce<PiTrustRemoveResult>(+ (best, item) => (priority[item.action] > priority[best.action] ? item : best),+ { action: 'not-present' },+ );+ const errors = outcomes.flatMap((item) => item.error ?? []);+ const details = outcomes.flatMap((item) => item.detail ?? []);+ if (errors.length > 0) {+ return {+ action: outcome.error !== undefined ? outcome.action : 'failed',+ error: [...errors, ...details].join('\n'),+ };+ }+ if (outcome.detail !== undefined) return { ...outcome, detail: details.join('\n') };+ return outcome;}export function removePiTrustEntry(cwd: string,home?: string,-): { action: PiTrustRemoveAction; error?: string } {- const base = resolvePiPaths(cwd, home);- const others = listOtherPiExtensions(base.bridgePath);- if (!others.verified) {- return { action: 'kept-unverified', error: 'could not read the Pi extensions folder' };+ env?: NodeJS.ProcessEnv,+ options: { recordedOnly?: boolean } = {},+): PiTrustRemoveResult {+ const base = resolvePiPaths(cwd, home, env);+ const resolvedHome = home ?? homedir();+ const project = resolvePiProjectPath(base.cwd);+ const missingCandidate =+ project.kind === 'refused' && options.recordedOnly+ ? missingPiProjectPathCandidate(base.cwd)+ : undefined;+ const receiptCwd = project.kind === 'ready' ? project.project.canonical : missingCandidate;+ let receipts: PiTrustGrantReceipt[];+ try {+ receipts = accessPiTrustReceipts(resolvedHome, () => {+ const literal = listPiTrustGrants(resolvedHome, base.cwd);+ if (receiptCwd === undefined || receiptCwd === base.cwd) return literal;+ return [...listPiTrustGrants(resolvedHome, receiptCwd), ...literal];+ });+ } catch (error) {+ return {+ action: 'failed',+ error: escapeDisplayPath(error instanceof Error ? error.message : String(error)),+ };+ }+ if (receipts.length === 0 && options.recordedOnly) {+ if (project.kind === 'ready' || missingCandidate !== undefined)+ return { action: 'not-present' };+ return {+ action: 'kept-unverified',+ error: `${project.error}. OpenKnowledge could not verify whether this path refers to a project with recorded Pi trust; cleanup was left pending. Retry once the project path can be resolved to check again.`,+ };+ }+ if (project.kind === 'refused') {+ if (receipts.length === 0) return { action: 'kept-unverified', error: project.error };+ const records = receipts.map(+ ({ path, record }) =>+ `key ${escapeDisplayPath(JSON.stringify(record.cwd))}; configured store ${escapeDisplayPath(JSON.stringify(record.configuredTrustPath))}; recorded destination ${escapeDisplayPath(JSON.stringify(record.canonicalTrustPath))}; ownership record ${escapeDisplayPath(JSON.stringify(path))} (${record.state})`,+ );+ return {+ action: 'kept-unverified',+ error: [+ `${project.error}. OpenKnowledge kept these Pi trust ownership records; current trust decisions were not checked:`,+ ...records,+ 'To review manually, close Pi, verify the intended store against its recorded destination, and inspect only the exact key. A pending record does not prove setup completed or ownership of a current grant. If you choose to undo a current true decision, restore the recorded previous value, or remove that key only when no previous entry was recorded. Preserve other current decisions; parent-folder and global trust settings still apply.',+ ].join('\n'),+ };+ }+ const resources = inspectPiTrustResources(+ project.project.canonical,+ resolvedHome,+ EDITOR_TARGETS.pi.projectConfigPath(project.project.canonical),+ );+ if (resources.kind === 'unreadable') {+ return { action: 'kept-unverified', error: resources.error };}- if (others.names.length > 0) return { action: 'kept-shared' };- if (!existsSync(base.trustPath)) return { action: 'not-present' };- const captured: { action: PiTrustRemoveAction } = { action: 'removed' };+ const sharedPaths = resources.kind === 'shared' ? resources.paths : [];+ const outcomes: PiTrustRemoveResult[] = [];+ const stores = new Map<string, PiTrustRemovalStore>();+ const addStore = (trustPath: string, receipt?: PiTrustGrantReceipt): void => {+ let store = stores.get(trustPath);+ if (!store) {+ const resolved = resolvePiTrustFilePath(trustPath);+ if (resolved.kind === 'refused') {+ outcomes.push({ action: 'refused-unreadable', error: resolved.error });+ return;+ }+ store = { trustPath, resolved, keys: new Map() };+ stores.set(trustPath, store);+ }+ if (!receipt) return;+ if (store.resolved.path !== receipt.record.canonicalTrustPath) {+ outcomes.push({+ action: 'refused-unreadable',+ error: `Pi trust store ${escapeDisplayPath(trustPath)} no longer points to its recorded destination ${escapeDisplayPath(receipt.record.canonicalTrustPath)}; restore the intended file location or symlink, then retry`,+ });+ return;+ }+ store.keys.set(receipt.record.cwd, { cwd: receipt.record.cwd, mode: 'recorded', receipt });+ };+ for (const receipt of receipts) addStore(receipt.record.configuredTrustPath, receipt);+ addStore(base.trustPath);+ for (const store of stores.values()) {+ for (const key of [project.project.canonical, base.cwd]) {+ if (!store.keys.has(key)) {+ store.keys.set(key, {+ cwd: key,+ mode: 'inspect',+ receipt: receipts.find(+ (receipt) =>+ receipt.record.cwd === key &&+ receipt.record.canonicalTrustPath === store.resolved.path,+ ),+ });+ }+ }+ outcomes.push(removePiTrustStore(store, resolvedHome, sharedPaths, project.project));+ }+ return aggregatePiTrustRemoval(outcomes);+}++function accessPiTrustReceipts<T>(home: string, operation: () => T): T {+ try {+ return operation();+ } catch (error) {+ if (error instanceof PiTrustReceiptError) throw error;+ throw new Error(+ `Could not access OpenKnowledge's Pi trust ownership records at ${escapeDisplayPath(join(home, '.ok', 'pi-trust'))}: ${escapeDisplayPath(error instanceof Error ? error.message : String(error))}. Check the records and their permissions, then retry.`,+ { cause: error },+ );+ }+}++function removePiTrustStore(+ store: PiTrustRemovalStore,+ home: string,+ sharedPaths: string[],+ project: PiProjectPath,+): PiTrustRemoveResult {+ const { trustPath, resolved } = store;+ const keys = [...store.keys.values()];+ if (!keys.some((key) => key.mode === 'recorded') && resolved.kind === 'missing')+ return { action: 'not-present' };+ if (resolved.kind === 'missing') {+ try {+ lstatSync(dirname(resolved.path));+ } catch (error) {+ return {+ action: 'failed',+ error: `The recorded Pi trust directory ${escapeDisplayPath(dirname(resolved.path))} is unavailable: ${escapeDisplayPath(error instanceof Error ? error.message : String(error))}. Restore access to its parent directory or mounted drive, then retry; the ownership record was kept.`,+ };+ }+ }+ const outcomes: PiTrustRemoveResult[] = [];+ const captured: { result: PiTrustRemoveResult } = { result: { action: 'not-present' } };try {- withFileLockSync(`${base.trustPath}.lock`, () => {- const current = readPiTrust(base.trustPath, base.cwd);- if (current.entries === null) {- captured.action = current.state === 'unreadable' ? 'refused-unreadable' : 'not-present';+ withPiTrustLockSync(trustPath, resolved.path, () => {+ const projectError = recheckPiProjectPath(project);+ if (projectError) {+ captured.result = { action: 'kept-unverified', error: projectError };return;}- if (!(base.cwd in current.entries)) {- captured.action = 'not-present';+ const checked = recheckPiTrustFilePath(trustPath, resolved);+ if (checked.kind === 'refused') {+ captured.result = { action: 'refused-unreadable', error: checked.error };return;}- const next = { ...current.entries };- delete next[base.cwd];- const serialized = JSON.stringify(next, null, 2) + (current.trailingNewline ? '\n' : '');- const mode = existingFileMode(base.trustPath);- atomicWriteFileSync(base.trustPath, serialized, mode !== undefined ? { mode } : undefined);- captured.action = 'removed';+ const current = readPiTrust(checked, project.canonical);+ if (current.state === 'unreadable') {+ captured.result = {+ action: 'refused-unreadable',+ error: refusedTrustPath(trustPath, current.reason).error,+ };+ return;+ }+ const currentKeys = keys.map((key) => ({+ cwd: key.cwd,+ mode: key.mode,+ expectedConfiguredPath: key.receipt?.record.configuredTrustPath,+ receipt: accessPiTrustReceipts(home, () =>+ listPiTrustGrants(home, key.cwd).find(+ (grant) => grant.record.canonicalTrustPath === checked.path,+ ),+ ),+ }));+ if (+ currentKeys.some(+ (key) =>+ key.receipt && key.receipt.record.configuredTrustPath !== key.expectedConfiguredPath,+ )+ ) {+ captured.result = {+ action: 'failed',+ error:+ 'The Pi trust ownership record changed during cleanup; retry to read its current location.',+ };+ return;+ }+ for (const key of currentKeys) {+ try {+ removePiTrustKey(+ key,+ home,+ trustPath,+ checked.path,+ current,+ sharedPaths,+ project,+ captured,+ );+ } catch (error) {+ const detail = escapeDisplayPath(error instanceof Error ? error.message : String(error));+ const retry =+ error instanceof PiTrustReceiptError ? '' : '; retry to check its current state.';+ outcomes.push({+ action: 'failed',+ error: `Pi trust entry ${escapeDisplayPath(JSON.stringify(key.cwd))} in ${escapeDisplayPath(trustPath)} could not be reconciled: ${detail}${retry}`,+ });+ }+ outcomes.push(captured.result);+ captured.result = { action: 'not-present' };+ }});- } catch (err) {- return { action: 'failed', error: err instanceof Error ? err.message : String(err) };+ } catch (error) {+ outcomes.push({+ action: 'failed',+ error: escapeDisplayPath(error instanceof Error ? error.message : String(error)),+ });+ }+ return aggregatePiTrustRemoval([...outcomes, captured.result]);+}++function removePiTrustKey(+ key: PiTrustRemovalKey,+ home: string,+ trustPath: string,+ canonicalTrustPath: string,+ current: Extract<PiTrustReadResult, { entries: unknown }>,+ sharedPaths: string[],+ project: PiProjectPath,+ captured: { result: PiTrustRemoveResult },+): void {+ const { cwd, receipt } = key;+ if (current.entries[cwd] !== true) {+ if (receipt && key.mode === 'recorded')+ accessPiTrustReceipts(home, () => forgetPiTrustGrant(home, receipt));+ captured.result = { action: 'not-present' };+ return;+ }+ const manualAction = `To remove this grant manually, close Pi and remove only the ${escapeDisplayPath(JSON.stringify(cwd))} entry from ${escapeDisplayPath(trustPath)}; parent-folder and global trust settings still apply.`;+ if (sharedPaths.length > 0 && cwd === project.canonical) {+ const shown = sharedPaths+ .slice(0, 3)+ .map((path) => escapeDisplayPath(JSON.stringify(path)))+ .join(', ');+ const remaining = sharedPaths.length > 3 ? ` (+${sharedPaths.length - 3} more)` : '';+ const detail = `kept Pi's folder trust because other resources still need it: ${shown}${remaining}. ${manualAction} Removing this grant may stop Pi from loading those resources, including any not listed here.`;+ captured.result = { action: 'kept-shared', detail };+ if (receipt && key.mode === 'recorded')+ accessPiTrustReceipts(home, () => forgetPiTrustGrant(home, receipt));+ const ownership = !receipt+ ? 'OpenKnowledge has no ownership record for this grant and will not revoke it on later cleanup runs.'+ : key.mode === 'recorded'+ ? 'OpenKnowledge has relinquished this grant and will not revoke it on later cleanup runs.'+ : 'OpenKnowledge kept the existing ownership record; cleanup of its recorded location remains incomplete.';+ captured.result = { action: 'kept-shared', detail: `${detail} ${ownership}` };+ return;+ }+ if (key.mode === 'inspect' || !receipt || receipt.record.state === 'pending') {+ const reason = !receipt+ ? 'no OpenKnowledge ownership record exists; this includes every grant made before ownership recording was introduced.'+ : receipt.record.state === 'pending'+ ? 'its ownership record is pending after an interrupted setup; completion cannot be verified. Re-running setup or cleanup does not reconcile this record while the folder remains trusted.'+ : `OpenKnowledge must reconcile its recorded location at ${escapeDisplayPath(receipt.record.configuredTrustPath)} before removing it.`;+ const subject =+ cwd === project.canonical+ ? `kept Pi's folder trust because ${reason}`+ : `kept a Pi trust entry under a non-canonical project path because ${reason} Pi uses the real project directory instead of this key.`;+ captured.result = { action: 'kept-unowned', detail: `${subject} ${manualAction}` };+ return;}- return captured.action === 'refused-unreadable'- ? { action: 'refused-unreadable', error: 'trust store is not a readable JSON object' }- : { action: captured.action };+ const next = { ...current.entries };+ if (receipt.record.previous.present) next[cwd] = receipt.record.previous.value;+ else delete next[cwd];+ const serialized = JSON.stringify(next, null, 2) + (current.trailingNewline ? '\n' : '');+ const mode = existingFileMode(canonicalTrustPath);+ atomicWriteFileSync(canonicalTrustPath, serialized, mode !== undefined ? { mode } : undefined);+ current.entries = next;+ accessPiTrustReceipts(home, () => forgetPiTrustGrant(home, receipt));+ captured.result = { action: 'removed' };}diff --git a/packages/cli/src/commands/pi-trust-grants.test.ts b/packages/cli/src/commands/pi-trust-grants.test.tsnew file mode 100644index 000000000..5537fe2fe--- /dev/null+++ b/packages/cli/src/commands/pi-trust-grants.test.ts@@ -0,0 +1,323 @@+import { createHash } from 'node:crypto';+import {+ chmodSync,+ copyFileSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ renameSync,+ rmSync,+ statSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { EDITOR_TARGETS } from './editors.ts';+import { removeOwnMcpEntry } from './mcp-config-removal.ts';+import { ensurePiBridge } from './pi-acp-bridge.ts';+import {+ commitPiTrustGrant,+ forgetPiTrustGrant,+ listPiTrustGrants,+ PiTrustReceiptError,+ preparePiTrustGrant,+} from './pi-trust-grants.ts';++describe('Pi trust grant receipts', () => {+ let root: string;+ let home: string;+ let cwd: string;+ let configured: string;+ let canonical: string;++ beforeEach(() => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pi-grant-')));+ home = join(root, 'home');+ cwd = join(root, 'project');+ configured = join(home, '.pi', 'agent', 'trust.json');+ canonical = join(root, 'dotfiles', 'trust.json');+ mkdirSync(home);+ mkdirSync(cwd);+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ test('makes direction controls visible when reporting a corrupt receipt path', () => {+ const displayHome = join(root, 'home\u202e');+ const receipt = preparePiTrustGrant(displayHome, cwd, configured, canonical, {+ present: false,+ });+ writeFileSync(receipt.path, '{');+ let failure: unknown;+ try {+ listPiTrustGrants(displayHome, cwd);+ } catch (error) {+ failure = error;+ }+ expect(failure).toBeInstanceOf(PiTrustReceiptError);+ if (!(failure instanceof PiTrustReceiptError)) throw new Error('receipt read did not fail');+ expect(failure.message).toContain('home\\u202e');+ expect(failure.message).not.toContain('\u202e');+ expect(failure.message).toContain('repair its JSON syntax');+ expect(readFileSync(receipt.path, 'utf8')).toBe('{');+ });++ test('persists a pending receipt before it can prove ownership, then commits it', () => {+ const pending = preparePiTrustGrant(home, cwd, configured, canonical, { present: false });+ const hash = (path: string) => createHash('sha256').update(path).digest('hex');+ expect(pending.path).toBe(join(home, '.ok', 'pi-trust', hash(cwd), `${hash(canonical)}.json`));+ expect(JSON.parse(readFileSync(pending.path, 'utf8'))).toEqual({+ version: 1,+ cwd,+ configuredTrustPath: configured,+ canonicalTrustPath: canonical,+ state: 'pending',+ previous: { present: false },+ });+ expect(+ listPiTrustGrants(home, cwd).filter((receipt) => receipt.record.state === 'committed'),+ ).toEqual([]);++ const committed = commitPiTrustGrant(home, pending);++ expect(committed.record.state).toBe('committed');+ expect(listPiTrustGrants(home, cwd)).toEqual([committed]);+ if (process.platform !== 'win32') expect(statSync(committed.path).mode & 0o777).toBe(0o600);+ });++ test.each([false, null, { choice: 'previous', nested: [1, true] }])(+ 'preserves the prior existing JSON decision %j',+ (value) => {+ const receipt = preparePiTrustGrant(home, cwd, configured, canonical, {+ present: true,+ value,+ });+ expect(listPiTrustGrants(home, cwd)[0]?.record.previous).toEqual({ present: true, value });+ expect(commitPiTrustGrant(home, receipt).record.previous).toEqual({ present: true, value });+ },+ );++ test('independent stores and projects keep independent pending and committed receipts', () => {+ const first = preparePiTrustGrant(home, cwd, configured, canonical, { present: false });+ const second = preparePiTrustGrant(+ home,+ cwd,+ join(home, 'other', 'trust.json'),+ join(root, 'other-trust.json'),+ {+ present: true,+ value: false,+ },+ );+ const thirdCwd = join(root, 'another-project');+ const third = preparePiTrustGrant(home, thirdCwd, configured, canonical, { present: false });+ const committed = commitPiTrustGrant(home, first);++ expect(listPiTrustGrants(home, cwd)).toEqual(expect.arrayContaining([committed, second]));+ expect(listPiTrustGrants(home, cwd)).toHaveLength(2);+ expect(listPiTrustGrants(home, thirdCwd)).toEqual([third]);+ forgetPiTrustGrant(home, committed);+ expect(listPiTrustGrants(home, cwd)).toEqual([second]);+ expect(listPiTrustGrants(home, thirdCwd)).toEqual([third]);+ });++ test.each(['pending', 'committed'] as const)(+ 'refuses to overwrite an existing %s receipt',+ (state) => {+ const pending = preparePiTrustGrant(home, cwd, configured, canonical, { present: false });+ const receipt = state === 'committed' ? commitPiTrustGrant(home, pending) : pending;+ const before = readFileSync(receipt.path, 'utf8');++ expect(() =>+ preparePiTrustGrant(home, cwd, configured, canonical, { present: true, value: false }),+ ).toThrow('already exists');+ expect(readFileSync(receipt.path, 'utf8')).toBe(before);+ },+ );++ test('refuses a changed receipt before commit or forget', () => {+ const pending = preparePiTrustGrant(home, cwd, configured, canonical, { present: false });+ const changed = { ...pending.record, previous: { present: true, value: false } };+ writeFileSync(pending.path, JSON.stringify(changed));++ expect(() => commitPiTrustGrant(home, pending)).toThrow('changed while');+ expect(() => forgetPiTrustGrant(home, pending)).toThrow('changed while');+ expect(JSON.parse(readFileSync(pending.path, 'utf8'))).toEqual(changed);+ });++ test('retains a malformed receipt during reads, commit, and forget', () => {+ const pending = preparePiTrustGrant(home, cwd, configured, canonical, { present: false });+ writeFileSync(pending.path, '{invalid');++ expect(() => listPiTrustGrants(home, cwd)).toThrow('is not valid JSON');+ expect(() => commitPiTrustGrant(home, pending)).toThrow('is not valid JSON');+ expect(() => forgetPiTrustGrant(home, pending)).toThrow('is not valid JSON');+ expect(() => listPiTrustGrants(home, cwd)).toThrow(PiTrustReceiptError);+ try {+ listPiTrustGrants(home, cwd);+ } catch (error) {+ expect(error).toMatchObject({+ cause: expect.any(SyntaxError),+ message: expect.stringContaining(+ 'repair its JSON syntax without changing the recorded decision',+ ),+ });+ expect(error).toHaveProperty('message', expect.not.stringContaining('permissions'));+ }+ expect(readFileSync(pending.path, 'utf8')).toBe('{invalid');+ });++ test('rejects records stored under another project or filename', () => {+ const pending = preparePiTrustGrant(home, cwd, configured, canonical, { present: false });+ const otherCwd = join(root, 'other');+ const other = preparePiTrustGrant(home, otherCwd, configured, canonical, { present: false });+ copyFileSync(pending.path, other.path);+ expect(() => listPiTrustGrants(home, otherCwd)).toThrow(+ 'does not match its project or trust-store location',+ );+ const renamed = join(dirname(pending.path), `${'0'.repeat(64)}.json`);+ renameSync(pending.path, renamed);+ expect(() => listPiTrustGrants(home, cwd)).toThrow(+ 'does not match its project or trust-store location',+ );+ expect(existsSync(renamed)).toBe(true);+ expect(existsSync(other.path)).toBe(true);+ });++ test.skipIf(process.platform === 'win32')(+ 'refuses symlinked receipts and preserves their target',+ () => {+ const pending = preparePiTrustGrant(home, cwd, configured, canonical, { present: false });+ const target = join(root, 'receipt-copy.json');+ renameSync(pending.path, target);+ symlinkSync(target, pending.path);++ expect(() => listPiTrustGrants(home, cwd)).toThrow('is not a regular file');+ expect(() => forgetPiTrustGrant(home, pending)).toThrow('is not a regular file');+ expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual(pending.record);+ },+ );++ test('ignores unrelated and atomic temporary files without modifying them', () => {+ const pending = preparePiTrustGrant(home, cwd, configured, canonical, { present: false });+ const temporary = `${pending.path}.tmp.3fd292cf-19e2-47ef-bcfa-f338727da468`;+ const unrelated = join(dirname(pending.path), 'notes.txt');+ writeFileSync(temporary, 'unfinished atomic write');+ writeFileSync(unrelated, 'unrelated user data');++ expect(listPiTrustGrants(home, cwd)).toEqual([pending]);+ const committed = commitPiTrustGrant(home, pending);+ forgetPiTrustGrant(home, committed);++ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ expect(readFileSync(temporary, 'utf8')).toBe('unfinished atomic write');+ expect(readFileSync(unrelated, 'utf8')).toBe('unrelated user data');+ });++ test('removes the bridge and recorded grant despite an interrupted receipt write', async () => {+ expect((await ensurePiBridge(cwd, { mode: 'published' }, home)).ok).toBe(true);+ const [receipt] = listPiTrustGrants(home, cwd);+ if (!receipt) throw new Error('expected committed receipt');+ const temporary = `${receipt.path}.tmp.2c814e13-d940-4e41-9bf7-dc3072e7c0e8`;+ writeFileSync(temporary, 'unfinished receipt write');+ const bridgePath = join(cwd, '.pi', 'extensions', 'open-knowledge.ts');++ expect(removeOwnMcpEntry(EDITOR_TARGETS.pi, cwd, home, bridgePath)).toMatchObject({+ kind: 'removed',+ trust: 'removed',+ });+ expect(existsSync(bridgePath)).toBe(false);+ expect(JSON.parse(readFileSync(configured, 'utf8'))).toEqual({});+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ expect(readFileSync(temporary, 'utf8')).toBe('unfinished receipt write');+ });++ test('reports invalid record fields and previous decisions without hiding their diagnosis', () => {+ const receipt = preparePiTrustGrant(home, cwd, configured, canonical, { present: false });+ writeFileSync(receipt.path, JSON.stringify({ ...receipt.record, state: 'unknown' }));+ expect(() => listPiTrustGrants(home, cwd)).toThrow('has invalid contents');++ writeFileSync(receipt.path, JSON.stringify({ ...receipt.record, previous: { present: true } }));+ expect(() => listPiTrustGrants(home, cwd)).toThrow('has an invalid previous decision');+ });++ test('reports a missing receipt directory accurately before commit and forget', () => {+ const receipt = preparePiTrustGrant(home, cwd, configured, canonical, { present: false });+ rmSync(dirname(receipt.path), { recursive: true });++ expect(() => commitPiTrustGrant(home, receipt)).toThrow('no longer exists');+ expect(() => forgetPiTrustGrant(home, receipt)).toThrow('no longer exists');+ expect(existsSync(dirname(receipt.path))).toBe(false);+ });++ test('reports a regular file in place of the receipt directory', () => {+ const path = join(home, '.ok', 'pi-trust');+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, 'unrelated file');++ expect(() => listPiTrustGrants(home, cwd)).toThrow('is not a regular directory');+ expect(readFileSync(path, 'utf8')).toBe('unrelated file');+ });++ test.skipIf(process.platform === 'win32')(+ 'refuses a receipt directory replaced by a symlink before commit and forget',+ () => {+ const receipt = preparePiTrustGrant(home, cwd, configured, canonical, { present: false });+ const directory = dirname(receipt.path);+ const target = join(root, 'moved-receipts');+ renameSync(directory, target);+ symlinkSync(target, directory);++ expect(() => commitPiTrustGrant(home, receipt)).toThrow('is not a regular directory');+ expect(() => forgetPiTrustGrant(home, receipt)).toThrow('is not a regular directory');+ expect(JSON.parse(readFileSync(receipt.path, 'utf8'))).toEqual(receipt.record);+ },+ );++ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(+ 'retains an unreadable receipt with actionable failure',+ () => {+ const receipt = preparePiTrustGrant(home, cwd, configured, canonical, { present: false });+ const before = readFileSync(receipt.path, 'utf8');+ chmodSync(receipt.path, 0o000);+ try {+ expect(() => listPiTrustGrants(home, cwd)).toThrow(+ 'parent-directory permissions, then retry',+ );+ expect(() => forgetPiTrustGrant(home, receipt)).toThrow(+ 'parent-directory permissions, then retry',+ );+ } finally {+ chmodSync(receipt.path, 0o600);+ }+ expect(readFileSync(receipt.path, 'utf8')).toBe(before);+ },+ );++ test('forgets only the receipt and empty receipt directories, leaving .ok and other state', () => {+ const receipt = preparePiTrustGrant(home, cwd, configured, canonical, { present: false });+ const keep = join(home, '.ok', 'keep.json');+ writeFileSync(keep, 'user state');++ forgetPiTrustGrant(home, receipt);++ expect(existsSync(receipt.path)).toBe(false);+ expect(existsSync(dirname(receipt.path))).toBe(false);+ expect(existsSync(join(home, '.ok', 'pi-trust'))).toBe(false);+ expect(readFileSync(keep, 'utf8')).toBe('user state');+ expect(listPiTrustGrants(home, cwd)).toEqual([]);+ });++ test('refuses non-JSON prior state before creating receipt storage', () => {+ expect(() =>+ preparePiTrustGrant(home, cwd, configured, canonical, { present: true, value: undefined }),+ ).toThrow('receipt');+ expect(existsSync(join(home, '.ok'))).toBe(false);+ });+});diff --git a/packages/cli/src/commands/pi-trust-grants.ts b/packages/cli/src/commands/pi-trust-grants.tsnew file mode 100644index 000000000..98703df9a--- /dev/null+++ b/packages/cli/src/commands/pi-trust-grants.ts@@ -0,0 +1,311 @@+import { createHash } from 'node:crypto';+import { lstatSync, mkdirSync, readdirSync, readFileSync, rmdirSync, unlinkSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { isDeepStrictEqual } from 'node:util';+import { atomicWriteFileSync } from '@inkeep/open-knowledge-core/server';+import { escapeDisplayPath } from '../utils/escape-display-path.ts';+import { isObject } from '../utils/is-object.ts';++export type PiTrustGrantPrevious = { present: false } | { present: true; value: unknown };++interface PiTrustGrantRecord {+ version: 1;+ cwd: string;+ configuredTrustPath: string;+ canonicalTrustPath: string;+ state: 'pending' | 'committed';+ previous: PiTrustGrantPrevious;+}++export interface PiTrustGrantReceipt {+ path: string;+ record: PiTrustGrantRecord;+}++function digest(path: string): string {+ return createHash('sha256').update(path).digest('hex');+}++function receiptsRoot(home: string): string {+ return join(resolve(home), '.ok', 'pi-trust');+}++function receiptsDirectory(home: string, cwd: string): string {+ return join(receiptsRoot(home), digest(resolve(cwd)));+}++function receiptPath(home: string, cwd: string, canonicalTrustPath: string): string {+ return join(receiptsDirectory(home, cwd), `${digest(canonicalTrustPath)}.json`);+}++export class PiTrustReceiptError extends Error {+ constructor(path: string, detail: string, remedy: string, cause?: unknown) {+ super(+ `Pi trust receipt at ${escapeDisplayPath(path)} ${escapeDisplayPath(detail)}; ${escapeDisplayPath(remedy)}`,+ { cause },+ );+ this.name = 'PiTrustReceiptError';+ }+}++function receiptFsError(path: string, operation: string, cause: unknown): PiTrustReceiptError {+ const code = (cause as NodeJS.ErrnoException).code;+ const detail = cause instanceof Error ? cause.message : String(cause);+ let remedy: string;+ switch (code) {+ case 'EACCES':+ case 'EPERM':+ remedy = 'check receipt and parent-directory permissions, then retry';+ break;+ case 'ENOENT':+ remedy = 'the location no longer exists; restore access to its expected location, then retry';+ break;+ default:+ remedy = 'check the path and available storage, then retry';+ }+ return new PiTrustReceiptError(path, `could not ${operation}: ${detail}`, remedy, cause);+}++function directoryExists(path: string): boolean {+ let stat: ReturnType<typeof lstatSync>;+ try {+ stat = lstatSync(path);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;+ throw receiptFsError(path, 'be inspected', error);+ }+ if (!stat.isDirectory()) {+ throw new PiTrustReceiptError(+ path,+ 'is not a regular directory',+ 'restore the intended receipt directory without a symlink, then retry',+ );+ }+ return true;+}++function hasKeys(value: Record<string, unknown>, keys: string[]): boolean {+ return (+ Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key))+ );+}++function parseRecord(value: unknown, path: string): PiTrustGrantRecord {+ if (+ !isObject(value) ||+ !hasKeys(value, [+ 'version',+ 'cwd',+ 'configuredTrustPath',+ 'canonicalTrustPath',+ 'state',+ 'previous',+ ]) ||+ value.version !== 1 ||+ typeof value.cwd !== 'string' ||+ value.cwd !== resolve(value.cwd) ||+ typeof value.configuredTrustPath !== 'string' ||+ value.configuredTrustPath !== resolve(value.configuredTrustPath) ||+ typeof value.canonicalTrustPath !== 'string' ||+ value.canonicalTrustPath !== resolve(value.canonicalTrustPath) ||+ (value.state !== 'pending' && value.state !== 'committed') ||+ !isObject(value.previous)+ ) {+ throw new PiTrustReceiptError(+ path,+ 'has invalid contents',+ 'restore a valid ownership record from a backup without guessing its trust decision, then retry',+ );+ }+ let previous: PiTrustGrantPrevious;+ if (value.previous.present === false && hasKeys(value.previous, ['present'])) {+ previous = { present: false };+ } else if (value.previous.present === true && hasKeys(value.previous, ['present', 'value'])) {+ previous = { present: true, value: value.previous.value };+ } else {+ throw new PiTrustReceiptError(+ path,+ 'has an invalid previous decision',+ 'restore the recorded previous decision from a backup without guessing its value, then retry',+ );+ }+ return {+ version: 1,+ cwd: value.cwd,+ configuredTrustPath: value.configuredTrustPath,+ canonicalTrustPath: value.canonicalTrustPath,+ state: value.state,+ previous,+ };+}++function readReceipt(home: string, cwd: string, path: string): PiTrustGrantReceipt {+ let stat: ReturnType<typeof lstatSync>;+ try {+ stat = lstatSync(path);+ } catch (error) {+ throw receiptFsError(path, 'be inspected', error);+ }+ if (!stat.isFile()) {+ throw new PiTrustReceiptError(+ path,+ 'is not a regular file',+ 'restore the intended receipt as a regular file without a symlink, then retry',+ );+ }+ let raw: string;+ try {+ raw = readFileSync(path, 'utf8');+ } catch (error) {+ throw receiptFsError(path, 'be read', error);+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch (error) {+ throw new PiTrustReceiptError(+ path,+ 'is not valid JSON',+ 'repair its JSON syntax without changing the recorded decision, then retry',+ error,+ );+ }+ const record = parseRecord(parsed, path);+ if (record.cwd !== resolve(cwd) || path !== receiptPath(home, cwd, record.canonicalTrustPath)) {+ throw new PiTrustReceiptError(+ path,+ 'does not match its project or trust-store location',+ 'restore the ownership record to its original project and trust-store location, then retry',+ );+ }+ return { path, record };+}++function matchingReceipt(home: string, receipt: PiTrustGrantReceipt): PiTrustGrantReceipt {+ const { record, path } = receipt;+ for (const directory of [receiptsRoot(home), receiptsDirectory(home, record.cwd)]) {+ if (!directoryExists(directory)) {+ throw new PiTrustReceiptError(+ directory,+ 'no longer exists',+ 'restore access to the expected receipt directory, then retry',+ );+ }+ }+ const current = readReceipt(home, record.cwd, path);+ if (!isDeepStrictEqual(current.record, record)) {+ throw new PiTrustReceiptError(+ path,+ 'changed while its trust decision was being updated',+ 'retry to read its current ownership record',+ );+ }+ return current;+}++export function preparePiTrustGrant(+ home: string,+ cwd: string,+ configuredTrustPath: string,+ canonicalTrustPath: string,+ previous: PiTrustGrantPrevious,+): PiTrustGrantReceipt {+ const record: PiTrustGrantRecord = {+ version: 1,+ cwd: resolve(cwd),+ configuredTrustPath: resolve(configuredTrustPath),+ canonicalTrustPath: resolve(canonicalTrustPath),+ state: 'pending',+ previous,+ };+ const path = receiptPath(home, record.cwd, record.canonicalTrustPath);+ const serialized = `${JSON.stringify(record, null, 2)}\n`;+ if (!isDeepStrictEqual(parseRecord(JSON.parse(serialized), path), record)) {+ throw new PiTrustReceiptError(+ path,+ 'cannot preserve the previous decision as JSON',+ 'provide the original decision as a JSON value before retrying',+ );+ }+ directoryExists(receiptsRoot(home));+ directoryExists(dirname(path));+ try {+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });+ } catch (error) {+ throw receiptFsError(dirname(path), 'be created', error);+ }+ let existing: ReturnType<typeof lstatSync> | undefined;+ try {+ existing = lstatSync(path, { throwIfNoEntry: false });+ } catch (error) {+ throw receiptFsError(path, 'be inspected', error);+ }+ if (existing) {+ throw new PiTrustReceiptError(+ path,+ 'already exists',+ 'reconcile the existing ownership record before recording another grant',+ );+ }+ try {+ atomicWriteFileSync(path, serialized, { mode: 0o600 });+ } catch (error) {+ throw receiptFsError(path, 'be written', error);+ }+ return { path, record };+}++export function commitPiTrustGrant(+ home: string,+ receipt: PiTrustGrantReceipt,+): PiTrustGrantReceipt {+ const current = matchingReceipt(home, receipt);+ if (current.record.state !== 'pending') {+ throw new PiTrustReceiptError(+ current.path,+ 'is already committed',+ 'use the current ownership record without committing it again',+ );+ }+ const record: PiTrustGrantRecord = { ...current.record, state: 'committed' };+ try {+ atomicWriteFileSync(current.path, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 });+ } catch (error) {+ throw receiptFsError(current.path, 'be committed', error);+ }+ return { path: current.path, record };+}++export function listPiTrustGrants(home: string, cwd: string): PiTrustGrantReceipt[] {+ if (!directoryExists(receiptsRoot(home))) return [];+ const directory = receiptsDirectory(home, cwd);+ if (!directoryExists(directory)) return [];+ let names: string[];+ try {+ names = readdirSync(directory).sort();+ } catch (error) {+ throw receiptFsError(directory, 'be listed', error);+ }+ return names+ .filter((name) => /^[a-f0-9]{64}\.json$/.test(name))+ .map((name) => readReceipt(home, cwd, join(directory, name)));+}++export function forgetPiTrustGrant(home: string, receipt: PiTrustGrantReceipt): void {+ const current = matchingReceipt(home, receipt);+ try {+ unlinkSync(current.path);+ } catch (error) {+ throw receiptFsError(current.path, 'be removed after reconciling its grant', error);+ }+ for (const directory of [dirname(current.path), receiptsRoot(home)]) {+ try {+ rmdirSync(directory);+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (code !== 'ENOTEMPTY' && code !== 'EEXIST' && code !== 'ENOENT') {+ throw receiptFsError(directory, 'be removed after reconciling its grant', error);+ }+ }+ }+}diff --git a/packages/cli/src/commands/pi-trust-lock.test.ts b/packages/cli/src/commands/pi-trust-lock.test.tsnew file mode 100644index 000000000..4bd914c4e--- /dev/null+++ b/packages/cli/src/commands/pi-trust-lock.test.ts@@ -0,0 +1,222 @@+import { type ChildProcess, spawn } from 'node:child_process';+import { once } from 'node:events';+import {+ existsSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ utimesSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import lockfile from 'proper-lockfile';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { withPiTrustLock, withPiTrustLockSync } from './pi-trust-lock.ts';++const CHILD_WRITER = `+ import { readFileSync, writeFileSync } from 'node:fs';+ const [helperUrl, mode, configured, canonical] = process.argv.slice(1);+ const { withPiTrustLock, withPiTrustLockSync } = await import(helperUrl);+ const write = () => {+ process.send('entered');+ const state = JSON.parse(readFileSync(canonical, 'utf8'));+ if (mode === 'async') state.openknowledge = true;+ else delete state.openknowledge;+ writeFileSync(canonical, JSON.stringify(state));+ };+ process.send('ready');+ try {+ if (mode === 'async') await withPiTrustLock(configured, canonical, write);+ else withPiTrustLockSync(configured, canonical, write);+ process.disconnect();+ } catch (error) {+ process.stderr.write(String(error));+ process.exitCode = 1;+ process.disconnect();+ }+`;++describe.each(['async', 'sync'] as const)('Pi trust lock (%s)', (mode) => {+ let root: string;+ let configured: string;+ let canonical: string;+ const children: ChildProcess[] = [];++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'ok-pi-trust-lock-'));+ configured = join(root, 'configured', 'trust.json');+ canonical = join(root, 'canonical', 'trust.json');+ mkdirSync(dirname(configured));+ mkdirSync(dirname(canonical));+ writeFileSync(canonical, '{}');+ });++ afterEach(async () => {+ for (const child of children.splice(0)) {+ if (child.exitCode !== null || child.signalCode !== null) continue;+ const exited = once(child, 'exit');+ child.kill('SIGKILL');+ await exited;+ }+ rmSync(root, { recursive: true, force: true });+ });++ async function runLock(fn: () => void): Promise<void> {+ if (mode === 'async') await withPiTrustLock(configured, canonical, fn);+ else withPiTrustLockSync(configured, canonical, fn);+ }++ test('coordinates with a separate Pi writer and preserves its update', async () => {+ const original =+ mode === 'sync' ? { existing: false, openknowledge: true } : { existing: false };+ writeFileSync(canonical, JSON.stringify(original));+ const releasePi = lockfile.lockSync(dirname(configured), {+ realpath: false,+ lockfilePath: `${configured}.lock`,+ });+ const child = spawn(+ process.execPath,+ [+ '--import',+ 'tsx',+ '--conditions=development',+ '--input-type=module',+ '-e',+ CHILD_WRITER,+ new URL('./pi-trust-lock.ts', import.meta.url).href,+ mode,+ configured,+ canonical,+ ],+ { stdio: ['ignore', 'ignore', 'pipe', 'ipc'], windowsHide: true },+ );+ children.push(child);+ let entered = false;+ let stderr = '';+ child.on('message', (message) => {+ if (message === 'entered') entered = true;+ });+ child.stderr?.on('data', (chunk) => {+ stderr += chunk.toString();+ });+ const exited = once(child, 'exit');+ try {+ await vi.waitFor(+ () => {+ expect(child.exitCode, stderr).toBeNull();+ expect(existsSync(`${canonical}.ok.lock`), stderr).toBe(true);+ },+ { timeout: 15_000, interval: 10 },+ );+ expect(entered).toBe(false);+ writeFileSync(canonical, JSON.stringify({ ...original, pi: true }));+ } finally {+ releasePi();+ }+ expect((await exited)[0], stderr).toBe(0);+ expect(entered).toBe(true);+ expect(JSON.parse(readFileSync(canonical, 'utf8'))).toEqual(+ mode === 'async'+ ? { existing: false, pi: true, openknowledge: true }+ : { existing: false, pi: true },+ );+ expect(existsSync(`${canonical}.ok.lock`)).toBe(false);+ expect(existsSync(`${configured}.lock`)).toBe(false);+ });++ test('uses the same canonical lock when configured aliases differ', async () => {+ const otherConfigured = join(root, 'other-configured', 'trust.json');+ mkdirSync(dirname(otherConfigured));+ const canonicalLock = `${canonical}.ok.lock`;+ writeFileSync(canonicalLock, 'held through another alias');+ configured = otherConfigured;+ const callback = vi.fn();+ await expect(runLock(callback)).rejects.toMatchObject({ code: 'LOCK_TIMEOUT' });+ expect(callback).not.toHaveBeenCalled();+ expect(readFileSync(canonicalLock, 'utf8')).toBe('held through another alias');+ expect(existsSync(`${configured}.lock`)).toBe(false);+ });++ test('refuses a busy Pi directory lock and releases the canonical lock', async () => {+ mkdirSync(`${configured}.lock`);+ const callback = vi.fn();+ const pending = runLock(callback);+ await expect(pending).rejects.toMatchObject({ code: 'ELOCKED' });+ await expect(pending).rejects.toThrow(`${configured}.lock within 5000ms`);+ expect(callback).not.toHaveBeenCalled();+ expect(lstatSync(`${configured}.lock`).isDirectory()).toBe(true);+ expect(existsSync(`${canonical}.ok.lock`)).toBe(false);+ });++ test('recovers a stale Pi directory lock with Pi default expiry', async () => {+ mkdirSync(`${configured}.lock`);+ const old = new Date(Date.now() - 20_000);+ utimesSync(`${configured}.lock`, old, old);+ const callback = vi.fn(() => {+ expect(lstatSync(`${configured}.lock`).isDirectory()).toBe(true);+ expect(lstatSync(`${canonical}.ok.lock`).isFile()).toBe(true);+ });+ await runLock(callback);+ expect(callback).toHaveBeenCalledOnce();+ expect(existsSync(`${configured}.lock`)).toBe(false);+ expect(existsSync(`${canonical}.ok.lock`)).toBe(false);+ });++ test('preserves an incompatible regular lock artifact instead of claiming it', async () => {+ writeFileSync(`${configured}.lock`, 'another lock protocol');+ const old = new Date(Date.now() - 20_000);+ utimesSync(`${configured}.lock`, old, old);+ const callback = vi.fn();+ await expect(runLock(callback)).rejects.toThrow();+ expect(callback).not.toHaveBeenCalled();+ expect(readFileSync(`${configured}.lock`, 'utf8')).toBe('another lock protocol');+ expect(existsSync(`${canonical}.ok.lock`)).toBe(false);+ });++ test('releases both locks when the synchronous writer throws', async () => {+ const failure = new Error('trust write failed');+ await expect(+ runLock(() => {+ throw failure;+ }),+ ).rejects.toBe(failure);+ expect(existsSync(`${configured}.lock`)).toBe(false);+ expect(existsSync(`${canonical}.ok.lock`)).toBe(false);+ await runLock(() => writeFileSync(canonical, '{"recovered":true}'));+ expect(readFileSync(canonical, 'utf8')).toBe('{"recovered":true}');+ });++ test('propagates Pi release failure while releasing the canonical lock', async () => {+ const unexpectedFile = join(`${configured}.lock`, 'unexpected');+ await expect(+ runLock(() => writeFileSync(unexpectedFile, 'preserve this file')),+ ).rejects.toThrow();+ expect(readFileSync(unexpectedFile, 'utf8')).toBe('preserve this file');+ expect(existsSync(`${canonical}.ok.lock`)).toBe(false);+ });++ test('preserves both writer and release failures in the caller-visible message', async () => {+ const writeFailure = new Error('trust write failed; repair the receipt before retrying');+ const unexpectedFile = join(`${configured}.lock`, 'unexpected');+ const failure: unknown = await runLock(() => {+ writeFileSync(unexpectedFile, 'preserve this file');+ throw writeFailure;+ }).catch((error: unknown) => error);++ expect(failure).toBeInstanceOf(AggregateError);+ if (!(failure instanceof AggregateError)) throw failure;+ expect(failure.errors).toHaveLength(2);+ expect(failure.errors[0]).toBe(writeFailure);+ const releaseFailure: unknown = failure.errors[1];+ expect(releaseFailure).toBeInstanceOf(Error);+ if (!(releaseFailure instanceof Error)) throw releaseFailure;+ expect(failure.message).toContain(writeFailure.message);+ expect(failure.message).toContain(releaseFailure.message);+ expect(failure.message).toContain(`${configured}.lock`);+ expect(readFileSync(unexpectedFile, 'utf8')).toBe('preserve this file');+ expect(existsSync(`${canonical}.ok.lock`)).toBe(false);+ });+});diff --git a/packages/cli/src/commands/pi-trust-lock.ts b/packages/cli/src/commands/pi-trust-lock.tsnew file mode 100644index 000000000..cbd425c77--- /dev/null+++ b/packages/cli/src/commands/pi-trust-lock.ts@@ -0,0 +1,119 @@+import { dirname } from 'node:path';+import { setTimeout } from 'node:timers/promises';+import { withFileLock, withFileLockSync } from '@inkeep/open-knowledge-core/server';+import lockfile from 'proper-lockfile';+import { getCliLogger } from '../cli-logger.ts';++const ACQUISITION_TIMEOUT_MS = 5000;+const RETRY_INTERVAL_MS = 25;++function retryDelay(error: unknown, deadline: number, configuredTrustPath: string): number {+ if (!(error instanceof Error) || !('code' in error) || error.code !== 'ELOCKED') throw error;+ const remaining = deadline - performance.now();+ if (remaining <= 0) {+ throw Object.assign(+ new Error(+ `Could not acquire Pi trust lock at ${configuredTrustPath}.lock within ${ACQUISITION_TIMEOUT_MS}ms`,+ { cause: error },+ ),+ { code: 'ELOCKED' },+ );+ }+ return Math.min(RETRY_INTERVAL_MS, remaining);+}++function logCanonicalLockWarning(message: string, context: Record<string, unknown>): void {+ getCliLogger()?.warn(context, message);+}++function throwTrustFailures(errors: unknown[], configuredTrustPath: string): void {+ if (errors.length === 0) return;+ if (errors.length === 1) throw errors[0];+ const [writeError, releaseError] = errors;+ const writeMessage = writeError instanceof Error ? writeError.message : String(writeError);+ const releaseMessage =+ releaseError instanceof Error ? releaseError.message : String(releaseError);+ throw new AggregateError(+ errors,+ `Pi trust update failed: ${writeMessage}\nReleasing Pi trust lock ${configuredTrustPath}.lock also failed: ${releaseMessage}`,+ );+}++export async function withPiTrustLock(+ configuredTrustPath: string,+ canonicalTrustPath: string,+ fn: () => void,+): Promise<void> {+ await withFileLock(+ `${canonicalTrustPath}.ok.lock`,+ async () => {+ const deadline = performance.now() + ACQUISITION_TIMEOUT_MS;+ let release: () => Promise<void>;+ while (true) {+ try {+ release = await lockfile.lock(dirname(configuredTrustPath), {+ realpath: false,+ lockfilePath: `${configuredTrustPath}.lock`,+ });+ break;+ } catch (error) {+ await setTimeout(retryDelay(error, deadline, configuredTrustPath));+ }+ }+ const errors: unknown[] = [];+ try {+ fn();+ } catch (error) {+ errors.push(error);+ } finally {+ try {+ await release();+ } catch (error) {+ errors.push(error);+ }+ }+ throwTrustFailures(errors, configuredTrustPath);+ },+ { onWarn: logCanonicalLockWarning },+ );+}++export function withPiTrustLockSync(+ configuredTrustPath: string,+ canonicalTrustPath: string,+ fn: () => void,+): void {+ withFileLockSync(+ `${canonicalTrustPath}.ok.lock`,+ () => {+ const deadline = performance.now() + ACQUISITION_TIMEOUT_MS;+ const waitArray = new Int32Array(new SharedArrayBuffer(4));+ let release: () => void;+ while (true) {+ try {+ release = lockfile.lockSync(dirname(configuredTrustPath), {+ realpath: false,+ lockfilePath: `${configuredTrustPath}.lock`,+ });+ break;+ } catch (error) {+ Atomics.wait(waitArray, 0, 0, retryDelay(error, deadline, configuredTrustPath));+ }+ }+ const errors: unknown[] = [];+ try {+ fn();+ } catch (error) {+ errors.push(error);+ } finally {+ try {+ release();+ } catch (error) {+ errors.push(error);+ }+ }+ throwTrustFailures(errors, configuredTrustPath);+ },+ { onWarn: logCanonicalLockWarning },+ );+}diff --git a/packages/cli/src/commands/pi-trust-resources.test.ts b/packages/cli/src/commands/pi-trust-resources.test.tsnew file mode 100644index 000000000..2f870606b--- /dev/null+++ b/packages/cli/src/commands/pi-trust-resources.test.ts@@ -0,0 +1,197 @@+import {+ chmodSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { inspectPiTrustResources } from './pi-trust-resources.ts';++describe('Pi trust dependent resources', () => {+ let root: string;+ let home: string;+ let cwd: string;+ let bridgePath: string;++ beforeEach(() => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pi-resources-')));+ home = join(root, 'home');+ cwd = join(root, 'project');+ bridgePath = join(cwd, '.pi', 'extensions', 'open-knowledge.ts');+ mkdirSync(home);+ mkdirSync(dirname(bridgePath), { recursive: true });+ writeFileSync(bridgePath, 'owned bridge');+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ test('ignores only the bridge and owned skill namespaces in the current project', () => {+ for (const skillRoot of [join(cwd, '.pi', 'skills'), join(cwd, '.agents', 'skills')]) {+ for (const name of ['open-knowledge', 'open-knowledge-discovery', 'open-knowledge-custom']) {+ mkdirSync(join(skillRoot, name), { recursive: true });+ writeFileSync(join(skillRoot, name, 'keep.txt'), 'owned namespace');+ }+ }+ expect(inspectPiTrustResources(cwd, home, bridgePath)).toEqual({ kind: 'none' });+ expect(readFileSync(bridgePath, 'utf8')).toBe('owned bridge');+ });++ test('empty extension and skill directories need no shared trust', () => {+ mkdirSync(join(cwd, '.pi', 'skills'));+ mkdirSync(join(cwd, '.agents', 'skills'), { recursive: true });+ expect(inspectPiTrustResources(cwd, home, bridgePath)).toEqual({ kind: 'none' });+ });++ test.each(['settings.json', 'prompts', 'themes', 'SYSTEM.md', 'APPEND_SYSTEM.md'])(+ 'preserves trust for the existing %s resource, including empty files and directories',+ (name) => {+ const path = join(cwd, '.pi', name);+ if (name === 'prompts' || name === 'themes') mkdirSync(path);+ else writeFileSync(path, '');+ expect(inspectPiTrustResources(cwd, home, bridgePath)).toEqual({+ kind: 'shared',+ paths: [path],+ });+ },+ );++ test.each(['other.ts', 'other.js', 'package-extension', '.extension-state'])(+ 'preserves trust for every other extension entry: %s',+ (name) => {+ const path = join(dirname(bridgePath), name);+ if (name === 'package-extension') mkdirSync(path);+ else writeFileSync(path, '');+ expect(inspectPiTrustResources(cwd, home, bridgePath)).toEqual({+ kind: 'shared',+ paths: [path],+ });+ },+ );++ test.each(['.pi', '.agents'])(+ 'preserves unrelated %s skills without claiming a similar name',+ (dir) => {+ const path = join(cwd, dir, 'skills', 'open-knowledgeable');+ mkdirSync(path, { recursive: true });+ expect(inspectPiTrustResources(cwd, home, bridgePath)).toEqual({+ kind: 'shared',+ paths: [path],+ });+ },+ );++ test('ancestor skill roots remain shared even when empty or entirely OpenKnowledge-named', () => {+ const shared = join(root, '.agents', 'skills');+ mkdirSync(shared, { recursive: true });+ expect(inspectPiTrustResources(cwd, home, bridgePath)).toEqual({+ kind: 'shared',+ paths: [shared],+ });+ mkdirSync(join(shared, 'open-knowledge-discovery'));+ expect(inspectPiTrustResources(cwd, home, bridgePath)).toEqual({+ kind: 'shared',+ paths: [shared],+ });+ });++ test('ignores user-global agents skills when home is the project or an ancestor', () => {+ mkdirSync(join(home, '.agents', 'skills', 'personal-skill'), { recursive: true });+ const nested = join(home, 'project');+ mkdirSync(nested);+ expect(+ inspectPiTrustResources(nested, home, join(nested, '.pi', 'extensions', 'open-knowledge.ts')),+ ).toEqual({ kind: 'none' });+ expect(+ inspectPiTrustResources(home, home, join(home, '.pi', 'extensions', 'open-knowledge.ts')),+ ).toEqual({ kind: 'none' });+ });++ test.skipIf(process.platform === 'win32')(+ 'inspects a symlinked skill root and preserves foreign resources',+ () => {+ const target = join(root, 'user-skills');+ mkdirSync(join(target, 'foreign'), { recursive: true });+ symlinkSync(target, join(cwd, '.pi', 'skills'));+ expect(inspectPiTrustResources(cwd, home, bridgePath)).toEqual({+ kind: 'shared',+ paths: [join(cwd, '.pi', 'skills', 'foreign')],+ });+ },+ );++ test.skipIf(process.platform === 'win32')('refuses an unresolved resource symlink', () => {+ const path = join(cwd, '.pi', 'prompts');+ symlinkSync(join(root, 'missing-prompts'), path);+ const outcome = inspectPiTrustResources(cwd, home, bridgePath);+ expect(outcome).toMatchObject({ kind: 'unreadable' });+ if (outcome.kind === 'unreadable') {+ expect(outcome.error).toContain(path);+ expect(outcome.error).toContain('symlink target is missing');+ expect(outcome.error).toContain('restore the target or correct the symlink');+ expect(outcome.error).not.toContain('permissions');+ }+ });++ test.skipIf(process.platform === 'win32')(+ 'escapes terminal controls in an unreadable resource path',+ () => {+ const project = join(root, 'project\u001b[2K\r\n\u202e');+ mkdirSync(join(project, '.pi'), { recursive: true });+ symlinkSync(join(root, 'missing-prompts'), join(project, '.pi', 'prompts'));+ const outcome = inspectPiTrustResources(+ project,+ home,+ join(project, '.pi', 'extensions', 'open-knowledge.ts'),+ );+ expect(outcome).toMatchObject({ kind: 'unreadable' });+ if (outcome.kind === 'unreadable') {+ expect(outcome.error).toContain('project\\u001b[2K\\u000d\\u000a\\u202e');+ expect(outcome.error).not.toMatch(/[\p{Cc}\p{Zl}\p{Zp}]/u);+ expect(outcome.error).not.toContain('\u202e');+ expect(outcome.error).toContain('restore the target or correct the symlink');+ }+ },+ );++ test.skipIf(process.platform === 'win32')(+ 'reports a resource symlink cycle with its repair',+ () => {+ const path = join(cwd, '.pi', 'prompts');+ symlinkSync(path, path);+ const outcome = inspectPiTrustResources(cwd, home, bridgePath);+ expect(outcome).toMatchObject({ kind: 'unreadable' });+ if (outcome.kind === 'unreadable') {+ expect(outcome.error).toContain(path);+ expect(outcome.error).toContain('repair any symlink cycle');+ }+ },+ );++ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(+ 'refuses an unreadable skill root rather than treating it as empty',+ () => {+ const path = join(cwd, '.pi', 'skills');+ mkdirSync(path);+ chmodSync(path, 0o000);+ try {+ const outcome = inspectPiTrustResources(cwd, home, bridgePath);+ expect(outcome).toMatchObject({ kind: 'unreadable' });+ if (outcome.kind === 'unreadable') {+ expect(outcome.error).toContain(path);+ expect(outcome.error).toContain('permission denied');+ expect(outcome.error).toContain('check file and parent-directory permissions');+ }+ } finally {+ chmodSync(path, 0o700);+ }+ },+ );+});diff --git a/packages/cli/src/commands/pi-trust-resources.ts b/packages/cli/src/commands/pi-trust-resources.tsnew file mode 100644index 000000000..812a8b8cb--- /dev/null+++ b/packages/cli/src/commands/pi-trust-resources.ts@@ -0,0 +1,104 @@+import { accessSync, constants, lstatSync, readdirSync, realpathSync, statSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { configFileDeclineDetail, configFileDeclineReason } from '../utils/config-file-error.ts';+import { escapeDisplayPath } from '../utils/escape-display-path.ts';++export type PiTrustResources =+ | { kind: 'none' }+ | { kind: 'shared'; paths: string[] }+ | { kind: 'unreadable'; error: string };++const PI_PROJECT_RESOURCES = [+ 'settings.json',+ 'prompts',+ 'themes',+ 'SYSTEM.md',+ 'APPEND_SYSTEM.md',+];++class PiResourceInspectionError extends Error {+ override name = 'PiResourceInspectionError';+}++function readablePathExists(path: string): boolean {+ let entry: ReturnType<typeof lstatSync>;+ try {+ entry = lstatSync(path);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;+ throw error;+ }+ let stat: ReturnType<typeof statSync>;+ try {+ stat = statSync(path);+ } catch (error) {+ if (entry.isSymbolicLink() && (error as NodeJS.ErrnoException).code === 'ENOENT') {+ throw new PiResourceInspectionError(configFileDeclineDetail('missing-symlink-target'), {+ cause: error,+ });+ }+ throw error;+ }+ accessSync(path, constants.R_OK | (stat.isDirectory() ? constants.X_OK : 0));+ return true;+}++function isOwnedSkillName(name: string): boolean {+ return name === 'open-knowledge' || name.startsWith('open-knowledge-');+}++export function inspectPiTrustResources(+ cwd: string,+ home: string,+ bridgePath: string,+): PiTrustResources {+ let inspecting = cwd;+ try {+ const project = realpathSync(cwd);+ let userHome: string;+ inspecting = home;+ try {+ userHome = realpathSync(home);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ userHome = resolve(home);+ }+ const globalSkills = join(userHome, '.agents', 'skills');+ const paths: string[] = [];+ for (const name of PI_PROJECT_RESOURCES) {+ inspecting = join(project, '.pi', name);+ if (readablePathExists(inspecting)) paths.push(inspecting);+ }+ inspecting = join(project, '.pi', 'extensions');+ if (readablePathExists(inspecting)) {+ for (const name of readdirSync(inspecting).sort()) {+ const path = join(inspecting, name);+ if (resolve(bridgePath) !== join(resolve(cwd), '.pi', 'extensions', name)) {+ paths.push(path);+ }+ }+ }+ for (const directory of [join(project, '.pi', 'skills'), join(project, '.agents', 'skills')]) {+ if (directory === globalSkills) continue;+ inspecting = directory;+ if (!readablePathExists(directory)) continue;+ for (const name of readdirSync(directory).sort()) {+ if (!isOwnedSkillName(name)) paths.push(join(directory, name));+ }+ }+ let ancestor = dirname(project);+ while (ancestor !== project) {+ inspecting = join(ancestor, '.agents', 'skills');+ if (inspecting !== globalSkills && readablePathExists(inspecting)) paths.push(inspecting);+ const parent = dirname(ancestor);+ if (parent === ancestor) break;+ ancestor = parent;+ }+ return paths.length === 0 ? { kind: 'none' } : { kind: 'shared', paths: paths.sort() };+ } catch (error) {+ return {+ kind: 'unreadable',+ error: `Could not inspect Pi project resources at ${escapeDisplayPath(inspecting)}: ${error instanceof PiResourceInspectionError ? error.message : configFileDeclineDetail(configFileDeclineReason(error))}`,+ };+ }+}diff --git a/packages/cli/src/commands/removal-file-path.test.ts b/packages/cli/src/commands/removal-file-path.test.tsnew file mode 100644index 000000000..d1c847bb1--- /dev/null+++ b/packages/cli/src/commands/removal-file-path.test.ts@@ -0,0 +1,80 @@+import {+ chmodSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { resolveRemovalFilePath } from './removal-file-path.ts';++describe('resolveRemovalFilePath', () => {+ let dir: string;++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'ok-removal-file-'));+ });++ afterEach(() => {+ rmSync(dir, { recursive: true, force: true });+ });++ test('distinguishes missing files from existing regular files', () => {+ const path = join(dir, 'config');+ expect(resolveRemovalFilePath(path)).toEqual({ kind: 'not-present' });+ writeFileSync(path, 'settings');+ expect(resolveRemovalFilePath(path)).toEqual({ kind: 'ready', path, symlink: false });+ });++ test('declines a directory at the configuration path', () => {+ const path = join(dir, 'config');+ mkdirSync(path);+ expect(resolveRemovalFilePath(path)).toEqual({ kind: 'declined', reason: 'not-a-file' });+ });++ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(+ 'reports inaccessible parent-directory permissions without treating the file as absent',+ () => {+ const parent = join(dir, 'private');+ const path = join(parent, 'config');+ mkdirSync(parent);+ writeFileSync(path, 'settings');+ chmodSync(parent, 0o000);+ try {+ expect(resolveRemovalFilePath(path)).toEqual({+ kind: 'declined',+ reason: 'permission-denied',+ });+ } finally {+ chmodSync(parent, 0o700);+ }+ },+ );++ test.skipIf(process.platform === 'win32')('resolves a relative symlink chain', () => {+ const path = join(dir, 'config');+ const target = join(dir, 'target');+ writeFileSync(target, 'settings');+ symlinkSync('target', join(dir, 'intermediate'));+ symlinkSync('intermediate', path);+ expect(resolveRemovalFilePath(path)).toEqual({ kind: 'ready', path: target, symlink: true });+ expect(lstatSync(path).isSymbolicLink()).toBe(true);+ });++ test.skipIf(process.platform === 'win32').each(['dangling', 'cycle'])(+ 'declines a %s symlink without replacing it',+ (kind) => {+ const path = join(dir, 'config');+ symlinkSync(kind === 'cycle' ? 'config' : 'missing', path);+ expect(resolveRemovalFilePath(path)).toEqual({+ kind: 'declined',+ reason: kind === 'cycle' ? 'unresolved-symlink' : 'missing-symlink-target',+ });+ expect(lstatSync(path).isSymbolicLink()).toBe(true);+ },+ );+});diff --git a/packages/cli/src/commands/removal-file-path.ts b/packages/cli/src/commands/removal-file-path.tsnew file mode 100644index 000000000..5a149c9c2--- /dev/null+++ b/packages/cli/src/commands/removal-file-path.ts@@ -0,0 +1,37 @@+import { lstatSync, statSync } from 'node:fs';+import { resolveHarnessWritePaths } from '../native/symlink-resolve.ts';+import {+ type ConfigFileDeclineReason,+ configFileDeclineReason,+} from '../utils/config-file-error.ts';++type RemovalFilePath =+ | { kind: 'ready'; path: string; symlink: boolean }+ | { kind: 'not-present' }+ | { kind: 'declined'; reason: ConfigFileDeclineReason };++export function resolveRemovalFilePath(configPath: string): RemovalFilePath {+ let symlink: boolean;+ try {+ symlink = lstatSync(configPath).isSymbolicLink();+ } catch (error) {+ return (error as NodeJS.ErrnoException).code === 'ENOENT'+ ? { kind: 'not-present' }+ : { kind: 'declined', reason: configFileDeclineReason(error) };+ }++ const resolved = resolveHarnessWritePaths(configPath);+ if (resolved.readPath === null) return { kind: 'declined', reason: 'unresolved-symlink' };+ try {+ if (!statSync(resolved.readPath).isFile()) return { kind: 'declined', reason: 'not-a-file' };+ } catch (error) {+ return {+ kind: 'declined',+ reason:+ symlink && (error as NodeJS.ErrnoException).code === 'ENOENT'+ ? 'missing-symlink-target'+ : configFileDeclineReason(error),+ };+ }+ return { kind: 'ready', path: resolved.writePath, symlink };+}diff --git a/packages/cli/src/commands/removal-plan.test.ts b/packages/cli/src/commands/removal-plan.test.tsindex f70f6df1f..b326fc4b1 100644--- a/packages/cli/src/commands/removal-plan.test.ts+++ b/packages/cli/src/commands/removal-plan.test.ts@@ -5,6 +5,7 @@ import {mkdirSync,mkdtempSync,readFileSync,+ realpathSync,rmSync,symlinkSync,writeFileSync,@@ -15,13 +16,20 @@ import { MCP_SERVER_NAME } from '@inkeep/open-knowledge-server';import { describe, expect, test } from 'vitest';import { DESKTOP_UPDATER_CACHE_DIR_NAME } from '../integrations/desktop-state.ts';import { readPathInstallMarker } from '../integrations/path-shim.ts';+import {+ createTomlConfigEngine,+ setTomlConfigEngineForTesting,+} from '../native/toml-config-engine.ts';import { buildManagedServerEntry } from './editors.ts';import { ensurePiBridge, probePiBridgeState } from './pi-acp-bridge.ts';+import { listPiTrustGrants, preparePiTrustGrant } from './pi-trust-grants.ts';+import { withPiTrustLockSync } from './pi-trust-lock.ts';import {applicationDataOps,buildUninstallPlan,deinitOps,describeAttachedClients,+ type RemovalOp,type RunRemovalDeps,runRemoval,type UninstallPlanInput,@@ -445,7 +453,7 @@ describe('runRemoval — uninstall end to end', () => {}});- test('a locked keychain is marked failed with a manual hint, never aborting the run', async () => {+ test('a locked keychain reports failure and retains state for retry', async () => {const home = mkdtempSync(join(tmpdir(), 'ok-uninst-'));try {seedHome(home);@@ -459,13 +467,13 @@ describe('runRemoval — uninstall end to end', () => {const keychain = outcome.results.find((r) => r.op.kind === 'keychain-token');expect(keychain?.status).toBe('failed');expect(keychain?.detail).toContain('Keychain Access');- expect(existsSync(join(home, '.ok', 'auth.yml'))).toBe(false);+ expect(existsSync(join(home, '.ok', 'auth.yml'))).toBe(true);} finally {rmSync(home, { recursive: true, force: true });}});- test('a stop-server failure surfaces as failed (a live process may still hold the files)', async () => {+ test('a stop-server failure preserves files still needed by the live process', async () => {const home = mkdtempSync(join(tmpdir(), 'ok-uninst-'));try {seedHome(home);@@ -480,7 +488,7 @@ describe('runRemoval — uninstall end to end', () => {expect(stop?.status).toBe('failed');expect(stop?.detail).toContain('4242');expect(outcome.failed.some((r) => r.op.kind === 'stop-server')).toBe(true);- expect(existsSync(join(home, '.ok', 'auth.yml'))).toBe(false);+ expect(existsSync(join(home, '.ok', 'auth.yml'))).toBe(true);} finally {rmSync(home, { recursive: true, force: true });}@@ -573,6 +581,8 @@ describe('pi trust revocation surfaces through the removal plan', () => {const outcome = await runRemoval({ ops: [piOp(cwd, home)] }, stubDeps());expect(outcome.results[0]?.status).toBe('removed');expect(outcome.results[0]?.detail).toContain('folder trust');+ expect(outcome.results[0]?.detail).toContain(join(cwd, '.pi', 'extensions', 'theirs.ts'));+ expect(outcome.results[0]?.detail).toContain('will not revoke it on later cleanup runs');expect(probePiBridgeState(cwd, home).trust).toBe('trusted');expect(formatRemovalOutcome(outcome)).toContain('folder trust');const json = removalOutcomeToJson('deinit', outcome);@@ -583,6 +593,189 @@ describe('pi trust revocation surfaces through the removal plan', () => {}});+ test('reports every failed store alongside a completed trust handoff', async () => {+ const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pi-removal-')));+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pi-removal-home-')));+ try {+ const stores = ['first', 'second', 'shared'].map((name) => join(home, name));+ for (const store of stores) {+ expect(+ await ensurePiBridge(cwd, { mode: 'published' }, home, { PI_CODING_AGENT_DIR: store }),+ ).toMatchObject({ ok: true });+ }+ const sharedTrust = join(home, 'shared', 'trust.json');+ const before = readFileSync(sharedTrust, 'utf8');+ const prompts = join(cwd, '.pi', 'prompts');+ mkdirSync(prompts);+ for (const name of ['first', 'second']) write(join(home, name, 'trust.json'), '{broken');++ const outcome = await runRemoval({ ops: [piOp(cwd, home)] }, stubDeps());+ expect(outcome.failed).toHaveLength(1);+ const detail = outcome.failed[0]?.detail;+ expect(detail).toContain(join(home, 'first', 'trust.json'));+ expect(detail).toContain(join(home, 'second', 'trust.json'));+ expect(detail).toContain(sharedTrust);+ expect(detail).toContain(prompts);+ expect(detail).toContain(JSON.stringify(cwd));+ expect(detail).toContain('has relinquished this grant');+ expect(detail).toContain('will not revoke it on later cleanup runs');+ expect(formatRemovalOutcome(outcome)).toContain(detail?.replaceAll('\n', '\n '));+ const json = removalOutcomeToJson('deinit', outcome);+ expect(json.mode === 'applied' && json.failed[0]?.detail).toBe(detail);+ expect(readFileSync(sharedTrust, 'utf8')).toBe(before);+ expect(existsSync(piOp(cwd, home).configPath)).toBe(true);+ expect(+ listPiTrustGrants(home, cwd)+ .map((receipt) => receipt.record.configuredTrustPath)+ .sort(),+ ).toEqual(['first', 'second'].map((name) => join(home, name, 'trust.json')));+ } finally {+ rmSync(cwd, { recursive: true, force: true });+ rmSync(home, { recursive: true, force: true });+ }+ });++ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0).each([true, false])(+ 'reports bridge deletion failure after trust cleanup with shared resources: %s',+ async (shared) => {+ const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pi-removal-')));+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pi-removal-home-')));+ const extensions = join(cwd, '.pi', 'extensions');+ try {+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ const trustPath = join(home, '.pi', 'agent', 'trust.json');+ const before = readFileSync(trustPath, 'utf8');+ if (shared) mkdirSync(join(cwd, '.pi', 'prompts'));+ chmodSync(extensions, 0o555);+ const outcome = await runRemoval({ ops: [piOp(cwd, home)] }, stubDeps());+ expect(outcome.failed).toHaveLength(1);+ expect(outcome.results[0]?.status).toBe('failed');+ const detail = outcome.failed[0]?.detail;+ expect(detail).toMatch(/EACCES|EPERM/);+ if (shared) {+ expect(detail).toContain('has relinquished this grant');+ expect(detail).toContain('will not revoke it on later cleanup runs');+ expect(detail).toContain(trustPath);+ expect(readFileSync(trustPath, 'utf8')).toBe(before);+ } else {+ expect(detail).not.toContain('has relinquished this grant');+ expect(JSON.parse(readFileSync(trustPath, 'utf8'))).toEqual({});+ }+ expect(formatRemovalOutcome(outcome)).toContain(detail?.replaceAll('\n', '\n '));+ const json = removalOutcomeToJson('deinit', outcome);+ expect(json.mode === 'applied' && json.failed[0]?.detail).toBe(detail);+ expect(listPiTrustGrants(home, cwd)).toHaveLength(0);+ expect(existsSync(piOp(cwd, home).configPath)).toBe(true);+ } finally {+ chmodSync(extensions, 0o755);+ rmSync(cwd, { recursive: true, force: true });+ rmSync(home, { recursive: true, force: true });+ }+ },+ );++ test('explains shared trust without claiming ownership of a pre-existing grant', async () => {+ const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pi-removal-')));+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pi-removal-home-')));+ try {+ const trustPath = join(home, '.pi', 'agent', 'trust.json');+ const before = JSON.stringify({ [cwd]: true, other: false });+ write(trustPath, before);+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ mkdirSync(join(cwd, '.pi', 'prompts'));+ const outcome = await runRemoval({ ops: [piOp(cwd, home)] }, stubDeps());+ expect(outcome.results[0]?.status).toBe('removed');+ const detail = outcome.results[0]?.detail;+ expect(detail).toContain('has no ownership record for this grant');+ expect(detail).not.toContain('has relinquished');+ expect(detail).toContain('Removing this grant may stop Pi from loading');+ expect(detail).toContain('parent-folder and global trust settings still apply');+ expect(readFileSync(trustPath, 'utf8')).toBe(before);+ expect(listPiTrustGrants(home, cwd)).toHaveLength(0);+ } finally {+ rmSync(cwd, { recursive: true, force: true });+ rmSync(home, { recursive: true, force: true });+ }+ });++ test.skipIf(process.platform === 'win32')(+ 'quotes resource names, escapes terminal controls, and bounds the retained-resource list',+ async () => {+ const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pi-removal-')));+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pi-removal-home-')));+ try {+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ const name = '\u001b[2K\rforged\nnotice\u0085\u2028\u2029\u202e.ts';+ const commaName = 'a.ts, tailwind.ts';+ const adviceName = 'b.ts. This "grant" is safe to remove.ts';+ const names = [name, commaName, adviceName, 'c.ts', 'd.ts'];+ const trustPath = join(home, '.pi', 'agent', 'trust.json');+ const trustBefore = readFileSync(trustPath, 'utf8');+ for (const filename of names) {+ write(join(cwd, '.pi', 'extensions', filename), '');+ }+ const outcome = await runRemoval({ ops: [piOp(cwd, home)] }, stubDeps());+ const detail = outcome.results[0]?.detail;+ expect(outcome.results[0]?.status).toBe('removed');+ expect(detail).toContain('\\u001b[2K\\rforged\\nnotice\\u0085\\u2028\\u2029\\u202e.ts');+ expect(detail).toContain(JSON.stringify(join(cwd, '.pi', 'extensions', commaName)));+ expect(detail).toContain(JSON.stringify(join(cwd, '.pi', 'extensions', adviceName)));+ expect(detail).not.toMatch(/[\p{Cc}\p{Zl}\p{Zp}]/u);+ expect(detail).not.toContain('\u202e');+ expect(detail).toContain('(+2 more)');+ expect(detail).not.toContain(join(cwd, '.pi', 'extensions', 'c.ts'));+ const rendered = formatRemovalOutcome(outcome);+ expect(rendered).toContain(detail);+ expect(rendered).not.toContain('\u001b[2K');+ expect(rendered).not.toContain(name);+ expect(readFileSync(trustPath, 'utf8')).toBe(trustBefore);+ for (const filename of names)+ expect(readFileSync(join(cwd, '.pi', 'extensions', filename), 'utf8')).toBe('');+ } finally {+ rmSync(cwd, { recursive: true, force: true });+ rmSync(home, { recursive: true, force: true });+ }+ },+ );++ test.each(['unrecorded', 'pending'] as const)(+ 'explains %s trust retention in human and JSON output without changing the grant',+ async (ownership) => {+ const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pi-removal-')));+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pi-removal-home-')));+ try {+ const trustPath = join(home, '.pi', 'agent', 'trust.json');+ const before = `${JSON.stringify({ [cwd]: true, other: false })}\n`;+ write(trustPath, before);+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ if (ownership === 'pending') {+ withPiTrustLockSync(trustPath, trustPath, () => {+ preparePiTrustGrant(home, cwd, trustPath, trustPath, { present: false });+ });+ }+ const outcome = await runRemoval({ ops: [piOp(cwd, home)] }, stubDeps());+ const detail = outcome.results[0]?.detail;+ expect(outcome.results[0]?.status).toBe('removed');+ expect(detail).toContain(+ ownership === 'pending' ? 'record is pending' : 'no OpenKnowledge ownership record',+ );+ if (ownership === 'pending') expect(detail).toContain('does not reconcile this record');+ expect(detail).toContain(trustPath);+ expect(detail).toContain(JSON.stringify(cwd));+ expect(detail).toContain('remove only');+ expect(formatRemovalOutcome(outcome)).toContain(detail);+ const json = removalOutcomeToJson('deinit', outcome);+ expect(json.mode === 'applied' && json.removed[0]?.detail).toBe(detail);+ expect(readFileSync(trustPath, 'utf8')).toBe(before);+ expect(existsSync(piOp(cwd, home).configPath)).toBe(false);+ expect(listPiTrustGrants(home, cwd)).toHaveLength(ownership === 'pending' ? 1 : 0);+ } finally {+ rmSync(cwd, { recursive: true, force: true });+ rmSync(home, { recursive: true, force: true });+ }+ },+ );+test('a trust store OK cannot parse fails the op rather than reporting success', async () => {const cwd = mkdtempSync(join(tmpdir(), 'ok-pi-removal-'));const home = mkdtempSync(join(tmpdir(), 'ok-pi-removal-home-'));@@ -598,6 +791,273 @@ describe('pi trust revocation surfaces through the removal plan', () => {rmSync(home, { recursive: true, force: true });}});++ test.skipIf(process.platform === 'win32')(+ 'retains Pi trust and project state when the bridge symlink has no target',+ async () => {+ const home = mkdtempSync(join(tmpdir(), 'ok-pi-missing-'));+ const cwd = join(home, 'project');+ try {+ write(join(cwd, '.ok', 'config.yml'), '{}');+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ const op = piOp(cwd, home);+ const bridge = readFileSync(op.configPath, 'utf8');+ const trustPath = join(home, '.pi', 'agent', 'trust.json');+ const trust = readFileSync(trustPath, 'utf8');+ rmSync(op.configPath);+ symlinkSync(join(home, 'missing-bridge.ts'), op.configPath);+ const outcome = await runRemoval({ ops: deinitOps(cwd, home) }, stubDeps());+ expect(outcome.failed[0]?.op).toMatchObject({ kind: 'mcp-entry', editorId: 'pi' });+ expect(outcome.failed[0]?.detail).toContain('missing symlink target');+ expect(outcome.failed[0]?.detail).toContain(+ "Pi's separate folder trust grant has not been checked or removed",+ );+ expect(outcome.failed[0]?.detail).toContain(+ `Restore the missing target of the OpenKnowledge bridge symlink at ${op.configPath}`,+ );+ expect(lstatSync(op.configPath).isSymbolicLink()).toBe(true);+ expect(readFileSync(trustPath, 'utf8')).toBe(trust);+ expect(readFileSync(join(cwd, '.ok', 'config.yml'), 'utf8')).toBe('{}');+ writeFileSync(join(home, 'missing-bridge.ts'), bridge);+ const retry = await runRemoval({ ops: deinitOps(cwd, home) }, stubDeps());+ expect(retry.failed).toHaveLength(0);+ expect(probePiBridgeState(cwd, home).trust).toBe('untrusted');+ expect(existsSync(op.configPath)).toBe(false);+ expect(existsSync(join(cwd, '.ok'))).toBe(false);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ },+ );++ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(+ 'retains the bridge and reports why trust cannot be checked until permissions are repaired',+ async () => {+ const cwd = mkdtempSync(join(tmpdir(), 'ok-pi-removal-'));+ const home = mkdtempSync(join(tmpdir(), 'ok-pi-removal-home-'));+ const extensions = join(cwd, '.pi', 'extensions');+ try {+ await ensurePiBridge(cwd, { mode: 'published' }, home);+ const op = piOp(cwd, home);+ const bridge = readFileSync(op.configPath, 'utf8');+ const trustPath = join(home, '.pi', 'agent', 'trust.json');+ const trust = readFileSync(trustPath, 'utf8');+ chmodSync(extensions, 0o111);+ const outcome = await runRemoval({ ops: [op] }, stubDeps());+ expect(outcome.failed).toHaveLength(1);+ expect(outcome.failed[0]?.detail).toContain('kept-unverified');+ expect(outcome.failed[0]?.detail).toContain('Could not inspect Pi project resources');+ expect(outcome.failed[0]?.detail).toContain('check file and parent-directory permissions');+ expect(outcome.failed[0]?.detail).toContain('bridge file was left untouched');+ expect(readFileSync(op.configPath, 'utf8')).toBe(bridge);+ expect(readFileSync(trustPath, 'utf8')).toBe(trust);+ chmodSync(extensions, 0o755);+ const retry = await runRemoval({ ops: [op] }, stubDeps());+ expect(retry.failed).toHaveLength(0);+ expect(existsSync(op.configPath)).toBe(false);+ expect(probePiBridgeState(cwd, home).trust).toBe('untrusted');+ } finally {+ chmodSync(extensions, 0o755);+ rmSync(cwd, { recursive: true, force: true });+ rmSync(home, { recursive: true, force: true });+ }+ },+ );+});++describe.each(['mcp', 'launch', 'shell'] as const)(+ '%s configuration failure details',+ (surface) => {+ function configOp(dir: string): { op: RemovalOp; path: string } {+ const path = join(dir, '.claude', 'launch.json');+ mkdirSync(dirname(path), { recursive: true });+ const base = { group: 'config', label: path };+ const op: RemovalOp =+ surface === 'launch'+ ? { ...base, kind: 'launch-entry', projectRoot: dir }+ : surface === 'shell'+ ? { ...base, kind: 'shell-block', rcFile: path }+ : {+ ...base,+ kind: 'mcp-entry',+ editorId: 'claude',+ scope: 'project',+ cwd: dir,+ home: dir,+ configPath: path,+ };+ return { op, path };+ }++ test('names a non-file path without claiming its contents are malformed', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-config-decline-'));+ try {+ const { op, path } = configOp(dir);+ mkdirSync(path);+ writeFileSync(join(path, 'keep'), 'user data');+ const outcome = await runRemoval({ scope: 'deinit', ops: [op] }, stubDeps());+ expect(outcome.failed[0]?.detail).toContain('not a regular file');+ expect(outcome.failed[0]?.detail).toContain('restore the intended configuration file');+ expect(readFileSync(join(path, 'keep'), 'utf8')).toBe('user data');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(+ 'names read permission failures and leaves the existing configuration intact',+ async () => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-config-decline-'));+ const { op, path } = configOp(dir);+ const raw = '{"user":"settings"}';+ writeFileSync(path, raw);+ chmodSync(path, 0o000);+ try {+ const outcome = await runRemoval({ scope: 'deinit', ops: [op] }, stubDeps());+ expect(outcome.failed[0]?.detail).toContain('permission denied');+ expect(outcome.failed[0]?.detail).toContain(+ 'check file and parent-directory permissions',+ );+ expect(outcome.failed[0]?.detail).toContain('then retry');+ } finally {+ chmodSync(path, 0o600);+ expect(readFileSync(path, 'utf8')).toBe(raw);+ rmSync(dir, { recursive: true, force: true });+ }+ },+ );++ test.skipIf(process.platform === 'win32').each(['dangling', 'cycle'])(+ 'reports a %s symlink while preserving it',+ async (kind) => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-config-decline-'));+ try {+ const { op, path } = configOp(dir);+ symlinkSync(kind === 'cycle' ? path : join(dir, 'missing'), path);+ const outcome = await runRemoval({ scope: 'deinit', ops: [op] }, stubDeps());+ if (kind === 'dangling') {+ expect(outcome.failed).toHaveLength(0);+ expect(outcome.results[0]?.status).toBe('skipped');+ expect(formatRemovalOutcome(outcome)).toContain('left the dangling');+ const json = removalOutcomeToJson('deinit', outcome);+ expect(json.mode === 'applied' && json.skipped[0]?.detail).toContain('no target file');+ } else {+ expect(outcome.failed[0]?.detail).toContain('symlink cycle');+ expect(outcome.failed[0]?.detail).toContain('then retry');+ }+ expect(lstatSync(path).isSymbolicLink()).toBe(true);+ expect(existsSync(join(dir, 'missing'))).toBe(false);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ },+ );+ },+);++describe('configuration repair guidance', () => {+ function mcpOp(dir: string, editorId: 'claude' | 'codex', configPath: string): RemovalOp {+ return {+ kind: 'mcp-entry',+ group: 'config',+ label: configPath,+ editorId,+ scope: 'project',+ cwd: dir,+ home: dir,+ configPath,+ };+ }++ test.each(['oversize', 'duplicate-container'] as const)(+ 'explains how to repair %s without changing the existing file',+ async (reason) => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-config-remedy-'));+ try {+ const configPath = join(dir, 'config.json');+ const raw =+ reason === 'oversize'+ ? `{"mcpServers":{},"history":"${'x'.repeat(11 * 1024 * 1024)}"}`+ : '{"mcpServers":{"one":{"command":"one"}},"mcpServers":{"two":{"command":"two"}}}';+ writeFileSync(configPath, raw);+ const outcome = await runRemoval(+ { scope: 'deinit', ops: [mcpOp(dir, 'claude', configPath)] },+ stubDeps(),+ );+ const remedy =+ reason === 'oversize'+ ? 'back up the file and reduce its size to 10 MiB or less while preserving needed settings'+ : 'combine the duplicate blocks';+ expect(formatRemovalOutcome(outcome)).toContain(remedy);+ const json = removalOutcomeToJson('deinit', outcome);+ expect(json.mode === 'applied' && json.failed[0]?.detail).toContain(remedy);+ expect(readFileSync(configPath, 'utf8')).toBe(raw);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ },+ );++ test('explains the missing TOML writer and accepts manual entry removal on retry', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-config-remedy-'));+ try {+ const configPath = join(dir, 'config.toml');+ const raw = `[mcp_servers.${MCP_SERVER_NAME}]\ncommand = "/bin/sh"\nargs = ${JSON.stringify(OWN_ENTRY.args)}\n`;+ writeFileSync(configPath, raw);+ setTomlConfigEngineForTesting(createTomlConfigEngine(() => null));+ const plan = { scope: 'deinit' as const, ops: [mcpOp(dir, 'codex', configPath)] };+ const outcome = await runRemoval(plan, stubDeps());+ expect(outcome.failed[0]?.detail).toContain('no format-preserving TOML writer');+ expect(outcome.failed[0]?.detail).toContain(+ 'remove the OpenKnowledge entry manually or reinstall',+ );+ expect(readFileSync(configPath, 'utf8')).toBe(raw);+ const repaired = '# keep my other server\n[mcp_servers.other]\ncommand = "node"\n';+ writeFileSync(configPath, repaired);+ const retry = await runRemoval(plan, stubDeps());+ expect(retry.failed).toHaveLength(0);+ expect(retry.results[0]?.status).toBe('not-present');+ expect(readFileSync(configPath, 'utf8')).toBe(repaired);+ } finally {+ setTomlConfigEngineForTesting(null);+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('reports a file that disappears after classification and succeeds on a subsequent retry', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-config-remedy-'));+ try {+ const configPath = join(dir, 'config.toml');+ writeFileSync(+ configPath,+ `[mcp_servers.${MCP_SERVER_NAME}]\ncommand = "/bin/sh"\nargs = ${JSON.stringify(OWN_ENTRY.args)}\n`,+ );+ const parser = createTomlConfigEngine(() => null);+ setTomlConfigEngineForTesting({+ backend: 'native',+ parseToObject(raw) {+ const parsed = parser.parseToObject(raw);+ rmSync(configPath);+ return parsed;+ },+ upsertEntry: (text) => ({ text, existed: false }),+ removeEntry: (text) => ({ text, existed: false }),+ removeEntryKey: (text) => ({ text, existed: false }),+ });+ const plan = { scope: 'deinit' as const, ops: [mcpOp(dir, 'codex', configPath)] };+ const outcome = await runRemoval(plan, stubDeps());+ expect(outcome.failed[0]?.detail).toContain('file disappeared');+ expect(outcome.failed[0]?.detail).toContain('retry to check its current state');+ expect(existsSync(configPath)).toBe(false);+ const retry = await runRemoval(plan, stubDeps());+ expect(retry.failed).toHaveLength(0);+ expect(retry.results[0]?.status).toBe('not-present');+ expect(existsSync(configPath)).toBe(false);+ } finally {+ setTomlConfigEngineForTesting(null);+ rmSync(dir, { recursive: true, force: true });+ }+ });});describe('describeAttachedClients', () => {@@ -623,3 +1083,234 @@ describe('describeAttachedClients', () => {expect(plan.ops.filter((op) => op.kind === 'stop-server')).toHaveLength(1);});});++describe('safe uninstall cleanup', () => {+ test.skipIf(process.platform === 'win32')(+ 'identifies each dangling config when two projects have matching relative paths',+ async () => {+ const home = mkdtempSync(join(tmpdir(), 'ok-dangling-projects-'));+ try {+ const projects = [join(home, 'one'), join(home, 'two')];+ const paths: string[] = [];+ for (const project of projects) {+ for (const relativePath of ['.mcp.json', '.claude/launch.json']) {+ const path = join(project, relativePath);+ mkdirSync(dirname(path), { recursive: true });+ symlinkSync(join(home, 'missing-config.json'), path);+ paths.push(path);+ }+ }+ const outcome = await runRemoval(+ { ops: projects.flatMap((project) => deinitOps(project, home)) },+ stubDeps(),+ );+ expect(outcome.failed).toHaveLength(0);+ const text = formatRemovalOutcome(outcome);+ const json = removalOutcomeToJson('uninstall', outcome);+ for (const path of paths) {+ expect(text).toContain(path);+ expect(+ json.mode === 'applied' && json.skipped.some((item) => item.detail?.includes(path)),+ ).toBe(true);+ expect(lstatSync(path).isSymbolicLink()).toBe(true);+ }+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ },+ );++ test.skipIf(process.platform === 'win32')(+ 'preserves dangling editor and launch links without retaining unrelated project state',+ async () => {+ const home = mkdtempSync(join(tmpdir(), 'ok-dangling-configs-'));+ const project = join(home, 'project');+ try {+ write(join(project, '.ok', 'config.yml'), '{}');+ write(join(project, 'notes.md'), '# My notes\n');+ const paths = [join(project, '.mcp.json'), join(project, '.claude', 'launch.json')];+ for (const path of paths) {+ mkdirSync(dirname(path), { recursive: true });+ symlinkSync(join(home, 'missing-config.json'), path);+ }+ const outcome = await runRemoval({ ops: deinitOps(project, home) }, stubDeps());+ expect(outcome.failed).toHaveLength(0);+ expect(existsSync(join(project, '.ok'))).toBe(false);+ expect(readFileSync(join(project, 'notes.md'), 'utf8')).toBe('# My notes\n');+ for (const path of paths) expect(lstatSync(path).isSymbolicLink()).toBe(true);+ expect(formatRemovalOutcome(outcome)).toContain('no target file');+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ },+ );++ test('explains recovery for a permanently missing Git directory and permits cleanup after manual repair', async () => {+ const home = mkdtempSync(join(tmpdir(), 'ok-orphaned-worktree-'));+ const project = join(home, 'project');+ const pointer = join(project, '.git');+ const rawPointer = 'gitdir: ../missing-main/.git/worktrees/project\n';+ try {+ write(join(project, '.ok', 'config.yml'), '{}');+ write(join(project, 'notes.md'), '# My notes\n');+ write(pointer, rawPointer);+ const outcome = await runRemoval({ ops: deinitOps(project, home) }, stubDeps());+ expect(outcome.failed[0]?.op.kind).toBe('git-exclude');+ expect(formatRemovalOutcome(outcome)).toContain('restoring permissions or access');+ expect(formatRemovalOutcome(outcome)).toContain('including any mounted volume');+ expect(formatRemovalOutcome(outcome)).toContain('git worktree repair');+ const json = removalOutcomeToJson('deinit', outcome);+ expect(json.mode === 'applied' && json.failed[0]?.detail).toContain(+ 'If the repository is permanently gone, back up and remove only the stale .git pointer file',+ );+ expect(readFileSync(pointer, 'utf8')).toBe(rawPointer);+ expect(existsSync(join(project, '.ok'))).toBe(true);+ const backup = join(home, 'git-pointer.backup');+ writeFileSync(backup, readFileSync(pointer));+ rmSync(pointer);+ const retry = await runRemoval({ ops: deinitOps(project, home) }, stubDeps());+ expect(retry.failed).toHaveLength(0);+ expect(existsSync(join(project, '.ok'))).toBe(false);+ expect(readFileSync(join(project, 'notes.md'), 'utf8')).toBe('# My notes\n');+ expect(readFileSync(backup, 'utf8')).toBe(rawPointer);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });++ test('keeps remaining shared editor exclude rules while removing OK-only and absent artifact rules', async () => {+ const home = mkdtempSync(join(tmpdir(), 'ok-removal-excludes-'));+ const project = join(home, 'project');+ try {+ write(join(project, '.git', 'HEAD'), 'ref: refs/heads/main\n');+ mkdirSync(join(project, '.git', 'objects'), { recursive: true });+ mkdirSync(join(project, '.git', 'refs'), { recursive: true });+ write(join(project, '.ok', 'config.yml'), '{}');+ write(+ join(project, '.mcp.json'),+ JSON.stringify({+ mcpServers: { [MCP_SERVER_NAME]: OWN_ENTRY, other: { command: 'keep' } },+ }),+ );+ write(join(project, '.cursor', 'mcp.json'), '{invalid json');+ write(join(project, '.claude', 'launch.json'), '{"configurations":[]}');+ const exclude = join(project, '.git', 'info', 'exclude');+ write(+ exclude,+ '# personal rules\r\n/.mcp.json\r\n.cursor/mcp.json\r\n.claude/launch.json\r\n.codex/config.toml\r\n.ok/\r\n.okignore\r\nprivate.env\r\n',+ );+ await runRemoval({ scope: 'deinit', ops: deinitOps(project, home) }, stubDeps());+ expect(readFileSync(exclude, 'utf-8')).toBe(+ '# personal rules\r\n/.mcp.json\r\n.cursor/mcp.json\r\n.claude/launch.json\r\nprivate.env\r\n',+ );+ expect(JSON.parse(readFileSync(join(project, '.mcp.json'), 'utf-8')).mcpServers).toEqual({+ other: { command: 'keep' },+ });+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });++ test.each(['reported', 'thrown'] as const)(+ 'preserves blocked project and global state after a %s stop failure, but cleans an independent project',+ async (failure) => {+ const home = mkdtempSync(join(tmpdir(), 'ok-removal-stop-'));+ const blocked = join(home, 'one', 'project');+ const independent = join(home, 'two', 'project');+ try {+ seedHome(home);+ for (const project of [blocked, independent]) {+ write(join(project, '.ok', 'config.yml'), '{}');+ write(+ join(project, '.mcp.json'),+ JSON.stringify({ mcpServers: { [MCP_SERVER_NAME]: OWN_ENTRY } }),+ );+ }+ const blockedLock = join(blocked, '.ok', 'local');+ const calls: string[] = [];+ const outcome = await runRemoval(+ buildUninstallPlan(+ baseInput(home, {+ lockDirs: [blockedLock],+ recentDeinitProjectRoots: [blocked, independent],+ }),+ ),+ stubDeps({+ stopServer: async (lockDir) => {+ calls.push(lockDir);+ expect(existsSync(join(home, '.ok', 'auth.yml'))).toBe(true);+ if (lockDir !== blockedLock) return { stopped: 1, failed: [] };+ if (failure === 'thrown') throw new Error('stop unavailable');+ return { stopped: 0, failed: [{ pid: 4242, error: 'EPERM' }] };+ },+ }),+ );+ expect(calls.filter((dir) => dir === blockedLock)).toHaveLength(1);+ expect(existsSync(join(blocked, '.ok', 'config.yml'))).toBe(true);+ expect(readFileSync(join(blocked, '.mcp.json'), 'utf-8')).toContain(MCP_SERVER_NAME);+ expect(existsSync(join(home, '.ok', 'auth.yml'))).toBe(true);+ expect(+ existsSync(join(home, 'Library', 'Application Support', 'OpenKnowledge', 'state.json')),+ ).toBe(true);+ expect(existsSync(join(independent, '.ok'))).toBe(false);+ expect(outcome.failed.length).toBeGreaterThan(0);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ },+ );+});++describe('shell configuration symlinks', () => {+ test.skipIf(process.platform === 'win32')(+ 'preserves a dangling shell symlink without retaining unrelated uninstall state',+ async () => {+ const home = mkdtempSync(join(tmpdir(), 'ok-shell-missing-'));+ try {+ seedHome(home);+ const rcFile = join(home, '.zshrc');+ rmSync(rcFile);+ symlinkSync(join(home, 'missing-dotfiles', 'zshrc'), rcFile);+ const outcome = await runRemoval(buildUninstallPlan(baseInput(home)), stubDeps());+ expect(outcome.failed).toHaveLength(0);+ expect(lstatSync(rcFile).isSymbolicLink()).toBe(true);+ expect(existsSync(join(home, '.ok', 'auth.yml'))).toBe(false);+ expect(formatRemovalOutcome(outcome)).toContain(+ 'left the dangling shell symlink untouched',+ );+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ },+ );++ test.each(['alias ll="ls -la"\n', ''])(+ 'keeps the symlink and destination after stripping the managed block with remaining content %j',+ async (before) => {+ const home = mkdtempSync(join(tmpdir(), 'ok-shell-remove-'));+ try {+ const target = join(home, 'dotfiles', 'zshrc');+ const rcFile = join(home, '.zshrc');+ write(+ target,+ `${before}# >>> open-knowledge cli >>>\nmanaged\n# <<< open-knowledge cli <<<\n`,+ );+ chmodSync(target, 0o600);+ symlinkSync(target, rcFile);+ const outcome = await runRemoval(+ {+ scope: 'uninstall',+ ops: [{ kind: 'shell-block', group: 'Shell PATH', label: 'Remove PATH block', rcFile }],+ },+ stubDeps(),+ );+ expect(outcome.failed).toHaveLength(0);+ expect(lstatSync(rcFile).isSymbolicLink()).toBe(true);+ expect(readFileSync(target, 'utf-8')).toBe(before);+ expect(lstatSync(target).mode & 0o777).toBe(0o600);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ },+ );+});diff --git a/packages/cli/src/commands/removal-plan.ts b/packages/cli/src/commands/removal-plan.tsindex 559d47257..67160bc00 100644--- a/packages/cli/src/commands/removal-plan.ts+++ b/packages/cli/src/commands/removal-plan.ts@@ -1,5 +1,5 @@-import { existsSync, lstatSync, readdirSync, readFileSync, rmSync, unlinkSync } from 'node:fs';-import { basename, join, relative, sep } from 'node:path';+import { lstatSync, readdirSync, readFileSync, rmSync, unlinkSync } from 'node:fs';+import { basename, join, relative, resolve, sep } from 'node:path';import { PROJECT_SKILL_PROJECTION_PATHS } from '@inkeep/open-knowledge-core';import { atomicWriteFileSync } from '@inkeep/open-knowledge-core/server';import { resolveShadowDir } from '@inkeep/open-knowledge-core/shadow-repo-layout';@@ -20,20 +20,23 @@ import {import { userGlobalSkillBundleTargets } from '../integrations/skill-teardown.ts';import { assertProjectRemovalSafe } from '../integrations/write-project-skill.ts';import {- getExcludedOkPaths,getInstalledSkillProjectionPaths,getOkArtifactPaths,removeOkPathsFromGitExclude,} from '../sharing/git-exclude.ts';+import { configFileDeclineDetail, configFileDeclineReason } from '../utils/config-file-error.ts';import { ALL_EDITOR_IDS, EDITOR_TARGETS, type EditorId } from './editors.ts';+import type { McpConfigDeclineReason } from './init.ts';import { existingFileMode } from './jsonc-surgical.ts';import { removeOwnLaunchEntry } from './launch-json-removal.ts';import { removeOwnMcpEntry } from './mcp-config-removal.ts';-import { probeCollabClients, runStop } from './stop.ts';+import { resolveRemovalFilePath } from './removal-file-path.ts';+import { probeCollabClients } from './stop.ts';+import { stopServerForRemoval } from './stop-for-removal.ts';export type RemovalGroup = string;-export type RemovalOp =+export type RemovalOp = (| { kind: 'stop-server'; group: RemovalGroup; label: string; lockDir: string }| { kind: 'keychain-token'; group: RemovalGroup; label: string; host: string }| { kind: 'embeddings-key'; group: RemovalGroup; label: string }@@ -47,7 +50,7 @@ export type RemovalOp =scope: 'user' | 'project';cwd: string;home: string;- configPath?: string;+ configPath: string;}| { kind: 'launch-entry'; group: RemovalGroup; label: string; projectRoot: string }| { kind: 'git-exclude'; group: RemovalGroup; label: string; projectRoot: string }@@ -59,7 +62,9 @@ export type RemovalOp =preserve?: string[];requireOurState?: boolean;containWithin?: string;- };+ requiresSuccessfulCleanup?: boolean;+ }+) & { requiresStoppedServers?: readonly string[] };export interface RemovalPlan {scope: 'uninstall' | 'deinit';@@ -161,7 +166,21 @@ export function deinitOps(});} catch {}- return ops;+ const projectStatePath = join(projectRoot, '.ok');+ ops.sort(+ (left, right) =>+ Number(left.kind === 'remove-path' && left.path === projectStatePath) -+ Number(right.kind === 'remove-path' && right.path === projectStatePath),+ );+ return ops.map((op) =>+ op.kind === 'stop-server'+ ? op+ : {+ ...op,+ requiresStoppedServers: [resolveLockDir(projectRoot)],+ ...(op.kind === 'remove-path' ? { requiresSuccessfulCleanup: true } : {}),+ },+ );}export function buildDeinitPlan(projectRoot: string, home: string): RemovalPlan {@@ -235,15 +254,20 @@ export function buildUninstallPlan(input: UninstallPlanInput): RemovalPlan {});}- ops.push(...applicationDataOps(home, platform, input.env));-for (const projectRoot of recentDeinitProjectRoots) {ops.push(...deinitOps(projectRoot, home, `Project: ${basename(projectRoot)}`));}+ ops.push(+ ...applicationDataOps(home, platform, input.env).map((op) =>+ op.kind === 'remove-path' ? { ...op, requiresSuccessfulCleanup: true } : op,+ ),+ );+ops.push({kind: 'remove-path',group: 'Global directory',+ requiresSuccessfulCleanup: true,label: purgeContent? 'Remove ~/.ok (including user-authored skills)': 'Remove ~/.ok (keeping ~/.ok/skills)',@@ -266,7 +290,7 @@ function pathRevertOps(marker: PathInstallMarker | null, home: string): RemovalOconst ops: RemovalOp[] = [];const rcCandidates = new Set([...standardRcFiles(home), ...(marker?.rcFiles ?? [])]);for (const rcFile of rcCandidates) {- if (!existsSync(rcFile)) continue;+ if (resolveRemovalFilePath(rcFile).kind === 'not-present') continue;ops.push({kind: 'shell-block',group: 'Shell PATH',@@ -326,6 +350,7 @@ export function applicationDataOps(}export interface RunRemovalDeps {+ env?: NodeJS.ProcessEnv;clearToken?: (host: string,) => Promise<{ touched: Array<'keychain' | 'file'>; keychainError?: string }>;@@ -342,27 +367,60 @@ export async function runRemoval(): Promise<RemovalOutcome> {const clearToken = deps.clearToken ?? clearTokenFromAllBackends;const clearEmbeddingsKey = deps.clearEmbeddingsKey ?? clearAllEmbeddingsKeys;- const stopServer =- deps.stopServer ??- (async (lockDir: string) => {- const outcome = await runStop({ lockDir, force: true, log: () => {}, error: () => {} });- return {- stopped: outcome.stopped.length,- failed: outcome.failed.map((f) => ({ pid: f.target.pid, error: f.error })),- };- });+ const stopServer = deps.stopServer ?? stopServerForRemoval;- const results: RemovalOpResult[] = [];- for (const op of plan.ops) {+ const resolvedDeps = { clearToken, clearEmbeddingsKey, stopServer, env: deps.env ?? {} };+ const execute = async (op: RemovalOp): Promise<RemovalOpResult> => {try {- results.push(await executeOp(op, { clearToken, clearEmbeddingsKey, stopServer }));+ return await executeOp(op, resolvedDeps);} catch (err) {+ return { op, status: 'failed', detail: err instanceof Error ? err.message : String(err) };+ }+ };+ const stops = new Map<string, RemovalOpResult>();+ for (const op of plan.ops) {+ if (op.kind !== 'stop-server') continue;+ const key = resolve(op.lockDir);+ if (!stops.has(key)) stops.set(key, await execute(op));+ }++ const results: RemovalOpResult[] = [];+ for (const op of plan.ops) {+ if (op.kind === 'stop-server') {+ const result = stops.get(resolve(op.lockDir));+ if (result) results.push({ ...result, op });+ continue;+ }+ const required = op.requiresStoppedServers ?? [...stops.keys()];+ const blocked = required.filter((lockDir) => {+ const stop = stops.get(resolve(lockDir));+ return !stop || stop.status === 'failed';+ });+ if (blocked.length > 0) {results.push({op,status: 'failed',- detail: err instanceof Error ? err.message : String(err),+ detail: `left untouched because server shutdown was not verified: ${blocked.join(', ')}. Stop the server and retry cleanup.`,});+ continue;}+ if (op.kind === 'remove-path' && op.requiresSuccessfulCleanup) {+ const previousFailure = results.some((result) => {+ if (result.status !== 'failed') return false;+ if (!op.requiresStoppedServers) return true;+ return result.op.requiresStoppedServers?.some((lockDir) => required.includes(lockDir));+ });+ if (previousFailure) {+ results.push({+ op,+ status: 'failed',+ detail:+ 'left untouched so cleanup can be retried after the earlier failures are resolved',+ });+ continue;+ }+ }+ results.push(await execute(op));}return {@@ -402,7 +460,7 @@ async function executeOp(op: RemovalOp, deps: ResolvedDeps): Promise<RemovalOpRereturn {op,status: 'failed',- detail: `could not stop the server (${detail}); a process may still be using files that were removed`,+ detail: `could not stop the server (${detail}); dependent files were left untouched; stop the server and retry cleanup`,};}return { op, status: stopped > 0 ? 'removed' : 'not-present' };@@ -423,15 +481,38 @@ async function executeOp(op: RemovalOp, deps: ResolvedDeps): Promise<RemovalOpRereturn { op, status: touched.length > 0 ? 'removed' : 'not-present' };}case 'shell-block': {- if (!existsSync(op.rcFile)) return { op, status: 'not-present' };- const before = readFileSync(op.rcFile, 'utf-8');+ const resolved = resolveRemovalFilePath(op.rcFile);+ if (resolved.kind === 'not-present') return { op, status: 'not-present' };+ if (resolved.kind === 'declined' && resolved.reason === 'missing-symlink-target') {+ return {+ op,+ status: 'skipped',+ detail: `left the dangling shell symlink untouched; no target file contains a PATH block to remove: ${op.rcFile}`,+ };+ }+ if (resolved.kind === 'declined')+ return {+ op,+ status: 'failed',+ detail: `${configurationDeclineDetail(resolved.reason)}: ${op.rcFile}`,+ };+ let before: string;+ try {+ before = readFileSync(resolved.path, 'utf-8');+ } catch (error) {+ return {+ op,+ status: 'failed',+ detail: `${configurationDeclineDetail(configFileDeclineReason(error))}: ${op.rcFile}`,+ };+ }const { text, changed, emptyAfter } = stripManagedPathBlock(before);if (!changed) return { op, status: 'not-present' };- if (emptyAfter) {+ if (emptyAfter && !resolved.symlink) {rmSync(op.rcFile, { force: true });return { op, status: 'removed', detail: 'file removed (was OK-owned)' };}- atomicWriteFileSync(op.rcFile, text, { mode: existingFileMode(op.rcFile) });+ atomicWriteFileSync(resolved.path, text, { mode: existingFileMode(resolved.path) });return { op, status: 'removed' };}case 'extra-symlink': {@@ -445,42 +526,43 @@ async function executeOp(op: RemovalOp, deps: ResolvedDeps): Promise<RemovalOpReop.cwd,op.home,op.configPath,+ deps.env,);switch (outcome.kind) {case 'removed':- switch (outcome.trust) {- case undefined:- case 'removed':- case 'not-present':- return { op, status: 'removed' };- case 'kept-shared':- return {- op,- status: 'removed',- detail: "kept Pi's folder trust — another extension there still needs it",- };- case 'kept-unverified':- return {- op,- status: 'removed',- detail:- "kept Pi's folder trust — couldn't read the extensions folder to see what else needs it",- };- default:- return {- op,- status: 'failed',- detail: `removed the bridge file, but couldn't revoke Pi's folder trust (${outcome.trust})${- outcome.trustError !== undefined ? `: ${outcome.trustError}` : ''- }`,- };+ if (outcome.trustDetail) {+ return {+ op,+ status: 'removed',+ detail: outcome.trustDetail,+ };}+ return { op, status: 'removed' };case 'not-present':return { op, status: 'not-present' };case 'left-foreign':return { op, status: 'skipped', detail: 'left a non-OK server in place' };case 'declined':- return { op, status: 'skipped', detail: `declined (${outcome.reason})` };+ if (outcome.reason === 'missing-symlink-target') {+ const configPath = op.configPath;+ if (op.editorId === 'pi') {+ return {+ op,+ status: 'failed',+ detail: `Pi bridge configuration left untouched (missing symlink target); Pi's separate folder trust grant has not been checked or removed. Restore the missing target of the OpenKnowledge bridge symlink at ${configPath}, or repoint that symlink to the intended bridge file, then retry cleanup`,+ };+ }+ return {+ op,+ status: 'skipped',+ detail: `left the dangling configuration symlink untouched; no target file contains an OpenKnowledge entry to remove: ${configPath}`,+ };+ }+ return {+ op,+ status: 'failed',+ detail: configurationDeclineDetail(outcome.reason),+ };default: {const _exhaustive: never = outcome;throw new Error(@@ -497,7 +579,18 @@ async function executeOp(op: RemovalOp, deps: ResolvedDeps): Promise<RemovalOpRecase 'not-present':return { op, status: 'not-present' };case 'declined':- return { op, status: 'skipped', detail: 'declined (unparseable)' };+ if (outcome.reason === 'missing-symlink-target') {+ return {+ op,+ status: 'skipped',+ detail: `left the dangling configuration symlink untouched; no target file contains an OpenKnowledge entry to remove: ${join(op.projectRoot, '.claude', 'launch.json')}`,+ };+ }+ return {+ op,+ status: 'failed',+ detail: configurationDeclineDetail(outcome.reason),+ };default: {const _exhaustive: never = outcome;throw new Error(@@ -507,16 +600,28 @@ async function executeOp(op: RemovalOp, deps: ResolvedDeps): Promise<RemovalOpRe}}case 'git-exclude': {- const excluded = getExcludedOkPaths(op.projectRoot);- if (excluded.length === 0) return { op, status: 'not-present' };const result = removeOkPathsFromGitExclude(op.projectRoot,- getOkArtifactPaths(op.projectRoot),+ removableGitExcludePaths(op.projectRoot),);if (result.kind === 'no-exclude') {- return result.reason === 'inaccessible'- ? { op, status: 'failed', detail: 'could not write .git/info/exclude (inaccessible)' }- : { op, status: 'not-present', detail: result.reason };+ switch (result.reason) {+ case 'inaccessible':+ return {+ op,+ status: 'failed',+ detail: 'could not write .git/info/exclude (inaccessible)',+ };+ case 'malformed-pointer':+ return {+ op,+ status: 'failed',+ detail: `could not locate .git/info/exclude; repair the .git pointer at ${join(op.projectRoot, '.git')} by restoring permissions or access to its repository, including any mounted volume. If its contents are malformed, restore a valid gitdir: <path> line pointing to the existing Git directory. For a linked worktree, run git worktree repair from the main repository with this worktree's path. If the repository is permanently gone, back up and remove only the stale .git pointer file, then retry cleanup`,+ };+ case 'no-git':+ case 'no-info-dir':+ return { op, status: 'not-present' };+ }}return { op, status: result.removed.length > 0 ? 'removed' : 'not-present' };}@@ -525,6 +630,30 @@ async function executeOp(op: RemovalOp, deps: ResolvedDeps): Promise<RemovalOpRe}}+function configurationDeclineDetail(reason: McpConfigDeclineReason): string {+ switch (reason) {+ case 'permission-denied':+ case 'missing-symlink-target':+ case 'unresolved-symlink':+ case 'not-a-file':+ case 'unreadable':+ case 'disappeared':+ return `configuration left untouched: ${configFileDeclineDetail(reason)}`;+ case 'oversize':+ return 'configuration left untouched (file is too large to edit safely); back up the file and reduce its size to 10 MiB or less while preserving needed settings, then retry cleanup';+ case 'duplicate-container':+ return 'configuration left untouched (duplicate server configuration blocks); combine the duplicate blocks while preserving their settings, then retry cleanup';+ case 'no-native-writer':+ return 'configuration left untouched (this install has no format-preserving TOML writer); remove the OpenKnowledge entry manually or reinstall OpenKnowledge, then retry cleanup';+ case 'unparseable':+ return 'configuration left untouched (unparseable); repair it and retry cleanup';+ default: {+ const exhaustive: never = reason;+ throw new Error(`unhandled configuration decline reason: ${exhaustive}`);+ }+ }+}+function executeRemovePath(op: Extract<RemovalOp, { kind: 'remove-path' }>): RemovalOpResult {if (op.requireOurState && !stateDirIsOurs(op.path)) {return { op, status: 'skipped', detail: 'not verified as OpenKnowledge — left untouched' };@@ -559,3 +688,22 @@ function executeRemovePath(op: Extract<RemovalOp, { kind: 'remove-path' }>): RemrmSync(op.path, { recursive: true, force: true });return { op, status: 'removed' };}++function removableGitExcludePaths(projectRoot: string): readonly string[] {+ const sharedPaths = new Set<string>([join(projectRoot, '.claude', 'launch.json')]);+ for (const id of ALL_EDITOR_IDS) {+ const path = EDITOR_TARGETS[id].projectConfigPath?.(projectRoot);+ if (path) sharedPaths.add(path);+ }+ return getOkArtifactPaths(projectRoot).filter((path) => {+ const absolute = join(projectRoot, path);+ if (!sharedPaths.has(absolute)) return true;+ try {+ lstatSync(absolute);+ return false;+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return true;+ throw err;+ }+ });+}diff --git a/packages/cli/src/commands/removal-process-start.test.ts b/packages/cli/src/commands/removal-process-start.test.tsnew file mode 100644index 000000000..88376ff92--- /dev/null+++ b/packages/cli/src/commands/removal-process-start.test.ts@@ -0,0 +1,93 @@+import { describe, expect, test, vi } from 'vitest';+import { readRemovalProcessStart } from './removal-process-start.ts';++describe('readRemovalProcessStart', () => {+ test.each(['darwin', 'linux'] as const)(+ 'reads %s process start with second precision in UTC regardless of inherited locale',+ (platform) => {+ const run = vi.fn(() => 'Tue Sep 8 20:21:34 2026\n');+ expect(+ readRemovalProcessStart(123, {+ platform,+ env: { LC_ALL: 'fr_FR.UTF-8', TZ: 'America/New_York' },+ run,+ }),+ ).toBe(Date.parse('2026-09-08T20:21:34.000Z'));+ expect(run).toHaveBeenCalledWith(+ '/bin/ps',+ ['-p', '123', '-o', 'lstart='],+ expect.objectContaining({+ timeout: 5000,+ env: expect.objectContaining({ LC_ALL: 'C', TZ: 'UTC0' }),+ }),+ );+ },+ );++ test('reads a Windows process creation time without losing milliseconds', () => {+ const run = vi.fn(() => '\uFEFF2026-09-08T20:21:34.4567890Z\r\n');+ expect(+ readRemovalProcessStart(123, {+ platform: 'win32',+ env: { SYSTEMROOT: 'D:\\Windows' },+ run,+ }),+ ).toBe(Date.parse('2026-09-08T20:21:34.456Z'));+ expect(run).toHaveBeenCalledWith(+ 'D:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe',+ expect.arrayContaining([+ '-NoProfile',+ '-NonInteractive',+ expect.stringContaining('(Get-Process -Id 123).StartTime.ToUniversalTime()'),+ ]),+ expect.objectContaining({ timeout: 5000, windowsHide: true }),+ );+ });++ test.each([undefined, '', ' ', 'relative-windows'])(+ 'uses an absolute PowerShell fallback for an unusable SystemRoot %j',+ (systemRoot) => {+ const run = vi.fn(() => '2026-09-08T20:21:34.000Z');+ readRemovalProcessStart(123, {+ platform: 'win32',+ env: { SystemRoot: systemRoot },+ run,+ });+ expect(run).toHaveBeenCalledWith(+ 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe',+ expect.any(Array),+ expect.any(Object),+ );+ },+ );++ test.each(['', 'permission denied', 'Tue Sep 8 20:21:34 2026\nTue Sep 8 20:21:34 2026'])(+ 'refuses unusable process start output %j',+ (output) => {+ expect(readRemovalProcessStart(123, { platform: 'darwin', run: () => output })).toBeNull();+ },+ );++ test('refuses an unavailable, unsuccessful, or timed out probe', () => {+ expect(+ readRemovalProcessStart(123, {+ run: () => {+ throw new Error('process query failed');+ },+ }),+ ).toBeNull();+ });++ test.each([0, -1, Number.NaN, 12.5])('never queries an invalid PID %j', (pid) => {+ const run = vi.fn(() => '2026-09-08T20:21:34.000Z');+ expect(readRemovalProcessStart(pid, { run })).toBeNull();+ expect(run).not.toHaveBeenCalled();+ });++ test('reads the current process start on the current operating system', () => {+ const startedAt = readRemovalProcessStart(process.pid);+ expect(startedAt).not.toBeNull();+ expect(startedAt).toBeLessThanOrEqual(Date.now());+ expect(startedAt).toBeGreaterThan(Date.now() - process.uptime() * 1000 - 10_000);+ });+});diff --git a/packages/cli/src/commands/removal-process-start.ts b/packages/cli/src/commands/removal-process-start.tsnew file mode 100644index 000000000..dbbaac882--- /dev/null+++ b/packages/cli/src/commands/removal-process-start.ts@@ -0,0 +1,61 @@+import { type ExecFileSyncOptionsWithStringEncoding, execFileSync } from 'node:child_process';+import { win32 } from 'node:path';++interface ProcessStartOptions {+ platform?: NodeJS.Platform;+ env?: NodeJS.ProcessEnv;+ run?: (command: string, args: string[], options: ExecFileSyncOptionsWithStringEncoding) => string;+}++export function readRemovalProcessStart(+ pid: number,+ options: ProcessStartOptions = {},+): number | null {+ if (!Number.isSafeInteger(pid) || pid <= 0) return null;+ const platform = options.platform ?? process.platform;+ const env = options.env ?? process.env;+ const run = options.run ?? execFileSync;+ try {+ let output: string;+ const commandOptions: ExecFileSyncOptionsWithStringEncoding = {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'pipe'],+ timeout: 5000,+ windowsHide: true,+ env: { ...env, LC_ALL: 'C', TZ: 'UTC0' },+ };+ if (platform === 'win32') {+ const systemRoot = Object.entries(env)+ .find(([key]) => key.toLowerCase() === 'systemroot')?.[1]+ ?.trim();+ const powershell = win32.join(+ systemRoot && win32.isAbsolute(systemRoot) ? systemRoot : 'C:\\Windows',+ 'System32',+ 'WindowsPowerShell',+ 'v1.0',+ 'powershell.exe',+ );+ output = run(+ powershell,+ [+ '-NoLogo',+ '-NoProfile',+ '-NonInteractive',+ '-Command',+ `$ErrorActionPreference = 'Stop'; (Get-Process -Id ${pid}).StartTime.ToUniversalTime().ToString('O')`,+ ],+ commandOptions,+ ).trim();+ } else if (platform === 'darwin' || platform === 'linux') {+ const raw = run('/bin/ps', ['-p', String(pid), '-o', 'lstart='], commandOptions).trim();+ if (!/^\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4}$/.test(raw)) return null;+ output = `${raw} UTC`;+ } else {+ return null;+ }+ const startedAt = Date.parse(output);+ return Number.isFinite(startedAt) ? startedAt : null;+ } catch {+ return null;+ }+}diff --git a/packages/cli/src/commands/removal-render.test.ts b/packages/cli/src/commands/removal-render.test.tsnew file mode 100644index 000000000..882eb8deb--- /dev/null+++ b/packages/cli/src/commands/removal-render.test.ts@@ -0,0 +1,114 @@+import {+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ renameSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { stripVTControlCharacters } from 'node:util';+import { describe, expect, test } from 'vitest';+import { escapeDisplayPath } from '../utils/escape-display-path.ts';+import { commitPiTrustGrant, preparePiTrustGrant } from './pi-trust-grants.ts';+import { deinitOps, type RemovalOp, type RemovalOutcome, runRemoval } from './removal-plan.ts';+import { formatRemovalOutcome, removalOutcomeToJson } from './removal-render.ts';++describe('formatRemovalOutcome', () => {+ test.each([+ ['removed', '·', ''],+ ['skipped', '·', 'Left in place: '],+ ['failed', '✗', ''],+ ] as const)('keeps multiline %s details under their own items', (status, bullet, prefix) => {+ const results = ['Alpha', 'Beta'].map((label) => ({+ op: { kind: 'remove-path' as const, group: label, label, path: `/${label}` },+ status,+ detail: `${label} first line\n${label} second line`,+ }));+ const outcome: RemovalOutcome = {+ results,+ removed: status === 'removed' ? results : [],+ failed: status === 'failed' ? results : [],+ };++ expect(stripVTControlCharacters(formatRemovalOutcome(outcome))).toContain(+ ` ${bullet} ${prefix}Alpha — Alpha first line\n Alpha second line\n ${bullet} ${prefix}Beta — Beta first line\n Beta second line`,+ );+ const json = removalOutcomeToJson('uninstall', outcome);+ expect(json.mode === 'applied' && json[status].map((item) => item.detail)).toEqual([+ 'Alpha first line\nAlpha second line',+ 'Beta first line\nBeta second line',+ ]);+ expect(results.map((item) => item.detail)).toEqual([+ 'Alpha first line\nAlpha second line',+ 'Beta first line\nBeta second line',+ ]);+ });++ test('groups real retained Pi records and recovery guidance beneath each project failure', async () => {+ const base = realpathSync(mkdtempSync(join(tmpdir(), 'ok-removal-render-')));+ try {+ const home = join(base, 'home');+ mkdirSync(home);+ const ops: RemovalOp[] = [];+ const snapshots: Array<{ path: string; bytes: string }> = [];+ const records = ['project-alpha', 'project-beta'].map((name) => {+ const cwd = join(base, name);+ mkdirSync(cwd);+ const store = join(base, `${name}-trust.json`);+ writeFileSync(store, `${JSON.stringify({ [cwd]: true, unrelated: false })}\n`);+ const receipt = commitPiTrustGrant(+ home,+ preparePiTrustGrant(home, cwd, store, store, { present: true, value: false }),+ );+ for (const path of [store, receipt.path]) {+ snapshots.push({ path, bytes: readFileSync(path, 'utf8') });+ }+ renameSync(cwd, `${cwd}-moved`);+ ops.push(+ ...deinitOps(cwd, home, name).filter(+ (op) => op.kind === 'stop-server' || (op.kind === 'mcp-entry' && op.editorId === 'pi'),+ ),+ );+ return receipt;+ });++ const outcome = await runRemoval({ scope: 'uninstall', ops });+ expect(outcome.failed).toHaveLength(2);+ const rendered = stripVTControlCharacters(formatRemovalOutcome(outcome));+ const blocks = rendered.split('\n ✗ ').slice(1);+ expect(blocks).toHaveLength(2);+ for (const [index, receipt] of records.entries()) {+ const block = blocks[index];+ expect(block).toContain('Pi trust cleanup failed (kept-unverified):\n ');+ expect(block).toContain('current trust decisions were not checked:');+ expect(block).toContain(+ `\n key ${escapeDisplayPath(JSON.stringify(receipt.record.cwd))}; configured store ${escapeDisplayPath(JSON.stringify(receipt.record.configuredTrustPath))}; recorded destination ${escapeDisplayPath(JSON.stringify(receipt.record.canonicalTrustPath))}; ownership record ${escapeDisplayPath(JSON.stringify(receipt.path))} (committed)\n `,+ );+ expect(block).toContain('restore the recorded previous value');+ expect(block).toContain('remove that key only when no previous entry was recorded');+ expect(block).toContain(+ 'parent-folder and global trust settings still apply.\n Trust cleanup remains incomplete so cleanup can be retried.',+ );+ expect(+ block+ ?.split('\n')+ .slice(1)+ .every((line) => line.startsWith(' ')),+ ).toBe(true);+ for (const other of records) {+ if (other !== receipt) expect(block).not.toContain(other.record.cwd);+ }+ }+ const json = removalOutcomeToJson('uninstall', outcome);+ expect(json.mode === 'applied' && json.failed.map((item) => item.detail)).toEqual(+ outcome.failed.map((item) => item.detail),+ );+ for (const { path, bytes } of snapshots) expect(readFileSync(path, 'utf8')).toBe(bytes);+ } finally {+ rmSync(base, { recursive: true, force: true });+ }+ });+});diff --git a/packages/cli/src/commands/removal-render.ts b/packages/cli/src/commands/removal-render.tsindex 4dbeff3e0..0e2889efc 100644--- a/packages/cli/src/commands/removal-render.ts+++ b/packages/cli/src/commands/removal-render.ts@@ -24,6 +24,10 @@ export function formatRemovalPlan(plan: RemovalPlan): string {return lines.join('\n');}+function indentDetail(detail: string): string {+ return detail.replaceAll('\n', '\n ');+}+export function formatRemovalOutcome(outcome: RemovalOutcome): string {const removed = outcome.removed.length;const failed = outcome.failed.length;@@ -42,19 +46,21 @@ export function formatRemovalOutcome(outcome: RemovalOutcome): string {for (const r of outcome.removed) {if (r.detail === undefined) continue;- lines.push(` ${warning('·')} ${r.op.label} — ${dim(r.detail)}`);+ lines.push(` ${warning('·')} ${r.op.label} — ${dim(indentDetail(r.detail))}`);}for (const s of skipped) {lines.push(- ` ${warning('·')} Left in place: ${s.op.label}${s.detail ? ` — ${dim(s.detail)}` : ''}`,+ ` ${warning('·')} Left in place: ${s.op.label}${s.detail ? ` — ${dim(indentDetail(s.detail))}` : ''}`,);}if (failed > 0) {lines.push('');lines.push(errorColor('Could not remove:'));for (const f of outcome.failed) {- lines.push(` ${errorColor('✗')} ${f.op.label}${f.detail ? ` — ${f.detail}` : ''}`);+ lines.push(+ ` ${errorColor('✗')} ${f.op.label}${f.detail ? ` — ${indentDetail(f.detail)}` : ''}`,+ );}}return lines.join('\n');diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.tsindex 73aa71c4c..774b93107 100644--- a/packages/cli/src/commands/start.ts+++ b/packages/cli/src/commands/start.ts@@ -482,9 +482,10 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<BooprobeHarnessManagedMcpEntry: (editorId, agentCwd) =>probeOwnManagedEditorMcpEntry(editorId, agentCwd),probePiAcpBridge: (agentCwd) => probePiBridgeState(agentCwd),- ensurePiAcpBridge: (agentCwd) => ensurePiBridge(agentCwd),+ ensurePiAcpBridge: (agentCwd, approvedCanonicalCwd) =>+ ensurePiBridge(agentCwd, undefined, undefined, undefined, approvedCanonicalCwd),agentIntegrations: (() => {- const registryCtx = { cwd: ephemeralProjectDir ?? cwd, home: homedir() };+ const registryCtx = { cwd: ephemeralProjectDir ?? cwd, home: homedir(), env: process.env };return {probe: createCliProbeResolver(registryCtx),execute: createCliStepExecutor(registryCtx),diff --git a/packages/cli/src/commands/stop-for-removal.test.ts b/packages/cli/src/commands/stop-for-removal.test.tsnew file mode 100644index 000000000..d07842d1f--- /dev/null+++ b/packages/cli/src/commands/stop-for-removal.test.ts@@ -0,0 +1,274 @@+import { type ChildProcess, execFileSync, type SpawnSyncReturns, spawn } from 'node:child_process';+import { once } from 'node:events';+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { hostname, tmpdir } from 'node:os';+import { join } from 'node:path';+import { isProcessAlive, lockFilePath } from '@inkeep/open-knowledge-server';+import pino from 'pino';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import * as cliLogger from '../cli-logger.ts';+import { runRemoval } from './removal-plan.ts';+import { readRemovalProcessStart } from './removal-process-start.ts';+import { stopServerForRemoval } from './stop-for-removal.ts';++describe('stopServerForRemoval', () => {+ let dir: string;+ const children: ChildProcess[] = [];+ let warnings: Array<Record<string, unknown>>;++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'ok-removal-stop-'));+ warnings = [];+ vi.spyOn(cliLogger, 'getCliLogger').mockReturnValue(+ pino({ level: 'warn' }, { write: (record) => warnings.push(JSON.parse(record)) }),+ );+ });++ afterEach(async () => {+ for (const child of children.splice(0)) {+ if (child.exitCode !== null || child.signalCode !== null) continue;+ const exited = once(child, 'exit');+ child.kill('SIGKILL');+ await exited;+ }+ rmSync(dir, { recursive: true, force: true });+ vi.restoreAllMocks();+ });++ function expectRefusalLogged(status: string, detail: string): void {+ expect(warnings).toEqual([+ expect.objectContaining({+ level: 40,+ lockDir: dir,+ lockPath: lockFilePath(dir, 'server'),+ status,+ msg: expect.stringContaining(detail),+ }),+ ]);+ }++ async function startServer(source: string): Promise<number> {+ const child = spawn(process.execPath, ['-e', source], {+ stdio: ['ignore', 'ignore', 'ignore', 'ipc'],+ });+ children.push(child);+ await once(child, 'message');+ const pid = child.pid;+ if (pid === undefined) throw new Error('Server fixture did not start');+ writeFileSync(+ lockFilePath(dir, 'server'),+ JSON.stringify({ pid, hostname: hostname(), port: 0, startedAt: new Date().toISOString() }),+ );+ return pid;+ }++ test('reports no server when no lock exists', async () => {+ expect(await stopServerForRemoval(dir)).toEqual({ stopped: 0, failed: [] });+ });++ test('rejects an unreadable lock instead of claiming shutdown was verified', async () => {+ writeFileSync(lockFilePath(dir, 'server'), '{bad metadata');+ await expect(stopServerForRemoval(dir)).rejects.toThrow(+ `Once you have confirmed they have exited, remove the stale lock file at ${lockFilePath(dir, 'server')} and retry cleanup`,+ );+ expectRefusalLogged('corrupt', 'unreadable server lock');+ });++ test('does not signal an unrelated process whose PID appears in an older lock', async () => {+ const pid = await startServer(`+ process.send('ready');+ setInterval(() => {}, 1000);+ `);+ writeFileSync(+ lockFilePath(dir, 'server'),+ JSON.stringify({ pid, hostname: hostname(), port: 0, startedAt: '2000-01-01T00:00:00.000Z' }),+ );+ const probe: {+ elapsedMs?: number;+ code?: string | null;+ status?: number | null;+ signal?: NodeJS.Signals | null;+ output?: string;+ } = {};+ const removal = stopServerForRemoval(dir, {+ readProcessStart: (processId) =>+ readRemovalProcessStart(processId, {+ run: (command, args, options) => {+ const startedAt = performance.now();+ try {+ const output = execFileSync(command, args, options);+ probe.output = output.trim().slice(0, 80);+ return output;+ } catch (error) {+ const failure = error as NodeJS.ErrnoException &+ Pick<SpawnSyncReturns<string>, 'status' | 'signal'>;+ probe.code = failure.code ?? null;+ probe.status = failure.status ?? null;+ probe.signal = failure.signal ?? null;+ throw error;+ } finally {+ probe.elapsedMs = Math.round(performance.now() - startedAt);+ }+ },+ }),+ });+ await expect(removal, `OS process-start query: ${JSON.stringify(probe)}`).rejects.toThrow(+ 'started after the server lock',+ );+ expect(isProcessAlive(pid)).toBe(true);+ expectRefusalLogged('alive', 'started after the server lock');+ });++ test('does not signal a process when its lock has no acquisition timestamp', async () => {+ const pid = await startServer(`+ process.send('ready');+ setInterval(() => {}, 1000);+ `);+ writeFileSync(+ lockFilePath(dir, 'server'),+ JSON.stringify({ pid, hostname: hostname(), port: 0 }),+ );+ await expect(stopServerForRemoval(dir)).rejects.toThrow('valid start time');+ expect(isProcessAlive(pid)).toBe(true);+ expectRefusalLogged('alive', 'valid start time');+ });++ test('does not signal when the process start probe is unavailable and explains recovery', async () => {+ const pid = await startServer(`+ process.send('ready');+ setInterval(() => {}, 1000);+ `);+ await expect(stopServerForRemoval(dir, { readProcessStart: () => null })).rejects.toThrow(+ 'Confirm the OpenKnowledge server has exited before retrying cleanup',+ );+ expect(isProcessAlive(pid)).toBe(true);+ expectRefusalLogged('alive', 'Cannot verify the identity');+ if (process.platform === 'linux') {+ expect(warnings[0]?.msg).toContain('ps supporting -p and -o lstart=');+ }+ });++ test('requires a liveness recheck to accept an exited process after an unavailable identity probe', async () => {+ const pid = await startServer(`+ process.send('ready');+ setInterval(() => {}, 1000);+ `);+ const isAlive = vi.fn().mockReturnValueOnce(true).mockReturnValueOnce(false);+ expect(await stopServerForRemoval(dir, { readProcessStart: () => null, isAlive })).toEqual({+ stopped: 0,+ failed: [],+ });+ expect(isAlive).toHaveBeenCalledTimes(2);+ expect(isProcessAlive(pid)).toBe(true);+ });++ test('allows a process older than its lock even when start times have only second precision', async () => {+ const pid = await startServer(`+ process.send('ready');+ setInterval(() => {}, 1000);+ `);+ const startedAt = readRemovalProcessStart(pid);+ if (startedAt === null) throw new Error('Could not read fixture process start time');+ const startSecond = Math.floor(startedAt / 1000) * 1000;+ writeFileSync(+ lockFilePath(dir, 'server'),+ JSON.stringify({+ pid,+ hostname: hostname(),+ port: 0,+ startedAt: new Date(startSecond + 999).toISOString(),+ }),+ );+ expect(await stopServerForRemoval(dir, { readProcessStart: () => startSecond })).toEqual({+ stopped: 1,+ failed: [],+ });+ expect(isProcessAlive(pid)).toBe(false);+ });++ test('does not signal a local process named by a foreign-host lock', async () => {+ const pid = await startServer(`+ process.send('ready');+ setInterval(() => {}, 1000);+ `);+ writeFileSync(+ lockFilePath(dir, 'server'),+ JSON.stringify({ pid, hostname: `${hostname()}-other-machine`, port: 0 }),+ );+ await expect(stopServerForRemoval(dir)).rejects.toThrow(+ 'Confirm that no OpenKnowledge server is using this directory on the owning machine or any other machine sharing it',+ );+ expect(isProcessAlive(pid)).toBe(true);+ expectRefusalLogged('foreign-host', 'another machine');+ expect(warnings[0]?.msg).toContain(lockFilePath(dir, 'server'));+ });++ test.skipIf(process.platform === 'win32')('waits for the server to flush and exit', async () => {+ const flushed = join(dir, 'flushed');+ const pid = await startServer(`+ const fs = require('node:fs');+ process.on('SIGTERM', () => setTimeout(() => {+ fs.writeFileSync(${JSON.stringify(flushed)}, 'saved');+ process.exit(0);+ }, 120));+ process.send('ready');+ setInterval(() => {}, 1000);+ `);+ const outcome = await stopServerForRemoval(dir, { timeoutMs: 2000, pollIntervalMs: 10 });+ expect(outcome).toEqual({ stopped: 1, failed: [] });+ expect(readFileSync(flushed, 'utf8')).toBe('saved');+ expect(isProcessAlive(pid)).toBe(false);+ });++ test.skipIf(process.platform === 'win32')(+ 'fails without escalating when the server ignores SIGTERM',+ async () => {+ const pid = await startServer(`+ process.on('SIGTERM', () => {});+ process.send('ready');+ setInterval(() => {}, 1000);+ `);+ const statePath = join(dir, 'state');+ writeFileSync(statePath, 'must survive');+ const outcome = await runRemoval(+ {+ scope: 'deinit',+ ops: [+ { kind: 'stop-server', group: 'project', label: 'Stop server', lockDir: dir },+ { kind: 'remove-path', group: 'project', label: 'Remove state', path: statePath },+ ],+ },+ {+ stopServer: (lockDir) =>+ stopServerForRemoval(lockDir, { timeoutMs: 100, pollIntervalMs: 10 }),+ },+ );+ expect(outcome.failed).toEqual([+ expect.objectContaining({+ op: expect.objectContaining({ kind: 'stop-server' }),+ detail: expect.stringContaining('still running'),+ }),+ expect.objectContaining({ op: expect.objectContaining({ kind: 'remove-path' }) }),+ ]);+ expect(isProcessAlive(pid)).toBe(true);+ expect(existsSync(statePath)).toBe(true);+ },+ );++ test.skipIf(process.platform === 'win32')(+ 'accepts a stale lock after the process is gone',+ async () => {+ const pid = await startServer(`+ process.send('ready');+ setInterval(() => {}, 1000);+ `);+ const child = children.at(-1);+ if (!child) throw new Error('Server fixture missing');+ const exited = once(child, 'exit');+ child.kill('SIGTERM');+ await exited;+ expect(isProcessAlive(pid)).toBe(false);+ expect(await stopServerForRemoval(dir)).toEqual({ stopped: 0, failed: [] });+ },+ );+});diff --git a/packages/cli/src/commands/stop-for-removal.ts b/packages/cli/src/commands/stop-for-removal.tsnew file mode 100644index 000000000..d151a7ead--- /dev/null+++ b/packages/cli/src/commands/stop-for-removal.ts@@ -0,0 +1,92 @@+import { setTimeout } from 'node:timers/promises';+import { isProcessAlive } from '@inkeep/open-knowledge-server';+import { getCliLogger } from '../cli-logger.ts';+import { inspectLock } from './lock-state.ts';+import { readRemovalProcessStart } from './removal-process-start.ts';+import { runStop } from './stop.ts';++interface StopForRemovalOptions {+ timeoutMs?: number;+ pollIntervalMs?: number;+ readProcessStart?: (pid: number) => number | null;+ isAlive?: (pid: number) => boolean;+}++export async function stopServerForRemoval(+ lockDir: string,+ options: StopForRemovalOptions = {},+): Promise<{ stopped: number; failed: Array<{ pid: number; error: string }> }> {+ const isAlive = options.isAlive ?? isProcessAlive;+ const state = inspectLock(lockDir, 'server', { isAlive });+ const lockRecovery =+ 'Quit OpenKnowledge and stop any OpenKnowledge server processes. ' ++ `Once you have confirmed they have exited, remove the stale lock file at ${state.lockPath} and retry cleanup.`;+ const refusal = (message: string): Error => {+ getCliLogger()?.warn({ lockDir, lockPath: state.lockPath, status: state.status }, message);+ return new Error(message);+ };+ if (state.status === 'corrupt') {+ throw refusal(+ `Cannot verify shutdown from the unreadable server lock at ${state.lockPath}. ${lockRecovery}`,+ );+ }+ if (state.status === 'foreign-host') {+ throw refusal(+ `Cannot verify shutdown: the server lock at ${state.lockPath} belongs to another machine. ` ++ 'Stop OpenKnowledge on the owning machine. Confirm that no OpenKnowledge server is using this directory on the owning machine or any other machine sharing it. ' ++ `Only then remove the stale lock file at ${state.lockPath} and retry cleanup.`,+ );+ }+ if (state.status === 'alive') {+ const lockStartedAt =+ typeof state.lock.startedAt === 'string' ? Date.parse(state.lock.startedAt) : Number.NaN;+ if (!Number.isFinite(lockStartedAt)) {+ throw refusal(`The server lock has no valid start time. ${lockRecovery}`);+ }+ const processStartedAt = (options.readProcessStart ?? readRemovalProcessStart)(state.lock.pid);+ if (processStartedAt === null) {+ if (!isAlive(state.lock.pid)) return { stopped: 0, failed: [] };+ const probeRecovery =+ process.platform === 'linux'+ ? 'Linux requires ps supporting -p and -o lstart= (such as procps). Install a compatible ps and retry, or stop the server manually. '+ : 'Stop the server manually. ';+ throw refusal(+ `Cannot verify the identity of process ${state.lock.pid}; the OS process-start query failed or is unavailable, so it was not signalled. ` ++ probeRecovery ++ 'Confirm the OpenKnowledge server has exited before retrying cleanup after a manual stop.',+ );+ }+ if (processStartedAt > lockStartedAt) {+ throw refusal(+ `Process ${state.lock.pid} started after the server lock was acquired; it was not signalled. ${lockRecovery}`,+ );+ }+ }+ const outcome = await runStop({+ lockDir,+ inspect: () => state,+ force: true,+ log: () => {},+ error: () => {},+ });+ const failed = outcome.failed.map((failure) => ({+ pid: failure.target.pid,+ error: failure.error,+ }));+ const pending = new Set(outcome.stopped.map((target) => target.pid));+ const timeoutMs = options.timeoutMs ?? 10_000;+ const deadline = performance.now() + timeoutMs;+ while (pending.size > 0) {+ for (const pid of pending) {+ if (!isAlive(pid)) pending.delete(pid);+ }+ if (pending.size === 0) break;+ const remaining = deadline - performance.now();+ if (remaining <= 0) break;+ await setTimeout(Math.min(options.pollIntervalMs ?? 50, remaining));+ }+ for (const pid of pending) {+ failed.push({ pid, error: `still running ${timeoutMs}ms after SIGTERM` });+ }+ return { stopped: outcome.stopped.length - pending.size, failed };+}diff --git a/packages/cli/src/commands/uninstall.test.ts b/packages/cli/src/commands/uninstall.test.tsindex 4f3b026dc..f5de6af1f 100644--- a/packages/cli/src/commands/uninstall.test.ts+++ b/packages/cli/src/commands/uninstall.test.ts@@ -1,8 +1,9 @@-import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { Readable } from 'node:stream';import { describe, expect, test } from 'vitest';+import { ensurePiBridge } from './pi-acp-bridge.ts';import { detectInstallMethods, resolveRecentDeinitProjects, runUninstall } from './uninstall.ts';function write(path: string, content: string): void {@@ -193,6 +194,49 @@ describe('resolveRecentDeinitProjects', () => {});describe('runUninstall', () => {+ test('uses its explicit environment to clean Pi trust for selected projects', async () => {+ const home = mkdtempSync(join(tmpdir(), 'ok-uninstall-pi-'));+ const cwd = join(home, 'project');+ const agentDir = join(home, 'custom-pi');+ const trustPath = join(agentDir, 'trust.json');+ const defaultTrustPath = join(home, '.pi', 'agent', 'trust.json');+ const unrelated = join(home, 'other-project');+ const env = { PI_CODING_AGENT_DIR: agentDir };+ const defaultTrust = `${JSON.stringify({ [cwd]: true })}\n`;+ try {+ write(join(cwd, '.ok', 'config.yml'), 'content:\n dir: .\n');+ write(defaultTrustPath, defaultTrust);+ write(trustPath, JSON.stringify({ [unrelated]: true }));+ await ensurePiBridge(cwd, { mode: 'published' }, home, env);++ const result = await runUninstall({+ home,+ cwd,+ env,+ platform: 'darwin',+ yes: true,+ deps: {+ discoverLockDirs: async () => [],+ resolveRecentProjects: async () => [cwd],+ detectInstallMethods: () => [],+ probeClients: async () => null,+ runRemovalDeps: {+ clearToken: async () => ({ touched: [] }),+ clearEmbeddingsKey: async () => ({ touched: [] }),+ stopServer: async () => ({ stopped: 0, failed: [] }),+ },+ },+ });++ expect(result.status).toBe('done');+ expect(existsSync(join(cwd, '.pi', 'extensions', 'open-knowledge.ts'))).toBe(false);+ expect(JSON.parse(readFileSync(trustPath, 'utf8'))).toEqual({ [unrelated]: true });+ expect(readFileSync(defaultTrustPath, 'utf8')).toBe(defaultTrust);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });+test('dry-run renders the plan + binary instructions, removing nothing', async () => {const home = mkdtempSync(join(tmpdir(), 'ok-uninst-cmd-'));try {@@ -421,3 +465,45 @@ describe('runUninstall attached-client disclosure', () => {}});});++test.each([false, true])(+ 'unreadable editor configuration reports incomplete uninstall (json=%s)',+ async (json) => {+ const home = mkdtempSync(join(tmpdir(), 'ok-uninstall-incomplete-'));+ try {+ write(join(home, '.cursor', 'mcp.json'), '{broken json');+ const result = await runUninstall({+ home,+ cwd: home,+ platform: 'darwin',+ yes: true,+ json,+ deps: {+ discoverLockDirs: async () => [],+ resolveRecentProjects: async () => [],+ detectInstallMethods: () => [],+ runRemovalDeps: {+ clearToken: async () => ({ touched: [] }),+ clearEmbeddingsKey: async () => ({ touched: [] }),+ },+ },+ });+ expect(result.status).toBe('failed');+ expect(result.exitCode).toBe(1);+ expect(result.runFeedbackAfterReport).toBeUndefined();+ if (json)+ expect(+ JSON.parse(result.message).failed.some((item: { label: string }) =>+ item.label.includes('Cursor'),+ ),+ ).toBe(true);+ else+ expect(result.message).not.toContain(+ "OpenKnowledge's files have been removed from this machine.",+ );+ expect(existsSync(join(home, '.cursor', 'mcp.json'))).toBe(true);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ },+);diff --git a/packages/cli/src/commands/uninstall.ts b/packages/cli/src/commands/uninstall.tsindex d6288b989..223a875b1 100644--- a/packages/cli/src/commands/uninstall.ts+++ b/packages/cli/src/commands/uninstall.ts@@ -372,7 +372,10 @@ export async function runUninstall(opts: UninstallOptions = {}): Promise<Uninsta}}- const outcome = await runRemoval(plan, opts.deps?.runRemovalDeps);+ const outcome = await runRemoval(plan, {+ env: opts.env ?? (opts.home === undefined ? process.env : {}),+ ...opts.deps?.runRemovalDeps,+ });const runFeedbackAfterReport =outcome.failed.length === 0diff --git a/packages/cli/src/integrations/registry-apply.test.ts b/packages/cli/src/integrations/registry-apply.test.tsindex 14f0aff93..51df87698 100644--- a/packages/cli/src/integrations/registry-apply.test.ts+++ b/packages/cli/src/integrations/registry-apply.test.ts@@ -1,8 +1,10 @@import {+ chmodSync,existsSync,mkdirSync,mkdtempSync,readFileSync,+ realpathSync,rmSync,symlinkSync,writeFileSync,@@ -17,8 +19,10 @@ import {planIntents,type SatisfierId,} from '@inkeep/open-knowledge-core';+import { loggerFactory, logsCurrentPath } from '@inkeep/open-knowledge-server';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { EDITOR_TARGETS } from '../commands/editors.ts';+import { ensurePiBridge, probePiBridgeState } from '../commands/pi-acp-bridge.ts';import { type CliWriteContext, createCliStepExecutor } from './registry-apply.ts';import { collectCliHostSnapshot } from './registry-probes.ts';@@ -26,7 +30,7 @@ let root: string;let ctx: CliWriteContext;beforeEach(() => {- root = mkdtempSync(join(tmpdir(), 'ok-registry-apply-'));+ root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-registry-apply-')));mkdirSync(join(root, 'project'), { recursive: true });mkdirSync(join(root, 'home'), { recursive: true });ctx = { cwd: join(root, 'project'), home: join(root, 'home') };@@ -60,6 +64,112 @@ async function stateOf(satisfierId: string) {const projectMcpPath = () => join(ctx.cwd, '.mcp.json');+it.each(['kept-shared', 'kept-unowned'] as const)(+ 'logs why a successful Pi removal left %s trust',+ async (trust) => {+ loggerFactory.configure({+ pinoConfig: { options: { level: 'warn' }, fileSink: { projectDir: root } },+ });+ const home = join(root, 'home');+ const trustPath = join(home, '.pi', 'agent', 'trust.json');+ const prompts = join(ctx.cwd, '.pi', 'prompts');+ try {+ if (trust === 'kept-unowned') {+ mkdirSync(join(home, '.pi', 'agent'), { recursive: true });+ writeFileSync(trustPath, JSON.stringify({ [ctx.cwd]: true }));+ }+ await ensurePiBridge(ctx.cwd, { mode: 'published' }, home);+ if (trust === 'kept-shared') mkdirSync(prompts);+ const before = readFileSync(trustPath, 'utf8');+ const report = await run([{ satisfierId: 'pi/mcp/project/managed-file', desired: 'absent' }]);+ expect(actionFor(report, 'pi/mcp/project/managed-file')?.action).toBe('removed');+ await loggerFactory.flushAllFileSinks();+ const entries = readFileSync(logsCurrentPath(root), 'utf8')+ .trim()+ .split('\n')+ .map((line) => JSON.parse(line));+ expect(entries).toContainEqual(+ expect.objectContaining({+ msg: 'MCP config removal retained Pi folder trust',+ editor: 'pi',+ trust,+ trustDetail: expect.stringContaining(+ trust === 'kept-shared' ? prompts : 'no OpenKnowledge ownership record',+ ),+ }),+ );+ expect(readFileSync(trustPath, 'utf8')).toBe(before);+ } finally {+ loggerFactory.reset();+ }+ },+);++it('removes Pi trust from the configured agent directory without changing other grants', async () => {+ const home = join(root, 'home');+ const agentDir = join(root, 'custom-pi');+ const trustPath = join(agentDir, 'trust.json');+ const defaultTrustPath = join(home, '.pi', 'agent', 'trust.json');+ const unrelated = join(root, 'other-project');+ const defaultTrust = `${JSON.stringify({ [ctx.cwd]: true })}\n`;+ ctx = { ...ctx, env: { PI_CODING_AGENT_DIR: agentDir } };+ mkdirSync(agentDir, { recursive: true });+ mkdirSync(join(home, '.pi', 'agent'), { recursive: true });+ writeFileSync(defaultTrustPath, defaultTrust);+ writeFileSync(trustPath, JSON.stringify({ [unrelated]: true }));+ await ensurePiBridge(ctx.cwd, { mode: 'published' }, ctx.home, ctx.env);++ const report = await run([{ satisfierId: 'pi/mcp/project/managed-file', desired: 'absent' }]);++ expect(actionFor(report, 'pi/mcp/project/managed-file')?.action).toBe('removed');+ expect(existsSync(join(ctx.cwd, '.pi', 'extensions', 'open-knowledge.ts'))).toBe(false);+ expect(JSON.parse(readFileSync(trustPath, 'utf8'))).toEqual({ [unrelated]: true });+ expect(readFileSync(defaultTrustPath, 'utf8')).toBe(defaultTrust);+});++it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(+ 'logs the reason for a failed Pi removal and preserves its bridge and trust for retry',+ async () => {+ loggerFactory.configure({+ pinoConfig: {+ options: { level: 'warn' },+ fileSink: { projectDir: root },+ },+ });+ const extensions = join(ctx.cwd, '.pi', 'extensions');+ const bridgePath = join(extensions, 'open-knowledge.ts');+ const trustPath = join(root, 'home', '.pi', 'agent', 'trust.json');+ try {+ await ensurePiBridge(ctx.cwd, { mode: 'published' }, ctx.home);+ const bridge = readFileSync(bridgePath, 'utf8');+ const trust = readFileSync(trustPath, 'utf8');+ chmodSync(extensions, 0o111);+ const report = await run([{ satisfierId: 'pi/mcp/project/managed-file', desired: 'absent' }]);+ expect(actionFor(report, 'pi/mcp/project/managed-file')).toMatchObject({+ action: 'failed',+ errorId: 'write-failed',+ });+ await loggerFactory.flushAllFileSinks();+ const logs = readFileSync(logsCurrentPath(root), 'utf8');+ expect(logs).toContain('MCP config removal failed');+ expect(logs).toContain('kept-unverified');+ expect(logs).toContain('Could not inspect Pi project resources');+ expect(logs).toContain('bridge file was left untouched');+ expect(logs).toContain(bridgePath);+ expect(readFileSync(bridgePath, 'utf8')).toBe(bridge);+ expect(readFileSync(trustPath, 'utf8')).toBe(trust);+ chmodSync(extensions, 0o755);+ const retry = await run([{ satisfierId: 'pi/mcp/project/managed-file', desired: 'absent' }]);+ expect(actionFor(retry, 'pi/mcp/project/managed-file')?.action).toBe('removed');+ expect(existsSync(bridgePath)).toBe(false);+ expect(probePiBridgeState(ctx.cwd, ctx.home).trust).toBe('untrusted');+ } finally {+ chmodSync(extensions, 0o755);+ loggerFactory.reset();+ }+ },+);+describe('a project MCP artifact', () => {it('is written by the same primitive a single toggle uses, and reads back satisfied', async () => {const report = await run([diff --git a/packages/cli/src/integrations/registry-apply.ts b/packages/cli/src/integrations/registry-apply.tsindex e2fc46d45..4a13201ee 100644--- a/packages/cli/src/integrations/registry-apply.ts+++ b/packages/cli/src/integrations/registry-apply.ts@@ -24,6 +24,7 @@ const INSTALL_OPTIONS: McpInstallOptions = {export interface CliWriteContext {readonly cwd: string;readonly home?: string;+ readonly env?: NodeJS.ProcessEnv;}function fail(): ExecutedOutcome {@@ -55,6 +56,41 @@ function removalOutcome(kind: 'removed' | 'not-present' | 'left-foreign' | 'decl}}+function removeMcp(+ editor: EditorId,+ cwd: string,+ home: string | undefined,+ configPath?: string,+ env?: NodeJS.ProcessEnv,+): ExecutedOutcome {+ const target = EDITOR_TARGETS[editor];+ try {+ const outcome = removeOwnMcpEntry(target, cwd, home, configPath, env);+ if (outcome.kind === 'removed' && outcome.trustDetail) {+ getLogger('agent-integrations-apply').warn(+ {+ editor,+ path: configPath ?? target.configPath(cwd, home),+ trust: outcome.trust,+ trustDetail: outcome.trustDetail,+ },+ 'MCP config removal retained Pi folder trust',+ );+ }+ return removalOutcome(outcome.kind);+ } catch (error) {+ getLogger('agent-integrations-apply').warn(+ {+ editor,+ path: configPath ?? target.configPath(cwd, home),+ reason: error instanceof Error ? error.message : String(error),+ },+ 'MCP config removal failed',+ );+ return fail();+ }+}+async function applyUserMcp(editor: EditorId,ctx: CliWriteContext,@@ -63,7 +99,7 @@ async function applyUserMcp(if (EDITOR_TARGETS[editor].scope !== 'global') return missing();if (desired === 'absent') {- return removalOutcome(removeOwnMcpEntry(EDITOR_TARGETS[editor], '', ctx.home).kind);+ return removeMcp(editor, '', ctx.home, undefined, ctx.env);}const results = await writeUserMcpConfigs({@@ -98,9 +134,7 @@ function applyProjectMcp(const projectPath = join(ctx.cwd, relative);if (desired === 'absent') {- return removalOutcome(- removeOwnMcpEntry(EDITOR_TARGETS[editor], ctx.cwd, undefined, projectPath).kind,- );+ return removeMcp(editor, ctx.cwd, ctx.home, projectPath, ctx.env);}const result = writeEditorMcpConfig(diff --git a/packages/cli/src/utils/config-file-error.test.ts b/packages/cli/src/utils/config-file-error.test.tsnew file mode 100644index 000000000..687e8262a--- /dev/null+++ b/packages/cli/src/utils/config-file-error.test.ts@@ -0,0 +1,31 @@+import { describe, expect, test } from 'vitest';+import { configFileDeclineDetail, configFileDeclineReason } from './config-file-error.ts';++describe('configFileDeclineReason', () => {+ test.each([+ ['EACCES', 'permission-denied'],+ ['EPERM', 'permission-denied'],+ ['ELOOP', 'unresolved-symlink'],+ ['EISDIR', 'not-a-file'],+ ['ENOTDIR', 'not-a-file'],+ ['EIO', 'unreadable'],+ ['ENOENT', 'disappeared'],+ ])('preserves the actionable category for %s', (code, reason) => {+ expect(configFileDeclineReason(Object.assign(new Error(code), { code }))).toBe(reason);+ });++ test.each([null, undefined, new Error('read failed')])(+ 'reports an unknown read failure without inventing a syntax problem',+ (error) => {+ expect(configFileDeclineReason(error)).toBe('unreadable');+ },+ );++ test('an I/O failure suggests restoring access without inventing a permissions diagnosis', () => {+ const error = Object.assign(new Error('device unavailable'), { code: 'EIO' });+ const detail = configFileDeclineDetail(configFileDeclineReason(error));+ expect(detail).toContain('could not be read');+ expect(detail).toContain('check that the path is accessible');+ expect(detail).not.toContain('permission denied');+ });+});diff --git a/packages/cli/src/utils/config-file-error.ts b/packages/cli/src/utils/config-file-error.tsnew file mode 100644index 000000000..fe8a8de6d--- /dev/null+++ b/packages/cli/src/utils/config-file-error.ts@@ -0,0 +1,48 @@+export type ConfigFileDeclineReason =+ | 'permission-denied'+ | 'missing-symlink-target'+ | 'unresolved-symlink'+ | 'not-a-file'+ | 'disappeared'+ | 'unreadable';++export function configFileDeclineReason(+ error: unknown,+): Exclude<ConfigFileDeclineReason, 'missing-symlink-target'> {+ const code = (error as NodeJS.ErrnoException)?.code;+ switch (code) {+ case 'EACCES':+ case 'EPERM':+ return 'permission-denied';+ case 'ELOOP':+ return 'unresolved-symlink';+ case 'EISDIR':+ case 'ENOTDIR':+ return 'not-a-file';+ case 'ENOENT':+ return 'disappeared';+ default:+ return 'unreadable';+ }+}++export function configFileDeclineDetail(reason: ConfigFileDeclineReason): string {+ switch (reason) {+ case 'permission-denied':+ return 'permission denied; check file and parent-directory permissions, then retry';+ case 'missing-symlink-target':+ return 'the symlink target is missing; restore the target or correct the symlink, then retry';+ case 'unresolved-symlink':+ return 'the path or symlink could not be resolved; check path permissions and repair any symlink cycle, then retry';+ case 'not-a-file':+ return 'the path is not a regular file; restore the intended configuration file, then retry';+ case 'disappeared':+ return 'the file disappeared; retry to check its current state';+ case 'unreadable':+ return 'the file could not be read; check that the path is accessible, then retry';+ default: {+ const exhaustive: never = reason;+ throw new Error(`unhandled configuration file decline reason: ${exhaustive}`);+ }+ }+}diff --git a/packages/cli/src/utils/escape-display-path.test.ts b/packages/cli/src/utils/escape-display-path.test.tsnew file mode 100644index 000000000..e50e839c3--- /dev/null+++ b/packages/cli/src/utils/escape-display-path.test.ts@@ -0,0 +1,34 @@+import { describe, expect, test } from 'vitest';+import { escapeDisplayPath } from './escape-display-path.ts';++describe('escapeDisplayPath', () => {+ test.each([+ ['\u001b', '\\u001b'],+ ['\r', '\\u000d'],+ ['\n', '\\u000a'],+ ['\u0085', '\\u0085'],+ ['\u2028', '\\u2028'],+ ['\u2029', '\\u2029'],+ ['\u061c', '\\u061c'],+ ['\u200b', '\\u200b'],+ ['\u200e', '\\u200e'],+ ['\u200f', '\\u200f'],+ ['\u202a', '\\u202a'],+ ['\u202b', '\\u202b'],+ ['\u202c', '\\u202c'],+ ['\u202d', '\\u202d'],+ ['\u202e', '\\u202e'],+ ['\u2066', '\\u2066'],+ ['\u2067', '\\u2067'],+ ['\u2068', '\\u2068'],+ ['\u2069', '\\u2069'],+ ['\ufeff', '\\ufeff'],+ ])('makes display control %j visible in a path', (control, visible) => {+ expect(escapeDisplayPath(`project/${control}notes`)).toBe(`project/${visible}notes`);+ });++ test('preserves script joiners, emoji and already-visible escapes', () => {+ const path = 'notes/क्\u200dष/می\u200cروم/👩\u200d💻/\\u202e.md';+ expect(escapeDisplayPath(path)).toBe(path);+ });+});diff --git a/packages/cli/src/utils/escape-display-path.ts b/packages/cli/src/utils/escape-display-path.tsnew file mode 100644index 000000000..485c916e5--- /dev/null+++ b/packages/cli/src/utils/escape-display-path.ts@@ -0,0 +1,6 @@+export function escapeDisplayPath(path: string): string {+ return path.replace(+ /[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}\u200b\ufeff]/gu,+ (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`,+ );+}diff --git a/packages/cli/tsdown.config.ts b/packages/cli/tsdown.config.tsindex dbd85d0ab..44a2242ac 100644--- a/packages/cli/tsdown.config.ts+++ b/packages/cli/tsdown.config.ts@@ -51,6 +51,7 @@ const alwaysBundlePureJsDeps = [// can't cross into the sibling app.asar/ for node_modules. Inlining// here removes the runtime resolution entirely./^pino(\/|$)/,+ /^proper-lockfile(\/|$)/,/^shell-quote(\/|$)/,/^simple-git(\/|$)/,// sirv is inlined TRANSITIVELY via @inkeep/open-knowledge-server (boot.ts'sdiff --git a/packages/core/src/acp/thread-protocol.ts b/packages/core/src/acp/thread-protocol.tsindex 65b23809a..99d4b74f3 100644--- a/packages/core/src/acp/thread-protocol.ts+++ b/packages/core/src/acp/thread-protocol.ts@@ -29,6 +29,7 @@ export type PiBridgeWriteAction =| 'refreshed'| 'refused-foreign'| 'refused-unreadable'+ | 'refused-project-path'| 'failed';export type PiTrustWriteAction =@@ -44,6 +45,7 @@ export type PiBridgeThreadState =| 'ready'| 'foreign-file'| 'unreadable-file'+ | 'project-path-unavailable'| 'bridge-failed'| 'trust-failed';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 1ef62e19b..3936c608c 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -1909,7 +1909,6 @@ export type {UninstallDispatchRequest,UninstallDispatchResult,UninstallIntent,- UninstallNoticeChecklistItem,UninstallNoticeScreen,UninstallProjectRow,UninstallScreenSpec,diff --git a/packages/core/src/uninstall-bridge.ts b/packages/core/src/uninstall-bridge.tsindex 4a2ed5cf9..5e14a2148 100644--- a/packages/core/src/uninstall-bridge.ts+++ b/packages/core/src/uninstall-bridge.ts@@ -5,19 +5,10 @@ export interface UninstallProjectRow {readonly running: boolean;}-export interface UninstallNoticeChecklistItem {- readonly label: string;- readonly detail?: string;- readonly done: boolean;-}-export interface UninstallNoticeScreen {readonly title: string;- readonly subtitle?: string;readonly paragraphs: readonly string[];- readonly checklist?: readonly UninstallNoticeChecklistItem[];readonly footnote?: string;- readonly logRevealLabel?: string;readonly log?: string;readonly confirmLabel: string;readonly cancelLabel?: string;@@ -41,8 +32,7 @@ export type UninstallIntent =}| { readonly kind: 'survey-skip' }| { readonly kind: 'notice-confirm' }- | { readonly kind: 'notice-cancel' }- | { readonly kind: 'notice-reveal-log' };+ | { readonly kind: 'notice-cancel' };export type UninstallDispatchRequest = { readonly kind: 'ready' } | UninstallIntent;diff --git a/packages/desktop/src/main/agent-registry-apply.test.ts b/packages/desktop/src/main/agent-registry-apply.test.tsindex 24f2c2f63..0ea20f5b6 100644--- a/packages/desktop/src/main/agent-registry-apply.test.ts+++ b/packages/desktop/src/main/agent-registry-apply.test.ts@@ -1,6 +1,22 @@+import {+ chmodSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';import type { HostSnapshot, SurfaceState } from '@inkeep/open-knowledge-core';import type { IpcMainInvokeEvent } from 'electron';-import { describe, expect, test } from 'vitest';+import { describe, expect, test, vi } from 'vitest';+import { EDITOR_TARGETS } from '../../../cli/src/commands/editors.ts';+import { removeOwnMcpEntry } from '../../../cli/src/commands/mcp-config-removal.ts';+import { ensurePiBridge } from '../../../cli/src/commands/pi-acp-bridge.ts';+import { collectCliHostSnapshot } from '../../../cli/src/integrations/registry-probes.ts';import type {AgentIntegrationsApplyRequest,AgentIntegrationsApplyResult,@@ -22,6 +38,7 @@ const CLAUDE_USER_SKILL = 'claude/skill/user/skill-bundle-copy';const CODEX_PROJECT_SKILL = 'codex/skill/project/skill-bundle-copy';const CODEX_PROJECT_MCP = 'codex/mcp/project/config-entry';const COPILOT_PROJECT_MCP = 'copilot/mcp/project/config-entry';+const PI_PROJECT_MCP = 'pi/mcp/project/managed-file';interface Calls {userWrites: McpWiringEditorId[];@@ -41,6 +58,8 @@ interface SurfaceOverrides {projectWriteAction?: 'written' | 'overwritten' | 'declined' | 'failed';projectRemoveKind?: 'removed' | 'not-present' | 'left-foreign' | 'declined';projectWriteThrows?: boolean;+ userRemoveError?: unknown;+ projectRemoveError?: unknown;skillWriteAction?: 'written' | 'overwritten' | 'skipped-unsupported' | 'failed';userSkillWriteAction?: 'written' | 'overwritten' | 'skipped-unsupported' | 'failed';userSkillPresentAnywhere?: boolean;@@ -79,6 +98,7 @@ function makeSurfaces(},removeUserMcpEntry: (editorId) => {calls.userRemovals.push(editorId);+ if (overrides.userRemoveError !== undefined) throw overrides.userRemoveError;return { kind: overrides.userRemoveKind ?? ('removed' as const) };},writeUserSkill: (editorId) => {@@ -107,6 +127,7 @@ function makeSurfaces(},removeProjectMcpEntry: (id, _projectDir, projectPath) => {calls.projectRemovals.push({ id, path: projectPath });+ if (overrides.projectRemoveError !== undefined) throw overrides.projectRemoveError;return { kind: overrides.projectRemoveKind ?? 'removed' } as ReturnType<AgentRegistryWriterSurfaces['project']['removeProjectMcpEntry']>;@@ -161,6 +182,22 @@ function actionFor(return report.actions.find((entry) => entry.satisfierId === satisfierId);}+function piFixture() {+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-desktop-pi-removal-')));+ const projectDir = join(root, 'project');+ const home = join(root, 'home');+ mkdirSync(projectDir);+ mkdirSync(home);+ const bridgePath = join(projectDir, '.pi', 'extensions', 'open-knowledge.ts');+ const trustPath = join(home, '.pi', 'agent', 'trust.json');+ const surfaces = makeSurfaces();+ surfaces.project.projectConfigPath = (id, cwd) =>+ EDITOR_TARGETS[id].projectConfigPath?.(cwd) ?? null;+ surfaces.project.removeProjectMcpEntry = (id, cwd, path) =>+ removeOwnMcpEntry(EDITOR_TARGETS[id], cwd, home, path, {});+ return { root, projectDir, home, bridgePath, trustPath, surfaces };+}+describe('applyIntents on the desktop host', () => {test('a project MCP intent runs the project MCP writer', async () => {const surfaces = makeSurfaces();@@ -247,6 +284,137 @@ describe('applyIntents on the desktop host', () => {expect(actionFor(report, CLAUDE_USER_MCP)?.action).toBe('written');});+ test.each(['user', 'project'] as const)(+ 'logs a thrown %s MCP removal reason and continues the batch',+ async (scope) => {+ const reason = 'The config directory is read-only';+ const surfaces = makeSurfaces(+ scope === 'user' ? { userRemoveError: new Error(reason) } : { projectRemoveError: reason },+ );+ const satisfier = scope === 'user' ? CLAUDE_USER_MCP : CLAUDE_PROJECT_MCP;+ const warn = vi.fn();++ const { report } = await applyIntents(+ { intents: [drop(satisfier), want(CODEX_PROJECT_MCP)] },+ {+ surfaces,+ projectDir: PROJECT,+ logger: { warn },+ snapshot: async () =>+ snapshotWith({ [satisfier]: 'satisfied', [CODEX_PROJECT_MCP]: 'absent' }),+ },+ );++ expect(actionFor(report, satisfier)).toMatchObject({+ action: 'failed',+ errorId: 'write-failed',+ });+ expect(actionFor(report, CODEX_PROJECT_MCP)?.action).toBe('written');+ expect(warn).toHaveBeenCalledWith('MCP config removal failed', {+ channel: 'ok:integrations:dispatch',+ editor: 'claude',+ scope,+ ...(scope === 'project' ? { path: `${PROJECT}/claude.config` } : {}),+ reason,+ });+ },+ );++ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(+ 'logs an inaccessible recorded Pi trust store when the bridge disappears after probing',+ async () => {+ const { root, projectDir, home, bridgePath, trustPath, surfaces } = piFixture();+ try {+ expect((await ensurePiBridge(projectDir, { mode: 'published' }, home, {})).ok).toBe(true);+ const before = readFileSync(trustPath, 'utf8');+ chmodSync(trustPath, 0o000);+ const remove = surfaces.project.removeProjectMcpEntry;+ surfaces.project.removeProjectMcpEntry = (...args) => {+ rmSync(bridgePath);+ return remove(...args);+ };+ const warn = vi.fn();++ const { report, snapshot } = await applyIntents(+ { intents: [drop(PI_PROJECT_MCP)] },+ {+ surfaces,+ projectDir,+ logger: { warn },+ snapshot: () => collectCliHostSnapshot({ cwd: projectDir, home }),+ },+ );++ expect(actionFor(report, PI_PROJECT_MCP)).toMatchObject({+ action: 'failed',+ errorId: 'write-failed',+ });+ expect(warn).toHaveBeenCalledWith(+ 'MCP config removal failed',+ expect.objectContaining({+ editor: 'pi',+ path: bridgePath,+ reason: expect.stringContaining(trustPath),+ }),+ );+ expect(warn.mock.calls[0]?.[1].reason).toContain('permissions');+ chmodSync(trustPath, 0o600);+ expect(readFileSync(trustPath, 'utf8')).toBe(before);+ expect(existsSync(bridgePath)).toBe(false);+ expect(existsSync(join(home, '.ok', 'pi-trust'))).toBe(true);+ expect(snapshot.probes.satisfiers[PI_PROJECT_MCP]?.state).toBe('absent');+ } finally {+ if (existsSync(trustPath)) chmodSync(trustPath, 0o600);+ rmSync(root, { recursive: true, force: true });+ }+ },+ );++ test.each(['kept-shared', 'kept-unowned'] as const)(+ 'logs the reason for a successful Pi removal with %s trust',+ async (trust) => {+ const { root, projectDir, home, bridgePath, trustPath, surfaces } = piFixture();+ try {+ if (trust === 'kept-unowned') {+ mkdirSync(dirname(trustPath), { recursive: true });+ writeFileSync(trustPath, JSON.stringify({ [projectDir]: true }));+ }+ expect((await ensurePiBridge(projectDir, { mode: 'published' }, home, {})).ok).toBe(true);+ if (trust === 'kept-shared') mkdirSync(join(projectDir, '.pi', 'prompts'));+ const before = readFileSync(trustPath, 'utf8');+ const warn = vi.fn();++ const { report } = await applyIntents(+ { intents: [drop(PI_PROJECT_MCP)] },+ {+ surfaces,+ projectDir,+ logger: { warn },+ snapshot: () => collectCliHostSnapshot({ cwd: projectDir, home }),+ },+ );++ expect(actionFor(report, PI_PROJECT_MCP)?.action).toBe('removed');+ expect(warn).toHaveBeenCalledWith(+ 'MCP config removal retained Pi folder trust',+ expect.objectContaining({+ editor: 'pi',+ path: bridgePath,+ trust,+ trustDetail: expect.any(String),+ }),+ );+ if (trust === 'kept-shared') {+ expect(warn.mock.calls[0]?.[1].trustDetail).toContain(join(projectDir, '.pi', 'prompts'));+ }+ expect(existsSync(bridgePath)).toBe(false);+ expect(readFileSync(trustPath, 'utf8')).toBe(before);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ },+ );+test('a partial failure still comes back with a fresh snapshot', async () => {const surfaces = makeSurfaces({ projectWriteAction: 'failed' });diff --git a/packages/desktop/src/main/agent-registry-apply.ts b/packages/desktop/src/main/agent-registry-apply.tsindex 5d5d5b6f3..ab10c5a8d 100644--- a/packages/desktop/src/main/agent-registry-apply.ts+++ b/packages/desktop/src/main/agent-registry-apply.ts@@ -64,6 +64,20 @@ function logWriteFailure(logger.warn('skill write failed', { channel: CHANNEL, editor, reason: reason ?? '' });}+function logMcpRemovalFailure(+ logger: AgentIntegrationsLogger,+ editor: McpWiringEditorId,+ error: unknown,+ path?: string,+): void {+ logger.warn('MCP config removal failed', {+ channel: CHANNEL,+ editor,+ ...(path === undefined ? { scope: 'user' } : { scope: 'project', path }),+ reason: error instanceof Error ? error.message : String(error),+ });+}+function missing(): ExecutedOutcome {return { action: 'skipped-missing', errorId: 'surface-missing' };}@@ -79,19 +93,25 @@ function applyUserMcp(global: GlobalWriterSurface,editor: McpWiringEditorId,desired: PlannedStep['desired'],+ logger: AgentIntegrationsLogger,): ExecutedOutcome | Promise<ExecutedOutcome> {if (!global.allEditorIds.includes(editor)) return missing();if (desired === 'absent') {- switch (global.removeUserMcpEntry(editor).kind) {- case 'removed':- return { action: 'removed' };- case 'not-present':- return { action: 'no-op' };- case 'left-foreign':- return { action: 'skipped-foreign', errorId: 'foreign-artifact' };- case 'declined':- return { action: 'declined', errorId: 'write-declined' };+ try {+ switch (global.removeUserMcpEntry(editor).kind) {+ case 'removed':+ return { action: 'removed' };+ case 'not-present':+ return { action: 'no-op' };+ case 'left-foreign':+ return { action: 'skipped-foreign', errorId: 'foreign-artifact' };+ case 'declined':+ return { action: 'declined', errorId: 'write-declined' };+ }+ } catch (error) {+ logMcpRemovalFailure(logger, editor, error);+ return fail('write-failed');}}@@ -119,20 +139,36 @@ function applyProjectMcp(editor: McpWiringEditorId,projectDir: string,desired: PlannedStep['desired'],+ logger: AgentIntegrationsLogger,): ExecutedOutcome {const projectPath = project.projectConfigPath(editor, projectDir);if (projectPath === null) return missing();if (desired === 'absent') {- switch (project.removeProjectMcpEntry(editor, projectDir, projectPath).kind) {- case 'removed':- return { action: 'removed' };- case 'not-present':- return { action: 'no-op' };- case 'left-foreign':- return { action: 'skipped-foreign', errorId: 'foreign-artifact' };- case 'declined':- return { action: 'declined', errorId: 'write-declined' };+ try {+ const result = project.removeProjectMcpEntry(editor, projectDir, projectPath);+ if (result.kind === 'removed' && result.trustDetail) {+ logger.warn('MCP config removal retained Pi folder trust', {+ channel: CHANNEL,+ editor,+ path: projectPath,+ trust: result.trust,+ trustDetail: result.trustDetail,+ });+ }+ switch (result.kind) {+ case 'removed':+ return { action: 'removed' };+ case 'not-present':+ return { action: 'no-op' };+ case 'left-foreign':+ return { action: 'skipped-foreign', errorId: 'foreign-artifact' };+ case 'declined':+ return { action: 'declined', errorId: 'write-declined' };+ }+ } catch (error) {+ logMcpRemovalFailure(logger, editor, error, projectPath);+ return fail('write-failed');}}@@ -233,14 +269,14 @@ function createDesktopStepExecutor(options: DesktopStepExecutorOptions): StepExeif (step.scope === 'user') {return step.piece === 'mcp'- ? applyUserMcp(surfaces.global, editor, step.desired)+ ? applyUserMcp(surfaces.global, editor, step.desired, options.logger): applyUserSkill(surfaces.global, editor, step.desired, options.logger);}if (step.scope !== 'project') return { action: 'skipped-unsupported', errorId: 'no-writer' };if (projectDir === null) return missing();return step.piece === 'mcp'- ? applyProjectMcp(surfaces.project, editor, projectDir, step.desired)+ ? applyProjectMcp(surfaces.project, editor, projectDir, step.desired, options.logger): applyProjectSkill(surfaces.project, editor, projectDir, step.desired, options.logger);};}diff --git a/packages/desktop/src/main/desktop-uninstall-handoff.ts b/packages/desktop/src/main/desktop-uninstall-handoff.tsnew file mode 100644index 000000000..81be23747--- /dev/null+++ b/packages/desktop/src/main/desktop-uninstall-handoff.ts@@ -0,0 +1,255 @@+import { execFileSync, spawn as spawnChild } from 'node:child_process';+import { dirname } from 'node:path';+import type { Readable } from 'node:stream';+import {+ buildDesktopUninstallCleanupScript,+ type DesktopUninstallCleanupInput,+ type RunDesktopUninstallCleanupResult,+ shellQuote,+} from './desktop-uninstall.ts';++interface DesktopUninstallHandoffInput extends DesktopUninstallCleanupInput {+ appBundlePath: string;+ parentPid: number;+ parentStartedAt: string;+}++interface DesktopUninstallHandoffCommands {+ ps?: string;+ sleep?: string;+ osascript?: string;+ open?: string;+}++interface DesktopUninstallResultInput {+ appBundlePath: string;+ logPath: string;+ cleanup: RunDesktopUninstallCleanupResult;+}++interface DesktopUninstallHandoffStepDeps {+ collectFeedback: () => Promise<void>;+ launchHandoff: () => Promise<RunDesktopUninstallCleanupResult>;+ showFailure: (failure: { error: string }) => Promise<void>;+ suppressAutoInstallOnQuit: () => void;+ quit: () => void | Promise<void>;+}++export async function runDesktopUninstallHandoffStep(+ deps: DesktopUninstallHandoffStepDeps,+): Promise<void> {+ await deps.collectFeedback();+ const handoff = await deps.launchHandoff();+ if (!handoff.ok) {+ await deps.showFailure(handoff);+ return;+ }+ deps.suppressAutoInstallOnQuit();+ await deps.quit();+}++interface HandoffChild {+ stdout: Pick<Readable, 'on'> | null;+ once(event: 'error', listener: (error: Error) => void): void;+ once(event: 'close', listener: (code: number | null) => void): void;+ kill(): void;+ unref(): void;+}++interface LaunchDesktopUninstallHandoffDeps {+ spawn?: (command: string, args: readonly string[], options: object) => HandoffChild;+ readParentStartedAt?: () => string;+}++const HANDOFF_READY = 'OK_UNINSTALL_READY';+const NOTICE_SCRIPT = `on run argv+ set noticeTitle to item 1 of argv+ set noticeText to item 2 of argv+ set actionLabel to item 3 of argv+ set result to display dialog noticeText with title noticeTitle buttons {"Cleanup log", actionLabel} default button actionLabel+ return button returned of result+end run`;++function buildDesktopUninstallResultFunctions(+ input: Pick<DesktopUninstallResultInput, 'logPath' | 'appBundlePath'>,+ commands: DesktopUninstallHandoffCommands,+): string {+ return `LOG=${shellQuote(input.logPath)}+APP_BUNDLE=${shellQuote(input.appBundlePath)}+OSASCRIPT=${shellQuote(commands.osascript ?? '/usr/bin/osascript')}+OPEN=${shellQuote(commands.open ?? '/usr/bin/open')}+NOTICE_SCRIPT=${shellQuote(NOTICE_SCRIPT)}++show_result() {+ while :; do+ action=$("$OSASCRIPT" -e "$NOTICE_SCRIPT" "$1" "$2" "$3" 2>> "$LOG") || return+ if [ "$action" = 'Cleanup log' ]; then+ "$OPEN" -R "$LOG" 2>> "$LOG"+ else+ if [ "$action" = 'Reveal in Finder' ]; then+ "$OPEN" -R "$APP_BUNDLE" 2>> "$LOG"+ fi+ return+ fi+ done+}++show_failure() {+ printf '%s\\n' 'Cleanup result: failed' "$1" >> "$LOG"+ show_result 'Cleanup didn’t finish' "Some files may not have been removed. $1++Open the cleanup log for details. You can reopen OpenKnowledge to try again." 'Close'+}++show_success() {+ printf '%s\\n' 'Cleanup result: succeeded' >> "$LOG"+ show_result 'OpenKnowledge files were removed' 'OpenKnowledge’s settings and integrations were removed. Your markdown content and authored skills were kept.++Move OpenKnowledge.app to the Trash to remove the app itself.' 'Reveal in Finder'+}+`;+}++export function buildDesktopUninstallResultScript(+ input: DesktopUninstallResultInput,+ commands: DesktopUninstallHandoffCommands = {},+): string {+ return `#!/bin/sh+/bin/mkdir -p ${shellQuote(dirname(input.logPath))} || exit 1+${buildDesktopUninstallResultFunctions(input, commands)}+${input.cleanup.ok ? 'show_success' : `show_failure ${shellQuote(input.cleanup.error)}`}+`;+}++export async function showDesktopUninstallResult(+ input: DesktopUninstallResultInput,+): Promise<void> {+ await new Promise<void>((resolveResult, reject) => {+ const child = spawnChild('/bin/sh', ['-c', buildDesktopUninstallResultScript(input)], {+ cwd: '/',+ stdio: 'ignore',+ windowsHide: true,+ });+ child.once('error', reject);+ child.once('close', (code) => {+ if (code === 0) resolveResult();+ else reject(new Error(`The cleanup result dialog exited with code ${code}.`));+ });+ });+}++export function buildDesktopUninstallHandoffScript(+ input: DesktopUninstallHandoffInput,+ commands: DesktopUninstallHandoffCommands = {},+): string {+ if (!Number.isSafeInteger(input.parentPid) || input.parentPid <= 0) {+ throw new Error('Invalid uninstall parent process');+ }+ if (input.parentStartedAt.trim() === '') throw new Error('Missing uninstall parent identity');+ return `#!/bin/sh+${buildDesktopUninstallResultFunctions(input, commands)}+PARENT_PID=${input.parentPid}+PARENT_STARTED_AT=${shellQuote(input.parentStartedAt)}+PS=${shellQuote(commands.ps ?? '/bin/ps')}+SLEEP=${shellQuote(commands.sleep ?? '/bin/sleep')}++fail() {+ show_failure "$1"+ exit 1+}++/bin/mkdir -p ${shellQuote(dirname(input.logPath))} || exit 1+: >> "$LOG" || exit 1+printf '${HANDOFF_READY}\\n'+exec 1>/dev/null+attempts=0+while :; do+ current_start=$("$PS" -p "$PARENT_PID" -o lstart= 2>> "$LOG")+ status=$?+ if [ "$status" -eq 1 ] && [ -z "$current_start" ]; then+ break+ fi+ if [ "$status" -ne 0 ] || [ -z "$current_start" ]; then+ fail 'Could not verify that OpenKnowledge stopped; no cleanup was started.'+ fi+ current_start=$(printf '%s' "$current_start" | /usr/bin/sed 's/^[[:space:]]*//;s/[[:space:]]*$//')+ if [ "$current_start" != "$PARENT_STARTED_AT" ]; then+ break+ fi+ attempts=$((attempts + 1))+ if [ "$attempts" -ge 120 ]; then+ fail 'OpenKnowledge did not stop; no cleanup was started.'+ fi+ "$SLEEP" 0.5 || fail 'Could not wait for OpenKnowledge to stop; no cleanup was started.'+done++/bin/sh -c ${shellQuote(buildDesktopUninstallCleanupScript(input))}+status=$?+if [ "$status" -ne 0 ]; then+ fail 'The cleanup command reported a failure.'+fi+show_success+exit 0+`;+}++export async function launchDesktopUninstallHandoff(+ input: DesktopUninstallCleanupInput & { appBundlePath: string },+ deps: LaunchDesktopUninstallHandoffDeps = {},+): Promise<RunDesktopUninstallCleanupResult> {+ try {+ const parentStartedAt =+ deps.readParentStartedAt?.() ??+ execFileSync('/bin/ps', ['-p', String(process.pid), '-o', 'lstart='], {+ encoding: 'utf8',+ timeout: 5000,+ windowsHide: true,+ }).trim();+ const spawn = deps.spawn ?? spawnChild;+ const script = buildDesktopUninstallHandoffScript({+ ...input,+ parentPid: process.pid,+ parentStartedAt,+ });+ return await new Promise((resolveResult) => {+ const child = spawn('/bin/sh', ['-c', script], {+ cwd: '/',+ detached: true,+ stdio: ['ignore', 'pipe', 'ignore'],+ windowsHide: true,+ });+ if (child.stdout === null) {+ child.kill();+ resolveResult({ ok: false, error: 'The cleanup helper could not report readiness.' });+ return;+ }+ let settled = false;+ let output = '';+ const timeout = setTimeout(() => {+ child.kill();+ finish({ ok: false, error: 'The cleanup helper did not become ready.' });+ }, 5000);+ const finish = (result: RunDesktopUninstallCleanupResult) => {+ if (settled) return;+ settled = true;+ clearTimeout(timeout);+ if (result.ok) child.unref();+ resolveResult(result);+ };+ child.stdout.on('data', (chunk: Buffer) => {+ output += chunk.toString();+ if (output.includes(`${HANDOFF_READY}\n`)) finish({ ok: true });+ });+ child.once('error', (error) => finish({ ok: false, error: error.message }));+ child.once('close', (code) =>+ finish({+ ok: false,+ error: 'The cleanup helper stopped before it was ready.',+ exitCode: code,+ }),+ );+ });+ } catch (error) {+ return { ok: false, error: error instanceof Error ? error.message : String(error) };+ }+}diff --git a/packages/desktop/src/main/desktop-uninstall.ts b/packages/desktop/src/main/desktop-uninstall.tsindex 14b570056..7ead77c72 100644--- a/packages/desktop/src/main/desktop-uninstall.ts+++ b/packages/desktop/src/main/desktop-uninstall.ts@@ -1,4 +1,3 @@-import { spawn as spawnChild } from 'node:child_process';import { existsSync, readFileSync } from 'node:fs';import { homedir } from 'node:os';import { dirname, join, resolve } from 'node:path';@@ -36,18 +35,6 @@ export interface DesktopUninstallCleanupInput {logPath: string;}-interface SpawnedCleanupChildLike {- once(event: 'error', listener: (err: Error) => void): void;- once(- event: 'close',- listener: (code: number | null, signal: NodeJS.Signals | null) => void,- ): void;-}--interface RunDesktopUninstallCleanupDeps {- spawn?: (command: string, args: readonly string[], options: object) => SpawnedCleanupChildLike;-}-export type RunDesktopUninstallCleanupResult =| { ok: true }| { ok: false; error: string; exitCode?: number | null };@@ -221,24 +208,6 @@ export async function runDesktopUninstallFeedbackStep(}}-export interface DesktopUninstallOutcomeStepDeps {- cleanup: RunDesktopUninstallCleanupResult;- runFeedbackStep: () => Promise<void>;- showCompletion: () => Promise<void>;- showFailure: (cleanup: { error: string }) => Promise<void>;-}--export async function runDesktopUninstallOutcomeStep(- deps: DesktopUninstallOutcomeStepDeps,-): Promise<void> {- if (!deps.cleanup.ok) {- await deps.showFailure(deps.cleanup);- return;- }- await deps.runFeedbackStep();- await deps.showCompletion();-}-export function defaultDesktopUninstallLogPath(home: string = homedir(),now: Date = new Date(),@@ -264,19 +233,10 @@ export function readDesktopUninstallLogForDisplay(}}-interface DesktopUninstallChecklistItem {- label: string;- detail?: string;- done: boolean;-}-export interface DesktopUninstallNoticeSpec {title: string;- subtitle?: string;paragraphs: string[];- checklist?: DesktopUninstallChecklistItem[];footnote?: string;- logRevealLabel?: string;log?: string;confirmLabel: string;cancelLabel?: string;@@ -288,7 +248,7 @@ export function desktopUninstallConfirmNotice(): DesktopUninstallNoticeSpec {title: 'Uninstall OpenKnowledge?',paragraphs: ['This removes OpenKnowledge’s settings and integrations from your Mac, but keeps your markdown content and authored skills.',- 'When cleanup finishes, OpenKnowledge will help you remove the app itself, then quit.',+ 'OpenKnowledge will quit before cleanup starts. A dialog will show the result and help you remove the app itself.',],confirmLabel: 'Uninstall OpenKnowledge',cancelLabel: 'Cancel',@@ -296,36 +256,6 @@ export function desktopUninstallConfirmNotice(): DesktopUninstallNoticeSpec {};}-export function desktopUninstallCompletionNotice(opts: {- projectCount: number;-}): DesktopUninstallNoticeSpec {- const removedDetail =- opts.projectCount > 0- ? `Cleaned up, including from ${opts.projectCount} project${opts.projectCount === 1 ? '' : 's'}.`- : 'Settings and integrations were cleaned up.';- return {- title: 'OpenKnowledge files were removed',- subtitle: "Almost done. Here's what happened and what's left.",- paragraphs: [],- checklist: [- {- label: 'Kept your content',- detail: 'Markdown files and authored skills were left untouched.',- done: true,- },- { label: 'Removed OpenKnowledge files', detail: removedDetail, done: true },- {- label: 'Move OpenKnowledge.app to the Trash',- detail:- 'Reveal in Finder shows the app and quits OpenKnowledge, so you can drag it to the Trash.',- done: false,- },- ],- logRevealLabel: 'Cleanup log',- confirmLabel: 'Reveal in Finder',- };-}-export function desktopUninstallFailureNotice(opts: {error: string;logPath: string;@@ -348,17 +278,7 @@ export function desktopUninstallFailureNotice(opts: {};}-export function desktopUninstallFinalStepNotice(): DesktopUninstallNoticeSpec {- return {- title: 'One more step',- paragraphs: [- 'Reveal in Finder shows the app and quits OpenKnowledge, so you can drag it to the Trash.',- ],- confirmLabel: 'Reveal in Finder',- };-}--function shellQuote(value: string): string {+export function shellQuote(value: string): string {return `'${value.split("'").join("'\\''")}'`;}@@ -391,9 +311,9 @@ LOG=${shellQuote(input.logPath)}LOG_DIR=${shellQuote(dirname(input.logPath))}EXIT_CODE=0-mkdir -p "$LOG_DIR"+/bin/mkdir -p "$LOG_DIR"{- echo "OpenKnowledge uninstall cleanup started at $(date -u +%Y-%m-%dT%H:%M:%SZ)"+ echo "OpenKnowledge uninstall cleanup started at $(/bin/date -u +%Y-%m-%dT%H:%M:%SZ)"echo "Log: $LOG"GLOBAL_EXIT=0@@ -403,11 +323,15 @@ ${projectBlock.split('\n').map((line) => ` ${line}`).join('\n')}- echo "Removing global OpenKnowledge footprint."- "$OK_CLI" uninstall --yes- GLOBAL_EXIT=$?- if [ "$GLOBAL_EXIT" -ne 0 ]; then- echo "Global uninstall failed with exit code $GLOBAL_EXIT."+ if [ "$DEINIT_EXIT" -eq 0 ]; then+ echo "Removing global OpenKnowledge footprint."+ "$OK_CLI" uninstall --yes+ GLOBAL_EXIT=$?+ if [ "$GLOBAL_EXIT" -ne 0 ]; then+ echo "Global uninstall failed with exit code $GLOBAL_EXIT."+ fi+ else+ echo "Global settings retained because project cleanup was incomplete."fielseecho "Bundled CLI missing or not executable: $OK_CLI"@@ -418,47 +342,9 @@ ${projectBlockEXIT_CODE=1fi- echo "OpenKnowledge uninstall cleanup finished at $(date -u +%Y-%m-%dT%H:%M:%SZ)"+ echo "OpenKnowledge uninstall cleanup finished at $(/bin/date -u +%Y-%m-%dT%H:%M:%SZ)"echo "deinit=$DEINIT_EXIT global=$GLOBAL_EXIT"} >> "$LOG" 2>&1exit "$EXIT_CODE"`;}--export function runDesktopUninstallCleanup(- input: DesktopUninstallCleanupInput,- deps: RunDesktopUninstallCleanupDeps = {},-): Promise<RunDesktopUninstallCleanupResult> {- const spawn = deps.spawn ?? spawnChild;- return new Promise((resolveResult) => {- let settled = false;- const finish = (result: RunDesktopUninstallCleanupResult): void => {- if (settled) return;- settled = true;- resolveResult(result);- };-- try {- const child = spawn('/bin/sh', ['-c', buildDesktopUninstallCleanupScript(input)], {- cwd: '/',- detached: false,- stdio: 'ignore',- windowsHide: true,- });- child.once('error', (err) => finish({ ok: false, error: err.message }));- child.once('close', (code, signal) => {- if (code === 0) {- finish({ ok: true });- return;- }- const error =- signal != null- ? `cleanup process exited after signal ${signal}`- : `cleanup process exited with code ${code ?? 'unknown'}`;- finish({ ok: false, error, exitCode: code });- });- } catch (err) {- finish({ ok: false, error: err instanceof Error ? err.message : String(err) });- }- });-}diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 07ac071e5..f6659e275 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -245,21 +245,21 @@ import {type DesktopUninstallProjectCandidate,type DesktopUninstallUiPreviewMode,defaultDesktopUninstallLogPath,- desktopUninstallCompletionNotice,desktopUninstallConfirmNotice,desktopUninstallFailureNotice,- desktopUninstallFinalStepNotice,isSupportedApplicationsBundle,normalizeDesktopUninstallFeedbackAnswers,- type RunDesktopUninstallCleanupResult,readDesktopUninstallLogForDisplay,resolveAppBundleFromExecPath,resolveDesktopUninstallUiPreviewMode,- runDesktopUninstallCleanup,runDesktopUninstallFeedbackStep,- runDesktopUninstallOutcomeStep,selectDesktopUninstallProjectsByIndex,} from './desktop-uninstall.ts';+import {+ launchDesktopUninstallHandoff,+ runDesktopUninstallHandoffStep,+ showDesktopUninstallResult,+} from './desktop-uninstall-handoff.ts';import { promptForExistingFolder, promptForExistingMarkdownFile } from './dialog-helpers.ts';import {type DriverUtilityLike,@@ -2513,7 +2513,6 @@ async function showDesktopUninstallNotice(width?: number;height?: number;resizable?: boolean;- onRevealLog?: () => void;} = {},): Promise<boolean> {const closeMeansConfirm = noticeCloseIsConfirm(spec);@@ -2533,9 +2532,7 @@ async function showDesktopUninstallNotice(resizable: options.resizable ?? false,title: spec.title,onIntent: (intent, win) => {- if (intent.kind === 'notice-reveal-log') {- options.onRevealLog?.();- } else if (intent.kind === 'notice-confirm') {+ if (intent.kind === 'notice-confirm') {finish(true, win);} else if (intent.kind === 'notice-cancel') {finish(false, win);@@ -2814,32 +2811,22 @@ async function startDesktopSelfUninstallFlow(): Promise<void> {if (!confirmation.proceed) return;const projectPaths = confirmation.projectPaths;- const includeProjects = projectPaths.length > 0;const logPath = defaultDesktopUninstallLogPath(osHomedir());- const cleanup = await withDesktopUninstallProgress(() =>- runDesktopUninstallCleanup({- cliPath: wrapperPathInBundle(process.execPath),- projectPaths,- logPath,- }),- );- await runDesktopUninstallOutcomeStep({- cleanup,- runFeedbackStep: collectDesktopUninstallFeedback,- showCompletion: async () => {- getLogger('lifecycle').info(- { includeProjects, projectCount: projectPaths.length, logPath },- 'desktop self-uninstall cleanup finished',- );- await showDesktopUninstallNotice(- desktopUninstallCompletionNotice({ projectCount: projectPaths.length }),- { height: 440, onRevealLog: () => shell.showItemInFolder(logPath) },- );- },+ await runDesktopUninstallHandoffStep({+ collectFeedback: collectDesktopUninstallFeedback,+ launchHandoff: () =>+ withDesktopUninstallProgress(() =>+ launchDesktopUninstallHandoff({+ cliPath: wrapperPathInBundle(process.execPath),+ projectPaths,+ logPath,+ appBundlePath,+ }),+ ),showFailure: async ({ error }) => {getLogger('lifecycle').warn(- { includeProjects, projectCount: projectPaths.length, logPath, error },- 'desktop self-uninstall cleanup reported failures',+ { projectCount: projectPaths.length, logPath, error },+ 'desktop self-uninstall handoff failed',);await showDesktopUninstallNotice(desktopUninstallFailureNotice({@@ -2849,13 +2836,16 @@ async function startDesktopSelfUninstallFlow(): Promise<void> {}),{ width: 560, height: 520, resizable: true },);- await showDesktopUninstallNotice(desktopUninstallFinalStepNotice(), { height: 240 });+ },+ suppressAutoInstallOnQuit: () => autoUpdaterHandle?.suppressAutoInstallOnQuit(),+ quit: () => {+ getLogger('lifecycle').info(+ { projectCount: projectPaths.length, logPath },+ 'desktop self-uninstall scheduled after exit',+ );+ app.quit();},});-- shell.showItemInFolder(appBundlePath);- autoUpdaterHandle?.suppressAutoInstallOnQuit();- app.quit();}function maybeRunDesktopUninstallUiPreview(): void {@@ -2910,13 +2900,16 @@ async function runDesktopUninstallPreviewMode(mode: DesktopUninstallUiPreviewModconst confirmed = await showDesktopUninstallNotice(desktopUninstallConfirmNotice(), {height: 280,});- let reveals = 0;const acknowledged = await showDesktopUninstallNotice(- desktopUninstallCompletionNotice({ projectCount: 2 }),- { height: 440, onRevealLog: () => (reveals += 1) },+ desktopUninstallFailureNotice({+ error: 'The cleanup helper could not start. No cleanup was started.',+ logPath: defaultDesktopUninstallLogPath(osHomedir()),+ logText: null,+ }),+ { height: 440 },);getLogger('lifecycle').info(- { confirmed, acknowledged, reveals },+ { confirmed, acknowledged },'uninstall UI preview: notices resolved',);await openDesktopUninstallRendererWindow({@@ -2926,8 +2919,7 @@ async function runDesktopUninstallPreviewMode(mode: DesktopUninstallUiPreviewModtitle: 'Notice results',paragraphs: [`confirm=${confirmed ? 'confirmed' : 'cancelled'}`,- `completion=${acknowledged ? 'confirmed' : 'cancelled'}`,- `revealLog=${reveals}`,+ `failure=${acknowledged ? 'confirmed' : 'cancelled'}`,],confirmLabel: 'Close',},@@ -3024,7 +3016,6 @@ async function runDesktopUninstallUiPreview(mode: DesktopUninstallFlowPreviewModreturn;}- const projectPaths = confirmation.projectPaths;const logPath = defaultDesktopUninstallLogPath(home);try {writeFileSync(@@ -3035,22 +3026,13 @@ async function runDesktopUninstallUiPreview(mode: DesktopUninstallFlowPreviewModlog.warn({ err, logPath }, 'uninstall UI preview: could not write placeholder log');}- const cleanup: RunDesktopUninstallCleanupResult = await withDesktopUninstallProgress(async () => {- await new Promise((resolve) => setTimeout(resolve, 1400));- return mode === 'failure'- ? { ok: false, error: 'Simulated cleanup failure (preview) — nothing was removed.' }- : { ok: true };- });-- await runDesktopUninstallOutcomeStep({- cleanup,- runFeedbackStep: collectDesktopUninstallFeedbackPreview,- showCompletion: async () => {- await showDesktopUninstallNotice(- desktopUninstallCompletionNotice({ projectCount: projectPaths.length }),- { height: 440, onRevealLog: () => shell.showItemInFolder(logPath) },- );- },+ await runDesktopUninstallHandoffStep({+ collectFeedback: collectDesktopUninstallFeedbackPreview,+ launchHandoff: () =>+ withDesktopUninstallProgress(async () => {+ await new Promise((resolve) => setTimeout(resolve, 1400));+ return { ok: true };+ }),showFailure: async ({ error }) => {await showDesktopUninstallNotice(desktopUninstallFailureNotice({@@ -3060,8 +3042,17 @@ async function runDesktopUninstallUiPreview(mode: DesktopUninstallFlowPreviewMod}),{ width: 560, height: 520, resizable: true },);- await showDesktopUninstallNotice(desktopUninstallFinalStepNotice(), { height: 240 });},+ suppressAutoInstallOnQuit: () => {},+ quit: () =>+ showDesktopUninstallResult({+ appBundlePath: resolveAppBundleFromExecPath(process.execPath) ?? process.execPath,+ logPath,+ cleanup:+ mode === 'failure'+ ? { ok: false, error: 'Simulated cleanup failure (preview) — nothing was removed.' }+ : { ok: true },+ }),});log.warn({ mode }, 'desktop uninstall UI preview finished — OpenKnowledge is still installed');diff --git a/packages/desktop/src/main/project-integrations-settings.test.ts b/packages/desktop/src/main/project-integrations-settings.test.tsindex bd4dd6c74..444585c3a 100644--- a/packages/desktop/src/main/project-integrations-settings.test.ts+++ b/packages/desktop/src/main/project-integrations-settings.test.ts@@ -1,6 +1,20 @@+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';import type { McpEntryClassification } from '@inkeep/open-knowledge';import type { IpcMainInvokeEvent } from 'electron';-import { describe, expect, test } from 'vitest';+import { describe, expect, test, vi } from 'vitest';+import { EDITOR_TARGETS } from '../../../cli/src/commands/editors.ts';+import { removeOwnMcpEntry } from '../../../cli/src/commands/mcp-config-removal.ts';+import { ensurePiBridge } from '../../../cli/src/commands/pi-acp-bridge.ts';import type {McpWiringEditorId,ProjectIntegrationsSetRequest,@@ -115,6 +129,7 @@ function register(opts: {available?: boolean;projectDir?: string | null;+ logger?: Parameters<typeof registerProjectIntegrationsSettings>[0]['logger'];probeEditorPresence?: Parameters<typeof registerProjectIntegrationsSettings>[0]['probeEditorPresence'];@@ -129,6 +144,7 @@ function register(opts.probeEditorPresence ?? (async () => ({ cliOnPath: {}, schemeHandler: {} })),resolveProjectDir: () => (opts.projectDir === undefined ? PROJECT : opts.projectDir),tildify: (p) => p,+ logger: opts.logger,});const dispatch = ipcMain.handlers.get('ok:project-integrations:dispatch');if (!dispatch) throw new Error('handler not registered');@@ -237,6 +253,58 @@ describe('registerProjectIntegrationsSettings — set', () => {expect(cli.removals).toEqual(['codex']);});+ test.each(['kept-shared', 'kept-unowned'] as const)(+ 'logs why successful project Pi removal retains %s trust',+ async (trust) => {+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-project-settings-pi-')));+ const projectDir = join(root, 'project');+ const home = join(root, 'home');+ const trustPath = join(home, '.pi', 'agent', 'trust.json');+ const bridgePath = join(projectDir, '.pi', 'extensions', 'open-knowledge.ts');+ const prompts = join(projectDir, '.pi', 'prompts');+ try {+ mkdirSync(projectDir);+ mkdirSync(home);+ if (trust === 'kept-unowned') {+ mkdirSync(dirname(trustPath), { recursive: true });+ writeFileSync(trustPath, JSON.stringify({ [projectDir]: true }));+ }+ expect((await ensurePiBridge(projectDir, { mode: 'published' }, home, {})).ok).toBe(true);+ if (trust === 'kept-shared') mkdirSync(prompts);+ const before = readFileSync(trustPath, 'utf8');+ const event = vi.fn();+ const { set } = register(+ {+ ...makeCli(),+ allEditorIds: ['pi'],+ projectConfigPath: (id, cwd) => EDITOR_TARGETS[id].projectConfigPath?.(cwd) ?? null,+ removeProjectMcpEntry: (id, cwd, path) =>+ removeOwnMcpEntry(EDITOR_TARGETS[id], cwd, home, path, {}),+ },+ { projectDir, logger: { warn: vi.fn(), event } },+ );++ const result = await set({ component: { kind: 'editor', id: 'pi' }, enabled: false });++ expect(result.ok).toBe(true);+ expect(event).toHaveBeenCalledWith({+ event: 'project-integrations-editor-removed',+ editor: 'pi',+ outcome: 'removed',+ path: bridgePath,+ trust,+ trustDetail: expect.stringContaining(+ trust === 'kept-shared' ? prompts : 'no OpenKnowledge ownership record',+ ),+ });+ expect(existsSync(bridgePath)).toBe(false);+ expect(readFileSync(trustPath, 'utf8')).toBe(before);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ },+ );+test('uninstall of a foreign entry refuses with an explanatory error', async () => {const cli = makeCli({ removeKind: 'left-foreign' });const { set } = register(cli);diff --git a/packages/desktop/src/main/project-integrations-settings.ts b/packages/desktop/src/main/project-integrations-settings.tsindex 502577483..f579a91ca 100644--- a/packages/desktop/src/main/project-integrations-settings.ts+++ b/packages/desktop/src/main/project-integrations-settings.ts@@ -249,6 +249,9 @@ export function registerProjectIntegrationsSettings(event: 'project-integrations-editor-removed',editor: id,outcome: outcome.kind,+ ...(outcome.kind === 'removed' && outcome.trustDetail+ ? { path: projectPath, trust: outcome.trust, trustDetail: outcome.trustDetail }+ : {}),});return { ok: true };case 'left-foreign':diff --git a/packages/desktop/src/main/uninstall-ipc.ts b/packages/desktop/src/main/uninstall-ipc.tsindex cc5e7d005..aa3056273 100644--- a/packages/desktop/src/main/uninstall-ipc.ts+++ b/packages/desktop/src/main/uninstall-ipc.ts@@ -35,7 +35,6 @@ const RECOGNIZED_UNINSTALL_INTENT_KINDS = {'survey-skip': true,'notice-confirm': true,'notice-cancel': true,- 'notice-reveal-log': true,} satisfies Record<UninstallIntent['kind'], true>;function isRecognizedUninstallIntentKind(value: unknown): value is UninstallIntent['kind'] {@@ -61,8 +60,6 @@ export function normalizeUninstallIntent(raw: unknown): UninstallIntent | null {return { kind: 'notice-confirm' };case 'notice-cancel':return { kind: 'notice-cancel' };- case 'notice-reveal-log':- return { kind: 'notice-reveal-log' };default: {const _exhaustive: never = raw.kind;return _exhaustive;diff --git a/packages/desktop/src/utility/server-entry.ts b/packages/desktop/src/utility/server-entry.tsindex a2e1b0525..3d9601308 100644--- a/packages/desktop/src/utility/server-entry.ts+++ b/packages/desktop/src/utility/server-entry.ts@@ -227,7 +227,8 @@ export function setupUtility(deps: SetupUtilityDeps): UtilityHandle {probeHarnessManagedMcpEntry: (editorId, agentCwd) =>probeOwnManagedEditorMcpEntry(editorId, agentCwd),probePiAcpBridge: (agentCwd) => probePiBridgeState(agentCwd),- ensurePiAcpBridge: (agentCwd) => ensurePiBridge(agentCwd),+ ensurePiAcpBridge: (agentCwd, approvedCanonicalCwd) =>+ ensurePiBridge(agentCwd, undefined, undefined, undefined, approvedCanonicalCwd),serveContentAssets: true,...(msg.opts.reactShellDistDir ? { reactShellDistDir: msg.opts.reactShellDistDir } : {}),};diff --git a/packages/desktop/tests/main/desktop-uninstall-feedback.test.ts b/packages/desktop/tests/main/desktop-uninstall-feedback.test.tsindex 46b18626c..9db260605 100644--- a/packages/desktop/tests/main/desktop-uninstall-feedback.test.ts+++ b/packages/desktop/tests/main/desktop-uninstall-feedback.test.ts@@ -7,7 +7,6 @@ import {confirmDesktopUninstall,type DesktopUninstallProjectCandidate,runDesktopUninstallFeedbackStep,- runDesktopUninstallOutcomeStep,} from '../../src/main/desktop-uninstall.ts';const settleQueue = () => new Promise((resolve) => setTimeout(resolve, 0));@@ -146,60 +145,3 @@ describe('desktop uninstall confirm step', () => {).toEqual({ proceed: false });});});--describe('runDesktopUninstallOutcomeStep', () => {- test('asks why then shows completion when cleanup succeeded', async () => {- const order: string[] = [];- await runDesktopUninstallOutcomeStep({- cleanup: { ok: true },- runFeedbackStep: async () => {- order.push('feedback');- },- showCompletion: async () => {- order.push('completion');- },- showFailure: async () => {- order.push('failure');- },- });- expect(order).toEqual(['feedback', 'completion']);- });-- test('shows failure and never asks why when cleanup failed', async () => {- const runFeedbackStep = vi.fn(async () => {});- const showCompletion = vi.fn(async () => {});- const showFailure = vi.fn(async () => {});- await runDesktopUninstallOutcomeStep({- cleanup: { ok: false, error: 'deinit refused /Users/me/notes' },- runFeedbackStep,- showCompletion,- showFailure,- });- expect(showFailure).toHaveBeenCalledTimes(1);- expect(runFeedbackStep).not.toHaveBeenCalled();- expect(showCompletion).not.toHaveBeenCalled();- });-- test('holds the completion screen until the awaited feedback send settles', async () => {- let releaseFeedback: () => void = () => {};- let completionShown = false;- const done = runDesktopUninstallOutcomeStep({- cleanup: { ok: true },- runFeedbackStep: () =>- new Promise<void>((resolve) => {- releaseFeedback = resolve;- }),- showCompletion: async () => {- completionShown = true;- },- showFailure: async () => {},- });-- await settleQueue();- expect(completionShown).toBe(false);-- releaseFeedback();- await done;- expect(completionShown).toBe(true);- });-});diff --git a/packages/desktop/tests/main/desktop-uninstall-handoff.test.ts b/packages/desktop/tests/main/desktop-uninstall-handoff.test.tsnew file mode 100644index 000000000..13f05662b--- /dev/null+++ b/packages/desktop/tests/main/desktop-uninstall-handoff.test.ts@@ -0,0 +1,402 @@+import { execFileSync, spawn } from 'node:child_process';+import { EventEmitter, once } from 'node:events';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PassThrough } from 'node:stream';+import { afterEach, describe, expect, test, vi } from 'vitest';+import {+ buildDesktopUninstallHandoffScript,+ buildDesktopUninstallResultScript,+ launchDesktopUninstallHandoff,+ runDesktopUninstallHandoffStep,+} from '../../src/main/desktop-uninstall-handoff.ts';++const fixtures: string[] = [];+afterEach(() => {+ for (const dir of fixtures.splice(0)) rmSync(dir, { recursive: true, force: true });+});++function fixture() {+ const dir = mkdtempSync(join(tmpdir(), 'ok-uninstall-handoff-'));+ fixtures.push(dir);+ const executable = (name: string, body: string) => {+ const path = join(dir, name);+ writeFileSync(path, `#!/bin/sh\n${body}\n`, { mode: 0o700 });+ return path;+ };+ const events = join(dir, 'events');+ const commands = {+ osascript: executable('notice', `printf '%s\\n' "$*" >> '${events}'\nprintf 'Close\\n'`),+ open: executable('reveal', `printf 'reveal\\n' >> '${events}'`),+ };+ return { dir, executable, events, commands };+}++describe.skipIf(process.platform === 'win32')('desktop uninstall after exit', () => {+ test('waits for final application writes before removing state and reporting success', async () => {+ const f = fixture();+ const state = join(f.dir, 'state.json');+ const sentinel = join(f.dir, 'crash.json');+ const parent = spawn(+ process.execPath,+ [+ '-e',+ `+ const fs = require('node:fs');+ process.on('SIGTERM', () => {+ fs.writeFileSync(${JSON.stringify(state)}, 'final window snapshot');+ fs.writeFileSync(${JSON.stringify(sentinel)}, 'final crash state');+ process.exit(0);+ });+ console.log('ready');+ setInterval(() => {}, 1000);+ `,+ ],+ { stdio: ['ignore', 'pipe', 'ignore'] },+ );+ await once(parent.stdout, 'data');+ const parentPid = parent.pid as number;+ const parentStartedAt = execFileSync('/bin/ps', ['-p', String(parentPid), '-o', 'lstart='], {+ encoding: 'utf8',+ }).trim();+ const cliPath = f.executable(+ 'cli',+ `test -f '${state}' && test -f '${sentinel}' || exit 12\nrm '${state}' '${sentinel}'\nprintf 'cleanup\\n' >> '${f.events}'`,+ );+ const child = spawn(+ '/bin/sh',+ [+ '-c',+ buildDesktopUninstallHandoffScript(+ {+ cliPath,+ projectPaths: [],+ logPath: join(f.dir, 'cleanup.log'),+ appBundlePath: '/Applications/OpenKnowledge.app',+ parentPid,+ parentStartedAt,+ },+ f.commands,+ ),+ ],+ { stdio: ['ignore', 'pipe', 'ignore'] },+ );+ const completion = once(child, 'close');+ try {+ await once(child.stdout, 'data');+ expect(existsSync(f.events)).toBe(false);+ parent.kill('SIGTERM');+ await expect(completion).resolves.toEqual([0, null]);+ expect(existsSync(state)).toBe(false);+ expect(existsSync(sentinel)).toBe(false);+ const events = readFileSync(f.events, 'utf8');+ expect(events.indexOf('cleanup')).toBeLessThan(+ events.indexOf('OpenKnowledge files were removed'),+ );+ expect(readFileSync(join(f.dir, 'cleanup.log'), 'utf8')).toContain(+ 'Cleanup result: succeeded',+ );+ } finally {+ parent.kill('SIGKILL');+ child.kill('SIGKILL');+ }+ });++ test('does no cleanup and reports failure when the original process remains alive', async () => {+ const f = fixture();+ const parentStartedAt = 'unchanged process';+ const script = buildDesktopUninstallHandoffScript(+ {+ cliPath: f.executable('cli', `printf 'cleanup\\n' >> '${f.events}'`),+ projectPaths: [],+ logPath: join(f.dir, 'cleanup.log'),+ appBundlePath: '/Applications/OpenKnowledge.app',+ parentPid: 123,+ parentStartedAt,+ },+ {+ ...f.commands,+ ps: f.executable('ps', `printf '${parentStartedAt}\\n'`),+ sleep: f.executable('sleep', 'exit 0'),+ },+ );+ const child = spawn('/bin/sh', ['-c', script], { stdio: 'ignore' });+ await expect(once(child, 'close')).resolves.toEqual([1, null]);+ expect(readFileSync(f.events, 'utf8')).toContain('Cleanup didn’t finish');+ expect(readFileSync(f.events, 'utf8')).not.toContain('cleanup\n');+ expect(readFileSync(f.events, 'utf8')).not.toContain('OpenKnowledge files were removed');+ });++ test('reports cleanup errors without a success dialog or app removal instruction', async () => {+ const f = fixture();+ const script = buildDesktopUninstallHandoffScript(+ {+ cliPath: f.executable('cli', 'exit 1'),+ projectPaths: [],+ logPath: join(f.dir, 'cleanup.log'),+ appBundlePath: '/Applications/OpenKnowledge.app',+ parentPid: 123,+ parentStartedAt: 'original process',+ },+ { ...f.commands, ps: f.executable('ps', 'exit 1') },+ );+ const child = spawn('/bin/sh', ['-c', script], { stdio: 'ignore' });+ await expect(once(child, 'close')).resolves.toEqual([1, null]);+ const events = readFileSync(f.events, 'utf8');+ expect(events).toContain('Cleanup didn’t finish');+ expect(events).not.toContain('OpenKnowledge files were removed');+ expect(events).not.toContain('Trash');+ });+});++describe('desktop uninstall handoff readiness', () => {+ class Child extends EventEmitter {+ stdout = new PassThrough();+ kill = vi.fn();+ unref = vi.fn();+ }+ const input = {+ cliPath: '/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh',+ projectPaths: [],+ logPath: '/tmp/uninstall.log',+ appBundlePath: '/Applications/OpenKnowledge.app',+ };++ test('detaches only after the helper reports readiness', async () => {+ const child = new Child();+ const spawn = vi.fn(() => child);+ const launched = launchDesktopUninstallHandoff(input, {+ spawn,+ readParentStartedAt: () => 'original process',+ });+ expect(child.unref).not.toHaveBeenCalled();+ child.stdout.write('OK_UNINSTALL_');+ expect(child.unref).not.toHaveBeenCalled();+ child.stdout.write('READY\n');+ await expect(launched).resolves.toEqual({ ok: true });+ expect(child.unref).toHaveBeenCalledOnce();+ expect(spawn.mock.calls[0]?.[2]).toMatchObject({+ detached: true,+ stdio: ['ignore', 'pipe', 'ignore'],+ });+ });++ test('surfaces a helper launch error without declaring readiness', async () => {+ const child = new Child();+ const launched = launchDesktopUninstallHandoff(input, {+ spawn: () => child,+ readParentStartedAt: () => 'original process',+ });+ child.emit('error', new Error('spawn EACCES'));+ await expect(launched).resolves.toEqual({ ok: false, error: 'spawn EACCES' });+ expect(child.unref).not.toHaveBeenCalled();+ });++ test('stops a helper that never becomes ready', async () => {+ vi.useFakeTimers();+ try {+ const child = new Child();+ const launched = launchDesktopUninstallHandoff(input, {+ spawn: () => child,+ readParentStartedAt: () => 'original process',+ });+ await vi.advanceTimersByTimeAsync(5000);+ await expect(launched).resolves.toMatchObject({ ok: false });+ expect(child.kill).toHaveBeenCalledOnce();+ expect(child.unref).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });+});++describe('desktop uninstall handoff flow', () => {+ test('waits for optional feedback before starting the bounded handoff and suppresses updates before quitting', async () => {+ vi.useFakeTimers();+ try {+ const events: string[] = [];+ let finishFeedback: () => void = () => {};+ const completed = runDesktopUninstallHandoffStep({+ collectFeedback: () =>+ new Promise<void>((resolve) => {+ events.push('feedback');+ finishFeedback = resolve;+ }),+ launchHandoff: async () => {+ events.push('handoff');+ return { ok: true };+ },+ showFailure: async () => {+ events.push('failure');+ },+ suppressAutoInstallOnQuit: () => {+ events.push('suppress update');+ },+ quit: () => {+ events.push('quit');+ },+ });+ await vi.advanceTimersByTimeAsync(120_000);+ expect(events).toEqual(['feedback']);+ finishFeedback();+ await completed;+ expect(events).toEqual(['feedback', 'handoff', 'suppress update', 'quit']);+ } finally {+ vi.useRealTimers();+ }+ });++ test('keeps the app running and displays the error when the helper cannot start', async () => {+ const showFailure = vi.fn(async () => {});+ const suppressAutoInstallOnQuit = vi.fn();+ const quit = vi.fn();+ await runDesktopUninstallHandoffStep({+ collectFeedback: async () => {},+ launchHandoff: async () => ({ ok: false, error: 'spawn EACCES' }),+ showFailure,+ suppressAutoInstallOnQuit,+ quit,+ });+ expect(showFailure).toHaveBeenCalledWith({ ok: false, error: 'spawn EACCES' });+ expect(suppressAutoInstallOnQuit).not.toHaveBeenCalled();+ expect(quit).not.toHaveBeenCalled();+ });+});++describe.skipIf(process.platform === 'win32')('desktop cleanup failure boundaries', () => {+ test('reports failure when selected projects succeed but global cleanup fails', async () => {+ const f = fixture();+ const project = join(f.dir, 'project');+ mkdirSync(join(project, '.ok'), { recursive: true });+ const logPath = join(f.dir, 'cleanup.log');+ const script = buildDesktopUninstallHandoffScript(+ {+ cliPath: f.executable(+ 'cli',+ `printf '%s\\n' "$1" >> '${f.events}'+if [ "$1" = 'uninstall' ]; then exit 31; fi`,+ ),+ projectPaths: [project],+ logPath,+ appBundlePath: '/Applications/OpenKnowledge.app',+ parentPid: 123,+ parentStartedAt: 'original process',+ },+ { ...f.commands, ps: f.executable('ps', 'exit 1') },+ );+ const child = spawn('/bin/sh', ['-c', script], { stdio: 'ignore' });+ await expect(once(child, 'close')).resolves.toEqual([1, null]);+ const events = readFileSync(f.events, 'utf8');+ expect(events).toMatch(/^deinit\nuninstall\n/);+ expect(events).toContain('Cleanup didn’t finish');+ expect(events).not.toContain('Trash');+ expect(events).not.toContain('OpenKnowledge files were removed');+ const log = readFileSync(logPath, 'utf8');+ expect(log).toContain('deinit=0 global=31');+ expect(log).toContain('Cleanup result: failed');+ });++ test('retains global settings after any selected project fails while still trying other selected projects', async () => {+ const f = fixture();+ const projects = [join(f.dir, 'failed'), join(f.dir, 'succeeded')];+ for (const project of projects) mkdirSync(join(project, '.ok'), { recursive: true });+ const cliPath = f.executable(+ 'cli',+ `printf '%s\\n' "$1 $3" >> '${f.events}'+if [ "$3" = '${projects[0]}' ]; then exit 1; fi`,+ );+ const script = buildDesktopUninstallHandoffScript(+ {+ cliPath,+ projectPaths: projects,+ logPath: join(f.dir, 'cleanup.log'),+ appBundlePath: '/Applications/OpenKnowledge.app',+ parentPid: 123,+ parentStartedAt: 'original process',+ },+ { ...f.commands, ps: f.executable('ps', 'exit 1') },+ );+ const child = spawn('/bin/sh', ['-c', script], { stdio: 'ignore' });+ await expect(once(child, 'close')).resolves.toEqual([1, null]);+ const events = readFileSync(f.events, 'utf8');+ for (const project of projects) expect(events).toContain(`deinit ${project}`);+ expect(events).not.toContain('uninstall ');+ expect(events).toContain('Cleanup didn’t finish');+ });++ test('does not delete files when process inspection fails', async () => {+ const f = fixture();+ const script = buildDesktopUninstallHandoffScript(+ {+ cliPath: f.executable('cli', `printf 'cleanup\\n' >> '${f.events}'`),+ projectPaths: [],+ logPath: join(f.dir, 'cleanup.log'),+ appBundlePath: '/Applications/OpenKnowledge.app',+ parentPid: 123,+ parentStartedAt: 'original process',+ },+ { ...f.commands, ps: f.executable('ps', 'exit 2') },+ );+ const child = spawn('/bin/sh', ['-c', script], { stdio: 'ignore' });+ await expect(once(child, 'close')).resolves.toEqual([1, null]);+ const events = readFileSync(f.events, 'utf8');+ expect(events).toContain('Could not verify that OpenKnowledge stopped');+ expect(events).not.toContain('cleanup\n');+ });+});++describe.skipIf(process.platform === 'win32')('desktop cleanup result', () => {+ test.each([true, false])(+ 'records the outcome before attempting a dialog that fails (ok=%s)',+ async (ok) => {+ const f = fixture();+ const logPath = join(f.dir, 'cleanup.log');+ const script = buildDesktopUninstallHandoffScript(+ {+ cliPath: f.executable('cli', ok ? 'exit 0' : 'exit 1'),+ projectPaths: [],+ logPath,+ appBundlePath: '/Applications/OpenKnowledge.app',+ parentPid: 123,+ parentStartedAt: 'original process',+ },+ {+ ...f.commands,+ ps: f.executable('ps', 'exit 1'),+ osascript: f.executable('notice-fails', `cat '${logPath}' > '${f.events}'\nexit 1`),+ },+ );+ const child = spawn('/bin/sh', ['-c', script], { stdio: 'ignore' });+ await expect(once(child, 'close')).resolves.toEqual([ok ? 0 : 1, null]);+ expect(readFileSync(f.events, 'utf8')).toContain(+ `Cleanup result: ${ok ? 'succeeded' : 'failed'}`,+ );+ },+ );++ test.each([true, false])(+ 'previews the actual native result without invoking cleanup (ok=%s)',+ async (ok) => {+ const f = fixture();+ const appBundlePath = join(f.dir, 'OpenKnowledge.app');+ const settings = join(appBundlePath, 'settings');+ mkdirSync(appBundlePath);+ writeFileSync(settings, 'pre-existing settings');+ const script = buildDesktopUninstallResultScript(+ {+ appBundlePath,+ logPath: join(f.dir, 'preview.log'),+ cleanup: ok ? { ok: true } : { ok: false, error: 'simulated failure' },+ },+ f.commands,+ );+ const child = spawn('/bin/sh', ['-c', script], { stdio: 'ignore' });+ await expect(once(child, 'close')).resolves.toEqual([0, null]);+ expect(readFileSync(settings, 'utf8')).toBe('pre-existing settings');+ const events = readFileSync(f.events, 'utf8');+ expect(events).toContain(ok ? 'OpenKnowledge files were removed' : 'Cleanup didn’t finish');+ if (!ok) expect(events).not.toContain('Trash');+ },+ );+});diff --git a/packages/desktop/tests/main/desktop-uninstall.test.ts b/packages/desktop/tests/main/desktop-uninstall.test.tsindex f757ffa2e..3f4614a1d 100644--- a/packages/desktop/tests/main/desktop-uninstall.test.ts+++ b/packages/desktop/tests/main/desktop-uninstall.test.ts@@ -1,18 +1,15 @@import { join } from 'node:path';-import { describe, expect, test, vi } from 'vitest';+import { describe, expect, test } from 'vitest';import {buildDesktopUninstallCleanupScript,collectDesktopUninstallProjectCandidates,defaultDesktopUninstallLogPath,- desktopUninstallCompletionNotice,desktopUninstallConfirmNotice,desktopUninstallFailureNotice,- desktopUninstallFinalStepNotice,isSupportedApplicationsBundle,readDesktopUninstallLogForDisplay,resolveAppBundleFromExecPath,resolveDesktopUninstallUiPreviewMode,- runDesktopUninstallCleanup,selectDesktopUninstallProjectsByIndex,} from '../../src/main/desktop-uninstall.ts';@@ -177,92 +174,6 @@ describe('desktop self-uninstall helpers', () => {expect(confirm.cancelLabel).toBe('Cancel');expect(confirm.danger).toBe(true);expect(confirm.paragraphs.join(' ')).not.toContain('Trash');-- const done = desktopUninstallCompletionNotice({ projectCount: 0 });- expect((done.checklist ?? []).map((item) => item.label)).toEqual([- 'Kept your content',- 'Removed OpenKnowledge files',- 'Move OpenKnowledge.app to the Trash',- ]);- expect(done.checklist?.[0]?.done).toBe(true);- expect(done.checklist?.[1]?.done).toBe(true);- expect(done.checklist?.[2]?.done).toBe(false);- expect(done.confirmLabel).toBe('Reveal in Finder');- expect(done.logRevealLabel).toBe('Cleanup log');- expect(done.footnote).toBeUndefined();- expect(done.paragraphs).toEqual([]);- expect(done.checklist?.[1]?.detail).not.toContain('project');- expect(desktopUninstallCompletionNotice({ projectCount: 2 }).checklist?.[1]?.detail).toContain(- '2 projects',- );-- expect(desktopUninstallFinalStepNotice().paragraphs.join(' ')).toContain('Trash');- });-- test('runDesktopUninstallCleanup spawns an attached shell and resolves on close', async () => {- const listeners = new Map<string, (...args: unknown[]) => void>();- const child = {- once: vi.fn((event: string, listener: (...args: unknown[]) => void) => {- listeners.set(event, listener);- }),- };- const spawn = vi.fn(() => child);- const resultPromise = runDesktopUninstallCleanup(- {- cliPath: '/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh',- projectPaths: [],- logPath: '/tmp/ok-uninstall.log',- },- { spawn },- );-- expect(spawn).toHaveBeenCalledTimes(1);- expect(spawn.mock.calls[0]?.[0]).toBe('/bin/sh');- expect(spawn.mock.calls[0]?.[1]).toEqual(['-c', expect.any(String)]);- expect(spawn.mock.calls[0]?.[2]).toMatchObject({ cwd: '/', detached: false, stdio: 'ignore' });- listeners.get('close')?.(0, null);- await expect(resultPromise).resolves.toEqual({ ok: true });- });-- test('runDesktopUninstallCleanup surfaces spawn errors, exit codes, and signals', async () => {- const input = {- cliPath: '/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh',- projectPaths: [],- logPath: '/tmp/ok-uninstall.log',- };- const run = (fire: (listeners: Map<string, (...args: unknown[]) => void>) => void) => {- const listeners = new Map<string, (...args: unknown[]) => void>();- const child = {- once: (event: string, listener: (...args: unknown[]) => void) => {- listeners.set(event, listener);- },- };- const result = runDesktopUninstallCleanup(input, { spawn: () => child });- fire(listeners);- return result;- };-- await expect(run((l) => l.get('error')?.(new Error('spawn EACCES')))).resolves.toEqual({- ok: false,- error: 'spawn EACCES',- });- await expect(run((l) => l.get('close')?.(1, null))).resolves.toEqual({- ok: false,- error: 'cleanup process exited with code 1',- exitCode: 1,- });- await expect(run((l) => l.get('close')?.(null, 'SIGKILL'))).resolves.toEqual({- ok: false,- error: 'cleanup process exited after signal SIGKILL',- exitCode: null,- });- await expect(- runDesktopUninstallCleanup(input, {- spawn: () => {- throw new Error('shell missing');- },- }),- ).resolves.toEqual({ ok: false, error: 'shell missing' });});});diff --git a/packages/desktop/tests/main/uninstall-ipc.test.ts b/packages/desktop/tests/main/uninstall-ipc.test.tsindex 1f0ddc104..86a88a49d 100644--- a/packages/desktop/tests/main/uninstall-ipc.test.ts+++ b/packages/desktop/tests/main/uninstall-ipc.test.ts@@ -65,12 +65,12 @@ describe('uninstall screen registry — intent delivery', () => {expect(registry.dispatch(7, { kind: 'picker-cancel' })).toEqual({ kind: 'accepted' });expect(registry.dispatch(7, { kind: 'survey-skip' })).toEqual({ kind: 'accepted' });- expect(registry.dispatch(7, { kind: 'notice-reveal-log' })).toEqual({ kind: 'accepted' });+ expect(registry.dispatch(7, { kind: 'notice-confirm' })).toEqual({ kind: 'accepted' });expect(received).toEqual([{ kind: 'picker-cancel' },{ kind: 'survey-skip' },- { kind: 'notice-reveal-log' },+ { kind: 'notice-confirm' },]);});@@ -88,6 +88,7 @@ describe('uninstall screen registry — intent delivery', () => {for (const payload of [{ kind: 'delete-everything' },+ { kind: 'notice-reveal-log' },{ kind: 42 },'notice-confirm',null,diff --git a/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts b/packages/desktop/tests/smoke/_helpers/launch-readiness.test.tsindex 68ce06938..a26a7f9af 100644--- a/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts+++ b/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts@@ -1,5 +1,5 @@import { spawnSync } from 'node:child_process';-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { describe, expect, it } from 'vitest';@@ -378,6 +378,33 @@ describe('launchDesktopApp', () => {),).rejects.toThrow(/Timeout 30000ms exceeded/);});++ it('retains the on-disk boot log and original cause before failed-launch cleanup', async () => {+ const line = markLine('serverSpawned', 8_500, '2026-09-04T00:00:08.500Z');+ const home = seedHome([line]);+ const failure = new Error('electron.launch: Timeout 30000ms exceeded.');+ try {+ const launch = launchDesktopApp(+ {+ launch: async () => {+ throw failure;+ },+ },+ {},+ { home },+ ).catch((error) => {+ rmSync(home, { recursive: true, force: true });+ throw error;+ });+ await expect(launch).rejects.toMatchObject({+ message: expect.stringContaining(line),+ cause: failure,+ });+ expect(existsSync(home)).toBe(false);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });});describe('launch-home registry', () => {diff --git a/packages/desktop/tests/smoke/terminal-dock.e2e.ts b/packages/desktop/tests/smoke/terminal-dock.e2e.tsindex 40ab803bf..c84587cc1 100644--- a/packages/desktop/tests/smoke/terminal-dock.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-dock.e2e.ts@@ -583,6 +583,7 @@ test.describe('Docked terminal — live Electron', () => {await expect(page.locator('#terminal-column section[aria-label="Terminal"]')).toBeVisible({timeout: 10_000,});+ await waitForStatus(page, 'running', 25_000);await clickViewAgentsItem(app);await expect(page.locator('#agents-column')).toBeVisible({ timeout: 10_000 });await expect@@ -592,7 +593,6 @@ test.describe('Docked terminal — live Electron', () => {.evaluate((element) => element.getBoundingClientRect().width),).toBeGreaterThan(739);- await waitForStatus(page, 'running', 25_000);await typeInTerminal(page, `${SHELL_COMMANDS.columns('RAIL_COLS')}\r`);await expect.poll(() => readTerminalText(page), { timeout: 15_000 }).toMatch(/RAIL_COLS=\d+/);const columns = (await readTerminalText(page)).match(/RAIL_COLS=(\d+)/)?.[1];diff --git a/packages/desktop/tests/smoke/terminal-tabs.e2e.ts b/packages/desktop/tests/smoke/terminal-tabs.e2e.tsindex 9082dbcf4..1a832e691 100644--- a/packages/desktop/tests/smoke/terminal-tabs.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-tabs.e2e.ts@@ -4,6 +4,7 @@ import { join } from 'node:path';import type { ElectronApplication, Locator, Page } from '@playwright/test';import { _electron as electron } from '@playwright/test';import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';+import { launchDesktopApp } from './_helpers/launch-readiness';import {PTY_PLATFORM_SKIP_REASON,PTY_PLATFORM_SUPPORTED,@@ -67,7 +68,8 @@ function seed(prefix: string): Seed {async function launchApp(s: Seed): Promise<ElectronApplication> {const deepLink = `openknowledge://open?project=${encodeURIComponent(s.projectDir)}&doc=start`;- return electron.launch(+ return launchDesktopApp(+ electron,desktopLaunchOptions({target: TARGET,args: [`--user-data-dir=${s.userDataDir}`, deepLink],@@ -79,10 +81,18 @@ async function launchApp(s: Seed): Promise<ElectronApplication> {OK_RECLAIM_DISABLE: '1',},}),- );+ { home: s.tmpHome },+ ).catch((error) => {+ for (const target of [s.tmpHome, s.projectDir]) {+ try {+ rmSync(target, { recursive: true, force: true });+ } catch {}+ }+ throw error;+ });}-async function findEditorWindow(app: ElectronApplication, timeoutMs = 15_000): Promise<Page> {+async function findEditorWindow(app: ElectronApplication, timeoutMs = 25_000): Promise<Page> {let page: Page | undefined;await expect(async () => {for (const p of app.windows()) {@@ -182,28 +192,14 @@ async function readActiveText(page: Page): Promise<string> {});}-const cleanup: string[] = [];-function track(...paths: string[]): void {- cleanup.push(...paths);-}-test.describe('Terminal tabs — live Electron', () => {test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');test.skip(!PTY_PLATFORM_SUPPORTED, PTY_PLATFORM_SKIP_REASON);test.skip(!TARGET.exists, TARGET.missingReason);- test.afterEach(() => {- for (const target of cleanup.splice(0)) {- try {- rmSync(target, { recursive: true, force: true });- } catch {}- }- });-test('a second tab spawns its own live shell (independent sessions)', async ({captureStderrFor,}) => {const s = seed('two-shells');- track(s.tmpHome, s.projectDir);const app = await launchApp(s);captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });const page = await findEditorWindow(app);@@ -249,7 +245,6 @@ test.describe('Terminal tabs — live Electron', () => {captureStderrFor,}) => {const s = seed('close-one');- track(s.tmpHome, s.projectDir);const app = await launchApp(s);captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });const page = await findEditorWindow(app);@@ -270,7 +265,6 @@ test.describe('Terminal tabs — live Electron', () => {test('a manual rename pins over the program’s OSC title', async ({ captureStderrFor }) => {const s = seed('rename-pin');- track(s.tmpHome, s.projectDir);const app = await launchApp(s);captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });const page = await findEditorWindow(app);@@ -292,7 +286,6 @@ test.describe('Terminal tabs — live Electron', () => {captureStderrFor,}) => {const s = seed('reorder-survive');- track(s.tmpHome, s.projectDir);const app = await launchApp(s);captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });const page = await findEditorWindow(app);@@ -336,7 +329,6 @@ test.describe('Terminal tabs — live Electron', () => {captureStderrFor,}) => {const s = seed('drag-survive');- track(s.tmpHome, s.projectDir);const app = await launchApp(s);captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });const page = await findEditorWindow(app);@@ -375,7 +367,6 @@ test.describe('Terminal tabs — live Electron', () => {test('a renderer reload preserves tab labels and order', async ({ captureStderrFor }) => {const s = seed('reload-preserve');- track(s.tmpHome, s.projectDir);const app = await launchApp(s);captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });const page = await findEditorWindow(app);diff --git a/packages/desktop/tests/smoke/uninstall-notice.e2e.ts b/packages/desktop/tests/smoke/uninstall-notice.e2e.tsindex 690ad5ca0..0a3208251 100644--- a/packages/desktop/tests/smoke/uninstall-notice.e2e.ts+++ b/packages/desktop/tests/smoke/uninstall-notice.e2e.ts@@ -11,7 +11,7 @@ const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';const DARWIN = process.platform === 'darwin';const CONFIRM_HEADING = 'Uninstall OpenKnowledge?';-const COMPLETION_HEADING = 'OpenKnowledge files were removed';+const FAILURE_HEADING = 'Cleanup didn’t finish';const RESULTS_HEADING = 'Notice results';async function findNoticeWindow(@@ -66,28 +66,25 @@ test.describe('uninstall notice smoke', () => {await app.firstWindow({ timeout: 20_000 });const confirm = await findNoticeWindow(app, CONFIRM_HEADING);- await expect(- confirm.getByText('When cleanup finishes, OpenKnowledge will help you remove the app itself'),- ).toBeVisible();+ await expect(confirm.getByText('OpenKnowledge will quit before cleanup starts.')).toBeVisible();let closed = confirm.waitForEvent('close', { timeout: 15_000 });await confirm.getByRole('button', { name: 'Uninstall OpenKnowledge' }).click();await closed;- const completion = await findNoticeWindow(app, COMPLETION_HEADING);- await expect(completion.getByText('Kept your content')).toBeVisible();- await expect(completion.getByText('Removed OpenKnowledge files')).toBeVisible();- await expect(completion.getByText('Move OpenKnowledge.app to the Trash')).toBeVisible();- closed = completion.waitForEvent('close', { timeout: 15_000 });- await completion.getByRole('button', { name: 'Reveal in Finder' }).click();+ const failure = await findNoticeWindow(app, FAILURE_HEADING);+ await expect(+ failure.getByText('The cleanup helper could not start. No cleanup was started.'),+ ).toBeVisible();+ closed = failure.waitForEvent('close', { timeout: 15_000 });+ await failure.getByRole('button', { name: 'Continue' }).click();await closed;const results = await findNoticeWindow(app, RESULTS_HEADING);await expect(results.getByText('confirm=confirmed')).toBeVisible();- await expect(results.getByText('completion=confirmed')).toBeVisible();- await expect(results.getByText('revealLog=0')).toBeVisible();+ await expect(results.getByText('failure=confirmed')).toBeVisible();});- test('closing an unanswered question cancels, closing a recap confirms', async ({+ test('closing an unanswered question cancels, closing a failure notice acknowledges it', async ({captureStderrFor,}) => {const { app, home } = await launchNoticePreview('ok-uninstall-notice-close-');@@ -100,17 +97,15 @@ test.describe('uninstall notice smoke', () => {await confirm.close();await closed;- const completion = await findNoticeWindow(app, COMPLETION_HEADING);- await completion.getByRole('button', { name: 'Cleanup log' }).click();- await expect(completion.getByRole('heading', { name: COMPLETION_HEADING })).toBeVisible();+ const failure = await findNoticeWindow(app, FAILURE_HEADING);+ await expect(failure.getByRole('heading', { name: FAILURE_HEADING })).toBeVisible();- closed = completion.waitForEvent('close', { timeout: 15_000 });- await completion.close();+ closed = failure.waitForEvent('close', { timeout: 15_000 });+ await failure.close();await closed;const results = await findNoticeWindow(app, RESULTS_HEADING);await expect(results.getByText('confirm=cancelled')).toBeVisible();- await expect(results.getByText('completion=confirmed')).toBeVisible();- await expect(results.getByText('revealLog=1')).toBeVisible();+ await expect(results.getByText('failure=confirmed')).toBeVisible();});});diff --git a/packages/server/src/acp/mcp-injection-skip.test.ts b/packages/server/src/acp/mcp-injection-skip.test.tsindex 0aab46b1c..12c21ab55 100644--- a/packages/server/src/acp/mcp-injection-skip.test.ts+++ b/packages/server/src/acp/mcp-injection-skip.test.ts@@ -232,10 +232,15 @@ describe('buildMcpServers hosted-marker outcomes', () => {describe('buildMcpServers × pi-acp', () => {const PI_LOADABLE = {+ project: 'ready' as const,+ cwd: '/tmp/acp-injection-skip-project',+ canonicalCwd: '/tmp/acp-injection-skip-project',bridgePath: '/tmp/acp-injection-skip-project/.pi/extensions/open-knowledge.ts',+ trustPath: '/tmp/acp-injection-skip-home/.pi/agent/trust.json',bridge: 'own-current' as const,trust: 'trusted' as const,bridgeLoadable: true,+ otherExtensions: [],};test('never injects for pi, even with an http-capable init and a working stdio command', async () => {@@ -275,7 +280,7 @@ describe('buildMcpServers × pi-acp', () => {test('an unprovisioned bridge with no ensure seam reports `none` without prompting', async () => {const m = makeManager(() => null, undefined, {probePiAcpBridge: () => ({- bridgePath: PI_LOADABLE.bridgePath,+ ...PI_LOADABLE,bridge: 'absent',trust: 'untrusted',bridgeLoadable: false,diff --git a/packages/server/src/acp/pi-bridge-flow.integration.test.ts b/packages/server/src/acp/pi-bridge-flow.integration.test.tsindex da265ca76..aa5ce4d8b 100644--- a/packages/server/src/acp/pi-bridge-flow.integration.test.ts+++ b/packages/server/src/acp/pi-bridge-flow.integration.test.ts@@ -134,7 +134,11 @@ function findStatus(const BRIDGE_PATH = '/tmp/pi-project/.pi/extensions/open-knowledge.ts';const unprovisioned: PiAcpBridgeProbe = {+ project: 'ready',+ cwd: '/tmp/pi-project',+ canonicalCwd: '/tmp/canonical-pi-project',bridgePath: BRIDGE_PATH,+ trustPath: '/tmp/pi-home/.pi/agent/trust.json',bridge: 'absent',trust: 'untrusted',bridgeLoadable: false,@@ -142,7 +146,7 @@ const unprovisioned: PiAcpBridgeProbe = {};const provisioned: PiAcpBridgeProbe = {- bridgePath: BRIDGE_PATH,+ ...unprovisioned,bridge: 'own-current',trust: 'trusted',bridgeLoadable: true,@@ -186,14 +190,18 @@ describe('pi bridge consent flow', () => {expect(ensureCalls).toBe(0);}, 30_000);- test('approve → the bridge is provisioned before the session opens', async () => {+ test('consent names the canonical trust key while provisioning keeps the opened path', async () => {const seen: string[] = [];+ const ensuredPaths: { cwd: string; approvedCanonicalCwd: string }[] = [];const manager = makeManager({probePiAcpBridge: (cwd) => {seen.push(cwd);return unprovisioned;},- ensurePiAcpBridge: () => ensured,+ ensurePiAcpBridge: (cwd, approvedCanonicalCwd) => {+ ensuredPaths.push({ cwd, approvedCanonicalCwd });+ return ensured;+ },});const events: ThreadEvent[] = [];const { threadId } = await startThread(manager, events);@@ -203,7 +211,8 @@ describe('pi bridge consent flow', () => {if (req === undefined) throw new Error('unreachable');expect(req.bridgePath).toBe(BRIDGE_PATH);expect(req.agentName).toBe(manager.getInfo(threadId)?.agent.name);- expect(req.cwd).toBe(seen[0]);+ expect(req.cwd).toBe(unprovisioned.canonicalCwd);+ expect(req.cwd).not.toBe(seen[0]);expect(manager.getInfo(threadId)?.status).not.toBe('ready');manager.respondPiBridgeConsent(threadId, req.requestId, { kind: 'granted' });@@ -217,6 +226,7 @@ describe('pi bridge consent flow', () => {trust: 'added',});expect(events.some((e) => e.kind === 'pi_bridge_consent_resolved')).toBe(true);+ expect(ensuredPaths).toEqual([{ cwd: seen[0], approvedCanonicalCwd: req.cwd }]);}, 30_000);test('refuse → the thread runs anyway, and the next thread asks again', async () => {@@ -329,6 +339,73 @@ describe('pi bridge consent flow', () => {expect(findStatus(events)?.requestId).toBeUndefined();}, 30_000);+ test('an unavailable project is reported with its remedy before consent or provisioning', async () => {+ let ensureCalls = 0;+ const detail = 'Project link could not be resolved; restore its target, then retry';+ const manager = makeManager({+ probePiAcpBridge: (cwd) => ({+ project: 'unavailable',+ cwd,+ bridgePath: BRIDGE_PATH,+ trustPath: unprovisioned.trustPath,+ error: detail,+ }),+ ensurePiAcpBridge: () => {+ ensureCalls += 1;+ return ensured;+ },+ });+ const events: ThreadEvent[] = [];+ const { threadId } = await startThread(manager, events);+ await waitReady(manager, threadId);+ await waitFor(() => findStatus(events) !== undefined, 5_000, 'the project limitation event');+ expect(findRequest(events)).toBeUndefined();+ expect(ensureCalls).toBe(0);+ expect(findStatus(events)).toMatchObject({+ state: 'project-path-unavailable',+ bridgePath: BRIDGE_PATH,+ detail,+ });+ expect(findStatus(events)?.requestId).toBeUndefined();+ }, 30_000);++ test.each([+ ['refused-project-path', 'project-path-unavailable'],+ ['refused-unreadable', 'unreadable-file'],+ ] as const)(+ 'provisioning refusal %s retains its resource classification after consent',+ async (bridge, state) => {+ const detail = 'The resource became unavailable while awaiting approval';+ const manager = makeManager({+ probePiAcpBridge: () => unprovisioned,+ ensurePiAcpBridge: () => ({+ ok: false,+ bridgePath: BRIDGE_PATH,+ bridge,+ trust: 'skipped',+ error: detail,+ }),+ });+ const events: ThreadEvent[] = [];+ const { threadId } = await startThread(manager, events);+ await waitFor(() => findRequest(events) !== undefined, 15_000, 'the consent request');+ const req = findRequest(events);+ if (req === undefined) throw new Error('unreachable');+ manager.respondPiBridgeConsent(threadId, req.requestId, { kind: 'granted' });++ await waitReady(manager, threadId);+ await waitFor(() => findStatus(events) !== undefined, 5_000, 'the refusal outcome event');+ expect(findStatus(events)).toMatchObject({+ state,+ requestId: req.requestId,+ bridge,+ trust: 'skipped',+ detail,+ });+ },+ 30_000,+ );+test('a half-landed provisioning reports which half failed and proceeds toolless', async () => {const manager = makeManager({probePiAcpBridge: () => unprovisioned,diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.tsindex 2d748eea7..fadc10643 100644--- a/packages/server/src/acp/thread-manager.ts+++ b/packages/server/src/acp/thread-manager.ts@@ -242,13 +242,21 @@ export interface HarnessManagedMcpEntryHit {configPath: string;}-export interface PiAcpBridgeProbe {+export type PiAcpBridgeProbe = {+ cwd: string;bridgePath: string;- bridge: 'absent' | 'own-current' | 'own-stale' | 'foreign' | 'unreadable';- trust: 'trusted' | 'untrusted' | 'unreadable';- bridgeLoadable: boolean;- otherExtensions: readonly string[];-}+ trustPath: string;+} & (+ | { project: 'unavailable'; error: string }+ | {+ project: 'ready';+ canonicalCwd: string;+ bridge: 'absent' | 'own-current' | 'own-stale' | 'foreign' | 'unreadable';+ trust: 'trusted' | 'untrusted' | 'unreadable';+ bridgeLoadable: boolean;+ otherExtensions: readonly string[];+ }+);export interface PiAcpBridgeEnsureResult {ok: boolean;@@ -284,7 +292,10 @@ export interface AcpThreadManagerOptions {) => HarnessManagedMcpEntryHit | null | Promise<HarnessManagedMcpEntryHit | null>;probePiAcpBridge?: (cwd: string) => PiAcpBridgeProbe | Promise<PiAcpBridgeProbe>;hostSnapshot?: () => Promise<HostSnapshot>;- ensurePiAcpBridge?: (cwd: string) => PiAcpBridgeEnsureResult | Promise<PiAcpBridgeEnsureResult>;+ ensurePiAcpBridge?: (+ cwd: string,+ approvedCanonicalCwd: string,+ ) => PiAcpBridgeEnsureResult | Promise<PiAcpBridgeEnsureResult>;runtimeInstall?: {root?: string;fetchImpl?: typeof fetch;@@ -1214,6 +1225,20 @@ export class AcpThreadManager {return 'unknown';}if (record.closed) return 'unknown';+ if (state.project === 'unavailable') {+ this.opts.log.warn(+ { threadId, cwd: state.cwd, err: new Error(state.error) },+ '[acp-threads] Pi project folder is unavailable; this thread has no OK tools',+ );+ this.emitPiBridgeStatus(record, {+ kind: 'pi_bridge_status',+ state: 'project-path-unavailable',+ bridgePath: state.bridgePath,+ detail: state.error,+ ts: Date.now(),+ });+ return 'unavailable';+ }if (state.bridgeLoadable) {this.opts.log.info({ threadId, bridge: state.bridge, bridgePath: state.bridgePath },@@ -1264,7 +1289,7 @@ export class AcpThreadManager {let result: PiAcpBridgeEnsureResult;try {- result = await ensure(record.cwd);+ result = await ensure(record.cwd, state.canonicalCwd);} catch (err) {const detail = err instanceof Error ? err.message : String(err);this.opts.log.warn({ err, threadId }, '[acp-threads] Pi bridge provisioning threw');@@ -1291,13 +1316,15 @@ export class AcpThreadManager {const bridgeLanded =result.bridge === 'written' || result.bridge === 'refreshed' || result.bridge === 'unchanged';const state2: PiBridgeThreadState =- result.bridge === 'refused-foreign'- ? 'foreign-file'- : result.bridge === 'refused-unreadable'- ? 'unreadable-file'- : bridgeLanded- ? 'trust-failed'- : 'bridge-failed';+ result.bridge === 'refused-project-path'+ ? 'project-path-unavailable'+ : result.bridge === 'refused-foreign'+ ? 'foreign-file'+ : result.bridge === 'refused-unreadable'+ ? 'unreadable-file'+ : bridgeLanded+ ? 'trust-failed'+ : 'bridge-failed';this.opts.log.warn({threadId,@@ -1346,7 +1373,7 @@ export class AcpThreadManager {private requestPiBridgeConsent(record: ThreadRecord,requestId: string,- state: PiAcpBridgeProbe,+ state: Extract<PiAcpBridgeProbe, { project: 'ready' }>,budgetMs: number,): Promise<'granted' | 'declined' | 'timeout' | 'closed'> {this.appendEvent(record, {@@ -1354,7 +1381,7 @@ export class AcpThreadManager {requestId,agentName: record.info.agent.name,bridgePath: state.bridgePath,- cwd: record.cwd,+ cwd: state.canonicalCwd,otherExtensions: state.otherExtensions,ts: Date.now(),});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f54f6fcfa..6cd8c6fc7 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -865,6 +865,9 @@ importers:pino:specifier: ^10.3.1version: 10.3.1+ proper-lockfile:+ specifier: ^4.1.2+ version: 4.1.2simple-git:specifier: ^3.36.0version: 3.36.0@@ -899,6 +902,9 @@ importers:'@types/node':specifier: ^24.7.0version: 24.13.3+ '@types/proper-lockfile':+ specifier: ^4.1.4+ version: 4.1.4'@types/yazl':specifier: ^3.3.1version: 3.3.1@@ -5990,6 +5996,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-uo2ABllncSqg9F1D4nugVl9v93RmjxF6LJzQLMLDdPaXCUIDPeOJ21Gbqi43xNKzBi/WQ0Q0dICqufzQbMjipQ==}+'@types/[email protected]':resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==}peerDependencies:@@ -6001,6 +6010,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-3xSjTp3v03X/lSQLkczaN9UIEwJMoMCA1+Nb5HfbJEQWogdeQIyVtTvxPXDQjZ5zws8rFQfVfRdz03ARihPJgw==}+'@types/[email protected]':resolution: {integrity: sha512-FmgJfu+MOcQ370SD0ev7EI8TlCAfKYU+B4m5T3yXc1CiRN94g/SZPtsCkk506aUDtlMnFZvasDwHHUcZUEaYuA==}@@ -16564,6 +16576,10 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]':+ dependencies:+ '@types/retry': 0.12.5+'@types/[email protected](@types/[email protected])':dependencies:'@types/react': 19.2.17@@ -16576,6 +16592,8 @@ snapshots:dependencies:'@types/node': 24.13.3+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}diff --git a/scripts/generate-third-party-notices.mjs b/scripts/generate-third-party-notices.mjsindex 5c546d6c0..5d21e0795 100644--- a/scripts/generate-third-party-notices.mjs+++ b/scripts/generate-third-party-notices.mjs@@ -238,7 +238,12 @@ function extractCopyrights(licenseText) {) {break;}- if (/^[-*•]/.test(next) || /^\S+ <\S+@\S+>/.test(next) || /^copyright\b/i.test(next)) {+ if (+ /^[-*•]/.test(next) ||+ /^\S+ <\S+@\S+>/.test(next) ||+ /\(\S+@\S+\)\s*$/.test(next) ||+ /^copyright\b/i.test(next)+ ) {block.push(next);j++;} else {