Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): refuse incoming symlinks into private state on sync pull (#5338)
Andrew Mikofalvy0edc8b2adbf5
diff --git a/.changeset/sync-pull-refuses-unsafe-symlinks.md b/.changeset/sync-pull-refuses-unsafe-symlinks.mdnew file mode 100644index 000000000..50bbd26d6--- /dev/null+++ b/.changeset/sync-pull-refuses-unsafe-symlinks.md@@ -0,0 +1,6 @@+---+"@inkeep/open-knowledge": patch+"@inkeep/open-knowledge-desktop": patch+---++Sync, `ok pull` and share-link branch switches now refuse a change that leaves a symlink pointing outside the repository, into private `.git` or OpenKnowledge state, at secrets such as `.env`, or anywhere uncheckable. Merges that change links need Git 2.38 or newer.diff --git a/docs/content/features/github-sync.mdx b/docs/content/features/github-sync.mdxindex 2a18b2918..33c6b035c 100644--- a/docs/content/features/github-sync.mdx+++ b/docs/content/features/github-sync.mdx@@ -178,6 +178,31 @@ A few situations stop sync from completing successfully. Most of them change the- **The project is parked on a specific commit, not a branch.** This usually means someone checked out an older commit from the terminal to look around. There's no branch to push to, so sync pauses. Switch back to your normal branch (`main`, your working branch, whichever) and sync resumes.- **Diverged history.** When the remote has been rewritten (force-push, rebase, branch reset) in a way OpenKnowledge can't reconcile automatically, sync stops and shows the error. This one usually needs a fix from the command line. Ask whoever rewrote the history for help, or restore from the [Timeline](/docs/features/timeline-and-recovery).+### Incoming changes with unsafe symlinks++If a teammate's update adds, retargets, or removes symlinks in a way that leaves an unsafe link, OpenKnowledge refuses the whole update. Nothing from it lands, and your local commits wait to be pushed.++- **Which links are refused.** Before writing anything, OpenKnowledge works out the tree the pull would land: the incoming tree for a fast-forward, or for a three-way merge the tree Git's merge would produce, including any move caused by a local folder rename. It follows each link the update adds, retargets, or turns a file into, through any other links on the way, the same way your operating system does. The link is refused when it:+ - points outside the repository, or at the repository root. The boundary is the Git repository, not the OpenKnowledge project, so a project in a subfolder can still link to other files in the same repository.+ - points into any `.git` folder, at an OpenKnowledge config folder itself (such as `.ok` or `.ok-beta`), or into its machine-local state (such as `.ok/local`, or the `auth.yml` and `secrets.yml` credential files in a repository rooted at your home folder)+ - points at a file that may hold secrets, matched by name alone, whatever the file contains: `.env` and any name starting `.env.` (including `.env.example`), `.netrc`, `.npmrc`, `.pgpass`, `.git-credentials`, `credentials`, any name starting `id_rsa`, `id_ed25519`, `id_ecdsa` or `id_dsa` (including `.pub` public keys), any name ending `.pem`, `.key`, `.p12`, `.pfx`, `.keystore`, `.jks` or `.ppk`, and the folders `.ssh`, `.aws`, `.gnupg`, `.kube` and `.docker` or anything inside them+ - sits inside that private state itself+ - has a target that cannot be checked: an empty target, a target containing a NUL byte, a backslash, or a colon (which Windows reads as a file-stream name), a link whose folder or resolution passes through a name inside the repository shaped like a Windows short name (up to seven characters, a tilde and a number, optionally followed by an extension of up to three characters, such as `week~3`, `GIT-CR~1` or `REPORT~1.MD`), even when `..` removes that name again or it is itself a link (a short name of `.git` or a config folder is refused as private state instead), a target longer than 4096 bytes, a path of more than 256 steps or more than 40 link hops, a folder on the way that cannot be inspected on this machine, or a name that could resolve to a link or to something else depending on how the filesystem compares names (letter case, Unicode composition, invisible characters, trailing dots or spaces)+ - needs Git 2.38 or newer to check, when the pull is a three-way merge that changes any link and your Git is older++ A link that both you and the update changed does not pause sync on its own. Both versions are checked, since either could land, and an unsafe one refuses the pull. A link whose resolution passes through such a conflicted link cannot be checked until the conflict is gone, so it refuses the pull too.++ A link the update does not change is checked when its resolution passes through a link the update changes or removes. It is refused if it is unsafe after the pull, whether or not it was unsafe before. It is also refused, on any update that changes links, when its resolution cannot be completed (a loop, too many steps, a folder this machine cannot inspect, or a name shaped like a Windows short name as described above), because the unchecked remainder could pass through a changed link. A link already in your repository whose resolution leaves the repository (an absolute path, or a `..` above the repository root) is judged where it leaves and not followed further. It is refused only when the part of its path before it leaves passes through a link the update changes or removes; otherwise it does not block an update. Where it lands outside, including back inside the repository through a folder or link outside it, is not checked. Otherwise a link the update does not change is not checked, so a link that was already unsafe does not block an unrelated update. Link chains that stay inside the repository and away from private state pull normally, as do skill links into `.agents/skills` or the legacy `.ok/skills`.+- **Where the refusal shows.** The sync indicator reads **Sync paused**, and its popover explains why and lists the paths of up to 50 refused links, without their reasons. **Settings → Sync** shows the same explanation and list. On the Share popover's freshness row, and on an opened [share link](/docs/features/share)'s message for a target changed in your local copy, the explanation and list take the place of **Sync now** while sync is paused. The share link's message for a local copy that is behind shows them only when a pull started from that message was refused. Without a running server, `ok pull` and `ok sync` stop with an error that names up to five refused links, each with its reason, followed by a count of any others. With a server running, those commands only trigger the pull, so check the sync indicator.+- **Switching branches from a share link.** When a share link offers to switch to its branch, OpenKnowledge checks every link the switch would land against the rules above, except the Git 2.38 rule, which applies only to merges. If one is unsafe, it stays on the current branch and shows up to five refused links and a count of the rest. Fix them as described under **What to do**; switching to the branch by hand would bring the links in.+- **What to do.** It depends on the reason:+ - For a link that points outside the repository, at its root, into private state, or at a file that may hold secrets, ask whoever pushed it to remove or fix it on the remote. If the unsafe version is your own local change to a link, fix or remove that link, commit, and pull again. If the refused link is one the update does not change, it is yours too: retarget or remove it, commit, and pull again.+ - For a target that cannot be checked, the cause can be on either side. A folder on the way that this machine cannot inspect is local: make it readable, then pull again. A link already in your repository whose resolution cannot be completed is also yours to fix or remove. Anything else, including a target with a NUL byte, backslash or colon, an overlong target or chain, and a name the repository spells more than one way, needs whoever pushed the link to fix it on the remote.+ - For a name shaped like a Windows short name, whether it was refused as private state or as a target that cannot be checked: if the name is in your local copy, rename that folder or file (or retarget the link around it) and pull again; if the update brings it, ask whoever pushed it to rename it.+ - For the Git version, update Git to 2.38 or newer.++ In the automatic modes, sync keeps checking and resumes on its own once the cause is gone; in Manual mode, press **Pull** again.+### The project has no commits yet- **The repository has no commits yet.** The project has a remote, but its branch does not exist yet, so there is nothing to send: **Push** stops before it starts and the sync menu says so. Editing a document does not clear this on its own — auto-save writes to OpenKnowledge's own internal ref, never to your branch. Closing and reopening the project (or restarting the app) makes that first commit for you; running `git commit` yourself does the same. Push works from then on.diff --git a/docs/content/features/share.mdx b/docs/content/features/share.mdxindex e095fa964..e05ff8585 100644--- a/docs/content/features/share.mdx+++ b/docs/content/features/share.mdx@@ -27,7 +27,7 @@ If the push fails after the repo was created (auth lost mid-flow, network blip),A share link points at GitHub, but your local edits only reach GitHub through **Auto (Pull and Push)** or a manual push — in Manual and Auto (Pull only), nothing is pushed on a schedule. 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. When the project isn't on Auto (Pull and Push), the row offers **Enable Auto (Pull and Push)** and **How to push manually**; when it is, it offers **Sync now** and clears itself once the push lands.+- **Not on GitHub yet.** The target has never been pushed, so the link won't resolve until it is. When the project isn't on Auto (Pull and Push), the row offers **Enable Auto (Pull and Push)** and **How to push manually**; when it is, it offers **Sync now** and clears itself once the push lands. While sync is paused on an unfinished Git operation or on [unsafe symlinks](/docs/features/github-sync#incoming-changes-with-unsafe-symlinks), a notice explaining the pause takes the place of **Sync now**.- **Unpushed changes.** The target is on GitHub but has local edits that aren't, so recipients see the last pushed version. On Auto (Pull and Push) this stays silent — the next scheduled push closes the gap.- **Empty folder.** The folder holds nothing Git can track — it has no documents, or everything inside it is ignored — so the link won't resolve, and unlike the never-pushed case no push will fix it. The row names the only remedy, adding a document, and offers no sync actions at all. Only folders reach this state: a doc is trackable at any size, including zero bytes.@@ -59,15 +59,15 @@ If you have the repo open locally but on a different branch, the app opens a bra- **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 uncommitted changes conflict with the switch, switching is disabled until you commit or stash them; if the share's branch is already checked out in another worktree, the dialog offers to open that worktree instead.+If uncommitted changes conflict with the switch, switching is disabled until you commit or stash them; if the share's branch is already checked out in another worktree, the dialog offers to open that worktree instead. If the branch has a symlink that would be unsafe to check out, the switch is refused and the refused links are listed; see [Incoming changes with unsafe symlinks](/docs/features/github-sync#incoming-changes-with-unsafe-symlinks) for what to do.If OpenKnowledge can't reach GitHub to make this call, the dialog falls back to the plain switch.### When the shared target is not on your local copyEven on the right branch, a shared target (file or folder) can be renamed or deleted after a link is minted. In this case, OpenKnowledge offers to open the 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 target was moved, renamed, or deleted in your own local copy, OpenKnowledge tells you to commit your changes manually or enable Auto (Pull and Push).-If the target is on GitHub but hasn't reached your local copy yet, OpenKnowledge alerts you that your local copy is behind. The **Pull latest changes** button on this message fetches from GitHub and fast-forwards your copy in place. It only ever pulls: nothing is committed or pushed on your behalf, and your uncommitted edits ride on top of what comes in. If the pull can't run — another sync operation is already in flight, or GitHub is unreachable — the reason appears under the message and the button stays available to retry.+If the target was moved, renamed, or deleted in your own local copy, OpenKnowledge tells you to commit your changes manually or enable Auto (Pull and Push). On Auto (Pull and Push) it says the change hasn't synced yet and offers **Sync now**; while sync is paused on an unfinished Git operation or on [unsafe symlinks](/docs/features/github-sync#incoming-changes-with-unsafe-symlinks), a notice explaining the pause takes its place.+If the target is on GitHub but hasn't reached your local copy yet, OpenKnowledge alerts you that your local copy is behind. The **Pull latest changes** button on this message fetches from GitHub and fast-forwards your copy in place. It only ever pulls: nothing is committed or pushed on your behalf, and your uncommitted edits ride on top of what comes in. If the pull can't run — another sync operation is already in flight, or GitHub is unreachable — the reason appears under the message and the button stays available to retry. If the incoming changes have an unsafe symlink, the pull is refused and sync pauses until the link is fixed; see [Incoming changes with unsafe symlinks](/docs/features/github-sync#incoming-changes-with-unsafe-symlinks).### Receiving without push permissiondiff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdxindex 5c772eb88..4acb31698 100644--- a/docs/content/reference/cli.mdx+++ b/docs/content/reference/cli.mdx@@ -112,6 +112,8 @@ Sync a project with its remote from the terminal:Each command goes through the running server when one is up. Otherwise it runs git directly. When the remote's URL is `https://` and names `github.com` or a declared GitHub Enterprise host exactly, in lowercase and with no port, and OpenKnowledge has a GitHub sign-in for it ([which account is used](/docs/features/github-sync#which-github-account-is-used)), that sign-in replaces your git credential helpers for HTTPS requests to that host during the command, though a `~/.netrc` entry for the host is still used before any helper. The sign-in answers only that exact spelling of the host: for a submodule or extra push URL that writes it with an explicit `:443` or in different letter case, git asks a configured askpass program (`GIT_ASKPASS`, `core.askPass` or `SSH_ASKPASS`; VS Code's integrated terminal sets one), and the request fails when none is configured. Requests to another host, a non-default port or a plain `http://` URL use your own git credentials. Pass `--json` for JSONL progress events when scripting. See [GitHub sync](/docs/features/github-sync) for how syncing works.+Without a running server, `ok pull` and `ok sync` check every symlink the pull would add, retarget or remove before writing anything, and refuse the whole update if one would be unsafe: it points outside the repository, into private `.git` or OpenKnowledge state, at a file that may hold secrets, or somewhere that cannot be checked. The command exits with an error naming up to five refused links, each with its reason, followed by a count of any others and what to do next. With a server running, the command only triggers the pull, and the refusal appears in the app's sync indicator instead. The full rules, including links both sides changed, links that pass through them, names spelled more than one way, and the Git 2.38 requirement for three-way pulls, are in [Incoming changes with unsafe symlinks](/docs/features/github-sync#incoming-changes-with-unsafe-symlinks).+## Manage local serversEach project runs its own local server. These commands let you see and stop them:diff --git a/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx b/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsxindex c907fd35a..234912636 100644--- a/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx+++ b/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx@@ -47,8 +47,14 @@ vi.doMock('@lingui/react/macro', () => ({}));const toastError = vi.fn(() => {});+const toastDismiss = vi.fn(() => {});vi.doMock('sonner', () => ({- toast: { error: toastError, info: vi.fn(() => {}), success: vi.fn(() => {}) },+ toast: {+ error: toastError,+ dismiss: toastDismiss,+ info: vi.fn(() => {}),+ success: vi.fn(() => {}),+ },}));const refreshWorktrees = vi.fn(() => {});@@ -511,6 +517,40 @@ describe('ShareBranchSwitchDialog — Switch path (runCheckout + CC1 gate)', ()});});+ test('Switch whose symlink check could not run says so, without suggesting a manual switch', async () => {+ toastError.mockReset();+ const store = createShareReceiveStore();+ const { bridge, calls } = makeBridge({+ runCheckout: vi.fn(async () => ({+ ok: false as const,+ reason: 'symlink-check-failed' as const,+ })),+ });+ 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} />);++ const switchBtn = await screen.findByTestId('share-branch-switch-switch');+ await act(async () => {+ fireEvent.click(switchBtn);+ await Promise.resolve();+ });++ await waitFor(() => {+ expect(toastError).toHaveBeenCalledWith(+ 'Could not check the symlinks in feat/branch-x, so it was not switched. Try again; if it keeps failing, check that Git is installed and the project folder is readable.',+ );+ });+ expect(toastError).not.toHaveBeenCalledWith(expect.stringContaining('switching manually'));+ expect(calls.open).not.toHaveBeenCalled();+ });+test('Switch with runCheckout {ok:false, checkout-failed} toasts and does not navigate', async () => {const store = createShareReceiveStore();const { bridge, calls } = makeBridge({@@ -541,6 +581,143 @@ describe('ShareBranchSwitchDialog — Switch path (runCheckout + CC1 gate)', ()expect(calls.open).not.toHaveBeenCalled();});+ test.each([+ [+ 'seven links',+ ['a.md', 'b.md', 'c.md', 'd.md', 'e.md', 'f.md', 'g.md'],+ {+ description: 'a.md, b.md, c.md, d.md, e.md, and 2 more links',+ id: 'share-switch-unsafe-symlinks:feat/branch-x',+ duration: Infinity,+ },+ ],+ [+ 'six links',+ ['a.md', 'b.md', 'c.md', 'd.md', 'e.md', 'f.md'],+ {+ description: 'a.md, b.md, c.md, d.md, e.md, and 1 more link',+ id: 'share-switch-unsafe-symlinks:feat/branch-x',+ duration: Infinity,+ },+ ],+ [+ 'exactly five links',+ ['a.md', 'b.md', 'c.md', 'd.md', 'e.md'],+ {+ description: 'a.md, b.md, c.md, d.md, and e.md',+ id: 'share-switch-unsafe-symlinks:feat/branch-x',+ duration: Infinity,+ },+ ],+ [+ 'one link',+ ['a.md'],+ { description: 'a.md', id: 'share-switch-unsafe-symlinks:feat/branch-x', duration: Infinity },+ ],+ [+ 'no listed links',+ [],+ { id: 'share-switch-unsafe-symlinks:feat/branch-x', duration: Infinity },+ ],+ ])(+ 'Switch refused for unsafe symlinks (%s) names the links, never suggests a manual switch, and stays open',+ async (_label, refusedSymlinkPaths, options) => {+ toastError.mockReset();+ const store = createShareReceiveStore();+ const { bridge, calls } = makeBridge({+ runCheckout: vi.fn(async () => ({+ ok: false as const,+ reason: 'unsafe-symlinks' as const,+ refusedSymlinkPaths,+ })),+ });+ 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} />);++ const switchBtn = await screen.findByTestId('share-branch-switch-switch');+ await act(async () => {+ fireEvent.click(switchBtn);+ await Promise.resolve();+ });++ await waitFor(() => {+ expect(toastError).toHaveBeenCalledWith(+ 'Did not switch to feat/branch-x: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again.',+ options,+ );+ });+ expect(Object.hasOwn(toastError.mock.calls.at(-1)?.[1] ?? {}, 'description')).toBe(true);+ expect(toastError).not.toHaveBeenCalledWith(expect.stringContaining('switching manually'));+ expect(calls.awaitBranchSwitched).not.toHaveBeenCalled();+ expect(calls.open).not.toHaveBeenCalled();+ expect(await screen.findByTestId('share-branch-switch-switch')).toBeTruthy();+ },+ );++ test.each([+ ['succeeds', () => Promise.resolve<CheckoutResponse>({ ok: true }), 1],+ [+ 'fails another way',+ () => Promise.resolve<CheckoutResponse>({ ok: false, reason: 'checkout-failed' }),+ 2,+ ],+ ['rejects', () => Promise.reject<CheckoutResponse>(new Error('bridge gone')), 2],+ ])(+ 'A switch that %s after an unsafe-symlink refusal clears the refusal toast',+ async (_label, retry, errorToasts) => {+ toastError.mockReset();+ toastDismiss.mockReset();+ const store = createShareReceiveStore();+ const runCheckout = vi+ .fn<() => Promise<CheckoutResponse>>()+ .mockResolvedValueOnce({+ ok: false,+ reason: 'unsafe-symlinks',+ refusedSymlinkPaths: ['a.md'],+ })+ .mockImplementation(retry);+ const { bridge } = makeBridge({ runCheckout });+ 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} />);++ const firstSwitch = await screen.findByTestId('share-branch-switch-switch');+ await act(async () => {+ fireEvent.click(firstSwitch);+ await Promise.resolve();+ });+ await waitFor(() => {+ expect(toastError).toHaveBeenCalledTimes(1);+ });+ expect(toastDismiss).not.toHaveBeenCalled();++ const secondSwitch = await screen.findByTestId('share-branch-switch-switch');+ await act(async () => {+ fireEvent.click(secondSwitch);+ await Promise.resolve();+ });+ await waitFor(() => {+ expect(toastDismiss).toHaveBeenCalledWith('share-switch-unsafe-symlinks:feat/branch-x');+ });+ await waitFor(() => {+ expect(toastError).toHaveBeenCalledTimes(errorToasts);+ });+ },+ );+test('Switch with awaitBranchSwitched {ok:false} (CC1 timeout) toasts the timeout copy', async () => {const store = createShareReceiveStore();const { bridge, calls } = makeBridge({diff --git a/packages/app/src/components/ShareBranchSwitchDialog.tsx b/packages/app/src/components/ShareBranchSwitchDialog.tsxindex 2117866fa..3eb31a516 100644--- a/packages/app/src/components/ShareBranchSwitchDialog.tsx+++ b/packages/app/src/components/ShareBranchSwitchDialog.tsx@@ -1,6 +1,8 @@// oxlint-disable ok/no-physical-direction-utility -- pre-rule backlog — physical margin/padding/inset utilities predate the rule; drain by swapping ml/mr → ms/me, pl/pr → ps/pe, left/right → start/end, then deleting this line. See https://github.com/inkeep/open-knowledge/blob/main/lint-plugins/ok-rules/README.md#no-physical-direction-utilityimport type { WorktreeCreateResult } from '@inkeep/open-knowledge-core';+import { i18n } from '@lingui/core';+import { plural } from '@lingui/core/macro';import { Trans, useLingui } from '@lingui/react/macro';import { AppWindow, GitBranch, MapPin } from 'lucide-react';import { useEffect, useRef, useState, useSyncExternalStore } from 'react';@@ -44,6 +46,7 @@ import {import { missDialogStore } from '@/lib/share/miss-dialog-store';import { formatReceiveLog } from '@/lib/share/receive-flow';import { type ShareReceiveStore, shareReceiveStore } from '@/lib/share/receive-store';+import { formatToolList } from '@/lib/tool-list-format';import { worktreeCreateErrorCopy } from '@/lib/worktree-create-error';import { refreshWorktrees } from '@/lib/worktree-store';@@ -86,6 +89,12 @@ function isBranchSwitchPayload(return payload !== null && payload.kind === 'project-branch-switch';}+const REFUSED_LINKS_SHOWN = 5;++function shareSwitchRefusalToastId(branch: string): string {+ return `share-switch-unsafe-symlinks:${branch}`;+}+export function ShareBranchSwitchDialog({bridge,store = shareReceiveStore,@@ -295,18 +304,44 @@ export function ShareBranchSwitchDialog({.then((response) => {let toastReason: CheckoutSideEffectReason | null = null;let shouldDismiss = false;+ let refusedPaths: readonly string[] = [];setBranchSwitchState((prev) => {const { state: next, sideEffect } = applyCheckoutOutcome(prev, response);if (sideEffect) {toastReason = sideEffect.reason;+ refusedPaths = sideEffect.paths ?? [];shouldDismiss = next.phase === 'dismissed';}return next;});- if (toastReason === 'branch-not-found') {+ const refusalToastId = shareSwitchRefusalToastId(shareBranch);+ if (toastReason !== 'unsafe-symlinks') toast.dismiss(refusalToastId);+ if (toastReason === 'unsafe-symlinks') {+ const shownPaths = refusedPaths.slice(0, REFUSED_LINKS_SHOWN);+ const hiddenCount = refusedPaths.length - shownPaths.length;+ const listed =+ hiddenCount > 0+ ? [+ ...shownPaths,+ t`${plural(hiddenCount, { one: '# more link', other: '# more links' })}`,+ ]+ : shownPaths;+ toast.error(+ t`Did not switch to ${shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again.`,+ {+ description: listed.length === 0 ? undefined : formatToolList(listed, i18n.locale),+ id: refusalToastId,+ duration: Infinity,+ },+ );+ } else if (toastReason === 'branch-not-found') {toast.error(t`Branch ${shareBranch} no longer exists on the remote.`);} else if (toastReason === 'fetch-failed') {toast.error(t`Could not fetch branch. Check your connection.`);+ } else if (toastReason === 'symlink-check-failed') {+ toast.error(+ t`Could not check the symlinks in ${shareBranch}, so it was not switched. Try again; if it keeps failing, check that Git is installed and the project folder is readable.`,+ );} else if (toastReason === 'checkout-failed' || toastReason === 'proxy-null') {toast.error(t`Could not switch to ${shareBranch}. Try switching manually.`);}@@ -318,6 +353,7 @@ export function ShareBranchSwitchDialog({err instanceof Error ? err.message : err,);setBranchSwitchState((prev) => applyCheckoutOutcome(prev, null).state);+ toast.dismiss(shareSwitchRefusalToastId(shareBranch));toast.error(t`Could not switch to ${shareBranch}. Try switching manually.`);});}diff --git a/packages/app/src/components/ShareFreshnessWarning.dom.test.tsx b/packages/app/src/components/ShareFreshnessWarning.dom.test.tsxindex 59e5430a8..54f5500ed 100644--- a/packages/app/src/components/ShareFreshnessWarning.dom.test.tsx+++ b/packages/app/src/components/ShareFreshnessWarning.dom.test.tsx@@ -191,6 +191,44 @@ describe('ShareFreshnessWarning — recovery CTAs (FR4/FR5)', () => {expect(screen.queryByRole('link', { name: /How to push manually/ })).toBeNull();});+ test('does not offer Sync now while sync is paused on unsafe incoming symlinks', () => {+ render(+ <ShareFreshnessWarning+ freshness="absent"+ status={makeStatus({+ syncEnabled: true,+ state: 'idle',+ pausedReason: 'unsafe-incoming-symlinks',+ refusedSymlinkPaths: ['notes/leak.md'],+ })}+ kind="doc"+ />,+ );+ expect(screen.queryByRole('button', { name: 'Sync now' })).toBeNull();+ const notice = screen.getByTestId('sync-now-paused-notice');+ expect(notice.textContent).toContain('Sync is paused because incoming changes leave a symlink');+ expect(within(notice).getByTestId('sync-refused-symlinks').textContent).toBe('notes/leak.md');+ });++ test('explains a paused Git operation where Sync now would be', () => {+ render(+ <ShareFreshnessWarning+ freshness="absent"+ status={makeStatus({+ syncEnabled: true,+ state: 'idle',+ pausedReason: 'git-operation-in-progress',+ refusedSymlinkPaths: ['notes/stale.md'],+ })}+ kind="doc"+ />,+ );+ expect(screen.queryByRole('button', { name: 'Sync now' })).toBeNull();+ const notice = screen.getByTestId('sync-now-paused-notice');+ expect(notice.textContent).toContain('Git syncing is paused');+ expect(within(notice).queryByTestId('sync-refused-symlinks')).toBeNull();+ });+test('Sync now goes in-flight, then self-clears to Synced on a completed sync', () => {const { rerender } = render(<ShareFreshnessWarningdiff --git a/packages/app/src/components/ShareFreshnessWarning.tsx b/packages/app/src/components/ShareFreshnessWarning.tsxindex 63d96e7b1..481297a77 100644--- a/packages/app/src/components/ShareFreshnessWarning.tsx+++ b/packages/app/src/components/ShareFreshnessWarning.tsx@@ -11,7 +11,14 @@ import {import type { GitSyncStatus } from '@/hooks/use-git-sync-status';import { dispatchExternalLinkClick } from '@/lib/external-link';import { triggerSync } from '@/lib/trigger-sync';+import { cn } from '@/lib/utils';import { EnableSyncConfirmDialog } from './EnableSyncConfirmDialog';+import {+ displayState,+ isSyncDisablingPausedReason,+ PausedReasonNotice,+ SyncRefusedSymlinks,+} from './SyncStatusBadge';type ShareKind = 'doc' | 'folder';@@ -29,11 +36,33 @@ export function shareFreshnessRowVisible(export function syncNowActionable(status: GitSyncStatus | null): boolean {if (!status) return false;+ const state = displayState(status);+ return (+ state !== 'dormant' && state !== 'disabled' && state !== 'auth-error' && state !== 'conflict'+ );+}++export function SyncNowPausedNotice({+ status,+ className,+}: {+ status: GitSyncStatus | null;+ className?: string;+}) {+ const reason = status?.pausedReason;+ if (!isSyncDisablingPausedReason(reason)) return null;return (- status.state !== 'dormant' &&- status.state !== 'disabled' &&- status.state !== 'auth-error' &&- status.state !== 'conflict'+ <div+ className={cn('flex min-w-0 flex-col gap-1.5', className)}+ data-testid="sync-now-paused-notice"+ >+ <span>+ <PausedReasonNotice reason={reason} />+ </span>+ {reason === 'unsafe-incoming-symlinks' ? (+ <SyncRefusedSymlinks paths={status?.refusedSymlinkPaths} />+ ) : null}+ </div>);}@@ -154,7 +183,9 @@ export function ShareFreshnessWarning({ freshness, status, kind }: ShareFreshnes</Button>)}</div>- ) : null+ ) : (+ <SyncNowPausedNotice status={status} />+ )) : (<div className="flex flex-wrap items-center gap-x-3 gap-y-1.5"><Button variant="outline" size="xs" onClick={() => onToggleRequest(true)}>diff --git a/packages/app/src/components/ShareReceiveMissDialog.dom.test.tsx b/packages/app/src/components/ShareReceiveMissDialog.dom.test.tsxindex c6a519043..bed97ca1f 100644--- a/packages/app/src/components/ShareReceiveMissDialog.dom.test.tsx+++ b/packages/app/src/components/ShareReceiveMissDialog.dom.test.tsx@@ -185,6 +185,43 @@ describe('ShareReceiveMissDialog', () => {});});+ test('changed-locally during an unsafe-symlink pause explains the pause instead of offering Sync now', async () => {+ installBridge(stubVerdict({ verdict: 'changed-locally' }));+ setSyncStatus(makeSyncStatus({ syncEnabled: true }));+ await renderArmed();++ const region = screen.getByTestId('share-receive-miss-sync-paused');+ expect(region.getAttribute('role')).toBe('status');+ expect(region.textContent).toBe('');+ expect(screen.getByTestId('share-receive-miss-sync-now')).toBeTruthy();++ setSyncStatus(+ makeSyncStatus({+ syncEnabled: true,+ pausedReason: 'unsafe-incoming-symlinks',+ refusedSymlinkPaths: ['notes/leak.md'],+ }),+ );+ await waitFor(() => {+ expect(screen.queryByTestId('share-receive-miss-sync-now')).toBeNull();+ });+ expect(screen.getByTestId('share-receive-miss-sync-paused')).toBe(region);+ const notice = within(region).getByTestId('sync-now-paused-notice');+ expect(notice.textContent).toContain('Sync is paused because incoming changes leave a symlink');+ expect(within(notice).getByTestId('sync-refused-symlinks').textContent).toBe('notes/leak.md');+ });++ test('changed-locally while blocked on a conflict keeps the pause region visually hidden', async () => {+ installBridge(stubVerdict({ verdict: 'changed-locally' }));+ setSyncStatus(makeSyncStatus({ syncEnabled: true, conflictCount: 1 }));+ await renderArmed();++ expect(screen.queryByTestId('share-receive-miss-sync-now')).toBeNull();+ const region = screen.getByTestId('share-receive-miss-sync-paused');+ expect(region.className).toBe('sr-only');+ expect(region.textContent).toBe('');+ });+test('changed-locally with auto-sync ON offers Sync now; a landed sync re-probes to the honest verdict', async () => {const verdicts: ShareTargetStatusResponse[] = [{ verdict: 'changed-locally' },diff --git a/packages/app/src/components/ShareReceiveMissPanel.dom.test.tsx b/packages/app/src/components/ShareReceiveMissPanel.dom.test.tsxindex aecbd7254..128a04345 100644--- a/packages/app/src/components/ShareReceiveMissPanel.dom.test.tsx+++ b/packages/app/src/components/ShareReceiveMissPanel.dom.test.tsx@@ -306,6 +306,34 @@ describe('ShareReceiveMissPanel pull recovery', () => {expect(probeCount).toBe(2);});+ test('a pull refused for an unsafe incoming symlink explains the pause instead of asking to retry', async () => {+ installBridge(stubVerdict({ verdict: 'on-origin' }));+ setSyncStatus(pullableSyncStatus());+ await renderResolved();++ fireEvent.click(screen.getByTestId('share-receive-miss-pull-now'));+ setSyncStatus(+ pullableSyncStatus({+ lastPullUtc: 'p1',+ lastPullOutcome: 'refused',+ pausedReason: 'unsafe-incoming-symlinks',+ refusedSymlinkPaths: ['notes/leak.md', 'skills/chain'],+ }),+ );++ const failure = await screen.findByTestId('share-receive-miss-pull-error');+ await waitFor(() => {+ expect(failure.textContent).toContain('symlink');+ });+ expect(failure.textContent).not.toContain('Try again in a moment');+ const refused = screen.getByTestId('sync-refused-symlinks');+ expect(+ within(refused)+ .getAllByRole('listitem')+ .map((item) => item.textContent),+ ).toEqual(['notes/leak.md', 'skills/chain']);+ });+test('an already-syncing receiver re-probes directly, with no follow offer in between', async () => {const verdicts: ShareTargetStatusResponse[] = [{ verdict: 'on-origin' },diff --git a/packages/app/src/components/SyncStatusBadge.dom.test.tsx b/packages/app/src/components/SyncStatusBadge.dom.test.tsxindex 3c574b089..5d13e65c0 100644--- a/packages/app/src/components/SyncStatusBadge.dom.test.tsx+++ b/packages/app/src/components/SyncStatusBadge.dom.test.tsx@@ -1166,6 +1166,21 @@ describe('SyncStatusBadge runtime behavior', () => {expect(screen.getByText('.claude/launch.json')).toBeTruthy();});+ test('a refused incoming symlink names the refused link without a commit action', async () => {+ status = {+ ...baseStatus,+ state: 'idle',+ pausedReason: 'unsafe-incoming-symlinks',+ refusedSymlinkPaths: ['notes/leak.md'],+ } as GitSyncStatus;+ await renderBadge();+ expect(screen.getByRole('button', { name: 'Sync status: Sync paused' })).toBeTruthy();+ await openPopover();++ expect(screen.getByTestId('sync-refused-symlinks').textContent).toContain('notes/leak.md');+ expect(screen.queryByTestId('sync-blocking-commit')).toBeNull();+ });+test('a paused reason with no actionable paths keeps the explanatory line', async () => {status = {...baseStatus,diff --git a/packages/app/src/components/SyncStatusBadge.tsx b/packages/app/src/components/SyncStatusBadge.tsxindex 19909b820..c44e2727d 100644--- a/packages/app/src/components/SyncStatusBadge.tsx+++ b/packages/app/src/components/SyncStatusBadge.tsx@@ -111,13 +111,26 @@ function isFollowingMode(status: GitSyncStatus): boolean {return status.syncMode === 'follow';}+const SYNC_DISABLING_PAUSED_REASONS = [+ 'git-operation-in-progress',+ 'unsafe-incoming-symlinks',+] as const satisfies readonly SyncPausedReason[];++export type SyncDisablingPausedReason = (typeof SYNC_DISABLING_PAUSED_REASONS)[number];++export function isSyncDisablingPausedReason(+ reason: string | undefined,+): reason is SyncDisablingPausedReason {+ return (SYNC_DISABLING_PAUSED_REASONS as readonly (string | undefined)[]).includes(reason);+}+export function displayState(status: GitSyncStatus): GitSyncStatus['state'] {if (status.state === 'idle' && status.conflictCount > 0) {return 'conflict';}if ((status.state === 'idle' || status.state === 'offline') &&- status.pausedReason === 'git-operation-in-progress'+ isSyncDisablingPausedReason(status.pausedReason)) {return 'disabled';}@@ -231,6 +244,7 @@ const PAUSED_REASON_MESSAGES: Record<SyncPausedReason, MessageDescriptor> = {'protected-branch': msg`Protected branch — cannot push`,'no-push-permission': msg`You don't have permission to push to this repo.`,'no-commits-yet': msg`This repository has no commits yet — reopen the project to create the first commit, then Push will work`,+ 'unsafe-incoming-symlinks': msg`Sync is paused because incoming changes leave a symlink pointing outside the repository or into private files, or with a target that cannot be checked. Ask whoever pushed them to fix the link, or update Git if yours is older than 2.38. Automatic sync then resumes; in Manual mode, pull again.`,};function isKnownPausedReason(reason: string): reason is SyncPausedReason {@@ -266,6 +280,27 @@ function PausedReasonNode({ reason }: { reason: NodeRenderedPausedReason }) {}}+export function SyncRefusedSymlinks({ paths }: { paths: readonly string[] | undefined }) {+ if (paths === undefined || paths.length === 0) return null;+ return (+ <ul+ className="flex max-h-28 flex-col gap-1 overflow-y-auto overscroll-contain"+ data-testid="sync-refused-symlinks"+ >+ {paths.map((path) => (+ <li+ key={path}+ title={path}+ dir="ltr"+ className="min-w-0 truncate font-mono text-2xs text-foreground"+ >+ {path}+ </li>+ ))}+ </ul>+ );+}+export function PausedReasonNotice({ reason }: { reason: string }) {const { t } = useLingui();if (isNodeRenderedPausedReason(reason)) {@@ -1219,9 +1254,12 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {) : blockingPaths.length > 0 ? (<SyncBlockingChanges paths={blockingPaths} />) : isParkedOnNotFoundAsIdentity(status) ? null : status.pausedReason ? (- <p className="text-xs text-muted-foreground">- <PausedReasonNotice reason={status.pausedReason} />- </p>+ <>+ <p className="text-xs text-muted-foreground">+ <PausedReasonNotice reason={status.pausedReason} />+ </p>+ <SyncRefusedSymlinks paths={status.refusedSymlinkPaths} />+ </>) : !following && genuineReadOnly && status.pushPermission?.checkStatus === 'denied' ? (formatPushPermissionDenied(status.pushPermission.deniedReason, status.pushPermission).map((sentence) => (diff --git a/packages/app/src/components/settings/SettingsDialogBody.sync-mode.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogBody.sync-mode.dom.test.tsxindex d2da83ece..d0224f73a 100644--- a/packages/app/src/components/settings/SettingsDialogBody.sync-mode.dom.test.tsx+++ b/packages/app/src/components/settings/SettingsDialogBody.sync-mode.dom.test.tsx@@ -9,6 +9,7 @@ type SyncStatus = {state: string;hasRemote: boolean;pausedReason?: string;+ refusedSymlinkPaths?: string[];pushPermission?: { checkStatus: 'allowed' | 'denied' | 'unknown'; deniedReason?: string };syncEnabled?: boolean;syncMode?: 'off' | 'follow' | 'full';@@ -342,6 +343,40 @@ describe('Settings Sync section — three-way mode control (real hooks + dialog)expect(localPatchCalls).toEqual([{ autoSync: { mode: 'follow', enabled: null } }]);});+ test('a refused incoming symlink is named under the paused reason', async () => {+ projectLocalConfig = { autoSync: { mode: 'full' } };+ syncStatus = {+ state: 'idle',+ hasRemote: true,+ syncEnabled: true,+ syncMode: 'full',+ pausedReason: 'unsafe-incoming-symlinks',+ refusedSymlinkPaths: ['notes/leak.md'],+ };++ await renderSyncSection();++ expect(screen.getByTestId('sync-refused-symlinks').textContent).toContain('notes/leak.md');+ });++ test('a read-only follower still sees the symlink pause and the refused link', async () => {+ projectLocalConfig = { autoSync: { mode: 'follow' } };+ syncStatus = {+ state: 'disabled',+ hasRemote: true,+ syncEnabled: true,+ syncMode: 'follow',+ pausedReason: 'unsafe-incoming-symlinks',+ refusedSymlinkPaths: ['notes/leak.md'],+ pushPermission: { checkStatus: 'denied', deniedReason: 'no-collaborator' },+ };++ await renderSyncSection();++ expect(screen.getByTestId('settings-sync-reason').textContent).toContain('Sync is paused');+ expect(screen.getByTestId('sync-refused-symlinks').textContent).toContain('notes/leak.md');+ });+test('a genuine read-only denial disables Full but keeps Off and Pull-only reachable', async () => {const user = userEvent.setup();syncStatus = {diff --git a/packages/app/src/components/settings/SyncSection.tsx b/packages/app/src/components/settings/SyncSection.tsxindex 9874f30cd..c20998dd3 100644--- a/packages/app/src/components/settings/SyncSection.tsx+++ b/packages/app/src/components/settings/SyncSection.tsx@@ -19,6 +19,7 @@ import {hasNotFoundAsIdentityError,isParkedOnNotFoundAsIdentity,PausedReasonNotice,+ SyncRefusedSymlinks,shouldOfferReconnect,shouldOfferSignInAgain,} from '@/components/SyncStatusBadge';@@ -166,9 +167,10 @@ function SyncSectionContent({status.pushPermission.deniedReason !== 'not-authenticated' &&!notFoundAsIdentity;const parkedOnNotFound = isParkedOnNotFoundAsIdentity(status);+ const pushDenialCoversPause = isPushDenied && status?.pausedReason !== 'unsafe-incoming-symlinks';const pausedNotice = !status?.pausedReason ? null : parkedOnNotFound ? (formatSyncFailureCode('auth-not-found-as-identity')- ) : isPushDenied ? null : (+ ) : pushDenialCoversPause ? null : (<PausedReasonNotice reason={status.pausedReason} />);@@ -416,6 +418,11 @@ function SyncSectionContent({{pausedNotice}</p>)}+ {pausedNotice !== null && (status?.refusedSymlinkPaths?.length ?? 0) > 0 && (+ <div className="mt-2">+ <SyncRefusedSymlinks paths={status?.refusedSymlinkPaths} />+ </div>+ )}{}{status?.pushPermission?.checkStatus === 'denied' &&(parkedOnNotFound || showSwitchToPullOnly || showDeniedHint) ? (diff --git a/packages/app/src/components/share-receive-miss-content.tsx b/packages/app/src/components/share-receive-miss-content.tsxindex 67662831e..373898528 100644--- a/packages/app/src/components/share-receive-miss-content.tsx+++ b/packages/app/src/components/share-receive-miss-content.tsx@@ -23,7 +23,12 @@ import { type GitSyncStatus, useGitSyncStatus } from '@/hooks/use-git-sync-statuimport type { PendingReceiveNav } from '@/lib/share/pending-receive-nav-store';import { triggerSync } from '@/lib/trigger-sync';import { EnableSyncConfirmDialog } from './EnableSyncConfirmDialog';-import { syncNowActionable } from './ShareFreshnessWarning';+import { SyncNowPausedNotice, syncNowActionable } from './ShareFreshnessWarning';+import {+ isSyncDisablingPausedReason,+ PausedReasonNotice,+ SyncRefusedSymlinks,+} from './SyncStatusBadge';export type ShareTargetVerdictState =| { readonly phase: 'pending' }@@ -447,7 +452,20 @@ export function ShareReceiveMissContent({}let syncAction: ReactNode = null;if (syncStatus?.syncEnabled) {- if (syncNowActionable(syncStatus) && !pushDegraded) {+ const actionable = syncNowActionable(syncStatus);+ const noticeShown = !actionable && isSyncDisablingPausedReason(syncStatus.pausedReason);+ failureLine = (+ <div+ role="status"+ className={+ noticeShown ? 'w-full max-w-md text-balance text-1sm text-muted-foreground' : 'sr-only'+ }+ data-testid="share-receive-miss-sync-paused"+ >+ {noticeShown ? <SyncNowPausedNotice status={syncStatus} /> : null}+ </div>+ );+ if (actionable && !pushDegraded) {syncAction = <SyncNowButton status={syncStatus} onSyncCompleted={onSyncCompleted} />;}} else if (syncStatus !== null) {@@ -487,20 +505,31 @@ export function ShareReceiveMissContent({</Trans>);}+ const refusedForUnsafeSymlinks =+ pull.failure === 'refused' && syncStatus?.pausedReason === 'unsafe-incoming-symlinks';failureLine = (- <p- role="alert"- className={- pull.failure !== null ? 'max-w-md text-balance text-1sm text-destructive' : 'sr-only'- }- data-testid="share-receive-miss-pull-error"+ <div+ className={refusedForUnsafeSymlinks ? 'flex w-full max-w-md flex-col gap-2' : 'contents'}>- {pull.failure === 'refused' ? (- <Trans>Another sync operation is in progress. Try again in a moment.</Trans>- ) : pull.failure === 'error' ? (- <Trans>Couldn't pull from GitHub. Check your connection and sign-in, then retry.</Trans>+ <p+ role="alert"+ className={+ pull.failure !== null ? 'max-w-md text-balance text-1sm text-destructive' : 'sr-only'+ }+ data-testid="share-receive-miss-pull-error"+ >+ {refusedForUnsafeSymlinks ? (+ <PausedReasonNotice reason="unsafe-incoming-symlinks" />+ ) : pull.failure === 'refused' ? (+ <Trans>Another sync operation is in progress. Try again in a moment.</Trans>+ ) : pull.failure === 'error' ? (+ <Trans>Couldn't pull from GitHub. Check your connection and sign-in, then retry.</Trans>+ ) : null}+ </p>+ {refusedForUnsafeSymlinks ? (+ <SyncRefusedSymlinks paths={syncStatus?.refusedSymlinkPaths} />) : null}- </p>+ </div>);actions = (<>diff --git a/packages/app/src/hooks/use-git-sync-status.ts b/packages/app/src/hooks/use-git-sync-status.tsindex ce5009aa4..b5c7598b3 100644--- a/packages/app/src/hooks/use-git-sync-status.ts+++ b/packages/app/src/hooks/use-git-sync-status.ts@@ -47,6 +47,7 @@ export interface GitSyncStatus {pullErrorCode?: SyncErrorCode;pausedReason?: string;blockingPaths?: string[];+ refusedSymlinkPaths?: string[];pushPermission?: GitPushPermission;}diff --git a/packages/app/src/lib/share/branch-switch-flow.test.ts b/packages/app/src/lib/share/branch-switch-flow.test.tsindex dd36fb545..37a5c2981 100644--- a/packages/app/src/lib/share/branch-switch-flow.test.ts+++ b/packages/app/src/lib/share/branch-switch-flow.test.ts@@ -188,6 +188,13 @@ describe('classifyCheckoutOutcome', () => {});});+ test('symlink-check-failed classifies to its own stay-with-toast reason', () => {+ expect(classifyCheckoutOutcome({ ok: false, reason: 'symlink-check-failed' })).toEqual({+ action: 'stay-with-toast',+ reason: 'symlink-check-failed',+ });+ });+test('dirty-conflict re-renders the variant with the fresh file list — never navigates', () => {expect(classifyCheckoutOutcome({@@ -317,6 +324,25 @@ describe('BranchSwitchDialogState transitions', () => {expect(result.sideEffect).toEqual({ kind: 'toast', reason: 'checkout-failed' });});+ test('an unsafe-symlink refusal returns to ready with its own toast and the refused links', () => {+ const switching: BranchSwitchDialogState = {+ phase: 'switching',+ info: cleanInfo(),+ pendingDoc: 'docs/foo.md',+ };+ const result = applyCheckoutOutcome(switching, {+ ok: false,+ reason: 'unsafe-symlinks',+ refusedSymlinkPaths: ['notes/leak.md'],+ });+ expect(result.state).toEqual({ phase: 'ready', info: cleanInfo() });+ expect(result.sideEffect).toEqual({+ kind: 'toast',+ reason: 'unsafe-symlinks',+ paths: ['notes/leak.md'],+ });+ });+test('checkout null (proxy failure) returns to ready with proxy-null toast', () => {const switching: BranchSwitchDialogState = {phase: 'switching',diff --git a/packages/app/src/lib/share/branch-switch-flow.ts b/packages/app/src/lib/share/branch-switch-flow.tsindex 6a2adf1a3..2ec41a678 100644--- a/packages/app/src/lib/share/branch-switch-flow.ts+++ b/packages/app/src/lib/share/branch-switch-flow.ts@@ -59,7 +59,7 @@ export type CheckoutOutcome =| { readonly action: 'dismiss-with-toast'; readonly reason: 'branch-not-found' }| {readonly action: 'stay-with-toast';- readonly reason: 'fetch-failed' | 'checkout-failed';+ readonly reason: 'fetch-failed' | 'checkout-failed' | 'symlink-check-failed';}| { readonly action: 'rerender-conflict'; readonly files: readonly string[] }| {@@ -68,6 +68,10 @@ export type CheckoutOutcome =}| {readonly action: 'branch-diverged';+ }+ | {+ readonly action: 'refused-unsafe-symlinks';+ readonly paths: readonly string[];};export function classifyCheckoutOutcome(response: CheckoutResponse): CheckoutOutcome {@@ -91,6 +95,10 @@ export function classifyCheckoutOutcome(response: CheckoutResponse): CheckoutOut}case 'ff-diverged':return { action: 'branch-diverged' };+ case 'unsafe-symlinks':+ return { action: 'refused-unsafe-symlinks', paths: response.refusedSymlinkPaths ?? [] };+ case 'symlink-check-failed':+ return { action: 'stay-with-toast', reason: 'symlink-check-failed' };default: {const _exhaustive: never = response.reason;throw new Error(`Unhandled CheckoutFailureReason: ${String(_exhaustive)}`);@@ -201,11 +209,17 @@ export type CheckoutSideEffectReason =| 'proxy-null'| 'fetch-failed'| 'checkout-failed'- | 'branch-not-found';+ | 'branch-not-found'+ | 'unsafe-symlinks'+ | 'symlink-check-failed';export interface ApplyCheckoutOutcomeResult {readonly state: BranchSwitchDialogState;- readonly sideEffect?: { readonly kind: 'toast'; readonly reason: CheckoutSideEffectReason };+ readonly sideEffect?: {+ readonly kind: 'toast';+ readonly reason: CheckoutSideEffectReason;+ readonly paths?: readonly string[];+ };}export function applyCheckoutOutcome(@@ -255,6 +269,12 @@ export function applyCheckoutOutcome(state: { phase: 'verdict', info: state.info, resolution: { kind: 'diverged' } },};}+ if (outcome.action === 'refused-unsafe-symlinks') {+ return {+ state: { phase: 'ready', info: state.info },+ sideEffect: { kind: 'toast', reason: 'unsafe-symlinks', paths: outcome.paths },+ };+ }return {state: { phase: 'ready', info: state.info },sideEffect: { kind: 'toast', reason: outcome.reason },diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.jsonindex c31ea712a..e51fd2380 100644--- a/packages/app/src/locales/ar/messages.json+++ b/packages/app/src/locales/ar/messages.json@@ -212,6 +212,11 @@"0t0bbC": ["تعذّر حفظ تفضيل المزامنة: ", ["detail"]],"0tV-rz": ["لا تزال الإعدادات قيد التحميل. أعد المحاولة بعد قليل."],"0uTHCg": ["ابدأ مشروع OpenKnowledge جديدًا."],+ "0uxLib": [+ "تعذّر فحص الروابط الرمزية في ",+ ["shareBranch"],+ "، لذا لم يتم التبديل إليه. حاول مرة أخرى؛ وإذا استمر الفشل، فتأكد من تثبيت Git ومن إمكانية قراءة مجلد المشروع."+ ],"0wkh7o": ["سجلات OpenKnowledge، بما في ذلك النشاط عبر المشاريع."],"0wswKc": ["خط أفقي يفصل بين الأقسام."],"0x9smA": ["لم تعد هذه الصفحة في هذا المسار."],@@ -486,6 +491,11 @@"هل لديك مستودع git بالفعل؟ أضفه بالأمر <0>git remote add origin <url></0> في مجلد هذا المشروع. تُحدَّث هذه الصفحة تلقائيًا بمجرد اكتشاف مستودع بعيد."],"45MZFs": ["الأوامر"],+ "461Vg9": [+ "لم يتم التبديل إلى ",+ ["shareBranch"],+ ": يحتوي على رابط رمزي يشير إلى خارج المستودع أو إلى ملفات خاصة أو إلى موضع لا يمكن التحقق منه. عادةً يجب على من دفع الفرع إصلاح الرابط. إذا تعذّرت قراءة مجلد على هذا الكمبيوتر، فاجعله قابلًا للقراءة وحاول مرة أخرى."+ ],"46YgRZ": ["إضافة كتلة أدناه"],"484LKL": ["إزالة الرابط"],"49Mb7P": ["تعذّر التحقق مما إذا كان Slidev مثبّتًا. عُد إلى هذه النافذة لإعادة المحاولة."],@@ -970,6 +980,9 @@"8nWu1k": ["مخطط فارغ"],"8oWgty": ["تحديد كل التعليقات للإرسال"],"8qgfac": ["خوادم MCP"],+ "8qsUJv": [+ "المزامنة متوقفة مؤقتًا لأن التغييرات الواردة تترك رابطًا رمزيًا يشير إلى خارج المستودع أو إلى ملفات خاصة، أو بوجهة لا يمكن التحقق منها. اطلب ممن دفعها إصلاح الرابط، أو حدّث Git إذا كان إصدارك أقدم من 2.38. بعد ذلك تُستأنف المزامنة التلقائية؛ وفي الوضع اليدوي، اسحب مرة أخرى."+ ],"8rZ1pk": ["تمكين ", ["id"]],"8ruqQi": ["روابط داخلية معطلة"],"8t9CRE": ["يجري تشغيل ", ["agentName"], "…"],@@ -5481,6 +5494,20 @@"pA16WG": ["لا يملك هذا المشروع أي مستودع بعيد على GitHub."],"pAgkuZ": ["يجري إعادة فتح «", ["docName"], "» بذاكرة تعاون محلية جديدة."],"pBROkv": ["شكرًا لاشتراكك. راقب بريدك لتحديثات المنتج."],+ "pCJv30": [+ [+ "hiddenCount",+ "plural",+ {+ "zero": ["لا روابط أخرى"],+ "one": ["رابط واحد آخر"],+ "two": ["رابطان آخران"],+ "few": ["#", " روابط أخرى"],+ "many": ["#", " رابطًا آخر"],+ "other": ["#", " رابط آخر"]+ }+ ]+ ],"pCralD": ["النقل إلى جزء جديد على اليسار"],"pEQFsW": ["لا توجد مشاريع مطابقة."],"pFPzHA": ["منتقي الرموز التعبيرية"],diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.poindex 67086bb48..e729f06c8 100644--- a/packages/app/src/locales/ar/messages.po+++ b/packages/app/src/locales/ar/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, zero {مجلدات} one {مجلد} two {مجلداmsgid "{formatted} GitHub stars"msgstr "{formatted} نجمة على GitHub"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "{hiddenCount, plural, one {# more link} other {# more links}}"+msgstr "{hiddenCount, plural, zero {لا روابط أخرى} one {رابط واحد آخر} two {رابطان آخران} few {# روابط أخرى} many {# رابطًا آخر} other {# رابط آخر}}"+#: src/lib/restart-collab-server.tsmsgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."msgstr "{holder} يخدم هذا المشروع، لذا لن يوقفه هذا التطبيق. أغلق هذه النافذة وافتح المشروع مرة أخرى لإيقاف خادم {holder} وفتح المشروع هنا."@@ -3934,6 +3938,10 @@ msgstr "يجري النسخ"msgid "Copying..."msgstr "يجري النسخ..."+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Could not check the symlinks in {shareBranch}, so it was not switched. Try again; if it keeps failing, check that Git is installed and the project folder is readable."+msgstr "تعذّر فحص الروابط الرمزية في {shareBranch}، لذا لم يتم التبديل إليه. حاول مرة أخرى؛ وإذا استمر الفشل، فتأكد من تثبيت Git ومن إمكانية قراءة مجلد المشروع."+#: src/components/settings/SkillTargetsPicker.tsxmsgid "Could not classify the merge — try again."msgstr "تعذّر تصنيف الدمج — حاول مرة أخرى."@@ -5164,6 +5172,10 @@ msgstr "مخطط من مصدر Mermaid — انسيابي، تسلسلي، أصmsgid "Diagram view mode"msgstr "وضع عرض المخطط"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."+msgstr "لم يتم التبديل إلى {shareBranch}: يحتوي على رابط رمزي يشير إلى خارج المستودع أو إلى ملفات خاصة أو إلى موضع لا يمكن التحقق منه. عادةً يجب على من دفع الفرع إصلاح الرابط. إذا تعذّرت قراءة مجلد على هذا الكمبيوتر، فاجعله قابلًا للقراءة وحاول مرة أخرى."+#: src/components/AgentDiffPane.tsx#: src/components/TimelineDiffPane.tsxmsgid "Diff render mode"@@ -14114,6 +14126,10 @@ msgstr "فشلت المزامنة — راجع سجلات الخادم للتفmsgid "Sync is failing. See the sync status for details."msgstr "المزامنة تفشل. راجع حالة المزامنة للتفاصيل."+#: src/components/SyncStatusBadge.tsx+msgid "Sync is paused because incoming changes leave a symlink pointing outside the repository or into private files, or with a target that cannot be checked. Ask whoever pushed them to fix the link, or update Git if yours is older than 2.38. Automatic sync then resumes; in Manual mode, pull again."+msgstr "المزامنة متوقفة مؤقتًا لأن التغييرات الواردة تترك رابطًا رمزيًا يشير إلى خارج المستودع أو إلى ملفات خاصة، أو بوجهة لا يمكن التحقق منها. اطلب ممن دفعها إصلاح الرابط، أو حدّث Git إذا كان إصدارك أقدم من 2.38. بعد ذلك تُستأنف المزامنة التلقائية؛ وفي الوضع اليدوي، اسحب مرة أخرى."+#: src/components/SyncBlockingChanges.tsxmsgid "Sync is paused. Commit these local edits to continue, or sort them out in a terminal."msgstr "المزامنة متوقفة مؤقتًا. ثبّت هذه التعديلات المحلية للمتابعة، أو عالجها في الطرفية."diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.jsonindex 821d51597..efcf99ee2 100644--- a/packages/app/src/locales/bn/messages.json+++ b/packages/app/src/locales/bn/messages.json@@ -154,6 +154,10 @@"0t0bbC": ["সিঙ্ক পছন্দ সংরক্ষণ করা যায়নি: ", ["detail"]],"0tV-rz": ["সেটিংস এখনও লোড হচ্ছে। একটু পরে আবার চেষ্টা করুন।"],"0uTHCg": ["একটি নতুন OpenKnowledge প্রকল্প শুরু করুন।"],+ "0uxLib": [+ ["shareBranch"],+ "-এর সিমলিংকগুলো যাচাই করা যায়নি, তাই সেখানে যাওয়া হয়নি। আবার চেষ্টা করুন; বারবার ব্যর্থ হলে Git ইনস্টল করা আছে কি না এবং প্রজেক্ট ফোল্ডারটি পড়া যায় কি না তা দেখুন।"+ ],"0wkh7o": ["OpenKnowledge লগ, যাতে বিভিন্ন প্রজেক্টের কার্যকলাপ অন্তর্ভুক্ত থাকে।"],"0wswKc": ["বিভাগ ভাগ করে দেওয়া অনুভূমিক রেখা।"],"0x9smA": ["এই পৃষ্ঠাটি আর এই পাথে নেই।"],@@ -402,6 +406,10 @@"আগে থেকেই একটি git রিপোজিটরি আছে? এই প্রকল্পের ফোল্ডারে <0>git remote add origin <url></0> দিয়ে সেটি যোগ করুন। রিমোট শনাক্ত হলেই এই পাতা নিজে থেকে হালনাগাদ হয়।"],"45MZFs": ["কমান্ড"],+ "461Vg9": [+ ["shareBranch"],+ "-এ যাওয়া হয়নি: এতে এমন একটি সিমলিংক আছে যা রিপোজিটরির বাইরে, ব্যক্তিগত ফাইলের দিকে, অথবা এমন কোথাও নির্দেশ করে যা যাচাই করা যায় না। সাধারণত যিনি ব্রাঞ্চটি পাঠিয়েছেন তাঁকেই লিংকটি ঠিক করতে হবে। এই কম্পিউটারের কোনো ফোল্ডার পড়া না গেলে সেটি পড়ার যোগ্য করে আবার চেষ্টা করুন।"+ ],"46YgRZ": ["নিচে ব্লক যোগ করুন"],"484LKL": ["লিংক সরান"],"49Mb7P": ["Slidev ইনস্টল আছে কিনা তা যাচাই করা যায়নি। আবার চেষ্টা করতে এই উইন্ডোতে ফিরে আসুন।"],@@ -800,6 +808,9 @@"8nWu1k": ["খালি চিত্র"],"8oWgty": ["পাঠানোর জন্য সব মন্তব্য চিহ্নিত করুন"],"8qgfac": ["MCP সার্ভার"],+ "8qsUJv": [+ "সিঙ্ক থেমে আছে কারণ আগত পরিবর্তনের ফলে একটি সিমলিংক রিপোজিটরির বাইরে বা ব্যক্তিগত ফাইলের দিকে নির্দেশ করে, অথবা এর লক্ষ্য যাচাই করা যায় না। যিনি পরিবর্তনগুলো পাঠিয়েছেন তাঁকে লিংকটি ঠিক করতে বলুন, অথবা আপনার Git 2.38-এর চেয়ে পুরোনো হলে Git আপডেট করুন। এরপর স্বয়ংক্রিয় সিঙ্ক আবার চালু হবে; ম্যানুয়াল মোডে আবার টানুন।"+ ],"8rZ1pk": [["id"], " সক্ষম করুন"],"8ruqQi": ["ভাঙা অভ্যন্তরীণ লিংক"],"8t9CRE": [["agentName"], " শুরু করা হচ্ছে…"],@@ -4651,6 +4662,13 @@"pA16WG": ["এই প্রকল্পের কোনো GitHub রিমোট নেই।"],"pAgkuZ": ["\"", ["docName"], "\" একটি নতুন স্থানীয় সহযোগিতা ক্যাশসহ আবার খোলা হচ্ছে।"],"pBROkv": ["সদস্য হওয়ার জন্য ধন্যবাদ। পণ্যের হালনাগাদের জন্য আপনার ইনবক্সে চোখ রাখুন।"],+ "pCJv30": [+ [+ "hiddenCount",+ "plural",+ { "one": ["আরও ", "#", "টি লিংক"], "other": ["আরও ", "#", "টি লিংক"] }+ ]+ ],"pCralD": ["বাঁ পাশের নতুন প্যানে সরান"],"pEQFsW": ["মিলে যাওয়া কোনো প্রকল্প নেই।"],"pFPzHA": ["ইমোজি নির্বাচক"],diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.poindex a110bf539..1aafe981f 100644--- a/packages/app/src/locales/bn/messages.po+++ b/packages/app/src/locales/bn/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, one {ফোল্ডার} other {ফোল্ডmsgid "{formatted} GitHub stars"msgstr "{formatted}টি GitHub স্টার"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "{hiddenCount, plural, one {# more link} other {# more links}}"+msgstr "{hiddenCount, plural, one {আরও #টি লিংক} other {আরও #টি লিংক}}"+#: src/lib/restart-collab-server.tsmsgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."msgstr "{holder} এই প্রজেক্টটি সার্ভ করছে, তাই এই অ্যাপ এটি বন্ধ করবে না। এই উইন্ডোটি বন্ধ করুন এবং {holder}-এর সার্ভার বন্ধ করে প্রজেক্টটি এখানে খুলতে আবার প্রজেক্টটি খুলুন।"@@ -3930,6 +3934,10 @@ msgstr "কপি করা হচ্ছে"msgid "Copying..."msgstr "কপি করা হচ্ছে…"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Could not check the symlinks in {shareBranch}, so it was not switched. Try again; if it keeps failing, check that Git is installed and the project folder is readable."+msgstr "{shareBranch}-এর সিমলিংকগুলো যাচাই করা যায়নি, তাই সেখানে যাওয়া হয়নি। আবার চেষ্টা করুন; বারবার ব্যর্থ হলে Git ইনস্টল করা আছে কি না এবং প্রজেক্ট ফোল্ডারটি পড়া যায় কি না তা দেখুন।"+#: src/components/settings/SkillTargetsPicker.tsxmsgid "Could not classify the merge — try again."msgstr "মার্জটি শ্রেণিবদ্ধ করা যায়নি — আবার চেষ্টা করুন।"@@ -5160,6 +5168,10 @@ msgstr "Mermaid সোর্স থেকে চিত্র — ফ্লোচmsgid "Diagram view mode"msgstr "চিত্র দেখার মোড"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."+msgstr "{shareBranch}-এ যাওয়া হয়নি: এতে এমন একটি সিমলিংক আছে যা রিপোজিটরির বাইরে, ব্যক্তিগত ফাইলের দিকে, অথবা এমন কোথাও নির্দেশ করে যা যাচাই করা যায় না। সাধারণত যিনি ব্রাঞ্চটি পাঠিয়েছেন তাঁকেই লিংকটি ঠিক করতে হবে। এই কম্পিউটারের কোনো ফোল্ডার পড়া না গেলে সেটি পড়ার যোগ্য করে আবার চেষ্টা করুন।"+#: src/components/AgentDiffPane.tsx#: src/components/TimelineDiffPane.tsxmsgid "Diff render mode"@@ -14110,6 +14122,10 @@ msgstr "সিঙ্ক ব্যর্থ — বিস্তারিত জmsgid "Sync is failing. See the sync status for details."msgstr "সিঙ্ক ব্যর্থ হচ্ছে। বিস্তারিত জানতে সিঙ্কের অবস্থা দেখুন।"+#: src/components/SyncStatusBadge.tsx+msgid "Sync is paused because incoming changes leave a symlink pointing outside the repository or into private files, or with a target that cannot be checked. Ask whoever pushed them to fix the link, or update Git if yours is older than 2.38. Automatic sync then resumes; in Manual mode, pull again."+msgstr "সিঙ্ক থেমে আছে কারণ আগত পরিবর্তনের ফলে একটি সিমলিংক রিপোজিটরির বাইরে বা ব্যক্তিগত ফাইলের দিকে নির্দেশ করে, অথবা এর লক্ষ্য যাচাই করা যায় না। যিনি পরিবর্তনগুলো পাঠিয়েছেন তাঁকে লিংকটি ঠিক করতে বলুন, অথবা আপনার Git 2.38-এর চেয়ে পুরোনো হলে Git আপডেট করুন। এরপর স্বয়ংক্রিয় সিঙ্ক আবার চালু হবে; ম্যানুয়াল মোডে আবার টানুন।"+#: src/components/SyncBlockingChanges.tsxmsgid "Sync is paused. Commit these local edits to continue, or sort them out in a terminal."msgstr "সিঙ্ক থেমে আছে। চালিয়ে যেতে এই স্থানীয় সম্পাদনাগুলি কমিট করুন, অথবা টার্মিনালে সেগুলি মিটিয়ে নিন।"diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex ed6a225ca..f96762422 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -158,6 +158,11 @@"0t0bbC": ["Could not save sync preference: ", ["detail"]],"0tV-rz": ["Settings are still loading. Try again in a moment."],"0uTHCg": ["Start a new OpenKnowledge project."],+ "0uxLib": [+ "Could not check the symlinks in ",+ ["shareBranch"],+ ", so it was not switched. Try again; if it keeps failing, check that Git is installed and the project folder is readable."+ ],"0wkh7o": ["OpenKnowledge logs, including activity across projects."],"0wswKc": ["Horizontal rule that divides sections."],"0x9smA": ["This page is no longer at this path."],@@ -417,6 +422,11 @@"Already have a git repository? Add it with <0>git remote add origin <url></0> in this project's folder. This page updates automatically once a remote is detected."],"45MZFs": ["Commands"],+ "461Vg9": [+ "Did not switch to ",+ ["shareBranch"],+ ": it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."+ ],"46YgRZ": ["Add block below"],"484LKL": ["Remove link"],"49Mb7P": ["We couldn't check whether Slidev is installed. Return to this window to retry."],@@ -828,6 +838,9 @@"8nWu1k": ["Empty diagram"],"8oWgty": ["Mark every comment to send"],"8qgfac": ["MCP servers"],+ "8qsUJv": [+ "Sync is paused because incoming changes leave a symlink pointing outside the repository or into private files, or with a target that cannot be checked. Ask whoever pushed them to fix the link, or update Git if yours is older than 2.38. Automatic sync then resumes; in Manual mode, pull again."+ ],"8rZ1pk": ["Enable ", ["id"]],"8ruqQi": ["Broken internal links"],"8t9CRE": ["Starting ", ["agentName"], "…"],@@ -4808,6 +4821,9 @@"pA16WG": ["This project has no GitHub remote."],"pAgkuZ": ["Reopening \"", ["docName"], "\" with a fresh local collaboration cache."],"pBROkv": ["Thanks for subscribing. Watch your inbox for product updates."],+ "pCJv30": [+ ["hiddenCount", "plural", { "one": ["#", " more link"], "other": ["#", " more links"] }]+ ],"pCralD": ["Move to new pane left"],"pEQFsW": ["No matching projects."],"pFPzHA": ["Emoji picker"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 1f83d9bef..64ef23dc6 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, one {folder} other {folders}}"msgid "{formatted} GitHub stars"msgstr "{formatted} GitHub stars"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "{hiddenCount, plural, one {# more link} other {# more links}}"+msgstr "{hiddenCount, plural, one {# more link} other {# more links}}"+#: src/lib/restart-collab-server.tsmsgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."msgstr "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."@@ -3934,6 +3938,10 @@ msgstr "Copying"msgid "Copying..."msgstr "Copying..."+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Could not check the symlinks in {shareBranch}, so it was not switched. Try again; if it keeps failing, check that Git is installed and the project folder is readable."+msgstr "Could not check the symlinks in {shareBranch}, so it was not switched. Try again; if it keeps failing, check that Git is installed and the project folder is readable."+#: src/components/settings/SkillTargetsPicker.tsxmsgid "Could not classify the merge — try again."msgstr "Could not classify the merge — try again."@@ -5164,6 +5172,10 @@ msgstr "Diagram from Mermaid source — flowchart, sequence, class, state, ER, gmsgid "Diagram view mode"msgstr "Diagram view mode"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."+msgstr "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."+#: src/components/AgentDiffPane.tsx#: src/components/TimelineDiffPane.tsxmsgid "Diff render mode"@@ -14114,6 +14126,10 @@ msgstr "Sync failed — check the server logs for details."msgid "Sync is failing. See the sync status for details."msgstr "Sync is failing. See the sync status for details."+#: src/components/SyncStatusBadge.tsx+msgid "Sync is paused because incoming changes leave a symlink pointing outside the repository or into private files, or with a target that cannot be checked. Ask whoever pushed them to fix the link, or update Git if yours is older than 2.38. Automatic sync then resumes; in Manual mode, pull again."+msgstr "Sync is paused because incoming changes leave a symlink pointing outside the repository or into private files, or with a target that cannot be checked. Ask whoever pushed them to fix the link, or update Git if yours is older than 2.38. Automatic sync then resumes; in Manual mode, pull again."+#: src/components/SyncBlockingChanges.tsxmsgid "Sync is paused. Commit these local edits to continue, or sort them out in a terminal."msgstr "Sync is paused. Commit these local edits to continue, or sort them out in a terminal."diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.jsonindex 4537425ed..847373ecf 100644--- a/packages/app/src/locales/es/messages.json+++ b/packages/app/src/locales/es/messages.json@@ -186,6 +186,11 @@"0t0bbC": ["No se pudo guardar la preferencia de sincronización: ", ["detail"]],"0tV-rz": ["Los ajustes todavía se están cargando. Inténtalo de nuevo en un momento."],"0uTHCg": ["Empieza un proyecto de OpenKnowledge."],+ "0uxLib": [+ "No se pudieron comprobar los enlaces simbólicos de ",+ ["shareBranch"],+ ", así que no se cambió. Vuelve a intentarlo; si sigue fallando, comprueba que Git esté instalado y que la carpeta del proyecto se pueda leer."+ ],"0wkh7o": ["Registros de OpenKnowledge, incluida actividad de varios proyectos."],"0wswKc": ["Línea horizontal que separa secciones."],"0x9smA": ["Esta página ya no está en esta ruta."],@@ -480,6 +485,11 @@"¿Ya tienes un repositorio git? Añádelo con <0>git remote add origin <url></0> en la carpeta de este proyecto. Esta página se actualiza automáticamente en cuanto se detecta un remoto."],"45MZFs": ["Comandos"],+ "461Vg9": [+ "No se cambió a ",+ ["shareBranch"],+ ": tiene un enlace simbólico que apunta fuera del repositorio, a archivos privados o a un lugar que no se puede comprobar. Normalmente quien envió la rama tiene que corregir el enlace. Si no se puede leer una carpeta de este equipo, hazla legible y vuelve a intentarlo."+ ],"46YgRZ": ["Añadir bloque debajo"],"484LKL": ["Quitar el enlace"],"49Mb7P": [@@ -966,6 +976,9 @@"8nWu1k": ["Diagrama vacío"],"8oWgty": ["Marcar todos los comentarios para enviar"],"8qgfac": ["Servidores MCP"],+ "8qsUJv": [+ "La sincronización está en pausa porque los cambios entrantes dejan un enlace simbólico que apunta fuera del repositorio o a archivos privados, o con un destino que no se puede comprobar. Pide a quien los envió que corrija el enlace, o actualiza Git si tu versión es anterior a la 2.38. Después, la sincronización automática se reanuda; en modo Manual, vuelve a hacer pull."+ ],"8rZ1pk": ["Habilitar ", ["id"]],"8ruqQi": ["Enlaces internos rotos"],"8t9CRE": ["Iniciando ", ["agentName"], "…"],@@ -5541,6 +5554,17 @@"pBROkv": ["Gracias por suscribirte. Estate atento a tu correo para recibir novedades del producto."],+ "pCJv30": [+ [+ "hiddenCount",+ "plural",+ {+ "one": ["#", " enlace más"],+ "many": ["#", " enlaces más"],+ "other": ["#", " enlaces más"]+ }+ ]+ ],"pCralD": ["Mover a un panel nuevo a la izquierda"],"pEQFsW": ["Ningún proyecto coincide."],"pFPzHA": ["Selector de emojis"],diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.poindex 86c849cbe..3aab897ad 100644--- a/packages/app/src/locales/es/messages.po+++ b/packages/app/src/locales/es/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, one {carpeta} many {carpetas} other {carpetas}}"msgid "{formatted} GitHub stars"msgstr "{formatted} estrellas en GitHub"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "{hiddenCount, plural, one {# more link} other {# more links}}"+msgstr "{hiddenCount, plural, one {# enlace más} many {# enlaces más} other {# enlaces más}}"+#: src/lib/restart-collab-server.tsmsgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."msgstr "{holder} está sirviendo este proyecto, así que esta app no lo detendrá. Cierra esta ventana y vuelve a abrir el proyecto para detener el servidor de {holder} y abrir el proyecto aquí."@@ -3934,6 +3938,10 @@ msgstr "Copiando"msgid "Copying..."msgstr "Copiando..."+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Could not check the symlinks in {shareBranch}, so it was not switched. Try again; if it keeps failing, check that Git is installed and the project folder is readable."+msgstr "No se pudieron comprobar los enlaces simbólicos de {shareBranch}, así que no se cambió. Vuelve a intentarlo; si sigue fallando, comprueba que Git esté instalado y que la carpeta del proyecto se pueda leer."+#: src/components/settings/SkillTargetsPicker.tsxmsgid "Could not classify the merge — try again."msgstr "No se pudo clasificar la fusión. Inténtalo de nuevo."@@ -5164,6 +5172,10 @@ msgstr "Diagrama a partir de código Mermaid: de flujo, de secuencia, de clases,msgid "Diagram view mode"msgstr "Modo de vista del diagrama"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."+msgstr "No se cambió a {shareBranch}: tiene un enlace simbólico que apunta fuera del repositorio, a archivos privados o a un lugar que no se puede comprobar. Normalmente quien envió la rama tiene que corregir el enlace. Si no se puede leer una carpeta de este equipo, hazla legible y vuelve a intentarlo."+#: src/components/AgentDiffPane.tsx#: src/components/TimelineDiffPane.tsxmsgid "Diff render mode"@@ -14114,6 +14126,10 @@ msgstr "Falló la sincronización: consulta los registros del servidor para vermsgid "Sync is failing. See the sync status for details."msgstr "La sincronización está fallando. Consulta el estado de sincronización para ver los detalles."+#: src/components/SyncStatusBadge.tsx+msgid "Sync is paused because incoming changes leave a symlink pointing outside the repository or into private files, or with a target that cannot be checked. Ask whoever pushed them to fix the link, or update Git if yours is older than 2.38. Automatic sync then resumes; in Manual mode, pull again."+msgstr "La sincronización está en pausa porque los cambios entrantes dejan un enlace simbólico que apunta fuera del repositorio o a archivos privados, o con un destino que no se puede comprobar. Pide a quien los envió que corrija el enlace, o actualiza Git si tu versión es anterior a la 2.38. Después, la sincronización automática se reanuda; en modo Manual, vuelve a hacer pull."+#: src/components/SyncBlockingChanges.tsxmsgid "Sync is paused. Commit these local edits to continue, or sort them out in a terminal."msgstr "La sincronización está en pausa. Confirma estas ediciones locales para continuar, o resuélvelas en una terminal."diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.jsonindex 021c80bc5..0ce6e7076 100644--- a/packages/app/src/locales/fr/messages.json+++ b/packages/app/src/locales/fr/messages.json@@ -190,6 +190,11 @@"0t0bbC": ["Impossible d'enregistrer la préférence de synchronisation : ", ["detail"]],"0tV-rz": ["Les paramètres sont toujours en cours de chargement. Réessayez dans un instant."],"0uTHCg": ["Démarrez un nouveau projet OpenKnowledge."],+ "0uxLib": [+ "Impossible de vérifier les liens symboliques de ",+ ["shareBranch"],+ " : le passage n'a donc pas eu lieu. Réessayez ; si l'échec persiste, vérifiez que Git est installé et que le dossier du projet est lisible."+ ],"0wkh7o": ["Journaux OpenKnowledge, y compris l’activité de plusieurs projets."],"0wswKc": ["Filet horizontal qui sépare les sections."],"0x9smA": ["Cette page ne se trouve plus à ce chemin."],@@ -496,6 +501,11 @@"Vous avez déjà un dépôt git ? Ajoutez-le avec <0>git remote add origin <url></0> dans le dossier de ce projet. Cette page se met à jour automatiquement dès qu'un dépôt distant est détecté."],"45MZFs": ["Commandes"],+ "461Vg9": [+ "Le passage à ",+ ["shareBranch"],+ " n'a pas eu lieu : cette branche contient un lien symbolique qui pointe hors du dépôt, vers des fichiers privés ou vers un emplacement qui ne peut pas être vérifié. En général, la personne qui a poussé la branche doit corriger le lien. Si un dossier de cet ordinateur ne peut pas être lu, rendez-le lisible et réessayez."+ ],"46YgRZ": ["Ajouter un bloc en dessous"],"484LKL": ["Retirer le lien"],"49Mb7P": [@@ -995,6 +1005,9 @@"8nWu1k": ["Diagramme vide"],"8oWgty": ["Cocher tous les commentaires à envoyer"],"8qgfac": ["Serveurs MCP"],+ "8qsUJv": [+ "La synchronisation est en pause, car les modifications entrantes laissent un lien symbolique qui pointe hors du dépôt ou vers des fichiers privés, ou dont la cible ne peut pas être vérifiée. Demandez à la personne qui les a poussées de corriger le lien, ou mettez à jour Git si votre version est antérieure à 2.38. La synchronisation automatique reprend ensuite ; en mode Manuel, tirez à nouveau."+ ],"8rZ1pk": ["Activer ", ["id"]],"8ruqQi": ["Liens internes cassés"],"8t9CRE": ["Démarrage de ", ["agentName"], "…"],@@ -5588,6 +5601,17 @@"pBROkv": ["Merci pour votre abonnement. Surveillez votre boîte mail pour les nouveautés du produit."],+ "pCJv30": [+ [+ "hiddenCount",+ "plural",+ {+ "one": ["#", " autre lien"],+ "many": ["#", " autres liens"],+ "other": ["#", " autres liens"]+ }+ ]+ ],"pCralD": ["Déplacer vers un nouveau volet à gauche"],"pEQFsW": ["Aucun projet correspondant."],"pFPzHA": ["Sélecteur d'émojis"],diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.poindex 39fbc48f6..409150ef6 100644--- a/packages/app/src/locales/fr/messages.po+++ b/packages/app/src/locales/fr/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, one {dossier} many {dossiers} other {dossiers}}"msgid "{formatted} GitHub stars"msgstr "{formatted} étoiles GitHub"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "{hiddenCount, plural, one {# more link} other {# more links}}"+msgstr "{hiddenCount, plural, one {# autre lien} many {# autres liens} other {# autres liens}}"+#: src/lib/restart-collab-server.tsmsgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."msgstr "{holder} sert ce projet, cette app ne l'arrêtera donc pas. Fermez cette fenêtre et rouvrez le projet pour arrêter le serveur de {holder} et ouvrir le projet ici."@@ -3934,6 +3938,10 @@ msgstr "Copie en cours"msgid "Copying..."msgstr "Copie en cours…"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Could not check the symlinks in {shareBranch}, so it was not switched. Try again; if it keeps failing, check that Git is installed and the project folder is readable."+msgstr "Impossible de vérifier les liens symboliques de {shareBranch} : le passage n'a donc pas eu lieu. Réessayez ; si l'échec persiste, vérifiez que Git est installé et que le dossier du projet est lisible."+#: src/components/settings/SkillTargetsPicker.tsxmsgid "Could not classify the merge — try again."msgstr "Impossible de classer la fusion. Réessayez."@@ -5164,6 +5172,10 @@ msgstr "Diagramme issu d'une source Mermaid — organigramme, séquence, classesmsgid "Diagram view mode"msgstr "Mode d'affichage du diagramme"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."+msgstr "Le passage à {shareBranch} n'a pas eu lieu : cette branche contient un lien symbolique qui pointe hors du dépôt, vers des fichiers privés ou vers un emplacement qui ne peut pas être vérifié. En général, la personne qui a poussé la branche doit corriger le lien. Si un dossier de cet ordinateur ne peut pas être lu, rendez-le lisible et réessayez."+#: src/components/AgentDiffPane.tsx#: src/components/TimelineDiffPane.tsxmsgid "Diff render mode"@@ -14114,6 +14126,10 @@ msgstr "Échec de la synchronisation — consultez les journaux du serveur pourmsgid "Sync is failing. See the sync status for details."msgstr "La synchronisation échoue. Consultez l'état de la synchronisation pour les détails."+#: src/components/SyncStatusBadge.tsx+msgid "Sync is paused because incoming changes leave a symlink pointing outside the repository or into private files, or with a target that cannot be checked. Ask whoever pushed them to fix the link, or update Git if yours is older than 2.38. Automatic sync then resumes; in Manual mode, pull again."+msgstr "La synchronisation est en pause, car les modifications entrantes laissent un lien symbolique qui pointe hors du dépôt ou vers des fichiers privés, ou dont la cible ne peut pas être vérifiée. Demandez à la personne qui les a poussées de corriger le lien, ou mettez à jour Git si votre version est antérieure à 2.38. La synchronisation automatique reprend ensuite ; en mode Manuel, tirez à nouveau."+#: src/components/SyncBlockingChanges.tsxmsgid "Sync is paused. Commit these local edits to continue, or sort them out in a terminal."msgstr "La synchronisation est en pause. Validez ces modifications locales pour continuer, ou réglez-les dans un terminal."diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.jsonindex 9a5a0d869..ad9725936 100644--- a/packages/app/src/locales/hi/messages.json+++ b/packages/app/src/locales/hi/messages.json@@ -156,6 +156,10 @@"0t0bbC": ["सिंक वरीयता नहीं सहेजी जा सकी: ", ["detail"]],"0tV-rz": ["सेटिंग अभी भी लोड हो रही हैं। कुछ देर बाद फिर कोशिश करें।"],"0uTHCg": ["एक नया OpenKnowledge प्रोजेक्ट शुरू करें।"],+ "0uxLib": [+ ["shareBranch"],+ " के सिमलिंक की जाँच नहीं हो सकी, इसलिए उस पर स्विच नहीं किया गया। फिर से कोशिश करें; अगर यह बार-बार विफल हो, तो देखें कि Git इंस्टॉल है और प्रोजेक्ट फ़ोल्डर पढ़ा जा सकता है।"+ ],"0wkh7o": ["OpenKnowledge लॉग, जिनमें अलग-अलग प्रोजेक्ट की गतिविधि शामिल है।"],"0wswKc": ["अनुभागों को विभाजित करने वाली क्षैतिज रेखा।"],"0x9smA": ["यह पेज अब इस पाथ पर नहीं है।"],@@ -404,6 +408,10 @@"पहले से एक git रिपॉज़िटरी है? इस प्रोजेक्ट के फ़ोल्डर में <0>git remote add origin <url></0> से इसे जोड़ें। रिमोट का पता चलते ही यह पेज अपने आप अद्यतित हो जाता है।"],"45MZFs": ["कमांड"],+ "461Vg9": [+ ["shareBranch"],+ " पर स्विच नहीं किया गया: इसमें एक सिमलिंक है जो रिपॉज़िटरी के बाहर, निजी फ़ाइलों की ओर, या ऐसी जगह की ओर इशारा करता है जिसकी जाँच नहीं की जा सकती। आमतौर पर जिसने ब्रांच भेजी है उसे ही लिंक ठीक करना होगा। अगर इस कंप्यूटर का कोई फ़ोल्डर पढ़ा नहीं जा सकता, तो उसे पढ़ने योग्य बनाएँ और फिर से कोशिश करें।"+ ],"46YgRZ": ["नीचे ब्लॉक जोड़ें"],"484LKL": ["लिंक हटाएँ"],"49Mb7P": ["हम जाँच नहीं सके कि Slidev इंस्टॉल है या नहीं। पुनः प्रयास के लिए इस विंडो पर लौटें।"],@@ -805,6 +813,9 @@"8nWu1k": ["खाली आरेख"],"8oWgty": ["भेजने के लिए सभी टिप्पणियाँ चुनें"],"8qgfac": ["MCP सर्वर"],+ "8qsUJv": [+ "सिंक रुका हुआ है क्योंकि आने वाले बदलावों के बाद एक सिमलिंक रिपॉज़िटरी के बाहर या निजी फ़ाइलों की ओर इशारा करता है, या इसके लक्ष्य की जाँच नहीं की जा सकती। जिसने ये बदलाव भेजे हैं उससे लिंक ठीक करने को कहें, या आपका Git 2.38 से पुराना हो तो Git अपडेट करें। इसके बाद स्वचालित सिंक फिर शुरू हो जाएगा; मैन्युअल मोड में फिर से खींचें।"+ ],"8rZ1pk": [["id"], " सक्षम करें"],"8ruqQi": ["टूटे हुए आंतरिक लिंक"],"8t9CRE": [["agentName"], " शुरू किया जा रहा है…"],@@ -4646,6 +4657,7 @@"pA16WG": ["इस प्रोजेक्ट का कोई GitHub रिमोट नहीं है।"],"pAgkuZ": ["\"", ["docName"], "\" को एक नए स्थानीय सहयोग कैश के साथ दोबारा खोला जा रहा है।"],"pBROkv": ["सदस्यता लेने के लिए धन्यवाद। उत्पाद अपडेट के लिए अपना इनबॉक्स देखते रहें।"],+ "pCJv30": [["hiddenCount", "plural", { "one": ["#", " और लिंक"], "other": ["#", " और लिंक"] }]],"pCralD": ["बाईं ओर नए फलक में ले जाएँ"],"pEQFsW": ["कोई मेल खाता प्रोजेक्ट नहीं।"],"pFPzHA": ["इमोजी चयनकर्ता"],diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.poindex 18e43b087..1d14d7edd 100644--- a/packages/app/src/locales/hi/messages.po+++ b/packages/app/src/locales/hi/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, one {फ़ोल्डर} other {फ़ोल्msgid "{formatted} GitHub stars"msgstr "{formatted} GitHub स्टार"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "{hiddenCount, plural, one {# more link} other {# more links}}"+msgstr "{hiddenCount, plural, one {# और लिंक} other {# और लिंक}}"+#: src/lib/restart-collab-server.tsmsgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."msgstr "{holder} इस प्रोजेक्ट को सर्व कर रहा है, इसलिए यह ऐप उसे नहीं रोकेगा। यह विंडो बंद करें और {holder} का सर्वर रोककर प्रोजेक्ट यहाँ खोलने के लिए प्रोजेक्ट फिर से खोलें।"@@ -3930,6 +3934,10 @@ msgstr "कॉपी किया जा रहा है"msgid "Copying..."msgstr "कॉपी किया जा रहा है…"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Could not check the symlinks in {shareBranch}, so it was not switched. Try again; if it keeps failing, check that Git is installed and the project folder is readable."+msgstr "{shareBranch} के सिमलिंक की जाँच नहीं हो सकी, इसलिए उस पर स्विच नहीं किया गया। फिर से कोशिश करें; अगर यह बार-बार विफल हो, तो देखें कि Git इंस्टॉल है और प्रोजेक्ट फ़ोल्डर पढ़ा जा सकता है।"+#: src/components/settings/SkillTargetsPicker.tsxmsgid "Could not classify the merge — try again."msgstr "मर्ज को वर्गीकृत नहीं किया जा सका — फिर से कोशिश करें।"@@ -5160,6 +5168,10 @@ msgstr "Mermaid स्रोत से आरेख — फ़्लोचारmsgid "Diagram view mode"msgstr "आरेख दृश्य मोड"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."+msgstr "{shareBranch} पर स्विच नहीं किया गया: इसमें एक सिमलिंक है जो रिपॉज़िटरी के बाहर, निजी फ़ाइलों की ओर, या ऐसी जगह की ओर इशारा करता है जिसकी जाँच नहीं की जा सकती। आमतौर पर जिसने ब्रांच भेजी है उसे ही लिंक ठीक करना होगा। अगर इस कंप्यूटर का कोई फ़ोल्डर पढ़ा नहीं जा सकता, तो उसे पढ़ने योग्य बनाएँ और फिर से कोशिश करें।"+#: src/components/AgentDiffPane.tsx#: src/components/TimelineDiffPane.tsxmsgid "Diff render mode"@@ -14110,6 +14122,10 @@ msgstr "सिंक विफल — विवरण के लिए सर्msgid "Sync is failing. See the sync status for details."msgstr "सिंक विफल हो रहा है। विवरण के लिए सिंक स्थिति देखें।"+#: src/components/SyncStatusBadge.tsx+msgid "Sync is paused because incoming changes leave a symlink pointing outside the repository or into private files, or with a target that cannot be checked. Ask whoever pushed them to fix the link, or update Git if yours is older than 2.38. Automatic sync then resumes; in Manual mode, pull again."+msgstr "सिंक रुका हुआ है क्योंकि आने वाले बदलावों के बाद एक सिमलिंक रिपॉज़िटरी के बाहर या निजी फ़ाइलों की ओर इशारा करता है, या इसके लक्ष्य की जाँच नहीं की जा सकती। जिसने ये बदलाव भेजे हैं उससे लिंक ठीक करने को कहें, या आपका Git 2.38 से पुराना हो तो Git अपडेट करें। इसके बाद स्वचालित सिंक फिर शुरू हो जाएगा; मैन्युअल मोड में फिर से खींचें।"+#: src/components/SyncBlockingChanges.tsxmsgid "Sync is paused. Commit these local edits to continue, or sort them out in a terminal."msgstr "सिंक रुका हुआ है। जारी रखने के लिए इन स्थानीय संपादनों को कमिट करें, या टर्मिनल में इन्हें निपटाएँ।"diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.jsonindex bdd9229f4..07f16de7c 100644--- a/packages/app/src/locales/id/messages.json+++ b/packages/app/src/locales/id/messages.json@@ -154,6 +154,11 @@"0t0bbC": ["Preferensi sinkronisasi tidak dapat disimpan: ", ["detail"]],"0tV-rz": ["Pengaturan masih dimuat. Coba lagi sebentar."],"0uTHCg": ["Mulai proyek OpenKnowledge baru."],+ "0uxLib": [+ "Tidak dapat memeriksa symlink di ",+ ["shareBranch"],+ ", jadi tidak beralih. Coba lagi; jika terus gagal, pastikan Git terpasang dan folder proyek dapat dibaca."+ ],"0wkh7o": ["Log OpenKnowledge, termasuk aktivitas lintas proyek."],"0wswKc": ["Garis mendatar yang memisahkan bagian."],"0x9smA": ["Halaman ini tidak lagi berada di jalur ini."],@@ -408,6 +413,11 @@"Sudah punya repositori git? Tambahkan dengan <0>git remote add origin <url></0> di folder proyek ini. Halaman ini diperbarui otomatis begitu sebuah remote terdeteksi."],"45MZFs": ["Perintah"],+ "461Vg9": [+ "Tidak beralih ke ",+ ["shareBranch"],+ ": cabang ini memiliki symlink yang mengarah ke luar repositori, ke berkas pribadi, atau ke tempat yang tidak dapat diperiksa. Biasanya orang yang melakukan push cabang ini yang harus memperbaiki tautannya. Jika sebuah folder di komputer ini tidak dapat dibaca, buat agar dapat dibaca lalu coba lagi."+ ],"46YgRZ": ["Tambahkan blok di bawah"],"484LKL": ["Hapus tautan"],"49Mb7P": [@@ -839,6 +849,9 @@"8nWu1k": ["Diagram kosong"],"8oWgty": ["Tandai semua komentar untuk dikirim"],"8qgfac": ["Server MCP"],+ "8qsUJv": [+ "Sinkronisasi dijeda karena perubahan yang masuk membuat symlink mengarah ke luar repositori atau ke berkas pribadi, atau targetnya tidak dapat diperiksa. Minta orang yang melakukan push untuk memperbaiki tautannya, atau perbarui Git jika versi Anda lebih lama dari 2.38. Setelah itu sinkronisasi otomatis berlanjut; dalam mode Manual, lakukan pull lagi."+ ],"8rZ1pk": ["Aktifkan ", ["id"]],"8ruqQi": ["Tautan internal rusak"],"8t9CRE": ["Memulai ", ["agentName"], "…"],@@ -4824,6 +4837,7 @@"pBROkv": ["Terima kasih sudah berlangganan. Pantau kotak masuk Anda untuk kabar terbaru produk."],+ "pCJv30": [["hiddenCount", "plural", { "other": ["#", " tautan lainnya"] }]],"pCralD": ["Pindahkan ke panel baru di kiri"],"pEQFsW": ["Tidak ada proyek yang cocok."],"pFPzHA": ["Pemilih emoji"],diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.poindex ff6eb551d..c42ea0e18 100644--- a/packages/app/src/locales/id/messages.po+++ b/packages/app/src/locales/id/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, other {folder}}"msgid "{formatted} GitHub stars"msgstr "{formatted} bintang GitHub"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "{hiddenCount, plural, one {# more link} other {# more links}}"+msgstr "{hiddenCount, plural, other {# tautan lainnya}}"+#: src/lib/restart-collab-server.tsmsgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."msgstr "{holder} sedang melayani proyek ini, jadi aplikasi ini tidak akan menghentikannya. Tutup jendela ini lalu buka proyek lagi untuk menghentikan server {holder} dan membuka proyek di sini."@@ -3930,6 +3934,10 @@ msgstr "Menyalin"msgid "Copying..."msgstr "Menyalin..."+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Could not check the symlinks in {shareBranch}, so it was not switched. Try again; if it keeps failing, check that Git is installed and the project folder is readable."+msgstr "Tidak dapat memeriksa symlink di {shareBranch}, jadi tidak beralih. Coba lagi; jika terus gagal, pastikan Git terpasang dan folder proyek dapat dibaca."+#: src/components/settings/SkillTargetsPicker.tsxmsgid "Could not classify the merge — try again."msgstr "Penggabungan tidak dapat diklasifikasikan — coba lagi."@@ -5160,6 +5168,10 @@ msgstr "Diagram dari sumber Mermaid — bagan alir, sekuens, kelas, keadaan, ER,msgid "Diagram view mode"msgstr "Mode tampilan diagram"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."+msgstr "Tidak beralih ke {shareBranch}: cabang ini memiliki symlink yang mengarah ke luar repositori, ke berkas pribadi, atau ke tempat yang tidak dapat diperiksa. Biasanya orang yang melakukan push cabang ini yang harus memperbaiki tautannya. Jika sebuah folder di komputer ini tidak dapat dibaca, buat agar dapat dibaca lalu coba lagi."+#: src/components/AgentDiffPane.tsx#: src/components/TimelineDiffPane.tsxmsgid "Diff render mode"@@ -14110,6 +14122,10 @@ msgstr "Sinkronisasi gagal — periksa log server untuk detailnya."msgid "Sync is failing. See the sync status for details."msgstr "Sinkronisasi sedang gagal. Lihat status sinkronisasi untuk detailnya."+#: src/components/SyncStatusBadge.tsx+msgid "Sync is paused because incoming changes leave a symlink pointing outside the repository or into private files, or with a target that cannot be checked. Ask whoever pushed them to fix the link, or update Git if yours is older than 2.38. Automatic sync then resumes; in Manual mode, pull again."+msgstr "Sinkronisasi dijeda karena perubahan yang masuk membuat symlink mengarah ke luar repositori atau ke berkas pribadi, atau targetnya tidak dapat diperiksa. Minta orang yang melakukan push untuk memperbaiki tautannya, atau perbarui Git jika versi Anda lebih lama dari 2.38. Setelah itu sinkronisasi otomatis berlanjut; dalam mode Manual, lakukan pull lagi."+#: src/components/SyncBlockingChanges.tsxmsgid "Sync is paused. Commit these local edits to continue, or sort them out in a terminal."msgstr "Sinkronisasi dijeda. Commit suntingan lokal ini untuk melanjutkan, atau selesaikan di terminal."diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.jsonindex 64a6239a8..1dbfb1d51 100644--- a/packages/app/src/locales/ko/messages.json+++ b/packages/app/src/locales/ko/messages.json@@ -148,6 +148,10 @@"0t0bbC": ["동기화 환경설정을 저장할 수 없습니다: ", ["detail"]],"0tV-rz": ["설정을 아직 불러오는 중입니다. 잠시 후 다시 시도하세요."],"0uTHCg": ["새 OpenKnowledge 프로젝트를 시작합니다."],+ "0uxLib": [+ ["shareBranch"],+ "의 심볼릭 링크를 확인할 수 없어 전환하지 않았습니다. 다시 시도하세요. 계속 실패하면 Git이 설치되어 있고 프로젝트 폴더를 읽을 수 있는지 확인하세요."+ ],"0wkh7o": ["여러 프로젝트의 활동을 포함한 OpenKnowledge 로그입니다."],"0wswKc": ["섹션을 나누는 가로줄입니다."],"0x9smA": ["이 페이지는 더 이상 이 경로에 없습니다."],@@ -397,6 +401,10 @@"이미 git 저장소가 있나요? 프로젝트 폴더에서 <0>git remote add origin <url></0>을 실행해 추가합니다. 원격 저장소가 감지되면 이 페이지가 자동으로 업데이트됩니다."],"45MZFs": ["명령"],+ "461Vg9": [+ ["shareBranch"],+ "(으)로 전환하지 않았습니다. 저장소 밖이나 비공개 파일, 또는 확인할 수 없는 위치를 가리키는 심볼릭 링크가 있습니다. 보통 브랜치를 푸시한 사람이 링크를 수정해야 합니다. 이 컴퓨터의 폴더를 읽을 수 없다면 읽을 수 있게 한 뒤 다시 시도하세요."+ ],"46YgRZ": ["아래에 블록 추가"],"484LKL": ["링크 제거"],"49Mb7P": ["Slidev가 설치되어 있는지 확인하지 못했습니다. 이 창으로 돌아와 다시 시도합니다."],@@ -811,6 +819,9 @@"8nWu1k": ["빈 다이어그램"],"8oWgty": ["모든 댓글 전송 표시"],"8qgfac": ["MCP 서버"],+ "8qsUJv": [+ "들어오는 변경 사항으로 인해 심볼릭 링크가 저장소 밖이나 비공개 파일을 가리키거나 대상을 확인할 수 없게 되어 동기화가 일시 중지되었습니다. 푸시한 사람에게 링크 수정을 요청하거나, Git 버전이 2.38보다 오래되었다면 Git을 업데이트하세요. 그러면 자동 동기화가 다시 시작되며, 수동 모드에서는 다시 풀하세요."+ ],"8rZ1pk": [["id"], " 활성화"],"8ruqQi": ["손상된 내부 링크"],"8t9CRE": [["agentName"], " 시작 중…"],@@ -4615,6 +4626,7 @@"pA16WG": ["이 프로젝트에는 GitHub 원격이 없습니다."],"pAgkuZ": ["새 로컬 협업 캐시로 \"", ["docName"], "\"을 다시 여는 중입니다."],"pBROkv": ["구독해 주셔서 감사합니다. 받은 편지함에서 제품 업데이트를 확인하세요."],+ "pCJv30": [["hiddenCount", "plural", { "other": ["링크 ", "#", "개 더"] }]],"pCralD": ["새 패널 왼쪽으로 이동"],"pEQFsW": ["일치하는 프로젝트 없음."],"pFPzHA": ["이모지 선택기"],diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.poindex 5a8b5987b..2ff8d90a1 100644--- a/packages/app/src/locales/ko/messages.po+++ b/packages/app/src/locales/ko/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, other {폴더}}"msgid "{formatted} GitHub stars"msgstr "{formatted} GitHub 스타"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "{hiddenCount, plural, one {# more link} other {# more links}}"+msgstr "{hiddenCount, plural, other {링크 #개 더}}"+#: src/lib/restart-collab-server.tsmsgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."msgstr "{holder}이(가) 이 프로젝트를 서비스하고 있으므로 이 앱은 중지하지 않습니다. 이 창을 닫고 프로젝트를 다시 열면 {holder}의 서버를 중지하고 여기에서 프로젝트를 열 수 있습니다."@@ -3934,6 +3938,10 @@ msgstr "복사 중"msgid "Copying..."msgstr "복사 중…"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Could not check the symlinks in {shareBranch}, so it was not switched. Try again; if it keeps failing, check that Git is installed and the project folder is readable."+msgstr "{shareBranch}의 심볼릭 링크를 확인할 수 없어 전환하지 않았습니다. 다시 시도하세요. 계속 실패하면 Git이 설치되어 있고 프로젝트 폴더를 읽을 수 있는지 확인하세요."+#: src/components/settings/SkillTargetsPicker.tsxmsgid "Could not classify the merge — try again."msgstr "병합을 분류할 수 없습니다. 다시 시도하세요."@@ -5164,6 +5172,10 @@ msgstr "Mermaid 소스에서 만든 다이어그램입니다. 플로차트, 시msgid "Diagram view mode"msgstr "다이어그램 보기 모드"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."+msgstr "{shareBranch}(으)로 전환하지 않았습니다. 저장소 밖이나 비공개 파일, 또는 확인할 수 없는 위치를 가리키는 심볼릭 링크가 있습니다. 보통 브랜치를 푸시한 사람이 링크를 수정해야 합니다. 이 컴퓨터의 폴더를 읽을 수 없다면 읽을 수 있게 한 뒤 다시 시도하세요."+#: src/components/AgentDiffPane.tsx#: src/components/TimelineDiffPane.tsxmsgid "Diff render mode"@@ -14114,6 +14126,10 @@ msgstr "동기화 실패. 자세한 내용은 서버 로그를 확인하세요."msgid "Sync is failing. See the sync status for details."msgstr "동기화에 실패하고 있습니다. 자세한 내용은 동기화 상태를 확인하세요."+#: src/components/SyncStatusBadge.tsx+msgid "Sync is paused because incoming changes leave a symlink pointing outside the repository or into private files, or with a target that cannot be checked. Ask whoever pushed them to fix the link, or update Git if yours is older than 2.38. Automatic sync then resumes; in Manual mode, pull again."+msgstr "들어오는 변경 사항으로 인해 심볼릭 링크가 저장소 밖이나 비공개 파일을 가리키거나 대상을 확인할 수 없게 되어 동기화가 일시 중지되었습니다. 푸시한 사람에게 링크 수정을 요청하거나, Git 버전이 2.38보다 오래되었다면 Git을 업데이트하세요. 그러면 자동 동기화가 다시 시작되며, 수동 모드에서는 다시 풀하세요."+#: src/components/SyncBlockingChanges.tsxmsgid "Sync is paused. Commit these local edits to continue, or sort them out in a terminal."msgstr "동기화가 일시 중지되었습니다. 계속하려면 이 로컬 편집 내용을 커밋하거나 터미널에서 정리하세요."diff --git a/packages/app/src/locales/pl/messages.json b/packages/app/src/locales/pl/messages.jsonindex 14d4da7ae..448b86649 100644--- a/packages/app/src/locales/pl/messages.json+++ b/packages/app/src/locales/pl/messages.json@@ -207,6 +207,11 @@"0t0bbC": ["Nie udało się zapisać ustawienia synchronizacji: ", ["detail"]],"0tV-rz": ["Ustawienia nadal się wczytują. Spróbuj ponownie za chwilę."],"0uTHCg": ["Rozpocznij nowy projekt OpenKnowledge."],+ "0uxLib": [+ "Nie udało się sprawdzić dowiązań symbolicznych w ",+ ["shareBranch"],+ ", więc nie przełączono. Spróbuj ponownie; jeśli błąd się powtarza, sprawdź, czy Git jest zainstalowany i czy folder projektu można odczytać."+ ],"0wkh7o": ["Logi OpenKnowledge, w tym aktywność ze wszystkich projektów."],"0wswKc": ["Pozioma linia dzieląca sekcje."],"0x9smA": ["Ta strona nie jest już pod tą ścieżką."],@@ -500,6 +505,11 @@"Masz już repozytorium git? Dodaj je poleceniem <0>git remote add origin <url></0> w folderze tego projektu. Ta strona zaktualizuje się automatycznie po wykryciu repozytorium zdalnego."],"45MZFs": ["Polecenia"],+ "461Vg9": [+ "Nie przełączono na ",+ ["shareBranch"],+ ": gałąź zawiera dowiązanie symboliczne wskazujące poza repozytorium, na prywatne pliki albo w miejsce, którego nie da się sprawdzić. Zwykle dowiązanie musi poprawić osoba, która wypchnęła gałąź. Jeśli nie da się odczytać folderu na tym komputerze, nadaj mu uprawnienia do odczytu i spróbuj ponownie."+ ],"46YgRZ": ["Dodaj blok poniżej"],"484LKL": ["Usuń link"],"49Mb7P": [@@ -1005,6 +1015,9 @@"8nWu1k": ["Pusty diagram"],"8oWgty": ["Zaznacz każdy komentarz do wysłania"],"8qgfac": ["Serwery MCP"],+ "8qsUJv": [+ "Synchronizacja jest wstrzymana, ponieważ przychodzące zmiany zostawiają dowiązanie symboliczne wskazujące poza repozytorium lub na prywatne pliki albo takie, którego celu nie da się sprawdzić. Poproś osobę, która je wypchnęła, o poprawienie dowiązania lub zaktualizuj Git, jeśli Twoja wersja jest starsza niż 2.38. Potem automatyczna synchronizacja zostanie wznowiona; w trybie ręcznym pobierz zmiany ponownie."+ ],"8rZ1pk": ["Włącz ", ["id"]],"8ruqQi": ["Zerwane linki wewnętrzne"],"8t9CRE": ["Uruchamianie ", ["agentName"], "…"],@@ -5659,6 +5672,18 @@"pBROkv": ["Dziękujemy za subskrypcję. Sprawdzaj skrzynkę na wiadomości o aktualizacjach produktu."],+ "pCJv30": [+ [+ "hiddenCount",+ "plural",+ {+ "one": ["jeszcze ", "#", " dowiązanie"],+ "few": ["jeszcze ", "#", " dowiązania"],+ "many": ["jeszcze ", "#", " dowiązań"],+ "other": ["jeszcze ", "#", " dowiązania"]+ }+ ]+ ],"pCralD": ["Przenieś do nowego panelu po lewej"],"pEQFsW": ["Brak pasujących projektów."],"pFPzHA": ["Wybór emoji"],diff --git a/packages/app/src/locales/pl/messages.po b/packages/app/src/locales/pl/messages.poindex f58986c8d..3ca531e2b 100644--- a/packages/app/src/locales/pl/messages.po+++ b/packages/app/src/locales/pl/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, one {folder} few {foldery} many {folderów} othermsgid "{formatted} GitHub stars"msgstr "{formatted} gwiazdek na GitHubie"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "{hiddenCount, plural, one {# more link} other {# more links}}"+msgstr "{hiddenCount, plural, one {jeszcze # dowiązanie} few {jeszcze # dowiązania} many {jeszcze # dowiązań} other {jeszcze # dowiązania}}"+#: src/lib/restart-collab-server.tsmsgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."msgstr "{holder} obsługuje ten projekt, więc ta aplikacja go nie zatrzyma. Zamknij to okno i otwórz projekt ponownie, aby zatrzymać serwer aplikacji {holder} i otworzyć projekt tutaj."@@ -3934,6 +3938,10 @@ msgstr "Kopiowanie"msgid "Copying..."msgstr "Kopiowanie..."+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Could not check the symlinks in {shareBranch}, so it was not switched. Try again; if it keeps failing, check that Git is installed and the project folder is readable."+msgstr "Nie udało się sprawdzić dowiązań symbolicznych w {shareBranch}, więc nie przełączono. Spróbuj ponownie; jeśli błąd się powtarza, sprawdź, czy Git jest zainstalowany i czy folder projektu można odczytać."+#: src/components/settings/SkillTargetsPicker.tsxmsgid "Could not classify the merge — try again."msgstr "Nie udało się sklasyfikować scalenia — spróbuj ponownie."@@ -5164,6 +5172,10 @@ msgstr "Diagram ze źródła Mermaid — schemat przepływu, sekwencji, klas, stmsgid "Diagram view mode"msgstr "Tryb widoku diagramu"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."+msgstr "Nie przełączono na {shareBranch}: gałąź zawiera dowiązanie symboliczne wskazujące poza repozytorium, na prywatne pliki albo w miejsce, którego nie da się sprawdzić. Zwykle dowiązanie musi poprawić osoba, która wypchnęła gałąź. Jeśli nie da się odczytać folderu na tym komputerze, nadaj mu uprawnienia do odczytu i spróbuj ponownie."+#: src/components/AgentDiffPane.tsx#: src/components/TimelineDiffPane.tsxmsgid "Diff render mode"@@ -14114,6 +14126,10 @@ msgstr "Synchronizacja nie powiodła się — sprawdź logi serwera, aby poznaćmsgid "Sync is failing. See the sync status for details."msgstr "Synchronizacja zawodzi. Zobacz status synchronizacji, aby poznać szczegóły."+#: src/components/SyncStatusBadge.tsx+msgid "Sync is paused because incoming changes leave a symlink pointing outside the repository or into private files, or with a target that cannot be checked. Ask whoever pushed them to fix the link, or update Git if yours is older than 2.38. Automatic sync then resumes; in Manual mode, pull again."+msgstr "Synchronizacja jest wstrzymana, ponieważ przychodzące zmiany zostawiają dowiązanie symboliczne wskazujące poza repozytorium lub na prywatne pliki albo takie, którego celu nie da się sprawdzić. Poproś osobę, która je wypchnęła, o poprawienie dowiązania lub zaktualizuj Git, jeśli Twoja wersja jest starsza niż 2.38. Potem automatyczna synchronizacja zostanie wznowiona; w trybie ręcznym pobierz zmiany ponownie."+#: src/components/SyncBlockingChanges.tsxmsgid "Sync is paused. Commit these local edits to continue, or sort them out in a terminal."msgstr "Synchronizacja jest wstrzymana. Zapisz te lokalne zmiany w Gitcie, aby kontynuować, albo uporządkuj je w terminalu."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 61ecda4f8..c760422c6 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -158,6 +158,11 @@"0t0bbC": ["Ćōũĺď ńōţ śàvē śŷńć ƥŕēƒēŕēńćē: ", ["detail"]],"0tV-rz": ["Śēţţĩńĝś àŕē śţĩĺĺ ĺōàďĩńĝ. Ţŕŷ àĝàĩń ĩń à ḿōḿēńţ."],"0uTHCg": ["Śţàŕţ à ńēŵ ŌƥēńĶńōŵĺēďĝē ƥŕōĴēćţ."],+ "0uxLib": [+ "Ćōũĺď ńōţ ćĥēćķ ţĥē śŷḿĺĩńķś ĩń ",+ ["shareBranch"],+ ", śō ĩţ ŵàś ńōţ śŵĩţćĥēď. Ţŕŷ àĝàĩń; ĩƒ ĩţ ķēēƥś ƒàĩĺĩńĝ, ćĥēćķ ţĥàţ Ĝĩţ ĩś ĩńśţàĺĺēď àńď ţĥē ƥŕōĴēćţ ƒōĺďēŕ ĩś ŕēàďàƀĺē."+ ],"0wkh7o": ["ŌƥēńĶńōŵĺēďĝē ĺōĝś, ĩńćĺũďĩńĝ àćţĩvĩţŷ àćŕōśś ƥŕōĴēćţś."],"0wswKc": ["Ĥōŕĩźōńţàĺ ŕũĺē ţĥàţ ďĩvĩďēś śēćţĩōńś."],"0x9smA": ["Ţĥĩś ƥàĝē ĩś ńō ĺōńĝēŕ àţ ţĥĩś ƥàţĥ."],@@ -417,6 +422,11 @@"Àĺŕēàďŷ ĥàvē à ĝĩţ ŕēƥōśĩţōŕŷ? Àďď ĩţ ŵĩţĥ <0>ĝĩţ ŕēḿōţē àďď ōŕĩĝĩń <url></0> ĩń ţĥĩś ƥŕōĴēćţ'ś ƒōĺďēŕ. Ţĥĩś ƥàĝē ũƥďàţēś àũţōḿàţĩćàĺĺŷ ōńćē à ŕēḿōţē ĩś ďēţēćţēď."],"45MZFs": ["Ćōḿḿàńďś"],+ "461Vg9": [+ "Ďĩď ńōţ śŵĩţćĥ ţō ",+ ["shareBranch"],+ ": ĩţ ĥàś à śŷḿĺĩńķ ƥōĩńţĩńĝ ōũţśĩďē ţĥē ŕēƥōśĩţōŕŷ, ĩńţō ƥŕĩvàţē ƒĩĺēś, ōŕ śōḿēŵĥēŕē ţĥàţ ćàńńōţ ƀē ćĥēćķēď. Ũśũàĺĺŷ ŵĥōēvēŕ ƥũśĥēď ţĥē ƀŕàńćĥ ĥàś ţō ƒĩx ţĥē ĺĩńķ. Ĩƒ à ƒōĺďēŕ ōń ţĥĩś ćōḿƥũţēŕ ćàńńōţ ƀē ŕēàď, ḿàķē ĩţ ŕēàďàƀĺē àńď ţŕŷ àĝàĩń."+ ],"46YgRZ": ["Àďď ƀĺōćķ ƀēĺōŵ"],"484LKL": ["Ŕēḿōvē ĺĩńķ"],"49Mb7P": ["Ŵē ćōũĺďń'ţ ćĥēćķ ŵĥēţĥēŕ Śĺĩďēv ĩś ĩńśţàĺĺēď. Ŕēţũŕń ţō ţĥĩś ŵĩńďōŵ ţō ŕēţŕŷ."],@@ -828,6 +838,9 @@"8nWu1k": ["Ēḿƥţŷ ďĩàĝŕàḿ"],"8oWgty": ["Ḿàŕķ ēvēŕŷ ćōḿḿēńţ ţō śēńď"],"8qgfac": ["ḾĆƤ śēŕvēŕś"],+ "8qsUJv": [+ "Śŷńć ĩś ƥàũśēď ƀēćàũśē ĩńćōḿĩńĝ ćĥàńĝēś ĺēàvē à śŷḿĺĩńķ ƥōĩńţĩńĝ ōũţśĩďē ţĥē ŕēƥōśĩţōŕŷ ōŕ ĩńţō ƥŕĩvàţē ƒĩĺēś, ōŕ ŵĩţĥ à ţàŕĝēţ ţĥàţ ćàńńōţ ƀē ćĥēćķēď. Àśķ ŵĥōēvēŕ ƥũśĥēď ţĥēḿ ţō ƒĩx ţĥē ĺĩńķ, ōŕ ũƥďàţē Ĝĩţ ĩƒ ŷōũŕś ĩś ōĺďēŕ ţĥàń 2.38. Àũţōḿàţĩć śŷńć ţĥēń ŕēśũḿēś; ĩń Ḿàńũàĺ ḿōďē, ƥũĺĺ àĝàĩń."+ ],"8rZ1pk": ["Ēńàƀĺē ", ["id"]],"8ruqQi": ["ßŕōķēń ĩńţēŕńàĺ ĺĩńķś"],"8t9CRE": ["Śţàŕţĩńĝ ", ["agentName"], "…"],@@ -4808,6 +4821,9 @@"pA16WG": ["Ţĥĩś ƥŕōĴēćţ ĥàś ńō ĜĩţĤũƀ ŕēḿōţē."],"pAgkuZ": ["Ŕēōƥēńĩńĝ \"", ["docName"], "\" ŵĩţĥ à ƒŕēśĥ ĺōćàĺ ćōĺĺàƀōŕàţĩōń ćàćĥē."],"pBROkv": ["Ţĥàńķś ƒōŕ śũƀśćŕĩƀĩńĝ. Ŵàţćĥ ŷōũŕ ĩńƀōx ƒōŕ ƥŕōďũćţ ũƥďàţēś."],+ "pCJv30": [+ ["hiddenCount", "plural", { "one": ["#", " ḿōŕē ĺĩńķ"], "other": ["#", " ḿōŕē ĺĩńķś"] }]+ ],"pCralD": ["Ḿōvē ţō ńēŵ ƥàńē ĺēƒţ"],"pEQFsW": ["Ńō ḿàţćĥĩńĝ ƥŕōĴēćţś."],"pFPzHA": ["ĒḿōĴĩ ƥĩćķēŕ"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 53435f0d8..3c187ce52 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -912,6 +912,10 @@ msgstr ""msgid "{formatted} GitHub stars"msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+msgid "{hiddenCount, plural, one {# more link} other {# more links}}"+msgstr ""+#: src/lib/restart-collab-server.tsmsgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."msgstr ""@@ -3930,6 +3934,10 @@ msgstr ""msgid "Copying..."msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Could not check the symlinks in {shareBranch}, so it was not switched. Try again; if it keeps failing, check that Git is installed and the project folder is readable."+msgstr ""+#: src/components/settings/SkillTargetsPicker.tsxmsgid "Could not classify the merge — try again."msgstr ""@@ -5160,6 +5168,10 @@ msgstr ""msgid "Diagram view mode"msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."+msgstr ""+#: src/components/AgentDiffPane.tsx#: src/components/TimelineDiffPane.tsxmsgid "Diff render mode"@@ -14110,6 +14122,10 @@ msgstr ""msgid "Sync is failing. See the sync status for details."msgstr ""+#: src/components/SyncStatusBadge.tsx+msgid "Sync is paused because incoming changes leave a symlink pointing outside the repository or into private files, or with a target that cannot be checked. Ask whoever pushed them to fix the link, or update Git if yours is older than 2.38. Automatic sync then resumes; in Manual mode, pull again."+msgstr ""+#: src/components/SyncBlockingChanges.tsxmsgid "Sync is paused. Commit these local edits to continue, or sort them out in a terminal."msgstr ""diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.jsonindex 3ed03dd14..741bd753b 100644--- a/packages/app/src/locales/pt-BR/messages.json+++ b/packages/app/src/locales/pt-BR/messages.json@@ -186,6 +186,11 @@"0t0bbC": ["Não foi possível salvar a preferência de sincronização: ", ["detail"]],"0tV-rz": ["As configurações ainda estão carregando. Tente de novo em instantes."],"0uTHCg": ["Comece um projeto do OpenKnowledge."],+ "0uxLib": [+ "Não foi possível verificar os links simbólicos de ",+ ["shareBranch"],+ ", então a troca não foi feita. Tente novamente; se continuar falhando, confira se o Git está instalado e se a pasta do projeto pode ser lida."+ ],"0wkh7o": ["Logs do OpenKnowledge, incluindo atividade de vários projetos."],"0wswKc": ["Linha horizontal que separa seções."],"0x9smA": ["Esta página não está mais neste caminho."],@@ -476,6 +481,11 @@"Já tem um repositório git? Adicione-o com <0>git remote add origin <url></0> na pasta deste projeto. Esta página se atualiza sozinha assim que um remoto for detectado."],"45MZFs": ["Comandos"],+ "461Vg9": [+ "A troca para ",+ ["shareBranch"],+ " não foi feita: ela tem um link simbólico apontando para fora do repositório, para arquivos privados ou para um lugar que não pode ser verificado. Normalmente quem enviou o branch precisa corrigir o link. Se uma pasta deste computador não puder ser lida, torne-a legível e tente novamente."+ ],"46YgRZ": ["Adicionar bloco abaixo"],"484LKL": ["Remover o link"],"49Mb7P": [@@ -956,6 +966,9 @@"8nWu1k": ["Diagrama vazio"],"8oWgty": ["Marcar todos os comentários para enviar"],"8qgfac": ["Servidores MCP"],+ "8qsUJv": [+ "A sincronização está pausada porque as alterações recebidas deixam um link simbólico apontando para fora do repositório ou para arquivos privados, ou com um destino que não pode ser verificado. Peça a quem as enviou que corrija o link, ou atualize o Git se a sua versão for anterior à 2.38. Depois, a sincronização automática é retomada; no modo Manual, faça pull novamente."+ ],"8rZ1pk": ["Habilitar ", ["id"]],"8ruqQi": ["Links internos quebrados"],"8t9CRE": ["Iniciando ", ["agentName"], "…"],@@ -5429,6 +5442,17 @@"pA16WG": ["Este projeto não tem nenhum remoto do GitHub."],"pAgkuZ": ["Reabrindo \"", ["docName"], "\" com um cache local de colaboração novo."],"pBROkv": ["Obrigado por assinar. Fique de olho no seu e-mail para as novidades do produto."],+ "pCJv30": [+ [+ "hiddenCount",+ "plural",+ {+ "one": ["mais ", "#", " link"],+ "many": ["mais ", "#", " links"],+ "other": ["mais ", "#", " links"]+ }+ ]+ ],"pCralD": ["Mover para um novo painel à esquerda"],"pEQFsW": ["Nenhum projeto corresponde."],"pFPzHA": ["Seletor de emojis"],diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.poindex b35d7999f..8d6eceb90 100644--- a/packages/app/src/locales/pt-BR/messages.po+++ b/packages/app/src/locales/pt-BR/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, one {pasta} many {pastas} other {pastas}}"msgid "{formatted} GitHub stars"msgstr "{formatted} estrelas no GitHub"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "{hiddenCount, plural, one {# more link} other {# more links}}"+msgstr "{hiddenCount, plural, one {mais # link} many {mais # links} other {mais # links}}"+#: src/lib/restart-collab-server.tsmsgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."msgstr "{holder} está servindo este projeto, então este app não vai pará-lo. Feche esta janela e abra o projeto novamente para parar o servidor de {holder} e abrir o projeto aqui."@@ -3930,6 +3934,10 @@ msgstr "Copiando"msgid "Copying..."msgstr "Copiando..."+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Could not check the symlinks in {shareBranch}, so it was not switched. Try again; if it keeps failing, check that Git is installed and the project folder is readable."+msgstr "Não foi possível verificar os links simbólicos de {shareBranch}, então a troca não foi feita. Tente novamente; se continuar falhando, confira se o Git está instalado e se a pasta do projeto pode ser lida."+#: src/components/settings/SkillTargetsPicker.tsxmsgid "Could not classify the merge — try again."msgstr "Não foi possível classificar a mesclagem. Tente novamente."@@ -5160,6 +5168,10 @@ msgstr "Diagrama a partir de código Mermaid — fluxograma, sequência, classesmsgid "Diagram view mode"msgstr "Modo de visualização do diagrama"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."+msgstr "A troca para {shareBranch} não foi feita: ela tem um link simbólico apontando para fora do repositório, para arquivos privados ou para um lugar que não pode ser verificado. Normalmente quem enviou o branch precisa corrigir o link. Se uma pasta deste computador não puder ser lida, torne-a legível e tente novamente."+#: src/components/AgentDiffPane.tsx#: src/components/TimelineDiffPane.tsxmsgid "Diff render mode"@@ -14110,6 +14122,10 @@ msgstr "Falha na sincronização — veja os logs do servidor para os detalhes."msgid "Sync is failing. See the sync status for details."msgstr "A sincronização está falhando. Veja o status de sincronização para os detalhes."+#: src/components/SyncStatusBadge.tsx+msgid "Sync is paused because incoming changes leave a symlink pointing outside the repository or into private files, or with a target that cannot be checked. Ask whoever pushed them to fix the link, or update Git if yours is older than 2.38. Automatic sync then resumes; in Manual mode, pull again."+msgstr "A sincronização está pausada porque as alterações recebidas deixam um link simbólico apontando para fora do repositório ou para arquivos privados, ou com um destino que não pode ser verificado. Peça a quem as enviou que corrija o link, ou atualize o Git se a sua versão for anterior à 2.38. Depois, a sincronização automática é retomada; no modo Manual, faça pull novamente."+#: src/components/SyncBlockingChanges.tsxmsgid "Sync is paused. Commit these local edits to continue, or sort them out in a terminal."msgstr "A sincronização está pausada. Faça commit destas edições locais para continuar, ou resolva-as em um terminal."diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.jsonindex 55fc1d963..72fccf93c 100644--- a/packages/app/src/locales/ur/messages.json+++ b/packages/app/src/locales/ur/messages.json@@ -156,6 +156,10 @@"0t0bbC": ["مطابقت پذیری کی ترجیح محفوظ نہیں ہو سکی: ", ["detail"]],"0tV-rz": ["ترتیبات ابھی لوڈ ہو رہی ہیں۔ تھوڑی دیر بعد دوبارہ کوشش کریں۔"],"0uTHCg": ["نیا OpenKnowledge پروجیکٹ شروع کریں۔"],+ "0uxLib": [+ ["shareBranch"],+ " کے سِم لنکس کی جانچ نہیں ہو سکی، اس لیے اس پر منتقل نہیں کیا گیا۔ دوبارہ کوشش کریں؛ اگر یہ بار بار ناکام ہو تو دیکھیں کہ Git انسٹال ہے اور پروجیکٹ فولڈر پڑھا جا سکتا ہے۔"+ ],"0wkh7o": ["OpenKnowledge لاگز، جن میں مختلف پروجیکٹس کی سرگرمی شامل ہے۔"],"0wswKc": ["افقی لکیر جو سیکشنز کو الگ کرتی ہے۔"],"0x9smA": ["یہ صفحہ اب اس راستے پر نہیں ہے۔"],@@ -411,6 +415,10 @@"پہلے سے git ریپازٹری موجود ہے؟ اس پروجیکٹ کے فولڈر میں <0>git remote add origin <url></0> سے شامل کریں۔ ریموٹ کا پتا چلتے ہی یہ صفحہ خودکار طور پر تازہ ہو جاتا ہے۔"],"45MZFs": ["کمانڈز"],+ "461Vg9": [+ ["shareBranch"],+ " پر منتقل نہیں کیا گیا: اس میں ایک سِم لنک ہے جو ریپازٹری سے باہر، نجی فائلوں کی طرف، یا ایسی جگہ کی طرف اشارہ کرتا ہے جس کی جانچ نہیں ہو سکتی۔ عام طور پر جس نے برانچ پُش کی ہے اسی کو لنک درست کرنا ہوگا۔ اگر اس کمپیوٹر کا کوئی فولڈر پڑھا نہیں جا سکتا تو اسے پڑھنے کے قابل بنائیں اور دوبارہ کوشش کریں۔"+ ],"46YgRZ": ["نیچے بلاک شامل کریں"],"484LKL": ["لنک ہٹائیں"],"49Mb7P": [@@ -842,6 +850,9 @@"8nWu1k": ["خالی خاکہ"],"8oWgty": ["بھیجنے کے لیے تمام تبصرے منتخب کریں"],"8qgfac": ["MCP سرورز"],+ "8qsUJv": [+ "مطابقت پذیری روکی گئی ہے کیونکہ آنے والی تبدیلیوں کے بعد ایک سِم لنک ریپازٹری سے باہر یا نجی فائلوں کی طرف اشارہ کرتا ہے، یا اس کے ہدف کی جانچ نہیں ہو سکتی۔ جس نے یہ تبدیلیاں پُش کی ہیں اس سے لنک درست کرنے کو کہیں، یا اگر آپ کا Git ورژن 2.38 سے پرانا ہے تو Git اپ ڈیٹ کریں۔ اس کے بعد خودکار مطابقت پذیری دوبارہ شروع ہو جائے گی؛ دستی موڈ میں دوبارہ کھینچیں۔"+ ],"8rZ1pk": [["id"], " کو فعال کریں"],"8ruqQi": ["ٹوٹے ہوئے داخلی لنکس"],"8t9CRE": [["agentName"], " شروع کیا جا رہا ہے…"],@@ -4904,6 +4915,9 @@"pA16WG": ["اس پروجیکٹ کا کوئی GitHub ریموٹ نہیں۔"],"pAgkuZ": ["«", ["docName"], "» کو نئی مقامی اشتراکی کیشے کے ساتھ دوبارہ کھولا جا رہا ہے۔"],"pBROkv": ["رکنیت لینے کا شکریہ۔ مصنوعات کی اپ ڈیٹس کے لیے اپنا اِن باکس دیکھتے رہیں۔"],+ "pCJv30": [+ ["hiddenCount", "plural", { "one": ["#", " مزید لنک"], "other": ["#", " مزید لنکس"] }]+ ],"pCralD": ["بائیں جانب نئے پین میں منتقل کریں"],"pEQFsW": ["کوئی مماثل پروجیکٹ نہیں۔"],"pFPzHA": ["ایموجی منتخب کنندہ"],diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.poindex 6ddaae1d9..cb048aedf 100644--- a/packages/app/src/locales/ur/messages.po+++ b/packages/app/src/locales/ur/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, one {فولڈر} other {فولڈرز}}"msgid "{formatted} GitHub stars"msgstr "{formatted} GitHub ستارے"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "{hiddenCount, plural, one {# more link} other {# more links}}"+msgstr "{hiddenCount, plural, one {# مزید لنک} other {# مزید لنکس}}"+#: src/lib/restart-collab-server.tsmsgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."msgstr "{holder} اس پروجیکٹ کو سرو کر رہا ہے، اس لیے یہ ایپ اسے نہیں روکے گی۔ یہ ونڈو بند کریں اور {holder} کا سرور روک کر پروجیکٹ یہاں کھولنے کے لیے پروجیکٹ دوبارہ کھولیں۔"@@ -3934,6 +3938,10 @@ msgstr "نقل کیا جا رہا ہے"msgid "Copying..."msgstr "نقل کیا جا رہا ہے..."+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Could not check the symlinks in {shareBranch}, so it was not switched. Try again; if it keeps failing, check that Git is installed and the project folder is readable."+msgstr "{shareBranch} کے سِم لنکس کی جانچ نہیں ہو سکی، اس لیے اس پر منتقل نہیں کیا گیا۔ دوبارہ کوشش کریں؛ اگر یہ بار بار ناکام ہو تو دیکھیں کہ Git انسٹال ہے اور پروجیکٹ فولڈر پڑھا جا سکتا ہے۔"+#: src/components/settings/SkillTargetsPicker.tsxmsgid "Could not classify the merge — try again."msgstr "ضم کی درجہ بندی نہیں ہو سکی — دوبارہ کوشش کریں۔"@@ -5164,6 +5172,10 @@ msgstr "Mermaid سورس سے خاکہ — فلو چارٹ، سیکوئنس، کmsgid "Diagram view mode"msgstr "خاکے کا منظر موڈ"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."+msgstr "{shareBranch} پر منتقل نہیں کیا گیا: اس میں ایک سِم لنک ہے جو ریپازٹری سے باہر، نجی فائلوں کی طرف، یا ایسی جگہ کی طرف اشارہ کرتا ہے جس کی جانچ نہیں ہو سکتی۔ عام طور پر جس نے برانچ پُش کی ہے اسی کو لنک درست کرنا ہوگا۔ اگر اس کمپیوٹر کا کوئی فولڈر پڑھا نہیں جا سکتا تو اسے پڑھنے کے قابل بنائیں اور دوبارہ کوشش کریں۔"+#: src/components/AgentDiffPane.tsx#: src/components/TimelineDiffPane.tsxmsgid "Diff render mode"@@ -14114,6 +14126,10 @@ msgstr "مطابقت پذیری ناکام رہی — تفصیلات کے لیےmsgid "Sync is failing. See the sync status for details."msgstr "مطابقت پذیری ناکام ہو رہی ہے۔ تفصیلات کے لیے مطابقت پذیری کی حالت دیکھیں۔"+#: src/components/SyncStatusBadge.tsx+msgid "Sync is paused because incoming changes leave a symlink pointing outside the repository or into private files, or with a target that cannot be checked. Ask whoever pushed them to fix the link, or update Git if yours is older than 2.38. Automatic sync then resumes; in Manual mode, pull again."+msgstr "مطابقت پذیری روکی گئی ہے کیونکہ آنے والی تبدیلیوں کے بعد ایک سِم لنک ریپازٹری سے باہر یا نجی فائلوں کی طرف اشارہ کرتا ہے، یا اس کے ہدف کی جانچ نہیں ہو سکتی۔ جس نے یہ تبدیلیاں پُش کی ہیں اس سے لنک درست کرنے کو کہیں، یا اگر آپ کا Git ورژن 2.38 سے پرانا ہے تو Git اپ ڈیٹ کریں۔ اس کے بعد خودکار مطابقت پذیری دوبارہ شروع ہو جائے گی؛ دستی موڈ میں دوبارہ کھینچیں۔"+#: src/components/SyncBlockingChanges.tsxmsgid "Sync is paused. Commit these local edits to continue, or sort them out in a terminal."msgstr "مطابقت پذیری روکی گئی ہے۔ جاری رکھنے کے لیے ان مقامی ترامیم کو کمٹ کریں، یا انہیں ٹرمینل میں حل کریں۔"diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.jsonindex 19e4ccda3..948becd67 100644--- a/packages/app/src/locales/zh-Hans/messages.json+++ b/packages/app/src/locales/zh-Hans/messages.json@@ -143,6 +143,11 @@"0t0bbC": ["无法保存同步偏好:", ["detail"]],"0tV-rz": ["设置仍在加载中。请稍后再试。"],"0uTHCg": ["开始一个新的 OpenKnowledge 项目。"],+ "0uxLib": [+ "无法检查 ",+ ["shareBranch"],+ " 中的符号链接,因此未切换。请重试;如果仍然失败,请确认已安装 Git 且项目文件夹可读。"+ ],"0wkh7o": ["OpenKnowledge 日志,包括跨项目的活动。"],"0wswKc": ["用于分隔章节的水平分割线。"],"0x9smA": ["此页面已不在该路径下。"],@@ -364,6 +369,11 @@"已经有 git 仓库了?在这个项目的文件夹中用 <0>git remote add origin <url></0> 添加它。检测到远程仓库后,本页会自动更新。"],"45MZFs": ["命令"],+ "461Vg9": [+ "未切换到 ",+ ["shareBranch"],+ ":它包含一个指向仓库之外、私有文件或无法检查之处的符号链接。通常需要由推送该分支的人修复该链接。如果这台电脑上的某个文件夹无法读取,请使其可读后重试。"+ ],"46YgRZ": ["在下方添加块"],"484LKL": ["移除链接"],"49Mb7P": ["无法检查是否已安装 Slidev。返回此窗口重试。"],@@ -725,6 +735,9 @@"8nWu1k": ["空图示"],"8oWgty": ["勾选全部评论以发送"],"8qgfac": ["MCP 服务器"],+ "8qsUJv": [+ "同步已暂停,因为传入的更改会使某个符号链接指向仓库之外或私有文件,或其目标无法检查。请让推送这些更改的人修复该链接;如果你的 Git 早于 2.38,请更新 Git。之后自动同步会恢复;在手动模式下,请重新拉取。"+ ],"8rZ1pk": ["启用 ", ["id"]],"8ruqQi": ["失效的内部链接"],"8t9CRE": ["正在启动 ", ["agentName"], "…"],@@ -4188,6 +4201,7 @@"pA16WG": ["此项目没有 GitHub 远程仓库。"],"pAgkuZ": ["正在用全新的本地协作缓存重新打开“", ["docName"], "”。"],"pBROkv": ["感谢订阅。请留意你的邮箱,我们会发送产品动态。"],+ "pCJv30": [["hiddenCount", "plural", { "other": ["另外 ", "#", " 个链接"] }]],"pCralD": ["移动到左侧新窗格"],"pEQFsW": ["没有匹配的项目。"],"pFPzHA": ["表情符号选择器"],diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.poindex 048cd30ce..c83854dad 100644--- a/packages/app/src/locales/zh-Hans/messages.po+++ b/packages/app/src/locales/zh-Hans/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, other {文件夹}}"msgid "{formatted} GitHub stars"msgstr "{formatted} 个 GitHub star"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "{hiddenCount, plural, one {# more link} other {# more links}}"+msgstr "{hiddenCount, plural, other {另外 # 个链接}}"+#: src/lib/restart-collab-server.tsmsgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."msgstr "{holder} 正在为此项目提供服务,因此此应用不会停止它。关闭此窗口并再次打开项目,即可停止 {holder} 的服务器并在此处打开项目。"@@ -3934,6 +3938,10 @@ msgstr "正在复制"msgid "Copying..."msgstr "正在复制…"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Could not check the symlinks in {shareBranch}, so it was not switched. Try again; if it keeps failing, check that Git is installed and the project folder is readable."+msgstr "无法检查 {shareBranch} 中的符号链接,因此未切换。请重试;如果仍然失败,请确认已安装 Git 且项目文件夹可读。"+#: src/components/settings/SkillTargetsPicker.tsxmsgid "Could not classify the merge — try again."msgstr "无法对合并进行分类,请重试。"@@ -5164,6 +5172,10 @@ msgstr "由 Mermaid 源码生成的图示——流程图、时序图、类图、msgid "Diagram view mode"msgstr "图示查看模式"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."+msgstr "未切换到 {shareBranch}:它包含一个指向仓库之外、私有文件或无法检查之处的符号链接。通常需要由推送该分支的人修复该链接。如果这台电脑上的某个文件夹无法读取,请使其可读后重试。"+#: src/components/AgentDiffPane.tsx#: src/components/TimelineDiffPane.tsxmsgid "Diff render mode"@@ -14114,6 +14126,10 @@ msgstr "同步失败——详情请查看服务器日志。"msgid "Sync is failing. See the sync status for details."msgstr "同步正在失败。详情请查看同步状态。"+#: src/components/SyncStatusBadge.tsx+msgid "Sync is paused because incoming changes leave a symlink pointing outside the repository or into private files, or with a target that cannot be checked. Ask whoever pushed them to fix the link, or update Git if yours is older than 2.38. Automatic sync then resumes; in Manual mode, pull again."+msgstr "同步已暂停,因为传入的更改会使某个符号链接指向仓库之外或私有文件,或其目标无法检查。请让推送这些更改的人修复该链接;如果你的 Git 早于 2.38,请更新 Git。之后自动同步会恢复;在手动模式下,请重新拉取。"+#: src/components/SyncBlockingChanges.tsxmsgid "Sync is paused. Commit these local edits to continue, or sort them out in a terminal."msgstr "同步已暂停。提交这些本地编辑以继续,或在终端中处理它们。"diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.jsonindex 8b742fb5c..615361e91 100644--- a/packages/app/src/locales/zh-Hant/messages.json+++ b/packages/app/src/locales/zh-Hant/messages.json@@ -143,6 +143,11 @@"0t0bbC": ["無法儲存同步偏好設定:", ["detail"]],"0tV-rz": ["設定仍在載入中。請稍候再試。"],"0uTHCg": ["開始一個新的 OpenKnowledge 專案。"],+ "0uxLib": [+ "無法檢查 ",+ ["shareBranch"],+ " 中的符號連結,因此未切換。請重試;如果仍然失敗,請確認已安裝 Git 且專案資料夾可讀取。"+ ],"0wkh7o": ["OpenKnowledge 紀錄,包括跨專案的活動。"],"0wswKc": ["用來分隔章節的水平分隔線。"],"0x9smA": ["此頁面已不在該路徑下。"],@@ -366,6 +371,11 @@"已經有 git 儲存庫了?在這個專案的資料夾中用 <0>git remote add origin <url></0> 加上它。偵測到遠端後,這個頁面會自動更新。"],"45MZFs": ["指令"],+ "461Vg9": [+ "未切換到 ",+ ["shareBranch"],+ ":它包含一個指向儲存庫之外、私有檔案或無法檢查之處的符號連結。通常需要由推送該分支的人修正該連結。如果這台電腦上的某個資料夾無法讀取,請使其可讀後重試。"+ ],"46YgRZ": ["在下方新增區塊"],"484LKL": ["移除連結"],"49Mb7P": ["無法檢查是否已安裝 Slidev。請回到此視窗重試。"],@@ -725,6 +735,9 @@"8nWu1k": ["空白圖表"],"8oWgty": ["勾選全部註解以傳送"],"8qgfac": ["MCP 伺服器"],+ "8qsUJv": [+ "同步已暫停,因為傳入的變更會使某個符號連結指向儲存庫之外或私有檔案,或其目標無法檢查。請推送這些變更的人修正該連結;如果你的 Git 早於 2.38,請更新 Git。之後自動同步會恢復;在手動模式下,請重新拉取。"+ ],"8rZ1pk": ["啟用 ", ["id"]],"8ruqQi": ["失效的內部連結"],"8t9CRE": ["正在啟動 ", ["agentName"], "…"],@@ -4206,6 +4219,7 @@"pA16WG": ["這個專案沒有 GitHub 遠端儲存庫。"],"pAgkuZ": ["正在用全新的本機協作快取重新開啟「", ["docName"], "」。"],"pBROkv": ["謝謝訂閱。請留意你的信箱,我們會寄出產品動態。"],+ "pCJv30": [["hiddenCount", "plural", { "other": ["另外 ", "#", " 個連結"] }]],"pCralD": ["移動到左側新窗格"],"pEQFsW": ["沒有相符的專案。"],"pFPzHA": ["表情符號選擇器"],diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.poindex 0293ecdbb..2bb1d3ecb 100644--- a/packages/app/src/locales/zh-Hant/messages.po+++ b/packages/app/src/locales/zh-Hant/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, other {資料夾}}"msgid "{formatted} GitHub stars"msgstr "{formatted} 個 GitHub star"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "{hiddenCount, plural, one {# more link} other {# more links}}"+msgstr "{hiddenCount, plural, other {另外 # 個連結}}"+#: src/lib/restart-collab-server.tsmsgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."msgstr "{holder} 正在為此專案提供服務,因此此應用程式不會停止它。關閉此視窗並再次開啟專案,即可停止 {holder} 的伺服器並在此處開啟專案。"@@ -3934,6 +3938,10 @@ msgstr "正在複製"msgid "Copying..."msgstr "正在複製…"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Could not check the symlinks in {shareBranch}, so it was not switched. Try again; if it keeps failing, check that Git is installed and the project folder is readable."+msgstr "無法檢查 {shareBranch} 中的符號連結,因此未切換。請重試;如果仍然失敗,請確認已安裝 Git 且專案資料夾可讀取。"+#: src/components/settings/SkillTargetsPicker.tsxmsgid "Could not classify the merge — try again."msgstr "無法對合併進行分類,請再試一次。"@@ -5164,6 +5172,10 @@ msgstr "由 Mermaid 原始碼產生的圖表——流程圖、循序圖、類別msgid "Diagram view mode"msgstr "圖表檢視模式"+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."+msgstr "未切換到 {shareBranch}:它包含一個指向儲存庫之外、私有檔案或無法檢查之處的符號連結。通常需要由推送該分支的人修正該連結。如果這台電腦上的某個資料夾無法讀取,請使其可讀後重試。"+#: src/components/AgentDiffPane.tsx#: src/components/TimelineDiffPane.tsxmsgid "Diff render mode"@@ -14114,6 +14126,10 @@ msgstr "同步失敗——詳情請看伺服器記錄。"msgid "Sync is failing. See the sync status for details."msgstr "同步一直失敗。詳情請看同步狀態。"+#: src/components/SyncStatusBadge.tsx+msgid "Sync is paused because incoming changes leave a symlink pointing outside the repository or into private files, or with a target that cannot be checked. Ask whoever pushed them to fix the link, or update Git if yours is older than 2.38. Automatic sync then resumes; in Manual mode, pull again."+msgstr "同步已暫停,因為傳入的變更會使某個符號連結指向儲存庫之外或私有檔案,或其目標無法檢查。請推送這些變更的人修正該連結;如果你的 Git 早於 2.38,請更新 Git。之後自動同步會恢復;在手動模式下,請重新拉取。"+#: src/components/SyncBlockingChanges.tsxmsgid "Sync is paused. Commit these local edits to continue, or sort them out in a terminal."msgstr "同步已暫停。提交這些本地編輯以繼續,或在終端機中處理它們。"diff --git a/packages/cli/src/auth/token-store.ts b/packages/cli/src/auth/token-store.tsindex be65dcaa4..b3a203188 100644--- a/packages/cli/src/auth/token-store.ts+++ b/packages/cli/src/auth/token-store.ts@@ -1,6 +1,10 @@import { existsSync, mkdirSync, readFileSync } from 'node:fs';import { dirname, join } from 'node:path';-import { currentDesktopProduct, okUserHomeDisplayPath } from '@inkeep/open-knowledge-core';+import {+ currentDesktopProduct,+ OK_USER_HOME_AUTH_FILE,+ okUserHomeDisplayPath,+} from '@inkeep/open-knowledge-core';import { atomicWriteFileSync, okUserHomeDir } from '@inkeep/open-knowledge-core/server';import { parse as yamlParse, stringify as yamlStringify } from 'yaml';@@ -25,7 +29,7 @@ export interface TokenStore {}export function authFileDisplayPath(): string {- return okUserHomeDisplayPath('auth.yml');+ return okUserHomeDisplayPath(OK_USER_HOME_AUTH_FILE);}function keyringService(): string {@@ -113,7 +117,7 @@ export class FileBackend implements TokenStore {private readonly authFile: string;constructor(authFile?: string) {- this.authFile = authFile ?? join(okUserHomeDir(), 'auth.yml');+ this.authFile = authFile ?? join(okUserHomeDir(), OK_USER_HOME_AUTH_FILE);}private read(): Record<string, TokenEntry> {diff --git a/packages/cli/src/commands/deinit.ts b/packages/cli/src/commands/deinit.tsindex eb8327bc4..004a4b117 100644--- a/packages/cli/src/commands/deinit.ts+++ b/packages/cli/src/commands/deinit.ts@@ -1,6 +1,7 @@import { existsSync } from 'node:fs';import { homedir } from 'node:os';import { join, resolve } from 'node:path';+import { OK_USER_HOME_AUTH_FILE } from '@inkeep/open-knowledge-core';import { isHomeDir } from '@inkeep/open-knowledge-server';import { Command } from 'commander';import { accent, dim, error as errorColor, warning } from '../ui/colors.ts';@@ -46,7 +47,7 @@ export async function runDeinit(opts: DeinitOptions = {}): Promise<DeinitResult>message:`${errorColor('Refusing to deinit your home directory.')}\n` +` ${projectRoot}/.ok is OpenKnowledge's user-global directory (global.yml, skills/,\n` +- ` auth.yml), not a project. Removing it would delete your global settings and skills.\n` ++ ` ${OK_USER_HOME_AUTH_FILE}), not a project. Removing it would delete your global settings and skills.\n` +` To remove OpenKnowledge everywhere, use 'ok uninstall'.`,exitCode: 64,};diff --git a/packages/cli/src/commands/diagnose-health-checks/git.test.ts b/packages/cli/src/commands/diagnose-health-checks/git.test.tsindex f3d8159be..2b7922f4d 100644--- a/packages/cli/src/commands/diagnose-health-checks/git.test.ts+++ b/packages/cli/src/commands/diagnose-health-checks/git.test.ts@@ -31,6 +31,19 @@ describe('git check', () => {expect(result.summary).toContain('/usr/bin/git');});+ test('warns below the Git version sync needs to check symlink merges', async () => {+ const detected: GitDetected = {+ ok: true,+ version: '2.34.1',+ resolvedPath: '/usr/bin/git',+ source: 'PATH',+ };+ const result = await makeGitCheck({ assert: () => detected }).run(ctx);+ expect(result.status).toBe('warn');+ expect(result.summary).toContain('2.34.1');+ expect(result.remediation).toBe('Update Git to 2.38 or newer');+ });+test('fails when assert throws GitNotAvailableError; embeds install guidance', async () => {const def = makeGitCheck({assert: () => {diff --git a/packages/cli/src/commands/diagnose-health-checks/git.ts b/packages/cli/src/commands/diagnose-health-checks/git.tsindex ee5f861ad..6d9af19db 100644--- a/packages/cli/src/commands/diagnose-health-checks/git.ts+++ b/packages/cli/src/commands/diagnose-health-checks/git.ts@@ -1,9 +1,12 @@import {assertGitAvailable,+ compareSemver,type GitDetected,GitNotAvailableError,GitTooOldError,MIN_GIT_VERSION,+ SYMLINK_MERGE_MIN_GIT_LABEL,+ SYMLINK_MERGE_MIN_GIT_VERSION,} from '@inkeep/open-knowledge-server';import type { CheckDefinition, CheckResult } from './types.ts';@@ -18,11 +21,16 @@ export function makeGitCheck(deps: GitCheckDeps = {}): CheckDefinition {run: async (): Promise<CheckResult> => {try {const detected = assertFn();- return {- name: 'git',- status: 'pass',- summary: `git ${detected.version} (${detected.source} — ${detected.resolvedPath})`,- };+ const summary = `git ${detected.version} (${detected.source} — ${detected.resolvedPath})`;+ if (compareSemver(detected.version, SYMLINK_MERGE_MIN_GIT_VERSION) < 0) {+ return {+ name: 'git',+ status: 'warn',+ summary: `${summary}; sync refuses merges that change symlinks on Git older than ${SYMLINK_MERGE_MIN_GIT_LABEL}`,+ remediation: `Update Git to ${SYMLINK_MERGE_MIN_GIT_LABEL} or newer`,+ };+ }+ return { name: 'git', status: 'pass', summary };} catch (err) {if (err instanceof GitNotAvailableError) {return {diff --git a/packages/cli/src/commands/embeddings/index.ts b/packages/cli/src/commands/embeddings/index.tsindex 88b12f4f6..9f5b1244b 100644--- a/packages/cli/src/commands/embeddings/index.ts+++ b/packages/cli/src/commands/embeddings/index.ts@@ -6,6 +6,7 @@ import {DEFAULT_EMBEDDINGS_MODEL,humanFormat,isSemanticSearchOffered,+ OK_USER_HOME_SECRETS_FILE,okUserHomeDisplayPath,type SemanticIndexStatus,SemanticIndexStatusSchema,@@ -119,7 +120,7 @@ function setKeyCommand(): Command {}process.stderr.write(`✓ Embeddings API key stored for ${baseUrl}\n` +- ` (kept in ${okUserHomeDisplayPath('secrets.yml')}, 0600, this machine only — never in the project).\n` ++ ` (kept in ${okUserHomeDisplayPath(OK_USER_HOME_SECRETS_FILE)}, 0600, this machine only — never in the project).\n` +' Enable semantic search with `ok embeddings enable`, or in\n' +' OK Desktop → Settings → This project → Search.\n',);@@ -366,7 +367,7 @@ function statusCommand(): Command {}const keyLabel = hasKey- ? `set for this endpoint — ${keySource === 'env' ? `environment (${EMBEDDINGS_API_KEY_ENV})` : okUserHomeDisplayPath('secrets.yml')}`+ ? `set for this endpoint — ${keySource === 'env' ? `environment (${EMBEDDINGS_API_KEY_ENV})` : okUserHomeDisplayPath(OK_USER_HOME_SECRETS_FILE)}`: keyNotRequired? 'not required (loopback endpoint)': 'not set';diff --git a/packages/cli/src/commands/pull.ts b/packages/cli/src/commands/pull.tsindex 63b12913e..150193c7d 100644--- a/packages/cli/src/commands/pull.ts+++ b/packages/cli/src/commands/pull.ts@@ -1,6 +1,6 @@import type { Config } from '@inkeep/open-knowledge-server';import { Command } from 'commander';-import { runSync } from './sync.ts';+import { runSync, syncFailureMessage } from './sync.ts';export function pullCommand(getConfig: () => Config): Command {return new Command('pull')@@ -10,7 +10,7 @@ export function pullCommand(getConfig: () => Config): Command {try {await runSync({ json: opts.json, op: 'pull' }, getConfig());} catch (err) {- const msg = err instanceof Error ? err.message : String(err);+ const msg = syncFailureMessage(err);if (opts.json) {process.stdout.write(`${JSON.stringify({ type: 'error', message: msg })}\n`);} else {diff --git a/packages/cli/src/commands/removal-plan.ts b/packages/cli/src/commands/removal-plan.tsindex 268297b06..496da37d1 100644--- a/packages/cli/src/commands/removal-plan.ts+++ b/packages/cli/src/commands/removal-plan.ts@@ -3,6 +3,8 @@ import { basename, join, relative, resolve, sep } from 'node:path';import {currentDesktopProduct,OK_DIR,+ OK_USER_HOME_AUTH_FILE,+ OK_USER_HOME_SECRETS_FILE,PROJECT_SKILL_PROJECTION_PATHS,resolveDesktopProductName,SHARED_OK_ENTRIES,@@ -256,13 +258,13 @@ export function buildUninstallPlan(input: UninstallPlanInput): RemovalPlan {ops.push({kind: 'keychain-token',group: 'Credentials',- label: `Remove the GitHub credential (${host}) from the OS keychain + auth.yml`,+ label: `Remove the GitHub credential (${host}) from the OS keychain + ${OK_USER_HOME_AUTH_FILE}`,host,});ops.push({kind: 'embeddings-key',group: 'Credentials',- label: 'Remove all embeddings API keys (secrets.yml)',+ label: `Remove all embeddings API keys (${OK_USER_HOME_SECRETS_FILE})`,});ops.push(...pathRevertOps(marker, home));diff --git a/packages/cli/src/commands/sync-credential-helper.test.ts b/packages/cli/src/commands/sync-credential-helper.test.tsindex 6031981fd..78536ca4e 100644--- a/packages/cli/src/commands/sync-credential-helper.test.ts+++ b/packages/cli/src/commands/sync-credential-helper.test.ts@@ -359,7 +359,7 @@ describe("ok sync without a running server authenticates through OpenKnowledge'sfunction expectCredentialConfinedToCliHelper(token: string,- context: { tracedCommand?: 'pull' | 'push'; remoteName?: string } = {},+ context: { tracedCommand?: 'fetch' | 'pull' | 'push'; remoteName?: string } = {},): void {const { tracedCommand = 'pull', remoteName = 'origin' } = context;const trace = readFileSync(traceFile, 'utf-8');@@ -1465,10 +1465,10 @@ describe("ok sync without a running server authenticates through OpenKnowledge'sconst outcome = await syncWith(signedInSeam());- expect.soft(outcome.error, 'the error runSync threw').not.toBeNull();+ expect.soft(String(outcome.error), 'the error runSync threw').toMatch(/no upstream configured/);expect- .soft(readFileSync(traceFile, 'utf-8'), "git's own pull in the trace")- .toMatch(/built-in: git pull/);+ .soft(readFileSync(traceFile, 'utf-8'), 'a pull that could merge')+ .not.toMatch(/built-in: git pull/);expect.soft(readJsonLines<CliHelperCall>(cliHelperLog), "calls reaching the CLI's own helper").toEqual([]);@@ -1492,6 +1492,6 @@ describe("ok sync without a running server authenticates through OpenKnowledge's.toContainEqual(authenticatedRequest('fetch', { username: expect.any(String), password: OK_TOKEN }),);- expectCredentialConfinedToCliHelper(OK_TOKEN);+ expectCredentialConfinedToCliHelper(OK_TOKEN, { tracedCommand: 'fetch' });});});diff --git a/packages/cli/src/commands/sync-incoming-symlinks.test.ts b/packages/cli/src/commands/sync-incoming-symlinks.test.tsnew file mode 100644index 000000000..a31755aa6--- /dev/null+++ b/packages/cli/src/commands/sync-incoming-symlinks.test.ts@@ -0,0 +1,265 @@+import { spawnSync } from 'node:child_process';+import {+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readlinkSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import {+ assertMergeNameResolvesTo,+ type Config,+ UnsafeIncomingSymlinkError,+} from '@inkeep/open-knowledge-server';+import simpleGit, { type SimpleGit } from 'simple-git';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { FileBackend } from '../auth/token-store.ts';+import { runSync, syncFailureMessage } from './sync.ts';++const CLI_ENTRY = fileURLToPath(new URL('../cli.ts', import.meta.url));++let tmpDir = '';+let projectDir = '';+let sister: SimpleGit;+let project: SimpleGit;++beforeEach(async () => {+ tmpDir = mkdtempSync(join(tmpdir(), 'ok-pull-incoming-symlinks-'));+ const bareDir = join(tmpDir, 'bare.git');+ const sisterDir = join(tmpDir, 'sister');+ projectDir = join(tmpDir, 'project');+ mkdirSync(bareDir, { recursive: true });+ await simpleGit(bareDir).init(true);+ await simpleGit(bareDir).raw('symbolic-ref', 'HEAD', 'refs/heads/main');++ mkdirSync(join(sisterDir, 'notes'), { recursive: true });+ sister = simpleGit(sisterDir);+ await sister.init(['--initial-branch=main']);+ await sister.raw('config', 'user.name', 'Sister');+ await sister.raw('config', 'user.email', '[email protected]');+ writeFileSync(join(sisterDir, 'notes', 'real.md'), '# real\n', 'utf-8');+ await sister.add('.');+ await sister.commit('base');+ await sister.addRemote('origin', bareDir);+ await sister.push('origin', 'main');++ await simpleGit(tmpDir).clone(bareDir, projectDir);+ project = simpleGit(projectDir);+ await project.raw('config', 'user.name', 'Project');+ await project.raw('config', 'user.email', '[email protected]');+});++afterEach(() => {+ vi.unstubAllEnvs();+ rmSync(tmpDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+});++async function pushSymlink(path: string, target: string, remoteBranch = 'main'): Promise<void> {+ const targetFile = join(tmpDir, 'link-target.txt');+ writeFileSync(targetFile, target, 'utf-8');+ const blob = (await sister.raw('hash-object', '-w', targetFile)).trim();+ await sister.raw('update-index', '--add', '--cacheinfo', `120000,${blob},${path}`);+ await sister.commit('add symlink');+ await sister.push('origin', `HEAD:${remoteBranch}`);+}++async function narrowFetchToMain(): Promise<void> {+ await project.raw('config', 'remote.origin.fetch', '+refs/heads/main:refs/remotes/origin/main');+}++function pullWithoutServer(): Promise<void> {+ return runSync(+ {+ json: true,+ op: 'pull',+ tokenStore: new FileBackend(join(tmpDir, 'auth.yml')),+ _detectGhFn: () => ({ available: false }),+ },+ {} as Config,+ projectDir,+ );+}++function existsAsEntry(relPath: string): boolean {+ try {+ lstatSync(join(projectDir, relPath));+ return true;+ } catch {+ return false;+ }+}++describe('ok pull refusal remedies', () => {+ test.each([+ [+ [{ path: 'a', reason: 'requires-newer-git' }],+ 'Update Git to 2.38 or newer. Then pull again.',+ ],+ [+ [{ path: 'a', reason: 'unverifiable-target' }],+ 'If a folder on the way is unreadable on this machine, make it readable. Remove or fix these links on the remote, or fix your own local change to them, then pull again.',+ ],+ [+ [{ path: 'a', reason: 'secret-file' }],+ 'Remove or fix these links on the remote, or fix your own local change to them, then pull again.',+ ],+ [+ [+ { path: 'a', reason: 'requires-newer-git' },+ { path: 'b', reason: 'outside-repository' },+ ],+ 'Update Git to 2.38 or newer. Remove or fix these links on the remote, or fix your own local change to them, then pull again.',+ ],+ ] as const)('names the remedy for %j', (unsafe, remedy) => {+ expect(syncFailureMessage(new UnsafeIncomingSymlinkError(unsafe)).endsWith(remedy)).toBe(true);+ });+});++describe('ok pull without a running server', () => {+ test('refuses a remote symlink into private state, naming it only when rendered', async () => {+ await pushSymlink('notes/leak.md', '../.git/config');++ const error = await pullWithoutServer().then(+ () => null,+ (caught: unknown) => caught,+ );+ expect(error).toBeInstanceOf(UnsafeIncomingSymlinkError);+ expect((error as Error).message).not.toContain('leak');+ expect(syncFailureMessage(error)).toBe(+ 'incoming symlinks are unsafe to check out: "notes/leak.md" (points into private .git or OpenKnowledge state). Remove or fix these links on the remote, or fix your own local change to them, then pull again.',+ );+ expect(existsAsEntry('notes/leak.md')).toBe(false);+ });++ test("leaves git's own error for a branch with no upstream, without merging anything", async () => {+ await narrowFetchToMain();+ await project.raw('checkout', '-b', 'no-upstream');+ await pushSymlink('notes/leak.md', '../.git/config');++ await expect(pullWithoutServer()).rejects.toThrow(+ /no upstream configured for branch "no-upstream".*git branch --set-upstream-to=origin\/no-upstream no-upstream/,+ );+ expect(existsAsEntry('notes/leak.md')).toBe(false);+ });++ test('names the remedy on a detached HEAD, without merging anything', async () => {+ await project.raw('checkout', '--detach');+ await pushSymlink('notes/leak.md', '../.git/config');++ await expect(pullWithoutServer()).rejects.toThrow(/not on a branch.*git switch/);+ expect(existsAsEntry('notes/leak.md')).toBe(false);+ });++ test('pulls the inspected tracking ref by its full name, never a shadowable short name', async () => {+ await pushSymlink('notes/alias.md', 'real.md');+ const traceFile = join(tmpDir, 'git-trace.log');+ vi.stubEnv('GIT_TRACE', traceFile);++ await pullWithoutServer();+ const commands = readFileSync(traceFile, 'utf-8')+ .split('\n')+ .filter((line) => line.includes('trace: built-in: git '))+ .map((line) => line.slice(line.indexOf('git ')));+ expect(commands.filter((command) => command.startsWith('git pull'))).toEqual([+ 'git pull . refs/remotes/origin/main',+ ]);+ });++ test('refuses to pull when the tracking ref moves after inspection', async () => {+ await pushSymlink('notes/alias.md', 'real.md');+ const inspected = (await sister.revparse(['HEAD'])).trim();+ await pushSymlink('notes/leak.md', '../.git/config', 'later');+ await project.fetch('origin', 'later');+ const later = (await project.revparse(['origin/later'])).trim();+ await project.fetch('origin', 'main');++ await expect(+ assertMergeNameResolvesTo(project, {+ name: 'refs/remotes/origin/main',+ trackingRef: 'refs/remotes/origin/main',+ commit: later,+ }),+ ).rejects.toThrow(/moved after its incoming symlinks were inspected/);+ await assertMergeNameResolvesTo(project, {+ name: 'refs/remotes/origin/main',+ trackingRef: 'refs/remotes/origin/main',+ commit: inspected,+ });+ });++ test('refuses to merge a short name that a tag shadows', async () => {+ await pushSymlink('notes/alias.md', 'real.md');+ await project.fetch('origin', 'main');+ const tracked = (await project.revparse(['refs/remotes/origin/main'])).trim();+ await project.raw('tag', 'origin/main', `${tracked}~1`);++ await expect(+ assertMergeNameResolvesTo(project, {+ name: 'origin/main',+ trackingRef: 'refs/remotes/origin/main',+ commit: tracked,+ }),+ ).rejects.toThrow(/shadows it/);+ });++ test('guards an upstream that is configured but not stored as a remote-tracking ref', async () => {+ await narrowFetchToMain();+ await sister.push('origin', 'main:feature');+ await project.raw('checkout', '-b', 'feature');+ await project.raw('config', 'branch.feature.remote', 'origin');+ await project.raw('config', 'branch.feature.merge', 'refs/heads/feature');+ await pushSymlink('notes/leak.md', '../.git/config', 'feature');++ await expect(pullWithoutServer()).rejects.toBeInstanceOf(UnsafeIncomingSymlinkError);+ expect(existsAsEntry('notes/leak.md')).toBe(false);+ });++ test('pulls a safe link through an upstream that is configured but not stored as a remote-tracking ref', async () => {+ await narrowFetchToMain();+ await sister.push('origin', 'main:feature');+ await project.raw('checkout', '-b', 'feature');+ await project.raw('config', 'branch.feature.remote', 'origin');+ await project.raw('config', 'branch.feature.merge', 'refs/heads/feature');+ await pushSymlink('notes/alias.md', 'real.md', 'feature');++ await pullWithoutServer();+ expect(readlinkSync(join(projectDir, 'notes', 'alias.md'))).toBe('real.md');+ });++ test('still pulls an in-repository symlink', async () => {+ await pushSymlink('notes/alias.md', 'real.md');++ await pullWithoutServer();+ expect(readlinkSync(join(projectDir, 'notes', 'alias.md'))).toBe('real.md');+ });++ test('ok pull --json keeps stdout to JSON lines and reports the refused path in its error record', async () => {+ await pushSymlink('notes/leak.md', '../.git/config');+ const env = { ...process.env };+ for (const variable of ['NODE_ENV', 'LOG_LEVEL', 'OK_CONSOLE_LEVEL', 'OK_FILE_LEVEL']) {+ delete env[variable];+ }++ const result = spawnSync(+ process.execPath,+ ['--conditions=@inkeep/source', CLI_ENTRY, 'pull', '--json'],+ { cwd: projectDir, encoding: 'utf-8', env },+ );++ expect(result.status).toBe(1);+ const records = result.stdout+ .split('\n')+ .filter((line) => line.trim() !== '')+ .map((line) => JSON.parse(line) as Record<string, unknown>);+ expect(records.at(-1)).toEqual({+ type: 'error',+ message: expect.stringMatching(/"notes\/leak\.md" \(points into private.*on the remote/),+ });+ expect(existsAsEntry('notes/leak.md')).toBe(false);+ }, 60_000);+});diff --git a/packages/cli/src/commands/sync.ts b/packages/cli/src/commands/sync.tsindex 15a1fd73c..45c7630cf 100644--- a/packages/cli/src/commands/sync.ts+++ b/packages/cli/src/commands/sync.ts@@ -6,11 +6,16 @@ import {normalizeGitHostname,} from '@inkeep/open-knowledge-core';import {+ assertIncomingSymlinksSafe,+ assertMergeNameResolvesTo,type Config,RUNTIME_VERSION,readDeclaredGitHubHosts,readServerLock,resolveLockDir,+ SYMLINK_MERGE_MIN_GIT_LABEL,+ UnsafeIncomingSymlinkError,+ type UnsafeSymlinkReason,} from '@inkeep/open-knowledge-server';import { Command } from 'commander';import simpleGit, { type SimpleGit } from 'simple-git';@@ -198,6 +203,83 @@ async function runOnRemote<T>(}}+interface IncomingCommit {+ commit: string;+ trackingRef: string | null;+}++async function fetchIncomingCommit(git: SimpleGit): Promise<IncomingCommit> {+ await git.fetch();+ const tracked = (+ await git.raw(['rev-parse', '--verify', '--quiet', '@{upstream}^{commit}'])+ ).trim();+ if (tracked !== '') {+ const trackingRef = (+ await git.raw(['rev-parse', '--symbolic-full-name', '@{upstream}'])+ ).trim();+ return { commit: tracked, trackingRef: trackingRef.startsWith('refs/') ? trackingRef : null };+ }+ const branch = (await git.raw(['symbolic-ref', '--quiet', '--short', 'HEAD'])).trim();+ if (branch === '') {+ throw new Error(+ 'not on a branch, so there is nothing to pull into; switch to a branch first, for example: git switch main',+ );+ }+ const mergeRef = (await git.raw(['config', '--get', `branch.${branch}.merge`])).trim();+ const remote = (await git.raw(['config', '--get', `branch.${branch}.remote`])).trim() || 'origin';+ if (mergeRef === '') {+ throw new Error(+ `no upstream configured for branch "${branch}"; set one with: git branch --set-upstream-to=${remote}/${branch} ${branch}`,+ );+ }+ await git.fetch(remote, mergeRef);+ const fetched = (+ await git.raw(['rev-parse', '--verify', '--quiet', 'FETCH_HEAD^{commit}'])+ ).trim();+ if (fetched === '') throw new Error(`could not resolve the fetched ${mergeRef}`);+ return { commit: fetched, trackingRef: null };+}++type SymlinkRemedy = 'update-git' | 'readable-folder' | 'fix-link';++function remediesFor(reason: UnsafeSymlinkReason): readonly SymlinkRemedy[] {+ switch (reason) {+ case 'requires-newer-git':+ return ['update-git'];+ case 'unverifiable-target':+ return ['readable-folder', 'fix-link'];+ case 'outside-repository':+ case 'repository-root':+ case 'private-state':+ case 'secret-file':+ case 'inside-private-state':+ return ['fix-link'];+ default: {+ const exhaustive: never = reason;+ return exhaustive;+ }+ }+}++const REMEDY_TEXT: Record<SymlinkRemedy, string> = {+ 'update-git': `Update Git to ${SYMLINK_MERGE_MIN_GIT_LABEL} or newer.`,+ 'readable-folder': 'If a folder on the way is unreadable on this machine, make it readable.',+ 'fix-link':+ 'Remove or fix these links on the remote, or fix your own local change to them, then pull again.',+};++export function syncFailureMessage(err: unknown): string {+ if (err instanceof UnsafeIncomingSymlinkError) {+ const remedies = new Set(err.unsafe.flatMap(({ reason }) => remediesFor(reason)));+ const steps = Object.entries(REMEDY_TEXT)+ .filter(([remedy]) => remedies.has(remedy as SymlinkRemedy))+ .map(([, text]) => text);+ if (!remedies.has('fix-link')) steps.push('Then pull again.');+ return `incoming symlinks are unsafe to check out: ${err.describeLinks()}. ${steps.join(' ')}`;+ }+ return err instanceof Error ? err.message : String(err);+}+export async function runSync(opts: SyncOptions,_config: Config,@@ -270,7 +352,17 @@ export async function runSync(emit(opts.json, { type: 'step', step: 'pull' });const url = await contactedRemoteUrl(local, 'pull');pulled = { url, remote: await remoteFor(url) };- const result = await runOnRemote(pulled.remote, 'pull', (git) => git.pull());+ const incoming = await runOnRemote(pulled.remote, 'pull', fetchIncomingCommit);+ await assertIncomingSymlinksSafe(local, incoming.commit, 'merge');+ const { trackingRef } = incoming;+ if (trackingRef !== null) {+ await assertMergeNameResolvesTo(local, {+ name: trackingRef,+ trackingRef,+ commit: incoming.commit,+ });+ }+ const result = await local.pull('.', trackingRef ?? incoming.commit);emit(opts.json, { type: 'pull', summary: result.summary });if (!opts.json) {process.stderr.write(` pull: ${result.summary.changes} changes\n`);@@ -303,7 +395,7 @@ export function syncCommand(getConfig: () => Config): Command {try {await runSync({ json: opts.json, op: 'sync' }, getConfig());} catch (err) {- const msg = err instanceof Error ? err.message : String(err);+ const msg = syncFailureMessage(err);if (opts.json) {process.stdout.write(`${JSON.stringify({ type: 'error', message: msg })}\n`);} else {diff --git a/packages/core/src/constants/ok-dir.ts b/packages/core/src/constants/ok-dir.tsindex 64d2a1b8c..21502c53a 100644--- a/packages/core/src/constants/ok-dir.ts+++ b/packages/core/src/constants/ok-dir.ts@@ -22,6 +22,15 @@ export const OK_MACHINE_LOCAL_ROOT_FILES = ['last-spawn-error.log',] as const;+export const OK_USER_HOME_AUTH_FILE = 'auth.yml';++export const OK_USER_HOME_SECRETS_FILE = 'secrets.yml';++export const OK_USER_HOME_CREDENTIAL_FILES = [+ OK_USER_HOME_AUTH_FILE,+ OK_USER_HOME_SECRETS_FILE,+] as const;+export const OK_ACTIVE_MACHINE_LOCAL_ROOT_DIRS = [LOCAL_DIR, WORKTREES_DIRNAME] as const;export const OK_MACHINE_LOCAL_ROOT_DIRS = [diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 02d7bf105..1c141aa13 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -514,6 +514,9 @@ export {OK_MACHINE_LOCAL_ROOT_DIRS,OK_MACHINE_LOCAL_ROOT_FILES,OK_PROJECT_MARKER,+ OK_USER_HOME_AUTH_FILE,+ OK_USER_HOME_CREDENTIAL_FILES,+ OK_USER_HOME_SECRETS_FILE,type OkMachineLocalRootDir,type OkMachineLocalRootFile,okUserHomeDisplayPath,@@ -1458,6 +1461,7 @@ export {type PushPermissionWire,QueueSuccessSchema,RECONCILE_REASONS,+ REFUSED_SYMLINK_PATHS_CAP,RESOLVE_STRATEGIES,ReconcileReasonSchema,type ReconcileReasonWire,diff --git a/packages/core/src/schemas/api/share.ts b/packages/core/src/schemas/api/share.tsindex fcbd56b3b..b973c9e50 100644--- a/packages/core/src/schemas/api/share.ts+++ b/packages/core/src/schemas/api/share.ts@@ -1,5 +1,6 @@import type { StandardSchemaV1 } from '@standard-schema/spec';import { z } from 'zod';+import { RefusedSymlinkPathsSchema } from './sync-seed.ts';export const ShareConstructUrlRequestSchema = z.discriminatedUnion('kind', [z@@ -309,6 +310,8 @@ export const CheckoutFailureReasonSchema = z.enum(['checkout-failed','branch-in-other-worktree','ff-diverged',+ 'unsafe-symlinks',+ 'symlink-check-failed',]) satisfies StandardSchemaV1;export type CheckoutFailureReason = z.infer<typeof CheckoutFailureReasonSchema>;@@ -324,6 +327,7 @@ export const CheckoutResponseSchema = z.discriminatedUnion('ok', [reason: CheckoutFailureReasonSchema,files: z.array(z.string().min(1)).optional(),otherWorktreePath: z.string().min(1).optional(),+ refusedSymlinkPaths: RefusedSymlinkPathsSchema.optional(),}).loose(),]) satisfies StandardSchemaV1;diff --git a/packages/core/src/schemas/api/sync-seed.ts b/packages/core/src/schemas/api/sync-seed.tsindex 88d7af08c..7409f3946 100644--- a/packages/core/src/schemas/api/sync-seed.ts+++ b/packages/core/src/schemas/api/sync-seed.ts@@ -2,6 +2,12 @@ import type { StandardSchemaV1 } from '@standard-schema/spec';import { z } from 'zod';import { SYNC_MODES } from '../../config/auto-sync-mode.ts';+export const REFUSED_SYMLINK_PATHS_CAP = 50;++export const RefusedSymlinkPathsSchema = z+ .array(z.string().min(1))+ .max(REFUSED_SYMLINK_PATHS_CAP) satisfies StandardSchemaV1;+export const SyncStateSchema = z.enum(['dormant','idle',@@ -100,6 +106,7 @@ export const SyncStatusSchema = zpullErrorCode: SyncErrorCodeSchema.optional(),pausedReason: z.string().optional(),blockingPaths: z.array(z.string().min(1)).optional(),+ refusedSymlinkPaths: RefusedSymlinkPathsSchema.optional(),pushPermission: PushPermissionSchema.optional(),syncMode: SyncModeSchema.optional(),lastPullUtc: z.string().nullable().optional(),diff --git a/packages/core/src/sync-paused-reason.ts b/packages/core/src/sync-paused-reason.tsindex f487decad..362cd3a0a 100644--- a/packages/core/src/sync-paused-reason.ts+++ b/packages/core/src/sync-paused-reason.ts@@ -10,6 +10,7 @@ export const SYNC_PAUSED_REASONS = ['no-push-permission','non-content-merge-failure','protected-branch',+ 'unsafe-incoming-symlinks',] as const;export type SyncPausedReason = (typeof SYNC_PAUSED_REASONS)[number];diff --git a/packages/server/src/content-filter.ts b/packages/server/src/content-filter.tsindex 3d812e7d9..75d0e51ee 100644--- a/packages/server/src/content-filter.ts+++ b/packages/server/src/content-filter.ts@@ -349,7 +349,7 @@ function isAlwaysSkipFile(relativePath: string): boolean {const SECRET_BEARING_DIRS = new Set(['.ssh', '.aws', '.gnupg', '.kube', '.docker']);-function pathHasSecretBearingDirSegment(relativePath: string): boolean {+export function pathHasSecretBearingDirSegment(relativePath: string): boolean {for (const segment of relativePath.split('/')) {if (SECRET_BEARING_DIRS.has(segment.toLowerCase())) return true;}@@ -364,7 +364,7 @@ const SECRET_CREDENTIAL_BASENAMES = new Set(['.git-credentials',]);const SECRET_KEY_SUFFIXES = ['.pem', '.key', '.p12', '.pfx', '.keystore', '.jks', '.ppk'] as const;-function isSecretBearingFile(relativePath: string): boolean {+export function isSecretBearingFile(relativePath: string): boolean {const lower = relativePath.slice(relativePath.lastIndexOf('/') + 1).toLowerCase();if (lower === '.env' || lower.startsWith('.env.')) return true;if (SECRET_CREDENTIAL_BASENAMES.has(lower)) return true;diff --git a/packages/server/src/embeddings/secrets-store.ts b/packages/server/src/embeddings/secrets-store.tsindex 56092275c..d6bd335b8 100644--- a/packages/server/src/embeddings/secrets-store.ts+++ b/packages/server/src/embeddings/secrets-store.ts@@ -11,7 +11,10 @@ import {} from 'node:fs';import { homedir } from 'node:os';import { dirname, join, resolve } from 'node:path';-import { DEFAULT_EMBEDDINGS_BASE_URL } from '@inkeep/open-knowledge-core';+import {+ DEFAULT_EMBEDDINGS_BASE_URL,+ OK_USER_HOME_SECRETS_FILE,+} from '@inkeep/open-knowledge-core';import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';import { parse as yamlParse, stringify as yamlStringify } from 'yaml';import {@@ -47,7 +50,7 @@ export function canonicalProjectKey(projectDir: string): string {}export function secretsFilePath(homedirOverride?: string): string {- return join(okUserHomeDir(homedirOverride ?? homedir()), 'secrets.yml');+ return join(okUserHomeDir(homedirOverride ?? homedir()), OK_USER_HOME_SECRETS_FILE);}export interface EmbeddingsKeyPresence {diff --git a/packages/server/src/git-checkout-symlink-check-failure.test.ts b/packages/server/src/git-checkout-symlink-check-failure.test.tsnew file mode 100644index 000000000..fb30c5a96--- /dev/null+++ b/packages/server/src/git-checkout-symlink-check-failure.test.ts@@ -0,0 +1,68 @@+import { execFileSync } from 'node:child_process';+import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';++vi.mock('./incoming-symlink-guard.ts', async (importOriginal) => {+ const actual = await importOriginal<typeof import('./incoming-symlink-guard.ts')>();+ return {+ ...actual,+ assertIncomingSymlinksSafe: vi.fn(async () => {+ throw new Error('could not read incoming symlink targets from git (spawn)');+ }),+ };+});++const { runCheckoutFlow } = await import('./git-checkout.ts');++function git(cwd: string, ...args: string[]): string {+ return execFileSync('git', args, {+ cwd,+ encoding: 'utf-8',+ env: {+ ...process.env,+ GIT_CONFIG_GLOBAL: '/dev/null',+ GIT_AUTHOR_NAME: 'test',+ GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'test',+ GIT_COMMITTER_EMAIL: '[email protected]',+ },+ }).trim();+}++describe('share-link branch switch when the symlink check cannot run', () => {+ let tmpDir = '';+ let projectDir = '';++ beforeEach(() => {+ tmpDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-checkout-guard-failure-')));+ const bareDir = join(tmpDir, 'bare.git');+ const seedDir = join(tmpDir, 'seed');+ projectDir = join(tmpDir, 'project');+ git(tmpDir, 'init', '-q', '--bare', '--initial-branch=main', bareDir);+ git(tmpDir, 'init', '-q', '--initial-branch=main', seedDir);+ writeFileSync(join(seedDir, 'a.md'), '# A\n');+ git(seedDir, 'add', 'a.md');+ git(seedDir, 'commit', '-q', '-m', 'base');+ git(seedDir, 'remote', 'add', 'origin', bareDir);+ git(seedDir, 'push', '-q', 'origin', 'main');+ git(seedDir, 'checkout', '-q', '-b', 'shared');+ writeFileSync(join(seedDir, 'b.md'), '# B\n');+ git(seedDir, 'add', 'b.md');+ git(seedDir, 'commit', '-q', '-m', 'shared');+ git(seedDir, 'push', '-q', 'origin', 'shared');+ git(tmpDir, 'clone', '-q', bareDir, projectDir);+ });++ afterEach(() => {+ rmSync(tmpDir, { recursive: true, force: true });+ });++ test('reports symlink-check-failed and leaves HEAD where it was', async () => {+ const outcome = await runCheckoutFlow(projectDir, 'shared', { credentialConfig: [] });++ expect(outcome).toEqual({ ok: false, reason: 'symlink-check-failed' });+ expect(git(projectDir, 'rev-parse', '--abbrev-ref', 'HEAD')).toBe('main');+ });+});diff --git a/packages/server/src/git-checkout.ts b/packages/server/src/git-checkout.tsindex 73267207e..4b271ff4d 100644--- a/packages/server/src/git-checkout.ts+++ b/packages/server/src/git-checkout.ts@@ -1,8 +1,18 @@import { realpathSync } from 'node:fs';-import { type CheckoutFailureReason, isBranchNotFoundGitError } from '@inkeep/open-knowledge-core';+import {+ type CheckoutFailureReason,+ isBranchNotFoundGitError,+ REFUSED_SYMLINK_PATHS_CAP,+} from '@inkeep/open-knowledge-core';import { truncateError } from './error-format.ts';import { dirtyFilesOverlapWith } from './git-dirty.ts';import { createGitInstance } from './git-handle.ts';+import {+ assertIncomingSymlinksSafe,+ escapePathForDisplay,+ resolveIncomingCommit,+ UnsafeIncomingSymlinkError,+} from './incoming-symlink-guard.ts';import { getLogger } from './logger.ts';const log = getLogger('git-checkout');@@ -16,6 +26,7 @@ export type CheckoutOutcome =reason: CheckoutFailureReason;files?: string[];otherWorktreePath?: string;+ refusedSymlinkPaths?: string[];};const BRANCH_IN_OTHER_WORKTREE_RE =@@ -54,7 +65,9 @@ export async function runCheckoutFlow(}}- const { git } = createGitInstance(projectDir, { credentialConfig: opts.credentialConfig });+ const { git, env: gitEnv } = createGitInstance(projectDir, {+ credentialConfig: opts.credentialConfig,+ });const branchIsLocal = await git.raw(['rev-parse', '--verify', `refs/heads/${branch}`])@@ -72,16 +85,80 @@ export async function runCheckoutFlow(}}- const targetRef = branchIsLocal ? branch : `origin/${branch}`;- const overlap = await dirtyFilesOverlapWith(projectDir, targetRef);+ let target: string;+ try {+ target = await resolveIncomingCommit(+ git,+ branchIsLocal ? `refs/heads/${branch}` : `refs/remotes/origin/${branch}`,+ );+ } catch (err) {+ log.warn({ branch, err }, `action=checkout-failed branch=${branch}`);+ return { ok: false, reason: 'checkout-failed' };+ }++ const overlap = await dirtyFilesOverlapWith(projectDir, target);if (overlap.conflicts) {return { ok: false, reason: 'dirty-conflict', files: overlap.files };}try {+ await assertIncomingSymlinksSafe(git, target, 'checkout', gitEnv);+ } catch (err) {+ if (err instanceof UnsafeIncomingSymlinkError) {+ log.warn(+ {+ event: 'unsafe-incoming-symlinks',+ branch,+ target,+ links: err.unsafe.slice(0, REFUSED_SYMLINK_PATHS_CAP),+ refusedCount: err.unsafe.length,+ },+ `action=checkout-refused branch=${branch}`,+ );+ return {+ ok: false,+ reason: 'unsafe-symlinks',+ refusedSymlinkPaths: err.unsafe+ .slice(0, REFUSED_SYMLINK_PATHS_CAP)+ .map(({ path }) => escapePathForDisplay(path)),+ };+ }+ log.warn({ branch, target, err }, `action=symlink-check-failed branch=${branch}`);+ return { ok: false, reason: 'symlink-check-failed' };+ }++ const readHeadRef = (): Promise<string> =>+ git+ .raw(['symbolic-ref', '--quiet', 'HEAD'])+ .then((ref) => ref.trim())+ .catch(() => '');+ const targetHeadRef = `refs/heads/${branch}`;+ const headRefBefore = await readHeadRef();+ let createdBranch = false;+ try {+ if (!branchIsLocal) {+ await git.raw(['branch', '--no-track', branch, target]);+ createdBranch = true;+ await git.raw(['branch', `--set-upstream-to=refs/remotes/origin/${branch}`, branch]);+ }await git.raw(['checkout', branch]);return { ok: true };} catch (err) {+ if (headRefBefore !== targetHeadRef && (await readHeadRef()) === targetHeadRef) {+ log.warn(+ { branch, target, err },+ `action=checkout-hook-failed branch=${branch} error=${truncateError(err)}`,+ );+ return { ok: true };+ }+ if (createdBranch) {+ await git.raw(['branch', '-D', branch]).catch((cleanupErr: unknown) => {+ log.warn(+ { branch, target, err: cleanupErr },+ `action=checkout-cleanup-failed branch=${branch}`,+ );+ });+ }const heldElsewhere = isBranchInOtherWorktreeError(err);if (heldElsewhere.held) {log.warn(diff --git a/packages/server/src/incoming-symlink-guard.ts b/packages/server/src/incoming-symlink-guard.tsnew file mode 100644index 000000000..e326f914d--- /dev/null+++ b/packages/server/src/incoming-symlink-guard.ts@@ -0,0 +1,766 @@+import { spawn } from 'node:child_process';+import { lstat, readlink } from 'node:fs/promises';+import { join } from 'node:path';+import {+ DESKTOP_PRODUCTS,+ OK_MACHINE_LOCAL_ROOT_DIRS,+ OK_MACHINE_LOCAL_ROOT_FILES,+ OK_USER_HOME_CREDENTIAL_FILES,+} from '@inkeep/open-knowledge-core';+import type { SimpleGit } from 'simple-git';+import { isSecretBearingFile, pathHasSecretBearingDirSegment } from './content-filter.ts';+import { compareSemver, parseGitVersion } from './git-preflight.ts';+import { errnoCode } from './http/handler-utils.ts';++export const SYMLINK_MERGE_MIN_GIT_VERSION = '2.38.0';+export const SYMLINK_MERGE_MIN_GIT_LABEL = '2.38';++const GIT_SYMLINK_MODE = '120000';+const EMPTY_TREE_SHA1 = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';+const EMPTY_TREE_SHA256 = '6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321';+const REPORTED_PATH_LIMIT = 5;+const MAX_SYMLINK_TARGET_BYTES = 4096;+const MAX_WALK_STEPS = 256;+const MAX_SYMLINK_HOPS = 40;+const MAX_INSPECTION_STEPS = 20_000;+const BLOB_READ_TIMEOUT_MS = 60_000;+const HFS_IGNORABLE_CHARACTERS = /[\u200C-\u200F\u202A-\u202E\u206A-\u206F\uFEFF]/gu;+const INVISIBLE_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu;+const REPOSITORY_SCOPED_GIT_VARIABLES = [+ 'GIT_DIR',+ 'GIT_WORK_TREE',+ 'GIT_COMMON_DIR',+ 'GIT_INDEX_FILE',+ 'GIT_OBJECT_DIRECTORY',+ 'GIT_ALTERNATE_OBJECT_DIRECTORIES',+ 'GIT_NAMESPACE',+];++function foldOnce(name: string): string {+ return name+ .replace(HFS_IGNORABLE_CHARACTERS, '')+ .normalize('NFC')+ .toUpperCase()+ .toLowerCase()+ .normalize('NFC');+}++function foldName(name: string): string {+ let folded = foldOnce(name);+ for (let round = 0; round < 4; round++) {+ const next = foldOnce(folded);+ if (next === folded) break;+ folded = next;+ }+ return folded.replace(/[. ]+$/u, (trailing, offset: number) => (offset === 0 ? trailing : ''));+}++function foldPath(path: string): string {+ return path.split('/').map(foldName).join('/');+}++const CONFIG_DIR_NAMES: ReadonlySet<string> = new Set(+ [+ '.ok',+ '.open-knowledge',+ '.openknowledge',+ ...Object.values(DESKTOP_PRODUCTS).map(({ userHomeDirName }) => userHomeDirName),+ ].map(foldName),+);+const MACHINE_LOCAL_NAMES: ReadonlySet<string> = new Set(+ [+ ...OK_MACHINE_LOCAL_ROOT_DIRS,+ ...OK_MACHINE_LOCAL_ROOT_FILES,+ ...OK_USER_HOME_CREDENTIAL_FILES,+ ].map(foldName),+);++function shortNamePattern(longNames: Iterable<string>): RegExp {+ const alternatives = new Set<string>();+ for (const name of longNames) {+ const basis = name.replace(/^\.+/u, '');+ if (!/^[a-z0-9-]+$/u.test(basis)) {+ throw new Error(`cannot derive 8.3 short names for config dir "${name}"`);+ }+ if (basis.length <= 2) {+ alternatives.add(`${basis}[0-9a-f]{4}`);+ } else {+ alternatives.add(basis.slice(0, 6));+ alternatives.add(`${basis.slice(0, 2)}[0-9a-f]{4}`);+ }+ }+ return new RegExp(`^(?:${[...alternatives].join('|')})~\\d+$`, 'u');+}++const CONFIG_DIR_SHORT_NAME = shortNamePattern(CONFIG_DIR_NAMES);++function isShortNameAlias(folded: string): boolean {+ return /^[^.~]{1,7}~\d{1,7}(?:\.[^.]{1,3})?$/u.test(folded);+}++function isGitDirName(folded: string): boolean {+ return folded === '.git' || /^git~\d+$/u.test(folded);+}++function isConfigDirName(folded: string): boolean {+ return CONFIG_DIR_NAMES.has(folded) || CONFIG_DIR_SHORT_NAME.test(folded);+}++export type UnsafeSymlinkReason =+ | 'outside-repository'+ | 'repository-root'+ | 'private-state'+ | 'secret-file'+ | 'inside-private-state'+ | 'requires-newer-git'+ | 'unverifiable-target';++export interface UnsafeIncomingSymlink {+ path: string;+ reason: UnsafeSymlinkReason;+}++interface TreeSymlink {+ path: string;+ folded: string;+ blob: string;+ size: number;+}++interface TreeListing {+ links: TreeSymlink[];+ spellings: Map<string, Set<string>>;+}++interface Inspection {+ links: TreeSymlink[];+ spellings: ReadonlyMap<string, ReadonlySet<string>>;+ changed: ReadonlySet<string>;+ changedPaths: readonly string[];+ candidates: ConflictCandidate[];+ conflicted: ConflictedPath[];+ refused: UnsafeIncomingSymlink[];+ targets: ReadonlyMap<string, string>;+}++type Resolution = { kind: 'plain' } | { kind: 'link'; target: string } | { kind: 'unverifiable' };++interface WalkOutcome {+ reason: UnsafeSymlinkReason | null;+ crossed: ReadonlySet<string>;+ complete: boolean;+}++function touchesPrivateState(folded: readonly string[]): boolean {+ return folded.some(+ (segment, index) =>+ isGitDirName(segment) ||+ (isConfigDirName(segment) &&+ (index === folded.length - 1 || MACHINE_LOCAL_NAMES.has(folded[index + 1] ?? ''))),+ );+}++function isUnverifiableTarget(target: string): boolean {+ return (+ target === '' ||+ target.includes('\0') ||+ target.includes('\\') ||+ target.includes(':') ||+ Buffer.byteLength(target, 'utf-8') > MAX_SYMLINK_TARGET_BYTES+ );+}++async function walkLink(+ linkPath: string,+ target: string,+ resolve: (folded: string, raw: string) => Promise<Resolution>,+ budget: { steps: number },+): Promise<WalkOutcome> {+ const crossed = new Set<string>();+ const outcome = (reason: UnsafeSymlinkReason | null): WalkOutcome => ({+ reason,+ crossed,+ complete: true,+ });+ const cut = (): WalkOutcome => ({ reason: 'unverifiable-target', crossed, complete: false });+ if (isUnverifiableTarget(target)) return outcome('unverifiable-target');+ if (target.startsWith('/')) return outcome('outside-repository');+ const pending = [...linkPath.split('/').slice(0, -1), ...target.split('/')];+ const raw: string[] = [];+ const folded: string[] = [];+ let steps = 0;+ let hops = 0;+ while (pending.length > 0) {+ const step = pending.shift() ?? '';+ steps += 1;+ budget.steps -= 1;+ if (steps > MAX_WALK_STEPS || budget.steps < 0) return cut();+ if (step === '' || step === '.') continue;+ if (step === '..') {+ if (raw.length === 0) return outcome('outside-repository');+ raw.pop();+ folded.pop();+ continue;+ }+ raw.push(step);+ const segment = foldName(step);+ folded.push(segment);+ if (isShortNameAlias(segment)) {+ return touchesPrivateState(folded)+ ? { reason: 'private-state', crossed, complete: false }+ : cut();+ }+ const visited = folded.join('/');+ crossed.add(visited);+ const resolution = await resolve(visited, raw.join('/'));+ if (resolution.kind === 'unverifiable') return cut();+ if (resolution.kind === 'link') {+ hops += 1;+ if (hops > MAX_SYMLINK_HOPS || isUnverifiableTarget(resolution.target)) return cut();+ if (resolution.target.startsWith('/')) return outcome('outside-repository');+ raw.pop();+ folded.pop();+ pending.unshift(...resolution.target.split('/'));+ }+ }+ if (folded.length === 0) return outcome('repository-root');+ if (touchesPrivateState(folded)) return outcome('private-state');+ const resolved = folded.join('/');+ if (isSecretBearingFile(resolved) || pathHasSecretBearingDirSegment(resolved)) {+ return outcome('secret-file');+ }+ return outcome(null);+}++function addSpelling(spellings: Map<string, Set<string>>, path: string): void {+ const segments = path.split('/');+ for (let length = 1; length <= segments.length; length++) {+ const prefix = segments.slice(0, length).join('/');+ const key = foldPath(prefix);+ const known = spellings.get(key);+ if (known === undefined) spellings.set(key, new Set([prefix]));+ else known.add(prefix);+ }+}++async function listTree(git: SimpleGit, treeish: string): Promise<TreeListing> {+ const raw = await git.raw(['ls-tree', '-r', '-z', '-l', '--full-tree', treeish]);+ const links: TreeSymlink[] = [];+ const spellings = new Map<string, Set<string>>();+ for (const record of raw.split('\0')) {+ if (record === '') continue;+ const tab = record.indexOf('\t');+ const [mode, , blob, size] = record.slice(0, Math.max(tab, 0)).trim().split(/\s+/u);+ if (tab < 0 || mode === undefined || blob === undefined || size === undefined) {+ throw new Error('unparseable git ls-tree record while inspecting incoming symlinks');+ }+ const path = record.slice(tab + 1);+ addSpelling(spellings, path);+ if (mode === GIT_SYMLINK_MODE) {+ links.push({ path, folded: foldPath(path), blob, size: Number(size) });+ }+ }+ return { links, spellings };+}++async function changedLinkPaths(+ git: SimpleGit,+ from: string,+ to: string,+): Promise<Map<string, string>> {+ const raw = await git.raw([+ 'diff-tree',+ '-r',+ '-z',+ '--raw',+ '--no-renames',+ '--no-abbrev',+ from,+ to,+ ]);+ const records = raw.split('\0');+ const changed = new Map<string, string>();+ for (let i = 0; i + 1 < records.length; i += 2) {+ const meta = records[i] ?? '';+ const path = records[i + 1] ?? '';+ const [srcMode, dstMode] = meta.replace(/^\n?:/u, '').split(' ');+ if (!meta.includes(':') || dstMode === undefined || path === '') {+ throw new Error('unparseable git diff-tree record while inspecting incoming symlinks');+ }+ if (srcMode === GIT_SYMLINK_MODE || dstMode === GIT_SYMLINK_MODE) {+ changed.set(foldPath(path), path);+ }+ }+ return changed;+}++function blobReadEnv(env: NodeJS.ProcessEnv | undefined): NodeJS.ProcessEnv {+ const next: NodeJS.ProcessEnv = { ...(env ?? process.env) };+ for (const name of REPOSITORY_SCOPED_GIT_VARIABLES) delete next[name];+ next.GIT_TERMINAL_PROMPT = '0';+ next.GIT_NO_LAZY_FETCH = '1';+ return next;+}++class IncomingBlobReadError extends Error {+ readonly failure: string;+ readonly detail: unknown;+ readonly stderr: string;++ constructor(failure: string, detail: unknown, stderr: string) {+ super(`could not read incoming symlink targets from git (${failure})`);+ this.name = 'IncomingBlobReadError';+ this.failure = failure;+ this.detail = detail;+ this.stderr = stderr;+ }+}++function readBlobs(+ repoRoot: string,+ links: readonly Pick<TreeSymlink, 'blob' | 'size'>[],+ env: NodeJS.ProcessEnv | undefined,+): Promise<Map<string, string>> {+ const wanted = [+ ...new Set(+ links+ .filter((link) => Number.isFinite(link.size) && link.size <= MAX_SYMLINK_TARGET_BYTES)+ .map((link) => link.blob),+ ),+ ];+ if (wanted.length === 0) return Promise.resolve(new Map());+ return new Promise((resolve, reject) => {+ let settled = false;+ const stderr: Buffer[] = [];+ let stderrBytes = 0;+ const settle = (result: Map<string, string> | { failure: string; detail?: unknown }) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ if (result instanceof Map) {+ resolve(result);+ return;+ }+ reject(+ new IncomingBlobReadError(+ result.failure,+ result.detail,+ Buffer.concat(stderr).toString('utf-8'),+ ),+ );+ };+ const child = spawn('git', ['cat-file', '--batch'], {+ cwd: repoRoot,+ env: blobReadEnv(env),+ stdio: ['pipe', 'pipe', 'pipe'],+ windowsHide: true,+ });+ const timer = setTimeout(() => {+ child.kill('SIGKILL');+ settle({ failure: 'timeout' });+ }, BLOB_READ_TIMEOUT_MS);+ const chunks: Buffer[] = [];+ child.stdout.on('data', (chunk: Buffer) => chunks.push(chunk));+ child.stderr.on('data', (chunk: Buffer) => {+ if (stderrBytes >= 4096) return;+ stderr.push(chunk);+ stderrBytes += chunk.length;+ });+ child.stdin.on('error', (err) => settle({ failure: 'stdin', detail: errnoCode(err) }));+ child.on('error', (err) => settle({ failure: 'spawn', detail: errnoCode(err) }));+ child.on('close', (code, signal) => {+ if (code !== 0) {+ settle({ failure: 'exit', detail: signal ?? code });+ return;+ }+ const out = Buffer.concat(chunks);+ const blobs = new Map<string, string>();+ let offset = 0;+ for (const blob of wanted) {+ const headerEnd = out.indexOf(0x0a, offset);+ const [sha, type, size] = out.subarray(offset, headerEnd).toString('utf-8').split(' ');+ const length = Number(size);+ if (headerEnd < 0 || sha !== blob || type !== 'blob' || !Number.isFinite(length)) {+ settle({ failure: 'output' });+ return;+ }+ blobs.set(blob, out.subarray(headerEnd + 1, headerEnd + 1 + length).toString('utf-8'));+ offset = headerEnd + 1 + length + 1;+ }+ settle(blobs);+ });+ child.stdin.end(`${wanted.join('\n')}\n`);+ });+}++async function emptyTree(git: SimpleGit): Promise<string> {+ const format = (await git.raw(['rev-parse', '--show-object-format'])).trim();+ return format === 'sha256' ? EMPTY_TREE_SHA256 : EMPTY_TREE_SHA1;+}++async function isAncestor(git: SimpleGit, ancestor: string, descendant: string): Promise<boolean> {+ const base = (await git.raw(['merge-base', ancestor, descendant])).trim();+ return base === ancestor;+}++interface ConflictCandidate {+ path: string;+ stage: string;+ blob: string;+ size: number;+}++interface ConflictedPath {+ path: string;+ folded: string;+}++interface MergeResult {+ tree: string;+ candidates: ConflictCandidate[];+ conflicted: ConflictedPath[];+}++async function supportsMergeTreeWriteTree(git: SimpleGit): Promise<boolean> {+ const version = parseGitVersion(await git.raw(['version']));+ return version === null || compareSemver(version, SYMLINK_MERGE_MIN_GIT_VERSION) >= 0;+}++async function mergeResultTree(+ git: SimpleGit,+ head: string,+ incoming: string,+): Promise<MergeResult> {+ const raw = await git.raw(['merge-tree', '--write-tree', '-z', '--no-messages', head, incoming]);+ const [tree = '', ...entries] = raw.split('\0');+ if (!/^[0-9a-f]{40,64}$/u.test(tree)) {+ throw new Error('unexpected git merge-tree output while inspecting incoming symlinks');+ }+ const candidates: ConflictCandidate[] = [];+ const stagesByPath = new Map<string, Map<string, { mode: string; blob: string }>>();+ for (const entry of entries) {+ if (entry === '') continue;+ const tab = entry.indexOf('\t');+ const [mode, blob, stage] = entry.slice(0, Math.max(tab, 0)).split(' ');+ const path = entry.slice(tab + 1);+ if (+ tab < 0 ||+ mode === undefined ||+ blob === undefined ||+ stage === undefined ||+ !/^[123]$/u.test(stage) ||+ path === ''+ ) {+ throw new Error('unparseable git merge-tree record while inspecting incoming symlinks');+ }+ const stages = stagesByPath.get(path) ?? new Map<string, { mode: string; blob: string }>();+ stages.set(stage, { mode, blob });+ stagesByPath.set(path, stages);+ if (mode !== GIT_SYMLINK_MODE || stage !== '3') continue;+ const size = Number((await git.raw(['cat-file', '-s', blob])).trim());+ candidates.push({ path, stage, blob, size });+ }+ const conflicted: ConflictedPath[] = [];+ for (const [path, stages] of stagesByPath) {+ if (![...stages.values()].some(({ mode }) => mode === GIT_SYMLINK_MODE)) continue;+ conflicted.push({ path, folded: foldPath(path) });+ }+ return { tree, candidates, conflicted };+}++let cachedInspection: { key: string; inspection: Inspection | null } | undefined;++async function inspect(+ git: SimpleGit,+ repoRoot: string,+ head: string | null,+ incoming: string,+ landing: IncomingLanding,+ env: NodeJS.ProcessEnv | undefined,+): Promise<Inspection | null> {+ const key = JSON.stringify([repoRoot, head, incoming, landing]);+ if (cachedInspection?.key === key) return cachedInspection.inspection;+ const from = head ?? (await emptyTree(git));+ let result = incoming;+ let candidates: ConflictCandidate[] = [];+ let conflicted: ConflictedPath[] = [];+ if (landing === 'merge' && head !== null && !(await isAncestor(git, head, incoming))) {+ if (!(await supportsMergeTreeWriteTree(git))) {+ const bases = (await git.raw(['merge-base', '--all', head, incoming]))+ .split('\n')+ .map((line) => line.trim())+ .filter((line) => line !== '');+ const changed = new Map<string, string>();+ for (const base of bases.length > 0 ? bases : [head]) {+ for (const [folded, path] of await changedLinkPaths(git, base, incoming)) {+ changed.set(folded, path);+ }+ }+ if (changed.size === 0) return null;+ return {+ links: [],+ spellings: new Map(),+ changed: new Set(changed.keys()),+ changedPaths: [...changed.values()],+ candidates: [],+ conflicted: [],+ refused: [...changed.values()].map((path) => ({+ path,+ reason: 'requires-newer-git' as const,+ })),+ targets: new Map(),+ };+ }+ const merge = await mergeResultTree(git, head, incoming);+ result = merge.tree;+ candidates = merge.candidates;+ conflicted = merge.conflicted;+ }+ const changed = await changedLinkPaths(git, from, result);+ for (const entry of conflicted) changed.set(entry.folded, entry.path);+ let inspection: Inspection | null = null;+ if (changed.size > 0 || candidates.length > 0) {+ const listing = await listTree(git, result);+ inspection = {+ links: listing.links,+ spellings: listing.spellings,+ changed: new Set(changed.keys()),+ changedPaths: [...changed.values()],+ candidates,+ conflicted,+ refused: [],+ targets: await readBlobs(repoRoot, [...listing.links, ...candidates], env),+ };+ }+ cachedInspection = { key, inspection };+ return inspection;+}++async function findUnsafeIncomingSymlinks(+ git: SimpleGit,+ incoming: string,+ landing: IncomingLanding,+ env: NodeJS.ProcessEnv | undefined,+): Promise<UnsafeIncomingSymlink[]> {+ const repoRoot = (await git.raw(['rev-parse', '--show-toplevel'])).trim();+ if (repoRoot === '') throw new Error('could not resolve the repository root');+ const head = (await git.raw(['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'])).trim();+ const inspection = await inspect(+ git,+ repoRoot,+ head === '' ? null : head,+ incoming,+ landing,+ env,+ );+ if (inspection === null) return [];+ const { spellings, changed, candidates, targets } = inspection;+ if (inspection.refused.length > 0) return inspection.refused;++ const { links } = inspection;+ const conflictedFolds = new Set(inspection.conflicted.map(({ folded }) => folded));+ const relocatable = [+ ...[...conflictedFolds].map((folded) => folded.replace(/~[^/]*$/u, '')),+ ...changed,+ ];+ const crossesConflict = (folded: string): boolean =>+ conflictedFolds.has(folded) || relocatable.some((path) => folded.startsWith(`${path}~`));+ const linksByFold = new Map<string, TreeSymlink[]>();+ for (const link of links) {+ const known = linksByFold.get(link.folded);+ if (known === undefined) linksByFold.set(link.folded, [link]);+ else known.push(link);+ }+ const targetOfBlob = (blob: string): string => targets.get(blob) ?? '\0';++ const memo = new Map<string, Promise<Resolution>>();+ const resolveUncached = async (folded: string, rawPath: string): Promise<Resolution> => {+ if (crossesConflict(folded)) return { kind: 'unverifiable' };+ const known = spellings.get(folded);+ const foldedLinks = linksByFold.get(folded);+ if (foldedLinks !== undefined) {+ if (foldedLinks.length > 1 || (known !== undefined && known.size > 1)) {+ return { kind: 'unverifiable' };+ }+ const [link] = foldedLinks;+ return link === undefined+ ? { kind: 'unverifiable' }+ : { kind: 'link', target: targetOfBlob(link.blob) };+ }+ if (known !== undefined) return { kind: 'plain' };+ const onDisk = join(repoRoot, rawPath);+ try {+ if (!(await lstat(onDisk)).isSymbolicLink()) return { kind: 'plain' };+ return { kind: 'link', target: await readlink(onDisk) };+ } catch (err) {+ const code = errnoCode(err);+ return code === 'ENOENT' || code === 'ENOTDIR' ? { kind: 'plain' } : { kind: 'unverifiable' };+ }+ };+ const resolve = (folded: string, rawPath: string): Promise<Resolution> => {+ const key = `${folded}\0${rawPath}`;+ let pending = memo.get(key);+ if (pending === undefined) {+ pending = resolveUncached(folded, rawPath);+ memo.set(key, pending);+ }+ return pending;+ };+ const budget = { steps: MAX_INSPECTION_STEPS };++ const unsafe: UnsafeIncomingSymlink[] = [];+ const refusedPaths = new Set<string>();+ const refuse = (path: string, reason: UnsafeSymlinkReason): void => {+ if (refusedPaths.has(path)) return;+ refusedPaths.add(path);+ unsafe.push({ path, reason });+ };+ for (const candidate of candidates) {+ const { reason } = await walkLink(+ candidate.path,+ targetOfBlob(candidate.blob),+ resolve,+ budget,+ );+ if (reason !== null) refuse(candidate.path, reason);+ }+ for (const link of links) {+ const isChanged = changed.has(link.folded);+ if (isChanged && touchesPrivateState(link.folded.split('/'))) {+ refuse(link.path, 'inside-private-state');+ continue;+ }+ const { reason, crossed, complete } = await walkLink(+ link.path,+ targetOfBlob(link.blob),+ resolve,+ budget,+ );+ if (reason === null) continue;+ if (isChanged || !complete || [...crossed].some((visited) => changed.has(visited))) {+ refuse(link.path, reason);+ }+ }+ if (budget.steps < 0) {+ for (const path of [...inspection.changedPaths, ...candidates.map(({ path }) => path)]) {+ refuse(path, 'unverifiable-target');+ }+ }+ return unsafe;+}++export async function resolveIncomingCommit(git: SimpleGit, ref: string): Promise<string> {+ const commit = (await git.raw(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`])).trim();+ if (!/^[0-9a-f]{40,64}$/u.test(commit)) {+ throw new Error('cannot resolve the incoming commit');+ }+ return commit;+}++function describeSymlinkReason(reason: UnsafeSymlinkReason): string {+ switch (reason) {+ case 'outside-repository':+ return 'points outside the repository';+ case 'repository-root':+ return 'points at the repository root';+ case 'private-state':+ return 'points into private .git or OpenKnowledge state';+ case 'secret-file':+ return 'points at a file that may hold secrets, such as .env or a key';+ case 'inside-private-state':+ return 'is placed inside private .git or OpenKnowledge state';+ case 'requires-newer-git':+ return `needs Git ${SYMLINK_MERGE_MIN_GIT_LABEL} or newer to check during a merge`;+ case 'unverifiable-target':+ return 'has a target that cannot be checked';+ default: {+ const exhaustive: never = reason;+ return exhaustive;+ }+ }+}++export function escapePathForDisplay(path: string): string {+ return JSON.stringify(path)+ .slice(1, -1)+ .replace(INVISIBLE_CHARACTERS, (character) =>+ Array.from(+ { length: character.length },+ (_, index) => `\\u${character.charCodeAt(index).toString(16).padStart(4, '0')}`,+ ).join(''),+ );+}++export class UnsafeIncomingSymlinkError extends Error {+ readonly unsafe: readonly UnsafeIncomingSymlink[];++ constructor(unsafe: readonly UnsafeIncomingSymlink[]) {+ super('refusing to pull: incoming symlinks are unsafe to check out');+ this.name = 'UnsafeIncomingSymlinkError';+ this.unsafe = unsafe;+ }++ describeLinks(): string {+ const shown = this.unsafe+ .slice(0, REPORTED_PATH_LIMIT)+ .map(+ ({ path, reason }) => `"${escapePathForDisplay(path)}" (${describeSymlinkReason(reason)})`,+ );+ const more =+ this.unsafe.length > REPORTED_PATH_LIMIT+ ? `, and ${this.unsafe.length - REPORTED_PATH_LIMIT} more`+ : '';+ return `${shown.join(', ')}${more}`;+ }+}++export type IncomingLanding = 'merge' | 'checkout';++export async function assertIncomingSymlinksSafe(+ git: SimpleGit,+ incoming: string,+ landing: IncomingLanding,+ env?: NodeJS.ProcessEnv,+): Promise<void> {+ const commit = await resolveIncomingCommit(git, incoming);+ const unsafe = await findUnsafeIncomingSymlinks(git, commit, landing, env);+ if (unsafe.length > 0) throw new UnsafeIncomingSymlinkError(unsafe);+}++export class IncomingRefMovedError extends Error {+ readonly ref: string;++ constructor(ref: string) {+ super('the incoming branch moved after its incoming symlinks were inspected; pull again');+ this.name = 'IncomingRefMovedError';+ this.ref = ref;+ }+}++export class IncomingRefShadowedError extends Error {+ readonly shadowedName: string;++ constructor(shadowedName: string) {+ super(+ 'another ref with the incoming branch name, such as a tag, shadows it, so sync will not merge it until that ref is deleted here and on the remote',+ );+ this.name = 'IncomingRefShadowedError';+ this.shadowedName = shadowedName;+ }+}++async function resolvedCommitOrEmpty(git: SimpleGit, name: string): Promise<string> {+ return (await git.raw(['rev-parse', '--verify', '--quiet', `${name}^{commit}`])).trim();+}++export async function assertMergeNameResolvesTo(+ git: SimpleGit,+ target: { name: string; trackingRef: string; commit: string },+): Promise<void> {+ if ((await resolvedCommitOrEmpty(git, target.trackingRef)) !== target.commit) {+ throw new IncomingRefMovedError(target.trackingRef);+ }+ if ((await resolvedCommitOrEmpty(git, target.name)) !== target.commit) {+ throw new IncomingRefShadowedError(target.name);+ }+}diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex f93aa971f..065dc6fad 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -278,6 +278,15 @@ export {type CollabClientCounter,type IdleShutdownHandle,} from './idle-shutdown.ts';+export {+ assertIncomingSymlinksSafe,+ assertMergeNameResolvesTo,+ SYMLINK_MERGE_MIN_GIT_LABEL,+ SYMLINK_MERGE_MIN_GIT_VERSION,+ type UnsafeIncomingSymlink,+ UnsafeIncomingSymlinkError,+ type UnsafeSymlinkReason,+} from './incoming-symlink-guard.ts';export {buildIngressPolicy,ExposureConsentError,diff --git a/packages/server/src/sync-engine.incoming-symlinks.test.ts b/packages/server/src/sync-engine.incoming-symlinks.test.tsnew file mode 100644index 000000000..cd5c51974--- /dev/null+++ b/packages/server/src/sync-engine.incoming-symlinks.test.ts@@ -0,0 +1,1749 @@+import { execFileSync } from 'node:child_process';+import {+ existsSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readlinkSync,+ rmSync,+ symlinkSync,+ unlinkSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { LOCAL_DIR } from '@inkeep/open-knowledge-core';+import simpleGit, { type SimpleGit } from 'simple-git';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { createTestConflictAuthority } from './conflict-authority.test-helper.ts';+import { classifyGitError } from './error-classification.ts';+import { runCheckoutFlow } from './git-checkout.ts';+import {+ assertIncomingSymlinksSafe,+ resolveIncomingCommit,+ UnsafeIncomingSymlinkError,+} from './incoming-symlink-guard.ts';+import { getLogger } from './logger.ts';+import { SyncEngine } from './sync-engine.ts';++const stubContentFilter = {+ isExcluded: (_path: string) => false,+ isDirExcluded: (_path: string) => false,+};++let tmpDir = '';+let projectDir = '';+let sisterDir = '';+let sister: SimpleGit;+let project: SimpleGit;++beforeEach(async () => {+ tmpDir = mkdtempSync(join(tmpdir(), 'sync-engine-incoming-symlinks-'));+ projectDir = join(tmpDir, 'project');+ sisterDir = join(tmpDir, 'sister');+ const bareDir = join(tmpDir, 'bare.git');+ mkdirSync(bareDir, { recursive: true });+ await simpleGit(bareDir).init(true);+ await simpleGit(bareDir).raw('symbolic-ref', 'HEAD', 'refs/heads/main');++ mkdirSync(sisterDir, { recursive: true });+ sister = simpleGit(sisterDir);+ await sister.init(['--initial-branch=main']);+ await sister.raw('config', 'user.name', 'Sister');+ await sister.raw('config', 'user.email', '[email protected]');+ mkdirSync(join(sisterDir, 'notes'), { recursive: true });+ writeFileSync(join(sisterDir, 'notes', 'real.md'), '# real\n', 'utf-8');+ await sister.add('.');+ await sister.commit('base');+ await sister.addRemote('origin', bareDir);+ await sister.push('origin', 'main');++ await simpleGit(tmpDir).clone(bareDir, projectDir);+ mkdirSync(join(projectDir, '.ok', LOCAL_DIR), { recursive: true });+ writeFileSync(join(projectDir, '.ok', LOCAL_DIR, 'principal.json'), '{"secret":1}\n', 'utf-8');+ project = simpleGit(projectDir);+ await project.raw('config', 'user.name', 'Project');+ await project.raw('config', 'user.email', '[email protected]');+});++afterEach(() => {+ rmSync(tmpDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+});++async function pushSymlinks(links: Record<string, string>, remoteBranch = 'main'): Promise<void> {+ for (const [path, target] of Object.entries(links)) {+ const targetFile = join(tmpDir, 'link-target.txt');+ writeFileSync(targetFile, target, 'utf-8');+ const blob = (await sister.raw('hash-object', '-w', targetFile)).trim();+ await sister.raw('update-index', '--add', '--cacheinfo', `120000,${blob},${path}`);+ }+ await sister.commit('add symlinks');+ await sister.push('origin', `HEAD:${remoteBranch}`);+}++async function pushRemoval(paths: string[]): Promise<void> {+ await sister.raw('rm', '-r', '--cached', '--quiet', ...paths);+ await sister.commit('remove paths');+ await sister.push('origin', 'HEAD:main');+}++function makeEngine(+ options: {+ setBatchInProgress?: (value: boolean) => void;+ onAutoDisable?: (reason: 'protected-branch') => void;+ syncEnabled?: boolean;+ } = {},+) {+ return new SyncEngine({+ conflicts: createTestConflictAuthority(projectDir),+ projectDir,+ contentDir: projectDir,+ contentFilter: stubContentFilter,+ syncEnabled: true,+ ...options,+ });+}++function captureSyncLogs(): {+ entries: Array<{ level: 'info' | 'warn'; data: Record<string, unknown>; msg: string }>;+ restore: () => void;+} {+ const entries: Array<{ level: 'info' | 'warn'; data: Record<string, unknown>; msg: string }> = [];+ const logger = getLogger('sync-engine');+ const record =+ (level: 'info' | 'warn') =>+ (data: unknown, msg?: string): void => {+ entries.push({ level, data: (data ?? {}) as Record<string, unknown>, msg: msg ?? '' });+ };+ const infoSpy = vi.spyOn(logger, 'info').mockImplementation(record('info') as never);+ const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(record('warn') as never);+ return {+ entries,+ restore: () => {+ infoSpy.mockRestore();+ warnSpy.mockRestore();+ },+ };+}++async function commitLocally(relPath: string, content: string): Promise<void> {+ writeFileSync(join(projectDir, relPath), content, 'utf-8');+ await project.add(relPath);+ await project.commit(`local ${relPath}`);+}++function existsAsEntry(relPath: string): boolean {+ try {+ lstatSync(join(projectDir, relPath));+ return true;+ } catch {+ return false;+ }+}++async function headSha(): Promise<string> {+ return (await project.revparse(['HEAD'])).trim();+}++function isAncestorOfHead(commit: string): boolean {+ try {+ execFileSync('git', ['merge-base', '--is-ancestor', commit, 'HEAD'], { cwd: projectDir });+ return true;+ } catch {+ return false;+ }+}++async function pullWithEngine(): Promise<void> {+ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce()).toBe('succeeded');+ } finally {+ await engine.destroy();+ }+}++async function expectRefusedPull(linkPaths: string[]): Promise<string[] | undefined> {+ const before = await headSha();+ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce()).toBe('refused');+ for (const linkPath of linkPaths) expect(existsAsEntry(linkPath)).toBe(false);+ expect(await headSha()).toBe(before);+ const status = engine.getStatus();+ expect(status.pausedReason).toBe('unsafe-incoming-symlinks');+ return status.refusedSymlinkPaths;+ } finally {+ await engine.destroy();+ }+}++describe('SyncEngine refuses incoming symlinks into private state or outside the repository', () => {+ test.each([+ ['explicit pull (fast-forward)', 'explicit'],+ ['background sync (merge)', 'sync'],+ ] as const)('%s keeps an OK local-state symlink off disk', async (_label, invocation) => {+ await pushSymlinks({ 'notes/leak.md': '../.ok/local/principal.json' });+ const before = await headSha();++ const engine = makeEngine();+ try {+ await engine.start();+ const outcome = await engine.pullOnce(invocation);++ expect(outcome).toBe('refused');+ expect(existsAsEntry('notes/leak.md')).toBe(false);+ expect(await headSha()).toBe(before);+ expect(engine.getStatus().pausedReason).toBe('unsafe-incoming-symlinks');+ } finally {+ await engine.destroy();+ }+ });++ test.each([+ ['the git dir', 'notes/leak-git.md', '../.git/config'],+ ['a case variant of the OK dir', 'notes/leak-upper.md', '../.OK/local/principal.json'],+ ['the renamed config dir', 'notes/leak-renamed.md', '../.open-knowledge/local/server.lock'],+ ['the OK dir itself', 'notes/ok-dir', '../.ok'],+ ['a parent directory', 'notes/leak-up.md', '../../outside.md'],+ ['an absolute path', 'notes/leak-abs.md', '/etc/hosts'],+ ['a target cut short by a NUL byte', 'notes/nul.md', '../.git/config\0/../../notes/x'],+ ['a target longer than any path', 'notes/long.md', `${'a/'.repeat(2100)}real.md`],+ ['a backslash-separated target', 'notes/bs.md', '..\\.git\\config'],+ ['a trailing-dot spelling of the git dir', 'notes/dot.md', '../.git./config'],+ ['an 8.3 short name of the git dir', 'notes/short.md', '../GIT~1/config'],+ ['an 8.3 short name of the OK dir', 'notes/short-ok.md', '../OK3A7F~1/local/principal.json'],+ [+ 'an 8.3 short name of the renamed config dir',+ 'notes/short-renamed.md',+ '../OPEN-K~1/local/server.lock',+ ],+ [+ 'an 8.3 short name of the dotless config dir',+ 'notes/short-dotless.md',+ '../OPENKN~1/local/server.lock',+ ],+ [+ 'a hashed 8.3 short name of a long config dir',+ 'notes/short-hashed.md',+ '../OPB2C4~5/local/server.lock',+ ],+ ['the dotless config dir', 'notes/dotless.md', '../.openknowledge/local/state.json'],+ ['a nested git dir', 'notes/nested.md', 'sub/.git/config'],+ ['an HFS-ignorable spelling of the git dir', 'notes/zw.md', '../.g\u200cit/config'],+ ["the user home's credential file", 'notes/auth.md', '../.ok/auth.yml'],+ ["the beta product's credential file", 'notes/auth-beta.md', '../.ok-beta/auth.yml'],+ ["the user home's secrets file", 'notes/secrets.md', '../.ok/secrets.yml'],+ ["the beta product's secrets file", 'notes/secrets-beta.md', '../.ok-beta/secrets.yml'],+ [+ "an 8.3 short name of the beta product's user-home dir",+ 'notes/short-beta.md',+ '../OK-BET~1/auth.yml',+ ],+ ['a Windows drive-letter target', 'notes/drive.md', 'Q: real.md'],+ ['an 8.3 short name of a credentials file', 'notes/short-cred.md', '../GIT-CR~1'],+ ['an 8.3 short name of an env file', 'notes/short-env.md', '../ENV~1'],+ ['an 8.3 short name inside a secret folder', 'notes/short-aws.md', '../AWS~1/CREDEN~1'],+ ['an 8.3 short name removed again by ..', 'notes/short-up.md', 'LINK~1/../real.md'],+ ['an 8.3 short-name folder inside the OK dir', '.ok/WORKTR~1/x', '../../notes/real.md'],+ ['an NTFS data-stream spelling of a credential file', 'notes/ads.md', '../.ok/auth.yml::$DATA'],+ [+ 'an NTFS index-stream spelling of a config dir',+ 'notes/ads-dir.md',+ '../.ok-beta::$INDEX_ALLOCATION/secrets.yml',+ ],+ [+ 'an NTFS index-stream spelling of the git dir',+ 'notes/ads-git.md',+ '../.git::$INDEX_ALLOCATION/config',+ ],+ ['an env file', 'notes/env.md', '../.env'],+ ['a private key', 'notes/key.md', '../id_ed25519'],+ ['a secret-bearing folder', 'notes/aws.md', '../.aws/config'],+ ['a long-s spelling of a private key', 'notes/key-s.md', '../id_r\u017fa'],+ ['a long-s spelling of a secret folder', 'notes/aws-s.md', '../.aw\u017f/config'],+ ['an HFS-ignorable spelling of an env file', 'notes/env-zw.md', '../.e\u200cnv'],+ ['a trailing-dot spelling of a secret file', 'notes/npmrc-dot.md', '../.npmrc.'],+ ])('refuses a symlink into %s', async (_label, linkPath, target) => {+ await pushSymlinks({ [linkPath]: target });+ await expectRefusedPull([linkPath]);+ });++ test.each([+ [+ 'a link to the OK dir',+ { x: '.ok', 'notes/leak.md': '../x/local/principal.json' },+ ['notes/leak.md', 'x'],+ ],+ [+ 'a link to the repository root',+ { a: '.', 'notes/out.md': '../a/../outside.txt' },+ ['a', 'notes/out.md'],+ ],+ [+ 'a link with an NTFS stream spelling',+ { y: '.git::$INDEX_ALLOCATION', 'notes/leak-ads.md': '../y/config' },+ ['notes/leak-ads.md', 'y'],+ ],+ ])('refuses a pair that escapes through %s', async (_label, links, refused) => {+ await pushSymlinks(links);+ expect(await expectRefusedPull(Object.keys(links))).toEqual(refused);+ });++ test.runIf(process.platform !== 'win32')(+ 'refuses a link that resolves through an untracked on-disk link named like an 8.3 short name',+ async () => {+ mkdirSync(join(projectDir, 'notes', 'safe'), { recursive: true });+ symlinkSync('safe', join(projectDir, 'notes', 'LINK~1'));+ await pushSymlinks({ 'notes/x.md': 'LINK~1/f.md' });+ expect(await expectRefusedPull(['notes/x.md'])).toEqual(['notes/x.md']);+ },+ );++ test.each([+ ['an 8.3 short name of the git dir', '../GIT~1/config', 'private-state'],+ ['an 8.3 short name of the OK dir', '../OK3A7F~1/local/principal.json', 'private-state'],+ [+ 'an 8.3 short name of the renamed config dir',+ '../OPEN-K~1/local/server.lock',+ 'private-state',+ ],+ [+ 'an 8.3 short name of the dotless config dir',+ '../OPENKN~1/local/server.lock',+ 'private-state',+ ],+ [+ 'a hashed 8.3 short name of a long config dir',+ '../OPB2C4~5/local/server.lock',+ 'private-state',+ ],+ [+ "an 8.3 short name of the beta product's user-home dir",+ '../OK-BET~1/auth.yml',+ 'private-state',+ ],+ ['an 8.3 short name of a credentials file', '../GIT-CR~1', 'unverifiable-target'],+ ['an 8.3 short-name folder before a plain name', '../DOCS~1/plain.md', 'unverifiable-target'],+ ['an 8.3 short name with an extension', '../REPORT~1.MD', 'unverifiable-target'],+ ['an 8.3 short name removed again by ..', 'LINK~1/../real.md', 'unverifiable-target'],+ ])('gives %s its own refusal reason', async (_label, target, reason) => {+ await pushSymlinks({ 'notes/alias-reason.md': target });+ await project.fetch('origin', 'main');+ const failure = await assertIncomingSymlinksSafe(+ project,+ 'refs/remotes/origin/main',+ 'merge',+ ).then(+ () => null,+ (caught: unknown) => caught,+ );+ expect(failure).toBeInstanceOf(UnsafeIncomingSymlinkError);+ expect((failure as UnsafeIncomingSymlinkError).unsafe).toEqual([+ { path: 'notes/alias-reason.md', reason },+ ]);+ });++ test('a name with a tilde that is not shaped like an 8.3 short name still pulls', async () => {+ await pushSymlinks({+ 'notes/near-long.md': 'LONGNAME~1.md',+ 'notes/near-word.md': 'notes~draft.md',+ });+ await pullWithEngine();+ expect(readlinkSync(join(projectDir, 'notes', 'near-long.md'))).toBe('LONGNAME~1.md');+ expect(readlinkSync(join(projectDir, 'notes', 'near-word.md'))).toBe('notes~draft.md');+ });++ test('refuses a link that escapes through a link pulled earlier, though its spelling stays inside', async () => {+ await pushSymlinks({ 'notes/sub/a': '..' });+ await pullWithEngine();+ expect(readlinkSync(join(projectDir, 'notes', 'sub', 'a'))).toBe('..');++ await pushSymlinks({ 'notes/out.md': 'sub/a/../../outside.txt' });+ expect(await expectRefusedPull(['notes/out.md'])).toEqual(['notes/out.md']);+ });++ test('pulls a chain of in-repository links like the ones skill linking writes', async () => {+ mkdirSync(join(sisterDir, 'shared', 'foreign'), { recursive: true });+ writeFileSync(join(sisterDir, 'shared', 'foreign', 'SKILL.md'), '# foreign\n', 'utf-8');+ await sister.add('shared/foreign/SKILL.md');+ await pushSymlinks({+ '.agents/skills/foreign': '../../shared/foreign',+ '.codex/skills/foreign': '../../.agents/skills/foreign',+ });++ await pullWithEngine();+ expect(readlinkSync(join(projectDir, '.codex', 'skills', 'foreign'))).toBe(+ '../../.agents/skills/foreign',+ );+ });++ test('refuses a link that escapes through a directory the same change replaces with a link', async () => {+ mkdirSync(join(sisterDir, 'notes', 'sub'), { recursive: true });+ writeFileSync(join(sisterDir, 'notes', 'sub', 'keep.md'), '# keep\n', 'utf-8');+ await sister.add('.');+ await sister.commit('add sub');+ await sister.push('origin', 'HEAD:main');+ await pullWithEngine();+ expect(lstatSync(join(projectDir, 'notes', 'sub')).isDirectory()).toBe(true);++ await sister.raw('rm', '-r', '--cached', '--quiet', 'notes/sub');+ await pushSymlinks({ 'notes/sub': '..', 'notes/leak.md': 'sub/../outside.txt' });+ expect(await expectRefusedPull(['notes/leak.md'])).toEqual(['notes/leak.md', 'notes/sub']);+ expect(lstatSync(join(projectDir, 'notes', 'sub')).isDirectory()).toBe(true);+ });++ test('refuses a tracked file the remote turns into an unsafe symlink', async () => {+ await pushSymlinks({ 'notes/real.md': '../.git/config' });+ const before = await headSha();++ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce()).toBe('refused');+ expect(lstatSync(join(projectDir, 'notes', 'real.md')).isSymbolicLink()).toBe(false);+ expect(await headSha()).toBe(before);+ } finally {+ await engine.destroy();+ }+ });++ test('refuses a safe symlink the remote retargets into private state', async () => {+ await pushSymlinks({ 'notes/alias.md': 'real.md' });+ await pullWithEngine();++ await pushSymlinks({ 'notes/alias.md': '../.git/config' });+ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce()).toBe('refused');+ expect(readlinkSync(join(projectDir, 'notes', 'alias.md'))).toBe('real.md');+ } finally {+ await engine.destroy();+ }+ });++ test('a refused link named after classifier keywords still pauses with the symlink reason', async () => {+ await pushSymlinks({ 'notes/protected branch authentication failed.md': '../.git/config' });++ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce()).toBe('refused');+ const status = engine.getStatus();+ expect(status.pausedReason).toBe('unsafe-incoming-symlinks');+ expect(status.state).toBe('idle');+ } finally {+ await engine.destroy();+ }+ });++ test('a refusal pauses sync with its own reason across cycles and clears once the remote removes the link', async () => {+ await pushSymlinks({ 'notes/leak.md': '../.ok/local/principal.json' });++ const engine = makeEngine();+ try {+ await engine.start();+ for (let cycle = 0; cycle < 2; cycle++) {+ expect(await engine.pullOnce('sync')).toBe('refused');+ const status = engine.getStatus();+ expect(status.state).toBe('idle');+ expect(status.pausedReason).toBe('unsafe-incoming-symlinks');+ expect(status.refusedSymlinkPaths).toEqual(['notes/leak.md']);+ expect(status.blockingPaths).toBeUndefined();+ expect(status.pullError).toBeUndefined();+ expect(status.consecutiveFailures).toBe(0);+ }++ await pushRemoval(['notes/leak.md']);+ expect(await engine.pullOnce('sync')).toBe('succeeded');+ const recovered = engine.getStatus();+ expect(recovered.pausedReason).toBeUndefined();+ expect(recovered.refusedSymlinkPaths).toBeUndefined();+ expect(existsAsEntry('notes/leak.md')).toBe(false);+ } finally {+ await engine.destroy();+ }+ });++ test('the push retry merge does not merge a tag that shadows the tracking ref', async () => {+ await pushSymlinks({ 'notes/leak.md': '../.git/config' }, 'unchecked');+ await sister.raw('tag', 'origin/main', 'HEAD');+ await sister.push(['origin', 'refs/tags/origin/main']);+ await sister.raw('reset', '--hard', 'HEAD~1');+ await pushSymlinks({ 'notes/alias.md': 'real.md' });+ const remoteBefore = (await sister.revparse(['HEAD'])).trim();+ writeFileSync(join(projectDir, 'notes', 'local.md'), '# local\n', 'utf-8');+ await project.add('notes/local.md');+ await project.commit('local work');++ const engine = makeEngine();+ try {+ await engine.start();+ await engine.pushOnce();++ expect((await project.raw('ls-tree', 'HEAD', 'notes/leak.md')).trim()).toBe('');+ expect(existsAsEntry('notes/leak.md')).toBe(false);+ expect((await sister.raw('ls-remote', 'origin', 'refs/heads/main')).split('\t')[0]).toBe(+ remoteBefore,+ );+ expect(engine.getStatus().pullError).toMatch(/shadows it/);+ } finally {+ await engine.destroy();+ }+ });++ test('the push retry merge refuses the same symlinks', async () => {+ await pushSymlinks({ 'notes/leak.md': '../.ok/local/principal.json' });+ writeFileSync(join(projectDir, 'notes', 'local.md'), '# local\n', 'utf-8');+ await project.add('notes/local.md');+ await project.commit('local work');++ const engine = makeEngine();+ try {+ await engine.start();+ await engine.pushOnce();++ expect(existsAsEntry('notes/leak.md')).toBe(false);+ expect((await project.raw('ls-tree', 'HEAD', 'notes/leak.md')).trim()).toBe('');+ const status = engine.getStatus();+ expect(status.pausedReason).toBe('unsafe-incoming-symlinks');+ expect(status.refusedSymlinkPaths).toEqual(['notes/leak.md']);+ } finally {+ await engine.destroy();+ }+ });++ test('explicit pull (fast-forward) lands exactly the commit the guard inspected', async () => {+ await pushSymlinks({ 'notes/alias.md': 'real.md' });+ const inspected = (await sister.revparse(['HEAD'])).trim();+ await pushSymlinks({ 'notes/leak.md': '../.git/config' }, 'later');+ await project.fetch('origin', 'later');+ const later = (await project.revparse(['origin/later'])).trim();++ let moved = false;+ const engine = makeEngine({+ setBatchInProgress: (value) => {+ if (value && !moved) {+ moved = true;+ execFileSync('git', ['update-ref', 'refs/remotes/origin/main', later], {+ cwd: projectDir,+ });+ }+ },+ });+ try {+ await engine.start();+ expect(await engine.pullOnce()).toBe('succeeded');+ expect(await headSha()).toBe(inspected);+ expect(existsAsEntry('notes/leak.md')).toBe(false);+ expect(readlinkSync(join(projectDir, 'notes', 'alias.md'))).toBe('real.md');+ } finally {+ await engine.destroy();+ }+ });++ test('background sync does not merge a tag that shadows the tracking ref, and says why', async () => {+ await pushSymlinks({ 'notes/leak.md': '../.git/config' }, 'unchecked');+ await sister.raw('tag', 'origin/main', 'HEAD');+ await sister.push(['origin', 'refs/tags/origin/main']);+ await sister.raw('reset', '--hard', 'HEAD~1');+ await pushSymlinks({ 'notes/alias.md': 'real.md' });++ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce('sync')).toBe('error');+ expect((await project.raw('ls-tree', 'HEAD', 'notes/leak.md')).trim()).toBe('');+ expect(existsAsEntry('notes/leak.md')).toBe(false);+ expect(engine.getStatus().pullError).toMatch(/shadows it/);+ } finally {+ await engine.destroy();+ }+ });++ test.each([['background sync (merge)', 'sync']] as const)(+ '%s lands only the commit the guard inspected',+ async (_label, invocation) => {+ await pushSymlinks({ 'notes/alias.md': 'real.md' });+ const inspected = (await sister.revparse(['HEAD'])).trim();+ await pushSymlinks({ 'notes/leak.md': '../.git/config' }, 'later');+ await project.fetch('origin', 'later');+ const later = (await project.revparse(['origin/later'])).trim();++ let moved = false;+ const engine = makeEngine({+ setBatchInProgress: (value) => {+ if (value && !moved) {+ moved = true;+ execFileSync('git', ['update-ref', 'refs/remotes/origin/main', later], {+ cwd: projectDir,+ });+ }+ },+ });+ try {+ await engine.start();+ expect(await engine.pullOnce(invocation)).toBe('refused');+ expect(existsAsEntry('notes/leak.md')).toBe(false);+ expect(isAncestorOfHead(later)).toBe(false);++ expect(await engine.pullOnce(invocation)).toBe('succeeded');+ expect(existsAsEntry('notes/leak.md')).toBe(false);+ expect(readlinkSync(join(projectDir, 'notes', 'alias.md'))).toBe('real.md');+ expect(isAncestorOfHead(inspected)).toBe(true);+ expect(isAncestorOfHead(later)).toBe(false);+ } finally {+ await engine.destroy();+ }+ },+ );++ test('refuses a later pull that redirects an accepted link through a directory turned into a link', async () => {+ mkdirSync(join(sisterDir, 'notes', 'd'), { recursive: true });+ writeFileSync(join(sisterDir, 'notes', 'd', 'keep.md'), '# keep\n', 'utf-8');+ await sister.add('.');+ await pushSymlinks({ 'notes/l': 'd/../outside.txt' });+ await pullWithEngine();++ await sister.raw('rm', '-r', '--cached', '--quiet', 'notes/d');+ await pushSymlinks({ 'notes/d': '..' });+ expect(await expectRefusedPull([])).toEqual(['notes/d', 'notes/l']);+ expect(lstatSync(join(projectDir, 'notes', 'd')).isDirectory()).toBe(true);+ });++ test('refuses a later pull that redirects an accepted link into OK machine-local state', async () => {+ mkdirSync(join(sisterDir, 'd'), { recursive: true });+ writeFileSync(join(sisterDir, 'd', 'keep.md'), '# keep\n', 'utf-8');+ await sister.add('.');+ await pushSymlinks({ l: 'd/../local/principal.json' });+ await pullWithEngine();++ await sister.raw('rm', '-r', '--cached', '--quiet', 'd');+ await pushSymlinks({ d: '.ok/skills' });+ expect(await expectRefusedPull([])).toEqual(['l']);+ });++ test('a link that was already unsafe before a pull does not block it', async () => {+ const blob = execFileSync('git', ['hash-object', '-w', '--stdin'], {+ cwd: projectDir,+ input: '../.git/config',+ encoding: 'utf-8',+ }).trim();+ await project.raw('update-index', '--add', '--cacheinfo', `120000,${blob},notes/bad`);+ await project.commit('local unsafe link');+ await project.push('origin', 'HEAD:main');+ await sister.pull('origin', 'main');++ await pushSymlinks({ 'notes/alias.md': 'real.md' });+ await pullWithEngine();+ expect(readlinkSync(join(projectDir, 'notes', 'alias.md'))).toBe('real.md');+ });++ test.each([+ [+ 'a canonically equivalent spelling of a link',+ { 'caf\u00e9': '.', 'notes/leak.md': '../cafe\u0301/../outside.txt' },+ ['notes/leak.md'],+ ],+ [+ 'a case variant of a link',+ { X: '.', 'notes/leak.md': '../x/../outside.txt' },+ ['notes/leak.md'],+ ],+ [+ 'a long-s spelling of a machine-local file',+ { 'notes/leak.md': '../.ok/principal.j\u017fon' },+ ['notes/leak.md'],+ ],+ ])('refuses a symlink that escapes through %s', async (_label, links, refused) => {+ await pushSymlinks(links);+ expect(await expectRefusedPull(['notes/leak.md'])).toEqual(expect.arrayContaining(refused));+ });++ test('a link that collides with a directory under case folding is treated as a link', async () => {+ mkdirSync(join(sisterDir, 'notes', 'sub', 'X'), { recursive: true });+ writeFileSync(join(sisterDir, 'notes', 'sub', 'X', 'keep.md'), '# keep\n', 'utf-8');+ await sister.add('notes/sub/X/keep.md');+ await pushSymlinks({+ 'notes/sub/x': '..',+ 'notes/leak.md': 'sub/X/../../../outside.txt',+ });+ expect(await expectRefusedPull(['notes/leak.md'])).toEqual(['notes/leak.md']);+ });++ test('refuses an acyclic chain of more symlinks than the kernel follows', async () => {+ const chain: Record<string, string> = { 'notes/c41': 'real.md' };+ for (let index = 0; index < 41; index++) chain[`notes/c${index}`] = `c${index + 1}`;+ await pushSymlinks(chain);+ expect(await expectRefusedPull(['notes/c0'])).toContain('notes/c0');+ });++ test('refuses incoming links whose resolution exceeds the inspection budget', async () => {+ const links: Record<string, string> = {};+ for (let index = 0; index < 100; index++) {+ links[`notes/deep${index}`] = `${'sub/../'.repeat(120)}real.md`;+ }+ await pushSymlinks(links);+ const refused = await expectRefusedPull(['notes/deep0']);+ expect(refused?.length).toBe(50);+ }, 60_000);++ test('a keyword-bearing component the filesystem cannot inspect pauses without disabling sync', async () => {+ const onAutoDisable = vi.fn();+ await pushSymlinks({+ 'notes/leak.md': `../${'protected branch '.repeat(16)}/../outside.txt`,+ });++ const engine = makeEngine({ onAutoDisable });+ try {+ await engine.start();+ expect(await engine.pullOnce()).toBe('refused');+ const status = engine.getStatus();+ expect(status.pausedReason).toBe('unsafe-incoming-symlinks');+ expect(status.refusedSymlinkPaths).toEqual(['notes/leak.md']);+ expect(status.syncMode).toBe('full');+ expect(status.syncEnabled).toBe(true);+ expect(onAutoDisable).not.toHaveBeenCalled();+ } finally {+ await engine.destroy();+ }+ });++ test('follows an untracked local link and re-inspects once it is removed', async () => {+ symlinkSync('..', join(projectDir, 'u'));+ await pushSymlinks({ 'notes/leak.md': '../u/outside.txt' });++ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce()).toBe('refused');+ expect(existsAsEntry('notes/leak.md')).toBe(false);++ unlinkSync(join(projectDir, 'u'));+ expect(await engine.pullOnce()).toBe('succeeded');+ expect(readlinkSync(join(projectDir, 'notes', 'leak.md'))).toBe('../u/outside.txt');+ } finally {+ await engine.destroy();+ }+ });++ test('logs a standing refusal once, even after a local commit', async () => {+ await pushSymlinks({ 'notes/leak.md': '../.ok/local/principal.json' });+ const logs = captureSyncLogs();+ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce('sync')).toBe('refused');+ await commitLocally('notes/local.md', '# local\n');+ expect(await engine.pullOnce('sync')).toBe('refused');+ expect(+ logs.entries.filter((entry) => entry.data.event === 'unsafe-incoming-symlinks'),+ ).toHaveLength(1);+ } finally {+ logs.restore();+ await engine.destroy();+ }+ });++ test('the push leg does not attempt a push while the refusal stands', async () => {+ await pushSymlinks({ 'notes/leak.md': '../.ok/local/principal.json' });+ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce('sync')).toBe('refused');+ await commitLocally('notes/local.md', '# local\n');++ const logs = captureSyncLogs();+ try {+ await engine.pushOnce();+ expect(logs.entries.some((entry) => entry.msg.includes('push rejected'))).toBe(false);+ } finally {+ logs.restore();+ }+ expect(engine.getStatus().pausedReason).toBe('unsafe-incoming-symlinks');+ } finally {+ await engine.destroy();+ }+ });++ test('a Manual one-shot pull keeps the refusal visible', async () => {+ await pushSymlinks({ 'notes/leak.md': '../.ok/local/principal.json' });+ const engine = makeEngine({ syncEnabled: false });+ try {+ await engine.start();+ expect(await engine.pullOnce()).toBe('refused');+ const status = engine.getStatus();+ expect(status.pausedReason).toBe('unsafe-incoming-symlinks');+ expect(status.refusedSymlinkPaths).toEqual(['notes/leak.md']);+ } finally {+ await engine.destroy();+ }+ });++ test('a refusal is recomputed after a restart rather than restored', async () => {+ await pushSymlinks({ 'notes/leak.md': '../.ok/local/principal.json' });+ const first = makeEngine();+ try {+ await first.start();+ expect(await first.pullOnce()).toBe('refused');+ } finally {+ await first.destroy();+ }++ const second = makeEngine();+ try {+ await second.start();+ expect(second.getStatus().pausedReason).toBeUndefined();+ } finally {+ await second.destroy();+ }+ });++ test('a force-push that removes the incoming commit clears the refusal', async () => {+ const base = (await sister.revparse(['HEAD'])).trim();+ await pushSymlinks({ 'notes/leak.md': '../.ok/local/principal.json' });+ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce()).toBe('refused');++ await sister.push(['--force', 'origin', `${base}:main`]);+ expect(await engine.pullOnce()).toBe('up-to-date');+ const status = engine.getStatus();+ expect(status.pausedReason).toBeUndefined();+ expect(status.refusedSymlinkPaths).toBeUndefined();+ } finally {+ await engine.destroy();+ }+ });++ test('in-repository symlinks, including legacy skill links, still pull', async () => {+ await pushSymlinks({+ 'notes/alias.md': 'real.md',+ '.claude/skills/demo': '../../.ok/skills/demo',+ });++ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce()).toBe('succeeded');+ expect(readlinkSync(join(projectDir, 'notes', 'alias.md'))).toBe('real.md');+ expect(readlinkSync(join(projectDir, '.claude', 'skills', 'demo'))).toBe(+ '../../.ok/skills/demo',+ );+ } finally {+ await engine.destroy();+ }+ });+});++describe('SyncEngine incoming symlink edge shapes', () => {+ test.each([+ ['a case pair', { 'notes/A': '../.git/config', 'notes/a': 'real.md' }, 'notes/A'],+ ['a trailing-dot pair', { 'notes/x': '../.git/config', 'notes/x.': 'real.md' }, 'notes/x'],+ [+ 'a composed and decomposed pair',+ { 'notes/cafe\u0301': '../.git/config', 'notes/caf\u00e9': 'real.md' },+ 'notes/cafe\u0301',+ ],+ ])('judges every link in %s under its own path', async (_label, links, unsafePath) => {+ await sister.raw('config', 'core.precomposeUnicode', 'false');+ await pushSymlinks(links);+ expect(+ (await sister.raw('ls-tree', '-z', '--name-only', 'HEAD', 'notes/')).split('\0'),+ ).toEqual(expect.arrayContaining(Object.keys(links)));+ expect(await expectRefusedPull([])).toContain(unsafePath);+ });++ test.runIf(process.platform !== 'win32' && process.getuid?.() !== 0)(+ 'a component the filesystem refuses to inspect pauses without disabling sync',+ async () => {+ const locked = join(projectDir, 'locked');+ mkdirSync(join(locked, 'inner'), { recursive: true });+ execFileSync('chmod', ['000', locked]);+ try {+ await pushSymlinks({ 'notes/protected branch.md': '../locked/inner/real.md' });+ const autoDisabled: string[] = [];+ const engine = makeEngine({ onAutoDisable: (reason) => autoDisabled.push(reason) });+ try {+ await engine.start();+ const modeBefore = engine.getStatus().syncMode;+ expect(await engine.pullOnce('sync')).toBe('refused');+ const status = engine.getStatus();+ expect(status.pausedReason).toBe('unsafe-incoming-symlinks');+ expect(status.syncMode).toBe(modeBefore);+ expect(autoDisabled).toEqual([]);+ } finally {+ await engine.destroy();+ }+ } finally {+ execFileSync('chmod', ['755', locked]);+ }+ },+ );++ test.each([+ ['the machine-local dir itself', '.ok/local', '../notes'],+ ['a machine-local file', '.ok/local/principal.json', '../../notes/real.md'],+ ])('refuses a link placed at %s', async (_label, linkPath, target) => {+ await pushSymlinks({ [linkPath]: target });+ expect(await expectRefusedPull([])).toEqual([linkPath]);+ expect(lstatSync(join(projectDir, '.ok', LOCAL_DIR, 'principal.json')).isFile()).toBe(true);+ });++ test('refuses a pull that deletes a link an existing link resolves through', async () => {+ mkdirSync(join(projectDir, 'notes', 'sub', 'deeper'), { recursive: true });+ writeFileSync(join(projectDir, 'notes', 'sub', 'deeper', 'keep.md'), '# keep\n', 'utf-8');+ symlinkSync('sub/deeper', join(projectDir, 'notes', 'd'));+ symlinkSync('d/../../../outside.txt', join(projectDir, 'notes', 'l'));+ await project.add(['notes/sub/deeper/keep.md', 'notes/d', 'notes/l']);+ await project.commit('existing chain');+ await project.push('origin', 'HEAD:main');+ await sister.pull('origin', 'main');++ await sister.raw('rm', '--cached', '--quiet', 'notes/d');+ rmSync(join(sisterDir, 'notes', 'd'), { force: true });+ mkdirSync(join(sisterDir, 'notes', 'd'), { recursive: true });+ writeFileSync(join(sisterDir, 'notes', 'd', 'keep.md'), '# keep\n', 'utf-8');+ await sister.add('notes/d/keep.md');+ await sister.commit('turn the link into a directory');+ await sister.push('origin', 'HEAD:main');++ expect(await expectRefusedPull([])).toEqual(['notes/l']);+ });++ test('judges an incoming link at the path a local directory rename moves it to', async () => {+ mkdirSync(join(sisterDir, 'notes', 'sub'), { recursive: true });+ writeFileSync(join(sisterDir, 'notes', 'sub', 'keep.md'), '# keep\n', 'utf-8');+ await sister.add('notes/sub/keep.md');+ await sister.commit('add sub folder');+ await sister.push('origin', 'HEAD:main');+ await project.pull('origin', 'main');+ mkdirSync(join(projectDir, 'top'), { recursive: true });+ await project.raw('mv', 'notes/sub/keep.md', 'top/keep.md');+ await project.commit('move the folder up locally');+ await pushSymlinks({ 'notes/sub/new.md': '../../x.md' });++ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce('sync')).toBe('refused');+ expect(engine.getStatus().refusedSymlinkPaths).toEqual(['top/new.md']);+ expect(existsAsEntry('notes/sub/new.md')).toBe(false);+ expect(existsAsEntry('top/new.md')).toBe(false);+ } finally {+ await engine.destroy();+ }+ });++ test.each([+ ['safe in both versions does not pause sync', '../notes/real.md', false],+ ['unsafe in the incoming version is refused', '../.git/config', true],+ ])('a link both sides changed and that is %s', async (_label, incomingTarget, refused) => {+ await pushSymlinks({ 'notes/alias.md': 'real.md' });+ await pullWithEngine();+ writeFileSync(join(projectDir, 'notes', 'other.md'), '# other\n', 'utf-8');+ rmSync(join(projectDir, 'notes', 'alias.md'));+ symlinkSync('other.md', join(projectDir, 'notes', 'alias.md'));+ await project.add(['notes/other.md', 'notes/alias.md']);+ await project.commit('retarget locally');+ await pushSymlinks({ 'notes/alias.md': incomingTarget });++ const engine = makeEngine();+ try {+ await engine.start();+ const outcome = await engine.pullOnce('sync');+ const status = engine.getStatus();+ if (refused) {+ expect(outcome).toBe('refused');+ expect(status.refusedSymlinkPaths).toEqual(['notes/alias.md']);+ expect(readlinkSync(join(projectDir, 'notes', 'alias.md'))).toBe('other.md');+ } else {+ expect(['succeeded', 'conflict']).toContain(outcome);+ expect(status.pausedReason).not.toBe('unsafe-incoming-symlinks');+ }+ } finally {+ await engine.destroy();+ }+ });++ test('a document link both sides changed is refused when the local version is unsafe', async () => {+ await pushSymlinks({ 'notes/alias.md': 'real.md' });+ await pullWithEngine();+ rmSync(join(projectDir, 'notes', 'alias.md'));+ symlinkSync('../.git/config', join(projectDir, 'notes', 'alias.md'));+ await project.add('notes/alias.md');+ await project.commit('local unsafe document link');+ writeFileSync(join(sisterDir, 'notes', 'other.md'), '# other\n', 'utf-8');+ await sister.add('notes/other.md');+ await pushSymlinks({ 'notes/alias.md': 'other.md' });++ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce('sync')).toBe('refused');+ expect(engine.getStatus().refusedSymlinkPaths).toEqual(['notes/alias.md']);+ } finally {+ await engine.destroy();+ }+ });++ test('a non-document link both sides changed is refused when either version that could land is unsafe', async () => {+ writeFileSync(join(sisterDir, 'notes', 'data.json'), '{}\n', 'utf-8');+ writeFileSync(join(sisterDir, 'notes', 'safe.json'), '{}\n', 'utf-8');+ await sister.add(['notes/data.json', 'notes/safe.json']);+ await sister.commit('add data files');+ await sister.push('origin', 'HEAD:main');+ await project.pull('origin', 'main');++ rmSync(join(projectDir, 'notes', 'data.json'));+ symlinkSync('../.git/config', join(projectDir, 'notes', 'data.json'));+ await project.add('notes/data.json');+ await project.commit('local unsafe link');++ rmSync(join(sisterDir, 'notes', 'data.json'));+ symlinkSync('safe.json', join(sisterDir, 'notes', 'data.json'));+ await sister.add('notes/data.json');+ await sister.commit('remote safe link');+ await sister.push('origin', 'HEAD:main');++ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce('sync')).toBe('refused');+ expect(engine.getStatus().refusedSymlinkPaths).toEqual(['notes/data.json']);+ expect(readlinkSync(join(projectDir, 'notes', 'data.json'))).toBe('../.git/config');+ } finally {+ await engine.destroy();+ }+ });++ test('refuses an existing link whose walk is cut short before it reaches a changed link', async () => {+ for (const dir of [+ ['notes', 'sub'],+ ['notes', 'd', 'e'],+ ['notes', 'e'],+ ]) {+ mkdirSync(join(projectDir, ...dir), { recursive: true });+ writeFileSync(join(projectDir, ...dir, 'keep.md'), '# keep\n', 'utf-8');+ }+ symlinkSync(`${'sub/../'.repeat(130)}d/e/../../../x.md`, join(projectDir, 'notes', 'l'));+ await project.add('notes');+ await project.commit('existing long link');+ await project.push('origin', 'HEAD:main');+ await sister.pull('origin', 'main');++ await sister.raw('rm', '-r', '--cached', '--quiet', 'notes/d');+ await pushSymlinks({ 'notes/d': '.' });+ expect(await expectRefusedPull([])).toContain('notes/l');+ expect(lstatSync(join(projectDir, 'notes', 'd')).isDirectory()).toBe(true);+ });++ test.runIf(process.platform !== 'win32')(+ 'refuses an existing link through a config-dir short name when a later link on its path changes',+ async () => {+ mkdirSync(join(projectDir, 'OK3A7F~1'), { recursive: true });+ writeFileSync(join(projectDir, 'OK3A7F~1', 'p.md'), '# p\n', 'utf-8');+ mkdirSync(join(projectDir, 'notes', 'sub'), { recursive: true });+ writeFileSync(join(projectDir, 'notes', 'sub', 'keep.md'), '# keep\n', 'utf-8');+ symlinkSync('sub', join(projectDir, 'notes', 'c'));+ symlinkSync('../OK3A7F~1/../notes/c/../.git/config', join(projectDir, 'notes', 'x.md'));+ await project.add(['OK3A7F~1', 'notes']);+ await project.commit('existing link through a short name');+ await project.push('origin', 'HEAD:main');+ await sister.pull('origin', 'main');++ await pushSymlinks({ 'notes/c': '../top' });+ expect(await expectRefusedPull([])).toContain('notes/x.md');+ },+ );++ test.runIf(process.platform !== 'win32')(+ 'refuses a link that leaves through an outside alias even when it lands somewhere safe inside',+ async () => {+ symlinkSync(join(projectDir, 'notes'), join(tmpDir, 'notes-alias'));+ await pushSymlinks({ 'notes/z.md': '../../notes-alias/real.md' });+ expect(await expectRefusedPull(['notes/z.md'])).toEqual(['notes/z.md']);+ },+ );++ test('an existing link outside the repository does not block a pull that changes links', async () => {+ mkdirSync(join(projectDir, 'notes'), { recursive: true });+ symlinkSync('../../elsewhere/shared.md', join(projectDir, 'notes', 'shared.md'));+ symlinkSync('/etc/hosts', join(projectDir, 'notes', 'hosts.md'));+ await project.add('notes');+ await project.commit('existing links outside the repository');+ await project.push('origin', 'HEAD:main');+ await sister.pull('origin', 'main');++ await pushSymlinks({ 'notes/other.md': 'real.md' });+ await pullWithEngine();+ expect(readlinkSync(join(projectDir, 'notes', 'other.md'))).toBe('real.md');+ });++ test.runIf(process.platform !== 'win32')(+ 'refuses an existing link through a generic short name on any pull that changes links',+ async () => {+ mkdirSync(join(projectDir, 'notes'), { recursive: true });+ symlinkSync('LINK~1/f.md', join(projectDir, 'notes', 'e.md'));+ await project.add('notes');+ await project.commit('existing link through a short name');+ await project.push('origin', 'HEAD:main');+ await sister.pull('origin', 'main');++ await pushSymlinks({ 'notes/other.md': 'real.md' });+ expect(await expectRefusedPull(['notes/other.md'])).toContain('notes/e.md');+ },+ );++ test('judges links that resolve through a conflicted link against the version that lands', async () => {+ for (const dir of [+ ['notes', 'sub', 'e'],+ ['notes', 'sub2', 'e'],+ ['notes', 'e'],+ ]) {+ mkdirSync(join(sisterDir, ...dir), { recursive: true });+ writeFileSync(join(sisterDir, ...dir, 'keep.md'), '# keep\n', 'utf-8');+ }+ await sister.add('.');+ await pushSymlinks({ 'notes/d': 'sub' });+ await pullWithEngine();++ rmSync(join(projectDir, 'notes', 'd'));+ symlinkSync('sub2', join(projectDir, 'notes', 'd'));+ await project.add('notes/d');+ await project.commit('retarget locally');+ await pushSymlinks({ 'notes/d': '.', 'notes/l': 'd/e/../../../x.md' });++ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce('sync')).toBe('refused');+ expect(engine.getStatus().refusedSymlinkPaths).toContain('notes/l');+ expect(existsAsEntry('notes/l')).toBe(false);+ } finally {+ await engine.destroy();+ }+ });++ test('refuses a link that resolves through the relocated spelling of a conflicted folder', async () => {+ mkdirSync(join(sisterDir, 'notes', 'd', 'e'), { recursive: true });+ writeFileSync(join(sisterDir, 'notes', 'd', 'e', 'keep.md'), '# keep\n', 'utf-8');+ await sister.add('notes/d/e/keep.md');+ await sister.commit('add folder');+ await sister.push('origin', 'HEAD:main');+ await project.pull('origin', 'main');++ writeFileSync(join(projectDir, 'notes', 'd', 'e', 'keep.md'), '# local edit\n', 'utf-8');+ await project.add('notes/d/e/keep.md');+ await project.commit('edit inside the folder locally');+ await sister.raw('rm', '-r', '--cached', '--quiet', 'notes/d');+ await pushSymlinks({ 'notes/d': '.', 'notes/l': 'd~origin_main/e/../../../x.md' });++ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce('sync')).toBe('refused');+ expect(engine.getStatus().refusedSymlinkPaths).toContain('notes/l');+ expect(existsAsEntry('notes/l')).toBe(false);+ } finally {+ await engine.destroy();+ }+ });++ test('refuses a link that resolves through a conflicted link outside any document folder', async () => {+ for (const dir of [+ ['vendor', 'sub', 'e'],+ ['vendor', 'sub2', 'e'],+ ['vendor', 'e'],+ ]) {+ mkdirSync(join(sisterDir, ...dir), { recursive: true });+ writeFileSync(join(sisterDir, ...dir, 'keep.txt'), 'keep\n', 'utf-8');+ }+ await sister.add('.');+ await pushSymlinks({ 'vendor/d.md': 'sub' });+ await pullWithEngine();++ rmSync(join(projectDir, 'vendor', 'd.md'));+ symlinkSync('sub2', join(projectDir, 'vendor', 'd.md'));+ await project.add('vendor/d.md');+ await project.commit('retarget locally');+ await pushSymlinks({ 'vendor/d.md': '.', 'vendor/l': 'd.md/e/../../../x.md' });++ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce('sync')).toBe('refused');+ expect(engine.getStatus().refusedSymlinkPaths).toContain('vendor/l');+ } finally {+ await engine.destroy();+ }+ });++ test('refuses a link whose walk exceeds the step cap', async () => {+ await pushSymlinks({ 'notes/steps.md': `${'x/../'.repeat(130)}real.md` });+ expect(await expectRefusedPull([])).toEqual(['notes/steps.md']);+ });++ test('follows a link spelled with a capital sharp s', async () => {+ mkdirSync(join(sisterDir, 'notes', 'sub'), { recursive: true });+ writeFileSync(join(sisterDir, 'notes', 'sub', 'keep.md'), '# keep\n', 'utf-8');+ await sister.add('notes/sub/keep.md');+ await pushSymlinks({+ 'notes/sub/\u00df': '..',+ 'notes/l': 'sub/\u1e9e/../../outside.txt',+ });+ expect(await expectRefusedPull([])).toContain('notes/l');+ });++ test('a safe link a local rename relocates still merges', async () => {+ mkdirSync(join(projectDir, 'moved'), { recursive: true });+ await project.raw('mv', 'notes/real.md', 'moved/real.md');+ await project.commit('move locally');+ await pushSymlinks({ 'notes/new.md': 'real.md' });++ const engine = makeEngine();+ try {+ await engine.start();+ expect(['succeeded', 'conflict']).toContain(await engine.pullOnce('sync'));+ expect(engine.getStatus().pausedReason).not.toBe('unsafe-incoming-symlinks');+ } finally {+ await engine.destroy();+ }+ });++ test('judges the tree the merge produces, not the incoming tree', async () => {+ mkdirSync(join(sisterDir, 'notes', 'sub', 'deeper'), { recursive: true });+ writeFileSync(join(sisterDir, 'notes', 'sub', 'deeper', 'keep.md'), '# keep\n', 'utf-8');+ await sister.add('notes/sub/deeper/keep.md');+ await pushSymlinks({ 'notes/d': 'sub/deeper' });+ await pullWithEngine();++ await project.raw('rm', '--cached', '--quiet', 'notes/d');+ rmSync(join(projectDir, 'notes', 'd'), { force: true });+ mkdirSync(join(projectDir, 'notes', 'd'), { recursive: true });+ writeFileSync(join(projectDir, 'notes', 'd', 'keep.md'), '# local\n', 'utf-8');+ await project.add('notes/d/keep.md');+ await project.commit('replace the link with a folder locally');+ await pushSymlinks({ 'notes/l': 'd/../../../outside.txt' });++ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce('sync')).toBe('refused');+ expect(engine.getStatus().refusedSymlinkPaths).toEqual(['notes/l']);+ expect(existsAsEntry('notes/l')).toBe(false);+ } finally {+ await engine.destroy();+ }+ });++ test('treats a name the filesystem could resolve to either a link or a folder as unverifiable', async () => {+ mkdirSync(join(sisterDir, 'notes', 'sub', 'X'), { recursive: true });+ mkdirSync(join(sisterDir, 'notes', 'sub', 'deeper', 'er'), { recursive: true });+ writeFileSync(join(sisterDir, 'notes', 'sub', 'X', 'keep.md'), '# keep\n', 'utf-8');+ writeFileSync(join(sisterDir, 'notes', 'sub', 'deeper', 'er', 'keep.md'), '# keep\n', 'utf-8');+ await sister.add(['notes/sub/X/keep.md', 'notes/sub/deeper/er/keep.md']);+ await pushSymlinks({+ 'notes/sub/x': 'deeper/er',+ 'notes/leak.md': 'sub/X/../../../../outside.txt',+ });+ expect(await expectRefusedPull([])).toContain('notes/leak.md');+ });++ test('a local rename elsewhere does not block a safe incoming link', async () => {+ mkdirSync(join(projectDir, 'docs'), { recursive: true });+ writeFileSync(join(projectDir, 'docs', 'old.md'), '# old\n', 'utf-8');+ await project.add('docs/old.md');+ await project.commit('add docs');+ await project.raw('mv', 'docs/old.md', 'docs/new.md');+ await project.commit('rename locally');+ await pushSymlinks({ 'notes/alias.md': 'real.md' });++ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce('sync')).toBe('succeeded');+ expect(readlinkSync(join(projectDir, 'notes', 'alias.md'))).toBe('real.md');+ } finally {+ await engine.destroy();+ }+ });++ test('re-inspects after committing an uncommitted folder move before merging', async () => {+ mkdirSync(join(sisterDir, 'deep', 'er', 'a'), { recursive: true });+ writeFileSync(join(sisterDir, 'deep', 'er', 'a', 'f.md'), '# f\n', 'utf-8');+ await sister.add('deep/er/a/f.md');+ await sister.commit('add deep folder');+ await sister.push('origin', 'HEAD:main');+ await project.pull('origin', 'main');++ await pushSymlinks({ 'deep/er/a/l': '../../../x.md' });+ mkdirSync(join(projectDir, 'a'), { recursive: true });+ execFileSync('git', ['mv', 'deep/er/a/f.md', 'a/f.md'], { cwd: projectDir });+ execFileSync('git', ['reset', '--quiet'], { cwd: projectDir });++ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce('sync')).toBe('refused');+ expect(engine.getStatus().pausedReason).toBe('unsafe-incoming-symlinks');+ expect(existsAsEntry('a/l')).toBe(false);+ expect(existsAsEntry('deep/er/a/l')).toBe(false);+ } finally {+ await engine.destroy();+ }+ });++ test('guards a project that lives below the git root', async () => {+ mkdirSync(join(sisterDir, 'sub', 'notes'), { recursive: true });+ writeFileSync(join(sisterDir, 'sub', 'notes', 'real.md'), '# real\n', 'utf-8');+ await sister.add('sub/notes/real.md');+ await sister.commit('add sub project');+ await sister.push('origin', 'HEAD:main');+ await project.pull('origin', 'main');+ const subProject = join(projectDir, 'sub');+ mkdirSync(join(subProject, '.ok', LOCAL_DIR), { recursive: true });+ writeFileSync(join(subProject, '.ok', LOCAL_DIR, 'principal.json'), '{"secret":1}\n', 'utf-8');+ await pushSymlinks({ 'sub/notes/leak.md': '../.ok/local/principal.json' });++ const engine = new SyncEngine({+ conflicts: createTestConflictAuthority(subProject),+ projectDir: subProject,+ contentDir: subProject,+ contentFilter: stubContentFilter,+ syncEnabled: true,+ });+ try {+ await engine.start();+ expect(await engine.pullOnce()).toBe('refused');+ expect(engine.getStatus().refusedSymlinkPaths).toEqual(['sub/notes/leak.md']);+ expect(existsAsEntry('sub/notes/leak.md')).toBe(false);+ } finally {+ await engine.destroy();+ }+ });++ test('fails closed on an unsafe link arriving on unrelated history', async () => {+ await sister.raw('checkout', '--quiet', '--orphan', 'unrelated');+ await sister.raw('rm', '-r', '--cached', '--quiet', '.');+ await pushSymlinks({ 'notes/leak.md': '../.git/config' }, 'unrelated-main');+ await sister.push(['--force', 'origin', 'unrelated:main']);++ const engine = makeEngine();+ try {+ await engine.start();+ expect(await engine.pullOnce('sync')).toBe('error');+ expect(existsAsEntry('notes/leak.md')).toBe(false);+ } finally {+ await engine.destroy();+ }+ });++ test('publishes refused paths with invisible characters escaped', async () => {+ await pushSymlinks({ 'notes/\u202egnp.md': '../.git/config' });+ expect(await expectRefusedPull([])).toEqual(['notes/\\u202egnp.md']);+ });+});++describe('share-link branch switch', () => {+ test.each([+ ['refuses a branch that carries an unsafe link', '../.git/config', false],+ ['switches to a branch whose links are safe', 'real.md', true],+ ])('%s', async (_label, target, switched) => {+ await pushSymlinks({ 'notes/link.md': target }, 'shared');+ await sister.raw('reset', '--hard', 'HEAD~1');++ const outcome = await runCheckoutFlow(projectDir, 'shared', { credentialConfig: [] });++ expect(outcome).toEqual(+ switched+ ? { ok: true }+ : { ok: false, reason: 'unsafe-symlinks', refusedSymlinkPaths: ['notes/link.md'] },+ );+ expect(existsAsEntry('notes/link.md')).toBe(switched);+ expect((await project.raw('rev-parse', '--abbrev-ref', 'HEAD')).trim()).toBe(+ switched ? 'shared' : 'main',+ );+ });++ test('lands the inspected branch tip, not a tag that shares its name', async () => {+ await pushSymlinks({ 'notes/link.md': '../.git/config' }, 'unchecked');+ await sister.raw('tag', 'shared', 'HEAD');+ await sister.push(['origin', 'refs/tags/shared']);+ await sister.raw('reset', '--hard', 'HEAD~1');+ await pushSymlinks({ 'notes/link.md': 'real.md' }, 'refs/heads/shared');+ const tip = (await sister.revparse(['HEAD'])).trim();+ await sister.raw('reset', '--hard', 'HEAD~1');+ await project.fetch('origin');++ const outcome = await runCheckoutFlow(projectDir, 'shared', { credentialConfig: [] });++ expect(outcome.ok).toBe(true);+ expect(await headSha()).toBe(tip);+ expect((await project.raw('symbolic-ref', 'HEAD')).trim()).toBe('refs/heads/shared');+ expect(readlinkSync(join(projectDir, 'notes', 'link.md'))).toBe('real.md');+ expect((await project.raw('rev-parse', '--symbolic-full-name', '@{upstream}')).trim()).toBe(+ 'refs/remotes/origin/shared',+ );+ });++ async function divergedTargetKeepingALinkHeadDeleted(): Promise<string> {+ const targetFile = join(tmpDir, 'link-target.txt');+ writeFileSync(targetFile, '../.git/config', 'utf-8');+ const blob = (await project.raw('hash-object', '-w', targetFile)).trim();+ await project.raw('update-index', '--add', '--cacheinfo', `120000,${blob},notes/leak.md`);+ await project.commit('base with link');+ const base = await headSha();+ await project.raw('rm', '--cached', '--quiet', 'notes/leak.md');+ await project.commit('drop link');+ const target = (+ await project.raw('commit-tree', `${base}^{tree}`, '-p', base, '-m', 'shared work')+ ).trim();+ await project.push('origin', `${target}:refs/heads/shared`);+ return target;+ }++ test.each([+ [+ 'the upstream write',+ () => writeFileSync(join(projectDir, '.git', 'config.lock'), '', 'utf-8'),+ ],+ ['the checkout', () => writeFileSync(join(projectDir, 'newdir'), 'untracked\n', 'utf-8')],+ ])('a switch that fails at %s leaves no new branch behind', async (_label, breakStep) => {+ const pageFile = join(tmpDir, 'page.txt');+ writeFileSync(pageFile, '# page\n', 'utf-8');+ const blob = (await sister.raw('hash-object', '-w', pageFile)).trim();+ await sister.raw('update-index', '--add', '--cacheinfo', `100644,${blob},newdir/page.md`);+ await sister.commit('add folder');+ await sister.push('origin', 'HEAD:shared');+ await sister.raw('reset', '--hard', 'HEAD~1');+ const head = await headSha();+ breakStep();++ try {+ const outcome = await runCheckoutFlow(projectDir, 'shared', { credentialConfig: [] });++ expect(outcome).toEqual({ ok: false, reason: 'checkout-failed' });+ expect(await headSha()).toBe(head);+ expect((await project.raw('branch', '--list', 'shared')).trim()).toBe('');+ } finally {+ rmSync(join(projectDir, '.git', 'config.lock'), { force: true });+ }+ });++ test('a failed switch to an existing local branch leaves that branch where it was', async () => {+ const pageFile = join(tmpDir, 'page.txt');+ writeFileSync(pageFile, '# page\n', 'utf-8');+ const blob = (await project.raw('hash-object', '-w', pageFile)).trim();+ const head = await headSha();+ await project.raw('update-index', '--add', '--cacheinfo', `100644,${blob},newdir/page.md`);+ const withFolder = (await project.raw('write-tree')).trim();+ await project.raw('rm', '--cached', '--quiet', 'newdir/page.md');+ const local = (+ await project.raw('commit-tree', withFolder, '-p', head, '-m', 'local branch work')+ ).trim();+ await project.raw('branch', 'shared', local);+ writeFileSync(join(projectDir, 'newdir'), 'untracked\n', 'utf-8');++ const outcome = await runCheckoutFlow(projectDir, 'shared', { credentialConfig: [] });++ expect(outcome).toEqual({ ok: false, reason: 'checkout-failed' });+ expect(await headSha()).toBe(head);+ expect((await project.revparse(['refs/heads/shared'])).trim()).toBe(local);+ });++ test('refuses an existing local branch fast-forwarded to an unsafe remote tip', async () => {+ const head = await headSha();+ await project.raw('branch', 'shared', head);+ await pushSymlinks({ 'notes/link.md': '../.git/config' }, 'shared');+ await sister.raw('reset', '--hard', 'HEAD~1');++ const outcome = await runCheckoutFlow(projectDir, 'shared', {+ fastForward: true,+ credentialConfig: [],+ });++ expect(outcome).toEqual({+ ok: false,+ reason: 'unsafe-symlinks',+ refusedSymlinkPaths: ['notes/link.md'],+ });+ expect(await headSha()).toBe(head);+ expect((await project.raw('symbolic-ref', 'HEAD')).trim()).toBe('refs/heads/main');+ expect(existsAsEntry('notes/link.md')).toBe(false);+ });++ test('refuses an existing local branch whose own tip is unsafe though its remote is safe', async () => {+ await pushSymlinks({ 'notes/link.md': 'real.md' }, 'shared');+ await sister.raw('reset', '--hard', 'HEAD~1');+ await project.fetch('origin');+ const head = await headSha();+ const targetFile = join(tmpDir, 'link-target.txt');+ writeFileSync(targetFile, '../.git/config', 'utf-8');+ const blob = (await project.raw('hash-object', '-w', targetFile)).trim();+ await project.raw('update-index', '--add', '--cacheinfo', `120000,${blob},notes/link.md`);+ const unsafeTree = (await project.raw('write-tree')).trim();+ await project.raw('rm', '--cached', '--quiet', 'notes/link.md');+ const local = (+ await project.raw('commit-tree', unsafeTree, '-p', head, '-m', 'unsafe local branch')+ ).trim();+ await project.raw('branch', 'shared', local);+ await project.raw('branch', '--set-upstream-to=origin/shared', 'shared');++ const outcome = await runCheckoutFlow(projectDir, 'shared', { credentialConfig: [] });++ expect(outcome).toEqual({+ ok: false,+ reason: 'unsafe-symlinks',+ refusedSymlinkPaths: ['notes/link.md'],+ });+ expect(await headSha()).toBe(head);+ expect((await project.raw('symbolic-ref', 'HEAD')).trim()).toBe('refs/heads/main');+ expect(existsAsEntry('notes/link.md')).toBe(false);+ });++ function installFailingPostCheckoutHook(): string {+ const hooksDir = join(tmpDir, 'checkout-hooks');+ const ranMarker = join(tmpDir, 'post-checkout-ran');+ mkdirSync(hooksDir, { recursive: true });+ const hook = join(hooksDir, 'post-checkout');+ writeFileSync(hook, `#!/bin/sh\ntouch '${ranMarker}'\nexit 1\n`, 'utf-8');+ execFileSync('chmod', ['755', hook]);+ execFileSync('git', ['config', 'core.hooksPath', hooksDir], { cwd: projectDir });+ return ranMarker;+ }++ test.runIf(process.platform !== 'win32')(+ 'a post-checkout hook that fails after the switch reports the switch it made',+ async () => {+ await pushSymlinks({ 'notes/link.md': 'real.md' }, 'shared');+ await sister.raw('reset', '--hard', 'HEAD~1');+ const ranMarker = installFailingPostCheckoutHook();++ const outcome = await runCheckoutFlow(projectDir, 'shared', { credentialConfig: [] });++ expect(existsSync(ranMarker)).toBe(true);+ expect(outcome).toEqual({ ok: true });+ expect((await project.raw('symbolic-ref', 'HEAD')).trim()).toBe('refs/heads/shared');+ expect(readlinkSync(join(projectDir, 'notes', 'link.md'))).toBe('real.md');+ },+ );++ test.runIf(process.platform !== 'win32')(+ 'a failed checkout of the branch HEAD is already on is not credited to a hook',+ async () => {+ await project.raw('checkout', '-b', 'shared');+ const head = await headSha();+ const ranMarker = installFailingPostCheckoutHook();++ const outcome = await runCheckoutFlow(projectDir, 'shared', { credentialConfig: [] });++ expect(existsSync(ranMarker)).toBe(true);+ expect(outcome).toEqual({ ok: false, reason: 'checkout-failed' });+ expect((await project.raw('symbolic-ref', 'HEAD')).trim()).toBe('refs/heads/shared');+ expect(await headSha()).toBe(head);+ },+ );++ test('judges the tree a switch lands, not what a merge of it would keep', async () => {+ await divergedTargetKeepingALinkHeadDeleted();+ const head = await headSha();++ const outcome = await runCheckoutFlow(projectDir, 'shared', { credentialConfig: [] });++ expect(outcome).toEqual({+ ok: false,+ reason: 'unsafe-symlinks',+ refusedSymlinkPaths: ['notes/leak.md'],+ });+ expect(await headSha()).toBe(head);+ expect((await project.raw('symbolic-ref', 'HEAD')).trim()).toBe('refs/heads/main');+ expect(existsAsEntry('notes/leak.md')).toBe(false);+ });++ test.each([+ ['merge first', ['merge', 'checkout']],+ ['checkout first', ['checkout', 'merge']],+ ] as const)('keeps merge and checkout verdicts apart (%s)', async (_label, order) => {+ const target = await divergedTargetKeepingALinkHeadDeleted();+ const verdicts: Record<string, boolean> = {};+ for (const landing of order) {+ verdicts[landing] = await assertIncomingSymlinksSafe(project, target, landing).then(+ () => true,+ () => false,+ );+ }+ expect(verdicts).toEqual({ merge: true, checkout: false });+ });+});++describe('incoming symlink inspection', () => {+ function gitReportingVersion(versionLine: string): SimpleGit {+ const binary = join(tmpDir, 'fake-git');+ writeFileSync(+ binary,+ `#!/bin/sh\nif [ "$1" = version ]; then echo "${versionLine}"; exit 0; fi\nexec git "$@"\n`,+ 'utf-8',+ );+ execFileSync('chmod', ['755', binary]);+ return simpleGit({ baseDir: projectDir, binary });+ }++ async function divergeWith(remote: () => Promise<void>): Promise<string> {+ await commitLocally('notes/local.md', '# local\n');+ await remote();+ await project.fetch('origin', 'main');+ return (await project.revparse(['refs/remotes/origin/main'])).trim();+ }++ test.runIf(process.platform !== 'win32')(+ 'below the merge-tree Git floor, a three-way pull that changes a link is refused',+ async () => {+ const incoming = await divergeWith(() => pushSymlinks({ 'notes/alias.md': 'real.md' }));+ const failure = await assertIncomingSymlinksSafe(+ gitReportingVersion('git version 2.34.1'),+ incoming,+ 'merge',+ ).then(+ () => null,+ (caught: unknown) => caught,+ );+ expect(failure).toBeInstanceOf(UnsafeIncomingSymlinkError);+ expect((failure as UnsafeIncomingSymlinkError).unsafe).toEqual([+ { path: 'notes/alias.md', reason: 'requires-newer-git' },+ ]);+ },+ );++ test.runIf(process.platform !== 'win32')(+ 'below the merge-tree Git floor, a link changed only locally does not refuse the pull',+ async () => {+ const blob = execFileSync('git', ['hash-object', '-w', '--stdin'], {+ cwd: projectDir,+ input: 'real.md',+ encoding: 'utf-8',+ }).trim();+ await project.raw('update-index', '--add', '--cacheinfo', `120000,${blob},notes/mine.md`);+ await project.commit('local link');+ const incoming = await divergeWith(async () => {+ writeFileSync(join(sisterDir, 'notes', 'remote.md'), '# remote\n', 'utf-8');+ await sister.add('notes/remote.md');+ await sister.commit('remote doc');+ await sister.push('origin', 'HEAD:main');+ });+ await expect(+ assertIncomingSymlinksSafe(gitReportingVersion('git version 2.34.1'), incoming, 'merge'),+ ).resolves.toBeUndefined();+ },+ );++ test.runIf(process.platform !== 'win32')(+ 'an unparseable git version still checks through merge-tree',+ async () => {+ const incoming = await divergeWith(() => pushSymlinks({ 'notes/leak.md': '../.git/config' }));+ const failure = await assertIncomingSymlinksSafe(+ gitReportingVersion('git version unknown-build'),+ incoming,+ 'merge',+ ).then(+ () => null,+ (caught: unknown) => caught,+ );+ expect((failure as UnsafeIncomingSymlinkError).unsafe).toEqual([+ { path: 'notes/leak.md', reason: 'private-state' },+ ]);+ },+ );++ test.runIf(process.platform !== 'win32')(+ 'fails closed on a merge-tree conflict record it cannot parse',+ async () => {+ const binary = join(tmpDir, 'stageless-git');+ writeFileSync(+ binary,+ '#!/bin/sh\nif [ "$1" = merge-tree ]; then git "$@" | perl -0pe \'s/ [123]\\t/\\t/g\'; exit 0; fi\nexec git "$@"\n',+ 'utf-8',+ );+ execFileSync('chmod', ['755', binary]);+ await pushSymlinks({ 'notes/alias.md': 'real.md' });+ await pullWithEngine();+ rmSync(join(projectDir, 'notes', 'alias.md'));+ symlinkSync('../.git/config', join(projectDir, 'notes', 'alias.md'));+ await project.add('notes/alias.md');+ await project.commit('local link');+ const incoming = await divergeWith(() => pushSymlinks({ 'notes/alias.md': 'other.md' }));++ await expect(+ assertIncomingSymlinksSafe(simpleGit({ baseDir: projectDir, binary }), incoming, 'merge'),+ ).rejects.toThrow('unparseable git merge-tree record while inspecting incoming symlinks');+ },+ );++ test('refuses to resolve an incoming ref that does not exist', async () => {+ await expect(resolveIncomingCommit(project, 'origin/missing')).rejects.toThrow(+ /cannot resolve the incoming commit/,+ );+ });++ test('a branch name never reaches the error text the engine classifies', async () => {+ const failure = await resolveIncomingCommit(project, 'refs/remotes/origin/fix-403').then(+ () => null,+ (caught: unknown) => caught,+ );+ expect(failure).toBeInstanceOf(Error);+ expect(classifyGitError(failure).class).not.toBe('auth');+ });++ test('refuses to vouch for a commit it cannot inspect', async () => {+ await expect(assertIncomingSymlinksSafe(project, '0'.repeat(40), 'merge')).rejects.toThrow();+ });++ test('fails closed with the cause attached when link targets cannot be read', async () => {+ await pushSymlinks({ 'notes/alias.md': 'real.md' });+ await project.fetch('origin', 'main');++ const failure = await assertIncomingSymlinksSafe(project, 'refs/remotes/origin/main', 'merge', {+ PATH: join(tmpDir, 'no-git-here'),+ }).then(+ () => null,+ (caught: unknown) => caught,+ );+ expect(failure).toBeInstanceOf(Error);+ expect((failure as Error).message).toBe(+ 'could not read incoming symlink targets from git (spawn)',+ );+ expect(failure).toMatchObject({ failure: 'spawn', detail: 'ENOENT', stderr: '' });+ expect(classifyGitError(failure).class).toBe('local');+ });+});++describe('UnsafeIncomingSymlinkError', () => {+ test('keeps remote-controlled paths out of the message', () => {+ const error = new UnsafeIncomingSymlinkError([+ { path: 'notes/connection refused.md', reason: 'private-state' },+ ]);+ expect(error.message).not.toContain('connection refused');+ expect(error.describeLinks()).toContain('"notes/connection refused.md"');+ });++ test('escapes control, C1, and bidirectional formatting characters in described paths', () => {+ const error = new UnsafeIncomingSymlinkError([+ {+ path: 'notes/\u001b]0;pwned\u0007\u007f\u009b31m\u202egnp.md\u2066.md',+ reason: 'outside-repository',+ },+ ]);+ const described = error.describeLinks();+ for (const raw of ['\u001b', '\u0007', '\u007f', '\u009b', '\u202e', '\u2066']) {+ expect(described).not.toContain(raw);+ }+ expect(described).toContain('\\u007f');+ expect(described).toContain('\\u009b');+ expect(described).toContain('\\u202e');+ expect(described).toContain('\\u2066');+ });+});diff --git a/packages/server/src/sync-engine.test.ts b/packages/server/src/sync-engine.test.tsindex 81d8315fc..a98bc5882 100644--- a/packages/server/src/sync-engine.test.ts+++ b/packages/server/src/sync-engine.test.ts@@ -3,6 +3,7 @@ import {appendFileSync,chmodSync,existsSync,+ lstatSync,mkdirSync,mkdtempSync,readFileSync,@@ -5583,7 +5584,7 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {}});- test('refuses to write an overlay through a symlink escaping the repo, and surfaces the failure', async () => {+ test('refuses an incoming symlink that escapes the repo before any overlay write, leaving its target untouched', async () => {const bareDir = await seedBareOrigin();const sisterDir = join(tmpDir, 'sister');mkdirSync(sisterDir, { recursive: true });@@ -5617,7 +5618,53 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {await engine.trigger('pull');expect(readFileSync(escapeTarget, 'utf-8')).toBe('PRECIOUS\n');- expect(engine.getStatus().lastPullOutcome).toBe('error');+ expect(engine.getStatus().lastPullOutcome).toBe('refused');+ expect(engine.getStatus().pausedReason).toBe('unsafe-incoming-symlinks');+ } finally {+ await engine.destroy();+ }+ });++ test('a local symlink in the way of an overlay is replaced by the restore, never written through', async () => {+ const bareDir = await seedBareOrigin();+ const sisterDir = join(tmpDir, 'sister');+ mkdirSync(sisterDir, { recursive: true });+ const sister = simpleGit(sisterDir);+ await sister.init(['--initial-branch=main']);+ await sister.raw('config', 'user.name', 'Sister');+ await sister.raw('config', 'user.email', '[email protected]');+ writeFileSync(join(sisterDir, 'a.md'), 'A1\n', 'utf-8');+ mkdirSync(join(sisterDir, 'sub'), { recursive: true });+ writeFileSync(join(sisterDir, 'sub', 'a.md'), 'A1\n', 'utf-8');+ await sister.add('.');+ await sister.commit('seed');+ await sister.addRemote('origin', bareDir);+ await sister.push('origin', 'main');++ rmSync(projectDir, { recursive: true, force: true });+ await simpleGit(tmpDir).clone(bareDir, projectDir);+ mkdirSync(okDir, { recursive: true });++ const escapeDir = join(tmpDir, 'escape-dir');+ mkdirSync(escapeDir, { recursive: true });+ const escapeTarget = join(escapeDir, 'a.md');+ writeFileSync(escapeTarget, 'A1\nLOCAL\n', 'utf-8');+ rmSync(join(projectDir, 'sub'), { recursive: true, force: true });+ symlinkSync(escapeDir, join(projectDir, 'sub'));++ writeFileSync(join(sisterDir, 'sub', 'a.md'), 'A1\nREMOTE\n', 'utf-8');+ await sister.add('sub/a.md');+ await sister.commit('remote edit');+ await sister.push('origin', 'main');++ const engine = makePullEngine();+ try {+ await engine.start();+ await engine.trigger('pull');++ expect(readFileSync(escapeTarget, 'utf-8')).toBe('A1\nLOCAL\n');+ expect(lstatSync(join(projectDir, 'sub')).isSymbolicLink()).toBe(false);+ expect(engine.getStatus().pausedReason).not.toBe('unsafe-incoming-symlinks');} finally {await engine.destroy();}diff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.tsindex 8d08a24d7..3e947ba09 100644--- a/packages/server/src/sync-engine.ts+++ b/packages/server/src/sync-engine.ts@@ -15,6 +15,7 @@ import {OK_DIR,type PullOutcome,pathspecArgs,+ REFUSED_SYMLINK_PATHS_CAP,SYNC_PAUSED_REASONS,type SyncMode,type SyncModeChangeSource,@@ -62,6 +63,15 @@ import {type ProbeTokenStore,type PushPermission,} from './github-permissions.ts';+import {+ assertIncomingSymlinksSafe,+ assertMergeNameResolvesTo,+ escapePathForDisplay,+ IncomingRefMovedError,+ IncomingRefShadowedError,+ resolveIncomingCommit,+ UnsafeIncomingSymlinkError,+} from './incoming-symlink-guard.ts';import { getLogger } from './logger.ts';import {applyManagedMcpEntry,@@ -264,6 +274,7 @@ const ONE_SHOT_PAUSES: ReadonlySet<SyncPausedReason | undefined> = new Set<SyncP'git-index-locked','git-operation-in-progress','no-commits-yet',+ 'unsafe-incoming-symlinks',]);const NON_PERSISTED_PAUSE_LIST = [@@ -272,6 +283,7 @@ const NON_PERSISTED_PAUSE_LIST = ['git-index-locked','git-operation-in-progress','no-commits-yet',+ 'unsafe-incoming-symlinks',] as const satisfies readonly SyncPausedReason[];const NON_PERSISTED_PAUSES: ReadonlySet<SyncPausedReason | undefined> = new Set<SyncPausedReason>(@@ -453,6 +465,8 @@ export class SyncEngine {private lastLockNoticeKind: 'index-locked' | 'git-lock-held' | undefined;private restingIndexLockPause: SyncPausedReason | undefined;private blockingPaths: string[] = [];+ private loggedSymlinkRefusal: string | undefined;+ private refusedSymlinkPaths: string[] = [];private currentBranch = 'main';private cycleInFlight: 'pull' | 'push' | null = null;@@ -1109,6 +1123,9 @@ export class SyncEngine {...(this.blockingPathsForStatus().length > 0? { blockingPaths: this.blockingPathsForStatus() }: {}),+ ...(this.pausedReason === 'unsafe-incoming-symlinks' && this.refusedSymlinkPaths.length > 0+ ? { refusedSymlinkPaths: this.refusedSymlinkPaths.slice(0, REFUSED_SYMLINK_PATHS_CAP) }+ : {}),...(this.pushPermission !== null ? { pushPermission: this.pushPermission } : {}),};}@@ -1499,8 +1516,26 @@ export class SyncEngine {await this.refreshDivergenceCounts(handle);+ let incoming = '';+ const willLand =+ this.behind > 0 && (invocation === 'explicit' ? this.ahead === 0 : this.conflictCount === 0);+ if (willLand) {+ try {+ incoming = await this.validateIncomingSymlinks(handle, branch);+ } catch (e) {+ if (e instanceof UnsafeIncomingSymlinkError) {+ this.handleIncomingSymlinkRefusal(e, 'pull');+ return 'refused';+ }+ this.handleError(classifyGitError(e instanceof Error ? e : new Error(String(e))), 'pull');+ return 'error';+ }+ } else if (this.behind === 0) {+ this.clearIncomingSymlinkPause();+ }+if (this.behind > 0 && invocation === 'explicit') {- const outcome = await this.doPullCycleB1(handle, branch);+ const outcome = await this.doPullCycleB1(handle, branch, incoming);this.scheduleSaveState();return outcome;}@@ -1508,15 +1543,16 @@ export class SyncEngine {if (this.pausedReason === 'diverged-local-commits') this.pausedReason = undefined;this.transitionTo('pulling');this.setBatchInProgress?.(true);+ let stashRestored = true;+ let overlaysRestored = true;try {await this.commitDirtyContentFilesToHead(handle, 'pull');- const mergePrep = await this.prepareForMerge(handle, branch);+ await this.validateIncomingSymlinks(handle, branch, incoming);+ const mergePrep = await this.prepareForMerge(handle, branch, incoming);if (!mergePrep.proceed) return 'refused';- let stashRestored = true;- let overlaysRestored = true;try {await this.applyCommitIdentity(handle);- await handle.git.merge([`origin/${branch}`]);+ await this.mergeIncomingCommit(handle, branch, incoming);this.lastSyncUtc = new Date().toISOString();this.behind = 0;if (this.pausedReason === 'external-changes-pending') this.clearBlockingPause();@@ -1537,7 +1573,28 @@ export class SyncEngine {this.handleGitOperationRefusal(e, 'pull');return 'refused';}- const classified = classifyGitError(e instanceof Error ? e : new Error(String(e)));+ if (e instanceof UnsafeIncomingSymlinkError) {+ this.handleIncomingSymlinkRefusal(e, 'pull');+ return 'refused';+ }+ if (e instanceof IncomingRefMovedError && stashRestored && overlaysRestored) {+ log.info(+ { branch, incoming, ref: e.ref },+ '[sync] incoming commit moved after inspection; re-inspecting next cycle',+ );+ this.transitionTo('idle');+ return 'refused';+ }+ const failure = !(e instanceof IncomingRefMovedError)+ ? e+ : new Error(+ stashRestored+ ? 'failed to restore reconciled MCP overlays'+ : 'failed to replay pre-merge working-tree state',+ );+ const classified = classifyGitError(+ failure instanceof Error ? failure : new Error(String(failure)),+ );if (classified.class === 'semantic' && classified.subclass === 'merge-conflict') {await this.handleMergeConflict();if (this.state === 'conflict') return 'conflict';@@ -1554,7 +1611,11 @@ export class SyncEngine {return this.behind === 0 ? 'up-to-date' : 'conflict';}- private async doPullCycleB1(handle: GitHandle, branch: string): Promise<PullOutcome> {+ private async doPullCycleB1(+ handle: GitHandle,+ branch: string,+ incomingCommit: string,+ ): Promise<PullOutcome> {this.transitionTo('pulling');if (this.ahead > 0) {@@ -1574,7 +1635,7 @@ export class SyncEngine {oldHead = (await handle.git.revparse(['HEAD'])).trim();const overlayPaths = await listNames(handle.git, ['diff-index', '--name-only', 'HEAD']);const incoming = new Set(- await listNames(handle.git, ['diff', '--name-only', `HEAD..origin/${branch}`]),+ await listNames(handle.git, ['diff', '--name-only', `HEAD..${incomingCommit}`]),);overlapping = overlayPaths.filter((p) => incoming.has(p));} catch (e) {@@ -1589,7 +1650,13 @@ export class SyncEngine {let plan: Awaited<ReturnType<typeof this.planOverlapReconciliation>>;try {- plan = await this.planOverlapReconciliation(handle, branch, oldHead, overlapping, existing);+ plan = await this.planOverlapReconciliation(+ handle,+ incomingCommit,+ oldHead,+ overlapping,+ existing,+ );} catch (e) {this.handleError(classifyGitError(e instanceof Error ? e : new Error(String(e))), 'pull');return 'error';@@ -1624,7 +1691,7 @@ export class SyncEngine {}}- const ff = await this.fastForwardOnly(handle, branch);+ const ff = await this.fastForwardOnly(handle, incomingCommit);if (!ff.ok) {try {this.applyOverlayPlan(plan.mineRestore, plan.deletions);@@ -1696,7 +1763,7 @@ export class SyncEngine {private async fastForwardOnly(handle: GitHandle,- branch: string,+ incoming: string,): Promise<| { ok: true }| {@@ -1708,11 +1775,12 @@ export class SyncEngine {}> {try {- await execFileAsync(- 'git',- ['-c', 'core.autocrlf=false', 'merge', '--ff-only', `origin/${branch}`],- { cwd: this.projectDir, env: handle.env, windowsHide: true, timeout: FF_ONLY_TIMEOUT_MS },- );+ await execFileAsync('git', ['-c', 'core.autocrlf=false', 'merge', '--ff-only', incoming], {+ cwd: this.projectDir,+ env: handle.env,+ windowsHide: true,+ timeout: FF_ONLY_TIMEOUT_MS,+ });return { ok: true };} catch (e) {const err = e as {@@ -1737,7 +1805,7 @@ export class SyncEngine {private async planOverlapReconciliation(handle: GitHandle,- branch: string,+ incoming: string,oldHead: string,overlapping: string[],existing: Map<string, Extract<Conflict, { kind: 'working-tree' }>>,@@ -1766,7 +1834,7 @@ export class SyncEngine {if (!existsSync(join(this.projectDir, p))) {try {- await handle.git.revparse([`origin/${branch}:${p}`]);+ await handle.git.revparse([`${incoming}:${p}`]);} catch (e) {if (this.classifyRefReadFailure(e) === 'error') {deletions.push(p);@@ -1800,7 +1868,7 @@ export class SyncEngine {let theirsStr: string | null = null;try {- theirsStr = await handle.git.raw(['show', `origin/${branch}:${p}`]);+ theirsStr = await handle.git.raw(['show', `${incoming}:${p}`]);} catch (e) {if (this.classifyRefReadFailure(e) === 'error') {log.warn(@@ -1871,7 +1939,7 @@ export class SyncEngine {}writes.push({ path: p, bytes: mineBuf });- const theirsSha = await this.gitBlobSha(handle, `origin/${branch}:${p}`);+ const theirsSha = await this.gitBlobSha(handle, `${incoming}:${p}`);if (theirsSha === undefined) {log.warn({ path: p },@@ -1975,6 +2043,10 @@ export class SyncEngine {if (this.cycleInFlight === 'pull' && this.pushTimer === null) this.schedulePush();return;}+ if (this.pausedReason === 'unsafe-incoming-symlinks') {+ this.schedulePush();+ return;+ }this.cycleInFlight = 'push';this.beginIndexLockWatch('push');@@ -2199,21 +2271,25 @@ export class SyncEngine {const retryHandle = this.gitHandle();this.setBatchInProgress?.(true);let retryStage: 'fetch' | 'merge' | 'push' = 'fetch';+ let stashRestored = true;+ let overlaysRestored = true;try {await retryHandle.git.fetch('origin');+ const incoming = await this.validateIncomingSymlinks(retryHandle, this.currentBranch);retryStage = 'push';await this.commitDirtyContentFilesToHead(retryHandle, 'push');- const mergePrep = await this.prepareForMerge(retryHandle, this.currentBranch);+ retryStage = 'fetch';+ await this.validateIncomingSymlinks(retryHandle, this.currentBranch, incoming);+ retryStage = 'push';+ const mergePrep = await this.prepareForMerge(retryHandle, this.currentBranch, incoming);if (!mergePrep.proceed) {this.setBatchInProgress?.(false);return;}- let stashRestored = true;- let overlaysRestored = true;try {await this.applyCommitIdentity(retryHandle);retryStage = 'merge';- await retryHandle.git.merge([`origin/${this.currentBranch}`]);+ await this.mergeIncomingCommit(retryHandle, this.currentBranch, incoming);retryStage = 'push';} finally {if (mergePrep.needsStashPop) {@@ -2229,8 +2305,28 @@ export class SyncEngine {this.handleGitOperationRefusal(mergeErr, 'push');return;}+ if (mergeErr instanceof UnsafeIncomingSymlinkError) {+ this.handleIncomingSymlinkRefusal(mergeErr, 'push');+ return;+ }+ if (mergeErr instanceof IncomingRefMovedError && stashRestored && overlaysRestored) {+ log.info(+ { ref: mergeErr.ref },+ '[sync] push retry: incoming commit moved after inspection; re-inspecting next cycle',+ );+ if (this.state === 'pushing') this.transitionTo('idle');+ this.scheduleSaveState();+ return;+ }+ const failure = !(mergeErr instanceof IncomingRefMovedError)+ ? mergeErr+ : new Error(+ stashRestored+ ? 'failed to restore reconciled MCP overlays'+ : 'failed to replay pre-merge working-tree state',+ );const mc = classifyGitError(- mergeErr instanceof Error ? mergeErr : new Error(String(mergeErr)),+ failure instanceof Error ? failure : new Error(String(failure)),);if (mc.class === 'semantic' && mc.subclass === 'merge-conflict') {await this.handleMergeConflict();@@ -2350,15 +2446,15 @@ export class SyncEngine {private async planTrackedMcpOverlap(handle: GitHandle,- branch: string,+ incomingCommit: string,path: string,): Promise<ReturnType<typeof reconcileTrackedMcpConfig>> {let baseRevision: string;try {- baseRevision = (await handle.git.raw(['merge-base', 'HEAD', `origin/${branch}`])).trim();+ baseRevision = (await handle.git.raw(['merge-base', 'HEAD', incomingCommit])).trim();} catch (err) {log.warn(- { err, branch, path },+ { err, incomingCommit, path },'[sync] MCP reconciliation merge-base unavailable — declining',);return { kind: 'declined', reason: 'merge-base-unavailable' };@@ -2367,7 +2463,7 @@ export class SyncEngine {this.readMcpGitBlob(handle, baseRevision, path),this.readMcpGitBlob(handle, 'HEAD', path),this.readMcpGitBlob(handle, '', path),- this.readMcpGitBlob(handle, `origin/${branch}`, path),+ this.readMcpGitBlob(handle, incomingCommit, path),]);let worktree: string | null = null;try {@@ -2380,7 +2476,11 @@ export class SyncEngine {});}- private async prepareForMerge(handle: GitHandle, branch: string): Promise<MergePreparation> {+ private async prepareForMerge(+ handle: GitHandle,+ branch: string,+ incoming: string,+ ): Promise<MergePreparation> {const reconciled: PreparedMcpReconciliation[] = [];let dirtyPaths: string[];try {@@ -2394,7 +2494,7 @@ export class SyncEngine {let mergePaths: Set<string>;try {mergePaths = new Set(- await listNames(handle.git, ['diff', '--name-only', `HEAD..origin/${branch}`]),+ await listNames(handle.git, ['diff', '--name-only', `HEAD..${incoming}`]),);} catch (err) {log.warn({ err, branch }, '[sync] merge-path diff failed — allowing merge attempt');@@ -2408,7 +2508,7 @@ export class SyncEngine {const plans = await Promise.all(mcpOverlaps.map(async (path) => ({path,- plan: await this.planTrackedMcpOverlap(handle, branch, path),+ plan: await this.planTrackedMcpOverlap(handle, incoming, path),})),);const declined = plans.find(({ plan }) => plan.kind === 'declined');@@ -2566,6 +2666,88 @@ export class SyncEngine {this.scheduleSaveState();}+ private async validateIncomingSymlinks(+ handle: GitHandle,+ branch: string,+ inspected?: string,+ ): Promise<string> {+ const trackingRef = `refs/remotes/origin/${branch}`;+ let incoming = inspected;+ try {+ incoming ??= await resolveIncomingCommit(handle.git, trackingRef);+ await assertIncomingSymlinksSafe(handle.git, incoming, 'merge', handle.env);+ } catch (e) {+ const links =+ e instanceof UnsafeIncomingSymlinkError+ ? e.unsafe.slice(0, REFUSED_SYMLINK_PATHS_CAP)+ : null;+ const refusalKey = links === null ? undefined : JSON.stringify([incoming, links]);+ if (links !== null && refusalKey !== this.loggedSymlinkRefusal) {+ this.loggedSymlinkRefusal = refusalKey;+ log.warn(+ { event: 'unsafe-incoming-symlinks', branch, incoming, links },+ '[sync] refusing incoming changes with unsafe symlinks until they are fixed',+ );+ }+ if (links === null) {+ log.warn(+ { err: e, branch, trackingRef, incoming },+ '[sync] incoming symlink inspection failed',+ );+ }+ throw e;+ }+ this.clearIncomingSymlinkPause();+ return incoming;+ }++ private handleIncomingSymlinkRefusal(+ error: UnsafeIncomingSymlinkError,+ op: 'push' | 'pull',+ ): void {+ this.pausedReason = 'unsafe-incoming-symlinks';+ this.refusedSymlinkPaths = error.unsafe.map(({ path }) => escapePathForDisplay(path));+ if (op === 'push') this.clearPushError();+ else this.clearPullError();+ if (this.state === 'pushing' || this.state === 'pulling' || this.state === 'fetching') {+ this.transitionTo('idle');+ }+ this.cc1Broadcaster?.signal('sync-status');+ this.scheduleSaveState();+ }++ private clearIncomingSymlinkPause(): void {+ this.loggedSymlinkRefusal = undefined;+ if (this.pausedReason !== 'unsafe-incoming-symlinks') return;+ this.pausedReason = undefined;+ this.refusedSymlinkPaths = [];+ this.cc1Broadcaster?.signal('sync-status');+ }++ private async mergeIncomingCommit(+ handle: GitHandle,+ branch: string,+ incoming: string,+ ): Promise<void> {+ const name = `origin/${branch}`;+ try {+ await assertMergeNameResolvesTo(handle.git, {+ name,+ trackingRef: `refs/remotes/${name}`,+ commit: incoming,+ });+ } catch (e) {+ if (e instanceof IncomingRefShadowedError) {+ log.warn(+ { event: 'incoming-ref-shadowed', shadowedName: e.shadowedName, incoming },+ '[sync] another ref shadows the incoming branch name; delete it locally and on the remote',+ );+ }+ throw e;+ }+ await handle.git.merge([name]);+ }+private hasGitOperationInProgress(): boolean {const gitDir = resolveGitDir(this.projectDir);if (!gitDir) return true;