Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
PRD-8103: stop silent project misrouting and duplicate document rooms (#3675)
tim-inkeepf3f575f7fbf6
diff --git a/.changeset/open-project-disclosure-and-stop-guard.md b/.changeset/open-project-disclosure-and-stop-guard.mdnew file mode 100644index 000000000..9f68229b0--- /dev/null+++ b/.changeset/open-project-disclosure-and-stop-guard.md@@ -0,0 +1,13 @@+---+"@inkeep/open-knowledge": minor+---++One file on disk can no longer be backed by two separate collaboration documents. Addressing a document by a name that kept its `.md` or `.mdx` extension used to open a second, independent room over the same file. Both rooms then wrote to that file with no merge and no conflict shown, so whichever saved last silently overwrote the other, and an affected editor tab restored the broken state on every launch. Extension-qualified names now collapse onto the document they actually name, at the one point a room is keyed, so every surface converges: wiki links, graph nodes, share links, skill references, the preview URL, and the HTTP document routes. When a `.md` and an `.mdx` file genuinely exist side by side under one name, the document API still reaches each of them: the extension-qualified name serves the file the bare name does not. The editor lists such a pair as a single entry, so only one half opens there, and that is unchanged. Tabs carrying the old shape are repaired when they are read, so an affected install fixes itself on upgrade.++- `ok open` now prints the project it resolved. Before, a path that landed in a different project than you expected looked identical to one that landed where you meant, and the only way to tell was to run `ok ps` afterwards. When the resolved project sits inside another OpenKnowledge project, the output names both.+- `--project` is honored wherever you put it. Previously it worked only when it came before the target and the target had no file extension. In every other shape it was silently dropped and the project was derived from the file instead. When an override cannot be honored the command now fails and says why, rather than quietly opening somewhere else.+- `ok stop` declines to stop a server that something is still connected to, naming how many clients are attached, and `--force` overrides it. This counts every kind of client, including agents, because stopping a server an agent is writing through loses work the same way. A server that cannot be reached is stopped without the check. `ok deinit` and `ok uninstall` do not gain a second prompt: they add a line to the plan they already show, noting that restarting will not bring those windows back.+- A window whose server has stopped now offers to restart it from the file sidebar, which is the surface that reports the failure. The action already existed but only appeared in a transient toast and in the document error state, so it was easy to miss and the window read as permanently broken.+- `ok stop` records what it stopped, and servers record why they exited. Neither left a durable trace before, so an external stop, an idle shutdown, and a crash were indistinguishable afterwards and none of them reached a diagnostic bundle. Log records also name the project actually resolved instead of a placeholder, and `ok stop` reports its target rather than the directory you happened to be in.+- A project nested inside another project is no longer indexed by its parent. The two used to share content and reconcile only through disk writes.+- `runStop`, exported for programmatic use, is now async and refuses by default when clients are connected. Callers must await it, and pass `force: true` for the previous unconditional behavior.diff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdxindex 4fbdac3b8..551972dc9 100644--- a/docs/content/reference/cli.mdx+++ b/docs/content/reference/cli.mdx@@ -56,15 +56,19 @@ Idle shutdown is on by default at 30 minutes — a server with no connected clieFor a complete list of every file OpenKnowledge creates or changes — during install, at runtime, and in the desktop app — see [What OpenKnowledge writes to your system](/docs/reference/what-open-knowledge-writes).-## Editing a single file+## Open a doc, folder, or file-If you don't have a project initialized, you can still open a file directly in the editor.+`ok open` takes a doc name, a folder, or a path to a Markdown file.```bashok open <path-to-your-file.md>```-This opens your file directly in the WYSIWYG/source editor without any of the version history or `open with AI` frills.+The output names the absolute project root OpenKnowledge resolved for the argument you gave, so you can tell which project it acted on without running a second command. When the resolved root itself sits inside another project, the output names both, once.++To choose the project yourself, pass `--project <dir>`. It is honored wherever it appears: `--project <dir>` or `--project=<dir>`, before or after the target, and with or without the `.md` extension on the path. If it cannot be honored, the command exits non-zero with a message saying why instead of quietly resolving somewhere else.++If you don't have a project initialized, this still works. The file opens directly in the WYSIWYG/source editor without any of the version history or `open with AI` frills.## Clone from GitHub@@ -114,7 +118,7 @@ Each project runs its own local server. These commands let you see and stop them| --- | --- || `ok status` | Show whether a server and UI are running for the current project || `ok ps` | List every running OpenKnowledge server on your machine |-| `ok stop` | Stop the server for the current directory — or pass a port, path, or PID to stop a specific server, or `all` to stop every server |+| `ok stop` | Stop the server for the current directory — or pass a port, path, or PID to stop a specific server, or `all` to stop every server. Declines when something is still connected to the target, naming how many clients are attached; pass `--force` to stop it anyway. A server it cannot reach is stopped without the check || `ok clean` | Remove stale lock files left behind by a crash (never touches live servers) |## Remote Controldiff --git a/packages/app/src/components/ConnectingBanner.tsx b/packages/app/src/components/ConnectingBanner.tsxindex 4248b5391..75eb38209 100644--- a/packages/app/src/components/ConnectingBanner.tsx+++ b/packages/app/src/components/ConnectingBanner.tsx@@ -16,6 +16,12 @@* (b) a manual "Retry" button that resets the backoff window. Shown* immediately regardless of grace — the user has already waited 30s.*+ * Terminal is browser-only: every window that mounts this banner is handed a+ * populated `collabUrl` on the desktop bridge, so `useCollabUrl` short-circuits+ * and never polls, let alone gives up. Server-restart recovery therefore has no+ * reachable home here — it lives on the surfaces the desktop actually renders+ * when a server dies (the document error boundary and the sidebar listing).+ ** A silent-forever banner is itself a form of ceremony — users hit-refresh* or kill the tab. The terminal state surfaces an actionable diagnostic* (pointer at `ok status` / `last-spawn-error.log`) so the user can fix@@ -28,7 +34,6 @@ import { Trans } from '@lingui/react/macro';import { useEffect, useState } from 'react';import { OkBlob } from '@/components/OkBlob';import { useDocumentContext, useOpenBlobRunner } from '@/editor/DocumentContext';-import { restartCollabServer } from '@/lib/restart-collab-server';/*** Grace-period length before the amber retrying banner surfaces. 500 ms@@ -96,11 +101,6 @@ export function ConnectingBanner() {const openBlobRunner = useOpenBlobRunner();const { collabUrl, collabTerminal, collabLastError, retryCollab } = useDocumentContext();const [graceElapsed, setGraceElapsed] = useState(false);- const [restarting, setRestarting] = useState(false);- const [restartError, setRestartError] = useState<string | null>(null);- // Desktop-only: `restartServer` lives on the Electron bridge. In `ok ui`- // (browser) mode there is no owned process to restart, so only Retry shows.- const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;useEffect(() => {// Resolved or terminal → no grace timer needed. Reset the flag so a@@ -130,30 +130,6 @@ export function ConnectingBanner() {// indefinite "Connecting".const isNoCollabServer = isNoCollabServerError(collabLastError);const errorDetail = describeError(collabLastError);- // Retry only re-attempts the SAME server — futile once it has exited (e.g.- // idle-shutdown). In the desktop app we can spawn a fresh one; `restartServer`- // reads the (now absent) lock and boots a new server + window.- const handleRestart = async () => {- if (!bridge) return;- setRestartError(null);- setRestarting(true);- try {- const result = await restartCollabServer(bridge);- // Success: main tears this window down and recreates it, so this- // component is unmounting — nothing to reset. Only a resolved failure- // needs surfacing.- if (!result.ok) {- setRestartError(result.message);- setRestarting(false);- }- } catch {- // The invoke rejects when main destroys this window mid-call (the- // success path) — but an unexpected IPC failure lands here too. Re-enable- // the button so it can't stick on "Restarting"; on the success path the- // component is unmounting, so the state update is a harmless no-op.- setRestarting(false);- }- };return (<divrole="alert"@@ -177,27 +153,11 @@ export function ConnectingBanner() {</span><buttontype="button"- onClick={() => {- // Clear any prior restart-failure message so a fresh Retry doesn't- // read as if the retry itself produced the stale error.- setRestartError(null);- retryCollab();- }}- disabled={restarting}- className="bg-red-950 text-red-50 px-2 py-0.5 rounded text-xs font-medium hover:bg-red-900 disabled:opacity-60"+ onClick={retryCollab}+ className="bg-red-950 text-red-50 px-2 py-0.5 rounded text-xs font-medium hover:bg-red-900"><Trans>Retry</Trans></button>- {bridge ? (- <button- type="button"- onClick={handleRestart}- disabled={restarting}- className="bg-red-950 text-red-50 px-2 py-0.5 rounded text-xs font-medium hover:bg-red-900 disabled:opacity-60"- >- {restarting ? <Trans>Restarting</Trans> : <Trans>Restart server</Trans>}- </button>- ) : null}{/* Deliberate exception to the hidden-game gate: waking the mascotelsewhere costs a rage-click streak, but this banner only appearswhile the user is stuck waiting on the server, which is the wait@@ -213,9 +173,6 @@ export function ConnectingBanner() {<OkBlob size={22} trackMouse={false} variant="sleeping" /></button>) : null}- {restartError !== null ? (- <span className="w-full text-red-950 text-xs">{restartError}</span>- ) : null}</div>);}diff --git a/packages/app/src/components/DocumentErrorBoundary.dom.test.tsx b/packages/app/src/components/DocumentErrorBoundary.dom.test.tsxindex 0b07789f2..fad21754d 100644--- a/packages/app/src/components/DocumentErrorBoundary.dom.test.tsx+++ b/packages/app/src/components/DocumentErrorBoundary.dom.test.tsx@@ -11,6 +11,7 @@ import { cleanup, render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import * as syncPromiseModule from '@/editor/sync-promise';+import { SyncTimeoutError } from '@/editor/sync-promise';import { DocumentErrorBoundary, errorCopy } from './DocumentErrorBoundary';// Radix Dialog (focus trap) reaches for DOM globals the jsdom preload does not@@ -43,11 +44,23 @@ function MaybeThrow({ label }: { label: string }) {return <span data-testid="payload">{label}</span>;}+function ThrowSyncTimeout({ docName }: { docName: string }) {+ if (shouldThrow) {+ // Only a reach failure offers the restart affordance.+ throw new SyncTimeoutError(docName, 10_000);+ }+ return <span data-testid="payload">{docName}</span>;+}+type CreateRequest = { level: 'standard' | 'full'; note?: string };+const restartServer = vi.fn(async () => ({ ok: true as const }));+function installBugReportBridge(): CreateRequest[] {const createCalls: CreateRequest[] = [];const bridge = {+ config: { projectPath: '/tmp/ok', collabUrl: 'ws://127.0.0.1:5200/collab' },+ restartServer,bugReport: {create: (request: CreateRequest) => {createCalls.push(request);@@ -96,6 +109,7 @@ describe('DocumentErrorBoundary (Tier-3 mount)', () => {beforeEach(() => {shouldThrow = false;+ restartServer.mockClear();consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});});@@ -306,4 +320,34 @@ describe('DocumentErrorBoundary (Tier-3 mount)', () => {});expect(sawBoundaryError).toBe(true);});++ test('the restart action is disabled while a restart is in flight', async () => {+ shouldThrow = true;+ installBugReportBridge();+ let releaseRestart!: (value: { ok: true }) => void;+ restartServer.mockImplementationOnce(+ () =>+ new Promise<{ ok: true }>((resolve) => {+ releaseRestart = resolve;+ }),+ );++ render(+ <DocumentErrorBoundary activeDocName="alpha.md" onRecycle={vi.fn(() => {})}>+ <ThrowSyncTimeout docName="alpha.md" />+ </DocumentErrorBoundary>,+ );++ const restart = screen.getByRole('button', { name: /restart server/i });+ await userEvent.click(restart);+ expect((restart as HTMLButtonElement).disabled).toBe(true);++ // A second press while the first is outstanding must not spawn twice.+ await userEvent.click(restart);+ expect(restartServer).toHaveBeenCalledTimes(1);++ releaseRestart({ ok: true });+ await screen.findByRole('button', { name: /restart server/i });+ expect((restart as HTMLButtonElement).disabled).toBe(false);+ });});diff --git a/packages/app/src/components/DocumentErrorBoundary.tsx b/packages/app/src/components/DocumentErrorBoundary.tsxindex d407e9842..3ff43ded4 100644--- a/packages/app/src/components/DocumentErrorBoundary.tsx+++ b/packages/app/src/components/DocumentErrorBoundary.tsx@@ -179,6 +179,10 @@ function DocumentErrorFallback({const canGoBack = !!previousDocName && !!onNavigateBack;const retryRef = useRef<HTMLButtonElement>(null);const [reportOpen, setReportOpen] = useState(false);+ // Same in-flight guard as the sidebar's restart affordance: the call spawns+ // a process and tears this window down, so a second click while it is+ // outstanding dispatches a second spawn.+ const [restarting, setRestarting] = useState(false);// Desktop only, and only for reach failures: "Try again" recycles the// provider against the SAME server, which never succeeds once that server// has stopped. Restart spawns a fresh one. `ok ui` (browser) mode has no@@ -221,7 +225,9 @@ function DocumentErrorFallback({{restartBridge ? (<Buttonvariant="outline-mono"+ disabled={restarting}onClick={() => {+ setRestarting(true);restartCollabServer(restartBridge).then((result) => {// Success: main tears this window down and recreates it.@@ -236,7 +242,8 @@ function DocumentErrorFallback({})// The invoke can reject when main destroys this window mid-call// (the success path) — nothing to surface.- .catch(() => {});+ .catch(() => {})+ .finally(() => setRestarting(false));}}><Trans>Restart server</Trans>diff --git a/packages/app/src/components/FileTree.restart-server.dom.test.tsx b/packages/app/src/components/FileTree.restart-server.dom.test.tsxnew file mode 100644index 000000000..553741cf0--- /dev/null+++ b/packages/app/src/components/FileTree.restart-server.dom.test.tsx@@ -0,0 +1,351 @@+/**+ * Sidebar "Could not reach server" recovery affordance.+ *+ * When the collab server exits under an open window, the sidebar listing is+ * the surface the user is actually looking at — and it offered no way out.+ * These tests drive the real FileTree (testing-library + jsdom) with a+ * network-failing listing and assert the restart action renders, is absent+ * with nothing to restart, is absent for server-answered errors (a live+ * server needs no respawn), and reaches the desktop bridge when pressed.+ *+ * `@pierre/trees/react`'s FileTree is mocked to render the `header` prop so+ * the populated-tree notice row is observable.+ */++import { i18n } from '@lingui/core';+import { cleanup, render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import type { ReactNode } from 'react';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';++i18n.load('en', {});+i18n.activate('en');++function PassThrough({ children }: { children?: ReactNode }) {+ return <>{children}</>;+}++// --- mutable per-test state ---+let listingFails = false;+let listingStatus = 200;+let listingDocuments: unknown[] = [];++function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'content-type': 'application/json' },+ });+}++function docEntry(docName: string) {+ return {+ kind: 'document',+ docName,+ docExt: '.md',+ size: 1,+ modified: '2026-08-18T00:00:00.000Z',+ };+}++function makeFetchMock() {+ return vi.fn(async (input: RequestInfo | URL) => {+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;+ if (url.startsWith('/api/documents')) {+ if (listingFails) throw new TypeError('Failed to fetch');+ if (listingStatus !== 200) return jsonResponse({ title: 'Internal server error' }, 500);+ return jsonResponse({ documents: listingDocuments });+ }+ if (url === '/api/workspace') {+ return jsonResponse({ contentDir: '/tmp/ok', pathSeparator: '/', symlinkResolved: true });+ }+ return jsonResponse({ ok: true });+ });+}++const restartServer = vi.fn(async () => ({ ok: true as const }));++function installBridge() {+ (window as unknown as { okDesktop?: unknown }).okDesktop = {+ platform: 'darwin',+ config: { projectPath: '/tmp/ok', collabUrl: 'ws://127.0.0.1:5200/collab' },+ restartServer,+ };+}++// --- module mocks (mirrors the sibling FileTree dom-test harnesses) ---++class StubItem {+ expanded = false;+ selected = false;+ constructor(+ readonly path: string,+ private readonly directory: boolean,+ ) {}+ getPath() {+ return this.path;+ }+ isDirectory() {+ return this.directory;+ }+ isExpanded() {+ return this.expanded;+ }+ expand() {+ this.expanded = true;+ }+ collapse() {+ this.expanded = false;+ }+ isSelected() {+ return this.selected;+ }+ select() {+ this.selected = true;+ }+ deselect() {+ this.selected = false;+ }+ focus() {}+}++class StubModel {+ focusedPath: string | null = null;+ selectedPaths: string[] = [];+ items = new Map<string, StubItem>();+ startRenaming = vi.fn(() => {});+ getFocusedPath() {+ return this.focusedPath;+ }+ getFocusedIndex() {+ return -1;+ }+ getItemHeight() {+ return 24;+ }+ getSelectedPaths() {+ return this.selectedPaths;+ }+ getItem(path: string) {+ return this.items.get(path) ?? null;+ }+ resetPaths(paths: string[]) {+ this.items.clear();+ for (const path of paths) this.items.set(path, new StubItem(path, path.endsWith('/')));+ }+ subscribe() {+ return () => {};+ }+ onMutation() {+ return () => {};+ }+ isSearchOpen() {+ return false;+ }+ add(path: string) {+ this.items.set(path, new StubItem(path, path.endsWith('/')));+ }+ move() {}+ remove() {}+}++const model = new StubModel();++vi.doMock('sonner', () => ({ toast: { success: vi.fn(() => {}), error: vi.fn(() => {}) } }));+vi.doMock('next-themes', () => ({ useTheme: () => ({ resolvedTheme: 'light' }) }));+vi.doMock('@/editor/DocumentContext', () => ({+ useDocumentContext: () => ({+ activeDocName: null,+ activeTarget: null,+ closeTabs: vi.fn(() => {}),+ closeDocument: vi.fn(() => {}),+ isNewTabActive: false,+ openTarget: vi.fn(() => {}),+ prewarm: () => {},+ reconcileLocalRemoval: vi.fn(async () => {}),+ reconcileLocalRename: vi.fn(async () => {}),+ }),+}));+vi.doMock('@/components/PageListContext', () => ({+ usePageList: () => ({ addPage: vi.fn(() => {}) }),+}));+vi.doMock('./ui/sidebar', () => ({+ useSidebar: () => ({ notifySidebarFileSelected: vi.fn(() => {}) }),+}));+vi.doMock('@/lib/config-provider', () => ({+ useConfigContext: () => ({+ okignoreBinding: null,+ projectLocalBinding: null,+ merged: { appearance: { sidebar: {} } },+ }),+}));+vi.doMock('./handoff/useInstalledAgents', () => ({ useInstalledAgents: () => ({ states: {} }) }));+vi.doMock('./handoff/useHandoffDispatch', () => ({+ buildFolderHandoffInput: () => null,+ buildHandoffInput: () => null,+ useHandoffDispatch: () => ({ dispatch: vi.fn(async () => ({ ok: true as const })) }),+}));+vi.doMock('./handoff/OpenInAgentContextSubmenu', () => ({+ OpenInAgentContextSubmenu: () => null,+}));+vi.doMock('./sidebar-hover-prewarm', () => ({+ cancelHoverPrewarm: () => {},+ scheduleHoverPrewarm: () => {},+}));+vi.doMock('@/components/ui/button', () => ({+ Button: ({ children, ...props }: { children?: ReactNode; [k: string]: unknown }) => (+ <button type="button" {...props}>+ {children}+ </button>+ ),+}));+vi.doMock('@/components/ui/dialog', () => ({ Dialog: PassThrough }));+vi.doMock('@/components/ui/dropdown-menu', () => ({+ DropdownMenu: PassThrough,+ DropdownMenuCheckboxItem: PassThrough,+ DropdownMenuContent: PassThrough,+ DropdownMenuItem: PassThrough,+ DropdownMenuSeparator: () => <hr />,+ DropdownMenuSub: PassThrough,+ DropdownMenuSubContent: PassThrough,+ DropdownMenuSubTrigger: PassThrough,+ DropdownMenuTrigger: PassThrough,+}));+vi.doMock('@/components/ui/skeleton', () => ({+ Skeleton: ({ className }: { className?: string }) => <span className={className} />,+}));+vi.doMock('@/components/DeleteConfirmationDialog', () => ({+ DeleteConfirmationDialog: () => null,+}));+vi.doMock('@/components/NewItemDialog', () => ({ NewItemDialog: () => null }));+vi.doMock('@/components/TrashFailureModal', () => ({+ TrashFailureModal: () => null,+ coerceTrashFailureReason: (reason: string) => reason,+}));+vi.doMock('@/components/use-selection-mirror', () => ({+ asDirectoryHandle: (item: StubItem | null) => (item?.isDirectory() ? item : null),+ useSelectionMirror: () => {},+}));+vi.doMock('@pierre/trees', () => ({+ FILE_TREE_TAG_NAME: 'ok-file-tree',+ themeToTreeStyles: () => ({}),+}));+vi.doMock('@pierre/trees/react', () => ({+ useFileTree: () => ({ model }),+ FileTree: ({ header }: { header?: ReactNode }) => (+ <div data-testid="fake-pierre-tree" role="tree">+ {header}+ </div>+ ),+}));++const { FileTree } = await import('./FileTree');++const RESTART_LABEL = /restart server/i;++describe('FileTree unreachable-server restart action', () => {+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ listingFails = false;+ listingStatus = 200;+ listingDocuments = [];+ restartServer.mockClear();+ globalThis.fetch = makeFetchMock() as unknown as typeof fetch;+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ });++ afterEach(() => {+ cleanup();+ consoleWarnSpy.mockRestore();+ (window as unknown as { okDesktop?: unknown }).okDesktop = undefined;+ });++ test('offers the restart action on the unreachable-server empty state', async () => {+ installBridge();+ listingFails = true;+ render(<FileTree />);++ const alert = await screen.findByRole('alert');+ expect(alert.textContent ?? '').toContain('Could not reach server');+ expect(await screen.findByRole('button', { name: RESTART_LABEL })).toBeTruthy();+ });++ test('omits the restart action when there is no bridge to restart through', async () => {+ listingFails = true;+ render(<FileTree />);++ const alert = await screen.findByRole('alert');+ expect(alert.textContent ?? '').toContain('Could not reach server');+ expect(screen.queryByRole('button', { name: RESTART_LABEL })).toBeNull();+ });++ test('omits the restart action when the server answered with an error', async () => {+ installBridge();+ listingStatus = 500;+ render(<FileTree />);++ const alert = await screen.findByRole('alert');+ expect(alert.textContent ?? '').toContain('Internal server error');+ expect(screen.queryByRole('button', { name: RESTART_LABEL })).toBeNull();+ });++ test('pressing the action restarts this project through the desktop bridge', async () => {+ installBridge();+ listingFails = true;+ render(<FileTree />);++ const restart = await screen.findByRole('button', { name: RESTART_LABEL });+ await userEvent.click(restart);++ await waitFor(() => expect(restartServer).toHaveBeenCalledTimes(1));+ expect(restartServer).toHaveBeenCalledWith('/tmp/ok');+ });++ test('a restart already in flight disables the action instead of spawning twice', async () => {+ installBridge();+ listingFails = true;+ let releaseRestart!: (value: { ok: true }) => void;+ restartServer.mockImplementationOnce(+ () =>+ new Promise<{ ok: true }>((resolve) => {+ releaseRestart = resolve;+ }),+ );+ render(<FileTree />);++ const restart = await screen.findByRole('button', { name: RESTART_LABEL });+ await userEvent.click(restart);+ expect((restart as HTMLButtonElement).disabled).toBe(true);++ await userEvent.click(restart);+ expect(restartServer).toHaveBeenCalledTimes(1);++ releaseRestart({ ok: true });+ await waitFor(() => expect((restart as HTMLButtonElement).disabled).toBe(false));+ });++ test('offers the restart action alongside the header notice on a populated tree', async () => {+ installBridge();+ listingDocuments = [docEntry('notes/a')];+ render(<FileTree />);++ await screen.findByTestId('fake-pierre-tree');+ expect(screen.queryByRole('button', { name: RESTART_LABEL })).toBeNull();++ // A refresh that cannot reach the server leaves the already-listed rows on+ // screen, so the recovery affordance has to live in the header notice slot+ // rather than the empty state.+ listingFails = true;+ window.dispatchEvent(new Event('focus'));++ await waitFor(() =>+ expect((screen.getByRole('alert').textContent ?? '').includes('Could not reach server')).toBe(+ true,+ ),+ );+ const restart = await screen.findByRole('button', { name: RESTART_LABEL });+ // The notice is an aria-live region; a focusable descendant inside one+ // diverges from what screen readers announce.+ expect(screen.getByRole('alert').contains(restart)).toBe(false);+ });+});diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsxindex 3bec7a38b..bb272f655 100644--- a/packages/app/src/components/FileTree.tsx+++ b/packages/app/src/components/FileTree.tsx@@ -163,6 +163,7 @@ import {type ResolvedNavigationTarget,} from '@/components/navigation-targets';import { usePageList } from '@/components/PageListContext';+import { RestartServerButton } from '@/components/RestartServerButton';import {appendPattern,parseOkignoreDoc,@@ -902,6 +903,10 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {disposition: previewOpenDisposition(previewTabsEnabled),consumeActiveNewTab: true,} satisfies OpenTargetOptions;+ // Held as a local so the render below can tell this one failure class apart+ // from server-answered errors: only an unreachable server is recoverable by+ // spawning a new one.+ const couldNotReachServerTitle = t`Could not reach server`;const {documents,setDocuments,@@ -921,7 +926,7 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {messages: {fallbackErrorTitle: t`Failed to load documents`,schemaMismatchTitle: t`Documents response did not match expected shape.`,- couldNotReachServerTitle: t`Could not reach server`,+ couldNotReachServerTitle,},});function navigationTargetForDocument(@@ -3553,6 +3558,7 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {? t`Relaunching to install the update…`: t`Reconnecting…`: null;+ const serverUnreachable = error === couldNotReachServerTitle;if (documents.length === 0) {// The empty tree is the most likely state during a relaunch (zero docs@@ -3569,10 +3575,11 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {}if (error) {return (- <div className="flex flex-1 items-center justify-center py-8">+ <div className="flex flex-1 flex-col items-center justify-center gap-3 py-8"><span role="alert" className="select-none text-sidebar-foreground/50 text-sm">{error}</span>+ {serverUnreachable ? <RestartServerButton /> : null}</div>);}@@ -3636,7 +3643,15 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {{reconnectNotice !== null ? (<FileTreeHeaderNotice kind="reconnecting">{reconnectNotice}</FileTreeHeaderNotice>) : (- error && <FileTreeHeaderNotice kind="error">{error}</FileTreeHeaderNotice>+ error && (+ <>+ <FileTreeHeaderNotice kind="error">{error}</FileTreeHeaderNotice>+ {/* Outside the notice: it is an aria-live region and a+ focusable descendant would diverge from what screen+ readers announce. */}+ {serverUnreachable ? <RestartServerButton className="mx-2 mb-1" /> : null}+ </>+ ))}{truncationNotice !== null && (<FileTreeHeaderNotice kind="info">{truncationNotice}</FileTreeHeaderNotice>diff --git a/packages/app/src/components/RestartServerButton.tsx b/packages/app/src/components/RestartServerButton.tsxnew file mode 100644index 000000000..8e2140037--- /dev/null+++ b/packages/app/src/components/RestartServerButton.tsx@@ -0,0 +1,53 @@+/**+ * Recovery affordance for a surface that can no longer reach its collab+ * server.+ *+ * Retrying the same server is futile once it has exited (`ok stop`, an+ * idle-shutdown, a crash) — the only remedy is a fresh process, which only the+ * desktop bridge can spawn. Browser (`ok ui`) mode has no bridge and nothing+ * to restart, so this renders nothing there.+ */++import { Trans } from '@lingui/react/macro';+import { useState } from 'react';+import { toast } from 'sonner';+import { Button } from '@/components/ui/button';+// Side-effect import for the `Window.okDesktop` global augmentation.+import '@/lib/desktop-bridge-types';+import { restartCollabServer } from '@/lib/restart-collab-server';++export function RestartServerButton({ className }: { className?: string }) {+ // A restart spawns a process and tears this window down; the outstanding+ // call is invisible, so an impatient second click would dispatch a second+ // spawn against a project that is already restarting.+ const [restarting, setRestarting] = useState(false);+ const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;+ if (!bridge) return null;++ return (+ <Button+ variant="outline-mono"+ size="sm"+ className={className}+ disabled={restarting}+ onClick={() => {+ setRestarting(true);+ restartCollabServer(bridge)+ .then((result) => {+ // Success: main tears this window down and recreates it. A fixed+ // `id` dedupes repeated failed clicks into one toast; `Infinity`+ // keeps this actionable error up until it is replaced.+ if (!result.ok) {+ toast.error(result.message, { id: 'server-restart-error', duration: Infinity });+ }+ })+ // The invoke can reject when main destroys this window mid-call+ // (the success path) — nothing to surface.+ .catch(() => {})+ .finally(() => setRestarting(false));+ }}+ >+ <Trans>Restart server</Trans>+ </Button>+ );+}diff --git a/packages/app/src/components/navigation-targets.test.ts b/packages/app/src/components/navigation-targets.test.tsindex 444c06057..d3e47a28b 100644--- a/packages/app/src/components/navigation-targets.test.ts+++ b/packages/app/src/components/navigation-targets.test.ts@@ -157,9 +157,12 @@ describe('resolveNavigationTarget', () => {});});- test('preserves extension-qualified document targets when the exact page exists', () => {+ test('two double-extension files under one stem keep their qualified names', () => {+ // `docs/guide.md.md` and `docs/guide.mdx.md` on disk: each indexes as a page+ // whose own name still ends in a markdown extension, and nothing owns the+ // bare `docs/guide`, so a strip would merge the two onto a name for neither.const resolved = resolveNavigationTarget('docs/guide.md', {- pages: new Set(['docs/guide.md', 'docs/guide.mdx', 'docs/guide']),+ pages: new Set(['docs/guide.md', 'docs/guide.mdx']),folderPaths: new Set(['docs']),});@@ -170,6 +173,19 @@ describe('resolveNavigationTarget', () => {});});+ test('an extension-less page outranks a qualified entry for the same stem', () => {+ const resolved = resolveNavigationTarget('docs/guide.md', {+ pages: new Set(['docs/guide.md', 'docs/guide.mdx', 'docs/guide']),+ folderPaths: new Set(['docs']),+ });++ expect(resolved).toEqual({+ kind: 'doc',+ target: 'docs/guide',+ docName: 'docs/guide',+ });+ });+test('falls back to extensionless document targets when no exact extension page exists', () => {const resolved = resolveNavigationTarget('docs/guide.md', {pages: new Set(['docs/guide']),@@ -817,3 +833,80 @@ describe('editable text docs resolve as doc targets', () => {expect(target).toMatchObject({ kind: 'doc', docName: 'src/util.ts' });});});++describe('markdown-extension normalization keeps one room per file', () => {+ test('a managed-artifact skill reference normalizes before the early return', () => {+ expect(+ resolveNavigationTarget('__skill__/global/my-skill/references/guide.md', {+ pages: new Set<string>(),+ }),+ ).toEqual({+ kind: 'doc',+ target: '__skill__/global/my-skill/references/guide',+ docName: '__skill__/global/my-skill/references/guide',+ });+ });++ test('an external-skill bundle reference normalizes too', () => {+ expect(+ resolveNavigationTarget('__extskill__/my-skill/references/guide.mdx', {+ pages: new Set<string>(),+ }),+ ).toMatchObject({+ kind: 'doc',+ docName: '__extskill__/my-skill/references/guide',+ });+ });++ test('the stripped twin wins over an extension-qualified index entry', () => {+ const pages = new Set(['specs/demo/SPEC', 'specs/demo/SPEC.md']);+ expect(resolveNavigationTarget('specs/demo/SPEC.md', { pages })).toEqual({+ kind: 'doc',+ target: 'specs/demo/SPEC',+ docName: 'specs/demo/SPEC',+ });+ });++ test('repeated extensions collapse to the stem', () => {+ const pages = new Set(['notes/idea']);+ expect(resolveNavigationTarget('notes/idea.md.md', { pages })).toMatchObject({+ kind: 'doc',+ docName: 'notes/idea',+ });+ });++ test('a file whose own name ends in .md keeps that extension', () => {+ // `specs/demo/NOTE.md.md` on disk indexes as the page `specs/demo/NOTE.md`.+ // No page owns `specs/demo/NOTE`, so stripping addresses nothing.+ const pages = new Set(['specs/demo/NOTE.md']);+ expect(resolveNavigationTarget('specs/demo/NOTE.md', { pages })).toEqual({+ kind: 'doc',+ target: 'specs/demo/NOTE.md',+ docName: 'specs/demo/NOTE.md',+ });+ });++ test('system and config doc names pass through untouched', () => {+ const synthetic = [+ '__system__',+ '__config__/project',+ '__local__/project',+ '__user__/config.yml',+ ];+ for (const docName of synthetic) {+ expect(resolveNavigationTarget(docName, { pages: new Set([docName]) })).toEqual({+ kind: 'doc',+ target: docName,+ docName,+ });+ expect(resolveNavigationTarget(docName, { pages: new Set<string>() }).target).toBe(docName);+ }+ });++ test('non-markdown doc names keep their extension', () => {+ expect(resolveNavigationTarget('assets/flow.mmd', { pages: new Set<string>() })).toMatchObject({+ kind: 'doc',+ docName: 'assets/flow.mmd',+ });+ });+});diff --git a/packages/app/src/components/navigation-targets.ts b/packages/app/src/components/navigation-targets.tsindex 8cc300e50..2f750d2f1 100644--- a/packages/app/src/components/navigation-targets.ts+++ b/packages/app/src/components/navigation-targets.ts@@ -131,6 +131,55 @@ function extensionlessTargetPath(target: string): string {return normalizeDocNameInput(target).replace(/\/+$/g, '');}+const MARKDOWN_TARGET_EXTENSION = /\.(md|mdx)$/i;++/**+ * Drop every trailing markdown extension, so `foo.md.md` lands on `foo` rather+ * than on the still-qualified `foo.md`. A name that is nothing but an extension+ * is left as-is — there is no stem to fall back to.+ */+function stripMarkdownTargetExtensions(target: string): string {+ let candidate = target;+ while (MARKDOWN_TARGET_EXTENSION.test(candidate)) {+ const next = candidate.replace(MARKDOWN_TARGET_EXTENSION, '');+ if (!next) return candidate;+ candidate = next;+ }+ return candidate;+}++/**+ * The name every branch of the resolver works from, with a stray markdown+ * extension removed.+ *+ * A doc name IS the collaboration room key, and an extension-carrying name+ * addresses the same file on disk as its stripped twin while keying a SEPARATE+ * room. Two rooms over one file diverge permanently and both write to it, so+ * the loser's edits are overwritten with no merge and no conflict signal.+ * Normalizing here — ahead of the managed-artifact and structural early+ * returns, which hand back a docName without ever consulting the page index —+ * is what stops those paths minting one.+ *+ * The extension is identity in exactly one shape: a file whose OWN name ends in+ * a markdown extension ahead of the one the index strips, so `foo.md.md` on disk+ * is the page `foo.md`. There the trailing extension belongs to the file, and+ * stripping it would address a different file or none at all. That shape is+ * recognisable as a qualified page whose stripped stem is NOT itself a page.+ * Anything else qualified in the index is a stray row for a file already listed+ * ext-less, and must not be allowed to defeat the strip. A same-stem `.md` ++ * `.mdx` pair on disk never arrives here as two pages: the index keys by stem+ * and carries only the winning half. Folder-shaped targets key no room and pass+ * through; so does any name without a markdown extension, including the+ * synthetic system and config docs, whose suffix (or lack of one) is identity.+ */+function canonicalNavigationTarget(target: string, pages: ReadonlySet<string>): string {+ const { normalizedTarget, expectsFolder } = normalizeTargetPath(target);+ if (expectsFolder || !MARKDOWN_TARGET_EXTENSION.test(normalizedTarget)) return target;+ const stripped = stripMarkdownTargetExtensions(normalizedTarget);+ if (pages.has(normalizedTarget) && !pages.has(stripped)) return target;+ return stripped;+}+export function deriveKnownFolderPaths(docNames: Iterable<string>): Set<string> {const folderPaths = new Set<string>();for (const docName of docNames) {@@ -248,7 +297,7 @@ export function okContentNavigationTarget(}export function resolveNavigationTarget(- target: string,+ requestedTarget: string,options: {pages: ReadonlySet<string>;folderPaths?: ReadonlySet<string>;@@ -256,6 +305,7 @@ export function resolveNavigationTarget(pagesByBasename?: ReadonlyMap<string, string>;},): ResolvedContentTarget {+ const target = canonicalNavigationTarget(requestedTarget, options.pages);// Managed-artifact docs (skills) are real docs addressed by their exact// synthetic name, but they live OUTSIDE the page list — so the membership// checks below would mark them 'missing'. Resolve them directly as a doc@@ -333,14 +383,10 @@ export function resolveNavigationTarget(}const extensionlessTarget = extensionlessTargetPath(target);- if (!expectsFolder && options.pages.has(normalizedTarget)) {- return {- kind: 'doc',- target: normalizedTarget,- docName: normalizedTarget,- };- }-+ // The stripped twin is tested FIRST. An index that has picked up an+ // extension-qualified row for a file it already lists ext-less would+ // otherwise redirect navigation onto the second room that row stands for,+ // which is exactly the divergence the canonicalization above prevents.if (!expectsFolder &&extensionlessTarget !== normalizedTarget &&@@ -353,6 +399,14 @@ export function resolveNavigationTarget(};}+ if (!expectsFolder && options.pages.has(normalizedTarget)) {+ return {+ kind: 'doc',+ target: normalizedTarget,+ docName: normalizedTarget,+ };+ }+if (!expectsFolder) {const slugMatchDocName = slugResolve(extensionlessTarget, options.pagesBySlug);if (slugMatchDocName) {diff --git a/packages/app/src/editor/DocumentContext.dom.test.tsx b/packages/app/src/editor/DocumentContext.dom.test.tsxindex db987a18d..b6b9f1cbc 100644--- a/packages/app/src/editor/DocumentContext.dom.test.tsx+++ b/packages/app/src/editor/DocumentContext.dom.test.tsx@@ -41,9 +41,9 @@ vi.doMock('@/hooks/use-skills', () => ({const { DocumentProvider, useDocumentContext } = await import('./DocumentContext');-const PINNED_TAB_ID = docTabId('Pinned.md');-const OTHER_TAB_ID = docTabId('Other.md');-const THIRD_TAB_ID = docTabId('Third.md');+const PINNED_TAB_ID = docTabId('Pinned');+const OTHER_TAB_ID = docTabId('Other');+const THIRD_TAB_ID = docTabId('Third');const LICENSE_TAB_ID = assetTabId('LICENSE');const SKILL_TAB_ID = skillFileTabId({ scope: 'project', name: 'example', path: 'SKILL.md' });const originalFetch = globalThis.fetch;@@ -317,14 +317,14 @@ function CloseActiveHarness() {<button type="button" onClick={() => ctx.focusPane('pane-right')}>Focus right</button>- <button type="button" onClick={() => ctx.openDocument('Other.md')}>+ <button type="button" onClick={() => ctx.openDocument('Other')}>Open other</button><buttontype="button"onClick={() =>ctx.openTarget(- { kind: 'doc', target: 'Other.md', docName: 'Other.md' },+ { kind: 'doc', target: 'Other', docName: 'Other' },{ disposition: 'permanent', consumeActiveNewTab: true },)}@@ -432,7 +432,7 @@ function PaneWorkspaceHarness() {type="button"onClick={() =>ctx.openTarget(- { kind: 'doc', target: 'Third.md', docName: 'Third.md' },+ { kind: 'doc', target: 'Third', docName: 'Third' },{ disposition: 'permanent', consumeActiveNewTab: true },)}@@ -878,9 +878,9 @@ describe('DocumentContext tab close force contract', () => {});});-const REORDER_A = docTabId('A.md');-const REORDER_B = docTabId('B.md');-const REORDER_C = docTabId('C.md');+const REORDER_A = docTabId('A');+const REORDER_B = docTabId('B');+const REORDER_C = docTabId('C');function seedReorderSession() {window.localStorage.setItem(@@ -1556,7 +1556,7 @@ describe('DocumentContext tab restore', () => {),);window.okDesktop = stub.bridge;- window.location.hash = '#/Other.md';+ window.location.hash = '#/Other';render(<CloseActiveHarness />, { wrapper: ProviderHarness });@@ -1598,7 +1598,7 @@ describe('DocumentContext pane workspace', () => {expect(screen.getByTestId('focused-pane').textContent).toBe('pane-left');expect(screen.getByTestId('active-pane-tab').textContent).toBe(OTHER_TAB_ID);- expect(window.location.hash).toBe('#/Other.md');+ expect(window.location.hash).toBe('#/Other');});test('activates the first tab when a reloaded pane has no valid active tab', () => {@@ -1630,7 +1630,7 @@ describe('DocumentContext pane workspace', () => {expect(screen.getByTestId('focused-pane').textContent).toBe('pane-right');expect(screen.getByTestId('active-pane-tab').textContent).toBe(THIRD_TAB_ID);- expect(screen.getByTestId('pane-tabs').textContent?.match(/Third\.md/g)).toHaveLength(1);+ expect(screen.getByTestId('pane-tabs').textContent?.match(/Third/g)).toHaveLength(1);});test('splits a tab into a focused pane without duplicating its target', async () => {@@ -1643,7 +1643,7 @@ describe('DocumentContext pane workspace', () => {expect(screen.getByTestId('pane-count').textContent).toBe('3');expect(screen.getByTestId('focused-pane').textContent).toBe('pane-1');expect(screen.getByTestId('active-pane-tab').textContent).toBe(OTHER_TAB_ID);- expect(screen.getByTestId('pane-tabs').textContent?.match(/Other\.md/g)).toHaveLength(1);+ expect(screen.getByTestId('pane-tabs').textContent?.match(/Other/g)).toHaveLength(1);});// The acceptance test for unifying the Files/Skills surfaces. `skillFocused`@@ -1702,9 +1702,9 @@ describe('DocumentContext pane workspace', () => {});});-const RENAME_FOO = docTabId('foo.md');-const RENAME_BAR = docTabId('bar.md');-const RENAME_BAZZ = docTabId('bazz.md');+const RENAME_FOO = docTabId('foo');+const RENAME_BAR = docTabId('bar');+const RENAME_BAZZ = docTabId('bazz');function seedRenameSession() {window.localStorage.setItem(@@ -1767,7 +1767,7 @@ describe('DocumentContext local rename reconciliation — preserves tab position// reconcileVisibleTabOrder, which dropped the stale `foo` id and re-appended// the new `bazz` id at the end, producing [bar, bazz].seedRenameSession();- render(<RenameHarness fromDocName="foo.md" toDocName="bazz.md" />, {+ render(<RenameHarness fromDocName="foo" toDocName="bazz" />, {wrapper: ProviderHarness,});@@ -1788,7 +1788,7 @@ describe('DocumentContext local rename reconciliation — preserves tab position// the tab itself was remapped, leaving the editor's active-tab UI desynced// from the rendered tab strip.seedRenameSession();- render(<RenameHarness fromDocName="foo.md" toDocName="bazz.md" />, {+ render(<RenameHarness fromDocName="foo" toDocName="bazz" />, {wrapper: ProviderHarness,});diff --git a/packages/app/src/editor/editor-tabs.test.ts b/packages/app/src/editor/editor-tabs.test.tsindex 3df60c316..d7eb93995 100644--- a/packages/app/src/editor/editor-tabs.test.ts+++ b/packages/app/src/editor/editor-tabs.test.ts@@ -943,3 +943,89 @@ test('a global-level skill-preview tab id round-trips its level through the hash});expect(skillPreviewFromHash(hash)?.level).toBe('global');});++describe('persisted tab ids are repaired on read', () => {+ const session = (+ openTabs: string[],+ extras: { pinnedTabIds?: string[]; activeTabId?: string } = {},+ ) => ({+ panes: [+ {+ id: 'pane-main',+ openTabs,+ pinnedTabIds: extras.pinnedTabIds ?? [],+ activeTabId: extras.activeTabId ?? openTabs[0],+ size: 100,+ },+ ],+ focusedPaneId: 'pane-main',+ });++ test('an extension-carrying doc tab restores under its canonical name', () => {+ const state = parseEditorTabSessionState(session(['specs/demo/SPEC.md']));+ expect(state.panes[0].openTabs).toEqual(['specs/demo/SPEC']);+ expect(state.panes[0].activeTabId).toBe('specs/demo/SPEC');+ });++ test('repeated extensions collapse to the stem', () => {+ expect(parseEditorTabSessionState(session(['notes/idea.md.mdx'])).panes[0].openTabs).toEqual([+ 'notes/idea',+ ]);+ });++ test('a managed-artifact skill reference tab is repaired', () => {+ expect(+ parseEditorTabSessionState(session(['__skill__/global/my-skill/references/guide.md']))+ .panes[0].openTabs,+ ).toEqual(['__skill__/global/my-skill/references/guide']);+ });++ test('repair dedupes rather than opening two tabs on one file', () => {+ const state = parseEditorTabSessionState(+ session(['specs/demo/SPEC', 'specs/demo/SPEC.md'], {+ pinnedTabIds: ['specs/demo/SPEC.md'],+ activeTabId: 'specs/demo/SPEC.md',+ }),+ );+ expect(state.panes[0].openTabs).toEqual(['specs/demo/SPEC']);+ expect(state.panes[0].pinnedTabIds).toEqual(['specs/demo/SPEC']);+ expect(state.panes[0].activeTabId).toBe('specs/demo/SPEC');+ });++ test('system and config doc tabs pass through untouched', () => {+ const synthetic = [+ '__system__',+ '__config__/project',+ '__local__/project',+ '__user__/config.yml',+ ];+ expect(parseEditorTabSessionState(session(synthetic)).panes[0].openTabs).toEqual(synthetic);+ });++ test('two double-extension files under one stem keep their tab ids apart', () => {+ // `notes/foo.md.md` and `notes/foo.mdx.md` on disk. Each doc name still ends+ // in a markdown extension that belongs to its file, so stripping either+ // would collapse two distinct documents onto one tab. A genuine same-stem+ // `.md` + `.mdx` pair cannot produce this session: it is indexed under one+ // bare stem, so only its winning half ever becomes a tab id.+ const state = parseEditorTabSessionState(+ session(['notes/foo.md', 'notes/foo.mdx'], { activeTabId: 'notes/foo.mdx' }),+ );+ expect(state.panes[0].openTabs).toEqual(['notes/foo.md', 'notes/foo.mdx']);+ expect(state.panes[0].activeTabId).toBe('notes/foo.mdx');+ });++ test('folder and asset tab ids keep their path verbatim', () => {+ const ids = [folderTabId('specs/demo'), assetTabId('.ok/local/notes.md')];+ expect(parseEditorTabSessionState(session(ids)).panes[0].openTabs).toEqual(ids);+ });++ test('the repair survives the local-storage read path', () => {+ const storage = {+ getItem: () => JSON.stringify(session(['specs/demo/SPEC.md'])),+ };+ expect(readLocalTabSessionState(storage, 'ok-editor-tabs-v1:test').panes[0].openTabs).toEqual([+ 'specs/demo/SPEC',+ ]);+ });+});diff --git a/packages/app/src/editor/editor-tabs.ts b/packages/app/src/editor/editor-tabs.tsindex fcc0291e2..245eaa961 100644--- a/packages/app/src/editor/editor-tabs.ts+++ b/packages/app/src/editor/editor-tabs.ts@@ -82,6 +82,108 @@ function stripMarkdownTabExtension(path: string): string | null {: null;}+/**+ * True when another id in the session is extension-qualified under the same stem+ * as `tabId` — `foo.md` alongside `foo.mdx`.+ *+ * A doc name is its on-disk path with one markdown extension removed, so a+ * QUALIFIED doc name belongs to a file carrying a second markdown extension of+ * its own (`foo.md.md`, `foo.mdx.md`). Two of those under one stem are two+ * DISTINCT files, and stripping either would merge both into a single tab. This+ * is not the same-stem `.md` + `.mdx` case: that pair is indexed under one bare+ * stem, so only its winning half ever becomes a tab id. An extension-carrying id+ * whose only relative is the bare stem is the opposite case — one file+ * addressed twice.+ */+function sharesStemWithAnotherQualifiedTab(+ tabId: string,+ siblingTabIds: readonly string[],+): boolean {+ const stem = stripMarkdownTabExtension(tabId);+ if (stem === null) return false;+ return siblingTabIds.some(+ (other) => other !== tabId && stripMarkdownTabExtension(other) === stem,+ );+}++/**+ * Collapse a doc tab id onto the name that keys exactly ONE collaboration room.+ *+ * A doc tab's id IS its docName, so an extension-carrying id addresses the same+ * file on disk as its stripped twin while keying a second room over that file.+ * The two rooms diverge permanently and both write to it, so the loser's edits+ * are overwritten with no merge. Strips repeatedly, so `foo.md.md` lands on+ * `foo` rather than on the still-qualified `foo.md`.+ *+ * Folder, asset, and skill-viewer ids address a path rather than a room, so they+ * keep their extension; so does any doc name without a markdown extension,+ * including the synthetic system and config docs.+ */+function canonicalTabId(tabId: string, siblingTabIds: readonly string[] = []): string {+ if (parseEditorTabId(tabId).kind !== 'doc') return tabId;+ if (sharesStemWithAnotherQualifiedTab(tabId, siblingTabIds)) return tabId;+ let docName = tabId;+ let stripped = stripMarkdownTabExtension(docName);+ while (stripped !== null && stripped.length > 0) {+ docName = stripped;+ stripped = stripMarkdownTabExtension(docName);+ }+ return docName;+}++function canonicalTabIdList(value: unknown, siblingTabIds: readonly string[]): unknown {+ if (!Array.isArray(value)) return value;+ return value.map((item) =>+ typeof item === 'string' ? canonicalTabId(item, siblingTabIds) : item,+ );+}++/** Every persisted tab id across the session's panes, in pane order. */+function persistedTabIds(panes: readonly unknown[]): string[] {+ return panes.flatMap((pane) => {+ if (typeof pane !== 'object' || pane === null) return [];+ const openTabs = (pane as Record<string, unknown>).openTabs;+ if (!Array.isArray(openTabs)) return [];+ return openTabs.filter((tabId): tabId is string => typeof tabId === 'string');+ });+}++/**+ * Rewrite persisted tab identifiers to their canonical form before the pane+ * parser reads them.+ *+ * Nothing normalized these ids on the way in, so a profile that ever opened an+ * extension-carrying doc name re-mints that second room on every launch:+ * normalizing only what is written from here on would leave those profiles+ * broken indefinitely. Repair happens on the read side of BOTH stores (browser+ * local storage and the desktop bridge), which share this parse.+ *+ * Entries are mapped rather than dropped — dropping one would close a tab the+ * user left open. The pane parser's own de-duplication then folds a repaired id+ * into an already-open canonical one, so a session holding both shapes restores+ * as one tab instead of two over the same file.+ */+function repairPersistedTabIds(record: Record<string, unknown>): Record<string, unknown> {+ const repaired: Record<string, unknown> = { ...record };+ const siblingTabIds = Array.isArray(record.panes) ? persistedTabIds(record.panes) : [];+ if (Array.isArray(record.panes)) {+ repaired.panes = record.panes.map((pane) => {+ if (typeof pane !== 'object' || pane === null) return pane;+ const entry = pane as Record<string, unknown>;+ return {+ ...entry,+ openTabs: canonicalTabIdList(entry.openTabs, siblingTabIds),+ pinnedTabIds: canonicalTabIdList(entry.pinnedTabIds, siblingTabIds),+ activeTabId:+ typeof entry.activeTabId === 'string'+ ? canonicalTabId(entry.activeTabId, siblingTabIds)+ : entry.activeTabId,+ };+ });+ }+ return repaired;+}+function isValidTabId(value: unknown): value is string {if (typeof value !== 'string' || value.length === 0 || value.includes('\u0000doc-tab:')) {return false;@@ -846,7 +948,7 @@ export function parseEditorTabSessionState(value: unknown): EditorTabSessionStatif (typeof value !== 'object' || value === null) {return emptyTabSessionState();}- const record = value as Record<string, unknown>;+ const record = repairPersistedTabIds(value as Record<string, unknown>);if (!Array.isArray(record.panes)) return emptyTabSessionState();const workspace = parsePersistedEditorWorkspace(record);return sessionStateFromWorkspace(diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.poindex 76684801e..0954f3d0c 100644--- a/packages/app/src/locales/ar/messages.po+++ b/packages/app/src/locales/ar/messages.po@@ -11035,8 +11035,8 @@ msgid "Resources"msgstr "الموارد"#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsx#: src/components/DocumentErrorBoundary.tsx+#: src/components/RestartServerButton.tsx#: src/presence/use-sync-toasts.tsmsgid "Restart server"msgstr "إعادة تشغيل الخادم"@@ -11054,7 +11054,6 @@ msgid "Restarted — now running v{appRuntime}."msgstr "أُعيد التشغيل — يعمل الآن بالإصدار v{appRuntime}."#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsxmsgid "Restarting"msgstr "تجري إعادة التشغيل"diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.poindex 473db013b..fbce585c4 100644--- a/packages/app/src/locales/bn/messages.po+++ b/packages/app/src/locales/bn/messages.po@@ -11031,8 +11031,8 @@ msgid "Resources"msgstr "সম্পদ"#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsx#: src/components/DocumentErrorBoundary.tsx+#: src/components/RestartServerButton.tsx#: src/presence/use-sync-toasts.tsmsgid "Restart server"msgstr "সার্ভার পুনরায় চালু করুন"@@ -11050,7 +11050,6 @@ msgid "Restarted — now running v{appRuntime}."msgstr "পুনরায় চালু হয়েছে — এখন v{appRuntime} চলছে।"#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsxmsgid "Restarting"msgstr "পুনরায় চালু করা হচ্ছে"diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex d2ede6cb7..a977529ae 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -11035,8 +11035,8 @@ msgid "Resources"msgstr "Resources"#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsx#: src/components/DocumentErrorBoundary.tsx+#: src/components/RestartServerButton.tsx#: src/presence/use-sync-toasts.tsmsgid "Restart server"msgstr "Restart server"@@ -11054,7 +11054,6 @@ msgid "Restarted — now running v{appRuntime}."msgstr "Restarted — now running v{appRuntime}."#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsxmsgid "Restarting"msgstr "Restarting"diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.poindex 7e2a1d25f..9e5b85161 100644--- a/packages/app/src/locales/es/messages.po+++ b/packages/app/src/locales/es/messages.po@@ -11035,8 +11035,8 @@ msgid "Resources"msgstr "Recursos"#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsx#: src/components/DocumentErrorBoundary.tsx+#: src/components/RestartServerButton.tsx#: src/presence/use-sync-toasts.tsmsgid "Restart server"msgstr "Reiniciar el servidor"@@ -11054,7 +11054,6 @@ msgid "Restarted — now running v{appRuntime}."msgstr "Reiniciado: ahora se ejecuta la v{appRuntime}."#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsxmsgid "Restarting"msgstr "Reiniciando"diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.poindex 8b4f66a05..0b3fdb9ec 100644--- a/packages/app/src/locales/fr/messages.po+++ b/packages/app/src/locales/fr/messages.po@@ -11035,8 +11035,8 @@ msgid "Resources"msgstr "Ressources"#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsx#: src/components/DocumentErrorBoundary.tsx+#: src/components/RestartServerButton.tsx#: src/presence/use-sync-toasts.tsmsgid "Restart server"msgstr "Redémarrer le serveur"@@ -11054,7 +11054,6 @@ msgid "Restarted — now running v{appRuntime}."msgstr "Redémarré — exécute maintenant la v{appRuntime}."#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsxmsgid "Restarting"msgstr "Redémarrage"diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.poindex 929dcec3a..8c641fbcb 100644--- a/packages/app/src/locales/hi/messages.po+++ b/packages/app/src/locales/hi/messages.po@@ -11031,8 +11031,8 @@ msgid "Resources"msgstr "संसाधन"#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsx#: src/components/DocumentErrorBoundary.tsx+#: src/components/RestartServerButton.tsx#: src/presence/use-sync-toasts.tsmsgid "Restart server"msgstr "सर्वर पुनः आरंभ करें"@@ -11050,7 +11050,6 @@ msgid "Restarted — now running v{appRuntime}."msgstr "पुनः आरंभ हुआ — अब v{appRuntime} चल रहा है।"#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsxmsgid "Restarting"msgstr "पुनः आरंभ किया जा रहा है"diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.poindex a01910686..93660637e 100644--- a/packages/app/src/locales/id/messages.po+++ b/packages/app/src/locales/id/messages.po@@ -11031,8 +11031,8 @@ msgid "Resources"msgstr "Sumber daya"#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsx#: src/components/DocumentErrorBoundary.tsx+#: src/components/RestartServerButton.tsx#: src/presence/use-sync-toasts.tsmsgid "Restart server"msgstr "Mulai ulang server"@@ -11050,7 +11050,6 @@ msgid "Restarted — now running v{appRuntime}."msgstr "Dimulai ulang — kini menjalankan v{appRuntime}."#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsxmsgid "Restarting"msgstr "Memulai ulang"diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.poindex 627f35401..101a5dfd1 100644--- a/packages/app/src/locales/ko/messages.po+++ b/packages/app/src/locales/ko/messages.po@@ -11035,8 +11035,8 @@ msgid "Resources"msgstr "리소스"#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsx#: src/components/DocumentErrorBoundary.tsx+#: src/components/RestartServerButton.tsx#: src/presence/use-sync-toasts.tsmsgid "Restart server"msgstr "서버 재시작"@@ -11054,7 +11054,6 @@ msgid "Restarted — now running v{appRuntime}."msgstr "다시 시작했습니다. 현재 v{appRuntime}을 실행 중입니다."#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsxmsgid "Restarting"msgstr "재시작 중"diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 548e9eb43..6939b22f0 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -11031,8 +11031,8 @@ msgid "Resources"msgstr ""#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsx#: src/components/DocumentErrorBoundary.tsx+#: src/components/RestartServerButton.tsx#: src/presence/use-sync-toasts.tsmsgid "Restart server"msgstr ""@@ -11050,7 +11050,6 @@ msgid "Restarted — now running v{appRuntime}."msgstr ""#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsxmsgid "Restarting"msgstr ""diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.poindex 1488b68dd..255fea570 100644--- a/packages/app/src/locales/pt-BR/messages.po+++ b/packages/app/src/locales/pt-BR/messages.po@@ -11031,8 +11031,8 @@ msgid "Resources"msgstr "Recursos"#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsx#: src/components/DocumentErrorBoundary.tsx+#: src/components/RestartServerButton.tsx#: src/presence/use-sync-toasts.tsmsgid "Restart server"msgstr "Reiniciar o servidor"@@ -11050,7 +11050,6 @@ msgid "Restarted — now running v{appRuntime}."msgstr "Reiniciado — agora rodando a v{appRuntime}."#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsxmsgid "Restarting"msgstr "Reiniciando"diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.poindex 6c7ac84ad..d8dc16256 100644--- a/packages/app/src/locales/ur/messages.po+++ b/packages/app/src/locales/ur/messages.po@@ -11035,8 +11035,8 @@ msgid "Resources"msgstr "وسائل"#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsx#: src/components/DocumentErrorBoundary.tsx+#: src/components/RestartServerButton.tsx#: src/presence/use-sync-toasts.tsmsgid "Restart server"msgstr "سرور دوبارہ چلائیں"@@ -11054,7 +11054,6 @@ msgid "Restarted — now running v{appRuntime}."msgstr "دوبارہ چل پڑا — اب v{appRuntime} چل رہا ہے۔"#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsxmsgid "Restarting"msgstr "دوبارہ چلایا جا رہا ہے"diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.poindex 94d2b9ba7..48d52a2c9 100644--- a/packages/app/src/locales/zh-Hans/messages.po+++ b/packages/app/src/locales/zh-Hans/messages.po@@ -11035,8 +11035,8 @@ msgid "Resources"msgstr "资源"#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsx#: src/components/DocumentErrorBoundary.tsx+#: src/components/RestartServerButton.tsx#: src/presence/use-sync-toasts.tsmsgid "Restart server"msgstr "重启服务器"@@ -11054,7 +11054,6 @@ msgid "Restarted — now running v{appRuntime}."msgstr "已重启——现在运行的是 v{appRuntime}。"#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsxmsgid "Restarting"msgstr "正在重启"diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.poindex 4d57039be..b1467ad75 100644--- a/packages/app/src/locales/zh-Hant/messages.po+++ b/packages/app/src/locales/zh-Hant/messages.po@@ -11035,8 +11035,8 @@ msgid "Resources"msgstr "資源"#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsx#: src/components/DocumentErrorBoundary.tsx+#: src/components/RestartServerButton.tsx#: src/presence/use-sync-toasts.tsmsgid "Restart server"msgstr "重新啟動伺服器"@@ -11054,7 +11054,6 @@ msgid "Restarted — now running v{appRuntime}."msgstr "已重新啟動——現在執行的是 v{appRuntime}。"#: src/components/BranchRecycleBanner.tsx-#: src/components/ConnectingBanner.tsxmsgid "Restarting"msgstr "正在重新啟動"diff --git a/packages/cli/README.md b/packages/cli/README.mdindex 8038e5df6..79519fba4 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -24,7 +24,7 @@ ok start # serve the editor and open it in your browser- `ok init` — turn a folder into an OpenKnowledge project and register the MCP server with supported AI tools.- `ok start` — run the local server and web editor, then open it in your browser.-- `ok open <file.md>` — open a single Markdown file in the editor.+- `ok open <target>` — open a doc, a folder, or a path to a Markdown file in the editor. It prints the project root it resolved; pass `--project <dir>` anywhere in the command to name one yourself.- `ok --help` — list every command.## Desktop appdiff --git a/packages/cli/src/cli-logger.test.ts b/packages/cli/src/cli-logger.test.tsnew file mode 100644index 000000000..daa36fb3b--- /dev/null+++ b/packages/cli/src/cli-logger.test.ts@@ -0,0 +1,46 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import { resolveLogProject } from './cli-logger.ts';++const cleanups: string[] = [];+function tmp(prefix: string): string {+ const dir = mkdtempSync(join(tmpdir(), prefix));+ cleanups.push(dir);+ return dir;+}+function makeProject(root: string): void {+ mkdirSync(join(root, '.ok'), { recursive: true });+ writeFileSync(join(root, '.ok', 'config.yml'), 'content:\n dir: .\n', 'utf-8');+}++afterEach(() => {+ for (const d of cleanups.splice(0)) rmSync(d, { recursive: true, force: true });+});++describe('resolveLogProject', () => {+ test('a configured project name wins', () => {+ const root = tmp('ok-log-named-');+ makeProject(root);+ expect(resolveLogProject(root, 'my-kb')).toBe('my-kb');+ });++ test('inside a project with no name → the resolved project root, not a placeholder', () => {+ const root = tmp('ok-log-root-');+ makeProject(root);+ const sub = join(root, 'a', 'b');+ mkdirSync(sub, { recursive: true });+ expect(resolveLogProject(sub)).toBe(root);+ });++ test('outside any project → undefined (the record carries no false project)', () => {+ expect(resolveLogProject(tmp('ok-log-bare-'))).toBeUndefined();+ });++ test('an empty configured name falls through to the resolved root', () => {+ const root = tmp('ok-log-empty-');+ makeProject(root);+ expect(resolveLogProject(root, '')).toBe(root);+ });+});diff --git a/packages/cli/src/cli-logger.ts b/packages/cli/src/cli-logger.tsnew file mode 100644index 000000000..311197f0c--- /dev/null+++ b/packages/cli/src/cli-logger.ts@@ -0,0 +1,53 @@+/**+ * Process-wide holder for the CLI's pino file logger (`~/.ok/logs/cli.*.log`).+ *+ * Lives outside `cli.ts` for two reasons: the bare `ok <file>` argv+ * pre-dispatch runs BEFORE Commander's `preAction` hook and must still be+ * instrumented, and command modules (`stop.ts`) need the logger without+ * importing the entry point back (an import cycle).+ */++import { createFileLogger, findEnclosingProjectRoot } from '@inkeep/open-knowledge-server';+import type { Logger as PinoLoggerInstance } from 'pino';++let cliLogger: PinoLoggerInstance | undefined;++export function getCliLogger(): PinoLoggerInstance | undefined {+ return cliLogger;+}++/**+ * The `project` field stamped on every record. A configured project name wins;+ * otherwise the enclosing project root identifies the project the command+ * actually acted on — the previous `<no-project>` placeholder was stamped even+ * for commands run inside a project.+ */+export function resolveLogProject(cwd: string, configuredName?: string): string | undefined {+ if (configuredName !== undefined && configuredName.length > 0) return configuredName;+ try {+ return findEnclosingProjectRoot(cwd)?.rootPath;+ } catch {+ return undefined;+ }+}++export interface InitCliLoggerOptions {+ /** Subcommand name, or a synthetic name for the pre-dispatch entry points. */+ command: string;+ cwd: string;+ /** Configured `project.name`, when the command loaded a project config. */+ configuredProjectName?: string;+}++/**+ * Create (or re-create) the CLI file logger and emit the invocation record.+ * The pre-dispatch path exits before Commander runs, so exactly one of the two+ * entry points calls this per invocation.+ */+export function initCliLogger(opts: InitCliLoggerOptions): PinoLoggerInstance {+ const project = resolveLogProject(opts.cwd, opts.configuredProjectName);+ const logger = createFileLogger({ name: 'cli', project });+ cliLogger = logger;+ logger.info({ command: opts.command, cwd: opts.cwd, project }, 'cli command started');+ return logger;+}diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.tsindex c3033e192..ffa856716 100644--- a/packages/cli/src/cli.ts+++ b/packages/cli/src/cli.ts@@ -34,6 +34,7 @@ import { type Config, ConfigSchema, trustSystemCertificates } from '@inkeep/open* Config loaded via preAction hook: CLI > ENV > project > user > Zod defaults.*/import { Command } from 'commander';+import { getCliLogger, initCliLogger } from './cli-logger.ts';import { auditCommand } from './commands/audit.ts';import { authCommand } from './commands/auth/index.ts';import { bugReportCommand } from './commands/bug-report.ts';@@ -58,11 +59,7 @@ import { repairSkillsCommand } from './commands/repair-skills.ts';import { seedCommand } from './commands/seed.ts';import { shareCommand } from './commands/share/index.ts';import { sharingCommand } from './commands/sharing/index.ts';-import {- decideSingleFileTarget,- isFileishTarget,- scanRootArgv,-} from './commands/single-file-dispatch.ts';+import { isFileishTarget, resolveRootDispatch } from './commands/single-file-dispatch.ts';import { createRealSingleFileOpenDeps, runSingleFileOpen } from './commands/single-file-open.ts';import { skillsCommand } from './commands/skills.ts';import { runStartCommand, startCommand } from './commands/start.ts';@@ -77,17 +74,8 @@ import { buildVersionNotice } from './version-notice.ts';const program = new Command();-import { createFileLogger } from '@inkeep/open-knowledge-server';--import type { Logger as PinoLoggerInstance } from 'pino';-// Shared state populated by preAction hooklet resolvedConfig: Config;-let cliLogger: PinoLoggerInstance | undefined;--export function getCliLogger(): PinoLoggerInstance | undefined {- return cliLogger;-}program.name('open-knowledge')@@ -193,11 +181,11 @@ programresolvedConfig = config;const commandName = thisCommand.args?.[0] ?? thisCommand.name() ?? 'cli';- cliLogger = createFileLogger({- name: 'cli',- project: (config as { project?: { name?: string } }).project?.name ?? undefined,+ initCliLogger({+ command: commandName,+ cwd: process.cwd(),+ configuredProjectName: (config as { project?: { name?: string } }).project?.name ?? undefined,});- cliLogger.info({ command: commandName, cwd: process.cwd() }, 'cli command started');});// `ok` (no positional args) — desktop dispatch with fallback to start.@@ -362,21 +350,25 @@ Examples:// ext-less `ok open <doc>` contract untouched). Everything else falls through// to Commander unchanged.{- const scanned = scanRootArgv(process.argv.slice(2));- if (!scanned.sawTerminalFlag) {- const baseDir = scanned.cwd ? resolve(scanned.cwd) : process.cwd();- const knownSubcommands = new Set(program.commands.map((c) => c.name()));- const target = decideSingleFileTarget(scanned.operands, {- knownSubcommands,- isFileish: (t) => isFileishTarget(resolve(baseDir, t), t),+ const dispatch = resolveRootDispatch(process.argv.slice(2), {+ knownSubcommands: new Set(program.commands.map((c) => c.name())),+ cwd: process.cwd(),+ isFileish: isFileishTarget,+ resolvePath: (base, token) => resolve(base, token),+ });+ if (dispatch !== null) {+ // This path exits before Commander's preAction hook runs, so it owns its+ // own logger creation — otherwise the one route that diverts here is the+ // one route that leaves no file-log record.+ initCliLogger({ command: 'open-file', cwd: process.cwd() });+ getCliLogger()?.info(+ { file: dispatch.absPath, projectOverride: dispatch.projectRoot },+ 'single-file open dispatch',+ );+ const code = await runSingleFileOpen(dispatch.absPath, createRealSingleFileOpenDeps(), {+ projectRoot: dispatch.projectRoot ?? undefined,});- if (target !== null) {- const code = await runSingleFileOpen(- resolve(baseDir, target),- createRealSingleFileOpenDeps(),- );- process.exit(code);- }+ process.exit(code);}}diff --git a/packages/cli/src/commands/bug-report.ts b/packages/cli/src/commands/bug-report.tsindex 3ec51cf25..19be6b26a 100644--- a/packages/cli/src/commands/bug-report.ts+++ b/packages/cli/src/commands/bug-report.ts@@ -1,5 +1,5 @@import { Command } from 'commander';-import { getCliLogger } from '../cli.ts';+import { getCliLogger } from '../cli-logger.ts';import { collectReportBundle } from '../report-bundle.ts';import { defaultBugReportZipPath } from './bug-report-bundle.ts';import { revealBundle } from './bug-report-reveal.ts';diff --git a/packages/cli/src/commands/deinit.test.ts b/packages/cli/src/commands/deinit.test.tsindex 135c80d44..b66fd6267 100644--- a/packages/cli/src/commands/deinit.test.ts+++ b/packages/cli/src/commands/deinit.test.ts@@ -227,3 +227,115 @@ describe('runDeinit — refuses the home directory', () => {}});});++describe('runDeinit attached-client disclosure', () => {+ test('names attached clients in the plan without gating the removal', async () => {+ const dir = seedProject();+ try {+ const result = await runDeinit({+ cwd: dir,+ home: dirname(dir),+ dryRun: true,+ probeClients: async () => 2,+ });+ expect(result.status).toBe('dry-run');+ expect(result.exitCode).toBe(0);+ expect(result.message).toContain('2 collaboration clients');+ expect(result.message).toContain('restarting will NOT recover them');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('no disclosure line when nothing is attached', async () => {+ const dir = seedProject();+ try {+ const result = await runDeinit({+ cwd: dir,+ home: dirname(dir),+ dryRun: true,+ probeClients: async () => 0,+ });+ expect(result.message).not.toContain('collaboration client');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('--json --dry-run carries the probe result', async () => {+ const dir = seedProject();+ try {+ const result = await runDeinit({+ cwd: dir,+ home: dirname(dir),+ dryRun: true,+ json: true,+ probeClients: async () => 2,+ });+ const json = JSON.parse(result.message);+ expect(json.mode).toBe('dry-run');+ expect(json.attachedClients).toHaveLength(1);+ expect(json.attachedClients[0]).toContain('2 collaboration clients');+ expect(json.attachedClients[0]).toContain('restarting will NOT recover them');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('--json --dry-run reports an empty probe result when nothing is attached', async () => {+ const dir = seedProject();+ try {+ const result = await runDeinit({+ cwd: dir,+ home: dirname(dir),+ dryRun: true,+ json: true,+ probeClients: async () => 0,+ });+ expect(JSON.parse(result.message).attachedClients).toEqual([]);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('--json --yes carries the probe result on the applied outcome too', async () => {+ const dir = seedProject();+ try {+ const result = await runDeinit({+ cwd: dir,+ home: dirname(dir),+ yes: true,+ json: true,+ probeClients: async () => 3,+ runRemovalDeps: {+ stopServer: async () => ({ stopped: 1, failed: [] }),+ },+ });+ const json = JSON.parse(result.message);+ expect(json.mode).toBe('applied');+ expect(json.attachedClients).toHaveLength(1);+ expect(json.attachedClients[0]).toContain('3 collaboration clients');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('--yes still removes with clients attached (disclosure, not a gate)', async () => {+ const dir = seedProject();+ try {+ const result = await runDeinit({+ cwd: dir,+ home: dirname(dir),+ yes: true,+ probeClients: async () => 4,+ runRemovalDeps: {+ stopServer: async () => ({ stopped: 1, failed: [] }),+ },+ });+ expect(result.status).toBe('done');+ expect(existsSync(join(dir, '.ok'))).toBe(false);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/packages/cli/src/commands/deinit.ts b/packages/cli/src/commands/deinit.tsindex 24e8e3cc9..69cf6336f 100644--- a/packages/cli/src/commands/deinit.ts+++ b/packages/cli/src/commands/deinit.ts@@ -11,9 +11,14 @@ import { homedir } from 'node:os';import { join, resolve } from 'node:path';import { isHomeDir } from '@inkeep/open-knowledge-server';import { Command } from 'commander';-import { accent, dim, error as errorColor } from '../ui/colors.ts';+import { accent, dim, error as errorColor, warning } from '../ui/colors.ts';import { confirmDestructive } from '../ui/confirm.ts';-import { buildDeinitPlan, type RunRemovalDeps, runRemoval } from './removal-plan.ts';+import {+ buildDeinitPlan,+ describeAttachedClients,+ type RunRemovalDeps,+ runRemoval,+} from './removal-plan.ts';import {formatRemovalOutcome,formatRemovalPlan,@@ -30,6 +35,8 @@ export interface DeinitOptions {json?: boolean;/** Test-only stdin override for the confirmation prompt. */confirmStream?: NodeJS.ReadableStream;+ /** Live-client probe seam (hits the running server over HTTP in production). */+ probeClients?: (lockDir: string) => Promise<number | null>;/** Test-only: stub the machine-touching removal primitives (stop-server, etc.)* so the failed-exit branch is exercisable without real side effects. */runRemovalDeps?: RunRemovalDeps;@@ -77,13 +84,16 @@ export async function runDeinit(opts: DeinitOptions = {}): Promise<DeinitResult>}const plan = buildDeinitPlan(projectRoot, home);+ const attached = await describeAttachedClients(plan, opts.probeClients);+ const attachedBlock =+ attached.length > 0 ? `\n\n${attached.map((l) => warning(l)).join('\n')}` : '';if (opts.dryRun) {return {status: 'dry-run',message: opts.json- ? JSON.stringify(removalPlanToJson(plan), null, 2)- : `${accent('Would remove (dry-run — no changes made):')}\n\n${formatRemovalPlan(plan)}`,+ ? JSON.stringify(removalPlanToJson(plan, attached), null, 2)+ : `${accent('Would remove (dry-run — no changes made):')}\n\n${formatRemovalPlan(plan)}${attachedBlock}`,exitCode: 0,};}@@ -98,7 +108,7 @@ export async function runDeinit(opts: DeinitOptions = {}): Promise<DeinitResult>if (!opts.yes) {process.stderr.write(- `${accent(`Remove OpenKnowledge from ${projectRoot}:`)}\n\n${formatRemovalPlan(plan)}\n\n`,+ `${accent(`Remove OpenKnowledge from ${projectRoot}:`)}\n\n${formatRemovalPlan(plan)}${attachedBlock}\n\n`,);const confirmed = await confirmDestructive(`${accent('Remove these?')} ${dim('[y/N] ')}`,@@ -113,7 +123,7 @@ export async function runDeinit(opts: DeinitOptions = {}): Promise<DeinitResult>return {status: outcome.failed.length > 0 ? 'failed' : 'done',message: opts.json- ? JSON.stringify(removalOutcomeToJson('deinit', outcome), null, 2)+ ? JSON.stringify(removalOutcomeToJson('deinit', outcome, attached), null, 2): formatRemovalOutcome(outcome),exitCode: outcome.failed.length > 0 ? 1 : 0,};diff --git a/packages/cli/src/commands/open.test.ts b/packages/cli/src/commands/open.test.tsindex ff2a03980..e76f3379d 100644--- a/packages/cli/src/commands/open.test.ts+++ b/packages/cli/src/commands/open.test.ts@@ -20,6 +20,9 @@ function makeDeps(overrides: Partial<OpenDeps> = {}): {opened.push(t);return { ok: true };},+ findAncestorProject: () => null,+ isProjectRoot: () => true,+ enclosingProject: () => null,log: (m) => logs.push(m),error: (m) => errors.push(m),...overrides,@@ -244,3 +247,173 @@ describe('createRealOpenDeps wiring', () => {expect(deps.detectBundlePath()).toBe('/Applications/OpenKnowledge.app');});});++describe('resolved-project disclosure', () => {+ test('doc open names the absolute project root', async () => {+ const { deps, logs } = makeDeps({+ detectBundlePath: () => '/Applications/OpenKnowledge.app',+ });+ const code = await runOpen('specs/foo/SPEC', { project: '/abs/proj' }, deps);+ expect(code).toBe(0);+ expect(logs).toContain('Project: /abs/proj');+ });++ test('folder open names the absolute project root', async () => {+ const { deps, logs } = makeDeps({+ detectBundlePath: () => null,+ resolveBaseUrl: () => 'http://localhost:5173',+ classifyName: () => 'folder',+ });+ const code = await runOpen('specs/foo', { project: '/abs/proj' }, deps);+ expect(code).toBe(0);+ expect(logs).toContain('Project: /abs/proj');+ });++ test('skill open names the absolute project root', async () => {+ const { deps, logs } = makeDeps({+ detectBundlePath: () => '/Applications/OpenKnowledge.app',+ });+ const code = await runOpen('my-skill', { skill: true, project: '/abs/proj' }, deps);+ expect(code).toBe(0);+ expect(logs).toContain('Project: /abs/proj');+ });++ test('a failed open discloses nothing (no false project claim)', async () => {+ const { deps, logs } = makeDeps({+ detectBundlePath: () => '/Applications/OpenKnowledge.app',+ openTarget: async () => ({ ok: false, reason: 'not-installed' }),+ });+ const code = await runOpen('doc', { project: '/abs/proj' }, deps);+ expect(code).toBe(1);+ expect(logs).toEqual([]);+ });++ test('a nested project root names BOTH roots, once', async () => {+ const { deps, logs } = makeDeps({+ detectBundlePath: () => '/Applications/OpenKnowledge.app',+ findAncestorProject: () => '/abs',+ });+ const code = await runOpen('doc', { project: '/abs/nested' }, deps);+ expect(code).toBe(0);+ const nested = logs.filter((l) => l.startsWith('Note:'));+ expect(nested).toHaveLength(1);+ expect(nested[0]).toContain('/abs/nested');+ expect(nested[0]).toContain('/abs');+ });++ test('a non-nested project root says nothing extra', async () => {+ const { deps, logs } = makeDeps({+ detectBundlePath: () => '/Applications/OpenKnowledge.app',+ findAncestorProject: () => null,+ });+ await runOpen('doc', { project: '/abs/proj' }, deps);+ expect(logs.filter((l) => l.startsWith('Note:'))).toHaveLength(0);+ });+});++describe('explicit --project validation', () => {+ test('refuses an override that does not name a project, without opening anything', async () => {+ const { deps, opened, errors } = makeDeps({+ detectBundlePath: () => '/Applications/OpenKnowledge.app',+ isProjectRoot: () => false,+ });+ const code = await runOpen('README', { project: '/tmp/not-a-project' }, deps);+ expect(code).toBe(1);+ expect(opened).toEqual([]);+ expect(errors.join('\n')).toContain('not an OpenKnowledge project');+ });++ test('honors an override that does name a project', async () => {+ const { deps, opened } = makeDeps({+ detectBundlePath: () => '/Applications/OpenKnowledge.app',+ isProjectRoot: () => true,+ });+ const code = await runOpen('README', { project: '/tmp/real-project' }, deps);+ expect(code).toBe(0);+ expect(opened[0]).toContain(encodeURIComponent('/tmp/real-project'));+ });++ test('an absent override keeps the cwd default and is never validated', async () => {+ let consulted = false;+ const { deps, logs } = makeDeps({+ detectBundlePath: () => '/Applications/OpenKnowledge.app',+ isProjectRoot: () => {+ consulted = true;+ return false;+ },+ });+ const code = await runOpen('README', {}, deps);+ expect(code).toBe(0);+ expect(consulted).toBe(false);+ // No project encloses the cwd here, so the fallback directory must not be+ // reported as one.+ expect(logs.filter((l) => l.startsWith('Project:'))).toHaveLength(0);+ expect(logs.join('\n')).toContain('not an OpenKnowledge project');+ });+});++describe('running outside any project', () => {+ test('does not call the cwd fallback a project', async () => {+ const { deps, logs } = makeDeps({+ detectBundlePath: () => '/Applications/OpenKnowledge.app',+ enclosingProject: () => null,+ });+ const code = await runOpen('notes', {}, deps);+ expect(code).toBe(0);+ expect(logs.some((l) => l.startsWith('Project:'))).toBe(false);+ expect(logs.some((l) => l.startsWith('Working directory:'))).toBe(true);+ });++ test('does not derive a nested-project note from a non-project directory', async () => {+ const { deps, logs } = makeDeps({+ detectBundlePath: () => '/Applications/OpenKnowledge.app',+ enclosingProject: () => null,+ // A real project DOES sit above the cwd, but the cwd is not a project, so+ // there is no nesting to report.+ findAncestorProject: () => '/repo/root',+ });+ await runOpen('notes', {}, deps);+ expect(logs.filter((l) => l.startsWith('Note:'))).toHaveLength(0);+ });+});++describe('running from a subdirectory of a project', () => {+ test('acts on the enclosing project, not the subdirectory it was run from', async () => {+ const { deps, opened, logs } = makeDeps({+ detectBundlePath: () => '/Applications/OpenKnowledge.app',+ // cwd is <root>/specs; the project is <root>.+ enclosingProject: () => '/repo/root',+ findAncestorProject: () => null,+ });+ const code = await runOpen('notes', {}, deps);+ expect(code).toBe(0);+ expect(opened[0]).toContain(encodeURIComponent('/repo/root'));+ expect(logs.join('\n')).toContain('/repo/root');+ });++ test('does not claim a nested topology just because it ran below the root', async () => {+ const { deps, logs } = makeDeps({+ detectBundlePath: () => '/Applications/OpenKnowledge.app',+ enclosingProject: () => '/repo/root',+ // Nothing encloses the real project root.+ findAncestorProject: () => null,+ });+ await runOpen('notes', {}, deps);+ expect(logs.join('\n').toLowerCase()).not.toContain('nested');+ });++ test('an explicit --project is never overridden by the cwd lookup', async () => {+ let consulted = false;+ const { deps, opened } = makeDeps({+ detectBundlePath: () => '/Applications/OpenKnowledge.app',+ enclosingProject: () => {+ consulted = true;+ return '/repo/root';+ },+ isProjectRoot: () => true,+ });+ await runOpen('notes', { project: '/other/project' }, deps);+ expect(consulted).toBe(false);+ expect(opened[0]).toContain(encodeURIComponent('/other/project'));+ });+});diff --git a/packages/cli/src/commands/open.ts b/packages/cli/src/commands/open.tsindex e0e5f609b..78a6eb349 100644--- a/packages/cli/src/commands/open.ts+++ b/packages/cli/src/commands/open.ts@@ -28,12 +28,13 @@* platform-native URL handler rather than `launchDesktop`.*/import { statSync } from 'node:fs';-import { join, resolve } from 'node:path';+import { dirname, join, resolve } from 'node:path';import { MANAGED_ARTIFACT_SCOPES, type SkillScope } from '@inkeep/open-knowledge-core';import {encodeDocName,encodeFolderRoute,encodeSkillRoute,+ findEnclosingProjectRoot,resolveLockDir,resolveUiInfo,} from '@inkeep/open-knowledge-server';@@ -68,6 +69,28 @@ export interface OpenDeps {classifyName: (projectDir: string, name: string) => 'doc' | 'folder';/** Hand a URL or `openknowledge://` deep link to the OS to open. */openTarget: (target: string) => Promise<SpawnDetachedScrubbedOutcome>;+ /**+ * Nearest project root STRICTLY above `projectDir`, or null. Drives the+ * nested-project disclosure — a resolved root that sits inside another+ * project is the topology behind silent misrouting, so it is named rather+ * than left for a second command to discover.+ */+ findAncestorProject: (projectDir: string) => string | null;+ /**+ * True when `dir` is itself an OpenKnowledge project root. Only consulted for+ * an EXPLICIT `--project`: an override that names a non-project must fail+ * loudly, because proceeding would open a different project than the caller+ * asked for and report success while doing it.+ */+ isProjectRoot: (dir: string) => boolean;+ /**+ * The project root enclosing `dir`, or `dir` itself when it is one; null when+ * no project encloses it. Used for the cwd default: running from a+ * subdirectory of a project must act on the PROJECT, not on the+ * subdirectory, which is neither a valid deep-link target nor a truthful+ * thing to print.+ */+ enclosingProject: (dir: string) => string | null;log: (message: string) => void;error: (message: string) => void;}@@ -103,6 +126,10 @@ export function createRealOpenDeps(}},openTarget: openTargetReal,+ findAncestorProject: (projectDir) =>+ findEnclosingProjectRoot(dirname(resolve(projectDir)))?.rootPath ?? null,+ isProjectRoot: (dir) => findEnclosingProjectRoot(dir)?.distance === 0,+ enclosingProject: (dir) => findEnclosingProjectRoot(resolve(dir))?.rootPath ?? null,log: (message) => process.stdout.write(`${message}\n`),error: (message) => process.stderr.write(`${message}\n`),};@@ -122,9 +149,22 @@ function noTargetError(deps: OpenDeps): number {return 1;}+/**+ * The one reporting point for every CLI open entry point (subcommand and the+ * bare-file dispatch, which routes through `runOpen`): the resolved absolute+ * directory is named on success so no caller can drift into opening silently,+ * and a nested resolution names both roots once.+ *+ * `isProject` is threaded rather than re-derived: the caller already knows+ * whether the directory is a project root, and calling it a "project" when it+ * is only a cwd fallback is the same class of confidently-wrong output this+ * surface exists to prevent.+ */async function openAndReport(target: string,successMessage: string,+ projectDir: string,+ isProject: boolean,deps: OpenDeps,): Promise<number> {const outcome = await deps.openTarget(target);@@ -133,6 +173,21 @@ async function openAndReport(return 1;}deps.log(successMessage);+ // Nothing encloses the working directory, so there is no project to name and+ // no nesting to describe — a nested-project note derived from a non-project+ // would assert a topology that does not exist.+ if (!isProject) {+ deps.log(`Working directory: ${projectDir} (not an OpenKnowledge project).`);+ return 0;+ }+ deps.log(`Project: ${projectDir}`);+ const ancestor = deps.findAncestorProject(projectDir);+ if (ancestor !== null) {+ deps.log(+ `Note: this project (${projectDir}) is nested inside another OpenKnowledge project at ${ancestor}. ` ++ 'Pass --project to choose explicitly.',+ );+ }return 0;}@@ -144,9 +199,31 @@ async function openAndReport(* lands on the renderer route, which resolves missing targets.*/export async function runOpen(name: string, options: OpenOptions, deps: OpenDeps): Promise<number> {- const projectDir = resolve(options.project ?? process.cwd());+ // An explicit override is taken as given (and validated below). Otherwise+ // resolve the project that ENCLOSES the working directory: `ok open` is+ // routinely run from a subdirectory, and treating that subdirectory as the+ // project both misroutes the deep link and makes the disclosure line — and+ // the nested-project note derived from it — untrue.+ const explicitProject = options.project !== undefined;+ const cwdProject = explicitProject ? null : deps.enclosingProject(process.cwd());+ const projectDir = resolve(options.project ?? cwdProject ?? process.cwd());+ // An explicit override is validated as a project root below; a cwd default is+ // one only when a project actually encloses the working directory. Everything+ // else is a bare directory, and the reporting must not claim otherwise.+ const isProject = explicitProject || cwdProject !== null;const cleanName = name.replace(/\/+$/, '');+ // An explicit override that does not name a project is refused rather than+ // silently resolved elsewhere — a wrong project that reports success is the+ // failure this whole surface exists to prevent. An absent override keeps the+ // cwd default, which resolves normally.+ if (explicitProject && !deps.isProjectRoot(projectDir)) {+ deps.error(+ `Cannot open with --project ${projectDir}: no .ok/config.yml there, so it is not an OpenKnowledge project.`,+ );+ return 1;+ }+if (!cleanName) {deps.error('Nothing to open: pass a doc, folder, or skill name (e.g. `ok open specs/foo/SPEC`).',@@ -186,6 +263,8 @@ export async function runOpen(name: string, options: OpenOptions, deps: OpenDepsreturn openAndReport(deepLink,`Opening skill ${cleanName} (${scope}) in the OpenKnowledge desktop app.`,+ projectDir,+ isProject,deps,);}@@ -195,6 +274,8 @@ export async function runOpen(name: string, options: OpenOptions, deps: OpenDepsreturn openAndReport(url,`Opening skill ${cleanName} (${scope}) in your browser: ${url}`,+ projectDir,+ isProject,deps,);}@@ -213,13 +294,21 @@ export async function runOpen(name: string, options: OpenOptions, deps: OpenDepsreturn openAndReport(deepLink,`Opening folder ${cleanName} in the OpenKnowledge desktop app.`,+ projectDir,+ isProject,deps,);}const baseUrl = deps.resolveBaseUrl(projectDir);if (baseUrl) {const url = `${baseUrl}/#/${encodeFolderRoute(cleanName)}`;- return openAndReport(url, `Opening folder ${cleanName} in your browser: ${url}`, deps);+ return openAndReport(+ url,+ `Opening folder ${cleanName} in your browser: ${url}`,+ projectDir,+ isProject,+ deps,+ );}return noTargetError(deps);}@@ -229,12 +318,24 @@ export async function runOpen(name: string, options: OpenOptions, deps: OpenDepsconst deepLink = `openknowledge://open?project=${encodeURIComponent(projectDir,)}&doc=${encodeURIComponent(cleanName)}`;- return openAndReport(deepLink, `Opening ${cleanName} in the OpenKnowledge desktop app.`, deps);+ return openAndReport(+ deepLink,+ `Opening ${cleanName} in the OpenKnowledge desktop app.`,+ projectDir,+ isProject,+ deps,+ );}const baseUrl = deps.resolveBaseUrl(projectDir);if (baseUrl) {const url = `${baseUrl}/#/${encodeDocName(cleanName)}`;- return openAndReport(url, `Opening ${cleanName} in your browser: ${url}`, deps);+ return openAndReport(+ url,+ `Opening ${cleanName} in your browser: ${url}`,+ projectDir,+ isProject,+ deps,+ );}return noTargetError(deps);}@@ -255,7 +356,10 @@ export function openCommand(): Command {`Skill scope when --skill is set: ${MANAGED_ARTIFACT_SCOPES.join(' | ')}`,'project',)- .option('--project <dir>', 'Project root (defaults to the current directory)')+ .option(+ '--project <dir>',+ 'Project root (defaults to the project enclosing the current directory)',+ ).action(async (name: string, options: OpenOptions) => {process.exitCode = await runOpen(name, options, createRealOpenDeps());});diff --git a/packages/cli/src/commands/removal-plan.test.ts b/packages/cli/src/commands/removal-plan.test.tsindex f87866812..d6c739994 100644--- a/packages/cli/src/commands/removal-plan.test.ts+++ b/packages/cli/src/commands/removal-plan.test.ts@@ -21,6 +21,7 @@ import {applicationDataOps,buildUninstallPlan,deinitOps,+ describeAttachedClients,type RunRemovalDeps,runRemoval,type UninstallPlanInput,@@ -646,3 +647,27 @@ describe('pi trust revocation surfaces through the removal plan', () => {}});});++describe('describeAttachedClients', () => {+ const plan = { scope: 'deinit' as const, ops: deinitOps('/proj', '/home/u') };++ test('names the attached clients and that restart will not recover them', async () => {+ const lines = await describeAttachedClients(plan, async () => 3);+ expect(lines).toHaveLength(1);+ expect(lines[0]).toContain('3 collaboration clients');+ expect(lines[0]).toContain('restarting will NOT recover them');+ });++ test('says nothing when no clients are attached', async () => {+ expect(await describeAttachedClients(plan, async () => 0)).toEqual([]);+ });++ test('says nothing when the server cannot be reached', async () => {+ expect(await describeAttachedClients(plan, async () => null)).toEqual([]);+ });++ test('disclosure does not gate: the stop op stays in the plan', async () => {+ await describeAttachedClients(plan, async () => 2);+ expect(plan.ops.filter((op) => op.kind === 'stop-server')).toHaveLength(1);+ });+});diff --git a/packages/cli/src/commands/removal-plan.ts b/packages/cli/src/commands/removal-plan.tsindex 5d2054297..b3e5dd8c7 100644--- a/packages/cli/src/commands/removal-plan.ts+++ b/packages/cli/src/commands/removal-plan.ts@@ -51,7 +51,7 @@ import { ALL_EDITOR_IDS, EDITOR_TARGETS, type EditorId } from './editors.ts';import { existingFileMode } from './jsonc-surgical.ts';import { removeOwnLaunchEntry } from './launch-json-removal.ts';import { removeOwnMcpEntry } from './mcp-config-removal.ts';-import { runStop } from './stop.ts';+import { probeCollabClients, runStop } from './stop.ts';// ---------------------------------------------------------------------------// Op model@@ -465,10 +465,10 @@ export interface RunRemovalDeps {* (EPERM, etc.) by return value, not by throwing, so the executor must inspect* `failed` to avoid deleting files out from under a still-running server.*/- stopServer?: (lockDir: string) => {+ stopServer?: (lockDir: string) => Promise<{stopped: number;failed: Array<{ pid: number; error: string }>;- };+ }>;}/**@@ -483,8 +483,11 @@ export async function runRemoval(const clearEmbeddingsKey = deps.clearEmbeddingsKey ?? clearAllEmbeddingsKeys;const stopServer =deps.stopServer ??- ((lockDir: string) => {- const outcome = runStop({ lockDir, log: () => {}, error: () => {} });+ (async (lockDir: string) => {+ // `force` because the removal verbs disclose attached clients in the plan+ // the user already confirmed; a second refusal here would double-prompt+ // one decision.+ 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 })),@@ -511,12 +514,37 @@ export async function runRemoval(};}+/**+ * One line per server in the plan that still has clients attached, for the+ * plan the user confirms. Disclosure only — `deinit`/`uninstall` remove the+ * `.ok/` those windows depend on, so a restart cannot bring them back and a+ * second confirmation would only re-ask the decision the plan prompt asks.+ */+export async function describeAttachedClients(+ plan: RemovalPlan,+ probe: (lockDir: string) => Promise<number | null> = probeCollabClients,+): Promise<string[]> {+ const lines: string[] = [];+ for (const op of plan.ops) {+ if (op.kind !== 'stop-server') continue;+ const clients = await probe(op.lockDir);+ if (clients === null || clients === 0) continue;+ lines.push(+ `${clients} collaboration client${clients === 1 ? '' : 's'} ` ++ `(editor window${clients === 1 ? '' : 's'} or agents) ${clients === 1 ? 'is' : 'are'} ` ++ `connected to the server at ${op.lockDir}. Those windows will stop working, and ` ++ 'restarting will NOT recover them — this removes the project state they depend on.',+ );+ }+ return lines;+}+type ResolvedDeps = Required<RunRemovalDeps>;async function executeOp(op: RemovalOp, deps: ResolvedDeps): Promise<RemovalOpResult> {switch (op.kind) {case 'stop-server': {- const { stopped, failed } = deps.stopServer(op.lockDir);+ const { stopped, failed } = await deps.stopServer(op.lockDir);if (failed.length > 0) {// A SIGTERM that failed (EPERM, foreign-host live PID) means a process// may still be holding the files this run is about to remove. Surface itdiff --git a/packages/cli/src/commands/removal-render.ts b/packages/cli/src/commands/removal-render.tsindex 6e2c006d9..db6b2f8fa 100644--- a/packages/cli/src/commands/removal-render.ts+++ b/packages/cli/src/commands/removal-render.ts@@ -83,28 +83,41 @@ interface RemovalItem {* removed, under `planned`) distinct from an applied OUTCOME (what actually* happened, under `removed`/`skipped`/`failed`) — so a consumer never confuses* "these are the ops I intend to run" with "these ops succeeded".+ *+ * `attachedClients` carries the live-client probe on BOTH modes, empty when+ * nothing is attached. The human-readable path warns that those editor windows+ * stop working and that restarting will not recover them; a machine consumer+ * that only reads the removal lists would otherwise never learn it.*/export type RemovalJson =- | { scope: 'uninstall' | 'deinit'; mode: 'dry-run'; planned: RemovalItem[] }+ | {+ scope: 'uninstall' | 'deinit';+ mode: 'dry-run';+ planned: RemovalItem[];+ attachedClients: string[];+ }| {scope: 'uninstall' | 'deinit';mode: 'applied';removed: RemovalItem[];skipped: RemovalItem[];failed: RemovalItem[];+ attachedClients: string[];};-export function removalPlanToJson(plan: RemovalPlan): RemovalJson {+export function removalPlanToJson(plan: RemovalPlan, attachedClients: string[] = []): RemovalJson {return {scope: plan.scope,mode: 'dry-run',planned: plan.ops.map((op) => ({ kind: op.kind, label: op.label })),+ attachedClients,};}export function removalOutcomeToJson(scope: 'uninstall' | 'deinit',outcome: RemovalOutcome,+ attachedClients: string[] = [],): RemovalJson {return {scope,@@ -118,5 +131,6 @@ export function removalOutcomeToJson(.filter((r) => r.status === 'skipped').map((r) => ({ kind: r.op.kind, label: r.op.label, detail: r.detail })),failed: outcome.failed.map((r) => ({ kind: r.op.kind, label: r.op.label, detail: r.detail })),+ attachedClients,};}diff --git a/packages/cli/src/commands/single-file-dispatch.test.ts b/packages/cli/src/commands/single-file-dispatch.test.tsindex 4e5e68e6d..977f110d0 100644--- a/packages/cli/src/commands/single-file-dispatch.test.ts+++ b/packages/cli/src/commands/single-file-dispatch.test.ts@@ -6,6 +6,7 @@ import {decideSingleFileTarget,hasMarkdownExtension,isFileishTarget,+ resolveRootDispatch,scanRootArgv,} from './single-file-dispatch.ts';@@ -131,3 +132,118 @@ describe('isFileishTarget (fs-backed predicate)', () => {expect(isFileishTarget(join(dir, 'nope'), 'nope')).toBe(false);});});++/**+ * The eight accepted shapes of an explicit project override: `--project <v>`+ * and `--project=<v>`, before or after the target, with and without a markdown+ * extension. Every one must resolve to the named root — a dropped override is+ * how a command silently acts on a different project.+ */+describe('--project override matrix', () => {+ const ROOT = '/abs/project';+ const combos: Array<{ name: string; argv: string[]; fileTarget: string | null }> = [+ {+ name: 'space syntax, flag before target, with extension',+ argv: ['open', '--project', ROOT, 'notes.md'],+ fileTarget: '/base/notes.md',+ },+ {+ name: 'space syntax, flag after target, with extension',+ argv: ['open', 'notes.md', '--project', ROOT],+ fileTarget: '/base/notes.md',+ },+ {+ name: 'equals syntax, flag before target, with extension',+ argv: ['open', `--project=${ROOT}`, 'notes.md'],+ fileTarget: '/base/notes.md',+ },+ {+ name: 'equals syntax, flag after target, with extension',+ argv: ['open', 'notes.md', `--project=${ROOT}`],+ fileTarget: '/base/notes.md',+ },+ {+ name: 'space syntax, flag before target, no extension',+ argv: ['open', '--project', ROOT, 'notes'],+ fileTarget: null,+ },+ {+ name: 'space syntax, flag after target, no extension',+ argv: ['open', 'notes', '--project', ROOT],+ fileTarget: null,+ },+ {+ name: 'equals syntax, flag before target, no extension',+ argv: ['open', `--project=${ROOT}`, 'notes'],+ fileTarget: null,+ },+ {+ name: 'equals syntax, flag after target, no extension',+ argv: ['open', 'notes', `--project=${ROOT}`],+ fileTarget: null,+ },+ ];++ for (const combo of combos) {+ test(`${combo.name} → project root is carried, never an operand`, () => {+ const scanned = scanRootArgv(combo.argv);+ expect(scanned.project).toBe(ROOT);+ // The flag value must never be mistaken for the thing to open.+ expect(scanned.operands).not.toContain(ROOT);++ const dispatch = resolveRootDispatch(combo.argv, {+ knownSubcommands: SUBCOMMANDS,+ cwd: '/base',+ isFileish: (_abs, token) => hasMarkdownExtension(token),+ resolvePath: (base, token) => (token.startsWith('/') ? token : `${base}/${token}`),+ });++ if (combo.fileTarget === null) {+ // Ext-less names stay with Commander's `open` subcommand, which reads+ // `--project` itself — the pre-dispatch must not divert them.+ expect(dispatch).toBeNull();+ expect(scanned.operands).toEqual(['open', 'notes']);+ } else {+ expect(dispatch).toEqual({ absPath: combo.fileTarget, projectRoot: ROOT });+ }+ });+ }++ test('a bare `ok <file> --project <dir>` carries the override too', () => {+ const dispatch = resolveRootDispatch(['notes.md', '--project', ROOT], {+ knownSubcommands: SUBCOMMANDS,+ cwd: '/base',+ isFileish: (_abs, token) => hasMarkdownExtension(token),+ resolvePath: (base, token) => (token.startsWith('/') ? token : `${base}/${token}`),+ });+ expect(dispatch).toEqual({ absPath: '/base/notes.md', projectRoot: ROOT });+ });++ test('no override → null project root (ancestor walk decides)', () => {+ const dispatch = resolveRootDispatch(['notes.md'], {+ knownSubcommands: SUBCOMMANDS,+ cwd: '/base',+ isFileish: (_abs, token) => hasMarkdownExtension(token),+ resolvePath: (base, token) => (token.startsWith('/') ? token : `${base}/${token}`),+ });+ expect(dispatch).toEqual({ absPath: '/base/notes.md', projectRoot: null });+ });++ test('--scope value is not mistaken for an operand', () => {+ expect(scanRootArgv(['open', '--skill', '--scope', 'user', 'my-skill']).operands).toEqual([+ 'open',+ 'my-skill',+ ]);+ });++ test('help/version still short-circuits the dispatch', () => {+ expect(+ resolveRootDispatch(['--help', 'notes.md'], {+ knownSubcommands: SUBCOMMANDS,+ cwd: '/base',+ isFileish: () => true,+ resolvePath: (base, token) => `${base}/${token}`,+ }),+ ).toBeNull();+ });+});diff --git a/packages/cli/src/commands/single-file-dispatch.ts b/packages/cli/src/commands/single-file-dispatch.tsindex f9181080e..50ee9eaa5 100644--- a/packages/cli/src/commands/single-file-dispatch.ts+++ b/packages/cli/src/commands/single-file-dispatch.ts@@ -15,14 +15,21 @@import { statSync } from 'node:fs';-/** Global root options that consume the following token as their value. */-const VALUE_TAKING_GLOBAL_FLAGS = new Set(['--cwd', '--log-level']);+/**+ * Options that consume the FOLLOWING token as their value. Includes the+ * subcommand flags this scan can meet before Commander parses: an unlisted+ * value-taking flag makes its value look like a positional operand, which is+ * how an explicit `--project <dir>` was silently dropped on the diverted path.+ */+const VALUE_TAKING_FLAGS = new Set(['--cwd', '--log-level', '--project', '--scope']);export interface ScannedRootArgv {- /** Positional operands, in order, with global options stripped. */+ /** Positional operands, in order, with options + their values stripped. */readonly operands: string[];/** `--cwd <dir>` (or `--cwd=<dir>`) when present — used to resolve relative file paths. */readonly cwd: string | null;+ /** `--project <dir>` (or `--project=<dir>`) when present — the explicit project override. */+ readonly project: string | null;/** True when a terminal/help flag (`-h`/`--help`/`-V`/`--version`) appeared before any operand. */readonly sawTerminalFlag: boolean;}@@ -36,6 +43,7 @@ export interface ScannedRootArgv {export function scanRootArgv(argv: string[]): ScannedRootArgv {const operands: string[] = [];let cwd: string | null = null;+ let project: string | null = null;let sawTerminalFlag = false;for (let i = 0; i < argv.length; i++) {@@ -44,8 +52,10 @@ export function scanRootArgv(argv: string[]): ScannedRootArgv {sawTerminalFlag = true;break;}- if (tok === '--cwd' || tok === '--log-level') {- if (tok === '--cwd') cwd = argv[i + 1] ?? null;+ if (VALUE_TAKING_FLAGS.has(tok)) {+ const value = argv[i + 1] ?? null;+ if (tok === '--cwd') cwd = value;+ if (tok === '--project') project = value;i++; // consume the value tokencontinue;}@@ -53,18 +63,19 @@ export function scanRootArgv(argv: string[]): ScannedRootArgv {cwd = tok.slice('--cwd='.length);continue;}- if (tok.startsWith('--log-level=')) continue;- if (tok === '--no-color' || tok === '--color') continue;+ if (tok.startsWith('--project=')) {+ project = tok.slice('--project='.length);+ continue;+ }if (tok.startsWith('-')) {- // An unrecognized option before any operand — let Commander parse + report.- // (Known value-taking flags are handled above.)- if (VALUE_TAKING_GLOBAL_FLAGS.has(tok)) i++;+ // Any other option (including `--scope=x`, `--no-color`, an unknown flag)+ // carries its own value or takes none — let Commander parse + report.continue;}operands.push(tok);}- return { operands, cwd, sawTerminalFlag };+ return { operands, cwd, project, sawTerminalFlag };}export interface DecideSingleFileOptions {@@ -140,3 +151,42 @@ export function isFileishTarget(absPath: string, token: string): boolean {return false;}}++export interface RootDispatch {+ /** Absolute path of the markdown file to open. */+ readonly absPath: string;+ /** Explicit `--project` override, resolved absolute, or null when absent. */+ readonly projectRoot: string | null;+}++export interface ResolveRootDispatchOptions {+ readonly knownSubcommands: ReadonlySet<string>;+ /** Directory relative operands resolve against (`--cwd` or `process.cwd()`). */+ readonly cwd: string;+ readonly isFileish: (absPath: string, token: string) => boolean;+ readonly resolvePath: (base: string, token: string) => string;+}++/**+ * The whole bare-`ok <file>` pre-dispatch decision as one pure function: scan+ * argv, decide the target, and carry the explicit project override through.+ * `cli.ts` is a thin caller so the dispatch matrix — including every accepted+ * `--project` syntax and position — is testable without a filesystem.+ */+export function resolveRootDispatch(+ argv: string[],+ opts: ResolveRootDispatchOptions,+): RootDispatch | null {+ const scanned = scanRootArgv(argv);+ if (scanned.sawTerminalFlag) return null;+ const baseDir = scanned.cwd ? opts.resolvePath(opts.cwd, scanned.cwd) : opts.cwd;+ const target = decideSingleFileTarget(scanned.operands, {+ knownSubcommands: opts.knownSubcommands,+ isFileish: (t) => opts.isFileish(opts.resolvePath(baseDir, t), t),+ });+ if (target === null) return null;+ return {+ absPath: opts.resolvePath(baseDir, target),+ projectRoot: scanned.project === null ? null : opts.resolvePath(baseDir, scanned.project),+ };+}diff --git a/packages/cli/src/commands/single-file-open.test.ts b/packages/cli/src/commands/single-file-open.test.tsindex c3efd3507..c1fa7d894 100644--- a/packages/cli/src/commands/single-file-open.test.ts+++ b/packages/cli/src/commands/single-file-open.test.ts@@ -1,12 +1,15 @@import {+ type PrepareSingleFileOpenOptions,SingleFileNotFoundError,SingleFileNotMarkdownError,type SingleFileOpenPlan,+ SingleFileProjectOverrideError,} from '@inkeep/open-knowledge-server';import { describe, expect, test } from 'vitest';import { runSingleFileOpen, type SingleFileOpenDeps } from './single-file-open.ts';interface Recorder {+ prepareOptions: Array<PrepareSingleFileOpenOptions | undefined>;openTargets: string[];projectOpens: Array<{ docName: string; projectRoot: string }>;browserOpens: Array<Extract<SingleFileOpenPlan, { mode: 'ephemeral' }>>;@@ -18,6 +21,7 @@ function makeDeps(overrides: Partial<SingleFileOpenDeps> & { plan?: SingleFileOpenPlan; planThrows?: Error },): { deps: SingleFileOpenDeps; rec: Recorder } {const rec: Recorder = {+ prepareOptions: [],openTargets: [],projectOpens: [],browserOpens: [],@@ -25,7 +29,8 @@ function makeDeps(errors: [],};const deps: SingleFileOpenDeps = {- prepare: () => {+ prepare: (_filePath, options) => {+ rec.prepareOptions.push(options);if (overrides.planThrows) throw overrides.planThrows;if (!overrides.plan) throw new Error('no plan configured');return overrides.plan;@@ -133,3 +138,31 @@ describe('runSingleFileOpen', () => {await expect(runSingleFileOpen('/x/notes.md', deps)).rejects.toThrow('disk on fire');});});++describe('runSingleFileOpen with an explicit --project override', () => {+ test('passes the named root through to the shared preparation step', async () => {+ const { deps, rec } = makeDeps({ plan: projectPlan });+ const code = await runSingleFileOpen('/proj/sub/spec.md', deps, { projectRoot: '/named' });+ expect(code).toBe(0);+ expect(rec.prepareOptions).toEqual([{ projectRoot: '/named' }]);+ expect(rec.projectOpens).toEqual([{ docName: 'sub/spec', projectRoot: '/proj' }]);+ });++ test('an override that cannot be honored exits non-zero with the reason', async () => {+ const { deps, rec } = makeDeps({+ planThrows: new SingleFileProjectOverrideError('/named', 'no .ok/config.yml there'),+ });+ const code = await runSingleFileOpen('/x/notes.md', deps, { projectRoot: '/named' });+ expect(code).toBe(1);+ expect(rec.errors[0]).toContain('/named');+ expect(rec.errors[0]).toContain('no .ok/config.yml there');+ expect(rec.projectOpens).toEqual([]);+ expect(rec.openTargets).toEqual([]);+ });++ test('no override → prepare is called without a root (ancestor walk decides)', async () => {+ const { deps, rec } = makeDeps({ plan: projectPlan });+ await runSingleFileOpen('/proj/sub/spec.md', deps);+ expect(rec.prepareOptions).toEqual([{ projectRoot: undefined }]);+ });+});diff --git a/packages/cli/src/commands/single-file-open.ts b/packages/cli/src/commands/single-file-open.tsindex 985e6f8d2..dd3e12200 100644--- a/packages/cli/src/commands/single-file-open.ts+++ b/packages/cli/src/commands/single-file-open.ts@@ -16,11 +16,13 @@import { rm } from 'node:fs/promises';import {encodeDocName,+ type PrepareSingleFileOpenOptions,prepareSingleFileOpen,SingleFileNotAFileError,SingleFileNotFoundError,SingleFileNotMarkdownError,type SingleFileOpenPlan,+ SingleFileProjectOverrideError,} from '@inkeep/open-knowledge-server';import type { SpawnDetachedScrubbedOutcome } from '../utils/detached-spawn.ts';import { openTargetFailureMessage, openTarget as openTargetReal } from '../utils/open-target.ts';@@ -38,7 +40,7 @@ const EPHEMERAL_IDLE_SHUTDOWN_MS = 10 * 60 * 1000;/** Injectable surface so `cli.test.ts` can drive the dispatch matrix without a* real desktop / server / browser. */export interface SingleFileOpenDeps {- prepare: (filePath: string) => SingleFileOpenPlan;+ prepare: (filePath: string, options?: PrepareSingleFileOpenOptions) => SingleFileOpenPlan;/** Absolute desktop bundle path when one is installed, else null. */detectBundlePath: () => string | null;/** Hand a URL / `openknowledge://` deep link to the OS to open. */@@ -66,6 +68,11 @@ export function createRealSingleFileOpenDeps(};}+export interface SingleFileOpenOptions {+ /** Explicit `--project` override, absolute. Honored or the open fails. */+ projectRoot?: string;+}+/*** Open `filePath` (an absolute path) in the editor. Returns a process exit code* (0 opened, 1 error). Never throws for the typed user-facing errors — they@@ -76,15 +83,17 @@ export function createRealSingleFileOpenDeps(export async function runSingleFileOpen(filePath: string,deps: SingleFileOpenDeps,+ options: SingleFileOpenOptions = {},): Promise<number> {let plan: SingleFileOpenPlan;try {- plan = deps.prepare(filePath);+ plan = deps.prepare(filePath, { projectRoot: options.projectRoot });} catch (err) {if (err instanceof SingleFileNotFoundError ||err instanceof SingleFileNotAFileError ||- err instanceof SingleFileNotMarkdownError+ err instanceof SingleFileNotMarkdownError ||+ err instanceof SingleFileProjectOverrideError) {deps.error(err.message);return 1;@@ -159,7 +168,7 @@ async function runSingleFileBrowserOpen(if (tornDown) return;tornDown = true;try {- await booted?.destroy();+ await booted?.destroy('external-signal');} catch {// best-effort — we're exiting anyway}diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.tsindex a7c8e08d9..e73ae30fa 100644--- a/packages/cli/src/commands/start.ts+++ b/packages/cli/src/commands/start.ts@@ -47,6 +47,7 @@ import {lockAdvertisesUi,type PinoLogger,prepareSingleFileOpen,+ type ServerExitReason,} from '@inkeep/open-knowledge-server';import { Command, InvalidArgumentError, Option } from 'commander';import { makeLazyEmbeddingsKeyStore } from '../auth/embeddings-key-store.ts';@@ -606,7 +607,7 @@ export interface BootedStartServer {/** The bound HTTP server listening on `port`. */httpServer: HttpServer;/** Composite shutdown — closes httpServer, detaches idle-shutdown, destroys the Hocuspocus server (which releases server.lock). */- destroy: () => Promise<void>;+ destroy: (reason?: ServerExitReason) => Promise<void>;/** Absolute path to `<projectDir>/.ok/local` — runtime-state anchor. */lockDir: string;/** Resolved content directory (`resolveContentDir(config, cwd)`). */@@ -1373,7 +1374,7 @@ export async function runStartCommand(configArg: Config, opts: StartCommandOptioconsole.log(dim(` ${line}`));}try {- await booted.destroy();+ await booted.destroy('external-signal');} catch (err) {console.error(`${error('destroy() failed:')} ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`,diff --git a/packages/cli/src/commands/stop.test.ts b/packages/cli/src/commands/stop.test.tsindex c14cd3769..c18a09362 100644--- a/packages/cli/src/commands/stop.test.ts+++ b/packages/cli/src/commands/stop.test.ts@@ -1,6 +1,10 @@-import { describe, expect, test } from 'vitest';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { hostname, tmpdir } from 'node:os';+import { join } from 'node:path';+import { lockFilePath } from '@inkeep/open-knowledge-server';+import { afterEach, describe, expect, test, vi } from 'vitest';import type { LockState } from './lock-state.ts';-import { buildStopPlan, runStop } from './stop.ts';+import { buildStopPlan, formatNoTargetMessage, probeCollabClients, runStop } from './stop.ts';function aliveLock(pid: number, port: number): LockState {return {@@ -71,10 +75,10 @@ describe('buildStopPlan', () => {});describe('runStop', () => {- test('no running processes → log and exit 0 equivalent', () => {+ test('no running processes → log and exit 0 equivalent', async () => {const logs: string[] = [];const killed: Array<[number, string]> = [];- const outcome = runStop({+ const outcome = await runStop({lockDir: '/tmp/x',inspect: () => missing(),kill: (pid, sig) => killed.push([pid, sig]),@@ -88,10 +92,10 @@ describe('runStop', () => {expect(logs).toEqual(['No running open-knowledge processes.']);});- test('both alive → SIGTERM both, log stopped summary', () => {+ test('both alive → SIGTERM both, log stopped summary', async () => {const logs: string[] = [];const killed: Array<[number, string]> = [];- const outcome = runStop({+ const outcome = await runStop({lockDir: '/tmp/x',inspect: (name) => (name === 'server' ? aliveLock(100, 3001) : aliveLock(200, 3000)),kill: (pid, sig) => killed.push([pid, sig]),@@ -108,9 +112,9 @@ describe('runStop', () => {expect(logs.at(0)).toContain('ui (pid=200, port=3000)');});- test('EPERM on kill → failure reported, outcome.failed populated', () => {+ test('EPERM on kill → failure reported, outcome.failed populated', async () => {const errors: string[] = [];- const outcome = runStop({+ const outcome = await runStop({lockDir: '/tmp/x',inspect: (name) => (name === 'server' ? aliveLock(100, 3001) : missing()),kill: () => {@@ -126,10 +130,10 @@ describe('runStop', () => {expect(errors.at(0)).toContain('server (pid=100)');});- test('mix of success + failure — reports both', () => {+ test('mix of success + failure — reports both', async () => {const logs: string[] = [];const errors: string[] = [];- const outcome = runStop({+ const outcome = await runStop({lockDir: '/tmp/x',inspect: (name) => (name === 'server' ? aliveLock(100, 3001) : aliveLock(200, 3000)),kill: (pid) => {@@ -144,9 +148,9 @@ describe('runStop', () => {expect(errors.some((e) => e.includes('ui (pid=200)'))).toBe(true);});- test('dead/corrupt locks are not killed (ok clean will prune them)', () => {+ test('dead/corrupt locks are not killed (ok clean will prune them)', async () => {const killed: number[] = [];- const outcome = runStop({+ const outcome = await runStop({lockDir: '/tmp/x',inspect: (name) => (name === 'server' ? dead(999) : aliveLock(200, 3000)),kill: (pid) => killed.push(pid),@@ -210,9 +214,9 @@ describe('buildStopPlan with foreign-host states', () => {});describe('runStop with foreign-host states', () => {- test('foreign-host + locally-live → SIGTERM sent', () => {+ test('foreign-host + locally-live → SIGTERM sent', async () => {const killed: Array<[number, string]> = [];- const outcome = runStop({+ const outcome = await runStop({lockDir: '/tmp/x',inspect: (name) => (name === 'server' ? foreign(100, 3001) : foreign(200, 3000)),kill: (pid, sig) => killed.push([pid, sig]),@@ -227,9 +231,9 @@ describe('runStop with foreign-host states', () => {expect(outcome.stopped.map((t) => t.pid)).toEqual([100, 200]);});- test('foreign-host + dead PID → no targets, no SIGTERM', () => {+ test('foreign-host + dead PID → no targets, no SIGTERM', async () => {const killed: number[] = [];- const outcome = runStop({+ const outcome = await runStop({lockDir: '/tmp/x',inspect: (name) => (name === 'server' ? foreign(100, 3001) : foreign(200, 3000)),kill: (pid) => killed.push(pid),@@ -241,3 +245,247 @@ describe('runStop with foreign-host states', () => {expect(outcome.hadTargets).toBe(false);});});++describe('runStop in-use guard', () => {+ const twoAlive = () => ({+ lockDir: '/tmp/guard',+ inspect: (name: 'server' | 'ui') =>+ name === 'server' ? aliveLock(100, 3001) : aliveLock(200, 3000),+ });++ test('declines when the target reports live collaboration clients', async () => {+ const killed: Array<[number, string]> = [];+ const errors: string[] = [];+ const outcome = await runStop({+ ...twoAlive(),+ kill: (pid, sig) => killed.push([pid, sig]),+ log: () => {},+ error: (msg) => errors.push(msg),+ probeClients: async () => 2,+ });++ expect(killed).toEqual([]);+ expect(outcome.stopped).toEqual([]);+ expect(outcome.declined).toEqual({ clients: 2 });+ expect(errors).toHaveLength(1);+ expect(errors[0]).toContain('2 collaboration clients');+ expect(errors[0]).toContain('--force');+ });++ test('--force terminates despite live clients', async () => {+ const killed: Array<[number, string]> = [];+ const outcome = await runStop({+ ...twoAlive(),+ force: true,+ kill: (pid, sig) => killed.push([pid, sig]),+ log: () => {},+ error: () => {},+ probeClients: async () => 5,+ });++ expect(killed).toEqual([+ [100, 'SIGTERM'],+ [200, 'SIGTERM'],+ ]);+ expect(outcome.declined).toBeUndefined();+ expect(outcome.stopped).toHaveLength(2);+ });++ test('an unreachable server (probe returns null) proceeds — it is already gone', async () => {+ const killed: Array<[number, string]> = [];+ const outcome = await runStop({+ ...twoAlive(),+ kill: (pid, sig) => killed.push([pid, sig]),+ log: () => {},+ error: () => {},+ probeClients: async () => null,+ });++ expect(killed).toHaveLength(2);+ expect(outcome.declined).toBeUndefined();+ });++ test('zero reported clients proceeds', async () => {+ const killed: Array<[number, string]> = [];+ const outcome = await runStop({+ ...twoAlive(),+ kill: (pid, sig) => killed.push([pid, sig]),+ log: () => {},+ error: () => {},+ probeClients: async () => 0,+ });++ expect(killed).toHaveLength(2);+ expect(outcome.stopped).toHaveLength(2);+ });+});++describe('runStop durable record', () => {+ function captureLogger(): {+ logger: Parameters<typeof runStop>[0]['logger'];+ records: Array<{ level: string; obj: Record<string, unknown>; msg: string }>;+ } {+ const records: Array<{ level: string; obj: Record<string, unknown>; msg: string }> = [];+ const logger = {+ info: (obj: Record<string, unknown>, msg: string) =>+ records.push({ level: 'info', obj, msg }),+ warn: (obj: Record<string, unknown>, msg: string) =>+ records.push({ level: 'warn', obj, msg }),+ } as unknown as Parameters<typeof runStop>[0]['logger'];+ return { logger, records };+ }++ test('records the resolved lock dir and every signalled pid', async () => {+ const { logger, records } = captureLogger();+ await runStop({+ lockDir: '/tmp/target/.ok/local',+ inspect: (name) => (name === 'server' ? aliveLock(100, 3001) : aliveLock(200, 3000)),+ kill: () => {},+ log: () => {},+ error: () => {},+ probeClients: async () => 0,+ logger,+ });++ const record = records.find((r) => r.msg === 'stop signalled processes');+ expect(record).toBeDefined();+ expect(record?.obj.lockDir).toBe('/tmp/target/.ok/local');+ expect(record?.obj.signalled).toEqual([+ { name: 'server', pid: 100, port: 3001 },+ { name: 'ui', pid: 200, port: 3000 },+ ]);+ expect(record?.obj.forced).toBe(false);+ });++ test('records a decline with the client count and the target', async () => {+ const { logger, records } = captureLogger();+ await runStop({+ lockDir: '/tmp/other/.ok/local',+ inspect: (name) => (name === 'server' ? aliveLock(7, 3001) : missing()),+ kill: () => {},+ log: () => {},+ error: () => {},+ probeClients: async () => 1,+ logger,+ });++ const record = records.find((r) => r.msg === 'stop declined: live collaboration clients');+ expect(record?.level).toBe('warn');+ expect(record?.obj).toMatchObject({ lockDir: '/tmp/other/.ok/local', clients: 1, pids: [7] });+ });+});++describe('formatNoTargetMessage', () => {+ test('nothing here AND nothing anywhere says both', () => {+ const msg = formatNoTargetMessage('/proj', 0);+ expect(msg).toContain('/proj');+ expect(msg).toContain('no other open-knowledge servers are running');+ });++ test('nothing here but servers elsewhere does not claim nothing is running', () => {+ const msg = formatNoTargetMessage('/proj', 2);+ expect(msg).toContain('Nothing was running for /proj');+ expect(msg).toContain('2 other open-knowledge servers are running');+ expect(msg).toContain('ok ps');+ expect(msg).not.toContain('no other');+ });++ test('singular agreement for one other server', () => {+ expect(formatNoTargetMessage('/proj', 1)).toContain('1 other open-knowledge server is running');+ });++ test('drops the `ok ps` pointer when the caller prints the listing itself', () => {+ const msg = formatNoTargetMessage('/proj', 2, { listingFollows: true });+ expect(msg).toContain('Nothing was running for /proj');+ expect(msg).toContain('2 other open-knowledge servers are running');+ expect(msg).not.toContain('ok ps');+ });+});++describe('probeCollabClients failure record', () => {+ const records: Array<{ obj: Record<string, unknown>; msg: string }> = [];+ const logger = {+ info: () => {},+ warn: (obj: Record<string, unknown>, msg: string) => records.push({ obj, msg }),+ } as unknown as Parameters<typeof runStop>[0]['logger'];++ let lockDir: string;++ /** A same-host, live-pid server lock so `inspectLock` classifies `alive`. */+ function seedAliveServerLock(): string {+ const dir = mkdtempSync(join(tmpdir(), 'ok-stop-probe-'));+ mkdirSync(dir, { recursive: true });+ writeFileSync(+ lockFilePath(dir, 'server'),+ JSON.stringify({+ pid: process.pid,+ port: 24999,+ hostname: hostname(),+ startedAt: '2026-08-18T00:00:00Z',+ worktreeRoot: dir,+ }),+ 'utf-8',+ );+ return dir;+ }++ afterEach(() => {+ records.length = 0;+ vi.unstubAllGlobals();+ if (lockDir !== undefined) rmSync(lockDir, { recursive: true, force: true });+ });++ test('records an unreachable server, and still reports "proceed"', async () => {+ lockDir = seedAliveServerLock();+ vi.stubGlobal('fetch', () => Promise.reject(new Error('connect ECONNREFUSED')));++ expect(await probeCollabClients(lockDir, logger)).toBeNull();++ const record = records.find((r) => r.msg === 'stop client-probe failed');+ expect(record?.obj).toMatchObject({ lockDir, outcome: 'unreachable' });+ // The raw error rides under `err` so pino's serializer keeps the stack.+ expect((record?.obj.err as Error).message).toContain('ECONNREFUSED');+ });++ test('records a malformed answer distinctly from an unreachable one', async () => {+ lockDir = seedAliveServerLock();+ vi.stubGlobal('fetch', () =>+ Promise.resolve(+ new Response(JSON.stringify({ version: '1' }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ }),+ ),+ );++ expect(await probeCollabClients(lockDir, logger)).toBeNull();++ const record = records.find((r) => r.msg === 'stop client-probe failed');+ expect(record?.obj).toMatchObject({ lockDir, outcome: 'no-client-count' });+ });++ test('records a server that answered non-2xx', async () => {+ lockDir = seedAliveServerLock();+ vi.stubGlobal('fetch', () => Promise.resolve(new Response('nope', { status: 503 })));++ expect(await probeCollabClients(lockDir, logger)).toBeNull();++ const record = records.find((r) => r.msg === 'stop client-probe failed');+ expect(record?.obj).toMatchObject({ lockDir, outcome: 'http-error', status: 503 });+ });++ test('a live client count is not a failure', async () => {+ lockDir = seedAliveServerLock();+ vi.stubGlobal('fetch', () =>+ Promise.resolve(+ new Response(JSON.stringify({ collabClients: 3 }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ }),+ ),+ );++ expect(await probeCollabClients(lockDir, logger)).toBe(3);+ expect(records).toEqual([]);+ });+});diff --git a/packages/cli/src/commands/stop.ts b/packages/cli/src/commands/stop.tsindex a032a8ce4..f9d3d4a14 100644--- a/packages/cli/src/commands/stop.ts+++ b/packages/cli/src/commands/stop.ts@@ -8,13 +8,81 @@*/import { resolve } from 'node:path';-import { type Config, isProcessAlive, resolveLockDir } from '@inkeep/open-knowledge-server';+import {+ type Config,+ isProcessAlive,+ lockBaseUrl,+ resolveLockDir,+} from '@inkeep/open-knowledge-server';import { Command } from 'commander';+import type { Logger as PinoLoggerInstance } from 'pino';+import { getCliLogger } from '../cli-logger.ts';import { getInvocationCwd } from '../project-anchor.ts';import { discoverLockDirs } from '../utils/process-scan.ts';import { inspectLegacyUiLock, inspectLock, type LockState } from './lock-state.ts';import { runPs } from './ps.ts';+/** How long to wait for the target server to answer the in-use probe. */+const CLIENT_PROBE_TIMEOUT_MS = 1500;++/**+ * Live collaboration clients on the server recorded in `<lockDir>/server.lock`,+ * or `null` when that cannot be established (no lock, no advertised URL, the+ * server does not answer, or it is old enough not to report the count).+ *+ * Provenance — who spawned the server — is deliberately not consulted: the+ * process title is rewritten at start, so no process-inspection signal+ * survives, and a terminal-spawned server with a desktop window attached is+ * exactly the case that must be caught.+ *+ * Every `null` that came from a server we DID try to reach is recorded on the+ * file logger with which failure it was. All of them proceed with the stop, so+ * the distinction survives nowhere else — a server that answered garbage and a+ * server that never answered are the same no-op on stdout.+ */+export async function probeCollabClients(+ lockDir: string,+ logger: PinoLoggerInstance | undefined = getCliLogger(),+): Promise<number | null> {+ const state = inspectLock(lockDir, 'server');+ if (state.status !== 'alive' && state.status !== 'foreign-host') return null;+ const baseUrl = lockBaseUrl(state.lock);+ if (baseUrl === null) return null;+ try {+ const res = await fetch(`${baseUrl}/api/server-info`, {+ signal: AbortSignal.timeout(CLIENT_PROBE_TIMEOUT_MS),+ });+ if (!res.ok) {+ logger?.warn(+ { lockDir, baseUrl, outcome: 'http-error', status: res.status },+ 'stop client-probe failed',+ );+ return null;+ }+ const body: unknown = await res.json();+ const count = (body as { collabClients?: unknown } | null)?.collabClients;+ if (typeof count === 'number' && Number.isFinite(count)) return count;+ logger?.warn(+ { lockDir, baseUrl, outcome: 'no-client-count', received: typeof count },+ 'stop client-probe failed',+ );+ return null;+ } catch (err) {+ // Unreachable, draining, or mid-start: nothing is usefully attached to a+ // server that cannot answer, so the caller proceeds.+ logger?.warn(+ {+ lockDir,+ baseUrl,+ outcome: 'unreachable',+ err,+ },+ 'stop client-probe failed',+ );+ return null;+ }+}+interface StopTargetPlan {name: 'server' | 'ui';pid: number;@@ -62,17 +130,29 @@ export function buildStopPlan(interface RunStopDeps {lockDir: string;+ /**+ * Terminate even when the server reports live collaboration clients. Off by+ * default so the safe behavior is what any caller of this published export+ * gets without opting in.+ */+ force?: boolean;inspect?: (name: 'server' | 'ui') => LockState;kill?: (pid: number, signal: NodeJS.Signals) => void;isAlive?: (pid: number) => boolean;log?: (msg: string) => void;error?: (msg: string) => void;+ /** Live-client probe. `null` = could not establish → proceed. */+ probeClients?: (lockDir: string, logger?: PinoLoggerInstance) => Promise<number | null>;+ /** File logger for the durable record. Defaults to the CLI's. */+ logger?: PinoLoggerInstance;}interface StopOutcome {stopped: StopTargetPlan[];failed: Array<{ target: StopTargetPlan; error: string }>;hadTargets: boolean;+ /** Set when the stop was refused because clients are attached. */+ declined?: { clients: number };}/**@@ -80,7 +160,7 @@ interface StopOutcome {* going through Commander. The Commander action wraps this and translates* `failed.length > 0` into `process.exitCode = 1`.*/-export function runStop(deps: RunStopDeps): StopOutcome {+export async function runStop(deps: RunStopDeps): Promise<StopOutcome> {// The `ui` slot is the one-release legacy reap: `inspectLegacyUiLock` peeks a// leftover pre-migration `ok ui` holder so a live one still gets SIGTERM'd.// The current binary writes no `ui.lock`, so `server` is the only live slot.@@ -91,6 +171,8 @@ export function runStop(deps: RunStopDeps): StopOutcome {const kill = deps.kill ?? ((pid, signal) => process.kill(pid, signal));const log = deps.log ?? ((msg) => console.log(msg));const error = deps.error ?? ((msg) => console.error(msg));+ const probeClients = deps.probeClients ?? probeCollabClients;+ const logger = deps.logger ?? getCliLogger();const serverState = inspect('server');const uiState = inspect('ui');@@ -98,9 +180,26 @@ export function runStop(deps: RunStopDeps): StopOutcome {if (plan.targets.length === 0) {log('No running open-knowledge processes.');+ logger?.info({ lockDir: deps.lockDir, targets: 0 }, 'stop found nothing to signal');return { stopped: [], failed: [], hadTargets: false };}+ if (deps.force !== true) {+ const clients = await probeClients(deps.lockDir, logger);+ if (clients !== null && clients > 0) {+ error(+ `Not stopping: ${clients} collaboration client${clients === 1 ? '' : 's'} ` ++ `(editor window${clients === 1 ? '' : 's'} or agents) still connected to the server at ${deps.lockDir}. ` ++ 'Close them, or re-run with --force to terminate anyway.',+ );+ logger?.warn(+ { lockDir: deps.lockDir, clients, pids: plan.targets.map((t) => t.pid) },+ 'stop declined: live collaboration clients',+ );+ return { stopped: [], failed: [], hadTargets: true, declined: { clients } };+ }+ }+const stopped: StopTargetPlan[] = [];const failed: Array<{ target: StopTargetPlan; error: string }> = [];for (const target of plan.targets) {@@ -116,6 +215,17 @@ export function runStop(deps: RunStopDeps): StopOutcome {const rendered = stopped.map((t) => `${t.name} (pid=${t.pid}, port=${t.port})`).join(', ');log(`Stopped: ${rendered}`);}+ // Durable record of WHAT was signalled and WHERE — stdout alone leaves a+ // terminated server undiagnosable from a bug bundle.+ logger?.info(+ {+ lockDir: deps.lockDir,+ signalled: stopped.map((t) => ({ name: t.name, pid: t.pid, port: t.port })),+ failed: failed.map(({ target, error: msg }) => ({ pid: target.pid, error: msg })),+ forced: deps.force === true,+ },+ 'stop signalled processes',+ );if (failed.length > 0) {const rendered = failed.map(({ target, error: msg }) => `${target.name} (pid=${target.pid}): ${msg}`)@@ -165,12 +275,61 @@ async function findLockDirByNumber(return pidMatch;}-function executeStop(lockDir: string): StopOutcome {- const outcome = runStop({ lockDir });- if (outcome.failed.length > 0) process.exitCode = 1;+async function executeStop(lockDir: string, force: boolean): Promise<StopOutcome> {+ const outcome = await runStop({ lockDir, force });+ if (outcome.failed.length > 0 || outcome.declined !== undefined) process.exitCode = 1;return outcome;}+/**+ * The "found nothing here" message. Names the target, and distinguishes+ * "nothing is running for this directory" from "nothing is running at all" —+ * conflating the two is what made a stop against the wrong directory read as+ * a clean no-op.+ */+export function formatNoTargetMessage(+ targetDir: string,+ otherRunningServers: number,+ opts: {+ /**+ * Set by a caller that prints the `ok ps` listing itself, so the message+ * doesn't tell the user to run what is about to appear below it.+ */+ listingFollows?: boolean;+ } = {},+): string {+ if (otherRunningServers === 0) {+ return `Nothing was running for ${targetDir}, and no other open-knowledge servers are running.`;+ }+ const agreement = otherRunningServers === 1 ? ' is' : 's are';+ const pointer = opts.listingFollows === true ? '' : ' — run `ok ps` to list them';+ return (+ `Nothing was running for ${targetDir}. ${otherRunningServers} other open-knowledge server` ++ `${agreement} running${pointer}.`+ );+}++/**+ * Count servers running OUTSIDE `exceptLockDir`, so a stop that found nothing+ * here can say so without claiming nothing is running anywhere.+ */+async function countOtherRunningServers(exceptLockDir: string): Promise<number> {+ const lockDirs = await discoverLockDirs();+ let count = 0;+ for (const lockDir of lockDirs) {+ if (lockDir === exceptLockDir) continue;+ if (+ isStoppableState(inspectLock(lockDir, 'server'), isProcessAlive) ||+ // Legacy `ok ui` holder: the current binary writes no `ui.lock`, so this+ // only matches a leftover pre-migration process.+ isStoppableState(inspectLegacyUiLock(lockDir), isProcessAlive)+ ) {+ count++;+ }+ }+ return count;+}+export function stopCommand(getConfig: () => Config): Command {return new Command('stop').description(@@ -178,7 +337,9 @@ export function stopCommand(getConfig: () => Config): Command {'Pass a port number, a directory path, or "all" to target globally.',).argument('[target...]', 'port number, directory path (spaces OK), or "all"')- .action(async (parts: string[]) => {+ .option('--force', 'Stop even when editor windows or agents are still connected to the server')+ .action(async (parts: string[], options: { force?: boolean }) => {+ const force = options.force === true;// Rejoin space-split path parts so unquoted paths like /foo/bar baz workconst target = parts.length === 0 ? undefined : parts.join(' ');@@ -191,7 +352,7 @@ export function stopCommand(getConfig: () => Config): Command {getConfig(); // still load config to surface any project-config errorsconst lockDir = resolveLockDir(process.cwd());// Suppress runStop's own log so we control all output- const outcome = runStop({ lockDir, log: () => {} });+ const outcome = await runStop({ lockDir, force, log: () => {} });if (outcome.hadTargets) {if (outcome.stopped.length > 0) {const rendered = outcome.stopped@@ -199,10 +360,14 @@ export function stopCommand(getConfig: () => Config): Command {.join(', ');console.log(`Stopped: ${rendered}`);}- if (outcome.failed.length > 0) process.exitCode = 1;+ if (outcome.failed.length > 0 || outcome.declined !== undefined) process.exitCode = 1;} else {- // Nothing running in cwd — show what's running elsewhere- await runPs({});+ // Nothing running in cwd — same phrasing as an explicitly targeted+ // directory (one formatter, one wording), then the listing itself+ // rather than the pointer to it.+ const others = await countOtherRunningServers(lockDir);+ console.log(formatNoTargetMessage(process.cwd(), others, { listingFollows: others > 0 }));+ if (others > 0) await runPs({});}return;}@@ -222,7 +387,7 @@ export function stopCommand(getConfig: () => Config): Command {const ui = inspectLegacyUiLock(lockDir);if (!isStoppableState(server, isProcessAlive) && !isStoppableState(ui, isProcessAlive))continue;- executeStop(lockDir);+ await executeStop(lockDir, force);stopped++;}if (stopped === 0) console.log('No running open-knowledge servers found.');@@ -237,7 +402,7 @@ export function stopCommand(getConfig: () => Config): Command {console.log(`No running open-knowledge server found with port or PID ${n}.`);return;}- executeStop(lockDir);+ await executeStop(lockDir, force);return;}@@ -246,7 +411,17 @@ export function stopCommand(getConfig: () => Config): Command {// invoked the CLI from — the preAction project anchor may have chdir'd// to the enclosing project root, which must not re-base a path the// user typed.- const lockDir = resolveLockDir(resolve(getInvocationCwd(), target));- executeStop(lockDir);+ const targetDir = resolve(getInvocationCwd(), target);+ const lockDir = resolveLockDir(targetDir);+ // Buffer runStop's own output: its generic "nothing here" line is+ // replaced below by one that names the target and the wider state.+ const buffered: string[] = [];+ const outcome = await runStop({ lockDir, force, log: (msg) => buffered.push(msg) });+ if (outcome.failed.length > 0 || outcome.declined !== undefined) process.exitCode = 1;+ if (outcome.hadTargets) {+ for (const line of buffered) console.log(line);+ } else {+ console.log(formatNoTargetMessage(targetDir, await countOtherRunningServers(lockDir)));+ }});}diff --git a/packages/cli/src/commands/uninstall.test.ts b/packages/cli/src/commands/uninstall.test.tsindex 09992ec2b..b9bf2ec0d 100644--- a/packages/cli/src/commands/uninstall.test.ts+++ b/packages/cli/src/commands/uninstall.test.ts@@ -336,3 +336,98 @@ describe('runUninstall', () => {}});});++describe('runUninstall attached-client disclosure', () => {+ test('names attached clients in the plan without adding a gate', async () => {+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-clients-'));+ try {+ write(join(home, '.ok', 'auth.yml'), 'x\n');+ const result = await runUninstall({+ home,+ platform: 'darwin',+ cwd: home,+ dryRun: true,+ deps: {+ discoverLockDirs: async () => ['/some/proj/.ok/local'], // → a stop-server op+ detectInstallMethods: () => [],+ probeClients: async () => 1,+ },+ });+ expect(result.status).toBe('dry-run');+ expect(result.exitCode).toBe(0);+ expect(result.message).toContain('1 collaboration client');+ expect(result.message).toContain('restarting will NOT recover them');+ // Disclosure only — no `--force`, no second prompt.+ expect(result.message).not.toContain('--force');+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });++ test('--json --dry-run carries the probe result', async () => {+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-clients-'));+ try {+ write(join(home, '.ok', 'auth.yml'), 'x\n');+ const result = await runUninstall({+ home,+ platform: 'darwin',+ cwd: home,+ dryRun: true,+ json: true,+ deps: {+ discoverLockDirs: async () => ['/some/proj/.ok/local'],+ detectInstallMethods: () => [],+ probeClients: async () => 1,+ },+ });+ const json = JSON.parse(result.message);+ expect(json.mode).toBe('dry-run');+ expect(json.attachedClients).toHaveLength(1);+ expect(json.attachedClients[0]).toContain('1 collaboration client');+ expect(json.attachedClients[0]).toContain('restarting will NOT recover them');+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });++ test('--json --dry-run reports an empty probe result when nothing is attached', async () => {+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-clients-'));+ try {+ const result = await runUninstall({+ home,+ platform: 'darwin',+ cwd: home,+ dryRun: true,+ json: true,+ deps: {+ discoverLockDirs: async () => ['/some/proj/.ok/local'],+ detectInstallMethods: () => [],+ probeClients: async () => null,+ },+ });+ expect(JSON.parse(result.message).attachedClients).toEqual([]);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });++ test('silent when nothing is attached', async () => {+ const home = mkdtempSync(join(tmpdir(), 'ok-uninst-clients-'));+ try {+ const result = await runUninstall({+ home,+ platform: 'darwin',+ cwd: home,+ dryRun: true,+ deps: {+ discoverLockDirs: async () => ['/some/proj/.ok/local'],+ detectInstallMethods: () => [],+ probeClients: async () => null,+ },+ });+ expect(result.message).not.toContain('collaboration client');+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });+});diff --git a/packages/cli/src/commands/uninstall.ts b/packages/cli/src/commands/uninstall.tsindex dd6d7febd..67a9ae374 100644--- a/packages/cli/src/commands/uninstall.ts+++ b/packages/cli/src/commands/uninstall.ts@@ -26,7 +26,12 @@ import { readPathInstallMarker } from '../integrations/path-shim.ts';import { accent, dim, error as errorColor, info, success, warning } from '../ui/colors.ts';import { confirmDestructive } from '../ui/confirm.ts';import { discoverLockDirs } from '../utils/process-scan.ts';-import { buildUninstallPlan, type RunRemovalDeps, runRemoval } from './removal-plan.ts';+import {+ buildUninstallPlan,+ describeAttachedClients,+ type RunRemovalDeps,+ runRemoval,+} from './removal-plan.ts';import {formatRemovalOutcome,formatRemovalPlan,@@ -323,6 +328,8 @@ interface UninstallDeps {runRemovalDeps?: RunRemovalDeps;/** Prompt + transport seams for the post-confirm churn survey. */feedback?: Pick<UninstallFeedbackPromptDeps, 'collect' | 'submit'>;+ /** Live-client probe seam (hits each running server over HTTP in production). */+ probeClients?: (lockDir: string) => Promise<number | null>;}export interface UninstallOptions {@@ -399,6 +406,10 @@ export async function runUninstall(opts: UninstallOptions = {}): Promise<UninstapurgeContent,});+ const attached = await describeAttachedClients(plan, opts.deps?.probeClients);+ const attachedBlock =+ attached.length > 0 ? `\n\n${attached.map((l) => warning(l)).join('\n')}` : '';+const fallbackNote = dim('Individual projects are only removed when you select them (or pass --all-projects). ' +'To remove OpenKnowledge from one project, run `ok deinit` inside it.',@@ -416,11 +427,11 @@ export async function runUninstall(opts: UninstallOptions = {}): Promise<Uninstaif (opts.dryRun) {// The app-removal callout goes LAST so it doesn't get buried in the plan.const body = opts.json- ? JSON.stringify(removalPlanToJson(plan), null, 2)+ ? JSON.stringify(removalPlanToJson(plan, attached), null, 2): [accent('Would remove (dry-run — no changes made):'),'',- formatRemovalPlan(plan),+ `${formatRemovalPlan(plan)}${attachedBlock}`,'',fallbackNote,'',@@ -447,7 +458,7 @@ export async function runUninstall(opts: UninstallOptions = {}): Promise<Uninsta};}process.stderr.write(- `${accent('This will remove OpenKnowledge from your machine:')}\n\n${formatRemovalPlan(plan)}\n\n${warning('This cannot be undone.')}\n\n`,+ `${accent('This will remove OpenKnowledge from your machine:')}\n\n${formatRemovalPlan(plan)}${attachedBlock}\n\n${warning('This cannot be undone.')}\n\n`,);const confirmed = await confirmDestructive(`${accent('Remove all of the above?')} ${dim('[y/N] ')}`,@@ -482,7 +493,7 @@ export async function runUninstall(opts: UninstallOptions = {}): Promise<Uninstaconst parts = [opts.json- ? JSON.stringify(removalOutcomeToJson('uninstall', outcome), null, 2)+ ? JSON.stringify(removalOutcomeToJson('uninstall', outcome, attached), null, 2): formatRemovalOutcome(outcome),];if (!opts.json) {diff --git a/packages/core/src/schemas/api/_envelope.ts b/packages/core/src/schemas/api/_envelope.tsindex 7c796a093..dc44c494e 100644--- a/packages/core/src/schemas/api/_envelope.ts+++ b/packages/core/src/schemas/api/_envelope.ts@@ -80,6 +80,12 @@ export const ServerInfoSuccessSchema = zcurrentBranch: z.string().min(1).optional(),currentDiskAckSVs: z.record(z.string().min(1), z.string().min(1)).optional(),boot: ServerInfoBootSchema.optional(),+ /**+ * Live `/collab` WebSocket clients — editor windows and agents alike.+ * Optional: absent means the server did not wire a counter, which a+ * reader must treat as unknown rather than as zero.+ */+ collabClients: z.number().int().nonnegative().optional(),}).loose() satisfies StandardSchemaV1;export type ServerInfoSuccess = z.infer<typeof ServerInfoSuccessSchema>;diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex ed3223bcb..c53e46647 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -6638,8 +6638,11 @@ function registerIpcHandlers() {// Route runStop's own log through the structured logger (not stdout) so// the success path — which PIDs were SIGTERM'd before `.git` deletion —// is captured for incident forensics, not silently dropped.- const outcome = runStop({+ const outcome = await runStop({lockDir: resolveLockDir(gitRoot),+ // The worktree and its `.git` are going away regardless, so the+ // in-use decline would only strand the server it is about to orphan.+ force: true,log: (msg) => getLogger('project').info({ gitRoot }, `[remove-git-folder] ${msg}`),});getLogger('project').info(diff --git a/packages/desktop/src/utility/server-entry.test.ts b/packages/desktop/src/utility/server-entry.test.tsindex f79cafe49..d843afa3d 100644--- a/packages/desktop/src/utility/server-entry.test.ts+++ b/packages/desktop/src/utility/server-entry.test.ts@@ -4,7 +4,7 @@ import { resolve } from 'node:path';import type { ServerRuntimeConfig } from '@inkeep/open-knowledge-core';import type { BootedServer, BootServerOptions } from '@inkeep/open-knowledge-server';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';-import type { SetupUtilityDeps } from './server-entry.ts';+import type { SetupUtilityDeps, UtilityHandle } from './server-entry.ts';// Stub node:os.homedir() before importing the utility (which transitively pulls// in the CLI's layered `loadConfig`) so the user-global layer@@ -135,6 +135,9 @@ interface DriveResult {bootPorts: Array<number | undefined>;ready?: { type: string; port: number; apiOrigin: string };readyErr?: Error;+ handle: UtilityHandle;+ /** Every `reason` the booted server's `destroy` was handed. */+ destroyReasons: Array<string | undefined>;}/**@@ -149,12 +152,19 @@ async function driveInit(opts: {}): Promise<DriveResult> {const posted: Array<Record<string, unknown>> = [];const bootPorts: Array<number | undefined> = [];+ const destroyReasons: Array<string | undefined> = [];let messageHandler: ((e: { data: unknown }) => void) | undefined;const fakeBootServer = async (o: BootServerOptions): Promise<BootedServer> => {bootPorts.push(o.port);const res = await opts.boot(o.port);- return { port: res.port, degraded: [], destroy: async () => {} } as unknown as BootedServer;+ return {+ port: res.port,+ degraded: [],+ destroy: async (reason?: string) => {+ destroyReasons.push(reason);+ },+ } as unknown as BootedServer;};const deps: SetupUtilityDeps = {@@ -193,9 +203,9 @@ async function driveInit(opts: {});try {const ready = await handle.readyPromise;- return { posted, bootPorts, ready };+ return { posted, bootPorts, ready, handle, destroyReasons };} catch (err) {- return { posted, bootPorts, readyErr: err as Error };+ return { posted, bootPorts, readyErr: err as Error, handle, destroyReasons };}}@@ -250,3 +260,30 @@ describe('port pinning + EADDRINUSE fallback', () => {expect(posted.find((m) => m.type === 'error')).toBeDefined();});});++describe('shutdown exit reason', () => {+ async function drive() {+ return driveInit({+ requestedPort: 24560,+ boot: (port) => Promise.resolve({ port: port ?? 0 }),+ });+ }++ test('a dead parent drains the server as parent-exit', async () => {+ const { handle, destroyReasons } = await drive();+ await handle.shutdown('parent-died');+ expect(destroyReasons).toEqual(['parent-exit']);+ });++ test('window-close IPC drains as parent-exit too — the host is going away', async () => {+ const { handle, destroyReasons } = await drive();+ await handle.shutdown('shutdown-ipc');+ expect(destroyReasons).toEqual(['parent-exit']);+ });++ test('a signal drains as external-signal', async () => {+ const { handle, destroyReasons } = await drive();+ await handle.shutdown('SIGTERM');+ expect(destroyReasons).toEqual(['external-signal']);+ });+});diff --git a/packages/desktop/src/utility/server-entry.ts b/packages/desktop/src/utility/server-entry.tsindex 01765cb1c..ead640733 100644--- a/packages/desktop/src/utility/server-entry.ts+++ b/packages/desktop/src/utility/server-entry.ts@@ -41,6 +41,7 @@ import {ensureProjectGit,initContent,makeLazyEmbeddingsKeyStore,+ type ServerExitReason,} from '@inkeep/open-knowledge-server';import { type KeyringSmokeResult, runKeyringSmoke } from './keyring-smoke.ts';@@ -233,13 +234,31 @@ export type PrepareBootEnvironment = (ipcOpts: UtilityInitMessage['opts'],) => Promise<PreparedBootEnvironment>;+/** Every path that tears this utility down. */+export type UtilityShutdownReason = 'parent-died' | 'shutdown-ipc' | 'SIGTERM' | 'SIGINT';++/**+ * Utility lifecycle reasons projected onto the server's own exit taxonomy.+ * The server records only what it is handed, so a reason that stops here+ * leaves every desktop-hosted shutdown logged as `unspecified` — the one+ * class of shutdown a bundle can never explain after the fact. Window close+ * and a dead parent are both "the host went away"; a signal is someone+ * outside the topology.+ */+const SERVER_EXIT_REASONS: Record<UtilityShutdownReason, ServerExitReason> = {+ 'parent-died': 'parent-exit',+ 'shutdown-ipc': 'parent-exit',+ SIGTERM: 'external-signal',+ SIGINT: 'external-signal',+};+export interface UtilityHandle {/** Resolves once the utility has booted (after `ready` IPC fired). Tests await this. */readyPromise: Promise<UtilityReadyMessage>;/** Cancel the parent-death polling interval (called on shutdown). */stopParentPoll(): void;/** Run the drain sequence + exit. Idempotent. */- shutdown(reason: string): Promise<void>;+ shutdown(reason: UtilityShutdownReason): Promise<void>;}/**@@ -293,14 +312,14 @@ export function setupUtility(deps: SetupUtilityDeps): UtilityHandle {parentPollHandle = null;}- async function shutdown(reason: string): Promise<void> {+ async function shutdown(reason: UtilityShutdownReason): Promise<void> {if (shuttingDown) return;shuttingDown = true;stopParentPoll();let drainOk = true;if (booted) {try {- await booted.destroy();+ await booted.destroy(SERVER_EXIT_REASONS[reason]);} catch (err) {// Report via IPC AND exit non-zero. The parent correlates the error// IPC with the non-zero exit code; silently exiting 0 on a faileddiff --git a/packages/server/assets/skills/discovery/SKILL.md b/packages/server/assets/skills/discovery/SKILL.mdindex e38e9397d..1bf62d8b7 100644--- a/packages/server/assets/skills/discovery/SKILL.md+++ b/packages/server/assets/skills/discovery/SKILL.md@@ -112,9 +112,18 @@ If the OK MCP server isn't wired into this host there is no `preview_url` tocall — use the `ok open` path above. Don't reconstruct what `preview_url` doesby hand (spawning `ok mcp` yourself, scraping ports from `ok ps`).-The path must be absolute (a file outside a project has no cwd to anchor a-relative path). Re-opening the same file lands on the same session. Never-construct or guess the URL — use the one `preview_url` returns.+Give an absolute path. `ok open` prints the absolute project root it resolved+for that path, and names the enclosing project too when the resolved root sits+inside another one. Read that line rather than assuming which project you got.++To name the project yourself, pass `--project <dir>`. It is honored wherever it+appears: `--project <dir>` or `--project=<dir>`, before or after the path, with+or without the `.md` extension. If it cannot be honored the command exits+non-zero and says why, so you never need a second command to find out where it+landed, and never need to stop a server to correct it.++Re-opening the same file lands on the same session. Never construct or guess the+URL — use the one `preview_url` returns.## What else OK doesdiff --git a/packages/server/assets/skills/project/references/preview.md b/packages/server/assets/skills/project/references/preview.mdindex c34c8afdf..ff28d5a4a 100644--- a/packages/server/assets/skills/project/references/preview.md+++ b/packages/server/assets/skills/project/references/preview.md@@ -41,6 +41,7 @@ Decide once; then every "open / show / preview this doc" this session uses that- **`ok open <name>`** — opens a **doc or folder** in the OK Desktop app. The type is auto-detected (a directory on disk → folder, otherwise a doc), so **`--folder` is not needed** (it stays only as an explicit override for a folder that doesn't exist on disk yet). An action you run, not a URL to print.- **`ok open <skill-name> --skill [--scope project|global]`** — opens a **skill** in the skill editor (skills are addressed by name + scope, not a content path, so they need the flag).- All three deep-link into OK Desktop when a bundle is installed, and fall back to the browser UI (`ok start`) otherwise. No `ok` on PATH or no shell → `preview_url`, then `open <url>` in the system browser as a last resort, and say so plainly. The system browser is the fallback, never the default.+- **`ok open` prints the absolute project root it resolved**, and names the enclosing project too when that root sits inside another one. Read that line instead of assuming which project you got. To name the project yourself, pass `--project <dir>`; it is honored wherever it appears (`--project <dir>` or `--project=<dir>`, before or after the target, with or without a `.md` extension), or the command exits non-zero saying why.(The same vendors' *desktop apps* with a built-in browser — Cursor, Codex desktop — are NOT here; they navigate their own browser per the in-app branch above. Codex **IDE extension** / **Cloud** are web-search-only → they're on this CLI track too.) **Running inside OpenKnowledge itself — the desktop built-in terminal (`OK_DESKTOP_TERMINAL`) or the in-app agent panel (`OK_HOSTED_AGENT`)? Same track — `ok open <name>` re-targets the surface you're already in** (switches it to the doc/folder; when that surface is a desktop window there's no second window, and no need to raise it since it's already frontmost). Don't resolve preview URLs in that case; `ok open` is the whole answer.diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 023c3495f..45088df6c 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -570,6 +570,7 @@ import {isDerivedDocumentIndexClosedError,} from './derived-document-index.ts';import {+ canonicalDocName,docNameToRelativePath,extensionlessDocTreePath,forgetDocExtension,@@ -2570,6 +2571,14 @@ export interface ApiExtensionOptions {* server). Values are base64-encoded `Uint8Array` state vectors.*/getDiskAckSVs?: () => Record<string, string>;+ /**+ * Live `/collab` WebSocket client count — editor windows and agents alike.+ * Disclosed on `GET /api/server-info` so a caller about to terminate this+ * server can ask whether anything is using it. Omitted (field absent) when+ * the boot path did not wire a counter; a reader must treat absence as+ * "unknown", never as zero.+ */+ getCollabClientCount?: () => number;contentRoot?: string;derivedDocumentIndex?: DerivedDocumentIndexApiPort;// `comments` joins main's narrowed channel union: the comment views are@@ -2918,6 +2927,7 @@ export function createApiExtension(flushContributors,getCurrentBranch,getDiskAckSVs,+ getCollabClientCount,contentRoot,derivedDocumentIndex,signalChannel: rawSignalChannel,@@ -5561,7 +5571,11 @@ export function createApiExtension(const position = body.position ?? 'append';const effectiveDocName = requireNonEmptyDocName(body.docName, res, 'agent-write-md');if (effectiveDocName === null) return;- const resolvedDocName = resolveAlias(effectiveDocName);+ // Collapse an extension-qualified spelling before it reaches the room+ // or the file index. Without this a write addressed as `notes.md`+ // leaves a second index row for the one file it actually wrote, and+ // that row then shadows the real one for later lookups.+ const resolvedDocName = canonicalDocName(resolveAlias(effectiveDocName));const { agentId, agentName, colorSeed, clientName, clientVersion, label } =extractAgentIdentity(body);@@ -7565,7 +7579,13 @@ export function createApiExtension(async (req, res) => {try {const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);- const docName = resolveAlias(url.searchParams.get('docName') ?? 'test-doc');+ // Collapse an extension-qualified spelling onto the document it names.+ // The room lookup below is a direct read, so without this a caller+ // asking for `notes.md` is answered from a room that never converged+ // with the `notes` room backing the same file.+ const docName = canonicalDocName(+ resolveAlias(url.searchParams.get('docName') ?? 'test-doc'),+ );// Path traversal guard — reuse the canonical validator from persistence.ts.// Throws `Invalid document name: ${docName}` for names that escape contentDir;@@ -8514,6 +8534,7 @@ export function createApiExtension(// `.optional()` keeps the response valid. All bounded numbers — safe to// disclose (per-process timing, no paths/content).const boot = getBootTimings();+ const collabClients = getCollabClientCount?.();// `Cache-Control: no-store` matches the disclosure semantics: every// field is per-process / per-moment state. A back/forward-cached// 304 carrying a stale `currentDiskAckSVs` could silently corrupt@@ -8527,6 +8548,7 @@ export function createApiExtension(currentBranch,...(currentDiskAckSVs !== undefined ? { currentDiskAckSVs } : {}),...(boot !== undefined ? { boot } : {}),+ ...(collabClients !== undefined ? { collabClients } : {}),},{handler: 'server-info',diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.tsindex a14319c16..b712885c9 100644--- a/packages/server/src/boot.ts+++ b/packages/server/src/boot.ts@@ -62,7 +62,12 @@ import {GitTooOldError,} from './git-preflight.ts';import { emitPreflightFailureSpan } from './git-preflight-telemetry.ts';-import { attachIdleShutdown, type IdleShutdownHandle } from './idle-shutdown.ts';+import {+ attachCollabClientCounter,+ attachIdleShutdown,+ type CollabClientCounter,+ type IdleShutdownHandle,+} from './idle-shutdown.ts';import { scanGlobalInPlaceSkills, scanInPlaceSkills } from './in-place-skills.ts';import { buildIngressPolicy, ExposureConsentError } from './ingress-policy.ts';import { resolveLocalSinkConfig } from './local-sink-resolver.ts';@@ -362,11 +367,18 @@ export interface BootServerOptionsskipStateManifestCheck?: boolean;}+/**+ * Why this server is shutting down. Recorded at the top of teardown so a bundle+ * distinguishes a stop/kill from a self-reap from the host going away — three+ * outcomes that otherwise leave byte-identical shutdown logs.+ */+export type ServerExitReason = 'external-signal' | 'idle-shutdown' | 'parent-exit' | 'unspecified';+export interface BootedServer {/** The bound HTTP server listening on `port`. */httpServer: HttpServer;/** Composite shutdown — closes httpServer, detaches idle-shutdown, destroys the Hocuspocus server (which releases server.lock). */- destroy: () => Promise<void>;+ destroy: (reason?: ServerExitReason) => Promise<void>;/** Absolute path to `<contentDir>/.ok`. */lockDir: string;/** Resolved content directory. */@@ -534,9 +546,9 @@ export async function bootServer(opts: BootServerOptions): Promise<BootedServer>throw err;}const innerDestroy = booted.destroy;- booted.destroy = async () => {+ booted.destroy = async (reason) => {try {- await innerDestroy();+ await innerDestroy(reason);} finally {crashCapture.uninstall();}@@ -772,8 +784,14 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {);}+ // Live `/collab` client count. The counter can only attach once the HTTP+ // server exists (further down), while the API extension is built here — so+ // the route reads through this indirection rather than a captured value.+ let collabClientCounter: CollabClientCounter | null = null;+// Compose createServer options from the subset we accept.const serverInstance = createServer({+ getCollabClientCount: () => collabClientCounter?.getCount() ?? 0,contentDir: opts.contentDir,projectDir: opts.projectDir,ingressPolicy,@@ -1028,10 +1046,15 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {// before that listen resolves. But if something ever does call this before// the real assignment, a clear error beats a "Cannot access 'destroy' before// initialization" TDZ trace.- let destroy: () => Promise<void> = async () => {+ let destroy: (reason?: ServerExitReason) => Promise<void> = async () => {throw new Error('bootServer: destroy() invoked before initialization — boot did not complete');};+ // Attached unconditionally: the count is the termination guard's predicate,+ // and desktop boots disable idle-shutdown entirely — exactly the topology+ // where a window is attached and a stop would strand it.+ collabClientCounter = attachCollabClientCounter(httpServer);+// Idle-shutdown wiring — suppressed entirely when idleShutdownMs is null.// The CLI uses this to tear the server down after 30 min of zero WS// clients; the Electron utility disables it because window-close IS the@@ -1046,10 +1069,13 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {});idleHandle = attachIdleShutdown({httpServer,+ // Share the counter attached above rather than attaching a second+ // listener to the same server for the same events.+ counter: collabClientCounter,thresholdMs: idleMs,log,onShutdown: idleHandler(async () => {- await destroy();+ await destroy('idle-shutdown');}),});}@@ -1195,9 +1221,10 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {if (timer !== undefined) clearTimeout(timer);}};- destroy = async (): Promise<void> => {+ destroy = async (reason: ServerExitReason = 'unspecified'): Promise<void> => {if (destroyed) return;destroyed = true;+ log.info({ reason, pid: process.pid, lockDir }, `[server] shutdown initiated (${reason})`);// Flip /readyz to not-ready synchronously, before any teardown step, so// probe-driven routers stop sending traffic during the drain window —// the HTTP mirror of the lock-file draining mark below.@@ -1222,6 +1249,12 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {log.warn({ err, step: 'markServerLockDraining' }, 'bootServer destroy step failed');}+ try {+ collabClientCounter?.detach();+ } catch (err) {+ log.warn({ err, step: 'collabClientCounter.detach' }, 'bootServer destroy step failed');+ }+try {idleHandle?.detach();} catch (err) {diff --git a/packages/server/src/collab-client-disclosure.test.ts b/packages/server/src/collab-client-disclosure.test.tsnew file mode 100644index 000000000..01d0c33cb--- /dev/null+++ b/packages/server/src/collab-client-disclosure.test.ts@@ -0,0 +1,60 @@+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { resolve } from 'node:path';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import { WebSocket } from 'ws';+import type { BootedServer } from './boot.ts';+import { bootCompositionRig } from './composition-rig.test-helper.ts';++/**+ * `GET /api/server-info` discloses the live `/collab` client count so a caller+ * about to terminate this process can ask whether anything is using it. The+ * count is the only answerable form of that question — the process title is+ * rewritten at start, so provenance is not recoverable from the OS.+ */+let tmpRoot: string;+let booted: BootedServer;++beforeAll(async () => {+ tmpRoot = await mkdtemp(resolve(tmpdir(), 'ok-collab-count-'));+ booted = await bootCompositionRig(tmpRoot);+ await booted.ready;+}, 60_000);++afterAll(async () => {+ await booted?.destroy();+ await rm(tmpRoot, { recursive: true, force: true });+});++async function readCollabClients(): Promise<number | undefined> {+ const res = await fetch(`http://127.0.0.1:${booted.port}/api/server-info`);+ expect(res.status).toBe(200);+ const body = (await res.json()) as { collabClients?: number };+ return body.collabClients;+}++describe('server-info collabClients', () => {+ test('reports zero with no clients attached', async () => {+ expect(await readCollabClients()).toBe(0);+ });++ test('counts a live collaboration client and releases it on close', async () => {+ const ws = new WebSocket(`ws://127.0.0.1:${booted.port}/collab/count-probe`);+ await new Promise<void>((resolvePromise, reject) => {+ ws.on('open', () => resolvePromise());+ ws.on('error', reject);+ });++ expect(await readCollabClients()).toBe(1);++ ws.close();+ await new Promise<void>((resolvePromise) => ws.on('close', () => resolvePromise()));+ // The count drops on the server's socket 'close', which can land after the+ // client-side close event.+ for (let attempt = 0; attempt < 50; attempt++) {+ if ((await readCollabClients()) === 0) break;+ await new Promise((r) => setTimeout(r, 20));+ }+ expect(await readCollabClients()).toBe(0);+ });+});diff --git a/packages/server/src/content-filter-descendant-probe.test.ts b/packages/server/src/content-filter-descendant-probe.test.tsnew file mode 100644index 000000000..32929df98--- /dev/null+++ b/packages/server/src/content-filter-descendant-probe.test.ts@@ -0,0 +1,56 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, test, vi } from 'vitest';++/**+ * The descendant-project gate memoizes its answer per directory. A probe that+ * THREW did not answer — caching it as "not a project" would admit a real+ * descendant project's content into this project's index for the life of the+ * filter, and nothing retries.+ */+const probe = vi.hoisted(() => ({ throwFor: null as string | null }));++vi.mock('./fs/find-project-root.ts', async (importOriginal) => {+ const actual = await importOriginal<typeof import('./fs/find-project-root.ts')>();+ return {+ ...actual,+ isProjectRoot: (dir: string): boolean => {+ if (probe.throwFor !== null && dir === probe.throwFor) {+ probe.throwFor = null;+ throw Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' });+ }+ return actual.isProjectRoot(dir);+ },+ };+});++const { createContentFilter } = await import('./content-filter.ts');++describe('descendant-project probe failures', () => {+ let projectDir: string | undefined;++ afterEach(() => {+ probe.throwFor = null;+ if (projectDir !== undefined) rmSync(projectDir, { recursive: true, force: true });+ projectDir = undefined;+ });++ test('a throwing probe is not cached as a negative', () => {+ projectDir = mkdtempSync(join(tmpdir(), 'ok-descendant-probe-'));+ const nested = join(projectDir, 'nested');+ mkdirSync(join(nested, '.ok'), { recursive: true });+ writeFileSync(join(nested, '.ok', 'config.yml'), 'autoSync:\n enabled: false\n');+ writeFileSync(join(nested, 'inside.md'), '# inside');++ const filter = createContentFilter({ projectDir, contentDir: projectDir });++ probe.throwFor = nested;+ expect(filter.isDirExcluded('nested')).toBe(false);++ // The probe answers on the next call: the descendant is recognized without+ // an ignore rebuild or a fresh filter.+ expect(filter.isDirExcluded('nested')).toBe(true);+ expect(filter.isExcluded('nested/inside.md')).toBe(true);+ });+});diff --git a/packages/server/src/content-filter.test.ts b/packages/server/src/content-filter.test.tsindex 82886ba82..47aa0bab7 100644--- a/packages/server/src/content-filter.test.ts+++ b/packages/server/src/content-filter.test.ts@@ -2916,4 +2916,104 @@ describe('ContentFilter', () => {expect(filter.isPathIgnored('sibling.png')).toBe(false);});});++ describe('descendant projects', () => {+ // Ancestor project with a real nested project and a folder that only+ // carries OK folder metadata. The two `.ok/` dirs differ by `config.yml`.+ function seedTwoLevelFixture(): void {+ writeFileSync(join(projectDir, 'ancestor.md'), '# ancestor');+ mkdirSync(join(projectDir, 'notes'), { recursive: true });+ writeFileSync(join(projectDir, 'notes', 'own.md'), '# own');++ mkdirSync(join(projectDir, 'nested', '.ok'), { recursive: true });+ writeFileSync(+ join(projectDir, 'nested', '.ok', 'config.yml'),+ 'autoSync:\n enabled: false\n',+ );+ writeFileSync(join(projectDir, 'nested', 'inside.md'), '# inside');+ mkdirSync(join(projectDir, 'nested', 'deep'), { recursive: true });+ writeFileSync(join(projectDir, 'nested', 'deep', 'deeper.md'), '# deeper');++ mkdirSync(join(projectDir, 'rules', '.ok', 'templates'), { recursive: true });+ writeFileSync(join(projectDir, 'rules', '.ok', 'frontmatter.yml'), 'type: note\n');+ writeFileSync(join(projectDir, 'rules', '.ok', 'templates', 'note.md'), '# template');+ writeFileSync(join(projectDir, 'rules', 'ruled.md'), '# ruled');+ }++ test('excludes a descendant project root and everything under it', () => {+ seedTwoLevelFixture();+ const filter = createContentFilter({ projectDir, contentDir: projectDir });++ expect(filter.isDirExcluded('nested')).toBe(true);+ expect(filter.isDirExcluded('nested/deep')).toBe(true);+ expect(filter.isExcluded('nested/inside.md')).toBe(true);+ expect(filter.isExcluded('nested/deep/deeper.md')).toBe(true);+ // A descendant project's own skills are its project's content, not ours.+ expect(filter.isExcluded('nested/.ok/skills/demo/SKILL.md')).toBe(true);++ // The ancestor's own content is untouched.+ expect(filter.isExcluded('ancestor.md')).toBe(false);+ expect(filter.isExcluded('notes/own.md')).toBe(false);+ expect(filter.isDirExcluded('notes')).toBe(false);+ });++ test('a nested `.ok` carrying only folder metadata is not a project', () => {+ seedTwoLevelFixture();+ const filter = createContentFilter({ projectDir, contentDir: projectDir });++ expect(filter.isDirExcluded('rules')).toBe(false);+ expect(filter.isExcluded('rules/ruled.md')).toBe(false);+ expect(filter.isExcluded('rules/.ok/templates/note.md')).toBe(false);+ });++ test('single-file scope is unaffected — the one admitted doc stays admitted', () => {+ seedTwoLevelFixture();+ const filter = createContentFilter({+ projectDir,+ contentDir: projectDir,+ singleDocRelPath: 'nested/inside.md',+ });++ expect(filter.isExcluded('nested/inside.md')).toBe(false);+ expect(filter.isDirExcluded('nested')).toBe(false);+ });++ test('detects the descendant root under either path base', () => {+ // Sync-scope callers pass project-relative paths; every other caller+ // passes contentDir-relative ones. Resolving both against contentDir+ // would silently miss the descendant on the project-relative side.+ mkdirSync(join(projectDir, 'content', 'docs', '.ok'), { recursive: true });+ writeFileSync(join(projectDir, 'content', 'docs', '.ok', 'config.yml'), 'x: 1\n');+ writeFileSync(join(projectDir, 'content', 'docs', 'inside.md'), '# inside');+ mkdirSync(join(projectDir, 'content', 'guides', '.ok'), { recursive: true });+ writeFileSync(join(projectDir, 'content', 'guides', '.ok', 'frontmatter.yml'), 'icon: map\n');+ writeFileSync(join(projectDir, 'content', 'guides', 'ruled.md'), '# ruled');++ const filter = createContentFilter({+ projectDir,+ contentDir: join(projectDir, 'content'),+ });+ const projectScope = { syncScope: { pathBase: 'project' } } as const;++ expect(filter.isDirExcluded('docs')).toBe(true);+ expect(filter.isExcluded('docs/inside.md')).toBe(true);+ expect(filter.isDirExcluded('content/docs', projectScope)).toBe(true);+ expect(filter.isExcluded('content/docs/inside.md', projectScope)).toBe(true);++ expect(filter.isDirExcluded('guides')).toBe(false);+ expect(filter.isDirExcluded('content/guides', projectScope)).toBe(false);+ expect(filter.isExcluded('content/guides/.ok/frontmatter.yml', projectScope)).toBe(false);+ });++ test('async factory mirrors the descendant-project floor', async () => {+ seedTwoLevelFixture();+ const filter = await createContentFilterAsync({ projectDir, contentDir: projectDir });++ expect(filter.isDirExcluded('nested')).toBe(true);+ expect(filter.isExcluded('nested/inside.md')).toBe(true);+ expect(filter.isExcluded('ancestor.md')).toBe(false);+ expect(filter.isDirExcluded('rules')).toBe(false);+ expect(filter.isExcluded('rules/ruled.md')).toBe(false);+ });+ });});diff --git a/packages/server/src/content-filter.ts b/packages/server/src/content-filter.tsindex fc5462b20..36c0d84c0 100644--- a/packages/server/src/content-filter.ts+++ b/packages/server/src/content-filter.ts@@ -36,6 +36,7 @@ import ignore, { type Ignore } from 'ignore';import { isReservedForUserTree } from './cc1-broadcast.ts';import { withHiddenWindowsConsole } from './child-process-windows-hide.ts';import { isSupportedDocFile, stripDocExtension } from './doc-extensions.ts';+import { isProjectRoot } from './fs/find-project-root.ts';import { getLogger } from './logger.ts';import { toPosix } from './path-utils.ts';import { withSpan } from './telemetry.ts';@@ -732,6 +733,74 @@ function isSingleDocAncestorDir(relativeDir: string, singleDocRelPath: string):return singleDocRelPath === relativeDir || singleDocRelPath.startsWith(`${relativeDir}/`);}+/**+ * Gate that keeps a descendant project's content out of the enclosing+ * project's scope.+ *+ * A directory carrying `.ok/config.yml` is its own project root, so a server+ * anchored there owns those files. Indexing them from the enclosing project as+ * well gives one file on disk two owners that reconcile only through disk+ * writes. `isProjectRoot` is the marker check, and it is also what keeps a+ * nested `.ok/` holding folder rules (`frontmatter.yml`, `templates/`) but no+ * `config.yml` admitted — folder metadata is not a project.+ *+ * Consulted by both `isExcluded` and `isDirExcluded` so a walker pruning+ * directories and a caller classifying a single path agree (precedent #55).+ *+ * Inert in single-file scope: an ephemeral single-doc filter has no enclosing+ * project, and the one admitted doc must stay admitted wherever it lives.+ */+function createDescendantProjectGate(+ projectDir: string,+ contentDir: string,+ singleDocRelPath: string | undefined,+): {+ isInside: (relativePath: string, syncScope?: { pathBase: 'content' | 'project' }) => boolean;+ reset: () => void;+} {+ const enabled = singleDocRelPath === undefined;+ // Memoized on the ABSOLUTE dir, so the two path bases a caller can use+ // (contentDir-relative by default, projectDir-relative under a project sync+ // scope) share one set of answers instead of drifting. Cleared on ignore+ // rebuild, so a project created under contentDir at runtime is recognized+ // from that point rather than immediately.+ const cache = new Map<string, boolean>();++ function isRoot(absoluteDir: string): boolean {+ const cached = cache.get(absoluteDir);+ if (cached !== undefined) return cached;+ let hit: boolean;+ try {+ hit = isProjectRoot(absoluteDir);+ } catch {+ // EACCES / ELOOP / EMFILE, or a race with a concurrent write: fall+ // through to the ordinary rules rather than excluding content we could+ // not classify — but do NOT cache it. "Could not tell" is not "not a+ // project"; memoizing it would admit a real descendant project for the+ // life of the filter on the strength of one transient error.+ return false;+ }+ cache.set(absoluteDir, hit);+ return hit;+ }++ return {+ isInside(relativePath: string, syncScope?: { pathBase: 'content' | 'project' }): boolean {+ if (!enabled || relativePath === '') return false;+ const base = syncScope?.pathBase === 'project' ? projectDir : contentDir;+ let prefix = base;+ for (const segment of relativePath.split('/')) {+ prefix = join(prefix, segment);+ if (isRoot(prefix)) return true;+ }+ return false;+ },+ reset(): void {+ cache.clear();+ },+ };+}+/** File names recognized as ignore-pattern sources, in load order. */const IGNORE_FILE_NAMES = ['.gitignore', '.okignore'] as const;@@ -1177,6 +1246,7 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {opts.attachmentFolderPath ?? DEFAULT_ATTACHMENT_FOLDER_PATH,);const skillRootPaths: ReadonlySet<string> = opts.skillRootPaths ?? new Set();+ const descendantProjects = createDescendantProjectGate(projectDir, contentDir, singleDocRelPath);// Precompute the contentDir-to-projectDir prefix for path conversion.// When contentDir is outside projectDir, the relative path starts with ".."@@ -1409,6 +1479,12 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {if (isSecretBearingFile(relativePath)) return true;if (pathHasSecretBearingDirSegment(relativePath)) return true;+ // Descendant-project floor — a directory carrying `.ok/config.yml` is+ // another project's root, and its content is that project's to own.+ // Ahead of the skills / templates carve-outs so a nested project's `.ok`+ // leaves are not re-admitted here as this project's content.+ if (descendantProjects.isInside(relativePath, opts?.syncScope)) return true;+// (0b) Skills-as-content carve-out — project skill files under// `.ok/skills/**` are real content. Admit supported docs + linkable// assets (no sibling-`.md` requirement), overriding the blanket `.ok`@@ -1551,6 +1627,11 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {// skills carve-out: a secret dir nested under a skill (`.ok/skills/x/.ssh`)// would otherwise be kept descendable by the ancestor carve-out.if (pathHasSecretBearingDirSegment(relativePath)) return true;+ // Descendant-project floor — prune another project's root so the walk+ // never enters it. Mirrors the file-level floor in `isExcluded`+ // (precedent #55) and precedes the skills / templates carve-outs, which+ // would otherwise keep a nested project's `.ok` descendable.+ if (descendantProjects.isInside(relativePath, opts?.syncScope)) return true;// Skills- and templates-as-content: keep `.ok`, `.ok/skills[/**]`, and// any `<folder>/.ok/templates` descendable so the NORMAL index walk// reaches skill + template leaves; the file-level predicates keep the rest@@ -1717,6 +1798,12 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {return rebuildInFlight;};const runRebuild = async (): Promise<RebuildResult> => {+ // Project roots can appear or vanish between walks, so the memoized+ // descendant answers must not outlive a rebuild. Reset per RUN rather+ // than at the entry point: callers arriving mid-flight piggyback on a+ // walk already in progress, and clearing under it would refill the+ // cache from a half-finished snapshot.+ descendantProjects.reset();// Refresh the in-place skill allow-list first (live re-scan): the new// set governs the dirCount refresh + every predicate after the swap. A// provider throw keeps the previous set (fail-soft, matching the@@ -2114,6 +2201,7 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Promopts.attachmentFolderPath ?? DEFAULT_ATTACHMENT_FOLDER_PATH,);const skillRootPaths: ReadonlySet<string> = opts.skillRootPaths ?? new Set();+ const descendantProjects = createDescendantProjectGate(projectDir, contentDir, singleDocRelPath);const contentRelPrefix = toPosix(relative(projectDir, contentDir));const contentOutsideProject = contentRelPrefix.startsWith('..');@@ -2274,6 +2362,11 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom// asset extension), so the floor wins over skill-asset admission.if (isSecretBearingFile(relativePath)) return true;if (pathHasSecretBearingDirSegment(relativePath)) return true;+ // Descendant-project floor — a directory carrying `.ok/config.yml` is+ // another project's root, and its content is that project's to own.+ // Ahead of the skills / templates carve-outs so a nested project's `.ok`+ // leaves are not re-admitted here as this project's content.+ if (descendantProjects.isInside(relativePath, opts?.syncScope)) return true;// Skills-as-content carve-out — admit project skill docs + linkable assets// under `.ok/skills/**` (see sync variant for rationale, incl. the// `!bypassFilters` gate that mirrors `isDirExcluded`).@@ -2353,6 +2446,11 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom// MUST precede the skills carve-out so a secret dir nested under a skill// (`.ok/skills/x/.ssh`) isn't kept descendable by the ancestor carve-out.if (pathHasSecretBearingDirSegment(relativePath)) return true;+ // Descendant-project floor — prune another project's root so the walk+ // never enters it. Mirrors the file-level floor in `isExcluded`+ // (precedent #55) and precedes the skills / templates carve-outs, which+ // would otherwise keep a nested project's `.ok` descendable.+ if (descendantProjects.isInside(relativePath, opts?.syncScope)) return true;// Skills- and templates-as-content: keep `.ok` / `.ok/skills[/**]` and any// `<folder>/.ok/templates` descendable for the NORMAL index walk only (see// sync variant); under bypass the always-skip floor below keeps `.ok`@@ -2491,6 +2589,12 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Promreturn rebuildInFlight;};const runRebuild = async (): Promise<RebuildResult> => {+ // Project roots can appear or vanish between walks, so the memoized+ // descendant answers must not outlive a rebuild. Reset per RUN rather+ // than at the entry point: callers arriving mid-flight piggyback on a+ // walk already in progress, and clearing under it would refill the+ // cache from a half-finished snapshot.+ descendantProjects.reset();// Refresh the in-place skill allow-list first (live re-scan) — mirrors// the sync factory; a provider throw keeps the previous set.if (opts.rescanInPlaceSkillDirs) {diff --git a/packages/server/src/doc-extensions.test.ts b/packages/server/src/doc-extensions.test.tsindex a2476b2e8..74b61f309 100644--- a/packages/server/src/doc-extensions.test.ts+++ b/packages/server/src/doc-extensions.test.ts@@ -1,6 +1,7 @@import { beforeEach, describe, expect, test } from 'vitest';import {_resetDocExtensionsForTests,+ canonicalDocName,docNameToRelativePath,forgetDocExtension,getDocExtension,@@ -193,3 +194,72 @@ describe('registerDocExtension / getDocExtension', () => {expect(() => registerDocExtension('foo', '')).toThrow();});});++describe('canonicalDocName', () => {+ test('collapses a stray extension onto its extension-less twin', () => {+ expect(canonicalDocName('specs/demo/SPEC.md')).toBe('specs/demo/SPEC');+ expect(canonicalDocName('notes.mdx')).toBe('notes');+ });++ test('collapses repeated extensions rather than leaving a qualified name', () => {+ expect(canonicalDocName('foo.md.md')).toBe('foo');+ expect(canonicalDocName('foo.mdx.md')).toBe('foo');+ });++ test('leaves an extension-less docName untouched', () => {+ expect(canonicalDocName('specs/demo/SPEC')).toBe('specs/demo/SPEC');+ });++ test('preserves the shadowed half of a real same-stem pair', () => {+ // Registered the way the watcher does it: by STEM, once per file seen.+ // `.mdx` wins, so `foo` resolves to the mdx and `foo.md` is the only way+ // to reach the md file.+ registerDocExtension('foo', '.md');+ registerDocExtension('foo', '.mdx');+ expect(canonicalDocName('foo.md')).toBe('foo.md');+ });++ test('collapses the winning half, which the bare stem already reaches', () => {+ registerDocExtension('foo', '.md');+ registerDocExtension('foo', '.mdx');+ expect(canonicalDocName('foo.mdx')).toBe('foo');+ });++ test('collapses when only one file exists under the stem', () => {+ registerDocExtension('solo', '.md');+ expect(canonicalDocName('solo.md')).toBe('solo');+ });++ test('collapses once the shadowing file is gone', () => {+ registerDocExtension('foo', '.md');+ registerDocExtension('foo', '.mdx');+ expect(canonicalDocName('foo.md')).toBe('foo.md');+ forgetDocExtension('foo');+ expect(canonicalDocName('foo.md')).toBe('foo');+ });++ test('registering a qualified name does not manufacture ambiguity', () => {+ // Guards the blind spot that hid an earlier defect: hand-registering+ // `notes.md` is a state the watcher never produces, and must not be+ // mistaken for a real pair.+ registerDocExtension('notes.md', '.md');+ expect(canonicalDocName('notes.md')).toBe('notes');+ });++ test('leaves non-markdown docNames that own their extension alone', () => {+ expect(canonicalDocName('diagram.mermaid')).toBe('diagram.mermaid');+ expect(canonicalDocName('board.excalidraw')).toBe('board.excalidraw');+ expect(canonicalDocName('script.ts')).toBe('script.ts');+ });++ test('is idempotent', () => {+ const once = canonicalDocName('specs/demo/SPEC.md');+ expect(canonicalDocName(once)).toBe(once);+ });++ test('resolves to the same file path as the name it collapses', () => {+ expect(docNameToRelativePath(canonicalDocName('specs/demo/SPEC.md'))).toBe(+ docNameToRelativePath('specs/demo/SPEC.md'),+ );+ });+});diff --git a/packages/server/src/doc-extensions.ts b/packages/server/src/doc-extensions.tsindex b2e628dbb..3e1e01a94 100644--- a/packages/server/src/doc-extensions.ts+++ b/packages/server/src/doc-extensions.ts@@ -106,6 +106,17 @@ function rank(ext: DocExtension): number {*/const docExtensionByName = new Map<string, string>();+/**+ * The LOSING extension when a docName has both `.md` and `.mdx` on disk.+ *+ * `docExtensionByName` records only the winner, so without this the fact that+ * a second file exists under the same stem is computed at registration and+ * then discarded. That fact is what makes an extension-qualified docName+ * meaningful: `foo.md` addresses a real, distinct file only while `foo`+ * resolves to `foo.mdx`.+ */+const shadowedExtByName = new Map<string, string>();+/*** Record the on-disk extension for a docName. The caller passes the actual* observed extension (e.g. `.MD` or `.mdx`); the casing is preserved verbatim@@ -131,6 +142,7 @@ export function registerDocExtension(const existing = docExtensionByName.get(docName);if (!existing) {docExtensionByName.set(docName, observedExt);+ shadowedExtByName.delete(docName);return { effective: observedExt, changed: true, shadowed: null };}const existingCanonical = canonicalize(existing);@@ -138,6 +150,7 @@ export function registerDocExtension(// Defensive: an entry stored without going through this function. Replace// it with the freshly observed (well-formed) extension and report change.docExtensionByName.set(docName, observedExt);+ shadowedExtByName.set(docName, existing);return { effective: observedExt, changed: true, shadowed: existing };}if (existingCanonical === canonical) {@@ -148,8 +161,10 @@ export function registerDocExtension(// Different canonical extensions — apply precedence.if (rank(canonical) < rank(existingCanonical)) {docExtensionByName.set(docName, observedExt);+ shadowedExtByName.set(docName, existing);return { effective: observedExt, changed: true, shadowed: existing };}+ shadowedExtByName.set(docName, observedExt);return { effective: existing, changed: false, shadowed: observedExt };}@@ -179,6 +194,55 @@ export function isRegisteredMarkdownDocName(docName: string): boolean {return recorded === '.md' || recorded === '.mdx';}+/**+ * Collapse an extension-qualified markdown docName onto its extension-less+ * twin unless the extension is load-bearing.+ *+ * Extension-qualified markdown docNames are legitimate for exactly one case:+ * same-stem `.md` and `.mdx` files that both exist on disk, which the disk+ * walk registers so each stays independently addressable. Those are the names+ * `isRegisteredMarkdownDocName` knows about, and they pass through untouched.+ *+ * Every other extension-carrying markdown name is a stray that would resolve+ * to the same file as its extension-less twin while keying a SEPARATE+ * collaboration room. Two rooms over one file diverge permanently and both+ * write to it, so the loser's edits are overwritten with no merge and no+ * conflict. Collapsing here is what keeps one file backed by one document.+ *+ * Non-markdown docNames (mermaid, excalidraw, editable-text) carry their+ * extension as part of their identity and are returned unchanged.+ *+ * Strips repeatedly so `foo.md.md` collapses to `foo` rather than to the+ * still-qualified `foo.md`.+ */+export function canonicalDocName(docName: string): string {+ if (!isSupportedDocFile(docName)) return docName;+ if (addressesShadowedSibling(docName)) return docName;+ let candidate = docName;+ while (isSupportedDocFile(candidate)) {+ candidate = stripDocExtension(candidate);+ }+ return candidate;+}++/**+ * True when `docName`'s extension addresses a file that would otherwise be+ * unreachable: the SHADOWED half of a same-stem `.md` + `.mdx` pair.+ *+ * The extension-less stem resolves to the winning file, so only the loser+ * needs its extension to stay addressable. Consulting the recorded shadow is+ * what ties this to files that actually exist — the registry keys stems, not+ * qualified names, so asking whether the qualified name is "registered" can+ * never be true for anything the watcher produced.+ */+function addressesShadowedSibling(docName: string): boolean {+ const stem = stripDocExtension(docName);+ if (stem === docName) return false;+ const shadowed = shadowedExtByName.get(stem);+ if (shadowed === undefined) return false;+ return docName.slice(stem.length).toLowerCase() === shadowed.toLowerCase();+}+/*** Materialize the content-tree relative path for a docName. Callers still own* traversal validation against their target root after resolving the result.@@ -222,10 +286,12 @@ export function extensionlessDocTreePath(fullPath: string, docName: string): str/** Clear the recorded extension for a docName (e.g. on file delete). */export function forgetDocExtension(docName: string): void {+ shadowedExtByName.delete(docName);docExtensionByName.delete(docName);}/** Test hook — reset the map between tests that share the module scope. */export function _resetDocExtensionsForTests(): void {+ shadowedExtByName.clear();docExtensionByName.clear();}diff --git a/packages/server/src/document-room-canonicalization.test.ts b/packages/server/src/document-room-canonicalization.test.tsnew file mode 100644index 000000000..d34b50cfa--- /dev/null+++ b/packages/server/src/document-room-canonicalization.test.ts@@ -0,0 +1,116 @@+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { resolve } from 'node:path';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import type { BootedServer } from './boot.ts';+import { bootCompositionRig, rawRequest } from './composition-rig.test-helper.ts';++/**+ * One file on disk must be backed by exactly one collaboration document.+ *+ * A name that keeps its markdown extension resolves to the same file as its+ * extension-less twin, so if the two key separate rooms both persist to that+ * file independently and the later write silently overwrites the earlier one.+ *+ * This drives a REAL booted server over a real socket rather than testing a+ * name-normalizing helper in isolation: the room key is chosen deep inside the+ * collaboration server, and a helper that looks correct can sit on a seam the+ * client never crosses. Only an end-to-end write/read across both spellings+ * proves the two names share a room.+ */++let tmpRoot: string;+let server: BootedServer;+let contentDir: string;++async function writeDoc(docName: string, markdown: string): Promise<number> {+ const res = await rawRequest(server.port, '/api/agent-write-md', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ docName, markdown, position: 'replace' }),+ });+ return res.status;+}++async function readDoc(docName: string): Promise<string> {+ const res = await rawRequest(server.port, `/api/document?docName=${encodeURIComponent(docName)}`);+ return res.body;+}++beforeAll(async () => {+ tmpRoot = await mkdtemp(resolve(tmpdir(), 'ok-room-canon-'));+ contentDir = tmpRoot;+ await writeFile(resolve(contentDir, 'notes.md'), '# original\n', 'utf-8');+ // A genuine same-stem pair: both files exist, so `pair.md` is the only way+ // to reach the md half once `pair` resolves to the mdx half.+ await writeFile(resolve(contentDir, 'pair.md'), 'MD-ORIGINAL\n', 'utf-8');+ await writeFile(resolve(contentDir, 'pair.mdx'), 'MDX-ORIGINAL\n', 'utf-8');+ server = await bootCompositionRig(contentDir);+ await server.ready;+}, 60_000);++afterAll(async () => {+ await server?.destroy();+ await rm(tmpRoot, { recursive: true, force: true });+});++describe('one file is backed by one collaboration document', () => {+ test('a write through the extension-qualified name is visible through the extension-less name', async () => {+ expect(await writeDoc('notes', 'CONTENT-A')).toBe(200);+ expect(await readDoc('notes')).toContain('CONTENT-A');++ expect(await writeDoc('notes.md', 'CONTENT-B')).toBe(200);++ // The failure this guards: the extension-qualified write lands in a second+ // room, disk holds CONTENT-B, and this read still returns the stale+ // CONTENT-A from a room that never converged.+ expect(await readDoc('notes')).toContain('CONTENT-B');+ expect(await readDoc('notes')).not.toContain('CONTENT-A');+ }, 30_000);++ test('both spellings resolve to the same document, and it reaches disk', async () => {+ await writeDoc('notes.md', 'CONVERGED');++ // Both spellings answer from one room, and echo the canonical name back.+ expect(await readDoc('notes')).toContain('CONVERGED');+ expect(await readDoc('notes.md')).toContain('CONVERGED');+ expect(await readDoc('notes.md')).toContain('"docName":"notes"');++ // Disk lags by the persistence debounce, so poll rather than assuming the+ // write has already landed.+ await expect+ .poll(() => readFile(resolve(contentDir, 'notes.md'), 'utf-8'), { timeout: 15_000 })+ .toContain('CONVERGED');+ }, 30_000);++ test('no shadow file is created for the extension-qualified name', async () => {+ await writeDoc('notes.md', 'NO-SHADOW');+ await expect(readFile(resolve(contentDir, 'notes.md.md'), 'utf-8')).rejects.toThrow();+ }, 30_000);+});++describe('a genuine same-stem pair stays independently addressable', () => {+ test('the shadowed half is reachable by its qualified name, not collapsed onto its sibling', async () => {+ const viaStem = await readDoc('pair');+ const viaShadowed = await readDoc('pair.md');++ // `.mdx` wins the stem by precedence, so the bare name must serve it.+ expect(viaStem).toContain('MDX-ORIGINAL');+ // ...and the md half must remain reachable rather than being answered+ // with its sibling's content.+ expect(viaShadowed).toContain('MD-ORIGINAL');+ expect(viaShadowed).not.toContain('MDX-ORIGINAL');+ }, 30_000);+});++describe('the file index is not polluted by an extension-qualified write', () => {+ test('a write addressed with the extension leaves one page row, not two', async () => {+ await writeDoc('notes.md', 'INDEX-CHECK');+ const pages = await rawRequest(server.port, '/api/pages');+ const rows = (pages.body.match(/"notes(\.md)?"/g) ?? []).filter(+ (r) => r === '"notes"' || r === '"notes.md"',+ );+ expect(rows).toContain('"notes"');+ expect(rows).not.toContain('"notes.md"');+ }, 30_000);+});diff --git a/packages/server/src/http/document-routes.ts b/packages/server/src/http/document-routes.tsindex 4eac74525..ab4462452 100644--- a/packages/server/src/http/document-routes.ts+++ b/packages/server/src/http/document-routes.ts@@ -25,7 +25,7 @@ import {import { collectReferencedAssets } from '../asset-references.ts';import { isConfigDoc, isSystemDoc } from '../cc1-broadcast.ts';import type { ContentFilter } from '../content-filter.ts';-import { getDocExtension } from '../doc-extensions.ts';+import { canonicalDocName, getDocExtension } from '../doc-extensions.ts';import type { FileIndexEntry, FolderIndexEntry } from '../file-watcher.ts';import type { PinoLogger } from '../logger.ts';import { extractPageIcon, extractPageTitle } from '../page-identity.ts';@@ -206,7 +206,11 @@ export function createDocumentRoutes(deps: DocumentRouteDeps): DocumentRoutes {});return;}- const docName = resolveAlias(rawDocName);+ // Collapse an extension-qualified spelling onto the document it names.+ // The room lookup below is a direct map read, so without this a caller+ // asking for `notes.md` misses the `notes` room and is answered from a+ // separate one that never converged with it.+ const docName = canonicalDocName(resolveAlias(rawDocName));if (isSystemDoc(docName) || isConfigDoc(docName)) {errorResponse(res,diff --git a/packages/server/src/idle-shutdown.test.ts b/packages/server/src/idle-shutdown.test.tsindex 293f992c4..33f562a8a 100644--- a/packages/server/src/idle-shutdown.test.ts+++ b/packages/server/src/idle-shutdown.test.ts@@ -3,7 +3,7 @@ import type { Server as HttpServer, IncomingMessage } from 'node:http';import type { Duplex } from 'node:stream';import type { Scheduler } from '@inkeep/open-knowledge-core';import { describe, expect, test, vi } from 'vitest';-import { attachIdleShutdown } from './idle-shutdown';+import { attachCollabClientCounter, attachIdleShutdown } from './idle-shutdown';// ─────────────────────────────────────────────────────────────// Test helpers@@ -389,3 +389,55 @@ describe('attachIdleShutdown', () => {});});});++describe('attachCollabClientCounter', () => {+ test('counts /collab upgrades and decrements on socket close', () => {+ const server = createFakeHttpServer();+ const counter = attachCollabClientCounter(server);+ expect(counter.getCount()).toBe(0);++ const a = createFakeSocket();+ const b = createFakeSocket();+ emitUpgrade(server, '/collab/doc-a', a);+ emitUpgrade(server, '/collab/doc-b', b);+ expect(counter.getCount()).toBe(2);++ (a as unknown as EventEmitter).emit('close');+ expect(counter.getCount()).toBe(1);+ (b as unknown as EventEmitter).emit('close');+ expect(counter.getCount()).toBe(0);+ });++ test('counts every client kind on /collab, including agent keepalive sockets', () => {+ const server = createFakeHttpServer();+ const counter = attachCollabClientCounter(server);+ emitUpgrade(server, '/collab/keepalive?connectionId=agent-1', createFakeSocket());+ expect(counter.getCount()).toBe(1);+ });++ test('ignores non-/collab upgrades', () => {+ const server = createFakeHttpServer();+ const counter = attachCollabClientCounter(server);+ emitUpgrade(server, '/mcp', createFakeSocket());+ expect(counter.getCount()).toBe(0);+ });++ test('detach stops counting', () => {+ const server = createFakeHttpServer();+ const counter = attachCollabClientCounter(server);+ counter.detach();+ emitUpgrade(server, '/collab/doc', createFakeSocket());+ expect(counter.getCount()).toBe(0);+ });++ test('reports changes so idle-shutdown can schedule off the same count', () => {+ const server = createFakeHttpServer();+ const seen: number[] = [];+ const counter = attachCollabClientCounter(server, (n) => seen.push(n));+ const socket = createFakeSocket();+ emitUpgrade(server, '/collab/doc', socket);+ (socket as unknown as EventEmitter).emit('close');+ expect(seen).toEqual([1, 0]);+ expect(counter.getCount()).toBe(0);+ });+});diff --git a/packages/server/src/idle-shutdown.ts b/packages/server/src/idle-shutdown.tsindex 97306b917..669775181 100644--- a/packages/server/src/idle-shutdown.ts+++ b/packages/server/src/idle-shutdown.ts@@ -40,6 +40,12 @@ export interface AttachIdleShutdownOptions {warnBeforeMs?: number;/** Injectable scheduler for deterministic tests. */scheduler?: Scheduler;+ /**+ * An already-attached counter to schedule off. Supplied when the caller+ * already counts for another consumer, so one upgrade listener serves both.+ * When omitted this attaches its own and owns tearing it down.+ */+ counter?: CollabClientCounter;}export interface IdleShutdownHandle {@@ -47,11 +53,79 @@ export interface IdleShutdownHandle {detach: () => void;}+export interface CollabClientCounter {+ /** Live `/collab` WebSocket clients right now — editor windows AND agents. */+ getCount: () => number;+ /**+ * Observe count changes. Returns an unsubscribe. Several consumers watch the+ * same count (idle-shutdown schedules off it; the server-info route reads+ * it), so this is a fan-out rather than a single callback — two counters over+ * one server would double the upgrade listeners and drift the moment the+ * counting rule changes.+ */+ subscribe: (listener: (count: number) => void) => () => void;+ /**+ * Removes the upgrade listener. Idempotent. Belongs to whoever CREATED the+ * counter — a consumer handed one it did not create unsubscribes instead,+ * or it would stop counting for every other consumer.+ */+ detach: () => void;+}++/**+ * Count live `/collab` WebSocket upgrades on `httpServer`.+ *+ * The single counting implementation: idle-shutdown schedules off it, and the+ * server-info route discloses it so a caller about to terminate this process+ * can ask "is anything using it" rather than "who started it" (the latter is+ * unanswerable — the process title is rewritten at start). DirectConnections+ * (CC1 broadcaster, agent sessions) never transit an upgrade and are invisible+ * here, which is what keeps a permanently-connected internal consumer from+ * pinning the count above zero (precedent #14).+ */+export function attachCollabClientCounter(+ httpServer: HttpServer,+ onChange?: (count: number) => void,+): CollabClientCounter {+ let count = 0;+ let detached = false;+ const listeners = new Set<(next: number) => void>();+ if (onChange) listeners.add(onChange);+ const emit = (next: number): void => {+ for (const listener of listeners) listener(next);+ };++ const onUpgrade = (req: IncomingMessage, socket: Duplex): void => {+ if (!req.url?.startsWith('/collab')) return;+ count++;+ emit(count);+ socket.once('close', () => {+ count--;+ if (count < 0) count = 0;+ emit(count);+ });+ };++ httpServer.on('upgrade', onUpgrade);++ return {+ getCount: () => count,+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ detach: () => {+ if (detached) return;+ detached = true;+ httpServer.off('upgrade', onUpgrade);+ },+ };+}+export function attachIdleShutdown(opts: AttachIdleShutdownOptions): IdleShutdownHandle {const scheduler = opts.scheduler ?? defaultScheduler;const warnBeforeMs = opts.warnBeforeMs ?? DEFAULT_WARN_BEFORE_MS;- let webSocketClientCount = 0;let shutdownTimer: ReturnType<typeof setTimeout> | null = null;let warnTimer: ReturnType<typeof setTimeout> | null = null;let fired = false;@@ -71,12 +145,12 @@ export function attachIdleShutdown(opts: AttachIdleShutdownOptions): IdleShutdowfunction scheduleShutdown(): void {clearTimers();if (detached || fired) return;- if (webSocketClientCount !== 0) return;+ if (counter.getCount() !== 0) return;if (warnBeforeMs > 0 && warnBeforeMs < opts.thresholdMs) {warnTimer = scheduler.setTimeout(() => {warnTimer = null;- if (webSocketClientCount === 0 && !fired) {+ if (counter.getCount() === 0 && !fired) {opts.log?.warn({ msUntilShutdown: warnBeforeMs, webSocketClientCount: 0 },'idle shutdown pending: no WebSocket clients',@@ -88,7 +162,7 @@ export function attachIdleShutdown(opts: AttachIdleShutdownOptions): IdleShutdowshutdownTimer = scheduler.setTimeout(() => {shutdownTimer = null;if (detached || fired) return;- if (webSocketClientCount !== 0) return;+ if (counter.getCount() !== 0) return;fired = true;opts.log?.info({ webSocketClientCount: 0 }, 'idle shutdown firing');try {@@ -104,25 +178,23 @@ export function attachIdleShutdown(opts: AttachIdleShutdownOptions): IdleShutdow}, opts.thresholdMs);}- const onUpgrade = (req: IncomingMessage, socket: Duplex): void => {- if (!req.url?.startsWith('/collab')) return;- webSocketClientCount++;- clearTimers();- socket.once('close', () => {- webSocketClientCount--;- if (webSocketClientCount < 0) webSocketClientCount = 0;- if (webSocketClientCount === 0) scheduleShutdown();- });+ const onCount = (count: number): void => {+ if (count === 0) scheduleShutdown();+ else clearTimers();};+ const ownsCounter = opts.counter === undefined;+ const counter = opts.counter ?? attachCollabClientCounter(opts.httpServer);+ const unsubscribe = counter.subscribe(onCount);- opts.httpServer.on('upgrade', onUpgrade);scheduleShutdown();return {detach: () => {if (detached) return;detached = true;- opts.httpServer.off('upgrade', onUpgrade);+ unsubscribe();+ // Detaching a counter we were handed would stop counting for its owner.+ if (ownsCounter) counter.detach();clearTimers();},};diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex f8943a3e9..11775e6b5 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -72,6 +72,7 @@ export {type BootServerOptions,bootServer,restoreLifecycleFromConflictsJson,+ type ServerExitReason,} from './boot.ts';export {type BuildSkillZipOptions,@@ -238,7 +239,9 @@ export {} from './http/error-response.ts';export {type AttachIdleShutdownOptions,+ attachCollabClientCounter,attachIdleShutdown,+ type CollabClientCounter,type IdleShutdownHandle,} from './idle-shutdown.ts';export {@@ -540,11 +543,13 @@ export { redactShareSubprocessStderr } from './share/publish.ts';export {createEphemeralProjectDir,EPHEMERAL_PROJECT_DIR_PREFIX,+ type PrepareSingleFileOpenOptions,prepareSingleFileOpen,SingleFileNotAFileError,SingleFileNotFoundError,SingleFileNotMarkdownError,type SingleFileOpenPlan,+ SingleFileProjectOverrideError,seedEphemeralProjectDir,} from './single-file-open.ts';export {diff --git a/packages/server/src/server-exit-reason.test.ts b/packages/server/src/server-exit-reason.test.tsnew file mode 100644index 000000000..5260d0269--- /dev/null+++ b/packages/server/src/server-exit-reason.test.ts@@ -0,0 +1,99 @@+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { resolve } from 'node:path';+import { describe, expect, test } from 'vitest';+import { bootCompositionRig } from './composition-rig.test-helper.ts';+import type { PinoLogger } from './logger.ts';++/**+ * Shutdown records WHY the server exited. Without it an external stop, an idle+ * self-reap, and the host going away leave byte-identical logs, so the whole+ * class is invisible after the fact.+ */+interface Entry {+ level: string;+ msg: string;+ payload: Record<string, unknown>;+}++function captureLog(): { log: PinoLogger; entries: Entry[] } {+ const entries: Entry[] = [];+ const record =+ (level: string) =>+ (data: unknown, message?: string): void => {+ entries.push({+ level,+ msg: message ?? '',+ payload: (data as Record<string, unknown>) ?? {},+ });+ };+ const log = {+ info: record('info'),+ warn: record('warn'),+ error: record('error'),+ debug: record('debug'),+ trace: record('trace'),+ fatal: record('fatal'),+ } as unknown as PinoLogger;+ return { log, entries };+}++describe('server exit reason', () => {+ test('an external signal teardown records the reason', async () => {+ const dir = await mkdtemp(resolve(tmpdir(), 'ok-exit-reason-'));+ const { log, entries } = captureLog();+ const booted = await bootCompositionRig(dir, { log });+ await booted.ready;+ try {+ await booted.destroy('external-signal');+ const record = entries.find((e) => e.msg.includes('shutdown initiated'));+ expect(record).toBeDefined();+ expect(record?.payload.reason).toBe('external-signal');+ expect(record?.payload.pid).toBe(process.pid);+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+ }, 60_000);++ test('an idle self-reap records a different reason than an external stop', async () => {+ const dir = await mkdtemp(resolve(tmpdir(), 'ok-exit-reason-idle-'));+ const { log, entries } = captureLog();+ let fireIdle: (() => Promise<void>) | undefined;+ const booted = await bootCompositionRig(dir, {+ log,+ // Boot wires the handler around its own destroy; capture it instead of+ // waiting out a real idle window.+ idleShutdownMs: 60_000,+ idleShutdownHandler: (destroyServer) => {+ fireIdle = destroyServer;+ return async () => {+ await destroyServer();+ };+ },+ });+ await booted.ready;+ try {+ expect(fireIdle).toBeDefined();+ await fireIdle?.();+ const record = entries.find((e) => e.msg.includes('shutdown initiated'));+ expect(record?.payload.reason).toBe('idle-shutdown');+ } finally {+ await booted.destroy();+ await rm(dir, { recursive: true, force: true });+ }+ }, 60_000);++ test('an unattributed teardown is recorded as unspecified, not as a stop', async () => {+ const dir = await mkdtemp(resolve(tmpdir(), 'ok-exit-reason-plain-'));+ const { log, entries } = captureLog();+ const booted = await bootCompositionRig(dir, { log });+ await booted.ready;+ try {+ await booted.destroy();+ const record = entries.find((e) => e.msg.includes('shutdown initiated'));+ expect(record?.payload.reason).toBe('unspecified');+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+ }, 60_000);+});diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.tsindex 4b2a87779..093c8c79a 100644--- a/packages/server/src/server-factory.ts+++ b/packages/server/src/server-factory.ts@@ -124,7 +124,12 @@ import {type DerivedDocumentIndexBranchTransition,} from './derived-document-index.ts';import { applyDiskContentToDoc } from './disk-content-intake.ts';-import { docNameToRelativePath, getDocExtension, stripDocExtension } from './doc-extensions.ts';+import {+ canonicalDocName,+ docNameToRelativePath,+ getDocExtension,+ stripDocExtension,+} from './doc-extensions.ts';import { runDocLineageGuard } from './doc-lineage-guard.ts';import { DocumentDurabilityState } from './document-durability-state.ts';import {@@ -310,6 +315,13 @@ export interface ServerOptions {* exposed in production. Enable only in tests.*/enableTestRoutes?: boolean;+ /**+ * Live `/collab` WebSocket client count, disclosed on `GET /api/server-info`.+ * Wired by `bootServer` (which owns the HTTP server the counter attaches to);+ * omitted by the dev-server / plugin path, where the field is left off the+ * response rather than reported as a possibly-wrong zero.+ */+ getCollabClientCount?: () => number;/** Shadow repo handle — passed to persistence. */shadowRepo?: ShadowHandle;/** Content root relative to project dir. */@@ -2426,6 +2438,25 @@ export function createServer(options: ServerOptions): ServerInstance {extensions: [persistence.extension],});+ // Server-side room access converges on `openDirectConnection`, so an+ // extension-qualified name is collapsed before it can key a SECOND room+ // over the same file on disk. Two rooms over one file persist+ // independently and the later write overwrites the earlier one with no+ // merge and no conflict surfaced.+ //+ // Deliberately NOT wrapping `createDocument`: overriding that method+ // perturbs the collaboration server's own internals and broke sync+ // conflict resolution even for names this guard leaves untouched. The+ // names that reach a room converge instead at the surfaces that accept+ // them from outside: the HTTP document read and write routes here, and+ // the client's own navigation and tab-restore paths.+ const openDirect = hocuspocus.openDirectConnection.bind(hocuspocus);+ hocuspocus.openDirectConnection = ((documentName: string, context?: unknown) =>+ openDirect(+ canonicalDocName(documentName),+ context,+ )) as typeof hocuspocus.openDirectConnection;+// Workload observable gauges (loaded docs, persistence queue depths,// bridge drain backlog). Providers are sampled only at metric-export// time; registering them is a Set add and safe when OTel is disabled.@@ -3007,6 +3038,7 @@ export function createServer(options: ServerOptions): ServerInstance {// server has flushed nothing yet, matching the schema's// empty-object case.getDiskAckSVs: () => cc1Broadcaster?.getLatestDiskAckSVsAsBase64() ?? {},+ getCollabClientCount: options.getCollabClientCount,contentRoot,derivedDocumentIndex,signalChannel,diff --git a/packages/server/src/single-file-open.test.ts b/packages/server/src/single-file-open.test.tsindex e21d89da4..f0d259cdd 100644--- a/packages/server/src/single-file-open.test.ts+++ b/packages/server/src/single-file-open.test.ts@@ -18,6 +18,7 @@ import {SingleFileNotAFileError,SingleFileNotFoundError,SingleFileNotMarkdownError,+ SingleFileProjectOverrideError,seedEphemeralProjectDir,} from './single-file-open.ts';@@ -123,6 +124,71 @@ describe('prepareSingleFileOpen', () => {});});+describe('prepareSingleFileOpen with an explicit project root', () => {+ test('honors the named root and skips the ancestor walk', () => {+ const outer = tmp('sfo-outer-');+ makeProject(outer);+ const inner = join(outer, 'nested');+ mkdirSync(inner, { recursive: true });+ makeProject(inner);+ writeFileSync(join(inner, 'notes.md'), '# Notes\n');++ // Innermost-wins is unchanged without an override…+ const walked = prepareSingleFileOpen(join(inner, 'notes.md'));+ if (walked.mode !== 'project') throw new Error('expected project mode');+ expect(walked.projectRoot).toBe(inner);++ // …and the override outranks it when named.+ const overridden = prepareSingleFileOpen(join(inner, 'notes.md'), { projectRoot: outer });+ if (overridden.mode !== 'project') throw new Error('expected project mode');+ expect(overridden.projectRoot).toBe(outer);+ expect(overridden.docName).toBe('nested/notes');+ });++ test('an override that is not a project root fails loudly', () => {+ const root = tmp('sfo-ovr-notproj-');+ makeProject(root);+ writeFileSync(join(root, 'notes.md'), '# Notes\n');+ const bare = tmp('sfo-ovr-bare-');+ expect(() => prepareSingleFileOpen(join(root, 'notes.md'), { projectRoot: bare })).toThrow(+ SingleFileProjectOverrideError,+ );+ });++ test('an override that does not contain the file fails loudly', () => {+ const root = tmp('sfo-ovr-elsewhere-');+ makeProject(root);+ const other = tmp('sfo-ovr-other-');+ makeProject(other);+ writeFileSync(join(other, 'notes.md'), '# Notes\n');+ expect(() => prepareSingleFileOpen(join(other, 'notes.md'), { projectRoot: root })).toThrow(+ /not inside that project/,+ );+ });++ test('the override respects content.dir', () => {+ const root = tmp('sfo-ovr-contentdir-');+ makeProject(root, 'docs');+ mkdirSync(join(root, 'docs'), { recursive: true });+ writeFileSync(join(root, 'docs', 'intro.md'), '# Intro\n');+ const plan = prepareSingleFileOpen(join(root, 'docs', 'intro.md'), { projectRoot: root });+ if (plan.mode !== 'project') throw new Error('expected project mode');+ expect(plan.docName).toBe('intro');+ });++ test('realpath still runs before the override is applied', () => {+ const root = tmp('sfo-ovr-symlink-');+ makeProject(root);+ writeFileSync(join(root, 'real.md'), '# Real\n');+ const linkDir = tmp('sfo-ovr-link-');+ symlinkSync(join(root, 'real.md'), join(linkDir, 'alias.md'));+ const plan = prepareSingleFileOpen(join(linkDir, 'alias.md'), { projectRoot: root });+ if (plan.mode !== 'project') throw new Error('expected project mode');+ expect(plan.canonicalFilePath).toBe(join(root, 'real.md'));+ expect(plan.docName).toBe('real');+ });+});+describe('createEphemeralProjectDir', () => {test('synthesizes a throwaway projectDir with a valid .ok/config.yml + .gitignore', () => {const contentDir = tmp('sfo-content-');diff --git a/packages/server/src/single-file-open.ts b/packages/server/src/single-file-open.tsindex e8761d416..94496601b 100644--- a/packages/server/src/single-file-open.ts+++ b/packages/server/src/single-file-open.ts@@ -18,11 +18,11 @@import { mkdirSync, mkdtempSync, realpathSync, statSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { basename, dirname, relative, resolve, sep } from 'node:path';+import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';import { OK_DIR } from '@inkeep/open-knowledge-core';import { readConfigSafely, resolveConfigPath } from '@inkeep/open-knowledge-core/server';import { isSupportedDocFile, stripDocExtension } from './doc-extensions.ts';-import { findEnclosingProjectRoot } from './fs/find-project-root.ts';+import { findEnclosingProjectRoot, isProjectRoot } from './fs/find-project-root.ts';/** The file passed to `ok <file>` does not exist on disk. */export class SingleFileNotFoundError extends Error {@@ -40,6 +40,21 @@ export class SingleFileNotAFileError extends Error {}}+/**+ * An explicit `--project` override could not be honored (the path is not an+ * OpenKnowledge project root, or the file does not live under it). Callers+ * exit non-zero rather than silently resolving a different project.+ */+export class SingleFileProjectOverrideError extends Error {+ constructor(+ readonly projectRoot: string,+ reason: string,+ ) {+ super(`Cannot open with --project ${projectRoot}: ${reason}`);+ this.name = 'SingleFileProjectOverrideError';+ }+}+/** The file passed to `ok <file>` is not a supported markdown file (.md/.mdx). */export class SingleFileNotMarkdownError extends Error {constructor(readonly filePath: string) {@@ -76,7 +91,20 @@ export type SingleFileOpenPlan =* message). REALPATHS the file first, then runs project detection on the* canonical parent dir.*/-export function prepareSingleFileOpen(filePath: string): SingleFileOpenPlan {+export interface PrepareSingleFileOpenOptions {+ /**+ * Explicit project root (the `--project` override). When given, the ancestor+ * walk is skipped entirely and the named root is used — or the call fails+ * loudly. Never a silent fallback: an override that cannot be honored is a+ * wrong-project open waiting to happen.+ */+ readonly projectRoot?: string;+}++export function prepareSingleFileOpen(+ filePath: string,+ options: PrepareSingleFileOpenOptions = {},+): SingleFileOpenPlan {// Validate the markdown extension on the user-supplied path before touching// the filesystem — a clear, fast rejection for `ok notes.txt`.if (!isSupportedDocFile(filePath)) {@@ -98,6 +126,31 @@ export function prepareSingleFileOpen(filePath: string): SingleFileOpenPlan {}const fileDir = dirname(canonicalFilePath);++ if (options.projectRoot !== undefined) {+ const projectRoot = resolve(options.projectRoot);+ if (!isProjectRoot(projectRoot)) {+ throw new SingleFileProjectOverrideError(+ projectRoot,+ 'no .ok/config.yml there, so it is not an OpenKnowledge project root',+ );+ }+ const projectContentDir = resolveProjectContentDir(projectRoot);+ const relPath = relative(projectContentDir, canonicalFilePath);+ if (relPath.startsWith('..') || isAbsolute(relPath)) {+ throw new SingleFileProjectOverrideError(+ projectRoot,+ `${canonicalFilePath} is not inside that project's content directory`,+ );+ }+ return {+ mode: 'project',+ projectRoot,+ docName: stripDocExtension(relPath.split(sep).join('/')),+ canonicalFilePath,+ };+ }+const hit = findEnclosingProjectRoot(fileDir);if (hit) {const projectRoot = hit.rootPath;diff --git a/packages/server/src/sync-engine.test.ts b/packages/server/src/sync-engine.test.tsindex 15171f082..878e03485 100644--- a/packages/server/src/sync-engine.test.ts+++ b/packages/server/src/sync-engine.test.ts@@ -3654,6 +3654,7 @@ describe('SyncEngine push cycle stages shareable .ok artifacts (sync scope)', ()test('stages the project-root shareable set alongside subfolder content', async () => {const { git } = await initSharedRepoWithBareRemote();mkdirSync(join(projectDir, 'content', 'docs', '.ok'), { recursive: true });+ mkdirSync(join(projectDir, 'content', 'guides', '.ok'), { recursive: true });mkdirSync(join(projectDir, 'content', '.ok', 'schemas'), { recursive: true });mkdirSync(join(projectDir, 'content', '.ok', 'templates'), { recursive: true });mkdirSync(join(projectDir, '.ok', 'schemas'), { recursive: true });@@ -3667,8 +3668,13 @@ describe('SyncEngine push cycle stages shareable .ok artifacts (sync scope)', ()writeFileSync(join(projectDir, 'content', '.ok', 'schemas', 'nested.json'), '{}\n');writeFileSync(join(projectDir, 'content', '.ok', 'templates', 'daily.md'), '# Daily\n');writeFileSync(join(projectDir, 'content', 'note.md'), '# Note\n');+ // `content/docs` carries the project marker, so it is a descendant+ // project: nothing under it belongs to this project's scope. Folder+ // metadata with no marker beside it (`content/guides`) is an ordinary+ // folder rule and still stages.writeFileSync(join(projectDir, 'content', 'docs', '.ok', 'config.yml'), 'not: project\n');writeFileSync(join(projectDir, 'content', 'docs', '.ok', 'frontmatter.yml'), 'icon: book\n');+ writeFileSync(join(projectDir, 'content', 'guides', '.ok', 'frontmatter.yml'), 'icon: map\n');const engine = makeSubfolderEngine();try {@@ -3687,7 +3693,7 @@ describe('SyncEngine push cycle stages shareable .ok artifacts (sync scope)', ()'.ok/templates/meeting.md','content/.ok/templates/daily.md','content/note.md',- 'content/docs/.ok/frontmatter.yml',+ 'content/guides/.ok/frontmatter.yml',]) {expect(headPaths).toContain(path);}@@ -3695,6 +3701,7 @@ describe('SyncEngine push cycle stages shareable .ok artifacts (sync scope)', ()expect(headPaths).not.toContain('content/.ok/.gitignore');expect(headPaths).not.toContain('content/.ok/schemas/nested.json');expect(headPaths).not.toContain('content/docs/.ok/config.yml');+ expect(headPaths).not.toContain('content/docs/.ok/frontmatter.yml');const remoteHead = (await git.revparse(['origin/main'])).trim();expect(remoteHead).toBe((await git.revparse(['HEAD'])).trim());