Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Share-link freshness signal + honest renamed/deleted receive handling (#2415)
miles-kt-inkeep2a349f80526c
diff --git a/.changeset/share-freshness-send.md b/.changeset/share-freshness-send.mdnew file mode 100644index 000000000..c4844481e--- /dev/null+++ b/.changeset/share-freshness-send.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": minor+---++Share links now tell you at share time when the link won't show what you see. When you copy a share link for a doc or folder that isn't on GitHub yet, or that has unpushed changes, the share popover shows a non-blocking warning — for example "This doc isn't on GitHub yet. The link won't work until it's pushed." or "This doc has unpushed changes. Recipients will see the last pushed version." The warning stays out of the way when the target is already up to date (and when auto-sync will publish the change on its own). The `share_link` MCP tool relays the same signal so agents don't hand over a dead link as if it were good. The freshness check is local-only — it never reaches the network, and it never blocks or fails the share.diff --git a/.changeset/share-receive-branch-verdict.md b/.changeset/share-receive-branch-verdict.mdnew file mode 100644index 000000000..7c4c54ec2--- /dev/null+++ b/.changeset/share-receive-branch-verdict.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": minor+---++Opening a share link whose target moved or vanished now gives an honest, cause-specific answer instead of a misleading "not on this branch yet." When the shared doc or folder is missing on your current branch, the branch-switch dialog checks GitHub and tells you what actually happened: if it was just added to the branch, "Switch and update branch" fast-forwards your local branch and opens it; if it moved, you're offered to open it at its new path; if it was removed, you're told so plainly; and if it was never pushed, you're told that distinctly (never "removed"). If your local branch has diverged from GitHub, the update is refused and a plain switch is offered with an honest note — the receive flow never merges or rebases, leaving reconciliation to sync. When the check can't reach GitHub, it falls back to today's behavior.diff --git a/.changeset/share-receive-miss-panel.md b/.changeset/share-receive-miss-panel.mdnew file mode 100644index 000000000..7fc0b5a4f--- /dev/null+++ b/.changeset/share-receive-miss-panel.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": minor+---++Opening a share link no longer drops you into an empty "start writing" editor when the shared doc isn't on your checkout — the trap where typing would silently fork a new doc at the shared path. When a share-receive navigation lands on a target your branch doesn't carry, the editor now renders an honest panel that checks GitHub and explains what happened: your local copy is just behind (pull to get it), the doc moved (open it at its new path), it was removed, or it was never pushed to the branch. Each panel offers a Browse folder escape to the parent folder, and the check falls back to today's pull guidance when GitHub can't be reached. Ordinary in-app navigation (wiki links) still creates a new page on navigate as before.diff --git a/docs/content/features/share.mdx b/docs/content/features/share.mdxindex b48516987..d00397233 100644--- a/docs/content/features/share.mdx+++ b/docs/content/features/share.mdx@@ -21,6 +21,15 @@ If the project has no `origin` configured, the Share button opens the **PublishIf the push fails after the repo was created (auth lost mid-flow, network blip), the wizard shows a **Retry push** affordance. The GitHub-side repo isn't recreated, only the push is retried.+### Freshness warnings++A share link points at GitHub, but your local edits only reach GitHub through auto-sync (off by default) or a manual push. When you click Share, OpenKnowledge checks the shared doc or folder against its last-known state on GitHub and, if the link won't yet show what you're looking at, adds a non-blocking warning row to the popover:++- **Not on GitHub yet.** The target has never been pushed, so the link won't resolve until it is. With auto-sync off, the row offers **Enable auto-sync** and **How to push manually**; with auto-sync on, it offers **Sync now** and clears itself once the push lands.+- **Unpushed changes.** The target is on GitHub but has local edits that aren't, so recipients see the last pushed version. With auto-sync on this stays silent — the next sync closes the gap.++If you don't have write access to the repo, the row explains that instead of offering a push action. The check is local, adds no network round-trip, and never blocks sharing: if it can't run, the link still copies with no warning. Folder shares get the same treatment as docs.+## Opening a share linkThe recipient clicks the URL and lands on a splash page showing the target (file or folder) name, the `owner/repo` path, and the branch from which it was shared.@@ -40,10 +49,18 @@ The deep link arrives at the desktop app's handler, which runs a three-question### Receiving on a different branch-If you have the repo open locally but on a different branch, the app falls through to a branch-switch dialog instead of silently opening the wrong content. Behavior depends on whether the shared target (file or folder) exists on your current branch:+If you have the repo open locally but on a different branch, the app opens a branch-switch dialog instead of silently showing the wrong content. It compares the shared target (file or folder) against your current branch and against GitHub, then offers the action that matches what it finds:++- **On your current branch.** Open it where you are, or switch to the share's branch and open.+- **Not local yet, but on GitHub (your local copy is behind).** **Switch and update branch** fast-forwards your local branch to GitHub's tip and opens the doc. This is fast-forward-only — the receive flow never merges. A branch that has diverged from GitHub instead gets a plain switch with a note that the doc will appear once the branch syncs.+- **Moved.** If GitHub shows the target was renamed, the dialog offers to open it at its new path.+- **Removed, or never pushed.** A deleted target is messaged as removed from the branch; a path that never existed on the branch is messaged as "may not have been pushed yet." The two are distinct, and neither drops you into an empty create-mode editor.++If OpenKnowledge can't reach GitHub to make this call, it falls back to today's "pull the latest, then re-open" guidance.++### When the shared target has moved or been removed-- **Target exists on both branches.** The dialog offers `Open on <current-branch>` or `Switch to <share-branch> and open`.-- **Target only on the share's branch.** The dialog offers `Switch to <share-branch> and open` plus Cancel.+Even on the right branch, a doc or folder can be renamed or deleted after a link is minted. Rather than opening an empty editor at the old path — where you could unknowingly start a divergent copy — OpenKnowledge shows an honest terminal panel with the same verdict-driven copy as the branch-switch dialog: an offer to open a renamed target at its new path, a plain "removed from this branch" message with a link back to the parent folder, or "not pushed yet" when the path never existed. If the check can't reach GitHub, it falls back to the usual pull-and-retry guidance.### Receiving without push permissiondiff --git a/packages/app/src/App.dom.test.tsx b/packages/app/src/App.dom.test.tsxindex e557be590..3a6ba9783 100644--- a/packages/app/src/App.dom.test.tsx+++ b/packages/app/src/App.dom.test.tsx@@ -158,6 +158,10 @@ mock.module('@/components/ShareBranchSwitchDialog', () => ({ShareBranchSwitchDialog: () => <div data-testid="share-branch-switch-dialog" />,}));+mock.module('@/components/ShareReceiveMissDialog', () => ({+ ShareReceiveMissDialog: () => <div data-testid="share-receive-miss-dialog" />,+}));+mock.module('@/components/NewItemDialog', () => ({isNewItemShortcut: () => false,NewItemDialog: ({ open, initialDir }: { open: boolean; initialDir: string }) => (diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsxindex acf37f30b..7a363463c 100644--- a/packages/app/src/App.tsx+++ b/packages/app/src/App.tsx@@ -1,5 +1,5 @@import { mediaKindForSidebarAssetExtension, SHOW_INSTALL_SKILL } from '@inkeep/open-knowledge-core';-import { type ReactNode, useEffect, useRef, useState } from 'react';+import { lazy, type ReactNode, Suspense, useEffect, useRef, useState } from 'react';import { CommandPalette } from '@/components/CommandPalette';import { ConnectingBanner } from '@/components/ConnectingBanner';import { CreateProjectMenuTrigger } from '@/components/CreateProjectMenuTrigger';@@ -21,7 +21,6 @@ import {withLargeFileOpenGuard,} from '@/components/navigation-targets';import { PageListProvider, usePageList } from '@/components/PageListContext';-import { ShareBranchSwitchDialog } from '@/components/ShareBranchSwitchDialog';import { SystemDocSubscriber } from '@/components/SystemDocSubscriber';import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar';import {@@ -43,6 +42,25 @@ import { SingleFileModeProvider, useSingleFileMode } from '@/lib/single-file-modimport { useServerKeepalive } from '@/lib/use-server-keepalive';import { isSettingsShortcut, SETTINGS_OPEN_HASH } from '@/lib/use-settings-route';+// Cold-path receive surface: only mounts when main routes a+// 'project-branch-switch' payload. Lazy so its branch-info / checkout / variant+// code (and the target-status client it pulls in) splits out of the main bundle.+const ShareBranchSwitchDialog = lazy(() =>+ import('@/components/ShareBranchSwitchDialog').then((m) => ({+ default: m.ShareBranchSwitchDialog,+ })),+);++// Cold-path receive surface: the honest verdict modal for a share deep link+// whose target is absent on the receiver's branch. Self-gates on+// `missDialogStore`; lazy so its verdict-fetch code splits out of the main+// bundle until a miss actually occurs.+const ShareReceiveMissDialog = lazy(() =>+ import('@/components/ShareReceiveMissDialog').then((m) => ({+ default: m.ShareReceiveMissDialog,+ })),+);+/*** Hashes that open overlay dialogs (Settings, Install Claude Desktop)* rather than navigate to a document. NavigationHandler treats these as@@ -505,7 +523,12 @@ function AppBody() {'project-branch-switch' payload to this editor window.Clone / locate / consent surfaces live on the Navigator,never in an editor (see NavigatorApp). */}- {desktopBridge ? <ShareBranchSwitchDialog bridge={desktopBridge} /> : null}+ {desktopBridge ? (+ <Suspense fallback={null}>+ <ShareBranchSwitchDialog bridge={desktopBridge} />+ <ShareReceiveMissDialog />+ </Suspense>+ ) : null}<CommandPalettebridge={desktopBridge}open={commandPaletteOpen}diff --git a/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx b/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsxnew file mode 100644index 000000000..0261eb162--- /dev/null+++ b/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx@@ -0,0 +1,154 @@+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';+import { cleanup, render, screen } from '@testing-library/react';+import type { ReactNode } from 'react';+import { pendingReceiveNavStore } from '@/lib/share/pending-receive-nav-store';++// A missing target with a live provider — the phantom-doc state the resolver+// lands on for a share target the branch doesn't carry. Reaches the editor+// `else` branch (create-mode) unless the share-receive miss guard diverts it.+const MISSING_DOC_CTX = {+ activeDocName: 'notes/plan',+ activeProvider: {} as never,+ activeTarget: { kind: 'missing', target: 'notes/plan' },+ recycleDocument: () => {},+ docPanelMode: 'timeline',+ docPanelAgentId: null,+ docPanelExpandSignal: 0,+};+let docCtx: typeof MISSING_DOC_CTX = MISSING_DOC_CTX;++mock.module('@/lib/perf', () => ({+ mark: () => {},+ ProfilerBoundary: ({ children }: { children: ReactNode }) => children,+}));+mock.module('@/components/PropertyContext', () => ({+ PropertyProvider: ({ children }: { children: ReactNode }) => children,+ useProperties: () => ({ requestAddProperty: () => {} }),+}));+mock.module('@/editor/DocumentContext', () => ({+ useDocumentContext: () => docCtx,+ useDocumentTransition: () => ({ openDocumentTransition: null }),+}));+mock.module('@/hooks/use-document-stats', () => ({ useDocumentStats: () => null }));+mock.module('@/hooks/use-selection-stats', () => ({ useSelectionStats: () => null }));+mock.module('@/hooks/use-lifecycle-status', () => ({ useLifecycleStatus: () => 'ready' }));+mock.module('@/presence/use-sync-status', () => ({ useSyncStatus: () => 'synced' }));+mock.module('@/lib/use-settings-route', () => ({+ useSettingsRoute: () => ({ open: false, close: () => {} }),+ SETTINGS_OPEN_HASH: '#settings',+ isSettingsShortcut: () => false,+}));+mock.module('@/components/settings/SettingsDialogShell', () => ({+ SettingsDialogShell: () => <div data-testid="settings-shell" />,+}));+mock.module('@/components/EditorSkeleton', () => ({+ EditorSkeleton: () => <div data-testid="editor-skeleton" />,+}));+mock.module('@/components/EmptyEditorState', () => ({+ EmptyEditorState: () => <div data-testid="empty-editor-state" />,+}));+mock.module('./TerminalDock', () => ({+ TerminalDock: ({ children }: { children: ReactNode }) => <div>{children}</div>,+}));+mock.module('react-resizable-panels', () => ({+ usePanelRef: () => ({ current: { collapse: () => {}, expand: () => {} } }),+ // EditorArea imports `useGroupRef` alongside `usePanelRef`; the mock must+ // carry BOTH named exports or the `import { useGroupRef }` binding fails to+ // resolve and the whole file errors on load.+ useGroupRef: () => ({ current: { getLayout: () => [], setLayout: () => {} } }),+}));+mock.module('@/components/ui/resizable', () => ({+ ResizablePanelGroup: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ ResizablePanel: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ ResizableHandle: () => <div />,+}));+// The share-receive miss panel — stubbed so this test observes only which+// branch EditorArea takes, not the panel's own fetch/verdict behavior (its own+// dom test owns that).+mock.module('@/components/ShareReceiveMissPanel', () => ({+ ShareReceiveMissPanel: ({ nav }: { nav: { path: string } }) => (+ <div data-testid="miss-panel" data-path={nav.path} />+ ),+}));+// Editor-branch children — stubbed to a marker that surfaces the create-mode+// placeholder, so "fell through to create-mode" is observable without the real+// TipTap/CodeMirror stack.+mock.module('./EditorActivityPool', () => ({+ EditorActivityPool: ({ editorPlaceholder }: { editorPlaceholder?: string }) => (+ <div data-testid="editor-pool" data-placeholder={editorPlaceholder} />+ ),+}));+mock.module('@/editor/find-replace/FindReplaceController', () => ({+ FindReplaceController: () => null,+}));+mock.module('./EditorToolbar', () => ({+ EditorToolbar: () => <div data-testid="editor-toolbar" />,+}));+mock.module('./EditorFooter', () => ({ EditorFooter: () => <div data-testid="editor-footer" /> }));+// The create-mode branch mounts BottomComposer, which reaches useConfigContext+// via useHandoffDispatch — stub it out (this test only asserts which primary+// view renders, not the ask-composer, and pulling in the real config context+// is out of scope).+mock.module('./BottomComposer', () => ({+ BottomComposer: () => <div data-testid="bottom-composer" />,+}));+mock.module('./editor-area-overlay', () => ({ shouldPaintOverlay: () => false }));+// The editor `else` branch mounts DocPanel as its right panel; it reads+// usePageList, so stub it out — this test only cares which primary view renders.+mock.module('@/components/DocPanel', () => ({ DocPanel: () => <div data-testid="doc-panel" /> }));++const { EditorArea } = await import('./EditorArea');++function renderEditorArea() {+ return render(+ <EditorArea+ editorMode="wysiwyg"+ onModeChange={() => {}}+ activeTab="timeline"+ onActiveTabChange={() => {}}+ />,+ );+}++describe('EditorArea share-receive miss guard', () => {+ beforeEach(() => {+ cleanup();+ docCtx = MISSING_DOC_CTX;+ pendingReceiveNavStore.clear();+ window.location.hash = '';+ });+ afterEach(() => {+ cleanup();+ pendingReceiveNavStore.clear();+ });++ // A share-receive navigation to a missing target renders the miss panel,+ // never the create-mode editor — the fork trap is mechanically closed.+ test('renders the miss panel for a share-receive miss instead of create-mode', () => {+ pendingReceiveNavStore.arm({ kind: 'doc', path: 'notes/plan', branch: 'feature' });+ renderEditorArea();++ expect(screen.getByTestId('miss-panel').getAttribute('data-path')).toBe('notes/plan');+ expect(screen.queryByTestId('editor-pool')).toBeNull();+ });++ // An ordinary wiki-link create-on-navigate (no armed share-receive nav) still+ // opens the create-mode editor — the guard doesn't interfere.+ test('leaves create-mode reachable for an unarmed missing target (wiki-link)', () => {+ renderEditorArea();++ expect(screen.queryByTestId('miss-panel')).toBeNull();+ const pool = screen.getByTestId('editor-pool');+ expect(pool.getAttribute('data-placeholder')).toBe('Start writing to create this page');+ });++ // Path-scoping: an armed nav for a DIFFERENT path must not divert this+ // target — only the exact shared path gets the panel.+ test('does not divert a missing target whose path differs from the armed nav', () => {+ pendingReceiveNavStore.arm({ kind: 'doc', path: 'some/other-doc', branch: 'feature' });+ renderEditorArea();++ expect(screen.queryByTestId('miss-panel')).toBeNull();+ expect(screen.getByTestId('editor-pool')).toBeTruthy();+ });+});diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsxindex e6c0bb26d..18e405069 100644--- a/packages/app/src/components/EditorArea.tsx+++ b/packages/app/src/components/EditorArea.tsx@@ -10,6 +10,7 @@ import {useLayoutEffect,useRef,useState,+ useSyncExternalStore,} from 'react';import { useGroupRef, usePanelRef } from 'react-resizable-panels';import { AssetPreview } from '@/components/AssetPreview';@@ -24,6 +25,7 @@ import { FolderOverview } from '@/components/FolderOverview';import { LargeFileEditorState } from '@/components/LargeFileEditorState';import { MountStalledAffordance } from '@/components/MountStalledAffordance';import { PropertyProvider, useProperties } from '@/components/PropertyContext';+import { ShareReceiveMissPanel } from '@/components/ShareReceiveMissPanel';import { SkillFileViewer } from '@/components/SkillFileViewer';import { SettingsDialogShell } from '@/components/settings/SettingsDialogShell';import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@/components/ui/resizable';@@ -39,6 +41,10 @@ import { docNameFromHash, hashFromDocName } from '@/lib/doc-hash';import { getInitialDocPanelWidth, writeDocPanelWidth } from '@/lib/doc-panel-width-store';import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';import { ProfilerBoundary } from '@/lib/perf';+import {+ matchesShareReceiveMiss,+ pendingReceiveNavStore,+} from '@/lib/share/pending-receive-nav-store';import { RIGHT_COLLAPSE_THRESHOLD, resolvePartition } from '@/lib/sidebar-partition';import { applyToggle, readPins, resolveEffectiveState } from '@/lib/sidebar-pin-store';import type { TerminalDockPosition } from '@/lib/terminal-dock-store';@@ -240,6 +246,17 @@ function EditorAreaInner({const isNewDoc = activeTarget?.kind === 'missing';const showStats = !!activeDocName && activeTarget?.kind !== 'folder';const editorPlaceholder = isNewDoc ? t`Start writing to create this page` : undefined;+ // A share-receive navigation that resolved to a missing target renders an+ // honest verdict panel instead of the create-mode editor, so a receiver can't+ // silently fork the doc at the shared path. A plain missing target — an+ // ordinary wiki-link create-on-navigate — leaves this null and keeps+ // create-mode reachable.+ const pendingReceiveNav = useSyncExternalStore(+ pendingReceiveNavStore.subscribe,+ pendingReceiveNavStore.getSnapshot,+ pendingReceiveNavStore.getSnapshot,+ );+ const shareReceiveMiss = matchesShareReceiveMiss(activeTarget, pendingReceiveNav);const [embeddedHost] = useState(() => detectEmbeddedHostFromBrowser());// Derive from the cached `embeddedHost` instead of calling@@ -803,6 +820,12 @@ function EditorAreaInner({path={activeTarget.path}/>);+ } else if (shareReceiveMiss) {+ // Terminal state for a share-receive miss — replaces the create-mode editor+ // the missing target would otherwise open, before the phantom provider's+ // editor can paint. Keyed by path so a redirect to another miss remounts ++ // re-fetches its verdict.+ viewContent = <ShareReceiveMissPanel key={shareReceiveMiss.path} nav={shareReceiveMiss} />;} else if (!activeProvider || !activeDocName) {// On initial page load the URL hash tells us a doc is about to open — render// the skeleton instead of the "Select a document" empty state so the userdiff --git a/packages/app/src/components/NavigatorApp.tsx b/packages/app/src/components/NavigatorApp.tsxindex c336efbed..a8fecd628 100644--- a/packages/app/src/components/NavigatorApp.tsx+++ b/packages/app/src/components/NavigatorApp.tsx@@ -17,7 +17,7 @@import { Trans, useLingui } from '@lingui/react/macro';import { Folder, FolderOpenIcon, GitBranch, Loader2Icon, PlusIcon, XIcon } from 'lucide-react';import { useTheme } from 'next-themes';-import { type ComponentType, useEffect, useState } from 'react';+import { type ComponentType, lazy, Suspense, useEffect, useState } from 'react';import { useThemeBridge } from '@/hooks/use-theme-bridge';import type {OkDesktopBridge,@@ -43,10 +43,16 @@ import { GithubIcon } from './icons/github';import { OkIcon } from './icons/ok';import { McpConsentDialog } from './McpConsentDialog';import { basenameOf } from './project-switcher-recents';-import { ShareReceiveDialog } from './ShareReceiveDialog';import { Badge } from './ui/badge';import { Button } from './ui/button';+// Cold-path launcher surface: renders nothing until main fires+// `ok:share:received`. Lazy so its clone / auth-preflight / Q2-picker code+// (and the transports it pulls in) splits out of the main bundle.+const ShareReceiveDialog = lazy(() =>+ import('./ShareReceiveDialog').then((m) => ({ default: m.ShareReceiveDialog })),+);+// Re-exports for tests — keeping the surface here avoids churn in existing// test files that import directly from NavigatorApp.tsx and keeps the// shared-helper move transparent.@@ -418,20 +424,22 @@ export function NavigatorApp({ bridge }: { bridge: OkDesktopBridge }) {streamlined clone (folder picker → progress toast → done) viathe shared cloneController. IPC transports for the Navigatorwindow (no backing API server). */}- <ShareReceiveDialog- bridge={bridge}- cloneController={createCloneController({- bridge,- authQueryTransport: ipcAuthQueryTransport(bridge),- cloneTransport: ipcCloneTransport(bridge),- openSignIn: () =>- new Promise<OkLocalOpAuthStatusResponse | null>((resolve) => {- // Wrap in function so useState doesn't treat `resolve` as an updater.- setShareSignInResolver(() => resolve);- setAuthModalOpen(true);- }),- })}- />+ <Suspense fallback={null}>+ <ShareReceiveDialog+ bridge={bridge}+ cloneController={createCloneController({+ bridge,+ authQueryTransport: ipcAuthQueryTransport(bridge),+ cloneTransport: ipcCloneTransport(bridge),+ openSignIn: () =>+ new Promise<OkLocalOpAuthStatusResponse | null>((resolve) => {+ // Wrap in function so useState doesn't treat `resolve` as an updater.+ setShareSignInResolver(() => resolve);+ setAuthModalOpen(true);+ }),+ })}+ />+ </Suspense></div>);}diff --git a/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx b/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsxindex 16f6fb894..00dc4e236 100644--- a/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx+++ b/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx@@ -64,11 +64,13 @@ mock.module('sonner', () => ({}));const { createShareReceiveStore } = await import('@/lib/share/receive-store');+const { missDialogStore } = await import('@/lib/share/miss-dialog-store');const { ShareBranchSwitchDialog } = await import('./ShareBranchSwitchDialog');interface BridgeMock {fetchBranchInfo: ReturnType<typeof mock>;runCheckout: ReturnType<typeof mock>;+ fetchTargetStatus: ReturnType<typeof mock>;awaitBranchSwitched: ReturnType<typeof mock>;open: ReturnType<typeof mock>;}@@ -92,6 +94,7 @@ function makeBridge(overrides: Partial<BridgeMock> = {}): {),runCheckout:overrides.runCheckout ?? mock(async (): Promise<CheckoutResponse> => ({ ok: true })),+ fetchTargetStatus: overrides.fetchTargetStatus ?? mock(async () => null),awaitBranchSwitched: overrides.awaitBranchSwitched ?? mock(async () => ({ ok: true as const })),open: overrides.open ?? mock(async () => undefined),};@@ -99,6 +102,7 @@ function makeBridge(overrides: Partial<BridgeMock> = {}): {project: {fetchBranchInfo: calls.fetchBranchInfo,runCheckout: calls.runCheckout,+ fetchTargetStatus: calls.fetchTargetStatus,awaitBranchSwitched: calls.awaitBranchSwitched,open: calls.open,},@@ -106,6 +110,36 @@ function makeBridge(overrides: Partial<BridgeMock> = {}): {return { bridge, calls };}+/**+ * branch-info for the "switch to recover" variant with an explicitly-false+ * origin hint — the state that triggers the verdict pivot. `shareTargetExists`+ * false (target missing on the current branch) + a clean tree = variant B;+ * `shareTargetOnOriginBranch: false` = the stale-local-ref hint.+ */+function missWithFalseOriginHint(): BranchInfoResponse {+ return {+ ok: true,+ currentBranch: 'main',+ currentHeadSha: 'aaaaaaa',+ detached: false,+ shareTargetExists: false,+ dirtyConflicts: { conflicts: false, files: [] },+ branchIsLocal: true,+ shareTargetOnOriginBranch: false,+ } as unknown as BranchInfoResponse;+}++function pivotBridge(+ targetStatus: ReturnType<typeof mock>,+ extra: Partial<BridgeMock> = {},+): { bridge: OkDesktopBridge; calls: BridgeMock } {+ return makeBridge({+ fetchBranchInfo: mock(async () => missWithFalseOriginHint()),+ fetchTargetStatus: targetStatus,+ ...extra,+ });+}+function projectBranchSwitchPayload(): Extract<OkShareReceivedPayload,{ kind: 'project-branch-switch' }@@ -560,3 +594,226 @@ describe('ShareBranchSwitchDialog — Switch path (runCheckout + CC1 gate)', ()expect(calls.open).not.toHaveBeenCalled();});});++describe('ShareBranchSwitchDialog — verdict pivot (FR9)', () => {+ afterEach(() => {+ cleanup();+ toastError.mockReset();+ });++ function installAndRender(+ bridge: OkDesktopBridge,+ store: ReturnType<typeof createShareReceiveStore>,+ ) {+ const payload = projectBranchSwitchPayload();+ const fakeBridgeForStore = {+ onShareReceived: (cb: (p: OkShareReceivedPayload) => void) => {+ cb(payload);+ return () => {};+ },+ } as unknown as OkDesktopBridge;+ store.install({ bridge: fakeBridgeForStore });+ render(<ShareBranchSwitchDialog bridge={bridge} store={store} />);+ return payload;+ }++ test('a false origin hint fetches target-status and renders the on-origin verdict', async () => {+ const store = createShareReceiveStore();+ const targetStatus = mock(async () => ({ verdict: 'on-origin' as const }));+ const { bridge, calls } = pivotBridge(targetStatus);+ const payload = installAndRender(bridge, store);++ await screen.findByTestId('share-branch-switch-verdict-on-origin');+ expect(calls.fetchTargetStatus).toHaveBeenCalledTimes(1);+ expect(calls.fetchTargetStatus).toHaveBeenCalledWith({+ projectPath: payload.projectPath,+ branch: payload.share.branch,+ kind: 'doc',+ path: 'docs/notes.md',+ });+ });++ test('on-origin "Switch and update branch" runs a fast-forward checkout and navigates to the doc', async () => {+ const store = createShareReceiveStore();+ const { bridge, calls } = pivotBridge(mock(async () => ({ verdict: 'on-origin' as const })));+ const payload = installAndRender(bridge, store);++ const btn = await screen.findByTestId('share-branch-switch-verdict-switch-update');+ await act(async () => {+ fireEvent.click(btn);+ await Promise.resolve();+ });++ expect(calls.runCheckout).toHaveBeenCalledWith({+ projectPath: payload.projectPath,+ branch: payload.share.branch,+ fastForward: true,+ });+ await waitFor(() => {+ expect(calls.open).toHaveBeenCalledTimes(1);+ });+ const openArg = calls.open.mock.calls[0]?.[0] as Record<string, unknown>;+ expect(openArg.pendingDeepLinkTarget).toEqual({ kind: 'doc', path: 'docs/notes.md' });+ expect(openArg.pendingBranch).toBe(payload.share.branch);+ });++ test('renamed offer opens the NEW path with a fast-forward checkout', async () => {+ const store = createShareReceiveStore();+ const { bridge, calls } = pivotBridge(+ mock(async () => ({ verdict: 'renamed' as const, renamedTo: 'guides/notes.md' })),+ );+ const payload = installAndRender(bridge, store);++ // The body names the new path so the receiver sees where it moved.+ const cell = await screen.findByTestId('share-branch-switch-verdict-renamed');+ expect(cell.textContent).toContain('guides/notes.md');++ const btn = await screen.findByTestId('share-branch-switch-verdict-open-renamed');+ await act(async () => {+ fireEvent.click(btn);+ await Promise.resolve();+ });++ expect(calls.runCheckout).toHaveBeenCalledWith({+ projectPath: payload.projectPath,+ branch: payload.share.branch,+ fastForward: true,+ });+ await waitFor(() => {+ expect(calls.open).toHaveBeenCalledTimes(1);+ });+ const openArg = calls.open.mock.calls[0]?.[0] as Record<string, unknown>;+ // Navigation lands on the renamed path, NOT the original share path.+ expect(openArg.pendingDeepLinkTarget).toEqual({ kind: 'doc', path: 'guides/notes.md' });+ });++ test('deleted verdict hands off to the miss dialog (no switch, dismisses this shell)', async () => {+ missDialogStore.dismiss();+ const store = createShareReceiveStore();+ const { bridge, calls } = pivotBridge(mock(async () => ({ verdict: 'deleted' as const })));+ installAndRender(bridge, store);++ // A gone-on-the-share-branch target has nothing to switch to — this shell+ // hands off to the dedicated miss dialog (which owns the honest copy + a+ // Browse-folder escape) rather than showing a terminal Cancel-only cell.+ await waitFor(() => {+ expect(missDialogStore.getSnapshot()).toEqual({+ kind: 'doc',+ path: 'docs/notes.md',+ branch: 'feat/branch-x',+ });+ });+ // This shell dismisses itself and never runs a checkout.+ expect(store.getSnapshot()).toBeNull();+ expect(calls.runCheckout).not.toHaveBeenCalled();+ missDialogStore.dismiss();+ });++ test('never-on-branch hands off to the miss dialog too (nothing to switch to)', async () => {+ missDialogStore.dismiss();+ const store = createShareReceiveStore();+ const { bridge, calls } = pivotBridge(+ mock(async () => ({ verdict: 'never-on-branch' as const })),+ );+ installAndRender(bridge, store);++ await waitFor(() => {+ expect(missDialogStore.getSnapshot()?.path).toBe('docs/notes.md');+ });+ expect(store.getSnapshot()).toBeNull();+ expect(calls.runCheckout).not.toHaveBeenCalled();+ missDialogStore.dismiss();+ });++ test('a fast-forward that diverges shows the diverged cell offering a plain switch (no merge)', async () => {+ const store = createShareReceiveStore();+ // The server refuses the fast-forward only when it is requested; a plain+ // switch (no fastForward) succeeds.+ const runCheckout = mock(async (req: { fastForward?: boolean }) =>+ req.fastForward+ ? { ok: false as const, reason: 'ff-diverged' as const }+ : { ok: true as const },+ );+ const { bridge, calls } = pivotBridge(+ mock(async () => ({ verdict: 'on-origin' as const })),+ {+ runCheckout,+ },+ );+ const payload = installAndRender(bridge, store);++ const updateBtn = await screen.findByTestId('share-branch-switch-verdict-switch-update');+ await act(async () => {+ fireEvent.click(updateBtn);+ await Promise.resolve();+ });++ // The fast-forward was refused → diverged cell, no navigation yet.+ await screen.findByTestId('share-branch-switch-verdict-diverged');+ expect(calls.open).not.toHaveBeenCalled();++ const plainBtn = screen.getByTestId('share-branch-switch-verdict-plain-switch');+ await act(async () => {+ fireEvent.click(plainBtn);+ await Promise.resolve();+ });++ // The plain switch carries NO fastForward — the receive flow never merges.+ expect(calls.runCheckout).toHaveBeenLastCalledWith({+ projectPath: payload.projectPath,+ branch: payload.share.branch,+ });+ await waitFor(() => {+ expect(calls.open).toHaveBeenCalledTimes(1);+ });+ });++ test('unknown verdict falls back to today plain switch and does NOT re-probe', async () => {+ const store = createShareReceiveStore();+ const targetStatus = mock(async () => ({ verdict: 'unknown' as const }));+ const { bridge, calls } = pivotBridge(targetStatus);+ const payload = installAndRender(bridge, store);++ // Fail-open: once the unknown verdict lands, the dialog re-enables today's+ // plain switch button (it renders disabled during the checking state).+ const switchBtn = await screen.findByTestId('share-branch-switch-switch');+ await waitFor(() => {+ expect((switchBtn as HTMLButtonElement).disabled).toBe(false);+ });+ // Single-fire guard: an `unknown` fallback to `ready` must not re-arm the probe.+ expect(calls.fetchTargetStatus).toHaveBeenCalledTimes(1);++ await act(async () => {+ fireEvent.click(switchBtn);+ await Promise.resolve();+ });+ // The plain switch does not fast-forward.+ expect(calls.runCheckout).toHaveBeenCalledWith({+ projectPath: payload.projectPath,+ branch: payload.share.branch,+ });+ });++ test('a missing target with NO origin hint keeps today plain switch (no probe)', async () => {+ const store = createShareReceiveStore();+ const { bridge, calls } = makeBridge({+ fetchBranchInfo: mock(+ async (): Promise<BranchInfoResponse> =>+ ({+ ok: true,+ currentBranch: 'main',+ currentHeadSha: 'aaaaaaa',+ detached: false,+ shareTargetExists: false,+ dirtyConflicts: { conflicts: false, files: [] },+ branchIsLocal: true,+ }) as unknown as BranchInfoResponse,+ ),+ });+ installAndRender(bridge, store);++ await screen.findByTestId('share-branch-switch-switch');+ // Fail-open on the omitted hint: no verdict fetch, today's behavior.+ expect(calls.fetchTargetStatus).not.toHaveBeenCalled();+ });+});diff --git a/packages/app/src/components/ShareBranchSwitchDialog.tsx b/packages/app/src/components/ShareBranchSwitchDialog.tsxindex ea73becb6..978b677c1 100644--- a/packages/app/src/components/ShareBranchSwitchDialog.tsx+++ b/packages/app/src/components/ShareBranchSwitchDialog.tsx@@ -39,13 +39,17 @@ import {import {applyBranchInfo,applyCheckoutOutcome,+ applyVerdict,type BranchSwitchDialogState,type CheckoutSideEffectReason,formatCurrentLabel,initialBranchSwitchState,markSwitching,+ markVerdictPending,selectBranchSwitchVariant,+ shouldProbeTargetStatus,} from '@/lib/share/branch-switch-flow';+import { missDialogStore } from '@/lib/share/miss-dialog-store';import { formatReceiveLog } from '@/lib/share/receive-flow';import { type ShareReceiveStore, shareReceiveStore } from '@/lib/share/receive-store';@@ -76,6 +80,12 @@ export function ShareBranchSwitchDialog({useState<BranchSwitchDialogState>(initialBranchSwitchState);const branchInfoStartedRef = useRef(false);const awaitBranchSwitchedStartedRef = useRef(false);+ const verdictProbeStartedRef = useRef(false);+ // The payload the verdict probe currently belongs to. The verdict-probe effect+ // self-transitions its own phase dep, so a cleanup-based cancel would drop its+ // own result; it compares against this instead to ignore a late verdict from a+ // superseded share. Updated in the per-payload reset effect below.+ const verdictPayloadRef = useRef<ProjectBranchSwitchPayload | null>(null);const active = isBranchSwitchPayload(payload) ? payload : null;// Kind-aware noun so every surface (title, body, toasts) reads correctly for@@ -89,11 +99,13 @@ export function ShareBranchSwitchDialog({// consent-seed-vs-reset race between two effects), this dialog resets in a// single effect with no competing seed effect, and the store nulls `payload`// via dismiss() between shares — so the imperative reset is race-free here.- // biome-ignore lint/correctness/useExhaustiveDependencies: payload is the reset trigger; effect body only resets state.+ // biome-ignore lint/correctness/useExhaustiveDependencies: payload is the reset trigger; the body resets state and captures the payload for the verdict staleness check.useEffect(() => {setBranchSwitchState(initialBranchSwitchState);branchInfoStartedRef.current = false;awaitBranchSwitchedStartedRef.current = false;+ verdictProbeStartedRef.current = false;+ verdictPayloadRef.current = active;}, [payload]);// Fetch branch-info once per payload so the variant matrix has fresh@@ -104,6 +116,10 @@ export function ShareBranchSwitchDialog({if (!active) return;if (branchInfoStartedRef.current) return;branchInfoStartedRef.current = true;+ // Guard against a stale write: the dialog stays mounted across payloads, so+ // a payload-A fetch that resolves after payload B armed must not stomp B's+ // freshly-reset state (mirrors the awaiting-cc1 effect below).+ let cancelled = false;void bridge.project.fetchBranchInfo({projectPath: active.projectPath,@@ -112,17 +128,82 @@ export function ShareBranchSwitchDialog({path: shareTargetPath(active.share.target),}).then((info) => {+ if (cancelled) return;setBranchSwitchState((prev) => applyBranchInfo(prev, info));}).catch((err) => {+ if (cancelled) return;console.warn('[receive] branch-info-fetch-failed',err instanceof Error ? err.message : err,);setBranchSwitchState((prev) => applyBranchInfo(prev, null));});+ return () => {+ cancelled = true;+ };}, [active]);+ // Origin-hint pivot: when branch-info reports the target isn't on origin's+ // branch (a stale-local-ref hint), fetch a real verdict rather than+ // over-promising that a plain switch recovers it. Single-fire per payload so+ // an `unknown` fallback to `ready` can't re-arm the probe into a loop.+ // biome-ignore lint/correctness/useExhaustiveDependencies: phase-gated single-fire; bridge identity churns every parent render.+ useEffect(() => {+ if (!active) return;+ if (branchSwitchState.phase !== 'ready') return;+ if (verdictProbeStartedRef.current) return;+ if (!shouldProbeTargetStatus(branchSwitchState.info)) return;+ verdictProbeStartedRef.current = true;+ setBranchSwitchState(markVerdictPending);+ // Stale-write guard keyed on payload identity, not a cleanup cancel: this+ // effect self-transitions its own phase dep (markVerdictPending), so a+ // cleanup would fire on that transition and drop this very verdict. Compare+ // the payload this fetch was issued for against the latest one instead, so a+ // late verdict from a superseded share is ignored.+ const fetchedFor = active;+ void bridge.project+ .fetchTargetStatus({+ projectPath: active.projectPath,+ branch: active.share.branch,+ kind: active.share.target.kind,+ path: shareTargetPath(active.share.target),+ })+ .then((status) => {+ if (verdictPayloadRef.current !== fetchedFor) return;+ setBranchSwitchState((prev) => applyVerdict(prev, status));+ })+ .catch((err) => {+ if (verdictPayloadRef.current !== fetchedFor) return;+ // Fail-open: a rejected probe degrades to today's plain switch (the+ // post-switch guard backstops the residual miss), never a stuck dialog.+ console.warn(+ '[receive] target-status-fetch-failed',+ err instanceof Error ? err.message : err,+ );+ setBranchSwitchState((prev) => applyVerdict(prev, null));+ });+ }, [branchSwitchState.phase, active]);++ // Terminal-miss handoff: `deleted` / `never-on-branch` mean the shared target+ // is gone on the share branch, so there is nothing to switch to — the+ // "Open shared document" branch-switch shell is the wrong surface. Hand off to+ // the dedicated miss dialog (honest verdict + Browse-folder escape), which the+ // branch-match-ok deep-link path already uses, so a removed target reads+ // identically regardless of which dispatch path delivered the share.+ useEffect(() => {+ if (branchSwitchState.phase !== 'verdict') return;+ const { kind } = branchSwitchState.resolution;+ if (kind !== 'deleted' && kind !== 'never-on-branch') return;+ if (!active) return;+ missDialogStore.arm({+ kind: active.share.target.kind,+ path: shareTargetPath(active.share.target),+ branch: active.share.branch,+ });+ store.dismiss();+ }, [branchSwitchState, active, store]);+// CC1-driven post-checkout navigation gate. After Switch resolves// `{ok:true}` the state transitions to `awaiting-cc1-recycle`; we poll// server-info (the late-join backstop for the CC1 `branch-switched`@@ -133,6 +214,9 @@ export function ShareBranchSwitchDialog({if (branchSwitchState.phase !== 'awaiting-cc1-recycle') return;if (!active) return;const shareBranch = active.share.branch;+ // The navigation target the switch committed to — the original share path+ // for a plain / on-origin switch, or `renamedTo` when a rename was accepted.+ const pendingNavPath = branchSwitchState.pendingDoc;if (!shareBranch) {store.dismiss();return;@@ -162,7 +246,7 @@ export function ShareBranchSwitchDialog({entryPoint: 'share-receive',pendingDeepLinkTarget: {kind: active.share.target.kind,- path: shareTargetPath(active.share.target),+ path: pendingNavPath,},pendingBranch: shareBranch,})@@ -213,10 +297,12 @@ export function ShareBranchSwitchDialog({const { share, projectPath, currentBranch: payloadCurrentBranch } = active;const shareBranch = share.branch;- function handleSwitch(): void {- if (branchSwitchState.phase !== 'ready') return;- const variant = selectBranchSwitchVariant(branchSwitchState.info);- if (!variant.switchEnabled) return;+ // Shared switch executor. `fastForward` rides only for the on-origin /+ // renamed verdict cells (the server updates the stale local ref before+ // checkout so the doc lands); the plain switch and the diverged cell pass it+ // off. `pendingDoc` is the post-switch navigation target — the original path,+ // or `renamedTo` when a rename was accepted.+ function runSwitch(pendingDoc: string, fastForward: boolean): void {console.log(formatReceiveLog({branch_dialog_action: 'switch',@@ -224,9 +310,13 @@ export function ShareBranchSwitchDialog({branch: shareBranch,}),);- setBranchSwitchState((prev) => markSwitching(prev, shareTargetPath(share.target)));+ setBranchSwitchState((prev) => markSwitching(prev, pendingDoc));void bridge.project- .runCheckout({ projectPath, branch: shareBranch })+ .runCheckout(+ fastForward+ ? { projectPath, branch: shareBranch, fastForward: true }+ : { projectPath, branch: shareBranch },+ ).then((response) => {let toastReason: CheckoutSideEffectReason | null = null;let shouldDismiss = false;@@ -260,6 +350,32 @@ export function ShareBranchSwitchDialog({});}+ function handleSwitch(): void {+ if (branchSwitchState.phase !== 'ready') return;+ const variant = selectBranchSwitchVariant(branchSwitchState.info);+ if (!variant.switchEnabled) return;+ runSwitch(shareTargetPath(share.target), false);+ }++ // Verdict-cell actions. on-origin / renamed fast-forward the stale local ref+ // to origin's tip before switching so the doc actually lands; diverged offers+ // a plain switch (no fast-forward — the receive flow never merges).+ function handleSwitchAndUpdate(): void {+ if (branchSwitchState.phase !== 'verdict') return;+ runSwitch(shareTargetPath(share.target), true);+ }++ function handleOpenRenamed(): void {+ if (branchSwitchState.phase !== 'verdict') return;+ if (branchSwitchState.resolution.kind !== 'renamed') return;+ runSwitch(branchSwitchState.resolution.renamedTo, true);+ }++ function handlePlainSwitchFromVerdict(): void {+ if (branchSwitchState.phase !== 'verdict') return;+ runSwitch(shareTargetPath(share.target), false);+ }+function handleOpenCurrent(): void {console.log(formatReceiveLog({@@ -396,6 +512,73 @@ export function ShareBranchSwitchDialog({{branchSwitchState.otherWorktreePath}</p></div>+ ) : branchSwitchState.phase === 'verdict-pending' ? (+ <p+ className="flex items-center gap-2 text-sm text-muted-foreground"+ data-testid="share-branch-switch-verdict-pending"+ role="status"+ aria-live="polite"+ >+ <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />+ <Trans>Checking for updates on GitHub</Trans>+ </p>+ ) : branchSwitchState.phase === 'verdict' ? (+ branchSwitchState.resolution.kind === 'on-origin' ? (+ <p+ className="text-sm leading-6 text-muted-foreground"+ data-testid="share-branch-switch-verdict-on-origin"+ >+ <Trans>+ This {targetNoun} was added to branch{' '}+ <code className="rounded-sm bg-muted px-1 py-0.5 text-foreground/80">+ {shareBranch}+ </code>{' '}+ recently. Switch and update to open it.+ </Trans>+ </p>+ ) : branchSwitchState.resolution.kind === 'renamed' ? (+ <p+ className="text-sm leading-6 text-muted-foreground"+ data-testid="share-branch-switch-verdict-renamed"+ >+ <Trans>+ This {targetNoun} moved to{' '}+ <code className="rounded-sm bg-muted px-1 py-0.5 text-foreground/80">+ {branchSwitchState.resolution.renamedTo}+ </code>+ . Open it there?+ </Trans>+ </p>+ ) : branchSwitchState.resolution.kind === 'diverged' ? (+ <p+ className="text-sm leading-6 text-muted-foreground"+ data-testid="share-branch-switch-verdict-diverged"+ >+ <Trans>+ Your copy of branch{' '}+ <code className="rounded-sm bg-muted px-1 py-0.5 text-foreground/80">+ {shareBranch}+ </code>{' '}+ has changes that aren't on GitHub. The {targetNoun} will appear once the branch+ syncs.+ </Trans>+ </p>+ ) : (+ // deleted / never-on-branch: the target is gone on the share+ // branch. The handoff effect arms the dedicated miss dialog and+ // dismisses this one, so render a brief spinner rather than the+ // terminal verdict cell — the miss dialog owns that copy + the+ // Browse-folder escape now.+ <p+ className="flex items-center gap-2 text-sm text-muted-foreground"+ data-testid="share-branch-switch-verdict-handoff"+ role="status"+ aria-live="polite"+ >+ <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />+ <Trans>Checking for updates on GitHub</Trans>+ </p>+ )) : isLoading ? (<pclassName="flex items-center gap-2 text-sm text-muted-foreground"@@ -498,6 +681,32 @@ export function ShareBranchSwitchDialog({<Button onClick={handlePivot} data-testid="share-branch-switch-in-other-worktree-pivot"><Trans>Open that worktree instead</Trans></Button>+ ) : branchSwitchState.phase === 'verdict' ? (+ branchSwitchState.resolution.kind === 'on-origin' ? (+ <Button+ onClick={handleSwitchAndUpdate}+ data-testid="share-branch-switch-verdict-switch-update"+ >+ <GitBranch className="size-3.5" aria-hidden />+ <Trans>Switch and update branch</Trans>+ </Button>+ ) : branchSwitchState.resolution.kind === 'renamed' ? (+ <Button+ onClick={handleOpenRenamed}+ data-testid="share-branch-switch-verdict-open-renamed"+ >+ <MapPin className="size-3.5" aria-hidden />+ <Trans>Open it there</Trans>+ </Button>+ ) : branchSwitchState.resolution.kind === 'diverged' ? (+ <Button+ onClick={handlePlainSwitchFromVerdict}+ data-testid="share-branch-switch-verdict-plain-switch"+ >+ <GitBranch className="size-3.5" aria-hidden />+ {switchLabel}+ </Button>+ ) : null) : (<div className="flex flex-col-reverse gap-2 sm:flex-row sm:gap-2">{variant?.openCurrentEnabled ? (diff --git a/packages/app/src/components/ShareButton.dom.test.tsx b/packages/app/src/components/ShareButton.dom.test.tsxindex a0a44649b..66e5c0fea 100644--- a/packages/app/src/components/ShareButton.dom.test.tsx+++ b/packages/app/src/components/ShareButton.dom.test.tsx@@ -58,6 +58,13 @@ mock.module('@/hooks/use-git-sync-status', () => ({}),}));+// The freshness warning row inside the popover reads the project-local config+// binding (for its "Enable auto-sync" gate). Stub the context so mounting the+// popover doesn't require a full <ConfigProvider>.+mock.module('@/lib/config-provider', () => ({+ useConfigContext: () => ({ projectLocalBinding: { patch: () => ({ ok: true }) } }),+}));+const { ShareButton } = await import('./ShareButton');const { TooltipProvider } = await import('@/components/ui/tooltip');@@ -163,4 +170,58 @@ describe('ShareButton', () => {body: JSON.stringify({ kind: 'doc', docPath: 'docs/readme.md' }),});});++ test('threads an absent freshness from the response into a warning row', async () => {+ globalThis.fetch = mock(() =>+ Promise.resolve(+ new Response(+ JSON.stringify({+ ok: true,+ shareUrl: 'https://openknowledge.ai/d/Share123',+ sharedUrl: 'https://github.com/inkeep/open-knowledge/blob/main/docs/readme.md',+ branch: 'main',+ freshness: 'absent',+ }),+ { status: 200 },+ ),+ ),+ ) as never;+ renderShareButton({ kind: 'doc', docName: 'docs/readme' });++ fireEvent.click(screen.getByRole('button', { name: 'Share doc' }));++ await waitFor(() => {+ expect(screen.getByTestId('share-button-popover')).not.toBeNull();+ });+ // The mocked status reports a remote with sync off, so an absent target is+ // the strong dead-link cell.+ expect(screen.getByTestId('share-freshness-row').textContent).toContain(+ "This doc isn't on GitHub yet",+ );+ });++ test('renders no warning row when the response reports current freshness', async () => {+ globalThis.fetch = mock(() =>+ Promise.resolve(+ new Response(+ JSON.stringify({+ ok: true,+ shareUrl: 'https://openknowledge.ai/d/Share123',+ sharedUrl: 'https://github.com/inkeep/open-knowledge/blob/main/docs/readme.md',+ branch: 'main',+ freshness: 'current',+ }),+ { status: 200 },+ ),+ ),+ ) as never;+ renderShareButton({ kind: 'doc', docName: 'docs/readme' });++ fireEvent.click(screen.getByRole('button', { name: 'Share doc' }));++ await waitFor(() => {+ expect(screen.getByTestId('share-button-popover')).not.toBeNull();+ });+ expect(screen.queryByTestId('share-freshness-row')).toBeNull();+ });});diff --git a/packages/app/src/components/ShareButton.tsx b/packages/app/src/components/ShareButton.tsxindex 768e0cc35..68ca3d06d 100644--- a/packages/app/src/components/ShareButton.tsx+++ b/packages/app/src/components/ShareButton.tsx@@ -26,6 +26,7 @@* unit-testable without React.*/+import type { ShareFreshness } from '@inkeep/open-knowledge-core';import { Trans, useLingui } from '@lingui/react/macro';import { CircleHelp, Share2 } from 'lucide-react';import { useEffect, useRef, useState } from 'react';@@ -42,6 +43,8 @@ import {runShareAction,type ShareTargetInput,} from '@/lib/share/run-share-action';+import { cn } from '@/lib/utils';+import { ShareFreshnessWarning, shareFreshnessRowVisible } from './ShareFreshnessWarning';/** Docs page explaining the share flow (links out of the popover). */const SHARE_DOCS_URL = 'https://openknowledge.ai/docs/features/share';@@ -75,6 +78,7 @@ export function ShareButton({ input, onClickWhenNoRemote }: ShareButtonProps) {const [sharePopover, setSharePopover] = useState<{url: string;autoCopyFailed: boolean;+ freshness?: ShareFreshness;} | null>(null);const urlInputRef = useRef<HTMLInputElement | null>(null);@@ -89,6 +93,7 @@ export function ShareButton({ input, onClickWhenNoRemote }: ShareButtonProps) {const hasRemote = status?.hasRemote === true;const triggerDisabled = input === null;+ const showFreshnessRow = shareFreshnessRowVisible(sharePopover?.freshness, status);async function handleClick() {if (busy) return;@@ -116,9 +121,17 @@ export function ShareButton({ input, onClickWhenNoRemote }: ShareButtonProps) {},);if (result.kind === 'copied') {- setSharePopover({ url: result.shareUrl, autoCopyFailed: false });+ setSharePopover({+ url: result.shareUrl,+ autoCopyFailed: false,+ freshness: result.freshness,+ });} else if (result.kind === 'clipboard-failed') {- setSharePopover({ url: result.shareUrl, autoCopyFailed: true });+ setSharePopover({+ url: result.shareUrl,+ autoCopyFailed: true,+ freshness: result.freshness,+ });}} catch {// runShareAction handles its own transport + clipboard rejections@@ -157,7 +170,7 @@ export function ShareButton({ input, onClickWhenNoRemote }: ShareButtonProps) {</PopoverAnchor><PopoverContentalign="end"- className="flex w-80 flex-col gap-2"+ className={cn('flex flex-col gap-2', showFreshnessRow ? 'w-96' : 'w-80')}data-testid="share-button-popover">{/* Mono/uppercase muted label — the same treatment the help menu uses@@ -201,6 +214,11 @@ export function ShareButton({ input, onClickWhenNoRemote }: ShareButtonProps) {</div></div></div>+ <ShareFreshnessWarning+ freshness={sharePopover?.freshness}+ status={status}+ kind={input?.kind ?? 'doc'}+ /><ahref={SHARE_DOCS_URL}target="_blank"diff --git a/packages/app/src/components/ShareFreshnessWarning.dom.test.tsx b/packages/app/src/components/ShareFreshnessWarning.dom.test.tsxnew file mode 100644index 000000000..9680f228a--- /dev/null+++ b/packages/app/src/components/ShareFreshnessWarning.dom.test.tsx@@ -0,0 +1,313 @@+/**+ * Matrix coverage for the share popover's freshness warning row. Prop-driven+ * (the `GitSyncStatus` is passed directly, not mocked through the hook), so each+ * cell of freshness × syncEnabled × pushPermission is exercised in isolation.+ *+ * Substrate: jsdom via `bun run test:dom`.+ */+import { afterEach, describe, expect, mock, test } from 'bun:test';+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import type { GitSyncStatus } from '@/hooks/use-git-sync-status';++// The Sync now CTA fires a real fetch through `triggerSync`; stub it so the+// click is observable without a network dependency (the landed transition is+// driven by re-rendering with an updated status, not by this call resolving).+// A mutable impl lets one test drive a rejected trigger (offline / server down).+let triggerSyncImpl: () => Promise<void> = () => Promise.resolve();+mock.module('@/lib/trigger-sync', () => ({ triggerSync: () => triggerSyncImpl() }));++// "Enable auto-sync" enables in place via the project-local config binding+// (through useSyncEnabledWriter). Capture the writes so a test can assert the+// off → on transition instead of a navigation.+let autoSyncWrites: boolean[] = [];+mock.module('@/lib/config-provider', () => ({+ useConfigContext: () => ({+ projectLocalBinding: {+ patch: (value: { autoSync?: { enabled?: boolean } }) => {+ if (value.autoSync?.enabled !== undefined) autoSyncWrites.push(value.autoSync.enabled);+ return { ok: true };+ },+ },+ }),+}));++const { ShareFreshnessWarning } = await import('./ShareFreshnessWarning');++function makeStatus(overrides: Partial<GitSyncStatus> = {}): GitSyncStatus {+ return {+ state: 'idle',+ lastSyncUtc: null,+ lastFetchUtc: null,+ ahead: 0,+ behind: 0,+ conflictCount: 0,+ hasRemote: true,+ syncEnabled: false,+ ...overrides,+ };+}++afterEach(() => {+ cleanup();+ window.location.hash = '';+ triggerSyncImpl = () => Promise.resolve();+ autoSyncWrites = [];+});++describe('ShareFreshnessWarning', () => {+ test('renders no row when freshness is current', () => {+ render(<ShareFreshnessWarning freshness="current" status={makeStatus()} kind="doc" />);+ expect(screen.queryByTestId('share-freshness-row')).toBeNull();+ });++ test('renders no row when freshness is omitted (fail-open)', () => {+ render(<ShareFreshnessWarning freshness={undefined} status={makeStatus()} kind="doc" />);+ expect(screen.queryByTestId('share-freshness-row')).toBeNull();+ });++ test('absent + sync off: strong dead-link warning, icon + text (not color-only)', () => {+ render(+ <ShareFreshnessWarning+ freshness="absent"+ status={makeStatus({ syncEnabled: false })}+ kind="doc"+ />,+ );+ const row = screen.getByTestId('share-freshness-row');+ expect(row.textContent).toContain("This doc isn't on GitHub yet");+ expect(row.textContent).toContain("won't work until it's pushed");+ // A rendered icon is the non-color cue that makes the warning perceivable+ // without relying on the tint alone.+ expect(row.querySelector('svg')).not.toBeNull();+ });++ test('stale + sync off: soft unpushed-changes note', () => {+ render(+ <ShareFreshnessWarning+ freshness="stale"+ status={makeStatus({ syncEnabled: false })}+ kind="doc"+ />,+ );+ expect(screen.getByTestId('share-freshness-row').textContent).toContain(+ 'This doc has unpushed changes',+ );+ });++ test('stale + sync on: ratified silent cell renders no row', () => {+ render(+ <ShareFreshnessWarning+ freshness="stale"+ status={makeStatus({ syncEnabled: true })}+ kind="doc"+ />,+ );+ expect(screen.queryByTestId('share-freshness-row')).toBeNull();+ });++ test('absent + sync on: soft not-synced-yet note', () => {+ render(+ <ShareFreshnessWarning+ freshness="absent"+ status={makeStatus({ syncEnabled: true })}+ kind="doc"+ />,+ );+ expect(screen.getByTestId('share-freshness-row').textContent).toContain(+ "This doc hasn't synced to GitHub yet",+ );+ });++ test('pushPermission denied: keeps the fact line and adds the no-write-access line', () => {+ render(+ <ShareFreshnessWarning+ freshness="absent"+ status={makeStatus({+ syncEnabled: false,+ pushPermission: { checkStatus: 'denied', deniedReason: 'no-collaborator' },+ })}+ kind="doc"+ />,+ );+ const text = screen.getByTestId('share-freshness-row').textContent ?? '';+ expect(text).toContain("This doc isn't on GitHub yet");+ expect(text).toContain("don't have write access to this repo");+ });++ test('active push error: keeps the fact line and defers to the sync status', () => {+ render(+ <ShareFreshnessWarning+ freshness="absent"+ status={makeStatus({ syncEnabled: false, pushError: 'push rejected (non-fast-forward)' })}+ kind="doc"+ />,+ );+ const text = screen.getByTestId('share-freshness-row').textContent ?? '';+ expect(text).toContain("This doc isn't on GitHub yet");+ expect(text).toContain('Sync is failing');+ });++ test('folder kind substitutes "folder" in the fact line', () => {+ render(+ <ShareFreshnessWarning+ freshness="absent"+ status={makeStatus({ syncEnabled: false })}+ kind="folder"+ />,+ );+ expect(screen.getByTestId('share-freshness-row').textContent).toContain(+ "This folder isn't on GitHub yet",+ );+ });+});++describe('ShareFreshnessWarning — recovery CTAs (FR4/FR5)', () => {+ test('absent + sync off offers Enable auto-sync and How to push manually (git-scm)', () => {+ render(+ <ShareFreshnessWarning+ freshness="absent"+ status={makeStatus({ syncEnabled: false })}+ kind="doc"+ />,+ );+ expect(screen.getByRole('button', { name: 'Enable auto-sync' })).not.toBeNull();+ const link = screen.getByRole('link', { name: /How to push manually/ }) as HTMLAnchorElement;+ expect(link.getAttribute('href')).toBe('https://git-scm.com/docs/git-push');+ });++ test('Enable auto-sync opens the guarded confirm and enables in place (no navigation)', () => {+ window.location.hash = '';+ render(+ <ShareFreshnessWarning+ freshness="absent"+ status={makeStatus({ syncEnabled: false })}+ kind="doc"+ />,+ );+ // The row CTA opens the off → on confirmation gate rather than navigating+ // the sender away to the settings surface.+ fireEvent.click(screen.getByRole('button', { name: 'Enable auto-sync' }));+ const dialog = screen.getByRole('dialog');+ expect(window.location.hash).toBe('');+ expect(autoSyncWrites).toEqual([]); // nothing written until the user confirms++ // Confirming the gate enables auto-sync in place via the project-local+ // config binding.+ fireEvent.click(within(dialog).getByRole('button', { name: 'Enable auto-sync' }));+ expect(autoSyncWrites).toEqual([true]);+ });++ test('absent + sync on offers Sync now (not the push-manually CTAs)', () => {+ render(+ <ShareFreshnessWarning+ freshness="absent"+ status={makeStatus({ syncEnabled: true, state: 'idle' })}+ kind="doc"+ />,+ );+ expect(screen.getByRole('button', { name: 'Sync now' })).not.toBeNull();+ expect(screen.queryByRole('button', { name: 'Enable auto-sync' })).toBeNull();+ expect(screen.queryByRole('link', { name: /How to push manually/ })).toBeNull();+ });++ test('Sync now goes in-flight, then self-clears to Synced on a completed sync', () => {+ const { rerender } = render(+ <ShareFreshnessWarning+ freshness="absent"+ status={makeStatus({ syncEnabled: true, state: 'idle', lastSyncUtc: null })}+ kind="doc"+ />,+ );+ fireEvent.click(screen.getByRole('button', { name: 'Sync now' }));+ expect(screen.getByRole('button', { name: /Syncing/ })).not.toBeNull();++ // A completed sync bumps lastSyncUtc — the "push landed" signal.+ rerender(+ <ShareFreshnessWarning+ freshness="absent"+ status={makeStatus({+ syncEnabled: true,+ state: 'idle',+ lastSyncUtc: '2026-07-02T12:00:00Z',+ })}+ kind="doc"+ />,+ );+ expect(screen.getByTestId('share-freshness-row').textContent).toContain(+ 'Synced. The link is up to date.',+ );+ expect(screen.queryByRole('button', { name: 'Sync now' })).toBeNull();+ });++ test('Sync now reverts from in-flight when the push errors, surfacing the failure line', () => {+ const { rerender } = render(+ <ShareFreshnessWarning+ freshness="absent"+ status={makeStatus({ syncEnabled: true, state: 'idle', lastSyncUtc: null })}+ kind="doc"+ />,+ );+ fireEvent.click(screen.getByRole('button', { name: 'Sync now' }));+ rerender(+ <ShareFreshnessWarning+ freshness="absent"+ status={makeStatus({ syncEnabled: true, state: 'idle', pushError: 'push rejected' })}+ kind="doc"+ />,+ );+ const text = screen.getByTestId('share-freshness-row').textContent ?? '';+ expect(text).toContain('Sync is failing');+ expect(screen.queryByRole('button', { name: /Syncing/ })).toBeNull();+ });++ test('Sync now reverts to actionable when the trigger itself fails, never a stuck spinner', async () => {+ // The trigger never lands (offline / server down): no CC1 status update+ // follows, so without recovery the button would spin "Syncing" forever.+ triggerSyncImpl = () => Promise.reject(new Error('offline'));+ render(+ <ShareFreshnessWarning+ freshness="absent"+ status={makeStatus({ syncEnabled: true, state: 'idle', lastSyncUtc: null })}+ kind="doc"+ />,+ );+ fireEvent.click(screen.getByRole('button', { name: 'Sync now' }));+ expect(screen.getByRole('button', { name: /Syncing/ })).not.toBeNull();++ // The rejected trigger drops back to the actionable Sync now button.+ await waitFor(() => {+ expect(screen.getByRole('button', { name: 'Sync now' })).not.toBeNull();+ });+ expect(screen.queryByRole('button', { name: /Syncing/ })).toBeNull();+ });++ test('Sync now is hidden when the engine is blocked (conflict), leaving the fact line', () => {+ render(+ <ShareFreshnessWarning+ freshness="absent"+ status={makeStatus({ syncEnabled: true, state: 'conflict', conflictCount: 1 })}+ kind="doc"+ />,+ );+ expect(screen.getByTestId('share-freshness-row').textContent).toContain(+ "This doc hasn't synced to GitHub yet",+ );+ expect(screen.queryByRole('button', { name: 'Sync now' })).toBeNull();+ });++ test('a denied push probe shows no recovery CTAs', () => {+ render(+ <ShareFreshnessWarning+ freshness="absent"+ status={makeStatus({+ syncEnabled: false,+ pushPermission: { checkStatus: 'denied', deniedReason: 'no-collaborator' },+ })}+ kind="doc"+ />,+ );+ expect(screen.queryByRole('button', { name: 'Enable auto-sync' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'Sync now' })).toBeNull();+ expect(screen.queryByRole('link', { name: /How to push manually/ })).toBeNull();+ });+});diff --git a/packages/app/src/components/ShareFreshnessWarning.tsx b/packages/app/src/components/ShareFreshnessWarning.tsxnew file mode 100644index 000000000..c39aa784e--- /dev/null+++ b/packages/app/src/components/ShareFreshnessWarning.tsx@@ -0,0 +1,212 @@+/**+ * Non-blocking freshness warning row for the share popover. Renders only when+ * the minted link won't reflect what the sender sees — a stale or absent+ * target — and stays silent otherwise, including the auto-sync-on + stale cell+ * that self-heals within the push cadence.+ *+ * The row is icon + text (never color-only): the fact line always states the+ * problem in words, so a screen reader (and a user who can't perceive the tint)+ * gets the full signal. It also carries the recovery CTAs — enable auto-sync,+ * push manually, or Sync now — except where a denied push probe or an active+ * push error would make those CTAs wrong.+ */++import type { ShareFreshness } from '@inkeep/open-knowledge-core';+import { Trans, useLingui } from '@lingui/react/macro';+import { ArrowUpRight, Check, Info, RefreshCw, TriangleAlert } from 'lucide-react';+import { useEffect, useRef, useState } from 'react';+import { Button } from '@/components/ui/button';+import {+ useEnableSyncWithConfirm,+ useSyncEnabledWriter,+} from '@/hooks/use-enable-sync-with-confirm';+import type { GitSyncStatus } from '@/hooks/use-git-sync-status';+import { dispatchExternalLinkClick } from '@/lib/external-link';+import { triggerSync } from '@/lib/trigger-sync';+import { EnableSyncConfirmDialog } from './EnableSyncConfirmDialog';++type ShareKind = 'doc' | 'folder';++/** Official git-push documentation the "push manually" CTA links out to. */+const PUSH_DOCS_URL = 'https://git-scm.com/docs/git-push';++/**+ * Whether the warning row renders for `(freshness, status)`. The share popover+ * reads this to size itself before the row mounts. `current` / omitted freshness+ * never warns; `stale` with auto-sync ON is the ratified silent cell.+ */+export function shareFreshnessRowVisible(+ freshness: ShareFreshness | undefined,+ status: GitSyncStatus | null,+): boolean {+ if (freshness !== 'stale' && freshness !== 'absent') return false;+ if (freshness === 'stale' && status?.syncEnabled === true) return false;+ return true;+}++/**+ * "Sync now" mirrors the sync badge's own visibility: it is hidden in the+ * states where a manual trigger is meaningless or handled elsewhere (no engine,+ * turned off, needs re-auth, or blocked on a conflict).+ */+function syncNowActionable(status: GitSyncStatus | null): boolean {+ if (!status) return false;+ return (+ status.state !== 'dormant' &&+ status.state !== 'disabled' &&+ status.state !== 'auth-error' &&+ status.state !== 'conflict'+ );+}++export interface ShareFreshnessWarningProps {+ freshness: ShareFreshness | undefined;+ status: GitSyncStatus | null;+ kind: ShareKind;+}++export function ShareFreshnessWarning({ freshness, status, kind }: ShareFreshnessWarningProps) {+ const { t } = useLingui();+ // "Enable auto-sync" runs the same guarded off → on flow as the sync badge and+ // the settings toggle — the EnableSyncConfirmDialog is the sanctioned gate for+ // a transition that starts pushing the repo. It enables sync in place rather+ // than sending the sender off to the settings surface to find the toggle.+ const enableSyncWriter = useSyncEnabledWriter();+ const { confirmOpen, setConfirmOpen, onToggleRequest, onConfirm } =+ useEnableSyncWithConfirm(enableSyncWriter);+ const [syncNow, setSyncNow] = useState<'idle' | 'pending' | 'synced'>('idle');+ // The `lastSyncUtc` at click time; a later value means a sync completed since,+ // which is our "the push landed" signal over the CC1-refreshed status.+ const lastSyncAtClick = useRef<string | null>(null);++ useEffect(() => {+ if (syncNow !== 'pending' || !status) return;+ if (status.pushError || status.pushErrorCode) {+ // The manual sync failed — drop the in-flight state so the warning (now+ // showing the sync-failing line) stands rather than spinning forever.+ setSyncNow('idle');+ return;+ }+ if ((status.lastSyncUtc ?? null) !== lastSyncAtClick.current) {+ setSyncNow('synced');+ }+ }, [syncNow, status]);++ if (!shareFreshnessRowVisible(freshness, status)) return null;++ const rowClass =+ 'flex items-start gap-2 rounded-md border border-dashed border-border bg-muted/40 p-2 text-xs text-muted-foreground';++ if (syncNow === 'synced') {+ return (+ <div className={rowClass} data-testid="share-freshness-row">+ <Check className="mt-0.5 size-3.5 shrink-0" aria-hidden="true" />+ <span>+ <Trans>Synced. The link is up to date.</Trans>+ </span>+ </div>+ );+ }++ const syncEnabled = status?.syncEnabled === true;+ const pushDenied = status?.pushPermission?.checkStatus === 'denied';+ const activePushError = Boolean(status?.pushError || status?.pushErrorCode);+ const degraded = pushDenied || activePushError;+ // A never-pushed target with sync off is the only strong (dead-link) warning;+ // the rest are soft notes.+ const strong = freshness === 'absent' && !syncEnabled;++ let factLine: string;+ if (freshness === 'absent' && !syncEnabled) {+ factLine =+ kind === 'folder'+ ? t`This folder isn't on GitHub yet. The link won't work until it's pushed.`+ : t`This doc isn't on GitHub yet. The link won't work until it's pushed.`;+ } else if (freshness === 'stale') {+ factLine =+ kind === 'folder'+ ? t`This folder has unpushed changes. Recipients will see the last pushed version.`+ : t`This doc has unpushed changes. Recipients will see the last pushed version.`;+ } else {+ factLine =+ kind === 'folder'+ ? t`This folder hasn't synced to GitHub yet. The link will work after the next sync.`+ : t`This doc hasn't synced to GitHub yet. The link will work after the next sync.`;+ }++ // A denied push probe or an active push error makes the recovery CTAs wrong+ // (the sender can't push), so the row states the blocker instead.+ const degradedLine = pushDenied+ ? t`You don't have write access to this repo.`+ : activePushError+ ? t`Sync is failing. See the sync status for details.`+ : null;++ const handleSyncNow = () => {+ lastSyncAtClick.current = status?.lastSyncUtc ?? null;+ setSyncNow('pending');+ // On a trigger that never lands (offline / server down / non-2xx) no CC1+ // status update follows, so drop out of the in-flight state rather than+ // spin forever — the user can retry, and the row falls back to its fact+ // line. Success stays 'pending' until the status effect sees the push land.+ triggerSync('sync').catch((err) => {+ console.warn(+ '[share-freshness] sync trigger failed',+ err instanceof Error ? err.message : err,+ );+ setSyncNow('idle');+ });+ };++ const Icon = strong ? TriangleAlert : Info;++ return (+ <>+ <div className={rowClass} data-testid="share-freshness-row">+ <Icon className="mt-0.5 size-3.5 shrink-0" aria-hidden="true" />+ <div className="flex min-w-0 flex-col gap-1.5">+ <span>{factLine}</span>+ {degradedLine ? <span>{degradedLine}</span> : null}+ {degraded ? null : syncEnabled ? (+ syncNowActionable(status) ? (+ <div>+ {syncNow === 'pending' ? (+ <Button variant="outline" size="xs" disabled>+ <RefreshCw className="size-3 shrink-0 animate-spin" aria-hidden="true" />+ <Trans>Syncing</Trans>+ </Button>+ ) : (+ <Button variant="outline" size="xs" onClick={handleSyncNow}>+ <Trans>Sync now</Trans>+ </Button>+ )}+ </div>+ ) : null+ ) : (+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">+ <Button variant="outline" size="xs" onClick={() => onToggleRequest(true)}>+ <Trans>Enable auto-sync</Trans>+ </Button>+ <a+ href={PUSH_DOCS_URL}+ target="_blank"+ rel="noopener noreferrer"+ onClick={(e) => dispatchExternalLinkClick(e, PUSH_DOCS_URL)}+ onAuxClick={(e) => dispatchExternalLinkClick(e, PUSH_DOCS_URL)}+ className="inline-flex items-center gap-1 transition-colors hover:text-primary"+ >+ <Trans>How to push manually</Trans>+ <ArrowUpRight className="size-3 shrink-0" aria-hidden="true" />+ </a>+ </div>+ )}+ </div>+ </div>+ <EnableSyncConfirmDialog+ open={confirmOpen}+ onOpenChange={setConfirmOpen}+ onConfirm={onConfirm}+ />+ </>+ );+}diff --git a/packages/app/src/components/ShareReceiveMissDialog.dom.test.tsx b/packages/app/src/components/ShareReceiveMissDialog.dom.test.tsxnew file mode 100644index 000000000..6c1df0176--- /dev/null+++ b/packages/app/src/components/ShareReceiveMissDialog.dom.test.tsx@@ -0,0 +1,174 @@+/**+ * Behavioral tests for `ShareReceiveMissDialog` — the primary (no-navigation)+ * miss surface. Self-gates on `missDialogStore`; the verdict fetch reads a+ * stubbed `window.okDesktop`. The load-bearing property: acting on the dialog+ * navigates via the hash but the dialog itself NEVER sets the hash to the dead+ * path, so no phantom tab is opened.+ *+ * Substrate: jsdom via `bun run test:dom`.+ */+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';+import type { ShareTargetStatusResponse } from '@inkeep/open-knowledge-core';+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import { missDialogStore } from '@/lib/share/miss-dialog-store';+import { pendingReceiveNavStore } from '@/lib/share/pending-receive-nav-store';++// The changed-locally cell's Enable auto-sync CTA reaches useSyncEnabledWriter →+// useConfigContext; mock the binding so the guarded flow runs without a live+// config context, and capture writes. Mocked before the dynamic import below.+let autoSyncWrites: boolean[] = [];+mock.module('@/lib/config-provider', () => ({+ useConfigContext: () => ({+ projectLocalBinding: {+ patch: (value: { autoSync?: { enabled?: boolean } }) => {+ if (value.autoSync?.enabled !== undefined) autoSyncWrites.push(value.autoSync.enabled);+ return { ok: true };+ },+ },+ }),+}));++const { ShareReceiveMissDialog } = await import('./ShareReceiveMissDialog');++type FetchTargetStatus = (req: {+ projectPath: string;+ branch: string;+ path: string;+ kind: 'doc' | 'folder';+}) => Promise<ShareTargetStatusResponse | null>;++function installBridge(fetchTargetStatus: FetchTargetStatus): void {+ (window as { okDesktop?: unknown }).okDesktop = {+ config: { projectPath: '/tmp/project' },+ project: { fetchTargetStatus },+ };+}++function stubVerdict(response: ShareTargetStatusResponse | null): FetchTargetStatus {+ return () => Promise.resolve(response);+}++const DOC_NAV = { kind: 'doc' as const, path: 'notes/plan.md', branch: 'feature' };++async function renderArmed(nav = DOC_NAV): Promise<HTMLElement> {+ render(<ShareReceiveMissDialog />);+ missDialogStore.arm(nav);+ const dialog = await screen.findByTestId('share-receive-miss-dialog');+ await screen.findByText((_, el) => el?.getAttribute('data-phase') === 'resolved');+ return dialog;+}++beforeEach(() => {+ cleanup();+ window.location.hash = '';+ missDialogStore.dismiss();+ pendingReceiveNavStore.clear();+});+afterEach(() => {+ cleanup();+ missDialogStore.dismiss();+ pendingReceiveNavStore.clear();+ Reflect.deleteProperty(window, 'okDesktop');+ autoSyncWrites = [];+});++describe('ShareReceiveMissDialog', () => {+ test('renders nothing until the store is armed', () => {+ installBridge(stubVerdict({ verdict: 'deleted' }));+ render(<ShareReceiveMissDialog />);+ expect(screen.queryByTestId('share-receive-miss-dialog')).toBeNull();+ });++ test('deleted verdict shows the honest removed message titled by the target', async () => {+ installBridge(stubVerdict({ verdict: 'deleted' }));+ const dialog = await renderArmed();++ expect(dialog.getAttribute('data-verdict')).toBe('deleted');+ expect(dialog.textContent).toContain('was removed from branch');+ expect(dialog.textContent).toContain('feature');+ // Titled by the target basename so the receiver sees what they tried to open.+ expect(dialog.textContent).toContain('plan.md');+ expect(screen.getByTestId('share-receive-miss-browse')).toBeTruthy();+ expect(screen.queryByTestId('share-receive-miss-open-renamed')).toBeNull();+ });++ test('renamed verdict offers the redirect', async () => {+ installBridge(stubVerdict({ verdict: 'renamed', renamedTo: 'knowledge/new-plan.md' }));+ const dialog = await renderArmed();++ expect(dialog.getAttribute('data-verdict')).toBe('renamed');+ expect(dialog.textContent).toContain('moved to');+ expect(dialog.textContent).toContain('knowledge/new-plan.md');+ });++ test('changed-locally: Enable auto-sync enables in place and dismisses the dialog', async () => {+ installBridge(stubVerdict({ verdict: 'changed-locally' }));+ const dialog = await renderArmed();++ expect(dialog.getAttribute('data-verdict')).toBe('changed-locally');+ expect(dialog.textContent).toContain('has been moved, renamed, or deleted');++ // Open the guarded confirm, then confirm inside it (the confirm dialog is the+ // OTHER role=dialog — the miss dialog carries the testid). Confirming enables+ // in place AND dismisses the miss dialog (the reported gap: it used to stay).+ fireEvent.click(screen.getByTestId('share-receive-miss-enable-sync'));+ const confirm = screen+ .getAllByRole('dialog')+ .find((d) => d.getAttribute('data-testid') !== 'share-receive-miss-dialog');+ if (!confirm) throw new Error('confirm dialog not found');+ fireEvent.click(within(confirm).getByRole('button', { name: 'Enable auto-sync' }));++ expect(autoSyncWrites).toEqual([true]);+ await waitFor(() => {+ expect(missDialogStore.getSnapshot()).toBeNull();+ });+ });++ test('browse folder navigates to the parent folder and dismisses — never to the dead path', async () => {+ installBridge(stubVerdict({ verdict: 'deleted' }));+ await renderArmed();++ fireEvent.click(screen.getByTestId('share-receive-miss-browse'));++ // Navigated to the folder, NOT to the missing doc (no phantom tab).+ expect(window.location.hash).toBe('#/notes/');+ // Dialog dismissed itself.+ await waitFor(() => {+ expect(missDialogStore.getSnapshot()).toBeNull();+ });+ });++ test('accepting the rename navigates to the redirect, arms the backstop, and dismisses', async () => {+ installBridge(stubVerdict({ verdict: 'renamed', renamedTo: 'knowledge/new-plan.md' }));+ await renderArmed();++ fireEvent.click(screen.getByTestId('share-receive-miss-open-renamed'));++ expect(window.location.hash).toBe('#/knowledge/new-plan.md');+ // Backstop armed so a locally-behind redirect target still lands on the miss+ // surface rather than create-mode.+ expect(pendingReceiveNavStore.getSnapshot()).toEqual({+ kind: 'doc',+ path: 'knowledge/new-plan.md',+ branch: 'feature',+ });+ await waitFor(() => {+ expect(missDialogStore.getSnapshot()).toBeNull();+ });+ });++ test('a failed target-status fetch falls back to pull guidance (fail-open)', async () => {+ installBridge(stubVerdict(null));+ const dialog = await renderArmed();++ expect(dialog.getAttribute('data-verdict')).toBe('unknown');+ expect(dialog.textContent).toContain('behind');+ });++ test('folder-share copy substitutes the folder noun', async () => {+ installBridge(stubVerdict({ verdict: 'deleted' }));+ const dialog = await renderArmed({ kind: 'folder', path: 'docs/guides', branch: 'feature' });++ expect(dialog.textContent).toContain('This folder was removed');+ });+});diff --git a/packages/app/src/components/ShareReceiveMissDialog.tsx b/packages/app/src/components/ShareReceiveMissDialog.tsxnew file mode 100644index 000000000..9a12fded1--- /dev/null+++ b/packages/app/src/components/ShareReceiveMissDialog.tsx@@ -0,0 +1,108 @@+/**+ * Primary surface for a share-receive miss: a modal shown WITHOUT navigating to+ * the dead path. When a share deep link targets a doc/folder main's pre-nav+ * probe found absent on the receiver's branch, the deep-link listener arms+ * `missDialogStore` (instead of setting the hash), and this dialog renders the+ * honest verdict — deleted / renamed / never pushed / behind — over whatever the+ * receiver was already looking at. Because navigation never happens, no phantom+ * tab is opened at the missing path and the create-mode fork trap can't fire.+ *+ * Self-gates on the store (renders null until armed), mirroring+ * `ShareBranchSwitchDialog`. Mounted in the editor shell and lazy-loaded, so its+ * verdict-fetch code stays out of the main bundle until a miss actually occurs.+ */+import { useSyncExternalStore } from 'react';+import {+ parentFolderPath,+ ShareReceiveMissContent,+ useShareTargetVerdict,+} from '@/components/share-receive-miss-content';+import {+ DialogBody,+ DialogContent,+ DialogHeader,+ Dialog as DialogRoot,+ DialogTitle,+} from '@/components/ui/dialog';+import { hashFromDocName, hashFromFolderPath } from '@/lib/doc-hash';+import { missDialogStore } from '@/lib/share/miss-dialog-store';+import {+ type PendingReceiveNav,+ pendingReceiveNavStore,+} from '@/lib/share/pending-receive-nav-store';++/** Last path segment — what the receiver tried to open, for the dialog title. */+function targetBasename(path: string): string {+ const segments = path.split('/').filter(Boolean);+ return segments.length > 0 ? segments[segments.length - 1] : path;+}++export function ShareReceiveMissDialog() {+ const nav = useSyncExternalStore(+ missDialogStore.subscribe,+ missDialogStore.getSnapshot,+ () => null,+ );+ if (nav === null) return null;+ // Key on the target so re-arming for a different miss (e.g. a chained rename+ // whose destination is also absent) remounts with a fresh verdict fetch.+ return <ShareReceiveMissDialogInner key={nav.path} nav={nav} />;+}++function ShareReceiveMissDialogInner({ nav }: { nav: PendingReceiveNav }) {+ const state = useShareTargetVerdict(nav);++ function dismiss(): void {+ missDialogStore.dismiss();+ }++ function browseFolder(): void {+ window.location.hash = hashFromFolderPath(parentFolderPath(nav.path));+ dismiss();+ }++ function openRenamed(renamedTo: string): void {+ // Arm the in-tab backstop before navigating: if the rename destination is+ // also missing locally (the receiver's ref is behind), the miss surface+ // renders for it too instead of the create-mode editor.+ pendingReceiveNavStore.arm({ kind: nav.kind, path: renamedTo, branch: nav.branch });+ window.location.hash =+ nav.kind === 'folder' ? hashFromFolderPath(renamedTo) : hashFromDocName(renamedTo);+ dismiss();+ }++ return (+ <DialogRoot+ open+ onOpenChange={(open) => {+ if (!open) dismiss();+ }}+ >+ <DialogContent+ className="sm:max-w-md"+ data-testid="share-receive-miss-dialog"+ data-phase={state.phase}+ data-verdict={state.phase === 'resolved' ? state.resolution.verdict : undefined}+ >+ <DialogHeader>+ <DialogTitle className="truncate">{targetBasename(nav.path)}</DialogTitle>+ </DialogHeader>+ <DialogBody+ className={+ state.phase === 'pending'+ ? 'flex flex-col items-center justify-center gap-3 py-6 text-center text-sm text-muted-foreground'+ : 'flex flex-col items-center justify-center gap-6 py-2 text-center'+ }+ >+ <ShareReceiveMissContent+ nav={nav}+ state={state}+ onBrowseFolder={browseFolder}+ onOpenRenamed={openRenamed}+ onEnableAutoSync={dismiss}+ />+ </DialogBody>+ </DialogContent>+ </DialogRoot>+ );+}diff --git a/packages/app/src/components/ShareReceiveMissPanel.dom.test.tsx b/packages/app/src/components/ShareReceiveMissPanel.dom.test.tsxnew file mode 100644index 000000000..0b853f9e2--- /dev/null+++ b/packages/app/src/components/ShareReceiveMissPanel.dom.test.tsx@@ -0,0 +1,219 @@+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';+import type { ShareTargetStatusResponse } from '@inkeep/open-knowledge-core';+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';+import { pendingReceiveNavStore } from '@/lib/share/pending-receive-nav-store';++// The changed-locally cell's "Enable auto-sync" CTA enables in place via the+// project-local config binding (through useSyncEnabledWriter). Capture the+// writes so the guarded off → on flow is assertable without a live binding.+// Mocked at the module boundary so the dynamic import below picks it up.+let autoSyncWrites: boolean[] = [];+mock.module('@/lib/config-provider', () => ({+ useConfigContext: () => ({+ projectLocalBinding: {+ patch: (value: { autoSync?: { enabled?: boolean } }) => {+ if (value.autoSync?.enabled !== undefined) autoSyncWrites.push(value.autoSync.enabled);+ return { ok: true };+ },+ },+ }),+}));++const { ShareReceiveMissPanel } = await import('./ShareReceiveMissPanel');++type FetchTargetStatus = (req: {+ projectPath: string;+ branch: string;+ path: string;+ kind: 'doc' | 'folder';+}) => Promise<ShareTargetStatusResponse | null>;++function installBridge(fetchTargetStatus: FetchTargetStatus): void {+ (window as { okDesktop?: unknown }).okDesktop = {+ config: { projectPath: '/project' },+ project: { fetchTargetStatus },+ };+}++function stubVerdict(response: ShareTargetStatusResponse | null): FetchTargetStatus {+ return () => Promise.resolve(response);+}++const DOC_NAV = { kind: 'doc' as const, path: 'notes/plan', branch: 'feature' };++async function renderResolved(nav: typeof DOC_NAV = DOC_NAV): Promise<HTMLElement> {+ render(<ShareReceiveMissPanel nav={nav} />);+ const panel = await screen.findByTestId('share-receive-miss-panel');+ // Wait for the fetch to resolve out of the pending phase.+ await screen.findByText((_, el) => el?.getAttribute('data-phase') === 'resolved');+ return panel;+}++beforeEach(() => {+ cleanup();+ window.location.hash = '';+ pendingReceiveNavStore.clear();+});+afterEach(() => {+ cleanup();+ Reflect.deleteProperty(window, 'okDesktop');+ window.location.hash = '';+ pendingReceiveNavStore.clear();+ autoSyncWrites = [];+});++describe('ShareReceiveMissPanel verdict surfaces', () => {+ test('renamed verdict offers to open the redirect target', async () => {+ installBridge(stubVerdict({ verdict: 'renamed', renamedTo: 'knowledge/new-plan' }));+ const panel = await renderResolved();++ expect(panel.getAttribute('data-verdict')).toBe('renamed');+ expect(panel.textContent).toContain('moved to');+ expect(panel.textContent).toContain('knowledge/new-plan');+ expect(screen.getByTestId('share-receive-miss-open-renamed')).toBeTruthy();+ expect(screen.getByTestId('share-receive-miss-browse')).toBeTruthy();+ });++ test('accepting the rename navigates to the redirect and re-arms the miss guard', async () => {+ installBridge(stubVerdict({ verdict: 'renamed', renamedTo: 'knowledge/new-plan' }));+ await renderResolved();++ fireEvent.click(screen.getByTestId('share-receive-miss-open-renamed'));++ expect(window.location.hash).toBe('#/knowledge/new-plan');+ // Re-armed so the redirect target, if also missing locally, renders the+ // panel again rather than the create-mode editor.+ expect(pendingReceiveNavStore.getSnapshot()).toEqual({+ kind: 'doc',+ path: 'knowledge/new-plan',+ branch: 'feature',+ });+ });++ // The verdict fetch must query the real repo file — a stripped docName makes+ // git report `never-on-branch` for every `.md` share miss regardless of cause.+ test('the verdict fetch preserves the share target file extension', async () => {+ let captured: { path: string; branch: string; kind: string } | null = null;+ installBridge((req) => {+ captured = { path: req.path, branch: req.branch, kind: req.kind };+ return Promise.resolve({ verdict: 'deleted' });+ });+ await renderResolved({ kind: 'doc', path: 'docs/moved.md', branch: 'main' });++ expect(captured).toEqual({ path: 'docs/moved.md', branch: 'main', kind: 'doc' });+ });++ test('deleted verdict shows an honest removed message with a browse escape', async () => {+ installBridge(stubVerdict({ verdict: 'deleted' }));+ const panel = await renderResolved();++ expect(panel.getAttribute('data-verdict')).toBe('deleted');+ expect(panel.textContent).toContain('was removed from branch');+ expect(panel.textContent).toContain('feature');+ expect(screen.queryByTestId('share-receive-miss-open-renamed')).toBeNull();+ expect(screen.getByTestId('share-receive-miss-browse')).toBeTruthy();+ });++ // A path that never existed on the branch must never be messaged as "removed".+ test('never-on-branch verdict is not messaged as removed', async () => {+ installBridge(stubVerdict({ verdict: 'never-on-branch' }));+ const panel = await renderResolved();++ expect(panel.getAttribute('data-verdict')).toBe('never-on-branch');+ expect(panel.textContent).toContain("isn't on branch");+ expect(panel.textContent).toContain('may not have been pushed yet');+ expect(panel.textContent).not.toContain('was removed');+ });++ test('on-origin verdict shows the stale-local pull guidance', async () => {+ installBridge(stubVerdict({ verdict: 'on-origin' }));+ const panel = await renderResolved();++ expect(panel.getAttribute('data-verdict')).toBe('on-origin');+ expect(panel.textContent).toContain('is behind');+ expect(panel.textContent).toContain('Pull the latest changes');+ });++ // A local uncommitted change (rm/mv of the target the receiver never synced)+ // is NOT "behind — pull"; it gets its own honest copy plus an in-place+ // Enable auto-sync recovery CTA (the guarded off → on flow).+ test('changed-locally verdict shows the local-change message and enables auto-sync in place', async () => {+ installBridge(stubVerdict({ verdict: 'changed-locally' }));+ const panel = await renderResolved();++ expect(panel.getAttribute('data-verdict')).toBe('changed-locally');+ expect(panel.textContent).toContain('has been moved, renamed, or deleted');+ expect(panel.textContent).not.toContain('Pull the latest changes');+ expect(screen.getByTestId('share-receive-miss-browse')).toBeTruthy();++ // The CTA opens the off → on confirmation gate; nothing is written until the+ // user confirms, and confirming enables auto-sync in place (no navigation).+ fireEvent.click(screen.getByTestId('share-receive-miss-enable-sync'));+ const dialog = screen.getByRole('dialog');+ expect(autoSyncWrites).toEqual([]);+ fireEvent.click(within(dialog).getByRole('button', { name: 'Enable auto-sync' }));+ expect(autoSyncWrites).toEqual([true]);+ // The in-tab surface has no modal to close, so a successful enable clears it+ // by navigating to the parent folder (DOC_NAV path 'notes/plan' → 'notes').+ expect(window.location.hash).toBe('#/notes/');+ });++ // Fail-open (Pattern B): a transport failure surfaces as `null` from the proxy;+ // the panel degrades to today's pull guidance, never a stuck spinner or throw.+ test('a failed target-status fetch falls back to pull guidance', async () => {+ installBridge(stubVerdict(null));+ const panel = await renderResolved();++ expect(panel.getAttribute('data-verdict')).toBe('unknown');+ expect(panel.textContent).toContain('Pull the latest changes');+ });++ test('a rejected target-status fetch falls back to pull guidance', async () => {+ installBridge(() => Promise.reject(new Error('ipc closed')));+ const panel = await renderResolved();++ expect(panel.getAttribute('data-verdict')).toBe('unknown');+ expect(panel.textContent).toContain('Pull the latest changes');+ });++ test('no desktop bridge (web host) falls back to pull guidance without fetching', async () => {+ Reflect.deleteProperty(window, 'okDesktop');+ const panel = await renderResolved();++ expect(panel.getAttribute('data-verdict')).toBe('unknown');+ expect(panel.textContent).toContain('Pull the latest changes');+ });++ test('the browse-folder escape navigates to the parent folder view', async () => {+ installBridge(stubVerdict({ verdict: 'deleted' }));+ await renderResolved();++ fireEvent.click(screen.getByTestId('share-receive-miss-browse'));+ expect(window.location.hash).toBe('#/notes/');+ });++ test('folder-share copy substitutes the folder noun', async () => {+ installBridge(stubVerdict({ verdict: 'deleted' }));+ const panel = await renderResolved({ kind: 'folder', path: 'knowledge', branch: 'feature' });++ expect(panel.textContent).toContain('folder');+ });++ // A11y: the terminal surface is a status region and its icon is decorative —+ // the message text (not color) carries the meaning, and controls have names.+ test('exposes an accessible status region with a decorative icon', async () => {+ installBridge(stubVerdict({ verdict: 'deleted' }));+ const panel = await renderResolved();++ expect(panel.getAttribute('role')).toBe('status');+ expect(panel.querySelector('svg')?.getAttribute('aria-hidden')).toBe('true');+ expect(screen.getByTestId('share-receive-miss-browse').textContent).toContain('Browse folder');+ });++ test('moves focus to the primary action when the verdict resolves', async () => {+ installBridge(stubVerdict({ verdict: 'renamed', renamedTo: 'knowledge/new-plan' }));+ await renderResolved();+ // The rename redirect is the primary action; keyboard users land on it.+ expect(document.activeElement).toBe(screen.getByTestId('share-receive-miss-open-renamed'));+ });+});diff --git a/packages/app/src/components/ShareReceiveMissPanel.tsx b/packages/app/src/components/ShareReceiveMissPanel.tsxnew file mode 100644index 000000000..4f9a7c84e--- /dev/null+++ b/packages/app/src/components/ShareReceiveMissPanel.tsx@@ -0,0 +1,76 @@+import { useEffect, useRef } from 'react';+import {+ parentFolderPath,+ ShareReceiveMissContent,+ useShareTargetVerdict,+} from '@/components/share-receive-miss-content';+import { hashFromDocName, hashFromFolderPath } from '@/lib/doc-hash';+import {+ type PendingReceiveNav,+ pendingReceiveNavStore,+} from '@/lib/share/pending-receive-nav-store';++/**+ * In-tab BACKSTOP for a share-receive miss discovered only after navigation —+ * main's pre-nav probe said the target existed, but the receiver's local ref no+ * longer carries it, so the resolver returns `{ kind: 'missing' }` and the+ * editor would otherwise open create-mode (the silent-fork trap). The common+ * case — a target main already knows is absent — is handled BEFORE navigation+ * by `ShareReceiveMissDialog`, so this panel only renders for the residual+ * post-nav miss. Both surfaces share the verdict fetch + rendering.+ */+export function ShareReceiveMissPanel({ nav }: { nav: PendingReceiveNav }) {+ const state = useShareTargetVerdict(nav);+ const containerRef = useRef<HTMLDivElement>(null);+ const branch = nav.branch;++ // Focus the primary action (the first button — the rename redirect where+ // present, else Browse folder) once a verdict resolves, so keyboard users land+ // on an actionable control rather than stranded where the editor used to be.+ useEffect(() => {+ if (state.phase === 'resolved') containerRef.current?.querySelector('button')?.focus();+ }, [state.phase]);++ function browseFolder(): void {+ window.location.hash = hashFromFolderPath(parentFolderPath(nav.path));+ }++ function openRenamed(renamedTo: string): void {+ // Re-arm for the redirect target so, if the rename destination is also+ // missing locally (the receiver's ref is behind), the miss surface renders+ // for it too instead of the create-mode editor.+ pendingReceiveNavStore.arm({ kind: nav.kind, path: renamedTo, branch });+ window.location.hash =+ nav.kind === 'folder' ? hashFromFolderPath(renamedTo) : hashFromDocName(renamedTo);+ }++ // One stable container across the pending → resolved transition — the node+ // must not remount, so the shared content renders inside rather than swapping+ // element types.+ return (+ <div+ ref={containerRef}+ role="status"+ aria-live={state.phase === 'pending' ? 'polite' : undefined}+ data-testid="share-receive-miss-panel"+ data-phase={state.phase}+ data-verdict={state.phase === 'resolved' ? state.resolution.verdict : undefined}+ className={+ state.phase === 'pending'+ ? 'flex h-full flex-col items-center justify-center gap-3 p-8 text-center text-sm text-muted-foreground'+ : 'flex h-full flex-col items-center justify-center gap-6 p-8 text-center'+ }+ >+ <ShareReceiveMissContent+ nav={nav}+ state={state}+ onBrowseFolder={browseFolder}+ onOpenRenamed={openRenamed}+ // No modal to close for the in-tab backstop; navigate to the parent+ // folder so the recovery action clears the surface (same escape as+ // Browse folder).+ onEnableAutoSync={browseFolder}+ />+ </div>+ );+}diff --git a/packages/app/src/components/SyncStatusBadge.tsx b/packages/app/src/components/SyncStatusBadge.tsxindex d2a0f09cc..e5dab3ba0 100644--- a/packages/app/src/components/SyncStatusBadge.tsx+++ b/packages/app/src/components/SyncStatusBadge.tsx@@ -28,6 +28,7 @@ import type { GitSyncStatus } from '@/hooks/use-git-sync-status';import { useGitSyncStatusDetailed } from '@/hooks/use-git-sync-status';import { useConfigContext } from '@/lib/config-provider';import { filePathToDocName, hashFromDocName } from '@/lib/doc-hash';+import { triggerSync } from '@/lib/trigger-sync';import { EnableSyncConfirmDialog } from './EnableSyncConfirmDialog';import { Button } from './ui/button';import { Popover, PopoverContent, PopoverTrigger } from './ui/popover';@@ -36,6 +37,21 @@ import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';// ── helpers ──────────────────────────────────────────────────────────────────+/**+ * Fire-and-forget manual sync from a badge button. The badge's own status+ * stream drives the visible state, so a rejected trigger (offline / server+ * down) needs no UI handling — but it gets a breadcrumb rather than being+ * swallowed silently, so a "Sync now did nothing" report is triageable.+ */+function triggerSyncFromBadge(): void {+ triggerSync('sync').catch((err) => {+ console.warn(+ '[sync-badge] manual sync trigger failed',+ err instanceof Error ? err.message : err,+ );+ });+}+function formatRelative(iso: string | null): string {if (!iso) return t`never`;const diff = Date.now() - new Date(iso).getTime();@@ -51,14 +67,6 @@ function formatRelative(iso: string | null): string {return new Date(iso).toLocaleDateString();}-async function triggerSync(op: 'sync' | 'push' | 'pull'): Promise<void> {- await fetch('/api/sync/trigger', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ op }),- });-}-// ── inner: icon + color per state ────────────────────────────────────────────interface BadgeIconProps {@@ -560,7 +568,7 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {status.state !== 'disabled' &&status.state !== 'auth-error' &&status.state !== 'conflict' && (- <Button variant="outline" size="xs" onClick={() => void triggerSync('sync')}>+ <Button variant="outline" size="xs" onClick={triggerSyncFromBadge}><Trans>Sync now</Trans></Button>)}@@ -570,7 +578,7 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {</Button>)}{enabled && status.state === 'offline' && (- <Button variant="outline" size="xs" onClick={() => void triggerSync('sync')}>+ <Button variant="outline" size="xs" onClick={triggerSyncFromBadge}><Trans>Retry</Trans></Button>)}diff --git a/packages/app/src/components/navigation-targets.ts b/packages/app/src/components/navigation-targets.tsindex baf7adc2c..1cb76aa48 100644--- a/packages/app/src/components/navigation-targets.ts+++ b/packages/app/src/components/navigation-targets.ts@@ -65,7 +65,10 @@ interface DocumentSizeMeta {size?: number;}-function normalizeTargetPath(target: string): { normalizedTarget: string; expectsFolder: boolean } {+export function normalizeTargetPath(target: string): {+ normalizedTarget: string;+ expectsFolder: boolean;+} {const trimmed = target.trim();return {normalizedTarget: normalizeDocNameInput(trimmed).replace(/\/+$/g, ''),diff --git a/packages/app/src/components/share-receive-miss-content.tsx b/packages/app/src/components/share-receive-miss-content.tsxnew file mode 100644index 000000000..9397be1f7--- /dev/null+++ b/packages/app/src/components/share-receive-miss-content.tsx@@ -0,0 +1,265 @@+/**+ * Shared content for the share-receive miss surface — the target-status verdict+ * fetch plus the icon / message / actions rendering. Consumed by two shells:+ *+ * - `ShareReceiveMissDialog` (primary) — a modal shown WITHOUT navigating to+ * the dead path, so a deleted / renamed / never-pushed target never opens a+ * phantom tab.+ * - `ShareReceiveMissPanel` (backstop) — the in-tab surface for the rare case+ * where the miss is only discovered after navigation (main's pre-nav probe+ * said the target existed, but the receiver's local ref no longer carries+ * it). Kept so the create-mode fork trap stays mechanically closed.+ *+ * Fail-open: no desktop bridge, no branch, or a failed fetch resolves to+ * `unknown` (the honest "your checkout is behind — pull" guidance).+ */+import type { ShareTargetStatusResponse } from '@inkeep/open-knowledge-core';+import { Trans, useLingui } from '@lingui/react/macro';+import {+ ArrowDownToLine,+ FilePen,+ FileQuestion,+ FileX2,+ FolderOpen,+ Loader2,+ MapPin,+ RefreshCw,+} from 'lucide-react';+import { type ReactNode, useEffect, useState } from 'react';+import { Button } from '@/components/ui/button';+import {+ useEnableSyncWithConfirm,+ useSyncEnabledWriter,+} from '@/hooks/use-enable-sync-with-confirm';+import type { PendingReceiveNav } from '@/lib/share/pending-receive-nav-store';+import { EnableSyncConfirmDialog } from './EnableSyncConfirmDialog';++export type ShareTargetVerdictState =+ | { readonly phase: 'pending' }+ | { readonly phase: 'resolved'; readonly resolution: ShareTargetStatusResponse };++/** Parent folder of a target path — the browse-folder escape destination. */+export function parentFolderPath(path: string): string {+ const idx = path.lastIndexOf('/');+ return idx === -1 ? '' : path.slice(0, idx);+}++/**+ * Fetch the target-status verdict for a share-receive miss. Fail-open: no+ * bridge / no branch / failed fetch → `unknown`.+ */+export function useShareTargetVerdict(nav: PendingReceiveNav): ShareTargetVerdictState {+ const [state, setState] = useState<ShareTargetVerdictState>({ phase: 'pending' });+ const branch = nav.branch;+ useEffect(() => {+ const bridge = window.okDesktop ?? null;+ // No desktop bridge (web host) or a branch-less legacy share → skip the+ // fetch and fall back to today's pull guidance rather than a bare spinner.+ if (!bridge || branch === null) {+ setState({ phase: 'resolved', resolution: { verdict: 'unknown' } });+ return;+ }+ let cancelled = false;+ void bridge.project+ .fetchTargetStatus({+ projectPath: bridge.config.projectPath,+ branch,+ path: nav.path,+ kind: nav.kind,+ })+ .then((response) => {+ // `null` is a transport failure; the proxy already coerces a skewed 200+ // to `unknown`. Both degrade to today's guidance (fail-open).+ if (!cancelled)+ setState({ phase: 'resolved', resolution: response ?? { verdict: 'unknown' } });+ })+ .catch((err) => {+ if (!cancelled) {+ // Keep the error identity for triage (a bare `unknown` verdict hides+ // whether the IPC bridge, the fetch, or the server was the cause).+ console.warn(+ '[receive] miss target-status fetch failed',+ err instanceof Error ? err.message : err,+ );+ setState({ phase: 'resolved', resolution: { verdict: 'unknown' } });+ }+ });+ return () => {+ cancelled = true;+ };+ }, [branch, nav.kind, nav.path]);+ return state;+}++/**+ * "Enable auto-sync" recovery action for the `changed-locally` cell — mounted+ * ONLY for that verdict, so the shared miss content stays free of config+ * context for every other verdict (and every other surface that renders it).+ * Runs the same guarded off → on flow as the sync badge, the settings toggle,+ * and the share popover's freshness row: `EnableSyncConfirmDialog` is the+ * sanctioned gate for a transition that starts pushing the repo. Reuses the+ * canonical hook so the safety gate can't be bypassed, and enables in place+ * rather than sending the user off to the settings surface.+ */+function EnableAutoSyncButton({ onEnabled }: { onEnabled?: () => void }) {+ const enableSyncWriter = useSyncEnabledWriter();+ const { confirmOpen, setConfirmOpen, onToggleRequest, onConfirm } = useEnableSyncWithConfirm(+ enableSyncWriter,+ { onEnabled },+ );+ return (+ <>+ <Button onClick={() => onToggleRequest(true)} data-testid="share-receive-miss-enable-sync">+ <RefreshCw className="size-4" aria-hidden="true" />+ <Trans>Enable auto-sync</Trans>+ </Button>+ <EnableSyncConfirmDialog+ open={confirmOpen}+ onOpenChange={setConfirmOpen}+ onConfirm={onConfirm}+ />+ </>+ );+}++/**+ * Inner content for the miss surface — spinner while pending, else the icon ++ * cause-specific message + escape actions. The OUTER container (with its+ * `data-testid` / `data-phase` / `data-verdict`) is owned by each shell so the+ * DOM node stays stable across the pending → resolved transition (a type swap+ * here would remount the node). Callbacks let each shell decide what "browse+ * folder" / "open renamed" do (the dialog dismisses itself; the panel re-arms+ * for a chained miss).+ */+export function ShareReceiveMissContent({+ nav,+ state,+ onBrowseFolder,+ onOpenRenamed,+ onEnableAutoSync,+}: {+ nav: PendingReceiveNav;+ state: ShareTargetVerdictState;+ onBrowseFolder: () => void;+ onOpenRenamed: (renamedTo: string) => void;+ /** Called after a successful in-place Enable auto-sync (changed-locally cell) — the shell dismisses or navigates away. */+ onEnableAutoSync?: () => void;+}) {+ const { t } = useLingui();+ const branch = nav.branch;+ const targetNoun = nav.kind === 'folder' ? t`folder` : t`document`;++ if (state.phase === 'pending') {+ return (+ <>+ <Loader2 className="size-5 animate-spin" aria-hidden="true" />+ <Trans>Checking for updates on GitHub</Trans>+ </>+ );+ }+ const { resolution } = state;++ const browseFolderButton = (+ <Button variant="outline" onClick={onBrowseFolder} data-testid="share-receive-miss-browse">+ <FolderOpen className="size-4" aria-hidden="true" />+ <Trans>Browse folder</Trans>+ </Button>+ );++ let icon: ReactNode;+ let message: ReactNode;+ let actions: ReactNode;++ if (resolution.verdict === 'renamed') {+ icon = <MapPin className="size-9" aria-hidden="true" />;+ message = (+ <Trans>+ This {targetNoun} moved to{' '}+ <code className="rounded-sm bg-muted px-1 py-0.5 text-foreground/80">+ {resolution.renamedTo}+ </code>+ . Open it there?+ </Trans>+ );+ actions = (+ <>+ <Button+ onClick={() => onOpenRenamed(resolution.renamedTo)}+ data-testid="share-receive-miss-open-renamed"+ >+ <MapPin className="size-4" aria-hidden="true" />+ <Trans>Open it there</Trans>+ </Button>+ {browseFolderButton}+ </>+ );+ } else if (resolution.verdict === 'deleted') {+ icon = <FileX2 className="size-9" aria-hidden="true" />;+ message = (+ <Trans>+ This {targetNoun} was removed from branch{' '}+ <code className="rounded-sm bg-muted px-1 py-0.5 text-foreground/80">{branch}</code>.+ </Trans>+ );+ actions = browseFolderButton;+ } else if (resolution.verdict === 'never-on-branch') {+ icon = <FileQuestion className="size-9" aria-hidden="true" />;+ message = (+ <Trans>+ This {targetNoun} isn't on branch{' '}+ <code className="rounded-sm bg-muted px-1 py-0.5 text-foreground/80">{branch}</code>. It may+ not have been pushed yet.+ </Trans>+ );+ actions = browseFolderButton;+ } else if (resolution.verdict === 'changed-locally') {+ // The target is still on origin and in the receiver's committed HEAD, but+ // they removed/renamed it in their own working tree without syncing. This is+ // NOT "behind — pull": pulling can't reconcile an uncommitted local change.+ icon = <FilePen className="size-9" aria-hidden="true" />;+ message =+ branch === null ? (+ <Trans>+ This {targetNoun} has been moved, renamed, or deleted in your local copy. Please commit+ your changes or enable auto-sync.+ </Trans>+ ) : (+ <Trans>+ This {targetNoun} has been moved, renamed, or deleted in your local copy of branch{' '}+ <code className="rounded-sm bg-muted px-1 py-0.5 text-foreground/80">{branch}</code>.+ Please commit your changes or enable auto-sync.+ </Trans>+ );+ actions = (+ <>+ <EnableAutoSyncButton onEnabled={onEnableAutoSync} />+ {browseFolderButton}+ </>+ );+ } else {+ // on-origin (local ref behind) and unknown (fetch failed / no bridge) both+ // land on the honest stale-local pull guidance.+ icon = <ArrowDownToLine className="size-9" aria-hidden="true" />;+ message =+ branch === null ? (+ <Trans>Your local copy is behind. Pull the latest changes, then open the link again.</Trans>+ ) : (+ <Trans>+ Your local copy of branch{' '}+ <code className="rounded-sm bg-muted px-1 py-0.5 text-foreground/80">{branch}</code> is+ behind. Pull the latest changes, then open the link again.+ </Trans>+ );+ actions = browseFolderButton;+ }++ return (+ <>+ <div className="flex size-16 items-center justify-center rounded-full border bg-muted/40 text-muted-foreground">+ {icon}+ </div>+ <p className="max-w-md text-balance text-base leading-6 text-foreground/90">{message}</p>+ <div className="flex flex-col-reverse gap-2 sm:flex-row">{actions}</div>+ </>+ );+}diff --git a/packages/app/src/hooks/use-enable-sync-with-confirm.dom.test.tsx b/packages/app/src/hooks/use-enable-sync-with-confirm.dom.test.tsxindex 330ae0890..236954121 100644--- a/packages/app/src/hooks/use-enable-sync-with-confirm.dom.test.tsx+++ b/packages/app/src/hooks/use-enable-sync-with-confirm.dom.test.tsx@@ -43,9 +43,12 @@ async function loadHooks() {return hooks;}-function ConfirmProbe({ writer }: { writer: Writer }) {+function ConfirmProbe({ writer, onEnabled }: { writer: Writer; onEnabled?: () => void }) {if (!hooks) throw new Error('hooks not loaded');- latestConfirmState = hooks.useEnableSyncWithConfirm(writer);+ latestConfirmState = hooks.useEnableSyncWithConfirm(+ writer,+ onEnabled ? { onEnabled } : undefined,+ );return <div data-testid="confirm-open">{String(latestConfirmState.confirmOpen)}</div>;}@@ -138,6 +141,40 @@ describe('useEnableSyncWithConfirm runtime behavior', () => {expect(screen.getByTestId('confirm-open').textContent).toBe('true');expect(toastErrors).toEqual(['Failed to enable sync — branch is protected']);});++ test('fires opts.onEnabled once, only after a successful confirm', async () => {+ await loadHooks();+ let enabledCalls = 0;+ const writer: Writer = () => ({ ok: true });+ render(<ConfirmProbe writer={writer} onEnabled={() => enabledCalls++} />);++ await act(async () => {+ latestConfirmState?.onToggleRequest(true);+ });+ expect(enabledCalls).toBe(0); // not until the user confirms++ await act(async () => {+ latestConfirmState?.onConfirm();+ });+ expect(enabledCalls).toBe(1);+ });++ test('does not fire opts.onEnabled when the enable write fails', async () => {+ await loadHooks();+ consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});+ let enabledCalls = 0;+ const writer: Writer = () => ({ ok: false, error: 'branch is protected' });+ render(<ConfirmProbe writer={writer} onEnabled={() => enabledCalls++} />);++ await act(async () => {+ latestConfirmState?.onToggleRequest(true);+ latestConfirmState?.onConfirm();+ });++ expect(enabledCalls).toBe(0);+ // Confirm dialog stays open on failure so the user can retry.+ expect(screen.getByTestId('confirm-open').textContent).toBe('true');+ });});describe('useSyncEnabledWriter runtime behavior', () => {diff --git a/packages/app/src/hooks/use-enable-sync-with-confirm.ts b/packages/app/src/hooks/use-enable-sync-with-confirm.tsindex 7ae01bf8c..145b51250 100644--- a/packages/app/src/hooks/use-enable-sync-with-confirm.ts+++ b/packages/app/src/hooks/use-enable-sync-with-confirm.ts@@ -8,6 +8,11 @@* The dialog state lives here so both surfaces share the same gate; the* caller renders <EnableSyncConfirmDialog> with the returned props.*+ * `opts.onEnabled` (optional) fires once, on a SUCCESSFUL enable, so a host+ * surface can dismiss itself on the same confirm click (e.g. the share-receive+ * miss dialog closing after the user chooses Enable auto-sync). It never fires+ * on a failed write or on the on → off direction.+ ** The hook accepts a `writer` so the toggle is decoupled from any specific* persistence backend. Today the writer is always a `ConfigBinding.patch`* adapter targeting `__local__/project`; tests inject fakes; future@@ -85,6 +90,7 @@ interface UseEnableSyncWithConfirmResult {export function useEnableSyncWithConfirm(writer: SyncEnabledWriter | null,+ opts?: { onEnabled?: () => void },): UseEnableSyncWithConfirmResult {const { t } = useLingui();const [confirmOpen, setConfirmOpen] = useState(false);@@ -120,7 +126,12 @@ export function useEnableSyncWithConfirm(// Close only on success — closing on failure would contradict the// error toast and force the user to re-trigger the toggle to retry.const ok = applyEnabled(true);- if (ok) setConfirmOpen(false);+ if (ok) {+ setConfirmOpen(false);+ // Success-only notify so a host surface can dismiss itself on the same+ // click. A failed write leaves both dialogs up so the user can retry.+ opts?.onEnabled?.();+ }}return { confirmOpen, setConfirmOpen, onToggleRequest, onConfirm };diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.tsindex dadce0680..8c0f42f37 100644--- a/packages/app/src/lib/desktop-bridge-types.ts+++ b/packages/app/src/lib/desktop-bridge-types.ts@@ -24,6 +24,7 @@ import type {LocalOpOkInitResponse,OkFolderState,RecentProjectEntry,+ ShareTargetStatusResponse,TerminalCli,WorktreeCreateRequest,WorktreeCreateResult,@@ -916,9 +917,28 @@ export interface OkDesktopBridge {}): Promise<BranchInfoResponse | null>;/*** Proxy `POST /api/git/checkout` against the project's running server.- * See canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.+ * `fastForward` (on-origin "Switch and update branch") fast-forwards the+ * target branch to origin's tip before checkout; divergence → `ff-diverged`+ * (nothing mutated). See canonical JSDoc in+ * `packages/desktop/src/shared/bridge-contract.ts`.*/- runCheckout(request: { projectPath: string; branch: string }): Promise<CheckoutResponse | null>;+ runCheckout(request: {+ projectPath: string;+ branch: string;+ fastForward?: boolean;+ }): Promise<CheckoutResponse | null>;+ /**+ * Proxy `POST /api/share/target-status` for the branch-switch dialog's+ * verdict pivot (on-origin / renamed / deleted / never-on-branch /+ * unknown). See canonical JSDoc in+ * `packages/desktop/src/shared/bridge-contract.ts`.+ */+ fetchTargetStatus(request: {+ projectPath: string;+ branch: string;+ path: string;+ kind: 'doc' | 'folder';+ }): Promise<ShareTargetStatusResponse | null>;/*** Gate dialog dismissal on the `branch-switched` broadcast landing* in the project window. See canonical JSDoc indiff --git a/packages/app/src/lib/install-deep-link-listener.test.ts b/packages/app/src/lib/install-deep-link-listener.test.tsindex 58842c609..d49a0ef21 100644--- a/packages/app/src/lib/install-deep-link-listener.test.ts+++ b/packages/app/src/lib/install-deep-link-listener.test.ts@@ -1,4 +1,7 @@-import { describe, expect, mock, test } from 'bun:test';+import { afterEach, describe, expect, mock, test } from 'bun:test';+import { normalizeTargetPath } from '@/components/navigation-targets';+import { missDialogStore } from '@/lib/share/miss-dialog-store';+import { pendingReceiveNavStore } from '@/lib/share/pending-receive-nav-store';import type { OkDesktopBridge, OkDesktopConfig } from './desktop-bridge-types';import { deriveShareReceiveToast, installDeepLinkListener } from './install-deep-link-listener';@@ -7,6 +10,7 @@ type DeepLinkPayload = {kind?: 'doc' | 'folder';branch?: string | null;multiCandidate?: boolean;+ targetMissing?: boolean;};function makeBridge(overrides: Partial<OkDesktopBridge> = {}): OkDesktopBridge & {@@ -207,6 +211,75 @@ describe('installDeepLinkListener — folder + content-root shares (US-010)', ()});});+describe('installDeepLinkListener — share-receive miss guard arming', () => {+ afterEach(() => {+ pendingReceiveNavStore.clear();+ missDialogStore.dismiss();+ });++ test('arms the miss guard before navigating a doc share', () => {+ const bridge = makeBridge();+ const setHash = mock(() => {});+ installDeepLinkListener({ bridge, setHash });+ bridge.fireDeepLink({ doc: 'notes/plan', branch: 'feature' });+ // Path is the resolver's normalized form so it matches the missing+ // target's `.target` when navigation lands.+ expect(pendingReceiveNavStore.getSnapshot()).toEqual({+ kind: 'doc',+ path: normalizeTargetPath('notes/plan').normalizedTarget,+ branch: 'feature',+ });+ });++ test('arms with a null branch for a branch-less legacy doc share', () => {+ const bridge = makeBridge();+ const setHash = mock(() => {});+ installDeepLinkListener({ bridge, setHash });+ bridge.fireDeepLink({ doc: 'intro' });+ expect(pendingReceiveNavStore.getSnapshot()?.branch).toBeNull();+ });++ test('arms with the folder kind for a folder share', () => {+ const bridge = makeBridge();+ const setHash = mock(() => {});+ installDeepLinkListener({ bridge, setHash });+ bridge.fireDeepLink({ doc: 'docs/sub', kind: 'folder' });+ expect(pendingReceiveNavStore.getSnapshot()?.kind).toBe('folder');+ });++ // The existing-project leg: main's stat probe already found the target+ // missing on the receiver's branch. Arm the miss DIALOG and do NOT navigate —+ // the honest verdict shows as a modal, so no phantom tab opens at the dead+ // path. The in-tab pendingReceiveNav panel is not armed on this leg.+ test('arms the miss dialog without navigating when main flags the target missing', () => {+ const bridge = makeBridge();+ const setHash = mock(() => {});+ installDeepLinkListener({ bridge, setHash });+ bridge.fireDeepLink({ doc: 'notes/plan', branch: 'feature', targetMissing: true });+ expect(setHash.mock.calls.length).toBe(0);+ expect(missDialogStore.getSnapshot()).toEqual({+ kind: 'doc',+ path: 'notes/plan',+ branch: 'feature',+ });+ expect(pendingReceiveNavStore.getSnapshot()).toBeNull();+ });++ test('arms the miss dialog for a missing folder target without navigating', () => {+ const bridge = makeBridge();+ const setHash = mock(() => {});+ installDeepLinkListener({ bridge, setHash });+ bridge.fireDeepLink({ doc: 'docs/sub', kind: 'folder', targetMissing: true });+ expect(setHash.mock.calls.length).toBe(0);+ expect(missDialogStore.getSnapshot()).toEqual({+ kind: 'folder',+ path: 'docs/sub',+ branch: null,+ });+ expect(pendingReceiveNavStore.getSnapshot()).toBeNull();+ });+});+describe('deriveShareReceiveToast (FR9)', () => {test('returns payload with branch + projectPath when multiCandidate is true', () => {expect(@@ -305,4 +378,23 @@ describe('installDeepLinkListener — FR9 toast emission', () => {bridge.fireDeepLink({ doc: 'docs/x.md', branch: 'feat-bar' });expect(emitToast.mock.calls).toHaveLength(0);});++ test('suppresses the confirmation toast on a known-missing target (miss dialog is the surface)', () => {+ const bridge = makeBridge();+ const setHash = mock(() => {});+ const emitToast = mock(() => {});+ installDeepLinkListener({ bridge, setHash, emitToast });+ // multiCandidate would normally emit "Opened on branch X"; a missing target+ // shows the verdict dialog without navigating, so the confirmation is+ // suppressed rather than misleadingly claiming the share opened.+ bridge.fireDeepLink({+ doc: 'docs/x.md',+ branch: 'feat-bar',+ multiCandidate: true,+ targetMissing: true,+ });+ expect(emitToast.mock.calls).toHaveLength(0);+ expect(setHash.mock.calls.length).toBe(0);+ expect(missDialogStore.getSnapshot()?.path).toBe('docs/x.md');+ });});diff --git a/packages/app/src/lib/install-deep-link-listener.ts b/packages/app/src/lib/install-deep-link-listener.tsindex 0057a9c2f..36a9bd889 100644--- a/packages/app/src/lib/install-deep-link-listener.ts+++ b/packages/app/src/lib/install-deep-link-listener.ts@@ -46,6 +46,8 @@import { toast } from 'sonner';import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';import { encodeShareTargetForHash } from '@/lib/doc-hash';+import { missDialogStore } from '@/lib/share/miss-dialog-store';+import { pendingReceiveNavStore } from '@/lib/share/pending-receive-nav-store';interface InstallDeepLinkListenerOptions {/** Bridge resolved from `window.okDesktop`. Absent in web/CLI. */@@ -110,23 +112,24 @@ export function installDeepLinkListener(// folder-share — those payloads carry no `kind`, and the doc form is the// back-compat target.const kind = evt.kind ?? 'doc';- // Stale-branch gate: main's target-existence probe found the share's- // target absent on the receiver's checked-out branch (target added on the- // remote branch but not yet fetched). Surface a toast in-context instead- // of navigating into a blank editor / empty folder, and skip the hash nav- // so the window stays on its current view.+ // Keep the share target's file extension: the verdict fetch needs the real+ // repo path, and both stores normalize for matching.+ const nav = { kind, path: evt.doc, branch: evt.branch ?? null };+ // Main's pre-nav stat probe already found the target absent on the+ // receiver's checked-out branch (deleted / renamed / not yet fetched). Show+ // the honest verdict as a modal WITHOUT navigating to the dead path — no+ // phantom tab is opened and create-mode can't fork. The in-tab+ // `pendingReceiveNav` panel stays the backstop for a miss discovered only+ // AFTER navigation (main said present, but the local ref no longer carries+ // it), which the branch below arms.if (evt.targetMissing === true) {- const label = kind === 'folder' ? 'folder' : 'file';- const onBranch =- evt.branch === undefined || evt.branch === null || evt.branch === ''- ? ''- : ` on branch ${evt.branch}`;- emitToast(`This ${label} isn't in your local checkout${onBranch} yet`, {- description: 'Pull the latest changes, then open the share link again.',- duration: 5000,- });+ missDialogStore.arm(nav);return;}+ // Arm the renderer's in-tab miss backstop before navigating, then navigate.+ // The store self-clears once navigation leaves this target, so a later+ // wiki-link to the same path is create-on-navigate again.+ pendingReceiveNavStore.arm(nav);// `branch` rides the hash as `?branch=` ONLY for doc shares (a// defense-in-depth signal for the renderer's branch-switch trigger). Folder// shares resolve the branch-switch upstream before navigation, so the folderdiff --git a/packages/app/src/lib/share/branch-switch-flow.test.ts b/packages/app/src/lib/share/branch-switch-flow.test.tsindex 84293e0bd..23d283283 100644--- a/packages/app/src/lib/share/branch-switch-flow.test.ts+++ b/packages/app/src/lib/share/branch-switch-flow.test.ts@@ -5,12 +5,15 @@ import { type BranchInfoResponse, BranchInfoResponseSchema } from '@inkeep/open-import {applyBranchInfo,applyCheckoutOutcome,+ applyVerdict,type BranchSwitchDialogState,classifyCheckoutOutcome,formatCurrentLabel,initialBranchSwitchState,markSwitching,+ markVerdictPending,selectBranchSwitchVariant,+ shouldProbeTargetStatus,} from './branch-switch-flow';const cleanInfo = (overrides: Partial<BranchInfoResponse> = {}): BranchInfoResponse =>@@ -375,18 +378,6 @@ describe('classifyCheckoutOutcome — branch-in-other-worktree (FR6 / J5)', () =});describe('applyCheckoutOutcome — J5 transition', () => {- function cleanInfo(): BranchInfoResponse {- return {- currentBranch: 'main',- currentHeadSha: null,- detached: false,- targetBranchExists: true,- docExistsOnTarget: true,- docExistsOnCurrent: true,- dirtyConflicts: { conflicts: false, files: [] },- };- }-test('switching → branch-in-other-worktree carries otherWorktreePath + preserves pendingDoc + info', () => {const switching: BranchSwitchDialogState = {phase: 'switching',@@ -450,7 +441,7 @@ describe('applyCheckoutOutcome — J5 transition', () => {// typed result returns the unchanged state with no side-effect so a// delayed checkout response can't fire a ghost toast after the user// has already chosen the pivot CTA path.- const lateResponse = applyCheckoutOutcome(pivot, { ok: true, currentBranch: 'feat-bar' });+ const lateResponse = applyCheckoutOutcome(pivot, { ok: true });expect(lateResponse.state).toBe(pivot);expect(lateResponse.sideEffect).toBeUndefined();@@ -466,3 +457,170 @@ describe('applyCheckoutOutcome — J5 transition', () => {expect(lateOtherFailure.sideEffect).toBeUndefined();});});++describe('shouldProbeTargetStatus (origin-hint pivot gate)', () => {+ test('true on the switch-to-recover variant when the origin hint is false', () => {+ expect(+ shouldProbeTargetStatus(+ cleanInfo({ shareTargetExists: false, shareTargetOnOriginBranch: false }),+ ),+ ).toBe(true);+ });++ test('false when the origin hint is true (doc is on origin — plain switch is fine)', () => {+ expect(+ shouldProbeTargetStatus(+ cleanInfo({ shareTargetExists: false, shareTargetOnOriginBranch: true }),+ ),+ ).toBe(false);+ });++ test('false when the hint is omitted (fail-open to today plain switch)', () => {+ expect(shouldProbeTargetStatus(cleanInfo({ shareTargetExists: false }))).toBe(false);+ });++ test('false when the target already exists on the current branch (variant A, not a miss)', () => {+ expect(+ shouldProbeTargetStatus(+ cleanInfo({ shareTargetExists: true, shareTargetOnOriginBranch: false }),+ ),+ ).toBe(false);+ });++ test('false when a dirty conflict blocks the switch (variant D, no recovery via switch)', () => {+ expect(+ shouldProbeTargetStatus(+ cleanInfo({+ shareTargetExists: false,+ shareTargetOnOriginBranch: false,+ dirtyConflicts: { conflicts: true, files: ['x.md'] },+ }),+ ),+ ).toBe(false);+ });+});++describe('markVerdictPending', () => {+ test('ready → verdict-pending, preserving info', () => {+ const ready: BranchSwitchDialogState = { phase: 'ready', info: cleanInfo() };+ expect(markVerdictPending(ready)).toEqual({ phase: 'verdict-pending', info: cleanInfo() });+ });++ test('identity from non-ready phases (a late dispatch cannot rewind a switch)', () => {+ const switching: BranchSwitchDialogState = {+ phase: 'switching',+ info: cleanInfo(),+ pendingDoc: 'docs/foo.md',+ };+ expect(markVerdictPending(switching)).toBe(switching);+ });+});++describe('applyVerdict', () => {+ const pending: BranchSwitchDialogState = { phase: 'verdict-pending', info: cleanInfo() };++ test('on-origin resolves to the on-origin verdict cell', () => {+ expect(applyVerdict(pending, { verdict: 'on-origin' })).toEqual({+ phase: 'verdict',+ info: cleanInfo(),+ resolution: { kind: 'on-origin' },+ });+ });++ test('renamed carries renamedTo through to the resolution', () => {+ expect(applyVerdict(pending, { verdict: 'renamed', renamedTo: 'guides/a.md' })).toEqual({+ phase: 'verdict',+ info: cleanInfo(),+ resolution: { kind: 'renamed', renamedTo: 'guides/a.md' },+ });+ });++ test('deleted resolves to the deleted terminal cell', () => {+ expect(applyVerdict(pending, { verdict: 'deleted' })).toEqual({+ phase: 'verdict',+ info: cleanInfo(),+ resolution: { kind: 'deleted' },+ });+ });++ test('never-on-branch resolves distinctly from deleted', () => {+ expect(applyVerdict(pending, { verdict: 'never-on-branch' })).toEqual({+ phase: 'verdict',+ info: cleanInfo(),+ resolution: { kind: 'never-on-branch' },+ });+ });++ test('unknown verdict falls back to ready (today plain switch)', () => {+ expect(applyVerdict(pending, { verdict: 'unknown' })).toEqual({+ phase: 'ready',+ info: cleanInfo(),+ });+ });++ test('null proxy result falls back to ready (fail-open on transport failure)', () => {+ expect(applyVerdict(pending, null)).toEqual({ phase: 'ready', info: cleanInfo() });+ });++ test('identity from non-verdict-pending phases (a late fetch cannot clobber a switch in flight)', () => {+ const switching: BranchSwitchDialogState = {+ phase: 'switching',+ info: cleanInfo(),+ pendingDoc: 'docs/foo.md',+ };+ expect(applyVerdict(switching, { verdict: 'on-origin' })).toBe(switching);+ });+});++describe('markSwitching from a verdict cell', () => {+ test('on-origin verdict → switching, carrying the navigation target', () => {+ const verdict: BranchSwitchDialogState = {+ phase: 'verdict',+ info: cleanInfo(),+ resolution: { kind: 'on-origin' },+ };+ expect(markSwitching(verdict, 'docs/notes.md')).toEqual({+ phase: 'switching',+ info: cleanInfo(),+ pendingDoc: 'docs/notes.md',+ });+ });++ test('renamed verdict → switching, navigating to the renamed path', () => {+ const verdict: BranchSwitchDialogState = {+ phase: 'verdict',+ info: cleanInfo(),+ resolution: { kind: 'renamed', renamedTo: 'guides/notes.md' },+ };+ expect(markSwitching(verdict, 'guides/notes.md')).toEqual({+ phase: 'switching',+ info: cleanInfo(),+ pendingDoc: 'guides/notes.md',+ });+ });+});++describe('classifyCheckoutOutcome — ff-diverged (FR9 fast-forward refusal)', () => {+ test('ff-diverged classifies to the branch-diverged action', () => {+ expect(classifyCheckoutOutcome({ ok: false, reason: 'ff-diverged' })).toEqual({+ action: 'branch-diverged',+ });+ });+});++describe('applyCheckoutOutcome — ff-diverged transition', () => {+ test('switching → verdict{diverged} with no toast (dialog offers a plain switch)', () => {+ const switching: BranchSwitchDialogState = {+ phase: 'switching',+ info: cleanInfo(),+ pendingDoc: 'docs/notes.md',+ };+ const result = applyCheckoutOutcome(switching, { ok: false, reason: 'ff-diverged' });+ expect(result.state).toEqual({+ phase: 'verdict',+ info: cleanInfo(),+ resolution: { kind: 'diverged' },+ });+ expect(result.sideEffect).toBeUndefined();+ });+});diff --git a/packages/app/src/lib/share/branch-switch-flow.ts b/packages/app/src/lib/share/branch-switch-flow.tsindex 9d4744373..7c6eb9936 100644--- a/packages/app/src/lib/share/branch-switch-flow.ts+++ b/packages/app/src/lib/share/branch-switch-flow.ts@@ -17,11 +17,15 @@* The dialog MUST NOT navigate when checkout returns `{ok: true}` — navigation* waits on the CC1 `branch-switched` signal so the CRDT transition is fully* settled before the doc opens. `classifyCheckoutOutcome` returns- * `'await-cc1'` for this case; the listener registration is owned by a- * follow-up story.+ * `'await-cc1'` for this case; the dialog then waits on that signal before+ * opening the doc.*/-import type { BranchInfoResponse, CheckoutResponse } from '@inkeep/open-knowledge-core';+import type {+ BranchInfoResponse,+ CheckoutResponse,+ ShareTargetStatusResponse,+} from '@inkeep/open-knowledge-core';/*** Discriminated outcome of `selectBranchSwitchVariant` — the four cells of@@ -149,6 +153,15 @@ export type CheckoutOutcome =*/readonly action: 'pivot-to-other-worktree';readonly otherWorktreePath: string;+ }+ | {+ /**+ * The fast-forward-only pre-checkout update was refused because the+ * local branch diverged from origin, so the checkout was never+ * attempted. Dialog shows the diverged verdict cell — an honest note+ * plus a plain switch — and leaves reconciliation to the sync engine.+ */+ readonly action: 'branch-diverged';};/**@@ -186,6 +199,8 @@ export function classifyCheckoutOutcome(response: CheckoutResponse): CheckoutOut}return { action: 'pivot-to-other-worktree', otherWorktreePath: path };}+ case 'ff-diverged':+ return { action: 'branch-diverged' };default: {const _exhaustive: never = response.reason;throw new Error(`Unhandled CheckoutFailureReason: ${String(_exhaustive)}`);@@ -215,9 +230,54 @@ export function classifyCheckoutOutcome(response: CheckoutResponse): CheckoutOut* `applyCheckoutOutcome`) are pure and exhaustively unit-tested so the* React component stays declarative.*/+/**+ * Resolved verdict for the branch-switch dialog's origin-hint pivot. When+ * `branch-info` reports `shareTargetOnOriginBranch === false` on the+ * switch-to-recover variant, the dialog fetches a real verdict rather than+ * over-promising that a plain switch recovers the doc:+ *+ * - `on-origin` — the doc IS at origin's tip (the local ref was just stale);+ * offer "Switch and update branch" (fast-forward + checkout).+ * - `renamed` — the doc moved; offer to open `renamedTo` after the switch.+ * - `deleted` — a removal commit exists; honest terminal message.+ * - `never-on-branch` — the path never existed on this branch; messaged+ * distinctly from `deleted` (never "removed").+ * - `diverged` — reached only after a fast-forward attempt found the local+ * branch diverged from origin; offer a plain switch with an honest note,+ * reconciliation left to the sync engine.+ *+ * `unknown` and `changed-locally` verdicts (and a null proxy result) never+ * reach here — they fall back to the `ready` variant so the dialog offers+ * today's plain switch. (`changed-locally` is a receive-miss-only verdict: the+ * shared target-status endpoint can return it, but the branch-switch dialog has+ * no cell for it, so it degrades to the plain switch.)+ */+type VerdictResolution =+ | { readonly kind: 'on-origin' }+ | { readonly kind: 'renamed'; readonly renamedTo: string }+ | { readonly kind: 'deleted' }+ | { readonly kind: 'never-on-branch' }+ | { readonly kind: 'diverged' };+export type BranchSwitchDialogState =| { readonly phase: 'loading' }| { readonly phase: 'ready'; readonly info: BranchInfoResponse }+ | {+ /**+ * The origin-existence hint was `false` on the switch-to-recover+ * variant; a `target-status` fetch is in flight. The dialog shows a+ * lightweight checking state. `info` is preserved so an `unknown`+ * verdict can fall back to the `ready` variant without re-fetching.+ */+ readonly phase: 'verdict-pending';+ readonly info: BranchInfoResponse;+ }+ | {+ /** A `target-status` (or post-fast-forward) verdict resolved. */+ readonly phase: 'verdict';+ readonly info: BranchInfoResponse;+ readonly resolution: VerdictResolution;+ }| {readonly phase: 'switching';readonly info: BranchInfoResponse;@@ -261,20 +321,74 @@ export function applyBranchInfo(}/**- * Transition from `ready` to `switching` when the user clicks Switch.- * Stores the pending doc on the new state — the CC1 listener reads it- * after `branch-switched` to fire navigation. From non-ready phases this- * is an identity no-op so a delayed click can't race a checkout already- * in flight.+ * Transition to `switching` when the user clicks a switch affordance. Fires+ * from `ready` (the plain switch) or `verdict` (the on-origin / renamed /+ * diverged cells re-offer a switch). `pendingDoc` is the navigation target the+ * CC1 listener opens after `branch-switched` — the original share path for a+ * plain / on-origin switch, or `renamedTo` for the rename offer. From every+ * other phase this is an identity no-op so a delayed click can't race a+ * checkout already in flight.*/export function markSwitching(state: BranchSwitchDialogState,pendingDoc: string,): BranchSwitchDialogState {- if (state.phase !== 'ready') return state;+ if (state.phase !== 'ready' && state.phase !== 'verdict') return state;return { phase: 'switching', info: state.info, pendingDoc };}+/**+ * True when the branch-switch dialog should replace its plain-switch offer+ * with a fetch-backed verdict. Fires only on the "switch to recover" variant+ * (target missing on the current branch, clean tree) AND when the network-free+ * origin hint is explicitly `false` — i.e. the local remote-tracking ref does+ * not carry the target. A `true` or omitted hint keeps today's plain switch+ * (fail-open): the post-switch guard backstops the residual miss.+ */+export function shouldProbeTargetStatus(info: BranchInfoResponse): boolean {+ return selectBranchSwitchVariant(info).kind === 'B' && info.shareTargetOnOriginBranch === false;+}++/**+ * Transition `ready` → `verdict-pending` when the dialog kicks off the+ * target-status fetch. Identity from every other phase so a delayed dispatch+ * can't rewind a switch already in flight. The caller gates on+ * `shouldProbeTargetStatus`.+ */+export function markVerdictPending(state: BranchSwitchDialogState): BranchSwitchDialogState {+ if (state.phase !== 'ready') return state;+ return { phase: 'verdict-pending', info: state.info };+}++/**+ * Apply a `target-status` response to the pending verdict state. A `null`+ * proxy result or an `unknown` verdict falls back to the `ready` variant so+ * the dialog offers today's plain switch (fail-open, backstopped by the+ * post-switch guard). Every other verdict resolves to its `verdict` cell.+ * Identity from non-`verdict-pending` phases so a late fetch can't clobber a+ * state the user already advanced past.+ */+export function applyVerdict(+ state: BranchSwitchDialogState,+ response: ShareTargetStatusResponse | null,+): BranchSwitchDialogState {+ if (state.phase !== 'verdict-pending') return state;+ // Fail-open (null / `unknown`) AND `changed-locally` (a receive-miss-only+ // verdict with no branch-switch cell) fall back to today's plain switch.+ if (+ response === null ||+ response.verdict === 'unknown' ||+ response.verdict === 'changed-locally'+ ) {+ return { phase: 'ready', info: state.info };+ }+ const resolution: VerdictResolution =+ response.verdict === 'renamed'+ ? { kind: 'renamed', renamedTo: response.renamedTo }+ : { kind: response.verdict };+ return { phase: 'verdict', info: state.info, resolution };+}+/*** Discriminated reason for the toast side-effect the dialog renders when* `applyCheckoutOutcome` transitions out of `switching`. Made explicit so the@@ -372,6 +486,14 @@ export function applyCheckoutOutcome(sideEffect: { kind: 'toast', reason: outcome.reason },};}+ if (outcome.action === 'branch-diverged') {+ // The fast-forward pre-update refused the divergent branch and skipped the+ // checkout. Surface the diverged verdict cell (honest note + plain switch)+ // instead of a toast — the user chooses whether to switch without the doc.+ return {+ state: { phase: 'verdict', info: state.info, resolution: { kind: 'diverged' } },+ };+ }return {state: { phase: 'ready', info: state.info },sideEffect: { kind: 'toast', reason: outcome.reason },diff --git a/packages/app/src/lib/share/miss-dialog-store.ts b/packages/app/src/lib/share/miss-dialog-store.tsnew file mode 100644index 000000000..1825a1dcd--- /dev/null+++ b/packages/app/src/lib/share/miss-dialog-store.ts@@ -0,0 +1,61 @@+/**+ * Renderer store for the share-receive MISS DIALOG.+ *+ * When a share deep link targets a doc/folder main's pre-nav probe found absent+ * on the receiver's checked-out branch (`targetMissing`), the deep-link listener+ * arms this store INSTEAD of navigating to the dead path. `ShareReceiveMissDialog`+ * self-gates on it and shows the honest verdict (deleted / renamed / never+ * pushed / behind) as a modal — so the receiver never opens a phantom tab at a+ * path that carries no doc, and never silently forks it in create-mode.+ *+ * Armed at deep-link time (which can fire before React mounts, e.g. cold-start+ * from the link), so the value buffers here until the dialog subscribes — the+ * same module-singleton + `useSyncExternalStore` pattern as `receive-store`.+ * `dismiss()` clears it after the user picks an escape (browse / open-renamed)+ * or closes the dialog.+ */++import type { PendingReceiveNav } from '@/lib/share/pending-receive-nav-store';++export interface MissDialogStore {+ arm(nav: PendingReceiveNav): void;+ dismiss(): void;+ getSnapshot(): PendingReceiveNav | null;+ subscribe(listener: () => void): () => void;+}++function createMissDialogStore(): MissDialogStore {+ let current: PendingReceiveNav | null = null;+ const listeners = new Set<() => void>();++ function notify(): void {+ for (const l of listeners) l();+ }++ function setCurrent(next: PendingReceiveNav | null): void {+ if (current === next) return;+ current = next;+ notify();+ }++ return {+ arm(nav): void {+ setCurrent(nav);+ },+ dismiss(): void {+ setCurrent(null);+ },+ getSnapshot(): PendingReceiveNav | null {+ return current;+ },+ subscribe(listener): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ };+}++/** Module-level singleton — the deep-link listener arms it, the dialog reads it. */+export const missDialogStore: MissDialogStore = createMissDialogStore();diff --git a/packages/app/src/lib/share/pending-receive-nav-store.test.ts b/packages/app/src/lib/share/pending-receive-nav-store.test.tsnew file mode 100644index 000000000..e443d520e--- /dev/null+++ b/packages/app/src/lib/share/pending-receive-nav-store.test.ts@@ -0,0 +1,178 @@+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import type { ResolvedNavigationTarget } from '@/components/navigation-targets';+import {+ createPendingReceiveNavStore,+ hashSelectsPendingNav,+ matchesShareReceiveMiss,+ type PendingReceiveNav,+ type PendingReceiveNavStore,+} from './pending-receive-nav-store';++const DOC_NAV: PendingReceiveNav = { kind: 'doc', path: 'notes/plan', branch: 'feature' };++function missing(target: string): ResolvedNavigationTarget {+ return { kind: 'missing', target };+}+function doc(docName: string): ResolvedNavigationTarget {+ return { kind: 'doc', target: docName, docName };+}++describe('matchesShareReceiveMiss', () => {+ test('a missing target matching the armed pending nav is a share-receive miss', () => {+ expect(matchesShareReceiveMiss(missing('notes/plan'), DOC_NAV)).toEqual(DOC_NAV);+ });++ // A missing target with no armed nav is an ordinary wiki-link+ // create-on-navigate — the guard must stay out of its way.+ test('a missing target with no armed nav is not a share-receive miss', () => {+ expect(matchesShareReceiveMiss(missing('notes/plan'), null)).toBeNull();+ });++ test('a missing target whose path differs from the armed nav is not a miss', () => {+ expect(matchesShareReceiveMiss(missing('other/doc'), DOC_NAV)).toBeNull();+ });++ // The store keeps the share target's extension (the verdict fetch needs it),+ // while the resolver reports the stripped docName — the matcher normalizes so+ // an extension-bearing armed nav still recognizes its missing target.+ test('an extension-bearing armed nav matches its stripped missing target', () => {+ const mdNav: PendingReceiveNav = { kind: 'doc', path: 'docs/moved.md', branch: 'main' };+ expect(matchesShareReceiveMiss(missing('docs/moved'), mdNav)).toEqual(mdNav);+ });++ test('a present doc target is never a miss even while a nav is armed', () => {+ expect(matchesShareReceiveMiss(doc('notes/plan'), DOC_NAV)).toBeNull();+ });++ test('a null active target is not a miss', () => {+ expect(matchesShareReceiveMiss(null, DOC_NAV)).toBeNull();+ });+});++describe('hashSelectsPendingNav', () => {+ test('a doc hash still selects the armed doc (branch query ignored)', () => {+ expect(hashSelectsPendingNav('#/notes/plan?branch=feature', DOC_NAV)).toBe(true);+ expect(hashSelectsPendingNav('#/notes/plan', DOC_NAV)).toBe(true);+ });++ test('a different doc hash does not select the armed doc', () => {+ expect(hashSelectsPendingNav('#/other', DOC_NAV)).toBe(false);+ });++ // A real share link's target carries the `.md`/`.mdx` extension (GitHub blob+ // URLs always do), so the store is armed with that extension-bearing path and+ // the hash encodes the same. Both sides must normalize to compare, or the store+ // clears itself on its own arming navigation and the miss guard never fires.+ test('a doc hash carrying a file extension still selects the armed extension-bearing nav', () => {+ const mdNav: PendingReceiveNav = { kind: 'doc', path: 'docs/moved.md', branch: 'main' };+ expect(hashSelectsPendingNav('#/docs%2Fmoved.md?branch=main', mdNav)).toBe(true);+ expect(+ hashSelectsPendingNav('#/notes%2Fplan.mdx', { ...DOC_NAV, path: 'notes/plan.mdx' }),+ ).toBe(true);+ });++ test('a folder hash selects the armed folder regardless of trailing slash', () => {+ const folderNav: PendingReceiveNav = { kind: 'folder', path: 'knowledge', branch: 'main' };+ expect(hashSelectsPendingNav('#/knowledge/', folderNav)).toBe(true);+ expect(hashSelectsPendingNav('#/', folderNav)).toBe(false);+ });++ test('the content-root sentinel selects an armed root-folder share', () => {+ const rootNav: PendingReceiveNav = { kind: 'folder', path: '', branch: 'main' };+ expect(hashSelectsPendingNav('#/', rootNav)).toBe(true);+ expect(hashSelectsPendingNav('#/somewhere', rootNav)).toBe(false);+ });+});++// Drives the store's real hashchange wiring through a controllable fake+// `window` (the DOM is a system boundary). The store captures its own+// `hashchange` handler on first arm; `navigateTo` sets the fake location and+// invokes that captured handler, so `onHashChange` runs its real+// `hashSelectsPendingNav` logic against a live-looking navigation. Mirrors the+// `globalThis.window` fake pattern in `relaunch-store.test.ts`.+describe('pendingReceiveNavStore lifecycle', () => {+ let hashHandler: (() => void) | null = null;+ const stores: PendingReceiveNavStore[] = [];++ beforeEach(() => {+ hashHandler = null;+ const fakeWindow = {+ location: { hash: '' },+ addEventListener: (type: string, fn: () => void) => {+ if (type === 'hashchange') hashHandler = fn;+ },+ removeEventListener: (type: string, fn: () => void) => {+ if (type === 'hashchange' && hashHandler === fn) hashHandler = null;+ },+ };+ Object.defineProperty(globalThis, 'window', { configurable: true, value: fakeWindow });+ });++ afterEach(() => {+ for (const s of stores.splice(0)) s.dispose();+ Reflect.deleteProperty(globalThis, 'window');+ });++ function freshStore(): PendingReceiveNavStore {+ const s = createPendingReceiveNavStore();+ stores.push(s);+ return s;+ }+ function navigateTo(hash: string): void {+ (window as unknown as { location: { hash: string } }).location.hash = hash;+ hashHandler?.();+ }++ test('arm publishes the pending nav and notifies subscribers', () => {+ const store = freshStore();+ let notifications = 0;+ store.subscribe(() => {+ notifications += 1;+ });+ store.arm(DOC_NAV);+ expect(store.getSnapshot()).toEqual(DOC_NAV);+ expect(notifications).toBe(1);+ });++ // After a share-receive miss, a later navigation elsewhere must drop the+ // pending nav so a subsequent wiki-link to the same path is create-on-navigate+ // again, not a spurious miss panel.+ test('navigating away from the armed target self-clears the pending nav', () => {+ const store = freshStore();+ navigateTo('#/notes/plan?branch=feature');+ store.arm(DOC_NAV);+ expect(store.getSnapshot()).toEqual(DOC_NAV);++ navigateTo('#/somewhere-else');+ expect(store.getSnapshot()).toBeNull();+ });++ test('a hashchange that stays on the armed target keeps the pending nav', () => {+ const store = freshStore();+ navigateTo('#/notes/plan');+ store.arm(DOC_NAV);++ // e.g. a re-dispatched deep link re-appends the branch query — same target.+ navigateTo('#/notes/plan?branch=feature');+ expect(store.getSnapshot()).toEqual(DOC_NAV);+ });++ // The listener arms with the extension-bearing share target, then sets the hash+ // from the same path. The store must survive its own arming navigation —+ // otherwise the guard self-clears before the editor reads it and the receiver+ // lands in create-mode at the shared path.+ test('a share target with a file extension survives its own arming hashchange', () => {+ const store = freshStore();+ const mdNav: PendingReceiveNav = { kind: 'doc', path: 'docs/moved.md', branch: 'main' };+ store.arm(mdNav);+ navigateTo('#/docs%2Fmoved.md?branch=main');+ expect(store.getSnapshot()).toEqual(mdNav);+ });++ test('clear resets the pending nav', () => {+ const store = freshStore();+ store.arm(DOC_NAV);+ store.clear();+ expect(store.getSnapshot()).toBeNull();+ });+});diff --git a/packages/app/src/lib/share/pending-receive-nav-store.ts b/packages/app/src/lib/share/pending-receive-nav-store.tsnew file mode 100644index 000000000..9a3d5f2d8--- /dev/null+++ b/packages/app/src/lib/share/pending-receive-nav-store.ts@@ -0,0 +1,156 @@+/**+ * Renderer store for the pending share-receive navigation.+ *+ * A share-receive deep link (desktop) navigates the window to the shared+ * doc. When that navigation lands on a path the branch doesn't carry, the+ * resolver returns `{ kind: 'missing' }` and the editor would otherwise open+ * create-mode — the "type here and silently fork the doc at the shared path"+ * trap. The renderer can't tell that miss apart from an ordinary wiki-link+ * create-on-navigate by the target alone (both are `missing`); this store+ * carries the provenance that distinguishes them, so EditorArea renders an+ * honest terminal panel for a share-receive miss and leaves wiki-link+ * create-on-navigate untouched.+ *+ * Armed by the deep-link listener right before it sets the hash, and+ * self-clears on the first hashchange that leaves the armed target — keyed to+ * the hash (the navigation source of truth) rather than React render timing,+ * so arming can't race a stale render into clearing itself, and a later+ * wiki-link to the same path is create-on-navigate again. Mirrors the+ * `receive-store` singleton + `useSyncExternalStore` pattern.+ */++import {+ normalizeTargetPath,+ type ResolvedNavigationTarget,+} from '@/components/navigation-targets';+import { docNameFromHash, isContentRootHash } from '@/lib/doc-hash';++export interface PendingReceiveNav {+ readonly kind: 'doc' | 'folder';+ /**+ * The share target path as delivered — the file extension is preserved so the+ * target-status verdict fetch queries the real repo file (a stripped docName+ * makes every `.md` share miss look `never-on-branch`). The miss matcher and+ * the self-clear normalize it to compare against the resolver's+ * extension-stripped `activeTarget.target`.+ */+ readonly path: string;+ /** Share branch the target-status verdict fetch keys off; null on legacy branch-less shares. */+ readonly branch: string | null;+}++export interface PendingReceiveNavStore {+ arm(nav: PendingReceiveNav): void;+ clear(): void;+ getSnapshot(): PendingReceiveNav | null;+ subscribe(listener: () => void): () => void;+ /** Test-only teardown: detach the hashchange listener the store installs on first arm. */+ dispose(): void;+}++function normalizeFolder(path: string): string {+ return path.replace(/^\/+|\/+$/g, '');+}++/**+ * True while `hash` still selects `armed`'s target. Doc: the hash's docName+ * (the `?branch=` query stripped by `docNameFromHash`) equals the armed path.+ * Folder: the trailing-slash form (or the `#/` content-root sentinel) resolves+ * to the same folder. Drives the self-clear — a hashchange that no longer+ * selects the armed target has navigated away, so the pending nav is stale.+ */+export function hashSelectsPendingNav(hash: string, armed: PendingReceiveNav): boolean {+ if (armed.kind === 'folder') {+ if (isContentRootHash(hash)) return normalizeFolder(armed.path) === '';+ const docName = docNameFromHash(hash);+ return docName !== null && normalizeFolder(docName) === normalizeFolder(armed.path);+ }+ const docName = docNameFromHash(hash);+ if (docName === null) return false;+ // Both sides carry the file extension a real share target has (`armed.path` as+ // delivered, the hash as encoded), while the resolver strips it — so normalize+ // both to the same extension-stripped form. Without this the store self-clears+ // on its own arming navigation and the miss guard never fires.+ return (+ normalizeTargetPath(docName).normalizedTarget ===+ normalizeTargetPath(armed.path).normalizedTarget+ );+}++export function createPendingReceiveNavStore(): PendingReceiveNavStore {+ let current: PendingReceiveNav | null = null;+ const listeners = new Set<() => void>();+ let hashListenerAttached = false;++ function notify(): void {+ for (const l of listeners) l();+ }++ function setCurrent(next: PendingReceiveNav | null): void {+ if (current === next) return;+ current = next;+ notify();+ }++ function onHashChange(): void {+ if (current === null) return;+ if (hashSelectsPendingNav(window.location.hash, current)) return;+ setCurrent(null);+ }++ function ensureHashListener(): void {+ if (hashListenerAttached || typeof window === 'undefined') return;+ hashListenerAttached = true;+ window.addEventListener('hashchange', onHashChange);+ }++ return {+ arm(nav): void {+ ensureHashListener();+ setCurrent(nav);+ },+ clear(): void {+ setCurrent(null);+ },+ getSnapshot(): PendingReceiveNav | null {+ return current;+ },+ subscribe(listener): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ dispose(): void {+ if (hashListenerAttached && typeof window !== 'undefined') {+ window.removeEventListener('hashchange', onHashChange);+ hashListenerAttached = false;+ }+ setCurrent(null);+ },+ };+}++/** Module-level singleton — the deep-link listener arms it, EditorArea reads it. */+export const pendingReceiveNavStore: PendingReceiveNavStore = createPendingReceiveNavStore();++/**+ * The pending share-receive nav the editor should render as an honest miss+ * panel instead of create-mode, or null when the active target isn't a+ * share-receive miss. Pure: a target qualifies only when the resolver marked+ * it `missing` AND its path matches the armed pending nav. A missing target+ * with no armed nav — an ordinary wiki-link create-on-navigate — returns null,+ * so create-mode stays reachable for those (the fork-trap fix is scoped to+ * share-receive navigation).+ */+export function matchesShareReceiveMiss(+ activeTarget: ResolvedNavigationTarget | null,+ armed: PendingReceiveNav | null,+): PendingReceiveNav | null {+ if (activeTarget === null || activeTarget.kind !== 'missing') return null;+ // `armed.path` keeps the share target's extension; `activeTarget.target` is the+ // resolver's stripped form — normalize before comparing.+ if (armed === null || normalizeTargetPath(armed.path).normalizedTarget !== activeTarget.target)+ return null;+ return armed;+}diff --git a/packages/app/src/lib/share/run-share-action.ts b/packages/app/src/lib/share/run-share-action.tsindex 123446a27..076821118 100644--- a/packages/app/src/lib/share/run-share-action.ts+++ b/packages/app/src/lib/share/run-share-action.ts@@ -2,6 +2,7 @@ import type {ShareConstructUrlErrorCode,ShareConstructUrlRequest,ShareConstructUrlResponse,+ ShareFreshness,} from '@inkeep/open-knowledge-core';import { ShareConstructUrlResponseSchema } from '@inkeep/open-knowledge-core';import { docNameToMarkdownPath } from '@/lib/doc-paths';@@ -56,8 +57,8 @@ export type RunShareActionInput = {export type RunShareActionResult =| { kind: 'opened-wizard' }- | { kind: 'copied'; shareUrl: string; branch: string }- | { kind: 'clipboard-failed'; shareUrl: string }+ | { kind: 'copied'; shareUrl: string; branch: string; freshness?: ShareFreshness }+ | { kind: 'clipboard-failed'; shareUrl: string; freshness?: ShareFreshness }| { kind: 'business-error'; error: ShareConstructUrlErrorCode; branch?: string }| { kind: 'transport-error' };@@ -141,11 +142,20 @@ export async function runShareAction(// assuming the share flow itself failed.deps.toastError(CLIPBOARD_ERROR_TOAST);deps.logEvent('[share] action=link-construct result=clipboard-failed');- return { kind: 'clipboard-failed', shareUrl: response.shareUrl };+ return {+ kind: 'clipboard-failed',+ shareUrl: response.shareUrl,+ freshness: response.freshness,+ };}deps.toastSuccess(input.kind === 'folder' ? 'Folder share link copied.' : 'Link copied.');deps.logEvent('[share] action=link-construct');- return { kind: 'copied', shareUrl: response.shareUrl, branch: response.branch };+ return {+ kind: 'copied',+ shareUrl: response.shareUrl,+ branch: response.branch,+ freshness: response.freshness,+ };}// Server-side `no-remote` is the wizard's domain too — the client-sidediff --git a/packages/app/src/lib/trigger-sync.ts b/packages/app/src/lib/trigger-sync.tsnew file mode 100644index 000000000..2f5571378--- /dev/null+++ b/packages/app/src/lib/trigger-sync.ts@@ -0,0 +1,26 @@+/**+ * Trigger a sync-engine operation. POSTs to `/api/sync/trigger`; the push/pull+ * runs server-side and reports completion over the CC1 `sync-status` channel,+ * so callers watch the sync-status hook for the result rather than awaiting a+ * meaningful body here.+ *+ * Rejects when the trigger itself did not land — a network failure (fetch+ * rejects) or a non-2xx response. A caller with UI state gated on the trigger+ * (the share popover's "Sync now" in-flight row) must `.catch` this to recover;+ * otherwise it would spin forever, since no CC1 status update follows a trigger+ * that never reached the engine. Fire-and-forget callers that only watch the+ * status channel `.catch(() => {})` to keep the rejection from going unhandled.+ *+ * Shared by the sync status badge and the share popover's "Sync now" CTA so+ * both hit the same endpoint the same way.+ */+export async function triggerSync(op: 'sync' | 'push' | 'pull'): Promise<void> {+ const res = await fetch('/api/sync/trigger', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ op }),+ });+ if (!res.ok) {+ throw new Error(`sync trigger failed: ${res.status}`);+ }+}diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 83a7958a1..bb004c822 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -106,6 +106,7 @@"2BBAbc": ["List"],"2FYpfJ": ["More"],"2GT3Hf": ["Global"],+ "2IYGkU": ["This doc has unpushed changes. Recipients will see the last pushed version."],"2QM24L": ["All tags"],"2RBzMG": ["Network error — check your connection and try again"],"2XQ8Ww": ["Open preview when agent edits"],@@ -131,6 +132,7 @@"36aWJD": ["Join us on Discord"],"379t2h": ["Unified diff"],"38foVZ": ["Loading diff"],+ "3BnyYc": ["This doc isn't on GitHub yet. The link won't work until it's pushed."],"3DTatP": ["Copy a prompt for your agent, start a blank file, or scaffold from a template."],"3Fcb0I": ["Open graph"],"3HNlwb": ["Hello, world!"],@@ -386,6 +388,7 @@"99eR72": ["Visual editor table selection"],"9Bd18D": ["Failed to load hub pages"],"9NJWgv": ["Backlinks"],+ "9OIqw4": ["You don't have write access to this repo."],"9PQysm": ["Hide advanced"],"9R7pRC": ["No tags match \"", ["trimmed"], "\". Continue typing to create one."],"9UQ730": ["Clone"],@@ -428,6 +431,7 @@"AB4qw9": ["New terminal"],"AE7BY3": ["The terminal session ended."],"AIn2Yv": [["displayName"], " CLI, ", ["hint"]],+ "AItsE5": ["Open it there"],"ALhMYW": ["Terminal"],"AQ-Lfg": ["Couldn't load templates"],"AQGtjK": [@@ -570,6 +574,7 @@"EDl9kS": ["Subscribe"],"EDm3wJ": ["Loading diff renderer"],"EEYbdt": ["Publish"],+ "EHu0x2": ["Syncing"],"EJuO7B": ["Connect a GitHub account to browse and sync your repositories."],"EL_YRd": ["Mirror of <0>api-spec</0>"],"EOjU5V": ["Inline Math Properties"],@@ -673,6 +678,7 @@"."],"GK-IRZ": ["Undo buttons are disabled — per-session state has been garbage-collected."],+ "GLxIKR": ["How to push manually"],"GN6L5F": ["Filename"],"GQDSBN": ["Layout options"],"GUYwCr": ["Dismiss notice"],@@ -688,6 +694,7 @@"GhjUB_": ["Reconnected"],"Gp_twO": ["Local path"],"GsBUCk": ["Loading settings"],+ "Gt4gOO": ["This folder has unpushed changes. Recipients will see the last pushed version."],"GubkSu": ["Use a starter pack"],"GuqOb1": ["Failed to load headings"],"Gx0VS1": ["e.g. drafts/ or *.draft.md"],@@ -706,6 +713,13 @@"Hl89Qd": ["Loading templates"],"HlmZBk": ["Documents response did not match expected shape."],"Hnl9nT": ["Set where pasted and dropped files are stored for this project."],+ "HoWElC": [+ "This ",+ ["targetNoun"],+ " has been moved, renamed, or deleted in your local copy of branch <0>",+ ["branch"],+ "</0>. Please commit your changes or enable auto-sync."+ ],"Hp1l6f": ["Current"],"HpK_8d": ["Reload"],"HptUxX": ["Number"],@@ -769,6 +783,7 @@"K-h9cT": ["Couldn't save the resolution for ", ["filePath"], "."],"K0N7zS": ["Config sharing status read failed"],"K1ckLX": ["Failed to create folder"],+ "K6MQQk": ["Sync is failing. See the sync status for details."],"K6jjWB": [["packName"], " was already set up. Nothing to do."],"K6jxcj": ["Add a key"],"K8-WWn": ["Move between table cells"],@@ -974,6 +989,7 @@"Oxyd5f": ["Pick a name"],"OyIC0Q": ["Project name"],"P-ye9o": ["Could not open folder picker"],+ "P0HC30": ["This ", ["targetNoun"], " moved to <0>", ["0"], "</0>. Open it there?"],"P3NS4G": ["Pattern syntax error (line ", ["lineNumber"], "): ", ["message"]],"P3hnm0": ["File too large to open"],"P47EWZ": ["Could not update sidebar settings"],@@ -1004,6 +1020,7 @@"PqYWiC": ["Couldn't restart the server automatically. Try running `ok stop all` in a terminal, then reopen this project — or restart your computer if it persists."],+ "PrJYSN": ["This folder isn't on GitHub yet. The link won't work until it's pushed."],"PrhzDE": ["Pan up"],"Pyp1NA": ["Restore to this point?"],"Q5fqMz": ["Connection error — try again"],@@ -1143,6 +1160,13 @@"Ua78MH": ["no response"],"UaDyeb": ["Hide selection preview"],"UaRsDu": ["Show worktrees"],+ "Uay5NL": [+ "This ",+ ["targetNoun"],+ " was added to branch <0>",+ ["shareBranch"],+ "</0> recently. Switch and update to open it."+ ],"Uci-Ph": ["Ordered List"],"Ud0Pj9": ["<0>Mirror source removed.</0> The doc <1>",@@ -1155,6 +1179,11 @@"UhpfxY": ["Pan left"],"UkQGhd": ["Hide replace"],"Up2_7p": ["Copy full path"],+ "UuYo7g": [+ "This ",+ ["targetNoun"],+ " has been moved, renamed, or deleted in your local copy. Please commit your changes or enable auto-sync."+ ],"Uuj_R4": ["New from template"],"Uw6ERJ": ["Couldn't copy: ", ["detail"]],"UyROxs": [["mins", "plural", { "one": ["#", " min ago"], "other": ["#", " min ago"] }]],@@ -1238,6 +1267,7 @@"XYlJJT": ["Setting up"],"XcGbim": ["Show hidden files"],"Xet9MX": ["Failed to load backlinks"],+ "Xewl6B": ["Your local copy is behind. Pull the latest changes, then open the link again."],"XfzqjK": ["template \"", ["name"], "\""],"Xl-UUg": ["guides/install or https://example.com"],"XmJfZT": ["name"],@@ -1429,6 +1459,7 @@"c5rF4v": ["What is this knowledge base for?"],"c863eW": ["Could not switch to ", ["shareBranch"], ". Try switching manually."],"c8iK2Y": ["No templates found."],+ "c8jBgX": ["Checking for updates on GitHub"],"cEoyWz": ["Add item to ", ["keyName"]],"cF9DyA": ["Reconnecting after server restart"],"cIptmH": ["In the Claude Desktop App"],@@ -1457,6 +1488,11 @@"csDS2L": ["Available"],"ct2kv5": ["No headings in ", ["pageTarget"]],"cuA8QW": ["Organize specs"],+ "d1JjXo": [+ "Your local copy of branch <0>",+ ["branch"],+ "</0> is behind. Pull the latest changes, then open the link again."+ ],"d2uTPx": ["Server error (HTTP ", ["status"], ")"],"d5rK4X": [["chars", "plural", { "one": ["char"], "other": ["chars"] }]],"dD7NPy": ["Outline"],@@ -1551,6 +1587,7 @@"fqSfXY": ["Replace"],"fuJZKk": ["Search branches"],"fwhX-N": ["Indent or outdent source"],+ "fxbCNQ": ["Synced. The link is up to date."],"g3UF2V": ["Accept"],"g4XBm0": ["Small section heading."],"g58Kwy": [@@ -1588,6 +1625,7 @@"goO4Ll": ["Editor status bar"],"gp3I7-": ["Before syncing, set your identity for git commits:"],"gtEbeW": ["Highlight"],+ "gwykHF": ["This doc hasn't synced to GitHub yet. The link will work after the next sync."],"h06R3C": ["No pages are missing outgoing graph links."],"h6EvY-": ["This will replace the current document content with the version from <0>",@@ -1609,6 +1647,7 @@"hGmuTc": ["Docs tagged #", ["tagDocsName"]],"hHMv6l": ["Delete block"],"hIQkLb": ["New chat"],+ "hItdtk": ["Browse folder"],"hLy8b1": ["Updated to Version ", ["version"]],"hQXiDc": ["Search branches..."],"hSBIG-": ["A title, description, tags — anything that describes this folder."],@@ -1634,6 +1673,13 @@"i3f2kh": ["No matching commands."],"i92eAT": ["We'll create a repository and start syncing — no terminal needed."],"i9OyGp": ["Undo or redo"],+ "i9TPUi": [+ "This ",+ ["targetNoun"],+ " isn't on branch <0>",+ ["branch"],+ "</0>. It may not have been pushed yet."+ ],"i9toLO": ["Agent configuration file"],"iAoh55": ["Update \"", ["0"], "\"?"],"iDZtvM": ["Failed to load templates: ", ["message"]],@@ -1709,6 +1755,13 @@],"kCqCyf": ["Open CodeMirror's lint diagnostics panel."],"kFLlsI": ["Insert a footnote reference + matching definition stub."],+ "kLv8d3": [+ "Your copy of branch <0>",+ ["shareBranch"],+ "</0> has changes that aren't on GitHub. The ",+ ["targetNoun"],+ " will appear once the branch syncs."+ ],"kNqMMd": ["Folder"],"kPtvEH": ["The pack skill <0>", ["0"], "</0> will be (re)installed."],"kUn-CN": ["Sync off"],@@ -1725,6 +1778,7 @@"kmKqZg": ["Clusters"],"knjOzA": ["Tag value"],"kolRU1": ["Do you want to permanently delete instead?"],+ "kpqWwG": ["This ", ["targetNoun"], " was removed from branch <0>", ["branch"], "</0>."],"ku0yLQ": ["Pages are embedded the first time a search needs them."],"ky9Tuc": ["Edit ", ["0"], " source"],"l17ab4": ["Could not write project files. Try a different location."],@@ -1847,6 +1901,7 @@". Try <0>ok status</0> or check <1>.ok/local/last-spawn-error.log</1>."],"npcziF": ["Install on"],+ "nqV0Kk": ["This folder hasn't synced to GitHub yet. The link will work after the next sync."],"nrGWJ7": ["Git identity isn't set — commits use a default author. Set yours so teammates see your name."],@@ -2067,6 +2122,7 @@"u3wRF-": ["Published"],"u6Hp4N": ["Markdown"],"u7H-Wn": ["Show panel (", ["panelShortcutLabel"], ")"],+ "uA_jXp": ["Switch and update branch"],"uCaIdy": ["GitHub sign-in is missing or expired. Reconnect to resume syncing."],"uDlyqd": ["Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex f061f92ef..4467bed6a 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -1013,6 +1013,10 @@ msgstr "Broken link"msgid "Browse"msgstr "Browse"+#: src/components/share-receive-miss-content.tsx+msgid "Browse folder"+msgstr "Browse folder"+#: src/components/CloneDialog.tsxmsgid "Browse your repos:"msgstr "Browse your repos:"@@ -1105,6 +1109,11 @@ msgstr "Checkbox"msgid "Checking for installed agents"msgstr "Checking for installed agents"+#: src/components/share-receive-miss-content.tsx+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Checking for updates on GitHub"+msgstr "Checking for updates on GitHub"+#: src/components/ShareReceiveDialog.tsxmsgid "Checking GitHub connection..."msgstr "Checking GitHub connection..."@@ -2316,6 +2325,7 @@ msgstr "Docs"msgid "Docs tagged #{tagDocsName}"msgstr "Docs tagged #{tagDocsName}"+#: src/components/share-receive-miss-content.tsx#: src/components/ShareBranchSwitchDialog.tsx#: src/components/ShareReceiveDialog.tsxmsgid "document"@@ -2556,6 +2566,8 @@ msgstr "Empty starting content"#: src/components/AutoSyncOnboardingDialog.tsx#: src/components/EnableSyncConfirmDialog.tsx+#: src/components/share-receive-miss-content.tsx+#: src/components/ShareFreshnessWarning.tsxmsgid "Enable auto-sync"msgstr "Enable auto-sync"@@ -3023,6 +3035,7 @@ msgstr "Fold or unfold source"msgid "Fold, unfold, fold all, or unfold all source ranges."msgstr "Fold, unfold, fold all, or unfold all source ranges."+#: src/components/share-receive-miss-content.tsx#: src/components/ShareBranchSwitchDialog.tsx#: src/components/ShareReceiveDialog.tsx#: src/components/TemplateProperties.tsx@@ -3323,6 +3336,10 @@ msgstr "Hotkeys"msgid "How does sharing work?"msgstr "How does sharing work?"+#: src/components/ShareFreshnessWarning.tsx+msgid "How to push manually"+msgstr "How to push manually"+#: src/editor/slash-command/embed-starter-items.tsxmsgid "HTML"msgstr "HTML"@@ -4637,6 +4654,11 @@ msgstr "Open in {shareBranch}"msgid "Open in current branch"msgstr "Open in current branch"+#: src/components/share-receive-miss-content.tsx+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Open it there"+msgstr "Open it there"+#. placeholder {0}: state.importable#: src/components/SkillsSidebarSection.tsxmsgid "Open Knowledge can manage {0} editor skill(s) for this project. Import moves them into .ok/skills and replaces the .claude, .codex, etc. copies with symlinks — one place to edit, in sync everywhere. If those folders are committed to git, review the change first; symlinks can behave differently on some editors and on Windows."@@ -6318,6 +6340,10 @@ msgstr "Suggestion menu open"msgid "Summarize everything I changed this week"msgstr "Summarize everything I changed this week"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Switch and update branch"+msgstr "Switch and update branch"+#: src/components/CommandPalette.tsx#: src/components/ProjectSwitcher.tsx#: src/lib/keyboard-shortcuts.ts@@ -6362,10 +6388,15 @@ msgstr "Sync disabled — you don't have permission to push"msgid "Sync failed — check the server logs for details."msgstr "Sync failed — check the server logs for details."+#: src/components/ShareFreshnessWarning.tsx+msgid "Sync is failing. See the sync status for details."+msgstr "Sync is failing. See the sync status for details."+#: src/components/SyncStatusBadge.tsxmsgid "Sync is off — your edits will not sync to the remote repository."msgstr "Sync is off — your edits will not sync to the remote repository."+#: src/components/ShareFreshnessWarning.tsx#: src/components/SyncStatusBadge.tsxmsgid "Sync now"msgstr "Sync now"@@ -6412,6 +6443,14 @@ msgstr "Sync status: {syncStateLabel} — git identity unset"msgid "Synced"msgstr "Synced"+#: src/components/ShareFreshnessWarning.tsx+msgid "Synced. The link is up to date."+msgstr "Synced. The link is up to date."++#: src/components/ShareFreshnessWarning.tsx+msgid "Syncing"+msgstr "Syncing"+#: src/components/TrashFailureModal.tsxmsgid "System error"msgstr "System error"@@ -6649,10 +6688,37 @@ msgstr "Theme"msgid "There's no project folder for this window, so a terminal can't start here."msgstr "There's no project folder for this window, so a terminal can't start here."+#: src/components/share-receive-miss-content.tsx+msgid "This {targetNoun} has been moved, renamed, or deleted in your local copy of branch <0>{branch}</0>. Please commit your changes or enable auto-sync."+msgstr "This {targetNoun} has been moved, renamed, or deleted in your local copy of branch <0>{branch}</0>. Please commit your changes or enable auto-sync."++#: src/components/share-receive-miss-content.tsx+msgid "This {targetNoun} has been moved, renamed, or deleted in your local copy. Please commit your changes or enable auto-sync."+msgstr "This {targetNoun} has been moved, renamed, or deleted in your local copy. Please commit your changes or enable auto-sync."++#: src/components/share-receive-miss-content.tsx+msgid "This {targetNoun} isn't on branch <0>{branch}</0>. It may not have been pushed yet."+msgstr "This {targetNoun} isn't on branch <0>{branch}</0>. It may not have been pushed yet."++#. placeholder {0}: branchSwitchState.resolution.renamedTo+#. placeholder {0}: resolution.renamedTo+#: src/components/share-receive-miss-content.tsx+#: src/components/ShareBranchSwitchDialog.tsx+msgid "This {targetNoun} moved to <0>{0}</0>. Open it there?"+msgstr "This {targetNoun} moved to <0>{0}</0>. Open it there?"+#: src/components/ShareBranchSwitchDialog.tsxmsgid "This {targetNoun} only exists on branch <0>{shareBranch}</0>. You have uncommitted changes that prevent switching. Commit or stash your changes, then open the share link again."msgstr "This {targetNoun} only exists on branch <0>{shareBranch}</0>. You have uncommitted changes that prevent switching. Commit or stash your changes, then open the share link again."+#: src/components/ShareBranchSwitchDialog.tsx+msgid "This {targetNoun} was added to branch <0>{shareBranch}</0> recently. Switch and update to open it."+msgstr "This {targetNoun} was added to branch <0>{shareBranch}</0> recently. Switch and update to open it."++#: src/components/share-receive-miss-content.tsx+msgid "This {targetNoun} was removed from branch <0>{branch}</0>."+msgstr "This {targetNoun} was removed from branch <0>{branch}</0>."+#: src/components/ShareBranchSwitchDialog.tsxmsgid "This {targetNoun} was shared from branch <0>{shareBranch}</0>. It doesn't exist on your current branch (<1>{currentLabel}</1>)."msgstr "This {targetNoun} was shared from branch <0>{shareBranch}</0>. It doesn't exist on your current branch (<1>{currentLabel}</1>)."@@ -6665,6 +6731,18 @@ msgstr "This {targetNoun} was shared from branch <0>{shareBranch}</0>. You're cumsgid "This branch is checked out in:"msgstr "This branch is checked out in:"+#: src/components/ShareFreshnessWarning.tsx+msgid "This doc has unpushed changes. Recipients will see the last pushed version."+msgstr "This doc has unpushed changes. Recipients will see the last pushed version."++#: src/components/ShareFreshnessWarning.tsx+msgid "This doc hasn't synced to GitHub yet. The link will work after the next sync."+msgstr "This doc hasn't synced to GitHub yet. The link will work after the next sync."++#: src/components/ShareFreshnessWarning.tsx+msgid "This doc isn't on GitHub yet. The link won't work until it's pushed."+msgstr "This doc isn't on GitHub yet. The link won't work until it's pushed."+#: src/components/GraphPanel.tsxmsgid "This document is already active in the editor. Use Open to collapse the graph."msgstr "This document is already active in the editor. Use Open to collapse the graph."@@ -6685,10 +6763,22 @@ msgstr "This file is binary and can't be shown as text."msgid "This file is too large to open in the built-in text editor (1 MB limit). Use Open file below to open it in another app."msgstr "This file is too large to open in the built-in text editor (1 MB limit). Use Open file below to open it in another app."+#: src/components/ShareFreshnessWarning.tsx+msgid "This folder has unpushed changes. Recipients will see the last pushed version."+msgstr "This folder has unpushed changes. Recipients will see the last pushed version."++#: src/components/ShareFreshnessWarning.tsx+msgid "This folder hasn't synced to GitHub yet. The link will work after the next sync."+msgstr "This folder hasn't synced to GitHub yet. The link will work after the next sync."+#: src/components/FolderOverview.tsxmsgid "This folder is empty."msgstr "This folder is empty."+#: src/components/ShareFreshnessWarning.tsx+msgid "This folder isn't on GitHub yet. The link won't work until it's pushed."+msgstr "This folder isn't on GitHub yet. The link won't work until it's pushed."+#: src/components/DeleteConfirmationDialog.tsxmsgid "this item"msgstr "this item"@@ -7398,6 +7488,10 @@ msgstr "You don't have permission to push to this repo"msgid "You don't have permission to push to this repo."msgstr "You don't have permission to push to this repo."+#: src/components/ShareFreshnessWarning.tsx+msgid "You don't have write access to this repo."+msgstr "You don't have write access to this repo."+#: src/components/DiffViewBoundary.tsxmsgid "You modified <0>{filePath}</0> locally, but it was deleted upstream."msgstr "You modified <0>{filePath}</0> locally, but it was deleted upstream."@@ -7430,6 +7524,10 @@ msgstr "You're all set up!"msgid "You're subscribed!"msgstr "You're subscribed!"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Your copy of branch <0>{shareBranch}</0> has changes that aren't on GitHub. The {targetNoun} will appear once the branch syncs."+msgstr "Your copy of branch <0>{shareBranch}</0> has changes that aren't on GitHub. The {targetNoun} will appear once the branch syncs."+#: src/components/settings/SettingsDialogBody.tsx#: src/components/SyncStatusBadge.tsxmsgid "Your GitHub session expired — sign in again to verify push access."@@ -7443,6 +7541,14 @@ msgstr "Your GitHub token is missing required scopes. Try signing in again."msgid "Your knowledge base is now on GitHub at <0>{ownerLogin}/{repoName}</0>."msgstr "Your knowledge base is now on GitHub at <0>{ownerLogin}/{repoName}</0>."+#: src/components/share-receive-miss-content.tsx+msgid "Your local copy is behind. Pull the latest changes, then open the link again."+msgstr "Your local copy is behind. Pull the latest changes, then open the link again."++#: src/components/share-receive-miss-content.tsx+msgid "Your local copy of branch <0>{branch}</0> is behind. Pull the latest changes, then open the link again."+msgstr "Your local copy of branch <0>{branch}</0> is behind. Pull the latest changes, then open the link again."+#: src/components/settings/EmbeddingsKeySection.tsxmsgid "Your OpenAI API key, used only to create embeddings of your content for semantic search. Stored once for this machine in <0>~/.ok/secrets.yml</0> (readable only by your user account) and shared across all projects. Turn the feature on per project in This project → Search."msgstr "Your OpenAI API key, used only to create embeddings of your content for semantic search. Stored once for this machine in <0>~/.ok/secrets.yml</0> (readable only by your user account) and shared across all projects. Turn the feature on per project in This project → Search."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 4dc6d109f..dca3ccdea 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -106,6 +106,7 @@"2BBAbc": ["Ĺĩśţ"],"2FYpfJ": ["Ḿōŕē"],"2GT3Hf": ["Ĝĺōƀàĺ"],+ "2IYGkU": ["Ţĥĩś ďōć ĥàś ũńƥũśĥēď ćĥàńĝēś. Ŕēćĩƥĩēńţś ŵĩĺĺ śēē ţĥē ĺàśţ ƥũśĥēď vēŕśĩōń."],"2QM24L": ["Àĺĺ ţàĝś"],"2RBzMG": ["Ńēţŵōŕķ ēŕŕōŕ — ćĥēćķ ŷōũŕ ćōńńēćţĩōń àńď ţŕŷ àĝàĩń"],"2XQ8Ww": ["Ōƥēń ƥŕēvĩēŵ ŵĥēń àĝēńţ ēďĩţś"],@@ -131,6 +132,7 @@"36aWJD": ["ĵōĩń ũś ōń Ďĩśćōŕď"],"379t2h": ["Ũńĩƒĩēď ďĩƒƒ"],"38foVZ": ["Ĺōàďĩńĝ ďĩƒƒ"],+ "3BnyYc": ["Ţĥĩś ďōć ĩśń'ţ ōń ĜĩţĤũƀ ŷēţ. Ţĥē ĺĩńķ ŵōń'ţ ŵōŕķ ũńţĩĺ ĩţ'ś ƥũśĥēď."],"3DTatP": ["Ćōƥŷ à ƥŕōḿƥţ ƒōŕ ŷōũŕ àĝēńţ, śţàŕţ à ƀĺàńķ ƒĩĺē, ōŕ śćàƒƒōĺď ƒŕōḿ à ţēḿƥĺàţē."],"3Fcb0I": ["Ōƥēń ĝŕàƥĥ"],"3HNlwb": ["Ĥēĺĺō, ŵōŕĺď!"],@@ -386,6 +388,7 @@"99eR72": ["Vĩśũàĺ ēďĩţōŕ ţàƀĺē śēĺēćţĩōń"],"9Bd18D": ["Ƒàĩĺēď ţō ĺōàď ĥũƀ ƥàĝēś"],"9NJWgv": ["ßàćķĺĩńķś"],+ "9OIqw4": ["Ŷōũ ďōń'ţ ĥàvē ŵŕĩţē àććēśś ţō ţĥĩś ŕēƥō."],"9PQysm": ["Ĥĩďē àďvàńćēď"],"9R7pRC": ["Ńō ţàĝś ḿàţćĥ \"", ["trimmed"], "\". Ćōńţĩńũē ţŷƥĩńĝ ţō ćŕēàţē ōńē."],"9UQ730": ["Ćĺōńē"],@@ -428,6 +431,7 @@"AB4qw9": ["Ńēŵ ţēŕḿĩńàĺ"],"AE7BY3": ["Ţĥē ţēŕḿĩńàĺ śēśśĩōń ēńďēď."],"AIn2Yv": [["displayName"], " ĆĹĨ, ", ["hint"]],+ "AItsE5": ["Ōƥēń ĩţ ţĥēŕē"],"ALhMYW": ["Ţēŕḿĩńàĺ"],"AQ-Lfg": ["Ćōũĺďń'ţ ĺōàď ţēḿƥĺàţēś"],"AQGtjK": [@@ -570,6 +574,7 @@"EDl9kS": ["Śũƀśćŕĩƀē"],"EDm3wJ": ["Ĺōàďĩńĝ ďĩƒƒ ŕēńďēŕēŕ"],"EEYbdt": ["Ƥũƀĺĩśĥ"],+ "EHu0x2": ["Śŷńćĩńĝ"],"EJuO7B": ["Ćōńńēćţ à ĜĩţĤũƀ àććōũńţ ţō ƀŕōŵśē àńď śŷńć ŷōũŕ ŕēƥōśĩţōŕĩēś."],"EL_YRd": ["Ḿĩŕŕōŕ ōƒ <0>àƥĩ-śƥēć</0>"],"EOjU5V": ["Ĩńĺĩńē Ḿàţĥ Ƥŕōƥēŕţĩēś"],@@ -673,6 +678,7 @@"."],"GK-IRZ": ["Ũńďō ƀũţţōńś àŕē ďĩśàƀĺēď — ƥēŕ-śēśśĩōń śţàţē ĥàś ƀēēń ĝàŕƀàĝē-ćōĺĺēćţēď."],+ "GLxIKR": ["Ĥōŵ ţō ƥũśĥ ḿàńũàĺĺŷ"],"GN6L5F": ["Ƒĩĺēńàḿē"],"GQDSBN": ["Ĺàŷōũţ ōƥţĩōńś"],"GUYwCr": ["Ďĩśḿĩśś ńōţĩćē"],@@ -688,6 +694,7 @@"GhjUB_": ["Ŕēćōńńēćţēď"],"Gp_twO": ["Ĺōćàĺ ƥàţĥ"],"GsBUCk": ["Ĺōàďĩńĝ śēţţĩńĝś"],+ "Gt4gOO": ["Ţĥĩś ƒōĺďēŕ ĥàś ũńƥũśĥēď ćĥàńĝēś. Ŕēćĩƥĩēńţś ŵĩĺĺ śēē ţĥē ĺàśţ ƥũśĥēď vēŕśĩōń."],"GubkSu": ["Ũśē à śţàŕţēŕ ƥàćķ"],"GuqOb1": ["Ƒàĩĺēď ţō ĺōàď ĥēàďĩńĝś"],"Gx0VS1": ["ē.ĝ. ďŕàƒţś/ ōŕ *.ďŕàƒţ.ḿď"],@@ -706,6 +713,13 @@"Hl89Qd": ["Ĺōàďĩńĝ ţēḿƥĺàţēś"],"HlmZBk": ["Ďōćũḿēńţś ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ēxƥēćţēď śĥàƥē."],"Hnl9nT": ["Śēţ ŵĥēŕē ƥàśţēď àńď ďŕōƥƥēď ƒĩĺēś àŕē śţōŕēď ƒōŕ ţĥĩś ƥŕōĴēćţ."],+ "HoWElC": [+ "Ţĥĩś ",+ ["targetNoun"],+ " ĥàś ƀēēń ḿōvēď, ŕēńàḿēď, ōŕ ďēĺēţēď ĩń ŷōũŕ ĺōćàĺ ćōƥŷ ōƒ ƀŕàńćĥ <0>",+ ["branch"],+ "</0>. Ƥĺēàśē ćōḿḿĩţ ŷōũŕ ćĥàńĝēś ōŕ ēńàƀĺē àũţō-śŷńć."+ ],"Hp1l6f": ["Ćũŕŕēńţ"],"HpK_8d": ["Ŕēĺōàď"],"HptUxX": ["Ńũḿƀēŕ"],@@ -769,6 +783,7 @@"K-h9cT": ["Ćōũĺďń'ţ śàvē ţĥē ŕēśōĺũţĩōń ƒōŕ ", ["filePath"], "."],"K0N7zS": ["Ćōńƒĩĝ śĥàŕĩńĝ śţàţũś ŕēàď ƒàĩĺēď"],"K1ckLX": ["Ƒàĩĺēď ţō ćŕēàţē ƒōĺďēŕ"],+ "K6MQQk": ["Śŷńć ĩś ƒàĩĺĩńĝ. Śēē ţĥē śŷńć śţàţũś ƒōŕ ďēţàĩĺś."],"K6jjWB": [["packName"], " ŵàś àĺŕēàďŷ śēţ ũƥ. Ńōţĥĩńĝ ţō ďō."],"K6jxcj": ["Àďď à ķēŷ"],"K8-WWn": ["Ḿōvē ƀēţŵēēń ţàƀĺē ćēĺĺś"],@@ -974,6 +989,7 @@"Oxyd5f": ["Ƥĩćķ à ńàḿē"],"OyIC0Q": ["ƤŕōĴēćţ ńàḿē"],"P-ye9o": ["Ćōũĺď ńōţ ōƥēń ƒōĺďēŕ ƥĩćķēŕ"],+ "P0HC30": ["Ţĥĩś ", ["targetNoun"], " ḿōvēď ţō <0>", ["0"], "</0>. Ōƥēń ĩţ ţĥēŕē?"],"P3NS4G": ["Ƥàţţēŕń śŷńţàx ēŕŕōŕ (ĺĩńē ", ["lineNumber"], "): ", ["message"]],"P3hnm0": ["Ƒĩĺē ţōō ĺàŕĝē ţō ōƥēń"],"P47EWZ": ["Ćōũĺď ńōţ ũƥďàţē śĩďēƀàŕ śēţţĩńĝś"],@@ -1004,6 +1020,7 @@"PqYWiC": ["Ćōũĺďń'ţ ŕēśţàŕţ ţĥē śēŕvēŕ àũţōḿàţĩćàĺĺŷ. Ţŕŷ ŕũńńĩńĝ `ōķ śţōƥ àĺĺ` ĩń à ţēŕḿĩńàĺ, ţĥēń ŕēōƥēń ţĥĩś ƥŕōĴēćţ — ōŕ ŕēśţàŕţ ŷōũŕ ćōḿƥũţēŕ ĩƒ ĩţ ƥēŕśĩśţś."],+ "PrJYSN": ["Ţĥĩś ƒōĺďēŕ ĩśń'ţ ōń ĜĩţĤũƀ ŷēţ. Ţĥē ĺĩńķ ŵōń'ţ ŵōŕķ ũńţĩĺ ĩţ'ś ƥũśĥēď."],"PrhzDE": ["Ƥàń ũƥ"],"Pyp1NA": ["Ŕēśţōŕē ţō ţĥĩś ƥōĩńţ?"],"Q5fqMz": ["Ćōńńēćţĩōń ēŕŕōŕ — ţŕŷ àĝàĩń"],@@ -1143,6 +1160,13 @@"Ua78MH": ["ńō ŕēśƥōńśē"],"UaDyeb": ["Ĥĩďē śēĺēćţĩōń ƥŕēvĩēŵ"],"UaRsDu": ["Śĥōŵ ŵōŕķţŕēēś"],+ "Uay5NL": [+ "Ţĥĩś ",+ ["targetNoun"],+ " ŵàś àďďēď ţō ƀŕàńćĥ <0>",+ ["shareBranch"],+ "</0> ŕēćēńţĺŷ. Śŵĩţćĥ àńď ũƥďàţē ţō ōƥēń ĩţ."+ ],"Uci-Ph": ["Ōŕďēŕēď Ĺĩśţ"],"Ud0Pj9": ["<0>Ḿĩŕŕōŕ śōũŕćē ŕēḿōvēď.</0> Ţĥē ďōć <1>",@@ -1155,6 +1179,11 @@"UhpfxY": ["Ƥàń ĺēƒţ"],"UkQGhd": ["Ĥĩďē ŕēƥĺàćē"],"Up2_7p": ["Ćōƥŷ ƒũĺĺ ƥàţĥ"],+ "UuYo7g": [+ "Ţĥĩś ",+ ["targetNoun"],+ " ĥàś ƀēēń ḿōvēď, ŕēńàḿēď, ōŕ ďēĺēţēď ĩń ŷōũŕ ĺōćàĺ ćōƥŷ. Ƥĺēàśē ćōḿḿĩţ ŷōũŕ ćĥàńĝēś ōŕ ēńàƀĺē àũţō-śŷńć."+ ],"Uuj_R4": ["Ńēŵ ƒŕōḿ ţēḿƥĺàţē"],"Uw6ERJ": ["Ćōũĺďń'ţ ćōƥŷ: ", ["detail"]],"UyROxs": [["mins", "plural", { "one": ["#", " ḿĩń àĝō"], "other": ["#", " ḿĩń àĝō"] }]],@@ -1238,6 +1267,7 @@"XYlJJT": ["Śēţţĩńĝ ũƥ"],"XcGbim": ["Śĥōŵ ĥĩďďēń ƒĩĺēś"],"Xet9MX": ["Ƒàĩĺēď ţō ĺōàď ƀàćķĺĩńķś"],+ "Xewl6B": ["Ŷōũŕ ĺōćàĺ ćōƥŷ ĩś ƀēĥĩńď. Ƥũĺĺ ţĥē ĺàţēśţ ćĥàńĝēś, ţĥēń ōƥēń ţĥē ĺĩńķ àĝàĩń."],"XfzqjK": ["ţēḿƥĺàţē \"", ["name"], "\""],"Xl-UUg": ["ĝũĩďēś/ĩńśţàĺĺ ōŕ ĥţţƥś://ēxàḿƥĺē.ćōḿ"],"XmJfZT": ["ńàḿē"],@@ -1429,6 +1459,7 @@"c5rF4v": ["Ŵĥàţ ĩś ţĥĩś ķńōŵĺēďĝē ƀàśē ƒōŕ?"],"c863eW": ["Ćōũĺď ńōţ śŵĩţćĥ ţō ", ["shareBranch"], ". Ţŕŷ śŵĩţćĥĩńĝ ḿàńũàĺĺŷ."],"c8iK2Y": ["Ńō ţēḿƥĺàţēś ƒōũńď."],+ "c8jBgX": ["Ćĥēćķĩńĝ ƒōŕ ũƥďàţēś ōń ĜĩţĤũƀ"],"cEoyWz": ["Àďď ĩţēḿ ţō ", ["keyName"]],"cF9DyA": ["Ŕēćōńńēćţĩńĝ àƒţēŕ śēŕvēŕ ŕēśţàŕţ"],"cIptmH": ["Ĩń ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ"],@@ -1457,6 +1488,11 @@"csDS2L": ["Àvàĩĺàƀĺē"],"ct2kv5": ["Ńō ĥēàďĩńĝś ĩń ", ["pageTarget"]],"cuA8QW": ["Ōŕĝàńĩźē śƥēćś"],+ "d1JjXo": [+ "Ŷōũŕ ĺōćàĺ ćōƥŷ ōƒ ƀŕàńćĥ <0>",+ ["branch"],+ "</0> ĩś ƀēĥĩńď. Ƥũĺĺ ţĥē ĺàţēśţ ćĥàńĝēś, ţĥēń ōƥēń ţĥē ĺĩńķ àĝàĩń."+ ],"d2uTPx": ["Śēŕvēŕ ēŕŕōŕ (ĤŢŢƤ ", ["status"], ")"],"d5rK4X": [["chars", "plural", { "one": ["ćĥàŕ"], "other": ["ćĥàŕś"] }]],"dD7NPy": ["Ōũţĺĩńē"],@@ -1551,6 +1587,7 @@"fqSfXY": ["Ŕēƥĺàćē"],"fuJZKk": ["Śēàŕćĥ ƀŕàńćĥēś"],"fwhX-N": ["Ĩńďēńţ ōŕ ōũţďēńţ śōũŕćē"],+ "fxbCNQ": ["Śŷńćēď. Ţĥē ĺĩńķ ĩś ũƥ ţō ďàţē."],"g3UF2V": ["Àććēƥţ"],"g4XBm0": ["Śḿàĺĺ śēćţĩōń ĥēàďĩńĝ."],"g58Kwy": [@@ -1588,6 +1625,7 @@"goO4Ll": ["Ēďĩţōŕ śţàţũś ƀàŕ"],"gp3I7-": ["ßēƒōŕē śŷńćĩńĝ, śēţ ŷōũŕ ĩďēńţĩţŷ ƒōŕ ĝĩţ ćōḿḿĩţś:"],"gtEbeW": ["Ĥĩĝĥĺĩĝĥţ"],+ "gwykHF": ["Ţĥĩś ďōć ĥàśń'ţ śŷńćēď ţō ĜĩţĤũƀ ŷēţ. Ţĥē ĺĩńķ ŵĩĺĺ ŵōŕķ àƒţēŕ ţĥē ńēxţ śŷńć."],"h06R3C": ["Ńō ƥàĝēś àŕē ḿĩśśĩńĝ ōũţĝōĩńĝ ĝŕàƥĥ ĺĩńķś."],"h6EvY-": ["Ţĥĩś ŵĩĺĺ ŕēƥĺàćē ţĥē ćũŕŕēńţ ďōćũḿēńţ ćōńţēńţ ŵĩţĥ ţĥē vēŕśĩōń ƒŕōḿ <0>",@@ -1609,6 +1647,7 @@"hGmuTc": ["Ďōćś ţàĝĝēď #", ["tagDocsName"]],"hHMv6l": ["Ďēĺēţē ƀĺōćķ"],"hIQkLb": ["Ńēŵ ćĥàţ"],+ "hItdtk": ["ßŕōŵśē ƒōĺďēŕ"],"hLy8b1": ["Ũƥďàţēď ţō Vēŕśĩōń ", ["version"]],"hQXiDc": ["Śēàŕćĥ ƀŕàńćĥēś..."],"hSBIG-": ["À ţĩţĺē, ďēśćŕĩƥţĩōń, ţàĝś — àńŷţĥĩńĝ ţĥàţ ďēśćŕĩƀēś ţĥĩś ƒōĺďēŕ."],@@ -1634,6 +1673,13 @@"i3f2kh": ["Ńō ḿàţćĥĩńĝ ćōḿḿàńďś."],"i92eAT": ["Ŵē'ĺĺ ćŕēàţē à ŕēƥōśĩţōŕŷ àńď śţàŕţ śŷńćĩńĝ — ńō ţēŕḿĩńàĺ ńēēďēď."],"i9OyGp": ["Ũńďō ōŕ ŕēďō"],+ "i9TPUi": [+ "Ţĥĩś ",+ ["targetNoun"],+ " ĩśń'ţ ōń ƀŕàńćĥ <0>",+ ["branch"],+ "</0>. Ĩţ ḿàŷ ńōţ ĥàvē ƀēēń ƥũśĥēď ŷēţ."+ ],"i9toLO": ["Àĝēńţ ćōńƒĩĝũŕàţĩōń ƒĩĺē"],"iAoh55": ["Ũƥďàţē \"", ["0"], "\"?"],"iDZtvM": ["Ƒàĩĺēď ţō ĺōàď ţēḿƥĺàţēś: ", ["message"]],@@ -1709,6 +1755,13 @@],"kCqCyf": ["Ōƥēń ĆōďēḾĩŕŕōŕ'ś ĺĩńţ ďĩàĝńōśţĩćś ƥàńēĺ."],"kFLlsI": ["Ĩńśēŕţ à ƒōōţńōţē ŕēƒēŕēńćē + ḿàţćĥĩńĝ ďēƒĩńĩţĩōń śţũƀ."],+ "kLv8d3": [+ "Ŷōũŕ ćōƥŷ ōƒ ƀŕàńćĥ <0>",+ ["shareBranch"],+ "</0> ĥàś ćĥàńĝēś ţĥàţ àŕēń'ţ ōń ĜĩţĤũƀ. Ţĥē ",+ ["targetNoun"],+ " ŵĩĺĺ àƥƥēàŕ ōńćē ţĥē ƀŕàńćĥ śŷńćś."+ ],"kNqMMd": ["Ƒōĺďēŕ"],"kPtvEH": ["Ţĥē ƥàćķ śķĩĺĺ <0>", ["0"], "</0> ŵĩĺĺ ƀē (ŕē)ĩńśţàĺĺēď."],"kUn-CN": ["Śŷńć ōƒƒ"],@@ -1725,6 +1778,7 @@"kmKqZg": ["Ćĺũśţēŕś"],"knjOzA": ["Ţàĝ vàĺũē"],"kolRU1": ["Ďō ŷōũ ŵàńţ ţō ƥēŕḿàńēńţĺŷ ďēĺēţē ĩńśţēàď?"],+ "kpqWwG": ["Ţĥĩś ", ["targetNoun"], " ŵàś ŕēḿōvēď ƒŕōḿ ƀŕàńćĥ <0>", ["branch"], "</0>."],"ku0yLQ": ["Ƥàĝēś àŕē ēḿƀēďďēď ţĥē ƒĩŕśţ ţĩḿē à śēàŕćĥ ńēēďś ţĥēḿ."],"ky9Tuc": ["Ēďĩţ ", ["0"], " śōũŕćē"],"l17ab4": ["Ćōũĺď ńōţ ŵŕĩţē ƥŕōĴēćţ ƒĩĺēś. Ţŕŷ à ďĩƒƒēŕēńţ ĺōćàţĩōń."],@@ -1847,6 +1901,7 @@". Ţŕŷ <0>ōķ śţàţũś</0> ōŕ ćĥēćķ <1>.ōķ/ĺōćàĺ/ĺàśţ-śƥàŵń-ēŕŕōŕ.ĺōĝ</1>."],"npcziF": ["Ĩńśţàĺĺ ōń"],+ "nqV0Kk": ["Ţĥĩś ƒōĺďēŕ ĥàśń'ţ śŷńćēď ţō ĜĩţĤũƀ ŷēţ. Ţĥē ĺĩńķ ŵĩĺĺ ŵōŕķ àƒţēŕ ţĥē ńēxţ śŷńć."],"nrGWJ7": ["Ĝĩţ ĩďēńţĩţŷ ĩśń'ţ śēţ — ćōḿḿĩţś ũśē à ďēƒàũĺţ àũţĥōŕ. Śēţ ŷōũŕś śō ţēàḿḿàţēś śēē ŷōũŕ ńàḿē."],@@ -2067,6 +2122,7 @@"u3wRF-": ["Ƥũƀĺĩśĥēď"],"u6Hp4N": ["Ḿàŕķďōŵń"],"u7H-Wn": ["Śĥōŵ ƥàńēĺ (", ["panelShortcutLabel"], ")"],+ "uA_jXp": ["Śŵĩţćĥ àńď ũƥďàţē ƀŕàńćĥ"],"uCaIdy": ["ĜĩţĤũƀ śĩĝń-ĩń ĩś ḿĩśśĩńĝ ōŕ ēxƥĩŕēď. Ŕēćōńńēćţ ţō ŕēśũḿē śŷńćĩńĝ."],"uDlyqd": ["Ďōćũḿēńţ ţĥē àŕćĥĩţēćţũŕē ōƒ ţĥĩś ŕēƥō: ćŕēàţē àń ōvēŕvĩēŵ ƥàĝē ţĥàţ ĺĩńķś ţō à ƥàĝē ƥēŕ ḿàĴōŕ ḿōďũĺē ďēśćŕĩƀĩńĝ ĩţś ŕēśƥōńśĩƀĩĺĩţĩēś àńď ēńţŕŷ ƥōĩńţś."diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 94d93c2c3..5ba851761 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -1008,6 +1008,10 @@ msgstr ""msgid "Browse"msgstr ""+#: src/components/share-receive-miss-content.tsx+msgid "Browse folder"+msgstr ""+#: src/components/CloneDialog.tsxmsgid "Browse your repos:"msgstr ""@@ -1100,6 +1104,11 @@ msgstr ""msgid "Checking for installed agents"msgstr ""+#: src/components/share-receive-miss-content.tsx+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Checking for updates on GitHub"+msgstr ""+#: src/components/ShareReceiveDialog.tsxmsgid "Checking GitHub connection..."msgstr ""@@ -2311,6 +2320,7 @@ msgstr ""msgid "Docs tagged #{tagDocsName}"msgstr ""+#: src/components/share-receive-miss-content.tsx#: src/components/ShareBranchSwitchDialog.tsx#: src/components/ShareReceiveDialog.tsxmsgid "document"@@ -2551,6 +2561,8 @@ msgstr ""#: src/components/AutoSyncOnboardingDialog.tsx#: src/components/EnableSyncConfirmDialog.tsx+#: src/components/share-receive-miss-content.tsx+#: src/components/ShareFreshnessWarning.tsxmsgid "Enable auto-sync"msgstr ""@@ -3018,6 +3030,7 @@ msgstr ""msgid "Fold, unfold, fold all, or unfold all source ranges."msgstr ""+#: src/components/share-receive-miss-content.tsx#: src/components/ShareBranchSwitchDialog.tsx#: src/components/ShareReceiveDialog.tsx#: src/components/TemplateProperties.tsx@@ -3318,6 +3331,10 @@ msgstr ""msgid "How does sharing work?"msgstr ""+#: src/components/ShareFreshnessWarning.tsx+msgid "How to push manually"+msgstr ""+#: src/editor/slash-command/embed-starter-items.tsxmsgid "HTML"msgstr ""@@ -4632,6 +4649,11 @@ msgstr ""msgid "Open in current branch"msgstr ""+#: src/components/share-receive-miss-content.tsx+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Open it there"+msgstr ""+#. placeholder {0}: state.importable#: src/components/SkillsSidebarSection.tsxmsgid "Open Knowledge can manage {0} editor skill(s) for this project. Import moves them into .ok/skills and replaces the .claude, .codex, etc. copies with symlinks — one place to edit, in sync everywhere. If those folders are committed to git, review the change first; symlinks can behave differently on some editors and on Windows."@@ -6313,6 +6335,10 @@ msgstr ""msgid "Summarize everything I changed this week"msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Switch and update branch"+msgstr ""+#: src/components/CommandPalette.tsx#: src/components/ProjectSwitcher.tsx#: src/lib/keyboard-shortcuts.ts@@ -6357,10 +6383,15 @@ msgstr ""msgid "Sync failed — check the server logs for details."msgstr ""+#: src/components/ShareFreshnessWarning.tsx+msgid "Sync is failing. See the sync status for details."+msgstr ""+#: src/components/SyncStatusBadge.tsxmsgid "Sync is off — your edits will not sync to the remote repository."msgstr ""+#: src/components/ShareFreshnessWarning.tsx#: src/components/SyncStatusBadge.tsxmsgid "Sync now"msgstr ""@@ -6407,6 +6438,14 @@ msgstr ""msgid "Synced"msgstr ""+#: src/components/ShareFreshnessWarning.tsx+msgid "Synced. The link is up to date."+msgstr ""++#: src/components/ShareFreshnessWarning.tsx+msgid "Syncing"+msgstr ""+#: src/components/TrashFailureModal.tsxmsgid "System error"msgstr ""@@ -6644,10 +6683,37 @@ msgstr ""msgid "There's no project folder for this window, so a terminal can't start here."msgstr ""+#: src/components/share-receive-miss-content.tsx+msgid "This {targetNoun} has been moved, renamed, or deleted in your local copy of branch <0>{branch}</0>. Please commit your changes or enable auto-sync."+msgstr ""++#: src/components/share-receive-miss-content.tsx+msgid "This {targetNoun} has been moved, renamed, or deleted in your local copy. Please commit your changes or enable auto-sync."+msgstr ""++#: src/components/share-receive-miss-content.tsx+msgid "This {targetNoun} isn't on branch <0>{branch}</0>. It may not have been pushed yet."+msgstr ""++#. placeholder {0}: branchSwitchState.resolution.renamedTo+#. placeholder {0}: resolution.renamedTo+#: src/components/share-receive-miss-content.tsx+#: src/components/ShareBranchSwitchDialog.tsx+msgid "This {targetNoun} moved to <0>{0}</0>. Open it there?"+msgstr ""+#: src/components/ShareBranchSwitchDialog.tsxmsgid "This {targetNoun} only exists on branch <0>{shareBranch}</0>. You have uncommitted changes that prevent switching. Commit or stash your changes, then open the share link again."msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+msgid "This {targetNoun} was added to branch <0>{shareBranch}</0> recently. Switch and update to open it."+msgstr ""++#: src/components/share-receive-miss-content.tsx+msgid "This {targetNoun} was removed from branch <0>{branch}</0>."+msgstr ""+#: src/components/ShareBranchSwitchDialog.tsxmsgid "This {targetNoun} was shared from branch <0>{shareBranch}</0>. It doesn't exist on your current branch (<1>{currentLabel}</1>)."msgstr ""@@ -6660,6 +6726,18 @@ msgstr ""msgid "This branch is checked out in:"msgstr ""+#: src/components/ShareFreshnessWarning.tsx+msgid "This doc has unpushed changes. Recipients will see the last pushed version."+msgstr ""++#: src/components/ShareFreshnessWarning.tsx+msgid "This doc hasn't synced to GitHub yet. The link will work after the next sync."+msgstr ""++#: src/components/ShareFreshnessWarning.tsx+msgid "This doc isn't on GitHub yet. The link won't work until it's pushed."+msgstr ""+#: src/components/GraphPanel.tsxmsgid "This document is already active in the editor. Use Open to collapse the graph."msgstr ""@@ -6680,10 +6758,22 @@ msgstr ""msgid "This file is too large to open in the built-in text editor (1 MB limit). Use Open file below to open it in another app."msgstr ""+#: src/components/ShareFreshnessWarning.tsx+msgid "This folder has unpushed changes. Recipients will see the last pushed version."+msgstr ""++#: src/components/ShareFreshnessWarning.tsx+msgid "This folder hasn't synced to GitHub yet. The link will work after the next sync."+msgstr ""+#: src/components/FolderOverview.tsxmsgid "This folder is empty."msgstr ""+#: src/components/ShareFreshnessWarning.tsx+msgid "This folder isn't on GitHub yet. The link won't work until it's pushed."+msgstr ""+#: src/components/DeleteConfirmationDialog.tsxmsgid "this item"msgstr ""@@ -7393,6 +7483,10 @@ msgstr ""msgid "You don't have permission to push to this repo."msgstr ""+#: src/components/ShareFreshnessWarning.tsx+msgid "You don't have write access to this repo."+msgstr ""+#: src/components/DiffViewBoundary.tsxmsgid "You modified <0>{filePath}</0> locally, but it was deleted upstream."msgstr ""@@ -7425,6 +7519,10 @@ msgstr ""msgid "You're subscribed!"msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Your copy of branch <0>{shareBranch}</0> has changes that aren't on GitHub. The {targetNoun} will appear once the branch syncs."+msgstr ""+#: src/components/settings/SettingsDialogBody.tsx#: src/components/SyncStatusBadge.tsxmsgid "Your GitHub session expired — sign in again to verify push access."@@ -7438,6 +7536,14 @@ msgstr ""msgid "Your knowledge base is now on GitHub at <0>{ownerLogin}/{repoName}</0>."msgstr ""+#: src/components/share-receive-miss-content.tsx+msgid "Your local copy is behind. Pull the latest changes, then open the link again."+msgstr ""++#: src/components/share-receive-miss-content.tsx+msgid "Your local copy of branch <0>{branch}</0> is behind. Pull the latest changes, then open the link again."+msgstr ""+#: src/components/settings/EmbeddingsKeySection.tsxmsgid "Your OpenAI API key, used only to create embeddings of your content for semantic search. Stored once for this machine in <0>~/.ok/secrets.yml</0> (readable only by your user account) and shared across all projects. Turn the feature on per project in This project → Search."msgstr ""diff --git a/packages/app/tests/integration/attribution-sweep-coverage.test.ts b/packages/app/tests/integration/attribution-sweep-coverage.test.tsindex 0ef27b2be..01b2024c6 100644--- a/packages/app/tests/integration/attribution-sweep-coverage.test.ts+++ b/packages/app/tests/integration/attribution-sweep-coverage.test.ts@@ -261,6 +261,11 @@ const EXEMPT_HANDLERS = new Set([// Identity is still extracted at entry for observability, but the// operation never touches Y.Docs so identity threading is exempt.'handleCheckout',+ // `/api/share/target-status` — receive-side git verdict (targeted fetch ++ // `cat-file -e` / removal-commit lookup / rename detection). Updates only+ // remote-tracking refs, no CRDT mutation, no agent-authored content; same+ // rationale as `handleBranchInfo` / `handleCheckout`.+ 'handleShareTargetStatus',]);function extractHandlerBody(handlerName: string): string | null {diff --git a/packages/app/tests/integration/conflict-gate-coverage.test.ts b/packages/app/tests/integration/conflict-gate-coverage.test.tsindex 3822deb49..f294dda45 100644--- a/packages/app/tests/integration/conflict-gate-coverage.test.ts+++ b/packages/app/tests/integration/conflict-gate-coverage.test.ts@@ -172,6 +172,10 @@ const EXEMPT_HANDLERS = new Set([// is a read endpoint with no lock per the lock-free-reads contract.'handleBranchInfo','handleCheckout',+ // `/api/share/target-status` — receive-side git verdict (fetch + rename+ // detection). Updates only remote-tracking refs, never Y.Doc content, so the+ // per-doc conflict gate does not apply. Same posture as `handleBranchInfo`.+ 'handleShareTargetStatus',// Test-only handlers. Wipe + rebuild semantics; conflict gate is orthogonal// (the wipe IS the resolution path in test scope).'handleTestReset',diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.tsindex 4404c914d..00cfc81a8 100644--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts@@ -413,6 +413,7 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): PreadHeadBranch: async () => ({ currentBranch: null, headSha: null, detached: false }),fetchBranchInfo: async () => null,runCheckout: async () => null,+ fetchTargetStatus: async () => null,awaitBranchSwitched: async () => ({ ok: false, reason: 'timeout' as const }),okInit: async () => ({ok: false as const,diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.tsindex c014b1413..8f9d95287 100644--- a/packages/core/src/bridge/bind-frontmatter-doc.ts+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts@@ -1,3 +1,4 @@+import type * as Y from 'yjs';import type { Err, Ok, Result } from '../config/result.ts';import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.tsindex 005627195..8bfdb40cd 100644--- a/packages/core/src/bridge/bridge-invariant.ts+++ b/packages/core/src/bridge/bridge-invariant.ts@@ -1,3 +1,4 @@+import { fnv1aDigest } from './hash-util.ts';export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 8890f6739..c18c086d5 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,3 +1,4 @@+import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';const LEADING_BOUNDARY_RE = /^(?:\r?\n)+/;diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.tsindex b0a80fbd9..864bc7245 100644--- a/packages/core/src/bridge/merge-three-way.ts+++ b/packages/core/src/bridge/merge-three-way.ts@@ -37,6 +37,7 @@ function mergeThreeWayImpl(baseline: string, userText: string, agentText: stringreturn parts.join('\n');}+export type BridgeMergeContentLossSide = 'user' | 'agent';export type BridgeMergeContentLossWhich = 'substring' | 'order';diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.tsindex e67f33b40..592f0b956 100644--- a/packages/core/src/bridge/normalize.ts+++ b/packages/core/src/bridge/normalize.ts@@ -1,3 +1,4 @@+const COMMONMARK_ESCAPE_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~])/g;const TABLE_ALIGN_ROW_RE = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/;diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.tsindex d84b7072f..3b9376190 100644--- a/packages/core/src/desktop-bridge.ts+++ b/packages/core/src/desktop-bridge.ts@@ -18,7 +18,11 @@ import type {} from './git/worktree-selector-model.ts';import type { TerminalCli } from './handoff/terminal-launch.ts';import type { LocalOpOkInitResponse } from './schemas/api/local-op.ts';-import type { BranchInfoResponse, CheckoutResponse } from './schemas/api/share.ts';+import type {+ BranchInfoResponse,+ CheckoutResponse,+ ShareTargetStatusResponse,+} from './schemas/api/share.ts';import type { RecentProjectEntry } from './sharing/index.ts';/** Render mode picked by the main process when creating a BrowserWindow. */@@ -1113,9 +1117,27 @@ export interface OkDesktopBridge {}): Promise<BranchInfoResponse | null>;/*** Proxy `POST /api/git/checkout` against the project's running server.- * See canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.+ * `fastForward` (on-origin "Switch and update branch") fast-forwards the+ * target branch to origin's tip before checkout; divergence → `ff-diverged`+ * (nothing mutated). See canonical JSDoc in+ * `packages/desktop/src/shared/bridge-contract.ts`.+ */+ runCheckout(request: {+ projectPath: string;+ branch: string;+ fastForward?: boolean;+ }): Promise<CheckoutResponse | null>;+ /**+ * Proxy `POST /api/share/target-status` for the branch-switch dialog's+ * verdict pivot. See canonical JSDoc in+ * `packages/desktop/src/shared/bridge-contract.ts`.*/- runCheckout(request: { projectPath: string; branch: string }): Promise<CheckoutResponse | null>;+ fetchTargetStatus(request: {+ projectPath: string;+ branch: string;+ path: string;+ kind: 'doc' | 'folder';+ }): Promise<ShareTargetStatusResponse | null>;/*** Gate dialog dismissal on the `branch-switched` broadcast landing* in the project window. See canonical JSDoc indiff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 9570ebbef..f68bd2bca 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -712,6 +712,8 @@ export {ShareConstructUrlRequestSchema,type ShareConstructUrlResponse,ShareConstructUrlResponseSchema,+ type ShareFreshness,+ ShareFreshnessSchema,type SharePublishErrorCode,SharePublishErrorCodeSchema,type SharePublishNameCheckResponse,@@ -730,6 +732,12 @@ export {SharePublishResponseSchema,type SharePublishVisibility,SharePublishVisibilitySchema,+ type ShareTargetStatusRequest,+ ShareTargetStatusRequestSchema,+ type ShareTargetStatusResponse,+ ShareTargetStatusResponseSchema,+ type ShareTargetStatusVerdict,+ ShareTargetStatusVerdictSchema,SKILL_INSTALL_WARNING_CODES,SKILL_NAME_REGEX,type SkillDeleteSuccess,diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.tsindex 83d47404a..a363dfd54 100644--- a/packages/core/src/markdown/callout-transformer.ts+++ b/packages/core/src/markdown/callout-transformer.ts@@ -1,3 +1,4 @@+import type { Blockquote, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex 193e286b0..47f0d07e4 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.tsindex ece5c02a1..b6299a948 100644--- a/packages/core/src/markdown/dedent-block-jsx-close.ts+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts@@ -1,3 +1,4 @@+import { findFencedRegions, isInsideFence } from './fence-regions.ts';const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.tsindex 54774764a..acd398aa6 100644--- a/packages/core/src/markdown/details-accordion-promoter.ts+++ b/packages/core/src/markdown/details-accordion-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.tsindex c7518d614..fb5ac8e8a 100644--- a/packages/core/src/markdown/fence-regions.ts+++ b/packages/core/src/markdown/fence-regions.ts@@ -1,3 +1,4 @@+const FENCE_RE = /^(`{3,}|~{3,})/gm;export function findFencedRegions(src: string): Array<[number, number]> {diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.tsindex 00f5771ee..6931623c7 100644--- a/packages/core/src/markdown/fixtures/index.ts+++ b/packages/core/src/markdown/fixtures/index.ts@@ -1,3 +1,4 @@+import { readFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -8,6 +9,7 @@ function fixturePath(...segments: string[]): string {return resolve(FIXTURES_DIR, ...segments);}+interface GfmExample {section: string;markdown: string;@@ -17,6 +19,7 @@ export function loadGfmExamples(): GfmExample[] {return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];}+interface MdxCrashEntry {id: string;input: string;@@ -68,6 +71,7 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {) as LargeEmbedFixture[];}+export function loadPrd6955Before(): string {return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');}@@ -76,6 +80,7 @@ export function loadPrd6955CorruptedTriplicated(): string {return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');}+export interface NgPinnedCase {id: string;name: string;@@ -92,6 +97,7 @@ export function loadNgPinnedCases(): NgPinnedCase[] {) as NgPinnedCase[];}+export function loadLargeRealistic(): string {return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');}diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.tsindex 8b1eb8519..daa3ef82b 100644--- a/packages/core/src/markdown/fixtures/perf/generate.ts+++ b/packages/core/src/markdown/fixtures/perf/generate.ts@@ -1,3 +1,4 @@+import { writeFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -10,6 +11,7 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;const SEED = 0xf1de1117;+function mulberry32(seed: number): () => number {let a = seed >>> 0;return () => {@@ -36,6 +38,7 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {return items[items.length - 1][0];}+const WORDS = ['lorem','ipsum',@@ -153,6 +156,7 @@ function mdxBlock(rand: () => number): string {return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;}+type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';const MIX: readonly [BlockKind, number][] = [@@ -191,6 +195,7 @@ function generateDocument(blockCount: number, seed: number): string {return `${blocks.join('\n\n')}\n`;}+function main(): void {for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {const doc = generateDocument(count, SEED);diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.tsindex 420dc0fe5..32c055c5b 100644--- a/packages/core/src/markdown/guard-flanking-matrix.ts+++ b/packages/core/src/markdown/guard-flanking-matrix.ts@@ -7,6 +7,7 @@ import {import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';+export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;export type FlankClass = 'whitespace' | 'punctuation' | 'other';diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.tsindex 2653473da..283913255 100644--- a/packages/core/src/markdown/handler-shadow-audit.ts+++ b/packages/core/src/markdown/handler-shadow-audit.ts@@ -1,3 +1,4 @@+export interface HandlerShadowWitness {input: string;expect: 'byte' | 'byte-and-reparse-type';diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.tsindex f758cf737..7a22e8016 100644--- a/packages/core/src/markdown/highlight-promoter.ts+++ b/packages/core/src/markdown/highlight-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.tsindex 78fdfeb02..2f082e6d0 100644--- a/packages/core/src/markdown/html-to-mdast.ts+++ b/packages/core/src/markdown/html-to-mdast.ts@@ -1,3 +1,4 @@+import type { Root as HastRoot } from 'hast';import type { Root as MdastRoot } from 'mdast';import rehypeParse from 'rehype-parse';@@ -75,7 +76,8 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRothrow new HtmlPayloadTooLargeError(html.length, maxBytes);}- const processor = unified().use(rehypeParse, { fragment: true });+ const processor = unified()+ .use(rehypeParse, { fragment: true });for (const plugin of cleanupPlugins) {processor.use(plugin);diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.tsindex 706fa9afb..994eb6917 100644--- a/packages/core/src/markdown/image-promoter.ts+++ b/packages/core/src/markdown/image-promoter.ts@@ -1,3 +1,4 @@+import type { Image, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.tsindex 58a810193..064fa0773 100644--- a/packages/core/src/markdown/index.ts+++ b/packages/core/src/markdown/index.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromPmMark,@@ -164,6 +165,7 @@ export class MarkdownManager {}}+const registry = createRegistry();function destructureAttrs(@@ -212,6 +214,7 @@ function destructureAttrs(return result;}+function hasDirtyDescendant(node: PmNode): boolean {let found = false;node.descendants((child) => {@@ -230,6 +233,7 @@ function effectiveDirty(node: PmNode): boolean {return node.attrs.sourceDirty || hasDirtyDescendant(node);}+function isEmptyMdastParagraph(node: MdastNodes): boolean {if (node.type !== 'paragraph') return false;const children = node.children ?? [];@@ -298,6 +302,7 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {return out;}+import {AUDIO_EXTENSIONS,FILE_ATTACHMENT_EXTENSIONS,@@ -547,6 +552,7 @@ function buildMdastToPmHandlers(}));}+if (m.emphasis) {handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({sourceDelimiter: node.data?.sourceDelimiter ?? '*',@@ -626,6 +632,7 @@ function buildMdastToPmHandlers(}));}+if (m.link) {const sourceLiteralMark = m.sourceLiteral;handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {@@ -904,6 +911,7 @@ function buildMdastToPmHandlers(};}+const blockUnknownHandler = (node: {type: string;position?: { start: { offset: number }; end: { offset: number } };@@ -1029,6 +1037,7 @@ function buildMdastToPmHandlers(return handlers as RemarkProseMirrorOptions['handlers'];}+function buildPmToMdastHandlers(schema: Schema): {nodeHandlers: FromProseMirrorOptions<string, string>['nodeHandlers'];markHandlers: FromProseMirrorOptions<string, string>['markHandlers'];diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.tsindex a5b511f25..bd79424c7 100644--- a/packages/core/src/markdown/math-promoter.ts+++ b/packages/core/src/markdown/math-promoter.ts@@ -1,3 +1,4 @@+import type { Code, Root } from 'mdast';import type { Math as MdastMath } from 'mdast-util-math';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.tsindex 679c72ef7..f84967798 100644--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts@@ -1,3 +1,4 @@+import type { Comment, Element, ElementContent, Properties } from 'hast';import type { FootnoteDefinition, FootnoteReference } from 'mdast';import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.tsindex 79072375c..153fdc1d8 100644--- a/packages/core/src/markdown/mdast-to-html.ts+++ b/packages/core/src/markdown/mdast-to-html.ts@@ -1,3 +1,4 @@+import type { Element, Root as HastRoot } from 'hast';import type { Root as MdastRoot } from 'mdast';import { normalizeUri } from 'micromark-util-sanitize-uri';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex 35d74b85e..a58f8c720 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.tsindex 1a897fca8..17ed2b829 100644--- a/packages/core/src/markdown/mermaid-promoter.ts+++ b/packages/core/src/markdown/mermaid-promoter.ts@@ -1,3 +1,4 @@+import type { Code, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.tsindex 9864b3b60..7e4a9a48b 100644--- a/packages/core/src/markdown/parse-with-fallback.ts+++ b/packages/core/src/markdown/parse-with-fallback.ts@@ -168,6 +168,7 @@ export function parseRecursive(}}+interface VFilePlace {offset?: number;start?: { offset?: number };@@ -186,6 +187,7 @@ function extractErrorOffset(err: unknown): number | undefined {return undefined;}+interface Region {start: number;end: number;@@ -209,6 +211,7 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {return null;}+export interface TagEvent {kind: 'open' | 'close' | 'self-close';name: string;@@ -355,6 +358,7 @@ function findFallbackRegion(src: string, errorOffset: number): Region {return { start: blockStart, end: blockEnd };}+interface SourceBlock {src: string;start: number;@@ -452,6 +456,7 @@ function tryPerBlockFallback(};}+function wholeDocRawText(source: string): JSONContent {return {type: 'doc',diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.tsindex e6ab4fd57..43d420187 100644--- a/packages/core/src/markdown/parser-drop-closure.ts+++ b/packages/core/src/markdown/parser-drop-closure.ts@@ -1,3 +1,4 @@+export type DroppedTokenAdjudication =| {kind: 'format-dof-axis';diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.tsindex 5d6db7aa8..5b9550e90 100644--- a/packages/core/src/markdown/pipeline.ts+++ b/packages/core/src/markdown/pipeline.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromProseMirror,diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.tsindex 248685cfe..4ac5731e7 100644--- a/packages/core/src/markdown/position-aware-join.ts+++ b/packages/core/src/markdown/position-aware-join.ts@@ -1,3 +1,4 @@+import type { Join } from 'mdast-util-to-markdown';import type { Position } from 'unist';diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.tsindex 50a193a16..240be90e6 100644--- a/packages/core/src/markdown/position-slice.ts+++ b/packages/core/src/markdown/position-slice.ts@@ -1,3 +1,4 @@+import type { Nodes, Root } from 'mdast';import { visit } from 'unist-util-visit';import type { VFile } from 'vfile';@@ -466,7 +467,8 @@ export function applyPositionSliceToNode(const first = source[startOff];if (first !== '[' && first !== '<' && !node.title) {node.data.sourceStyle = 'gfm-autolink';- } else if (first === '[') {+ }+ else if (first === '[') {const slice = source.slice(startOff, endOff);const closeBracketIdx = slice.lastIndexOf('](');if (closeBracketIdx !== -1) {diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.tsindex db10fa54b..ca225ce9b 100644--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts@@ -1,3 +1,4 @@+import type { Comment, Element, Root, Text } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.tsindex 34068d103..3a2524a9a 100644--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.tsindex 93151d43b..2279a0189 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.tsindex 188f02d83..a0f467c42 100644--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.tsindex 4ba2c3418..4e8542a21 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.tsindex 1a74b1272..a3c96b24a 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.tsindex de35e7b79..e95cf43d6 100644--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts@@ -1,3 +1,4 @@+import type { Comment, Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.tsindex b4be1b2ea..ffdb4d5b5 100644--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.tsindex 3c8d88b7c..e2a96d1a7 100644--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.tsindex cf2c9da8e..0389575ac 100644--- a/packages/core/src/markdown/resolve-image-url.ts+++ b/packages/core/src/markdown/resolve-image-url.ts@@ -1,3 +1,4 @@+import { isRelativeUrl } from './safe-url.ts';function isDevDiagnosticContext(): boolean {diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 4d3250d3a..8be632ba4 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,3 +1,4 @@+export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.tsindex 46cc6a074..542204403 100644--- a/packages/core/src/markdown/serialize-helpers.ts+++ b/packages/core/src/markdown/serialize-helpers.ts@@ -1,3 +1,4 @@+import type { Node as PmNode } from '@tiptap/pm/model';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { PropDef, SerializeContext } from '../registry/types.ts';diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.tsindex be97d4d62..fe73659e6 100644--- a/packages/core/src/markdown/single-dollar-math-promoter.ts+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts@@ -1,3 +1,4 @@+import type { PhrasingContent, Root, Text } from 'mdast';import type { InlineMath } from 'mdast-util-math';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.tsindex 1a2fb5d50..e1161455b 100644--- a/packages/core/src/markdown/to-markdown-handlers.ts+++ b/packages/core/src/markdown/to-markdown-handlers.ts@@ -1,3 +1,4 @@+import type { Nodes, Parents } from 'mdast';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { Handle, Info, State } from 'mdast-util-to-markdown';diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.tsindex cd245c38c..c5bfd2386 100644--- a/packages/core/src/markdown/unknown-mdast-guard.ts+++ b/packages/core/src/markdown/unknown-mdast-guard.ts@@ -1,3 +1,4 @@+import type { Root as MdastRoot } from 'mdast';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.tsindex a100cad76..1b75ba564 100644--- a/packages/core/src/markdown/whitespace-char-ref.ts+++ b/packages/core/src/markdown/whitespace-char-ref.ts@@ -1,3 +1,4 @@+const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([[0x20, ' '],[0x09, '\t'],diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.tsindex 6dad26200..afd9936fe 100644--- a/packages/core/src/markdown/wiki-link-micromark.ts+++ b/packages/core/src/markdown/wiki-link-micromark.ts@@ -17,6 +17,7 @@ declare module 'micromark-util-types' {}}+const CODE_BANG = 33; // !const CODE_LBRACKET = 91; // [const CODE_RBRACKET = 93; // ]@@ -260,6 +261,7 @@ export function wikiLinkSyntax(): Extension {};}+function enterWikiLink(this: CompileContext, token: Token) {this.enter({@@ -385,6 +387,7 @@ export const wikiLinkToMarkdown: {unsafe: [{ character: '[', inConstruct: ['phrasing'] }],};+const MICROMARK_EXT = wikiLinkSyntax();export function remarkWikiLink(this: Processor) {diff --git a/packages/core/src/schemas/api/share.test.ts b/packages/core/src/schemas/api/share.test.tsindex ca3429408..cacab783b 100644--- a/packages/core/src/schemas/api/share.test.ts+++ b/packages/core/src/schemas/api/share.test.ts@@ -1,10 +1,16 @@import { describe, expect, test } from 'bun:test';import {+ BranchInfoResponseSchema,type ClassifiedGitAuthError,classifyGitAuthError,isBranchNotFoundGitError,isLoginFixableGitAuthError,isValidBranchName,+ ShareConstructUrlResponseSchema,+ ShareFreshnessSchema,+ ShareTargetStatusRequestSchema,+ ShareTargetStatusResponseSchema,+ ShareTargetStatusVerdictSchema,} from './share.ts';function withGitStderr(message: string, stderr: string): Error & { git: string } {@@ -237,3 +243,201 @@ describe('isBranchNotFoundGitError', () => {expect(isBranchNotFoundGitError(undefined)).toBe(false);});});++describe('ShareFreshnessSchema (closed v1 enum)', () => {+ test('accepts the three v1 freshness states', () => {+ for (const value of ['current', 'stale', 'absent'] as const) {+ expect(ShareFreshnessSchema.parse(value)).toBe(value);+ }+ });++ test('rejects a value outside the closed enum', () => {+ expect(ShareFreshnessSchema.safeParse('unpushed').success).toBe(false);+ expect(ShareFreshnessSchema.safeParse('').success).toBe(false);+ expect(ShareFreshnessSchema.safeParse(null).success).toBe(false);+ });+});++describe('ShareConstructUrlResponseSchema freshness field', () => {+ const successBase = {+ ok: true,+ shareUrl: 'https://openknowledge.ai/d/abc',+ sharedUrl: 'https://github.com/o/r/blob/main/doc.md',+ branch: 'main',+ };++ test('a success response without freshness still parses (additive optional)', () => {+ const parsed = ShareConstructUrlResponseSchema.parse({ ...successBase });+ expect(parsed.ok).toBe(true);+ if (parsed.ok) expect(parsed.freshness).toBeUndefined();+ });++ test('each valid freshness value round-trips on the success variant', () => {+ for (const value of ['current', 'stale', 'absent'] as const) {+ const parsed = ShareConstructUrlResponseSchema.parse({ ...successBase, freshness: value });+ expect(parsed.ok).toBe(true);+ if (parsed.ok) expect(parsed.freshness).toBe(value);+ }+ });++ test('an unknown freshness value is treated as omitted, not a parse failure', () => {+ // Value-level forward-compat: a newer server may emit a freshness state+ // this client's enum predates; the share must still parse, minus the+ // warning it can't interpret.+ const result = ShareConstructUrlResponseSchema.safeParse({+ ...successBase,+ freshness: 'catching-up',+ });+ expect(result.success).toBe(true);+ if (result.success && result.data.ok) {+ expect(result.data.freshness).toBeUndefined();+ }+ });++ test('a non-string freshness value is tolerated as omitted', () => {+ for (const bad of [null, 42, {}, ['stale']]) {+ const result = ShareConstructUrlResponseSchema.safeParse({ ...successBase, freshness: bad });+ expect(result.success).toBe(true);+ if (result.success && result.data.ok) {+ expect(result.data.freshness).toBeUndefined();+ }+ }+ });++ test('the error variant still gates on the unchanged error-code enum', () => {+ expect(+ ShareConstructUrlResponseSchema.safeParse({ ok: false, error: 'no-remote' }).success,+ ).toBe(true);+ expect(+ ShareConstructUrlResponseSchema.safeParse({ ok: false, error: 'invalid-path' }).success,+ ).toBe(true);+ // A freshness value is not an error code — adding `freshness` never+ // widened the error enum.+ expect(ShareConstructUrlResponseSchema.safeParse({ ok: false, error: 'stale' }).success).toBe(+ false,+ );+ expect(ShareConstructUrlResponseSchema.safeParse({ ok: false, error: 'bogus' }).success).toBe(+ false,+ );+ });+});++describe('ShareTargetStatusVerdictSchema (closed v1 enum)', () => {+ test('accepts the six v1 verdicts', () => {+ for (const v of [+ 'on-origin',+ 'renamed',+ 'deleted',+ 'never-on-branch',+ 'changed-locally',+ 'unknown',+ ] as const) {+ expect(ShareTargetStatusVerdictSchema.parse(v)).toBe(v);+ }+ });++ test('rejects a value outside the closed enum', () => {+ expect(ShareTargetStatusVerdictSchema.safeParse('moved').success).toBe(false);+ expect(ShareTargetStatusVerdictSchema.safeParse('').success).toBe(false);+ });+});++describe('ShareTargetStatusRequestSchema', () => {+ test('accepts a well-formed doc request', () => {+ expect(+ ShareTargetStatusRequestSchema.safeParse({ branch: 'main', path: 'doc.md', kind: 'doc' })+ .success,+ ).toBe(true);+ });++ test('accepts an empty path for a folder (content root)', () => {+ expect(+ ShareTargetStatusRequestSchema.safeParse({ branch: 'main', path: '', kind: 'folder' })+ .success,+ ).toBe(true);+ });++ test('rejects an unsafe branch name (refspec injection)', () => {+ expect(+ ShareTargetStatusRequestSchema.safeParse({+ branch: 'HEAD:refs/heads/evil',+ path: 'doc.md',+ kind: 'doc',+ }).success,+ ).toBe(false);+ });++ test('rejects a missing or invalid kind', () => {+ expect(+ ShareTargetStatusRequestSchema.safeParse({ branch: 'main', path: 'doc.md' }).success,+ ).toBe(false);+ expect(+ ShareTargetStatusRequestSchema.safeParse({ branch: 'main', path: 'doc.md', kind: 'blob' })+ .success,+ ).toBe(false);+ });+});++describe('ShareTargetStatusResponseSchema (value-tolerant verdict union)', () => {+ test('parses each destination-free verdict', () => {+ for (const verdict of [+ 'on-origin',+ 'deleted',+ 'never-on-branch',+ 'changed-locally',+ 'unknown',+ ] as const) {+ expect(ShareTargetStatusResponseSchema.parse({ verdict }).verdict).toBe(verdict);+ }+ });++ test('renamed carries its verified renamedTo destination', () => {+ const parsed = ShareTargetStatusResponseSchema.parse({+ verdict: 'renamed',+ renamedTo: 'knowledge/a.md',+ });+ expect(parsed.verdict).toBe('renamed');+ if (parsed.verdict === 'renamed') expect(parsed.renamedTo).toBe('knowledge/a.md');+ });++ test('a renamed verdict missing renamedTo degrades to unknown (no illegal state)', () => {+ expect(ShareTargetStatusResponseSchema.parse({ verdict: 'renamed' }).verdict).toBe('unknown');+ });++ test('an unrecognized verdict value degrades to unknown, not a parse failure', () => {+ const result = ShareTargetStatusResponseSchema.safeParse({ verdict: 'moved' });+ expect(result.success).toBe(true);+ if (result.success) expect(result.data.verdict).toBe('unknown');+ });++ test('a non-object or nullish body degrades to unknown', () => {+ for (const bad of [null, undefined, 42, 'renamed', {}]) {+ const result = ShareTargetStatusResponseSchema.safeParse(bad);+ expect(result.success).toBe(true);+ if (result.success) expect(result.data.verdict).toBe('unknown');+ }+ });+});++describe('BranchInfoResponseSchema shareTargetOnOriginBranch field', () => {+ const base = {+ detached: false,+ currentBranch: 'main',+ currentHeadSha: null,+ shareTargetExists: true,+ dirtyConflicts: { conflicts: false, files: [] },+ branchIsLocal: true,+ };++ test('an existing response without the field still parses (additive optional)', () => {+ const parsed = BranchInfoResponseSchema.parse({ ...base });+ if (!parsed.detached) expect(parsed.shareTargetOnOriginBranch).toBeUndefined();+ });++ test('the hint parses when present (true or false)', () => {+ for (const hint of [true, false]) {+ const parsed = BranchInfoResponseSchema.parse({ ...base, shareTargetOnOriginBranch: hint });+ if (!parsed.detached) expect(parsed.shareTargetOnOriginBranch).toBe(hint);+ }+ });+});diff --git a/packages/core/src/schemas/api/share.ts b/packages/core/src/schemas/api/share.tsindex e9e244a5a..336de1049 100644--- a/packages/core/src/schemas/api/share.ts+++ b/packages/core/src/schemas/api/share.ts@@ -1,5 +1,6 @@/**- * share/virality flow.+ * Share-link API schemas: send-side construct-url plus the receive-side+ * branch-info, checkout, and target-status contracts.** `handleShareConstructUrl` reads the project's local git state — HEAD branch,* `[remote "origin"] url`, and `refs/remotes/origin/<branch>` — and emits a@@ -82,6 +83,27 @@ export const ShareConstructUrlErrorCodeSchema = z.enum([]) satisfies StandardSchemaV1;export type ShareConstructUrlErrorCode = z.infer<typeof ShareConstructUrlErrorCodeSchema>;+/**+ * Freshness of a share target relative to origin, computed from local git+ * state at share time (never a fetch):+ *+ * - `current` — the shared doc/folder matches origin's copy.+ * - `stale` — committed-but-unpushed or uncommitted edits exist; the recipient+ * reads the last pushed version until a push lands.+ * - `absent` — the target isn't on origin at all, so the minted link 404s for+ * the recipient until it's pushed.+ *+ * Closed enum for v1. Producers only ever emit these three; consumers parse+ * tolerantly (see the `freshness` field below), so a value a newer server+ * adds degrades to "no signal" on an older client rather than a parse failure.+ */+export const ShareFreshnessSchema = z.enum([+ 'current',+ 'stale',+ 'absent',+]) satisfies StandardSchemaV1;+export type ShareFreshness = z.infer<typeof ShareFreshnessSchema>;+/*** Success body for `POST /api/share/construct-url`, discriminated on `ok`.*@@ -91,6 +113,10 @@ export type ShareConstructUrlErrorCode = z.infer<typeof ShareConstructUrlErrorCo* re-encoding, and the resolved branch name (so* the toast can name it on `branch-not-on-origin` retries).*+ * The success variant also carries an optional `freshness` signal+ * (`ShareFreshnessSchema`) describing whether the shared target is current /+ * stale / absent vs. origin; it is omitted whenever the signal is unavailable.+ ** Schemas are `.loose()` per the file-wide convention for forward-compat;* adding fields (e.g., `defaultBranch` for splash branch-indicator hints)* stays a non-breaking change.@@ -102,6 +128,11 @@ export const ShareConstructUrlResponseSchema = z.discriminatedUnion('ok', [shareUrl: z.string().min(1),sharedUrl: z.string().min(1),branch: z.string().min(1),+ // Additive, and value-tolerant on purpose: an unrecognized value (a+ // newer server emitting a freshness state this client's enum predates)+ // parses to `undefined` rather than failing the whole response. A+ // missing warning degrades safely; a broken share does not.+ freshness: ShareFreshnessSchema.optional().catch(undefined),}).loose(),z@@ -514,6 +545,11 @@ export function isLoginFixableGitAuthError(classified: ClassifiedGitAuthError):* would change when switching to `targetBranch`. Empty when no overlap.* - `branchIsLocal` — true iff `refs/heads/<targetBranch>` resolves locally* (no fetch attempted). Drives whether the checkout endpoint must fetch.+ * - `shareTargetOnOriginBranch` — additive optional HINT: true iff the target+ * exists at `origin/<targetBranch>` per the local remote-tracking ref (still+ * network-free). Omitted when the probe couldn't run. The dialog treats it as+ * a hint, never a terminal denial — a `false`/omitted value routes through+ * the fetch-backed target-status verdict, not an immediate refusal.*/const BranchInfoSharedFields = {shareTargetExists: z.boolean(),@@ -524,6 +560,7 @@ const BranchInfoSharedFields = {}).loose(),branchIsLocal: z.boolean(),+ shareTargetOnOriginBranch: z.boolean().optional(),};export const BranchInfoResponseSchema = z.discriminatedUnion('detached', [@@ -564,6 +601,13 @@ export const CheckoutRequestSchema = z.object({branch: refineBranchName(z.string().min(1)),principalId: z.string().optional(),+ // When set, the handler fast-forwards the target branch's local ref to+ // origin's tip BEFORE checking out, so a receiver whose local ref is stale+ // lands the switch WITH a recently-pushed doc. Fast-forward-only: on+ // divergence the update is refused (`ff-diverged`) and the checkout is not+ // attempted — the receive flow never merges. Absent/false = today's plain+ // checkout.+ fastForward: z.boolean().optional(),}).loose() satisfies StandardSchemaV1;export type CheckoutRequest = z.infer<typeof CheckoutRequestSchema>;@@ -594,6 +638,11 @@ export type CheckoutRequest = z.infer<typeof CheckoutRequestSchema>;* instead" instead of the generic "try switching manually" copy. The* accompanying `otherWorktreePath` carries the realpath-collapsed path* git reported.+ * - `ff-diverged` — only reachable with `fastForward: true`. The local branch+ * and origin diverged, so the fast-forward-only pre-checkout update was+ * refused and the checkout was NOT attempted (nothing mutated). The dialog+ * offers a plain switch with an honest note; reconciliation is the sync+ * engine's job — the receive flow never merges.*/export const CheckoutFailureReasonSchema = z.enum(['dirty-conflict',@@ -601,6 +650,7 @@ export const CheckoutFailureReasonSchema = z.enum(['fetch-failed','checkout-failed','branch-in-other-worktree',+ 'ff-diverged',]) satisfies StandardSchemaV1;export type CheckoutFailureReason = z.infer<typeof CheckoutFailureReasonSchema>;@@ -640,3 +690,77 @@ export const CheckoutResponseSchema = z.discriminatedUnion('ok', [.loose(),]) satisfies StandardSchemaV1;export type CheckoutResponse = z.infer<typeof CheckoutResponseSchema>;++// ─── Target-status (share-link receive integrity) ─────────────────────++/**+ * Closed verdict enum for `POST /api/share/target-status` — why a receiver's+ * open of a share link missed, computed AFTER a targeted fetch:+ *+ * - `on-origin` — the target exists at `origin/<branch>`; the receiver's local+ * ref was just stale (switch-and-update recovers it).+ * - `renamed` — git proves the target moved; `renamedTo` carries the new path+ * (verified to exist at the origin ref before it is offered).+ * - `deleted` — a removal commit exists and it was not a rename.+ * - `never-on-branch` — the removal-commit lookup is EMPTY: the path never+ * existed on this branch (e.g. never pushed). Messaged distinctly from+ * `deleted` — never "removed".+ * - `changed-locally` — the target is still on `origin/<branch>` AND in the+ * receiver's committed HEAD, but they removed or renamed it in their own+ * working tree without syncing. They are NOT behind, so "pull" is the wrong+ * guidance; the copy tells them they changed it locally.+ * - `unknown` — the fetch failed (offline / auth / timeout); the caller falls+ * back to today's guidance.+ *+ * Closed for v1. Consumers parse tolerantly (see the response schema): an+ * unrecognized verdict a newer server adds degrades to `unknown` rather than a+ * parse failure, preserving the fail-open contract.+ */+export const ShareTargetStatusVerdictSchema = z.enum([+ 'on-origin',+ 'renamed',+ 'deleted',+ 'never-on-branch',+ 'changed-locally',+ 'unknown',+]) satisfies StandardSchemaV1;+export type ShareTargetStatusVerdict = z.infer<typeof ShareTargetStatusVerdictSchema>;++/**+ * Request body for `POST /api/share/target-status`. `branch` is the share+ * link's target branch (validated via the shared seven-rule predicate);+ * `path` is the content-relative target path (empty string = content-root+ * folder share); `kind` disambiguates doc vs folder for the removal-commit+ * lookup.+ */+export const ShareTargetStatusRequestSchema = z+ .object({+ branch: refineBranchName(z.string().min(1)),+ path: z.string(),+ kind: z.enum(['doc', 'folder']),+ })+ .loose() satisfies StandardSchemaV1;+export type ShareTargetStatusRequest = z.infer<typeof ShareTargetStatusRequestSchema>;++/**+ * Response body for `POST /api/share/target-status`, discriminated on+ * `verdict`. Only `renamed` carries `renamedTo` (the redirect target), so the+ * illegal state "renamed with no destination" is unrepresentable.+ *+ * The whole union is value-tolerant: any parse failure — an unrecognized+ * verdict from a newer server, or a malformed `renamed` missing `renamedTo` —+ * collapses to `{ verdict: 'unknown' }`, so a skewed client degrades to today's+ * guidance instead of throwing. Members are `.loose()` so the desktop proxy+ * passes unknown additive fields through.+ */+export const ShareTargetStatusResponseSchema = z+ .discriminatedUnion('verdict', [+ z.object({ verdict: z.literal('on-origin') }).loose(),+ z.object({ verdict: z.literal('renamed'), renamedTo: z.string().min(1) }).loose(),+ z.object({ verdict: z.literal('deleted') }).loose(),+ z.object({ verdict: z.literal('never-on-branch') }).loose(),+ z.object({ verdict: z.literal('changed-locally') }).loose(),+ z.object({ verdict: z.literal('unknown') }).loose(),+ ])+ .catch({ verdict: 'unknown' }) satisfies StandardSchemaV1;+export type ShareTargetStatusResponse = z.infer<typeof ShareTargetStatusResponseSchema>;diff --git a/packages/desktop/src/main/branch-info-proxy.test.ts b/packages/desktop/src/main/branch-info-proxy.test.tsindex 2edf20d5d..ac0dc1a31 100644--- a/packages/desktop/src/main/branch-info-proxy.test.ts+++ b/packages/desktop/src/main/branch-info-proxy.test.ts@@ -1,6 +1,10 @@import { describe, expect, test } from 'bun:test';-import type { BranchInfoResponse, CheckoutResponse } from '@inkeep/open-knowledge-core';+import type {+ BranchInfoResponse,+ CheckoutResponse,+ ShareTargetStatusResponse,+} from '@inkeep/open-knowledge-core';import { RUNTIME_VERSION } from '@inkeep/open-knowledge-server';import {@@ -8,6 +12,7 @@ import {proxyAwaitBranchSwitched,proxyFetchBranchInfo,proxyRunCheckout,+ proxyShareTargetStatus,resolveProjectServerOrigin,type ServerLockReadShape,} from './branch-info-proxy';@@ -282,6 +287,124 @@ describe('proxyRunCheckout', () => {);expect(result).toBeNull();});++ test('omits fastForward from the body unless requested', async () => {+ let capturedBody: string | undefined;+ const fetchMock: typeof fetch = (async (_url, init) => {+ capturedBody = String(init?.body ?? '');+ return new Response(JSON.stringify({ ok: true } satisfies CheckoutResponse), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ });+ }) as typeof fetch;+ await proxyRunCheckout(+ { projectPath: '/tmp/p', branch: 'main' },+ buildDeps({ fetch: fetchMock }),+ );+ expect(JSON.parse(capturedBody as string)).toEqual({ branch: 'main' });+ });++ test('threads fastForward:true into the checkout body (Switch and update branch)', async () => {+ let capturedBody: string | undefined;+ const fetchMock: typeof fetch = (async (_url, init) => {+ capturedBody = String(init?.body ?? '');+ return new Response(JSON.stringify({ ok: true } satisfies CheckoutResponse), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ });+ }) as typeof fetch;+ await proxyRunCheckout(+ { projectPath: '/tmp/p', branch: 'feat/x', fastForward: true },+ buildDeps({ fetch: fetchMock }),+ );+ expect(JSON.parse(capturedBody as string)).toEqual({ branch: 'feat/x', fastForward: true });+ });++ test('returns the ff-diverged reason verbatim so the dialog can show the honest note', async () => {+ const body: CheckoutResponse = { ok: false, reason: 'ff-diverged' };+ const fetchMock: typeof fetch = (async () =>+ new Response(JSON.stringify(body), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ })) as typeof fetch;+ const result = await proxyRunCheckout(+ { projectPath: '/tmp/p', branch: 'feat/x', fastForward: true },+ buildDeps({ fetch: fetchMock }),+ );+ expect(result).toEqual(body);+ });+});++describe('proxyShareTargetStatus', () => {+ test('POSTs branch/path/kind and returns the on-origin verdict', async () => {+ let capturedBody: string | undefined;+ let capturedUrl = '';+ const fetchMock: typeof fetch = (async (url, init) => {+ capturedUrl = String(url);+ capturedBody = String(init?.body ?? '');+ const okBody: ShareTargetStatusResponse = { verdict: 'on-origin' };+ return new Response(JSON.stringify(okBody), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ });+ }) as typeof fetch;+ const result = await proxyShareTargetStatus(+ { projectPath: '/tmp/p', branch: 'feat/x', path: 'docs/a.md', kind: 'doc' },+ buildDeps({ fetch: fetchMock }),+ );+ expect(result).toEqual({ verdict: 'on-origin' });+ expect(capturedUrl).toContain('/api/share/target-status');+ expect(JSON.parse(capturedBody as string)).toEqual({+ branch: 'feat/x',+ path: 'docs/a.md',+ kind: 'doc',+ });+ });++ test('returns the renamed verdict with renamedTo verbatim', async () => {+ const body: ShareTargetStatusResponse = { verdict: 'renamed', renamedTo: 'guides/a.md' };+ const fetchMock: typeof fetch = (async () =>+ new Response(JSON.stringify(body), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ })) as typeof fetch;+ const result = await proxyShareTargetStatus(+ { projectPath: '/tmp/p', branch: 'main', path: 'docs/a.md', kind: 'doc' },+ buildDeps({ fetch: fetchMock }),+ );+ expect(result).toEqual(body);+ });++ test('returns null on a non-2xx transport failure (dialog falls back to today guidance)', async () => {+ const fetchMock: typeof fetch = (async () =>+ new Response(null, { status: 500 })) as typeof fetch;+ const result = await proxyShareTargetStatus(+ { projectPath: '/tmp/p', branch: 'main', path: '', kind: 'folder' },+ buildDeps({ fetch: fetchMock }),+ );+ expect(result).toBeNull();+ });++ test('coerces a malformed 200 body to the unknown verdict (never throws)', async () => {+ const fetchMock: typeof fetch = (async () =>+ new Response(JSON.stringify({ verdict: 'bogus-future-value' }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ })) as typeof fetch;+ const result = await proxyShareTargetStatus(+ { projectPath: '/tmp/p', branch: 'main', path: 'docs/a.md', kind: 'doc' },+ buildDeps({ fetch: fetchMock }),+ );+ expect(result).toEqual({ verdict: 'unknown' });+ });++ test('returns null when the server lock never resolves', async () => {+ const result = await proxyShareTargetStatus(+ { projectPath: '/tmp/p', branch: 'main', path: 'docs/a.md', kind: 'doc' },+ buildDeps({ readServerLock: () => null }),+ );+ expect(result).toBeNull();+ });});describe('proxyAwaitBranchSwitched', () => {diff --git a/packages/desktop/src/main/branch-info-proxy.ts b/packages/desktop/src/main/branch-info-proxy.tsindex 4a2483332..5bfa943e5 100644--- a/packages/desktop/src/main/branch-info-proxy.ts+++ b/packages/desktop/src/main/branch-info-proxy.ts@@ -33,12 +33,17 @@import { resolve as joinPath } from 'node:path';-import type { BranchInfoResponse, CheckoutResponse } from '@inkeep/open-knowledge-core';+import type {+ BranchInfoResponse,+ CheckoutResponse,+ ShareTargetStatusResponse,+} from '@inkeep/open-knowledge-core';import {BranchInfoResponseSchema,CheckoutResponseSchema,clientVersionHeaders,ServerInfoSuccessSchema,+ ShareTargetStatusResponseSchema,} from '@inkeep/open-knowledge-core';import { RUNTIME_VERSION } from '@inkeep/open-knowledge-server';@@ -166,7 +171,7 @@ export async function proxyFetchBranchInfo(if (parsed instanceof Promise) {// Standard Schema permits async validators; ours is sync. Defensive null// so a future schema swap doesn't silently invent a value.- deps.log?.warn('[branch-info-proxy] unexpected async validator');+ deps.log?.warn('[branch-info-proxy] branch-info unexpected async validator');return null;}if (parsed.issues) {@@ -260,9 +265,16 @@ export async function proxyAwaitBranchSwitched(}}-/** Proxy `POST /api/git/checkout`. Mirrors `proxyFetchBranchInfo`. */+/**+ * Proxy `POST /api/git/checkout`. Mirrors `proxyFetchBranchInfo`.+ *+ * `fastForward` rides in the body only when the caller requests it (the+ * on-origin "Switch and update branch" cell): the server fast-forwards the+ * target branch to origin's tip before checking out. Omitted → today's plain+ * checkout, so existing callers are byte-for-byte unchanged on the wire.+ */export async function proxyRunCheckout(- request: { projectPath: string; branch: string },+ request: { projectPath: string; branch: string; fastForward?: boolean },deps: BranchInfoProxyDeps,signal?: AbortSignal,): Promise<CheckoutResponse | null> {@@ -276,7 +288,11 @@ export async function proxyRunCheckout(const res = await deps.fetch(url, {method: 'POST',headers: { 'content-type': 'application/json', ...DESKTOP_MAIN_VERSION_HEADERS },- body: JSON.stringify({ branch: request.branch }),+ body: JSON.stringify(+ request.fastForward+ ? { branch: request.branch, fastForward: true }+ : { branch: request.branch },+ ),signal: composeFetchSignal(timeoutMs, signal),});if (!res.ok) {@@ -292,7 +308,7 @@ export async function proxyRunCheckout(}const parsed = CheckoutResponseSchema['~standard'].validate(raw);if (parsed instanceof Promise) {- deps.log?.warn('[branch-info-proxy] unexpected async validator');+ deps.log?.warn('[branch-info-proxy] checkout unexpected async validator');return null;}if (parsed.issues) {@@ -303,3 +319,68 @@ export async function proxyRunCheckout(}return parsed.value;}++/**+ * Proxy `POST /api/share/target-status` for the branch-switch dialog's verdict+ * pivot. The server runs a targeted fetch, then classifies why a share target+ * missed (on-origin / renamed / deleted / never-on-branch / unknown).+ *+ * Returns `null` only on a transport-level failure (no server lock, non-2xx,+ * network error) — the dialog treats that the same as an `unknown` verdict and+ * falls back to today's guidance. A 200 with an unexpected body is NOT null:+ * the response schema's `.catch` coerces it to `{ verdict: 'unknown' }`, so a+ * skewed server degrades to the fail-open verdict rather than a dropped call.+ *+ * The HTTP timeout is generous (30s) because the server's own fetch may take+ * network time before it returns its `unknown` verdict; a shorter proxy timeout+ * would abort the request before the server's fail-open answer arrives.+ */+export async function proxyShareTargetStatus(+ request: { projectPath: string; branch: string; path: string; kind: 'doc' | 'folder' },+ deps: BranchInfoProxyDeps,+ signal?: AbortSignal,+): Promise<ShareTargetStatusResponse | null> {+ const origin = await resolveProjectServerOrigin(request.projectPath, deps, signal);+ if (origin === null) return null;+ if (signal?.aborted) return null;+ const url = `${origin}/api/share/target-status`;+ const timeoutMs = deps.requestTimeoutMs ?? 30_000;+ let raw: unknown;+ try {+ const res = await deps.fetch(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json', ...DESKTOP_MAIN_VERSION_HEADERS },+ body: JSON.stringify({+ branch: request.branch,+ path: request.path,+ kind: request.kind,+ }),+ signal: composeFetchSignal(timeoutMs, signal),+ });+ if (!res.ok) {+ deps.log?.warn('[branch-info-proxy] non-2xx from target-status', { status: res.status });+ return null;+ }+ raw = await res.json();+ } catch (err) {+ deps.log?.warn('[branch-info-proxy] target-status fetch failed', {+ err: err instanceof Error ? err.message : String(err),+ });+ return null;+ }+ const parsed = ShareTargetStatusResponseSchema['~standard'].validate(raw);+ if (parsed instanceof Promise) {+ deps.log?.warn('[branch-info-proxy] target-status unexpected async validator');+ return null;+ }+ // The schema `.catch`es any parse failure to `{verdict: 'unknown'}`, so+ // `issues` is never populated here; the guard mirrors the sibling proxies so+ // a future schema swap that drops the catch surfaces as null, not a throw.+ if (parsed.issues) {+ deps.log?.warn('[branch-info-proxy] target-status shape invalid', {+ issues: parsed.issues.length,+ });+ return null;+ }+ return parsed.value;+}diff --git a/packages/desktop/src/main/check-target-exists.test.ts b/packages/desktop/src/main/check-target-exists.test.tsindex f397d523d..724e7f962 100644--- a/packages/desktop/src/main/check-target-exists.test.ts+++ b/packages/desktop/src/main/check-target-exists.test.ts@@ -3,7 +3,7 @@ import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync }import { tmpdir } from 'node:os';import { join } from 'node:path';-import { checkTargetExists } from './check-target-exists.ts';+import { checkTargetExists, computeShareTargetMissing } from './check-target-exists.ts';describe('checkTargetExists', () => {function makeProject(): string {@@ -277,3 +277,111 @@ describe('checkTargetExists', () => {});});});++describe('computeShareTargetMissing', () => {+ function makeProject(): string {+ return mkdtempSync(join(tmpdir(), 'ok-compute-target-missing-'));+ }++ function cleanup(path: string): void {+ rmSync(path, { recursive: true, force: true });+ }++ // Real probe + real filesystem: the decision is exercised through the actual+ // `checkTargetExists` (no stub), so the mapping from probe result to the+ // caller's boolean is pinned end-to-end.+ test('flags a doc target that is absent on the working tree', () => {+ const project = makeProject();+ try {+ // Project exists, the shared doc does not — the receiver's branch is+ // behind, or the doc was deleted/renamed upstream after the share.+ expect(+ computeShareTargetMissing(checkTargetExists, project, {+ kind: 'doc',+ path: 'notes/plan.md',+ }),+ ).toBe(true);+ } finally {+ cleanup(project);+ }+ });++ test('does not flag a doc target present on the working tree', () => {+ const project = makeProject();+ try {+ mkdirSync(join(project, 'notes'), { recursive: true });+ writeFileSync(join(project, 'notes', 'plan.md'), '# plan\n');+ expect(+ computeShareTargetMissing(checkTargetExists, project, {+ kind: 'doc',+ path: 'notes/plan.md',+ }),+ ).toBe(false);+ } finally {+ cleanup(project);+ }+ });++ test('flags a folder target that is absent on the working tree', () => {+ const project = makeProject();+ try {+ expect(+ computeShareTargetMissing(checkTargetExists, project, { kind: 'folder', path: 'guides' }),+ ).toBe(true);+ } finally {+ cleanup(project);+ }+ });++ test('does not flag a folder target present on the working tree', () => {+ const project = makeProject();+ try {+ mkdirSync(join(project, 'guides'), { recursive: true });+ expect(+ computeShareTargetMissing(checkTargetExists, project, { kind: 'folder', path: 'guides' }),+ ).toBe(false);+ } finally {+ cleanup(project);+ }+ });++ test('never flags a content-root folder share (empty path)', () => {+ // The working-tree root is always present, and the probe rejects an empty+ // path as unreadable — either way the content root must dispatch normally.+ const project = makeProject();+ try {+ expect(+ computeShareTargetMissing(checkTargetExists, project, { kind: 'folder', path: '' }),+ ).toBe(false);+ } finally {+ cleanup(project);+ }+ });++ test('fails open (no flag) when the target path is unsafe', () => {+ // A traversal path resolves to `unreadable`, not `missing` — a probe that+ // refuses the input must never route the receiver to the miss panel.+ const project = makeProject();+ try {+ expect(+ computeShareTargetMissing(checkTargetExists, project, {+ kind: 'doc',+ path: '../escape.md',+ }),+ ).toBe(false);+ } finally {+ cleanup(project);+ }+ });++ test('fails open (no flag) when the project path is unsafe', () => {+ // A non-absolute project path is rejected as `unreadable`; the open proceeds+ // rather than surfacing a false miss.+ expect(+ computeShareTargetMissing(checkTargetExists, 'relative/project', {+ kind: 'doc',+ path: 'README.md',+ }),+ ).toBe(false);+ });+});diff --git a/packages/desktop/src/main/check-target-exists.ts b/packages/desktop/src/main/check-target-exists.tsindex 85a853271..4e43e68e8 100644--- a/packages/desktop/src/main/check-target-exists.ts+++ b/packages/desktop/src/main/check-target-exists.ts@@ -1,6 +1,6 @@/*** Lightweight `<projectPath>/<path>` existence probe for the share-receive- * Q1 pre-server target check. Runs after the `.git/HEAD` branch comparison+ * pre-server target check. Runs after the `.git/HEAD` branch comparison* passes — answers "does the target the share links to actually exist on the* current working tree?" Without this gate, a share-link whose target does* not exist on the receiver's locally checked-out branch (typical@@ -15,7 +15,7 @@* skip this probe entirely at the call site — the root always exists — so* this function never receives an empty `path`.*- * Q1 runs before any project is opened — no server, no `simple-git`. The+ * This runs before any project is opened — no server, no `simple-git`. The* receiver is choosing between silent dispatch (target present) and* surfacing a "missing on branch" toast (target absent); a graceful fail* must collapse to silent dispatch so a single broken project never blocks@@ -175,3 +175,30 @@ export function checkTargetExists(if (!matches) return 'missing';return 'exists';}++/**+ * Decide whether a share-receive deep-link target is absent on the receiver's+ * checked-out working tree, so the caller can flag the window it is about to+ * open. Renderer-initiated opens — a fresh clone, or a pivot into another+ * worktree — reach window-open through the `ok:project:open` IPC handler rather+ * than the deep-link dispatcher, so they never run the target probe that+ * `dispatchResolvedShare` runs on the `branch-match-ok` leg. Without it a moved+ * or deleted target lands the receiver in the create-mode editor and lets them+ * silently fork the doc at the shared path. (This mirrors the `isContentRoot`+ * short-circuit + `=== 'missing'` check in `url-scheme.ts`'s dispatcher; kept+ * separate because that path takes the probe as an injected dep.)+ *+ * Content-root folder shares (empty `path`) always exist — the working-tree+ * root is the target — so they short-circuit before the probe, which classifies+ * an empty path as `unreadable`. Only a definitive `'missing'` flags the target:+ * `'unreadable'` (unsafe input, or an I/O error other than ENOENT) collapses to+ * `false`, so a probe failure never blocks the open.+ */+export function computeShareTargetMissing(+ probe: (projectPath: string, kind: 'doc' | 'folder', path: string) => CheckTargetExistsResult,+ projectPath: string,+ target: { kind: 'doc' | 'folder'; path: string },+): boolean {+ if (target.kind === 'folder' && target.path === '') return false;+ return probe(projectPath, target.kind, target.path) === 'missing';+}diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 6abe69a02..5eab3c310 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -137,6 +137,7 @@ import {proxyAwaitBranchSwitched,proxyFetchBranchInfo,proxyRunCheckout,+ proxyShareTargetStatus,} from './branch-info-proxy.ts';import { wrapperPathInBundle } from './bundle-paths.ts';import {@@ -144,7 +145,10 @@ import {startBundleReplaceWatcher,} from './bundle-replace-detector.ts';import { cascadePosition } from './cascade-position.ts';-import { checkTargetExists as checkTargetExistsImpl } from './check-target-exists.ts';+import {+ checkTargetExists as checkTargetExistsImpl,+ computeShareTargetMissing,+} from './check-target-exists.ts';import {cliProbeArgs,resolveClaudeReadiness,@@ -3144,6 +3148,15 @@ function registerIpcHandlers() {`ok:project:open rejected: invalid entryPoint '${String(request.entryPoint)}'`,);}+ // Renderer-initiated share-receive opens (fresh clone, multi-worktree pivot)+ // reach window-open here instead of through the URL-scheme dispatcher, which+ // is where `dispatchResolvedShare` probes the target. Run the same probe so a+ // moved/deleted target flags `targetMissing` and the editor renders the+ // honest verdict panel instead of the create-mode editor. Synchronous native+ // probe — no new IPC — computed once for both the warm and cold branches.+ const targetMissing =+ request.pendingDeepLinkTarget !== undefined &&+ computeShareTargetMissing(checkTargetExistsImpl, request.path, request.pendingDeepLinkTarget);// Warm-focus path for share-receive: when an existing window holds the// requested project, focus it and dispatch the deep-link directly. Mirrors// the URL-scheme warm path in url-scheme.ts so the IPC and the deep-link@@ -3158,6 +3171,9 @@ function registerIpcHandlers() {kind: request.pendingDeepLinkTarget.kind,branch: request.pendingBranch ?? null,multiCandidate: request.pendingMultiCandidate === true,+ // Only carry the flag when set — keeps the common (present) case's+ // payload identical to the pre-gate shape.+ ...(targetMissing ? { targetMissing: true } : {}),});return undefined;}@@ -3191,6 +3207,7 @@ function registerIpcHandlers() {request.pendingBranch,request.pendingMultiCandidate,request.pendingShareBranchSwitch,+ targetMissing || undefined,);return undefined;});@@ -3268,6 +3285,10 @@ function registerIpcHandlers() {return proxyRunCheckout(request, branchInfoProxyDeps);});+ handle('ok:project:fetch-target-status', async (_event, request) => {+ return proxyShareTargetStatus(request, branchInfoProxyDeps);+ });+handle('ok:project:await-branch-switched', async (_event, request) => {return proxyAwaitBranchSwitched(request, branchInfoProxyDeps);});diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.tsindex 2bfc55a31..b55100344 100644--- a/packages/desktop/src/preload/index.ts+++ b/packages/desktop/src/preload/index.ts@@ -404,6 +404,7 @@ const bridge: OkDesktopBridge = {readHeadBranch: (projectPath: string) => invoke('ok:project:read-head-branch', projectPath),fetchBranchInfo: (request) => invoke('ok:project:fetch-branch-info', request),runCheckout: (request) => invoke('ok:project:run-checkout', request),+ fetchTargetStatus: (request) => invoke('ok:project:fetch-target-status', request),awaitBranchSwitched: (request) => invoke('ok:project:await-branch-switched', request),okInit: (request) => invoke('ok:project:ok-init', request),close: () => invoke('ok:project:close'),diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.tsindex 266d7f7cd..19288a656 100644--- a/packages/desktop/src/shared/bridge-contract.ts+++ b/packages/desktop/src/shared/bridge-contract.ts@@ -25,6 +25,7 @@ import type {EditorId,LocalOpOkInitResponse,OkFolderState,+ ShareTargetStatusResponse,TerminalCli,WorktreeCreateRequest,WorktreeCreateResult,@@ -1260,8 +1261,36 @@ export interface OkDesktopBridge {* `{ok: true}`. The CRDT transition is still in flight at HTTP 200 —* navigation waits on the CC1 `branch-switched` signal landing in the* project window via `awaitBranchSwitched` (below).+ *+ * `fastForward` (on-origin "Switch and update branch") tells the server to+ * fast-forward the target branch's local ref to origin's tip before the+ * checkout, so a stale receiver lands the switch WITH a recently-pushed+ * doc. On divergence the server refuses and returns `ff-diverged` (nothing+ * mutated) — the receive flow never merges. Omitted = today's plain switch.+ */+ runCheckout(request: {+ projectPath: string;+ branch: string;+ fastForward?: boolean;+ }): Promise<CheckoutResponse | null>;+ /**+ * Proxy `POST /api/share/target-status` for the branch-switch dialog's+ * verdict pivot. When the origin-existence hint from `fetchBranchInfo` is+ * `false`, the dialog asks main to run the fetch-backed verdict (on-origin+ * / renamed / deleted / never-on-branch / unknown) rather than treating the+ * stale hint as a terminal denial.+ *+ * Returns `null` on any transport-level failure; the dialog treats that+ * the same as an `unknown` verdict (today's guidance). A 200 with an+ * unexpected body degrades to `{ verdict: 'unknown' }` via the schema's+ * value-tolerant parse, never a throw.*/- runCheckout(request: { projectPath: string; branch: string }): Promise<CheckoutResponse | null>;+ fetchTargetStatus(request: {+ projectPath: string;+ branch: string;+ path: string;+ kind: 'doc' | 'folder';+ }): Promise<ShareTargetStatusResponse | null>;/*** Wait for the project's running server to report `currentBranch === branch`* via `GET /api/server-info`. The share-receive branch-switch dialog callsdiff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.tsindex f21edf18a..df6b71d0c 100644--- a/packages/desktop/src/shared/ipc-channels.ts+++ b/packages/desktop/src/shared/ipc-channels.ts@@ -30,7 +30,14 @@* existing channels is preferred over net-new hand-rolled channels until* that migration lands.*- * Count is 76 (ratchet cap 76). Full rationale in the ratchet test header.+ * Count is 77 (ratchet cap 77). The 74→75 bump reconciled a merge collision:+ * the worktree selector (`ok:worktree:dispatch`) and the terminal-controls PR+ * (`ok:terminal:cli-installed-map`) each landed in the base tree's single free+ * slot concurrently. The 75→76 bump then unioned in the desktop+ * startup-instrumentation channel (`ok:startup:renderer-marks`), which landed+ * on main in parallel. The 76→77 bump added the share-receive branch-switch+ * dialog's verdict probe (`ok:project:fetch-target-status`). Full rationale in+ * the ratchet test header.*/import type {@@ -40,6 +47,7 @@ import type {EditorId,LocalOpOkInitResponse,OkFolderState,+ ShareTargetStatusResponse,TerminalCli,WorktreeCreateRequest,WorktreeCreateResult,@@ -662,12 +670,29 @@ export interface RequestChannels {* be parsed; the dialog treats this as a generic checkout-failed and* stays open. Server-classified failures (`dirty-conflict`,* `branch-not-found`, `fetch-failed`, `checkout-failed`) are returned- * verbatim so the dialog can map each to its own toast copy.+ * verbatim so the dialog can map each to its own toast copy. `fastForward`+ * (on-origin "Switch and update branch") asks the server to fast-forward the+ * target branch to origin's tip before checkout; divergence returns the+ * verbatim `ff-diverged` reason so the dialog can offer a plain switch.*/'ok:project:run-checkout': {- args: [request: { projectPath: string; branch: string }];+ args: [request: { projectPath: string; branch: string; fastForward?: boolean }];result: CheckoutResponse | null;};+ /**+ * Proxy `POST /api/share/target-status` against the project's running server+ * for the branch-switch dialog's verdict pivot. When `fetch-branch-info`'s+ * origin-existence hint is `false`, the dialog asks main to run the+ * fetch-backed verdict (on-origin / renamed / deleted / never-on-branch /+ * unknown) instead of treating the stale hint as a terminal denial. Returns+ * `null` on transport failure (the dialog treats it as `unknown`); a 200 with+ * an unexpected body degrades to `{verdict:'unknown'}` via the schema's+ * value-tolerant parse. Never throws.+ */+ 'ok:project:fetch-target-status': {+ args: [request: { projectPath: string; branch: string; path: string; kind: 'doc' | 'folder' }];+ result: ShareTargetStatusResponse | null;+ };/*** Poll the project's `GET /api/server-info` until `currentBranch` matches* `branch` (or the dispatcher's timeout elapses). The dispatcher dialogdiff --git a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.tsindex 0a85574a1..ab567af81 100644--- a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts+++ b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts@@ -250,8 +250,20 @@ const CHANNELS_SRC = readFileSync(SRC_PATH, 'utf-8');* theme-applied fires on the show-gate edge + matchMedia changes, these* fire once content is usable) nor `ok:editor:*` (editor-area state, not a* launch metric). New `ok:startup:*` namespace, single member.+ *+ * Bumped from 76 to 77 for the share-receive branch-switch dialog's verdict+ * pivot:+ *+ * - `ok:project:fetch-target-status` — proxies `POST /api/share/target-status`+ * so the dialog can fetch a real verdict (on-origin / renamed / deleted /+ * never-on-branch / unknown) when the network-free origin hint is stale.+ * Could not fold into `ok:project:fetch-branch-info` (a GET proxy that is+ * deliberately network-free — the whole point of a separate endpoint is to+ * keep branch-info's fast path off the network) nor `ok:project:run-checkout`+ * (a POST that MUTATES the working tree; this is a read-only fetch+classify).+ * Extends the existing `ok:project:*` namespace, single member.*/-const REQUEST_CHANNEL_CAP = 76;+const REQUEST_CHANNEL_CAP = 77;/*** Extract the body of an interface block by name. Returns the substringdiff --git a/packages/desktop/tests/smoke/share-receive-miss-terminal.e2e.ts b/packages/desktop/tests/smoke/share-receive-miss-terminal.e2e.tsnew file mode 100644index 000000000..7e5b2adfb--- /dev/null+++ b/packages/desktop/tests/smoke/share-receive-miss-terminal.e2e.ts@@ -0,0 +1,185 @@+/**+ * Share-receive miss smoke — the cross-process proof that a share link whose+ * target vanished upstream lands the receiver on the honest verdict DIALOG and+ * NEVER the create-mode editor (where a receiver could silently fork the doc at+ * the shared path). Because main flags the target missing, the dialog shows+ * without navigating to the dead path — no phantom tab is opened.+ *+ * The journey: seed a receiver clone whose branch no longer carries the shared+ * doc (deleted on origin), fire the share URL, and assert the dispatched window+ * resolves the miss dialog with the `deleted` verdict — proving the whole chain+ * end-to-end (main share-resolution -> `ok:deep-link` IPC -> renderer miss+ * dispatch -> the real target-status fetch against the receiver's server).+ *+ * **Delivery: argv cold-start, not `open -g`.** The sibling smokes shell out to+ * `open -g "openknowledge://..."` for true Apple-Event delivery, and that is the+ * right channel on a CI runner where no app owns the scheme. But on any host with+ * OpenKnowledge.app installed (every dev machine, this one included), macOS Launch+ * Services binds `openknowledge://` to that signed bundle, so `open -g` routes the+ * event there and the Playwright-launched dev Electron never receives it — the+ * poll then times out. Passing the URL as an argv entry drives the app's+ * documented cold-start CLI-launch scan (`registerProtocolHandler`'s initial-argv+ * loop), which reaches `enqueueOrRoute` and runs the identical routing the Apple+ * Event would, deterministically on every host. The pure Apple-Event channel stays+ * covered by `deep-link.e2e.ts` on a clean runner.+ *+ * Candidate selection matches on the seeded Recents `gitRemoteUrl`, which is+ * intentionally decoupled from the receiver's real `origin` (a local bare repo):+ * the GitHub URL satisfies the share's owner/repo match while the local origin lets+ * the target-status fetch run for real and return a genuine `deleted` verdict.+ */++import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { _electron as electron } from '@playwright/test';+import { expect, test } from './_helpers/smoke-test';++const __dirname = dirname(fileURLToPath(import.meta.url));+const MAIN_ENTRY = resolve(__dirname, '..', '..', 'out', 'main', 'index.js');++const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';+const DARWIN = process.platform === 'darwin';+const BUILD_EXISTS = existsSync(MAIN_ENTRY);++function git(cwd: string, ...args: string[]): void {+ execFileSync('git', args, {+ cwd,+ env: { ...process.env, LANG: 'C', LC_ALL: 'C', GIT_CONFIG_GLOBAL: '/dev/null' },+ stdio: 'pipe',+ });+}++const OK_CONFIG = "content:\n dir: '.'\n include: ['**/*.md']\n exclude: []\n";++interface MissFixture {+ readonly root: string;+ readonly receiver: string;+ readonly docPath: string;+}++/**+ * Build origin (bare) + receiver (clone) where the shared doc was committed then+ * deleted on the branch, so the receiver's working tree lacks it and origin's+ * history proves the deletion. Returns realpath-collapsed paths so the receiver+ * matches the dispatched window's `projectPath` after the macOS `/var` ->+ * `/private/var` normalization the main process applies.+ */+function setupDeletedTargetFixture(): MissFixture {+ const uniq = randomUUID().slice(0, 8);+ const docPath = `docs/moved-${uniq}.md`;+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-share-miss-')));+ const originDir = join(root, 'origin.git');+ const seedDir = join(root, 'seed');+ const receiverDir = join(root, 'receiver');++ mkdirSync(originDir);+ git(originDir, 'init', '--bare', '--initial-branch=main');++ mkdirSync(seedDir);+ git(seedDir, 'init', '--initial-branch=main');+ git(seedDir, 'config', 'user.email', '[email protected]');+ git(seedDir, 'config', 'user.name', 'Test');+ git(seedDir, 'remote', 'add', 'origin', originDir);+ mkdirSync(join(seedDir, '.ok'), { recursive: true });+ writeFileSync(join(seedDir, '.ok', 'config.yml'), OK_CONFIG);+ mkdirSync(join(seedDir, 'docs'), { recursive: true });+ writeFileSync(join(seedDir, docPath), `# moved ${uniq}\n`);+ git(seedDir, 'add', '.');+ git(seedDir, 'commit', '-m', 'seed doc');+ git(seedDir, 'push', 'origin', 'main');+ git(seedDir, 'rm', docPath);+ git(seedDir, 'commit', '-m', 'delete doc');+ git(seedDir, 'push', 'origin', 'main');++ git(root, 'clone', originDir, receiverDir);+ return { root, receiver: realpathSync(receiverDir), docPath };+}++test.describe('share-receive miss terminal smoke', () => {+ test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');+ test.skip(!DARWIN, 'Deep-link URL scheme is macOS-only in v0.');+ test.skip(+ !BUILD_EXISTS,+ `Main build missing at ${MAIN_ENTRY} — run "bun run build:desktop" first.`,+ );++ test('a deleted share target lands the receiver on the miss dialog, never create-mode', async ({+ captureStderrFor,+ }, testInfo) => {+ testInfo.setTimeout(120_000);+ const fixture = setupDeletedTargetFixture();++ const tmpHome = mkdtempSync(join(tmpdir(), 'ok-share-miss-home-'));+ const userData = join(tmpHome, 'electron-userdata');+ mkdirSync(userData, { recursive: true });+ writeFileSync(+ join(userData, 'state.json'),+ JSON.stringify({+ recentProjects: [+ {+ path: fixture.receiver,+ name: 'receiver',+ lastOpenedAt: new Date().toISOString(),+ gitRemoteUrl: 'https://github.com/inkeep/open-knowledge.git',+ },+ ],+ projectSessions: {},+ }),+ );++ const githubBlobUrl = `https://github.com/inkeep/open-knowledge/blob/main/${fixture.docPath}`;+ const shareUrl = `openknowledge://share?url=${encodeURIComponent(githubBlobUrl)}`;++ const app = await electron.launch({+ args: [MAIN_ENTRY, `--user-data-dir=${userData}`, shareUrl],+ timeout: 30_000,+ });+ captureStderrFor(app, { cleanupDirs: [fixture.root, tmpHome] });++ const firstWindow = await app.firstWindow({ timeout: 15_000 });+ expect(firstWindow).toBeDefined();++ // Poll every window until one resolves the miss DIALOG. A known-missing+ // target shows the honest verdict as a modal WITHOUT navigating to the dead+ // path, so `hasEditor === false` alongside the resolved dialog is the "never+ // create-mode fork" proof — the receiver never landed in an editor at the+ // shared path.+ type MissState = {+ phase: string | null;+ verdict: string | null;+ hasEditor: boolean;+ bodyText: string;+ };+ let resolved: MissState | null = null;+ await expect(async () => {+ for (const page of app.windows()) {+ const info: MissState | null = await page+ .evaluate(() => {+ const dialog = document.querySelector('[data-testid="share-receive-miss-dialog"]');+ return {+ phase: dialog?.getAttribute('data-phase') ?? null,+ verdict: dialog?.getAttribute('data-verdict') ?? null,+ hasEditor: !!document.querySelector('.ProseMirror'),+ bodyText: document.body?.innerText ?? '',+ };+ })+ .catch(() => null);+ if (info?.phase === 'resolved') {+ resolved = info;+ return;+ }+ }+ throw new Error('no window has resolved the share-receive miss dialog yet');+ }).toPass({ timeout: 60_000 });++ if (resolved === null) throw new Error('share-receive miss dialog never resolved');+ const outcome: MissState = resolved;+ expect(outcome.verdict).toBe('deleted');+ expect(outcome.hasEditor).toBe(false);+ expect(outcome.bodyText).toContain('removed from branch');+ });+});diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 515f8fd06..84809463e 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -160,6 +160,8 @@ import {SharePublishOwnersResponseSchema,SharePublishRequestSchema,SharePublishResponseSchema,+ ShareTargetStatusRequestSchema,+ ShareTargetStatusResponseSchema,SKILL_NAME_REGEX,SkillDeleteSuccessSchema,SkillFileDeleteSuccessSchema,@@ -330,6 +332,7 @@ import {SHARE_BASE_URL,SHARE_CONSTRUCT_URL_HANDLER_TAG,} from './share/construct-url.ts';+import { computeShareFreshness } from './share/freshness.ts';import {branchExistsOnOrigin,readGitHeadBranch,@@ -352,6 +355,10 @@ import {SHARE_PUBLISH_OWNERS_KEY,SHARE_PUBLISH_TIMEOUT_MS,} from './share/publish.ts';+import {+ computeShareTargetStatus,+ SHARE_TARGET_STATUS_HANDLER_TAG,+} from './share/target-status.ts';import { buildAndOpenSkill } from './skill-install.ts';import { readSkillManagement, writeSkillManagement } from './skill-management.ts';import {@@ -16451,12 +16458,23 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {sharedUrl = buildGitHubTreeUrl(origin.owner, origin.repo, branch, treePath);}const shareUrl = `${SHARE_BASE_URL}${encodeShareUrl(sharedUrl)}`;- emitShareConstructUrlLog('ok', { branchExists: true, kind: body.kind });+ // Freshness probes the repo-relative path of the shared target: it+ // lives under content.dir, so join contentRel with the content-relative+ // share path. For the dominant content.dir === '.' case contentRel is+ // '' and this is just sharePath; an empty result is the content root.+ const freshnessPath =+ contentRel === ''+ ? sharePath+ : sharePath === ''+ ? contentRel+ : `${contentRel}/${sharePath}`;+ const freshness = await computeShareFreshness(projectDir, branch, freshnessPath, body.kind);+ emitShareConstructUrlLog('ok', { branchExists: true, kind: body.kind, freshness });successResponse(res,200,ShareConstructUrlResponseSchema,- { ok: true, shareUrl, sharedUrl, branch },+ { ok: true, shareUrl, sharedUrl, branch, freshness },{ handler: SHARE_CONSTRUCT_URL_HANDLER_TAG },);} catch (err) {@@ -16553,6 +16571,79 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {},);+ /**+ * `POST /api/share/target-status` — receive-side verdict for a share link+ * whose target is missing on the receiver's current ref. Runs a targeted+ * `git fetch origin <branch>` (authenticated by the user's ambient git+ * credential helper, same as checkout's fetch; no explicit token injection)+ * bounded by a timeout, then classifies the miss from git's rename detection:+ * on-origin (the local ref was stale) / renamed (+ a new path verified to+ * resolve at the origin ref) / deleted / never-on-branch / unknown (fetch+ * failed). Fail-open: any error returns `unknown`, and the caller falls back+ * to today's guidance.+ *+ * Updates only remote-tracking refs, no CRDT mutation — so the+ * attribution-sweep meta-test exempts it (see EXEMPT_HANDLERS).+ */+ const handleShareTargetStatus = withValidation(+ ShareTargetStatusRequestSchema,+ async (_req, res, body) => {+ try {+ if (!projectDir) {+ errorResponse(+ res,+ 500,+ 'urn:ok:error:internal-server-error',+ 'projectDir is not configured for this server.',+ { handler: SHARE_TARGET_STATUS_HANDLER_TAG },+ );+ return;+ }+ // Validate the path shape before it reaches git's `<ref>:<path>`+ // ref-spec, mirroring the sibling share handlers (construct-url's+ // `isValidSharePath`, branch-info's `isValidBranchInfoPath`) —+ // precedent #55 content-scope predicate symmetry. Kind-aware: an empty+ // path is the folder-root sentinel, invalid for a doc; `..`, `.git`,+ // control chars, and backslashes are rejected so a malformed path can't+ // reach git and degrade the verdict classification.+ if (!isValidBranchInfoPath(body.path, body.kind)) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'path is missing or malformed.', {+ handler: SHARE_TARGET_STATUS_HANDLER_TAG,+ });+ return;+ }+ // The target lives under content.dir; map the content-relative request+ // path to the repo-relative path git reads (same join as construct-url;+ // '' for the dominant content.dir === '.' case).+ const contentRel = toGitRelativePath(projectDir, contentDir);+ if (contentRel === null) {+ throw new Error('content dir is not contained within the project dir');+ }+ const gitPath =+ contentRel === ''+ ? body.path+ : body.path === ''+ ? contentRel+ : `${contentRel}/${body.path}`;+ const status = await computeShareTargetStatus(projectDir, body.branch, gitPath, body.kind);+ successResponse(res, 200, ShareTargetStatusResponseSchema, status, {+ handler: SHARE_TARGET_STATUS_HANDLER_TAG,+ });+ } catch (err) {+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Internal server error.', {+ handler: SHARE_TARGET_STATUS_HANDLER_TAG,+ cause: err,+ });+ }+ },+ {+ handler: SHARE_TARGET_STATUS_HANDLER_TAG,+ method: 'POST',+ preBodyGate: (req, res) =>+ checkLocalOpSecurity(req, res, { handler: SHARE_TARGET_STATUS_HANDLER_TAG }),+ },+ );+/*** `POST /api/git/checkout` — share-receive branch-switch executor.*@@ -16594,7 +16685,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {}try {- const outcome = await withParentLock(() => runCheckoutFlow(projectDir, body.branch));+ const outcome = await withParentLock(() =>+ runCheckoutFlow(projectDir, body.branch, { fastForward: body.fastForward === true }),+ );successResponse(res, 200, CheckoutResponseSchema, outcome, {handler: CHECKOUT_HANDLER_TAG,});@@ -17265,6 +17358,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {'/api/__embed-detect': handleEmbedDetect,'/api/server-info': handleServerInfo,'/api/share/construct-url': handleShareConstructUrl,+ '/api/share/target-status': handleShareTargetStatus,'/api/git/branch-info': handleBranchInfo,'/api/git/checkout': handleCheckout,'/api/share/publish/owners': handleSharePublishOwners,diff --git a/packages/server/src/error-format.ts b/packages/server/src/error-format.tsnew file mode 100644index 000000000..152ce423c--- /dev/null+++ b/packages/server/src/error-format.ts@@ -0,0 +1,12 @@+/**+ * Shared error-message formatting for fail-open diagnostic breadcrumbs. The+ * git branch-info / checkout / freshness / target-status catches all bound an+ * arbitrary error to a single log-safe line the same way; one definition keeps+ * the 500-char cap and the ellipsis consistent across those sites.+ */++/** Bound an error to a log-safe message: non-Errors stringify; over 500 chars truncates with an ellipsis. */+export function truncateError(err: unknown): string {+ const message = err instanceof Error ? err.message : String(err);+ return message.length > 500 ? `${message.slice(0, 500)}…` : message;+}diff --git a/packages/server/src/git-branch-info.test.ts b/packages/server/src/git-branch-info.test.tsindex e3d73d71c..92bfffa60 100644--- a/packages/server/src/git-branch-info.test.ts+++ b/packages/server/src/git-branch-info.test.ts@@ -1,10 +1,12 @@-import { describe, expect, test } from 'bun:test';+import { afterEach, describe, expect, test } from 'bun:test';import {+ computeBranchInfo,isBranchResolutionError,isValidBranchInfoPath,isValidBranchName,} from './git-branch-info.ts';+import { createGitTriangle, type GitTriangle } from './share/git-fixture.test-helper.ts';describe('isValidBranchName', () => {test('accepts a plain branch name', () => {@@ -167,3 +169,50 @@ describe('isBranchResolutionError', () => {expect(isBranchResolutionError(undefined)).toBe(false);});});++describe('computeBranchInfo — shareTargetOnOriginBranch (network-free hint)', () => {+ const triangles: GitTriangle[] = [];+ function newTriangle(): GitTriangle {+ const t = createGitTriangle();+ triangles.push(t);+ return t;+ }+ afterEach(() => {+ for (const t of triangles.splice(0)) t.cleanup();+ });++ test('true when the target exists at origin/<branch>', async () => {+ const t = newTriangle();+ t.seedAndPush('doc.md', '# hi\n');+ const info = await computeBranchInfo(t.senderDir, t.branch, 'doc.md', 'doc');+ expect(info.shareTargetOnOriginBranch).toBe(true);+ });++ test('false when the target is missing on an existing origin ref', async () => {+ const t = newTriangle();+ t.seedAndPush('doc.md', '# hi\n');+ const info = await computeBranchInfo(t.senderDir, t.branch, 'gone.md', 'doc');+ expect(info.shareTargetOnOriginBranch).toBe(false);+ });++ test('reads the origin ref, not HEAD: a committed-but-unpushed doc is false', async () => {+ const t = newTriangle();+ // Committed locally but never pushed — HEAD has it, origin/<branch> does not.+ t.commitWithoutPush('local-only.md', '# local\n');+ const info = await computeBranchInfo(t.senderDir, t.branch, 'local-only.md', 'doc');+ expect(info.shareTargetOnOriginBranch).toBe(false);+ });++ test('undefined when the origin ref is not present locally (unknown until a fetch)', async () => {+ const t = newTriangle();+ t.seedAndPush('doc.md', '# hi\n');+ const info = await computeBranchInfo(t.senderDir, 'never-fetched-branch', 'doc.md', 'doc');+ expect(info.shareTargetOnOriginBranch).toBeUndefined();+ });++ test('folder content root is always present on the ref (true)', async () => {+ const t = newTriangle();+ const info = await computeBranchInfo(t.senderDir, t.branch, '', 'folder');+ expect(info.shareTargetOnOriginBranch).toBe(true);+ });+});diff --git a/packages/server/src/git-branch-info.ts b/packages/server/src/git-branch-info.tsindex f02748ecd..e9fb36771 100644--- a/packages/server/src/git-branch-info.ts+++ b/packages/server/src/git-branch-info.ts@@ -8,6 +8,7 @@*/import { isValidBranchName } from '@inkeep/open-knowledge-core';+import { truncateError } from './error-format.ts';import { type DirtyOverlapResult, dirtyFilesOverlapWith } from './git-dirty.ts';import { createGitInstance } from './git-handle.ts';@@ -31,6 +32,7 @@ export type BranchInfo =shareTargetExists: boolean;dirtyConflicts: DirtyOverlapResult;branchIsLocal: boolean;+ shareTargetOnOriginBranch?: boolean;}| {detached: true;@@ -39,6 +41,7 @@ export type BranchInfo =shareTargetExists: boolean;dirtyConflicts: DirtyOverlapResult;branchIsLocal: boolean;+ shareTargetOnOriginBranch?: boolean;};/**@@ -142,6 +145,27 @@ export async function computeBranchInfo(.then(() => true).catch(() => false);+ // Additive HINT for the branch-switch dialog: does the share target exist at+ // `origin/<targetBranch>` per the local remote-tracking ref? Network-free —+ // the fetch that would refresh a stale ref belongs to target-status, not this+ // fast-path endpoint. `undefined` when the remote-tracking ref isn't present+ // locally (the answer is genuinely unknown until a fetch), which the dialog+ // treats the same as `false`: a hint to ask target-status, never a denial.+ const shareTargetOnOriginBranchPromise = (async (): Promise<boolean | undefined> => {+ const originRef = `origin/${targetBranch}`;+ const refPresent = await git+ .raw(['rev-parse', '--verify', originRef])+ .then(() => true)+ .catch(() => false);+ if (!refPresent) return undefined;+ // A folder-root share targets the content-root tree, which exists on every ref.+ if (kind === 'folder' && path === '') return true;+ return git+ .raw(['cat-file', '-e', `${originRef}:${path}`])+ .then(() => true)+ .catch(() => false);+ })();+// dirtyFilesOverlapWith throws when targetBranch isn't resolvable (e.g.// the share branch is not local yet). The dialog still needs the other// fields, so surface a no-conflict result in that case; the@@ -162,8 +186,7 @@ export async function computeBranchInfo(// conflict signal is preferable to crashing the whole branch-info// endpoint when only one of its four probes fails for an unrelated// reason (the other three may still be intact).- const message = err instanceof Error ? err.message : String(err);- const truncated = message.length > 500 ? `${message.slice(0, 500)}…` : message;+ const truncated = truncateError(err);console.warn(`[git-branch-info] action=dirty-overlap-failed branch=${targetBranch} error=${truncated}`,);@@ -171,12 +194,14 @@ export async function computeBranchInfo(},);- const [headState, shareTargetExists, branchIsLocal, dirtyConflicts] = await Promise.all([- headStatePromise,- shareTargetPromise,- branchIsLocalPromise,- dirtyPromise,- ]);+ const [headState, shareTargetExists, branchIsLocal, dirtyConflicts, shareTargetOnOriginBranch] =+ await Promise.all([+ headStatePromise,+ shareTargetPromise,+ branchIsLocalPromise,+ dirtyPromise,+ shareTargetOnOriginBranchPromise,+ ]);if (headState.detached) {return {@@ -186,6 +211,7 @@ export async function computeBranchInfo(shareTargetExists,dirtyConflicts,branchIsLocal,+ shareTargetOnOriginBranch,};}return {@@ -195,6 +221,7 @@ export async function computeBranchInfo(shareTargetExists,dirtyConflicts,branchIsLocal,+ shareTargetOnOriginBranch,};}@@ -213,8 +240,9 @@ export const BRANCH_INFO_HANDLER_TAG = 'git-branch-info';* mid-write) flows through to the caller's log + degrade path so it* doesn't get silently classified as "no conflict".*- * Exported for unit testing — the narrow check is the load-bearing part of- * the fix, and a regression test pins the message-shape match.+ * Exported for unit testing — the narrow check is load-bearing (a mis-scoped+ * match would silently classify a real error as "no conflict"), and a+ * regression test pins the message-shape match.*/export function isBranchResolutionError(error: unknown): boolean {const message = error instanceof Error ? error.message : String(error);diff --git a/packages/server/src/git-checkout.test.ts b/packages/server/src/git-checkout.test.tsindex c98aac4ca..d5bf356b3 100644--- a/packages/server/src/git-checkout.test.ts+++ b/packages/server/src/git-checkout.test.ts@@ -1,16 +1,18 @@-import { describe, expect, test } from 'bun:test';+import { afterEach, describe, expect, test } from 'bun:test';import { execFile } from 'node:child_process';-import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { promisify } from 'node:util';import {+ fastForwardBranchToOrigin,isBranchInOtherWorktreeError,isBranchNotFoundFetchError,runCheckoutFlow,} from './git-checkout.ts';import { createGitInstance } from './git-handle.ts';+import { createGitTriangle, type GitTriangle } from './share/git-fixture.test-helper.ts';const execFileAsync = promisify(execFile);@@ -233,3 +235,144 @@ describe('runCheckoutFlow against real git', () => {}});});++describe('fastForwardBranchToOrigin (FR9 FF-only pre-checkout update)', () => {+ const triangles: GitTriangle[] = [];+ function newTriangle(): GitTriangle {+ const t = createGitTriangle();+ triangles.push(t);+ return t;+ }+ afterEach(() => {+ for (const t of triangles.splice(0)) t.cleanup();+ });++ // Push a `feature` branch to origin, then create a LOCAL feature ref on the+ // receiver pointing at origin's initial tip — WITHOUT checking it out (the+ // receiver stays on main, so the FF must never touch the working tree).+ function setupReceiverWithLocalFeature(t: GitTriangle): string {+ t.git(t.senderDir, ['checkout', '-b', 'feature']);+ writeFileSync(join(t.senderDir, 'feat.md'), '# v1\n', 'utf-8');+ t.git(t.senderDir, ['add', '-A']);+ t.git(t.senderDir, ['commit', '-m', 'feature v1']);+ t.git(t.senderDir, ['push', 'origin', 'feature']);+ t.git(t.senderDir, ['checkout', 'main']);+ const receiver = t.cloneReceiver();+ t.git(receiver, ['branch', 'feature', 'origin/feature']);+ return receiver;+ }++ function advanceOriginFeature(t: GitTriangle): void {+ t.git(t.senderDir, ['checkout', 'feature']);+ writeFileSync(join(t.senderDir, 'feat.md'), '# v2\n', 'utf-8');+ t.git(t.senderDir, ['add', '-A']);+ t.git(t.senderDir, ['commit', '-m', 'feature v2']);+ t.git(t.senderDir, ['push', 'origin', 'feature']);+ t.git(t.senderDir, ['checkout', 'main']);+ }++ test('fast-forwardable: the local branch advances to origin, working tree untouched', async () => {+ const t = newTriangle();+ const receiver = setupReceiverWithLocalFeature(t);+ advanceOriginFeature(t);++ const outcome = await fastForwardBranchToOrigin(receiver, 'feature');+ expect(outcome).toBe('advanced');+ // The local feature ref now points at origin's advanced tip.+ expect(t.git(receiver, ['rev-parse', 'refs/heads/feature'])).toBe(+ t.git(receiver, ['rev-parse', 'refs/remotes/origin/feature']),+ );+ // The receiver never left main — the FF is a pure ref move.+ expect(t.git(receiver, ['rev-parse', '--abbrev-ref', 'HEAD'])).toBe('main');+ });++ test('diverged: refused, the local ref is untouched, no merge', async () => {+ const t = newTriangle();+ const receiver = setupReceiverWithLocalFeature(t);+ // Receiver commits its own change on feature, diverging its local history.+ t.git(receiver, ['checkout', 'feature']);+ writeFileSync(join(receiver, 'feat.md'), '# receiver-only change\n', 'utf-8');+ t.git(receiver, ['add', '-A']);+ t.git(receiver, ['commit', '-m', 'receiver diverging commit']);+ t.git(receiver, ['checkout', 'main']);+ const localBefore = t.git(receiver, ['rev-parse', 'refs/heads/feature']);+ advanceOriginFeature(t);++ const outcome = await fastForwardBranchToOrigin(receiver, 'feature');+ expect(outcome).toBe('diverged');+ // Nothing mutated — the divergent local ref stands, untouched.+ expect(t.git(receiver, ['rev-parse', 'refs/heads/feature'])).toBe(localBefore);+ });++ test('already up to date: local branch equals origin, no-op', async () => {+ const t = newTriangle();+ const receiver = setupReceiverWithLocalFeature(t);+ const outcome = await fastForwardBranchToOrigin(receiver, 'feature');+ expect(outcome).toBe('up-to-date');+ });++ test('branch not local yet: up-to-date (checkout creates it at origin tip)', async () => {+ const t = newTriangle();+ t.git(t.senderDir, ['checkout', '-b', 'feature']);+ writeFileSync(join(t.senderDir, 'feat.md'), '# v1\n', 'utf-8');+ t.git(t.senderDir, ['add', '-A']);+ t.git(t.senderDir, ['commit', '-m', 'feature v1']);+ t.git(t.senderDir, ['push', 'origin', 'feature']);+ t.git(t.senderDir, ['checkout', 'main']);+ const receiver = t.cloneReceiver();+ const outcome = await fastForwardBranchToOrigin(receiver, 'feature');+ expect(outcome).toBe('up-to-date');+ });++ test('offline: the fetch fails, unavailable, nothing mutated', async () => {+ const t = newTriangle();+ const receiver = setupReceiverWithLocalFeature(t);+ const localBefore = t.git(receiver, ['rev-parse', 'refs/heads/feature']);+ t.git(receiver, ['remote', 'remove', 'origin']);+ const outcome = await fastForwardBranchToOrigin(receiver, 'feature');+ expect(outcome).toBe('unavailable');+ expect(t.git(receiver, ['rev-parse', 'refs/heads/feature'])).toBe(localBefore);+ });++ test("fastForward:true lands the checkout on origin's advanced tip with the fresh doc", async () => {+ const t = newTriangle();+ const receiver = setupReceiverWithLocalFeature(t);+ advanceOriginFeature(t);++ const outcome = await runCheckoutFlow(receiver, 'feature', { fastForward: true });+ expect(outcome.ok).toBe(true);+ // HEAD switched to feature AND the working tree carries origin's v2 — the+ // FF advanced the stale local ref before the checkout landed on it.+ expect(t.git(receiver, ['rev-parse', '--abbrev-ref', 'HEAD'])).toBe('feature');+ expect(readFileSync(join(receiver, 'feat.md'), 'utf-8')).toBe('# v2\n');+ });++ test('fastForward:true on a diverged branch returns ff-diverged and never checks out', async () => {+ const t = newTriangle();+ const receiver = setupReceiverWithLocalFeature(t);+ t.git(receiver, ['checkout', 'feature']);+ writeFileSync(join(receiver, 'feat.md'), '# receiver-only change\n', 'utf-8');+ t.git(receiver, ['add', '-A']);+ t.git(receiver, ['commit', '-m', 'receiver diverging commit']);+ t.git(receiver, ['checkout', 'main']);+ advanceOriginFeature(t);++ const outcome = await runCheckoutFlow(receiver, 'feature', { fastForward: true });+ expect(outcome.ok).toBe(false);+ if (!outcome.ok) expect(outcome.reason).toBe('ff-diverged');+ // Checkout was NOT attempted — the receiver is still on main.+ expect(t.git(receiver, ['rev-parse', '--abbrev-ref', 'HEAD'])).toBe('main');+ });++ test('fastForward omitted does NOT advance the ref (plain checkout lands on the stale local tip)', async () => {+ const t = newTriangle();+ const receiver = setupReceiverWithLocalFeature(t);+ advanceOriginFeature(t);++ const outcome = await runCheckoutFlow(receiver, 'feature');+ expect(outcome.ok).toBe(true);+ // Without the flag the branch is not fast-forwarded, so the checkout lands+ // on the receiver's stale local tip (v1), not origin's v2.+ expect(readFileSync(join(receiver, 'feat.md'), 'utf-8')).toBe('# v1\n');+ });+});diff --git a/packages/server/src/git-checkout.ts b/packages/server/src/git-checkout.tsindex d98306649..c9609c6c4 100644--- a/packages/server/src/git-checkout.ts+++ b/packages/server/src/git-checkout.ts@@ -16,9 +16,18 @@import { realpathSync } from 'node:fs';import { type CheckoutFailureReason, isBranchNotFoundGitError } from '@inkeep/open-knowledge-core';+import { truncateError } from './error-format.ts';import { dirtyFilesOverlapWith } from './git-dirty.ts';import { createGitInstance } from './git-handle.ts';+/**+ * Block timeout for the fast-forward fetches. These run inside `withParentLock`,+ * so a hung fetch would hold the lock indefinitely — bound it (matching the+ * receive-side target-status fetch) so a stalled network degrades to+ * `unavailable` rather than wedging the checkout path.+ */+const FF_FETCH_TIMEOUT_MS = 15_000;+export type CheckoutOutcome =| { ok: true }| {@@ -42,7 +51,7 @@ export type CheckoutOutcome =* Older git (e.g. macOS system git) emits "checked out at"; newer git (e.g.* the Linux CI image) emits "used by worktree at". Matching only the former* silently drops the typed branch-in-other-worktree outcome on newer git,- * collapsing the pivot into a generic checkout-failed.+ * collapsing the in-place pivot into a generic checkout-failed.** Branch names with single quotes inside them never reach here — git refuses* to create branches with single quotes (`refname` validation). A worktree@@ -128,11 +137,27 @@ export const isBranchNotFoundFetchError = isBranchNotFoundGitError;* No internal try/catch wraps the whole flow — errors at each step are* either mapped to a typed outcome (steps 2, 4) or propagated to the* handler boundary for the catch-all 500 path.+ *+ * `opts.fastForward` prepends a fast-forward-only update of the target+ * branch's local ref to origin's tip (step 0). It runs inside the same+ * caller-held lock as the checkout so the ref move and the switch are atomic.+ * On divergence the update is refused and `ff-diverged` short-circuits the+ * flow WITHOUT checking out — the receive flow never merges. On a successful+ * advance the branch is now local, so the fetch in step 2 is skipped and the+ * dirty re-check in step 3 runs against the fast-forwarded tip.*/export async function runCheckoutFlow(projectDir: string,branch: string,+ opts?: { readonly fastForward?: boolean },): Promise<CheckoutOutcome> {+ if (opts?.fastForward) {+ const ff = await fastForwardBranchToOrigin(projectDir, branch);+ if (ff === 'diverged') {+ return { ok: false, reason: 'ff-diverged' };+ }+ }+const { git } = createGitInstance(projectDir);const branchIsLocal = await git@@ -187,9 +212,104 @@ export async function runCheckoutFlow(// gates (rev-parse, fetch, dirty-overlap) all passed, so the most likely// causes are lock contention, filesystem permissions, or partial merge// state — which are the hardest to reproduce without a stderr breadcrumb.- const message = err instanceof Error ? err.message : String(err);- const truncated = message.length > 500 ? `${message.slice(0, 500)}…` : message;+ const truncated = truncateError(err);console.warn(`[git-checkout] action=checkout-failed branch=${branch} error=${truncated}`);return { ok: false, reason: 'checkout-failed' };}}++/**+ * Outcome of {@link fastForwardBranchToOrigin}.+ *+ * - `advanced` — the local branch was fast-forwarded to origin's tip (ref move+ * only; verified by re-reading the ref).+ * - `up-to-date` — the local branch already contains origin's tip (equal, or+ * ahead with unpushed commits), or isn't local yet (checkout will create it+ * at origin's tip). Nothing to update.+ * - `diverged` — the local branch and origin have diverged (neither is an+ * ancestor of the other). REFUSED: nothing mutated. The receive flow never+ * merges — reconciliation is the sync engine's job.+ * - `unavailable` — the initial fetch failed, origin's ref couldn't be resolved+ * (offline / branch not on origin), or the fast-forward advance did not reach+ * origin's tip (a rare origin-moved-again race). Callers fall back to today's+ * behavior; any ref move that did land was still a fast-forward.+ */+export type FastForwardOutcome = 'advanced' | 'up-to-date' | 'diverged' | 'unavailable';++/**+ * Fast-forward-only pre-checkout update of a NOT-checked-out branch to origin's+ * tip. First fetches origin's branch into the remote-tracking ref (working tree+ * and `refs/heads` untouched) to learn origin's tip, then advances+ * `refs/heads/<branch>` ONLY when the local tip is a strict ancestor of it. The+ * advance is a fast-forward-only `git fetch origin <branch>:<branch>`: git+ * refuses a non-fast-forward ref update without `--force`, so even a regression+ * in the ancestry classification below could never rewrite the branch+ * non-linearly. The branch is not checked out, so the ref move never touches the+ * working tree; it is never a merge or rebase. Divergence is refused with+ * nothing mutated; the sync engine owns reconciliation.+ *+ * The advance is VERIFIED by re-reading the ref rather than trusting any exit+ * code, and the ancestry check uses `git merge-base` (which signals via stdout)+ * rather than `merge-base --is-ancestor` (exit-code-only, which simple-git+ * cannot branch on — it rejects on stderr, not exit status). merge-base also+ * distinguishes "local is ahead (up-to-date)" from "diverged (refuse)" — a+ * rejected fast-forward fetch alone cannot tell those apart.+ *+ * PRECONDITION: `branch` must not be the checked-out branch. `git` refuses to+ * move the current branch's ref this way; callers FF the TARGET branch before+ * switching to it, so it is never HEAD.+ */+export async function fastForwardBranchToOrigin(+ projectDir: string,+ branch: string,+): Promise<FastForwardOutcome> {+ const { git } = createGitInstance(projectDir, { timeoutMs: FF_FETCH_TIMEOUT_MS });++ const revParse = (ref: string): Promise<string | null> =>+ git+ .raw(['rev-parse', '--verify', ref])+ .then((sha) => sha.trim())+ .catch(() => null);++ try {+ await git.raw(['fetch', 'origin', branch]);+ } catch (err) {+ const truncated = truncateError(err);+ console.warn(`[git-checkout] action=ff-fetch-failed branch=${branch} error=${truncated}`);+ return 'unavailable';+ }++ const originTip = await revParse(`refs/remotes/origin/${branch}`);+ if (!originTip) return 'unavailable';++ const localTip = await revParse(`refs/heads/${branch}`);+ // Not local yet — checkout will create it at origin's tip; nothing to FF.+ if (!localTip || localTip === originTip) return 'up-to-date';++ // `git merge-base <a> <b>` prints the best common ancestor on stdout; when it+ // equals the local tip, local is strictly behind origin (fast-forwardable).+ const mergeBase = await git+ .raw(['merge-base', localTip, originTip])+ .then((sha) => sha.trim())+ .catch(() => '');++ if (mergeBase === localTip) {+ // Fast-forwardable. git's fetch refuses a non-fast-forward ref update, so a+ // rejection or network failure here (e.g. origin advanced to a non-FF tip+ // between the two fetches) throws and degrades to `unavailable` — never a+ // merge, never a forced move.+ try {+ await git.raw(['fetch', 'origin', `${branch}:${branch}`]);+ } catch (err) {+ const truncated = truncateError(err);+ console.warn(`[git-checkout] action=ff-advance-failed branch=${branch} error=${truncated}`);+ return 'unavailable';+ }+ const after = await revParse(`refs/heads/${branch}`);+ return after === originTip ? 'advanced' : 'unavailable';+ }+ // Local already contains origin's tip (ahead with unpushed commits).+ if (mergeBase === originTip) return 'up-to-date';+ // Genuinely diverged — refuse, mutate nothing.+ return 'diverged';+}diff --git a/packages/server/src/git-handle.ts b/packages/server/src/git-handle.tsindex f5724c88c..b3ab8f9b7 100644--- a/packages/server/src/git-handle.ts+++ b/packages/server/src/git-handle.ts@@ -38,6 +38,14 @@ interface GitHandleOptions {gitIndexFile?: string;/** gh token relayed to the credential helper via env (see {@link RelayGhToken}). */ghToken?: RelayGhToken;+ /**+ * Per-operation block timeout (ms) — simple-git kills the git child if it+ * emits no output for this long. The target-status fetch sets it so a hung+ * credentialed fetch degrades to an `unknown` verdict instead of stalling the+ * receiver's miss surface. Omitted = no timeout (the historical default that+ * the checkout/sync callers rely on).+ */+ timeoutMs?: number;}export interface GitHandle {@@ -158,7 +166,7 @@ export function applyGitEnv(* preserved through simple-git's env replacement) lives in `buildGitEnv`.*/export function createGitInstance(projectDir: string, options: GitHandleOptions = {}): GitHandle {- const { credentialArgs = [], gitIndexFile, ghToken } = options;+ const { credentialArgs = [], gitIndexFile, ghToken, timeoutMs } = options;const env: Record<string, string | undefined> = buildGitEnv(ghToken);if (gitIndexFile) {@@ -187,6 +195,7 @@ export function createGitInstance(projectDir: string, options: GitHandleOptionsbaseDir: projectDir,config: gitConfig,unsafe: { allowUnsafeCredentialHelper: true },+ ...(timeoutMs === undefined ? {} : { timeout: { block: timeoutMs } }),};const git = simpleGit(gitOptions as Partial<SimpleGitOptions>).env(env as Record<string, string>);diff --git a/packages/server/src/mcp/tools/output-schema-strictness.test.ts b/packages/server/src/mcp/tools/output-schema-strictness.test.tsindex fd70b13eb..0ad7b0aab 100644--- a/packages/server/src/mcp/tools/output-schema-strictness.test.ts+++ b/packages/server/src/mcp/tools/output-schema-strictness.test.ts@@ -342,3 +342,65 @@ describe('move outputSchema admits the cross-level skill-move payloads (CORR-1)'});}});++describe('share_link outputSchema admits the freshness success payloads (S3)', () => {+ // The `{text}`-only sweep can't catch a handler-emitted field the schema+ // omits (it never sends `freshness`), so validate the EXACT success+ // structuredContent — with and without freshness — against the compiled+ // share_link schema. A strict client (Claude/AJV) rejects the whole result+ // with "additional properties" if `freshness` isn't declared, and the agent+ // silently loses the warning it was supposed to relay.+ function shareLinkOutputJsonSchema(): Record<string, unknown> {+ const cwd = newProject();+ const captured: Array<{ name: string; outputSchema?: unknown }> = [];+ const server = {+ registerTool(name: string, cfg: { outputSchema?: unknown }) {+ captured.push({ name, outputSchema: cfg.outputSchema });+ },+ tool() {},+ } as unknown as ServerInstance;+ registerAllTools(server, {+ config: BASE_CONFIG,+ resolveCwd: async () => cwd,+ serverUrl: undefined,+ });+ const shareLink = captured.find((r) => r.name === 'share_link');+ if (!shareLink?.outputSchema) {+ throw new Error('share_link tool did not register an outputSchema');+ }+ return compileOutputSchemaForClient(shareLink.outputSchema);+ }++ const base = {+ ok: true,+ shareUrl: 'https://openknowledge.ai/d/enc',+ sharedUrl: 'https://github.com/o/r/blob/main/notes.md',+ branch: 'main',+ resolvedKind: 'doc',+ previewUrl: null,+ };+ const withFreshness = {+ ...base,+ freshness: 'stale',+ text: 'This doc has unpushed changes. Recipients will see the last pushed version.\n\nShare link for doc `notes` on branch `main`:\nhttps://openknowledge.ai/d/enc',+ };+ const withoutFreshness = {+ ...base,+ text: 'Share link for doc `notes` on branch `main`:\nhttps://openknowledge.ai/d/enc',+ };++ for (const [label, payload] of [+ ['success with freshness', withFreshness],+ ['success without freshness (happy-path passthrough)', withoutFreshness],+ ] as const) {+ test(`${label} structuredContent validates against the compiled share_link schema`, () => {+ const validator = new AjvJsonSchemaValidator();+ const validate = validator.getValidator(shareLinkOutputJsonSchema());+ const result = validate(payload) as { valid: boolean; errorMessage?: string };+ expect(result.valid).toBe(true);+ if (!result.valid) {+ expect(result.errorMessage).not.toMatch(/additional propert/i);+ }+ });+ }+});diff --git a/packages/server/src/mcp/tools/share-link.test.ts b/packages/server/src/mcp/tools/share-link.test.tsindex e4e7cb0e9..edc7649aa 100644--- a/packages/server/src/mcp/tools/share-link.test.ts+++ b/packages/server/src/mcp/tools/share-link.test.ts@@ -731,3 +731,73 @@ describe('share_link — transport / protocol error paths', () => {expect(result.content[0]?.text).toContain('unexpected share-construct-url response shape');});});++describe('share_link — freshness relay (FR6)', () => {+ test('threads a stale freshness into structuredContent and prepends the fact line', async () => {+ await writeFile(resolve(tmpDir, 'notes.md'), '# notes');+ mockResponse = { status: 200, body: { ...successBody(), freshness: 'stale' } };+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'notes' });+ expect(result.structuredContent).toMatchObject({ ok: true, freshness: 'stale' });+ expect(result.content[0]?.text).toContain('has unpushed changes');+ expect(result.content[0]?.text).toContain('Share link for doc');+ });++ test('threads an absent freshness and prepends the dead-link fact line', async () => {+ await writeFile(resolve(tmpDir, 'notes.md'), '# notes');+ mockResponse = { status: 200, body: { ...successBody(), freshness: 'absent' } };+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'notes' });+ expect(result.structuredContent).toMatchObject({ ok: true, freshness: 'absent' });+ expect(result.content[0]?.text).toContain("isn't on GitHub yet");+ });++ test('uses the "folder" word in the fact line for a folder share', async () => {+ await mkdir(resolve(tmpDir, 'guides'), { recursive: true });+ mockResponse = { status: 200, body: { ...successBody(), freshness: 'absent' } };+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'guides' });+ expect(result.content[0]?.text).toContain("This folder isn't on GitHub yet");+ });++ test('adds no warning when the target is current', async () => {+ await writeFile(resolve(tmpDir, 'notes.md'), '# notes');+ mockResponse = { status: 200, body: { ...successBody(), freshness: 'current' } };+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'notes' });+ expect(result.structuredContent).toMatchObject({ ok: true, freshness: 'current' });+ const text = result.content[0]?.text ?? '';+ expect(text).not.toContain('unpushed');+ expect(text).not.toContain("isn't on GitHub");+ expect(text.startsWith('Share link for')).toBe(true);+ });++ test('omits freshness and adds no warning when the server omits it (fail-open)', async () => {+ await writeFile(resolve(tmpDir, 'notes.md'), '# notes');+ mockResponse = { status: 200, body: successBody() };+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'notes' });+ expect(result.structuredContent).toMatchObject({ ok: true });+ expect(result.structuredContent?.freshness).toBeUndefined();+ expect(result.content[0]?.text?.startsWith('Share link for')).toBe(true);+ });++ test('tolerates an unknown freshness value: no warning, field omitted, tool still succeeds (D21)', async () => {+ await writeFile(resolve(tmpDir, 'notes.md'), '# notes');+ mockResponse = { status: 200, body: { ...successBody(), freshness: 'catching-up' } };+ const { server, getTool } = createFakeServer();+ register(server, makeDeps(baseUrl));+ const result = await getTool().handler({ path: 'notes' });+ // The core schema's value-tolerant catch coerces the unknown value to+ // undefined at parse, so the relay degrades to silence rather than a crash.+ expect(result.isError).toBeUndefined();+ expect(result.structuredContent).toMatchObject({ ok: true });+ expect(result.structuredContent?.freshness).toBeUndefined();+ expect(result.content[0]?.text?.startsWith('Share link for')).toBe(true);+ });+});diff --git a/packages/server/src/mcp/tools/share-link.ts b/packages/server/src/mcp/tools/share-link.tsindex 87da07d34..f12c53669 100644--- a/packages/server/src/mcp/tools/share-link.ts+++ b/packages/server/src/mcp/tools/share-link.ts@@ -18,6 +18,7 @@ import { join } from 'node:path';import {type ShareConstructUrlErrorCode,ShareConstructUrlResponseSchema,+ type ShareFreshness,} from '@inkeep/open-knowledge-core';import { z } from 'zod';import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';@@ -62,6 +63,24 @@ interface ShareLinkSuccess {sharedUrl: string;branch: string;resolvedKind: ShareKind;+ freshness?: ShareFreshness;+}++/**+ * The relayable warning an agent prepends to a share link when the target+ * isn't current on origin — the `share_link` mirror of the popover's fact line+ * (kind substitutes doc/folder). `current` and `undefined` (the fail-open and+ * unknown-value cases) get no warning, so an older client that can't interpret+ * a newer freshness value degrades to silence rather than a bad relay.+ */+function freshnessWarning(freshness: ShareFreshness | undefined, kind: ShareKind): string {+ if (freshness === 'absent') {+ return `This ${kind} isn't on GitHub yet. The link won't work until it's pushed.\n\n`;+ }+ if (freshness === 'stale') {+ return `This ${kind} has unpushed changes. Recipients will see the last pushed version.\n\n`;+ }+ return '';}/**@@ -266,6 +285,12 @@ const OutputSchema = outputSchemaWithText({.enum(['doc', 'folder']).optional().describe('Kind the target resolved to (success only).'),+ freshness: z+ .enum(['current', 'stale', 'absent'])+ .optional()+ .describe(+ 'Whether the shared target matches origin (success only): current, stale (unpushed edits), or absent (not on origin). Omitted when the probe could not run.',+ ),error: z.enum(['no-remote',@@ -432,13 +457,16 @@ export function register(server: ServerInstance, deps: ShareLinkDeps): void {return textPlusStructured(`Error: ${message}`, structured, true);}- const { shareUrl, sharedUrl, branch } = body;+ const { shareUrl, sharedUrl, branch, freshness } = body;const structured: ShareLinkSuccess = {ok: true,shareUrl,sharedUrl,branch,resolvedKind: resolved.kind,+ // Omit rather than emit `undefined` so the fail-open / unknown-value+ // case leaves the field absent (the outputSchema declares it optional).+ ...(freshness ? { freshness } : {}),};// Preview hint is route-only and symmetric across kinds: a doc previews// at `/#/<doc>`, a folder at `/#/<folderPath>/` (`/#/` for the@@ -460,8 +488,11 @@ export function register(server: ServerInstance, deps: ShareLinkDeps): void {preview = { ...preview, url: folderRoute };}const displayPath = args.path === '' ? '(content root)' : args.path;+ // Prepend the freshness fact line so an agent relays the same caution a+ // human would see in the popover before handing over a stale/dead link.+ const warning = freshnessWarning(freshness, resolved.kind);return textPlusStructured(- `Share link for ${resolved.kind} \`${displayPath}\` on branch \`${branch}\`:\n${shareUrl}`,+ `${warning}Share link for ${resolved.kind} \`${displayPath}\` on branch \`${branch}\`:\n${shareUrl}`,{...structured,previewUrl: preview?.url ?? null,diff --git a/packages/server/src/share/construct-url.ts b/packages/server/src/share/construct-url.tsindex 9dd855073..efa33df8e 100644--- a/packages/server/src/share/construct-url.ts+++ b/packages/server/src/share/construct-url.ts@@ -8,7 +8,7 @@* focused unit tests in the integration suite at `./construct-url.test.ts`.*/-import type { ShareConstructUrlErrorCode } from '@inkeep/open-knowledge-core';+import type { ShareConstructUrlErrorCode, ShareFreshness } from '@inkeep/open-knowledge-core';import { getLogger } from '../logger.ts';/**@@ -101,22 +101,25 @@ export function buildGitHubTreeUrl(/*** Emit one structured ops log line per request. All fields are non-PII (no- * project path, no doc filename, no URL bytes). `kind` is a bounded enum- * (`'doc' | 'folder'`) so it's safe as a span/log attribute per the- * cardinality STOP rule.+ * project path, no doc filename, no URL bytes). `kind` (`'doc' | 'folder'`)+ * and `freshness` (`'current' | 'stale' | 'absent'`) are bounded enums, so+ * they're safe as span/log attributes per the cardinality STOP rule.+ * `freshness` is omitted when the probe couldn't run (fail-open).*/export function emitShareConstructUrlLog(result: 'ok' | ShareConstructUrlErrorCode,- opts?: { branchExists?: boolean; kind?: 'doc' | 'folder' },+ opts?: { branchExists?: boolean; kind?: 'doc' | 'folder'; freshness?: ShareFreshness },): void {const branchExists = opts?.branchExists;const kind = opts?.kind;+ const freshness = opts?.freshness;getLogger('share').info({action: 'construct-url',result,...(branchExists === undefined ? {} : { branchExists }),...(kind === undefined ? {} : { kind }),+ ...(freshness === undefined ? {} : { freshness }),},'share action',);diff --git a/packages/server/src/share/endpoint-http.test-helper.ts b/packages/server/src/share/endpoint-http.test-helper.tsnew file mode 100644index 000000000..ba7dc9fc9--- /dev/null+++ b/packages/server/src/share/endpoint-http.test-helper.ts@@ -0,0 +1,74 @@+/**+ * Boot the real HTTP API extension (the Hocuspocus `onRequest` pipeline) rooted+ * at a caller-provided `projectDir`, on a loopback-bound ephemeral port.+ *+ * This is the reusable half of construct-url.test.ts's `bootRig`. The difference+ * that matters: `bootRig` manufactures a synthetic `projectDir` and seeds a fake+ * `.git` (enough for the branch-level URL gates, which never touch a real+ * remote). The share-receive endpoints — target-status and branch-info — run an+ * actual credentialed `git fetch` and remote-tracking-ref probes, so they need a+ * REAL git working tree. Callers pass one (a `createGitTriangle` receiver clone+ * or sender) and drive the endpoints over HTTP against it.+ */+import { createServer, type Server } from 'node:http';++export interface EndpointRig {+ port: number;+ cleanup: () => Promise<void>;+}++/**+ * Boot the API extension against `projectDir`. `contentDir` defaults to+ * `projectDir` (the dominant `content.dir === '.'` layout, which is what the+ * git-triangle fixtures produce). Binds 127.0.0.1 explicitly so the OS picks a+ * port free on the family the client uses — a bare `listen(0)` binds dual-stack+ * `::` and can collide with a foreign v4 listener under parallel load (the same+ * reasoning `bootRig` documents).+ */+export async function bootEndpointServer(opts: {+ projectDir: string;+ contentDir?: string;+}): Promise<EndpointRig> {+ const { projectDir } = opts;+ const contentDir = opts.contentDir ?? projectDir;++ const { Hocuspocus } = await import('@hocuspocus/server');+ const { AgentSessionManager } = await import('../agent-sessions.ts');+ const { createApiExtension } = await import('../api-extension.ts');++ const hocuspocus = new Hocuspocus({ quiet: true });+ const sessionManager = new AgentSessionManager(hocuspocus);+ const ext = createApiExtension({+ hocuspocus,+ sessionManager,+ contentDir,+ projectDir,+ getFileIndex: () => new Map(),+ serverInstanceId: 'test-instance',+ });+ hocuspocus.configuration.extensions.push(ext);++ const server: Server = createServer((req, res) => {+ // biome-ignore lint/suspicious/noExplicitAny: test harness+ hocuspocus.hooks('onRequest', { request: req, response: res } as any).catch(() => {+ if (!res.writableEnded) {+ res.writeHead(500);+ res.end('Error');+ }+ });+ });++ const port = await new Promise<number>((resolveListen) => {+ server.listen(0, '127.0.0.1', () => {+ const addr = server.address();+ resolveListen(typeof addr === 'object' && addr ? addr.port : 0);+ });+ });++ return {+ port,+ cleanup: async () => {+ await new Promise<void>((res) => server.close(() => res()));+ },+ };+}diff --git a/packages/server/src/share/endpoint-real-git.test.ts b/packages/server/src/share/endpoint-real-git.test.tsnew file mode 100644index 000000000..ddc8fadaf--- /dev/null+++ b/packages/server/src/share/endpoint-real-git.test.ts@@ -0,0 +1,199 @@+/**+ * The first tests in the repo that drive a git fetch THROUGH an HTTP endpoint:+ * construct-url's real-HTTP boot harness composed with the real-git triangle+ * fixture. `POST /api/share/target-status` and `GET /api/git/branch-info` run+ * their actual fetch + remote-tracking-ref probes against a receiver clone, so+ * the endpoint wiring (routing, request validation, content-relative path+ * mapping, response serialization) is exercised at production fidelity rather+ * than mocked. All local (bare origin on the same filesystem) — no network, so+ * they run unskipped in the default test tier.+ */++import { afterEach, describe, expect, test } from 'bun:test';+import { createServer as createHttpServer } from 'node:http';+import type { AddressInfo, Socket } from 'node:net';+import { bootEndpointServer, type EndpointRig } from './endpoint-http.test-helper.ts';+import { createGitTriangle, type GitTriangle } from './git-fixture.test-helper.ts';+import { computeShareTargetStatus } from './target-status.ts';++const triangles: GitTriangle[] = [];+function newTriangle(): GitTriangle {+ const t = createGitTriangle();+ triangles.push(t);+ return t;+}++let rig: EndpointRig | undefined;++afterEach(async () => {+ if (rig) {+ await rig.cleanup();+ rig = undefined;+ }+ for (const t of triangles.splice(0)) t.cleanup();+});++async function postTargetStatus(port: number, body: unknown): Promise<Response> {+ return fetch(`http://127.0.0.1:${port}/api/share/target-status`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });+}++async function getBranchInfo(+ port: number,+ query: { branch: string; path: string; kind: 'doc' | 'folder' },+): Promise<Response> {+ const params = new URLSearchParams(query);+ return fetch(`http://127.0.0.1:${port}/api/git/branch-info?${params.toString()}`);+}++describe('POST /api/share/target-status (fetch through the endpoint)', () => {+ test('a recently-pushed doc the receiver ref does not know is on-origin after the endpoint fetch', async () => {+ const t = newTriangle();+ t.seedAndPush('doc1.md', 'one\n');+ const receiver = t.cloneReceiver();+ // Pushed AFTER the clone: the receiver's origin ref is stale and does not+ // know doc2 yet. Only the endpoint's own fetch can reveal it — without the+ // fetch this would classify as never-on-branch.+ t.seedAndPush('doc2.md', 'two\n');++ rig = await bootEndpointServer({ projectDir: receiver });+ const res = await postTargetStatus(rig.port, {+ branch: t.branch,+ path: 'doc2.md',+ kind: 'doc',+ });++ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ verdict: 'on-origin' });+ });++ test('a renamed target returns renamed with the new path carried over the wire', async () => {+ const t = newTriangle();+ t.seedAndPush('old.md', '# stable content that survives the move intact\n');+ const receiver = t.cloneReceiver();+ t.renameOnOrigin('old.md', 'new.md');++ rig = await bootEndpointServer({ projectDir: receiver });+ const res = await postTargetStatus(rig.port, { branch: t.branch, path: 'old.md', kind: 'doc' });++ expect(res.status).toBe(200);+ // renamedTo survives the discriminated-union response serialization.+ expect(await res.json()).toEqual({ verdict: 'renamed', renamedTo: 'new.md' });+ });++ test('an unreachable origin degrades to unknown (fail-open through the endpoint)', async () => {+ const t = newTriangle();+ t.seedAndPush('doc.md', 'one\n');+ const receiver = t.cloneReceiver();+ // No reachable origin — the endpoint's fetch fails fast and the handler+ // falls open to today's guidance rather than 500ing the miss surface.+ t.git(receiver, ['remote', 'remove', 'origin']);++ rig = await bootEndpointServer({ projectDir: receiver });+ const res = await postTargetStatus(rig.port, { branch: t.branch, path: 'doc.md', kind: 'doc' });++ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ verdict: 'unknown' });+ });+});++describe('POST /api/share/target-status path validation', () => {+ test('a traversal path is rejected with 400 before it reaches git', async () => {+ const t = newTriangle();+ t.seedAndPush('doc.md', 'one\n');+ const receiver = t.cloneReceiver();+ rig = await bootEndpointServer({ projectDir: receiver });++ const res = await postTargetStatus(rig.port, {+ branch: t.branch,+ path: '../etc/passwd',+ kind: 'doc',+ });++ // Malformed paths are refused at the handler boundary (parity with the+ // sibling share handlers) — a degraded verdict is never computed for them.+ expect(res.status).toBe(400);+ });++ test('an empty path for a doc is rejected with 400 (folder-root sentinel is folder-only)', async () => {+ const t = newTriangle();+ t.seedAndPush('doc.md', 'one\n');+ const receiver = t.cloneReceiver();+ rig = await bootEndpointServer({ projectDir: receiver });++ const res = await postTargetStatus(rig.port, { branch: t.branch, path: '', kind: 'doc' });++ expect(res.status).toBe(400);+ });+});++describe('GET /api/git/branch-info (shareTargetOnOriginBranch over HTTP)', () => {+ test('surfaces the network-free origin-branch probe: present is true, absent is false', async () => {+ const t = newTriangle();+ t.seedAndPush('present.md', '# here\n');+ const receiver = t.cloneReceiver();+ rig = await bootEndpointServer({ projectDir: receiver });++ const present = await getBranchInfo(rig.port, {+ branch: t.branch,+ path: 'present.md',+ kind: 'doc',+ });+ expect(present.status).toBe(200);+ expect((await present.json()).shareTargetOnOriginBranch).toBe(true);++ const absent = await getBranchInfo(rig.port, {+ branch: t.branch,+ path: 'absent.md',+ kind: 'doc',+ });+ expect(absent.status).toBe(200);+ expect((await absent.json()).shareTargetOnOriginBranch).toBe(false);+ });+});++describe('target-status fetch timeout', () => {+ test('a hanging credentialed fetch is bounded by the block timeout and degrades to unknown', async () => {+ const t = newTriangle();+ t.seedAndPush('doc.md', 'one\n');+ const receiver = t.cloneReceiver();++ // A black-hole HTTP origin accepts git's info/refs request and never+ // responds, so the fetch hangs with no output — exactly the stall the block+ // timeout exists to bound. The endpoint handler hardcodes the 15s default,+ // so the timeout knob is exercised here at the compute layer; the handler's+ // fail-open catch is covered by the offline test above.+ const sockets = new Set<Socket>();+ const blackhole = createHttpServer(() => {+ // intentionally never responds+ });+ blackhole.on('connection', (s) => {+ sockets.add(s);+ s.on('close', () => sockets.delete(s));+ });+ await new Promise<void>((r) => blackhole.listen(0, '127.0.0.1', () => r()));+ const bhPort = (blackhole.address() as AddressInfo).port;+ t.git(receiver, ['remote', 'set-url', 'origin', `http://127.0.0.1:${bhPort}/repo.git`]);++ try {+ const start = performance.now();+ const status = await computeShareTargetStatus(receiver, t.branch, 'doc.md', 'doc', {+ fetchTimeoutMs: 2000,+ });+ const elapsed = performance.now() - start;+ expect(status.verdict).toBe('unknown');+ // The band proves the timeout actually engaged rather than the test being+ // an offline fast-fail in disguise: git hung on the black hole for roughly+ // the injected budget (lower bound), and the injected budget — not the 15s+ // default — is what released it (upper bound).+ expect(elapsed).toBeGreaterThanOrEqual(1500);+ expect(elapsed).toBeLessThan(10_000);+ } finally {+ for (const s of sockets) s.destroy();+ await new Promise<void>((r) => blackhole.close(() => r()));+ }+ }, 30_000);+});diff --git a/packages/server/src/share/freshness.test.ts b/packages/server/src/share/freshness.test.tsnew file mode 100644index 000000000..f88f6b161--- /dev/null+++ b/packages/server/src/share/freshness.test.ts@@ -0,0 +1,116 @@+/**+ * Freshness verdicts verified against the real-git S1 fixture — one case+ * per drift cell, no mocks. The fail-open cases are behavioral pins: a probe+ * that can't run returns `undefined` (the share still ships) rather than a+ * wrong verdict or a throw.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { computeShareFreshness } from './freshness.ts';+import { createGitTriangle, type GitTriangle } from './git-fixture.test-helper.ts';++const triangles: GitTriangle[] = [];+const scratchDirs: string[] = [];++function newTriangle(): GitTriangle {+ const t = createGitTriangle();+ triangles.push(t);+ return t;+}++afterEach(() => {+ for (const t of triangles.splice(0)) t.cleanup();+ for (const d of scratchDirs.splice(0)) rmSync(d, { recursive: true, force: true });+});++describe('computeShareFreshness — doc drift cells', () => {+ test('a clean pushed doc is current', async () => {+ const t = newTriangle();+ t.seedAndPush('doc.md', '# hello\n');+ expect(await computeShareFreshness(t.senderDir, t.branch, 'doc.md', 'doc')).toBe('current');+ });++ test('an untracked doc is absent', async () => {+ const t = newTriangle();+ t.writeWorkingTree('new.md', '# never saved\n');+ expect(await computeShareFreshness(t.senderDir, t.branch, 'new.md', 'doc')).toBe('absent');+ });++ test('an uncommitted edit of a pushed doc is stale', async () => {+ const t = newTriangle();+ t.seedAndPush('doc.md', 'v1\n');+ t.writeWorkingTree('doc.md', 'v2 edited, not committed\n');+ expect(await computeShareFreshness(t.senderDir, t.branch, 'doc.md', 'doc')).toBe('stale');+ });++ test('a committed-but-unpushed edit is stale', async () => {+ const t = newTriangle();+ t.seedAndPush('doc.md', 'v1\n');+ t.commitWithoutPush('doc.md', 'v2 committed, not pushed\n');+ expect(await computeShareFreshness(t.senderDir, t.branch, 'doc.md', 'doc')).toBe('stale');+ });++ test('a clean pushed symlink doc is current', async () => {+ const t = newTriangle();+ t.seedSymlinkAndPush('link.md', 'target.md', '# target\n');+ expect(await computeShareFreshness(t.senderDir, t.branch, 'link.md', 'doc')).toBe('current');+ });+});++describe('computeShareFreshness — folder drift cells', () => {+ test('a clean pushed folder is current', async () => {+ const t = newTriangle();+ t.seedAndPush('docs/a.md', 'a\n');+ expect(await computeShareFreshness(t.senderDir, t.branch, 'docs', 'folder')).toBe('current');+ });++ test('an untracked file inside a pushed folder makes the folder stale', async () => {+ const t = newTriangle();+ t.seedAndPush('docs/a.md', 'a\n');+ t.writeWorkingTree('docs/new.md', 'brand new, unstaged\n');+ expect(await computeShareFreshness(t.senderDir, t.branch, 'docs', 'folder')).toBe('stale');+ });++ test('a folder never pushed to origin is absent', async () => {+ const t = newTriangle();+ t.writeWorkingTree('drafts/x.md', 'unstaged\n');+ expect(await computeShareFreshness(t.senderDir, t.branch, 'drafts', 'folder')).toBe('absent');+ });+});++describe('computeShareFreshness — content-root folder share (empty path)', () => {+ test('a clean content root is current (root tree exists; pathspec falls back to ".")', async () => {+ const t = newTriangle();+ expect(await computeShareFreshness(t.senderDir, t.branch, '', 'folder')).toBe('current');+ });++ test('an uncommitted edit anywhere under the content root is stale', async () => {+ const t = newTriangle();+ t.writeWorkingTree('README.md', '# base changed, not committed\n');+ expect(await computeShareFreshness(t.senderDir, t.branch, '', 'folder')).toBe('stale');+ });++ test('a new untracked file at the content root is stale', async () => {+ const t = newTriangle();+ t.writeWorkingTree('loose.md', 'untracked at root\n');+ expect(await computeShareFreshness(t.senderDir, t.branch, '', 'folder')).toBe('stale');+ });+});++describe('computeShareFreshness — fail-open', () => {+ test('a non-git directory omits freshness (returns undefined, does not throw)', async () => {+ const notARepo = mkdtempSync(join(tmpdir(), 'ok-share-not-a-repo-'));+ scratchDirs.push(notARepo);+ expect(await computeShareFreshness(notARepo, 'main', 'doc.md', 'doc')).toBeUndefined();+ });++ test('an unresolvable branch ref omits freshness rather than guessing', async () => {+ const t = newTriangle();+ t.seedAndPush('doc.md', 'v1\n');+ expect(+ await computeShareFreshness(t.senderDir, 'branch-that-was-never-pushed', 'doc.md', 'doc'),+ ).toBeUndefined();+ });+});diff --git a/packages/server/src/share/freshness.ts b/packages/server/src/share/freshness.tsnew file mode 100644index 000000000..743739aa0--- /dev/null+++ b/packages/server/src/share/freshness.ts@@ -0,0 +1,82 @@+/**+ * Send-side freshness probe for `POST /api/share/construct-url`: does the+ * shared target match what origin has? Three local-only git reads against+ * `refs/remotes/origin/<branch>` — never a fetch — run in parallel and combine+ * into `current` / `stale` / `absent`.+ *+ * simple-git's `raw` rejects on non-empty stderr, not on exit code (see+ * `git-branch-info.ts`), so the exit-1 `diff --quiet` from the verified recipe+ * cannot be branched on here — `diff --name-only` carries the same "does the+ * working tree differ from the ref" signal in stdout instead. `cat-file -e`+ * DOES reject (its miss writes stderr), so a fail-fast `rev-parse` of the ref+ * first lets a later `cat-file` rejection mean "path absent" rather than "git+ * broke"; the broken-git case throws past the probes and omits freshness.+ */+import type { ShareFreshness } from '@inkeep/open-knowledge-core';+import { truncateError } from '../error-format.ts';+import { createGitInstance } from '../git-handle.ts';+import { getLogger } from '../logger.ts';++/**+ * Block timeout for the local freshness reads. They are local-only (no fetch),+ * so this never fires in normal use; it backstops a pathologically stuck git+ * (huge repo, index-lock contention) from blocking the interactive Share click+ * with no wall-clock bound. A timeout throws past the probes → freshness omitted+ * (fail-open), matching the target-status fetch's block-timeout precedent.+ */+const FRESHNESS_PROBE_TIMEOUT_MS = 5_000;++/**+ * Compute freshness for the shared target at `gitPath` (repo-root-relative)+ * against `refs/remotes/origin/<branch>`. Returns `undefined` — the field is+ * omitted — whenever any probe fails, so a probe never turns a working share+ * into a broken one (fail-open); the caller ships the URL regardless.+ *+ * `gitPath === ''` is the content-root folder share: the empty path is the+ * root tree for the existence probe (`<ref>:`), but an empty pathspec is fatal+ * to `diff` / `status`, which fall back to `.`.+ */+export async function computeShareFreshness(+ projectDir: string,+ branch: string,+ gitPath: string,+ kind: 'doc' | 'folder',+): Promise<ShareFreshness | undefined> {+ try {+ const { git } = createGitInstance(projectDir, { timeoutMs: FRESHNESS_PROBE_TIMEOUT_MS });+ const ref = `refs/remotes/origin/${branch}`;++ // Fail-fast: the git binary works AND the remote-tracking ref resolves.+ // After this, a `cat-file` rejection can only mean the path is absent from+ // the ref — not that git itself failed.+ await git.raw(['rev-parse', '--verify', ref]);++ const pathspec = gitPath === '' ? '.' : gitPath;++ const [present, trackedDiff, untracked] = await Promise.all([+ git+ .raw(['cat-file', '-e', `${ref}:${gitPath}`])+ .then(() => true)+ .catch(() => false),+ git.raw(['diff', '--name-only', ref, '--', pathspec]),+ git.raw(['status', '--porcelain', '--untracked-files=all', '--', pathspec]),+ ]);++ if (!present) return 'absent';+ // Tracked drift (committed-unpushed or uncommitted) surfaces in the diff;+ // a brand-new untracked file beneath a shared folder surfaces only in+ // status. Either makes the recipient's copy differ from what they'd see.+ if (trackedDiff.trim() !== '' || untracked.trim() !== '') return 'stale';+ return 'current';+ } catch (err) {+ // Keep the error identity (bounded) so a "freshness always missing" report+ // can be triaged — matching the truncated-message pattern the sibling+ // git-branch-info / git-checkout fail-open catches use.+ const truncated = truncateError(err);+ getLogger('share').warn(+ { action: 'freshness-probe-failed', kind, error: truncated },+ '[share] freshness probe failed; omitting freshness',+ );+ return undefined;+ }+}diff --git a/packages/server/src/share/git-fixture.test-helper.ts b/packages/server/src/share/git-fixture.test-helper.tsnew file mode 100644index 000000000..301469f70--- /dev/null+++ b/packages/server/src/share/git-fixture.test-helper.ts@@ -0,0 +1,237 @@+/**+ * Real-git test substrate for the share freshness (send) and target-status+ * (receive) paths: a sender working tree, a bare origin, and a lazily-cloned+ * receiver, driven through the actual `git` binary.+ *+ * Every git call goes through synchronous `execFileSync`. The async+ * `simple-git`-based sibling fixture (`setupDivergence` in+ * `sync-engine.test.ts`) is skipped on CI because Bun fails to reap async git+ * children on the GHA ubuntu runners (oven-sh/bun#11892); a synchronous+ * subprocess never leaves a child for Bun to reap, so a triangle built this way+ * runs unskipped in the default test tier — the whole point of this helper.+ *+ * The primitives are deliberately small and compose into the freshness drift+ * cells rather than enumerating one method per cell:+ * - `seedAndPush` -> the target is on origin and clean (current)+ * - `writeWorkingTree` -> unstaged write: a NEW path is absent; overwriting+ * a seeded path (or adding a file under a seeded+ * folder) is stale+ * - `commitWithoutPush` -> a seeded path edited + committed but not pushed+ * is stale (origin keeps the old blob)+ * and the receive-side legs (`renameOnOrigin` / `renameFolderOnOrigin` /+ * `deleteOnOrigin`) advance origin so a receiver clone observes the move.+ * `deleteInReceiverWorkingTree` / `renameInReceiverWorkingTree` mutate the+ * receiver's OWN working tree WITHOUT committing — the local-change case a miss+ * verdict must read as `changed-locally`, not "behind — pull".+ */+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, relative } from 'node:path';++export interface GitTriangle {+ readonly senderDir: string;+ readonly originDir: string;+ readonly branch: string;+ /** Run git in an arbitrary repo dir; returns trimmed stdout, throws on non-zero exit. */+ git(cwd: string, args: string[]): string;+ /** Sender: write + stage + commit + push. The target lands on origin, clean. */+ seedAndPush(relPath: string, content: string): void;+ /**+ * Sender: seed a symlink (`linkRel` -> `targetRel`) plus its target, then+ * push both. The link is stored as a symlink blob (mode 120000), the state a+ * freshness probe must read as `current` when only the link is shared.+ */+ seedSymlinkAndPush(linkRel: string, targetRel: string, targetContent: string): void;+ /**+ * Sender: write to the working tree WITHOUT staging. A path never seeded is+ * absent from origin; overwriting a seeded path, or adding a file beneath a+ * seeded folder, is stale.+ */+ writeWorkingTree(relPath: string, content: string): void;+ /** Sender: overwrite + commit a seeded path but do NOT push (origin keeps the old blob). */+ commitWithoutPush(relPath: string, content: string): void;+ /** Sender -> origin: `git mv` a file + commit + push (origin gains `newRel`, loses `oldRel`). */+ renameOnOrigin(oldRel: string, newRel: string): void;+ /** Sender -> origin: `git mv` a whole folder + commit + push. */+ renameFolderOnOrigin(oldFolderRel: string, newFolderRel: string): void;+ /**+ * Sender -> origin: introduce a rename as part of a MERGE commit (an "evil+ * merge") so `git log -1 -- <oldRel>` returns the merge itself. The merge's+ * bare `diff-tree` is combined-format; this exercises the first-parent diff+ * that keeps the rename readable instead of misclassifying it as deleted.+ */+ mergeRenameOnOrigin(oldRel: string, newRel: string): void;+ /**+ * Sender -> origin: `git mv` several files to DIFFERENT destinations in ONE+ * commit + push. Used to reproduce a split-folder rename (files under one+ * prefix scatter to multiple new prefixes) so the removing commit's diff+ * carries R rows with inconsistent destinations.+ */+ splitRenameOnOrigin(pairs: ReadonlyArray<readonly [string, string]>): void;+ /** Sender -> origin: `git rm` + commit + push. */+ deleteOnOrigin(relPath: string): void;+ /**+ * Receiver working tree: delete a tracked path WITHOUT committing (a local+ * `rm`). The path stays in the receiver's committed HEAD but vanishes from the+ * working tree — the "changed locally" case a share-receive miss must NOT+ * report as "behind — pull". Requires `cloneReceiver()` first.+ */+ deleteInReceiverWorkingTree(relPath: string): void;+ /**+ * Receiver working tree: rename a tracked path WITHOUT committing (a local+ * `mv`). Like `deleteInReceiverWorkingTree`, the OLD path is gone from the+ * working tree but still in HEAD, so a miss on the old path is+ * `changed-locally`. Requires `cloneReceiver()` first.+ */+ renameInReceiverWorkingTree(oldRel: string, newRel: string): void;+ /** Clone origin into a fresh receiver dir (idempotent; returns the same dir on repeat). */+ cloneReceiver(): string;+ /** Remove every temp repo this triangle created. */+ cleanup(): void;+}++export function createGitTriangle(opts: { branch?: string } = {}): GitTriangle {+ const branch = opts.branch ?? 'main';+ const senderDir = mkdtempSync(join(tmpdir(), 'ok-share-sender-'));+ const originDir = mkdtempSync(join(tmpdir(), 'ok-share-origin-'));+ let receiverDir: string | null = null;++ const git = (cwd: string, args: string[]): string =>+ // Capture stderr (push/clone progress) instead of inheriting it, so a+ // passing run leaves the test log clean; a failure still surfaces it on the+ // thrown error's `.stderr`.+ execFileSync('git', args, {+ cwd,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'pipe'],+ }).trim();++ const configure = (dir: string): void => {+ git(dir, ['config', 'user.name', 'Fixture User']);+ git(dir, ['config', 'user.email', '[email protected]']);+ // gpg signing from a host/global config would make commits fail in the fixture.+ git(dir, ['config', 'commit.gpgsign', 'false']);+ };++ const writeFile = (dir: string, relPath: string, content: string): void => {+ const abs = join(dir, relPath);+ mkdirSync(dirname(abs), { recursive: true });+ writeFileSync(abs, content, 'utf-8');+ };++ const commitPush = (relPaths: string[], message: string): void => {+ git(senderDir, ['add', '--', ...relPaths]);+ git(senderDir, ['commit', '-m', message]);+ git(senderDir, ['push', 'origin', branch]);+ };++ // Bare origin + sender with one base commit so origin/<branch> exists and the+ // branch-on-origin gate upstream of every probe passes.+ git(originDir, ['init', '--bare', '-b', branch]);+ git(senderDir, ['init', '-b', branch]);+ configure(senderDir);+ writeFile(senderDir, '.ok/config.yml', '');+ writeFile(senderDir, 'README.md', '# base\n');+ git(senderDir, ['add', '-A']);+ git(senderDir, ['commit', '-m', 'seed base']);+ git(senderDir, ['remote', 'add', 'origin', originDir]);+ git(senderDir, ['push', '--set-upstream', 'origin', branch]);++ return {+ senderDir,+ originDir,+ branch,+ git,+ seedAndPush(relPath, content) {+ writeFile(senderDir, relPath, content);+ commitPush([relPath], `seed ${relPath}`);+ },+ seedSymlinkAndPush(linkRel, targetRel, targetContent) {+ writeFile(senderDir, targetRel, targetContent);+ const linkAbs = join(senderDir, linkRel);+ mkdirSync(dirname(linkAbs), { recursive: true });+ // Relative target so the symlink resolves regardless of where the tmp+ // repo lives, and git stores the link-target string verbatim.+ symlinkSync(relative(dirname(linkAbs), join(senderDir, targetRel)), linkAbs);+ commitPush([targetRel, linkRel], `seed symlink ${linkRel}`);+ },+ writeWorkingTree(relPath, content) {+ writeFile(senderDir, relPath, content);+ },+ commitWithoutPush(relPath, content) {+ writeFile(senderDir, relPath, content);+ git(senderDir, ['add', '--', relPath]);+ git(senderDir, ['commit', '-m', `edit ${relPath} (unpushed)`]);+ },+ renameOnOrigin(oldRel, newRel) {+ mkdirSync(dirname(join(senderDir, newRel)), { recursive: true });+ git(senderDir, ['mv', oldRel, newRel]);+ git(senderDir, ['commit', '-m', `rename ${oldRel} -> ${newRel}`]);+ git(senderDir, ['push', 'origin', branch]);+ },+ renameFolderOnOrigin(oldFolderRel, newFolderRel) {+ mkdirSync(dirname(join(senderDir, newFolderRel)), { recursive: true });+ git(senderDir, ['mv', oldFolderRel, newFolderRel]);+ git(senderDir, ['commit', '-m', `rename folder ${oldFolderRel} -> ${newFolderRel}`]);+ git(senderDir, ['push', 'origin', branch]);+ },+ mergeRenameOnOrigin(oldRel, newRel) {+ // Side branch gets an unrelated commit so the merge can't fast-forward.+ git(senderDir, ['checkout', '-b', 'ok-merge-side']);+ writeFile(senderDir, 'SIDE.md', '# side\n');+ git(senderDir, ['add', '--', 'SIDE.md']);+ git(senderDir, ['commit', '-m', 'side: unrelated change']);+ // Main also diverges, forcing a real (--no-ff) merge commit.+ git(senderDir, ['checkout', branch]);+ writeFile(senderDir, 'MAIN.md', '# main\n');+ git(senderDir, ['add', '--', 'MAIN.md']);+ git(senderDir, ['commit', '-m', 'main: unrelated change']);+ // Stage the merge, then rename the shared path INSIDE the merge before+ // committing: the rename belongs to the merge commit, not either parent,+ // so history simplification returns the merge for `git log -- <oldRel>`.+ git(senderDir, ['merge', '--no-ff', '--no-commit', 'ok-merge-side']);+ mkdirSync(dirname(join(senderDir, newRel)), { recursive: true });+ git(senderDir, ['mv', oldRel, newRel]);+ git(senderDir, ['commit', '--no-edit']);+ git(senderDir, ['push', 'origin', branch]);+ },+ splitRenameOnOrigin(pairs) {+ for (const [oldRel, newRel] of pairs) {+ mkdirSync(dirname(join(senderDir, newRel)), { recursive: true });+ git(senderDir, ['mv', oldRel, newRel]);+ }+ git(senderDir, ['commit', '-m', `split rename ${pairs.map(([o]) => o).join(', ')}`]);+ git(senderDir, ['push', 'origin', branch]);+ },+ deleteOnOrigin(relPath) {+ git(senderDir, ['rm', '--', relPath]);+ git(senderDir, ['commit', '-m', `delete ${relPath}`]);+ git(senderDir, ['push', 'origin', branch]);+ },+ deleteInReceiverWorkingTree(relPath) {+ if (!receiverDir)+ throw new Error('cloneReceiver() must run before deleteInReceiverWorkingTree');+ rmSync(join(receiverDir, relPath), { force: true });+ },+ renameInReceiverWorkingTree(oldRel, newRel) {+ if (!receiverDir)+ throw new Error('cloneReceiver() must run before renameInReceiverWorkingTree');+ mkdirSync(dirname(join(receiverDir, newRel)), { recursive: true });+ renameSync(join(receiverDir, oldRel), join(receiverDir, newRel));+ },+ cloneReceiver() {+ if (receiverDir) return receiverDir;+ const dir = mkdtempSync(join(tmpdir(), 'ok-share-receiver-'));+ git(dir, ['clone', originDir, '.']);+ configure(dir);+ receiverDir = dir;+ return dir;+ },+ cleanup() {+ rmSync(senderDir, { recursive: true, force: true });+ rmSync(originDir, { recursive: true, force: true });+ if (receiverDir) rmSync(receiverDir, { recursive: true, force: true });+ },+ };+}diff --git a/packages/server/src/share/git-fixture.test.ts b/packages/server/src/share/git-fixture.test.tsnew file mode 100644index 000000000..4e171a9ac--- /dev/null+++ b/packages/server/src/share/git-fixture.test.ts@@ -0,0 +1,187 @@+/**+ * Fidelity check for the real-git share fixture: every drift state the freshness+ * (send) and target-status (receive) paths care about is asserted here through+ * the exact git probe commands those paths use, so the substrate is proven+ * faithful before the handler tests depend on it. Synchronous `execFileSync`+ * git keeps this unskipped on CI (oven-sh/bun#11892 only bites async children).+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { existsSync } from 'node:fs';+import { createGitTriangle, type GitTriangle } from './git-fixture.test-helper.ts';++const triangles: GitTriangle[] = [];++function newTriangle(): GitTriangle {+ const t = createGitTriangle();+ triangles.push(t);+ return t;+}++afterEach(() => {+ for (const t of triangles.splice(0)) t.cleanup();+});++/** Exit status of a git probe without throwing — the freshness/verdict probes+ * branch on cat-file / diff exit codes, not on stdout. */+function gitExit(cwd: string, args: string[]): number {+ const r = spawnSync('git', args, { cwd, encoding: 'utf-8' });+ return r.status ?? -1;+}++describe('createGitTriangle — send-side freshness drift cells', () => {+ test('a clean pushed doc: on origin (cat-file passes) and unchanged (diff clean) -> current', () => {+ const t = newTriangle();+ t.seedAndPush('doc.md', '# hello\n');+ const ref = `origin/${t.branch}`;+ expect(gitExit(t.senderDir, ['cat-file', '-e', `${ref}:doc.md`])).toBe(0);+ expect(gitExit(t.senderDir, ['diff', '--quiet', ref, '--', 'doc.md'])).toBe(0);+ });++ test('an untracked doc: missing from the origin ref -> absent', () => {+ const t = newTriangle();+ t.writeWorkingTree('new.md', '# never saved\n');+ const ref = `origin/${t.branch}`;+ expect(gitExit(t.senderDir, ['cat-file', '-e', `${ref}:new.md`])).not.toBe(0);+ });++ test('an uncommitted edit of a pushed doc: on origin but the working tree differs -> stale', () => {+ const t = newTriangle();+ t.seedAndPush('doc.md', 'v1\n');+ t.writeWorkingTree('doc.md', 'v2 edited, not committed\n');+ const ref = `origin/${t.branch}`;+ expect(gitExit(t.senderDir, ['cat-file', '-e', `${ref}:doc.md`])).toBe(0);+ expect(gitExit(t.senderDir, ['diff', '--quiet', ref, '--', 'doc.md'])).not.toBe(0);+ });++ test('a committed-but-unpushed edit: origin keeps the old blob, diff differs -> stale', () => {+ const t = newTriangle();+ t.seedAndPush('doc.md', 'v1\n');+ t.commitWithoutPush('doc.md', 'v2 committed, not pushed\n');+ const ref = `origin/${t.branch}`;+ expect(t.git(t.senderDir, ['show', `${ref}:doc.md`])).toBe('v1');+ expect(gitExit(t.senderDir, ['cat-file', '-e', `${ref}:doc.md`])).toBe(0);+ expect(gitExit(t.senderDir, ['diff', '--quiet', ref, '--', 'doc.md'])).not.toBe(0);+ });++ test('an untracked file inside a pushed folder: diff is blind to it, status catches it -> stale', () => {+ const t = newTriangle();+ t.seedAndPush('docs/a.md', 'a\n');+ t.writeWorkingTree('docs/new.md', 'brand new, unstaged\n');+ const ref = `origin/${t.branch}`;+ expect(gitExit(t.senderDir, ['cat-file', '-e', `${ref}:docs`])).toBe(0);+ expect(gitExit(t.senderDir, ['diff', '--quiet', ref, '--', 'docs'])).toBe(0);+ expect(+ t.git(t.senderDir, ['status', '--porcelain', '--untracked-files=all', '--', 'docs']),+ ).not.toBe('');+ });++ test('a clean pushed symlink: unchanged -> current, and stored as a symlink (mode 120000)', () => {+ const t = newTriangle();+ t.seedSymlinkAndPush('link.md', 'target.md', '# target\n');+ const ref = `origin/${t.branch}`;+ expect(gitExit(t.senderDir, ['cat-file', '-e', `${ref}:link.md`])).toBe(0);+ expect(gitExit(t.senderDir, ['diff', '--quiet', ref, '--', 'link.md'])).toBe(0);+ expect(t.git(t.senderDir, ['ls-files', '--stage', '--', 'link.md']).startsWith('120000')).toBe(+ true,+ );+ });+});++describe('createGitTriangle — receive-side rename / delete legs', () => {+ test('renaming a doc on origin: new path present, old path gone, classified R by -M', () => {+ const t = newTriangle();+ t.seedAndPush('old.md', '# stable content that survives the move intact\n');+ t.renameOnOrigin('old.md', 'new.md');+ const ref = `origin/${t.branch}`;+ expect(gitExit(t.senderDir, ['cat-file', '-e', `${ref}:new.md`])).toBe(0);+ expect(gitExit(t.senderDir, ['cat-file', '-e', `${ref}:old.md`])).not.toBe(0);++ const removingCommit = t.git(t.senderDir, ['log', '-1', '--format=%H', ref, '--', 'old.md']);+ expect(removingCommit).not.toBe('');+ const nameStatus = t.git(t.senderDir, [+ 'diff-tree',+ '-M',+ '-r',+ '--name-status',+ removingCommit,+ ]);+ expect(nameStatus).toMatch(/^R\d*\told\.md\tnew\.md$/m);+ });++ test('a receiver clone observes the renamed path on origin', () => {+ const t = newTriangle();+ t.seedAndPush('old.md', '# content that moves\n');+ t.renameOnOrigin('old.md', 'renamed.md');+ const receiver = t.cloneReceiver();+ const ref = `origin/${t.branch}`;+ expect(gitExit(receiver, ['cat-file', '-e', `${ref}:renamed.md`])).toBe(0);+ expect(gitExit(receiver, ['cat-file', '-e', `${ref}:old.md`])).not.toBe(0);+ });++ test('renaming a folder on origin: per-file R rows share the old prefix', () => {+ const t = newTriangle();+ t.seedAndPush('docs/a.md', 'alpha content long enough to match on similarity\n');+ t.seedAndPush('docs/b.md', 'beta content long enough to match on similarity\n');+ t.renameFolderOnOrigin('docs', 'knowledge');+ const ref = `origin/${t.branch}`;+ expect(gitExit(t.senderDir, ['cat-file', '-e', `${ref}:knowledge/a.md`])).toBe(0);+ expect(gitExit(t.senderDir, ['cat-file', '-e', `${ref}:docs/a.md`])).not.toBe(0);++ const removingCommit = t.git(t.senderDir, ['log', '-1', '--format=%H', ref, '--', 'docs']);+ const nameStatus = t.git(t.senderDir, [+ 'diff-tree',+ '-M',+ '-r',+ '--name-status',+ removingCommit,+ ]);+ expect(nameStatus).toMatch(/^R\d*\tdocs\/a\.md\tknowledge\/a\.md$/m);+ expect(nameStatus).toMatch(/^R\d*\tdocs\/b\.md\tknowledge\/b\.md$/m);+ });++ test('deleting a doc on origin: removal commit exists with a D row (not an R)', () => {+ const t = newTriangle();+ t.seedAndPush('gone.md', '# will be deleted with no successor\n');+ t.deleteOnOrigin('gone.md');+ const ref = `origin/${t.branch}`;+ expect(gitExit(t.senderDir, ['cat-file', '-e', `${ref}:gone.md`])).not.toBe(0);++ const removingCommit = t.git(t.senderDir, ['log', '-1', '--format=%H', ref, '--', 'gone.md']);+ expect(removingCommit).not.toBe('');+ const nameStatus = t.git(t.senderDir, [+ 'diff-tree',+ '-M',+ '-r',+ '--name-status',+ removingCommit,+ ]);+ expect(nameStatus).toMatch(/^D\tgone\.md$/m);+ expect(nameStatus).not.toMatch(/^R/m);+ });++ test('a path that never existed: empty removal-commit lookup (never-on-branch, not deleted)', () => {+ const t = newTriangle();+ const ref = `origin/${t.branch}`;+ const removingCommit = t.git(t.senderDir, ['log', '-1', '--format=%H', ref, '--', 'never.md']);+ expect(removingCommit).toBe('');+ });+});++describe('createGitTriangle — lifecycle', () => {+ test('cleanup removes every temp repo it created', () => {+ // Intentionally unregistered: this test owns the cleanup it asserts.+ const t = createGitTriangle();+ const { senderDir, originDir } = t;+ const receiver = t.cloneReceiver();+ expect(existsSync(senderDir)).toBe(true);+ expect(existsSync(originDir)).toBe(true);+ expect(existsSync(receiver)).toBe(true);++ t.cleanup();++ expect(existsSync(senderDir)).toBe(false);+ expect(existsSync(originDir)).toBe(false);+ expect(existsSync(receiver)).toBe(false);+ });+});diff --git a/packages/server/src/share/target-status.test.ts b/packages/server/src/share/target-status.test.tsnew file mode 100644index 000000000..a9eedda55--- /dev/null+++ b/packages/server/src/share/target-status.test.ts@@ -0,0 +1,168 @@+/**+ * Target-status verdicts verified against the real-git S1 fixture — one+ * case per verdict, no mocks. The receiver clones BEFORE the sender's mutation+ * in the move/delete cases, so the fetch inside `computeShareTargetStatus` is+ * what reveals the change (a stale local ref would otherwise misclassify it).+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { createGitTriangle, type GitTriangle } from './git-fixture.test-helper.ts';+import { computeShareTargetStatus } from './target-status.ts';++const triangles: GitTriangle[] = [];++function newTriangle(): GitTriangle {+ const t = createGitTriangle();+ triangles.push(t);+ return t;+}++afterEach(() => {+ for (const t of triangles.splice(0)) t.cleanup();+});++describe('computeShareTargetStatus', () => {+ test('stale-local: a recently-pushed doc the receiver has not fetched is on-origin', async () => {+ const t = newTriangle();+ t.seedAndPush('doc1.md', 'one\n');+ const receiver = t.cloneReceiver();+ // Sender pushes a second doc AFTER the clone; the receiver's origin ref is+ // now stale and does not know about it — until the fetch.+ t.seedAndPush('doc2.md', 'two\n');+ const status = await computeShareTargetStatus(receiver, t.branch, 'doc2.md', 'doc');+ expect(status.verdict).toBe('on-origin');+ });++ test('renamed doc: the fetch reveals the move; verdict renamed with the new path', async () => {+ const t = newTriangle();+ t.seedAndPush('old.md', '# stable content that survives the move intact\n');+ const receiver = t.cloneReceiver();+ t.renameOnOrigin('old.md', 'new.md');+ const status = await computeShareTargetStatus(receiver, t.branch, 'old.md', 'doc');+ expect(status.verdict).toBe('renamed');+ if (status.verdict === 'renamed') expect(status.renamedTo).toBe('new.md');+ });++ test('renamed via a merge commit: read through the first parent, not misparsed as deleted', async () => {+ const t = newTriangle();+ t.seedAndPush('old.md', '# stable content that survives the move intact\n');+ const receiver = t.cloneReceiver();+ // The removal lands in a merge commit, whose bare diff-tree is combined+ // format — a first-parent diff is what keeps the rename row readable.+ t.mergeRenameOnOrigin('old.md', 'new.md');+ const status = await computeShareTargetStatus(receiver, t.branch, 'old.md', 'doc');+ expect(status.verdict).toBe('renamed');+ if (status.verdict === 'renamed') expect(status.renamedTo).toBe('new.md');+ });++ test('renamed folder: per-file rename rows map to the new folder by common prefix', async () => {+ const t = newTriangle();+ t.seedAndPush('docs/a.md', 'alpha content long enough to match on similarity\n');+ t.seedAndPush('docs/b.md', 'beta content long enough to match on similarity\n');+ const receiver = t.cloneReceiver();+ t.renameFolderOnOrigin('docs', 'knowledge');+ const status = await computeShareTargetStatus(receiver, t.branch, 'docs', 'folder');+ expect(status.verdict).toBe('renamed');+ if (status.verdict === 'renamed') expect(status.renamedTo).toBe('knowledge');+ });++ test('deleted doc: a removal commit with a delete row is deleted', async () => {+ const t = newTriangle();+ t.seedAndPush('gone.md', '# will be removed with no successor\n');+ const receiver = t.cloneReceiver();+ t.deleteOnOrigin('gone.md');+ const status = await computeShareTargetStatus(receiver, t.branch, 'gone.md', 'doc');+ expect(status.verdict).toBe('deleted');+ });++ test('never-on-branch: a path that never existed is distinct from deleted', async () => {+ const t = newTriangle();+ const receiver = t.cloneReceiver();+ const status = await computeShareTargetStatus(receiver, t.branch, 'never.md', 'doc');+ expect(status.verdict).toBe('never-on-branch');+ });++ test('offline: a failed fetch degrades to unknown', async () => {+ const t = newTriangle();+ t.seedAndPush('doc.md', 'one\n');+ const receiver = t.cloneReceiver();+ // No reachable origin — the fetch fails fast.+ t.git(receiver, ['remote', 'remove', 'origin']);+ const status = await computeShareTargetStatus(receiver, t.branch, 'doc.md', 'doc', {+ fetchTimeoutMs: 5000,+ });+ expect(status.verdict).toBe('unknown');+ });++ test('fresh-clone leg (skipFetch): reads the clone ref without fetching', async () => {+ const t = newTriangle();+ t.seedAndPush('doc.md', 'one\n');+ const receiver = t.cloneReceiver();+ const status = await computeShareTargetStatus(receiver, t.branch, 'doc.md', 'doc', {+ skipFetch: true,+ });+ expect(status.verdict).toBe('on-origin');+ });++ test('chained rename whose destination is gone degrades to deleted (no dead redirect)', async () => {+ const t = newTriangle();+ t.seedAndPush('a.md', '# content that moves more than once before it settles\n');+ const receiver = t.cloneReceiver();+ t.renameOnOrigin('a.md', 'b.md');+ t.renameOnOrigin('b.md', 'c.md');+ const status = await computeShareTargetStatus(receiver, t.branch, 'a.md', 'doc');+ // a.md's removal commit renamed it to b.md, but b.md no longer resolves at+ // origin (it became c.md), so the redirect is refused in favor of deleted.+ expect(status.verdict).toBe('deleted');+ });++ test('fresh-clone leg (skipFetch): a target deleted before the clone is deleted, no fetch', async () => {+ const t = newTriangle();+ t.seedAndPush('gone.md', 'bye\n');+ t.deleteOnOrigin('gone.md');+ // Clone AFTER the delete: the clone's own history carries the removal, so+ // the verdict is reachable from local refs with no fetch.+ const receiver = t.cloneReceiver();+ const status = await computeShareTargetStatus(receiver, t.branch, 'gone.md', 'doc', {+ skipFetch: true,+ });+ expect(status.verdict).toBe('deleted');+ });++ test('split-folder rename (files scatter to different prefixes) degrades to deleted, not a garbage redirect', async () => {+ const t = newTriangle();+ t.seedAndPush('docs/a.md', 'a\n');+ t.seedAndPush('docs/b.md', 'b\n');+ const receiver = t.cloneReceiver();+ // One commit moves docs/ files to two DIFFERENT prefixes — no single new+ // folder, so the common-prefix inference is ambiguous and must not redirect.+ t.splitRenameOnOrigin([+ ['docs/a.md', 'x/a.md'],+ ['docs/b.md', 'y/b.md'],+ ]);+ const status = await computeShareTargetStatus(receiver, t.branch, 'docs', 'folder');+ expect(status.verdict).toBe('deleted');+ });++ test('local uncommitted delete: still on origin + in HEAD but gone from the working tree is changed-locally', async () => {+ const t = newTriangle();+ t.seedAndPush('local-del.md', '# committed, then deleted locally without syncing\n');+ const receiver = t.cloneReceiver();+ // The receiver removes their own copy WITHOUT committing/pushing: the path+ // is still on origin and in their HEAD, but absent from the working tree.+ // "Pull" would be wrong guidance — they are not behind.+ t.deleteInReceiverWorkingTree('local-del.md');+ const status = await computeShareTargetStatus(receiver, t.branch, 'local-del.md', 'doc');+ expect(status.verdict).toBe('changed-locally');+ });++ test('local uncommitted rename: the old path gone from the working tree but still in HEAD is changed-locally', async () => {+ const t = newTriangle();+ t.seedAndPush('local-mv.md', '# committed, then renamed locally without syncing\n');+ const receiver = t.cloneReceiver();+ // A local rename looks identical to a local delete from the OLD path's+ // vantage: present in HEAD, gone from the working tree.+ t.renameInReceiverWorkingTree('local-mv.md', 'renamed-local.md');+ const status = await computeShareTargetStatus(receiver, t.branch, 'local-mv.md', 'doc');+ expect(status.verdict).toBe('changed-locally');+ });+});diff --git a/packages/server/src/share/target-status.ts b/packages/server/src/share/target-status.tsnew file mode 100644index 000000000..a8c71dafc--- /dev/null+++ b/packages/server/src/share/target-status.ts@@ -0,0 +1,201 @@+/**+ * Receive-side verdict for `POST /api/share/target-status`: when a receiver+ * opens a share link and the target isn't on their current ref, why — did it+ * move, get deleted, or was it never here? Runs a targeted `git fetch origin+ * <branch>` (via `createGitInstance`, so the user's ambient git credential+ * helper authenticates it exactly as checkout's fetch does — no explicit OK+ * token is injected) bounded by a block timeout, so a stale local ref can't+ * misreport a recently-added target as gone, then classifies the miss from+ * git's own rename detection.+ *+ * Everything is fail-open: a fetch failure, a broken git, or an ambiguous+ * classification returns `unknown`, and the caller falls back to today's+ * guidance. A miss degrades to honest `deleted`, never a wrong redirect.+ */+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import type { ShareTargetStatusResponse } from '@inkeep/open-knowledge-core';+import { truncateError } from '../error-format.ts';+import { createGitInstance } from '../git-handle.ts';+import { getLogger } from '../logger.ts';++/** Single source of truth for the handler tag used in logs + telemetry. */+export const SHARE_TARGET_STATUS_HANDLER_TAG = 'share-target-status';++/** Block timeout for the fetch — a hung fetch degrades to `unknown`. */+const DEFAULT_FETCH_TIMEOUT_MS = 15_000;++interface DiffRow {+ status: string;+ from: string;+ to: string;+}++/**+ * Parse `git diff-tree --name-status` rows (tab-separated). Rename/copy rows+ * carry a score and two paths (`R100\told\tnew`); every other status carries+ * one path (`D\told`).+ */+function parseNameStatus(output: string): DiffRow[] {+ const rows: DiffRow[] = [];+ for (const line of output.split('\n')) {+ if (line.trim() === '') continue;+ const parts = line.split('\t');+ const status = parts[0] ?? '';+ if ((status.startsWith('R') || status.startsWith('C')) && parts.length >= 3) {+ rows.push({ status, from: parts[1] ?? '', to: parts[2] ?? '' });+ } else {+ rows.push({ status, from: parts[1] ?? '', to: parts[1] ?? '' });+ }+ }+ return rows;+}++/** Classify a doc removal: the row whose source is exactly the shared path. */+function classifyDoc(rows: DiffRow[], gitPath: string): ShareTargetStatusResponse {+ for (const row of rows) {+ if (row.from !== gitPath) continue;+ if (row.status.startsWith('R')) return { verdict: 'renamed', renamedTo: row.to };+ if (row.status === 'D') return { verdict: 'deleted' };+ }+ // The removing commit touched the path but not via a rename/delete row we+ // recognize — treat as deleted (honest) rather than inventing a redirect.+ return { verdict: 'deleted' };+}++/**+ * Classify a folder removal: a `git mv` of a folder shows as per-file rename+ * rows under the old prefix, all rewriting to one new prefix. Map the folder by+ * the common prefix across those rows; anything else (deletes, inconsistent+ * destinations) is a deletion.+ */+function classifyFolder(rows: DiffRow[], folderPath: string): ShareTargetStatusResponse {+ const prefix = folderPath.endsWith('/') ? folderPath : `${folderPath}/`;+ const newPrefixes = new Set<string>();+ for (const row of rows) {+ if (!row.from.startsWith(prefix)) continue;+ if (!row.status.startsWith('R')) continue;+ const rest = row.from.slice(prefix.length);+ if (row.to.endsWith(`/${rest}`)) {+ newPrefixes.add(row.to.slice(0, row.to.length - rest.length - 1));+ } else {+ newPrefixes.add('\0ambiguous');+ }+ }+ const only = newPrefixes.size === 1 ? [...newPrefixes][0] : undefined;+ if (only !== undefined && only !== '\0ambiguous') {+ return { verdict: 'renamed', renamedTo: only };+ }+ return { verdict: 'deleted' };+}++/**+ * Compute the target-status verdict for `gitPath` (repo-root-relative) at+ * `origin/<branch>`. `skipFetch` is for the fresh-clone leg, whose clone is+ * already current, so no fetch is needed.+ */+export async function computeShareTargetStatus(+ projectDir: string,+ branch: string,+ gitPath: string,+ kind: 'doc' | 'folder',+ opts: { skipFetch?: boolean; fetchTimeoutMs?: number } = {},+): Promise<ShareTargetStatusResponse> {+ const log = getLogger('share');+ const emit = (result: ShareTargetStatusResponse): ShareTargetStatusResponse => {+ log.info({ action: 'target-status', verdict: result.verdict, kind }, 'target-status verdict');+ return result;+ };++ const { git } = createGitInstance(+ projectDir,+ opts.skipFetch ? {} : { timeoutMs: opts.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS },+ );++ if (!opts.skipFetch) {+ try {+ await git.raw(['fetch', 'origin', branch]);+ } catch (err) {+ // Offline / auth / timeout — the caller falls back to today's guidance.+ // Keep the error identity so a "receiver always sees pull-guidance"+ // report can distinguish offline from auth-denied from timeout.+ log.warn(+ { action: 'target-status', kind, error: truncateError(err) },+ 'target-status fetch failed',+ );+ return emit({ verdict: 'unknown' });+ }+ }++ const ref = `origin/${branch}`;+ try {+ // Present at origin's tip. Two sub-cases the receiver must not conflate:+ // - a genuinely stale local ref — they are behind, and a pull recovers+ // the target (`on-origin`); or+ // - a LOCAL uncommitted change — the target is still in their committed+ // HEAD but they removed or renamed it in their own working tree without+ // syncing (`changed-locally`). "Pull" is the wrong guidance there: they+ // are not behind, and a pull can't reconcile an uncommitted working-tree+ // change.+ // Distinguish by HEAD + working-tree state. `projectDir` is the receiver's+ // repo root, so the working-tree copy of `gitPath` lives at+ // `<projectDir>/<gitPath>`. A local delete AND a local rename both leave the+ // OLD path in HEAD yet gone from the working tree, so one check covers both.+ const present = await git+ .raw(['cat-file', '-e', `${ref}:${gitPath}`])+ .then(() => true)+ .catch(() => false);+ if (present) {+ const inHead = await git+ .raw(['cat-file', '-e', `HEAD:${gitPath}`])+ .then(() => true)+ .catch(() => false);+ const inWorkingTree = existsSync(join(projectDir, gitPath));+ if (inHead && !inWorkingTree) return emit({ verdict: 'changed-locally' });+ return emit({ verdict: 'on-origin' });+ }++ // The last commit that touched the path. Empty output = the path never+ // existed on this branch (never pushed) — distinct from a real deletion.+ const removingCommit = (await git.raw(['log', '-1', '--format=%H', ref, '--', gitPath])).trim();+ if (removingCommit === '') return emit({ verdict: 'never-on-branch' });++ // Diff the removing commit against its FIRST parent explicitly. A bare+ // `diff-tree <commit>` on a merge commit emits combined-diff format (one+ // status column per parent), which `parseNameStatus` can't read — so a path+ // removed via a merge would misclassify. `<commit>^1 <commit>` forces the+ // standard single-status format and is equivalent to the bare form for+ // ordinary single-parent commits. A removal only ever reachable through the+ // second parent falls through to the honest `deleted` verdict.+ const nameStatus = await git.raw([+ 'diff-tree',+ '-M',+ '-r',+ '--no-commit-id',+ '--name-status',+ `${removingCommit}^1`,+ removingCommit,+ ]);+ const rows = parseNameStatus(nameStatus);+ const classified =+ kind === 'folder' ? classifyFolder(rows, gitPath) : classifyDoc(rows, gitPath);++ // Chained rename guard: a redirect is only offered if its destination+ // actually resolves at the origin ref — otherwise degrade to deleted.+ if (classified.verdict === 'renamed') {+ const redirectExists = await git+ .raw(['cat-file', '-e', `${ref}:${classified.renamedTo}`])+ .then(() => true)+ .catch(() => false);+ if (!redirectExists) return emit({ verdict: 'deleted' });+ }+ return emit(classified);+ } catch (err) {+ // Git broke mid-detection — fail-open rather than guess.+ log.warn(+ { action: 'target-status', kind, error: truncateError(err) },+ 'target-status detection failed',+ );+ return emit({ verdict: 'unknown' });+ }+}