Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat: pull-only sync mode (one-directional GitHub sync) (#2857)
miles-kt-inkeep4239b9993b15
diff --git a/.changeset/pull-only-sync-mode.md b/.changeset/pull-only-sync-mode.mdnew file mode 100644index 000000000..7effab3a7--- /dev/null+++ b/.changeset/pull-only-sync-mode.md@@ -0,0 +1,22 @@+---+"@inkeep/open-knowledge": minor+---++Add Follow — a one-directional sync mode for people who follow a knowledge base they can read but not push to (share-link recipients and read-only followers).++Previously, opening a repository you lacked push access to left your copy silently frozen: the sync onboarding prompt was suppressed, no sync config was written, and the engine parked itself the moment a push was denied. Follow fixes that dead end.++What it does:++- Keeps your local copy current automatically by fast-forwarding to the latest on GitHub, without ever pushing or committing on your behalf.+- Lets your own uncommitted edits ride safely on top of incoming updates. Non-overlapping changes combine automatically; edits to the same lines the upstream changed surface in the familiar conflict view, where you choose keep-mine or take-theirs. Your branch always tracks the upstream tip and never forks.+- Is always opt-in. Push-denied users are now offered Follow at first open with plain-language copy ("updates flow in from GitHub; your edits stay on this computer"), and anyone can choose Off / Follow / Full in Settings. A project owner can commit `autoSync.default: follow` so a fresh clone starts following.++Also included:++- Full-sync users who lose push access now get a "Switch to Follow" action on the sync-paused notice instead of a silent stall; switching keeps any unshared local commits as a local overlay.+- The sync status badge stays visible for a followed project and shows a distinct following state (updating / up to date / conflict / offline).+- Anonymous followers of public repositories poll more gently than signed-in followers.+- A one-shot "Sync" pull that reports its outcome, for surfaces that need an on-demand refresh.++Configuration note: the sync preference is now stored as a single `autoSync.mode` (`off` / `follow` / `full`). Existing `autoSync.enabled` settings keep working, and choosing a mode clears the legacy flag so the two can't disagree across versions. An app that predates `autoSync.mode` then reads the config as unanswered and re-prompts rather than acting on a stale toggle, so it never pushes for a mode you didn't consent to there.diff --git a/docs/content/features/github-sync.mdx b/docs/content/features/github-sync.mdxindex 254ba3c1f..09f3648d6 100644--- a/docs/content/features/github-sync.mdx+++ b/docs/content/features/github-sync.mdx@@ -3,10 +3,18 @@ title: GitHub syncicon: custom/GitHubdescription: Clone repos from GitHub, auto-sync changes with your team, and resolve conflicts.----OpenKnowledge can connect a project to a GitHub remote repository and keep it synced over time. When GitHub sync is enabled, OpenKnowledge actively pulls commits from the remote and pushes commits back.++import { Cloud } from 'lucide-react';++OpenKnowledge can connect a project to a GitHub remote repository and keep it synced over time. When GitHub sync is enabled, OpenKnowledge keeps your copy current with the remote.++There are two modes for GitHub sync:++- **Full** pulls commits from the remote and pushes your commits back.+- **Follow** fetches updates from the remote and never pushes or commits on your behalf.<Callout type="warn">- Only enable GitHub sync for repositories where you are comfortable with OpenKnowledge writing commits to the remote history. If you are worried about automated commits cluttering your Git history, do not enable sync for that repository.+ Only enable full GitHub sync for repositories where you are comfortable with OpenKnowledge writing commits to the remote history. If you are worried about automated commits cluttering your Git history, do not enable full sync for that repository.</Callout>## What GitHub sync is for@@ -27,7 +35,7 @@ These steps use the desktop app; from a terminal, [`ok clone`](/docs/reference/c<Step>### Open the clone dialog- From the Navigator window, click **Clone from GitHub**. You can open the navigator window from the editor by clicking on your project name in the bottom left and then clicking **Switch project**.+ From the Navigator window, click **Clone from GitHub**. You can open the Navigator window from the editor by clicking on your project name in the bottom left and then clicking **Switch project**.</Step><Step>@@ -57,19 +65,30 @@ This will open a dialog where you can choose an owner and repository name. You c## Enable GitHub sync-When you open a freshly cloned project, you will be prompted to enable sync. You can also toggle it from the project settings page at any time.+When you open a freshly cloned project, you will be prompted to enable sync. If you have full access to the repository, you will be prompted to enable **Full** sync. If you have read only access, you will be prompted to enable **Follow** sync. You can change the sync mode from the sync popover (the <Cloud role="img" aria-label="Sync" className="inline size-4 align-text-bottom" /> icon) or from **Settings → Sync** at any time.++If you want to set a default sync setting for future collaborators, go to the project settings page and navigate to the **Sync** → **Shared default** section. This writes [`autoSync.default`](/docs/reference/configuration) — one of `off`, `follow`, or `full` — to the project's committed `.ok/config.yml`, pre-answering the enable-sync prompt for everyone who clones the repo; each machine's own auto-sync choice overrides it.-While sync is active, OpenKnowledge:+### Full++With full sync active, OpenKnowledge:- Fetches commits from the remote- Commits your edits locally using the configured Git identity- Pushes those commits back to the remote so collaborators see your changes-If your Git identity isn't set, sync still commits under a default "OpenKnowledge" author; the sync status indicator reminds you to set one so teammates see your name.+If your Git identity isn't set, OpenKnowledge commits under a default "OpenKnowledge" author; the sync status indicator reminds you to set one so teammates see your name.Pulls can overwrite uncommitted local file changes, so commit or discard work-in-progress before you enable sync.-If you want to set a default auto-sync setting for future collaborators, go to the project settings page and navigate to the **Sync** -> **Shared default** section. This writes [`autoSync.default`](/docs/reference/configuration) to the project's committed `.ok/config.yml`, pre-answering the enable-sync prompt for everyone who clones the repo; each machine's own auto-sync choice overrides it.+### Follow++With follow sync active, OpenKnowledge:++- Fetches commits from the remote+- Never commits or pushes your edits to the remote++Your own edits stay on this computer. You can keep editing a followed project: when an update arrives, non-overlapping changes combine automatically, and an edit to the same lines the remote changed surfaces in the [conflict view](#resolving-a-conflict) where you choose which side to keep. Your branch always tracks the remote tip and never forks.## Authentication@@ -104,7 +123,7 @@ A few situations stop sync from completing successfully. In each case the sync s### Conflicts and pending changes- **Unresolved conflicts.** If even one file has a conflict between your edits and your team's, sync waits. You can keep working on every other doc; only the conflicted files are frozen until you choose a side from the diff view. See [Resolving a conflict](#resolving-a-conflict) above.-- **Local changes would be overwritten by an incoming update.** A teammate's update is ready to pull, but a file it touches has uncommitted local changes. Doc edits are committed automatically before merging, so this usually means other tracked files, like configs. Sync pauses rather than clobber your work; commit, stash, or discard those changes from a terminal and sync resumes.+- **Local changes would be overwritten by an incoming update.** A teammate's update is ready to pull, but a file it touches has uncommitted local changes. Doc edits are committed automatically before merging, so this usually means other tracked files, like configs. Sync pauses rather than clobbering your work; commit, stash, or discard those changes from a terminal and sync resumes.- **Edits made outside the app aren't ready yet.** If you (or another tool) edited a file directly on disk while sync wanted to merge, OpenKnowledge waits until those external edits settle before merging. Usually this clears in a second or two on its own.### Project isn't on a normal branch@@ -115,7 +134,7 @@ A few situations stop sync from completing successfully. In each case the sync s### GitHub-side blockers- **Authentication errors.** Your stored credentials expired, were revoked, or don't have access to this repository anymore. Reconnect from the sync indicator (or from **Settings → Account**) to clear the error.-- **You don't have permission to push to this repo.** Someone shared a project backed by a GitHub repo where your account isn't a collaborator (or has read-only access on a private repo). OpenKnowledge checks this up front: instead of prompting you to enable sync that would just fail, the toggle is disabled with an inline "You don't have permission to push to this repo" message in both the sync indicator popover and **Settings → Sync**. If you had sync enabled on a different repo and switch to one you can't push to, OpenKnowledge pauses sync in-memory rather than mutating your preference; your `Auto-sync: on` setting is preserved for the next repo you have full access to. Ask the project owner for write access, then click sync to re-check.+- **You don't have permission to push to this repo.** Someone shared a project backed by a GitHub repo where your account isn't a collaborator (or has read-only access on a private repo). OpenKnowledge checks this up front and offers **Follow** instead of full sync.- **Protected branches and rejected pushes.** If the target branch requires reviews, signed commits, or status checks, GitHub rejects the push. OpenKnowledge turns sync off automatically so it stops retrying, and it stays off until you turn it back on from the sync indicator or **Settings → Sync**. Switch to a branch you can push to, or use a pull request for the protected branch instead.### Temporary problemsdiff --git a/docs/content/features/share.mdx b/docs/content/features/share.mdxindex 957df9262..a172ad524 100644--- a/docs/content/features/share.mdx+++ b/docs/content/features/share.mdx@@ -66,6 +66,6 @@ Even on the right branch, a doc or folder can be renamed or deleted after a link### Receiving without push permission-If the shared repo is one your GitHub account can't push to (you're not a collaborator on a public repo, or you have read-only access on a private one), OpenKnowledge skips the usual "Enable auto-sync?" prompt. Sync is also disabled for the same reason in **Settings → Sync**. If the project owner grants you write access later, push permission is re-checked the next time the project's server starts. See [GitHub sync: GitHub-side blockers](/docs/features/github-sync#github-side-blockers) for the full set of permission shapes the sync UI handles.+If the shared repo is one your GitHub account can't push to (you're not a collaborator on a public repo, or you have read-only access on a private one), OpenKnowledge offers **[Follow](/docs/features/github-sync#follow)** at first open instead of the full "Enable auto-sync?" prompt: your copy keeps up to date by pulling the latest from GitHub automatically, while your own edits stay on your computer. You can keep editing — an incoming update combines with your non-overlapping changes automatically, and an edit to the same lines surfaces as a conflict to resolve.See [GitHub sync](/docs/features/github-sync) for how to automatically sync changes to GitHub, and [Timeline and recovery](/docs/features/timeline-and-recovery) for per-doc history once the doc is open.diff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdxindex 90ede825c..ac31b5871 100644--- a/docs/content/reference/configuration.mdx+++ b/docs/content/reference/configuration.mdx@@ -8,7 +8,7 @@ OpenKnowledge reads YAML config from three places:- **Project**: `./.ok/config.yml` (this project, committed to git)- **User**: `~/.ok/global.yml` (every project on your machine)-- **Project-local**: `./.ok/local/config.yml` (this project on this machine; gitignored). Holds per-machine-per-project preferences such as `autoSync.enabled`. Maintained by the editor (auto-sync onboarding modal, sync popover, Settings pane Sync section); you don't normally hand-edit it.+- **Project-local**: `./.ok/local/config.yml` (this project on this machine; gitignored). Holds per-machine-per-project preferences such as `autoSync.mode`. Maintained by the editor (auto-sync onboarding modal, sync popover, Settings pane Sync section); you don't normally hand-edit it.All files are optional; defaults cover everything.@@ -36,8 +36,9 @@ A key set in a file more specific than its scope (a user-scope key in `.ok/confi| `contentRules.plugins.markdownlint.enabled` | boolean | `false` | project | Enable the [markdownlint](/docs/advanced/content-rules/markdownlint) content-rules plugin for this project (shared via git). Off by default — turn it on in **Settings → This project → Plugins**. The rules themselves live in your native `.markdownlint.*` file, not here. || `appearance.theme` | `"light" \| "dark" \| "system"` | (unset) | user | Editor theme. || `appearance.sidebar.showHiddenFiles` | boolean | `false` | project-local | Show files whose path segments start with `.`. The sidebar otherwise lists every file on disk under the content directory; tooling internals (`.git/`, `.ok/`, `node_modules/`) stay hidden regardless. Toggled from the sidebar's right-click menu or the macOS **View → Show Hidden Files** item. |-| `autoSync.enabled` | `boolean \| null` | `null` | project-local | Per-machine git auto-sync toggle. `null` means "unanswered"; the editor's onboarding modal triggers on first remote-detected open. |-| `autoSync.default` | `boolean \| null` | `null` | project | Committed seed for each machine's first-open auto-sync choice: `true` = on, `false` = off, `null` = ask. Lets a maintainer pre-answer the onboarding prompt for everyone who clones; a per-machine `autoSync.enabled` overrides it. |+| `autoSync.mode` | `"off" \| "follow" \| "full" \| null` | `null` | project-local | Per-machine sync mode for this project: `off` (no sync), `follow` (one-directional — pull remote changes, never push your own; the earlier value `pull` is accepted as an alias), `full` (bidirectional pull and push). `null` means "unanswered"; the editor's onboarding modal triggers on first remote-detected open. Supersedes `autoSync.enabled`. |+| `autoSync.enabled` | `boolean \| null` | `null` | project-local | Legacy per-machine auto-sync toggle, superseded by `autoSync.mode`. Read only when `mode` is absent (`true` = full, `false` = off). `null` means "unanswered". |+| `autoSync.default` | `"off" \| "follow" \| "full" \| boolean \| null` | `null` | project | Committed seed for each machine's first-open sync mode: `off` / `follow` / `full`, or the legacy boolean (`true` = full, `false` = off). `null` = ask. Lets a maintainer pre-answer the onboarding prompt for everyone who clones; a per-machine `autoSync.mode` overrides it. Compatibility note: a committed string value (`off` / `follow` / `full`) is rejected by app versions released before `autoSync.mode` existed, resetting that machine to config defaults until it updates (it never silently syncs). The legacy boolean seed (`true` / `false`) stays readable by older apps — commit `follow` only once collaborators are on a current version. || `editor.wordWrap` | boolean | `true` | user | Soft-wrap long lines in the source-mode CodeMirror editor. A personal preference, not project-shared. Toggle from the Settings pane. || `appearance.preview.autoOpen` | boolean | `true` | user | Whether the agent should open or refresh the OpenKnowledge preview when it edits a doc through the MCP. Default `true` lets the agent route the preview by host capability: the host's in-app browser (Cursor preview pane, Codex's built-in browser, Claude Code Desktop) when one exists, the system browser otherwise. Set `false` to keep the agent's hands off your preview window. This is useful when you're already viewing the doc in OK Desktop, a browser tab on a second display, a non-default browser, or any flow where your extensions / accessibility tooling only work in your own browser. The agent then surfaces the URL on request but does not navigate. The change takes effect on the next preview-related tool call. Toggle from **Settings → Preferences → "Open preview when agent edits"**. || `terminal.enabled` | `boolean \| null` | `null` | project-local | Opt-out for the in-app terminal (a real OS shell at full user privilege). On by default; set `false` to disable it for this project on this machine. |diff --git a/packages/app/src/components/AutoSyncEnableWarning.tsx b/packages/app/src/components/AutoSyncEnableWarning.tsxindex 4e854cbdc..988e7f032 100644--- a/packages/app/src/components/AutoSyncEnableWarning.tsx+++ b/packages/app/src/components/AutoSyncEnableWarning.tsx@@ -1,8 +1,37 @@import { Trans } from '@lingui/react/macro';-import { ArrowRightLeft, Eye, GitCommitVertical } from 'lucide-react';+import {+ ArrowDownToLine,+ ArrowRightLeft,+ Eye,+ GitCommitVertical,+ GitMerge,+ Laptop,+} from 'lucide-react';+import type { ReactNode } from 'react';+import type { AutoSyncOnboardingVariant } from '@/components/auto-sync-onboarding-gate';import { DialogDescription, DialogTitle } from '@/components/ui/dialog';-export function AutoSyncEnableDialogIntro() {+interface SyncVariantProps {+ /** 'full' = bidirectional sync copy (default); 'pull' = one-directional. */+ variant?: AutoSyncOnboardingVariant;+}++export function AutoSyncEnableDialogIntro({ variant = 'full' }: SyncVariantProps) {+ if (variant === 'follow') {+ return (+ <>+ <DialogTitle>+ <Trans>Enable Follow?</Trans>+ </DialogTitle>+ <DialogDescription>+ <Trans>+ Follow fetches updates from your remote git repository and fast-forwards your copy+ automatically. Your local edits stay on this computer and are never pushed.+ </Trans>+ </DialogDescription>+ </>+ );+ }return (<><DialogTitle>@@ -18,7 +47,7 @@ export function AutoSyncEnableDialogIntro() {);}-export function AutoSyncEnableWarning() {+export function AutoSyncEnableWarning({ variant = 'full' }: SyncVariantProps) {return (<div role="note" className="text-sm space-y-5"><p className="flex items-center gap-1.5 text-xs font-semibold font-mono uppercase tracking-wider text-primary">@@ -28,48 +57,104 @@ export function AutoSyncEnableWarning() {<Trans>Heads up</Trans></p><div className="space-y-5">- <div className="flex items-start gap-3">+ {variant === 'follow' ? <PullOnlyBullets /> : <FullSyncBullets />}+ </div>+ </div>+ );+}++function FullSyncBullets() {+ return (+ <>+ <WarningBullet+ icon={<ArrowRightLeftaria-hidden="true"className="mt-0.5 size-4 shrink-0 text-muted-foreground"/>- <div className="space-y-0.5">- <p className="font-medium">- <Trans>Uncommitted changes</Trans>- </p>- <p className="text-muted-foreground">- <Trans>Pulls may overwrite uncommitted edits in your local files.</Trans>- </p>- </div>- </div>- <div className="flex items-start gap-3">+ }+ title={<Trans>Uncommitted changes</Trans>}+ body={<Trans>Pulls may overwrite uncommitted edits in your local files.</Trans>}+ />+ <WarningBullet+ icon={<GitCommitVerticalaria-hidden="true"className="mt-0.5 size-4 shrink-0 text-muted-foreground"/>- <div className="space-y-0.5">- <p className="font-medium">- <Trans>Commits happen automatically</Trans>- </p>- <p className="text-muted-foreground">- <Trans>- OpenKnowledge will create commits and push them to your remote automatically. If you- do not want automatic commits in your git history, you should not enable auto-sync.- </Trans>- </p>- </div>- </div>- <div className="flex items-start gap-3">- <Eye aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-muted-foreground" />- <div className="space-y-0.5">- <p className="font-medium">- <Trans>Shared repositories</Trans>- </p>- <p className="text-muted-foreground">- <Trans>Collaborators see your in-progress edits as soon as they sync.</Trans>- </p>- </div>- </div>+ }+ title={<Trans>Commits happen automatically</Trans>}+ body={+ <Trans>+ OpenKnowledge will create commits and push them to your remote automatically. If you do+ not want automatic commits in your git history, you should not enable auto-sync.+ </Trans>+ }+ />+ <WarningBullet+ icon={<Eye aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-muted-foreground" />}+ title={<Trans>Shared repositories</Trans>}+ body={<Trans>Collaborators see your in-progress edits as soon as they sync.</Trans>}+ />+ </>+ );+}++function PullOnlyBullets() {+ return (+ <>+ <WarningBullet+ icon={+ <ArrowDownToLine+ aria-hidden="true"+ className="mt-0.5 size-4 shrink-0 text-muted-foreground"+ />+ }+ title={<Trans>Updates flow in</Trans>}+ body={<Trans>New changes from your remote appear in your copy automatically.</Trans>}+ />+ <WarningBullet+ icon={+ <Laptop aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-muted-foreground" />+ }+ title={<Trans>Your edits stay on this computer</Trans>}+ body={+ <Trans>+ Follow never pushes or commits your local changes. They stay only on this machine.+ </Trans>+ }+ />+ <WarningBullet+ icon={+ <GitMerge aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-muted-foreground" />+ }+ title={<Trans>Overlapping edits</Trans>}+ body={+ <Trans>+ If an update arrives for something you are editing, you choose which version to keep,+ like a merge conflict.+ </Trans>+ }+ />+ </>+ );+}++function WarningBullet({+ icon,+ title,+ body,+}: {+ icon: ReactNode;+ title: ReactNode;+ body: ReactNode;+}) {+ return (+ <div className="flex items-start gap-3">+ {icon}+ <div className="space-y-0.5">+ <p className="font-medium">{title}</p>+ <p className="text-muted-foreground">{body}</p></div></div>);diff --git a/packages/app/src/components/AutoSyncOnboardingDialog.dom.test.tsx b/packages/app/src/components/AutoSyncOnboardingDialog.dom.test.tsxindex a387b2112..0238051c5 100644--- a/packages/app/src/components/AutoSyncOnboardingDialog.dom.test.tsx+++ b/packages/app/src/components/AutoSyncOnboardingDialog.dom.test.tsx@@ -1,11 +1,13 @@+import type { SyncMode } from '@inkeep/open-knowledge-core';import { cleanup, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';import type { ReactNode } from 'react';import { afterEach, describe, expect, test, vi } from 'vitest';+import type { AutoSyncOnboardingVariant } from './auto-sync-onboarding-gate.ts';-type SyncWriter = (enabled: boolean) => { ok: true } | { ok: false; error: string };+type ModeWriter = (mode: SyncMode) => { ok: true } | { ok: false; error: string };-let writer: SyncWriter | null = null;+let writer: ModeWriter | null = null;const toastErrors: string[] = [];import * as actualLinguiMacro from '@lingui/react/macro';@@ -28,12 +30,15 @@ vi.doMock('sonner', () => ({}));vi.doMock('@/hooks/use-enable-sync-with-confirm', () => ({- useSyncEnabledWriter: () => writer,+ useSyncModeWriter: () => writer,}));-async function renderDialog(onResolved: () => void = () => {}) {+async function renderDialog(+ variant: AutoSyncOnboardingVariant = 'full',+ onResolved: () => void = () => {},+) {const { AutoSyncOnboardingDialog } = await import('./AutoSyncOnboardingDialog');- render(<AutoSyncOnboardingDialog open={true} onResolved={onResolved} />);+ render(<AutoSyncOnboardingDialog open={true} variant={variant} onResolved={onResolved} />);}describe('AutoSyncOnboardingDialog runtime behavior', () => {@@ -48,9 +53,9 @@ describe('AutoSyncOnboardingDialog runtime behavior', () => {expect(typeof mod.AutoSyncOnboardingDialog).toBe('function');});- test('renders stable primary and secondary choices without a close affordance', async () => {+ test('full variant renders the bidirectional prompt without a close affordance', async () => {writer = () => ({ ok: true });- await renderDialog();+ await renderDialog('full');expect(screen.getByRole('button', { name: 'Enable auto-sync' })).not.toBeNull();expect(screen.getByRole('button', { name: 'Keep disabled' })).not.toBeNull();@@ -58,45 +63,61 @@ describe('AutoSyncOnboardingDialog runtime behavior', () => {expect(screen.getByRole('note').textContent).toContain('Heads up');});- test('disables both choices until the project-local sync writer is ready', async () => {- writer = null;- await renderDialog();+ test('pull variant explains one-directional sync and that edits stay local', async () => {+ writer = () => ({ ok: true });+ await renderDialog('follow');- expect(- (screen.getByRole('button', { name: 'Enable auto-sync' }) as HTMLButtonElement).disabled,- ).toBe(true);- expect(- (screen.getByRole('button', { name: 'Keep disabled' }) as HTMLButtonElement).disabled,- ).toBe(true);+ expect(screen.getByRole('button', { name: 'Enable Follow' })).not.toBeNull();+ const note = screen.getByRole('note').textContent ?? '';+ expect(note).toContain('Updates flow in');+ expect(note).toContain('stay only on this machine');});- test('persists enable and disable choices through the shared writer', async () => {- const writerCalls: boolean[] = [];- const resolvedCalls: string[] = [];- writer = (enabled) => {- writerCalls.push(enabled);+ test('persists the resolved mode per variant through the writer', async () => {+ const modeWrites: SyncMode[] = [];+ writer = (mode) => {+ modeWrites.push(mode);return { ok: true };};- await renderDialog(() => resolvedCalls.push('resolved'));+ await renderDialog('full');await userEvent.click(screen.getByRole('button', { name: 'Enable auto-sync' }));- expect(writerCalls).toEqual([true]);- expect(resolvedCalls).toEqual(['resolved']);+ expect(modeWrites).toEqual(['full']);cleanup();- writerCalls.length = 0;- resolvedCalls.length = 0;- await renderDialog(() => resolvedCalls.push('resolved'));+ modeWrites.length = 0;+ await renderDialog('follow');+ await userEvent.click(screen.getByRole('button', { name: 'Enable Follow' }));+ expect(modeWrites).toEqual(['follow']);+ });++ test('Keep disabled writes mode off in either variant', async () => {+ const modeWrites: SyncMode[] = [];+ writer = (mode) => {+ modeWrites.push(mode);+ return { ok: true };+ };+ await renderDialog('follow');await userEvent.click(screen.getByRole('button', { name: 'Keep disabled' }));+ expect(modeWrites).toEqual(['off']);+ });++ test('disables both choices until the project-local sync writer is ready', async () => {+ writer = null;+ await renderDialog('follow');- expect(writerCalls).toEqual([false]);- expect(resolvedCalls).toEqual(['resolved']);+ expect(+ (screen.getByRole('button', { name: 'Enable Follow' }) as HTMLButtonElement).disabled,+ ).toBe(true);+ expect(+ (screen.getByRole('button', { name: 'Keep disabled' }) as HTMLButtonElement).disabled,+ ).toBe(true);});test('surfaces writer failures without resolving the dialog', async () => {const resolvedCalls: string[] = [];writer = () => ({ ok: false, error: 'binding unavailable' });- await renderDialog(() => resolvedCalls.push('resolved'));+ await renderDialog('full', () => resolvedCalls.push('resolved'));await userEvent.click(screen.getByRole('button', { name: 'Enable auto-sync' }));@@ -107,7 +128,7 @@ describe('AutoSyncOnboardingDialog runtime behavior', () => {test('Escape does not resolve the non-dismissible prompt', async () => {const resolvedCalls: string[] = [];writer = () => ({ ok: true });- await renderDialog(() => resolvedCalls.push('resolved'));+ await renderDialog('full', () => resolvedCalls.push('resolved'));await userEvent.keyboard('{Escape}');await waitFor(() => {diff --git a/packages/app/src/components/AutoSyncOnboardingDialog.tsx b/packages/app/src/components/AutoSyncOnboardingDialog.tsxindex 695f68a6c..0318cdbbb 100644--- a/packages/app/src/components/AutoSyncOnboardingDialog.tsx+++ b/packages/app/src/components/AutoSyncOnboardingDialog.tsx@@ -1,11 +1,13 @@/**- * AutoSyncOnboardingDialog — first-run prompt explaining git auto-sync.+ * AutoSyncOnboardingDialog — first-run prompt explaining git sync.*- * Shown once per project when the sync engine reports a remote exists AND- * the project-local config field `autoSync.enabled` has not been set- * (`=== null`). Both buttons write through the project-local ConfigBinding- * so the choice flows down the standard Y.Text → persistence-hook →- * file-watcher → SyncEngine pipeline.+ * Shown once per project when the sync engine reports a remote exists AND this+ * machine has not chosen a sync mode. `resolveAutoSyncOnboarding` decides+ * whether to show it and which `variant` to pass: 'full' (bidirectional, the+ * push-capable prompt) or 'pull' (one-directional, for a push-denied follower).+ * Both buttons write `autoSync.mode` through the project-local ConfigBinding so+ * the choice flows down the standard Y.Text → persistence-hook → file-watcher →+ * SyncEngine pipeline.*/import { Trans, useLingui } from '@lingui/react/macro';import { toast } from 'sonner';@@ -13,6 +15,7 @@ import {AutoSyncEnableDialogIntro,AutoSyncEnableWarning,} from '@/components/AutoSyncEnableWarning';+import type { AutoSyncOnboardingVariant } from '@/components/auto-sync-onboarding-gate';import { Button } from '@/components/ui/button';import {DialogBody,@@ -21,23 +24,28 @@ import {DialogHeader,Dialog as DialogRoot,} from '@/components/ui/dialog';-import { useSyncEnabledWriter } from '@/hooks/use-enable-sync-with-confirm';+import { useSyncModeWriter } from '@/hooks/use-enable-sync-with-confirm';interface AutoSyncOnboardingDialogProps {open: boolean;+ variant: AutoSyncOnboardingVariant;onResolved: () => void;}-export function AutoSyncOnboardingDialog({ open, onResolved }: AutoSyncOnboardingDialogProps) {+export function AutoSyncOnboardingDialog({+ open,+ variant,+ onResolved,+}: AutoSyncOnboardingDialogProps) {const { t } = useLingui();- const writer = useSyncEnabledWriter();+ const writer = useSyncModeWriter();function persistChoice(enabled: boolean): void {if (writer === null) {toast.error(t`Sync settings not yet loaded — try again in a moment`);return;}- const result = writer(enabled);+ const result = writer(enabled ? (variant === 'follow' ? 'follow' : 'full') : 'off');if (!result.ok) {const detail = result.error;toast.error(@@ -60,14 +68,14 @@ export function AutoSyncOnboardingDialog({ open, onResolved }: AutoSyncOnboardin><DialogContent className="sm:max-w-lg" showCloseButton={false}><DialogHeader>- <AutoSyncEnableDialogIntro />+ <AutoSyncEnableDialogIntro variant={variant} /></DialogHeader><DialogBody>- <AutoSyncEnableWarning />+ <AutoSyncEnableWarning variant={variant} /><p className="mt-3 text-1sm text-muted-foreground"><Trans>- You can turn this on later in <span className="font-medium">Settings → Sync</span>.+ You can change this later in <span className="font-medium">Settings → Sync</span>.</Trans></p></DialogBody>@@ -82,7 +90,7 @@ export function AutoSyncOnboardingDialog({ open, onResolved }: AutoSyncOnboardin<Trans>Keep disabled</Trans></Button><Button onClick={() => persistChoice(true)} disabled={writer === null}>- <Trans>Enable auto-sync</Trans>+ {variant === 'follow' ? <Trans>Enable Follow</Trans> : <Trans>Enable auto-sync</Trans>}</Button></DialogFooter></DialogContent>diff --git a/packages/app/src/components/EditorPane.dom.test.tsx b/packages/app/src/components/EditorPane.dom.test.tsxindex c220fdaf1..ccc17f229 100644--- a/packages/app/src/components/EditorPane.dom.test.tsx+++ b/packages/app/src/components/EditorPane.dom.test.tsx@@ -68,11 +68,12 @@ let projectLocalSynced = false;let projectSynced = false;let projectLocalConfig: { autoSync?: { enabled?: boolean | null } } | null = null;let projectConfig: { autoSync?: { default?: boolean | null } } | null = null;+let pushPermissionCheckStatus: 'allowed' | 'denied' | 'unknown' | undefined = 'allowed';vi.doMock('@/hooks/use-git-sync-status', () => ({useGitSyncStatus: () => ({hasRemote,- pushPermission: { checkStatus: 'allowed' },+ pushPermission: { checkStatus: pushPermissionCheckStatus },}),}));@@ -163,11 +164,20 @@ vi.doMock('@/editor/components/TagDialog', () => ({}));vi.doMock('./AutoSyncOnboardingDialog', () => ({- AutoSyncOnboardingDialog: ({ open, onResolved }: { open: boolean; onResolved: () => void }) => (+ AutoSyncOnboardingDialog: ({+ open,+ variant,+ onResolved,+ }: {+ open: boolean;+ variant: string;+ onResolved: () => void;+ }) => (<buttontype="button"data-testid="auto-sync-onboarding"data-open={String(open)}+ data-variant={variant}onClick={onResolved}>Auto sync onboarding@@ -192,6 +202,7 @@ describe('EditorPane auto-sync onboarding gate', () => {projectSynced = false;projectLocalConfig = null;projectConfig = null;+ pushPermissionCheckStatus = 'allowed';});test('exports the EditorPane component', async () => {@@ -211,6 +222,21 @@ describe('EditorPane auto-sync onboarding gate', () => {expect(screen.getByTestId('auto-sync-onboarding').getAttribute('data-open')).toBe('true');});+ test('opens when autoSync carries neither a mode nor a legacy enabled value', async () => {+ hasRemote = true;+ projectSynced = true;+ projectLocalSynced = true;+ // Neither key set → the resolved local mode is null (unanswered), so the+ // prompt fires — the mode resolver treats absent the same as the null+ // sentinel, unlike the old literal `enabled === null` check.+ projectLocalConfig = { autoSync: {} };+ projectConfig = { autoSync: { default: null } };++ await renderEditorPane();++ expect(screen.getByTestId('auto-sync-onboarding').getAttribute('data-open')).toBe('true');+ });+test.each([// label, hasRemote, projectSynced, projectLocalSynced, projectLocalConfig, projectConfig[@@ -254,14 +280,6 @@ describe('EditorPane auto-sync onboarding gate', () => {{ autoSync: { enabled: false } },{ autoSync: { default: null } },],- [- 'enabled undefined is not the unanswered sentinel',- true,- true,- true,- { autoSync: {} },- { autoSync: { default: null } },- ],['committed default off suppresses the prompt',true,@@ -290,6 +308,34 @@ describe('EditorPane auto-sync onboarding gate', () => {expect(screen.getByTestId('auto-sync-onboarding').getAttribute('data-open')).toBe('false');});+ test('a denied push probe opens the pull-only variant', async () => {+ hasRemote = true;+ projectSynced = true;+ projectLocalSynced = true;+ projectLocalConfig = { autoSync: { enabled: null } };+ projectConfig = { autoSync: { default: null } };+ pushPermissionCheckStatus = 'denied';++ await renderEditorPane();++ const dialog = screen.getByTestId('auto-sync-onboarding');+ expect(dialog.getAttribute('data-open')).toBe('true');+ expect(dialog.getAttribute('data-variant')).toBe('follow');+ });++ test('an unknown push probe keeps the prompt closed', async () => {+ hasRemote = true;+ projectSynced = true;+ projectLocalSynced = true;+ projectLocalConfig = { autoSync: { enabled: null } };+ projectConfig = { autoSync: { default: null } };+ pushPermissionCheckStatus = 'unknown';++ await renderEditorPane();++ expect(screen.getByTestId('auto-sync-onboarding').getAttribute('data-open')).toBe('false');+ });+test('resolved onboarding dismisses the dialog in the same render path', async () => {hasRemote = true;projectSynced = true;diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsxindex 24ef9323c..a2296b535 100644--- a/packages/app/src/components/EditorPane.tsx+++ b/packages/app/src/components/EditorPane.tsx@@ -25,7 +25,7 @@ import { loadStickyAgent } from '@/lib/unified-agent-store';import { setViewMenuState } from '@/lib/view-menu-state-store';import { AuthModal } from './AuthModal';import { AutoSyncOnboardingDialog } from './AutoSyncOnboardingDialog';-import { shouldShowAutoSyncOnboarding } from './auto-sync-onboarding-gate';+import { resolveAutoSyncOnboarding } from './auto-sync-onboarding-gate';import { type PanelTab, TABS } from './DocPanel';import { EditorArea, type TerminalPlacement } from './EditorArea';import { EditorHeader } from './EditorHeader';@@ -223,9 +223,10 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {const { activeDocName } = useDocumentContext();// Onboarding modal: open once per machine per project when every gate- // input aligns. Decision logic lives in `shouldShowAutoSyncOnboarding`- // so each input has its own row in the helper's truth table.- const showAutoSyncOnboarding = shouldShowAutoSyncOnboarding({+ // input aligns. Decision logic lives in `resolveAutoSyncOnboarding`, which+ // also forks the prompt variant on the push-permission probe (denied →+ // pull-only), so each input has its own row in the helper's truth table.+ const autoSyncOnboardingVariant = resolveAutoSyncOnboarding({autoSyncOnboardingDismissed,hasRemote: syncStatus?.hasRemote,projectLocalSynced,@@ -557,7 +558,8 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {}}/><AutoSyncOnboardingDialog- open={showAutoSyncOnboarding}+ open={autoSyncOnboardingVariant !== null}+ variant={autoSyncOnboardingVariant ?? 'full'}onResolved={() => setAutoSyncOnboardingDismissed(true)}/><TagDialog />diff --git a/packages/app/src/components/EnableSyncConfirmDialog.dom.test.tsx b/packages/app/src/components/EnableSyncConfirmDialog.dom.test.tsxnew file mode 100644index 000000000..124942ccd--- /dev/null+++ b/packages/app/src/components/EnableSyncConfirmDialog.dom.test.tsx@@ -0,0 +1,73 @@+import * as actualLinguiMacro from '@lingui/react/macro';+import { cleanup, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import type { ReactNode } from 'react';+import { afterEach, describe, expect, test, vi } from 'vitest';++vi.doMock('@lingui/react/macro', () => ({+ ...actualLinguiMacro,+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,+ Plural: ({ value, one, other }: { value: number; one: string; other: string }) => (+ <>{(value === 1 ? one : other).replace('#', String(value))}</>+ ),+}));++async function renderDialog(props: {+ variant?: 'full' | 'pull';+ strandedCommitCount?: number;+ onConfirm?: () => void;+ onOpenChange?: (open: boolean) => void;+}) {+ const { EnableSyncConfirmDialog } = await import('./EnableSyncConfirmDialog');+ render(+ <EnableSyncConfirmDialog+ open={true}+ onOpenChange={props.onOpenChange ?? (() => {})}+ onConfirm={props.onConfirm ?? (() => {})}+ variant={props.variant}+ strandedCommitCount={props.strandedCommitCount}+ />,+ );+}++describe('EnableSyncConfirmDialog', () => {+ afterEach(() => cleanup());++ test('full variant (default) shows the bidirectional warning and no stranded disclosure', async () => {+ await renderDialog({ strandedCommitCount: 3 });+ expect(screen.getByRole('button', { name: 'Enable auto-sync' })).not.toBeNull();+ const note = screen.getByRole('note').textContent ?? '';+ expect(note).toContain('Commits happen automatically');+ // Stranded disclosure is pull-only; a full enable pushes the commits, so it+ // must not appear even when a count is passed.+ expect(screen.queryByText(/stay on this computer/i)).toBeNull();+ });++ test('pull variant shows the one-directional warning', async () => {+ await renderDialog({ variant: 'follow' });+ expect(screen.getByRole('button', { name: 'Enable Follow' })).not.toBeNull();+ expect(screen.getByRole('note').textContent ?? '').toContain('Updates flow in');+ expect(screen.queryByText(/haven't shared/i)).toBeNull();+ });++ test('pull variant discloses stranded commits (plural)', async () => {+ await renderDialog({ variant: 'follow', strandedCommitCount: 2 });+ expect(+ screen.getByText("You have 2 changes you haven't shared. They will stay on this computer."),+ ).not.toBeNull();+ });++ test('pull variant discloses stranded commits (singular)', async () => {+ await renderDialog({ variant: 'follow', strandedCommitCount: 1 });+ expect(+ screen.getByText("You have 1 change you haven't shared. It will stay on this computer."),+ ).not.toBeNull();+ });++ test('confirm fires the callback', async () => {+ const confirms: string[] = [];+ await renderDialog({ variant: 'follow', onConfirm: () => confirms.push('ok') });+ await userEvent.click(screen.getByRole('button', { name: 'Enable Follow' }));+ expect(confirms).toEqual(['ok']);+ });+});diff --git a/packages/app/src/components/EnableSyncConfirmDialog.tsx b/packages/app/src/components/EnableSyncConfirmDialog.tsxindex da6ef488d..64cab2ec5 100644--- a/packages/app/src/components/EnableSyncConfirmDialog.tsx+++ b/packages/app/src/components/EnableSyncConfirmDialog.tsx@@ -1,16 +1,21 @@/**- * EnableSyncConfirmDialog — guards every off → on transition of the git- * auto-sync toggle (the SyncStatusBadge popover Switch + the SettingsDialog- * Sync section).+ * EnableSyncConfirmDialog — guards every off → on transition of the git sync+ * toggle (the SyncStatusBadge popover Switch + the SettingsDialog Sync section)+ * and the full → follow downgrade.** Off → on is the dangerous direction (push to remote, pull may overwrite- * local). On → off is safe and skips this dialog.+ * local). On → off is safe and skips this dialog. `variant` selects the copy:+ * 'full' (default) keeps today's bidirectional warning; 'follow' explains+ * one-directional sync. When switching an already-synced project down to+ * follow leaves unpushed local commits behind, `strandedCommitCount` drives+ * the one-sentence disclosure that those changes stay local.*/-import { Trans } from '@lingui/react/macro';+import { Plural, Trans } from '@lingui/react/macro';import {AutoSyncEnableDialogIntro,AutoSyncEnableWarning,} from '@/components/AutoSyncEnableWarning';+import type { AutoSyncOnboardingVariant } from '@/components/auto-sync-onboarding-gate';import { Button } from '@/components/ui/button';import {DialogBody,@@ -25,21 +30,36 @@ interface EnableSyncConfirmDialogProps {open: boolean;onOpenChange: (open: boolean) => void;onConfirm: () => void;+ variant?: AutoSyncOnboardingVariant;+ /** Unpushed local commits that switching to follow will strand locally. */+ strandedCommitCount?: number;}export function EnableSyncConfirmDialog({open,onOpenChange,onConfirm,+ variant = 'full',+ strandedCommitCount = 0,}: EnableSyncConfirmDialogProps) {+ const showStrandedDisclosure = variant === 'follow' && strandedCommitCount > 0;return (<DialogRoot open={open} onOpenChange={onOpenChange}><DialogContent className="sm:max-w-lg"><DialogHeader>- <AutoSyncEnableDialogIntro />+ <AutoSyncEnableDialogIntro variant={variant} /></DialogHeader><DialogBody>- <AutoSyncEnableWarning />+ <AutoSyncEnableWarning variant={variant} />+ {showStrandedDisclosure && (+ <p className="mt-4 text-sm text-muted-foreground">+ <Plural+ value={strandedCommitCount}+ one="You have 1 change you haven't shared. It will stay on this computer."+ other="You have # changes you haven't shared. They will stay on this computer."+ />+ </p>+ )}</DialogBody><DialogFooter><DialogClose asChild>@@ -48,7 +68,7 @@ export function EnableSyncConfirmDialog({</Button></DialogClose><Button onClick={onConfirm}>- <Trans>Enable auto-sync</Trans>+ {variant === 'follow' ? <Trans>Enable Follow</Trans> : <Trans>Enable auto-sync</Trans>}</Button></DialogFooter></DialogContent>diff --git a/packages/app/src/components/SyncStatusBadge.dom.test.tsx b/packages/app/src/components/SyncStatusBadge.dom.test.tsxindex 33fbc98fb..77db0bc3c 100644--- a/packages/app/src/components/SyncStatusBadge.dom.test.tsx+++ b/packages/app/src/components/SyncStatusBadge.dom.test.tsx@@ -26,7 +26,13 @@ vi.doMock('@lingui/react/macro', () => ({let status: GitSyncStatus | null = null;let fetchError: 'network' | 'server' | null = null;-let projectLocalConfig: { autoSync?: { enabled?: boolean | null } } | null = {+let projectLocalConfig: {+ autoSync?: {+ enabled?: boolean | null;+ mode?: 'off' | 'follow' | 'full' | null;+ resumeMode?: 'follow' | 'full';+ };+} | null = {autoSync: { enabled: false },};let projectLocalSynced = true;@@ -183,6 +189,58 @@ describe('SyncStatusBadge helper behavior', () => {);expect(shouldOfferSignInAgain(undefined)).toBe(false);});++ test('a pull-only toggle stays enabled even when push is denied', async () => {+ const { shouldDisableSyncSwitch } = await import('./SyncStatusBadge');++ // Pull-only never pushes, so a denied probe is irrelevant to its toggle.+ expect(shouldDisableSyncSwitch(true, 'denied', 'follow')).toBe(false);+ // Off/full still gate on denial — enabling there reaches push-requiring full sync.+ expect(shouldDisableSyncSwitch(true, 'denied', 'off')).toBe(true);+ expect(shouldDisableSyncSwitch(true, 'denied', 'full')).toBe(true);+ // Cold start (project-local config not yet synced) disables regardless of mode.+ expect(shouldDisableSyncSwitch(false, 'allowed', 'follow')).toBe(true);+ });++ test('displayState promotes a pull-only idle-with-conflicts project to conflict', async () => {+ const { displayState } = await import('./SyncStatusBadge');++ expect(+ displayState({ ...baseStatus, syncMode: 'follow', state: 'idle', conflictCount: 1 }),+ ).toBe('conflict');+ // No conflicts, or full sync, leaves the state untouched (full sets 'conflict' itself).+ expect(+ displayState({ ...baseStatus, syncMode: 'follow', state: 'idle', conflictCount: 0 }),+ ).toBe('idle');+ expect(displayState({ ...baseStatus, syncMode: 'full', state: 'idle', conflictCount: 1 })).toBe(+ 'idle',+ );+ expect(+ displayState({ ...baseStatus, syncMode: 'follow', state: 'pulling', conflictCount: 1 }),+ ).toBe('pulling');+ });++ test('tooltipLabel frames a following project as up to date, never "Sync off"', async () => {+ const { tooltipLabel } = await import('./SyncStatusBadge');+ const following = { ...baseStatus, syncMode: 'follow' as const };++ expect(tooltipLabel({ ...following, state: 'idle', behind: 0 })).toBe('Up to date');+ expect(tooltipLabel({ ...following, state: 'idle', behind: 3 })).toBe('3 behind');+ expect(tooltipLabel({ ...following, state: 'pulling' })).toBe('Updating');+ expect(tooltipLabel({ ...following, state: 'idle', conflictCount: 2 })).toBe('2 conflicts');+ // Even a following payload that arrives with syncEnabled false is never "Sync off".+ expect(tooltipLabel({ ...following, state: 'idle', syncEnabled: false })).toBe('Up to date');+ // Full sync is unchanged.+ expect(tooltipLabel({ ...baseStatus, state: 'idle' })).toBe('Synced');+ expect(tooltipLabel({ ...baseStatus, state: 'idle', syncEnabled: false })).toBe('Sync off');+ });++ test('formatPausedReason explains a pull-only divergence in plain language', async () => {+ const { formatPausedReason } = await import('./SyncStatusBadge');+ expect(formatPausedReason('diverged-local-commits')).toBe(+ 'Local commits are keeping this copy from updating',+ );+ });});describe('SyncStatusBadge runtime behavior', () => {@@ -234,6 +292,24 @@ describe('SyncStatusBadge runtime behavior', () => {expect(screen.getByRole('button', { name: /Sync status:/ })).toBeTruthy();});+ test('stays visible while a resume is in flight (config active, server still disabled)', async () => {+ // Resuming from paused flips the local config mode 'off'→active optimistically+ // (so `paused` clears) while the server status still lags at disabled/off. The+ // badge must stay mounted in that window — unmounting closes the popover and+ // flickers the icon (the user toggles on, the popover vanishes, then returns).+ projectLocalConfig = { autoSync: { mode: 'follow' } };+ status = {+ ...baseStatus,+ state: 'disabled',+ syncEnabled: false,+ syncMode: 'off',+ pausedReason: undefined,+ } as GitSyncStatus;+ await renderBadge();++ expect(screen.getByRole('button', { name: /Sync status:/ })).toBeTruthy();+ });+test('paused disabled state opens details explaining why sync stopped', async () => {status = {...baseStatus,@@ -247,13 +323,13 @@ describe('SyncStatusBadge runtime behavior', () => {expect(screen.getByText('Protected branch — cannot push')).toBeTruthy();});- test('popover switch checked state reads local config, not server syncEnabled', async () => {+ test('popover switch is on (Pause sync) when a mode is active', async () => {status = { ...baseStatus, state: 'idle', syncEnabled: false };projectLocalConfig = { autoSync: { enabled: true } };await renderBadge();await openPopover();- const toggle = screen.getByRole('switch', { name: 'Disable sync' });+ const toggle = screen.getByRole('switch', { name: 'Pause sync' });expect(toggle.getAttribute('aria-checked')).toBe('true');});@@ -264,20 +340,182 @@ describe('SyncStatusBadge runtime behavior', () => {await renderBadge();await openPopover();- const toggle = screen.getByRole('switch', { name: 'Enable sync' }) as HTMLButtonElement;+ const toggle = screen.getByRole('switch', { name: 'Resume sync' }) as HTMLButtonElement;expect(toggle.disabled).toBe(true);});- test('off to on opens confirmation before patching project-local config', async () => {+ test('resuming from off opens confirmation before patching (defaults to full)', async () => {status = { ...baseStatus, state: 'idle', syncEnabled: false };projectLocalConfig = { autoSync: { enabled: false } };await renderBadge();await openPopover();- await userEvent.click(screen.getByRole('switch', { name: 'Enable sync' }));+ await userEvent.click(screen.getByRole('switch', { name: 'Resume sync' }));expect(patches).toEqual([]);+ // Resuming a never-enabled project defaults to full sync (which pushes), so+ // it confirms; the write clears the resume memory.await userEvent.click(screen.getByRole('button', { name: 'Enable auto-sync' }));- expect(patches).toEqual([{ autoSync: { enabled: true } }]);+ expect(patches).toEqual([{ autoSync: { mode: 'full', enabled: null, resumeMode: null } }]);+ });++ test.each([+ ['idle', { state: 'idle' }, 'Sync status: Up to date'],+ ['pulling', { state: 'pulling' }, 'Sync status: Updating'],+ ['fetching', { state: 'fetching' }, 'Sync status: Checking for updates'],+ ['offline', { state: 'offline' }, 'Sync status: Offline'],+ ['auth-error', { state: 'auth-error' }, 'Sync status: Reconnect required'],+ ] as const)('pull-only %s renders a distinct following badge', async (_label, override, ariaName) => {+ status = { ...baseStatus, syncMode: 'follow', ...override } as GitSyncStatus;+ await renderBadge();++ expect(screen.getByRole('button', { name: ariaName })).toBeTruthy();+ });++ test('pull-only conflict surfaces on the badge even though the engine stays idle', async () => {+ // Pull-only holds the engine idle while a same-line collision waits in the+ // ledger; the badge promotes conflictCount to the conflict rendering.+ status = {+ ...baseStatus,+ syncMode: 'follow',+ state: 'idle',+ conflictCount: 1,+ } as GitSyncStatus;+ await renderBadge();++ expect(screen.getByRole('button', { name: 'Sync status: Conflict' })).toBeTruthy();+ expect(screen.getByText('1')).toBeTruthy();+ });++ test('pull-only stays visible even in a disabled-without-reason payload', async () => {+ // The engine never parks a pull-only project here, but the hide rule must+ // exempt following projects so one is never silently hidden.+ status = {+ ...baseStatus,+ syncMode: 'follow',+ state: 'disabled',+ pausedReason: undefined,+ } as GitSyncStatus;+ await renderBadge();++ expect(screen.getByRole('button', { name: /Sync status:/ })).toBeTruthy();+ });++ test('following popover shows the follow state, not "sync off", with a Sync action', async () => {+ status = { ...baseStatus, syncMode: 'follow', state: 'idle' } as GitSyncStatus;+ projectLocalConfig = { autoSync: { mode: 'follow' } };+ await renderBadge();+ await openPopover();++ const toggle = screen.getByRole('switch', { name: 'Pause sync' });+ expect(toggle.getAttribute('aria-checked')).toBe('true');+ expect(screen.queryByText(/Sync is off/)).toBeNull();+ expect(screen.getByRole('button', { name: 'Sync' })).toBeTruthy();+ });++ test('following popover keeps the Switch reachable when push is denied', async () => {+ status = {+ ...baseStatus,+ syncMode: 'follow',+ state: 'idle',+ pushPermission: { checkStatus: 'denied' },+ } as GitSyncStatus;+ projectLocalConfig = { autoSync: { mode: 'follow' } };+ await renderBadge();+ await openPopover();++ const toggle = screen.getByRole('switch', { name: 'Pause sync' }) as HTMLButtonElement;+ expect(toggle.disabled).toBe(false);+ });++ test('following popover states the mode instead of the push-permission verdict', async () => {+ status = {+ ...baseStatus,+ syncMode: 'follow',+ state: 'idle',+ pushPermission: { checkStatus: 'denied', deniedReason: 'no-collaborator' },+ } as GitSyncStatus;+ projectLocalConfig = { autoSync: { mode: 'follow' } };+ await renderBadge();+ await openPopover();++ expect(screen.getByTestId('sync-popover-mode-line').textContent).toContain('Follow');+ expect(screen.queryByText(/don't have permission to push/)).toBeNull();+ // A genuine read-only user cannot choose Full, so the mode toggle is hidden.+ expect(screen.queryByTestId('sync-popover-mode-toggle')).toBeNull();+ });++ test('pull-only popover suppresses the signed-out reconnect line (push-framed)', async () => {+ status = {+ ...baseStatus,+ syncMode: 'follow',+ state: 'idle',+ pushPermission: { checkStatus: 'denied', deniedReason: 'not-authenticated' },+ } as GitSyncStatus;+ projectLocalConfig = { autoSync: { mode: 'follow' } };+ await renderBadge();+ await openPopover();++ expect(screen.queryByText(/signed out — sign in to resume syncing/)).toBeNull();+ expect(screen.getByTestId('sync-popover-mode-line')).toBeTruthy();+ });++ test('a paused (was-enabled) project stays visible and shows the paused popover', async () => {+ // Engine reports a paused project as disabled; the config (resumeMode set)+ // keeps the badge visible and drives the paused rendering.+ status = {+ ...baseStatus,+ state: 'disabled',+ syncMode: 'off',+ pausedReason: undefined,+ syncEnabled: false,+ } as GitSyncStatus;+ projectLocalConfig = { autoSync: { mode: 'off', resumeMode: 'full' } };+ await renderBadge();++ // Not hidden (the disabled-hide rule exempts a paused project).+ expect(screen.getByRole('button', { name: 'Sync status: Sync paused' })).toBeTruthy();+ await openPopover();++ expect(screen.getByTestId('sync-popover-paused-line')).toBeTruthy();+ // Switch is off (resume), and a manual Sync is still offered (ever enabled).+ expect(screen.getByRole('switch', { name: 'Resume sync' }).getAttribute('aria-checked')).toBe(+ 'false',+ );+ expect(screen.getByRole('button', { name: 'Sync' })).toBeTruthy();+ // The mode is still editable while paused (push-capable user).+ expect(screen.getByTestId('sync-popover-mode-toggle')).toBeTruthy();+ });++ test('changing the mode while paused only updates the resume memory (no sync)', async () => {+ status = {+ ...baseStatus,+ state: 'disabled',+ syncMode: 'off',+ syncEnabled: false,+ } as GitSyncStatus;+ projectLocalConfig = { autoSync: { mode: 'off', resumeMode: 'full' } };+ await renderBadge();+ await openPopover();++ // Flip Full → Follow while paused: writes resumeMode only, mode stays off,+ // no confirmation (nothing syncs until the Switch is turned on).+ await userEvent.click(screen.getByTestId('sync-popover-mode-follow'));+ expect(patches).toEqual([{ autoSync: { resumeMode: 'follow' } }]);+ });++ test('the manual Sync action is hidden for a never-enabled project', async () => {+ // Off with no resume memory = never enabled → no manual Sync affordance.+ status = {+ ...baseStatus,+ state: 'dormant',+ syncMode: 'off',+ syncEnabled: false,+ } as GitSyncStatus;+ projectLocalConfig = { autoSync: { mode: 'off' } };+ await renderBadge();+ await openPopover();++ expect(screen.queryByRole('button', { name: 'Sync' })).toBeNull();});});diff --git a/packages/app/src/components/SyncStatusBadge.tsx b/packages/app/src/components/SyncStatusBadge.tsxindex 88f06b699..fce99831b 100644--- a/packages/app/src/components/SyncStatusBadge.tsx+++ b/packages/app/src/components/SyncStatusBadge.tsx@@ -7,7 +7,14 @@* Click opens a popover with last-sync details and action buttons.*/-import type { PushPermissionWire, SyncErrorCode } from '@inkeep/open-knowledge-core';+import {+ isSyncActiveMode,+ isSyncPaused,+ type PushPermissionWire,+ resolveLocalAutoSyncMode,+ type SyncErrorCode,+ type SyncMode,+} from '@inkeep/open-knowledge-core';import { plural, t } from '@lingui/core/macro';import { Plural, Trans, useLingui } from '@lingui/react/macro';import {@@ -16,14 +23,12 @@ import {Cloud,CloudOff,LogIn,+ Pause,RefreshCw,UserCog,} from 'lucide-react';import { useConflicts } from '@/hooks/use-conflicts';-import {- useEnableSyncWithConfirm,- useSyncEnabledWriter,-} from '@/hooks/use-enable-sync-with-confirm';+import { useBadgeSyncControls } from '@/hooks/use-enable-sync-with-confirm';import type { GitSyncStatus } from '@/hooks/use-git-sync-status';import { useGitSyncStatusDetailed } from '@/hooks/use-git-sync-status';import { useConfigContext } from '@/lib/config-provider';@@ -33,6 +38,7 @@ import { EnableSyncConfirmDialog } from './EnableSyncConfirmDialog';import { Button } from './ui/button';import { Popover, PopoverContent, PopoverTrigger } from './ui/popover';import { Switch } from './ui/switch';+import { ToggleGroup, ToggleGroupItem } from './ui/toggle-group';import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';// ── helpers ──────────────────────────────────────────────────────────────────@@ -42,9 +48,12 @@ import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';* stream drives the visible state, so a rejected trigger (offline / server* down) needs no UI handling — but it gets a breadcrumb rather than being* swallowed silently, so a "Sync now did nothing" report is triageable.+ *+ * A following (pull-only) project uses the `pull` op so the trigger runs the+ * one-directional cycle; full sync uses `sync` (fetch + merge + push).*/-function triggerSyncFromBadge(): void {- triggerSync('sync').catch((err) => {+function triggerSyncFromBadge(op: 'sync' | 'pull' = 'sync'): void {+ triggerSync(op).catch((err) => {console.warn('[sync-badge] manual sync trigger failed',err instanceof Error ? err.message : err,@@ -67,15 +76,41 @@ function formatRelative(iso: string | null): string {return new Date(iso).toLocaleDateString();}+// ── mode-aware state derivation ───────────────────────────────────────────────++/** True when the project follows upstream one-directionally (pull-only). */+function isFollowingMode(status: GitSyncStatus): boolean {+ return status.syncMode === 'follow';+}++/**+ * The state the badge renders. A pull-only engine deliberately holds `idle`+ * while a same-line collision waits in the conflict ledger — that keeps the rest+ * of the repo fast-forwarding, but a following project must still surface the+ * collision, so promote it to `conflict` on the badge. Full sync sets the+ * `conflict` state directly, so this never changes what it renders.+ */+export function displayState(status: GitSyncStatus): GitSyncStatus['state'] {+ if (isFollowingMode(status) && status.state === 'idle' && status.conflictCount > 0) {+ return 'conflict';+ }+ return status.state;+}+// ── inner: icon + color per state ────────────────────────────────────────────interface BadgeIconProps {status: GitSyncStatus;+ /** True when the user paused a previously-enabled project (config-driven). */+ paused?: boolean;}-function BadgeIcon({ status }: BadgeIconProps) {+function BadgeIcon({ status, paused }: BadgeIconProps) {const cls = 'size-3.5';- switch (status.state) {+ // Paused is a config state the engine's `state` can't express (it reads as+ // disabled/dormant), so it wins the icon.+ if (paused) return <Pause className={`${cls} text-muted-foreground`} />;+ switch (displayState(status)) {case 'dormant':// Available: remote exists but sync not yet enabledreturn <Cloud className={`${cls} text-muted-foreground`} />;@@ -104,9 +139,11 @@ function BadgeIcon({ status }: BadgeIconProps) {}function badgeLabel(status: GitSyncStatus): string {- switch (status.state) {+ switch (displayState(status)) {case 'idle':- if (status.ahead > 0) return `↑${status.ahead}`;+ // A following project never pushes, so "ahead" is not an actionable+ // signal — only surface how far behind upstream the copy is.+ if (!isFollowingMode(status) && status.ahead > 0) return `↑${status.ahead}`;if (status.behind > 0) return `↓${status.behind}`;return '';case 'fetching':@@ -126,16 +163,18 @@ function badgeLabel(status: GitSyncStatus): string {// ── popover content ───────────────────────────────────────────────────────────-function stateLabel(state: GitSyncStatus['state']): string {+function stateLabel(state: GitSyncStatus['state'], following = false): string {switch (state) {case 'dormant':return t`No git remote`;case 'idle':- return t`Synced`;+ // A following project tracks upstream one-directionally, so "Synced"+ // (which implies a two-way exchange) would overstate what happened.+ return following ? t`Up to date` : t`Synced`;case 'fetching':- return t`Fetching`;+ return following ? t`Checking for updates` : t`Fetching`;case 'pulling':- return t`Pulling`;+ return following ? t`Updating` : t`Pulling`;case 'pushing':return t`Pushing`;case 'conflict':@@ -161,6 +200,10 @@ export function formatPausedReason(reason: string): string {return t`Resolve conflict in your terminal`;case 'detached-head':return t`Detached HEAD — checkout a branch to resume`;+ case 'diverged-local-commits':+ // Pull-only reaches this when local commits sit ahead of origin: it never+ // pushes or merges to reconcile them, so updates stall until they're gone.+ return t`Local commits are keeping this copy from updating`;case 'auth-error':return t`Reconnect required`;case 'protected-branch':@@ -393,16 +436,37 @@ export function shouldOfferSignInAgain(pushPermission: PushPermissionWire | undeexport function shouldDisableSyncSwitch(projectLocalSynced: boolean | undefined,pushPermissionCheckStatus: 'allowed' | 'denied' | 'unknown' | undefined,+ currentMode?: SyncMode,): boolean {if (!projectLocalSynced) return true;+ // A following (pull-only) project never pushes, so a denied push probe is+ // irrelevant to it — the toggle (whose only action is turning sync off) stays+ // enabled. A denied probe still disables an off/full project, where enabling+ // reaches the push-requiring full mode.+ if (currentMode === 'follow') return false;if (pushPermissionCheckStatus === 'denied') return true;return false;}-function tooltipLabel(status: GitSyncStatus): string {- if (!status.syncEnabled) return t`Sync off`;- if (status.state === 'idle') {+export function tooltipLabel(status: GitSyncStatus, paused = false): string {+ if (paused) return t`Sync paused`;+ const following = isFollowingMode(status);+ // A following project is always on, so it never reads as "Sync off" — that+ // label is reserved for a genuinely disabled (mode off) project.+ if (!status.syncEnabled && !following) return t`Sync off`;+ const state = displayState(status);+ if (state === 'conflict' && status.conflictCount > 0) {+ const { conflictCount } = status;+ return plural(conflictCount, { one: '# conflict', other: '# conflicts' });+ }+ if (state === 'idle') {const { ahead, behind } = status;+ if (following) {+ // "ahead" is not actionable for a project that never pushes; only how far+ // behind upstream it is (before a pull completes) is worth surfacing.+ if (behind > 0) return t`${behind} behind`;+ return t`Up to date`;+ }if (ahead > 0 && behind > 0) {return t`${ahead} ahead, ${behind} behind`;}@@ -410,11 +474,7 @@ function tooltipLabel(status: GitSyncStatus): string {if (behind > 0) return t`${behind} behind`;return t`Synced`;}- if (status.state === 'conflict' && status.conflictCount > 0) {- const { conflictCount } = status;- return plural(conflictCount, { one: '# conflict', other: '# conflicts' });- }- return stateLabel(status.state);+ return stateLabel(state, following);}interface PopoverBodyProps {@@ -425,112 +485,163 @@ interface PopoverBodyProps {function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {const { t } = useLingui();- const { ahead, behind, conflictCount } = status;+ const { behind, conflictCount } = status;const { projectLocalConfig, projectLocalSynced } = useConfigContext();- const enabled = projectLocalConfig?.autoSync?.enabled ?? false;+ const autoSync = projectLocalConfig?.autoSync;+ const {+ active,+ paused,+ everEnabled,+ toggleMode,+ confirmOpen,+ setConfirmOpen,+ pendingMode,+ strandedCommitCount,+ onToggleActive,+ onModeSelect,+ onConfirm,+ } = useBadgeSyncControls(autoSync, status.ahead);+ const localMode = resolveLocalAutoSyncMode(autoSync) ?? 'off';+ // `following` (status-driven) is the ACTIVE pull state; the paused branch is+ // config-driven since the engine reports a paused project as disabled.+ const following = isFollowingMode(status);+ const state = displayState(status);const lastSyncedRelative = formatRelative(status.lastSyncUtc);- const writer = useSyncEnabledWriter();- const { confirmOpen, setConfirmOpen, onToggleRequest, onConfirm } =- useEnableSyncWithConfirm(writer);+ // The Full/Follow control appears only for a user who can actually choose —+ // a genuine read-only collaborator can only follow, so it's hidden for them+ // (a signed-out user may gain push after auth, so they keep it).+ const genuineReadOnly =+ status.pushPermission?.checkStatus === 'denied' &&+ status.pushPermission.deniedReason !== 'not-authenticated';+ const canChooseMode = !genuineReadOnly;// The "Review conflicts" affordance navigates to the first conflicted file// (so the editor-area DiffViewBoundary mounts via the lifecycle observer).- // There is no side-sheet to open — the sidebar Conflicts section is the- // project-level list, the editor-area DiffView is the resolution surface.const { conflicts } = useConflicts();const firstConflict = conflicts[0] ?? null;+ const showConflictButton = !paused && state === 'conflict' && firstConflict !== null;+ const showAuthButton = !paused && state === 'auth-error';+ const showSyncButton =+ everEnabled && !showConflictButton && !showAuthButton && (paused || state !== 'dormant');+ // A manual sync from a full-active project pushes too; every other case+ // (following, or paused) pulls only.+ const manualSyncOp: 'sync' | 'pull' = active && localMode === 'full' ? 'sync' : 'pull';+return (<div className="flex flex-col gap-3.5"><div className="flex items-center justify-between gap-2"><div className="flex items-center gap-2 min-w-0">- <BadgeIcon status={status} />- <span className="text-1sm font-medium truncate">{stateLabel(status.state)}</span>+ <BadgeIcon status={status} paused={paused} />+ <span className="text-1sm font-medium truncate">+ {paused ? t`Sync paused` : stateLabel(state, following)}+ </span></div><Switch- checked={enabled}- disabled={shouldDisableSyncSwitch(projectLocalSynced, status.pushPermission?.checkStatus)}- onCheckedChange={onToggleRequest}- aria-label={- status.pushPermission?.checkStatus === 'denied'- ? t`Sync disabled — you don't have permission to push`- : enabled- ? t`Disable sync`- : t`Enable sync`- }+ checked={active}+ disabled={!projectLocalSynced}+ onCheckedChange={onToggleActive}+ aria-label={active ? t`Pause sync` : t`Resume sync`}/></div><EnableSyncConfirmDialogopen={confirmOpen}onOpenChange={setConfirmOpen}onConfirm={onConfirm}+ variant={pendingMode ?? 'full'}+ strandedCommitCount={strandedCommitCount}/>- {computeSyncErrorLines(status).map((line) => (- <p key={line.key} className="text-xs text-destructive">- {line.direction === 'push' ? (- <>- <span className="font-medium">{t`Push`}: </span>- {line.message}- </>- ) : line.direction === 'pull' ? (- <>- <span className="font-medium">{t`Pull`}: </span>- {line.message}- </>- ) : (- line.message- )}+ {paused ? (+ <p className="text-xs text-muted-foreground" data-testid="sync-popover-paused-line">+ <Trans>Sync is paused. Turn it back on to resume.</Trans></p>- ))}- {shouldOfferReconnect(status.pushPermission) ? (- // Signed-out denial (no credential resolved) — reconnecting resumes- // sync, so offer it here. Takes precedence over the button-less- // `pausedReason`/`denied` branches below, which is exactly the stuck- // state (sync was enabled, then the credential went away). The genuine- // read-only-collaborator denial keeps the button-less copy.- <div className="flex items-start gap-2">- <p className="text-xs text-muted-foreground flex-1 min-w-0">- <Trans>You're signed out — sign in to resume syncing.</Trans>- </p>- {onSignIn && (- <Button variant="outline" size="xs" className="self-start" onClick={onSignIn}>- <Trans>Sign in</Trans>- </Button>- )}- </div>- ) : status.pausedReason ? (- <p className="text-xs text-muted-foreground">{formatPausedReason(status.pausedReason)}</p>- ) : status.pushPermission?.checkStatus === 'denied' ? (- <p className="text-xs text-muted-foreground">- {formatPushPermissionDenied(status.pushPermission.deniedReason)}- </p>- ) : shouldOfferSignInAgain(status.pushPermission) ? (- // Probe-401 branch: surface a "Sign in again" affordance without- // disabling sync — the probe couldn't reach a verdict, so the user's- // existing sync preference is preserved while they re-authenticate.- // The button reuses `onSignIn`, the same handler wired for the- // `auth-error` state below.- <div className="flex items-start gap-2">- <p className="text-xs text-muted-foreground flex-1 min-w-0">- <Trans>Your GitHub session expired — sign in again to verify push access.</Trans>- </p>- {onSignIn && (- <Button variant="outline" size="xs" className="self-start" onClick={onSignIn}>- <Trans>Sign in</Trans>- </Button>- )}- </div>- ) : null}+ ) : (+ <>+ {computeSyncErrorLines(status).map((line) => (+ <p key={line.key} className="text-xs text-destructive">+ {line.direction === 'push' ? (+ <>+ <span className="font-medium">{t`Push`}: </span>+ {line.message}+ </>+ ) : line.direction === 'pull' ? (+ <>+ <span className="font-medium">{t`Pull`}: </span>+ {line.message}+ </>+ ) : (+ line.message+ )}+ </p>+ ))}+ {!following && shouldOfferReconnect(status.pushPermission) ? (+ // Signed-out denial (no credential resolved) — reconnecting resumes+ // sync, so offer it here. Takes precedence over the button-less+ // `pausedReason`/`denied` branches below.+ <div className="flex items-start gap-2">+ <p className="text-xs text-muted-foreground flex-1 min-w-0">+ <Trans>You're signed out — sign in to resume syncing.</Trans>+ </p>+ {onSignIn && (+ <Button variant="outline" size="xs" className="self-start" onClick={onSignIn}>+ <Trans>Sign in</Trans>+ </Button>+ )}+ </div>+ ) : status.pausedReason ? (+ <p className="text-xs text-muted-foreground">+ {formatPausedReason(status.pausedReason)}+ </p>+ ) : following ? (+ // A follower never pushes, so the push-permission verdict is+ // irrelevant — say what the project IS (the mode).+ <p className="text-xs text-muted-foreground" data-testid="sync-popover-mode-line">+ <Trans>+ Follow — updates flow in from your remote; your edits stay on this computer.+ </Trans>+ </p>+ ) : active ? (+ <p className="text-xs text-muted-foreground" data-testid="sync-popover-mode-line">+ <Trans>+ Full sync — your edits are committed and pushed to your remote automatically.+ </Trans>+ </p>+ ) : status.pushPermission?.checkStatus === 'denied' ? (+ <p className="text-xs text-muted-foreground">+ {formatPushPermissionDenied(status.pushPermission.deniedReason)}+ </p>+ ) : shouldOfferSignInAgain(status.pushPermission) ? (+ // Probe-401 branch: surface a "Sign in again" affordance without+ // disabling sync — the probe couldn't reach a verdict.+ <div className="flex items-start gap-2">+ <p className="text-xs text-muted-foreground flex-1 min-w-0">+ <Trans>Your GitHub session expired — sign in again to verify push access.</Trans>+ </p>+ {onSignIn && (+ <Button variant="outline" size="xs" className="self-start" onClick={onSignIn}>+ <Trans>Sign in</Trans>+ </Button>+ )}+ </div>+ ) : null}+ </>+ )}- {status.state === 'conflict' && (+ {!paused && state === 'conflict' && (<p className="text-xs text-amber-700 dark:text-amber-400">- <Trans>Sync paused — resolve conflicts to resume.</Trans>+ {following ? (+ // A follower keeps fast-forwarding the rest of the repo while a single+ // document waits on resolution, so it is never globally "paused".+ <Trans>A document has a conflict — resolve it to keep it up to date.</Trans>+ ) : (+ <Trans>Sync paused — resolve conflicts to resume.</Trans>+ )}</p>)}- <div className="text-xs text-muted-foreground space-y-2">+ <div className="text-xs text-muted-foreground space-y-2 border-t pt-3">{status.remote && (- <div className="flex items-baseline gap-2">+ <div className="flex items-baseline justify-between gap-2"><span className="w-20 shrink-0 font-mono uppercase tracking-wide text-2xs"><Trans>Repository</Trans></span>@@ -550,20 +661,7 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {)}</div>)}- {enabled && status.state !== 'dormant' && (- <div className="flex items-baseline gap-2">- <span className="w-20 shrink-0 font-mono uppercase tracking-wide text-2xs">- <Trans>Last sync</Trans>- </span>- <span className="text-foreground">{lastSyncedRelative}</span>- </div>- )}- {status.ahead > 0 && (- <div>- <Plural value={ahead} one="# commit ahead" other="# commits ahead" />- </div>- )}- {status.behind > 0 && (+ {active && !following && status.behind > 0 && (<div><Plural value={behind} one="# commit behind" other="# commits behind" /></div>@@ -573,14 +671,37 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {<Plural value={conflictCount} one="# file conflicted" other="# files conflicted" /></div>)}- {!enabled && (- <div>- <Trans>Sync is off — your edits will not sync to the remote repository.</Trans>+ {canChooseMode && (+ <div className="flex items-center justify-between gap-2 pt-0.5">+ <span className="w-20 shrink-0 font-mono uppercase tracking-wide text-2xs">+ <Trans>Mode</Trans>+ </span>+ <ToggleGroup+ type="single"+ variant="segmented"+ size="sm"+ spacing={1}+ className="bg-muted p-0.5 data-[size=sm]:rounded-[10px]"+ value={toggleMode}+ onValueChange={(v) => {+ // Radix emits '' on re-press (deselect) — keep exactly one mode.+ if (isSyncActiveMode(v)) onModeSelect(v);+ }}+ aria-label={t`Sync mode`}+ data-testid="sync-popover-mode-toggle"+ >+ <ToggleGroupItem value="full" data-testid="sync-popover-mode-full">+ <Trans>Full</Trans>+ </ToggleGroupItem>+ <ToggleGroupItem value="follow" data-testid="sync-popover-mode-follow">+ <Trans>Follow</Trans>+ </ToggleGroupItem>+ </ToggleGroup></div>)}</div>- {status.identityUnresolved && onSetIdentity && (+ {!paused && status.identityUnresolved && onSetIdentity && (<div className="flex items-start gap-2 rounded-md border border-dashed p-2"><UserCog className="size-3.5 mt-0.5 text-muted-foreground shrink-0" /><div className="flex flex-col gap-1.5 min-w-0">@@ -597,42 +718,55 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {</div>)}- <div className="flex flex-wrap gap-1 pt-1">- {enabled &&- status.state !== 'dormant' &&- status.state !== 'disabled' &&- status.state !== 'auth-error' &&- status.state !== 'conflict' && (- <Button variant="outline" size="xs" onClick={triggerSyncFromBadge}>- <Trans>Sync now</Trans>- </Button>+ {(showSyncButton ||+ showAuthButton ||+ showConflictButton ||+ (active && state !== 'dormant')) && (+ <div className="flex items-center justify-between gap-2 pt-1">+ {active && state !== 'dormant' ? (+ // A follower pulls only, so "Synced" (two-way) would overstate it —+ // it reads "Updated"; full sync reads "Synced".+ <span className="text-xs text-muted-foreground" data-testid="sync-popover-last-sync">+ {following ? t`Updated ${lastSyncedRelative}` : t`Synced ${lastSyncedRelative}`}+ </span>+ ) : (+ <span />)}- {enabled && status.state === 'auth-error' && (- <Button variant="outline" size="xs" onClick={onSignIn}>- <Trans>Sign in</Trans>- </Button>- )}- {enabled && status.state === 'offline' && (- <Button variant="outline" size="xs" onClick={triggerSyncFromBadge}>- <Trans>Retry</Trans>- </Button>- )}- {enabled && status.state === 'conflict' && firstConflict && (- <Button- variant="outline"- size="xs"- onClick={() => {- if (typeof window === 'undefined') return;- const nextHash = hashFromDocName(filePathToDocName(firstConflict.file));- if (window.location.hash !== nextHash) {- window.location.hash = nextHash;- }- }}- >- <Trans>Review conflicts</Trans>- </Button>- )}- </div>+ <div className="flex flex-wrap justify-end gap-1">+ {showSyncButton && (+ // One label for every mode ("Sync"); the op pushes only when full+ // and active, and pulls otherwise (following, or a paused one-shot).+ <Button+ variant="outline"+ size="xs"+ onClick={() => triggerSyncFromBadge(manualSyncOp)}+ >+ <Trans>Sync</Trans>+ </Button>+ )}+ {showAuthButton && (+ <Button variant="outline" size="xs" onClick={onSignIn}>+ <Trans>Sign in</Trans>+ </Button>+ )}+ {showConflictButton && firstConflict && (+ <Button+ variant="outline"+ size="xs"+ onClick={() => {+ if (typeof window === 'undefined') return;+ const nextHash = hashFromDocName(filePathToDocName(firstConflict.file));+ if (window.location.hash !== nextHash) {+ window.location.hash = nextHash;+ }+ }}+ >+ <Trans>Review conflicts</Trans>+ </Button>+ )}+ </div>+ </div>+ )}</div>);}@@ -649,6 +783,17 @@ interface SyncStatusBadgeProps {export function SyncStatusBadge({ onSignIn, onSetIdentity }: SyncStatusBadgeProps = {}) {const { t } = useLingui();const { status, fetchError } = useGitSyncStatusDetailed();+ const { projectLocalConfig } = useConfigContext();+ // Paused = the user turned off a previously-enabled project. It's config-only+ // (the engine reports it as disabled/dormant), so the badge reads it here to+ // stay visible and render the paused icon/label.+ const paused = isSyncPaused(projectLocalConfig?.autoSync);+ // The local config is the source of truth for user intent; the server status+ // lags a resume by a beat. When the config already resolves to an active mode+ // (follow/full) but the engine still reports the pre-resume `disabled`, keep+ // the badge visible so the resume doesn't unmount it — unmounting closes the+ // popover and flickers the icon until the status catches up.+ const localWantsSync = isSyncActiveMode(resolveLocalAutoSyncMode(projectLocalConfig?.autoSync));// Surface a lightweight connectivity warning when the server has been// reachable before (we have a prior status) but the last refresh failed.@@ -692,11 +837,24 @@ export function SyncStatusBadge({ onSignIn, onSetIdentity }: SyncStatusBadgeProp// protected-branch) so the user can see *why* sync stopped — without it,// the only signal would be a missing badge. Manual disable clears// `pausedReason`; auto-disable sets it. (Unsafe states like auth-error /- // conflict / offline already render — they need attention.)- if (status.state === 'disabled' && !status.pausedReason) return null;+ // conflict / offline already render — they need attention.) A following+ // (pull-only) project is always on, so it must always show its state.+ // A paused project (config: was enabled, now off) stays visible so the user+ // isn't stranded in Settings to resume — the engine reports it as disabled.+ if (+ status.state === 'disabled' &&+ !status.pausedReason &&+ status.syncMode !== 'follow' &&+ !paused &&+ !localWantsSync+ ) {+ return null;+ }- const label = badgeLabel(status);- const syncStateLabel = stateLabel(status.state);+ const label = paused ? '' : badgeLabel(status);+ const syncStateLabel = paused+ ? t`Sync paused`+ : stateLabel(displayState(status), isFollowingMode(status));const showIdentityDot = Boolean(status.identityUnresolved);return (@@ -714,7 +872,7 @@ export function SyncStatusBadge({ onSignIn, onSetIdentity }: SyncStatusBadgeProp: t`Sync status: ${syncStateLabel}`}>- <BadgeIcon status={status} />+ <BadgeIcon status={status} paused={paused} />{label && (<span className="absolute -top-0.5 -right-0.5 text-[9px] leading-none font-medium bg-background border rounded-full px-0.5">{label}@@ -729,9 +887,9 @@ export function SyncStatusBadge({ onSignIn, onSetIdentity }: SyncStatusBadgeProp</Button></PopoverTrigger></TooltipTrigger>- <TooltipContent>{tooltipLabel(status)}</TooltipContent>+ <TooltipContent>{tooltipLabel(status, paused)}</TooltipContent></Tooltip>- <PopoverContent align="end" className="w-64 p-3">+ <PopoverContent align="end" className="w-80 p-3"><PopoverBody status={status} onSignIn={onSignIn} onSetIdentity={onSetIdentity} /></PopoverContent></Popover>diff --git a/packages/app/src/components/auto-sync-onboarding-gate.test.ts b/packages/app/src/components/auto-sync-onboarding-gate.test.tsindex 54b75f8c9..160cfefec 100644--- a/packages/app/src/components/auto-sync-onboarding-gate.test.ts+++ b/packages/app/src/components/auto-sync-onboarding-gate.test.ts@@ -1,110 +1,122 @@import { describe, expect, test } from 'vitest';import {type AutoSyncOnboardingGateInputs,- shouldShowAutoSyncOnboarding,+ resolveAutoSyncOnboarding,} from './auto-sync-onboarding-gate.ts';-// Baseline = every condition aligned so the modal SHOWS. Each test flips one-// input and asserts the gate's response, keeping every condition on its own-// independently verifiable row.+// Baseline = every condition aligned so the modal SHOWS the full-sync variant+// (probe allowed). Each test flips one input and asserts the gate's response,+// keeping every condition on its own independently verifiable row.const SHOWING: AutoSyncOnboardingGateInputs = {autoSyncOnboardingDismissed: false,hasRemote: true,projectLocalSynced: true,projectSynced: true,- projectLocalConfig: { autoSync: { enabled: null } },+ projectLocalConfig: { autoSync: { mode: null, enabled: null } },projectConfig: { autoSync: { default: null } },pushPermissionCheckStatus: 'allowed',};-describe('shouldShowAutoSyncOnboarding', () => {- test('shows when every condition is aligned (unanswered machine, no committed default)', () => {- expect(shouldShowAutoSyncOnboarding(SHOWING)).toBe(true);+describe('resolveAutoSyncOnboarding', () => {+ test('shows the full-sync variant when aligned and the probe allows pushing', () => {+ expect(resolveAutoSyncOnboarding(SHOWING)).toBe('full');});test('hidden once dismissed this session', () => {- expect(shouldShowAutoSyncOnboarding({ ...SHOWING, autoSyncOnboardingDismissed: true })).toBe(- false,- );+ expect(resolveAutoSyncOnboarding({ ...SHOWING, autoSyncOnboardingDismissed: true })).toBeNull();});test('hidden without a git remote', () => {- expect(shouldShowAutoSyncOnboarding({ ...SHOWING, hasRemote: false })).toBe(false);- expect(shouldShowAutoSyncOnboarding({ ...SHOWING, hasRemote: undefined })).toBe(false);+ expect(resolveAutoSyncOnboarding({ ...SHOWING, hasRemote: false })).toBeNull();+ expect(resolveAutoSyncOnboarding({ ...SHOWING, hasRemote: undefined })).toBeNull();});test('hidden until the project-local binding has synced (flash-free)', () => {- expect(shouldShowAutoSyncOnboarding({ ...SHOWING, projectLocalSynced: false })).toBe(false);- expect(shouldShowAutoSyncOnboarding({ ...SHOWING, projectLocalSynced: undefined })).toBe(false);+ expect(resolveAutoSyncOnboarding({ ...SHOWING, projectLocalSynced: false })).toBeNull();+ expect(resolveAutoSyncOnboarding({ ...SHOWING, projectLocalSynced: undefined })).toBeNull();});test('hidden until the committed project binding has synced (flash-free)', () => {- // Without the projectSynced guard, a project shipping default:false would- // briefly read the schema default (null) and flash the modal open.- expect(shouldShowAutoSyncOnboarding({ ...SHOWING, projectSynced: false })).toBe(false);- expect(shouldShowAutoSyncOnboarding({ ...SHOWING, projectSynced: undefined })).toBe(false);+ // Without the projectSynced guard, a project shipping a committed default+ // would briefly read the schema default (null) and flash the modal open.+ expect(resolveAutoSyncOnboarding({ ...SHOWING, projectSynced: false })).toBeNull();+ expect(resolveAutoSyncOnboarding({ ...SHOWING, projectSynced: undefined })).toBeNull();});test('hidden until project-local config hydrates', () => {- expect(shouldShowAutoSyncOnboarding({ ...SHOWING, projectLocalConfig: null })).toBe(false);+ expect(resolveAutoSyncOnboarding({ ...SHOWING, projectLocalConfig: null })).toBeNull();+ });++ test('hidden once this machine has answered via mode (off/pull/full)', () => {+ for (const mode of ['off', 'follow', 'full'] as const) {+ expect(+ resolveAutoSyncOnboarding({+ ...SHOWING,+ projectLocalConfig: { autoSync: { mode } },+ }),+ ).toBeNull();+ }});- test('hidden once this machine has answered (enabled true or false)', () => {+ test('hidden once this machine has answered via the legacy enabled boolean', () => {expect(- shouldShowAutoSyncOnboarding({+ resolveAutoSyncOnboarding({...SHOWING,projectLocalConfig: { autoSync: { enabled: true } },}),- ).toBe(false);+ ).toBeNull();expect(- shouldShowAutoSyncOnboarding({+ resolveAutoSyncOnboarding({...SHOWING,projectLocalConfig: { autoSync: { enabled: false } },}),- ).toBe(false);+ ).toBeNull();});- test('suppressed when the maintainer committed autoSync.default: false', () => {+ test('suppressed when the maintainer committed a mode-valued default', () => {+ for (const def of ['off', 'follow', 'full'] as const) {+ expect(+ resolveAutoSyncOnboarding({+ ...SHOWING,+ projectConfig: { autoSync: { default: def } },+ }),+ ).toBeNull();+ }+ });++ test('suppressed when the maintainer committed a legacy boolean default', () => {expect(- shouldShowAutoSyncOnboarding({+ resolveAutoSyncOnboarding({...SHOWING,projectConfig: { autoSync: { default: false } },}),- ).toBe(false);- });-- test('suppressed when the maintainer committed autoSync.default: true', () => {+ ).toBeNull();expect(- shouldShowAutoSyncOnboarding({+ resolveAutoSyncOnboarding({...SHOWING,projectConfig: { autoSync: { default: true } },}),- ).toBe(false);+ ).toBeNull();});test('still asks when committed config is absent or default is null/absent', () => {- // projectConfig === null (committed doc empty) → no seed → ask.- expect(shouldShowAutoSyncOnboarding({ ...SHOWING, projectConfig: null })).toBe(true);- // autoSync present but default absent → no seed → ask.- expect(shouldShowAutoSyncOnboarding({ ...SHOWING, projectConfig: { autoSync: {} } })).toBe(- true,- );- // autoSync absent entirely → no seed → ask.- expect(shouldShowAutoSyncOnboarding({ ...SHOWING, projectConfig: {} })).toBe(true);+ expect(resolveAutoSyncOnboarding({ ...SHOWING, projectConfig: null })).toBe('full');+ expect(resolveAutoSyncOnboarding({ ...SHOWING, projectConfig: { autoSync: {} } })).toBe('full');+ expect(resolveAutoSyncOnboarding({ ...SHOWING, projectConfig: {} })).toBe('full');});- test('hidden when the push-permission probe denied or is still pending', () => {- expect(shouldShowAutoSyncOnboarding({ ...SHOWING, pushPermissionCheckStatus: 'denied' })).toBe(- false,- );- expect(shouldShowAutoSyncOnboarding({ ...SHOWING, pushPermissionCheckStatus: undefined })).toBe(- false,+ test('forks to the follow variant when the push probe is denied', () => {+ expect(resolveAutoSyncOnboarding({ ...SHOWING, pushPermissionCheckStatus: 'denied' })).toBe(+ 'follow',);});- test('shows on probe unknown (graceful degradation)', () => {- expect(shouldShowAutoSyncOnboarding({ ...SHOWING, pushPermissionCheckStatus: 'unknown' })).toBe(- true,- );+ test('suppressed while the push probe is unknown or still pending', () => {+ expect(+ resolveAutoSyncOnboarding({ ...SHOWING, pushPermissionCheckStatus: 'unknown' }),+ ).toBeNull();+ expect(+ resolveAutoSyncOnboarding({ ...SHOWING, pushPermissionCheckStatus: undefined }),+ ).toBeNull();});});diff --git a/packages/app/src/components/auto-sync-onboarding-gate.ts b/packages/app/src/components/auto-sync-onboarding-gate.tsindex 0a0a4dd10..52ba550a7 100644--- a/packages/app/src/components/auto-sync-onboarding-gate.ts+++ b/packages/app/src/components/auto-sync-onboarding-gate.ts@@ -1,7 +1,8 @@/*** Pure decision function for the AutoSync onboarding modal.*- * The dialog opens once per machine per project when:+ * Returns which prompt variant to show, or `null` to stay hidden. The dialog+ * opens once per machine per project when every gate condition aligns:* 1. The user has not yet dismissed it this session.* 2. A git remote exists for the project (`hasRemote === true`).* 3. The project-local CRDT binding has synced from disk@@ -11,29 +12,39 @@* 4. The committed project binding has synced (`projectSynced === true`) —* the same flash-free guard for the committed `autoSync.default` read in* condition 7. Until the committed doc lands, `default` reads as the- * schema default (`null`), so a project that ships `default: false` would- * flash the modal open and then close once the real value arrives.+ * schema default (`null`), so a project that ships a default would flash+ * the modal open and then close once the real value arrives.* 5. The local config is hydrated (`projectLocalConfig !== null`).- * 6. The user hasn't answered the autoSync prompt yet- * (`autoSync.enabled === null`). The schema's `nullable().default(null)`- * makes `null` the canonical "unanswered" sentinel — never `undefined`.+ * 6. This machine hasn't answered yet — the resolved local mode is `null`.+ * `resolveLocalAutoSyncMode` reads `autoSync.mode` and falls back to the+ * legacy `autoSync.enabled` boolean, so a machine that answered under+ * either shape is treated as answered.* 7. The maintainer has NOT committed an `autoSync.default` seed- * (`projectConfig.autoSync.default` is `null`/absent). A committed `true`- * or `false` pre-answers the prompt for everyone who clones the project,- * so the modal is suppressed; only a null/absent default still asks.- * 8. The push-permission probe HAS resolved AND did not return `'denied'`.- * The gate requires the probe to settle first — `undefined` (probe- * still pending) keeps the dialog hidden so we don't flash it open- * and then close it the moment the probe returns `denied` (the- * common case on share-linked clones of someone else's repo).- * `'unknown'` (probe failed) still passes — graceful degradation- * preserves the read+write user's onboarding ask when the probe- * can't reach a verdict.+ * (`modeFromCommittedDefault(default)` is `null`). A committed default+ * (off/pull/full, or the legacy boolean) pre-answers the prompt for+ * everyone who clones the project, so the modal is suppressed; only a+ * null/absent default still asks.+ * 8. The push-permission probe HAS resolved to a forking verdict. `allowed`+ * returns the full-sync variant; `denied` (incl. the anonymous no-network+ * short-circuit, the common case on share-linked clones) returns the+ * pull-only variant. `unknown` (probe failed) and `undefined` (probe+ * pending) both suppress: showing a full-sync prompt to a maybe-denied+ * user promises pushes we can't keep, and Settings stays available for a+ * later opt-in. The pending suppression is also the flash-free guard.** Extracted from EditorPane into a pure function so each input contributes* to an independently testable truth table. The cheapest checks come first* to short-circuit before the more expensive reads.*/+import {+ modeFromCommittedDefault,+ resolveLocalAutoSyncMode,+ type StoredSyncMode,+} from '@inkeep/open-knowledge-core';++/** Which onboarding prompt to show; `follow` explains one-directional sync. */+export type AutoSyncOnboardingVariant = 'full' | 'follow';+export interface AutoSyncOnboardingGateInputs {/** Local React state — has the user already dismissed this session? */autoSyncOnboardingDismissed: boolean;@@ -44,32 +55,34 @@ export interface AutoSyncOnboardingGateInputs {/** CRDT lifecycle: has the committed project config doc finished its first sync? */projectSynced: boolean | undefined;/** Project-local config — null until the binding hydrates. */- projectLocalConfig: { autoSync?: { enabled: boolean | null } | null } | null;+ projectLocalConfig: {+ autoSync?: { mode?: StoredSyncMode | null; enabled?: boolean | null } | null;+ } | null;/** Committed project config — carries the maintainer's autoSync.default seed. */- projectConfig: { autoSync?: { default?: boolean | null } | null } | null;+ projectConfig: { autoSync?: { default?: boolean | StoredSyncMode | null } | null } | null;/** Push-permission probe outcome. */pushPermissionCheckStatus: 'allowed' | 'denied' | 'unknown' | undefined;}-export function shouldShowAutoSyncOnboarding(inputs: AutoSyncOnboardingGateInputs): boolean {- return (+export function resolveAutoSyncOnboarding(+ inputs: AutoSyncOnboardingGateInputs,+): AutoSyncOnboardingVariant | null {+ const aligned =!inputs.autoSyncOnboardingDismissed &&inputs.hasRemote === true &&inputs.projectLocalSynced === true &&inputs.projectSynced === true &&inputs.projectLocalConfig !== null &&- inputs.projectLocalConfig.autoSync?.enabled === null &&- // A committed autoSync.default (true OR false) pre-answers the prompt for- // everyone who clones the project — suppress the modal whenever the- // maintainer set one; only a null/absent default falls through to the ask.- // Gated on projectSynced above so this compares against the real committed- // value, not the schema default during the cold-start sync window.- (inputs.projectConfig?.autoSync?.default ?? null) === null &&- // Probe must have resolved AND not be 'denied' — `undefined` (pending)- // would flash the dialog and then close on the probe's `denied` return.- // `'unknown'` passes for graceful degradation when the probe can't- // reach a verdict (network failure, rate-limit, etc.).- (inputs.pushPermissionCheckStatus === 'allowed' ||- inputs.pushPermissionCheckStatus === 'unknown')- );+ resolveLocalAutoSyncMode(inputs.projectLocalConfig.autoSync ?? undefined) === null &&+ modeFromCommittedDefault(inputs.projectConfig?.autoSync?.default) === null;+ if (!aligned) return null;++ switch (inputs.pushPermissionCheckStatus) {+ case 'allowed':+ return 'full';+ case 'denied':+ return 'follow';+ default:+ return null;+ }}diff --git a/packages/app/src/components/bottom-composer-gate.ts b/packages/app/src/components/bottom-composer-gate.tsindex a9acdf69d..4c400c665 100644--- a/packages/app/src/components/bottom-composer-gate.ts+++ b/packages/app/src/components/bottom-composer-gate.ts@@ -23,7 +23,7 @@** Extracted from EditorArea into a pure function so each input contributes to* an independently testable truth table — mirrors `shouldPaintOverlay` and- * `shouldShowAutoSyncOnboarding`.+ * `resolveAutoSyncOnboarding`.*/export interface BottomComposerGateInputs {/** Whether the docked terminal is currently visible. */diff --git a/packages/app/src/components/settings/SettingsDialogBody.sections.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogBody.sections.dom.test.tsxindex 30bdd11f8..421f7d828 100644--- a/packages/app/src/components/settings/SettingsDialogBody.sections.dom.test.tsx+++ b/packages/app/src/components/settings/SettingsDialogBody.sections.dom.test.tsx@@ -13,11 +13,15 @@ type SyncStatus = {unknownError?: string;};syncEnabled?: boolean;+ syncMode?: 'off' | 'follow' | 'full';+ ahead?: number;remote?: { label: string; webUrl: string | null } | null;} | null;let syncStatus: SyncStatus = null;-let projectLocalConfig: { autoSync?: { enabled?: boolean } } | null = {+let projectLocalConfig: {+ autoSync?: { enabled?: boolean; mode?: 'off' | 'follow' | 'full' };+} | null = {autoSync: { enabled: true },};let projectLocalSynced = true;@@ -33,8 +37,9 @@ let projectBinding: {patch: (patch: unknown) => { ok: true } | { ok: false; error: unknown };} | null = null;let projectBindingPatchCalls: unknown[] = [];-let syncWriterCalls: boolean[] = [];-let syncDefaultWriterCalls: Array<boolean | null> = [];+let syncModeWriterCalls: string[] = [];+let syncModeSelectCalls: string[] = [];+let syncDefaultWriterCalls: Array<boolean | string | null> = [];let okignoreProps: Array<{ binding: unknown; synced: boolean }> = [];let installDialogProps: Array<{open: boolean;@@ -264,36 +269,42 @@ vi.doMock('@/lib/config-provider', () => ({}),}));+type ModeWriterFn = (mode: string) => { ok: true };vi.doMock('@/hooks/use-enable-sync-with-confirm', () => ({- useSyncEnabledWriter: () => ({- write: (enabled: boolean) => {- syncWriterCalls.push(enabled);- return true;- },- }),- useSyncDefaultWriter: () => (next: boolean | null) => {+ useSyncModeWriter: (): ModeWriterFn => (mode: string) => {+ syncModeWriterCalls.push(mode);+ return { ok: true };+ },+ useSyncDefaultWriter: () => (next: boolean | string | null) => {syncDefaultWriterCalls.push(next);return { ok: true };},- useEnableSyncWithConfirm: (writer: { write: (enabled: boolean) => boolean }) => {+ // Thin recorder mirroring the real hook's gating so the section's wiring is+ // exercised (deep confirm-flow behavior is covered against the real hook in+ // SettingsDialogBody.sync-mode.dom.test.tsx and the hook's own test).+ useSyncModeSelection: (writer: ModeWriterFn, currentMode: string) => {const [confirmOpen, setConfirmOpen] = useState(false);+ const [pendingMode, setPendingMode] = useState<'follow' | 'full' | null>(null);return {confirmOpen,setConfirmOpen,- onToggleRequest: (enabled: boolean) => {- if (enabled) {- setConfirmOpen(true);+ pendingMode,+ onModeSelect: (next: string) => {+ syncModeSelectCalls.push(next);+ if (next === currentMode) return;+ if (next === 'off') {+ writer('off');return;}- writer.write(false);+ setPendingMode(next as 'follow' | 'full');+ setConfirmOpen(true);},onConfirm: () => {- writer.write(true);+ if (pendingMode) writer(pendingMode);setConfirmOpen(false);},};},- EnableSyncConfirmDialog: () => null,}));vi.doMock('@/components/EnableSyncConfirmDialog', () => ({@@ -351,7 +362,8 @@ describe('SettingsDialogBody section runtime dispatch', () => {return { ok: true };},};- syncWriterCalls = [];+ syncModeWriterCalls = [];+ syncModeSelectCalls = [];syncDefaultWriterCalls = [];okignoreProps = [];installDialogProps = [];@@ -518,22 +530,24 @@ describe('SettingsDialogBody section runtime dispatch', () => {);});- test('sync section reads checked state from project-local config and keeps the writer/confirm path', async () => {+ test('sync section reflects the resolved mode and wires the three-way control', async () => {syncStatus = {- state: 'enabled',+ state: 'idle',hasRemote: true,- syncEnabled: false,+ syncEnabled: true,+ syncMode: 'full',remote: {label: 'inkeep/open-knowledge',webUrl: 'https://github.com/inkeep/open-knowledge',},};+ // Legacy `enabled: true` derives to full mode.projectLocalConfig = { autoSync: { enabled: true } };await renderBody({ activeId: 'sync' });- const toggle = screen.getByTestId('settings-sync-toggle');- expect(toggle.getAttribute('aria-checked')).toBe('true');+ const modeToggle = screen.getByTestId('settings-sync-mode-toggle');+ expect(modeToggle.getAttribute('data-value')).toBe('full');expect(screen.getByTestId('settings-sync-remote-link').getAttribute('href')).toBe('https://github.com/inkeep/open-knowledge',);@@ -541,23 +555,32 @@ describe('SettingsDialogBody section runtime dispatch', () => {'noopener noreferrer',);- fireEvent.click(toggle);- expect(syncWriterCalls).toEqual([false]);+ // Selecting Off is the safe direction — commits immediately, no confirm.+ fireEvent.click(screen.getByTestId('settings-sync-mode-off'));+ expect(syncModeSelectCalls).toEqual(['off']);+ expect(syncModeWriterCalls).toEqual(['off']);cleanup();syncStatus = {- state: 'enabled',+ state: 'idle',hasRemote: true,syncEnabled: true,+ syncMode: 'follow',remote: { label: 'ssh://git.example/repo.git', webUrl: null },};- projectLocalConfig = { autoSync: { enabled: false } };+ projectLocalConfig = { autoSync: { mode: 'follow' } };projectLocalSynced = false;await renderBody({ activeId: 'sync' });- expect(screen.getByTestId('settings-sync-toggle').getAttribute('aria-checked')).toBe('false');- expect(screen.getByTestId('settings-sync-toggle').hasAttribute('disabled')).toBe(true);+ // Explicit mode wins; the control is disabled until the project-local config+ // has hydrated (cold-start guard).+ expect(screen.getByTestId('settings-sync-mode-toggle').getAttribute('data-value')).toBe(+ 'follow',+ );+ expect(screen.getByTestId('settings-sync-mode-toggle').getAttribute('data-disabled')).toBe(+ 'true',+ );expect(screen.getByTestId('settings-sync-remote-label').textContent).toBe('ssh://git.example/repo.git',);@@ -584,13 +607,17 @@ describe('SettingsDialogBody section runtime dispatch', () => {'off',);- // "On by default" writes the committed seed `true`.- fireEvent.click(screen.getByTestId('settings-sync-default-on'));+ // "Full by default" writes the legacy boolean seed `true` (older builds honor it).+ fireEvent.click(screen.getByTestId('settings-sync-default-full'));expect(syncDefaultWriterCalls).toEqual([true]);- // "Ask each person" clears the committed seed (writes null → RFC 7396 delete).+ // "Pull-only by default" writes the widened mode string.+ fireEvent.click(screen.getByTestId('settings-sync-default-follow'));+ expect(syncDefaultWriterCalls).toEqual([true, 'follow']);++ // "None" clears the committed seed (writes null → RFC 7396 delete).fireEvent.click(screen.getByTestId('settings-sync-default-ask'));- expect(syncDefaultWriterCalls).toEqual([true, null]);+ expect(syncDefaultWriterCalls).toEqual([true, 'follow', null]);});test('committed default control is disabled until the committed config has synced', async () => {@@ -616,31 +643,60 @@ describe('SettingsDialogBody section runtime dispatch', () => {);});- test('sync section disables the toggle with denied-specific accessible copy when push permission is denied', async () => {+ test('sync section keeps the mode control enabled and points a denied receiver at pull-only', async () => {syncStatus = {state: 'idle',hasRemote: true,syncEnabled: false,+ syncMode: 'off',pushPermission: { checkStatus: 'denied', deniedReason: 'no-collaborator' },remote: {label: 'inkeep/open-knowledge',webUrl: 'https://github.com/inkeep/open-knowledge',},};- projectLocalConfig = { autoSync: { enabled: false } };+ projectLocalConfig = { autoSync: { mode: 'off' } };projectLocalSynced = true;await renderBody({ activeId: 'sync' });- const toggle = screen.getByTestId('settings-sync-toggle') as HTMLButtonElement;- expect(toggle.disabled).toBe(true);- expect(toggle.getAttribute('aria-label')).toBe(- "Sync disabled — you don't have permission to push",+ // A denied probe no longer disables the control — pull-only never pushes, so+ // the receiver must be able to reach it.+ expect(screen.getByTestId('settings-sync-mode-toggle').getAttribute('data-disabled')).toBe(+ 'false',);- expect(screen.getByTestId('settings-sync-body').textContent).toContain(- "you don't have permission to push",+ expect(screen.getByTestId('settings-sync-denied-hint').textContent).toContain(+ "You don't have permission to push",);- expect(screen.queryByTestId('settings-sync-reason')).toBeNull();+ // Off mode is not paused; the switch-to-pull affordance is full-only.+ expect(screen.queryByTestId('settings-sync-switch-follow')).toBeNull();+ });++ test('sync section offers Switch to pull-only when full sync is paused on a denied push probe', async () => {+ syncStatus = {+ state: 'disabled',+ hasRemote: true,+ syncEnabled: true,+ syncMode: 'full',+ pausedReason: 'no-push-permission',+ ahead: 2,+ remote: {+ label: 'inkeep/open-knowledge',+ webUrl: 'https://github.com/inkeep/open-knowledge',+ },+ };+ projectLocalConfig = { autoSync: { mode: 'full' } };+ projectLocalSynced = true;++ await renderBody({ activeId: 'sync' });++ expect(screen.getByTestId('settings-sync-switch-follow')).not.toBeNull();+ // The action routes through the mode selector toward pull-only.+ fireEvent.click(screen.getByTestId('settings-sync-switch-follow-action'));+ expect(syncModeSelectCalls).toEqual(['follow']);+ // Opening the confirm, not an immediate write (consent gate).+ expect(syncModeWriterCalls).toEqual([]);+ expect(screen.getByTestId('sync-confirm-dialog').getAttribute('data-open')).toBe('true');});test('sync section renders shared paused-reason copy for non-permission pause reasons', async () => {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.tsxnew file mode 100644index 000000000..e13b44fac--- /dev/null+++ b/packages/app/src/components/settings/SettingsDialogBody.sync-mode.dom.test.tsx@@ -0,0 +1,330 @@+/**+ * Integration coverage for the three-way sync-mode control in the Settings Sync+ * section. Unlike the sibling sections test (which stubs the sync hooks), this+ * renders the REAL `useSyncModeSelection` / `useSyncModeWriter` hooks and the+ * REAL `EnableSyncConfirmDialog`, mocking only the config-binding boundary, the+ * status feed, and leaf UI primitives. It proves the actual wiring: select a+ * mode -> the consent dialog opens with the right copy -> confirming patches+ * `autoSync.mode` on the project-local binding.+ */+import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { createContext, type ReactNode, use } from 'react';+import { beforeEach, describe, expect, test, vi } from 'vitest';+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';++type SyncStatus = {+ state: string;+ hasRemote: boolean;+ pausedReason?: string;+ pushPermission?: { checkStatus: 'allowed' | 'denied' | 'unknown'; deniedReason?: string };+ syncEnabled?: boolean;+ syncMode?: 'off' | 'follow' | 'full';+ ahead?: number;+ remote?: { label: string; webUrl: string | null } | null;+} | null;++let syncStatus: SyncStatus = null;+let projectLocalConfig: {+ autoSync?: { enabled?: boolean; mode?: 'off' | 'follow' | 'full' };+} | null = null;+let projectConfig: {+ autoSync?: { default?: boolean | string | null };+ content: { attachmentFolderPath: string };+} | null = null;+let projectLocalSynced = true;+let projectSynced = true;+let localPatchCalls: unknown[] = [];+const projectLocalBinding: {+ patch: (patch: unknown) => { ok: true } | { ok: false; error: unknown };+} = {+ patch: (patch: unknown) => {+ localPatchCalls.push(patch);+ return { ok: true };+ },+};++import * as actualLinguiMacro from '@lingui/react/macro';++vi.doMock('@lingui/react/macro', () => ({+ ...actualLinguiMacro,+ Plural: ({ value, one, other }: { value: number; one: string; other: string }) => (+ <>{(value === 1 ? one : other).replace('#', String(value))}</>+ ),+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,+ useLingui: () => ({ t: renderLinguiTemplate }),+}));++vi.doMock('@lingui/core/macro', () => ({+ ...actualLinguiMacro,+ msg: renderLinguiTemplate,+ plural: (value: number, options: { one: string; other: string }) =>+ (value === 1 ? options.one : options.other).replace('#', String(value)),+ t: renderLinguiTemplate,+}));++const toastErrors: string[] = [];+vi.doMock('sonner', () => ({ toast: { error: (m: string) => toastErrors.push(m) } }));++vi.doMock('@/components/ui/button', () => ({+ Button: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (+ <button type="button" {...props}>+ {children}+ </button>+ ),+}));++vi.doMock('@/components/ui/collapsible', () => ({+ Collapsible: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ CollapsibleContent: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ CollapsibleTrigger: ({ children }: { children?: ReactNode }) => <>{children}</>,+}));++// The sync section renders no Switch (mode uses a ToggleGroup); a bare stub+// satisfies the module import without tripping the switch-role a11y lint.+vi.doMock('@/components/ui/switch', () => ({+ Switch: (props: Record<string, unknown>) => <button type="button" {...props} />,+}));++vi.doMock('@/components/ui/skeleton', () => ({+ Skeleton: ({ className }: { className?: string }) => <div className={className} />,+}));++vi.doMock('@/components/ui/form', () => ({+ Form: ({ children }: { children?: ReactNode }) => <form>{children}</form>,+ FormControl: ({ children }: { children?: ReactNode }) => <>{children}</>,+ FormDescription: ({ children }: { children?: ReactNode }) => <p>{children}</p>,+ FormField: () => null,+ FormItem: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ FormLabel: ({ children }: { children?: ReactNode }) => <span>{children}</span>,+ FormMessage: () => null,+}));++vi.doMock('@/components/ui/input', () => ({+ Input: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,+}));++vi.doMock('@/components/ui/select', () => ({+ Select: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ SelectContent: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ SelectItem: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ SelectTrigger: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ SelectValue: () => null,+}));++// Recorder ToggleGroup: reliable, deterministic clicks that forward the item+// value to the REAL onValueChange handler (the hook under test).+const ToggleGroupHandlerCtx = createContext<((value: string) => void) | undefined>(undefined);+vi.doMock('@/components/ui/toggle-group', () => ({+ ToggleGroup: ({+ children,+ value,+ onValueChange,+ disabled,+ ...props+ }: {+ children?: ReactNode;+ value?: string;+ onValueChange?: (value: string) => void;+ disabled?: boolean;+ [key: string]: unknown;+ }) => (+ <ToggleGroupHandlerCtx.Provider value={onValueChange}>+ <div data-value={value} data-disabled={String(Boolean(disabled))} {...props}>+ {children}+ </div>+ </ToggleGroupHandlerCtx.Provider>+ ),+ ToggleGroupItem: ({+ children,+ value,+ ...props+ }: {+ children?: ReactNode;+ value?: string;+ [key: string]: unknown;+ }) => {+ const onValueChange = use(ToggleGroupHandlerCtx);+ return (+ <button type="button" onClick={() => onValueChange?.(value as string)} {...props}>+ {children}+ </button>+ );+ },+}));++vi.doMock('@/components/ui/tooltip', () => ({+ TooltipProvider: ({ children }: { children?: ReactNode }) => <>{children}</>,+ Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,+ TooltipContent: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (+ <div {...props}>{children}</div>+ ),+ TooltipTrigger: ({ children }: { children?: ReactNode }) => <>{children}</>,+}));++vi.doMock('@/components/PublishToGitHubDialog', () => ({+ PublishToGitHubDialog: () => null,+}));+vi.doMock('@/components/AuthModal', () => ({ AuthModal: () => null }));+vi.doMock('@/components/InstallInClaudeDesktopDialog', () => ({+ InstallInClaudeDesktopDialog: () => null,+}));+vi.doMock('./OkignoreSection', () => ({ OkignoreSection: () => null }));+vi.doMock('./ProjectTemplatesSection', () => ({ ProjectTemplatesSection: () => null }));++vi.doMock('@/hooks/use-git-sync-status', () => ({+ useGitSyncStatus: () => syncStatus,+ useGitSyncStatusDetailed: () => ({ status: syncStatus, fetchError: null }),+}));++vi.doMock('@/lib/config-provider', () => ({+ useConfigContext: () => ({+ projectBinding: projectLocalBinding,+ projectConfig,+ projectLocalConfig,+ projectLocalBinding,+ projectLocalSynced,+ projectSynced,+ }),+}));++// Import the component AFTER the doMock calls so it picks up the mocked deps+// while keeping the REAL sync hooks + REAL EnableSyncConfirmDialog. RTL itself+// depends on none of the mocked modules, so it stays a static top-level import+// (the Tier-3 filename contract requires it).+async function renderSyncSection() {+ const { SettingsDialogBody } = await import('./SettingsDialogBody');+ render(+ <SettingsDialogBody+ activeId="sync"+ userBinding={null as never}+ okignoreBinding={null as never}+ okignoreSynced={false}+ />,+ );+}++describe('Settings Sync section — three-way mode control (real hooks + dialog)', () => {+ beforeEach(() => {+ cleanup();+ syncStatus = {+ state: 'idle',+ hasRemote: true,+ syncEnabled: false,+ syncMode: 'off',+ ahead: 0,+ remote: {+ label: 'inkeep/open-knowledge',+ webUrl: 'https://github.com/inkeep/open-knowledge',+ },+ };+ projectLocalConfig = { autoSync: { mode: 'off' } };+ projectConfig = { autoSync: { default: null }, content: { attachmentFolderPath: './' } };+ projectLocalSynced = true;+ projectSynced = true;+ localPatchCalls = [];+ toastErrors.length = 0;+ });++ test('selecting Pull-only opens the one-directional confirm and patches mode on confirm', async () => {+ await renderSyncSection();++ fireEvent.click(screen.getByTestId('settings-sync-mode-follow'));++ // The real pull-variant confirmation renders; no write yet.+ expect(screen.getByRole('button', { name: 'Enable Follow' })).not.toBeNull();+ expect(screen.getByRole('note').textContent ?? '').toContain('Updates flow in');+ expect(localPatchCalls).toEqual([]);++ fireEvent.click(screen.getByRole('button', { name: 'Enable Follow' }));+ expect(localPatchCalls).toEqual([{ autoSync: { mode: 'follow', enabled: null } }]);+ });++ test('selecting Full opens the bidirectional confirm and patches full on confirm', async () => {+ await renderSyncSection();++ fireEvent.click(screen.getByTestId('settings-sync-mode-full'));++ expect(screen.getByRole('button', { name: 'Enable auto-sync' })).not.toBeNull();+ expect(screen.getByRole('note').textContent ?? '').toContain('Commits happen automatically');++ fireEvent.click(screen.getByRole('button', { name: 'Enable auto-sync' }));+ expect(localPatchCalls).toEqual([{ autoSync: { mode: 'full', enabled: null } }]);+ });++ test('selecting Off writes immediately with no confirmation', async () => {+ projectLocalConfig = { autoSync: { mode: 'full' } };+ syncStatus = { ...syncStatus, syncMode: 'full', syncEnabled: true } as SyncStatus;++ await renderSyncSection();++ fireEvent.click(screen.getByTestId('settings-sync-mode-off'));++ expect(localPatchCalls).toEqual([{ autoSync: { mode: 'off', enabled: null } }]);+ // No confirmation dialog for the safe direction.+ expect(screen.queryByRole('button', { name: /Enable/ })).toBeNull();+ });++ test('Switch to pull-only from a paused full sync discloses stranded commits then patches pull', async () => {+ projectLocalConfig = { autoSync: { mode: 'full' } };+ syncStatus = {+ state: 'disabled',+ hasRemote: true,+ syncEnabled: true,+ syncMode: 'full',+ pausedReason: 'no-push-permission',+ ahead: 2,+ remote: {+ label: 'inkeep/open-knowledge',+ webUrl: 'https://github.com/inkeep/open-knowledge',+ },+ };++ await renderSyncSection();++ fireEvent.click(screen.getByTestId('settings-sync-switch-follow-action'));++ // Pull-variant confirm with the stranded-commit disclosure sourced from ahead.+ expect(+ screen.getByText("You have 2 changes you haven't shared. They will stay on this computer."),+ ).not.toBeNull();++ fireEvent.click(screen.getByRole('button', { name: 'Enable Follow' }));+ expect(localPatchCalls).toEqual([{ autoSync: { mode: 'follow', enabled: null } }]);+ });++ test('a genuine read-only denial disables Full but keeps Off and Pull-only reachable', async () => {+ syncStatus = {+ ...syncStatus,+ pushPermission: { checkStatus: 'denied', deniedReason: 'no-collaborator' },+ } as SyncStatus;++ await renderSyncSection();++ expect((screen.getByTestId('settings-sync-mode-full') as HTMLButtonElement).disabled).toBe(+ true,+ );+ expect((screen.getByTestId('settings-sync-mode-off') as HTMLButtonElement).disabled).toBe(+ false,+ );+ expect((screen.getByTestId('settings-sync-mode-follow') as HTMLButtonElement).disabled).toBe(+ false,+ );+ // The disabled Full item carries a tooltip explaining the read-only denial.+ expect(screen.getByTestId('settings-sync-mode-full-tip').textContent ?? '').toContain(+ "You don't have permission to push to this repo",+ );+ });++ test('a signed-out denial keeps Full enabled (push access is unknowable until sign-in)', async () => {+ syncStatus = {+ ...syncStatus,+ pushPermission: { checkStatus: 'denied', deniedReason: 'not-authenticated' },+ } as SyncStatus;++ await renderSyncSection();++ expect((screen.getByTestId('settings-sync-mode-full') as HTMLButtonElement).disabled).toBe(+ false,+ );+ });+});diff --git a/packages/app/src/components/settings/SyncSection.tsx b/packages/app/src/components/settings/SyncSection.tsxindex 3ead62020..176a37580 100644--- a/packages/app/src/components/settings/SyncSection.tsx+++ b/packages/app/src/components/settings/SyncSection.tsx@@ -1,13 +1,20 @@/**- * Sync section — surface the git auto-sync toggle in Settings so users- * have a deliberate path to re-enable when the header badge is hidden- * (state === 'disabled' hides the badge).+ * Sync section — the Settings home for the three-way sync mode+ * (off / pull-only / full) plus the committed shared default, so users have a+ * deliberate path to change modes even when the header badge is hidden+ * (state === 'disabled' hides the badge for non-following projects).*- * The toggle writes through the project-local ConfigBinding so the choice- * lands in `<projectDir>/.ok/local/config.yml`; the file watcher then drives- * the SyncEngine to match.+ * The mode control writes through the project-local ConfigBinding so the+ * choice lands in `<projectDir>/.ok/local/config.yml`; the file watcher then+ * drives the SyncEngine to match.*/+import {+ isSyncMode,+ modeFromCommittedDefault,+ resolveLocalAutoSyncMode,+ type SyncMode,+} from '@inkeep/open-knowledge-core';import { Trans, useLingui } from '@lingui/react/macro';import { ArrowUpRight, ChevronRight } from 'lucide-react';import { useState } from 'react';@@ -17,27 +24,25 @@ import { EnableSyncConfirmDialog } from '@/components/EnableSyncConfirmDialog';import { PublishToGitHubDialog } from '@/components/PublishToGitHubDialog';import {formatPausedReason,- shouldDisableSyncSwitch,shouldOfferReconnect,shouldOfferSignInAgain,} from '@/components/SyncStatusBadge';import { Button } from '@/components/ui/button';import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';-import { Switch } from '@/components/ui/switch';import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import {- useEnableSyncWithConfirm,useSyncDefaultWriter,- useSyncEnabledWriter,+ useSyncModeSelection,+ useSyncModeWriter,} from '@/hooks/use-enable-sync-with-confirm';import { useGitSyncStatus } from '@/hooks/use-git-sync-status';import { useConfigContext } from '@/lib/config-provider';-// The selected committed-default option uses the app's primary blue (the same-// token as the Button default variant), not the muted ToggleGroup default, so-// the active stance reads as clearly chosen and matches the accent used-// elsewhere in the app.-const COMMITTED_DEFAULT_SELECTED_CLASS =+// Selected toggle items use the app's primary blue (the same token as the+// Button default variant), not the muted ToggleGroup default, so the active+// stance reads as clearly chosen and matches the accent used elsewhere.+const SYNC_SELECTED_TOGGLE_CLASS ='data-[state=on]:border-primary data-[state=on]:bg-primary data-[state=on]:text-primary-foreground data-[state=on]:hover:bg-primary/90';export function SyncSection() {@@ -45,10 +50,14 @@ export function SyncSection() {const status = useGitSyncStatus();const { projectConfig, projectLocalConfig, projectLocalSynced, projectSynced } =useConfigContext();- const writer = useSyncEnabledWriter();+ const modeWriter = useSyncModeWriter();const defaultWriter = useSyncDefaultWriter();- const { confirmOpen, setConfirmOpen, onToggleRequest, onConfirm } =- useEnableSyncWithConfirm(writer);+ // Per-machine mode: an explicit `autoSync.mode` wins, else derive from the+ // legacy `enabled` boolean; never-answered resolves to off for display (the+ // committed shared default has its own control below).+ const localMode = resolveLocalAutoSyncMode(projectLocalConfig?.autoSync) ?? 'off';+ const { confirmOpen, setConfirmOpen, pendingMode, onModeSelect, onConfirm } =+ useSyncModeSelection(modeWriter, localMode);const [publishOpen, setPublishOpen] = useState(false);// Local AuthModal control for the Sign-in-again affordance surfaced when// the probe returns 401. The editor header has its own AuthModal — settings@@ -119,47 +128,82 @@ export function SyncSection() {);}- // Read user intent from the synchronous local CRDT preference (the same- // binding `useSyncEnabledWriter` writes to). Don't read from the server's- // engine-state projection — that round-trips through ~2 s persistence- // debounce + chokidar settle + 100 ms CC1 debounce, making the Switch- // appear to lag every click.- const enabled = projectLocalConfig?.autoSync?.enabled ?? false;- // Mirrors the SyncStatusBadge popover so both surfaces gate identically.- // Disable on cold start OR on a denied probe; never disable on- // undefined / unknown / pending (preserves read+write parity).- const disabledControl = shouldDisableSyncSwitch(- projectLocalSynced,- status?.pushPermission?.checkStatus,- );- // Whether the body line should carry the no-permission copy inline (instead- // of the standard "your edits stay local" string + a redundant paragraph- // underneath). Fires for both the probe-`denied` path AND the in-memory- // pause path (autoSync was already enabled when probe came back denied —- // engine sets `pausedReason='no-push-permission'`).+ // Cold-start guard only: disable the control until the project-local config+ // has hydrated. Unlike the old boolean toggle, a denied probe does NOT disable+ // it — pull-only never pushes, so a push-denied receiver must still be able to+ // select it (the whole point of the mode).+ const modeControlDisabled = !projectLocalSynced;+ // Full sync paused (or would pause) because the push probe came back denied.+ // Only `full` cares about push permission — `pull`/`off` never push.const isPushDenied =status?.pushPermission?.checkStatus === 'denied' ||status?.pausedReason === 'no-push-permission';- const sectionMessage =- isPushDenied || !status?.pausedReason ? null : formatPausedReason(status.pausedReason);+ // Signed-out denial ('denied/not-authenticated') — signing back in restores+ // the full sync the user already consented to, so it takes precedence over+ // the switch-to-pull-only offer (that one is for genuinely revoked access).+ const offerReconnect = shouldOfferReconnect(status?.pushPermission);+ const showReconnect = localMode === 'full' && isPushDenied && offerReconnect;+ const showSwitchToPullOnly = localMode === 'full' && isPushDenied && !offerReconnect;+ // Full sync would immediately fail-and-pause for a genuine read-only user, so+ // don't offer it. Signed-out denial is excluded — that user may well have push+ // access once they authenticate, so Full stays reachable for them.+ const genuineReadOnlyDenied =+ status?.pushPermission?.checkStatus === 'denied' &&+ status.pushPermission.deniedReason !== 'not-authenticated';+ // A non-permission pause reason (protected-branch, dirty-tree, …) — reachable+ // only under full sync. Suppressed when the switch-to-pull-only affordance+ // already explains a paused full-sync engine.+ const pausedNotice =+ showSwitchToPullOnly || isPushDenied || !status?.pausedReason+ ? null+ : formatPausedReason(status.pausedReason);++ function onModeChange(next: string) {+ // Radix single ToggleGroup emits '' when the active item is re-pressed+ // (deselect) — ignore so there is always exactly one selected mode.+ if (!isSyncMode(next)) return;+ onModeSelect(next);+ }// Committed project default (`autoSync.default`) — the maintainer-facing,- // git-shared seed for everyone's first open. true/false/null map to the three- // ToggleGroup options; `null` (ask) is the absence of a committed seed.- const committedDefault = projectConfig?.autoSync?.default ?? null;- const committedDefaultValue =- committedDefault === true ? 'on' : committedDefault === false ? 'off' : 'ask';+ // git-shared seed for everyone's first open. Widened to the mode vocabulary so+ // a maintainer can ship a pull-only default; `modeFromCommittedDefault` reads+ // both the mode strings and the legacy boolean seed, `null` (ask) = no seed.+ const committedDefaultValue = modeFromCommittedDefault(projectConfig?.autoSync?.default) ?? 'ask';function onCommittedDefaultChange(next: string) {// Radix single ToggleGroup emits '' when the active item is re-pressed// (deselect) — ignore it so there is always exactly one committed stance.- if (next !== 'ask' && next !== 'on' && next !== 'off') return;+ if (next !== 'ask' && !isSyncMode(next)) return;if (defaultWriter === null) {toast.error(t`Sync settings not yet loaded — try again in a moment`);return;}- // 'ask' writes null, which clears the committed key (RFC 7396 merge-patch) →- // unanswered machines see the onboarding prompt again.- const value = next === 'on' ? true : next === 'off' ? false : null;+ // 'ask' clears the committed key (RFC 7396 merge-patch) → unanswered machines+ // see the onboarding prompt again. off/full stay legacy booleans so an older+ // OK build still honors them verbatim; 'pull' has no legacy equivalent, so it+ // is written as the mode string (older builds safely re-prompt on it).+ // Exhaustive per value: this writes committed (git-shared) config, so a+ // future mode must make a deliberate serialization choice here rather than+ // silently falling through to one arm.+ let value: boolean | SyncMode | null;+ switch (next) {+ case 'ask':+ value = null;+ break;+ case 'off':+ value = false;+ break;+ case 'full':+ value = true;+ break;+ case 'follow':+ value = 'follow';+ break;+ default: {+ const exhaustive: never = next;+ throw new Error(`unhandled committed default: ${String(exhaustive)}`);+ }+ }const result = defaultWriter(value);if (!result.ok) {const detail = result.error;@@ -175,40 +219,27 @@ export function SyncSection() {</h3><p className="text-sm text-muted-foreground"><Trans>- Auto-sync pushes/pulls commits to your git remote on intervals and on save. Toggling on- requires confirmation.+ Keep this project in sync with your git remote. Follow fetches updates without pushing;+ full sync pushes your commits too. Turning sync on requires confirmation.</Trans></p></div><div className="rounded-md border p-3">- <div className="flex items-center justify-between gap-3">+ <div className="flex flex-wrap items-start justify-between gap-3"><div className="min-w-0">- <label htmlFor="settings-sync-toggle" className="text-sm font-medium">- <Trans>Git auto-sync</Trans>- </label>+ <div id="settings-sync-mode-label" className="text-sm font-medium">+ <Trans>Git sync</Trans>+ </div><p className="text-muted-foreground text-1sm" data-testid="settings-sync-body">- {isPushDenied ? (- // Probe denied (or engine paused in-memory because autoSync was- // already on when probe denied). Replace the standard body copy- // with the permission-specific message — the redundant- // sectionMessage paragraph below is suppressed in this case.- // "Paused", not "off": the user's preference is still on (the- // toggle shows it), sync is just blocked. Signed-out vs genuine- // read-only get different remedies.- shouldOfferReconnect(status?.pushPermission) ? (- <Trans>Auto-sync is paused — sign in to resume.</Trans>- ) : (- <Trans>- Auto-sync is paused — you don't have permission to push to this repo.- </Trans>- )- ) : enabled ? (+ {localMode === 'full' ? (+ <Trans>Full sync — your commits push and remote changes pull automatically.</Trans>+ ) : localMode === 'follow' ? (<Trans>- Auto-sync is on — your commits push and remote changes pull on intervals.+ Follow — updates flow in from your remote; your edits stay on this computer.</Trans>) : (<Trans>- Auto-sync is off — your edits stay local until you commit and push manually.+ Sync is off — your edits stay on this computer until you commit and push manually.</Trans>)}</p>@@ -241,24 +272,117 @@ export function SyncSection() {</p>) : null}</div>- <Switch- id="settings-sync-toggle"- checked={enabled}- disabled={disabledControl}- onCheckedChange={onToggleRequest}- aria-label={- status?.pushPermission?.checkStatus === 'denied'- ? t`Sync disabled — you don't have permission to push`- : enabled- ? t`Disable git auto-sync`- : t`Enable git auto-sync`- }- data-testid="settings-sync-toggle"- />+ <ToggleGroup+ type="single"+ variant="outline"+ spacing={2}+ value={localMode}+ onValueChange={onModeChange}+ disabled={modeControlDisabled}+ aria-labelledby="settings-sync-mode-label"+ data-testid="settings-sync-mode-toggle"+ >+ <ToggleGroupItem+ value="off"+ className={SYNC_SELECTED_TOGGLE_CLASS}+ data-testid="settings-sync-mode-off"+ >+ <Trans>Off</Trans>+ </ToggleGroupItem>+ <ToggleGroupItem+ value="follow"+ className={SYNC_SELECTED_TOGGLE_CLASS}+ data-testid="settings-sync-mode-follow"+ >+ <Trans>Follow</Trans>+ </ToggleGroupItem>+ {genuineReadOnlyDenied ? (+ <Tooltip>+ <TooltipTrigger asChild>+ {/* A disabled button emits no pointer events, so the tooltip+ hangs off a wrapper span that still receives hover — the+ only way to surface why Full is greyed out. Keyboard users+ get the same reason from the read-only hint text below. */}+ <span className="inline-flex">+ <ToggleGroupItem+ value="full"+ className={SYNC_SELECTED_TOGGLE_CLASS}+ disabled+ data-testid="settings-sync-mode-full"+ >+ <Trans>Full</Trans>+ </ToggleGroupItem>+ </span>+ </TooltipTrigger>+ <TooltipContent data-testid="settings-sync-mode-full-tip">+ <Trans>You don't have permission to push to this repo</Trans>+ </TooltipContent>+ </Tooltip>+ ) : (+ <ToggleGroupItem+ value="full"+ className={SYNC_SELECTED_TOGGLE_CLASS}+ data-testid="settings-sync-mode-full"+ >+ <Trans>Full</Trans>+ </ToggleGroupItem>+ )}+ </ToggleGroup></div>- {sectionMessage !== null && (+ {showReconnect && (+ // "Paused", not "off": the preference is still full sync, it's just+ // blocked by a signed-out session — reconnecting resumes it. Mirrors+ // the popover's reconnect affordance.+ <div className="mt-2 flex items-start gap-2" data-testid="settings-sync-reconnect">+ <p className="text-1sm text-muted-foreground flex-1 min-w-0">+ <Trans>Auto-sync is paused — sign in to resume.</Trans>+ </p>+ <Button+ variant="outline"+ size="xs"+ className="self-start"+ onClick={() => setAuthModalOpen(true)}+ >+ <Trans>Sign in</Trans>+ </Button>+ </div>+ )}+ {showSwitchToPullOnly && (+ <div className="mt-2 flex items-start gap-2" data-testid="settings-sync-switch-follow">+ <p className="text-1sm text-muted-foreground flex-1 min-w-0">+ <Trans>+ Auto-sync is paused — you don't have permission to push to this repo. Switch to+ Follow to keep receiving updates.+ </Trans>+ </p>+ <Button+ variant="outline"+ size="xs"+ className="self-start"+ onClick={() => onModeSelect('follow')}+ data-testid="settings-sync-switch-follow-action"+ >+ <Trans>Switch to Follow</Trans>+ </Button>+ </div>+ )}+ {!showSwitchToPullOnly && !showReconnect && isPushDenied && localMode !== 'follow' && (+ // Push-denied and not yet following: point the receiver at pull-only,+ // which the mode control above already offers. Suppressed for the+ // signed-out shape — permission is unknowable until they sign in.+ <p+ className="text-1sm text-muted-foreground mt-2"+ data-testid="settings-sync-denied-hint"+ >+ <Trans>+ You don't have permission to push to this repo. Follow can still keep your copy up to+ date.+ </Trans>+ </p>+ )}+ {pausedNotice !== null && (<p className="text-1sm text-muted-foreground mt-2" data-testid="settings-sync-reason">- {sectionMessage}+ {pausedNotice}</p>)}{shouldOfferSignInAgain(status?.pushPermission) && (@@ -279,28 +403,16 @@ export function SyncSection() {</Button></div>)}- {shouldOfferReconnect(status?.pushPermission) && (- // Signed-out denial ('denied/not-authenticated') — reconnecting- // resumes sync (the body copy above reads "sign in to resume"), so- // surface the button. Mirrors the popover's reconnect affordance.- <div className="mt-2 flex justify-start" data-testid="settings-sync-reconnect">- {/* Default size (not xs) to match the None/On/Off toggle row above:- both resolve to h-8 / px-2.5 / text-sm. */}- <Button variant="outline" onClick={() => setAuthModalOpen(true)}>- <Trans>Sign in</Trans>- </Button>- </div>- )}</div><div className="rounded-md border p-3 space-y-2" data-testid="settings-sync-default"><div className="space-y-0.5">- <div className="text-sm font-medium">+ <div id="settings-sync-default-label" className="text-sm font-medium"><Trans>Shared default</Trans></div><p className="text-muted-foreground text-1sm"><Trans>- Set the auto-sync default for users opening this project for the first time. This- setting is committed to your repository.+ Set the sync default for users opening this project for the first time. This setting+ is committed to your repository.</Trans></p></div>@@ -311,36 +423,45 @@ export function SyncSection() {value={committedDefaultValue}onValueChange={onCommittedDefaultChange}disabled={!projectSynced}- aria-label={t`Shared auto-sync default`}+ aria-labelledby="settings-sync-default-label"data-testid="settings-sync-default-toggle"><ToggleGroupItemvalue="ask"- className={COMMITTED_DEFAULT_SELECTED_CLASS}+ className={SYNC_SELECTED_TOGGLE_CLASS}data-testid="settings-sync-default-ask"><Trans>None</Trans></ToggleGroupItem>- <ToggleGroupItem- value="on"- className={COMMITTED_DEFAULT_SELECTED_CLASS}- data-testid="settings-sync-default-on"- >- <Trans>On</Trans>- </ToggleGroupItem><ToggleGroupItemvalue="off"- className={COMMITTED_DEFAULT_SELECTED_CLASS}+ className={SYNC_SELECTED_TOGGLE_CLASS}data-testid="settings-sync-default-off"><Trans>Off</Trans></ToggleGroupItem>+ <ToggleGroupItem+ value="follow"+ className={SYNC_SELECTED_TOGGLE_CLASS}+ data-testid="settings-sync-default-follow"+ >+ <Trans>Follow</Trans>+ </ToggleGroupItem>+ <ToggleGroupItem+ value="full"+ className={SYNC_SELECTED_TOGGLE_CLASS}+ data-testid="settings-sync-default-full"+ >+ <Trans>Full</Trans>+ </ToggleGroupItem></ToggleGroup></div><EnableSyncConfirmDialogopen={confirmOpen}onOpenChange={setConfirmOpen}onConfirm={onConfirm}+ variant={pendingMode ?? 'full'}+ strandedCommitCount={pendingMode === 'follow' ? (status?.ahead ?? 0) : 0}/><AuthModalopen={authModalOpen}diff --git a/packages/app/src/hooks/use-enable-sync-with-confirm.dom.test.tsx b/packages/app/src/hooks/use-enable-sync-with-confirm.dom.test.tsxindex f2422dafd..58308d58f 100644--- a/packages/app/src/hooks/use-enable-sync-with-confirm.dom.test.tsx+++ b/packages/app/src/hooks/use-enable-sync-with-confirm.dom.test.tsx@@ -1,3 +1,4 @@+import type { SyncMode } from '@inkeep/open-knowledge-core';import * as actualLinguiMacro from '@lingui/react/macro';import { act, cleanup, render, screen } from '@testing-library/react';import type { ReactNode } from 'react';@@ -60,7 +61,18 @@ function WriterProbe({ children: _children }: { children?: ReactNode }) {return <div data-testid="writer-present">{String(latestWriter !== null)}</div>;}-type DefaultWriter = ((next: boolean | null) => { ok: true } | { ok: false; error: string }) | null;+type ModeWriter = ((mode: SyncMode) => { ok: true } | { ok: false; error: string }) | null;+let latestModeWriter: ModeWriter | undefined;++function ModeWriterProbe() {+ if (!hooks) throw new Error('hooks not loaded');+ latestModeWriter = hooks.useSyncModeWriter();+ return <div data-testid="mode-writer-present">{String(latestModeWriter !== null)}</div>;+}++type DefaultWriter =+ | ((next: boolean | SyncMode | null) => { ok: true } | { ok: false; error: string })+ | null;let latestDefaultWriter: DefaultWriter | undefined;function DefaultWriterProbe() {@@ -69,24 +81,51 @@ function DefaultWriterProbe() {return <div data-testid="default-writer-present">{String(latestDefaultWriter !== null)}</div>;}+type ModeSelectionState = {+ confirmOpen: boolean;+ pendingMode: 'follow' | 'full' | null;+ onModeSelect: (next: SyncMode) => void;+ onConfirm: () => void;+};+let latestModeSelection: ModeSelectionState | null = null;++function ModeSelectionProbe({+ writer,+ currentMode,+}: {+ writer: ModeWriter;+ currentMode: SyncMode;+}) {+ if (!hooks) throw new Error('hooks not loaded');+ latestModeSelection = hooks.useSyncModeSelection(writer, currentMode);+ return (+ <div data-testid="mode-selection">+ {String(latestModeSelection.confirmOpen)}:{String(latestModeSelection.pendingMode)}+ </div>+ );+}+describe('useEnableSyncWithConfirm runtime behavior', () => {- let consoleErrorSpy: ReturnType<typeof vi.spyOn>;+ let consoleErrorSpy: ReturnType<typeof spyOn>;afterEach(() => {cleanup();latestConfirmState = null;latestWriter = undefined;+ latestModeWriter = undefined;latestDefaultWriter = undefined;+ latestModeSelection = null;projectLocalBinding = null;projectBinding = null;toastErrors.length = 0;consoleErrorSpy?.mockRestore();});- test('exports the hook and both writer adapters', async () => {+ test('exports the hook and every writer adapter', async () => {const mod = await loadHooks();expect(typeof mod.useEnableSyncWithConfirm).toBe('function');expect(typeof mod.useSyncEnabledWriter).toBe('function');+ expect(typeof mod.useSyncModeWriter).toBe('function');expect(typeof mod.useSyncDefaultWriter).toBe('function');});@@ -195,7 +234,7 @@ describe('useSyncEnabledWriter runtime behavior', () => {expect(latestWriter).toBeNull();});- test('patches autoSync.enabled on the project-local binding', async () => {+ test('patches both autoSync.mode and the legacy enabled leaf so a set mode cannot mask the enable', async () => {await loadHooks();const patches: unknown[] = [];projectLocalBinding = {@@ -206,8 +245,15 @@ describe('useSyncEnabledWriter runtime behavior', () => {};render(<WriterProbe />);+ // Enabling must write mode:'full' (the value resolveLocalAutoSyncMode reads+ // first), not just enabled:true — otherwise a machine that previously set+ // mode:'off' would ignore the enable.expect(latestWriter?.(true)).toEqual({ ok: true });- expect(patches).toEqual([{ autoSync: { enabled: true } }]);+ expect(latestWriter?.(false)).toEqual({ ok: true });+ expect(patches).toEqual([+ { autoSync: { mode: 'full', enabled: true } },+ { autoSync: { mode: 'off', enabled: false } },+ ]);});test('wraps binding errors into a string result for toast rendering', async () => {@@ -224,6 +270,53 @@ describe('useSyncEnabledWriter runtime behavior', () => {});});+describe('useSyncModeWriter runtime behavior', () => {+ afterEach(() => {+ cleanup();+ latestModeWriter = undefined;+ projectLocalBinding = null;+ });++ test('returns null until the project-local binding mounts', async () => {+ await loadHooks();+ projectLocalBinding = null;+ render(<ModeWriterProbe />);++ expect(screen.getByTestId('mode-writer-present').textContent).toBe('false');+ expect(latestModeWriter).toBeNull();+ });++ test('patches autoSync.mode on the project-local binding', async () => {+ await loadHooks();+ const patches: unknown[] = [];+ projectLocalBinding = {+ patch: (patch: unknown) => {+ patches.push(patch);+ return { ok: true };+ },+ };+ render(<ModeWriterProbe />);++ expect(latestModeWriter?.('follow')).toEqual({ ok: true });+ // Writes the mode AND clears the legacy `enabled` flag so an older app+ // can't read a stale toggle and push for a mode the user switched away from.+ expect(patches).toEqual([{ autoSync: { mode: 'follow', enabled: null } }]);+ });++ test('wraps binding errors into a string result for toast rendering', async () => {+ await loadHooks();+ projectLocalBinding = {+ patch: () => ({ ok: false, error: { code: 'WRITE_ERROR', detail: 'disk denied' } }),+ };+ render(<ModeWriterProbe />);++ expect(latestModeWriter?.('full')).toEqual({+ ok: false,+ error: 'Failed to write config file: disk denied',+ });+ });+});+describe('useSyncDefaultWriter runtime behavior', () => {afterEach(() => {cleanup();@@ -275,6 +368,21 @@ describe('useSyncDefaultWriter runtime behavior', () => {expect(localPatches).toEqual([]);});+ test('patches a widened mode-string default (committed pull seed)', async () => {+ await loadHooks();+ const committedPatches: unknown[] = [];+ projectBinding = {+ patch: (patch: unknown) => {+ committedPatches.push(patch);+ return { ok: true };+ },+ };+ render(<DefaultWriterProbe />);++ expect(latestDefaultWriter?.('follow')).toEqual({ ok: true });+ expect(committedPatches).toEqual([{ autoSync: { default: 'follow' } }]);+ });+test('wraps binding errors into a string result for toast rendering', async () => {await loadHooks();projectBinding = {@@ -288,3 +396,111 @@ describe('useSyncDefaultWriter runtime behavior', () => {});});});++describe('useSyncModeSelection runtime behavior', () => {+ let consoleErrorSpy: ReturnType<typeof spyOn> | undefined;++ afterEach(() => {+ cleanup();+ latestModeSelection = null;+ projectLocalBinding = null;+ toastErrors.length = 0;+ consoleErrorSpy?.mockRestore();+ consoleErrorSpy = undefined;+ });++ test('selecting off commits immediately without a confirmation', async () => {+ await loadHooks();+ const writes: SyncMode[] = [];+ const writer: ModeWriter = (mode) => {+ writes.push(mode);+ return { ok: true };+ };+ render(<ModeSelectionProbe writer={writer} currentMode="full" />);++ await act(async () => {+ latestModeSelection?.onModeSelect('off');+ });++ expect(writes).toEqual(['off']);+ expect(screen.getByTestId('mode-selection').textContent).toBe('false:null');+ });++ test('selecting pull opens the confirmation and writes only after confirm', async () => {+ await loadHooks();+ const writes: SyncMode[] = [];+ const writer: ModeWriter = (mode) => {+ writes.push(mode);+ return { ok: true };+ };+ render(<ModeSelectionProbe writer={writer} currentMode="off" />);++ await act(async () => {+ latestModeSelection?.onModeSelect('follow');+ });+ expect(screen.getByTestId('mode-selection').textContent).toBe('true:follow');+ expect(writes).toEqual([]);++ await act(async () => {+ latestModeSelection?.onConfirm();+ });+ expect(writes).toEqual(['follow']);+ expect(screen.getByTestId('mode-selection').textContent).toBe('false:follow');+ });++ test('escalating pull to full confirms with the full variant', async () => {+ await loadHooks();+ const writes: SyncMode[] = [];+ const writer: ModeWriter = (mode) => {+ writes.push(mode);+ return { ok: true };+ };+ render(<ModeSelectionProbe writer={writer} currentMode="follow" />);++ await act(async () => {+ latestModeSelection?.onModeSelect('full');+ });+ expect(screen.getByTestId('mode-selection').textContent).toBe('true:full');++ await act(async () => {+ latestModeSelection?.onConfirm();+ });+ expect(writes).toEqual(['full']);+ });++ test('re-selecting the current mode is a no-op', async () => {+ await loadHooks();+ const writes: SyncMode[] = [];+ const writer: ModeWriter = (mode) => {+ writes.push(mode);+ return { ok: true };+ };+ render(<ModeSelectionProbe writer={writer} currentMode="follow" />);++ await act(async () => {+ latestModeSelection?.onModeSelect('follow');+ });++ expect(writes).toEqual([]);+ expect(screen.getByTestId('mode-selection').textContent).toBe('false:null');+ });++ test('a failed confirm keeps the dialog open and toasts', async () => {+ await loadHooks();+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const writer: ModeWriter = () => ({ ok: false, error: 'branch is protected' });+ render(<ModeSelectionProbe writer={writer} currentMode="off" />);++ // Two clicks in the real UI (select, re-render shows the dialog, then+ // confirm) — split acts so `onConfirm` reads the committed pendingMode.+ await act(async () => {+ latestModeSelection?.onModeSelect('full');+ });+ await act(async () => {+ latestModeSelection?.onConfirm();+ });++ expect(screen.getByTestId('mode-selection').textContent).toBe('true:full');+ expect(toastErrors).toEqual(['Failed to update sync mode — branch is protected']);+ });+});diff --git a/packages/app/src/hooks/use-enable-sync-with-confirm.ts b/packages/app/src/hooks/use-enable-sync-with-confirm.tsindex 145b51250..80afbc71f 100644--- a/packages/app/src/hooks/use-enable-sync-with-confirm.ts+++ b/packages/app/src/hooks/use-enable-sync-with-confirm.ts@@ -19,7 +19,17 @@* surfaces (CLI, Tauri IPC) can supply their own without touching this* hook.*/-import { humanFormat } from '@inkeep/open-knowledge-core';+import {+ displayActiveMode,+ hasEverEnabledSync,+ humanFormat,+ isSyncPaused,+ resolveLocalAutoSyncMode,+ type StoredSyncActiveMode,+ type StoredSyncMode,+ type SyncActiveMode,+ type SyncMode,+} from '@inkeep/open-knowledge-core';import { useLingui } from '@lingui/react/macro';import { useState } from 'react';import { toast } from 'sonner';@@ -34,32 +44,66 @@ import { useConfigContext } from '@/lib/config-provider';type SyncEnabledWriter = (enabled: boolean) => { ok: true } | { ok: false; error: string };/**- * Build a `SyncEnabledWriter` that targets the project-local config binding- * from `ConfigProvider`. Returns `null` until the binding mounts (cold-- * start window before the Hocuspocus provider connects); callers should- * check for null before letting the user trigger a write.+ * Legacy boolean writer targeting the project-local `autoSync.enabled` leaf.+ * Retained for the full-sync enable/disable surfaces that predate the three-way+ * mode (the share-receive recovery CTAs). The engine still honors `enabled`+ * (`resolveLocalAutoSyncMode` derives a mode from it when `mode` is absent), so+ * these surfaces keep working; new mode-aware surfaces use `useSyncModeWriter`.*- * Single source of the binding → writer translation so adding a future- * surface (e.g. a keyboard-shortcut quick-toggle) doesn't need to recreate- * the `humanFormat(error)` wrapping.+ * Returns `null` until the binding mounts (cold-start window before the+ * Hocuspocus provider connects); callers check for null before writing.*/export function useSyncEnabledWriter(): SyncEnabledWriter | null {const { projectLocalBinding } = useConfigContext();if (projectLocalBinding === null) return null;return (enabled: boolean) => {- const result = projectLocalBinding.patch({ autoSync: { enabled } });+ // Write `mode` too, not just the legacy `enabled` leaf. `resolveLocalAutoSyncMode`+ // reads `mode` first, so on a machine that already chose a mode (e.g. `off` via+ // Settings) a bare `{ enabled: true }` is a silent no-op — the stale `mode` wins.+ // The legacy writer only ever maps to full/off, so the paired `enabled` stays a+ // truthful mirror (no cross-version disagreement) while `mode` drives resolution.+ const mode: SyncMode = enabled ? 'full' : 'off';+ const result = projectLocalBinding.patch({ autoSync: { mode, enabled } });+ return result.ok ? { ok: true } : { ok: false, error: humanFormat(result.error) };+ };+}++/** Adapter that persists a chosen sync mode to the project-local `autoSync.mode`. */+type SyncModeWriter = (mode: SyncMode) => { ok: true } | { ok: false; error: string };++/**+ * Build a `SyncModeWriter` targeting the project-local config binding — the+ * mode-aware successor to `useSyncEnabledWriter`. Writes the canonical+ * `autoSync.mode` knob ('off' | 'follow' | 'full'), the single value the engine+ * reads to decide whether to push. Returns `null` until the binding mounts.+ *+ * Single source of the binding → writer translation so every consent surface+ * (onboarding prompt, Settings, badge) shares the `humanFormat(error)` wrapping.+ */+export function useSyncModeWriter(): SyncModeWriter | null {+ const { projectLocalBinding } = useConfigContext();+ if (projectLocalBinding === null) return null;+ return (mode: SyncMode) => {+ // Clear the legacy `enabled` flag as we set `mode`. Leaving a stale+ // `enabled: true` behind lets an app that predates `mode` read the project+ // as full-sync and push for a mode the user switched away from; `null` is+ // the "unanswered" sentinel, so the two layers can never disagree.+ const result = projectLocalBinding.patch({ autoSync: { mode, enabled: null } });return result.ok ? { ok: true } : { ok: false, error: humanFormat(result.error) };};}/*** Adapter for the COMMITTED project sync default (`autoSync.default`). Unlike- * `SyncEnabledWriter` (a per-machine boolean), this carries the tri-state seed- * the maintainer ships to everyone: `true` = default on, `false` = default off,- * `null` = ask (clears the committed key via RFC 7396 merge-patch, restoring the- * onboarding prompt).+ * `SyncEnabledWriter` (a per-machine boolean), this carries the seed the+ * maintainer ships to everyone. It accepts the mode vocabulary (`'off'` |+ * `'follow'` | `'full'`) as well as the legacy boolean seed (`true` = full,+ * `false` = off); `null` = ask (clears the committed key via RFC 7396 merge-patch,+ * restoring the onboarding prompt).*/-type SyncDefaultWriter = (next: boolean | null) => { ok: true } | { ok: false; error: string };+type SyncDefaultWriter = (+ next: boolean | SyncMode | null,+) => { ok: true } | { ok: false; error: string };/*** Build a `SyncDefaultWriter` targeting the COMMITTED project ConfigBinding@@ -71,7 +115,7 @@ type SyncDefaultWriter = (next: boolean | null) => { ok: true } | { ok: false; eexport function useSyncDefaultWriter(): SyncDefaultWriter | null {const { projectBinding } = useConfigContext();if (projectBinding === null) return null;- return (next: boolean | null) => {+ return (next: boolean | SyncMode | null) => {const result = projectBinding.patch({ autoSync: { default: next } });return result.ok ? { ok: true } : { ok: false, error: humanFormat(result.error) };};@@ -136,3 +180,224 @@ export function useEnableSyncWithConfirm(return { confirmOpen, setConfirmOpen, onToggleRequest, onConfirm };}++/** The two modes whose selection crosses a consent boundary and must confirm. */+type ConfirmableMode = Exclude<SyncMode, 'off'>;++interface UseSyncModeSelectionResult {+ /** Whether the confirmation dialog is open. */+ confirmOpen: boolean;+ /** Open/close the confirmation dialog (controlled). */+ setConfirmOpen: (open: boolean) => void;+ /**+ * The mode a pending confirmation will apply; `null` when idle. Drives the+ * confirm dialog's variant ('follow' vs 'full' copy).+ */+ pendingMode: ConfirmableMode | null;+ /** Call with the mode the user picked in the three-way selector. */+ onModeSelect: (next: SyncMode) => void;+ /** Call from the confirmation dialog's confirm button. */+ onConfirm: () => void;+}++/**+ * Mode-aware counterpart to {@link useEnableSyncWithConfirm} for the three-way+ * sync-mode selector. Selecting `off` commits immediately (turning sync off+ * never pushes or rewrites the tree — the safe direction). Selecting `pull` or+ * `full`, or escalating `pull`→`full`, gates behind the confirmation dialog so+ * enabling is always an explicit, informed act. Re-selecting the current mode is+ * a no-op.+ *+ * `currentMode` is the resolved per-machine mode; the caller renders+ * `<EnableSyncConfirmDialog variant={pendingMode ?? 'full'} ...>` with the+ * returned props.+ */+export function useSyncModeSelection(+ writer: SyncModeWriter | null,+ currentMode: SyncMode,+): UseSyncModeSelectionResult {+ const { t } = useLingui();+ const [confirmOpen, setConfirmOpen] = useState(false);+ const [pendingMode, setPendingMode] = useState<ConfirmableMode | null>(null);++ function applyMode(next: SyncMode): boolean {+ if (writer === null) {+ toast.error(t`Sync settings not yet loaded — try again in a moment`);+ return false;+ }+ const result = writer(next);+ if (!result.ok) {+ console.error('[sync] mode change failed:', result.error);+ const detail = result.error;+ toast.error(t`Failed to update sync mode — ${detail}`);+ return false;+ }+ return true;+ }++ function onModeSelect(next: SyncMode) {+ if (next === currentMode) return;+ if (next === 'off') {+ applyMode('off');+ return;+ }+ setPendingMode(next);+ setConfirmOpen(true);+ }++ function onConfirm() {+ if (pendingMode === null) return;+ // Close only on success — a failed write keeps the dialog up so the user can+ // retry, matching the boolean confirm path.+ if (applyMode(pendingMode)) {+ setConfirmOpen(false);+ }+ }++ return { confirmOpen, setConfirmOpen, pendingMode, onModeSelect, onConfirm };+}++/** Fields the badge control patches on the project-local `autoSync` object. */+type AutoSyncPatch = { mode?: SyncMode; enabled?: null; resumeMode?: SyncActiveMode | null };+type AutoSyncPatchWriter = (patch: AutoSyncPatch) => { ok: true } | { ok: false; error: string };++/**+ * Low-level writer for an arbitrary project-local `autoSync` merge-patch — the+ * badge control needs to set `mode` and `resumeMode` together (or `resumeMode`+ * alone while paused), which the single-value {@link useSyncModeWriter} can't+ * express. A `resumeMode: null` clears the key via RFC 7396 merge-patch. Returns+ * `null` until the binding mounts.+ */+export function useAutoSyncPatchWriter(): AutoSyncPatchWriter | null {+ const { projectLocalBinding } = useConfigContext();+ if (projectLocalBinding === null) return null;+ return (patch: AutoSyncPatch) => {+ const result = projectLocalBinding.patch({ autoSync: patch });+ return result.ok ? { ok: true } : { ok: false, error: humanFormat(result.error) };+ };+}++interface UseBadgeSyncControlsResult {+ /** Sync is running (mode pull or full) — the header Switch is on. */+ active: boolean;+ /** Sync was enabled then turned off — badge stays visible, mode still editable. */+ paused: boolean;+ /** Sync has ever been enabled — gates the manual "Sync" action. */+ everEnabled: boolean;+ /** The value the Full/Follow control shows: live mode when active, else the resume memory. */+ toggleMode: SyncActiveMode;+ confirmOpen: boolean;+ setConfirmOpen: (open: boolean) => void;+ /** Drives the confirm dialog variant ('follow' vs 'full'); null when idle. */+ pendingMode: ConfirmableMode | null;+ /** Unpushed commits disclosed on a full→follow downgrade confirm (0 otherwise). */+ strandedCommitCount: number;+ /** Header Switch handler: on = resume into `toggleMode`, off = pause. */+ onToggleActive: (next: boolean) => void;+ /** Full/Follow control handler. */+ onModeSelect: (next: SyncActiveMode) => void;+ onConfirm: () => void;+}++/**+ * Sync controls for the badge popover, where the header Switch means+ * active-vs-paused (not a mode) and a separate Full/Follow control sets the+ * mode. Pausing persists as `mode: 'off'` plus a remembered `resumeMode`, so an+ * older app reads a paused project as not-syncing (never pushes) while this app+ * can restore the prior mode. Entering `full` (which pushes) always confirms;+ * resuming into or staying on `pull` never pushes, so it applies immediately.+ * While paused, changing the Full/Follow control only updates the resume memory+ * — nothing syncs until the Switch is turned back on.+ */+export function useBadgeSyncControls(+ autoSync:+ | {+ mode?: StoredSyncMode | null;+ enabled?: boolean | null;+ resumeMode?: StoredSyncActiveMode | null;+ }+ | undefined,+ aheadCount: number,+): UseBadgeSyncControlsResult {+ const { t } = useLingui();+ const writer = useAutoSyncPatchWriter();+ const [confirmOpen, setConfirmOpen] = useState(false);+ const [pendingMode, setPendingMode] = useState<ConfirmableMode | null>(null);++ const localMode = resolveLocalAutoSyncMode(autoSync) ?? 'off';+ const active = localMode === 'follow' || localMode === 'full';+ const paused = isSyncPaused(autoSync);+ const everEnabled = hasEverEnabledSync(autoSync);+ const toggleMode = displayActiveMode(autoSync);++ function apply(patch: AutoSyncPatch): boolean {+ if (writer === null) {+ toast.error(t`Sync settings not yet loaded — try again in a moment`);+ return false;+ }+ const result = writer(patch);+ if (!result.ok) {+ console.error('[sync] badge control failed:', result.error);+ const detail = result.error;+ toast.error(t`Failed to update sync — ${detail}`);+ return false;+ }+ return true;+ }++ function onToggleActive(next: boolean) {+ if (next) {+ // Resume into the remembered mode. Full pushes, so it confirms; pull does+ // not, so it applies immediately (the user consented before pausing).+ if (toggleMode === 'full') {+ setPendingMode('full');+ setConfirmOpen(true);+ return;+ }+ apply({ mode: 'follow', enabled: null, resumeMode: null });+ return;+ }+ // Pause: store 'off' (so an old app never pushes) and remember the mode.+ apply({+ mode: 'off',+ enabled: null,+ resumeMode: active ? (localMode as SyncActiveMode) : toggleMode,+ });+ }++ function onModeSelect(next: SyncActiveMode) {+ if (next === toggleMode) return;+ if (!active) {+ // Paused/off: just remember which mode to resume into — nothing syncs yet,+ // so no push and no confirmation.+ apply({ resumeMode: next });+ return;+ }+ // Active: entering full pushes; downgrading full→follow strands unpushed+ // commits — both cross a consent boundary, so confirm.+ setPendingMode(next);+ setConfirmOpen(true);+ }++ function onConfirm() {+ if (pendingMode === null) return;+ if (apply({ mode: pendingMode, enabled: null, resumeMode: null })) {+ setConfirmOpen(false);+ setPendingMode(null);+ }+ }++ return {+ active,+ paused,+ everEnabled,+ toggleMode,+ confirmOpen,+ setConfirmOpen,+ pendingMode,+ strandedCommitCount: pendingMode === 'follow' ? aheadCount : 0,+ onToggleActive,+ onModeSelect,+ onConfirm,+ };+}diff --git a/packages/app/src/hooks/use-git-sync-status.ts b/packages/app/src/hooks/use-git-sync-status.tsindex f84855c0c..e2528204e 100644--- a/packages/app/src/hooks/use-git-sync-status.ts+++ b/packages/app/src/hooks/use-git-sync-status.ts@@ -6,7 +6,9 @@*/import type {PushPermissionWire as GitPushPermission,+ PullOutcome,SyncErrorCode,+ SyncMode,} from '@inkeep/open-knowledge-core';import { useEffect, useState } from 'react';import { subscribeToDocumentsChanged } from '@/lib/documents-events';@@ -36,13 +38,32 @@ export interface GitSyncStatus {state: GitSyncState;lastSyncUtc: string | null;lastFetchUtc: string | null;+ /**+ * Completion timestamp + bounded outcome of the last pull (background or+ * one-shot). Optional for version-skew safety — absent from a payload emitted+ * by an engine that predates the outcome contract. A surface that triggers a+ * pull reads status first, then waits for `lastPullUtc` to change and reads+ * `lastPullOutcome`.+ */+ lastPullUtc?: string | null;+ lastPullOutcome?: PullOutcome | null;ahead: number;behind: number;conflictCount: number;/** True when a git remote exists, even if sync is dormant/disabled. */hasRemote: boolean;- /** User's sync toggle preference (false by default — disabled for safety). */+ /**+ * True when sync is on at all (both `pull` and `full`), false for `off`.+ * Read `syncMode` to branch on push capability — this boolean cannot tell+ * pull-only from full.+ */syncEnabled: boolean;+ /**+ * Project sync mode. Optional for version-skew safety — absent from a status+ * payload emitted by an engine that predates the field. `full` is the only+ * mode that pushes.+ */+ syncMode?: SyncMode;/*** Soft signal: the git identity chain (merged git config → OAuth)* returned null on the last probe. Commits still succeed under a defaultdiff --git a/packages/app/src/hooks/use-worktree-autosync-notice.dom.test.tsx b/packages/app/src/hooks/use-worktree-autosync-notice.dom.test.tsxindex 7b354554c..0a5743ecc 100644--- a/packages/app/src/hooks/use-worktree-autosync-notice.dom.test.tsx+++ b/packages/app/src/hooks/use-worktree-autosync-notice.dom.test.tsx@@ -1,13 +1,24 @@import { cleanup, render, waitFor } from '@testing-library/react';+import type { ReactNode } from 'react';import { beforeEach, describe, expect, test, vi } from 'vitest';-const toast = vi.fn((_node: unknown) => {});+const toastNodes: ReactNode[] = [];+const toast = vi.fn((node: ReactNode) => {+ toastNodes.push(node);+});vi.doMock('sonner', () => ({ toast }));+import * as actualLinguiMacro from '@lingui/react/macro';++vi.doMock('@lingui/react/macro', () => ({+ ...actualLinguiMacro,+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,+}));+let ctx: {projectLocalConfig: unknown;projectLocalSynced: boolean;- projectLocalBinding: { patch: ReturnType<typeof vi.fn> } | null;+ projectLocalBinding: { patch: ReturnType<typeof mock> } | null;};vi.doMock('@/lib/config-provider', () => ({ useConfigContext: () => ctx }));@@ -20,19 +31,27 @@ function Probe() {return null;}+/** Render the most recent captured toast node and read its text. */+function lastToastText(): string {+ const node = toastNodes[toastNodes.length - 1];+ const { container } = render(node);+ return container.textContent ?? '';+}+const patch = vi.fn(() => ({ ok: true }));beforeEach(() => {cleanup();toast.mockClear();patch.mockClear();+ toastNodes.length = 0;ctx = { projectLocalConfig: null, projectLocalSynced: true, projectLocalBinding: { patch } };});describe('useWorktreeAutoSyncNotice', () => {test('fires one toast for an inherited worktree and clears the flag', async () => {ctx.projectLocalConfig = {- autoSync: { enabled: true, inheritedNoticePending: true, inheritedFrom: 'my-repo' },+ autoSync: { mode: 'full', inheritedNoticePending: true, inheritedFrom: 'my-repo' },};render(<Probe />);await waitFor(() => expect(toast).toHaveBeenCalledTimes(1));@@ -40,8 +59,26 @@ describe('useWorktreeAutoSyncNotice', () => {expect(patch).toHaveBeenCalledWith({ autoSync: { inheritedNoticePending: null } });});+ test('phrases the notice for an inherited pull-only worktree', async () => {+ ctx.projectLocalConfig = {+ autoSync: { mode: 'follow', inheritedNoticePending: true, inheritedFrom: 'my-repo' },+ };+ render(<Probe />);+ await waitFor(() => expect(toast).toHaveBeenCalledTimes(1));+ expect(lastToastText()).toContain('Follow is on for this worktree, inherited from my-repo');+ });++ test('phrases the notice for an inherited off worktree via the legacy enabled seed', async () => {+ ctx.projectLocalConfig = {+ autoSync: { enabled: false, inheritedNoticePending: true, inheritedFrom: 'my-repo' },+ };+ render(<Probe />);+ await waitFor(() => expect(toast).toHaveBeenCalledTimes(1));+ expect(lastToastText()).toContain('Auto-sync is off for this worktree');+ });+test('does nothing when the flag is not set', () => {- ctx.projectLocalConfig = { autoSync: { enabled: true } };+ ctx.projectLocalConfig = { autoSync: { mode: 'full' } };render(<Probe />);expect(toast).not.toHaveBeenCalled();expect(patch).not.toHaveBeenCalled();@@ -50,7 +87,7 @@ describe('useWorktreeAutoSyncNotice', () => {test('waits for the project-local binding to sync before firing', () => {ctx.projectLocalSynced = false;ctx.projectLocalConfig = {- autoSync: { enabled: false, inheritedNoticePending: true, inheritedFrom: 'my-repo' },+ autoSync: { mode: 'off', inheritedNoticePending: true, inheritedFrom: 'my-repo' },};render(<Probe />);expect(toast).not.toHaveBeenCalled();diff --git a/packages/app/src/hooks/use-worktree-autosync-notice.tsx b/packages/app/src/hooks/use-worktree-autosync-notice.tsxindex 52e6f8032..f8fbae652 100644--- a/packages/app/src/hooks/use-worktree-autosync-notice.tsx+++ b/packages/app/src/hooks/use-worktree-autosync-notice.tsx@@ -1,10 +1,10 @@/*** One-time toast telling the user a newly-opened worktree INHERITED the root- * project's git auto-sync setting (so the inheritance isn't silent).+ * project's git sync setting (so the inheritance isn't silent).** When a worktree is created, `seedWorktreeAutoSync` (desktop main) seeds the- * worktree's project-local `autoSync.enabled` from the root's resolved choice- * and arms a one-shot `autoSync.inheritedNoticePending: true` flag (plus+ * worktree's project-local `autoSync.mode` from the root's resolved choice and+ * arms a one-shot `autoSync.inheritedNoticePending: true` flag (plus* `autoSync.inheritedFrom: <project>`) — both loose keys on the `autoSync`* `looseObject`, so no schema change. On first open, this hook reads the flag,* fires ONE non-blocking toast, and CLEARS the flag on the project-local binding@@ -15,6 +15,7 @@* accepts a ReactNode rendered inside the app's I18nProvider.*/+import { resolveLocalAutoSyncMode, type SyncMode } from '@inkeep/open-knowledge-core';import { Trans } from '@lingui/react/macro';import { useEffect, useRef } from 'react';import { toast } from 'sonner';@@ -22,11 +23,34 @@ import { useConfigContext } from '@/lib/config-provider';/** The loose auto-sync notice keys the desktop seed writes (not in the strict schema). */interface InheritedAutoSync {+ mode?: SyncMode | null;enabled?: boolean | null;inheritedNoticePending?: unknown;inheritedFrom?: unknown;}+function inheritedNoticeMessage(mode: SyncMode | null, project: string) {+ if (mode === 'follow') {+ return (+ <Trans>+ Follow is on for this worktree, inherited from {project}. Change it in Settings → Sync.+ </Trans>+ );+ }+ if (mode === 'full') {+ return (+ <Trans>+ Auto-sync is on for this worktree, inherited from {project}. Change it in Settings → Sync.+ </Trans>+ );+ }+ return (+ <Trans>+ Auto-sync is off for this worktree, inherited from {project}. Change it in Settings → Sync.+ </Trans>+ );+}+export function useWorktreeAutoSyncNotice(): void {const { projectLocalConfig, projectLocalSynced, projectLocalBinding } = useConfigContext();// Fire at most once per mounted window — the flag-clear write also stops it,@@ -40,18 +64,8 @@ export function useWorktreeAutoSyncNotice(): void {shownRef.current = true;const project = typeof autoSync.inheritedFrom === 'string' ? autoSync.inheritedFrom : '';- toast(- autoSync.enabled === true ? (- <Trans>- Auto-sync is on for this worktree, inherited from {project}. Change it in Settings → Sync.- </Trans>- ) : (- <Trans>- Auto-sync is off for this worktree, inherited from {project}. Change it in Settings →- Sync.- </Trans>- ),- );+ const mode = resolveLocalAutoSyncMode({ mode: autoSync.mode, enabled: autoSync.enabled });+ toast(inheritedNoticeMessage(mode, project));// Clear the one-shot flag so the notice never repeats (persisted).projectLocalBinding.patch({ autoSync: { inheritedNoticePending: null } });}, [projectLocalSynced, projectLocalConfig, projectLocalBinding]);diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 3a4cc9592..c32468c15 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -21,8 +21,11 @@"-YV1Uo": ["Pattern ", ["patternNumber"]],"-bFGPF": ["Next change"],"-dNlfM": ["Undid the last edit on ", ["docName"]],+ "-f2Ogn": [+ "Keep this project in sync with your git remote. Follow fetches updates without pushing; full sync pushes your commits too. Turning sync on requires confirmation."+ ],"-g6KIS": ["Unrecognized link"],- "-gdcIo": ["Auto-sync is on — your commits push and remote changes pull on intervals."],+ "-imiMK": ["Follow — updates flow in from your remote; your edits stay on this computer."],"-kbIAr": ["Links & images"],"-lCAuQ": ["Loading graph"],"-o5XAG": [@@ -86,6 +89,7 @@"0t0bbC": ["Could not save sync preference: ", ["detail"]],"0uTHCg": ["Start a new OpenKnowledge project."],"0wswKc": ["Horizontal rule that divides sections."],+ "0xnQ_X": ["Updates flow in"],"0xnmlQ": ["Repository name"],"0yL--g": ["Review conflicts"],"10g8I_": ["Turn off Only markdown files"],@@ -236,6 +240,7 @@"4A3Yzu": ["Code block"],"4BITzH": ["Error:"],"4CfgPM": ["Project folder created, but git init failed. Try again."],+ "4DcimZ": ["Updated ", ["lastSyncedRelative"]],"4E9jPa": ["Create your first project"],"4EZrJN": ["Rules"],"4Gz2wC": ["Failed to upload file"],@@ -331,6 +336,7 @@}]],+ "5rnB76": ["Your edits stay on this computer"],"5vYdh9": ["New thread with ", ["0"]],"5wV2qQ": ["and more"],"5y_9lO": ["Waiting for authorization"],@@ -390,6 +396,7 @@"7FamGZ": ["Go to line"],"7Fkcej": ["+ Add ", ["addChildName"]],"7H4UHD": ["Documents tagged <0>#", ["tagName"], "</0>"],+ "7IsvrP": ["Checking for updates"],"7JtSLi": ["Failed to delete path"],"7OhaRy": ["Source search"],"7Ongq0": ["Condense my AGENTS.md file to less than 40k characters"],@@ -446,6 +453,9 @@"8RtNI0": ["Failed to load documents"],"8TvlHF": ["Crash dump"],"8Vq20-": ["Switch worktree"],+ "8Wav8y": [+ "If an update arrives for something you are editing, you choose which version to keep, like a merge conflict."+ ],"8XQRON": ["Loading repositories"],"8_brI5": ["Name is required"],"8cS0nH": ["Config sharing unavailable: ", ["0"], "."],@@ -459,6 +469,7 @@"8m8diM": ["No location selected. Use Browse to choose a folder."],"8nWu1k": ["Empty diagram"],"8ruqQi": ["Broken internal links"],+ "8sMErm": ["Enable Follow?"],"8t9CRE": ["Starting ", ["agentName"], "…"],"8tjQCz": ["Explore"],"8uAWix": [@@ -616,6 +627,9 @@"CSL0l1": ["Couldn't clear the key — please try again."],"CTJLpz": ["\"", ["trimmed"], "\" already exists here"],"CU3AiE": ["Switching branches"],+ "CVRM5N": [+ "Follow fetches updates from your remote git repository and fast-forwards your copy automatically. Your local edits stay on this computer and are never pushed."+ ],"CWzc2T": ["<0>~/.ok/bin</0> and <1>~/.ok/env.sh</1> stay either way — the app always maintains them."],@@ -630,6 +644,7 @@"CifUuG": ["Update available"],"Ck9XRt": ["Couldn't save the key — please try again."],"CmeH9S": ["Add property to ", ["keyName"]],+ "CnOGgs": ["Sync mode"],"CoHvYd": ["Moved ", ["0"], " to position ", ["1"], " of ", ["2"]],"CooKEf": ["Dock sessions at the bottom"],"CvsD6Y": ["via ", ["viaTags"]],@@ -807,7 +822,6 @@"FZtBeR": ["Enable ", ["0"]],"FgRAvd": ["Logs & system info"],"FjkaiT": ["Zoom out"],- "FnMkli": ["Sync disabled — you don't have permission to push"],"FqGWeR": ["Couldn't reach the agent registry."],"FqTpiN": ["Bird wiki"],"Fqr8BP": ["Multi-page PDF viewer with toolbar controls (thumbnails, page nav, zoom)."],@@ -1061,6 +1075,7 @@"LKOLNn": ["No AI agents installed"],"LNum6A": [["minutes"], " min ago"],"LPAv9E": [["days"], "d ago"],+ "LQsCPn": ["Local commits are keeping this copy from updating"],"LRgZAt": [["owner"], "/", ["name"], " already exists"],"LTeJuX": ["Toggle Full Screen"],"LXdWeS": ["Medium section heading."],@@ -1115,13 +1130,14 @@"MCjC9A": ["Delete ", ["deleteDescriptorLabel"]],"MDBJwN": ["Hard to use"],"MDZSJe": ["When the agent runs its scheduled work."],+ "MGBNwj": ["Pause sync"],"MGb89P": ["Insert, delete, move, copy, and indent source editor lines through CodeMirror's default keymap."],"MHrjPM": ["Title"],"MJqRO6": ["Your report is being sent."],"MJuO1q": ["Context window:"],- "MKOVhz": ["Enable git auto-sync"],+ "MKEPCY": ["Follow"],"MQIM_Y": ["Couldn't copy. Select the URL above to copy it manually."],"MRZxAn": ["Edited"],"MTs6g3": ["Couldn't reconnect after server restart"],@@ -1194,7 +1210,6 @@"NgZwB0": [["enabledCount"], "/", ["0"], " on"],"NjrIak": ["File: <0>", ["fixedName"], ".md</0>"],"NkXEFS": ["Restore failed — document unchanged"],- "Nm-3m-": ["Auto-sync is paused — you don't have permission to push to this repo."],"NmPNJJ": ["Copy code"],"Nn4GgW": ["Will be created as <0>", ["sanitizedName"], "</0>"],"NnQapF": ["Open with AI ", ["targetDisplayName"]],@@ -1206,7 +1221,6 @@"Nv3mUj": ["Show advanced"],"NvOvTi": ["Create in <0>", ["dirDisplay"], "</0>"],"Nwbs0q": ["Don't show"],- "Nx7BWE": ["Git auto-sync"],"NxW-md": ["Resize ", ["handleKey"]],"NzFvyK": ["Session ended — undo unavailable"],"NzluOx": ["(optional)"],@@ -1254,7 +1268,6 @@],"Okd2Xv": ["Toggle underline formatting."],"OlAl5i": ["Expand all"],- "OmHTGj": ["Disable git auto-sync"],"Oo_WWc": ["No pages found"],"Oos8fo": ["Copy command"],"OplnBG": ["Managing AI tools is unavailable in this build."],@@ -1283,6 +1296,7 @@"PQCdtv": ["\"", ["docName"], "\" doesn't exist."],"PR9FSv": ["Move to the next visual-editor find result."],"PRnH8G": ["of ", ["0"]],+ "PTb1Nx": ["Sync is paused. Turn it back on to resume."],"PVUn_c": ["Open folder"],"PYmp-0": ["Import as template"],"PZtgO0": ["Opening worktree"],@@ -1322,6 +1336,7 @@"QQghPu": ["Install in Claude Desktop"],"QR5SP1": ["created template"],"QTsvh1": ["This agent needs you to sign in first — see the notice below."],+ "QYTOaN": ["You can change this later in <0>Settings → Sync</0>."],"QYfQdv": [["displayName"], " CLI"],"QcpeeE": ["Navigate to ", ["docName"]],"QfFBdJ": ["The template's filename (without `.md`)."],@@ -1430,13 +1445,15 @@"Sq8lf2": ["Editors to install skills into"],"SrOuyg": ["Document panels"],"SvBFYA": ["No recent projects"],+ "Sxx_Zz": [+ "Follow is on for this worktree, inherited from ",+ ["project"],+ ". Change it in Settings → Sync."+ ],"T-654M": ["Loading PDF"],"T0OVm7": ["The default branch is protected — pushes need a pull request."],"T3Mld1": ["Window"],"T3j-7o": ["e.g. Switching projects while a sync was running"],- "T67A0Y": [- "Auto-sync pushes/pulls commits to your git remote on intervals and on save. Toggling on requires confirmation."- ],"TEEPPF": ["Will replace existing OpenKnowledge entry"],"TJnkyf": ["ok ui responded but server.lock has no port yet"],"TKQ7K-": ["Install"],@@ -1464,7 +1481,9 @@"U2Kx6T": ["Close all unpinned"],"U2pMtf": ["tag-name"],"U3IvM5": ["Full guide"],+ "U4nTfu": ["Enable Follow"],"U5Spo9": ["Content directory must be inside the project"],+ "U6wmNc": ["Sync paused"],"U7HJ4y": ["Managed by OpenKnowledge (read-only)"],"U8CD-l": ["Copy full path, No workspace"],"U9tm58": ["Hide problem indicators"],@@ -1482,6 +1501,9 @@"UTNVyS": ["Select the full source document."],"UTZ97u": ["Selection must be inside the project"],"UTgWxm": ["Nothing was uploaded. The report stays on this Mac until you email it to us."],+ "UVDasf": [+ "Sync is off — your edits stay on this computer until you commit and push manually."+ ],"UVLlMV": ["Couldn't reach GitHub. Try again?"],"UW2Fg3": ["This project's running server doesn't support live editing. Restart OpenKnowledge to fix."@@ -1557,9 +1579,6 @@"W0i24j": ["Object"],"W1SI2K": [["0", "plural", { "one": ["#", " warning"], "other": ["#", " warnings"] }]],"W1qRuM": ["This document is already active in the editor. Use Open to collapse the graph."],- "W3Xlpc": [- "Set the auto-sync default for users opening this project for the first time. This setting is committed to your repository."- ],"W5A0Ly": ["An unexpected error occurred."],"W7XJN4": ["Can't nest projects. An OpenKnowledge project already exists at <0>",@@ -1603,7 +1622,6 @@"WmPbvm": ["Get product updates in your inbox."],"Wq6Wcm": ["Please enter a valid email address."],"WqLq6M": ["Open with AI ", ["displayName"]],- "Wt5W56": ["Sync is off — your edits will not sync to the remote repository."],"Wtw22s": ["Installing"],"WuntOK": ["Preview of the screenshot"],"WyQxwa": ["Connect this project to GitHub to share."],@@ -1703,7 +1721,6 @@"Z1LF1M": ["Sharing a doc needs a GitHub repository. Create one for this project."],"Z2M5XM": ["Reason: ", ["reason"], " (", ["osDetail"], ")"],"Z3FXyt": ["Loading..."],- "Z5HWHd": ["On"],"Z5h97D": ["Hide files and folders from your knowledge base. Hidden items don’t appear in the file tree, search, or AI tools. <0>Learn more about patterns</0>."],@@ -1722,11 +1739,11 @@"ZBt4rI": ["Instruction for the AI"],"ZBxvV3": ["New Terminal"],"ZI8uvA": ["No problems found."],- "ZLQol-": ["You can turn this on later in <0>Settings → Sync</0>."],"ZNK2Tq": ["root"],"ZQJ1IV": ["Activate the last editor tab."],"ZQLDTl": ["created folder"],"ZU8VV_": ["Remove failed: ", ["error"]],+ "ZVOhXM": ["Failed to update sync — ", ["detail"]],"ZW3mlR": ["Diff render mode"],"ZWgr0b": ["In a subfolder"],"ZWolSV": [@@ -1820,6 +1837,7 @@"a9OzSn": ["No pages found for \"", ["trimmedQuery"], "\""],"aBgwis": ["Scope"],"aByJ8j": ["How does sharing work?"],+ "aCoQfY": ["New changes from your remote appear in your copy automatically."],"aE2_XM": ["One pattern per line — appended to <0>.okignore</0>."],"aENGMB": ["Semantic search adds meaning-based ranking to the search tool so conceptually-related pages surface even without shared keywords."@@ -1838,6 +1856,9 @@"abiHje": ["Delete selected items"],"adsMWO": ["Resolving deltas"],"aiArms": ["We couldn't clone this repository."],+ "ajHi4O": [+ "Auto-sync is paused — you don't have permission to push to this repo. Switch to Follow to keep receiving updates."+ ],"ajz9F8": ["Couldn't load conflict content for ", ["filePath"], ". Try reloading the page."],"ak4LLg": ["Clear menu"],"anmUZq": ["Missing a feature"],@@ -1911,6 +1932,20 @@"cZGNlb": ["Add another pattern"],"cZI5AL": ["OK Desktop"],"cZ_8zB": ["Stays on this computer."],+ "caw8gO": [+ [+ "strandedCommitCount",+ "plural",+ {+ "one": ["You have 1 change you haven't shared. It will stay on this computer."],+ "other": [+ "You have ",+ "#",+ " changes you haven't shared. They will stay on this computer."+ ]+ }+ ]+ ],"ccNps_": ["Only modified"],"cd5EXh": ["Report a bug"],"cdm00A": ["No Incoming"],@@ -1974,7 +2009,6 @@],"dprWmL": ["Anchor in this page"],"dr1vFs": ["Replace all matches"],- "dvGKu2": ["Shared auto-sync default"],"dw_3cv": ["Rename skill"],"dw_dUJ": ["Failed to duplicate path"],"dx-TwN": ["Running project audit"],@@ -2010,6 +2044,9 @@"Mark a block as the source of truth. Mirrors elsewhere update live as you edit it."],"euc6Ns": ["Duplicate"],+ "evHlIg": [+ "Follow never pushes or commits your local changes. They stay only on this machine."+ ],"evs0iw": ["Tags matching \"", ["tagListQuery"], "\""],"f1XQyZ": ["Move block"],"f3Nvg7": [@@ -2051,6 +2088,7 @@"fwrPh4": ["Please enter a valid email."],"fxJk_6": ["<0>Have more to add?</0> Write to <1/> and mention your reference."],"fxbCNQ": ["Synced. The link is up to date."],+ "g2Tj8R": ["Full"],"g3UF2V": ["Accept"],"g4WlQK": ["Project AI tool management is only available in the OpenKnowledge desktop app."],"g4XBm0": ["Small section heading."],@@ -2060,6 +2098,7 @@["descriptorLabel"],"> failed to render (likely a bad prop). Copy the source to see what went wrong, or delete the block."],+ "g85bAo": ["Synced ", ["lastSyncedRelative"]],"gBbxn_": ["Checking sign-in status"],"gGVP4q": ["Click <0>+</0> <1/> <2>Create skill</2> <3/> <4>Upload skill</4>."],"gHSAWT": ["Create worktree <0>“<1>", ["typedName"], "</1>”</0>"],@@ -2145,12 +2184,14 @@"hwFOFD": ["Settings failed to load"],"hxBHxQ": ["A line with a footnote<0><1>[1]</1></0> and a definition shown below."],"hxEUVJ": ["Initialize ", ["selectedPackName"]],+ "hxYFzm": ["Full sync — your commits push and remote changes pull automatically."],"hyCxJY": ["Open that worktree instead"],"hynz2K": ["Download started"],"i-ShMB": ["Diagram"],"i09An-": ["Restored an earlier version (", ["0"], ")"],"i1flq_": ["Wiki link suggestions"],"i3f2kh": ["No matching commands."],+ "i6ng22": ["Switch to Follow"],"i92eAT": ["We'll create a repository and start syncing — no terminal needed."],"i9OyGp": ["Undo or redo"],"i9TPUi": [@@ -2179,9 +2220,6 @@"iSLIjg": ["Connect"],"iSQTsg": ["Ordered list"],"iSnkwB": ["Failed to open cloned project."],- "iTlqm3": [- ["ahead", "plural", { "one": ["#", " commit ahead"], "other": ["#", " commits ahead"] }]- ],"iTylMl": ["Templates"],"iXTp5j": ["Scope: "],"idD8Ev": ["Saved"],@@ -2204,7 +2242,9 @@],"iuTKci": ["No edits yet."],"iv452l": ["Documentation for ", ["0"], " (opens in browser)"],+ "iy64Li": ["Full sync — your edits are committed and pushed to your remote automatically."],"iycx_A": ["Pushing"],+ "j5CWO4": ["Up to date"],"j9Vqvc": ["inherited"],"j9tqwO": ["Not in sidebar"],"jAMpHn": ["What is a starter pack?"],@@ -2298,6 +2338,7 @@"klPS-L": ["Original file — before this agent's edits."],"kmKqZg": ["Clusters"],"knjOzA": ["Tag value"],+ "ko386X": ["A document has a conflict — resolve it to keep it up to date."],"kolRU1": ["Do you want to permanently delete instead?"],"kpqWwG": ["This ", ["targetNoun"], " was removed from branch <0>", ["branch"], "</0>."],"ktspdq": ["Tint and badge files that have lint or link problems, without opening them."],@@ -2336,7 +2377,6 @@"lHCR4I": ["Clear the field to reset back to the default OpenAI endpoint."],"lHwYMr": ["Server error: ", ["status"], " ", ["statusText"]],"lI0Td2": ["Use letters, digits, <0>_</0> and <1>-</1> only."],- "lIn9L9": ["Disable sync"],"lKQnp-": ["Installed ", ["0"], " ", ["1"]],"lPzyrU": ["All hunks resolved"],"lVWEIL": ["Indexed ", ["embedded"], " of ", ["total"], " pages."],@@ -2403,6 +2443,9 @@"Repositories you've already cloned may keep syncing through git's own saved credentials, even after you disconnect."],"msqUNq": ["Ready-made folders and templates to get you started quickly."],+ "msuDyW": [+ "Set the sync default for users opening this project for the first time. This setting is committed to your repository."+ ],"mu1O0q": ["Open Knowledge can manage ",["0"],@@ -2433,6 +2476,7 @@"This path is on an external volume (/Volumes/...). OpenKnowledge will lose track of files when the drive ejects."],"nNYV3Y": ["and ", ["remaining"], " more"],+ "nOEDQs": ["Failed to update sync mode — ", ["detail"]],"nP-KFo": ["New ", ["0"], " chat"],"nP76lk": ["Applies to all projects on this machine. Claude and Codex, started from the built-in terminal, auto-approve OpenKnowledge's read and write tools (Claude also auto-runs \"ok open\"). Deleting, moving, sharing, installing skills, other commands, and non-OpenKnowledge file edits still ask. Cursor, OpenCode, and Pi are unaffected. Best-effort per agent."@@ -2499,6 +2543,7 @@["trimmed"],"</1>, in its own window under <2>.ok/worktrees/</2>."],+ "oBK5fD": ["Overlapping edits"],"oBXkm2": ["Delete code block"],"oCHfGC": ["Level"],"oCNLN8": [@@ -2592,7 +2637,6 @@"qRZh7J": ["Let Tab leave the source editor instead of indenting."],"qSKu2v": ["Source navigation and selection"],"qSxaOz": ["Accept their deletion"],- "qUB_o_": ["Auto-sync is off — your edits stay local until you commit and push manually."],"qX-ABr": ["Or to use browser sign-in instead:"],"qXN416": ["Couldn't share skills: internal error. Please restart the app."],"qXg5W9": ["File saves to <0>~/Downloads/openknowledge.skill</0>."],@@ -2655,6 +2699,7 @@"rgPqOw": ["Convert the current block to a paragraph."],"riqekz": ["Suggestion menu navigation"],"rlUzXK": ["Could not validate folder. Please try again."],+ "rn7n0G": ["Resume sync"],"roAe2K": ["Link URL"],"roiUQQ": ["This page doesn't link to anything yet."],"rppgXF": ["Disconnecting"],@@ -2780,11 +2825,13 @@"Couldn't restart the server — it's running under a different account. Restart your computer to clear it, then reopen this project."],"uR2YT3": ["Show problem indicators"],+ "uUiiyC": [+ "You don't have permission to push to this repo. Follow can still keep your copy up to date."+ ],"uVbUP8": ["Settings…"],"uWtdQR": ["No templates yet. Add one in this folder's Templates section, or in Settings → Templates."],- "uWx2ZP": ["Last sync"],"u_lS4C": ["Clone complete — opening project"],"uaUc6t": ["Restart server"],"ubMwcO": ["The terminal session ended (signal ", ["0"], ")."],@@ -2865,7 +2912,6 @@"w_Sphq": ["Attachments"],"waFx9W": ["Managed"],"wbv9xO": ["Create new project"],- "wbwHYD": ["Enable sync"],"wccmX0": ["Your embeddings provider API key, used only to create embeddings of your content for semantic search. Stored once for this machine in <0>~/.ok/secrets.yml</0> (readable only by your user account) and shared across all projects. Turn the feature on per project in This project → Search, where you can also override the endpoint."],@@ -2963,6 +3009,7 @@"yWSvcf": ["Content root"],"yWWThY": ["Asset reference"],"yYR6za": ["Display text"],+ "yZepkk": ["Git sync"],"yZmvQ4": ["This project's server (v", ["0"], ") is newer than this app (v", ["1"], ")."],"y_5CE8": ["Item ", ["0"]],"y_K0Dz": ["What happened?"],@@ -3037,6 +3084,7 @@"ztKII6": ["Failed to add item"],"zvjCD4": ["Detailed diagnostics"],"zwBp5t": ["Private"],- "zyKa-I": ["Star us on GitHub"]+ "zyKa-I": ["Star us on GitHub"],+ "zz_Wd_": ["Mode"]}}diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex e5d30caac..07d8bb908 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -285,10 +285,6 @@ msgstr "{0}y ago"msgid "{accessibleLabel} (conflict)"msgstr "{accessibleLabel} (conflict)"-#: src/components/SyncStatusBadge.tsx-msgid "{ahead, plural, one {# commit ahead} other {# commits ahead}}"-msgstr "{ahead, plural, one {# commit ahead} other {# commits ahead}}"-#: src/components/SyncStatusBadge.tsxmsgid "{ahead} ahead"msgstr "{ahead} ahead"@@ -561,6 +557,10 @@ msgstr "{sizeText} · secrets redacted · crash dump not redacted"msgid "{skillCount, plural, one {skill} other {skills}}"msgstr "{skillCount, plural, one {skill} other {skills}}"+#: src/components/EnableSyncConfirmDialog.tsx+msgid "{strandedCommitCount, plural, one {You have 1 change you haven't shared. It will stay on this computer.} other {You have # changes you haven't shared. They will stay on this computer.}}"+msgstr "{strandedCommitCount, plural, one {You have 1 change you haven't shared. It will stay on this computer.} other {You have # changes you haven't shared. They will stay on this computer.}}"+#: src/components/CreatedItemsList.tsxmsgid "{templateCount, plural, one {template} other {templates}}"msgstr "{templateCount, plural, one {template} other {templates}}"@@ -679,6 +679,10 @@ msgstr "A branch named {shareBranch} already exists. Open its worktree from themsgid "A branch with that name already exists. Open its worktree from the switcher instead."msgstr "A branch with that name already exists. Open its worktree from the switcher instead."+#: src/components/SyncStatusBadge.tsx+msgid "A document has a conflict — resolve it to keep it up to date."+msgstr "A document has a conflict — resolve it to keep it up to date."+#: src/components/CreateProjectDialog.tsxmsgid "A folder named <0>{sanitized}</0> already has files here. Pick a different name."msgstr "A folder named <0>{sanitized}</0> already has files here. Pick a different name."@@ -1224,18 +1228,10 @@ msgstr "Auto-denied"msgid "Auto-save"msgstr "Auto-save"-#: src/components/settings/SyncSection.tsx-msgid "Auto-sync is off — your edits stay local until you commit and push manually."-msgstr "Auto-sync is off — your edits stay local until you commit and push manually."-#: src/hooks/use-worktree-autosync-notice.tsxmsgid "Auto-sync is off for this worktree, inherited from {project}. Change it in Settings → Sync."msgstr "Auto-sync is off for this worktree, inherited from {project}. Change it in Settings → Sync."-#: src/components/settings/SyncSection.tsx-msgid "Auto-sync is on — your commits push and remote changes pull on intervals."-msgstr "Auto-sync is on — your commits push and remote changes pull on intervals."-#: src/hooks/use-worktree-autosync-notice.tsxmsgid "Auto-sync is on for this worktree, inherited from {project}. Change it in Settings → Sync."msgstr "Auto-sync is on for this worktree, inherited from {project}. Change it in Settings → Sync."@@ -1245,17 +1241,13 @@ msgid "Auto-sync is paused — sign in to resume."msgstr "Auto-sync is paused — sign in to resume."#: src/components/settings/SyncSection.tsx-msgid "Auto-sync is paused — you don't have permission to push to this repo."-msgstr "Auto-sync is paused — you don't have permission to push to this repo."+msgid "Auto-sync is paused — you don't have permission to push to this repo. Switch to Follow to keep receiving updates."+msgstr "Auto-sync is paused — you don't have permission to push to this repo. Switch to Follow to keep receiving updates."#: src/components/AutoSyncEnableWarning.tsxmsgid "Auto-sync periodically fetches, pulls, and pushes commits to your remote git repository so your edits stay in sync across machines."msgstr "Auto-sync periodically fetches, pulls, and pushes commits to your remote git repository so your edits stay in sync across machines."-#: src/components/settings/SyncSection.tsx-msgid "Auto-sync pushes/pulls commits to your git remote on intervals and on save. Toggling on requires confirmation."-msgstr "Auto-sync pushes/pulls commits to your git remote on intervals and on save. Toggling on requires confirmation."-#. Section label for the automatic, one-click install path#: src/components/InstallInClaudeDesktopDialog.tsxmsgid "Automatic"@@ -1547,6 +1539,10 @@ msgstr "Checkbox"msgid "Checking for agents"msgstr "Checking for agents"+#: src/components/SyncStatusBadge.tsx+msgid "Checking for updates"+msgstr "Checking for updates"+#: src/components/share-receive-miss-content.tsx#: src/components/ShareBranchSwitchDialog.tsxmsgid "Checking for updates on GitHub"@@ -3002,18 +2998,10 @@ msgstr "Disable {0}"msgid "Disable external link previews"msgstr "Disable external link previews"-#: src/components/settings/SyncSection.tsx-msgid "Disable git auto-sync"-msgstr "Disable git auto-sync"-#: src/components/settings/SearchSection.tsxmsgid "Disable semantic search"msgstr "Disable semantic search"-#: src/components/SyncStatusBadge.tsx-msgid "Disable sync"-msgstr "Disable sync"-#: src/components/settings/LintingSection.tsxmsgid "Disable Themes"msgstr "Disable Themes"@@ -3403,9 +3391,14 @@ msgstr "Enable auto-sync"msgid "Enable external link previews"msgstr "Enable external link previews"-#: src/components/settings/SyncSection.tsx-msgid "Enable git auto-sync"-msgstr "Enable git auto-sync"+#: src/components/AutoSyncOnboardingDialog.tsx+#: src/components/EnableSyncConfirmDialog.tsx+msgid "Enable Follow"+msgstr "Enable Follow"++#: src/components/AutoSyncEnableWarning.tsx+msgid "Enable Follow?"+msgstr "Enable Follow?"#: src/components/AutoSyncEnableWarning.tsxmsgid "Enable git auto-sync?"@@ -3415,10 +3408,6 @@ msgstr "Enable git auto-sync?"msgid "Enable semantic search"msgstr "Enable semantic search"-#: src/components/SyncStatusBadge.tsx-msgid "Enable sync"-msgstr "Enable sync"-#: src/components/TerminalGate.tsxmsgid "Enable terminal"msgstr "Enable terminal"@@ -3811,6 +3800,14 @@ msgstr "Failed to update markdownlint rules"msgid "Failed to update property"msgstr "Failed to update property"+#: src/hooks/use-enable-sync-with-confirm.ts+msgid "Failed to update sync — {detail}"+msgstr "Failed to update sync — {detail}"++#: src/hooks/use-enable-sync-with-confirm.ts+msgid "Failed to update sync mode — {detail}"+msgstr "Failed to update sync mode — {detail}"+#: src/components/settings/TerminalSection.tsxmsgid "Failed to update the auto-approve setting — {detail}"msgstr "Failed to update the auto-approve setting — {detail}"@@ -4031,6 +4028,28 @@ msgstr "Folder target: {linkTitle}. Click to open the overview."msgid "Folders"msgstr "Folders"+#: src/components/settings/SyncSection.tsx+#: src/components/SyncStatusBadge.tsx+msgid "Follow"+msgstr "Follow"++#: src/components/settings/SyncSection.tsx+#: src/components/SyncStatusBadge.tsx+msgid "Follow — updates flow in from your remote; your edits stay on this computer."+msgstr "Follow — updates flow in from your remote; your edits stay on this computer."++#: src/components/AutoSyncEnableWarning.tsx+msgid "Follow fetches updates from your remote git repository and fast-forwards your copy automatically. Your local edits stay on this computer and are never pushed."+msgstr "Follow fetches updates from your remote git repository and fast-forwards your copy automatically. Your local edits stay on this computer and are never pushed."++#: src/hooks/use-worktree-autosync-notice.tsx+msgid "Follow is on for this worktree, inherited from {project}. Change it in Settings → Sync."+msgstr "Follow is on for this worktree, inherited from {project}. Change it in Settings → Sync."++#: src/components/AutoSyncEnableWarning.tsx+msgid "Follow never pushes or commits your local changes. They stay only on this machine."+msgstr "Follow never pushes or commits your local changes. They stay only on this machine."+#: src/components/acp/ThreadView.tsxmsgid "Follow the agent's edits"msgstr "Follow the agent's edits"@@ -4087,6 +4106,11 @@ msgstr "From template"msgid "Frontmatter every document created from this template starts with. Values are YAML — a list is <0>[a, b]</0>; <1>{{date}}</1> fills in on create."msgstr "Frontmatter every document created from this template starts with. Values are YAML — a list is <0>[a, b]</0>; <1>{{date}}</1> fills in on create."+#: src/components/settings/SyncSection.tsx+#: src/components/SyncStatusBadge.tsx+msgid "Full"+msgstr "Full"+#: src/components/InstallInClaudeDesktopDialog.tsxmsgid "Full guide"msgstr "Full guide"@@ -4100,6 +4124,14 @@ msgstr "Full path"msgid "Full Path"msgstr "Full Path"+#: src/components/settings/SyncSection.tsx+msgid "Full sync — your commits push and remote changes pull automatically."+msgstr "Full sync — your commits push and remote changes pull automatically."++#: src/components/SyncStatusBadge.tsx+msgid "Full sync — your edits are committed and pushed to your remote automatically."+msgstr "Full sync — your edits are committed and pushed to your remote automatically."+#: src/lib/keyboard-shortcuts.tsmsgid "General"msgstr "General"@@ -4120,10 +4152,6 @@ msgstr "Get product updates in your inbox."msgid "Get set up"msgstr "Get set up"-#: src/components/settings/SyncSection.tsx-msgid "Git auto-sync"-msgstr "Git auto-sync"-#: src/components/settings/SharingSection.tsx#: src/components/SkillsSidebarSection.tsxmsgid "git configuration is unavailable"@@ -4141,6 +4169,10 @@ msgstr "Git needs {tool} for this repository, but it isn't installed or couldn'tmsgid "Git needs a helper tool (such as git-lfs) that isn't installed or couldn't be found. Install it, then try again."msgstr "Git needs a helper tool (such as git-lfs) that isn't installed or couldn't be found. Install it, then try again."+#: src/components/settings/SyncSection.tsx+msgid "Git sync"+msgstr "Git sync"+#: src/components/SyncStatusBadge.tsxmsgid "GitHub authentication failed. Try signing in again."msgstr "GitHub authentication failed. Try signing in again."@@ -4463,6 +4495,10 @@ msgstr "I already have it locally"msgid "I already have it locally →"msgstr "I already have it locally →"+#: src/components/AutoSyncEnableWarning.tsx+msgid "If an update arrives for something you are editing, you choose which version to keep, like a merge conflict."+msgstr "If an update arrives for something you are editing, you choose which version to keep, like a merge conflict."+#: src/components/ConsentDialogBody.tsx#: src/components/settings/OkignoreSection.tsx#: src/components/settings/SettingsDialogShell.tsx@@ -4775,6 +4811,10 @@ msgstr "Keep my version"msgid "Keep original file"msgstr "Keep original file"+#: src/components/settings/SyncSection.tsx+msgid "Keep this project in sync with your git remote. Follow fetches updates without pushing; full sync pushes your commits too. Turning sync on requires confirmation."+msgstr "Keep this project in sync with your git remote. Follow fetches updates without pushing; full sync pushes your commits too. Turning sync on requires confirmation."+#: src/components/SeedDialog.tsxmsgid "Keep track of the people and companies you work with and the meetings you have with them. Good for remembering who someone is, how you know them, and what you last talked about."msgstr "Keep track of the people and companies you work with and the meetings you have with them. Good for remembering who someone is, how you know them, and what you last talked about."@@ -4799,10 +4839,6 @@ msgstr "Label <0>(optional display text)</0>"msgid "Label <0>(visible link text)</0>"msgstr "Label <0>(visible link text)</0>"-#: src/components/SyncStatusBadge.tsx-msgid "Last sync"-msgstr "Last sync"-#: src/components/ActivityPanelBurstRow.tsxmsgid "Latest edit"msgstr "Latest edit"@@ -5040,6 +5076,10 @@ msgstr "Local collaboration data for \"{docName}\" could not be cleared in time.msgid "Local collaboration data for \"{docName}\" could not be cleared. Reload to retry."msgstr "Local collaboration data for \"{docName}\" could not be cleared. Reload to retry."+#: src/components/SyncStatusBadge.tsx+msgid "Local commits are keeping this copy from updating"+msgstr "Local commits are keeping this copy from updating"+#: src/components/settings/SharingSection.tsx#: src/components/SharingModeField.tsxmsgid "Local only"@@ -5200,6 +5240,10 @@ msgstr "Missing page — click to create"msgid "Missing page: {linkTitle}. Click to create."msgstr "Missing page: {linkTitle}. Click to create."+#: src/components/SyncStatusBadge.tsx+msgid "Mode"+msgstr "Mode"+#: src/components/FolderOverview.tsx#: src/components/settings/markdownlint-rule-browser.tsxmsgid "Modified"@@ -5412,6 +5456,10 @@ msgstr "New branch <0>{trimmed}</0> will be created from <1>{currentBaseLabel}</msgid "New branch <0>{trimmed}</0> will be created from the current commit, in its own worktree under <1>.ok/worktrees/</1>."msgstr "New branch <0>{trimmed}</0> will be created from the current commit, in its own worktree under <1>.ok/worktrees/</1>."+#: src/components/AutoSyncEnableWarning.tsx+msgid "New changes from your remote appear in your copy automatically."+msgstr "New changes from your remote appear in your copy automatically."+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.ts#: src/components/FileSidebar.tsx@@ -5904,10 +5952,6 @@ msgstr "OK Desktop"msgid "ok ui responded but server.lock has no port yet"msgstr "ok ui responded but server.lock has no port yet"-#: src/components/settings/SyncSection.tsx-msgid "On"-msgstr "On"-#: src/components/settings/LinkPreviewsSection.tsxmsgid "On — hovering an external link sends its URL to the destination site to fetch a preview."msgstr "On — hovering an external link sends its URL to the destination site to fetch a preview."@@ -6354,6 +6398,10 @@ msgstr "Outgoing"msgid "Outline"msgstr "Outline"+#: src/components/AutoSyncEnableWarning.tsx+msgid "Overlapping edits"+msgstr "Overlapping edits"+#: src/components/PublishToGitHubDialog.tsxmsgid "Owner"msgstr "Owner"@@ -6508,6 +6556,10 @@ msgstr "Pattern syntax error: {message}"msgid "Pattern warnings: {summary}"msgstr "Pattern warnings: {summary}"+#: src/components/SyncStatusBadge.tsx+msgid "Pause sync"+msgstr "Pause sync"+#: src/components/acp/ThreadView.tsxmsgid "pending"msgstr "pending"@@ -7314,6 +7366,10 @@ msgstr "Restored to the version from {0}"msgid "Results capped — this workspace has more files than search can index. A missing file may be a cap artifact, not a typo."msgstr "Results capped — this workspace has more files than search can index. A missing file may be a cap artifact, not a typo."+#: src/components/SyncStatusBadge.tsx+msgid "Resume sync"+msgstr "Resume sync"+#: src/components/acp/ThreadView.tsxmsgid "Resuming the conversation"msgstr "Resuming the conversation"@@ -7322,7 +7378,6 @@ msgstr "Resuming the conversation"#: src/components/ConnectingBanner.tsx#: src/components/PublishToGitHubDialog.tsx#: src/components/settings/ConfigureAgentsSection.tsx-#: src/components/SyncStatusBadge.tsx#: src/components/TrashFailureModal.tsxmsgid "Retry"msgstr "Retry"@@ -7751,8 +7806,8 @@ msgid "Set identity"msgstr "Set identity"#: src/components/settings/SyncSection.tsx-msgid "Set the auto-sync default for users opening this project for the first time. This setting is committed to your repository."-msgstr "Set the auto-sync default for users opening this project for the first time. This setting is committed to your repository."+msgid "Set the sync default for users opening this project for the first time. This setting is committed to your repository."+msgstr "Set the sync default for users opening this project for the first time. This setting is committed to your repository."#: src/components/command-palette-commands.tsmsgid "Set up OpenKnowledge integrations"@@ -7851,10 +7906,6 @@ msgstr "Share your email for followups"msgid "Shared"msgstr "Shared"-#: src/components/settings/SyncSection.tsx-msgid "Shared auto-sync default"-msgstr "Shared auto-sync default"-#: src/components/settings/SyncSection.tsxmsgid "Shared default"msgstr "Shared default"@@ -8380,6 +8431,10 @@ msgstr "Switch project"msgid "Switch project…"msgstr "Switch project…"+#: src/components/settings/SyncSection.tsx+msgid "Switch to Follow"+msgstr "Switch to Follow"+#: src/components/settings/SharingSection.tsxmsgid "Switch to local-only refused"msgstr "Switch to local-only refused"@@ -8410,6 +8465,7 @@ msgstr "Symlink to {targetPath}"#: src/components/settings/SettingsDialogShell.tsx#: src/components/settings/SyncSection.tsx+#: src/components/SyncStatusBadge.tsxmsgid "Sync"msgstr "Sync"@@ -8417,11 +8473,6 @@ msgstr "Sync"msgid "Sync disabled"msgstr "Sync disabled"-#: src/components/settings/SyncSection.tsx-#: src/components/SyncStatusBadge.tsx-msgid "Sync disabled — you don't have permission to push"-msgstr "Sync disabled — you don't have permission to push"-#: src/components/SyncStatusBadge.tsxmsgid "Sync failed — check the server logs for details."msgstr "Sync failed — check the server logs for details."@@ -8430,13 +8481,20 @@ 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/settings/SyncSection.tsx+msgid "Sync is off — your edits stay on this computer until you commit and push manually."+msgstr "Sync is off — your edits stay on this computer until you commit and push manually."+#: src/components/SyncStatusBadge.tsx-msgid "Sync is off — your edits will not sync to the remote repository."-msgstr "Sync is off — your edits will not sync to the remote repository."+msgid "Sync is paused. Turn it back on to resume."+msgstr "Sync is paused. Turn it back on to resume."++#: src/components/SyncStatusBadge.tsx+msgid "Sync mode"+msgstr "Sync mode"#: src/components/share-receive-miss-content.tsx#: src/components/ShareFreshnessWarning.tsx-#: src/components/SyncStatusBadge.tsxmsgid "Sync now"msgstr "Sync now"@@ -8444,6 +8502,10 @@ msgstr "Sync now"msgid "Sync off"msgstr "Sync off"+#: src/components/SyncStatusBadge.tsx+msgid "Sync paused"+msgstr "Sync paused"+#: src/components/SyncStatusBadge.tsxmsgid "Sync paused — resolve conflicts to resume."msgstr "Sync paused — resolve conflicts to resume."@@ -8482,6 +8544,10 @@ msgstr "Sync status: {syncStateLabel} — git identity unset"msgid "Synced"msgstr "Synced"+#: src/components/SyncStatusBadge.tsx+msgid "Synced {lastSyncedRelative}"+msgstr "Synced {lastSyncedRelative}"+#: src/components/TimelinePanel.tsxmsgid "Synced from disk"msgstr "Synced from disk"@@ -9319,6 +9385,10 @@ msgstr "Unrecognized link"msgid "Unrecognized wiki link"msgstr "Unrecognized wiki link"+#: src/components/SyncStatusBadge.tsx+msgid "Up to date"+msgstr "Up to date"+#: src/components/SkillUpdateDialog.tsxmsgid "Update"msgstr "Update"@@ -9362,6 +9432,10 @@ msgstr "Updated \"{display}\" to {0} — your previous version is in history ifmsgid "Updated \"{display}\" to {0}."msgstr "Updated \"{display}\" to {0}."+#: src/components/SyncStatusBadge.tsx+msgid "Updated {lastSyncedRelative}"+msgstr "Updated {lastSyncedRelative}"+#: src/components/FolderTimelineCard.tsxmsgid "updated folder properties"msgstr "updated folder properties"@@ -9370,7 +9444,12 @@ msgstr "updated folder properties"msgid "Updated to Version {version}"msgstr "Updated to Version {version}"+#: src/components/AutoSyncEnableWarning.tsx+msgid "Updates flow in"+msgstr "Updates flow in"+#: src/components/SkillUpdateDialog.tsx+#: src/components/SyncStatusBadge.tsxmsgid "Updating"msgstr "Updating"@@ -9756,8 +9835,8 @@ msgid "You can attach up to {MAX_ATTACHMENTS} images."msgstr "You can attach up to {MAX_ATTACHMENTS} images."#: src/components/AutoSyncOnboardingDialog.tsx-msgid "You can turn this on later in <0>Settings → Sync</0>."-msgstr "You can turn this on later in <0>Settings → Sync</0>."+msgid "You can change this later in <0>Settings → Sync</0>."+msgstr "You can change this later in <0>Settings → Sync</0>."#: src/components/DocumentErrorBoundary.tsxmsgid "You cancelled loading \"{docName}\"."@@ -9775,6 +9854,7 @@ msgstr "You don't have access to this private repo. Sign in with an account thatmsgid "You don't have access to this repository."msgstr "You don't have access to this repository."+#: src/components/settings/SyncSection.tsx#: src/components/SyncStatusBadge.tsxmsgid "You don't have permission to push to this repo"msgstr "You don't have permission to push to this repo"@@ -9783,6 +9863,10 @@ msgstr "You don't have permission to push to this repo"msgid "You don't have permission to push to this repo."msgstr "You don't have permission to push to this repo."+#: src/components/settings/SyncSection.tsx+msgid "You don't have permission to push to this repo. Follow can still keep your copy up to date."+msgstr "You don't have permission to push to this repo. Follow can still keep your copy up to date."+#: src/components/ShareFreshnessWarning.tsxmsgid "You don't have write access to this repo."msgstr "You don't have write access to this repo."@@ -9836,6 +9920,10 @@ msgstr "Your copy of branch <0>{shareBranch}</0> has changes that aren't on GitHmsgid "Your current version is saved first, so this is reversible."msgstr "Your current version is saved first, so this is reversible."+#: src/components/AutoSyncEnableWarning.tsx+msgid "Your edits stay on this computer"+msgstr "Your edits stay on this computer"+#: src/components/settings/EmbeddingsKeySection.tsxmsgid "Your embeddings provider API key, used only to create embeddings of your content for semantic search. Stored once for this machine in <0>~/.ok/secrets.yml</0> (readable only by your user account) and shared across all projects. Turn the feature on per project in This project → Search, where you can also override the endpoint."msgstr "Your embeddings provider API key, used only to create embeddings of your content for semantic search. Stored once for this machine in <0>~/.ok/secrets.yml</0> (readable only by your user account) and shared across all projects. Turn the feature on per project in This project → Search, where you can also override the endpoint."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex f2db6ccc4..67b9ecfae 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -21,8 +21,11 @@"-YV1Uo": ["Ƥàţţēŕń ", ["patternNumber"]],"-bFGPF": ["Ńēxţ ćĥàńĝē"],"-dNlfM": ["Ũńďĩď ţĥē ĺàśţ ēďĩţ ōń ", ["docName"]],+ "-f2Ogn": [+ "Ķēēƥ ţĥĩś ƥŕōĴēćţ ĩń śŷńć ŵĩţĥ ŷōũŕ ĝĩţ ŕēḿōţē. Ƒōĺĺōŵ ƒēţćĥēś ũƥďàţēś ŵĩţĥōũţ ƥũśĥĩńĝ; ƒũĺĺ śŷńć ƥũśĥēś ŷōũŕ ćōḿḿĩţś ţōō. Ţũŕńĩńĝ śŷńć ōń ŕēǫũĩŕēś ćōńƒĩŕḿàţĩōń."+ ],"-g6KIS": ["Ũńŕēćōĝńĩźēď ĺĩńķ"],- "-gdcIo": ["Àũţō-śŷńć ĩś ōń — ŷōũŕ ćōḿḿĩţś ƥũśĥ àńď ŕēḿōţē ćĥàńĝēś ƥũĺĺ ōń ĩńţēŕvàĺś."],+ "-imiMK": ["Ƒōĺĺōŵ — ũƥďàţēś ƒĺōŵ ĩń ƒŕōḿ ŷōũŕ ŕēḿōţē; ŷōũŕ ēďĩţś śţàŷ ōń ţĥĩś ćōḿƥũţēŕ."],"-kbIAr": ["Ĺĩńķś & ĩḿàĝēś"],"-lCAuQ": ["Ĺōàďĩńĝ ĝŕàƥĥ"],"-o5XAG": [@@ -86,6 +89,7 @@"0t0bbC": ["Ćōũĺď ńōţ śàvē śŷńć ƥŕēƒēŕēńćē: ", ["detail"]],"0uTHCg": ["Śţàŕţ à ńēŵ ŌƥēńĶńōŵĺēďĝē ƥŕōĴēćţ."],"0wswKc": ["Ĥōŕĩźōńţàĺ ŕũĺē ţĥàţ ďĩvĩďēś śēćţĩōńś."],+ "0xnQ_X": ["Ũƥďàţēś ƒĺōŵ ĩń"],"0xnmlQ": ["Ŕēƥōśĩţōŕŷ ńàḿē"],"0yL--g": ["Ŕēvĩēŵ ćōńƒĺĩćţś"],"10g8I_": ["Ţũŕń ōƒƒ Ōńĺŷ ḿàŕķďōŵń ƒĩĺēś"],@@ -236,6 +240,7 @@"4A3Yzu": ["Ćōďē ƀĺōćķ"],"4BITzH": ["Ēŕŕōŕ:"],"4CfgPM": ["ƤŕōĴēćţ ƒōĺďēŕ ćŕēàţēď, ƀũţ ĝĩţ ĩńĩţ ƒàĩĺēď. Ţŕŷ àĝàĩń."],+ "4DcimZ": ["Ũƥďàţēď ", ["lastSyncedRelative"]],"4E9jPa": ["Ćŕēàţē ŷōũŕ ƒĩŕśţ ƥŕōĴēćţ"],"4EZrJN": ["Ŕũĺēś"],"4Gz2wC": ["Ƒàĩĺēď ţō ũƥĺōàď ƒĩĺē"],@@ -331,6 +336,7 @@}]],+ "5rnB76": ["Ŷōũŕ ēďĩţś śţàŷ ōń ţĥĩś ćōḿƥũţēŕ"],"5vYdh9": ["Ńēŵ ţĥŕēàď ŵĩţĥ ", ["0"]],"5wV2qQ": ["àńď ḿōŕē"],"5y_9lO": ["Ŵàĩţĩńĝ ƒōŕ àũţĥōŕĩźàţĩōń"],@@ -390,6 +396,7 @@"7FamGZ": ["Ĝō ţō ĺĩńē"],"7Fkcej": ["+ Àďď ", ["addChildName"]],"7H4UHD": ["Ďōćũḿēńţś ţàĝĝēď <0>#", ["tagName"], "</0>"],+ "7IsvrP": ["Ćĥēćķĩńĝ ƒōŕ ũƥďàţēś"],"7JtSLi": ["Ƒàĩĺēď ţō ďēĺēţē ƥàţĥ"],"7OhaRy": ["Śōũŕćē śēàŕćĥ"],"7Ongq0": ["Ćōńďēńśē ḿŷ ÀĜĒŃŢŚ.ḿď ƒĩĺē ţō ĺēśś ţĥàń 40ķ ćĥàŕàćţēŕś"],@@ -446,6 +453,9 @@"8RtNI0": ["Ƒàĩĺēď ţō ĺōàď ďōćũḿēńţś"],"8TvlHF": ["Ćŕàśĥ ďũḿƥ"],"8Vq20-": ["Śŵĩţćĥ ŵōŕķţŕēē"],+ "8Wav8y": [+ "Ĩƒ àń ũƥďàţē àŕŕĩvēś ƒōŕ śōḿēţĥĩńĝ ŷōũ àŕē ēďĩţĩńĝ, ŷōũ ćĥōōśē ŵĥĩćĥ vēŕśĩōń ţō ķēēƥ, ĺĩķē à ḿēŕĝē ćōńƒĺĩćţ."+ ],"8XQRON": ["Ĺōàďĩńĝ ŕēƥōśĩţōŕĩēś"],"8_brI5": ["Ńàḿē ĩś ŕēǫũĩŕēď"],"8cS0nH": ["Ćōńƒĩĝ śĥàŕĩńĝ ũńàvàĩĺàƀĺē: ", ["0"], "."],@@ -459,6 +469,7 @@"8m8diM": ["Ńō ĺōćàţĩōń śēĺēćţēď. Ũśē ßŕōŵśē ţō ćĥōōśē à ƒōĺďēŕ."],"8nWu1k": ["Ēḿƥţŷ ďĩàĝŕàḿ"],"8ruqQi": ["ßŕōķēń ĩńţēŕńàĺ ĺĩńķś"],+ "8sMErm": ["Ēńàƀĺē Ƒōĺĺōŵ?"],"8t9CRE": ["Śţàŕţĩńĝ ", ["agentName"], "…"],"8tjQCz": ["Ēxƥĺōŕē"],"8uAWix": [@@ -616,6 +627,9 @@"CSL0l1": ["Ćōũĺďń'ţ ćĺēàŕ ţĥē ķēŷ — ƥĺēàśē ţŕŷ àĝàĩń."],"CTJLpz": ["\"", ["trimmed"], "\" àĺŕēàďŷ ēxĩśţś ĥēŕē"],"CU3AiE": ["Śŵĩţćĥĩńĝ ƀŕàńćĥēś"],+ "CVRM5N": [+ "Ƒōĺĺōŵ ƒēţćĥēś ũƥďàţēś ƒŕōḿ ŷōũŕ ŕēḿōţē ĝĩţ ŕēƥōśĩţōŕŷ àńď ƒàśţ-ƒōŕŵàŕďś ŷōũŕ ćōƥŷ àũţōḿàţĩćàĺĺŷ. Ŷōũŕ ĺōćàĺ ēďĩţś śţàŷ ōń ţĥĩś ćōḿƥũţēŕ àńď àŕē ńēvēŕ ƥũśĥēď."+ ],"CWzc2T": ["<0>~/.ōķ/ƀĩń</0> àńď <1>~/.ōķ/ēńv.śĥ</1> śţàŷ ēĩţĥēŕ ŵàŷ — ţĥē àƥƥ àĺŵàŷś ḿàĩńţàĩńś ţĥēḿ."],@@ -630,6 +644,7 @@"CifUuG": ["Ũƥďàţē àvàĩĺàƀĺē"],"Ck9XRt": ["Ćōũĺďń'ţ śàvē ţĥē ķēŷ — ƥĺēàśē ţŕŷ àĝàĩń."],"CmeH9S": ["Àďď ƥŕōƥēŕţŷ ţō ", ["keyName"]],+ "CnOGgs": ["Śŷńć ḿōďē"],"CoHvYd": ["Ḿōvēď ", ["0"], " ţō ƥōśĩţĩōń ", ["1"], " ōƒ ", ["2"]],"CooKEf": ["Ďōćķ śēśśĩōńś àţ ţĥē ƀōţţōḿ"],"CvsD6Y": ["vĩà ", ["viaTags"]],@@ -807,7 +822,6 @@"FZtBeR": ["Ēńàƀĺē ", ["0"]],"FgRAvd": ["Ĺōĝś & śŷśţēḿ ĩńƒō"],"FjkaiT": ["Źōōḿ ōũţ"],- "FnMkli": ["Śŷńć ďĩśàƀĺēď — ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ"],"FqGWeR": ["Ćōũĺďń'ţ ŕēàćĥ ţĥē àĝēńţ ŕēĝĩśţŕŷ."],"FqTpiN": ["ßĩŕď ŵĩķĩ"],"Fqr8BP": ["Ḿũĺţĩ-ƥàĝē ƤĎƑ vĩēŵēŕ ŵĩţĥ ţōōĺƀàŕ ćōńţŕōĺś (ţĥũḿƀńàĩĺś, ƥàĝē ńàv, źōōḿ)."],@@ -1061,6 +1075,7 @@"LKOLNn": ["Ńō ÀĨ àĝēńţś ĩńśţàĺĺēď"],"LNum6A": [["minutes"], " ḿĩń àĝō"],"LPAv9E": [["days"], "ď àĝō"],+ "LQsCPn": ["Ĺōćàĺ ćōḿḿĩţś àŕē ķēēƥĩńĝ ţĥĩś ćōƥŷ ƒŕōḿ ũƥďàţĩńĝ"],"LRgZAt": [["owner"], "/", ["name"], " àĺŕēàďŷ ēxĩśţś"],"LTeJuX": ["Ţōĝĝĺē Ƒũĺĺ Śćŕēēń"],"LXdWeS": ["Ḿēďĩũḿ śēćţĩōń ĥēàďĩńĝ."],@@ -1115,13 +1130,14 @@"MCjC9A": ["Ďēĺēţē ", ["deleteDescriptorLabel"]],"MDBJwN": ["Ĥàŕď ţō ũśē"],"MDZSJe": ["Ŵĥēń ţĥē àĝēńţ ŕũńś ĩţś śćĥēďũĺēď ŵōŕķ."],+ "MGBNwj": ["Ƥàũśē śŷńć"],"MGb89P": ["Ĩńśēŕţ, ďēĺēţē, ḿōvē, ćōƥŷ, àńď ĩńďēńţ śōũŕćē ēďĩţōŕ ĺĩńēś ţĥŕōũĝĥ ĆōďēḾĩŕŕōŕ'ś ďēƒàũĺţ ķēŷḿàƥ."],"MHrjPM": ["Ţĩţĺē"],"MJqRO6": ["Ŷōũŕ ŕēƥōŕţ ĩś ƀēĩńĝ śēńţ."],"MJuO1q": ["Ćōńţēxţ ŵĩńďōŵ:"],- "MKOVhz": ["Ēńàƀĺē ĝĩţ àũţō-śŷńć"],+ "MKEPCY": ["Ƒōĺĺōŵ"],"MQIM_Y": ["Ćōũĺďń'ţ ćōƥŷ. Śēĺēćţ ţĥē ŨŔĹ àƀōvē ţō ćōƥŷ ĩţ ḿàńũàĺĺŷ."],"MRZxAn": ["Ēďĩţēď"],"MTs6g3": ["Ćōũĺďń'ţ ŕēćōńńēćţ àƒţēŕ śēŕvēŕ ŕēśţàŕţ"],@@ -1194,7 +1210,6 @@"NgZwB0": [["enabledCount"], "/", ["0"], " ōń"],"NjrIak": ["Ƒĩĺē: <0>", ["fixedName"], ".ḿď</0>"],"NkXEFS": ["Ŕēśţōŕē ƒàĩĺēď — ďōćũḿēńţ ũńćĥàńĝēď"],- "Nm-3m-": ["Àũţō-śŷńć ĩś ƥàũśēď — ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō."],"NmPNJJ": ["Ćōƥŷ ćōďē"],"Nn4GgW": ["Ŵĩĺĺ ƀē ćŕēàţēď àś <0>", ["sanitizedName"], "</0>"],"NnQapF": ["Ōƥēń ŵĩţĥ ÀĨ ", ["targetDisplayName"]],@@ -1206,7 +1221,6 @@"Nv3mUj": ["Śĥōŵ àďvàńćēď"],"NvOvTi": ["Ćŕēàţē ĩń <0>", ["dirDisplay"], "</0>"],"Nwbs0q": ["Ďōń'ţ śĥōŵ"],- "Nx7BWE": ["Ĝĩţ àũţō-śŷńć"],"NxW-md": ["Ŕēśĩźē ", ["handleKey"]],"NzFvyK": ["Śēśśĩōń ēńďēď — ũńďō ũńàvàĩĺàƀĺē"],"NzluOx": ["(ōƥţĩōńàĺ)"],@@ -1254,7 +1268,6 @@],"Okd2Xv": ["Ţōĝĝĺē ũńďēŕĺĩńē ƒōŕḿàţţĩńĝ."],"OlAl5i": ["Ēxƥàńď àĺĺ"],- "OmHTGj": ["Ďĩśàƀĺē ĝĩţ àũţō-śŷńć"],"Oo_WWc": ["Ńō ƥàĝēś ƒōũńď"],"Oos8fo": ["Ćōƥŷ ćōḿḿàńď"],"OplnBG": ["Ḿàńàĝĩńĝ ÀĨ ţōōĺś ĩś ũńàvàĩĺàƀĺē ĩń ţĥĩś ƀũĩĺď."],@@ -1283,6 +1296,7 @@"PQCdtv": ["\"", ["docName"], "\" ďōēśń'ţ ēxĩśţ."],"PR9FSv": ["Ḿōvē ţō ţĥē ńēxţ vĩśũàĺ-ēďĩţōŕ ƒĩńď ŕēśũĺţ."],"PRnH8G": ["ōƒ ", ["0"]],+ "PTb1Nx": ["Śŷńć ĩś ƥàũśēď. Ţũŕń ĩţ ƀàćķ ōń ţō ŕēśũḿē."],"PVUn_c": ["Ōƥēń ƒōĺďēŕ"],"PYmp-0": ["Ĩḿƥōŕţ àś ţēḿƥĺàţē"],"PZtgO0": ["Ōƥēńĩńĝ ŵōŕķţŕēē"],@@ -1322,6 +1336,7 @@"QQghPu": ["Ĩńśţàĺĺ ĩń Ćĺàũďē Ďēśķţōƥ"],"QR5SP1": ["ćŕēàţēď ţēḿƥĺàţē"],"QTsvh1": ["Ţĥĩś àĝēńţ ńēēďś ŷōũ ţō śĩĝń ĩń ƒĩŕśţ — śēē ţĥē ńōţĩćē ƀēĺōŵ."],+ "QYTOaN": ["Ŷōũ ćàń ćĥàńĝē ţĥĩś ĺàţēŕ ĩń <0>Śēţţĩńĝś → Śŷńć</0>."],"QYfQdv": [["displayName"], " ĆĹĨ"],"QcpeeE": ["Ńàvĩĝàţē ţō ", ["docName"]],"QfFBdJ": ["Ţĥē ţēḿƥĺàţē'ś ƒĩĺēńàḿē (ŵĩţĥōũţ `.ḿď`)."],@@ -1430,13 +1445,15 @@"Sq8lf2": ["Ēďĩţōŕś ţō ĩńśţàĺĺ śķĩĺĺś ĩńţō"],"SrOuyg": ["Ďōćũḿēńţ ƥàńēĺś"],"SvBFYA": ["Ńō ŕēćēńţ ƥŕōĴēćţś"],+ "Sxx_Zz": [+ "Ƒōĺĺōŵ ĩś ōń ƒōŕ ţĥĩś ŵōŕķţŕēē, ĩńĥēŕĩţēď ƒŕōḿ ",+ ["project"],+ ". Ćĥàńĝē ĩţ ĩń Śēţţĩńĝś → Śŷńć."+ ],"T-654M": ["Ĺōàďĩńĝ ƤĎƑ"],"T0OVm7": ["Ţĥē ďēƒàũĺţ ƀŕàńćĥ ĩś ƥŕōţēćţēď — ƥũśĥēś ńēēď à ƥũĺĺ ŕēǫũēśţ."],"T3Mld1": ["Ŵĩńďōŵ"],"T3j-7o": ["ē.ĝ. Śŵĩţćĥĩńĝ ƥŕōĴēćţś ŵĥĩĺē à śŷńć ŵàś ŕũńńĩńĝ"],- "T67A0Y": [- "Àũţō-śŷńć ƥũśĥēś/ƥũĺĺś ćōḿḿĩţś ţō ŷōũŕ ĝĩţ ŕēḿōţē ōń ĩńţēŕvàĺś àńď ōń śàvē. Ţōĝĝĺĩńĝ ōń ŕēǫũĩŕēś ćōńƒĩŕḿàţĩōń."- ],"TEEPPF": ["Ŵĩĺĺ ŕēƥĺàćē ēxĩśţĩńĝ ŌƥēńĶńōŵĺēďĝē ēńţŕŷ"],"TJnkyf": ["ōķ ũĩ ŕēśƥōńďēď ƀũţ śēŕvēŕ.ĺōćķ ĥàś ńō ƥōŕţ ŷēţ"],"TKQ7K-": ["Ĩńśţàĺĺ"],@@ -1464,7 +1481,9 @@"U2Kx6T": ["Ćĺōśē àĺĺ ũńƥĩńńēď"],"U2pMtf": ["ţàĝ-ńàḿē"],"U3IvM5": ["Ƒũĺĺ ĝũĩďē"],+ "U4nTfu": ["Ēńàƀĺē Ƒōĺĺōŵ"],"U5Spo9": ["Ćōńţēńţ ďĩŕēćţōŕŷ ḿũśţ ƀē ĩńśĩďē ţĥē ƥŕōĴēćţ"],+ "U6wmNc": ["Śŷńć ƥàũśēď"],"U7HJ4y": ["Ḿàńàĝēď ƀŷ ŌƥēńĶńōŵĺēďĝē (ŕēàď-ōńĺŷ)"],"U8CD-l": ["Ćōƥŷ ƒũĺĺ ƥàţĥ, Ńō ŵōŕķśƥàćē"],"U9tm58": ["Ĥĩďē ƥŕōƀĺēḿ ĩńďĩćàţōŕś"],@@ -1482,6 +1501,9 @@"UTNVyS": ["Śēĺēćţ ţĥē ƒũĺĺ śōũŕćē ďōćũḿēńţ."],"UTZ97u": ["Śēĺēćţĩōń ḿũśţ ƀē ĩńśĩďē ţĥē ƥŕōĴēćţ"],"UTgWxm": ["Ńōţĥĩńĝ ŵàś ũƥĺōàďēď. Ţĥē ŕēƥōŕţ śţàŷś ōń ţĥĩś Ḿàć ũńţĩĺ ŷōũ ēḿàĩĺ ĩţ ţō ũś."],+ "UVDasf": [+ "Śŷńć ĩś ōƒƒ — ŷōũŕ ēďĩţś śţàŷ ōń ţĥĩś ćōḿƥũţēŕ ũńţĩĺ ŷōũ ćōḿḿĩţ àńď ƥũśĥ ḿàńũàĺĺŷ."+ ],"UVLlMV": ["Ćōũĺďń'ţ ŕēàćĥ ĜĩţĤũƀ. Ţŕŷ àĝàĩń?"],"UW2Fg3": ["Ţĥĩś ƥŕōĴēćţ'ś ŕũńńĩńĝ śēŕvēŕ ďōēśń'ţ śũƥƥōŕţ ĺĩvē ēďĩţĩńĝ. Ŕēśţàŕţ ŌƥēńĶńōŵĺēďĝē ţō ƒĩx."@@ -1557,9 +1579,6 @@"W0i24j": ["ŌƀĴēćţ"],"W1SI2K": [["0", "plural", { "one": ["#", " ŵàŕńĩńĝ"], "other": ["#", " ŵàŕńĩńĝś"] }]],"W1qRuM": ["Ţĥĩś ďōćũḿēńţ ĩś àĺŕēàďŷ àćţĩvē ĩń ţĥē ēďĩţōŕ. Ũśē Ōƥēń ţō ćōĺĺàƥśē ţĥē ĝŕàƥĥ."],- "W3Xlpc": [- "Śēţ ţĥē àũţō-śŷńć ďēƒàũĺţ ƒōŕ ũśēŕś ōƥēńĩńĝ ţĥĩś ƥŕōĴēćţ ƒōŕ ţĥē ƒĩŕśţ ţĩḿē. Ţĥĩś śēţţĩńĝ ĩś ćōḿḿĩţţēď ţō ŷōũŕ ŕēƥōśĩţōŕŷ."- ],"W5A0Ly": ["Àń ũńēxƥēćţēď ēŕŕōŕ ōććũŕŕēď."],"W7XJN4": ["Ćàń'ţ ńēśţ ƥŕōĴēćţś. Àń ŌƥēńĶńōŵĺēďĝē ƥŕōĴēćţ àĺŕēàďŷ ēxĩśţś àţ <0>",@@ -1603,7 +1622,6 @@"WmPbvm": ["Ĝēţ ƥŕōďũćţ ũƥďàţēś ĩń ŷōũŕ ĩńƀōx."],"Wq6Wcm": ["Ƥĺēàśē ēńţēŕ à vàĺĩď ēḿàĩĺ àďďŕēśś."],"WqLq6M": ["Ōƥēń ŵĩţĥ ÀĨ ", ["displayName"]],- "Wt5W56": ["Śŷńć ĩś ōƒƒ — ŷōũŕ ēďĩţś ŵĩĺĺ ńōţ śŷńć ţō ţĥē ŕēḿōţē ŕēƥōśĩţōŕŷ."],"Wtw22s": ["Ĩńśţàĺĺĩńĝ"],"WuntOK": ["Ƥŕēvĩēŵ ōƒ ţĥē śćŕēēńśĥōţ"],"WyQxwa": ["Ćōńńēćţ ţĥĩś ƥŕōĴēćţ ţō ĜĩţĤũƀ ţō śĥàŕē."],@@ -1703,7 +1721,6 @@"Z1LF1M": ["Śĥàŕĩńĝ à ďōć ńēēďś à ĜĩţĤũƀ ŕēƥōśĩţōŕŷ. Ćŕēàţē ōńē ƒōŕ ţĥĩś ƥŕōĴēćţ."],"Z2M5XM": ["Ŕēàśōń: ", ["reason"], " (", ["osDetail"], ")"],"Z3FXyt": ["Ĺōàďĩńĝ..."],- "Z5HWHd": ["Ōń"],"Z5h97D": ["Ĥĩďē ƒĩĺēś àńď ƒōĺďēŕś ƒŕōḿ ŷōũŕ ķńōŵĺēďĝē ƀàśē. Ĥĩďďēń ĩţēḿś ďōń’ţ àƥƥēàŕ ĩń ţĥē ƒĩĺē ţŕēē, śēàŕćĥ, ōŕ ÀĨ ţōōĺś. <0>Ĺēàŕń ḿōŕē àƀōũţ ƥàţţēŕńś</0>."],@@ -1722,11 +1739,11 @@"ZBt4rI": ["Ĩńśţŕũćţĩōń ƒōŕ ţĥē ÀĨ"],"ZBxvV3": ["Ńēŵ Ţēŕḿĩńàĺ"],"ZI8uvA": ["Ńō ƥŕōƀĺēḿś ƒōũńď."],- "ZLQol-": ["Ŷōũ ćàń ţũŕń ţĥĩś ōń ĺàţēŕ ĩń <0>Śēţţĩńĝś → Śŷńć</0>."],"ZNK2Tq": ["ŕōōţ"],"ZQJ1IV": ["Àćţĩvàţē ţĥē ĺàśţ ēďĩţōŕ ţàƀ."],"ZQLDTl": ["ćŕēàţēď ƒōĺďēŕ"],"ZU8VV_": ["Ŕēḿōvē ƒàĩĺēď: ", ["error"]],+ "ZVOhXM": ["Ƒàĩĺēď ţō ũƥďàţē śŷńć — ", ["detail"]],"ZW3mlR": ["Ďĩƒƒ ŕēńďēŕ ḿōďē"],"ZWgr0b": ["Ĩń à śũƀƒōĺďēŕ"],"ZWolSV": [@@ -1820,6 +1837,7 @@"a9OzSn": ["Ńō ƥàĝēś ƒōũńď ƒōŕ \"", ["trimmedQuery"], "\""],"aBgwis": ["Śćōƥē"],"aByJ8j": ["Ĥōŵ ďōēś śĥàŕĩńĝ ŵōŕķ?"],+ "aCoQfY": ["Ńēŵ ćĥàńĝēś ƒŕōḿ ŷōũŕ ŕēḿōţē àƥƥēàŕ ĩń ŷōũŕ ćōƥŷ àũţōḿàţĩćàĺĺŷ."],"aE2_XM": ["Ōńē ƥàţţēŕń ƥēŕ ĺĩńē — àƥƥēńďēď ţō <0>.ōķĩĝńōŕē</0>."],"aENGMB": ["Śēḿàńţĩć śēàŕćĥ àďďś ḿēàńĩńĝ-ƀàśēď ŕàńķĩńĝ ţō ţĥē śēàŕćĥ ţōōĺ śō ćōńćēƥţũàĺĺŷ-ŕēĺàţēď ƥàĝēś śũŕƒàćē ēvēń ŵĩţĥōũţ śĥàŕēď ķēŷŵōŕďś."@@ -1838,6 +1856,9 @@"abiHje": ["Ďēĺēţē śēĺēćţēď ĩţēḿś"],"adsMWO": ["Ŕēśōĺvĩńĝ ďēĺţàś"],"aiArms": ["Ŵē ćōũĺďń'ţ ćĺōńē ţĥĩś ŕēƥōśĩţōŕŷ."],+ "ajHi4O": [+ "Àũţō-śŷńć ĩś ƥàũśēď — ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō. Śŵĩţćĥ ţō Ƒōĺĺōŵ ţō ķēēƥ ŕēćēĩvĩńĝ ũƥďàţēś."+ ],"ajz9F8": ["Ćōũĺďń'ţ ĺōàď ćōńƒĺĩćţ ćōńţēńţ ƒōŕ ", ["filePath"], ". Ţŕŷ ŕēĺōàďĩńĝ ţĥē ƥàĝē."],"ak4LLg": ["Ćĺēàŕ ḿēńũ"],"anmUZq": ["Ḿĩśśĩńĝ à ƒēàţũŕē"],@@ -1911,6 +1932,20 @@"cZGNlb": ["Àďď àńōţĥēŕ ƥàţţēŕń"],"cZI5AL": ["ŌĶ Ďēśķţōƥ"],"cZ_8zB": ["Śţàŷś ōń ţĥĩś ćōḿƥũţēŕ."],+ "caw8gO": [+ [+ "strandedCommitCount",+ "plural",+ {+ "one": ["Ŷōũ ĥàvē 1 ćĥàńĝē ŷōũ ĥàvēń'ţ śĥàŕēď. Ĩţ ŵĩĺĺ śţàŷ ōń ţĥĩś ćōḿƥũţēŕ."],+ "other": [+ "Ŷōũ ĥàvē ",+ "#",+ " ćĥàńĝēś ŷōũ ĥàvēń'ţ śĥàŕēď. Ţĥēŷ ŵĩĺĺ śţàŷ ōń ţĥĩś ćōḿƥũţēŕ."+ ]+ }+ ]+ ],"ccNps_": ["Ōńĺŷ ḿōďĩƒĩēď"],"cd5EXh": ["Ŕēƥōŕţ à ƀũĝ"],"cdm00A": ["Ńō Ĩńćōḿĩńĝ"],@@ -1974,7 +2009,6 @@],"dprWmL": ["Àńćĥōŕ ĩń ţĥĩś ƥàĝē"],"dr1vFs": ["Ŕēƥĺàćē àĺĺ ḿàţćĥēś"],- "dvGKu2": ["Śĥàŕēď àũţō-śŷńć ďēƒàũĺţ"],"dw_3cv": ["Ŕēńàḿē śķĩĺĺ"],"dw_dUJ": ["Ƒàĩĺēď ţō ďũƥĺĩćàţē ƥàţĥ"],"dx-TwN": ["Ŕũńńĩńĝ ƥŕōĴēćţ àũďĩţ"],@@ -2010,6 +2044,9 @@"Ḿàŕķ à ƀĺōćķ àś ţĥē śōũŕćē ōƒ ţŕũţĥ. Ḿĩŕŕōŕś ēĺśēŵĥēŕē ũƥďàţē ĺĩvē àś ŷōũ ēďĩţ ĩţ."],"euc6Ns": ["Ďũƥĺĩćàţē"],+ "evHlIg": [+ "Ƒōĺĺōŵ ńēvēŕ ƥũśĥēś ōŕ ćōḿḿĩţś ŷōũŕ ĺōćàĺ ćĥàńĝēś. Ţĥēŷ śţàŷ ōńĺŷ ōń ţĥĩś ḿàćĥĩńē."+ ],"evs0iw": ["Ţàĝś ḿàţćĥĩńĝ \"", ["tagListQuery"], "\""],"f1XQyZ": ["Ḿōvē ƀĺōćķ"],"f3Nvg7": [@@ -2051,6 +2088,7 @@"fwrPh4": ["Ƥĺēàśē ēńţēŕ à vàĺĩď ēḿàĩĺ."],"fxJk_6": ["<0>Ĥàvē ḿōŕē ţō àďď?</0> Ŵŕĩţē ţō <1/> àńď ḿēńţĩōń ŷōũŕ ŕēƒēŕēńćē."],"fxbCNQ": ["Śŷńćēď. Ţĥē ĺĩńķ ĩś ũƥ ţō ďàţē."],+ "g2Tj8R": ["Ƒũĺĺ"],"g3UF2V": ["Àććēƥţ"],"g4WlQK": ["ƤŕōĴēćţ ÀĨ ţōōĺ ḿàńàĝēḿēńţ ĩś ōńĺŷ àvàĩĺàƀĺē ĩń ţĥē ŌƥēńĶńōŵĺēďĝē ďēśķţōƥ àƥƥ."],"g4XBm0": ["Śḿàĺĺ śēćţĩōń ĥēàďĩńĝ."],@@ -2060,6 +2098,7 @@["descriptorLabel"],"> ƒàĩĺēď ţō ŕēńďēŕ (ĺĩķēĺŷ à ƀàď ƥŕōƥ). Ćōƥŷ ţĥē śōũŕćē ţō śēē ŵĥàţ ŵēńţ ŵŕōńĝ, ōŕ ďēĺēţē ţĥē ƀĺōćķ."],+ "g85bAo": ["Śŷńćēď ", ["lastSyncedRelative"]],"gBbxn_": ["Ćĥēćķĩńĝ śĩĝń-ĩń śţàţũś"],"gGVP4q": ["Ćĺĩćķ <0>+</0> <1/> <2>Ćŕēàţē śķĩĺĺ</2> <3/> <4>Ũƥĺōàď śķĩĺĺ</4>."],"gHSAWT": ["Ćŕēàţē ŵōŕķţŕēē <0>“<1>", ["typedName"], "</1>”</0>"],@@ -2145,12 +2184,14 @@"hwFOFD": ["Śēţţĩńĝś ƒàĩĺēď ţō ĺōàď"],"hxBHxQ": ["À ĺĩńē ŵĩţĥ à ƒōōţńōţē<0><1>[1]</1></0> àńď à ďēƒĩńĩţĩōń śĥōŵń ƀēĺōŵ."],"hxEUVJ": ["Ĩńĩţĩàĺĩźē ", ["selectedPackName"]],+ "hxYFzm": ["Ƒũĺĺ śŷńć — ŷōũŕ ćōḿḿĩţś ƥũśĥ àńď ŕēḿōţē ćĥàńĝēś ƥũĺĺ àũţōḿàţĩćàĺĺŷ."],"hyCxJY": ["Ōƥēń ţĥàţ ŵōŕķţŕēē ĩńśţēàď"],"hynz2K": ["Ďōŵńĺōàď śţàŕţēď"],"i-ShMB": ["Ďĩàĝŕàḿ"],"i09An-": ["Ŕēśţōŕēď àń ēàŕĺĩēŕ vēŕśĩōń (", ["0"], ")"],"i1flq_": ["Ŵĩķĩ ĺĩńķ śũĝĝēśţĩōńś"],"i3f2kh": ["Ńō ḿàţćĥĩńĝ ćōḿḿàńďś."],+ "i6ng22": ["Śŵĩţćĥ ţō Ƒōĺĺōŵ"],"i92eAT": ["Ŵē'ĺĺ ćŕēàţē à ŕēƥōśĩţōŕŷ àńď śţàŕţ śŷńćĩńĝ — ńō ţēŕḿĩńàĺ ńēēďēď."],"i9OyGp": ["Ũńďō ōŕ ŕēďō"],"i9TPUi": [@@ -2179,9 +2220,6 @@"iSLIjg": ["Ćōńńēćţ"],"iSQTsg": ["Ōŕďēŕēď ĺĩśţ"],"iSnkwB": ["Ƒàĩĺēď ţō ōƥēń ćĺōńēď ƥŕōĴēćţ."],- "iTlqm3": [- ["ahead", "plural", { "one": ["#", " ćōḿḿĩţ àĥēàď"], "other": ["#", " ćōḿḿĩţś àĥēàď"] }]- ],"iTylMl": ["Ţēḿƥĺàţēś"],"iXTp5j": ["Śćōƥē: "],"idD8Ev": ["Śàvēď"],@@ -2204,7 +2242,9 @@],"iuTKci": ["Ńō ēďĩţś ŷēţ."],"iv452l": ["Ďōćũḿēńţàţĩōń ƒōŕ ", ["0"], " (ōƥēńś ĩń ƀŕōŵśēŕ)"],+ "iy64Li": ["Ƒũĺĺ śŷńć — ŷōũŕ ēďĩţś àŕē ćōḿḿĩţţēď àńď ƥũśĥēď ţō ŷōũŕ ŕēḿōţē àũţōḿàţĩćàĺĺŷ."],"iycx_A": ["Ƥũśĥĩńĝ"],+ "j5CWO4": ["Ũƥ ţō ďàţē"],"j9Vqvc": ["ĩńĥēŕĩţēď"],"j9tqwO": ["Ńōţ ĩń śĩďēƀàŕ"],"jAMpHn": ["Ŵĥàţ ĩś à śţàŕţēŕ ƥàćķ?"],@@ -2298,6 +2338,7 @@"klPS-L": ["Ōŕĩĝĩńàĺ ƒĩĺē — ƀēƒōŕē ţĥĩś àĝēńţ'ś ēďĩţś."],"kmKqZg": ["Ćĺũśţēŕś"],"knjOzA": ["Ţàĝ vàĺũē"],+ "ko386X": ["À ďōćũḿēńţ ĥàś à ćōńƒĺĩćţ — ŕēśōĺvē ĩţ ţō ķēēƥ ĩţ ũƥ ţō ďàţē."],"kolRU1": ["Ďō ŷōũ ŵàńţ ţō ƥēŕḿàńēńţĺŷ ďēĺēţē ĩńśţēàď?"],"kpqWwG": ["Ţĥĩś ", ["targetNoun"], " ŵàś ŕēḿōvēď ƒŕōḿ ƀŕàńćĥ <0>", ["branch"], "</0>."],"ktspdq": ["Ţĩńţ àńď ƀàďĝē ƒĩĺēś ţĥàţ ĥàvē ĺĩńţ ōŕ ĺĩńķ ƥŕōƀĺēḿś, ŵĩţĥōũţ ōƥēńĩńĝ ţĥēḿ."],@@ -2336,7 +2377,6 @@"lHCR4I": ["Ćĺēàŕ ţĥē ƒĩēĺď ţō ŕēśēţ ƀàćķ ţō ţĥē ďēƒàũĺţ ŌƥēńÀĨ ēńďƥōĩńţ."],"lHwYMr": ["Śēŕvēŕ ēŕŕōŕ: ", ["status"], " ", ["statusText"]],"lI0Td2": ["Ũśē ĺēţţēŕś, ďĩĝĩţś, <0>_</0> àńď <1>-</1> ōńĺŷ."],- "lIn9L9": ["Ďĩśàƀĺē śŷńć"],"lKQnp-": ["Ĩńśţàĺĺēď ", ["0"], " ", ["1"]],"lPzyrU": ["Àĺĺ ĥũńķś ŕēśōĺvēď"],"lVWEIL": ["Ĩńďēxēď ", ["embedded"], " ōƒ ", ["total"], " ƥàĝēś."],@@ -2403,6 +2443,9 @@"Ŕēƥōśĩţōŕĩēś ŷōũ'vē àĺŕēàďŷ ćĺōńēď ḿàŷ ķēēƥ śŷńćĩńĝ ţĥŕōũĝĥ ĝĩţ'ś ōŵń śàvēď ćŕēďēńţĩàĺś, ēvēń àƒţēŕ ŷōũ ďĩśćōńńēćţ."],"msqUNq": ["Ŕēàďŷ-ḿàďē ƒōĺďēŕś àńď ţēḿƥĺàţēś ţō ĝēţ ŷōũ śţàŕţēď ǫũĩćķĺŷ."],+ "msuDyW": [+ "Śēţ ţĥē śŷńć ďēƒàũĺţ ƒōŕ ũśēŕś ōƥēńĩńĝ ţĥĩś ƥŕōĴēćţ ƒōŕ ţĥē ƒĩŕśţ ţĩḿē. Ţĥĩś śēţţĩńĝ ĩś ćōḿḿĩţţēď ţō ŷōũŕ ŕēƥōśĩţōŕŷ."+ ],"mu1O0q": ["Ōƥēń Ķńōŵĺēďĝē ćàń ḿàńàĝē ",["0"],@@ -2433,6 +2476,7 @@"Ţĥĩś ƥàţĥ ĩś ōń àń ēxţēŕńàĺ vōĺũḿē (/Vōĺũḿēś/...). ŌƥēńĶńōŵĺēďĝē ŵĩĺĺ ĺōśē ţŕàćķ ōƒ ƒĩĺēś ŵĥēń ţĥē ďŕĩvē ēĴēćţś."],"nNYV3Y": ["àńď ", ["remaining"], " ḿōŕē"],+ "nOEDQs": ["Ƒàĩĺēď ţō ũƥďàţē śŷńć ḿōďē — ", ["detail"]],"nP-KFo": ["Ńēŵ ", ["0"], " ćĥàţ"],"nP76lk": ["Àƥƥĺĩēś ţō àĺĺ ƥŕōĴēćţś ōń ţĥĩś ḿàćĥĩńē. Ćĺàũďē àńď Ćōďēx, śţàŕţēď ƒŕōḿ ţĥē ƀũĩĺţ-ĩń ţēŕḿĩńàĺ, àũţō-àƥƥŕōvē ŌƥēńĶńōŵĺēďĝē'ś ŕēàď àńď ŵŕĩţē ţōōĺś (Ćĺàũďē àĺśō àũţō-ŕũńś \"ōķ ōƥēń\"). Ďēĺēţĩńĝ, ḿōvĩńĝ, śĥàŕĩńĝ, ĩńśţàĺĺĩńĝ śķĩĺĺś, ōţĥēŕ ćōḿḿàńďś, àńď ńōń-ŌƥēńĶńōŵĺēďĝē ƒĩĺē ēďĩţś śţĩĺĺ àśķ. Ćũŕśōŕ, ŌƥēńĆōďē, àńď Ƥĩ àŕē ũńàƒƒēćţēď. ßēśţ-ēƒƒōŕţ ƥēŕ àĝēńţ."@@ -2499,6 +2543,7 @@["trimmed"],"</1>, ĩń ĩţś ōŵń ŵĩńďōŵ ũńďēŕ <2>.ōķ/ŵōŕķţŕēēś/</2>."],+ "oBK5fD": ["Ōvēŕĺàƥƥĩńĝ ēďĩţś"],"oBXkm2": ["Ďēĺēţē ćōďē ƀĺōćķ"],"oCHfGC": ["Ĺēvēĺ"],"oCNLN8": [@@ -2592,7 +2637,6 @@"qRZh7J": ["Ĺēţ Ţàƀ ĺēàvē ţĥē śōũŕćē ēďĩţōŕ ĩńśţēàď ōƒ ĩńďēńţĩńĝ."],"qSKu2v": ["Śōũŕćē ńàvĩĝàţĩōń àńď śēĺēćţĩōń"],"qSxaOz": ["Àććēƥţ ţĥēĩŕ ďēĺēţĩōń"],- "qUB_o_": ["Àũţō-śŷńć ĩś ōƒƒ — ŷōũŕ ēďĩţś śţàŷ ĺōćàĺ ũńţĩĺ ŷōũ ćōḿḿĩţ àńď ƥũśĥ ḿàńũàĺĺŷ."],"qX-ABr": ["Ōŕ ţō ũśē ƀŕōŵśēŕ śĩĝń-ĩń ĩńśţēàď:"],"qXN416": ["Ćōũĺďń'ţ śĥàŕē śķĩĺĺś: ĩńţēŕńàĺ ēŕŕōŕ. Ƥĺēàśē ŕēśţàŕţ ţĥē àƥƥ."],"qXg5W9": ["Ƒĩĺē śàvēś ţō <0>~/Ďōŵńĺōàďś/ōƥēńķńōŵĺēďĝē.śķĩĺĺ</0>."],@@ -2655,6 +2699,7 @@"rgPqOw": ["Ćōńvēŕţ ţĥē ćũŕŕēńţ ƀĺōćķ ţō à ƥàŕàĝŕàƥĥ."],"riqekz": ["Śũĝĝēśţĩōń ḿēńũ ńàvĩĝàţĩōń"],"rlUzXK": ["Ćōũĺď ńōţ vàĺĩďàţē ƒōĺďēŕ. Ƥĺēàśē ţŕŷ àĝàĩń."],+ "rn7n0G": ["Ŕēśũḿē śŷńć"],"roAe2K": ["Ĺĩńķ ŨŔĹ"],"roiUQQ": ["Ţĥĩś ƥàĝē ďōēśń'ţ ĺĩńķ ţō àńŷţĥĩńĝ ŷēţ."],"rppgXF": ["Ďĩśćōńńēćţĩńĝ"],@@ -2780,11 +2825,13 @@"Ćōũĺďń'ţ ŕēśţàŕţ ţĥē śēŕvēŕ — ĩţ'ś ŕũńńĩńĝ ũńďēŕ à ďĩƒƒēŕēńţ àććōũńţ. Ŕēśţàŕţ ŷōũŕ ćōḿƥũţēŕ ţō ćĺēàŕ ĩţ, ţĥēń ŕēōƥēń ţĥĩś ƥŕōĴēćţ."],"uR2YT3": ["Śĥōŵ ƥŕōƀĺēḿ ĩńďĩćàţōŕś"],+ "uUiiyC": [+ "Ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō. Ƒōĺĺōŵ ćàń śţĩĺĺ ķēēƥ ŷōũŕ ćōƥŷ ũƥ ţō ďàţē."+ ],"uVbUP8": ["Śēţţĩńĝś…"],"uWtdQR": ["Ńō ţēḿƥĺàţēś ŷēţ. Àďď ōńē ĩń ţĥĩś ƒōĺďēŕ'ś Ţēḿƥĺàţēś śēćţĩōń, ōŕ ĩń Śēţţĩńĝś → Ţēḿƥĺàţēś."],- "uWx2ZP": ["Ĺàśţ śŷńć"],"u_lS4C": ["Ćĺōńē ćōḿƥĺēţē — ōƥēńĩńĝ ƥŕōĴēćţ"],"uaUc6t": ["Ŕēśţàŕţ śēŕvēŕ"],"ubMwcO": ["Ţĥē ţēŕḿĩńàĺ śēśśĩōń ēńďēď (śĩĝńàĺ ", ["0"], ")."],@@ -2865,7 +2912,6 @@"w_Sphq": ["Àţţàćĥḿēńţś"],"waFx9W": ["Ḿàńàĝēď"],"wbv9xO": ["Ćŕēàţē ńēŵ ƥŕōĴēćţ"],- "wbwHYD": ["Ēńàƀĺē śŷńć"],"wccmX0": ["Ŷōũŕ ēḿƀēďďĩńĝś ƥŕōvĩďēŕ ÀƤĨ ķēŷ, ũśēď ōńĺŷ ţō ćŕēàţē ēḿƀēďďĩńĝś ōƒ ŷōũŕ ćōńţēńţ ƒōŕ śēḿàńţĩć śēàŕćĥ. Śţōŕēď ōńćē ƒōŕ ţĥĩś ḿàćĥĩńē ĩń <0>~/.ōķ/śēćŕēţś.ŷḿĺ</0> (ŕēàďàƀĺē ōńĺŷ ƀŷ ŷōũŕ ũśēŕ àććōũńţ) àńď śĥàŕēď àćŕōśś àĺĺ ƥŕōĴēćţś. Ţũŕń ţĥē ƒēàţũŕē ōń ƥēŕ ƥŕōĴēćţ ĩń Ţĥĩś ƥŕōĴēćţ → Śēàŕćĥ, ŵĥēŕē ŷōũ ćàń àĺśō ōvēŕŕĩďē ţĥē ēńďƥōĩńţ."],@@ -2963,6 +3009,7 @@"yWSvcf": ["Ćōńţēńţ ŕōōţ"],"yWWThY": ["Àśśēţ ŕēƒēŕēńćē"],"yYR6za": ["Ďĩśƥĺàŷ ţēxţ"],+ "yZepkk": ["Ĝĩţ śŷńć"],"yZmvQ4": ["Ţĥĩś ƥŕōĴēćţ'ś śēŕvēŕ (v", ["0"], ") ĩś ńēŵēŕ ţĥàń ţĥĩś àƥƥ (v", ["1"], ")."],"y_5CE8": ["Ĩţēḿ ", ["0"]],"y_K0Dz": ["Ŵĥàţ ĥàƥƥēńēď?"],@@ -3037,6 +3084,7 @@"ztKII6": ["Ƒàĩĺēď ţō àďď ĩţēḿ"],"zvjCD4": ["Ďēţàĩĺēď ďĩàĝńōśţĩćś"],"zwBp5t": ["Ƥŕĩvàţē"],- "zyKa-I": ["Śţàŕ ũś ōń ĜĩţĤũƀ"]+ "zyKa-I": ["Śţàŕ ũś ōń ĜĩţĤũƀ"],+ "zz_Wd_": ["Ḿōďē"]}}diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex f109720ff..f457500e5 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -285,10 +285,6 @@ msgstr ""msgid "{accessibleLabel} (conflict)"msgstr ""-#: src/components/SyncStatusBadge.tsx-msgid "{ahead, plural, one {# commit ahead} other {# commits ahead}}"-msgstr ""-#: src/components/SyncStatusBadge.tsxmsgid "{ahead} ahead"msgstr ""@@ -561,6 +557,10 @@ msgstr ""msgid "{skillCount, plural, one {skill} other {skills}}"msgstr ""+#: src/components/EnableSyncConfirmDialog.tsx+msgid "{strandedCommitCount, plural, one {You have 1 change you haven't shared. It will stay on this computer.} other {You have # changes you haven't shared. They will stay on this computer.}}"+msgstr ""+#: src/components/CreatedItemsList.tsxmsgid "{templateCount, plural, one {template} other {templates}}"msgstr ""@@ -675,6 +675,10 @@ msgstr ""msgid "A branch with that name already exists. Open its worktree from the switcher instead."msgstr ""+#: src/components/SyncStatusBadge.tsx+msgid "A document has a conflict — resolve it to keep it up to date."+msgstr ""+#: src/components/CreateProjectDialog.tsxmsgid "A folder named <0>{sanitized}</0> already has files here. Pick a different name."msgstr ""@@ -1220,18 +1224,10 @@ msgstr ""msgid "Auto-save"msgstr ""-#: src/components/settings/SyncSection.tsx-msgid "Auto-sync is off — your edits stay local until you commit and push manually."-msgstr ""-#: src/hooks/use-worktree-autosync-notice.tsxmsgid "Auto-sync is off for this worktree, inherited from {project}. Change it in Settings → Sync."msgstr ""-#: src/components/settings/SyncSection.tsx-msgid "Auto-sync is on — your commits push and remote changes pull on intervals."-msgstr ""-#: src/hooks/use-worktree-autosync-notice.tsxmsgid "Auto-sync is on for this worktree, inherited from {project}. Change it in Settings → Sync."msgstr ""@@ -1241,17 +1237,13 @@ msgid "Auto-sync is paused — sign in to resume."msgstr ""#: src/components/settings/SyncSection.tsx-msgid "Auto-sync is paused — you don't have permission to push to this repo."+msgid "Auto-sync is paused — you don't have permission to push to this repo. Switch to Follow to keep receiving updates."msgstr ""#: src/components/AutoSyncEnableWarning.tsxmsgid "Auto-sync periodically fetches, pulls, and pushes commits to your remote git repository so your edits stay in sync across machines."msgstr ""-#: src/components/settings/SyncSection.tsx-msgid "Auto-sync pushes/pulls commits to your git remote on intervals and on save. Toggling on requires confirmation."-msgstr ""-#. Section label for the automatic, one-click install path#: src/components/InstallInClaudeDesktopDialog.tsxmsgid "Automatic"@@ -1543,6 +1535,10 @@ msgstr ""msgid "Checking for agents"msgstr ""+#: src/components/SyncStatusBadge.tsx+msgid "Checking for updates"+msgstr ""+#: src/components/share-receive-miss-content.tsx#: src/components/ShareBranchSwitchDialog.tsxmsgid "Checking for updates on GitHub"@@ -2998,18 +2994,10 @@ msgstr ""msgid "Disable external link previews"msgstr ""-#: src/components/settings/SyncSection.tsx-msgid "Disable git auto-sync"-msgstr ""-#: src/components/settings/SearchSection.tsxmsgid "Disable semantic search"msgstr ""-#: src/components/SyncStatusBadge.tsx-msgid "Disable sync"-msgstr ""-#: src/components/settings/LintingSection.tsxmsgid "Disable Themes"msgstr ""@@ -3399,8 +3387,13 @@ msgstr ""msgid "Enable external link previews"msgstr ""-#: src/components/settings/SyncSection.tsx-msgid "Enable git auto-sync"+#: src/components/AutoSyncOnboardingDialog.tsx+#: src/components/EnableSyncConfirmDialog.tsx+msgid "Enable Follow"+msgstr ""++#: src/components/AutoSyncEnableWarning.tsx+msgid "Enable Follow?"msgstr ""#: src/components/AutoSyncEnableWarning.tsx@@ -3411,10 +3404,6 @@ msgstr ""msgid "Enable semantic search"msgstr ""-#: src/components/SyncStatusBadge.tsx-msgid "Enable sync"-msgstr ""-#: src/components/TerminalGate.tsxmsgid "Enable terminal"msgstr ""@@ -3807,6 +3796,14 @@ msgstr ""msgid "Failed to update property"msgstr ""+#: src/hooks/use-enable-sync-with-confirm.ts+msgid "Failed to update sync — {detail}"+msgstr ""++#: src/hooks/use-enable-sync-with-confirm.ts+msgid "Failed to update sync mode — {detail}"+msgstr ""+#: src/components/settings/TerminalSection.tsxmsgid "Failed to update the auto-approve setting — {detail}"msgstr ""@@ -4027,6 +4024,28 @@ msgstr ""msgid "Folders"msgstr ""+#: src/components/settings/SyncSection.tsx+#: src/components/SyncStatusBadge.tsx+msgid "Follow"+msgstr ""++#: src/components/settings/SyncSection.tsx+#: src/components/SyncStatusBadge.tsx+msgid "Follow — updates flow in from your remote; your edits stay on this computer."+msgstr ""++#: src/components/AutoSyncEnableWarning.tsx+msgid "Follow fetches updates from your remote git repository and fast-forwards your copy automatically. Your local edits stay on this computer and are never pushed."+msgstr ""++#: src/hooks/use-worktree-autosync-notice.tsx+msgid "Follow is on for this worktree, inherited from {project}. Change it in Settings → Sync."+msgstr ""++#: src/components/AutoSyncEnableWarning.tsx+msgid "Follow never pushes or commits your local changes. They stay only on this machine."+msgstr ""+#: src/components/acp/ThreadView.tsxmsgid "Follow the agent's edits"msgstr ""@@ -4083,6 +4102,11 @@ msgstr ""msgid "Frontmatter every document created from this template starts with. Values are YAML — a list is <0>[a, b]</0>; <1>{{date}}</1> fills in on create."msgstr ""+#: src/components/settings/SyncSection.tsx+#: src/components/SyncStatusBadge.tsx+msgid "Full"+msgstr ""+#: src/components/InstallInClaudeDesktopDialog.tsxmsgid "Full guide"msgstr ""@@ -4096,6 +4120,14 @@ msgstr ""msgid "Full Path"msgstr ""+#: src/components/settings/SyncSection.tsx+msgid "Full sync — your commits push and remote changes pull automatically."+msgstr ""++#: src/components/SyncStatusBadge.tsx+msgid "Full sync — your edits are committed and pushed to your remote automatically."+msgstr ""+#: src/lib/keyboard-shortcuts.tsmsgid "General"msgstr ""@@ -4116,10 +4148,6 @@ msgstr ""msgid "Get set up"msgstr ""-#: src/components/settings/SyncSection.tsx-msgid "Git auto-sync"-msgstr ""-#: src/components/settings/SharingSection.tsx#: src/components/SkillsSidebarSection.tsxmsgid "git configuration is unavailable"@@ -4137,6 +4165,10 @@ msgstr ""msgid "Git needs a helper tool (such as git-lfs) that isn't installed or couldn't be found. Install it, then try again."msgstr ""+#: src/components/settings/SyncSection.tsx+msgid "Git sync"+msgstr ""+#: src/components/SyncStatusBadge.tsxmsgid "GitHub authentication failed. Try signing in again."msgstr ""@@ -4459,6 +4491,10 @@ msgstr ""msgid "I already have it locally →"msgstr ""+#: src/components/AutoSyncEnableWarning.tsx+msgid "If an update arrives for something you are editing, you choose which version to keep, like a merge conflict."+msgstr ""+#: src/components/ConsentDialogBody.tsx#: src/components/settings/OkignoreSection.tsx#: src/components/settings/SettingsDialogShell.tsx@@ -4771,6 +4807,10 @@ msgstr ""msgid "Keep original file"msgstr ""+#: src/components/settings/SyncSection.tsx+msgid "Keep this project in sync with your git remote. Follow fetches updates without pushing; full sync pushes your commits too. Turning sync on requires confirmation."+msgstr ""+#: src/components/SeedDialog.tsxmsgid "Keep track of the people and companies you work with and the meetings you have with them. Good for remembering who someone is, how you know them, and what you last talked about."msgstr ""@@ -4795,10 +4835,6 @@ msgstr ""msgid "Label <0>(visible link text)</0>"msgstr ""-#: src/components/SyncStatusBadge.tsx-msgid "Last sync"-msgstr ""-#: src/components/ActivityPanelBurstRow.tsxmsgid "Latest edit"msgstr ""@@ -5036,6 +5072,10 @@ msgstr ""msgid "Local collaboration data for \"{docName}\" could not be cleared. Reload to retry."msgstr ""+#: src/components/SyncStatusBadge.tsx+msgid "Local commits are keeping this copy from updating"+msgstr ""+#: src/components/settings/SharingSection.tsx#: src/components/SharingModeField.tsxmsgid "Local only"@@ -5196,6 +5236,10 @@ msgstr ""msgid "Missing page: {linkTitle}. Click to create."msgstr ""+#: src/components/SyncStatusBadge.tsx+msgid "Mode"+msgstr ""+#: src/components/FolderOverview.tsx#: src/components/settings/markdownlint-rule-browser.tsxmsgid "Modified"@@ -5408,6 +5452,10 @@ msgstr ""msgid "New branch <0>{trimmed}</0> will be created from the current commit, in its own worktree under <1>.ok/worktrees/</1>."msgstr ""+#: src/components/AutoSyncEnableWarning.tsx+msgid "New changes from your remote appear in your copy automatically."+msgstr ""+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.ts#: src/components/FileSidebar.tsx@@ -5900,10 +5948,6 @@ msgstr ""msgid "ok ui responded but server.lock has no port yet"msgstr ""-#: src/components/settings/SyncSection.tsx-msgid "On"-msgstr ""-#: src/components/settings/LinkPreviewsSection.tsxmsgid "On — hovering an external link sends its URL to the destination site to fetch a preview."msgstr ""@@ -6350,6 +6394,10 @@ msgstr ""msgid "Outline"msgstr ""+#: src/components/AutoSyncEnableWarning.tsx+msgid "Overlapping edits"+msgstr ""+#: src/components/PublishToGitHubDialog.tsxmsgid "Owner"msgstr ""@@ -6504,6 +6552,10 @@ msgstr ""msgid "Pattern warnings: {summary}"msgstr ""+#: src/components/SyncStatusBadge.tsx+msgid "Pause sync"+msgstr ""+#: src/components/acp/ThreadView.tsxmsgid "pending"msgstr ""@@ -7310,6 +7362,10 @@ msgstr ""msgid "Results capped — this workspace has more files than search can index. A missing file may be a cap artifact, not a typo."msgstr ""+#: src/components/SyncStatusBadge.tsx+msgid "Resume sync"+msgstr ""+#: src/components/acp/ThreadView.tsxmsgid "Resuming the conversation"msgstr ""@@ -7318,7 +7374,6 @@ msgstr ""#: src/components/ConnectingBanner.tsx#: src/components/PublishToGitHubDialog.tsx#: src/components/settings/ConfigureAgentsSection.tsx-#: src/components/SyncStatusBadge.tsx#: src/components/TrashFailureModal.tsxmsgid "Retry"msgstr ""@@ -7747,7 +7802,7 @@ msgid "Set identity"msgstr ""#: src/components/settings/SyncSection.tsx-msgid "Set the auto-sync default for users opening this project for the first time. This setting is committed to your repository."+msgid "Set the sync default for users opening this project for the first time. This setting is committed to your repository."msgstr ""#: src/components/command-palette-commands.ts@@ -7847,10 +7902,6 @@ msgstr ""msgid "Shared"msgstr ""-#: src/components/settings/SyncSection.tsx-msgid "Shared auto-sync default"-msgstr ""-#: src/components/settings/SyncSection.tsxmsgid "Shared default"msgstr ""@@ -8376,6 +8427,10 @@ msgstr ""msgid "Switch project…"msgstr ""+#: src/components/settings/SyncSection.tsx+msgid "Switch to Follow"+msgstr ""+#: src/components/settings/SharingSection.tsxmsgid "Switch to local-only refused"msgstr ""@@ -8406,6 +8461,7 @@ msgstr ""#: src/components/settings/SettingsDialogShell.tsx#: src/components/settings/SyncSection.tsx+#: src/components/SyncStatusBadge.tsxmsgid "Sync"msgstr ""@@ -8413,11 +8469,6 @@ msgstr ""msgid "Sync disabled"msgstr ""-#: src/components/settings/SyncSection.tsx-#: src/components/SyncStatusBadge.tsx-msgid "Sync disabled — you don't have permission to push"-msgstr ""-#: src/components/SyncStatusBadge.tsxmsgid "Sync failed — check the server logs for details."msgstr ""@@ -8426,13 +8477,20 @@ msgstr ""msgid "Sync is failing. See the sync status for details."msgstr ""+#: src/components/settings/SyncSection.tsx+msgid "Sync is off — your edits stay on this computer until you commit and push manually."+msgstr ""+#: src/components/SyncStatusBadge.tsx-msgid "Sync is off — your edits will not sync to the remote repository."+msgid "Sync is paused. Turn it back on to resume."+msgstr ""++#: src/components/SyncStatusBadge.tsx+msgid "Sync mode"msgstr ""#: src/components/share-receive-miss-content.tsx#: src/components/ShareFreshnessWarning.tsx-#: src/components/SyncStatusBadge.tsxmsgid "Sync now"msgstr ""@@ -8440,6 +8498,10 @@ msgstr ""msgid "Sync off"msgstr ""+#: src/components/SyncStatusBadge.tsx+msgid "Sync paused"+msgstr ""+#: src/components/SyncStatusBadge.tsxmsgid "Sync paused — resolve conflicts to resume."msgstr ""@@ -8478,6 +8540,10 @@ msgstr ""msgid "Synced"msgstr ""+#: src/components/SyncStatusBadge.tsx+msgid "Synced {lastSyncedRelative}"+msgstr ""+#: src/components/TimelinePanel.tsxmsgid "Synced from disk"msgstr ""@@ -9315,6 +9381,10 @@ msgstr ""msgid "Unrecognized wiki link"msgstr ""+#: src/components/SyncStatusBadge.tsx+msgid "Up to date"+msgstr ""+#: src/components/SkillUpdateDialog.tsxmsgid "Update"msgstr ""@@ -9358,6 +9428,10 @@ msgstr ""msgid "Updated \"{display}\" to {0}."msgstr ""+#: src/components/SyncStatusBadge.tsx+msgid "Updated {lastSyncedRelative}"+msgstr ""+#: src/components/FolderTimelineCard.tsxmsgid "updated folder properties"msgstr ""@@ -9366,7 +9440,12 @@ msgstr ""msgid "Updated to Version {version}"msgstr ""+#: src/components/AutoSyncEnableWarning.tsx+msgid "Updates flow in"+msgstr ""+#: src/components/SkillUpdateDialog.tsx+#: src/components/SyncStatusBadge.tsxmsgid "Updating"msgstr ""@@ -9752,7 +9831,7 @@ msgid "You can attach up to {MAX_ATTACHMENTS} images."msgstr ""#: src/components/AutoSyncOnboardingDialog.tsx-msgid "You can turn this on later in <0>Settings → Sync</0>."+msgid "You can change this later in <0>Settings → Sync</0>."msgstr ""#: src/components/DocumentErrorBoundary.tsx@@ -9771,6 +9850,7 @@ msgstr ""msgid "You don't have access to this repository."msgstr ""+#: src/components/settings/SyncSection.tsx#: src/components/SyncStatusBadge.tsxmsgid "You don't have permission to push to this repo"msgstr ""@@ -9779,6 +9859,10 @@ msgstr ""msgid "You don't have permission to push to this repo."msgstr ""+#: src/components/settings/SyncSection.tsx+msgid "You don't have permission to push to this repo. Follow can still keep your copy up to date."+msgstr ""+#: src/components/ShareFreshnessWarning.tsxmsgid "You don't have write access to this repo."msgstr ""@@ -9832,6 +9916,10 @@ msgstr ""msgid "Your current version is saved first, so this is reversible."msgstr ""+#: src/components/AutoSyncEnableWarning.tsx+msgid "Your edits stay on this computer"+msgstr ""+#: src/components/settings/EmbeddingsKeySection.tsxmsgid "Your embeddings provider API key, used only to create embeddings of your content for semantic search. Stored once for this machine in <0>~/.ok/secrets.yml</0> (readable only by your user account) and shared across all projects. Turn the feature on per project in This project → Search, where you can also override the endpoint."msgstr ""diff --git a/packages/app/tests/integration/sync-wired-harness.test.ts b/packages/app/tests/integration/sync-wired-harness.test.tsnew file mode 100644index 000000000..7276dca35--- /dev/null+++ b/packages/app/tests/integration/sync-wired-harness.test.ts@@ -0,0 +1,341 @@+/**+ * S2 substrate smoke tests for the sync-wired harness mode.+ *+ * `createSyncWiredTestServer` boots a real server whose SyncEngine is attached+ * to a bare origin repo. These tests prove the composed background-sync chain is+ * drivable in-process — seed an upstream commit, drive one pull, and observe the+ * fast-forward land on disk, in a live CRDT doc, and in the engine's status — so+ * downstream stories (the B1 pull cycle, one-shot pull, mode transitions) can+ * assert against the real fetch → merge → import → status path rather than a+ * stubbed engine.+ */++import { execFile } from 'node:child_process';+import { existsSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { promisify } from 'node:util';+import { afterEach, describe, expect, test } from 'vitest';+import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';+import {+ awaitFileWatcherIndexed,+ createSyncWiredTestServer,+ createTestClient,+ pollUntil,+ type SyncWiredTestServer,+ serializeFragment,+ type TestClient,+} from './test-harness';++const execFileAsync = promisify(execFile);++async function revParse(dir: string, ref: string): Promise<string> {+ const { stdout } = await execFileAsync('git', ['rev-parse', ref], { cwd: dir });+ return stdout.trim();+}++describe('sync-wired harness (S2 substrate)', () => {+ const servers: SyncWiredTestServer[] = [];+ const clients: TestClient[] = [];++ afterEach(async () => {+ // Disconnect clients before tearing down their servers so the per-doc+ // testReset in client cleanup still has a live server to talk to.+ for (const client of clients.splice(0)) {+ await client.cleanup().catch(() => {});+ }+ for (const server of servers.splice(0)) {+ await server.cleanup().catch(() => {});+ }+ });++ /**+ * The composed background-pull chain end to end: an upstream commit+ * fast-forwards into the follower's working tree, loads into a live CRDT+ * doc on connect, and settles the engine's status fields.+ *+ */+ test(+ 'full mode: an upstream commit fast-forwards to disk, into the CRDT, and updates status',+ async () => {+ const server = await createSyncWiredTestServer({+ mode: 'full',+ originSeed: { 'guide.md': '# Guide\n\nversion one\n' },+ });+ servers.push(server);+ const { engine } = server.sync;++ // The engine attached to the origin at boot and parked idle without+ // fetching yet — the composed chain has a clean starting line.+ const before = engine.getStatus();+ expect(before.hasRemote).toBe(true);+ expect(before.syncMode).toBe('full');+ expect(before.state).toBe('idle');+ expect(before.lastFetchUtc).toBeNull();++ // A teammate pushes: modify the seeded doc and add a brand-new one.+ await server.sync.pushToOrigin({+ 'guide.md': '# Guide\n\nversion two from origin\n',+ 'briefing.md': '# Briefing\n\nbrand new upstream doc\n',+ });++ await engine.trigger('pull');++ // Sync status reflects the outcome of a clean fast-forward.+ const after = engine.getStatus();+ expect(after.state).toBe('idle');+ expect(after.behind).toBe(0);+ expect(after.conflictCount).toBe(0);+ expect(after.lastFetchUtc).not.toBeNull();++ // The fast-forward wrote the working tree: both files land on disk.+ expect(readFileSync(join(server.contentDir, 'guide.md'), 'utf-8')).toContain(+ 'version two from origin',+ );+ expect(readFileSync(join(server.contentDir, 'briefing.md'), 'utf-8')).toContain(+ 'brand new upstream doc',+ );++ // The CRDT reflects the pulled content: the server indexes the new file+ // and a connecting client loads it through persistence into a live Y.Doc.+ await awaitFileWatcherIndexed(server, 'briefing');+ const client = await createTestClient(server.port, 'briefing');+ clients.push(client);+ await pollUntil(() => serializeFragment(client.fragment).includes('brand new upstream doc'));+ expect(serializeFragment(client.fragment)).toContain('brand new upstream doc');+ },+ HARNESS_BOOT_TIMEOUT_MS,+ );++ /**+ * Pull-only mode attaches to the remote (idle, not dormant) and fast-forwards+ * an upstream commit onto disk — the same composed chain without a push side.+ *+ */+ test(+ 'pull-only mode: attaches to the remote and fast-forwards an upstream commit',+ async () => {+ const server = await createSyncWiredTestServer({+ mode: 'follow',+ originSeed: { 'guide.md': '# Guide\n\nversion one\n' },+ });+ servers.push(server);+ const { engine } = server.sync;++ // Pull-only is a first-class attached mode — not dormant/disabled — and+ // reports itself through the additive syncMode status field.+ const before = engine.getStatus();+ expect(before.hasRemote).toBe(true);+ expect(before.syncMode).toBe('follow');+ expect(before.state).toBe('idle');++ await server.sync.pushToOrigin({+ 'briefing.md': '# Briefing\n\nfollower reads this\n',+ });++ await engine.trigger('pull');++ const after = engine.getStatus();+ expect(after.state).toBe('idle');+ expect(after.behind).toBe(0);+ expect(after.conflictCount).toBe(0);+ expect(readFileSync(join(server.contentDir, 'briefing.md'), 'utf-8')).toContain(+ 'follower reads this',+ );+ },+ HARNESS_BOOT_TIMEOUT_MS,+ );++ /**+ * The B1 fast-forward composed through the whole stack: a doc opened BEFORE the+ * pull updates in place when the upstream commit lands, the branch reaches+ * origin's tip, and the pull-only cycle leaves no git residue (no commit, no+ * MERGE_HEAD). Connecting first is what distinguishes this from a+ * load-from-disk-on-connect assertion — the FF must import into a live Y.Doc.+ *+ */+ test(+ 'pull-only: a background fast-forward updates an already-open live doc with no git residue',+ async () => {+ const server = await createSyncWiredTestServer({+ mode: 'follow',+ originSeed: { 'guide.md': '# Guide\n\nversion one\n' },+ });+ servers.push(server);+ const { engine } = server.sync;++ // Open the doc first, so the pull must reconcile into a live CRDT doc+ // rather than merely land bytes a later connect would read from disk.+ const client = await createTestClient(server.port, 'guide');+ clients.push(client);+ await pollUntil(() => serializeFragment(client.fragment).includes('version one'));++ await server.sync.pushToOrigin({ 'guide.md': '# Guide\n\nversion two from origin\n' });+ await engine.trigger('pull');++ const after = engine.getStatus();+ expect(after.state).toBe('idle');+ expect(after.behind).toBe(0);++ // Branch fast-forwarded to origin's tip.+ expect(await revParse(server.contentDir, 'HEAD')).toBe(+ await revParse(server.contentDir, 'origin/main'),+ );++ // The already-open Y.Doc reflects the pulled content in place.+ await pollUntil(() => serializeFragment(client.fragment).includes('version two from origin'));+ expect(serializeFragment(client.fragment)).toContain('version two from origin');++ // Pull-only never commits or merges: no MERGE_HEAD, no stash residue.+ expect(existsSync(join(server.contentDir, '.git', 'MERGE_HEAD'))).toBe(false);+ const { stdout: stashList } = await execFileAsync('git', ['stash', 'list'], {+ cwd: server.contentDir,+ });+ expect(stashList.trim()).toBe('');+ },+ HARNESS_BOOT_TIMEOUT_MS,+ );++ /**+ * A same-line collision composed through the whole stack: the conflict-content+ * endpoint serves `theirs`/`base` from the pinned blobs and `ours` from the+ * overlay (live Y.Doc once open), and an HTTP take-theirs resolution writes the+ * tip version and clears the conflict — all without a git commit. Opening the+ * doc loads the disk overlay into a live CRDT doc, covering the disk→CRDT path.+ *+ */+ test(+ 'pull-only: a same-line collision surfaces conflict-content and resolves via HTTP with no commit',+ async () => {+ const server = await createSyncWiredTestServer({+ mode: 'follow',+ originSeed: { 'guide.md': '# Guide\n\nintro\n\noutro\n' },+ });+ servers.push(server);+ const { engine } = server.sync;++ // Local overlay edits the intro; origin edits the SAME line — a collision.+ writeFileSync(+ join(server.contentDir, 'guide.md'),+ '# Guide\n\nLOCAL intro\n\noutro\n',+ 'utf-8',+ );+ await server.sync.pushToOrigin({ 'guide.md': '# Guide\n\nORIGIN intro\n\noutro\n' });+ await engine.trigger('pull');++ // The branch reached origin tip; the overlay is kept on disk; a working-tree+ // conflict is tracked.+ expect(await revParse(server.contentDir, 'HEAD')).toBe(+ await revParse(server.contentDir, 'origin/main'),+ );+ expect(readFileSync(join(server.contentDir, 'guide.md'), 'utf-8')).toContain('LOCAL intro');+ const conflicts = engine.getConflicts();+ expect(conflicts).toHaveLength(1);+ expect(conflicts[0]?.variant).toBe('working-tree');++ // conflict-content serves theirs/base from the pinned blobs; ours from the+ // on-disk overlay (no doc open yet).+ const base = `http://127.0.0.1:${server.port}/api/sync/conflict-content`;+ const diskRes = await fetch(`${base}?file=guide.md`);+ expect(diskRes.status).toBe(200);+ const diskBody = (await diskRes.json()) as {+ base: string;+ ours: string;+ theirs: string;+ kind: string;+ };+ expect(diskBody.kind).toBe('both-modified');+ expect(diskBody.theirs).toContain('ORIGIN intro');+ expect(diskBody.ours).toContain('LOCAL intro');+ expect(diskBody.base).toContain('intro');+ expect(diskBody.base).not.toContain('ORIGIN');+ expect(diskBody.base).not.toContain('LOCAL');++ // Opening the doc loads the disk overlay into a live CRDT doc and the+ // lifecycle seed flips it into conflict; conflict-content then serves ours+ // from the live Y.Text.+ const client = await createTestClient(server.port, 'guide');+ clients.push(client);+ await pollUntil(() => serializeFragment(client.fragment).includes('LOCAL intro'));+ const ytextRes = await fetch(`${base}?file=guide.md&source=ytext`);+ const ytextBody = (await ytextRes.json()) as { ours: string; lifecycleStatus: string | null };+ expect(ytextBody.ours).toContain('LOCAL intro');+ expect(ytextBody.lifecycleStatus).toBe('conflict');+ await pollUntil(() => client.doc.getMap('lifecycle').get('status') === 'conflict');++ // Keep-mine over HTTP leaves the overlay untouched (no disk change), so the+ // conflict lifecycle clears only via the resolved callback — not the+ // file-watcher's `case 'update'`. The overlay survives, the conflict is+ // gone, the lifecycle clears on the client, and nothing was committed.+ const resolveRes = await fetch(`http://127.0.0.1:${server.port}/api/sync/resolve-conflict`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ file: 'guide.md', strategy: 'mine' }),+ });+ expect(resolveRes.status).toBe(200);+ expect(engine.getConflicts()).toEqual([]);+ expect(readFileSync(join(server.contentDir, 'guide.md'), 'utf-8')).toContain('LOCAL intro');+ await pollUntil(() => client.doc.getMap('lifecycle').get('status') === undefined);+ expect(existsSync(join(server.contentDir, '.git', 'MERGE_HEAD'))).toBe(false);+ },+ HARNESS_BOOT_TIMEOUT_MS,+ );++ /**+ * The one-shot pull contract composed through the real HTTP surface: a+ * consumer reads status, POSTs `trigger {op:'pull'}` (202 fire-and-forget),+ * then waits for `lastPullUtc` to change and reads `lastPullOutcome` — the+ * change-detection consumer pattern end to end. The upstream commit+ * fast-forwards to disk and into a live CRDT doc.+ *+ */+ test(+ 'one-shot pull over HTTP: 202 accept, then status carries lastPullUtc + a succeeded outcome',+ async () => {+ const server = await createSyncWiredTestServer({+ mode: 'follow',+ originSeed: { 'guide.md': '# Guide\n\nversion one\n' },+ });+ servers.push(server);+ const statusUrl = `http://127.0.0.1:${server.port}/api/sync/status`;+ const triggerUrl = `http://127.0.0.1:${server.port}/api/sync/trigger`;+ type PullStatus = { lastPullUtc: string | null; lastPullOutcome: string | null };++ // The consumer reads status before triggering — no pull has completed yet.+ const before = (await (await fetch(statusUrl)).json()) as PullStatus;+ expect(before.lastPullUtc ?? null).toBeNull();++ // A teammate pushes an upstream change.+ await server.sync.pushToOrigin({ 'guide.md': '# Guide\n\nversion two from origin\n' });++ // Trigger a one-shot pull: 202 Accepted, background execution (no+ // synchronous outcome in the response body — the consumer polls status).+ const triggerRes = await fetch(triggerUrl, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ op: 'pull' }),+ });+ expect(triggerRes.status).toBe(202);+ expect(((await triggerRes.json()) as { op: string }).op).toBe('pull');++ // Wait for lastPullUtc to change, then read the outcome (the+ // change-detection consumer pattern: read-before-trigger,+ // wait-for-change, give-up-timeout).+ let after: PullStatus = before;+ await pollUntil(async () => {+ after = (await (await fetch(statusUrl)).json()) as PullStatus;+ return after.lastPullUtc != null && after.lastPullUtc !== (before.lastPullUtc ?? null);+ });+ expect(after.lastPullOutcome).toBe('succeeded');++ // The fast-forward landed on disk and imports into a live CRDT doc.+ expect(readFileSync(join(server.contentDir, 'guide.md'), 'utf-8')).toContain(+ 'version two from origin',+ );+ const client = await createTestClient(server.port, 'guide');+ clients.push(client);+ await pollUntil(() => serializeFragment(client.fragment).includes('version two from origin'));+ expect(serializeFragment(client.fragment)).toContain('version two from origin');+ },+ HARNESS_BOOT_TIMEOUT_MS,+ );+});diff --git a/packages/app/tests/integration/test-harness.ts b/packages/app/tests/integration/test-harness.tsindex 84d497fac..d32a53e9a 100644--- a/packages/app/tests/integration/test-harness.ts+++ b/packages/app/tests/integration/test-harness.ts@@ -17,12 +17,14 @@* (required for test.concurrent() correctness)*/+import { execFile } from 'node:child_process';import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';import { createServer as createHttpServer } from 'node:http';import { createServer as createNetServer, type Socket } from 'node:net';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { dirname, join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';+import { promisify } from 'node:util';export { wait };@@ -33,10 +35,12 @@ import {BridgeInvariantViolationError,type InvariantViolation,isParseEquivalentBridge,+ LOCAL_DIR,MarkdownManager,normalizeBridge,prependFrontmatter,ServerInfoSuccessSchema,+ type SyncMode,sharedExtensions,stripFrontmatter,} from '@inkeep/open-knowledge-core';@@ -182,6 +186,15 @@ export interface CreateTestServerOptions {* applies to fresh contentDirs (`options.contentDir === undefined`).*/markdownlintEnabled?: boolean;+ /**+ * Seconds between the attached SyncEngine's background pull/push cycles.+ * Forwarded to `ServerOptions`. Sync-wired tests (`createSyncWiredTestServer`)+ * pass a large value so a background timer never races the scenario the test+ * drives explicitly via `engine.trigger()`. Omit for the default engine+ * cadence (30 s pull / 60 s push).+ */+ pullIntervalSeconds?: number;+ pushIntervalSeconds?: number;}export async function createTestServer(options: CreateTestServerOptions = {}): Promise<TestServer> {@@ -270,6 +283,8 @@ export async function createTestServer(options: CreateTestServerOptions = {}): PlocalOpCliArgs: options.localOpCliArgs,configHomedirOverride: homeOverride,mdManager: options.mdManager,+ pullIntervalSeconds: options.pullIntervalSeconds,+ pushIntervalSeconds: options.pushIntervalSeconds,...(ephemeral ? { ephemeral: true, singleDocRelPath: options.singleDocRelPath } : {}),// Skip the durable state-manifest pre-flight gate. Each test allocates a fresh tmpdir, so the gate has nothing// meaningful to assert; the writes would just generate noise across thousands@@ -2004,3 +2019,173 @@ export async function pollDiskContentStable(`pollDiskContentStable: predicate never held for ${settleMs}ms within ${timeoutMs}ms budget on ${filePath}. Last content length: ${lastContent.length}`,);}++// ─── Sync-wired server (real bare origin + attached SyncEngine) ───+//+// The plain `createTestServer` boots a SyncEngine against a remote-less git+// repo, so it parks dormant and never pulls. `createSyncWiredTestServer` gives+// the harness a real upstream: a bare origin repo, a seeded author clone that+// authors upstream commits, and a follower clone (the server's contentDir) that+// carries an `origin` remote and a project-local `autoSync.mode`. The attached+// SyncEngine detects that remote at boot, so the composed+// fetch → fast-forward → CRDT-import → status chain becomes drivable in-process+// via `engine.trigger('pull')`.++const execFileAsync = promisify(execFile);++/** Large enough that the engine's background cadence never fires within a test;+ * sync-wired tests drive cycles explicitly via `trigger()`. Mirrors the+ * interval the engine-tier fixtures use to pin scheduling out of the way. */+const SYNC_WIRED_IDLE_INTERVAL_SECONDS = 99_999;++async function runGit(cwd: string, args: string[]): Promise<string> {+ const { stdout } = await execFileAsync('git', args, { cwd });+ return stdout;+}++/** Write each `path → content` entry under `root`, creating parent dirs. */+function writeFilesUnder(root: string, files: Record<string, string>): void {+ for (const [rel, content] of Object.entries(files)) {+ const abs = join(root, rel);+ mkdirSync(dirname(abs), { recursive: true });+ writeFileSync(abs, content, 'utf-8');+ }+}++export interface SyncWiredHandle {+ /** The bare origin repo the engine fetches from (the "GitHub" of the test). */+ originDir: string;+ /**+ * Author an upstream commit: write each `path → content` file into the+ * persistent author clone, commit, and push to `origin/main`. Resolves after+ * the push completes, so a subsequent `engine.trigger('pull')` observes the+ * new tip. Simulates a teammate pushing to the shared repo. File bytes must+ * differ from the current tip (an unchanged tree makes `git commit` fail).+ */+ pushToOrigin: (files: Record<string, string>, message?: string) => Promise<void>;+ /** The attached SyncEngine — asserted non-null at boot. Drive with+ * `trigger()` / `setMode()`; read with `getStatus()`. Also reachable via+ * `server.instance.syncEngine`. */+ engine: NonNullable<ServerInstance['syncEngine']>;+}++export interface SyncWiredTestServer extends TestServer {+ sync: SyncWiredHandle;+}++export interface CreateSyncWiredServerOptions {+ /** `autoSync.mode` seeded into the follower's project-local config, so the+ * engine attaches in this mode at boot. Default `'full'`. */+ mode?: SyncMode;+ /** Files committed to `origin/main` before the follower clone (so the clone+ * starts with them). Default seeds one document. */+ originSeed?: Record<string, string>;+ /** Engine pull cadence (seconds). Default: parked far out of the way. */+ pullIntervalSeconds?: number;+ /** Engine push cadence (seconds). Default: parked far out of the way. */+ pushIntervalSeconds?: number;+ /** Extra `createTestServer` options merged in (e.g. `debounce`). `contentDir`+ * and `keepContentDir` are managed by this helper and cannot be overridden. */+ serverOptions?: Omit<CreateTestServerOptions, 'contentDir' | 'keepContentDir'>;+}++/**+ * Boot a test server whose SyncEngine is wired to a real bare origin repo.+ *+ * Layout created (all under `os.tmpdir()`, per-call unique, parallel-safe):+ * - `originDir` — bare repo, `main` HEAD, seeded via the author clone.+ * - author clone — authors upstream commits; reused by `pushToOrigin`.+ * - follower clone — the server's `contentDir`; carries the `origin` remote+ * and `.ok/local/config.yml` → `autoSync.mode`, so the engine attaches.+ *+ * All existing `createTestServer` consumers are unaffected — this is a separate+ * entry point that layers git setup around the same factory.+ */+export async function createSyncWiredTestServer(+ options: CreateSyncWiredServerOptions = {},+): Promise<SyncWiredTestServer> {+ const mode = options.mode ?? 'full';+ const originSeed = options.originSeed ?? { 'guide.md': '# Guide\n\nseed content\n' };++ // ── Bare origin ──+ const originDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-sync-origin-')));+ await runGit(originDir, ['init', '--bare']);+ // Pin the default branch so the author's first push and the follower clone+ // agree on `main` regardless of the host git's `init.defaultBranch`.+ await runGit(originDir, ['symbolic-ref', 'HEAD', 'refs/heads/main']);++ // ── Author clone: seed origin/main ──+ const authorDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-sync-author-')));+ await runGit(authorDir, ['init', '--initial-branch=main']);+ await runGit(authorDir, ['config', 'user.email', '[email protected]']);+ await runGit(authorDir, ['config', 'user.name', 'Upstream Author']);+ await runGit(authorDir, ['remote', 'add', 'origin', originDir]);+ writeFilesUnder(authorDir, originSeed);+ await runGit(authorDir, ['add', '-A']);+ await runGit(authorDir, ['commit', '-m', 'seed origin']);+ await runGit(authorDir, ['push', 'origin', 'main']);++ // ── Follower clone: the server's contentDir ──+ const cloneParent = realpathSync(mkdtempSync(join(tmpdir(), 'ok-sync-clone-')));+ const clonePath = join(cloneParent, 'content');+ await runGit(cloneParent, ['clone', originDir, clonePath]);+ const contentDir = realpathSync(clonePath);+ await runGit(contentDir, ['config', 'user.email', '[email protected]']);+ await runGit(contentDir, ['config', 'user.name', 'Follower']);++ // Project marker (`.ok/config.yml`) so server handlers admit operations, and+ // the per-machine `autoSync.mode` the engine reads at construction. The+ // project-local file lives under `.ok/local/` (git-ignored runtime state), so+ // it never enters the working tree the engine fast-forwards.+ mkdirSync(join(contentDir, '.ok', LOCAL_DIR), { recursive: true });+ writeFileSync(join(contentDir, '.ok', 'config.yml'), '', 'utf-8');+ writeFileSync(+ join(contentDir, '.ok', LOCAL_DIR, 'config.yml'),+ `autoSync:\n mode: ${mode}\n`,+ 'utf-8',+ );++ const removeScratch = (): void => {+ rmSync(originDir, { recursive: true, force: true });+ rmSync(authorDir, { recursive: true, force: true });+ rmSync(cloneParent, { recursive: true, force: true });+ };++ const testServer = await createTestServer({+ ...options.serverOptions,+ contentDir,+ // This helper owns all scratch dirs (origin, author, follower parent) and+ // removes them together in the wrapped cleanup below.+ keepContentDir: true,+ pullIntervalSeconds: options.pullIntervalSeconds ?? SYNC_WIRED_IDLE_INTERVAL_SECONDS,+ pushIntervalSeconds: options.pushIntervalSeconds ?? SYNC_WIRED_IDLE_INTERVAL_SECONDS,+ });++ const engine = testServer.instance.syncEngine;+ if (engine === null) {+ await testServer.cleanup();+ removeScratch();+ throw new Error(+ 'createSyncWiredTestServer: SyncEngine did not attach — expected an origin remote on the cloned contentDir',+ );+ }++ const pushToOrigin = async (+ files: Record<string, string>,+ message = 'upstream update',+ ): Promise<void> => {+ writeFilesUnder(authorDir, files);+ await runGit(authorDir, ['add', '-A']);+ await runGit(authorDir, ['commit', '-m', message]);+ await runGit(authorDir, ['push', 'origin', 'main']);+ };++ return {+ ...testServer,+ sync: { originDir, pushToOrigin, engine },+ cleanup: async () => {+ await testServer.cleanup();+ removeScratch();+ },+ };+}diff --git a/packages/core/src/bridge/index.ts b/packages/core/src/bridge/index.tsindex 29455914e..32718b836 100644--- a/packages/core/src/bridge/index.ts+++ b/packages/core/src/bridge/index.ts@@ -60,6 +60,7 @@ export {type BridgeMergeContentLossSide,type BridgeMergeContentLossWhich,mergeThreeWay,+ tryLineLevelCombine,} from './merge-three-way.ts';export {BRIDGE_TOLERANCE_CLASSES,diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.tsindex 3c927eb47..f06c1614e 100644--- a/packages/core/src/bridge/merge-three-way.ts+++ b/packages/core/src/bridge/merge-three-way.ts@@ -38,6 +38,33 @@ function mergeThreeWayImpl(baseline: string, userText: string, agentText: stringreturn parts.join('\n');}+export function tryLineLevelCombine(+ base: string,+ mine: string,+ theirs: string,+): { clean: true; merged: string } | { clean: false } {+ if (base === mine) return { clean: true, merged: theirs };+ if (base === theirs) return { clean: true, merged: mine };+ if (mine === theirs) return { clean: true, merged: mine };++ const regions = diff3Merge(mine.split('\n'), base.split('\n'), theirs.split('\n'));+ const parts: string[] = [];+ for (const region of regions) {+ if ('ok' in region && region.ok) {+ parts.push(region.ok.join('\n'));+ } else {+ return { clean: false };+ }+ }+ const merged = parts.join('\n');+ try {+ assertContentPreservation(base, mine, theirs, merged);+ } catch {+ return { clean: false };+ }+ return { clean: true, merged };+}+export type BridgeMergeContentLossSide = 'user' | 'agent';diff --git a/packages/core/src/config/auto-sync-mode-confinement.test.ts b/packages/core/src/config/auto-sync-mode-confinement.test.tsnew file mode 100644index 000000000..467302529--- /dev/null+++ b/packages/core/src/config/auto-sync-mode-confinement.test.ts@@ -0,0 +1,96 @@+import { readdirSync, readFileSync, statSync } from 'node:fs';+import { join, relative, resolve } from 'node:path';+import { describe, expect, test } from 'vitest';++// Cross-file contract: `autoSync.mode` is the single sync knob. The legacy+// `autoSync.enabled` boolean may only be READ by the derive path in+// `auto-sync-mode.ts` (or by call sites that pass it straight into those+// resolvers). Any other read re-creates the two-knob split where a+// non-mode-aware reader could treat "enabled" as permission to push for a+// pull-only project. Runtime tests cannot catch a future rogue read (it only+// misbehaves once shipped), so this structural sweep is the machine guard.+// When adding a legitimate new derive-path caller, extend ALLOWED_READERS.+const ALLOWED_READERS = new Set([+ 'packages/core/src/config/auto-sync-mode.ts',+ 'packages/app/src/hooks/use-worktree-autosync-notice.tsx',+]);++// Dotted / optional-chained reads: `autoSync.enabled`, `autoSync?.enabled`.+const LEGACY_READ = /autoSync\??\.\s*enabled/;+// Bracket-indexed reads: `autoSync['enabled']`, `autoSync["enabled"]`. Matched+// against the raw line (not the string-blanked `code`) because blanking would+// erase the literal key that is the signal. Known blind spot: a destructured+// read (`const { enabled } = autoSync`) still slips past — the codebase reads+// `enabled` by property access, so this is the pragmatic floor, not exhaustive.+const LEGACY_READ_BRACKET = /autoSync\s*\[\s*['"]enabled['"]\s*\]/;+const STRING_LITERAL = /'[^']*'|"[^"]*"|`[^`]*`/g;++function findSubtreeRoot(): string {+ let dir = resolve(__dirname);+ for (let i = 0; i < 10; i++) {+ try {+ statSync(join(dir, 'pnpm-workspace.yaml'));+ return dir;+ } catch {+ dir = resolve(dir, '..');+ }+ }+ throw new Error(`pnpm-workspace.yaml not found walking up from ${__dirname}`);+}++function* sourceFiles(dir: string): Generator<string> {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = join(dir, entry.name);+ if (entry.isDirectory()) {+ if (entry.name === 'node_modules' || entry.name === 'dist') continue;+ yield* sourceFiles(full);+ } else if (+ (entry.name.endsWith('.ts') || entry.name.endsWith('.tsx')) &&+ !entry.name.includes('.test.') &&+ !entry.name.includes('test-helper')+ ) {+ yield full;+ }+ }+}++describe('autoSync.enabled read confinement', () => {+ test('legacy enabled is only read by the mode-derive path', () => {+ const root = findSubtreeRoot();+ const offenders: string[] = [];+ const packagesDir = join(root, 'packages');+ for (const pkg of readdirSync(packagesDir)) {+ const src = join(packagesDir, pkg, 'src');+ let srcStat: ReturnType<typeof statSync>;+ try {+ srcStat = statSync(src);+ } catch {+ continue;+ }+ if (!srcStat.isDirectory()) continue;+ for (const file of sourceFiles(src)) {+ const rel = relative(root, file);+ if (ALLOWED_READERS.has(rel)) continue;+ const lines = readFileSync(file, 'utf-8').split('\n');+ lines.forEach((line, idx) => {+ const trimmed = line.trim();+ if (trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('/*')) {+ return;+ }+ const code = line.replace(STRING_LITERAL, "''").split('//')[0];+ // Bracket reads keep their literal key, so match them on the raw line.+ const rawCode = line.split('//')[0];+ if (LEGACY_READ.test(code) || LEGACY_READ_BRACKET.test(rawCode)) {+ offenders.push(`${rel}:${idx + 1}: ${trimmed}`);+ }+ });+ }+ }+ expect(+ offenders,+ 'autoSync.enabled must only be read by the derive path (auto-sync-mode.ts resolvers). ' ++ 'Route new readers through resolveLocalAutoSyncMode/resolveEffectiveAutoSyncMode, ' ++ 'or extend ALLOWED_READERS only for call sites that feed those resolvers directly.',+ ).toEqual([]);+ });+});diff --git a/packages/core/src/config/auto-sync-mode.test.ts b/packages/core/src/config/auto-sync-mode.test.tsnew file mode 100644index 000000000..fd8dbc953--- /dev/null+++ b/packages/core/src/config/auto-sync-mode.test.ts@@ -0,0 +1,124 @@+import { describe, expect, test } from 'vitest';+import {+ isSyncMode,+ modeFromCommittedDefault,+ modeFromLegacyEnabled,+ resolveEffectiveAutoSyncMode,+ resolveLocalAutoSyncMode,+ SYNC_MODE_CHANGE_SOURCES,+ SYNC_MODES,+} from './auto-sync-mode.ts';++describe('isSyncMode', () => {+ test('accepts the three modes and nothing else', () => {+ expect(SYNC_MODES).toEqual(['off', 'follow', 'full']);+ for (const mode of SYNC_MODES) expect(isSyncMode(mode)).toBe(true);+ for (const other of ['on', 'sideways', '', 'FULL', null, undefined, true, 1]) {+ expect(isSyncMode(other)).toBe(false);+ }+ });+});++describe('SYNC_MODE_CHANGE_SOURCES', () => {+ test('is the bounded telemetry vocabulary and nothing else', () => {+ expect(SYNC_MODE_CHANGE_SOURCES).toEqual(['config', 'committed-default', 'worktree-inherit']);+ });+});++describe('modeFromLegacyEnabled', () => {+ test('true derives to full (bidirectional sync)', () => {+ expect(modeFromLegacyEnabled(true)).toBe('full');+ });++ test('false derives to off', () => {+ expect(modeFromLegacyEnabled(false)).toBe('off');+ });++ test('null/undefined stays unanswered (never asked)', () => {+ expect(modeFromLegacyEnabled(null)).toBeNull();+ expect(modeFromLegacyEnabled(undefined)).toBeNull();+ });+});++describe('modeFromCommittedDefault', () => {+ test('accepts the widened mode strings verbatim', () => {+ expect(modeFromCommittedDefault('off')).toBe('off');+ expect(modeFromCommittedDefault('follow')).toBe('follow');+ // Legacy alias: a committed 'pull' resolves to 'follow'.+ expect(modeFromCommittedDefault('pull')).toBe('follow');+ expect(modeFromCommittedDefault('full')).toBe('full');+ });++ test('translates the legacy boolean seed', () => {+ expect(modeFromCommittedDefault(true)).toBe('full');+ expect(modeFromCommittedDefault(false)).toBe('off');+ });++ test('null/undefined means no committed default', () => {+ expect(modeFromCommittedDefault(null)).toBeNull();+ expect(modeFromCommittedDefault(undefined)).toBeNull();+ });+});++describe('resolveLocalAutoSyncMode', () => {+ test('an explicit mode wins over the legacy enabled boolean', () => {+ expect(resolveLocalAutoSyncMode({ mode: 'follow', enabled: true })).toBe('follow');+ // Legacy alias: a stored 'pull' resolves to 'follow'.+ expect(resolveLocalAutoSyncMode({ mode: 'pull', enabled: true })).toBe('follow');+ expect(resolveLocalAutoSyncMode({ mode: 'off', enabled: true })).toBe('off');+ });++ test('with no mode key, derives from the legacy enabled boolean', () => {+ expect(resolveLocalAutoSyncMode({ enabled: true })).toBe('full');+ expect(resolveLocalAutoSyncMode({ enabled: false })).toBe('off');+ });++ test('a null mode falls through to the legacy derive (mode absent === unanswered)', () => {+ expect(resolveLocalAutoSyncMode({ mode: null, enabled: true })).toBe('full');+ });++ test('both absent, and a fully absent object, are unanswered', () => {+ expect(resolveLocalAutoSyncMode({ mode: null, enabled: null })).toBeNull();+ expect(resolveLocalAutoSyncMode({})).toBeNull();+ expect(resolveLocalAutoSyncMode(undefined)).toBeNull();+ });+});++describe('resolveEffectiveAutoSyncMode', () => {+ test('a non-null per-machine choice wins over the committed default', () => {+ expect(resolveEffectiveAutoSyncMode({ local: { mode: 'off' }, committedDefault: 'full' })).toBe(+ 'off',+ );+ expect(+ resolveEffectiveAutoSyncMode({ local: { enabled: false }, committedDefault: true }),+ ).toBe('off');+ });++ test('unanswered locally falls back to the committed default', () => {+ expect(+ resolveEffectiveAutoSyncMode({+ local: { mode: null, enabled: null },+ committedDefault: 'follow',+ }),+ ).toBe('follow');+ expect(resolveEffectiveAutoSyncMode({ local: undefined, committedDefault: true })).toBe('full');+ });++ test('unanswered everywhere resolves to null (onboarding prompts)', () => {+ expect(resolveEffectiveAutoSyncMode({ local: {}, committedDefault: null })).toBeNull();+ expect(+ resolveEffectiveAutoSyncMode({ local: undefined, committedDefault: undefined }),+ ).toBeNull();+ });++ test('legacy-only config round-trips to the pre-mode behavior', () => {+ // enabled:true → full (sync on); enabled:false → off; committed default:true seeds full.+ expect(resolveEffectiveAutoSyncMode({ local: { enabled: true }, committedDefault: null })).toBe(+ 'full',+ );+ expect(+ resolveEffectiveAutoSyncMode({ local: { enabled: false }, committedDefault: null }),+ ).toBe('off');+ expect(resolveEffectiveAutoSyncMode({ local: {}, committedDefault: true })).toBe('full');+ });+});diff --git a/packages/core/src/config/auto-sync-mode.ts b/packages/core/src/config/auto-sync-mode.tsnew file mode 100644index 000000000..02e9d853c--- /dev/null+++ b/packages/core/src/config/auto-sync-mode.ts@@ -0,0 +1,176 @@+/**+ * Sync-mode vocabulary and the rules that turn stored config into an effective+ * mode.+ *+ * `autoSync.mode` is the canonical per-project sync knob: `off` (no sync),+ * `follow` (one-directional — fetch and fast-forward, never push), `full`+ * (bidirectional). It is the single source of truth for "should this project+ * push?" — only `full` pushes — so no reader can misread a follow-only+ * project's consent as push permission.+ *+ * The follow mode was briefly stored as `'pull'` (after the git operation it+ * runs). That value is accepted as a permanent alias for `'follow'` — see+ * `LEGACY_FOLLOW_MODE` and `normalizeStoredMode` — so any config already on disk+ * keeps resolving correctly with no migration step. `mode` also supersedes the+ * even-older `autoSync.enabled` boolean (read via `modeFromLegacyEnabled`).+ * `null` means "never asked" (the onboarding prompt still fires).+ */++export const SYNC_MODES = ['off', 'follow', 'full'] as const;+export type SyncMode = (typeof SYNC_MODES)[number];++/** The two modes that actually sync — `off` is the paused/never state. */+export const SYNC_ACTIVE_MODES = ['follow', 'full'] as const;+export type SyncActiveMode = (typeof SYNC_ACTIVE_MODES)[number];++/** Legacy stored value for `follow` (the git op it runs), accepted permanently. */+const LEGACY_FOLLOW_MODE = 'pull';++/**+ * Mode values a stored config may legally carry — the canonical vocabulary plus+ * the legacy `'pull'` alias. Config schemas validate against this (so an+ * on-disk `'pull'` parses); readers normalize via {@link normalizeStoredMode}.+ */+export const STORED_SYNC_MODES = ['off', 'follow', 'full', LEGACY_FOLLOW_MODE] as const;+/** Active-mode stored values, including the legacy `'pull'` alias for `follow`. */+export const STORED_SYNC_ACTIVE_MODES = ['follow', 'full', LEGACY_FOLLOW_MODE] as const;++/** Normalize a stored `mode` value, mapping the legacy `'pull'` alias to `'follow'`. */+export function normalizeStoredMode(value: unknown): SyncMode | null {+ if (value === LEGACY_FOLLOW_MODE) return 'follow';+ return isSyncMode(value) ? value : null;+}++export function isSyncMode(value: unknown): value is SyncMode {+ return typeof value === 'string' && (SYNC_MODES as readonly string[]).includes(value);+}++export function isSyncActiveMode(value: unknown): value is SyncActiveMode {+ return typeof value === 'string' && (SYNC_ACTIVE_MODES as readonly string[]).includes(value);+}++/** A stored `mode` value: canonical, or the legacy `'pull'` alias for `follow`. */+export type StoredSyncMode = (typeof STORED_SYNC_MODES)[number];+/** A stored active-mode value, including the legacy `'pull'` alias. */+export type StoredSyncActiveMode = (typeof STORED_SYNC_ACTIVE_MODES)[number];++/** The autoSync shape the pause/resume helpers read (per-machine layer). */+type LocalAutoSync = {+ mode?: StoredSyncMode | null;+ enabled?: boolean | null;+ resumeMode?: StoredSyncActiveMode | null;+};++/**+ * The mode a paused project resumes into. `resumeMode` is per-machine UI memory+ * written only when sync is paused (mode `off`) after having been enabled, so an+ * older app that predates the key still reads `mode: 'off'` and never syncs or+ * pushes. It is meaningful only while `mode` is `off`; ignored otherwise.+ */+export function resumeModeOf(autoSync: LocalAutoSync | undefined): SyncActiveMode | null {+ const resume = autoSync?.resumeMode;+ if (resume === LEGACY_FOLLOW_MODE) return 'follow';+ return isSyncActiveMode(resume) ? resume : null;+}++/**+ * True when this machine turned sync off after having enabled it — the "paused"+ * state (distinct from a never-answered or explicitly-off project). Signalled by+ * `mode: 'off'` together with a remembered `resumeMode`.+ */+export function isSyncPaused(autoSync: LocalAutoSync | undefined): boolean {+ return resolveLocalAutoSyncMode(autoSync) === 'off' && resumeModeOf(autoSync) !== null;+}++/**+ * True when this machine has ever enabled sync for this project — either sync is+ * currently active, or it is paused (was enabled, now off). Drives whether the+ * manual "Sync" action is offered.+ */+export function hasEverEnabledSync(autoSync: LocalAutoSync | undefined): boolean {+ const mode = resolveLocalAutoSyncMode(autoSync);+ return mode === 'follow' || mode === 'full' || isSyncPaused(autoSync);+}++/**+ * The active-mode value a Full/Follow control should display: the live mode when+ * sync is active, otherwise the remembered resume mode (defaulting to `full`).+ */+export function displayActiveMode(autoSync: LocalAutoSync | undefined): SyncActiveMode {+ const mode = resolveLocalAutoSyncMode(autoSync);+ if (isSyncActiveMode(mode)) return mode;+ return resumeModeOf(autoSync) ?? 'full';+}++/**+ * Translate the legacy `autoSync.enabled` boolean into a mode: `true` was+ * bidirectional sync, `false` was off. `null`/absent stays the "never asked"+ * sentinel.+ */+export function modeFromLegacyEnabled(enabled: boolean | null | undefined): SyncMode | null {+ if (enabled === true) return 'full';+ if (enabled === false) return 'off';+ return null;+}++/**+ * Resolve the committed `autoSync.default` seed. It accepts both the widened+ * mode strings and the legacy boolean seed (`true`→full, `false`→off);+ * `null`/absent means no committed default.+ */+export function modeFromCommittedDefault(+ value: boolean | StoredSyncMode | null | undefined,+): SyncMode | null {+ if (value === true) return 'full';+ if (value === false) return 'off';+ return normalizeStoredMode(value);+}++/**+ * The per-machine mode for one project: an explicit `mode` wins; with no `mode`+ * key the legacy `enabled` boolean is derived. `null` means this machine has not+ * answered.+ */+export function resolveLocalAutoSyncMode(+ autoSync: { mode?: StoredSyncMode | null; enabled?: boolean | null } | undefined,+): SyncMode | null {+ const mode = normalizeStoredMode(autoSync?.mode);+ if (mode !== null) return mode;+ return modeFromLegacyEnabled(autoSync?.enabled);+}++/**+ * Effective mode across the two config layers, mirroring the existing+ * `enabled`/`default` precedence: a non-null per-machine choice wins, else the+ * committed project default, else `null` (never asked → prompt).+ */+export function resolveEffectiveAutoSyncMode(input: {+ local: { mode?: StoredSyncMode | null; enabled?: boolean | null } | undefined;+ committedDefault: boolean | StoredSyncMode | null | undefined;+}): SyncMode | null {+ const localMode = resolveLocalAutoSyncMode(input.local);+ if (localMode !== null) return localMode;+ return modeFromCommittedDefault(input.committedDefault);+}++/**+ * Bounded vocabulary for the origin of a sync-mode change, used as a telemetry+ * label. Kept small on purpose — it feeds structured logs, so the value set+ * must never grow unbounded.+ *+ * The user-facing surfaces that enable a mode (a first-open prompt, the+ * Settings control, the paused-notice switch action) all write the same+ * per-machine `autoSync.mode`, so the server cannot tell them apart from the+ * config alone — they collapse to `config`. The two origins the server (or+ * desktop) can attribute distinctly get their own value:+ * - `committed-default` — resolved from a maintainer's committed+ * `autoSync.default` seed rather than a per-machine choice.+ * - `worktree-inherit` — seeded into a new worktree from its parent's mode+ * (attributed at the desktop seed site, which knows the origin).+ */+export const SYNC_MODE_CHANGE_SOURCES = [+ 'config',+ 'committed-default',+ 'worktree-inherit',+] as const;+export type SyncModeChangeSource = (typeof SYNC_MODE_CHANGE_SOURCES)[number];diff --git a/packages/core/src/config/field-registry.test.ts b/packages/core/src/config/field-registry.test.tsindex 96dbf267b..b5e2280fa 100644--- a/packages/core/src/config/field-registry.test.ts+++ b/packages/core/src/config/field-registry.test.ts@@ -167,11 +167,12 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'});test('project-strict fields cover autoSync.default + content.* + contentRules.* + telemetry.localSink.*', () => {- // `autoSync.default` is the committed seed for a machine's- // `autoSync.enabled` on first open (true/false/null). Project scope is the- // whole point — it travels with the repo so a maintainer pre-answers the- // onboarding prompt for everyone. Its sibling `autoSync.enabled` stays- // project-local (per-machine) so the two never collide on scope.+ // `autoSync.default` is the committed seed for a machine's sync mode on+ // first open ('off'/'pull'/'full', or the legacy boolean, or null). Project+ // scope is the whole point — it travels with the repo so a maintainer+ // pre-answers the onboarding prompt for everyone. Its per-machine siblings+ // `autoSync.mode`/`autoSync.enabled` stay project-local so scopes never+ // collide.//// `content.dir` names the root of this project's knowledge graph — it is// project-shared (committed `config.yml`), so a user-global override@@ -213,11 +214,12 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)']);});- test('project-local-strict fields cover autoSync.enabled + appearance.sidebar.* + linkPreviews.enabled + search.semantic.* + terminal.enabled', () => {+ test('project-local-strict fields cover autoSync.mode + autoSync.enabled + appearance.sidebar.* + linkPreviews.enabled + search.semantic.* + terminal.enabled', () => {// Project-local fields are per-machine, per-project: each teammate's// choice never crosses the git boundary.// `<projectDir>/.ok/local/config.yml` is gitignored and never mirrored- // to the public repo. `autoSync.enabled` controls per-machine sync;+ // to the public repo. `autoSync.mode` is the canonical per-machine sync+ // knob (its legacy sibling `autoSync.enabled` stays project-local too);// the `appearance.sidebar.*` toggles are per-machine view preferences// for what the file tree and sidebar show; `search.semantic.*` is the// per-machine opt-in for embeddings search — enabling it sends content to@@ -240,6 +242,8 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)''appearance.sidebar.showOnlyMarkdownFiles','appearance.sidebar.showSkillsSection','autoSync.enabled',+ 'autoSync.mode',+ 'autoSync.resumeMode','linkPreviews.enabled','search.semantic.baseUrl','search.semantic.dimensions',diff --git a/packages/core/src/config/merge-layered.test.ts b/packages/core/src/config/merge-layered.test.tsindex 798e1736e..428e3994f 100644--- a/packages/core/src/config/merge-layered.test.ts+++ b/packages/core/src/config/merge-layered.test.ts@@ -135,7 +135,7 @@ describe('mergeLayered — scope-aware leaf short-circuits', () => {// `??` treats null + undefined alike — null in project-local falls through// to project, mirroring the existing scope: 'project' (project ?? user)- // contract. This matches the server's readProjectAutoSyncEnabled which+ // contract. This matches the server's readProjectAutoSyncMode which// checks `!== null && !== undefined` before short-circuiting.const merged = mergeLayered(user, project, projectLocal);expect(merged.autoSync?.enabled).toBe(true);diff --git a/packages/core/src/config/schema-jsonschema.test.ts b/packages/core/src/config/schema-jsonschema.test.tsindex d27ed9b8b..308f56729 100644--- a/packages/core/src/config/schema-jsonschema.test.ts+++ b/packages/core/src/config/schema-jsonschema.test.ts@@ -101,6 +101,31 @@ const FIXTURES: Fixture[] = [input: { telemetry: { localSink: { attributeDenylist: [42] } } },shouldAccept: false,},+ {+ name: 'autoSync.mode=pull accepted',+ input: { autoSync: { mode: 'pull' } },+ shouldAccept: true,+ },+ {+ name: 'autoSync.mode=sideways rejected',+ input: { autoSync: { mode: 'sideways' } },+ shouldAccept: false,+ },+ {+ name: 'autoSync.default=full (mode string) accepted',+ input: { autoSync: { default: 'full' } },+ shouldAccept: true,+ },+ {+ name: 'autoSync.default=true (legacy boolean seed) accepted',+ input: { autoSync: { default: true } },+ shouldAccept: true,+ },+ {+ name: 'autoSync.default=3 (outside boolean|mode union) rejected',+ input: { autoSync: { default: 3 } },+ shouldAccept: false,+ },{name: 'unknown top-level key passes (looseObject)',input: { future_feature: { enabled: true } },diff --git a/packages/core/src/config/schema-leaf.test.ts b/packages/core/src/config/schema-leaf.test.tsindex 436d0db25..0b6d4c299 100644--- a/packages/core/src/config/schema-leaf.test.ts+++ b/packages/core/src/config/schema-leaf.test.ts@@ -69,6 +69,36 @@ describe('getLeafFieldMeta', () => {});});+ test('resolves metadata for the project-local autoSync.mode enum leaf (.register before wrappers)', () => {+ const meta = getLeafFieldMeta(ConfigSchema, ['autoSync', 'mode']);+ expect(meta).toEqual({+ scope: 'project-local',+ agentSettable: false,+ defaultScope: 'project-local',+ description: expect.any(String),+ });+ });++ test('resolves metadata for the legacy project-local autoSync.enabled leaf', () => {+ const meta = getLeafFieldMeta(ConfigSchema, ['autoSync', 'enabled']);+ expect(meta).toEqual({+ scope: 'project-local',+ agentSettable: false,+ defaultScope: 'project-local',+ description: expect.any(String),+ });+ });++ test('resolves metadata for the committed autoSync.default union leaf (.register before wrappers)', () => {+ const meta = getLeafFieldMeta(ConfigSchema, ['autoSync', 'default']);+ expect(meta).toEqual({+ scope: 'project',+ agentSettable: false,+ defaultScope: 'project',+ description: expect.any(String),+ });+ });+test('returns undefined for an unresolved path', () => {const meta = getLeafFieldMeta(ConfigSchema, ['content', 'nonexistent']);expect(meta).toBeUndefined();diff --git a/packages/core/src/config/schema.test.ts b/packages/core/src/config/schema.test.tsindex 2aa475a03..d62635cea 100644--- a/packages/core/src/config/schema.test.ts+++ b/packages/core/src/config/schema.test.ts@@ -1,4 +1,5 @@import { describe, expect, test } from 'vitest';+import { z } from 'zod';import {ConfigSchema,checkEmbeddingsBaseUrl,@@ -215,3 +216,124 @@ describe('contentRules forward compatibility', () => {expect(parsed.contentRules.markdownlint).toEqual({ enabled: false });});});++describe('autoSync.mode (canonical per-machine sync knob)', () => {+ test('defaults to null (unanswered) when the whole block is absent', () => {+ expect(ConfigSchema.parse({}).autoSync).toEqual({ mode: null, enabled: null, default: null });+ });++ test('accepts each sync mode', () => {+ for (const mode of ['off', 'pull', 'full'] as const) {+ expect(ConfigSchema.parse({ autoSync: { mode } }).autoSync.mode).toBe(mode);+ }+ });++ test('accepts an explicit null', () => {+ expect(ConfigSchema.parse({ autoSync: { mode: null } }).autoSync.mode).toBeNull();+ });++ test('rejects a value outside the mode vocabulary', () => {+ expect(ConfigSchema.safeParse({ autoSync: { mode: 'sideways' } }).success).toBe(false);+ expect(ConfigSchema.safeParse({ autoSync: { mode: true } }).success).toBe(false);+ });++ test('the legacy enabled boolean still parses (derived to a mode only at read time)', () => {+ expect(ConfigSchema.parse({ autoSync: { enabled: true } }).autoSync.enabled).toBe(true);+ expect(ConfigSchema.parse({ autoSync: { enabled: false } }).autoSync.enabled).toBe(false);+ expect(ConfigSchema.parse({ autoSync: { enabled: null } }).autoSync.enabled).toBeNull();+ });+});++describe('autoSync.default (committed seed widened to the mode vocabulary)', () => {+ test('accepts the mode strings', () => {+ for (const mode of ['off', 'pull', 'full'] as const) {+ expect(ConfigSchema.parse({ autoSync: { default: mode } }).autoSync.default).toBe(mode);+ }+ });++ test('still accepts the legacy boolean seed', () => {+ expect(ConfigSchema.parse({ autoSync: { default: true } }).autoSync.default).toBe(true);+ expect(ConfigSchema.parse({ autoSync: { default: false } }).autoSync.default).toBe(false);+ });++ test('accepts an explicit null (ask)', () => {+ expect(ConfigSchema.parse({ autoSync: { default: null } }).autoSync.default).toBeNull();+ });++ test('rejects a value outside the boolean|mode union', () => {+ expect(ConfigSchema.safeParse({ autoSync: { default: 'sideways' } }).success).toBe(false);+ expect(ConfigSchema.safeParse({ autoSync: { default: 3 } }).success).toBe(false);+ });+});++describe('autoSync forward/backward compatibility (looseObject round-trip)', () => {+ test('unknown autoSync sub-keys survive parse instead of being stripped', () => {+ const parsed = ConfigSchema.parse({+ autoSync: { mode: 'pull', onboardingResolvedAt: '2026-01-01', inheritedFrom: 'root' },+ });+ expect(parsed.autoSync.mode).toBe('pull');+ // looseObject retains keys the schema doesn't model (worktree-inherit flags,+ // legacy onboarding stamps) so they round-trip on write-back.+ expect((parsed.autoSync as Record<string, unknown>).onboardingResolvedAt).toBe('2026-01-01');+ expect((parsed.autoSync as Record<string, unknown>).inheritedFrom).toBe('root');+ });++ test('an older mode-unaware schema reads a mode-only config as sync-off, never pushing', () => {+ // A newer OK can write autoSync.mode into a config an older OK never learned+ // about. The old schema (mode-unaware, enabled-only) must read that config as+ // UNANSWERED and never silently enable push. Snapshot the pre-change schema ++ // boot resolution so the guarantee is pinned even after the real schema moves.+ const legacyAutoSync = z+ .looseObject({+ enabled: z.boolean().nullable().default(null),+ default: z.boolean().nullable().default(null),+ })+ .default({ enabled: null, default: null });+ const legacySchema = z.looseObject({ autoSync: legacyAutoSync });++ const parsed = legacySchema.parse({ autoSync: { mode: 'pull' } });+ // The mode key is preserved (looseObject) but invisible to the old schema.+ expect((parsed.autoSync as Record<string, unknown>).mode).toBe('pull');+ expect(parsed.autoSync.enabled).toBeNull();+ expect(parsed.autoSync.default).toBeNull();++ // Pre-change boot resolution: per-machine enabled wins, else committed+ // default === true. With both null, sync is OFF and the engine never pushes.+ const legacyBootResolvesEnabled =+ parsed.autoSync.enabled !== null && parsed.autoSync.enabled !== undefined+ ? parsed.autoSync.enabled === true+ : parsed.autoSync.default === true;+ expect(legacyBootResolvesEnabled).toBe(false);+ });++ test('a committed default:"pull" fails an older schema wholesale — the accepted skew cost', () => {+ // `autoSync.mode` and `autoSync.default` have OPPOSITE forward-compat+ // profiles. `mode` is a NEW key an old looseObject passes through silently;+ // `default` is a KNOWN, type-checked leaf (boolean-only in the old schema),+ // so a committed default:'pull' is rejected — and because it's a leaf of the+ // whole config, that failure fails the ENTIRE parse, so a mode-unaware app+ // boots on schema defaults for that file. This whole-config reset is the+ // deliberately-accepted cost of the single-knob config design: the+ // no-silent-push guarantee still holds (the fallback default is null → off),+ // and the residual is that a skewed collaborator falls back to defaults+ // until they update. Pin the asymmetry so the two keys stay documented.+ const legacyAutoSync = z+ .looseObject({+ enabled: z.boolean().nullable().default(null),+ default: z.boolean().nullable().default(null),+ })+ .default({ enabled: null, default: null });+ const legacySchema = z.looseObject({ autoSync: legacyAutoSync });++ // The new `mode` key parses cleanly via looseObject (invisible to the old+ // schema)...+ expect(legacySchema.safeParse({ autoSync: { mode: 'pull' } }).success).toBe(true);+ // ...but a committed `default: 'pull'` is rejected, failing the whole parse.+ expect(legacySchema.safeParse({ autoSync: { default: 'pull' } }).success).toBe(false);++ // The all-defaults fallback a rejecting app boots on has `default: null`, so+ // boot resolution is OFF — no silent push on the skewed version.+ const legacyDefaults = legacySchema.parse({});+ expect(legacyDefaults.autoSync.default).toBeNull();+ });+});diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.tsindex ed44d0f7f..d941450b0 100644--- a/packages/core/src/config/schema.ts+++ b/packages/core/src/config/schema.ts@@ -2,6 +2,7 @@ import { z } from 'zod';import { DEFAULT_ATTACHMENT_FOLDER_PATH } from '../constants/upload.ts';import { DEFAULT_LINKS_VALIDATION, LINKS_VALIDATION_SETTINGS } from '../markdown/lint/types.ts';import { THEME_PLUGIN_IDS } from '../theme/theme-plugins.ts';+import { STORED_SYNC_ACTIVE_MODES, STORED_SYNC_MODES } from './auto-sync-mode.ts';import { fieldRegistry } from './field-registry.ts';// Credential attribute key denylist for the local telemetry file sink. The@@ -388,22 +389,41 @@ export const ConfigSchema = z.looseObject({.default(true),}).default({ autoApproveOkTools: true }),- // `autoSync.enabled` is a per-machine, per-project preference: each- // teammate decides independently whether their machine should auto-pull /- // auto-push commits for *this* project. Project scope would bleed across- // teammates via git; user scope would force one global toggle for every- // OK project. The new `'project-local'` layer at- // `<projectDir>/.ok/local/config.yml` (gitignored) is the only correct- // home. SettingsPane SyncSection, the SyncStatusBadge popover Switch, and- // the AutoSyncOnboardingDialog all write here via the project-local- // binding — no special HTTP endpoint.+ // `autoSync.mode` is a per-machine, per-project preference: each teammate+ // decides independently whether their machine syncs *this* project, and in+ // which direction. Project scope would bleed across teammates via git; user+ // scope would force one global choice for every OK project. The+ // `'project-local'` layer at `<projectDir>/.ok/local/config.yml` (gitignored)+ // is the only correct home. SettingsPane SyncSection, the SyncStatusBadge+ // popover, and the AutoSyncOnboardingDialog all write here via the+ // project-local binding — no special HTTP endpoint.//- // `null` is the canonical "unanswered" sentinel: the onboarding modal- // gates on `enabled === null`, distinguishing "user has not chosen" from- // `true` / `false` (chosen). `looseObject` is retained so legacy- // `onboardingResolvedAt` keys still on disk parse without error.+ // `mode` is the single knob the engine reads to decide whether to push: only+ // `'full'` pushes, so a `'pull'` follower can never be mistaken for a pusher.+ // It supersedes the legacy `enabled` boolean, which stays readable for configs+ // written before `mode` existed — `resolveLocalAutoSyncMode` derives a mode+ // from `enabled` when no `mode` key is present, so the two shapes coexist with+ // no migration.+ //+ // `null` is the canonical "unanswered" sentinel: the onboarding modal gates on+ // the resolved mode being `null`, distinguishing "user has not chosen" from a+ // chosen mode. `looseObject` is retained so legacy keys (e.g.+ // `onboardingResolvedAt`) and a newer version's extra keys still round-trip.autoSync: z.looseObject({+ mode: z+ .enum(STORED_SYNC_MODES)+ .register(fieldRegistry, {+ scope: 'project-local',+ agentSettable: false,+ defaultScope: 'project-local',+ description:+ "How this machine syncs this project with its git remote: 'off' (no sync), 'follow' (one-directional — pull remote changes, never push your own; 'pull' is accepted as a legacy alias), or 'full' (bidirectional pull and push). null = not chosen yet (onboarding asks). Per-machine (project-local) — not shared. Supersedes the legacy autoSync.enabled boolean.",+ })+ .nullable()+ .default(null),+ // Legacy per-machine toggle, superseded by `autoSync.mode`. Read only when+ // `mode` is absent (`true` → full, `false` → off); new writes set `mode`.enabled: z.boolean().register(fieldRegistry, {@@ -411,33 +431,48 @@ export const ConfigSchema = z.looseObject({agentSettable: false,defaultScope: 'project-local',description:- 'Whether this machine auto-pulls and auto-pushes git commits for this project. null = not chosen yet (onboarding asks). Per-machine (project-local) — not shared.',+ 'Legacy per-machine sync toggle, superseded by autoSync.mode. Read only when mode is absent (true = full, false = off). null = not chosen yet. Per-machine (project-local) — not shared.',}).nullable().default(null),- // `autoSync.default` is the COMMITTED (project-scope) seed for a- // machine's `autoSync.enabled` on first open: `true` = default auto-sync- // on, `false` = default off, `null` = ask (show the onboarding modal). It- // travels with the repo via git so a maintainer can pre-answer the prompt- // for everyone who clones the project. It is a soft default — a- // per-machine `autoSync.enabled` (above) always overrides it, in both the- // server's `readProjectAutoSyncEnabled` resolution and the onboarding- // gate. Sharing `enabled`'s `boolean | null` value space is deliberate:- // `null` reuses the same "unanswered → ask" sentinel; the only difference- // between the two leaves is scope (committed vs per-machine).+ // `autoSync.resumeMode` is per-machine UI memory: when sync is paused+ // (`mode: 'off'`) after having been enabled, it records which active mode+ // to resume into (and doubles as the "was enabled, now paused" signal that+ // keeps the badge visible and the manual Sync action available). Storing+ // paused as `mode: 'off'` keeps an older app — which ignores this key —+ // reading the project as not-syncing, so pausing never lets a stale reader+ // push. Meaningful only while `mode` is `off`; ignored otherwise.+ resumeMode: z+ .enum(STORED_SYNC_ACTIVE_MODES)+ .register(fieldRegistry, {+ scope: 'project-local',+ agentSettable: false,+ defaultScope: 'project-local',+ description:+ "When sync is paused (autoSync.mode 'off') after having been enabled, the active mode to resume into ('follow' | 'full'). Per-machine UI memory; ignored while a mode is active. Not shared.",+ })+ .optional(),+ // `autoSync.default` is the COMMITTED (project-scope) seed for a machine's+ // sync mode on first open. It travels with the repo via git so a+ // maintainer can pre-answer the prompt for everyone who clones the+ // project. It is a soft default — a per-machine choice always overrides+ // it, in both the server's `readProjectAutoSyncMode` resolution and the+ // onboarding gate. The value space is the mode vocabulary plus the legacy+ // boolean seed (`true` → full, `false` → off) so committed `default: true`+ // configs keep working; `null` reuses the "unanswered → ask" sentinel.default: z- .boolean()+ .union([z.boolean(), z.enum(STORED_SYNC_MODES)]).register(fieldRegistry, {scope: 'project',agentSettable: false,defaultScope: 'project',description:- "Committed project default for a machine's autoSync.enabled on first open: true = auto-sync on, false = off, null = ask (show the onboarding prompt). Shared via git. A per-machine autoSync.enabled choice overrides it.",+ "Committed project default for a machine's sync mode on first open: 'off' | 'follow' | 'full', or the legacy boolean (true = full, false = off). null = ask (show the onboarding prompt). Shared via git. A per-machine autoSync.mode choice overrides it.",}).nullable().default(null),})- .default({ enabled: null, default: null }),+ .default({ mode: null, enabled: null, default: null }),// `terminal.enabled` is the per-project, per-machine opt-out for the in-app// terminal's real OS shell. The terminal is available by default; only an// explicit `false` disables it (`null`/absent both read as the default-ondiff --git a/packages/core/src/config/write-config-patch.test.ts b/packages/core/src/config/write-config-patch.test.tsindex 2e8cbbc77..9a2e0674a 100644--- a/packages/core/src/config/write-config-patch.test.ts+++ b/packages/core/src/config/write-config-patch.test.ts@@ -190,6 +190,34 @@ describe('writeConfigPatch — project-local scope', () => {expect(after).not.toContain('enabled: false');});+ test('preserves unknown autoSync sub-keys on a mode write-back (looseObject round-trip)', async () => {+ // A newer version's extra autoSync keys (worktree-inheritance flags, legacy+ // onboarding stamps) must survive a surgical patch to a sibling field rather+ // than being stripped — the surgical yaml write touches only the patched path.+ mkdirSync(join(testDir, '.ok', 'local'), { recursive: true });+ writeFileSync(+ projectLocalConfigPath(),+ 'autoSync:\n mode: pull\n inheritedFrom: root\n inheritedNoticePending: true\n',+ 'utf-8',+ );++ const result = await writeConfigPatch({+ cwd: testDir,+ scope: 'project-local',+ patch: { autoSync: { mode: 'off' } },+ });+ expect(result.ok).toBe(true);+ if (!result.ok) throw new Error('expected success');+ expect(result.appliedPaths).toContain('autoSync.mode');++ const onDisk = readFileSync(projectLocalConfigPath(), 'utf-8');+ expect(onDisk).toContain('mode: off');+ expect(onDisk).not.toContain('mode: pull');+ // Sibling keys the schema does not model round-trip verbatim.+ expect(onDisk).toContain('inheritedFrom: root');+ expect(onDisk).toContain('inheritedNoticePending: true');+ });+test('does NOT touch the project file at <cwd>/.ok/config.yml', async () => {// Per-machine scope is opaque to the committed project layer. A patch at// project-local must never write into the sibling project file.diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 8ab50c02e..84cd906dc 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -80,6 +80,30 @@ export {type MenuPlatform,type MenuSection,} from './commands/command-identity.ts';+// Sync-mode vocabulary + resolution rules (off/follow/full). Browser+node compatible.+export {+ displayActiveMode,+ hasEverEnabledSync,+ isSyncActiveMode,+ isSyncMode,+ isSyncPaused,+ modeFromCommittedDefault,+ modeFromLegacyEnabled,+ normalizeStoredMode,+ resolveEffectiveAutoSyncMode,+ resolveLocalAutoSyncMode,+ resumeModeOf,+ STORED_SYNC_ACTIVE_MODES,+ STORED_SYNC_MODES,+ type StoredSyncActiveMode,+ type StoredSyncMode,+ SYNC_ACTIVE_MODES,+ SYNC_MODE_CHANGE_SOURCES,+ SYNC_MODES,+ type SyncActiveMode,+ type SyncMode,+ type SyncModeChangeSource,+} from './config/auto-sync-mode.ts';// Headless config writers + UI ConfigBinding.// Browser+node compatible — no Node deps; structural ConfigDocProvider type// keeps `@hocuspocus/provider` out of core's runtime deps.@@ -803,6 +827,9 @@ export {ProblemDetailsSchema,type ProblemType,ProblemTypeSchema,+ PULL_OUTCOMES,+ type PullOutcome,+ PullOutcomeSchema,PushPermissionSchema,type PushPermissionWire,type RenamedAssetMapping,@@ -976,6 +1003,8 @@ export {SyncConflictsSuccessSchema,type SyncErrorCode,SyncErrorCodeSchema,+ SyncModeSchema,+ type SyncModeWire,SyncRemoteSchema,type SyncRemoteWire,type SyncResolveConflictRequest,@@ -1212,6 +1241,7 @@ export {type ToleranceFireRecord,type ToleranceTelemetryHook,toBridgeInvariantLog,+ tryLineLevelCombine,} from './bridge/index.ts';// Two-phase shutdown timing constants — shared by the CLI's idle-shutdown// UI-sibling termination and the desktop's `stopAllOwnedServers` auto-diff --git a/packages/core/src/schemas/api/sync-seed.test.ts b/packages/core/src/schemas/api/sync-seed.test.tsindex e9b446dcc..f0a331ede 100644--- a/packages/core/src/schemas/api/sync-seed.test.ts+++ b/packages/core/src/schemas/api/sync-seed.test.ts@@ -3,12 +3,14 @@ import {ConflictEntrySchema,InstallSkillSuccessSchema,ProblemTypeSchema,+ PullOutcomeSchema,PushPermissionSchema,SeedApplyRequestSchema,SeedApplySuccessSchema,SeedPlanSuccessSchema,SyncConflictContentSuccessSchema,SyncConflictsSuccessSchema,+ SyncModeSchema,SyncRemoteSchema,SyncResolveConflictRequestSchema,SyncResolveConflictSuccessSchema,@@ -58,6 +60,34 @@ describe('SyncStateSchema', () => {});});+describe('SyncModeSchema', () => {+ test('accepts every documented mode', () => {+ for (const m of ['off', 'follow', 'full']) {+ expect(SyncModeSchema.safeParse(m).success).toBe(true);+ }+ });+ test('rejects unknown mode', () => {+ expect(SyncModeSchema.safeParse('bidirectional').success).toBe(false);+ // A boolean is not a mode — this is the field that replaced the legacy+ // `enabled` boolean on the wire.+ expect(SyncModeSchema.safeParse(true).success).toBe(false);+ });+});++describe('PullOutcomeSchema', () => {+ test('accepts every documented outcome', () => {+ for (const o of ['succeeded', 'up-to-date', 'conflict', 'refused', 'error']) {+ expect(PullOutcomeSchema.safeParse(o).success).toBe(true);+ }+ });+ test('rejects an unknown outcome', () => {+ // `error-class` (hyphenated) is the retired near-miss — the canonical value+ // is now `error`, so a producer emitting the old long form must fail here.+ expect(PullOutcomeSchema.safeParse('error-class').success).toBe(false);+ expect(PullOutcomeSchema.safeParse('pending').success).toBe(false);+ });+});+describe('SyncStatusSchema', () => {const validStatus = {state: 'idle' as const,@@ -122,6 +152,49 @@ describe('SyncStatusSchema', () => {}).success,).toBe(true);});+ test('accepts a populated syncMode', () => {+ for (const m of ['off', 'follow', 'full'] as const) {+ expect(SyncStatusSchema.safeParse({ ...validStatus, syncMode: m }).success).toBe(true);+ }+ });+ test('syncMode is additive: a status without it still parses', () => {+ // Optional for version-skew safety — a payload from an engine predating the+ // field must not fail validation on a newer client.+ expect('syncMode' in validStatus).toBe(false);+ expect(SyncStatusSchema.safeParse(validStatus).success).toBe(true);+ });+ test('rejects an invalid syncMode', () => {+ expect(SyncStatusSchema.safeParse({ ...validStatus, syncMode: 'sideways' }).success).toBe(+ false,+ );+ });+ test('accepts a populated lastPullUtc + lastPullOutcome', () => {+ expect(+ SyncStatusSchema.safeParse({+ ...validStatus,+ lastPullUtc: '2026-07-22T04:00:00.000Z',+ lastPullOutcome: 'succeeded',+ }).success,+ ).toBe(true);+ });+ test('lastPullUtc/lastPullOutcome are additive: a status without them still parses', () => {+ // Optional for version-skew safety — a payload from an engine predating the+ // one-shot-outcome contract must not fail validation on a newer client.+ expect('lastPullUtc' in validStatus).toBe(false);+ expect('lastPullOutcome' in validStatus).toBe(false);+ expect(SyncStatusSchema.safeParse(validStatus).success).toBe(true);+ });+ test('accepts null lastPullUtc/lastPullOutcome (no pull yet)', () => {+ expect(+ SyncStatusSchema.safeParse({ ...validStatus, lastPullUtc: null, lastPullOutcome: null })+ .success,+ ).toBe(true);+ });+ test('rejects an invalid lastPullOutcome', () => {+ expect(+ SyncStatusSchema.safeParse({ ...validStatus, lastPullOutcome: 'error-class' }).success,+ ).toBe(false);+ });});describe('PushPermissionSchema', () => {diff --git a/packages/core/src/schemas/api/sync-seed.ts b/packages/core/src/schemas/api/sync-seed.tsindex 4483d2dfd..821783bf4 100644--- a/packages/core/src/schemas/api/sync-seed.ts+++ b/packages/core/src/schemas/api/sync-seed.ts@@ -17,6 +17,7 @@import type { StandardSchemaV1 } from '@standard-schema/spec';import { z } from 'zod';+import { SYNC_MODES } from '../../config/auto-sync-mode.ts';/*** `SyncState` literal-union mirroring the in-process `SyncState` type from@@ -114,6 +115,34 @@ export const SYNC_ERROR_CODES = [export const SyncErrorCodeSchema = z.enum(SYNC_ERROR_CODES);export type SyncErrorCode = z.infer<typeof SyncErrorCodeSchema>;+/**+ * Project sync mode carried in the sync-status payload — mirrors the engine's+ * `SyncMode`. `off` = not syncing, `follow` = one-directional (fetch ++ * fast-forward, never push), `full` = bidirectional. Distinct from `syncEnabled`,+ * which is true for both `follow` and `full`: a consumer that must branch on push+ * capability reads `syncMode === 'full'`, not `syncEnabled`.+ */+export const SyncModeSchema = z.enum(SYNC_MODES) satisfies StandardSchemaV1;+export type SyncModeWire = z.infer<typeof SyncModeSchema>;++/**+ * Outcome of a completed pull cycle — the bounded value a downstream surface+ * reads to learn how a pull it triggered went. Written at every pull+ * completion (background and one-shot):+ *+ * - `succeeded` — fetched and advanced the branch to the remote tip.+ * - `up-to-date` — already at the tip; nothing to apply.+ * - `conflict` — a new same-line conflict surfaced and awaits resolution.+ * - `refused` — a state gate declined the pull without attempting it (a cycle+ * already in flight, an unresolved conflict holding the tree, detached HEAD,+ * no remote). Never a silent no-op — the refusal is recorded.+ * - `error` — the pull hit an error (offline, auth, unexpected git failure).+ * The direction's `pullError*` fields carry the detail.+ */+export const PULL_OUTCOMES = ['succeeded', 'up-to-date', 'conflict', 'refused', 'error'] as const;+export const PullOutcomeSchema = z.enum(PULL_OUTCOMES) satisfies StandardSchemaV1;+export type PullOutcome = z.infer<typeof PullOutcomeSchema>;+/*** Full sync engine status — emitted as the flat success body of* `GET /api/sync/status` AND as the nested `status` field of@@ -151,6 +180,23 @@ export const SyncStatusSchema = zpausedReason: z.string().optional(),/** Push-permission probe outcome. Absent when no probe has resolved yet. */pushPermission: PushPermissionSchema.optional(),+ /**+ * Project sync mode. Optional for version-skew safety — a status payload+ * from an engine that predates the mode field parses as absent; the current+ * engine always emits it. `syncEnabled` stays the boolean "is sync on at+ * all" (true for both `pull` and `full`).+ */+ syncMode: SyncModeSchema.optional(),+ /**+ * One-shot / background pull observability. Both additive + optional for+ * version skew (an engine predating the outcome contract omits them).+ * `lastPullUtc` bumps at EVERY pull completion so a consumer can detect a+ * fresh result by change; `lastPullOutcome` carries that pull's outcome.+ * Consumer contract: read-before-trigger, wait-for-change, give-up-timeout —+ * the changed timestamp reflects a pull that completed after the read.+ */+ lastPullUtc: z.string().nullable().optional(),+ lastPullOutcome: PullOutcomeSchema.nullable().optional(),}).loose() satisfies StandardSchemaV1;export type SyncStatusWire = z.infer<typeof SyncStatusSchema>;diff --git a/packages/desktop/src/main/worktree-autosync-inherit.test.ts b/packages/desktop/src/main/worktree-autosync-inherit.test.tsindex ef0d331c1..179ab9dfe 100644--- a/packages/desktop/src/main/worktree-autosync-inherit.test.ts+++ b/packages/desktop/src/main/worktree-autosync-inherit.test.ts@@ -2,9 +2,33 @@ import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'nodimport { tmpdir } from 'node:os';import { basename, join } from 'node:path';import { resolveConfigPath, writeConfigPatch } from '@inkeep/open-knowledge-core/server';-import { afterEach, describe, expect, test } from 'vitest';+import { afterEach, describe, expect, test, vi } from 'vitest';import { parse as parseYaml } from 'yaml';-import { resolveRootAutoSync, seedWorktreeAutoSync } from './worktree-autosync-inherit.ts';+import { getLogger } from './desktop-logger.ts';+import { resolveRootAutoSyncMode, seedWorktreeAutoSync } from './worktree-autosync-inherit.ts';++// Capture the seed site's structured telemetry without touching the real pino+// destination. `getLogger` caches by subsystem, so the spy intercepts the same+// instance the module resolves at call time.+function captureSeedLogs(): {+ entries: Array<{ data: Record<string, unknown>; msg: string }>;+ restore: () => void;+} {+ const entries: Array<{ data: Record<string, unknown>; msg: string }> = [];+ const logger = getLogger('worktree-autosync');+ const record = (data: Record<string, unknown>, msg: string): void => {+ entries.push({ data, msg });+ };+ const infoSpy = vi.spyOn(logger, 'info').mockImplementation(record);+ const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(record);+ return {+ entries,+ restore: () => {+ infoSpy.mockRestore();+ warnSpy.mockRestore();+ },+ };+}const dirs: string[] = [];function tmp(): string {@@ -17,53 +41,117 @@ afterEach(() => {dirs.length = 0;});-describe('resolveRootAutoSync', () => {- test('per-machine enabled wins over the committed default', async () => {+describe('resolveRootAutoSyncMode', () => {+ test('per-machine mode wins over the committed default', async () => {+ const root = tmp();+ await writeConfigPatch({+ cwd: root,+ scope: 'project-local',+ patch: { autoSync: { mode: 'pull' } },+ });+ await writeConfigPatch({+ cwd: root,+ scope: 'project',+ patch: { autoSync: { default: 'full' } },+ });+ expect(resolveRootAutoSyncMode(root)).toBe('follow');+ });++ test('derives the mode from a legacy per-machine enabled boolean', async () => {const root = tmp();await writeConfigPatch({cwd: root,scope: 'project-local',patch: { autoSync: { enabled: true } },});+ expect(resolveRootAutoSyncMode(root)).toBe('full');+ });++ test('falls back to a mode-valued committed default when per-machine is unset', async () => {+ const root = tmp();await writeConfigPatch({cwd: root,scope: 'project',- patch: { autoSync: { default: false } },+ patch: { autoSync: { default: 'pull' } },});- expect(resolveRootAutoSync(root)).toBe(true);+ expect(resolveRootAutoSyncMode(root)).toBe('follow');});- test('falls back to the committed default when per-machine is unset', async () => {+ test('falls back to a legacy boolean committed default', async () => {const root = tmp();await writeConfigPatch({ cwd: root, scope: 'project', patch: { autoSync: { default: true } } });- expect(resolveRootAutoSync(root)).toBe(true);+ expect(resolveRootAutoSyncMode(root)).toBe('full');});test('null when neither is answered', () => {- expect(resolveRootAutoSync(tmp())).toBeNull();+ expect(resolveRootAutoSyncMode(tmp())).toBeNull();});});describe('seedWorktreeAutoSync', () => {- test('seeds the worktree enabled + arms the one-time notice from the root setting', async () => {+ test('seeds the worktree mode + arms the one-time notice from the root setting', async () => {const root = tmp();const wt = tmp();await writeConfigPatch({cwd: root,scope: 'project-local',- patch: { autoSync: { enabled: false } },+ patch: { autoSync: { mode: 'pull' } },});await seedWorktreeAutoSync(wt, root);const parsed = parseYaml(readFileSync(resolveConfigPath('project-local', wt), 'utf-8'));- expect(parsed.autoSync.enabled).toBe(false);+ expect(parsed.autoSync.mode).toBe('follow');expect(parsed.autoSync.inheritedNoticePending).toBe(true);expect(parsed.autoSync.inheritedFrom).toBe(basename(root));});+ test('seeds from a committed default when per-machine is unset', async () => {+ const root = tmp();+ const wt = tmp();+ await writeConfigPatch({+ cwd: root,+ scope: 'project',+ patch: { autoSync: { default: 'full' } },+ });+ await seedWorktreeAutoSync(wt, root);+ const parsed = parseYaml(readFileSync(resolveConfigPath('project-local', wt), 'utf-8'));+ expect(parsed.autoSync.mode).toBe('full');+ });+test('no-op when the root is unanswered — the worktree prompts normally', async () => {const root = tmp();const wt = tmp();await seedWorktreeAutoSync(wt, root);expect(existsSync(resolveConfigPath('project-local', wt))).toBe(false);});++ test('logs the inherited mode with the worktree-inherit telemetry source', async () => {+ const root = tmp();+ const wt = tmp();+ await writeConfigPatch({+ cwd: root,+ scope: 'project-local',+ patch: { autoSync: { mode: 'pull' } },+ });+ const cap = captureSeedLogs();+ try {+ await seedWorktreeAutoSync(wt, root);+ const entry = cap.entries.find((e) => e.msg === 'seeded inherited autoSync mode');+ expect(entry).toBeDefined();+ expect(entry?.data).toEqual({ to: 'follow', source: 'worktree-inherit' });+ } finally {+ cap.restore();+ }+ });++ test('emits no seed telemetry when the root is unanswered', async () => {+ const root = tmp();+ const wt = tmp();+ const cap = captureSeedLogs();+ try {+ await seedWorktreeAutoSync(wt, root);+ expect(cap.entries.some((e) => e.msg === 'seeded inherited autoSync mode')).toBe(false);+ } finally {+ cap.restore();+ }+ });});diff --git a/packages/desktop/src/main/worktree-autosync-inherit.ts b/packages/desktop/src/main/worktree-autosync-inherit.tsindex 90a9e41b9..9d732a979 100644--- a/packages/desktop/src/main/worktree-autosync-inherit.ts+++ b/packages/desktop/src/main/worktree-autosync-inherit.ts@@ -1,30 +1,38 @@/**- * Seed a freshly-created worktree's per-machine git auto-sync choice from the- * root project's resolved setting, so opening a worktree doesn't re-ask the- * onboarding prompt for every branch (a worktree inherits the root's- * auto-sync on/off).+ * Seed a freshly-created worktree's per-machine git sync mode from the root+ * project's resolved setting, so opening a worktree doesn't re-ask the+ * onboarding prompt for every branch (a worktree inherits the root's sync+ * choice).*- * Two settings back auto-sync (`packages/core/src/config/schema.ts`):- * - `autoSync.enabled` — per-machine, project-local (`.ok/local/config.yml`,- * gitignored). The user's actual on/off choice. A new worktree is a new- * project dir, so this starts unset → the onboarding modal would fire again.+ * Two settings back sync (`packages/core/src/config/schema.ts`):+ * - `autoSync.mode` — per-machine, project-local (`.ok/local/config.yml`,+ * gitignored). This machine's actual off/pull/full choice (supersedes the+ * legacy `autoSync.enabled` boolean). A new worktree is a new project dir,+ * so this starts unset → the onboarding modal would fire again.* - `autoSync.default` — committed (`.ok/config.yml`, shared via git). A* worktree already inherits this from its branch.*- * We resolve the root's effective choice (per-machine `enabled`, else committed- * `default`) and, when it's a definite on/off, write it into the new worktree's- * project-local config. The onboarding gate then reads a non-null `enabled` and- * suppresses the prompt. When the root itself is unanswered we write nothing —- * the worktree prompts normally, exactly as the root would.+ * We resolve the root's effective mode (per-machine choice, else committed+ * default) and, when it's a definite off/pull/full, write it into the new+ * worktree's project-local config. The onboarding gate then reads a non-null+ * mode and suppresses the prompt. When the root itself is unanswered we write+ * nothing — the worktree prompts normally, exactly as the root would.** `inheritedNoticePending` is a loose key (the schema's `autoSync` is a* `looseObject`, so it round-trips without a schema change): the worktree window- * reads it to show a one-time "auto-sync is on/off, inherited from <project>"- * notice, then clears it.+ * reads it to show a one-time "sync is on/off, inherited from <project>" notice,+ * then clears it.*/import { existsSync, readFileSync } from 'node:fs';import { basename } from 'node:path';+import {+ normalizeStoredMode,+ resolveEffectiveAutoSyncMode,+ type StoredSyncMode,+ type SyncMode,+ type SyncModeChangeSource,+} from '@inkeep/open-knowledge-core';import { resolveConfigPath, writeConfigPatch } from '@inkeep/open-knowledge-core/server';import { parse as parseYaml } from 'yaml';import { getLogger } from './desktop-logger.ts';@@ -33,8 +41,8 @@ function isObject(v: unknown): v is Record<string, unknown> {return typeof v === 'object' && v !== null && !Array.isArray(v);}-/** Read one config file's `autoSync.<key>` boolean leaf; null if absent/other. */-function readAutoSyncBool(path: string, key: 'enabled' | 'default'): boolean | null {+/** Read one config file's `autoSync` node; null if absent/unparseable/other. */+function readAutoSyncNode(path: string): Record<string, unknown> | null {if (!existsSync(path)) return null;let parsed: unknown;try {@@ -43,38 +51,49 @@ function readAutoSyncBool(path: string, key: 'enabled' | 'default'): boolean | nreturn null;}if (!isObject(parsed)) return null;- const autoSync = parsed.autoSync;- if (!isObject(autoSync)) return null;- const value = autoSync[key];- return typeof value === 'boolean' ? value : null;+ return isObject(parsed.autoSync) ? parsed.autoSync : null;+}++function asBool(v: unknown): boolean | null {+ return typeof v === 'boolean' ? v : null;+}+function asModeOrBool(v: unknown): StoredSyncMode | boolean | null {+ // normalizeStoredMode accepts the legacy 'pull' alias for 'follow'; a boolean+ // stays a boolean (the even-older enabled-style seed).+ const mode = normalizeStoredMode(v);+ if (mode !== null) return mode;+ return typeof v === 'boolean' ? v : null;}/**- * The root project's resolved auto-sync choice: the per-machine- * `autoSync.enabled` if set, else the committed `autoSync.default`. `null` when- * neither is answered (→ the worktree should prompt normally).+ * The root project's resolved sync mode: the per-machine `autoSync.mode` (or the+ * legacy `enabled` boolean) if set, else the committed `autoSync.default`. `null`+ * when neither is answered (→ the worktree should prompt normally).*/-export function resolveRootAutoSync(mainRoot: string): boolean | null {- const enabled = readAutoSyncBool(resolveConfigPath('project-local', mainRoot), 'enabled');- if (enabled !== null) return enabled;- return readAutoSyncBool(resolveConfigPath('project', mainRoot), 'default');+export function resolveRootAutoSyncMode(mainRoot: string): SyncMode | null {+ const local = readAutoSyncNode(resolveConfigPath('project-local', mainRoot));+ const committed = readAutoSyncNode(resolveConfigPath('project', mainRoot));+ return resolveEffectiveAutoSyncMode({+ local: { mode: normalizeStoredMode(local?.mode), enabled: asBool(local?.enabled) },+ committedDefault: asModeOrBool(committed?.default),+ });}/**- * Seed the new worktree's per-machine `autoSync.enabled` from the root's- * resolved choice + arm the one-time inherited notice. No-op when the root is- * unanswered. Best-effort: a write failure is logged, never thrown (the worktree- * already exists — a missing seed just falls back to the normal prompt).+ * Seed the new worktree's per-machine `autoSync.mode` from the root's resolved+ * choice + arm the one-time inherited notice. No-op when the root is unanswered.+ * Best-effort: a write failure is logged, never thrown (the worktree already+ * exists — a missing seed just falls back to the normal prompt).*/export async function seedWorktreeAutoSync(worktreePath: string, mainRoot: string): Promise<void> {- const inherited = resolveRootAutoSync(mainRoot);+ const inherited = resolveRootAutoSyncMode(mainRoot);if (inherited === null) return;const result = await writeConfigPatch({cwd: worktreePath,scope: 'project-local',patch: {autoSync: {- enabled: inherited,+ mode: inherited,inheritedNoticePending: true,inheritedFrom: basename(mainRoot),},@@ -83,7 +102,16 @@ export async function seedWorktreeAutoSync(worktreePath: string, mainRoot: strinif (!result.ok) {getLogger('worktree-autosync').warn({ worktreePath, reason: result.error.code },- 'failed to seed inherited autoSync.enabled',+ 'failed to seed inherited autoSync.mode',);+ return;}+ // Attribute the activation here: once seeded, the mode is an ordinary+ // per-machine `autoSync.mode`, so the booting server can't tell it apart from+ // a user's own choice (it collapses to the `config` source). The seed site is+ // the only place that knows the origin is worktree inheritance. Bounded fields+ // only — the parent project name and worktree path are unbounded, so they stay+ // out of the telemetry payload.+ const source: SyncModeChangeSource = 'worktree-inherit';+ getLogger('worktree-autosync').info({ to: inherited, source }, 'seeded inherited autoSync mode');}diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 0a821bbb6..49cd96ed4 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -437,6 +437,7 @@ import { reprojectAllManagedSkills } from './skill-reproject.ts';import { readSkillInstallStateSnapshot } from './skill-state.ts';import { readSkillTargets, writeSkillTargets } from './skill-targets-store.ts';import { handleSpawnCursor } from './spawn-cursor-api.ts';+import { assertRealpathWithinDir } from './symlink-guard.ts';import { readUiLock } from './ui-lock.ts';import {HashingPassThrough,@@ -13609,6 +13610,98 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {// backward-compatible.const source = url.searchParams.get('source');const pg = simpleGit({ baseDir: projectDir, timeout: { block: 15_000 } });++ // Working-tree-variant conflicts (pull-only B1) have no git index stages:+ // the branch already fast-forwarded to origin tip and the overlay rides+ // uncommitted on top. Serve `theirs`/`base` from the pinned tip/base blobs+ // and `ours` from the live doc (or disk when unloaded). The merge-native+ // stage path below is untouched for git-merge conflicts.+ const wtEntry = engine+ ?.getConflicts()+ .find((c) => c.file === file && c.variant === 'working-tree');+ if (wtEntry) {+ try {+ // A pinned SHA that fails to read is an unexpected failure (the blob was+ // reachable when the engine pinned it), NOT an absent blob. Returning ''+ // would misread it downstream as origin-deleted (`kind: 'modify-delete'`)+ // and steer the user into a `delete` resolution that removes their own+ // doc. Discriminate: `undefined` sha = genuinely no pinned blob (the+ // empty side of a delete/modify); a read failure on a present sha logs+ // and rethrows to the outer catch → 500, matching the merge-native+ // `showStage` discipline below.+ const readBlob = async (sha: string | undefined): Promise<string> => {+ if (!sha) return '';+ try {+ return await pg.raw(['cat-file', 'blob', sha]);+ } catch (err) {+ console.warn(+ JSON.stringify({+ event: 'conflict-content-readblob-failed',+ file,+ detail: err instanceof Error ? err.message : String(err),+ handler: 'sync-conflict-content',+ }),+ );+ throw err;+ }+ };+ const theirs = await readBlob(wtEntry.theirsSha);+ const base = await readBlob(wtEntry.baseSha);+ const docName = stripDocExtension(file);+ const loaded = hocuspocus.documents.get(docName);+ let ours = '';+ let oursPresent = false;+ let lifecycleStatus: string | null = null;+ if (loaded) {+ const rawStatus = loaded.getMap('lifecycle').get('status');+ lifecycleStatus =+ typeof rawStatus === 'string' && rawStatus.length > 0 ? rawStatus : null;+ const ytextOurs = serializeDoc ? serializeDoc(docName) : null;+ if (ytextOurs !== null) {+ ours = ytextOurs;+ oursPresent = true;+ }+ } else {+ // Unloaded doc: the overlay is on disk (absent for a delete overlay).+ // Realpath-contain the read first — `file` is an origin-controlled+ // tracked path that could be a symlink escaping the working tree,+ // disclosing a foreign file. A SymlinkEscapeError propagates to the+ // outer catch → 500; the inner catch still handles the benign ENOENT+ // of a genuine delete overlay.+ assertRealpathWithinDir(join(projectDir, file), projectDir);+ try {+ ours = readFileSync(join(projectDir, file), 'utf-8');+ oursPresent = true;+ } catch {+ oursPresent = false;+ }+ }+ // A locally-deleted file the tip modified is a delete/modify shape;+ // otherwise both sides hold content.+ const kind: 'both-modified' | 'delete-modify' | 'modify-delete' = !oursPresent+ ? 'delete-modify'+ : theirs.length === 0+ ? 'modify-delete'+ : 'both-modified';+ successResponse(+ res,+ 200,+ SyncConflictContentSuccessSchema,+ { file, base, ours, theirs, kind, lifecycleStatus },+ { handler: 'sync-conflict-content' },+ );+ } catch (e) {+ errorResponse(+ res,+ 500,+ 'urn:ok:error:internal-server-error',+ 'Failed to read conflict content.',+ { handler: 'sync-conflict-content', cause: e },+ );+ }+ return;+ }+// git stages: 1 = base, 2 = ours, 3 = theirs. Any may be missing for// delete/edit or add/add conflicts. Return a discriminated shape so the// caller can derive `kind` from stage presence — empty-string content isdiff --git a/packages/server/src/boot-conflict-restore.test.ts b/packages/server/src/boot-conflict-restore.test.tsindex 878cd41ea..ac9d9658e 100644--- a/packages/server/src/boot-conflict-restore.test.ts+++ b/packages/server/src/boot-conflict-restore.test.ts@@ -8,14 +8,16 @@* relies on is open during the post-restart race window — silent data loss* by the same failure mode.*- * Skip on CI (subprocess + git child spawns; oven-sh/bun#11892) to mirror- * the existing boot.test.ts skip gate.+ * This runs in CI. The old blanket `process.env.CI` skip mirrored+ * boot.test.ts and cited oven-sh/bun#11892 (Bun failing to reap spawned git+ * children on GitHub runners) — irrelevant now that the suite runs under+ * vitest, not `bun test`. The restart-recovery guarantee is exactly the+ * highest-risk path this file exists to pin, and its full-server-boot ++ * git-child pattern already runs in CI via the sync-wired harness and+ * sync-engine.test.ts; leaving it CI-skipped meant it never ran there. If it+ * ever flakes or hangs in CI, narrow to a targeted skip, not a blanket gate.*/-import { describe as _bunDescribe, afterEach, beforeEach, expect, test } from 'vitest';--const describe = process.env.CI ? _bunDescribe.skip : _bunDescribe;-import { execFile } from 'node:child_process';import { mkdirSync, writeFileSync } from 'node:fs';import { mkdtemp, rm } from 'node:fs/promises';@@ -23,6 +25,7 @@ import { tmpdir } from 'node:os';import { resolve } from 'node:path';import { promisify } from 'node:util';import { OK_DIR } from '@inkeep/open-knowledge-core';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';import { bootServer } from './boot.ts';import { ConfigSchema } from './config/schema.ts';@@ -53,6 +56,30 @@ function seedConflictsJson(writeFileSync(resolve(localDir, 'conflicts.json'), JSON.stringify(data, null, 2), 'utf-8');}+/**+ * Seed a pull-only working-tree conflict entry (no MERGE_HEAD): the branch is at+ * origin tip and the overlay rides uncommitted. Boot restore must keep it even+ * though no merge is in progress.+ */+function seedWorkingTreeConflictsJson(projectDir: string, file: string): void {+ const localDir = resolve(projectDir, OK_DIR, 'local');+ mkdirSync(localDir, { recursive: true });+ const data = {+ version: 1,+ branch: 'main',+ conflicts: [+ {+ file,+ detectedAt: '2026-05-19T00:00:00.000Z',+ variant: 'working-tree',+ theirsSha: '0000000000000000000000000000000000000000',+ baseSha: '0000000000000000000000000000000000000000',+ },+ ],+ };+ writeFileSync(resolve(localDir, 'conflicts.json'), JSON.stringify(data, null, 2), 'utf-8');+}+/*** Create a real in-progress merge with a conflict on `filePath` so the* boot-scan's reconcile (`git diff --name-only --diff-filter=U` against a@@ -129,6 +156,42 @@ describe('bootServer — FR14 lifecycle restoration from conflicts.json', () =>}}, 30_000);+ test('preserves a working-tree conflict with no MERGE_HEAD and restores its lifecycle', async () => {+ const contentDir = tmpDir;+ await execFileAsync('git', ['init', '--initial-branch=main', contentDir]);+ seedOkScaffold(contentDir);+ // Commit the doc; NO merge in progress (no MERGE_HEAD). A merge-native entry+ // would be cleared as stale here — a working-tree overlay must survive.+ await execFileAsync('git', ['config', 'user.email', '[email protected]'], { cwd: contentDir });+ await execFileAsync('git', ['config', 'user.name', 'Test'], { cwd: contentDir });+ writeFileSync(resolve(contentDir, 'wt.md'), 'origin\n', 'utf-8');+ await execFileAsync('git', ['add', 'wt.md'], { cwd: contentDir });+ await execFileAsync('git', ['commit', '-m', 'seed'], { cwd: contentDir });+ seedWorkingTreeConflictsJson(contentDir, 'wt.md');++ const booted = await bootServer({+ config: TEST_CONFIG,+ contentDir,+ port: 0,+ quiet: true,+ gitEnabled: false,+ idleShutdownMs: null,+ attachUiSibling: false,+ });++ try {+ const dc = await booted.serverInstance.hocuspocus.openDirectConnection('wt');+ try {+ // Survived the no-MERGE_HEAD reconcile and the lifecycle was restored.+ expect(dc.document?.getMap('lifecycle').get('status')).toBe('conflict');+ } finally {+ await dc.disconnect();+ }+ } finally {+ await booted.destroy();+ }+ }, 30_000);+test('emits lifecycle-restored-from-conflicts-json event per restored doc', async () => {const contentDir = tmpDir;await execFileAsync('git', ['init', '--initial-branch=main', contentDir]);diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.tsindex 7c40f8fe1..dc6e1e3b0 100644--- a/packages/server/src/boot.ts+++ b/packages/server/src/boot.ts@@ -1162,7 +1162,7 @@ export async function restoreLifecycleFromConflictsJson(args: {}): Promise<void> {const { hocuspocus, projectDir, log } = args;let store: ConflictStore;- let entries: Array<{ file: string }>;+ let entries: Array<{ file: string; variant?: 'working-tree' }>;try {store = new ConflictStore(projectDir);entries = store.list();@@ -1184,6 +1184,11 @@ export async function restoreLifecycleFromConflictsJson(args: {// for <path>" indefinitely because conflicts.json + lifecycle disagree// with /api/sync/conflicts after the sync engine's own reconcile clears// the store).+ // Working-tree conflicts (pull-only overlays) have no MERGE_HEAD and are never+ // in the git unmerged index, so the merge-native reconciliation must not treat+ // them as stale — they are always restored. Only merge-native entries+ // reconcile against git's index.+ const isWorkingTree = (e: { variant?: string }): boolean => e.variant === 'working-tree';let stillUnmerged: Set<string> | null = null;try {// Linked-worktree safety: `<projectDir>/.git` is a regular file (not a@@ -1195,19 +1200,24 @@ export async function restoreLifecycleFromConflictsJson(args: {const gitDir = resolveGitDir(projectDir);const mergeHeadPath = gitDir ? join(gitDir, 'MERGE_HEAD') : null;if (!mergeHeadPath || !existsSync(mergeHeadPath)) {- // No merge in progress — every entry is stale.- store.clear();- console.warn(- JSON.stringify({- event: 'lifecycle-restore-cleared-stale-conflicts',- reason: 'no-merge-head',- count: entries.length,- }),- );- return;+ // No merge in progress — every MERGE-NATIVE entry is stale.+ const staleMergeNative = entries.filter((e) => !isWorkingTree(e));+ for (const entry of staleMergeNative) store.removeConflict(entry.file);+ entries = entries.filter(isWorkingTree);+ if (staleMergeNative.length > 0) {+ console.warn(+ JSON.stringify({+ event: 'lifecycle-restore-cleared-stale-conflicts',+ reason: 'no-merge-head',+ count: staleMergeNative.length,+ }),+ );+ }+ if (entries.length === 0) return;+ } else {+ const pg = simpleGit({ baseDir: projectDir, timeout: { block: 5_000 } });+ stillUnmerged = new Set(await listNames(pg, ['diff', '--name-only', '--diff-filter=U']));}- const pg = simpleGit({ baseDir: projectDir, timeout: { block: 5_000 } });- stillUnmerged = new Set(await listNames(pg, ['diff', '--name-only', '--diff-filter=U']));} catch (err) {// Probe failed — fall through and restore everything; the sync// engine's own reconcile on `start()` will mop up any stragglers.@@ -1217,11 +1227,11 @@ export async function restoreLifecycleFromConflictsJson(args: {);}- // Prune entries git considers resolved (still-unmerged probe succeeded).+ // Prune merge-native entries git considers resolved (working-tree entries kept).if (stillUnmerged !== null) {let pruned = 0;for (const entry of entries) {- if (!stillUnmerged.has(entry.file)) {+ if (!isWorkingTree(entry) && !stillUnmerged.has(entry.file)) {store.removeConflict(entry.file);pruned++;}@@ -1235,7 +1245,7 @@ export async function restoreLifecycleFromConflictsJson(args: {}),);}- entries = entries.filter((e) => stillUnmerged?.has(e.file));+ entries = entries.filter((e) => isWorkingTree(e) || stillUnmerged?.has(e.file));if (entries.length === 0) return;}diff --git a/packages/server/src/conflict-lifecycle-seed.ts b/packages/server/src/conflict-lifecycle-seed.tsindex de2e2c5cc..6acd67ada 100644--- a/packages/server/src/conflict-lifecycle-seed.ts+++ b/packages/server/src/conflict-lifecycle-seed.ts@@ -61,7 +61,7 @@ interface ConflictLifecycleSeedOptions {* `projectDir === contentDir` (the dominant case), but a project with* `contentDir` nested inside `projectDir` would otherwise misroute.*/-function entryMatchesDocName(+export function entryMatchesDocName(entry: ConflictEntry,docName: string,projectDir: string,diff --git a/packages/server/src/conflict-storage.test.ts b/packages/server/src/conflict-storage.test.tsindex b97ec2f4f..f2eb85b3a 100644--- a/packages/server/src/conflict-storage.test.ts+++ b/packages/server/src/conflict-storage.test.ts@@ -6,6 +6,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSyncimport { tmpdir } from 'node:os';import { join } from 'node:path';import { LOCAL_DIR } from '@inkeep/open-knowledge-core';+import simpleGit from 'simple-git';import { afterEach, beforeEach, describe, expect, test } from 'vitest';import { type ConflictEntry, ConflictStore } from './conflict-storage.ts';@@ -372,3 +373,100 @@ describe('ConflictStore resolveConflict()', () => {expect(store.hasConflicts()).toBe(false);});});++// ─── resolveConflict() — working-tree variant (pull-only B1) ──────────────────++describe('ConflictStore resolveConflict() — working-tree variant', () => {+ /**+ * Init a real git repo at projectDir with `file` committed at `remote`, then+ * overwrite the working tree with `local` (the uncommitted overlay). Returns+ * the committed blob SHA (the pin) and the HEAD SHA (to prove no commit runs).+ */+ async function seedOverlay(+ file: string,+ remote: string,+ local: string,+ ): Promise<{ blobSha: string; headSha: string }> {+ const git = simpleGit(projectDir);+ await git.init(['--initial-branch=main']);+ await git.raw('config', 'user.name', 'Test');+ await git.raw('config', 'user.email', '[email protected]');+ writeFileSync(join(projectDir, file), remote, 'utf-8');+ await git.add('.');+ await git.commit('seed');+ const blobSha = (await git.raw(['rev-parse', `HEAD:${file}`])).trim();+ const headSha = (await git.raw(['rev-parse', 'HEAD'])).trim();+ writeFileSync(join(projectDir, file), local, 'utf-8');+ return { blobSha, headSha };+ }++ async function headSha(): Promise<string> {+ return (await simpleGit(projectDir).raw(['rev-parse', 'HEAD'])).trim();+ }++ test("'theirs' restores the pinned origin-tip blob without committing", async () => {+ const { blobSha, headSha: before } = await seedOverlay('a.md', 'REMOTE\n', 'LOCAL\n');+ const store = new ConflictStore(projectDir, 'main');+ store.addConflict(makeEntry('a.md', { variant: 'working-tree', theirsSha: blobSha }));++ await store.resolveConflict('a.md', 'theirs');++ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('REMOTE\n');+ expect(store.count()).toBe(0);+ expect(await headSha()).toBe(before); // no commit created+ });++ test("'mine' keeps the overlay verbatim without committing", async () => {+ const { blobSha, headSha: before } = await seedOverlay('a.md', 'REMOTE\n', 'LOCAL\n');+ const store = new ConflictStore(projectDir, 'main');+ store.addConflict(makeEntry('a.md', { variant: 'working-tree', theirsSha: blobSha }));++ await store.resolveConflict('a.md', 'mine');++ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL\n');+ expect(store.count()).toBe(0);+ expect(await headSha()).toBe(before);+ });++ test("'content' writes the merged bytes without committing", async () => {+ const { blobSha, headSha: before } = await seedOverlay('a.md', 'REMOTE\n', 'LOCAL\n');+ const store = new ConflictStore(projectDir, 'main');+ store.addConflict(makeEntry('a.md', { variant: 'working-tree', theirsSha: blobSha }));++ await store.resolveConflict('a.md', 'content', 'HAND-MERGED\n');++ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('HAND-MERGED\n');+ expect(store.count()).toBe(0);+ expect(await headSha()).toBe(before);+ });++ test("'delete' honors the local deletion without committing", async () => {+ const { blobSha, headSha: before } = await seedOverlay('a.md', 'REMOTE\n', 'LOCAL\n');+ const store = new ConflictStore(projectDir, 'main');+ store.addConflict(makeEntry('a.md', { variant: 'working-tree', theirsSha: blobSha }));++ await store.resolveConflict('a.md', 'delete');++ expect(existsSync(join(projectDir, 'a.md'))).toBe(false);+ expect(store.count()).toBe(0);+ expect(await headSha()).toBe(before);+ });++ test('addConflict rejects a working-tree entry with no pinned blob', () => {+ const store = new ConflictStore(projectDir, 'main');+ expect(() => store.addConflict(makeEntry('a.md', { variant: 'working-tree' }))).toThrow(+ 'no pinned theirs blob',+ );+ });++ test("'theirs' still throws for a blob-less entry from a corrupt store", async () => {+ const store = new ConflictStore(projectDir, 'main');+ // addConflict now guards this invariant, so a blob-less working-tree entry+ // can only arrive via a hand-edited / corrupt conflicts.json loaded from+ // disk. Inject it past the guard to exercise the resolve-time defense.+ (store as unknown as { conflicts: unknown[] }).conflicts.push(+ makeEntry('a.md', { variant: 'working-tree' }),+ );+ await expect(store.resolveConflict('a.md', 'theirs')).rejects.toThrow('no pinned theirs blob');+ });+});diff --git a/packages/server/src/conflict-storage.ts b/packages/server/src/conflict-storage.tsindex 8c4d1cf1f..6a58b6682 100644--- a/packages/server/src/conflict-storage.ts+++ b/packages/server/src/conflict-storage.ts@@ -13,9 +13,11 @@import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { getLocalDir } from './config/paths.ts';+import { tracedUnlinkSync, tracedWriteFileSync } from './fs-traced.ts';import { listNames } from './git-paths.ts';import { getLogger } from './logger.ts';import { isWithinDir } from './path-utils.ts';+import { assertRealpathWithinDir } from './symlink-guard.ts';const log = getLogger('conflict-storage');@@ -32,6 +34,13 @@ export interface ConflictEntry {theirsSha?: string;/** SHA of the merge base at conflict time (optional). */baseSha?: string;+ /**+ * `'working-tree'` marks a pull-only overlay conflict: the branch is already+ * at origin tip and the local edit rides uncommitted on top, so there is no+ * unmerged index / MERGE_HEAD to resolve against. Absent (the default) means+ * a git-merge-native conflict resolved through the index stages.+ */+ variant?: 'working-tree';}export type ResolveStrategy = 'mine' | 'theirs' | 'content' | 'delete';@@ -82,8 +91,8 @@ export class ConflictStore {}}- /** Persist current state to disk. */- save(): void {+ /** Persist current state to disk. Returns false when the disk write failed. */+ save(): boolean {try {const dir = dirname(this.storePath);if (!existsSync(dir)) {@@ -95,26 +104,45 @@ export class ConflictStore {conflicts: this.conflicts,};writeFileSync(this.storePath, JSON.stringify(data, null, 2), 'utf-8');+ return true;} catch (e) {log.warn({ err: e }, '[conflicts] failed to save conflicts.json');+ return false;}}- /** Add a new conflict entry (idempotent by file path). */- addConflict(entry: ConflictEntry): void {+ /**+ * Add a new conflict entry (idempotent by file path). Returns false when the+ * in-memory upsert succeeded but the disk persist failed — the caller must+ * decide whether that divergence (a conflict shown this session but absent+ * from conflicts.json after a restart) is tolerable.+ */+ addConflict(entry: ConflictEntry): boolean {+ // Invariant: a working-tree (pull-only overlay) entry must carry the pinned+ // origin blob — the 'theirs' resolution reads it back by SHA. The optional+ // `theirsSha` field can't express this at the type level, so fail loudly at+ // insert time rather than with an opaque throw at resolve time.+ if (entry.variant === 'working-tree' && !entry.theirsSha) {+ throw new Error(+ `[conflicts] working-tree conflict for ${entry.file} has no pinned theirs blob`,+ );+ }const existing = this.conflicts.findIndex((c) => c.file === entry.file);if (existing !== -1) {this.conflicts[existing] = entry; // update if already tracked} else {this.conflicts.push(entry);}- this.save();+ return this.save();}- /** Remove a conflict entry by file path. */- removeConflict(file: string): void {+ /**+ * Remove a conflict entry by file path. Returns false when the in-memory+ * removal succeeded but the disk persist failed.+ */+ removeConflict(file: string): boolean {this.conflicts = this.conflicts.filter((c) => c.file !== file);- this.save();+ return this.save();}/** Remove all conflicts for the current branch. */@@ -177,6 +205,14 @@ export class ConflictStore {throw new Error(`[conflicts] strategy 'content' requires content parameter`);}+ // Pull-only overlay conflicts resolve without any index/commit — split off+ // before the merge-native path so its `git checkout --ours/--theirs` ++ // `git commit --no-edit` semantics stay untouched.+ if (entry.variant === 'working-tree') {+ await this.resolveWorkingTreeConflict(entry, strategy, content, credentialArgs);+ return;+ }+// Dynamic import so CRUD tests don't load simple-git (broken symlink in test env)const { createGitInstance } = await import('./git-handle.ts');const handle = createGitInstance(this.projectDir, { credentialArgs });@@ -212,7 +248,12 @@ export class ConflictStore {if (!isWithinDir(absPath, projectRoot)) {throw new Error(`[conflicts] file path escapes project directory: ${file}`);}- writeFileSync(absPath, content, 'utf-8');+ // Lexical containment alone lets a symlink materialized by the merge at+ // the conflicted path escape the tree on write; the working-tree path+ // already realpath-guards, so mirror it here and route through the+ // traced fs wrapper like every other server-side disk write.+ assertRealpathWithinDir(absPath, projectRoot);+ tracedWriteFileSync(absPath, content, 'utf-8');await handle.git.raw(['add', '--', file]);break;}@@ -297,4 +338,79 @@ export class ConflictStore {}}}++ /**+ * Resolve a pull-only overlay conflict. The branch already fast-forwarded to+ * origin tip and the local overlay is uncommitted on top, so there is no+ * unmerged index: resolution writes the chosen bytes straight to the working+ * tree and NEVER runs `git checkout --ours/--theirs` or `git commit` — the+ * engine never commits on a pull-only user's behalf.+ *+ * 'mine' — keep the local overlay verbatim (no disk write)+ * 'theirs' — restore the pinned origin-tip blob to disk+ * 'content' — write the caller-supplied merged bytes to disk+ * 'delete' — honor a local deletion (remove the file)+ *+ * After resolving, the entry is removed. The branch stays at origin tip in+ * every case; keep-mine leaves the overlay in place against the advanced tip.+ */+ private async resolveWorkingTreeConflict(+ entry: ConflictEntry,+ strategy: ResolveStrategy,+ content: string | undefined,+ credentialArgs: string[],+ ): Promise<void> {+ const projectRoot = resolve(this.projectDir);+ const absPath = resolve(projectRoot, entry.file);+ if (!isWithinDir(absPath, projectRoot)) {+ throw new Error(`[conflicts] file path escapes project directory: ${entry.file}`);+ }+ // Lexical containment is not enough: an untrusted origin can ship a symlink+ // at a tracked content path, and `writeFileSync`/`unlinkSync` would follow+ // it out of the working tree. Refuse when the realpath escapes.+ assertRealpathWithinDir(absPath, projectRoot);++ switch (strategy) {+ case 'mine':+ // The working tree already holds the overlay — keep it as-is.+ break;++ case 'theirs': {+ if (!entry.theirsSha) {+ throw new Error(+ `[conflicts] working-tree conflict for ${entry.file} has no pinned theirs blob`,+ );+ }+ const { createGitInstance } = await import('./git-handle.ts');+ const handle = createGitInstance(this.projectDir, { credentialArgs });+ const theirsBytes = await handle.git.raw(['cat-file', 'blob', entry.theirsSha]);+ // The realpath guard above ran before this `await`, which yielded the+ // event loop; a concurrent pull cycle could have materialized a symlink+ // at absPath in that gap. Re-check immediately before the write, matching+ // applyOverlayPlan's per-write containment.+ assertRealpathWithinDir(absPath, projectRoot);+ tracedWriteFileSync(absPath, theirsBytes, 'utf-8');+ break;+ }++ case 'content': {+ if (content === undefined) {+ throw new Error(`[conflicts] strategy 'content' requires content parameter`);+ }+ tracedWriteFileSync(absPath, content, 'utf-8');+ break;+ }++ case 'delete':+ if (existsSync(absPath)) tracedUnlinkSync(absPath);+ break;++ default: {+ const exhaustive: never = strategy;+ throw new Error(`[conflicts] unknown resolve strategy: ${exhaustive}`);+ }+ }++ this.removeConflict(entry.file);+ }}diff --git a/packages/server/src/server-factory.test.ts b/packages/server/src/server-factory.test.tsindex c67da0dac..00a67964b 100644--- a/packages/server/src/server-factory.test.ts+++ b/packages/server/src/server-factory.test.ts@@ -959,14 +959,14 @@ describe('createServer() — config file watcher (US-007)', () => {});});-// ─── file-watcher → engine.setEnabled loop ─────────────────────────────────+// ─── file-watcher → engine.setMode loop ────────────────────────────────────//// Writing autoSync.enabled to <projectDir>/.ok/local/config.yml externally-// must propagate via the file watcher to the SyncEngine's syncEnabled flag.-// Closes the persistence ↔ engine loop end-to-end without going through-// the client binding.+// must propagate via the file watcher to the SyncEngine's mode (legacy+// `enabled: true` derives to `full`). Closes the persistence ↔ engine loop+// end-to-end without going through the client binding.-describe('createServer() — project-local file watcher → engine.setEnabled', () => {+describe('createServer() — project-local file watcher → engine.setMode', () => {let testProjectDir: string;let testHomedir: string;@@ -1002,7 +1002,7 @@ describe('createServer() — project-local file watcher → engine.setEnabled',// Wait for file-watcher to detect the new file, applyExternalConfigChange// to update Y.Text, and the post-change handler to call- // syncEngine.setEnabled(readProjectAutoSyncEnabled()).+ // syncEngine.setMode(readProjectAutoSyncMode()).const flipped = await waitFor(() => srv.syncEngine?.getStatus().syncEnabled === true);expect(flipped).toBe(true);@@ -1056,7 +1056,7 @@ describe('createServer() — project-local file watcher → engine.setEnabled',expect(srv.syncEngine?.getStatus().syncEnabled).toBe(false);// A maintainer commits autoSync.default: true to <projectDir>/.ok/config.yml.- // The committed-config watcher must re-run readProjectAutoSyncEnabled and,+ // The committed-config watcher must re-run readProjectAutoSyncMode and,// because this machine is unanswered, seed the engine from the default.mkdirSync(join(testProjectDir, '.ok'), { recursive: true });writeFileSync(@@ -2080,16 +2080,16 @@ describe('createServer() — config-doc admission guard', () => {});});-// ─── readProjectAutoSyncEnabled precedence + onAutoDisable scope ────────────+// ─── readProjectAutoSyncMode precedence + onAutoDisable scope ────────────//-// readProjectAutoSyncEnabled reads the per-machine project-local+// readProjectAutoSyncMode reads the per-machine project-local// autoSync.enabled first; when unanswered (null/absent) it falls back to the// committed project-scope autoSync.default seed. A committed autoSync.enabled is// deliberately ignored (project-local-scoped field → a committed value is a// scope mismatch). onAutoDisable persists the auto-off flag to project-local so// a teammate's machine never overrides another teammate's preference via git.-describe('createServer() — readProjectAutoSyncEnabled precedence', () => {+describe('createServer() — readProjectAutoSyncMode precedence', () => {let testProjectDir: string;let testHomedir: string;@@ -2230,7 +2230,7 @@ describe('createServer() — readProjectAutoSyncEnabled precedence', () => {});test('invalid project-local YAML falls through to committed default (degraded path)', async () => {- // Pins the !local.valid branch in readProjectAutoSyncEnabled. A corrupt+ // Pins the !local.valid branch in readProjectAutoSyncMode. A corrupt// project-local file must not silently disable sync — the function logs and// falls back to the committed project default so the user keeps working// until the corruption is repaired.@@ -2250,7 +2250,7 @@ describe('createServer() — readProjectAutoSyncEnabled precedence', () => {test('invalid committed config defaults to disabled (degraded path)', async () => {// A corrupt committed `.ok/config.yml` means autoSync.default can't be read,- // so sync defaults to disabled (readProjectAutoSyncEnabled logs the+ // so sync defaults to disabled (readProjectAutoSyncMode logs the// correlation). The machine is unanswered, so there is no project-local// value to fall back to — mirrors the project-local degraded path.seedProjectConfig('autoSync:\n default: : not-yaml [[[\n');diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.tsindex 548daac9f..a2e604ba7 100644--- a/packages/server/src/server-factory.ts+++ b/packages/server/src/server-factory.ts@@ -29,9 +29,13 @@ import {type LinksValidationSetting,type LinterConfig,type MarkdownManager,+ modeFromCommittedDefault,type PersistedLinterConfig,type Principal,parseGlobalSkillBundleDoc,+ resolveLocalAutoSyncMode,+ type SyncMode,+ type SyncModeChangeSource,toEffectiveBase,} from '@inkeep/open-knowledge-core';import {@@ -74,7 +78,10 @@ import {} from './config-file-watcher.ts';import { applyExternalConfigChange } from './config-persistence.ts';import { isDocInConflict } from './conflict-errors.ts';-import { createConflictLifecycleSeedExtension } from './conflict-lifecycle-seed.ts';+import {+ createConflictLifecycleSeedExtension,+ entryMatchesDocName,+} from './conflict-lifecycle-seed.ts';import { resolveProjectTemplates } from './content/templates-resolver.ts';import { type ContentFilter, createContentFilter } from './content-filter.ts';import { isWithinContentDir, safeContentPath } from './content-path.ts';@@ -182,6 +189,7 @@ import {SERVICE_WRITER,type ShadowHandle,type ShadowRef,+ safetyCheckpoint,saveInMemoryCheckpoint,shadowGit,} from './shadow-repo.ts';@@ -304,6 +312,15 @@ export interface ServerOptions {* Mirrors `SyncEngineOptions.checkPushPermissionFn`.*/checkPushPermissionFn?: (opts: CheckPushPermissionOptions) => Promise<PushPermission>;+ /**+ * Seconds between the SyncEngine's background pull/push cycles. Production+ * leaves these undefined so the engine uses its own defaults (30 s pull /+ * 60 s push). The integration harness passes a large value so a sync-wired+ * test drives cycles explicitly via `trigger()` without a background timer+ * racing the scenario. Same DI rationale as `debounce` / `commitDebounceMs`.+ */+ pullIntervalSeconds?: number;+ pushIntervalSeconds?: number;/*** Read-only accessor for the embeddings API key (the CLI's 0600* `~/.ok/secrets.yml` file), injected from the CLI / desktop wiring layer.@@ -617,18 +634,20 @@ export function createServer(options: ServerOptions): ServerInstance {return project.value.content.attachmentFolderPath ?? DEFAULT_ATTACHMENT_FOLDER_PATH;}- function readProjectAutoSyncEnabled(): boolean {+ function readProjectAutoSyncMode(): { mode: SyncMode; source: SyncModeChangeSource } {const local = readConfigSafely({absPath: resolveConfigPath('project-local', projectDir),sideline: false,warn: (message) => log.warn({ message }, '[config] could not read project-local config'),});- const localEnabled = local.value.autoSync?.enabled;- if (localEnabled !== null && localEnabled !== undefined) {+ const localMode = resolveLocalAutoSyncMode(local.value.autoSync);+ if (localMode !== null) {// This machine has answered (or the engine auto-disabled on a denied// push probe) — the per-machine choice always wins over the committed- // default.- return localEnabled === true;+ // default. `full` pushes; `pull` fetches one-directionally; `off` stays+ // inactive. The prompt/Settings/paused-notice surfaces all write this same+ // per-machine mode, so they collapse to the `config` telemetry source.+ return { mode: localMode, source: 'config' };}// The file was present but failed validation — readConfigSafely already// logged the parse/schema detail. Surface the fallback decision so a@@ -643,8 +662,9 @@ export function createServer(options: ServerOptions): ServerInstance {// Unanswered on this machine: consult the committed project default// (`autoSync.default`), which a maintainer ships in `.ok/config.yml` to// pre-answer the onboarding prompt for everyone who clones the project.- // `true` seeds sync on; `false`/`null`/absent leaves it off here (and when- // the committed default is `null`/absent the onboarding gate prompts).+ // A `pull`/`full` (or legacy `true`) seed engages that mode; `off`/`false`/+ // `null`/absent leaves the engine off here (and when the committed default+ // is `null`/absent the onboarding gate prompts).//// We deliberately do NOT read a committed `autoSync.enabled`: that field is// project-local-scoped, so a committed value is a scope mismatch. The app@@ -666,7 +686,12 @@ export function createServer(options: ServerOptions): ServerInstance {'[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled',);}- return project.value.autoSync?.default === true;+ // `null` (never answered anywhere) resolves to `off` for the engine; the+ // onboarding prompt is a UI-layer concern that reads config directly.+ return {+ mode: modeFromCommittedDefault(project.value.autoSync?.default) ?? 'off',+ source: 'committed-default',+ };}// Project-scope base linter config, read FRESH per request so a config edit@@ -748,20 +773,21 @@ export function createServer(options: ServerOptions): ServerInstance {//// Both entry points can fire for the same change (producer notify + watcher// echo), so every consumer notified here MUST be idempotent on a same-value- // re-apply: `SyncEngine.setEnabled` and `SemanticSearchService.applyConfig`+ // re-apply: `SyncEngine.setMode` and `SemanticSearchService.applyConfig`// both early-return when the value is unchanged. A future non-idempotent// consumer added here would double-fire.function applyPersistedConfigToConsumers(configDocName: string): void {- let appliedAutoSyncEnabled: boolean | undefined;+ let appliedAutoSyncMode: SyncMode | undefined;if (configDocName === CONFIG_DOC_NAME_PROJECT ||configDocName === CONFIG_DOC_NAME_PROJECT_LOCAL) {- appliedAutoSyncEnabled = readProjectAutoSyncEnabled();- void syncEngine?.setEnabled(appliedAutoSyncEnabled).catch((err) => {+ const resolved = readProjectAutoSyncMode();+ appliedAutoSyncMode = resolved.mode;+ void syncEngine?.setMode(resolved.mode, resolved.source).catch((err) => {log.warn(- { err, enabled: appliedAutoSyncEnabled, docName: configDocName },- '[sync] failed to apply autoSync.enabled from config',+ { err, mode: resolved.mode, docName: configDocName },+ '[sync] failed to apply autoSync mode from config',);});}@@ -779,7 +805,7 @@ export function createServer(options: ServerOptions): ServerInstance {log.info({docName: configDocName,- autoSyncEnabled: appliedAutoSyncEnabled,+ autoSyncMode: appliedAutoSyncMode,semanticEnabled: semCfg.enabled,},'[config] applied persisted config to in-process consumers',@@ -1947,6 +1973,22 @@ export function createServer(options: ServerOptions): ServerInstance {*/function clearLifecycleConflict(document: Document): void {if (!isDocInConflict(document)) return;+ // Never clear while the engine still holds a standing conflict for this doc.+ // A B1 pull-only conflict pull fast-forwards the working tree via a raw git+ // write (outside `writeTracker`), which the file-watcher re-emits as an+ // `update`. That reconcile computes `noop` (base==ours==theirs, the conflict+ // content already applied) and would otherwise wipe the `lifecycle.status`+ // the pull just set — desyncing the editor→resolver swap from the+ // ConflictStore, so the resolver vanishes (and never reappears on reopen)+ // while the conflict is still unresolved. Clearing is correct only once the+ // engine agrees the conflict is gone (resolve / auto-dissolve).+ if (+ syncEngine+ ?.getConflicts()+ .some((entry) => entryMatchesDocName(entry, document.name, projectDir, contentDir))+ ) {+ return;+ }const lifecycleMap = document.getMap('lifecycle');lifecycleMap.delete('status');lifecycleMap.delete('reason');@@ -4244,15 +4286,44 @@ export function createServer(options: ServerOptions): ServerInstance {}}+ // Clear the conflict lifecycle on a resolved / auto-dissolved working-tree+ // conflict. Keep-mine resolution and upstream auto-dissolve may not change+ // disk bytes, so the file-watcher's `case 'update'` clear can't be relied on.+ function clearLoadedContentConflicts(files: string[]): void {+ for (const file of files) {+ try {+ const absPath = join(projectDir, file);+ const contentRelPath = toPosix(relative(contentDir, absPath));+ if (contentRelPath.startsWith('..')) continue;+ const document = hocuspocus.documents.get(stripDocExtension(contentRelPath));+ if (document) clearLifecycleConflict(document);+ } catch (err) {+ log.warn({ err, file }, '[sync] failed to clear resolved content conflict');+ }+ }+ }+// Start SyncEngine: remote detection + auto-sync.const syncCredentialArgs = buildSyncCredentialArgs(localOpCliArgs);+ const bootAutoSyncMode = readProjectAutoSyncMode();+ if (bootAutoSyncMode.mode !== 'off') {+ // A never-asked machine booting into a committed-default mode is the main+ // way pull-only activates silently; log it (with the resolution source) so+ // committed-default activations are observable alongside runtime changes.+ log.info(+ { mode: bootAutoSyncMode.mode, source: bootAutoSyncMode.source },+ '[sync] mode active at boot',+ );+ }try {syncEngine = new SyncEngine({projectDir,contentDir,contentFilter,contentRoot,- syncEnabled: readProjectAutoSyncEnabled(),+ mode: bootAutoSyncMode.mode,+ pullIntervalSeconds: options.pullIntervalSeconds,+ pushIntervalSeconds: options.pushIntervalSeconds,credentialArgs: syncCredentialArgs,cc1Broadcaster,// Push-permission probe auth seam — production callers (CLI `ok start`)@@ -4280,6 +4351,33 @@ export function createServer(options: ServerOptions): ServerInstance {log.info({ state }, `[sync] state → ${state}`);},onContentConflictsDetected: markLoadedContentConflicts,+ onContentConflictsResolved: clearLoadedContentConflicts,+ // Snapshot the working tree to the recoverable timeline before a+ // pull-only transition realigns the branch over stranded local commits,+ // so their content survives on the timeline, not just the reflog.+ checkpointBeforeStrandedConversion: async ({ branch, ahead }) => {+ const shadow = shadowRef.current;+ if (!shadow) return;+ await safetyCheckpoint(+ shadow,+ contentRoot ?? '',+ { action: 'pull-only-stranded-conversion', context: { ahead } },+ branch,+ );+ },+ // Before a pull-only fast-forward resets an overlapping uncommitted edit+ // to HEAD, snapshot the working tree so the pre-reset bytes survive on+ // the shadow timeline through the reset→re-write window.+ checkpointBeforeOverlayRestore: async ({ branch, paths }) => {+ const shadow = shadowRef.current;+ if (!shadow) return;+ await safetyCheckpoint(+ shadow,+ contentRoot ?? '',+ { action: 'pull-only-overlay-restore', context: { paths } },+ branch,+ );+ },onAutoDisable: async (reason) => {log.warn({ reason }, '[sync] auto-disabled — persisting to project-local config');const result = await writeConfigPatch({diff --git a/packages/server/src/symlink-guard.test.ts b/packages/server/src/symlink-guard.test.tsnew file mode 100644index 000000000..eab83b50b--- /dev/null+++ b/packages/server/src/symlink-guard.test.ts@@ -0,0 +1,80 @@+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { SymlinkEscapeError } from './apply-managed-rename.ts';+import { assertRealpathWithinDir } from './symlink-guard.ts';++describe('assertRealpathWithinDir', () => {+ let root: string;++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'symlink-guard-'));+ // Shape a realistic project: a git dir with the default (inactive) sample+ // hooks git actually ships, an .ok state dir, and a content sub-folder.+ mkdirSync(join(root, '.git', 'hooks'), { recursive: true });+ writeFileSync(join(root, '.git', 'config'), '[core]\n');+ mkdirSync(join(root, '.ok', 'local'), { recursive: true });+ writeFileSync(join(root, '.ok', 'local', 'config.yml'), 'autoSync:\n mode: full\n');+ mkdirSync(join(root, 'notes'), { recursive: true });+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ it('passes a plain content path that does not exist yet', () => {+ expect(() => assertRealpathWithinDir(join(root, 'notes', 'new.md'), root)).not.toThrow();+ });++ it('passes a symlink that resolves to a sibling content file', () => {+ writeFileSync(join(root, 'notes', 'real.md'), '# real\n');+ symlinkSync('./real.md', join(root, 'notes', 'link.md'));+ expect(() => assertRealpathWithinDir(join(root, 'notes', 'link.md'), root)).not.toThrow();+ });++ it('refuses a DANGLING symlink pointing into .git/hooks (git ships only *.sample, so the hook file is absent)', () => {+ // The realistic attack: an upstream commits notes/daily.md as a symlink to+ // .git/hooks/post-checkout. git ships post-checkout.sample, not post-checkout,+ // so the target is absent and realpath cannot resolve it — the write would+ // CREATE an executable hook. Must be refused before the write.+ symlinkSync('../.git/hooks/post-checkout', join(root, 'notes', 'daily.md'));+ expect(() => assertRealpathWithinDir(join(root, 'notes', 'daily.md'), root)).toThrow(+ SymlinkEscapeError,+ );+ });++ it('refuses an EXISTING symlink pointing into .git', () => {+ symlinkSync('../.git/config', join(root, 'notes', 'gitcfg.md'));+ expect(() => assertRealpathWithinDir(join(root, 'notes', 'gitcfg.md'), root)).toThrow(+ SymlinkEscapeError,+ );+ });++ it('refuses a symlink pointing into the .ok state dir (config hijack)', () => {+ symlinkSync('../.ok/local/config.yml', join(root, 'notes', 'okcfg.md'));+ expect(() => assertRealpathWithinDir(join(root, 'notes', 'okcfg.md'), root)).toThrow(+ SymlinkEscapeError,+ );+ });++ it('refuses a symlink that escapes the root entirely (existing containment)', () => {+ const outside = mkdtempSync(join(tmpdir(), 'symlink-guard-outside-'));+ try {+ writeFileSync(join(outside, 'secret.txt'), 'secret');+ symlinkSync(join(outside, 'secret.txt'), join(root, 'notes', 'escape.md'));+ expect(() => assertRealpathWithinDir(join(root, 'notes', 'escape.md'), root)).toThrow(+ SymlinkEscapeError,+ );+ } finally {+ rmSync(outside, { recursive: true, force: true });+ }+ });++ it('refuses a DANGLING symlink that escapes the root (absent target outside root)', () => {+ symlinkSync(resolve(root, '..', 'nonexistent-outside-target'), join(root, 'notes', 'esc2.md'));+ expect(() => assertRealpathWithinDir(join(root, 'notes', 'esc2.md'), root)).toThrow(+ SymlinkEscapeError,+ );+ });+});diff --git a/packages/server/src/symlink-guard.ts b/packages/server/src/symlink-guard.tsnew file mode 100644index 000000000..a264c1f1d--- /dev/null+++ b/packages/server/src/symlink-guard.ts@@ -0,0 +1,115 @@+/**+ * Realpath-based symlink-escape containment for the fs write/read sites that+ * operate on git-tracked paths — the pull-only overlay apply, working-tree+ * conflict resolution, and conflict-content reads.+ *+ * A git remote is untrusted: it can commit a symlink at a tracked path, and a+ * fast-forward materialises that link on disk. A subsequent bare `node:fs`+ * write follows the link to wherever it points, so a lexical `..`/absolute+ * check (which normalizes but never dereferences symlinks) is not enough — a+ * symlinked path component sails through it. Refuse when the target resolves+ * outside `rootDir`, OR into the root's own `.git`/`.ok` trees (see below).+ * Mirrors the persistence + api-extension `assertNoSymlinkEscape` controls;+ * fails closed on unexpected realpath errors.+ *+ * Two subtleties this handles that a plain realpath check does not:+ * 1. `.git`/`.ok` live INSIDE the git root, so a lexical/realpath "within+ * root" check alone still permits a symlink resolving to+ * `.git/hooks/post-checkout` (code-exec on the next git op) or+ * `.ok/local/config.yml` (config hijack). The logical-path content filter+ * only sees the pre-symlink name, so those must be re-refused on the+ * resolved path here.+ * 2. A DANGLING symlink (target not yet created — e.g. git ships+ * `post-checkout.sample`, not `post-checkout`) makes `realpathSync` throw+ * ENOENT, and a naive climb to the lexical parent would pass it — yet a+ * write through that link CREATES the target. The link is resolved+ * manually so its destination is checked even when absent.+ */++import { lstatSync, readlinkSync, realpathSync } from 'node:fs';+import { dirname, relative, resolve } from 'node:path';+import { SymlinkEscapeError } from './apply-managed-rename.ts';+import { isWithinDir, toPosix } from './path-utils.ts';++/**+ * Assert that `targetAbsPath` does not resolve (via symlinks) outside `rootDir`+ * and does not resolve into the root's `.git` or `.ok` state trees. Throws+ * {@link SymlinkEscapeError} on escape, on a symlink cycle, or on any+ * unexpected realpath failure (fail-closed). A missing leaf is fine — the walk+ * climbs to the nearest existing ancestor (or follows a dangling symlink to its+ * intended target) and checks that instead, so a brand-new file under a+ * legitimate directory passes.+ */+export function assertRealpathWithinDir(targetAbsPath: string, rootDir: string): void {+ const resolvedRoot = resolve(rootDir);+ let canonicalRoot: string;+ try {+ canonicalRoot = realpathSync(resolvedRoot);+ } catch (err) {+ const code = (err as NodeJS.ErrnoException).code;+ if (code === 'ENOENT') throw new SymlinkEscapeError('root directory does not exist');+ throw err;+ }++ let cur = resolve(targetAbsPath);+ // Each pass either climbs one lexical parent (path shrinks) or follows one+ // symlink; the counter is a fail-closed backstop against a pathological+ // dangling-symlink chain that neither resolves nor climbs to root.+ for (let steps = 0; ; steps++) {+ if (steps > 256) throw new SymlinkEscapeError('too many symlink resolutions in path');+ try {+ const canonical = realpathSync(cur);+ if (!isWithinDir(canonical, canonicalRoot)) {+ throw new SymlinkEscapeError(`path resolves outside ${rootDir}`);+ }+ if (resolvesIntoInternalStateDir(canonical, canonicalRoot)) {+ throw new SymlinkEscapeError('path resolves into the .git/.ok state tree');+ }+ return;+ } catch (err) {+ if (err instanceof SymlinkEscapeError) throw err;+ const code = (err as NodeJS.ErrnoException).code;+ if (code === 'ELOOP') throw new SymlinkEscapeError('symlink cycle in path');+ // Anything other than "leaf not created yet" leaves the gate unverifiable:+ // fail closed rather than silently permitting the write.+ if (code !== 'ENOENT') throw err;+ // `cur` didn't resolve. If `cur` itself is a symlink, its target is merely+ // absent (dangling) — realpath can't follow it, but a write WOULD create+ // the target. Resolve the link manually so its destination is checked;+ // otherwise a dangling symlink into `.git`/`.ok` (or outside root) would+ // slip through the lexical-parent climb.+ let linkTarget: string | null = null;+ try {+ if (lstatSync(cur).isSymbolicLink()) linkTarget = readlinkSync(cur);+ } catch {+ // `cur` doesn't exist at all (not even as a dangling link) — fall+ // through to the lexical climb to find the nearest existing ancestor.+ }+ if (linkTarget !== null) {+ cur = resolve(dirname(cur), linkTarget);+ continue;+ }+ const parent = dirname(cur);+ if (parent === cur) throw err;+ // Never climb above the root while chasing a missing leaf — a target that+ // would resolve above `rootDir` is itself an escape.+ if (parent !== resolvedRoot && !isWithinDir(parent, resolvedRoot)) {+ throw new SymlinkEscapeError(`path resolves outside ${rootDir}`);+ }+ cur = parent;+ }+ }+}++/**+ * True when `canonical` (already confirmed within `canonicalRoot`) sits inside+ * the root-level `.git` (git internals) or `.ok` (per-machine state) tree. Only+ * the two ROOT-level trees are matched — a nested `<folder>/.ok/` holding folder+ * metadata is legitimate content-adjacent state and is intentionally allowed.+ */+function resolvesIntoInternalStateDir(canonical: string, canonicalRoot: string): boolean {+ const rel = toPosix(relative(canonicalRoot, canonical));+ if (rel === '' || rel.startsWith('..')) return false;+ const first = rel.split('/')[0];+ return first === '.git' || first === '.ok';+}diff --git a/packages/server/src/sync-engine.test.ts b/packages/server/src/sync-engine.test.tsindex 73824beea..91592d86b 100644--- a/packages/server/src/sync-engine.test.ts+++ b/packages/server/src/sync-engine.test.ts@@ -9,7 +9,7 @@* detection) belong in a future integration test that spins up a bare git repo.*/-import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';// This suite runs in CI despite oven-sh/bun#11892 (Bun fails to kill/reap// spawned child processes on GitHub Actions runners; still open upstream).@@ -21,16 +21,29 @@ import { afterEach, beforeEach, describe, expect, test } from 'vitest';// narrow to a targeted skip of the specific live-git describe blocks —// do not restore a blanket process.env.CI gate.-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { execFile } from 'node:child_process';+import {+ chmodSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { LOCAL_DIR } from '@inkeep/open-knowledge-core';+import { promisify } from 'node:util';+import { LOCAL_DIR, type SyncMode, SyncStatusSchema } from '@inkeep/open-knowledge-core';import simpleGit from 'simple-git';import { classifyGitError } from './error-classification.ts';import { listNames } from './git-paths.ts';-import type { DetectGhFn } from './github-permissions.ts';-import type { SyncState } from './sync-engine.ts';-import { SyncEngine } from './sync-engine.ts';+import type { DetectGhFn, ProbeTokenStore } from './github-permissions.ts';+import { getLogger } from './logger.ts';+import { classifyFastForwardRefusal, SyncEngine, type SyncState } from './sync-engine.ts';++const execFileAsync = promisify(execFile);// ─── Minimal ContentFilter stub ───────────────────────────────────────────────@@ -39,6 +52,32 @@ const stubContentFilter = {isDirExcluded: (_path: string) => false,};+// Capture the engine's structured pino telemetry so a test can assert the+// bounded field shape of a log emitted by a real cycle. `getLogger` caches by+// name, so the spy intercepts the same instance the module captured at import.+interface CapturedLog {+ data: Record<string, unknown>;+ msg: string;+}+function captureSyncLogs(): { entries: CapturedLog[]; restore: () => void } {+ const entries: CapturedLog[] = [];+ const logger = getLogger('sync-engine');+ const record =+ (defaultMsg: string) =>+ (data: unknown, msg?: string): void => {+ entries.push({ data: (data ?? {}) as Record<string, unknown>, msg: msg ?? defaultMsg });+ };+ const infoSpy = vi.spyOn(logger, 'info').mockImplementation(record('') as never);+ const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(record('') as never);+ return {+ entries,+ restore: () => {+ infoSpy.mockRestore();+ warnSpy.mockRestore();+ },+ };+}+// ─── Temp dir fixtures ────────────────────────────────────────────────────────let tmpDir = '';@@ -59,12 +98,15 @@ afterEach(() => {rmSync(tmpDir, { recursive: true, force: true });});-function makeEngine(opts: { syncEnabled?: boolean; onStateChange?: (s: SyncState) => void } = {}) {+function makeEngine(+ opts: { syncEnabled?: boolean; mode?: SyncMode; onStateChange?: (s: SyncState) => void } = {},+) {return new SyncEngine({projectDir,contentDir,contentFilter: stubContentFilter,syncEnabled: opts.syncEnabled,+ mode: opts.mode,onStateChange: opts.onStateChange,});}@@ -112,12 +154,17 @@ function fakeProbe(...sequence: Array<import('./github-permissions.ts').PushPermreturn rec;}-function makeProbeEngine(opts: { syncEnabled?: boolean; fakeProbe: FakeProbeRecorder['fn'] }) {+function makeProbeEngine(opts: {+ syncEnabled?: boolean;+ mode?: SyncMode;+ fakeProbe: FakeProbeRecorder['fn'];+}) {return new SyncEngine({projectDir,contentDir,contentFilter: stubContentFilter,syncEnabled: opts.syncEnabled,+ mode: opts.mode,checkPushPermissionFn: opts.fakeProbe,});}@@ -630,6 +677,36 @@ describe('SyncEngine ConflictStore admission (content-only)', () => {}});+ test('a commit failure after auto-resolving a non-content conflict reports error, not success', async () => {+ await setupDivergence('modify');+ // A failing pre-commit hook rejects the merge-completion `git commit --no-edit`+ // after `.mcp.json` auto-resolves cleanly. simple-git does NOT throw on that+ // non-zero exit, so the engine must confirm the merge actually completed+ // (MERGE_HEAD cleared) rather than reporting a successful pull over a+ // half-merged tree.+ const hookPath = join(projectDir, '.git', 'hooks', 'pre-commit');+ writeFileSync(hookPath, '#!/bin/sh\nexit 1\n', { mode: 0o755 });+ chmodSync(hookPath, 0o755);++ const engine = makeEngineForConflict();+ try {+ await engine.start();+ const outcome = await engine.pullOnce();++ // The commit was rejected and the merge aborted: the outcome must be the+ // error class (not 'succeeded'), pullError must surface it, and no+ // half-merged residue may remain.+ expect(outcome).toBe('error');+ const status = engine.getStatus();+ expect(status.lastPullOutcome).toBe('error');+ expect(status.pullError ?? '').not.toBe('');+ expect(status.state).toBe('idle');+ expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(false);+ } finally {+ await engine.destroy();+ }+ });+test('modify/delete on .mcp.json aborts the merge and pauses without ConflictStore entry', async () => {await setupDivergence('delete');@@ -1148,6 +1225,94 @@ describe('SyncEngine backoff thresholds via persisted state', () => {});});+// ─── Auth-conditional pull cadence ──────────────────────────────────────────++describe('SyncEngine pull-only cadence (auth-conditional)', () => {+ // The scheduled pull delay carries ±15% jitter, so assert on the tier band+ // (base 30s vs the anonymous 180s floor) rather than an exact value.+ const AUTHENTICATED_BAND = { min: 30 * 0.85 * 1000, max: 30 * 1.15 * 1000 };+ const ANONYMOUS_BAND = { min: 180 * 0.85 * 1000, max: 180 * 1.15 * 1000 };++ type CadenceInternals = {+ refreshAuthTier(): Promise<void>;+ effectivePullDelayMs(): number;+ };++ function makeCadenceEngine(opts: {+ mode: SyncMode;+ detectGh?: DetectGhFn;+ tokenStore?: ProbeTokenStore | null;+ }) {+ return new SyncEngine({+ projectDir,+ contentDir,+ contentFilter: stubContentFilter,+ mode: opts.mode,+ pullIntervalSeconds: 30,+ pushIntervalSeconds: 99999,+ detectGh: opts.detectGh,+ tokenStore: opts.tokenStore,+ });+ }++ /** Resolve the auth tier, then read the delay the engine would schedule. */+ async function scheduledPullDelayMs(engine: SyncEngine): Promise<number> {+ const internals = engine as unknown as CadenceInternals;+ await internals.refreshAuthTier();+ return internals.effectivePullDelayMs();+ }++ test('an anonymous follower schedules pulls at the gentle cadence', async () => {+ const engine = makeCadenceEngine({ mode: 'follow' }); // no gh, no token store+ const delayMs = await scheduledPullDelayMs(engine);+ expect(delayMs).toBeGreaterThanOrEqual(ANONYMOUS_BAND.min);+ expect(delayMs).toBeLessThanOrEqual(ANONYMOUS_BAND.max);+ });++ test('a gh-authenticated follower keeps the responsive cadence', async () => {+ const engine = makeCadenceEngine({+ mode: 'follow',+ detectGh: () => ({ available: true, token: 'gh-token' }),+ });+ const delayMs = await scheduledPullDelayMs(engine);+ expect(delayMs).toBeGreaterThanOrEqual(AUTHENTICATED_BAND.min);+ expect(delayMs).toBeLessThanOrEqual(AUTHENTICATED_BAND.max);+ });++ test('a follower authenticated only through the token store keeps the responsive cadence', async () => {+ const engine = makeCadenceEngine({+ mode: 'follow',+ tokenStore: { get: async () => ({ token: 'store-token' }) },+ });+ const delayMs = await scheduledPullDelayMs(engine);+ expect(delayMs).toBeGreaterThanOrEqual(AUTHENTICATED_BAND.min);+ expect(delayMs).toBeLessThanOrEqual(AUTHENTICATED_BAND.max);+ });++ test('a token-store read failure degrades to the gentle cadence', async () => {+ const engine = makeCadenceEngine({+ mode: 'follow',+ tokenStore: {+ get: async () => {+ throw new Error('EACCES');+ },+ },+ });+ const delayMs = await scheduledPullDelayMs(engine);+ expect(delayMs).toBeGreaterThanOrEqual(ANONYMOUS_BAND.min);+ expect(delayMs).toBeLessThanOrEqual(ANONYMOUS_BAND.max);+ });++ test('full-sync cadence is untouched even with no credentials', async () => {+ // A credential-less full-sync engine must still schedule at the base+ // interval: the anonymous floor applies only to pull-only followers.+ const engine = makeCadenceEngine({ mode: 'full' });+ const delayMs = await scheduledPullDelayMs(engine);+ expect(delayMs).toBeGreaterThanOrEqual(AUTHENTICATED_BAND.min);+ expect(delayMs).toBeLessThanOrEqual(AUTHENTICATED_BAND.max);+ });+});+// ─── Lifecycle edge cases ───────────────────────────────────────────────────describe('SyncEngine lifecycle edge cases', () => {@@ -2022,3 +2187,1763 @@ describe('SyncEngine gh-token credential relay', () => {expect(detect.calls()).toBe(2);});});++// ─── Sync mode representation ─────────────────────────────────────────────────++describe('SyncEngine sync mode', () => {+ test('constructing with a mode reports it in status', () => {+ expect(makeEngine({ mode: 'follow' }).getStatus().syncMode).toBe('follow');+ expect(makeEngine({ mode: 'full' }).getStatus().syncMode).toBe('full');+ expect(makeEngine({ mode: 'off' }).getStatus().syncMode).toBe('off');+ });++ test('syncEnabled is true for pull and full, false for off', () => {+ // syncEnabled is the "is sync on at all" boolean; both directional modes are+ // "on". Consumers that must branch on push capability read syncMode instead.+ expect(makeEngine({ mode: 'follow' }).getStatus().syncEnabled).toBe(true);+ expect(makeEngine({ mode: 'full' }).getStatus().syncEnabled).toBe(true);+ expect(makeEngine({ mode: 'off' }).getStatus().syncEnabled).toBe(false);+ });++ test('legacy syncEnabled option maps to a mode (true→full, else off)', () => {+ expect(makeEngine({ syncEnabled: true }).getStatus().syncMode).toBe('full');+ expect(makeEngine({ syncEnabled: false }).getStatus().syncMode).toBe('off');+ expect(makeEngine({}).getStatus().syncMode).toBe('off');+ });++ test('setEnabled adapter maps to a mode (true→full, false→off)', async () => {+ const engine = makeEngine({ mode: 'off' });+ try {+ await engine.setEnabled(true);+ expect(engine.getStatus().syncMode).toBe('full');+ await engine.setEnabled(false);+ expect(engine.getStatus().syncMode).toBe('off');+ } finally {+ await engine.destroy();+ }+ });++ test('setMode records the new mode', async () => {+ const engine = makeEngine({ mode: 'off' });+ try {+ await engine.setMode('follow');+ expect(engine.getStatus().syncMode).toBe('follow');+ } finally {+ await engine.destroy();+ }+ });++ test('setMode is a no-op on a same-value call', async () => {+ const states: SyncState[] = [];+ const engine = makeEngine({ mode: 'off', onStateChange: (s) => states.push(s) });+ try {+ await engine.setMode('off');+ expect(states).toEqual([]);+ expect(engine.getStatus().syncMode).toBe('off');+ } finally {+ await engine.destroy();+ }+ });++ test('getStatus() output conforms to the wire schema and carries syncMode', () => {+ // getStatus() is exactly what the /api/sync/status handler serializes+ // (successResponse validates it against SyncStatusSchema), so parsing it+ // against that schema pins the server-output ↔ wire-contract seam.+ const parsed = SyncStatusSchema.safeParse(makeEngine({ mode: 'follow' }).getStatus());+ expect(parsed.success).toBe(true);+ expect(parsed.success && parsed.data.syncMode).toBe('follow');+ });+});++// ─── Pull-only mode ───────────────────────────────────────────────────────────+//+// A pull-only project fetches and fast-forwards but is never pushed for. These+// tests use real bare-origin + clone fixtures so the fetch/FF path runs for+// real, and pin the two push-side guarantees: (1) the push cycle never runs, so+// protected-branch — a push-only pause — is unreachable; (2) a denied push probe+// does not park the engine (pull-only expects to lack push).+//+// Under pull-only the legacy dirty-tree merge path does not run: the FF-only B1+// cycle below replaces it, never committing or stashing on the user's behalf, so+// the dirty-merge that produces the self-heal pause cannot arise for this mode.++describe('SyncEngine pull-only mode', () => {+ async function seedBareOrigin(): Promise<string> {+ 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');+ return bareDir;+ }++ test('pull cycle fast-forwards the clone to origin tip and updates the working tree', async () => {+ const bareDir = await seedBareOrigin();++ // A sister seeds origin, the project clones it, then the sister advances+ // origin by one commit — leaving the project one commit behind.+ 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, 'doc.md'), 'v1\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 });++ writeFileSync(join(sisterDir, 'doc.md'), 'v1\nv2\n', 'utf-8');+ await sister.add('.');+ await sister.commit('advance');+ await sister.push('origin', 'main');+ const originTip = (await sister.revparse(['HEAD'])).trim();++ const engine = new SyncEngine({+ projectDir,+ contentDir: projectDir,+ contentFilter: stubContentFilter,+ mode: 'follow',+ });+ try {+ await engine.start();+ await engine.trigger('pull');++ const project = simpleGit(projectDir);+ expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);+ expect(readFileSync(join(projectDir, 'doc.md'), 'utf-8')).toBe('v1\nv2\n');+ // A fast-forward creates no commit and leaves no merge in progress.+ expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(false);+ expect(engine.getStatus().state).toBe('idle');+ } finally {+ await engine.destroy();+ }+ });++ test('never pushes local commits (push cycle is gated off)', async () => {+ const git = simpleGit(projectDir);+ await git.init(['--initial-branch=main']);+ await git.raw('config', 'user.name', 'Test');+ await git.raw('config', 'user.email', '[email protected]');+ writeFileSync(join(projectDir, 'README.md'), '# seed\n');+ await git.add('.');+ await git.commit('seed');++ const bareDir = await seedBareOrigin();+ await git.addRemote('origin', bareDir);+ await git.push(['--set-upstream', 'origin', 'main']);+ const originBefore = (await git.revparse(['origin/main'])).trim();++ // A local commit the project has not pushed. Full sync would push it; a+ // pull-only project must leave it local.+ writeFileSync(join(projectDir, 'README.md'), '# seed\n\nlocal edit\n');+ await git.add('.');+ await git.commit('local commit not pushed');+ expect((await git.revparse(['HEAD'])).trim()).not.toBe(originBefore);++ const engine = new SyncEngine({+ projectDir,+ contentDir: projectDir,+ contentFilter: stubContentFilter,+ mode: 'follow',+ });+ try {+ await engine.start();+ // Both a direct push trigger and a full sync (push-then-pull) must leave+ // origin untouched — the push gate makes the push cycle a no-op.+ await engine.trigger('push');+ await engine.trigger('sync');++ expect((await git.revparse(['origin/main'])).trim()).toBe(originBefore);+ const status = engine.getStatus();+ expect(status.lastPushedSha).toBeNull();+ // protected-branch is a push-rejection pause; with the push cycle gated+ // off it can never be classified, so it is structurally unreachable here.+ expect(status.pausedReason).not.toBe('protected-branch');+ } finally {+ await engine.destroy();+ }+ });++ test('a denied push probe keeps the engine pulling (no pause)', async () => {+ await initGitWithOrigin();+ const probe = fakeProbe({ kind: 'denied', reason: 'no-collaborator' });+ const engine = makeProbeEngine({ mode: 'follow', fakeProbe: probe.fn });+ try {+ await engine.start();+ await waitForPushPermissionResolved(engine);+ const status = engine.getStatus();+ expect(status.pushPermission).toEqual({+ checkStatus: 'denied',+ deniedReason: 'no-collaborator',+ });+ // Pull-only expects to lack push — denial is its normal condition, so the+ // engine stays idle and keeps its scheduled pulls rather than parking.+ expect(status.state).not.toBe('disabled');+ expect(status.pausedReason).not.toBe('no-push-permission');+ expect(status.syncMode).toBe('follow');+ } finally {+ await engine.destroy();+ }+ });++ test('a denied push probe still pauses a full-sync engine (unchanged behavior)', async () => {+ await initGitWithOrigin();+ const probe = fakeProbe({ kind: 'denied', reason: 'no-collaborator' });+ const engine = makeProbeEngine({ mode: 'full', fakeProbe: probe.fn });+ try {+ await engine.start();+ await waitForPushPermissionResolved(engine);+ const status = engine.getStatus();+ expect(status.state).toBe('disabled');+ expect(status.pausedReason).toBe('no-push-permission');+ } finally {+ await engine.destroy();+ }+ });+});++// ─── Pull-only B1 fast-forward cycle ───────────────────────────────────────────+//+// The B1 cycle fast-forwards a pull-only clone to origin's tip while any+// uncommitted local edits ride along as a working-tree overlay, and it never+// commits, merges, stashes, or leaves a MERGE_HEAD. These tests drive the real+// git fetch/FF path against bare-origin + clone fixtures and pin the overlay+// matrix from the spike: non-overlap rides through, byte-identical converges,+// same-file overlap keeps-mine on the new tip, and — the asymmetric git guard —+// a locally-deleted file the tip modifies is NOT resurrected.++describe('SyncEngine pull-only B1 fast-forward cycle', () => {+ async function seedBareOrigin(): Promise<string> {+ 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');+ return bareDir;+ }++ /**+ * Seed origin from a sister clone, clone it into `projectDir`, then advance+ * origin — leaving the project one commit behind. `advance` values: a string+ * rewrites the file, `null` deletes it on origin. Returns origin's tip SHA and+ * the sister handle (so a caller can advance origin further).+ */+ async function cloneBehindOrigin(opts: {+ seed: Record<string, string>;+ advance: Record<string, string | null>;+ }): Promise<{ originTip: string; bareDir: string }> {+ 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]');+ for (const [f, c] of Object.entries(opts.seed)) writeFileSync(join(sisterDir, f), c, '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 });++ for (const [f, c] of Object.entries(opts.advance)) {+ if (c === null) rmSync(join(sisterDir, f), { force: true });+ else writeFileSync(join(sisterDir, f), c, 'utf-8');+ }+ await sister.raw(['add', '-A']);+ await sister.commit('advance');+ await sister.push('origin', 'main');+ return { originTip: (await sister.revparse(['HEAD'])).trim(), bareDir };+ }++ function makePullEngine(+ opts: {+ onContentConflictsResolved?: (files: string[]) => void | Promise<void>;+ onContentConflictsDetected?: (files: string[]) => void | Promise<void>;+ } = {},+ ) {+ return new SyncEngine({+ projectDir,+ contentDir: projectDir,+ contentFilter: stubContentFilter,+ mode: 'follow',+ onContentConflictsResolved: opts.onContentConflictsResolved,+ onContentConflictsDetected: opts.onContentConflictsDetected,+ });+ }++ /** No commit, no merge in progress, no stash — the B1 no-side-effect contract. */+ async function assertNoGitResidue(): Promise<void> {+ expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(false);+ const stashList = await simpleGit(projectDir).raw(['stash', 'list']);+ expect(stashList.trim()).toBe('');+ }++ test('non-overlapping local edit survives the fast-forward', async () => {+ // Local uncommitted edit to a.md; origin advances b.md. The FF brings b.md+ // and leaves a.md's overlay untouched.+ const { originTip } = await cloneBehindOrigin({+ seed: { 'a.md': 'A1\n', 'b.md': 'B1\n' },+ advance: { 'b.md': 'B1\nB2\n' },+ });+ writeFileSync(join(projectDir, 'a.md'), 'A1\nLOCAL\n', 'utf-8');++ const engine = makePullEngine();+ try {+ await engine.start();+ await engine.trigger('pull');++ const project = simpleGit(projectDir);+ expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);+ expect(readFileSync(join(projectDir, 'b.md'), 'utf-8')).toBe('B1\nB2\n');+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('A1\nLOCAL\n');+ // git status shows only the overlay file dirty.+ expect(await listNames(project, ['diff-index', '--name-only', 'HEAD'])).toEqual(['a.md']);+ await assertNoGitResidue();+ expect(engine.getStatus().state).toBe('idle');+ } finally {+ await engine.destroy();+ }+ });++ test('a byte-identical overlay converges silently', async () => {+ // The local edit equals origin's incoming bytes. git's FF guard would refuse+ // (it compares worktree-vs-HEAD, not vs the tip), so the cycle must restore+ // and let the FF re-materialise the identical bytes — leaving a clean tree.+ const { originTip } = await cloneBehindOrigin({+ seed: { 'a.md': 'v1\n' },+ advance: { 'a.md': 'v1\nv2\n' },+ });+ writeFileSync(join(projectDir, 'a.md'), 'v1\nv2\n', 'utf-8');++ const engine = makePullEngine();+ try {+ await engine.start();+ await engine.trigger('pull');++ const project = simpleGit(projectDir);+ expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('v1\nv2\n');+ // Converged: the file matches the new tip, so the tree is clean.+ expect(await listNames(project, ['diff-index', '--name-only', 'HEAD'])).toEqual([]);+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ });++ test('a locally-deleted content file the tip modifies is restored from origin', async () => {+ // Pull-only follows upstream: a locally-deleted content doc the tip modified+ // yields to the remote's change and is restored at origin's version (nothing+ // authored is lost — the local side was a deletion). Not conflicted, not gone.+ const { originTip } = await cloneBehindOrigin({+ seed: { 'a.md': 'C1\n', 'keep.md': 'K1\n' },+ advance: { 'a.md': 'C1\nC2\n', 'keep.md': 'K1\nK2\n' },+ });+ rmSync(join(projectDir, 'a.md'), { force: true });++ const engine = makePullEngine();+ try {+ await engine.start();+ await engine.trigger('pull');++ const project = simpleGit(projectDir);+ expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);+ // Restored at origin's version — the deletion yielded to upstream.+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('C1\nC2\n');+ // The non-overlapping origin change still landed.+ expect(readFileSync(join(projectDir, 'keep.md'), 'utf-8')).toBe('K1\nK2\n');+ expect(engine.getConflicts()).toEqual([]);+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ });++ test('a locally-deleted NON-content file the tip modifies stays deleted', async () => {+ // The follow-upstream restore is scoped to content docs. A non-content file+ // (config/asset) deleted locally keeps its deletion even when origin edits it.+ const { originTip } = await cloneBehindOrigin({+ seed: { 'cfg.json': '{"a":1}\n', 'keep.md': 'K1\n' },+ advance: { 'cfg.json': '{"a":2}\n', 'keep.md': 'K1\nK2\n' },+ });+ rmSync(join(projectDir, 'cfg.json'), { force: true });++ const engine = makePullEngine();+ try {+ await engine.start();+ await engine.trigger('pull');++ const project = simpleGit(projectDir);+ expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);+ // Deletion preserved for the non-content file; the .md change still landed.+ expect(existsSync(join(projectDir, 'cfg.json'))).toBe(false);+ expect(readFileSync(join(projectDir, 'keep.md'), 'utf-8')).toBe('K1\nK2\n');+ expect(engine.getConflicts()).toEqual([]);+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ });++ test('same-file overlap keeps the local edit while the branch reaches origin tip', async () => {+ // Local and origin both rewrite a.md's first line (a genuine overlap); origin+ // also advances b.md (non-overlapping). The branch fast-forwards to the tip,+ // b.md updates, and a.md keeps the local overlay — with no commit created.+ const { originTip } = await cloneBehindOrigin({+ seed: { 'a.md': 'line1\nline2\n', 'b.md': 'B1\n' },+ advance: { 'a.md': 'ORIGIN1\nline2\n', 'b.md': 'B1\nB2\n' },+ });+ writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');++ const engine = makePullEngine();+ try {+ await engine.start();+ await engine.trigger('pull');++ const project = simpleGit(projectDir);+ expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);+ expect(readFileSync(join(projectDir, 'b.md'), 'utf-8')).toBe('B1\nB2\n');+ // keep-mine: the local overlay rides on the advanced tip.+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nline2\n');+ expect(await listNames(project, ['diff-index', '--name-only', 'HEAD'])).toEqual(['a.md']);+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ });++ test('checkpoints the overlay before the reset, capturing the pre-reset bytes', async () => {+ // Same-file overlap: the cycle resets a.md to HEAD before the FF, then+ // re-writes the overlay. The checkpoint must fire BEFORE the reset, while the+ // local bytes are still on disk, so a crash in the reset->rewrite window+ // leaves them recoverable on the shadow timeline.+ const { originTip } = await cloneBehindOrigin({+ seed: { 'a.md': 'line1\nline2\n' },+ advance: { 'a.md': 'ORIGIN1\nline2\n' },+ });+ writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');++ const seen: Array<{ paths: number; bytesAtCheckpoint: string }> = [];+ const engine = new SyncEngine({+ projectDir,+ contentDir: projectDir,+ contentFilter: stubContentFilter,+ mode: 'follow',+ checkpointBeforeOverlayRestore: ({ paths }) => {+ seen.push({ paths, bytesAtCheckpoint: readFileSync(join(projectDir, 'a.md'), 'utf-8') });+ },+ });+ try {+ await engine.start();+ await engine.trigger('pull');++ expect(seen).toHaveLength(1);+ expect(seen[0]?.paths).toBe(1);+ // Ordering proof: the overlay was still on disk when the checkpoint ran.+ expect(seen[0]?.bytesAtCheckpoint).toBe('LOCAL1\nline2\n');+ // The cycle still completed normally.+ const project = simpleGit(projectDir);+ expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nline2\n');+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ });++ test('does not checkpoint when the pull has no overlapping edit', async () => {+ // Non-overlapping overlay (local a.md, origin advances b.md): no reset, no+ // crash window, so no checkpoint is owed.+ const { originTip } = await cloneBehindOrigin({+ seed: { 'a.md': 'A1\n', 'b.md': 'B1\n' },+ advance: { 'b.md': 'B1\nB2\n' },+ });+ writeFileSync(join(projectDir, 'a.md'), 'A1\nLOCAL\n', 'utf-8');++ let calls = 0;+ const engine = new SyncEngine({+ projectDir,+ contentDir: projectDir,+ contentFilter: stubContentFilter,+ mode: 'follow',+ checkpointBeforeOverlayRestore: () => {+ calls += 1;+ },+ });+ try {+ await engine.start();+ await engine.trigger('pull');++ expect(calls).toBe(0);+ const project = simpleGit(projectDir);+ expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);+ } finally {+ await engine.destroy();+ }+ });++ test('a failing overlay checkpoint does not abort the cycle', async () => {+ // The checkpoint is a best-effort safety net: a failure forfeits only the+ // crash-window recovery, so the pull must still fast-forward and keep-mine.+ const { originTip } = await cloneBehindOrigin({+ seed: { 'a.md': 'line1\nline2\n' },+ advance: { 'a.md': 'ORIGIN1\nline2\n' },+ });+ writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');++ const engine = new SyncEngine({+ projectDir,+ contentDir: projectDir,+ contentFilter: stubContentFilter,+ mode: 'follow',+ checkpointBeforeOverlayRestore: () => {+ throw new Error('shadow unavailable');+ },+ });+ try {+ await engine.start();+ await engine.trigger('pull');++ const project = simpleGit(projectDir);+ expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nline2\n');+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ });++ test('refuses to write an overlay through a symlink escaping the repo, and surfaces the failure', async () => {+ // A git remote is untrusted: it can turn a tracked content file the follower+ // also edited into a symlink pointing outside the working tree. After the FF+ // materialises the link, re-applying the overlay must refuse (realpath+ // escape) rather than following it out of the repo — and must surface an+ // error, not report a clean pull.+ 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');+ 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 });++ // Follower edits a.md locally — the overlay the cycle will try to re-apply.+ writeFileSync(join(projectDir, 'a.md'), 'A1\nLOCAL\n', 'utf-8');++ // Origin replaces a.md with a symlink to a file OUTSIDE the repo.+ const escapeTarget = join(tmpDir, 'escape-target.txt');+ writeFileSync(escapeTarget, 'PRECIOUS\n', 'utf-8');+ rmSync(join(sisterDir, 'a.md'), { force: true });+ symlinkSync(escapeTarget, join(sisterDir, 'a.md'));+ await sister.raw(['add', '-A']);+ await sister.commit('a.md -> escape');+ await sister.push('origin', 'main');++ const engine = makePullEngine();+ try {+ await engine.start();+ await engine.trigger('pull');++ // Containment: the out-of-repo file was NOT overwritten with the overlay.+ expect(readFileSync(escapeTarget, 'utf-8')).toBe('PRECIOUS\n');+ // Surfaced as an error outcome — not a clean 'succeeded'/'conflict' idle.+ expect(engine.getStatus().lastPullOutcome).toBe('error');+ } finally {+ await engine.destroy();+ }+ });++ test('diverged local history pauses instead of merging', async () => {+ // A local commit ahead of origin cannot fast-forward. Pull-only refuses to+ // merge/commit it — the branch stays put and a bounded paused reason surfaces.+ const { bareDir } = await cloneBehindOrigin({+ seed: { 'a.md': 'v1\n' },+ advance: { 'a.md': 'v1\nORIGIN\n' },+ });+ const project = simpleGit(projectDir);+ await project.raw('config', 'user.name', 'Follower');+ await project.raw('config', 'user.email', '[email protected]');+ writeFileSync(join(projectDir, 'a.md'), 'v1\nLOCAL COMMIT\n', 'utf-8');+ await project.add('.');+ await project.commit('local commit ahead');+ const localTip = (await project.revparse(['HEAD'])).trim();++ const engine = makePullEngine();+ try {+ await engine.start();+ await engine.trigger('pull');++ // Branch unchanged (not fast-forwarded onto origin), no merge commit made.+ expect((await project.revparse(['HEAD'])).trim()).toBe(localTip);+ expect(engine.getStatus().pausedReason).toBe('diverged-local-commits');+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ expect(bareDir).toContain('bare.git'); // fixture sanity+ });++ test('different-line edits to the same file auto-combine with no conflict', async () => {+ // Local edits the first line; origin edits the third line. diff3 combines+ // them into one overlay with no prompt.+ const { originTip } = await cloneBehindOrigin({+ seed: { 'a.md': 'L1\nL2\nL3\n' },+ advance: { 'a.md': 'L1\nL2\nORIGIN3\n' },+ });+ writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nL2\nL3\n', 'utf-8');++ const engine = makePullEngine();+ try {+ await engine.start();+ await engine.trigger('pull');++ const project = simpleGit(projectDir);+ expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);+ // Both edits present in the combined overlay.+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nL2\nORIGIN3\n');+ expect(engine.getConflicts()).toEqual([]);+ expect(engine.getStatus().state).toBe('idle');+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ });++ test('same-line collision raises a pinned working-tree conflict and never forks', async () => {+ const { originTip } = await cloneBehindOrigin({+ seed: { 'a.md': 'line1\nline2\n' },+ advance: { 'a.md': 'ORIGIN1\nline2\n' },+ });+ writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');++ const engine = makePullEngine();+ try {+ await engine.start();+ await engine.trigger('pull');++ const project = simpleGit(projectDir);+ // Branch reached origin tip; local overlay kept on disk; no commit.+ expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nline2\n');+ await assertNoGitResidue();++ const conflicts = engine.getConflicts();+ expect(conflicts).toHaveLength(1);+ expect(conflicts[0]?.file).toBe('a.md');+ expect(conflicts[0]?.variant).toBe('working-tree');+ expect(conflicts[0]?.theirsSha).toMatch(/^[0-9a-f]{40}$/);+ expect(conflicts[0]?.baseSha).toMatch(/^[0-9a-f]{40}$/);+ // The engine stays idle, not paused, so the rest of the repo keeps pulling.+ expect(engine.getStatus().state).toBe('idle');+ } finally {+ await engine.destroy();+ }+ });++ test('a non-content overlap keeps the local edit without raising a conflict', async () => {+ // A `.json` config is not an OK content doc, so a same-line overlap keeps the+ // local edit verbatim (never line-merged) and is never surfaced as a conflict+ // the user has no editor to resolve.+ const { originTip } = await cloneBehindOrigin({+ seed: { 'config.json': '{"a":1}\n' },+ advance: { 'config.json': '{"a":2}\n' },+ });+ writeFileSync(join(projectDir, 'config.json'), '{"a":3}\n', 'utf-8');++ const engine = makePullEngine();+ try {+ await engine.start();+ await engine.trigger('pull');++ const project = simpleGit(projectDir);+ expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);+ expect(readFileSync(join(projectDir, 'config.json'), 'utf-8')).toBe('{"a":3}\n');+ expect(engine.getConflicts()).toEqual([]);+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ });++ test('a locally-deleted content file the tip modifies is restored, not conflicted', async () => {+ const { originTip } = await cloneBehindOrigin({+ seed: { 'a.md': 'C1\n' },+ advance: { 'a.md': 'C1\nC2\n' },+ });+ rmSync(join(projectDir, 'a.md'), { force: true });++ const engine = makePullEngine();+ try {+ await engine.start();+ await engine.trigger('pull');++ const project = simpleGit(projectDir);+ expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);+ // Pull-only accepts the remote's change: the file is restored at origin's+ // version with no conflict raised.+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('C1\nC2\n');+ expect(engine.getConflicts()).toEqual([]);+ expect(engine.getStatus().state).toBe('idle');+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ });++ /** Advance origin again from the sister clone; returns the new tip SHA. */+ async function advanceOriginFrom(files: Record<string, string | null>): Promise<string> {+ const sisterDir = join(tmpDir, 'sister');+ const sister = simpleGit(sisterDir);+ for (const [f, c] of Object.entries(files)) {+ if (c === null) rmSync(join(sisterDir, f), { force: true });+ else writeFileSync(join(sisterDir, f), c, 'utf-8');+ }+ await sister.raw(['add', '-A']);+ await sister.commit('advance again');+ await sister.push('origin', 'main');+ return (await sister.revparse(['HEAD'])).trim();+ }++ test('an unresolved collision re-pins theirs to the latest tip on each pull', async () => {+ await cloneBehindOrigin({+ seed: { 'a.md': 'line1\nline2\n' },+ advance: { 'a.md': 'ORIGIN1\nline2\n' },+ });+ writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');++ const engine = makePullEngine();+ try {+ await engine.start();+ await engine.trigger('pull');+ const firstPin = engine.getConflicts()[0]?.theirsSha;+ expect(firstPin).toMatch(/^[0-9a-f]{40}$/);++ // Origin re-edits the same conflicting line; the collision persists.+ const tip2 = await advanceOriginFrom({ 'a.md': 'ORIGIN1b\nline2\n' });+ await engine.trigger('pull');++ const conflicts = engine.getConflicts();+ expect(conflicts).toHaveLength(1);+ // theirs re-pinned to the new tip's blob (resolver never shows stale content).+ expect(conflicts[0]?.theirsSha).not.toBe(firstPin);+ expect((await simpleGit(projectDir).revparse(['HEAD'])).trim()).toBe(tip2);+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nline2\n');+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ });++ test('a collision auto-dissolves when upstream converges to the local overlay', async () => {+ await cloneBehindOrigin({+ seed: { 'a.md': 'line1\nline2\n' },+ advance: { 'a.md': 'ORIGIN1\nline2\n' },+ });+ writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');++ const engine = makePullEngine();+ try {+ await engine.start();+ await engine.trigger('pull');+ expect(engine.getConflicts()).toHaveLength(1);++ // Upstream moves to match the local overlay — the collision disappears.+ const tip2 = await advanceOriginFrom({ 'a.md': 'LOCAL1\nline2\n' });+ await engine.trigger('pull');++ expect(engine.getConflicts()).toEqual([]);+ expect((await simpleGit(projectDir).revparse(['HEAD'])).trim()).toBe(tip2);+ // Converged: file matches the tip, tree clean.+ expect(await listNames(simpleGit(projectDir), ['diff-index', '--name-only', 'HEAD'])).toEqual(+ [],+ );+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ });++ test('notifies the resolved callback when a collision auto-dissolves', async () => {+ // onContentConflictsResolved is what clears an open document's conflict+ // lifecycle marker; a dropped or mis-pathed call leaves the conflict badge+ // stuck. Mirror of the auto-dissolve test, asserting the callback fires.+ await cloneBehindOrigin({+ seed: { 'a.md': 'line1\nline2\n' },+ advance: { 'a.md': 'ORIGIN1\nline2\n' },+ });+ writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');++ const resolved: string[][] = [];+ const engine = makePullEngine({+ onContentConflictsResolved: (files) => {+ resolved.push([...files]);+ },+ });+ try {+ await engine.start();+ await engine.trigger('pull');+ expect(engine.getConflicts()).toHaveLength(1);++ // Upstream moves to match the local overlay — the collision dissolves.+ await advanceOriginFrom({ 'a.md': 'LOCAL1\nline2\n' });+ await engine.trigger('pull');++ expect(engine.getConflicts()).toEqual([]);+ expect(resolved).toEqual([['a.md']]);+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ });++ test('a fast-forward refusal restores the overlay bytes (mineRestore guard)', async () => {+ // The overlapping paths are reset to HEAD before the fast-forward; if the FF+ // then refuses (a divergence the ahead-check missed), mineRestore must put+ // the user's uncommitted bytes back rather than leave HEAD's version on disk.+ await cloneBehindOrigin({+ seed: { 'a.md': 'line1\nline2\n' },+ advance: { 'a.md': 'ORIGIN1\nline2\n' },+ });+ writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');+ const headBefore = (await simpleGit(projectDir).revparse(['HEAD'])).trim();++ const engine = makePullEngine();+ // Force the FF to refuse after the overlay was reset to HEAD — the TOCTOU+ // path where ahead === 0 at plan time but the FF still can't advance.+ const ffSpy = vi+ .spyOn(engine as unknown as { fastForwardOnly: () => Promise<unknown> }, 'fastForwardOnly')+ .mockResolvedValue({+ ok: false,+ refusal: 'divergence',+ stderr: '',+ exitCode: 128,+ timedOut: false,+ });+ try {+ await engine.start();+ const outcome = await engine.pullOnce();++ expect(ffSpy).toHaveBeenCalled();+ // The overlay bytes are restored — not silently replaced with HEAD.+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nline2\n');+ expect(outcome).toBe('refused');+ expect(engine.getStatus().pausedReason).toBe('diverged-local-commits');+ // The FF never happened, so HEAD stayed put.+ expect((await simpleGit(projectDir).revparse(['HEAD'])).trim()).toBe(headBefore);+ } finally {+ await engine.destroy();+ }+ });++ test('resolving take-theirs writes the tip version and clears the conflict without committing', async () => {+ await cloneBehindOrigin({+ seed: { 'a.md': 'line1\nline2\n' },+ advance: { 'a.md': 'ORIGIN1\nline2\n' },+ });+ writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');++ const engine = makePullEngine();+ try {+ await engine.start();+ await engine.trigger('pull');+ const tip = (await simpleGit(projectDir).revparse(['HEAD'])).trim();+ expect(engine.getConflicts()).toHaveLength(1);++ await engine.resolveConflict('a.md', 'theirs');++ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('ORIGIN1\nline2\n');+ expect(engine.getConflicts()).toEqual([]);+ // Branch unchanged (still at origin tip); resolution never commits.+ expect((await simpleGit(projectDir).revparse(['HEAD'])).trim()).toBe(tip);+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ });++ test('resolving keep-mine leaves the overlay and clears the conflict without committing', async () => {+ await cloneBehindOrigin({+ seed: { 'a.md': 'line1\nline2\n' },+ advance: { 'a.md': 'ORIGIN1\nline2\n' },+ });+ writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');++ const engine = makePullEngine();+ try {+ await engine.start();+ await engine.trigger('pull');+ const tip = (await simpleGit(projectDir).revparse(['HEAD'])).trim();++ await engine.resolveConflict('a.md', 'mine');++ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nline2\n');+ expect(engine.getConflicts()).toEqual([]);+ expect((await simpleGit(projectDir).revparse(['HEAD'])).trim()).toBe(tip);+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ });++ test('a non-content overlap is never auto-committed in pull mode', async () => {+ // The merge-native path auto-resolves non-content conflicts with `--theirs`+ // and `git commit --no-edit`. Pull-only must never reach that commit: a+ // non-content overlap keeps the local edit with the branch exactly at the+ // origin tip (no extra commit).+ const { originTip } = await cloneBehindOrigin({+ seed: { '.mcp.json': '{"v":1}\n', 'a.md': 'A1\n' },+ advance: { '.mcp.json': '{"v":2}\n', 'a.md': 'A1\nA2\n' },+ });+ writeFileSync(join(projectDir, '.mcp.json'), '{"v":3}\n', 'utf-8');++ const engine = makePullEngine();+ try {+ await engine.start();+ await engine.trigger('pull');++ const project = simpleGit(projectDir);+ // HEAD is exactly origin's tip — no auto-resolve commit was minted.+ expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);+ expect(readFileSync(join(projectDir, '.mcp.json'), 'utf-8')).toBe('{"v":3}\n');+ expect(engine.getConflicts()).toEqual([]);+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ });++ test('reconcileConflictsFromGit leaves working-tree conflicts intact', async () => {+ // The batch-end reconcile keys on MERGE_HEAD, which a working-tree conflict+ // never has — it must not wipe the pull-only overlay ledger.+ await cloneBehindOrigin({+ seed: { 'a.md': 'line1\nline2\n' },+ advance: { 'a.md': 'ORIGIN1\nline2\n' },+ });+ writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');++ const engine = makePullEngine();+ try {+ await engine.start();+ await engine.trigger('pull');+ expect(engine.getConflicts()).toHaveLength(1);++ await engine.reconcileConflictsFromGit();+ expect(engine.getConflicts()).toHaveLength(1);+ } finally {+ await engine.destroy();+ }+ });++ test('a persisted working-tree conflict survives boot and keeps the engine idle', async () => {+ // A prior run left a working-tree conflict in conflicts.json. On restart the+ // engine must retain it (no MERGE_HEAD required) and stay idle — a paused+ // 'conflict' state would stop the follower pulling the rest of the repo.+ await cloneBehindOrigin({+ seed: { 'a.md': 'v1\n' },+ advance: { 'a.md': 'v1\nv2\n' },+ });+ const blob = (await simpleGit(projectDir).raw(['rev-parse', 'HEAD:a.md'])).trim();+ writeFileSync(+ join(okDir, 'conflicts.json'),+ JSON.stringify({+ version: 1,+ branch: 'main',+ conflicts: [+ {+ file: 'a.md',+ detectedAt: new Date().toISOString(),+ variant: 'working-tree',+ theirsSha: blob,+ baseSha: blob,+ },+ ],+ }),+ 'utf-8',+ );++ const engine = makePullEngine();+ try {+ await engine.start();+ expect(engine.getConflicts().map((c) => c.file)).toEqual(['a.md']);+ expect(engine.getStatus().state).toBe('idle');+ } finally {+ await engine.destroy();+ }+ });+});++// ─── Pull-only mode transitions (stranded-commit conversion) ───────────────────+//+// Entering pull-only with local commits ahead of origin folds those commits into+// a working-tree overlay and realigns the branch: a `--mixed` reset moves the ref+// without touching the working tree, so on-screen content is byte-identical and+// nothing is committed on the user's behalf. These tests use real bare-origin ++// clone fixtures so the reset, fast-forward, and push all run for real.++describe('SyncEngine pull-only mode transitions', () => {+ async function seedBareOrigin(): Promise<string> {+ 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');+ return bareDir;+ }++ /** Seed origin from a sister clone and clone it into projectDir. */+ async function seedAndClone(seed: Record<string, string>): Promise<{+ seedTip: string;+ bareDir: string;+ sister: ReturnType<typeof simpleGit>;+ sisterDir: string;+ }> {+ 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]');+ for (const [f, c] of Object.entries(seed)) writeFileSync(join(sisterDir, f), c, 'utf-8');+ await sister.add('.');+ await sister.commit('seed');+ await sister.addRemote('origin', bareDir);+ await sister.push('origin', 'main');+ const seedTip = (await sister.revparse(['HEAD'])).trim();++ rmSync(projectDir, { recursive: true, force: true });+ await simpleGit(tmpDir).clone(bareDir, projectDir);+ mkdirSync(okDir, { recursive: true });+ const project = simpleGit(projectDir);+ await project.raw('config', 'user.name', 'Follower');+ await project.raw('config', 'user.email', '[email protected]');+ return { seedTip, bareDir, sister, sisterDir };+ }++ async function advanceOrigin(+ sister: ReturnType<typeof simpleGit>,+ sisterDir: string,+ files: Record<string, string | null>,+ ): Promise<string> {+ for (const [f, c] of Object.entries(files)) {+ if (c === null) rmSync(join(sisterDir, f), { force: true });+ else writeFileSync(join(sisterDir, f), c, 'utf-8');+ }+ await sister.raw(['add', '-A']);+ await sister.commit('advance');+ await sister.push('origin', 'main');+ return (await sister.revparse(['HEAD'])).trim();+ }++ /** Commit local edits in projectDir, returning the new HEAD sha. */+ async function commitLocal(files: Record<string, string>, msg: string): Promise<string> {+ const project = simpleGit(projectDir);+ for (const [f, c] of Object.entries(files)) writeFileSync(join(projectDir, f), c, 'utf-8');+ await project.add('.');+ await project.commit(msg);+ return (await project.revparse(['HEAD'])).trim();+ }++ function makeEngineMode(+ mode: SyncMode,+ checkpoint?: (ctx: { branch: string; ahead: number }) => void | Promise<void>,+ ) {+ return new SyncEngine({+ projectDir,+ contentDir: projectDir,+ contentFilter: stubContentFilter,+ mode,+ pullIntervalSeconds: 99999,+ pushIntervalSeconds: 99999,+ checkpointBeforeStrandedConversion: checkpoint,+ });+ }++ /** Poll until projectDir's HEAD reaches `sha` (event-driven, not a fixed wait). */+ async function waitForHead(sha: string, timeoutMs = 5000): Promise<void> {+ const deadline = Date.now() + timeoutMs;+ const project = simpleGit(projectDir);+ while ((await project.revparse(['HEAD'])).trim() !== sha) {+ if (Date.now() > deadline) throw new Error(`HEAD did not reach ${sha} within ${timeoutMs}ms`);+ await new Promise((r) => setTimeout(r, 20));+ }+ }++ async function assertNoGitResidue(): Promise<void> {+ expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(false);+ const stashList = await simpleGit(projectDir).raw(['stash', 'list']);+ expect(stashList.trim()).toBe('');+ }++ test('a failed stranded-commit conversion surfaces the divergence instead of a clean idle', async () => {+ await seedAndClone({ 'a.md': 'A1\n' });+ // Two committed-but-unpushed edits (ahead 2, behind 0).+ await commitLocal({ 'a.md': 'A1\nLOCAL2\n' }, 'local 1');+ await commitLocal({ 'a.md': 'A1\nLOCAL2\nLOCAL3\n' }, 'local 2');+ // A stale index.lock makes the `git reset --mixed` inside the conversion+ // fail. setMode still continues to idle + a scheduled pull, and the ahead-only+ // shape (behind 0) means that pull reports up-to-date without re-surfacing the+ // divergence — so the conversion failure itself must set a paused reason,+ // otherwise the badge shows a clean idle over unpushable stranded commits.+ writeFileSync(join(projectDir, '.git', 'index.lock'), '', 'utf-8');++ const engine = makeEngineMode('full');+ try {+ await engine.setMode('follow');+ expect(engine.getStatus().pausedReason).toBe('diverged-local-commits');+ } finally {+ rmSync(join(projectDir, '.git', 'index.lock'), { force: true });+ await engine.destroy();+ }+ });++ test('full→pull downgrade folds ahead-only commits into an overlay at origin tip', async () => {+ const { seedTip } = await seedAndClone({ 'a.md': 'A1\n' });+ // Two committed-but-unpushed edits: ahead 2, behind 0 (push access revoked).+ await commitLocal({ 'a.md': 'A1\nLOCAL2\n' }, 'local 1');+ const localTip = await commitLocal({ 'a.md': 'A1\nLOCAL2\nLOCAL3\n' }, 'local 2');++ const engine = makeEngineMode('full');+ try {+ await engine.setMode('follow');++ const project = simpleGit(projectDir);+ // Branch realigned to origin tip (the seed IS the merge base for ahead-only).+ expect((await project.revparse(['HEAD'])).trim()).toBe(seedTip);+ // Docs byte-identical: the committed content now rides as an overlay.+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('A1\nLOCAL2\nLOCAL3\n');+ expect(await listNames(project, ['diff-index', '--name-only', 'HEAD'])).toEqual(['a.md']);+ // Zero local commits remain on the branch.+ expect((await project.raw(['rev-list', '--count', 'origin/main..HEAD'])).trim()).toBe('0');+ // Recoverable in history: the reset left ORIG_HEAD at the pre-conversion tip.+ expect((await project.revparse(['ORIG_HEAD'])).trim()).toBe(localTip);+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ });++ test('enable-time divergence converts then fast-forwards to origin tip', async () => {+ // Local commit edits a.md (ahead 1); origin independently advanced b.md+ // (behind 1) — a true divergence. Conversion lands on the merge base with the+ // local edit as overlay; the next pull carries the branch to origin's tip and+ // brings the non-overlapping origin change.+ const { sister, sisterDir } = await seedAndClone({ 'a.md': 'A1\n', 'b.md': 'B1\n' });+ const originTip = await advanceOrigin(sister, sisterDir, { 'b.md': 'B1\nB2\n' });+ await commitLocal({ 'a.md': 'A1\nLOCAL\n' }, 'local edit');++ const engine = makeEngineMode('off');+ try {+ await engine.setMode('follow');+ await waitForHead(originTip);++ const project = simpleGit(projectDir);+ expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);+ // Local edit survives as overlay; origin's non-overlapping change landed.+ expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('A1\nLOCAL\n');+ expect(readFileSync(join(projectDir, 'b.md'), 'utf-8')).toBe('B1\nB2\n');+ expect(await listNames(project, ['diff-index', '--name-only', 'HEAD'])).toEqual(['a.md']);+ expect((await project.raw(['rev-list', '--count', 'origin/main..HEAD'])).trim()).toBe('0');+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ });++ test('the checkpoint fires before the branch ref moves', async () => {+ const { seedTip } = await seedAndClone({ 'a.md': 'A1\n' });+ const localTip = await commitLocal({ 'a.md': 'A1\nLOCAL\n' }, 'local edit');++ let checkpointAhead = 0;+ let headAtCheckpoint: string | null = null;+ const engine = makeEngineMode('off', async ({ ahead }) => {+ checkpointAhead = ahead;+ // HEAD is still at the local tip when the checkpoint runs — the reset that+ // realigns the branch happens after, so the snapshot captures the stranded+ // content, not the post-reset state.+ headAtCheckpoint = (await simpleGit(projectDir).revparse(['HEAD'])).trim();+ });+ try {+ await engine.setMode('follow');++ expect(checkpointAhead).toBe(1);+ expect(headAtCheckpoint).toBe(localTip);+ const project = simpleGit(projectDir);+ expect((await project.revparse(['HEAD'])).trim()).toBe(seedTip);+ } finally {+ await engine.destroy();+ }+ });++ test('off→pull with no ahead commits enables plainly (no conversion)', async () => {+ const { seedTip } = await seedAndClone({ 'a.md': 'A1\n' });++ let checkpointCalled = false;+ const engine = makeEngineMode('off', () => {+ checkpointCalled = true;+ });+ try {+ await engine.setMode('follow');++ expect(checkpointCalled).toBe(false);+ // Branch untouched (no stranded commits to realign around).+ expect((await simpleGit(projectDir).revparse(['HEAD'])).trim()).toBe(seedTip);+ expect(engine.getStatus().syncMode).toBe('follow');+ } finally {+ await engine.destroy();+ }+ });++ test('off→full keeps ahead commits (full mode pushes them, never converts)', async () => {+ await seedAndClone({ 'a.md': 'A1\n' });+ const localTip = await commitLocal({ 'a.md': 'A1\nLOCAL\n' }, 'local edit');++ let checkpointCalled = false;+ const engine = makeEngineMode('off', () => {+ checkpointCalled = true;+ });+ try {+ await engine.setMode('full');++ // Full mode leaves the commits on the branch to push — no overlay conversion.+ expect(checkpointCalled).toBe(false);+ expect((await simpleGit(projectDir).revparse(['HEAD'])).trim()).toBe(localTip);+ await assertNoGitResidue();+ } finally {+ await engine.destroy();+ }+ });++ test('pull→full upgrade pushes the overlay content on the next cycle', async () => {+ const { bareDir } = await seedAndClone({ 'a.md': 'A1\n' });+ // A pull-only overlay: an uncommitted local edit riding on origin's tip.+ writeFileSync(join(projectDir, 'a.md'), 'A1\nOVERLAY\n', 'utf-8');++ const engine = makeEngineMode('follow');+ try {+ await engine.setMode('full');+ await engine.trigger('push');++ // The overlay was committed and pushed — origin now carries its content.+ const originContent = await simpleGit(bareDir).raw(['show', 'main:a.md']);+ expect(originContent).toBe('A1\nOVERLAY\n');+ } finally {+ await engine.destroy();+ }+ });++ test('probeUnpushedCommitCount reports the stranded count with and without an upstream', async () => {+ await seedAndClone({ 'a.md': 'A1\n' });+ await commitLocal({ 'a.md': 'A1\nL1\n' }, 'local 1');+ await commitLocal({ 'a.md': 'A1\nL1\nL2\n' }, 'local 2');++ const engine = makeEngineMode('off');+ try {+ // refreshRemote sets hasRemote without triggering a conversion (mode stays off).+ await engine.refreshRemote();+ expect(await engine.probeUnpushedCommitCount()).toBe(2);++ // With no configured upstream, the count comes from the rev-list fallback.+ await simpleGit(projectDir).raw(['branch', '--unset-upstream']);+ expect(await engine.probeUnpushedCommitCount()).toBe(2);+ } finally {+ await engine.destroy();+ }+ });+});++// ─── Fast-forward refusal classifier ───────────────────────────────────────────+//+// classifyFastForwardRefusal keys on git's exit code + stderr severity token.+// Both are version- and locale-sensitive, so these tests feed it the OUTPUT of+// a real `git merge --ff-only` against the shipped git build (LANG=C, matching+// the sync git env) rather than a hand-written string.++describe('classifyFastForwardRefusal (pinned against real git)', () => {+ async function realFfRefusal(): Promise<{ code: number | null; stderr: string }> {+ try {+ await execFileAsync(+ 'git',+ ['-c', 'core.autocrlf=false', 'merge', '--ff-only', 'origin/main'],+ {+ cwd: projectDir,+ env: { ...process.env, LANG: 'C', LC_ALL: 'C' },+ },+ );+ throw new Error('expected fast-forward to refuse');+ } catch (e) {+ const err = e as { code?: number | string; stderr?: string };+ return {+ code: typeof err.code === 'number' ? err.code : null,+ stderr: typeof err.stderr === 'string' ? err.stderr : String(e),+ };+ }+ }++ async function seedBareOrigin(): Promise<string> {+ 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');+ return bareDir;+ }++ async function cloneBehind(advance: string): Promise<void> {+ 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'), 'l1\nl2\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 });+ writeFileSync(join(sisterDir, 'a.md'), advance, 'utf-8');+ await sister.add('.');+ await sister.commit('advance');+ await sister.push('origin', 'main');+ // The clone's origin/main still points at the seed until it fetches; update+ // it so the direct `git merge --ff-only origin/main` below sees the advance.+ await simpleGit(projectDir).fetch('origin');+ }++ test('an overlapping dirty edit classifies as overlay-overlap', async () => {+ await cloneBehind('ORIGIN1\nl2\n');+ // Local uncommitted edit to the same file the incoming tip changed.+ writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nl2\n', 'utf-8');+ const { code, stderr } = await realFfRefusal();+ expect(code).toBe(1);+ expect(classifyFastForwardRefusal({ exitCode: code, stderr })).toBe('overlay-overlap');+ });++ test('diverged history classifies as divergence', async () => {+ await cloneBehind('ORIGIN1\nl2\n');+ const project = simpleGit(projectDir);+ await project.raw('config', 'user.name', 'Follower');+ await project.raw('config', 'user.email', '[email protected]');+ writeFileSync(join(projectDir, 'a.md'), 'LOCAL_COMMIT\nl2\n', 'utf-8');+ await project.add('.');+ await project.commit('local ahead');+ const { code, stderr } = await realFfRefusal();+ expect(code).toBe(128);+ expect(classifyFastForwardRefusal({ exitCode: code, stderr })).toBe('divergence');+ });+});++// ─── One-shot pull (op 'pull') ──────────────────────────────────────────────+//+// `trigger('pull')` (the spec-B contract) runs a single pull in every mode and+// records a bounded outcome. Unlike a background cycle it also runs for an+// off/null project — fetching + fast-forwarding via the B1 variant without ever+// committing or leaving the project enabled. Every path writes lastPullUtc ++// lastPullOutcome so a downstream surface can detect a fresh result by change.++describe("SyncEngine one-shot pull (op 'pull')", () => {+ async function seedBareOrigin(): Promise<string> {+ 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');+ return bareDir;+ }++ /**+ * Seed origin from a sister clone, clone it into projectDir, then optionally+ * advance origin so the project is one commit behind. Returns origin's tip SHA+ * and the bare dir (so a caller can read origin's ref).+ */+ async function cloneFromOrigin(opts: {+ seed: Record<string, string>;+ advance?: Record<string, string>;+ }): Promise<{ originTip: string; bareDir: string }> {+ 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]');+ for (const [f, c] of Object.entries(opts.seed)) writeFileSync(join(sisterDir, f), c, '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 });++ if (opts.advance) {+ for (const [f, c] of Object.entries(opts.advance)) {+ writeFileSync(join(sisterDir, f), c, 'utf-8');+ }+ await sister.add('.');+ await sister.commit('advance');+ await sister.push('origin', 'main');+ }+ return { originTip: (await sister.revparse(['HEAD'])).trim(), bareDir };+ }++ function makeEngineFor(mode: SyncMode) {+ return new SyncEngine({+ projectDir,+ contentDir: projectDir,+ contentFilter: stubContentFilter,+ mode,+ });+ }++ async function assertNoGitResidue(): Promise<void> {+ expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(false);+ expect((await simpleGit(projectDir).raw(['stash', 'list'])).trim()).toBe('');+ }++ test('mode off: a one-shot pull fast-forwards without enabling the project', async () => {+ const { originTip, bareDir } = await cloneFromOrigin({+ seed: { 'doc.md': 'v1\n' },+ advance: { 'doc.md': 'v1\nv2\n' },+ });+ const originRefBefore = (await simpleGit(bareDir).revparse(['main'])).trim();++ const engine = makeEngineFor('off');+ try {+ await engine.start();+ expect(engine.getStatus().state).toBe('disabled');++ const outcome = await engine.pullOnce();++ expect(outcome).toBe('succeeded');+ const project = simpleGit(projectDir);+ expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);+ expect(readFileSync(join(projectDir, 'doc.md'), 'utf-8')).toBe('v1\nv2\n');+ // Never enabled: mode stays off and the engine returns to its inactive+ // resting state instead of looking like a running sync.+ const status = engine.getStatus();+ expect(status.syncMode).toBe('off');+ expect(status.state).toBe('disabled');+ expect(status.lastPullOutcome).toBe('succeeded');+ expect(typeof status.lastPullUtc).toBe('string');+ // No commit made on the user's behalf (B1 variant) and no push to origin.+ await assertNoGitResidue();+ expect((await simpleGit(bareDir).revparse(['main'])).trim()).toBe(originRefBefore);+ } finally {+ await engine.destroy();+ }+ });++ test('an already-current project reports up-to-date', async () => {+ await cloneFromOrigin({ seed: { 'doc.md': 'v1\n' } }); // no advance — clone sits at tip+ const engine = makeEngineFor('follow');+ try {+ await engine.start();+ const outcome = await engine.pullOnce();+ expect(outcome).toBe('up-to-date');+ expect(typeof engine.getStatus().lastPullUtc).toBe('string');+ } finally {+ await engine.destroy();+ }+ });++ test('a same-line collision reports conflict', async () => {+ await cloneFromOrigin({+ seed: { 'doc.md': 'line1\nline2\n' },+ advance: { 'doc.md': 'ORIGIN1\nline2\n' },+ });+ writeFileSync(join(projectDir, 'doc.md'), 'LOCAL1\nline2\n', 'utf-8');+ const engine = makeEngineFor('follow');+ try {+ await engine.start();+ const outcome = await engine.pullOnce();+ expect(outcome).toBe('conflict');+ expect(engine.getStatus().conflictCount).toBe(1);+ expect(engine.getStatus().lastPullOutcome).toBe('conflict');+ } finally {+ await engine.destroy();+ }+ });++ test('a concurrent one-shot is refused (single-flight)', async () => {+ await cloneFromOrigin({+ seed: { 'doc.md': 'v1\n' },+ advance: { 'doc.md': 'v1\nv2\n' },+ });+ const engine = makeEngineFor('follow');+ try {+ await engine.start();+ // The first call holds the in-flight guard across its first await; the+ // second observes it and refuses without racing the working tree.+ const first = engine.pullOnce();+ const second = await engine.pullOnce();+ expect(second).toBe('refused');+ expect(await first).toBe('succeeded');+ } finally {+ await engine.destroy();+ }+ });++ test('an unreachable remote reports error-class', async () => {+ await cloneFromOrigin({ seed: { 'doc.md': 'v1\n' } });+ // Repoint origin at a nonexistent path so the fetch fails.+ await simpleGit(projectDir).raw(+ 'config',+ 'remote.origin.url',+ join(tmpDir, 'nonexistent-bare.git'),+ );+ const engine = makeEngineFor('follow');+ try {+ await engine.start();+ const outcome = await engine.pullOnce();+ expect(outcome).toBe('error');+ const status = engine.getStatus();+ expect(status.lastPullOutcome).toBe('error');+ expect(`${status.pullError ?? ''}${status.pullErrorCode ?? ''}`).not.toBe('');+ } finally {+ await engine.destroy();+ }+ });++ test("trigger('pull') records the outcome in status", async () => {+ await cloneFromOrigin({+ seed: { 'doc.md': 'v1\n' },+ advance: { 'doc.md': 'v1\nv2\n' },+ });+ const engine = makeEngineFor('follow');+ try {+ await engine.start();+ await engine.trigger('pull');+ const status = engine.getStatus();+ expect(status.lastPullOutcome).toBe('succeeded');+ expect(typeof status.lastPullUtc).toBe('string');+ } finally {+ await engine.destroy();+ }+ });++ test('lastPullUtc is null before the first pull and set after (change-detection)', async () => {+ await cloneFromOrigin({+ seed: { 'doc.md': 'v1\n' },+ advance: { 'doc.md': 'v1\nv2\n' },+ });+ const engine = makeEngineFor('off');+ try {+ await engine.start();+ expect(engine.getStatus().lastPullUtc).toBeNull();+ expect(engine.getStatus().lastPullOutcome).toBeNull();+ await engine.pullOnce();+ expect(engine.getStatus().lastPullUtc).not.toBeNull();+ expect(engine.getStatus().lastPullOutcome).toBe('succeeded');+ } finally {+ await engine.destroy();+ }+ });++ test('refuses when there is no remote', async () => {+ // A repo with commits but no origin — nothing to pull from.+ const git = simpleGit(projectDir);+ await git.init(['--initial-branch=main']);+ await git.raw('config', 'user.name', 'Solo');+ await git.raw('config', 'user.email', '[email protected]');+ writeFileSync(join(projectDir, 'doc.md'), 'v1\n', 'utf-8');+ await git.add('.');+ await git.commit('seed');+ const engine = makeEngineFor('off');+ try {+ await engine.start();+ const outcome = await engine.pullOnce();+ expect(outcome).toBe('refused');+ expect(engine.getStatus().lastPullOutcome).toBe('refused');+ } finally {+ await engine.destroy();+ }+ });+});++describe('SyncEngine telemetry', () => {+ async function seedBareOrigin(): Promise<string> {+ 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');+ return bareDir;+ }++ async function cloneFromOrigin(opts: {+ seed: Record<string, string>;+ advance?: Record<string, string>;+ }): Promise<void> {+ 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]');+ for (const [f, c] of Object.entries(opts.seed)) writeFileSync(join(sisterDir, f), c, '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 });++ if (opts.advance) {+ for (const [f, c] of Object.entries(opts.advance)) {+ writeFileSync(join(sisterDir, f), c, 'utf-8');+ }+ await sister.add('.');+ await sister.commit('advance');+ await sister.push('origin', 'main');+ }+ }++ function makeEngineFor(mode: SyncMode) {+ return new SyncEngine({+ projectDir,+ contentDir: projectDir,+ contentFilter: stubContentFilter,+ mode,+ });+ }++ test('setMode logs the mode change with its source', async () => {+ await cloneFromOrigin({ seed: { 'doc.md': 'v1\n' } });+ const engine = makeEngineFor('off');+ const cap = captureSyncLogs();+ try {+ await engine.start();+ await engine.setMode('full', 'committed-default');+ const entry = cap.entries.find((e) => e.msg === '[sync] mode changed');+ expect(entry).toBeDefined();+ expect(entry?.data).toMatchObject({ from: 'off', to: 'full', source: 'committed-default' });+ } finally {+ cap.restore();+ await engine.destroy();+ }+ });++ test('an unchanged setMode emits no mode-change log', async () => {+ await cloneFromOrigin({ seed: { 'doc.md': 'v1\n' } });+ const engine = makeEngineFor('follow');+ const cap = captureSyncLogs();+ try {+ await engine.start();+ await engine.setMode('follow'); // same value — idempotent early-return+ expect(cap.entries.some((e) => e.msg === '[sync] mode changed')).toBe(false);+ } finally {+ cap.restore();+ await engine.destroy();+ }+ });++ test('a one-shot pull logs its mode and outcome on success', async () => {+ await cloneFromOrigin({ seed: { 'doc.md': 'v1\n' }, advance: { 'doc.md': 'v1\nv2\n' } });+ const engine = makeEngineFor('off');+ const cap = captureSyncLogs();+ try {+ await engine.start();+ await engine.pullOnce();+ const entry = cap.entries.find((e) => e.msg === '[sync] one-shot pull complete');+ expect(entry).toBeDefined();+ expect(entry?.data).toMatchObject({ mode: 'off', outcome: 'succeeded' });+ } finally {+ cap.restore();+ await engine.destroy();+ }+ });++ test('a refused one-shot pull still logs the refused outcome', async () => {+ // No remote: the one-shot refuses rather than silently no-op'ing.+ const engine = makeEngineFor('off');+ const cap = captureSyncLogs();+ try {+ await engine.start();+ await engine.pullOnce();+ const entry = cap.entries.find((e) => e.msg === '[sync] one-shot pull complete');+ expect(entry?.data).toMatchObject({ mode: 'off', outcome: 'refused' });+ } finally {+ cap.restore();+ await engine.destroy();+ }+ });++ test('a B1 pull logs conflict-lifecycle counts and the overlay-stock gauge', async () => {+ await cloneFromOrigin({+ seed: { 'docA.md': 'line1\nline2\n', 'docB.md': 'b1\nb2\nb3\n', 'docC.md': 'c\n' },+ advance: { 'docA.md': 'ORIGIN1\nline2\n', 'docB.md': 'b1\nb2\nORIGIN3\n' },+ });+ // Three local overlays: a same-line collision (docA — line1 both sides), a+ // different-line auto-combine (docB — local line1, origin line3, unchanged+ // line2 anchoring the merge), and a non-overlapping local-only edit (docC)+ // that rides through the fast-forward.+ writeFileSync(join(projectDir, 'docA.md'), 'LOCAL1\nline2\n', 'utf-8');+ writeFileSync(join(projectDir, 'docB.md'), 'LOCAL1\nb2\nb3\n', 'utf-8');+ writeFileSync(join(projectDir, 'docC.md'), 'c\nlocal-extra\n', 'utf-8');+ const engine = makeEngineFor('follow');+ const cap = captureSyncLogs();+ try {+ await engine.start();+ await engine.pullOnce();+ const entry = cap.entries.find(+ (e) => e.msg === '[sync] pull-only: fast-forwarded to origin tip',+ );+ expect(entry).toBeDefined();+ expect(entry?.data).toMatchObject({+ created: 1,+ autoCombined: 1,+ autoDissolved: 0,+ overlayStock: 3,+ });+ } finally {+ cap.restore();+ await engine.destroy();+ }+ });++ test('resolving a working-tree conflict logs the chosen strategy', async () => {+ await cloneFromOrigin({+ seed: { 'doc.md': 'line1\nline2\n' },+ advance: { 'doc.md': 'ORIGIN1\nline2\n' },+ });+ writeFileSync(join(projectDir, 'doc.md'), 'LOCAL1\nline2\n', 'utf-8');+ const engine = makeEngineFor('follow');+ const cap = captureSyncLogs();+ try {+ await engine.start();+ await engine.pullOnce(); // same-line collision → working-tree conflict entry+ expect(engine.getStatus().conflictCount).toBe(1);+ await engine.resolveConflict('doc.md', 'theirs');+ const entry = cap.entries.find(+ (e) => e.msg === '[sync] pull-only: conflict resolved by choice',+ );+ expect(entry).toBeDefined();+ expect(entry?.data).toMatchObject({ choice: 'theirs' });+ } finally {+ cap.restore();+ await engine.destroy();+ }+ });+});diff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.tsindex cb1700245..bb998e0c7 100644--- a/packages/server/src/sync-engine.ts+++ b/packages/server/src/sync-engine.ts@@ -7,6 +7,7 @@* + restart recovery.*/+import { execFile } from 'node:child_process';import {type Dirent,existsSync,@@ -18,11 +19,18 @@ import {import { tmpdir } from 'node:os';import { join, relative, resolve } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';+import { promisify } from 'node:util';+import {+ type PullOutcome,+ type SyncMode,+ type SyncModeChangeSource,+ tryLineLevelCombine,+} from '@inkeep/open-knowledge-core';import { inspectGitRepository } from '@inkeep/open-knowledge-core/git-repository';import { resolveGitDir } from '@inkeep/open-knowledge-core/shadow-repo-layout';import type { CC1Broadcaster } from './cc1-broadcast.ts';import { getLocalDir } from './config/paths.ts';-import { ConflictStore } from './conflict-storage.ts';+import { type ConflictEntry, ConflictStore } from './conflict-storage.ts';import type { ContentFilter } from './content-filter.ts';import { isSupportedDocFile } from './doc-extensions.ts';import {@@ -30,6 +38,7 @@ import {classifyGitError,type UserFacingErrorCode,} from './error-classification.ts';+import { tracedUnlinkSync, tracedWriteFileSync } from './fs-traced.ts';import { createGhTokenSource, type GhTokenSource } from './gh-token-source.ts';import { applyGitEnv, createGitInstance, type GitHandle, withParentLock } from './git-handle.ts';import { resolveGitIdentity } from './git-identity.ts';@@ -49,7 +58,12 @@ import {readSyncRemoteInfo,type SyncRemoteInfo,} from './share/git-context.ts';-import { computeRemainingMs } from './sync-timing.ts';+import { assertRealpathWithinDir } from './symlink-guard.ts';+import {+ computeRemainingMs,+ type PullAuthTier,+ pullIntervalSecondsForAuthTier,+} from './sync-timing.ts';const log = getLogger('sync-engine');@@ -61,6 +75,43 @@ const log = getLogger('sync-engine');*/const SHA_HEX_40 = /^[0-9a-f]{40}$/i;+const execFileAsync = promisify(execFile);++/**+ * Why a `git merge --ff-only` refused. `git` distinguishes the two causes by+ * both exit code and stderr severity token, and the pull-only cycle must react+ * differently to each: an overlay overlap is recoverable (restore the file and+ * retry), a divergence is not fast-forwardable at all.+ */+export type FastForwardRefusal = 'overlay-overlap' | 'divergence' | 'unknown';++/**+ * Classify a fast-forward refusal from git's exit code and stderr. Two+ * independent discriminators are available and pinned against the shipped git+ * build by a test, because the message text is locale- and version-sensitive:+ * - divergence (local history not fast-forwardable): exit 128, `fatal:` ++ * "Not possible to fast-forward";+ * - overlay overlap (an uncommitted edit to a file the merge would update):+ * exit 1, `error:` + "would be overwritten by merge".+ * The severity token is the primary signal — git prints an informational+ * `Updating <a>..<b>` line to stdout even when it then aborts, so stdout is not+ * safe to key on.+ */+export function classifyFastForwardRefusal(input: {+ exitCode?: number | null;+ stderr: string;+}): FastForwardRefusal {+ const { exitCode, stderr } = input;+ const s = stderr ?? '';+ if (exitCode === 128 || (/^fatal:/m.test(s) && /not possible to fast-forward/i.test(s))) {+ return 'divergence';+ }+ if (/^error:/m.test(s) && /would be overwritten by merge/i.test(s)) {+ return 'overlay-overlap';+ }+ return 'unknown';+}+// ─── Types ───────────────────────────────────────────────────────────────────export type SyncState =@@ -134,14 +185,28 @@ interface SyncStatus {lastSyncUtc: string | null;lastFetchUtc: string | null;lastPushedSha: string | null;+ /**+ * Completion timestamp + bounded outcome of the last pull (background or+ * one-shot). `lastPullUtc` bumps at every pull completion so a downstream+ * surface can detect a fresh result by change; `lastPullOutcome` carries that+ * pull's outcome. Null until the first pull completes.+ */+ lastPullUtc: string | null;+ lastPullOutcome: PullOutcome | null;ahead: number;behind: number;consecutiveFailures: number;conflictCount: number;/** True when a git remote exists, even if sync is dormant/disabled. */hasRemote: boolean;- /** User's sync toggle preference. False by default (disabled for safety). */+ /**+ * Whether sync is on at all — true for both `pull` and `full` mode, false for+ * `off`. False by default (disabled for safety). Read `syncMode` to branch on+ * push capability; this boolean cannot distinguish pull-only from full.+ */syncEnabled: boolean;+ /** Project sync mode. `full` is the only mode that pushes. */+ syncMode: SyncMode;/*** Soft signal: `resolveGitIdentity()` returned null on the last probe.* The push cycle still commits under the "OpenKnowledge" default — this flag@@ -204,7 +269,16 @@ interface SyncEngineOptions {pullIntervalSeconds?: number;/** Seconds between push cycles. Default 60. */pushIntervalSeconds?: number;- /** Whether sync is enabled according to project config. Undefined is treated as disabled. */+ /**+ * Project sync mode from resolved config. When omitted, `syncEnabled` is used+ * as the legacy back-compat source (`true`→`full`, else `off`). Prefer `mode`.+ */+ mode?: SyncMode;+ /**+ * Legacy boolean enable flag. Retained so existing callers (and tests) keep+ * working; `true` maps to `full`, anything else to `off`. Ignored when `mode`+ * is provided.+ */syncEnabled?: boolean;/** Credential args for simple-git (e.g. ['-c', 'credential.helper=…']). */credentialArgs?: string[];@@ -217,6 +291,14 @@ interface SyncEngineOptions {* The server uses this to mark already-loaded Y.Docs as conflicted.*/onContentConflictsDetected?: (files: string[]) => void | Promise<void>;+ /**+ * Called after a content conflict clears (resolved by the user or+ * auto-dissolved when upstream converged). The server uses this to clear the+ * conflict status on already-loaded Y.Docs — for a working-tree conflict the+ * resolution may not change disk bytes (keep-mine), so the file-watcher's+ * `case 'update'` clear cannot be relied on.+ */+ onContentConflictsResolved?: (files: string[]) => void | Promise<void>;/** Callback to gate batch-in-progress during merge operations.* Prevents HEAD watcher from firing reconciliation mid-merge. */setBatchInProgress?: (value: boolean) => void;@@ -229,6 +311,34 @@ interface SyncEngineOptions {* push failure on every restart.*/onAutoDisable?: (reason: 'protected-branch') => void | Promise<void>;+ /**+ * Snapshot the working tree to the recoverable timeline just before a+ * pull-only transition folds stranded local commits into a working-tree+ * overlay (a `--mixed` reset realigns the branch to origin). Fired only when+ * there are commits to convert, and before the branch moves, so the+ * pre-conversion state is recoverable even if the process dies mid-transition.+ * The server wires this to a shadow-repo safety checkpoint; omit in tests /+ * headless boots where no shadow repo exists.+ */+ checkpointBeforeStrandedConversion?: (context: {+ branch: string;+ ahead: number;+ }) => void | Promise<void>;+ /**+ * Fired inside a pull-only cycle when an incoming fast-forward overlaps an+ * uncommitted local edit, right before the overlapping paths are reset to HEAD+ * (the reset is what lets the fast-forward land). Between that reset and the+ * overlay re-write the edit lives only in memory, so a hard crash in that+ * window would lose it for a doc with no live client. The server wires this to+ * a shadow-repo safety checkpoint so the pre-reset bytes survive on the shadow+ * timeline and stay recoverable. Best-effort — a failure only forfeits the+ * crash-window safety net, so the cycle proceeds. Omit in tests / headless+ * boots where no shadow repo exists.+ */+ checkpointBeforeOverlayRestore?: (context: {+ branch: string;+ paths: number;+ }) => void | Promise<void>;/*** Tier A token detector. Honors the existing three-tier model (see* `packages/cli/src/auth/resolve-auth.ts`) without `packages/server`@@ -284,6 +394,29 @@ function backoffMs(consecutiveFailures: number): number {return 0; // use normal interval}+/**+ * Wall-clock cap for the `git merge --ff-only` subprocess. It is the one git+ * call in the engine spawned directly (not via the simple-git handle's block+ * timeout), so without this a hang — a stuck credential-helper prompt, a+ * degraded disk/NFS — would block the pull cycle forever with `pullInFlight`+ * held, wedging every future pull and push. On timeout the child is killed and+ * the cycle takes the error path so it retries with backoff.+ */+const FF_ONLY_TIMEOUT_MS = 120_000;++/**+ * Inactivity cap (simple-git `timeout.block`: ms since the last stdout/stderr+ * chunk) for every git op run through the engine's shared handle — fetch, push,+ * status, rev-parse. Without it a stuck remote or a hung credential-helper+ * prompt blocks the op forever with `pullInFlight`/`pushInFlight` held, wedging+ * every future cycle until the app restarts; pull-only amplifies this since a+ * follower has no push cycle to interleave and the one-shot "Update now" is a+ * fresh entry point onto the same fetch. A progressing transfer resets the+ * timer on each chunk, so only genuine silence trips it and the cycle then+ * falls into the existing backoff.+ */+const GIT_BLOCK_TIMEOUT_MS = 120_000;+// ─── SyncEngine ──────────────────────────────────────────────────────────────export class SyncEngine {@@ -294,13 +427,27 @@ export class SyncEngine {private contentRoot: string;private pullIntervalSeconds: number;private pushIntervalSeconds: number;- private syncEnabled: boolean | undefined;+ /**+ * The single source of truth for what direction (if any) this engine syncs.+ * `off` = inactive, `pull` = fetch + fast-forward only (never pushes), `full`+ * = bidirectional. Push is structurally impossible unless this is `full` (the+ * gate lives at the push routine entrance), so no scheduling path can push for+ * a pull-only project.+ */+ private mode: SyncMode;private credentialArgs: string[];private cc1Broadcaster: CC1Broadcaster | null;private onStateChange: ((state: SyncState) => void) | undefined;private onContentConflictsDetected: ((files: string[]) => void | Promise<void>) | undefined;+ private onContentConflictsResolved: ((files: string[]) => void | Promise<void>) | undefined;private setBatchInProgress: ((value: boolean) => void) | undefined;private onAutoDisable: ((reason: 'protected-branch') => void | Promise<void>) | undefined;+ private checkpointBeforeStrandedConversion:+ | ((context: { branch: string; ahead: number }) => void | Promise<void>)+ | undefined;+ private checkpointBeforeOverlayRestore:+ | ((context: { branch: string; paths: number }) => void | Promise<void>)+ | undefined;private detectGh: DetectGhFn | undefined;/*** Resolves + caches the gh token relayed to the credential helper so sync@@ -321,6 +468,14 @@ export class SyncEngine {private pushPermission: PushPermissionStatus | null = null;/** Prevents concurrent probes — strict one-call-per-session contract. */private pushPermissionProbeInFlight = false;+ /**+ * Credential tier the next pull-mode cycle fetches as, resolved from the same+ * gh → token-store → anonymous order the push probe uses. Cached so the+ * scheduler can read it synchronously; refreshed before each pull-mode+ * schedule. Anonymous followers poll at a gentler cadence. `unknown` until+ * first resolved, treated as authenticated (the responsive default).+ */+ private authTier: PullAuthTier | 'unknown' = 'unknown';private pullTimer: ReturnType<typeof setTimeout> | null = null;private pushTimer: ReturnType<typeof setTimeout> | null = null;@@ -330,6 +485,8 @@ export class SyncEngine {private lastSyncUtc: string | null = null;private lastFetchUtc: string | null = null;private lastPushedSha: string | null = null;+ private lastPullUtc: string | null = null;+ private lastPullOutcome: PullOutcome | null = null;private consecutiveFailures = 0;private ahead = 0;private behind = 0;@@ -361,13 +518,18 @@ export class SyncEngine {this.contentRoot = options.contentRoot ?? '';this.pullIntervalSeconds = options.pullIntervalSeconds ?? 30;this.pushIntervalSeconds = options.pushIntervalSeconds ?? 60;- this.syncEnabled = options.syncEnabled;+ // `mode` wins; fall back to the legacy boolean so callers that still pass+ // `syncEnabled` keep their exact prior semantics (true→full, else off).+ this.mode = options.mode ?? (options.syncEnabled === true ? 'full' : 'off');this.credentialArgs = options.credentialArgs ?? [];this.cc1Broadcaster = options.cc1Broadcaster ?? null;this.onStateChange = options.onStateChange;this.onContentConflictsDetected = options.onContentConflictsDetected;+ this.onContentConflictsResolved = options.onContentConflictsResolved;this.setBatchInProgress = options.setBatchInProgress;this.onAutoDisable = options.onAutoDisable;+ this.checkpointBeforeStrandedConversion = options.checkpointBeforeStrandedConversion;+ this.checkpointBeforeOverlayRestore = options.checkpointBeforeOverlayRestore;this.detectGh = options.detectGh;this.ghTokenSource = createGhTokenSource(options.detectGh);this.tokenStore = options.tokenStore;@@ -404,6 +566,7 @@ export class SyncEngine {credentialArgs: this.credentialArgs,gitIndexFile,ghToken: this.ghTokenSource.get(this.syncGhTokenHost()) ?? undefined,+ timeoutMs: GIT_BLOCK_TIMEOUT_MS,});}@@ -448,12 +611,10 @@ export class SyncEngine {// Disabled by default: sync only runs when the user has explicitly opted in.// Protects real git repos (production code) from being mutated automatically.- if (this.syncEnabled !== true) {+ // Both `pull` and `full` are active here; only `off` stays inactive.+ if (this.mode === 'off') {if (hasRemote) this.transitionTo('disabled');- log.info(- { hasRemote, syncEnabled: this.syncEnabled },- '[sync] sync not enabled — staying inactive',- );+ log.info({ hasRemote, mode: this.mode }, '[sync] sync not enabled — staying inactive');return;}@@ -474,15 +635,22 @@ export class SyncEngine {const mergeHeadPath = gitDir ? join(gitDir, 'MERGE_HEAD') : null;const mergeInProgress = mergeHeadPath !== null && existsSync(mergeHeadPath);- if (this.conflictCount > 0 && !mergeInProgress) {- // Tracked conflicts but no merge in progress → fully resolved externally.+ // Align the cached count with the persisted store (conflicts.json) so the+ // reconcile below sees every entry, including working-tree variants.+ this.conflictCount = this.conflictStore.count();+ const mergeNativeEntries = () =>+ this.conflictStore.list().filter((e) => e.variant !== 'working-tree');++ if (mergeNativeEntries().length > 0 && !mergeInProgress) {+ // Merge-native entries with no merge in progress → resolved externally.+ // (Working-tree entries are MERGE_HEAD-free by design and survive.)log.warn(- { count: this.conflictCount },- '[sync] persisted conflicts but no MERGE_HEAD — clearing stale state',+ { count: mergeNativeEntries().length },+ '[sync] persisted merge conflicts but no MERGE_HEAD — clearing stale state',);- this.conflictStore.clear();- this.conflictCount = 0;- } else if (this.conflictCount > 0 && mergeInProgress) {+ for (const entry of mergeNativeEntries()) this.conflictStore.removeConflict(entry.file);+ this.conflictCount = this.conflictStore.count();+ } else if (mergeNativeEntries().length > 0 && mergeInProgress) {// Merge still in progress — drop any tracked entries git considers resolved.try {const handle = this.gitHandle();@@ -490,7 +658,7 @@ export class SyncEngine {await listNames(handle.git, ['diff', '--name-only', '--diff-filter=U']),);const before = this.conflictCount;- for (const entry of this.conflictStore.list()) {+ for (const entry of mergeNativeEntries()) {if (!stillUnmerged.has(entry.file)) {this.conflictStore.removeConflict(entry.file);}@@ -507,9 +675,9 @@ export class SyncEngine {}}- // Clean up stale merge state: if MERGE_HEAD exists but no conflicts are tracked,- // a previous crash left the repo in a half-merged state — abort to recover.- if (mergeInProgress && this.conflictCount === 0) {+ // Clean up stale merge state: MERGE_HEAD but no merge-native conflicts+ // tracked → a previous crash left a half-merged state; abort to recover.+ if (mergeInProgress && mergeNativeEntries().length === 0) {log.warn({}, '[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge');try {const handle = this.gitHandle();@@ -519,8 +687,9 @@ export class SyncEngine {}}- // If we restored in-flight conflicts, re-enter conflict state (timers paused)- if (this.conflictCount > 0) {+ // Merge-native conflicts pause the engine (a MERGE_HEAD blocks all sync);+ // working-tree conflicts only re-flag their doc and keep the engine pulling.+ if (mergeNativeEntries().length > 0) {await this.notifyContentConflictsDetected(this.conflictStore.list().map((entry) => entry.file),);@@ -531,9 +700,24 @@ export class SyncEngine {);return;}+ const workingTreeEntries = this.conflictStore+ .list()+ .filter((e) => e.variant === 'working-tree');+ if (workingTreeEntries.length > 0) {+ // Re-flag the per-doc lifecycle so the resolver mounts on open; stay idle+ // and keep scheduling pulls — the branch is already at origin tip.+ await this.notifyContentConflictsDetected(workingTreeEntries.map((entry) => entry.file));+ }- // Schedule with restart-aware remaining delay (FR: max(0, lastFetchUtc+interval - now))- const pullRemainingMs = computeRemainingMs(this.lastFetchUtc, this.pullIntervalSeconds);+ // Resolve the follower's credential tier before scheduling so an anonymous+ // pull-only follower's first cycle already uses the gentle cadence.+ if (this.mode === 'follow') await this.refreshAuthTier();++ // Schedule with restart-aware remaining delay (max(0, lastFetchUtc+interval - now)).+ const pullRemainingMs = computeRemainingMs(+ this.lastFetchUtc,+ this.currentPullIntervalSeconds(),+ );const pushRemainingMs = computeRemainingMs(this.lastSyncUtc, this.pushIntervalSeconds);this.schedulePull(pullRemainingMs > 0 ? pullRemainingMs : undefined);this.schedulePush(pushRemainingMs > 0 ? pushRemainingMs : undefined);@@ -569,41 +753,30 @@ export class SyncEngine {// ─── User-controlled enable/disable ────────────────────────────────────────/**- * Toggle sync on/off. Soft disable — cancels scheduled cycles but lets an- * in-flight pull/push finish cleanly to avoid leaving a partial merge.- * The caller persists the preference to project config; sync-state.json only+ * Set the sync mode. Soft transition — cancels scheduled cycles but lets an+ * in-flight pull/push finish cleanly to avoid leaving a partial merge. The+ * caller persists the preference to project config; sync-state.json only* records runtime status/history.+ *+ * Idempotent on a same-value call: the config re-apply path fires on both a+ * producer notify and a watcher echo, so this must not double-run.+ *+ * Switching between `pull` and `full` while local commits are ahead needs a+ * checkpoint + overlay conversion; that transition machinery is not wired here+ * yet, so this treats every non-`off` target as the plain enable path.*/- async setEnabled(enabled: boolean): Promise<void> {- if (this.syncEnabled === enabled) return;- this.syncEnabled = enabled;-- if (!enabled) {- if (this.pullTimer !== null) {- clearTimeout(this.pullTimer);- this.pullTimer = null;- }- if (this.pushTimer !== null) {- clearTimeout(this.pushTimer);- this.pushTimer = null;- }+ async setMode(mode: SyncMode, source: SyncModeChangeSource = 'config'): Promise<void> {+ if (this.mode === mode) return;+ const from = this.mode;+ this.mode = mode;+ log.info({ from, to: mode, source }, '[sync] mode changed');++ if (mode === 'off') {+ this.cancelScheduledCycles();// Drain in-flight cycles so disable is observed before the next cycle- // mutates state. Cap the wait so a wedged pull/push (hung network,- // unresponsive remote) can't hold the toggle forever — disable will- // still land in-memory; the stuck cycle logs its own outcome when it- // eventually resolves.- const DRAIN_TIMEOUT_MS = 30_000;- const drainStartMs = Date.now();- while (this.pullInFlight || this.pushInFlight) {- if (Date.now() - drainStartMs > DRAIN_TIMEOUT_MS) {- log.warn(- { pullInFlight: this.pullInFlight, pushInFlight: this.pushInFlight },- '[sync] setEnabled(false): timed out waiting for in-flight cycle to drain',- );- break;- }- await wait(50);- }+ // mutates state. Bounded so a wedged pull/push can't hold the toggle+ // forever — disable still lands in-memory.+ await this.drainInFlightCycles();this.pausedReason = undefined;this.clearPushError();this.clearPullError();@@ -612,10 +785,10 @@ export class SyncEngine {return;}- // Re-detect remote in case it was added (or removed) while sync was off.- // Unconditional — unlike refreshRemote() this handles both directions, so- // toggling sync on against an externally-removed remote correctly demotes- // to dormant instead of incorrectly transitioning to idle.+ // Enable (pull or full). Re-detect remote in case it was added (or removed)+ // while sync was off. Unconditional — unlike refreshRemote() this handles+ // both directions, so enabling against an externally-removed remote+ // correctly demotes to dormant instead of incorrectly transitioning to idle.this.hasRemote = await this.probeRemote();this.pausedReason = undefined;@@ -629,17 +802,180 @@ export class SyncEngine {return;}+ // Entering pull-only with local commits ahead of origin: those commits can+ // never be pushed, so fold them into the working-tree overlay and realign+ // the branch to origin. A full→pull downgrade first lets an in-flight push+ // finish (soft-disable drain) — it may land some of those commits — then+ // converts what remains; off→pull has nothing in flight to drain. Full mode+ // keeps stranded commits and pushes them, so it skips conversion entirely.+ if (mode === 'follow') {+ await this.drainInFlightCycles();+ this.cancelScheduledCycles();+ await this.convertStrandedCommitsToOverlay();+ }+this.transitionTo('idle');this.schedulePull(0);+ // No-op unless mode === 'full' (the push gate lives in schedulePush ++ // runPushCycle), so a pull-only project schedules pulls only.this.schedulePush();this.saveStateNow();// Re-check push permission so the engine state and the probe state stay- // consistent. Without this, a stale `denied` probe from a prior session- // would let setEnabled push the engine to 'idle' + schedule sync cycles- // that hit a 403. Matches the pattern in `trigger()`.+ // consistent. For `full`, a stale `denied` probe would otherwise let this+ // reach 'idle' + schedule cycles that hit a 403; for `pull`, the probe just+ // records the (expected) denial without pausing. Matches trigger()'s pattern.void this.probePushPermissionInternal('refresh');}+ /**+ * Back-compat adapter over {@link setMode}: `true`→`full`, `false`→`off`.+ * Retained so callers that predate the mode enum keep working; the idempotent+ * same-value early-return is preserved by setMode.+ */+ async setEnabled(enabled: boolean): Promise<void> {+ await this.setMode(enabled ? 'full' : 'off');+ }++ /** Cancel any pending pull/push timers so no scheduled cycle fires. */+ private cancelScheduledCycles(): void {+ if (this.pullTimer !== null) {+ clearTimeout(this.pullTimer);+ this.pullTimer = null;+ }+ if (this.pushTimer !== null) {+ clearTimeout(this.pushTimer);+ this.pushTimer = null;+ }+ }++ /**+ * Wait for any in-flight pull/push cycle to finish before mutating state that+ * would race it. Bounded so a wedged cycle (hung network, unresponsive+ * remote) can't block the caller forever — after the cap the caller proceeds+ * and the stuck cycle logs its own outcome when it eventually resolves.+ */+ private async drainInFlightCycles(): Promise<void> {+ const DRAIN_TIMEOUT_MS = 30_000;+ const drainStartMs = Date.now();+ while (this.pullInFlight || this.pushInFlight) {+ if (Date.now() - drainStartMs > DRAIN_TIMEOUT_MS) {+ log.warn(+ { pullInFlight: this.pullInFlight, pushInFlight: this.pushInFlight },+ '[sync] drain: timed out waiting for in-flight cycle',+ );+ break;+ }+ await wait(50);+ }+ }++ /**+ * Count local commits not yet on origin — the "unshared changes" figure a+ * downgrade confirm surfaces before those commits are folded into an overlay.+ * A fresh probe (not the cached `ahead`), so a UI can read it at an arbitrary+ * moment. Returns 0 when there's no remote or the branch is unborn.+ */+ async probeUnpushedCommitCount(): Promise<number> {+ if (!this.hasRemote || isUnbornHead(this.projectDir)) return 0;+ return this.unpushedCommitCount(this.gitHandle());+ }++ /**+ * Ahead count via the configured upstream (`git status`), falling back to an+ * explicit `rev-list` against `origin/<branch>` when the branch has no+ * upstream (an enable-time-divergence clone that never set tracking).+ */+ private async unpushedCommitCount(handle: GitHandle): Promise<number> {+ try {+ const status = await handle.git.status();+ if (status.tracking) return status.ahead;+ } catch {+ // Fall through to the rev-list probe below.+ }+ try {+ const out = (+ await handle.git.raw(['rev-list', '--count', `origin/${this.currentBranch}..HEAD`])+ ).trim();+ const n = Number.parseInt(out, 10);+ return Number.isFinite(n) ? n : 0;+ } catch {+ return 0;+ }+ }++ /**+ * Fold stranded local commits (ahead of origin) into a working-tree overlay+ * and realign the branch. Called when entering pull-only, where those commits+ * can never be pushed.+ *+ * A `--mixed` reset to the merge base moves the branch ref and index but never+ * touches the working tree, so the committed content survives verbatim as an+ * uncommitted overlay and nothing on screen changes. Ahead-only lands directly+ * on origin's tip (the merge base IS the tip); a diverged branch lands on the+ * common ancestor with the local edits as overlay, and the next fast-forward+ * cycle carries it to origin's tip, reconciling per B1. The pre-conversion+ * tree is checkpointed to the recoverable timeline first (before the ref+ * moves) so the stranded content is never only in the reflog.+ */+ private async convertStrandedCommitsToOverlay(): Promise<void> {+ if (!this.hasRemote || isUnbornHead(this.projectDir)) return;+ const handle = this.gitHandle();++ let ahead: number;+ try {+ ahead = await this.unpushedCommitCount(handle);+ } catch (e) {+ log.warn(+ { err: e },+ '[sync] pull-only: could not probe stranded commits — skipping conversion',+ );+ return;+ }+ if (ahead === 0) return;++ try {+ await this.checkpointBeforeStrandedConversion?.({ branch: this.currentBranch, ahead });+ } catch (e) {+ // The checkpoint is a recovery convenience; the reset below still leaves+ // the stranded commits reachable via the reflog / ORIG_HEAD, so proceed.+ log.warn({ err: e }, '[sync] pull-only: stranded-commit checkpoint failed — proceeding');+ }++ try {+ const base = (+ await handle.git.raw(['merge-base', 'HEAD', `origin/${this.currentBranch}`])+ ).trim();+ // Gate the HEAD/file watchers while the ref moves. The working tree is+ // byte-identical across a `--mixed` reset, so no reconciliation is owed —+ // the gate just suppresses a spurious mid-transition pass.+ this.setBatchInProgress?.(true);+ try {+ await withParentLock(() => handle.git.raw(['reset', '--mixed', base]));+ } finally {+ this.setBatchInProgress?.(false);+ }+ const status = await handle.git.status();+ this.ahead = status.ahead;+ this.behind = status.behind;+ this.pausedReason = undefined;+ log.info(+ { ahead, behind: this.behind },+ '[sync] pull-only: folded stranded local commits into a working-tree overlay',+ );+ } catch (e) {+ // Reset failed — leave the branch as-is, but surface the divergence now+ // rather than relying on the next pull: setMode continues to idle + a+ // scheduled pull, so without a paused reason the badge shows a clean idle+ // while stranded, unpushable commits remain. (transitionTo does not clear+ // pausedReason, so this survives setMode's subsequent idle transition.)+ this.pausedReason = 'diverged-local-commits';+ log.warn(+ { err: e },+ '[sync] pull-only: stranded-commit conversion failed — leaving branch as-is',+ );+ }+ }+// ─── Credential change (reconnect) ──────────────────────────────────────────/**@@ -657,7 +993,7 @@ export class SyncEngine {* during healthy operation is cheap.*/async notifyCredentialsChanged(): Promise<void> {- if (!this.syncEnabled) return;+ if (this.mode === 'off') return;// A credential change is precisely when any cached gh token is stale (the// user just signed in / switched accounts). Drop it BEFORE the auth-error@@ -717,9 +1053,18 @@ export class SyncEngine {// await this probe — doubling the latency of every manual sync to// close a single-cycle race isn't worth it.void this.probePushPermissionInternal('refresh');- // Log why a trigger is a no-op so "Sync now returns OK but nothing happens"- // is diagnosable from the server terminal. The cycle guards silently- // early-return in these states; surface them here.++ if (op === 'pull') {+ // A one-shot pull runs in every mode (including off/null): it never+ // commits, never enables anything, and records a bounded outcome rather+ // than a silent no-op. Its own state-gating decides refuse-vs-run.+ await this.pullOnce();+ return;+ }++ // Log why a push/sync trigger is a no-op so "Sync now returns OK but nothing+ // happens" is diagnosable from the server terminal. The cycle guards+ // silently early-return in these states; surface them here.if (this.state === 'dormant' ||this.state === 'disabled' ||@@ -730,7 +1075,7 @@ export class SyncEngine {{op,state: this.state,- syncEnabled: this.syncEnabled,+ mode: this.mode,hasRemote: this.hasRemote,pausedReason: this.pausedReason,conflictCount: this.conflictCount,@@ -742,8 +1087,6 @@ export class SyncEngine {}if (op === 'push') {await this.runPushCycle();- } else if (op === 'pull') {- await this.runPullCycle();} else {// Push first so pending working-tree edits get committed via the// isolated-index path. A subsequent merge then has a clean tree@@ -753,6 +1096,77 @@ export class SyncEngine {}}+ /**+ * Run a single pull and return its bounded outcome — the primitive a+ * downstream surface (e.g. an update button) triggers via `op: 'pull'`.+ *+ * Unlike the background cycle, this runs regardless of mode: an `off`/`null`+ * project fetches and fast-forwards via the B1 variant (never committing) and+ * is left exactly as inactive as it started — no mode flip, no scheduled loop.+ * A `pull`/`full` project runs its normal cycle variant and keeps its+ * background loop alive.+ *+ * State-gating is explicit and always recorded (never a silent no-op): the+ * pull is refused when a cycle is already in flight, an unresolved conflict+ * holds the tree, or there is nothing to pull from. Every path writes+ * `lastPullUtc` + `lastPullOutcome` and signals `sync-status`, so a consumer+ * that read status before triggering can wait for the timestamp to change and+ * read the outcome of a pull that completed after its trigger.+ */+ async pullOnce(): Promise<PullOutcome> {+ const mode = this.mode;+ const outcome = await this.runOneShotPull();+ // One-shot outcomes are the discrete, consumer-visible pull events (e.g. a+ // downstream update button); log each so their distribution is observable+ // without the per-cycle noise a background-pull log would add.+ log.info({ mode, outcome }, '[sync] one-shot pull complete');+ return outcome;+ }++ private async runOneShotPull(): Promise<PullOutcome> {+ // Single-flight: a background or concurrent one-shot cycle already owns the+ // working tree. Refuse rather than race it — the consumer retries on refused.+ if (this.pullInFlight || this.pushInFlight) return this.recordPullOutcome('refused');+ // The full-mode conflict resolver owns the tree until the user resolves.+ if (this.state === 'conflict') return this.recordPullOutcome('refused');+ // Nothing to pull from, or no commits to fast-forward against yet.+ if (!this.hasRemote || isUnbornHead(this.projectDir)) return this.recordPullOutcome('refused');++ // Snapshot the resting posture so an off/null project can be restored to it+ // afterwards — the cycle transitions through fetching/pulling/idle, which+ // must not leave a never-enabled project looking active.+ const restingMode = this.mode;+ const restingState = this.state;+ const restingPausedReason = this.pausedReason;+ this.pullInFlight = true;+ try {+ return this.recordPullOutcome(await this.doPullCycle());+ } finally {+ this.pullInFlight = false;+ if (restingMode === 'off') {+ this.pausedReason = restingPausedReason;+ this.transitionTo(restingState);+ } else {+ // A background timer that fired during this one-shot early-returned on+ // the single-flight guard without rescheduling; re-arm the loop.+ this.schedulePull();+ }+ }+ }++ /**+ * Record a pull's completion timestamp + outcome and signal `sync-status`,+ * then echo the outcome back to the caller. Called at every pull completion+ * (background and one-shot) so `lastPullUtc` changes on each — the signal the+ * change-detection consumer contract relies on.+ */+ private recordPullOutcome(outcome: PullOutcome): PullOutcome {+ this.lastPullUtc = new Date().toISOString();+ this.lastPullOutcome = outcome;+ this.cc1Broadcaster?.signal('sync-status');+ return outcome;+ }+// ─── Status ────────────────────────────────────────────────────────────────getStatus(): SyncStatus {@@ -761,12 +1175,15 @@ export class SyncEngine {lastSyncUtc: this.lastSyncUtc,lastFetchUtc: this.lastFetchUtc,lastPushedSha: this.lastPushedSha,+ lastPullUtc: this.lastPullUtc,+ lastPullOutcome: this.lastPullOutcome,ahead: this.ahead,behind: this.behind,consecutiveFailures: this.consecutiveFailures,conflictCount: this.conflictCount,hasRemote: this.hasRemote,- syncEnabled: this.syncEnabled === true,+ syncEnabled: this.mode !== 'off',+ syncMode: this.mode,identityUnresolved: this.identityUnresolved,// Resolve the origin label/URL only when a remote exists — keeps the// common no-remote dormant path free of `.git/config` reads.@@ -894,14 +1311,15 @@ export class SyncEngine {const prev = this.pushPermission;this.pushPermission = next;- // If the user already has sync enabled and the probe says denied, pause- // the engine in-memory. Mirrors the existing pausedReason precedent+ // A denial only pauses `full` mode, which needs push permission it just+ // learned it lacks. A pull-only follower expects to lack push — denial is+ // its normal condition, so it keeps fetching (no pause, no state change).+ // Pausing in-memory mirrors the existing pausedReason precedent// ('detached-head', 'protected-branch', ...) — no disk write. The// persistent-write alternative was rejected at spec time because it- // would silently mutate the user's preference and create a migration- // burden when continued read-only fetch eventually lands.+ // would silently mutate the user's preference.let transitioned = false;- if (next.checkStatus === 'denied' && this.syncEnabled === true) {+ if (next.checkStatus === 'denied' && this.mode === 'full') {if (this.pausedReason !== 'no-push-permission' || this.state !== 'disabled') {this.pausedReason = 'no-push-permission';this.transitionTo('disabled'); // already broadcasts CC1 sync-status@@ -927,7 +1345,7 @@ export class SyncEngine {// Either way, `transitioned = true` triggers the CC1 broadcast so the// popover + settings drop the disabled-with-reason copy immediately.this.pausedReason = undefined;- if (this.state === 'disabled' && this.syncEnabled === true) {+ if (this.state === 'disabled' && this.mode === 'full') {this.transitionTo('idle');}transitioned = true;@@ -962,14 +1380,12 @@ export class SyncEngine {if (!detected) return;this.hasRemote = true;- log.info(- { syncEnabled: this.syncEnabled },- '[sync] remote detected post-boot — re-evaluating state',- );+ log.info({ mode: this.mode }, '[sync] remote detected post-boot — re-evaluating state');- if (this.syncEnabled === true) {+ if (this.mode !== 'off') {this.transitionTo('idle');this.schedulePull(0);+ // No-op unless mode === 'full' (the push gate); pull-only schedules pulls.this.schedulePush();} else {this.transitionTo('disabled');@@ -1021,7 +1437,12 @@ export class SyncEngine {* `conflict` state when the last entry clears.*/async reconcileConflictsFromGit(): Promise<void> {- if (this.conflictCount === 0) return;+ // Working-tree conflicts (pull-only B1) have no MERGE_HEAD and are managed by+ // the pull cycle (re-pin / auto-dissolve) + the resolve path. This+ // git-index reconciliation governs merge-native entries only — leave the+ // working-tree entries untouched so the batch-end drain doesn't wipe them.+ const mergeNative = this.conflictStore.list().filter((e) => e.variant !== 'working-tree');+ if (mergeNative.length === 0) return;const before = this.conflictCount;// Linked-worktree safety (see `start()`): use the resolved gitdir.const gitDir = resolveGitDir(this.projectDir);@@ -1030,18 +1451,18 @@ export class SyncEngine {if (!mergeInProgress) {log.info(- { cleared: before },- '[sync] external resolve detected (no MERGE_HEAD) — clearing tracked conflicts',+ { cleared: mergeNative.length },+ '[sync] external resolve detected (no MERGE_HEAD) — clearing merge-native conflicts',);- this.conflictStore.clear();- this.conflictCount = 0;+ for (const entry of mergeNative) this.conflictStore.removeConflict(entry.file);+ this.conflictCount = this.conflictStore.count();} else {try {const handle = this.gitHandle();const stillUnmerged = new Set(await listNames(handle.git, ['diff', '--name-only', '--diff-filter=U']),);- for (const entry of this.conflictStore.list()) {+ for (const entry of mergeNative) {if (!stillUnmerged.has(entry.file)) {this.conflictStore.removeConflict(entry.file);}@@ -1086,6 +1507,11 @@ export class SyncEngine {// racing the API response, and the false-edge callback in// server-factory.ts flushes deferred persistence so the resolved// bytes land before the next sync cycle observes the state.+ // A working-tree resolution may not change disk bytes (keep-mine), so the+ // file-watcher's `case 'update'` clear can't be relied on — fire the+ // resolved callback explicitly to clear the doc's conflict lifecycle.+ const wasWorkingTree =+ this.conflictStore.list().find((c) => c.file === file)?.variant === 'working-tree';this.setBatchInProgress?.(true);try {try {@@ -1102,6 +1528,13 @@ export class SyncEngine {this.scheduleSaveState();throw e;}+ if (wasWorkingTree) {+ // The pull-only conflict lifecycle's terminal event: a user picked a+ // side in the resolver (`strategy` is bounded — mine/theirs/content/+ // delete). Merge-native resolutions are a separate lifecycle.+ log.info({ choice: strategy }, '[sync] pull-only: conflict resolved by choice');+ await this.notifyContentConflictsResolved([file]);+ }this.conflictCount = this.conflictStore.count();if (this.conflictCount === 0 && this.state === 'conflict') {this.transitionTo('idle');@@ -1158,6 +1591,10 @@ export class SyncEngine {}private schedulePush(overrideDelayMs?: number): void {+ // Only `full` mode pushes. Skipping the timer here means a pull-only project+ // never even schedules a push cycle; runPushCycle carries the authoritative+ // consent gate for any direct caller (e.g. trigger('push')).+ if (this.mode !== 'full') return;if (this.pushTimer !== null) clearTimeout(this.pushTimer);const delayMs = overrideDelayMs ?? jitteredMs(this.pushIntervalSeconds);this.pushTimer = setTimeout(() => {@@ -1168,10 +1605,57 @@ export class SyncEngine {}, delayMs);}+ /**+ * Resolve which credential tier the follower fetches as, mirroring the push+ * probe's gh → token-store → anonymous order. The probe doesn't surface which+ * tier it used, so the engine resolves it from the credential sources it+ * already holds. gh resolution is cached (at most one spawn per minute); the+ * token store is read at most once per pull.+ */+ private async resolveAuthTier(): Promise<PullAuthTier> {+ const host = this.syncGhTokenHost();+ if (this.ghTokenSource.get(host) !== null) return 'authenticated';+ if (this.tokenStore) {+ try {+ const entry = await this.tokenStore.get(host);+ if (entry?.token) return 'authenticated';+ } catch (err) {+ // A token-store backend can throw on read (corrupted keyring, EACCES).+ // Degrade to the anonymous cadence rather than letting a credential-read+ // failure abort the pull cycle or sync start. Mirrors the same+ // fall-through in github-permissions' probe token resolution.+ log.warn({ err }, '[sync] auth-tier token-store lookup threw — treating as anonymous');+ }+ }+ return 'anonymous';+ }++ /** Refresh the cached {@link authTier} so the next schedule reflects it. */+ private async refreshAuthTier(): Promise<void> {+ this.authTier = await this.resolveAuthTier();+ }++ /**+ * Base pull interval (seconds) for the current mode + auth tier, before jitter+ * and backoff. Only pull-only anonymous followers deviate from the configured+ * interval; full sync and authenticated pull-only keep it unchanged.+ */+ private currentPullIntervalSeconds(): number {+ if (this.mode !== 'follow') return this.pullIntervalSeconds;+ return pullIntervalSecondsForAuthTier(+ this.pullIntervalSeconds,+ this.authTier === 'anonymous' ? 'anonymous' : 'authenticated',+ );+ }+private effectivePullDelayMs(): number {- const failures = this.consecutiveFailures;- const bkoff = backoffMs(failures);- return bkoff > 0 ? bkoff : jitteredMs(this.pullIntervalSeconds);+ const bkoff = backoffMs(this.consecutiveFailures);+ // Jitter the backoff too, not just the normal interval: anonymous followers+ // of the same public repo fail in lockstep during an outage, so an un-jittered+ // fixed backoff (5/15/60 min) would retry at identical offsets and spike read+ // pressure on the recovering origin. jitteredMs takes seconds.+ const baseSeconds = bkoff > 0 ? bkoff / 1000 : this.currentPullIntervalSeconds();+ return jitteredMs(baseSeconds);}// ─── Pull cycle ────────────────────────────────────────────────────────────@@ -1198,16 +1682,20 @@ export class SyncEngine {return;}+ // Re-resolve the credential tier so a follower who signs in (or out)+ // mid-session picks up the matching cadence on the next reschedule.+ if (this.mode === 'follow') await this.refreshAuthTier();+this.pullInFlight = true;try {- await this.doPullCycle();+ this.recordPullOutcome(await this.doPullCycle());} finally {this.pullInFlight = false;this.schedulePull(); // chain: schedule next after current completes}}- private async doPullCycle(): Promise<void> {+ private async doPullCycle(): Promise<PullOutcome> {const handle = this.gitHandle();// Detached HEAD check@@ -1218,13 +1706,13 @@ export class SyncEngine {this.transitionTo('disabled');this.pausedReason = 'detached-head';log.warn({}, '[sync] detached HEAD — pausing sync');- return;+ return 'refused';}branch = b;this.currentBranch = branch;} catch (e) {this.handleError(classifyGitError(e instanceof Error ? e : new Error(String(e))), 'pull');- return;+ return 'error';}// Fetch@@ -1237,7 +1725,7 @@ export class SyncEngine {} catch (e) {const classified = classifyGitError(e instanceof Error ? e : new Error(String(e)));this.handleError(classified, 'pull');- return;+ return 'error';}// Check ahead/behind@@ -1249,7 +1737,17 @@ export class SyncEngine {// Non-fatal — continue with previous counts}- // Merge if behind and no unresolved conflicts+ // Merge if behind. Pull-only runs the B1 cycle even with existing+ // working-tree conflicts tracked — it re-pins them against the new tip and+ // fast-forwards the rest of the repo (the engine stays idle, not paused, so+ // followers keep updating while a single doc waits on resolution). The+ // full-sync merge still gates on `conflictCount === 0`: a MERGE_HEAD in+ // flight must be resolved before another merge starts.+ if (this.behind > 0 && this.mode !== 'full') {+ const outcome = await this.doPullCycleB1(handle, branch);+ this.scheduleSaveState();+ return outcome;+ }if (this.behind > 0 && this.conflictCount === 0) {this.transitionTo('pulling');// Gate batch to suppress HEAD watcher reconciliation during SyncEngine merge@@ -1262,7 +1760,7 @@ export class SyncEngine {// with the incoming merge — sync isn't blocked by adjacent dirt.await this.commitDirtyContentFilesToHead(handle);const mergePrep = await this.prepareForMerge(handle, branch);- if (!mergePrep.proceed) return;+ if (!mergePrep.proceed) return 'refused';try {await handle.git.merge([`origin/${branch}`]);this.lastSyncUtc = new Date().toISOString();@@ -1271,29 +1769,598 @@ export class SyncEngine {} finally {if (mergePrep.needsStashPop) await this.popPreMergeStash(handle);}+ this.scheduleSaveState();+ return 'succeeded';} catch (e) {const classified = classifyGitError(e instanceof Error ? e : new Error(String(e)));if (classified.class === 'semantic' && classified.subclass === 'merge-conflict') {- // Conflict detected — transition to conflict state+ // Conflict detected — content conflicts pause in 'conflict' state;+ // an all-non-content merge auto-resolves and returns to idle. But+ // auto-resolution can itself fail (a rejected commit, an aborted+ // merge): those paths set pullError and return to idle, so treat a+ // set pullError as the error outcome rather than reporting success.await this.handleMergeConflict();- } else {- this.handleError(classified, 'pull');+ if (this.state === 'conflict') return 'conflict';+ return this.pullError ? 'error' : 'succeeded';}- return;+ this.handleError(classified, 'pull');+ return 'error';} finally {this.setBatchInProgress?.(false);}- } else {+ }+ // Not behind (up-to-date), or behind but holding a conflict that blocks the+ // merge — either way the tree stays put this cycle.+ this.transitionTo('idle');+ this.scheduleSaveState();+ return this.behind === 0 ? 'up-to-date' : 'conflict';+ }++ /**+ * Pull-only fast-forward cycle. Fetch has already landed `origin/<branch>`+ * and the caller has confirmed the branch is behind. This never commits,+ * merges, stashes, or leaves a MERGE_HEAD: the branch advances only by+ * fast-forward, and uncommitted local edits ride along as a working-tree+ * overlay on the new tip.+ *+ * Git's own fast-forward guard is asymmetric, which forces the choreography:+ * - It refuses to clobber an uncommitted edit to a file the incoming tip+ * also changed — even a byte-identical one — so every overlapping edit is+ * restored to HEAD first, then re-applied after the fast-forward.+ * - It does NOT protect an uncommitted DELETION: a locally-removed file the+ * tip modifies is silently resurrected. So a deletion overlay is+ * re-applied explicitly afterwards.+ *+ * Overlapping edits to CONTENT files are reconciled per file:+ * different-line edits auto-combine into a new overlay; same-line collisions+ * keep the local edit and raise a working-tree conflict entry the resolver+ * serves. The engine stays idle (not paused) so the rest of the repo keeps+ * fast-forwarding while a single doc waits on resolution.+ */+ private async doPullCycleB1(handle: GitHandle, branch: string): Promise<PullOutcome> {+ this.transitionTo('pulling');++ // Local commits ahead of origin cannot fast-forward. Pull-only never merges+ // or commits to reconcile them: leave the branch where it is with the+ // overlay intact and surface a paused reason. (Converting stranded local+ // commits into an overlay is a mode-transition concern handled elsewhere.)+ if (this.ahead > 0) {+ this.clearPullError();+ this.pausedReason = 'diverged-local-commits';this.transitionTo('idle');+ log.warn(+ { ahead: this.ahead, behind: this.behind },+ '[sync] pull-only: local history diverged — not fast-forwardable, skipping cycle',+ );+ return 'refused';}- this.scheduleSaveState();+ // The overlay = tracked paths whose working tree differs from HEAD.+ // Intersect with the paths the incoming tip changes: only that intersection+ // can block the fast-forward; non-overlapping overlay files ride through.+ let oldHead: string;+ let overlapping: string[];+ try {+ 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}`]),+ );+ overlapping = overlayPaths.filter((p) => incoming.has(p));+ } catch (e) {+ this.handleError(classifyGitError(e instanceof Error ? e : new Error(String(e))), 'pull');+ return 'error';+ }++ // Existing working-tree conflicts, so an overlap that already collided can+ // be re-pinned to the new tip (or dissolved when the collision disappears).+ const existing = new Map<string, ConflictEntry>();+ for (const e of this.conflictStore.list()) {+ if (e.variant === 'working-tree') existing.set(e.file, e);+ }++ // Read-only planning pass over origin's blobs — decide each overlapping+ // path's disposition before mutating the tree. A throw here (an unreadable+ // blob from `cat-file`, a corrupt object store) must route through+ // handleError so consecutiveFailures increments and the retry backs off,+ // rather than propagating uncaught and re-firing at the base interval.+ let plan: Awaited<ReturnType<typeof this.planOverlapReconciliation>>;+ try {+ plan = await this.planOverlapReconciliation(handle, branch, oldHead, overlapping, existing);+ } catch (e) {+ this.handleError(classifyGitError(e instanceof Error ? e : new Error(String(e))), 'pull');+ return 'error';+ }++ // Gate the file-watcher / HEAD-watcher reconciliation while the tree is+ // mutated, exactly as the full-sync merge path does.+ this.setBatchInProgress?.(true);+ try {+ // Restore every overlapping path to HEAD so the fast-forward isn't refused.+ if (overlapping.length > 0) {+ // Snapshot the overlay bytes before the reset destroys them on disk.+ // Between the reset and the overlay re-write below they live only in the+ // in-memory plan, so a hard crash in that window would lose them for a+ // doc with no live client; the checkpoint keeps the pre-reset content+ // recoverable. Best-effort — a failed checkpoint only forfeits the+ // crash-window net, so proceed (mirrors convertStrandedCommitsToOverlay).+ try {+ await this.checkpointBeforeOverlayRestore?.({ branch, paths: overlapping.length });+ } catch (e) {+ log.warn(+ { err: e, paths: overlapping.length },+ '[sync] pull-only: overlay checkpoint failed before restore — proceeding',+ );+ }+ try {+ await handle.git.raw([+ 'restore',+ '--source=HEAD',+ '--staged',+ '--worktree',+ '--',+ ...overlapping,+ ]);+ } catch (e) {+ // Couldn't clear the overlay — abandon the cycle without mutating+ // history. The overlay is still on disk; route through handleError so+ // consecutiveFailures increments and the retry backs off instead of+ // re-firing at the base interval against a persistently locked file.+ log.warn(+ { err: e },+ '[sync] pull-only: failed to restore overlay before fast-forward — skipping cycle',+ );+ this.handleError(classifyGitError(e instanceof Error ? e : new Error(String(e))), 'pull');+ return 'error';+ }+ }++ const ff = await this.fastForwardOnly(handle, branch);+ if (!ff.ok) {+ // The FF didn't happen; restore the ORIGINAL overlay (not the planned+ // combine, which assumed the tip landed) so no local edit is lost. The+ // only expected refusal is a divergence the ahead-check missed (TOCTOU).+ // If even this restore fails, the overlapping paths are still reset to+ // HEAD and the user's bytes live only in the in-memory plan — surface it+ // as an error with backoff, never a clean 'refused' idle.+ try {+ this.applyOverlayPlan(plan.mineRestore, plan.deletions);+ } catch (e) {+ log.error(+ { err: e, refusal: ff.refusal },+ '[sync] pull-only: failed to restore overlay after fast-forward refusal',+ );+ this.handleError(classifyGitError(e instanceof Error ? e : new Error(String(e))), 'pull');+ return 'error';+ }+ if (ff.timedOut) {+ // A wedged ff-only subprocess is an operational failure, not a+ // semantic refusal — surface it with backoff so a stuck credential+ // helper or degraded disk doesn't re-fire at the base interval.+ log.warn({}, '[sync] pull-only: fast-forward timed out — backing off');+ this.handleError(+ classifyGitError(+ new Error(`git merge --ff-only timed out after ${FF_ONLY_TIMEOUT_MS}ms`),+ ),+ 'pull',+ );+ return 'error';+ }+ if (ff.refusal === 'divergence') this.pausedReason = 'diverged-local-commits';+ this.transitionTo('idle');+ log.warn(+ { refusal: ff.refusal, stderr: ff.stderr.slice(0, 200) },+ '[sync] pull-only: fast-forward refused — skipping cycle',+ );+ return 'refused';+ }++ // Branch is at origin tip. Apply the reconciliation on the new base. A+ // failure here means the fast-forward landed but the user's overlay+ // didn't reach disk — surface it rather than returning a clean outcome.+ try {+ this.applyOverlayPlan(plan.writes, plan.deletions);+ } catch (e) {+ log.error({ err: e }, '[sync] pull-only: failed to apply overlay after fast-forward');+ this.handleError(classifyGitError(e instanceof Error ? e : new Error(String(e))), 'pull');+ return 'error';+ }+ // Persist the conflict-store deltas. addConflict/removeConflict mutate+ // in-memory then return false when the disk write failed: the fast-forward+ // landed and the overlay is on disk, but a restart would read a+ // conflicts.json missing these entries — the resolver would lose the+ // pinned theirs blob and the user's overlay would strand with no conflict+ // UI. Surface it as an error so the outcome isn't reported clean and the+ // next cycle retries, rather than diverging in-memory state from disk.+ let conflictsPersisted = true;+ for (const entry of plan.upserts) {+ conflictsPersisted = this.conflictStore.addConflict(entry) && conflictsPersisted;+ }+ for (const file of plan.dissolved) {+ conflictsPersisted = this.conflictStore.removeConflict(file) && conflictsPersisted;+ }+ this.conflictCount = this.conflictStore.count();+ if (!conflictsPersisted) {+ log.error(+ {},+ '[sync] pull-only: failed to persist conflict state after fast-forward — surfacing as error',+ );+ this.handleError(+ classifyGitError(new Error('failed to persist conflict state after fast-forward')),+ 'pull',+ );+ return 'error';+ }++ this.lastSyncUtc = new Date().toISOString();+ this.behind = 0;+ this.clearPullError();+ this.pausedReason = undefined;+ this.transitionTo('idle');++ if (plan.newConflicts.length > 0) {+ await this.notifyContentConflictsDetected(plan.newConflicts);+ }+ if (plan.dissolved.length > 0) {+ await this.notifyContentConflictsResolved(plan.dissolved);+ }+ if (plan.newConflicts.length > 0 || plan.dissolved.length > 0) {+ this.cc1Broadcaster?.signal('sync-status');+ }++ const overlayStock = await this.countStandingOverlay(handle);+ log.info(+ {+ created: plan.newConflicts.length,+ autoCombined: plan.autoCombined.length,+ autoDissolved: plan.dissolved.length,+ autoRestored: plan.autoRestored.length,+ overlayStock,+ },+ '[sync] pull-only: fast-forwarded to origin tip',+ );++ // A newly-surfaced same-line collision is the consumer-visible "conflict"+ // signal; re-pins/dissolves of pre-known conflicts still read as a clean+ // fast-forward.+ return plan.newConflicts.length > 0 ? 'conflict' : 'succeeded';+ } finally {+ this.setBatchInProgress?.(false);+ }+ }++ /**+ * Run `git merge --ff-only` via a direct child process so the exit code is+ * observable (simple-git does not surface it reliably), and classify any+ * refusal. `core.autocrlf=false` mirrors the sync git handle so the FF's+ * working-tree update keeps the byte-exact LF round-trip.+ */+ private async fastForwardOnly(+ handle: GitHandle,+ branch: string,+ ): Promise<+ | { ok: true }+ | {+ ok: false;+ refusal: FastForwardRefusal;+ stderr: string;+ exitCode: number | null;+ timedOut: boolean;+ }+ > {+ 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 },+ );+ return { ok: true };+ } catch (e) {+ const err = e as {+ code?: number | string;+ stderr?: string;+ killed?: boolean;+ signal?: string;+ };+ // `child_process` kills the child on timeout (`killed`, SIGTERM). That is+ // an operational hang, not a semantic fast-forward refusal — flag it so+ // the caller takes the error/backoff path instead of a clean 'refused'.+ const timedOut = err.killed === true || err.signal === 'SIGTERM';+ const exitCode = typeof err.code === 'number' ? err.code : null;+ const stderr =+ typeof err.stderr === 'string' ? err.stderr : e instanceof Error ? e.message : String(e);+ return {+ ok: false,+ refusal: classifyFastForwardRefusal({ exitCode, stderr }),+ stderr,+ exitCode,+ timedOut,+ };+ }+ }++ /**+ * Classify each overlapping path (working-tree edit ∩ incoming change) into a+ * reconciliation action, reading only origin's blobs (no tree mutation yet):+ *+ * - byte-identical → converge (nothing to write; the FF re-materialises it)+ * - non-content → keep the overlay verbatim (never line-merge configs)+ * - content, combinable → line-level auto-combine into a new overlay+ * - content, collision → keep-mine + a working-tree conflict entry pinned to+ * the tip/base blobs the resolver serves+ *+ * Existing conflicts re-pin to the new tip, or dissolve when the tip's change+ * makes the collision combinable or byte-identical.+ *+ * `mineRestore` carries every present overlay verbatim for the fast-forward-+ * refusal path, where the planned combine (which assumed the tip landed) must+ * not be written.+ */+ private async planOverlapReconciliation(+ handle: GitHandle,+ branch: string,+ oldHead: string,+ overlapping: string[],+ existing: Map<string, ConflictEntry>,+ ): Promise<{+ writes: Array<{ path: string; bytes: Buffer }>;+ mineRestore: Array<{ path: string; bytes: Buffer }>;+ deletions: string[];+ upserts: ConflictEntry[];+ dissolved: string[];+ newConflicts: string[];+ autoCombined: string[];+ autoRestored: string[];+ }> {+ const writes: Array<{ path: string; bytes: Buffer }> = [];+ const mineRestore: Array<{ path: string; bytes: Buffer }> = [];+ const deletions: string[] = [];+ const upserts: ConflictEntry[] = [];+ const dissolved: string[] = [];+ const newConflicts: string[] = [];+ const autoCombined: string[] = [];+ // Content docs deleted locally that the tip modified — restored from origin+ // rather than conflicted (pull-only follower posture). Counted in the pull+ // telemetry so how often a follower's deletion yields to upstream is visible.+ const autoRestored: string[] = [];++ for (const p of overlapping) {+ const priorEntry = existing.get(p);+ const hadEntry = priorEntry !== undefined;++ if (!existsSync(join(this.projectDir, p))) {+ // Deleted locally and changed on the incoming tip.+ try {+ // Probe origin for its own throw behavior — a success means origin+ // still has the path (modify), a genuine miss means origin removed it.+ await handle.git.revparse([`origin/${branch}:${p}`]);+ } catch (e) {+ if (this.classifyRefReadFailure(e) === 'error') {+ // Unexpected failure probing origin — do NOT infer an agreed+ // deletion. Keep the deletion this cycle and re-evaluate next pull.+ deletions.push(p);+ log.warn(+ { err: e, path: p },+ '[sync] pull-only: unexpected error probing origin for a deleted overlay — deferring reconcile',+ );+ continue;+ }+ // Genuinely absent at origin — origin also removed it, deletion agreed.+ deletions.push(p);+ if (hadEntry) dissolved.push(p);+ continue;+ }+ if (!this.isContentConflictPath(p)) {+ // Non-content file (config/asset) deleted locally, modified on origin:+ // keep the deletion (these sit outside the content-doc follow model).+ deletions.push(p);+ continue;+ }+ // Content doc deleted locally, modified on origin. In pull-only the+ // follower tracks upstream, so accept the remote's change and let the+ // fast-forward restore the file rather than surfacing a delete/modify+ // conflict. Nothing authored is lost — the local side was a deletion —+ // so the deletion intent yields to upstream: do NOT re-apply the+ // deletion (leave `p` out of `deletions` so the FF resurrects it) and+ // dissolve any prior conflict entry for this path.+ autoRestored.push(p);+ if (hadEntry) dissolved.push(p);+ continue;+ }++ // Modified overlay.+ let mineBuf: Buffer;+ try {+ mineBuf = readFileSync(join(this.projectDir, p));+ } catch {+ continue; // vanished between status and read — treat as non-overlap+ }+ mineRestore.push({ path: p, bytes: mineBuf });+ const mineStr = mineBuf.toString('utf-8');++ let theirsStr: string | null = null;+ try {+ theirsStr = await handle.git.raw(['show', `origin/${branch}:${p}`]);+ } catch (e) {+ // `null` covers both "origin removed the path" (a modify/delete the+ // overlay keeps-mine over) and an unexpected read failure. Only the+ // latter is worth a log — a transient failure that keeps the overlay+ // but leaves a real collision un-surfaced this cycle should be+ // diagnosable rather than invisible.+ if (this.classifyRefReadFailure(e) === 'error') {+ log.warn(+ { err: e, path: p },+ '[sync] pull-only: unexpected error reading origin blob — keeping overlay, deferring reconcile',+ );+ }+ theirsStr = null;+ }++ if (theirsStr !== null && theirsStr === mineStr) {+ // Byte-identical: the FF re-materialises the identical bytes. Converged.+ if (hadEntry) dissolved.push(p);+ continue;+ }++ if (theirsStr === null || !this.isContentConflictPath(p)) {+ // Non-content or unreadable tip blob: keep the overlay verbatim, never+ // line-merge or escalate (matches adjacent-config behavior).+ writes.push({ path: p, bytes: mineBuf });+ continue;+ }++ const baseSha = hadEntry+ ? priorEntry.baseSha+ : await this.gitBlobSha(handle, `${oldHead}:${p}`);+ const baseStr = baseSha ? await this.gitBlobContent(handle, baseSha) : '';+ const combined = tryLineLevelCombine(baseStr, mineStr, theirsStr);+ if (combined.clean) {+ writes.push({ path: p, bytes: Buffer.from(combined.merged, 'utf-8') });+ autoCombined.push(p);+ if (hadEntry) dissolved.push(p); // the tip's change dissolved the collision+ continue;+ }++ // Same-line collision: keep-mine on disk, pin theirs+base for the resolver.+ writes.push({ path: p, bytes: mineBuf });+ const theirsSha = await this.gitBlobSha(handle, `origin/${branch}:${p}`);+ if (theirsSha === undefined) {+ // The tip blob was readable moments ago (theirsStr is non-null), so a+ // missing SHA here is a transient git failure, not a semantic absence.+ // A working-tree entry with no pinned theirs blob can't offer the+ // 'theirs' resolution, so keep the overlay and let the next pull+ // re-detect the collision rather than persist an unresolvable entry.+ log.warn(+ { path: p },+ '[sync] pull-only: could not pin origin blob for a collision — keeping overlay, deferring',+ );+ continue;+ }+ upserts.push({+ file: p,+ detectedAt: priorEntry?.detectedAt ?? new Date().toISOString(),+ variant: 'working-tree',+ theirsSha,+ baseSha,+ });+ if (!hadEntry) newConflicts.push(p);+ }++ return {+ writes,+ mineRestore,+ deletions,+ upserts,+ dissolved,+ newConflicts,+ autoCombined,+ autoRestored,+ };+ }++ /**+ * Apply a planned overlay: write the chosen bytes, then re-apply any+ * uncommitted deletions the fast-forward would otherwise resurrect (git's+ * overwrite guard does not cover a delete overlay).+ *+ * A write failure here is fatal to the cycle, not a swallowed warn. On the+ * fast-forward-refusal path the overlapping paths were already reset to HEAD,+ * so this write is the only thing restoring the user's uncommitted bytes from+ * the in-memory buffer — dropping it silently would lose the edit behind a+ * clean-looking `idle`. Each target is realpath-contained first: a git remote+ * is untrusted and could ship a symlink at a tracked path that a bare write+ * would follow out of the working tree. Writes route through the fs-traced+ * wrappers like every other server-side disk write.+ */+ private applyOverlayPlan(+ writes: Array<{ path: string; bytes: Buffer }>,+ deletions: string[],+ ): void {+ for (const { path, bytes } of writes) {+ const abs = join(this.projectDir, path);+ assertRealpathWithinDir(abs, this.projectDir);+ tracedWriteFileSync(abs, bytes);+ }+ for (const path of deletions) {+ const abs = join(this.projectDir, path);+ assertRealpathWithinDir(abs, this.projectDir);+ try {+ tracedUnlinkSync(abs);+ } catch (e) {+ // `ENOENT` is the benign converged case (origin also deleted it, or the+ // fast-forward already removed it). Any other errno (EACCES/EPERM/+ // EISDIR) is a real failure that must not be swallowed — surface it so+ // the cycle backs off instead of looking clean.+ if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;+ }+ }+ }++ /** True when a project-relative path is a resolvable OK content doc. */+ private isContentConflictPath(file: string): boolean {+ const absPath = join(this.projectDir, file);+ const contentRelPath = toPosix(relative(this.contentDir, absPath));+ return (+ !contentRelPath.startsWith('..') &&+ isSupportedDocFile(contentRelPath) &&+ !this.contentFilter.isExcluded(contentRelPath)+ );+ }++ /** Resolve a ref to its blob SHA, or `undefined` when the path is absent. */+ private async gitBlobSha(handle: GitHandle, ref: string): Promise<string | undefined> {+ try {+ return (await handle.git.revparse([ref])).trim();+ } catch {+ return undefined;+ }+ }++ /**+ * Discriminate why a `<ref>:<path>` read failed: the path is genuinely absent+ * at the ref (expected — origin deleted/never had it) vs an unexpected git+ * failure (timeout, corruption, bad ref). Conflating the two lets a transient+ * failure masquerade as a semantic fact — silently dissolving a tracked+ * conflict or suppressing a real collision. Locale-stable English fragments,+ * matching the merge-native `showStage` discipline (git messages are+ * English-only).+ */+ private classifyRefReadFailure(err: unknown): 'absent' | 'error' {+ const msg = err instanceof Error ? err.message : String(err);+ return /does not exist in|exists on disk, but not in/i.test(msg) ? 'absent' : 'error';+ }++ /** Read a blob's bytes by SHA. */+ private async gitBlobContent(handle: GitHandle, sha: string): Promise<string> {+ return handle.git.raw(['cat-file', 'blob', sha]);+ }++ /**+ * Count content docs carrying a standing overlay — tracked content paths whose+ * working tree differs from HEAD. This is the pull-only divergence surface: it+ * accumulates as a never-push follower edits locally, and per-pull conflict+ * rates don't capture the standing stock.+ */+ private async countStandingOverlay(handle: GitHandle): Promise<number | null> {+ try {+ const overlayPaths = await listNames(handle.git, ['diff-index', '--name-only', 'HEAD']);+ return overlayPaths.filter((p) => this.isContentConflictPath(p)).length;+ } catch {+ // Best-effort gauge sampled after a successful fast-forward; a transient+ // git failure here must not turn a completed pull into an error.+ return null;+ }}// ─── Push cycle ────────────────────────────────────────────────────────────private async runPushCycle(): Promise<void> {if (this.pushInFlight) return;+ // The single, authoritative push gate. Push is structurally impossible+ // unless the project is in `full` mode — no scheduling path, manual trigger,+ // or self-heal can reach the push subprocess for a pull-only or off project.+ // This is the consent guarantee: a pull-only follower is never pushed for.+ if (this.mode !== 'full') return;if (this.state === 'dormant' || this.state === 'disabled') return;if (this.state === 'conflict' || this.state === 'auth-error') return;if (isUnbornHead(this.projectDir)) {@@ -2067,25 +3134,39 @@ export class SyncEngine {'[sync] content conflicts — sync paused until resolved',);} else {- // All conflicts auto-resolved — complete the merge+ // All non-content conflicts auto-resolved — complete the merge. Confirm it+ // landed by checking MERGE_HEAD cleared, not by trusting the call not to+ // throw: simple-git does NOT throw on every non-zero `git commit` exit (a+ // pre-commit hook rejection returns without an error), so a rejected commit+ // would otherwise be reported as a successful pull over a half-merged tree.+ let committed = false;try {await handle.git.raw(['commit', '--no-edit']);+ const gitDir = resolveGitDir(this.projectDir);+ committed = gitDir === null || !existsSync(join(gitDir, 'MERGE_HEAD'));+ } catch (e) {+ log.warn({ err: e }, '[sync] failed to commit after auto-resolving conflicts');+ }+ if (committed) {this.lastSyncUtc = new Date().toISOString();this.behind = 0;this.transitionTo('idle');log.info({}, '[sync] all conflicts auto-resolved — merge committed');- } catch (e) {- // Commit failed after partial auto-resolve — abort merge to clean up git index- log.warn(- { err: e },- '[sync] failed to commit after auto-resolving conflicts — aborting merge',- );+ } else {+ // Commit rejected or threw — abort so the tree isn't left half-merged,+ // and set pullError so the pull reports the error class (doPullCycle+ // treats a set pullError as the error outcome) instead of a false success.try {await handle.git.raw(['merge', '--abort']);} catch (abortErr) {log.warn({ err: abortErr }, '[sync] git merge --abort failed during cleanup');}+ this.pullError = 'Sync paused — could not finalize the merge. Retry sync to try again.';this.transitionTo('idle');+ log.warn(+ {},+ '[sync] could not finalize merge after auto-resolving conflicts — merge aborted',+ );}}}@@ -2099,6 +3180,15 @@ export class SyncEngine {}}+ private async notifyContentConflictsResolved(files: string[]): Promise<void> {+ if (files.length === 0) return;+ try {+ await this.onContentConflictsResolved?.(files);+ } catch (err) {+ log.warn({ err, files }, '[sync] content conflict resolved callback failed');+ }+ }+// ─── Error handling ───────────────────────────────────────────────────────private clearPushError(): void {@@ -2160,7 +3250,10 @@ export class SyncEngine {this.transitionTo('auth-error');this.pausedReason = 'auth-error';} else if (classified.class === 'semantic' && classified.subclass === 'protected-branch') {- this.syncEnabled = false;+ // Reachable only in `full` mode — protected-branch is a push rejection and+ // the push gate keeps pull-only/off from ever pushing. Auto-disable to+ // `off`; onAutoDisable persists the equivalent legacy `enabled: false`.+ this.mode = 'off';this.transitionTo('disabled');this.pausedReason = 'protected-branch';// Persist the auto-disable to project-local config so it survives restart;diff --git a/packages/server/src/sync-timing.test.ts b/packages/server/src/sync-timing.test.tsindex 8fb151b6a..724e7915c 100644--- a/packages/server/src/sync-timing.test.ts+++ b/packages/server/src/sync-timing.test.ts@@ -3,7 +3,11 @@*/import { describe, expect, test } from 'vitest';-import { computeRemainingMs } from './sync-timing.ts';+import {+ ANONYMOUS_PULL_MIN_SECONDS,+ computeRemainingMs,+ pullIntervalSecondsForAuthTier,+} from './sync-timing.ts';const SECOND = 1000;const MINUTE = 60 * SECOND;@@ -76,3 +80,21 @@ describe('computeRemainingMs', () => {expect(remaining).toBe(8 * SECOND);});});++describe('pullIntervalSecondsForAuthTier', () => {+ test('authenticated followers keep the responsive base interval', () => {+ expect(pullIntervalSecondsForAuthTier(30, 'authenticated')).toBe(30);+ expect(pullIntervalSecondsForAuthTier(60, 'authenticated')).toBe(60);+ });++ test('anonymous followers are floored to the gentle cadence', () => {+ expect(pullIntervalSecondsForAuthTier(30, 'anonymous')).toBe(ANONYMOUS_PULL_MIN_SECONDS);+ expect(pullIntervalSecondsForAuthTier(30, 'anonymous')).toBe(180);+ expect(pullIntervalSecondsForAuthTier(60, 'anonymous')).toBe(180);+ });++ test('a base interval already at or above the floor is preserved for anonymous', () => {+ expect(pullIntervalSecondsForAuthTier(180, 'anonymous')).toBe(180);+ expect(pullIntervalSecondsForAuthTier(300, 'anonymous')).toBe(300);+ });+});diff --git a/packages/server/src/sync-timing.ts b/packages/server/src/sync-timing.tsindex 837cf1688..36b830ced 100644--- a/packages/server/src/sync-timing.ts+++ b/packages/server/src/sync-timing.ts@@ -29,3 +29,33 @@ export function computeRemainingMs(const nextMs = lastMs + intervalSeconds * 1000;return Math.max(0, nextMs - now);}++/**+ * Minimum seconds between pull cycles for an anonymous (unauthenticated)+ * pull-only follower. A single follower polling is far under GitHub's+ * per-client guidance; the real exposure is aggregate read pressure across+ * every anonymous follower of one public repo, and that population is the+ * least accountable and least freshness-sensitive, so it polls at a gentler+ * floor than signed-in followers. Hard-coded by design — cadence is not a+ * config knob.+ */+export const ANONYMOUS_PULL_MIN_SECONDS = 180;++/** Which credential tier a pull-only follower will fetch as. */+export type PullAuthTier = 'authenticated' | 'anonymous';++/**+ * Base pull interval (seconds) for a pull-only follower given its auth tier.+ * Signed-in followers keep the responsive base interval; anonymous followers+ * are floored to {@link ANONYMOUS_PULL_MIN_SECONDS} (a base already above the+ * floor is preserved). The caller applies jitter and backoff on top, so both+ * tiers keep the same ±15% spread and failure backoff.+ */+export function pullIntervalSecondsForAuthTier(+ baseIntervalSeconds: number,+ tier: PullAuthTier,+): number {+ return tier === 'anonymous'+ ? Math.max(ANONYMOUS_PULL_MIN_SECONDS, baseIntervalSeconds)+ : baseIntervalSeconds;+}