Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Sync UI improvements (#3958)
shagun-singh-inkeep7ffcaf90d2b2
diff --git a/.changeset/sync-panel-and-backoff.md b/.changeset/sync-panel-and-backoff.mdnew file mode 100644index 000000000..f5a5252ca--- /dev/null+++ b/.changeset/sync-panel-and-backoff.md@@ -0,0 +1,11 @@+---+"@inkeep/open-knowledge": patch+---++Back off pulls and pushes independently, and make the sync panel's file list readable at scale.++Auto sync kept a single count of recent failures. Both loops added to it, but only the pull loop read it, and only a successful pull could clear it. A push that kept being rejected therefore stretched the interval of the very loop it defers to when its own retry is exhausted, and a push that recovered left the count standing until a pull happened to run. Each direction now keeps its own streak: 3 consecutive failures hold the next attempt for at least 5 minutes, 5 for at least 15, and 8 for at least an hour — floors rather than replacements, so a configured interval longer than the tier is never shortened to it. (Pull already had this ladder but applied it as a replacement, which could speed a slow interval up; it is now a floor there too.) The two counters are independent — push failures do not slow down pulls and vice versa — and either counter resets immediately on a manual trigger or on a success in that direction. Saving state written by an earlier version still restores its pull backoff.++A push does not check for updates first — it sends, and reconciles only if the remote turns it back. Checking less often than you push therefore leaves each push to discover the remote moved and catch up before it can land, which costs nothing on a repository nobody else writes to and adds a round trip on every push when someone does. The sync settings note this where the two intervals are chosen, in Auto (Pull and Push) and only when the push interval is the shorter of the two. It is a note, not a restriction: fast pushes with slow update checks remain a reasonable setting for a repository you are the only author of.++The panel listed every changed path as its own row, up to a hundred per section, each clipped at the end to fit. On a real working tree that produced a column of near-identical strings — every row showing the same visible prefix, with the filename that distinguished it cut off — and a panel tall enough to push the sync controls off screen. Paths are now grouped by folder, with the directory stated once in a group header and the rows carrying only what is left of the path. A directory shared by everything in a section is lifted out and stated once above the list. Sections start collapsed with their file count in view; folders holding a single file stay as plain rows rather than costing a click, and a long group shows its first few rows with the rest one click away. Hovering a row gives its full path, and a folder header its untruncated directory, and the list scrolls within its own bounds so the mode selector and the Pull and Push buttons stay put.diff --git a/docs/content/features/github-sync.mdx b/docs/content/features/github-sync.mdxindex 4a23a8eda..3a7bf35ae 100644--- a/docs/content/features/github-sync.mdx+++ b/docs/content/features/github-sync.mdx@@ -74,6 +74,8 @@ Both automatic modes run on a timer, and the two directions have their own cadenChange either one in **Settings → Sync → Advanced** (the disclosure is collapsed by default), under **Check for updates every** and **Push my edits every**. The controls appear only while an automatic mode is active — in Manual nothing runs on a schedule, so there is no cadence to set. Both accept 30 seconds, 1 minute, 5 minutes, 15 minutes, or 1 hour, and both are per-machine — your choice stays on this computer and is not committed to the repository. **Push my edits every** appears only in Auto (Pull and Push), since no other mode pushes on a schedule.+After repeated failures, OpenKnowledge slows each direction down independently: 3 failures in a row hold the next attempt for at least 5 minutes, 5 failures for at least 15 minutes, and 8 failures for at least 1 hour. These are floors, not replacements: if your configured interval is already longer than the tier, the interval stands. The two directions back off on separate counters — push failures do not slow down pulls, and pull failures do not slow down pushes. A successful sync in a direction resets that direction's backoff; a manual trigger from the sync indicator (or clicking Pull/Push) resets both directions immediately. One cross-direction case: if pushes were backing off because the network was unreachable, the next successful update check releases that backoff straight away — it is direct proof the remote is reachable again. A backoff from a rejected push (a protected branch, say) is left alone, since reaching the remote says nothing about whether it will accept the write.+While you are signed out, **Auto (Pull only)** checks for updates at most every 3 minutes no matter what you choose here — a signed-out client is anonymous to GitHub, and the limit protects the repository from the combined polling of everyone following it. Auto (Pull and Push) is unaffected: pushing requires being signed in to begin with.When you open a freshly cloned project, you will be prompted to enable sync. If you have push access to the repository, you will be prompted to enable **Auto (Pull and Push)**. If you have read-only access, you will be prompted to enable **Auto (Pull only)**. 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.@@ -164,5 +166,5 @@ A few situations stop sync from completing successfully. In each case the sync s### Temporary problems-- **Network or service hiccups.** Flaky Wi-Fi, a VPN drop, or a brief GitHub outage. OpenKnowledge keeps retrying in the background; no action needed unless the issue lasts long enough that you want to manually trigger a sync from the indicator.+- **Network or service hiccups.** Flaky Wi-Fi, a VPN drop, or a brief GitHub outage. OpenKnowledge retries automatically, slowing down progressively as described in [How often sync runs](#how-often-sync-runs). No action needed; a manual trigger from the sync indicator resets the backoff immediately if you want sync to run sooner.diff --git a/knip.config.ts b/knip.config.tsindex 8ad68f996..b61debe5e 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -124,9 +124,7 @@ export default {'packages/server': {entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],project: 'src/**',- ignoreDependencies: [- '@types/shell-quote',- ],+ ignoreDependencies: ['@types/shell-quote'],},'packages/cli': {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],diff --git a/packages/app/src/components/SyncStatusBadge.dom.test.tsx b/packages/app/src/components/SyncStatusBadge.dom.test.tsxindex 4f394d7b4..fd04836f4 100644--- a/packages/app/src/components/SyncStatusBadge.dom.test.tsx+++ b/packages/app/src/components/SyncStatusBadge.dom.test.tsx@@ -153,6 +153,36 @@ async function openPopover() {});}+/**+ * Reveal the whole working-tree listing.+ *+ * Sections and folder buckets are collapsed on open, so every assertion about+ * rows has to expand first. Scoped to the listing because the sync-mode Select+ * also carries `aria-expanded`, and clicking that opens a dropdown instead.+ * Loops because expanding a section reveals buckets that were not in the DOM+ * when the pass started.+ */+async function expandWorktreeListing(): Promise<void> {+ // Three tiers can carry `aria-expanded`: section -> folder bucket -> the+ // `+N more` control an overflowing bucket reveals. Four passes is one per+ // tier plus a confirming pass that observes zero collapsed triggers.+ // Exhaustion throws rather than returning quietly, so a future fifth tier+ // names itself here instead of surfacing as a missing element in the caller.+ for (let pass = 0; pass < 4; pass++) {+ const listing = screen.queryByTestId('worktree-listing');+ if (!listing) return;+ // `{ expanded: false }` matches `aria-expanded="false"` only — Testing+ // Library treats an absent attribute as `undefined`, not `false` — so the+ // query needs no further filtering.+ const collapsed = within(listing).queryAllByRole('button', { expanded: false });+ if (collapsed.length === 0) return;+ for (const trigger of collapsed) await userEvent.click(trigger);+ }+ throw new Error(+ 'expandWorktreeListing: disclosures still collapsed after 4 passes — a new nesting tier?',+ );+}+/** Move the engine's reported state the way a poll tick would, mid-test. */async function advanceStatus(next: GitSyncStatus): Promise<void> {status = next;@@ -1201,6 +1231,7 @@ describe('SyncStatusBadge runtime behavior', () => {projectLocalConfig = { autoSync: { mode: 'off' } };await renderBadge();await openPopover();+ await expandWorktreeListing();expect(screen.getByTestId('sync-popover-pull')).toBeTruthy();expect(screen.getByTestId('sync-popover-push')).toBeTruthy();@@ -1234,6 +1265,7 @@ describe('SyncStatusBadge working-tree listing', () => {};await renderBadge();await openPopover();+ await expandWorktreeListing();// Tense-free and mode-independent: only `full` pushes on its own, so a// "will be pushed" heading would overstate it in Manual and Follow.@@ -1244,10 +1276,13 @@ describe('SyncStatusBadge working-tree listing', () => {expect(screen.queryByText('Not staged')).toBeNull();// An unstaged in-scope edit and an untracked in-scope file both ship.- expect(screen.getByText('docs/sync.mdx')).toBeTruthy();- expect(screen.getByText('notes/cadence-draft.md')).toBeTruthy();+ const listing = within(screen.getByTestId('worktree-listing'));+ expect(listing.getByText('docs/sync.mdx', { selector: 'span:not(.sr-only)' })).toBeTruthy();+ expect(+ listing.getByText('notes/cadence-draft.md', { selector: 'span:not(.sr-only)' }),+ ).toBeTruthy();// Out-of-scope lands in the other group with its explanation.- expect(screen.getByText('src/git/status.ts')).toBeTruthy();+ expect(listing.getByText('src/git/status.ts', { selector: 'span:not(.sr-only)' })).toBeTruthy();expect(screen.getByText(/Outside what Open Knowledge commits/)).toBeTruthy();// Divergence comes from the engine payload, not the worktree read.@@ -1280,13 +1315,25 @@ describe('SyncStatusBadge working-tree listing', () => {};await renderBadge();await openPopover();+ await expandWorktreeListing();await userEvent.click(screen.getByRole('button', { name: 'opencode.json' }));expect(window.location.hash).toBe('#/__asset__/opencode.json');await openPopover();- expect(screen.queryByRole('button', { name: 'notes/gone.md' })).toBeNull();- expect(screen.getByText('notes/gone.md')).toBeTruthy();+ await expandWorktreeListing();+ // Both live under the `notes` bucket, which states that segment in its+ // header. The visible label is the remainder ("cadence.md"), but the+ // accessible name is the full path so two folders each holding a file of+ // the same name stay distinguishable to a screen reader.+ expect(screen.queryByRole('button', { name: 'gone.md' })).toBeNull();+ expect(screen.getByText('gone.md')).toBeTruthy();+ // The `label !== entry.path` guard is what keeps the full path available to+ // a screen reader without waiting on the tooltip. Without it, two folders+ // each holding a `gone.md` are indistinguishable, and nothing else in the+ // suite would go red.+ const listing = within(screen.getByTestId('worktree-listing'));+ expect(listing.getByText('notes/gone.md', { selector: '.sr-only' })).toBeTruthy();// Layout is the actual contract and jsdom computes none, so the guard is// the one class that decides it: the Button base ships `shrink-0`, and a@@ -1298,7 +1345,10 @@ describe('SyncStatusBadge working-tree listing', () => {expect(rowClasses).toContain('shrink');expect(rowClasses).not.toContain('shrink-0');- await userEvent.click(screen.getByRole('button', { name: 'notes/cadence.md' }));+ // Accessible name is the full path (aria-label); visible label is the tail.+ const cadenceBtn = screen.getByRole('button', { name: 'notes/cadence.md' });+ expect(cadenceBtn.textContent).toContain('cadence.md');+ await userEvent.click(cadenceBtn);expect(window.location.hash).toBe('#/notes/cadence');// The popover overlays the editor, so it closes rather than hiding the@@ -1308,6 +1358,93 @@ describe('SyncStatusBadge working-tree listing', () => {});});+ test('a folder header resolves the full path, not the label it already shows', async () => {+ status = { ...baseStatus, state: 'idle' };+ projectLocalConfig = { autoSync: { mode: 'off' } };+ worktree = {+ ...emptyWorktree,+ // Two locale dirs under a shared prefix: the section hoists+ // `app/src/locales`, the bucket header shows only what is left of it.+ notStaged: ['ar', 'bn'].flatMap((l) => [+ { path: `app/src/locales/${l}/messages.po`, code: 'M' as const, syncScoped: true },+ { path: `app/src/locales/${l}/messages.json`, code: 'M' as const, syncScoped: true },+ ]),+ };+ await renderBadge();+ await openPopover();+ await expandWorktreeListing();++ const listing = within(screen.getByTestId('worktree-listing'));+ // The header's visible label is only the remainder after the hoist.+ const header = listing.getByRole('button', { name: /^ar/ });+ expect(header.textContent).toContain('ar');+ expect(header.textContent).not.toContain('app/src/locales');++ // FOCUS, not hover: the tooltip wraps the Button precisely so a keyboard+ // user reaches it. Radix opens on the trigger's focus, and this assertion+ // fails if the tooltip is ever moved back onto a nested span.+ (document.activeElement as HTMLElement | null)?.blur();+ header.focus();+ expect(document.activeElement).toBe(header);+ await waitFor(() => {+ expect(screen.getAllByText('app/src/locales/ar').length).toBeGreaterThan(0);+ });+ });++ test('a non-linking row is reachable by keyboard and its focus opens the full path', async () => {+ // A deletion row takes the plain-text branch, so the tooltip is the only+ // truncation recovery a sighted keyboard-only user has — and Radix opens on+ // the TRIGGER's focus, so a non-focusable span would give them nothing.+ status = { ...baseStatus, state: 'idle' };+ projectLocalConfig = { autoSync: { mode: 'off' } };+ worktree = {+ ...emptyWorktree,+ notStaged: [+ { path: 'notes/kept.md', code: 'M', syncScoped: true },+ // No open target → the plain-text branch under test.+ { path: 'notes/gone.md', code: 'D', syncScoped: true },+ ],+ };+ await renderBadge();+ await openPopover();+ await expandWorktreeListing();++ const listing = within(screen.getByTestId('worktree-listing'));+ const label = listing.getByText('gone.md', { selector: 'span:not(.sr-only)' });+ // Not a button — this is the branch that has no navigation target.+ expect(label.tagName).toBe('SPAN');++ // No tooltip before focus. Asserting on the text alone would match this+ // row's own `sr-only` full-path fallback, which is already in the DOM — so+ // the assertion would pass with the Tooltip deleted outright.+ expect(screen.queryByRole('tooltip')).toBeNull();++ (document.activeElement as HTMLElement | null)?.blur();+ label.focus();+ expect(document.activeElement).toBe(label);++ await waitFor(() => {+ expect(screen.getByRole('tooltip').textContent).toContain('notes/gone.md');+ });+ });++ test('an ungrouped row omits the sr-only fallback rather than repeating itself', async () => {+ status = { ...baseStatus, state: 'idle' };+ projectLocalConfig = { autoSync: { mode: 'off' } };+ worktree = {+ ...emptyWorktree,+ // One entry: no prefix is hoisted, so `label` IS the full path.+ notStaged: [{ path: 'notes/solo.md', code: 'D', syncScoped: true }],+ };+ await renderBadge();+ await openPopover();+ await expandWorktreeListing();++ const listing = within(screen.getByTestId('worktree-listing'));+ expect(listing.getByText('notes/solo.md')).toBeTruthy();+ expect(listing.queryByText('notes/solo.md', { selector: '.sr-only' })).toBeNull();+ });+test('clickability follows the document, not the group the row landed in', async () => {// `docName` is orthogonal to `syncScoped`: a gitignored note is openable// but never pushed, and an incoming row is openable whenever the file@@ -1335,6 +1472,7 @@ describe('SyncStatusBadge working-tree listing', () => {};await renderBadge();await openPopover();+ await expandWorktreeListing();expect(screen.getByText('Push skips')).toBeTruthy();expect(screen.getByRole('button', { name: 'notes/private.md' })).toBeTruthy();@@ -1350,6 +1488,7 @@ describe('SyncStatusBadge working-tree listing', () => {};await renderBadge();await openPopover();+ await expandWorktreeListing();expect(screen.getByText('Push includes')).toBeTruthy();expect(screen.queryByText('Push skips')).toBeNull();@@ -1366,8 +1505,13 @@ describe('SyncStatusBadge working-tree listing', () => {};await renderBadge();await openPopover();+ await expandWorktreeListing();- expect(screen.getAllByText('docs/sync.mdx')).toHaveLength(1);+ expect(+ within(screen.getByTestId('worktree-listing')).getAllByText('docs/sync.mdx', {+ selector: 'span:not(.sr-only)',+ }),+ ).toHaveLength(1);// 'A' (staged add) is more specific than the worktree's 'M'.expect(screen.getByText('A')).toBeTruthy();});@@ -1424,11 +1568,20 @@ describe('SyncStatusBadge working-tree listing', () => {};await renderBadge();await openPopover();+ await expandWorktreeListing();expect(screen.getByText('Pull brings in')).toBeTruthy();- expect(screen.getByText('notes/from-teammate.md')).toBeTruthy();+ expect(+ within(screen.getByTestId('worktree-listing')).getByText('notes/from-teammate.md', {+ selector: 'span:not(.sr-only)',+ }),+ ).toBeTruthy();expect(screen.getByText('Push includes')).toBeTruthy();- expect(screen.getByText('notes/mine.md')).toBeTruthy();+ expect(+ within(screen.getByTestId('worktree-listing')).getByText('notes/mine.md', {+ selector: 'span:not(.sr-only)',+ }),+ ).toBeTruthy();});test('an up-to-date remote shows no incoming group', async () => {@@ -1524,6 +1677,53 @@ describe('SyncStatusBadge working-tree listing', () => {expect(screen.getByText('detached HEAD')).toBeTruthy();});++ test('a row list with more than the cap shows only the cap and an overflow button', async () => {+ status = { ...baseStatus, state: 'idle' };+ projectLocalConfig = { autoSync: { mode: 'off' } };+ // 7 entries exceed MAX_ROWS_PER_GROUP (6), so the last entry hides behind+ // the overflow button until the user asks for more.+ worktree = {+ ...emptyWorktree,+ notStaged: Array.from({ length: 7 }, (_, i) => ({+ path: `notes/file-${i}.md`,+ code: 'M',+ syncScoped: true,+ open: { kind: 'doc' as const, docName: `notes/file-${i}` },+ })),+ };+ await renderBadge();+ await openPopover();+ // Manually open only the section trigger. expandWorktreeListing() would also+ // click the "+N more" button (it carries aria-expanded=false) and reveal all+ // rows — defeating what this test measures.+ await userEvent.click(screen.getByRole('button', { name: /Push includes/ }));++ expect(screen.getByTestId('worktree-rows-show-all')).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'notes/file-6.md' })).toBeNull();+ });++ test('a row list at or below the cap shows all entries without an overflow button', async () => {+ status = { ...baseStatus, state: 'idle' };+ projectLocalConfig = { autoSync: { mode: 'off' } };+ // 6 entries exactly match MAX_ROWS_PER_GROUP — all visible, no overflow.+ worktree = {+ ...emptyWorktree,+ notStaged: Array.from({ length: 6 }, (_, i) => ({+ path: `notes/file-${i}.md`,+ code: 'M',+ syncScoped: true,+ open: { kind: 'doc' as const, docName: `notes/file-${i}` },+ })),+ };+ await renderBadge();+ await openPopover();+ await expandWorktreeListing();++ expect(screen.queryByTestId('worktree-rows-show-all')).toBeNull();+ expect(screen.getByRole('button', { name: 'notes/file-0.md' })).toBeTruthy();+ expect(screen.getByRole('button', { name: 'notes/file-5.md' })).toBeTruthy();+ });});describe('SyncStatusBadge settings affordance', () => {diff --git a/packages/app/src/components/SyncStatusBadge.tsx b/packages/app/src/components/SyncStatusBadge.tsxindex a1f771570..a4d6fea79 100644--- a/packages/app/src/components/SyncStatusBadge.tsx+++ b/packages/app/src/components/SyncStatusBadge.tsx@@ -24,6 +24,7 @@ import {ArrowDown,ArrowUp,ArrowUpRight,+ ChevronRight,Cloud,CloudAlert,CloudOff,@@ -33,6 +34,7 @@ import {UserCog,} from 'lucide-react';import { useEffect, useState } from 'react';+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';import { Spinner } from '@/components/ui/spinner';import { useConflicts } from '@/hooks/use-conflicts';import { useBadgeSyncControls } from '@/hooks/use-enable-sync-with-confirm';@@ -46,6 +48,12 @@ import { triggerSync } from '@/lib/trigger-sync';import { openSyncSettings } from '@/lib/use-settings-route';import { EnableSyncConfirmDialog } from './EnableSyncConfirmDialog';import { SyncBlockingChanges } from './SyncBlockingChanges';+import {+ groupWorktreeEntries,+ MAX_ROWS_PER_GROUP,+ type WorktreeFolderGroup,+ type WorktreeRowModel,+} from './sync-worktree-grouping.ts';import { Badge } from './ui/badge';import { Button } from './ui/button';import { Popover, PopoverClose, PopoverContent, PopoverTrigger } from './ui/popover';@@ -662,9 +670,9 @@ interface PopoverBodyProps {}/** Section heading — the small uppercase rule the popover groups controls under. */-function SectionLabel({ children }: { children: React.ReactNode }) {+function SectionLabel({ children, id }: { children: React.ReactNode; id?: string }) {return (- <span className="font-mono uppercase tracking-wide text-2xs text-muted-foreground">+ <span id={id} className="font-mono uppercase tracking-wide text-2xs text-muted-foreground">{children}</span>);@@ -725,10 +733,21 @@ function statusCodeVariant(code: GitStatusCode): 'gray' | 'warning' | 'destructi* a document, or the asset viewer for everything else the sidebar would show.* The rows that stay plain text are the ones that would open on nothing: a* deletion, an incoming file that has not landed yet, a path outside the- * content dir, and the floors the sidebar hides too. The button carries no- * label of its own: the path IS its accessible name.+ * content dir, and the floors the sidebar hides too. The button's accessible+ * name is set to the full `entry.path` via `aria-label`, because the display+ * label is relative to the enclosing folder group and would collide with+ * sibling groups that hold files of the same name.*/-function WorktreeRow({ entry, dimmed }: { entry: GitWorktreeEntry; dimmed: boolean }) {+function WorktreeRow({+ entry,+ dimmed,+ label,+}: {+ entry: GitWorktreeEntry;+ dimmed: boolean;+ /** Path relative to the enclosing folder group; the header carries the rest. */+ label: string;+}) {// No locale subscription here, deliberately. `statusCodeLabel` reads the// module `t`, which resolves at CALL time, so on a locale switch these// tooltips render in the old language until something re-renders the row.@@ -741,7 +760,17 @@ function WorktreeRow({ entry, dimmed }: { entry: GitWorktreeEntry; dimmed: boole// macro module instead.const codeLabel = statusCodeLabel(entry.code);const openTarget = entry.open;- const pathClassName = `truncate font-mono text-2xs ${dimmed ? 'text-muted-foreground/60' : 'text-foreground'}`;+ // `text-start` AND `dir="auto"`, and the two are load-bearing for different+ // reasons. `dir` only resolves the logical start/end keywords, so it cannot+ // counter an inherited physical alignment: the openable row nests its span in+ // a real <Button>, which the UA centers and neither Preflight nor+ // `buttonVariants` resets — that is the site the round-4 regression hit, and+ // the one `text-start` exists for. On the non-openable row the span is a+ // direct child of a flex <li> with no button in its ancestry, so `text-start`+ // is a harmless no-op there and is kept only so both spans share one class.+ // `dir="auto"` is required on both: without it a non-Latin filename would be+ // forced to render LTR.+ const pathClassName = `truncate text-start font-mono text-2xs ${dimmed ? 'text-muted-foreground/60' : 'text-foreground'}`;return (<li className="flex min-w-0 items-center gap-2"><Tooltip>@@ -759,41 +788,200 @@ function WorktreeRow({ entry, dimmed }: { entry: GitWorktreeEntry; dimmed: boole{openTarget ? (// Closing on navigate: the popover overlays the editor, so leaving it// open would hide the document the click just asked for.- <PopoverClose asChild>+ // Tooltip wraps the BUTTON, not the label span: Radix opens on the+ // trigger's focus, and Tab lands on the button — a nested span never+ // receives focus, so a keyboard-only user got no truncation recovery.+ // Safe here where it was not on the folder header: `PopoverClose` does+ // not style on `data-state`, so nothing collides.+ <Tooltip>+ <TooltipTrigger asChild>+ <PopoverClose asChild>+ <Button+ variant="link-muted"+ size="xs"+ // `shrink` undoes the Button base's `shrink-0`, and `min-w-0`+ // releases the content-width floor — a flex item honors neither+ // truncation nor its parent's width without both, at every level+ // of the nest (li → button → span). Without `shrink` the row grew+ // to the length of the path and spilled out of the popover.+ // `min-h-6` restores a clickable target: `h-auto p-0` collapsed+ // these discrete list rows to the ~14px line box, under WCAG 2.2+ // SC 2.5.8's 24px floor — and a mis-aimed click here navigates the+ // editor. Horizontal p-0 stays for the flush-left alignment.+ className="h-auto min-h-6 min-w-0 shrink justify-start overflow-hidden p-0 font-normal"+ aria-label={entry.path}+ onClick={() => navigateToHash(hashForOpenTarget(openTarget))}+ data-testid="worktree-row-open"+ >+ <span dir="auto" className={`min-w-0 ${pathClassName}`}>+ {label}+ </span>+ </Button>+ </PopoverClose>+ </TooltipTrigger>+ <TooltipContent dir="auto" className="font-mono text-2xs">+ {entry.path}+ </TooltipContent>+ </Tooltip>+ ) : (+ <>+ <Tooltip>+ <TooltipTrigger asChild>+ <span+ dir="auto"+ // biome-ignore lint/a11y/noNoninteractiveTabindex: tooltip-on-static-text pattern (see EditorFooter) — Radix opens on the trigger's focus, so a non-focusable span leaves sighted keyboard-only users no way to recover a truncated path. Sibling rows that link are buttons and already take focus, so this also stops the list silently skipping the rows whose path is their only content.+ tabIndex={0}+ className={`min-w-0 rounded-xs focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50 ${pathClassName}`}+ >+ {label}+ </span>+ </TooltipTrigger>+ <TooltipContent dir="auto" className="font-mono text-2xs">+ {entry.path}+ </TooltipContent>+ </Tooltip>+ {/* Tooltip is pointer-only; give the full path to AT via a+ screen-reader-only fallback (same pattern as the status letter).+ Omitted when the label already IS the full path — a row in an+ ungrouped section — so the path is not announced twice. */}+ {label !== entry.path && <span className="sr-only">{entry.path}</span>}+ </>+ )}+ </li>+ );+}++/**+ * Row list, capped until asked otherwise.+ *+ * The cap keeps a freshly-opened folder short, but the overflow is a toggle:+ * reaching these rows already took a deliberate click, so a count that cannot+ * be opened just says "there is more, and no." The toggle is two-way so the+ * button stays mounted when expanded — unmounting the focused node drops+ * keyboard focus to `<body>`. The enclosing disclosure unmounts this state on+ * close, so the next open always starts capped.+ */+function WorktreeRows({ rows, dimmed }: { rows: WorktreeRowModel[]; dimmed: boolean }) {+ const [showAll, setShowAll] = useState(false);+ const hasOverflow = rows.length > MAX_ROWS_PER_GROUP;+ const shown = showAll ? rows : rows.slice(0, MAX_ROWS_PER_GROUP);+ const overflowCount = rows.length - MAX_ROWS_PER_GROUP;+ return (+ <ul className="flex flex-col gap-1">+ {shown.map(({ entry, label }) => (+ <WorktreeRow+ key={`${entry.code}:${entry.path}`}+ entry={entry}+ dimmed={dimmed}+ label={label}+ />+ ))}+ {hasOverflow && (+ <li><Button- variant="link"+ variant="link-muted"size="xs"- // `shrink` undoes the Button base's `shrink-0`, and `min-w-0`- // releases the content-width floor — a flex item honors neither- // truncation nor its parent's width without both, at every level- // of the nest (li → button → span). Without `shrink` the row grew- // to the length of the path and spilled out of the popover.- // `min-h-6` restores a clickable target: `h-auto p-0` collapsed- // these discrete list rows to the ~14px line box, under WCAG 2.2- // SC 2.5.8's 24px floor — and a mis-aimed click here navigates the- // editor. Horizontal p-0 stays for the flush-left alignment.- className="h-auto min-h-6 min-w-0 shrink justify-start overflow-hidden p-0 font-normal"- onClick={() => navigateToHash(hashForOpenTarget(openTarget))}- data-testid="worktree-row-open"+ aria-expanded={showAll}+ className="h-auto min-h-6 justify-start p-0 text-2xs font-normal"+ onClick={() => setShowAll((v) => !v)}+ data-testid="worktree-rows-show-all">- {/* `truncate` clips the END — the filename, the only identifying- part — so the full path rides on `title`, the same recovery- every git client offers. */}- <span title={entry.path} className={`min-w-0 ${pathClassName}`}>- {entry.path}- </span>+ {showAll ? <Trans>Collapse</Trans> : <Trans>+{overflowCount} more</Trans>}</Button>- </PopoverClose>- ) : (- <span title={entry.path} className={pathClassName}>- {entry.path}- </span>+ </li>)}- </li>+ </ul>);}-/** A titled group of changed paths; renders nothing when the group is empty. */+/**+ * One collapsible folder bucket. The directory is stated once in the header and+ * its rows carry only their remainder.+ *+ * The label is content-sized and the count is pushed out with `ms-auto`, so+ * alignment inside the row is unobservable — the same shape as the section+ * header in `WorktreeGroup`. The tooltip carries `prefix + dir`, which is more than the+ * header shows whenever the section hoisted a prefix, and equal to it when it+ * did not. It opens on focus as well as hover, because it wraps the Button+ * rather than a span nested inside it.+ */+function WorktreeFolder({+ group,+ prefix,+ dimmed,+}: {+ group: WorktreeFolderGroup;+ /** Section-wide directory this group's `dir` is stated relative to. */+ prefix: string;+ dimmed: boolean;+}) {+ // Named `fileCount` to match `WorktreeGroup`'s count and the entry the catalog+ // already had: Lingui keys the plural unit on the placeholder name, so a+ // second name mints a second translation unit for identical English.+ const fileCount = group.rows.length;+ // Controlled rather than reading `data-state` off the trigger. Radix Tooltip+ // and Collapsible both write that attribute, and an `asChild` chain spreads+ // the incoming one last — so a Tooltip wrapping the CollapsibleTrigger+ // silently overwrites `open` with the tooltip's own `closed`. Owning the flag+ // here lets the Tooltip wrap the BUTTON, which is what makes it reachable by+ // keyboard: Radix opens on the trigger's focus, and Tab lands on the button,+ // never on a span nested inside it.+ const [open, setOpen] = useState(false);+ // What a `WorktreeRow` never shows: its label is relative to `dir`, and+ // `dir` is itself relative to the hoisted prefix.+ const fullDir = prefix === '' ? group.dir : `${prefix}/${group.dir}`;+ return (+ <Collapsible open={open} onOpenChange={setOpen} className="flex flex-col gap-1">+ <Tooltip>+ <TooltipTrigger asChild>+ <CollapsibleTrigger asChild>+ <Button+ variant="ghost"+ size="xs"+ className="h-auto min-h-6 w-full justify-start gap-1 px-0 font-normal"+ >+ <ChevronRight+ className={`size-3 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none ${open ? 'rotate-90' : ''}`}+ aria-hidden+ />+ <span+ dir="auto"+ className="min-w-0 truncate text-start font-mono text-2xs text-muted-foreground"+ >+ {group.dir}+ </span>+ <span+ aria-hidden+ className="ms-auto shrink-0 ps-1 text-2xs text-muted-foreground tabular-nums"+ >+ {fileCount}+ </span>+ <span className="sr-only">+ <Plural value={fileCount} one="# file" other="# files" />+ </span>+ </Button>+ </CollapsibleTrigger>+ </TooltipTrigger>+ <TooltipContent dir="auto" className="font-mono text-2xs">+ {fullDir}+ </TooltipContent>+ </Tooltip>+ <CollapsibleContent className="ps-4">+ <WorktreeRows rows={group.rows} dimmed={dimmed} />+ </CollapsibleContent>+ </Collapsible>+ );+}++/**+ * A titled section of changed paths; renders nothing when empty.+ *+ * Collapsed by default, including the section the user is about to act on. The+ * popover is a status surface first: the count in the trigger is the signal, and+ * the paths are detail you open when you want them. The listing's scroll region+ * bounds the height independently, so this is a deliberate default rather than+ * a workaround for an overflowing panel.+ */function WorktreeGroup({title,note,@@ -806,16 +994,44 @@ function WorktreeGroup({dimmed?: boolean;}) {if (entries.length === 0) return null;+ const fileCount = entries.length;+ const { prefix, groups, loose } = groupWorktreeEntries(entries);return (- <div className="flex flex-col gap-1">- <span className="text-2xs font-medium text-muted-foreground">{title}</span>- {note && <span className="text-2xs text-muted-foreground/80">{note}</span>}- <ul className="flex flex-col gap-1">- {entries.map((entry) => (- <WorktreeRow key={`${entry.code}:${entry.path}`} entry={entry} dimmed={dimmed} />+ <Collapsible className="flex flex-col gap-1">+ <CollapsibleTrigger asChild>+ <Button+ variant="ghost"+ size="xs"+ className="group h-auto min-h-6 w-full justify-start gap-1 px-0 font-normal data-[state=open]:bg-transparent"+ >+ <ChevronRight+ className="size-3 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none group-data-[state=open]:rotate-90"+ aria-hidden+ />+ <span className="text-2xs font-medium text-muted-foreground">{title}</span>+ <span className="ms-auto shrink-0 ps-1 text-2xs text-muted-foreground tabular-nums">+ <Plural value={fileCount} one="# file" other="# files" />+ </span>+ </Button>+ </CollapsibleTrigger>+ <CollapsibleContent className="flex flex-col gap-1 ps-3">+ {note && <span className="text-2xs text-muted-foreground/80">{note}</span>}+ {prefix !== '' && (+ <span dir="auto" className="break-all font-mono text-2xs text-muted-foreground">+ {prefix}/+ </span>+ )}+ {groups.map((group) => (+ <WorktreeFolder+ key={prefix === '' ? group.dir : `${prefix}/${group.dir}`}+ group={group}+ prefix={prefix}+ dimmed={dimmed}+ />))}- </ul>- </div>+ {loose.length > 0 && <WorktreeRows rows={loose} dimmed={dimmed} />}+ </CollapsibleContent>+ </Collapsible>);}@@ -899,7 +1115,7 @@ function WorktreeStatusSection({return (<div className="flex flex-col gap-2.5 border-t pt-3"><div className="flex items-baseline justify-between gap-2">- <SectionLabel>+ <SectionLabel id="worktree-status-label"><Trans>Status</Trans></SectionLabel>{worktree && (worktree.branch || worktree.detached) && (@@ -936,7 +1152,23 @@ function WorktreeStatusSection({</p>) : (worktree && (- <div className="flex flex-col gap-2.5">+ <section+ // Its own scroll region, not the popover's: the mode selector and+ // the Pull/Push buttons sit above this, and letting an expanded+ // 25-file bucket grow the whole popover pushed them off-screen —+ // the listing is context for those controls, so it is the part+ // that should give way.+ // tabIndex makes the scroll region keyboard-focusable (Chromium+ // doesn't do this automatically); overscroll-contain keeps scroll+ // from bubbling to the popover's scroll chain.+ className="flex max-h-56 flex-col gap-2.5 overflow-y-auto overscroll-contain focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"+ // biome-ignore lint/a11y/noNoninteractiveTabindex: keyboard-focusable scroll container — Chromium doesn't make overflow:auto divs focusable without tabIndex.+ tabIndex={0}+ // <section> carries the region role implicitly, so `aria-labelledby`+ // has a role to attach its name to; on a bare div the name is dropped.+ aria-labelledby="worktree-status-label"+ data-testid="worktree-listing"+ >{/* Headings name the button rather than predicting the future:only `full` pushes on its own, so "will be pushed" would be apromise the product does not keep in Manual or Follow. */}@@ -953,7 +1185,7 @@ function WorktreeStatusSection({<Trans>Some files are not listed — the working tree has too many changes.</Trans></p>)}- </div>+ </section>))}</div>diff --git a/packages/app/src/components/settings/SettingsDialogBody.sync-mode.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogBody.sync-mode.dom.test.tsxindex 4b158cbbe..0b95307fa 100644--- a/packages/app/src/components/settings/SettingsDialogBody.sync-mode.dom.test.tsx+++ b/packages/app/src/components/settings/SettingsDialogBody.sync-mode.dom.test.tsx@@ -306,6 +306,37 @@ describe('Settings Sync section — three-way mode control (real hooks + dialog)expect(localPatchCalls).toEqual([{ autoSync: { mode: 'full', enabled: null } }]);});+ test('the push-outpaces-pull hint tracks both of its conditions', async () => {+ // Gated twice: only in `full`, and only when the push interval is the+ // shorter of the two. `off`/`follow` never push on a schedule, so the+ // control is absent there and a note about it would describe nothing.+ const hint = 'settings-sync-push-outpaces-pull-hint';++ projectLocalConfig = {+ autoSync: { mode: 'full', pullIntervalSeconds: 900, pushIntervalSeconds: 30 },+ };+ syncStatus = { ...syncStatus, syncMode: 'full', syncEnabled: true } as SyncStatus;+ await renderSyncSection();+ expect(screen.queryByTestId(hint)).toBeTruthy();+ cleanup();++ // Same mode, healthy ordering — nothing to say.+ projectLocalConfig = {+ autoSync: { mode: 'full', pullIntervalSeconds: 30, pushIntervalSeconds: 900 },+ };+ await renderSyncSection();+ expect(screen.queryByTestId(hint)).toBeNull();+ cleanup();++ // Inverted intervals but pull-only: no scheduled push exists to warn about.+ projectLocalConfig = {+ autoSync: { mode: 'follow', pullIntervalSeconds: 900, pushIntervalSeconds: 30 },+ };+ syncStatus = { ...syncStatus, syncMode: 'follow', syncEnabled: true } as SyncStatus;+ await renderSyncSection();+ expect(screen.queryByTestId(hint)).toBeNull();+ });+test('selecting Off writes immediately with no confirmation', async () => {projectLocalConfig = { autoSync: { mode: 'full' } };syncStatus = { ...syncStatus, syncMode: 'full', syncEnabled: true } as SyncStatus;diff --git a/packages/app/src/components/settings/SyncSection.tsx b/packages/app/src/components/settings/SyncSection.tsxindex 9678a10df..ee1673fa9 100644--- a/packages/app/src/components/settings/SyncSection.tsx+++ b/packages/app/src/components/settings/SyncSection.tsx@@ -93,6 +93,10 @@ export function SyncSection() {// Absent leaves resolve to the shipped 30 s / 60 s, so a project whose config// predates these keys shows today's cadence rather than an empty control.const intervals = resolveAutoSyncIntervals(projectLocalConfig?.autoSync);+ // Pushing faster than you pull leaves each push to discover the remote moved+ // and reconcile before it can land. Stated, not prevented: on a repo nobody+ // else writes to, the same setting is free, and clamping would forbid it.+ const pushOutpacesPull = intervals.pushIntervalSeconds < intervals.pullIntervalSeconds;// 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).@@ -663,6 +667,17 @@ export function SyncSection() {</Select></div>)}+ {localMode === 'full' && pushOutpacesPull && (+ <p+ className="text-1sm text-muted-foreground"+ data-testid="settings-sync-push-outpaces-pull-hint"+ >+ <Trans>+ You're pushing more often than you check for updates. If others write to this+ repo too, pushes will often have to pull and try again.+ </Trans>+ </p>+ )}</div></CollapsibleContent></Collapsible>diff --git a/packages/app/src/components/sync-worktree-grouping.test.ts b/packages/app/src/components/sync-worktree-grouping.test.tsnew file mode 100644index 000000000..5efb38c23--- /dev/null+++ b/packages/app/src/components/sync-worktree-grouping.test.ts@@ -0,0 +1,150 @@+import type { GitWorktreeEntry } from '@inkeep/open-knowledge-core';+import { describe, expect, test } from 'vitest';+import {+ commonDirPrefix,+ groupWorktreeEntries,+ MAX_WORKTREE_GROUPS,+} from './sync-worktree-grouping.ts';++function entry(path: string): GitWorktreeEntry {+ return { path, code: 'M', syncScoped: true };+}++describe('commonDirPrefix', () => {+ test('compares whole segments, never partial names', () => {+ // A character-wise prefix would hoist 'notes/' plus the shared 'a', which+ // is not a path any row could be stated relative to.+ expect(commonDirPrefix(['notes/alpha/x.md', 'notes/apex/y.md'])).toBe('notes');+ });++ test('is empty when the paths share no directory', () => {+ expect(commonDirPrefix(['a/x.md', 'b/y.md'])).toBe('');+ expect(commonDirPrefix(['x.md', 'a/y.md'])).toBe('');+ });++ test('a single path contributes its whole directory', () => {+ expect(commonDirPrefix(['a/b/c/x.md'])).toBe('a/b/c');+ });+});++describe('groupWorktreeEntries', () => {+ test('a lone entry keeps its full path rather than hoisting its folder', () => {+ const { prefix, groups, loose } = groupWorktreeEntries([entry('src/git/status.ts')]);+ expect(prefix).toBe('');+ expect(groups).toEqual([]);+ expect(loose.map((r) => r.label)).toEqual(['src/git/status.ts']);+ });++ test('an empty listing produces nothing', () => {+ expect(groupWorktreeEntries([])).toEqual({ prefix: '', groups: [], loose: [] });+ });++ test('the shared directory is hoisted once instead of repeating per row', () => {+ const { prefix, groups, loose } = groupWorktreeEntries([+ entry('public/ok/reports/a.md'),+ entry('public/ok/reports/b.md'),+ ]);+ expect(prefix).toBe('public/ok/reports');+ // Nothing left to bucket under the prefix, so both are loose rows.+ expect(groups).toEqual([]);+ expect(loose.map((r) => r.label)).toEqual(['a.md', 'b.md']);+ });++ test('a lone file never gets its own disclosure', () => {+ // The shape that looked wrong in the popover: five folders, four holding a+ // single file, each costing a click to reveal one row.+ const { groups, loose } = groupWorktreeEntries([+ entry('root/.agents/skills/one.md'),+ entry('root/.codex/skills/two.md'),+ entry('root/specs/three.md'),+ entry('root/reports/pierre/a.md'),+ entry('root/reports/pierre/b.md'),+ ]);+ expect(groups.map((g) => g.dir)).toEqual(['reports/pierre']);+ expect(loose.map((r) => r.label)).toEqual([+ '.agents/skills/one.md',+ '.codex/skills/two.md',+ 'specs/three.md',+ ]);+ });++ test('loose rows keep enough path to stay identifiable', () => {+ const { loose } = groupWorktreeEntries([+ entry('root/deep/nested/only.md'),+ entry('root/a.md'),+ entry('root/b.md'),+ ]);+ // Relative to the prefix, not just the basename — two `index.md` files in+ // different folders would otherwise render identically.+ expect(loose.map((r) => r.label)).toContain('deep/nested/only.md');+ });++ test('sibling leaf directories roll up into their shared parent', () => {+ const locales = ['ar', 'bn', 'es', 'fr', 'hi', 'id', 'ko', 'pt-BR', 'ur', 'zh-Hans'];+ const { prefix, groups, loose } = groupWorktreeEntries(+ locales.flatMap((l) => [+ entry(`app/src/locales/${l}/messages.po`),+ entry(`app/src/locales/${l}/messages.json`),+ ]),+ );+ expect(prefix).toBe('app/src/locales');+ // Ten locale dirs exceed MAX_WORKTREE_GROUPS (8), so the roll-up algorithm+ // collapses them all one level to the shared prefix. Once every key is ''+ // (directly under the prefix), all entries land in loose — not in folder+ // groups — so both these assertions must be checked on the full result, not+ // just on groups (which would be vacuously true on an empty array).+ expect(groups).toEqual([]);+ expect(loose).toHaveLength(20);+ // Every original entry survives in loose exactly once.+ const paths = loose.map((r) => r.entry.path).sort();+ const expected = locales+ .flatMap((l) => [`app/src/locales/${l}/messages.po`, `app/src/locales/${l}/messages.json`])+ .sort();+ expect(paths).toEqual(expected);+ });++ test('roll-up shortens the deepest groups and leaves shallow ones intact', () => {+ const deep = Array.from({ length: 10 }, (_, i) =>+ entry(`repo/app/src/locales/l${i}/messages.po`),+ );+ const { groups } = groupWorktreeEntries([+ ...deep,+ entry('repo/core/a.ts'),+ entry('repo/core/b.ts'),+ entry('repo/server/c.ts'),+ entry('repo/server/d.ts'),+ ]);+ expect(groups.length).toBeLessThanOrEqual(MAX_WORKTREE_GROUPS);+ const dirs = groups.map((g) => g.dir);+ // The shallow pairs were already legible and must not be rolled up just+ // because the deep ones were noisy.+ expect(dirs).toContain('core');+ expect(dirs).toContain('server');+ });++ test('groups come back biggest-first so the noisiest one is on top', () => {+ const { groups } = groupWorktreeEntries([+ entry('r/small/a.md'),+ entry('r/small/b.md'),+ entry('r/big/a.md'),+ entry('r/big/b.md'),+ entry('r/big/c.md'),+ ]);+ expect(groups.map((g) => g.dir)).toEqual(['big', 'small']);+ });++ test('every entry survives grouping exactly once', () => {+ const paths = ['a/b/c/one.md', 'a/b/d/two.md', 'a/e/three.md', 'f/four.md', 'five.md'];+ const { groups, loose } = groupWorktreeEntries(paths.map(entry), 2);+ const seen = [...groups.flatMap((g) => g.rows), ...loose].map((r) => r.entry.path);+ expect(seen.sort()).toEqual([...paths].sort());+ });++ test('a cap smaller than the number of root buckets terminates', () => {+ const { groups, loose } = groupWorktreeEntries(+ [entry('a/one.md'), entry('a/two.md'), entry('b/three.md'), entry('b/four.md')],+ 1,+ );+ expect([...groups.flatMap((g) => g.rows), ...loose]).toHaveLength(4);+ });+});diff --git a/packages/app/src/components/sync-worktree-grouping.ts b/packages/app/src/components/sync-worktree-grouping.tsnew file mode 100644index 000000000..aca9f2e97--- /dev/null+++ b/packages/app/src/components/sync-worktree-grouping.ts@@ -0,0 +1,147 @@+import type { GitWorktreeEntry } from '@inkeep/open-knowledge-core';++/**+ * How many folder groups a section may show before rows get rolled up into+ * shallower directories. Eight fits the popover without scrolling; past that+ * the listing stops reading as a summary and becomes the flat list it replaced.+ */+export const MAX_WORKTREE_GROUPS = 8;++/** Rows a group renders before it collapses the remainder into a "+N more". */+export const MAX_ROWS_PER_GROUP = 6;++export interface WorktreeRowModel {+ entry: GitWorktreeEntry;+ /** What the row renders: the path minus whatever its container already states. */+ label: string;+}++export interface WorktreeFolderGroup {+ /** Directory this group hoists, relative to the section prefix. Never empty. */+ dir: string;+ rows: WorktreeRowModel[];+}++export interface WorktreeGrouping {+ /**+ * Directory every entry in the section shares, stated once above the list.+ * Empty when they share nothing.+ */+ prefix: string;+ /** Folder buckets worth a disclosure — always more than one row each. */+ groups: WorktreeFolderGroup[];+ /**+ * Entries that never earned a bucket, rendered as plain rows. A group of one+ * is worse than no group: it costs a click and a line to reveal a single file.+ */+ loose: WorktreeRowModel[];+}++/** Directory portion of a POSIX path; '' when the path has no separator. */+function dirOf(path: string): string {+ const i = path.lastIndexOf('/');+ return i === -1 ? '' : path.slice(0, i);+}++function segments(dir: string): string[] {+ return dir === '' ? [] : dir.split('/');+}++/**+ * Longest directory shared by every path, compared segment-wise.+ *+ * Segment-wise, not character-wise: `notes/alpha` and `notes/beta` share the+ * string prefix `notes/`+`a`/`b`… — a character comparison would happily hoist+ * `notes/` plus a partial name and produce labels that are not paths.+ */+export function commonDirPrefix(paths: string[]): string {+ if (paths.length === 0) return '';+ let common = segments(dirOf(paths[0]));+ for (const path of paths.slice(1)) {+ const segs = segments(dirOf(path));+ let i = 0;+ while (i < common.length && i < segs.length && common[i] === segs[i]) i++;+ common = common.slice(0, i);+ if (common.length === 0) break;+ }+ return common.join('/');+}++function relativeTo(prefix: string, path: string): string {+ return prefix === '' ? path : path.slice(prefix.length + 1);+}++/**+ * Bucket changed paths into a hoisted prefix, collapsible folder groups, and+ * loose rows.+ *+ * Every level exists to state a path segment exactly once. The section prefix+ * carries what all entries share, a group header carries what its members+ * share, and the row carries only the remainder — because the flat listing this+ * replaces rendered the full path per row under `truncate`, which clips the+ * TAIL, so N files under one deep directory rendered as N identical strings.+ *+ * Grouping starts at each entry's own directory, then rolls the DEEPEST groups+ * up one segment at a time until the count fits `maxGroups`. Trimming deepest+ * first is what turns thirteen sibling `locales/<lang>` directories into one+ * `locales` group instead of shortening unrelated shallow paths that were+ * already legible.+ */+export function groupWorktreeEntries(+ entries: GitWorktreeEntry[],+ maxGroups: number = MAX_WORKTREE_GROUPS,+): WorktreeGrouping {+ if (entries.length === 0) return { prefix: '', groups: [], loose: [] };+ // Hoisting exists to stop a directory repeating. With one entry there is no+ // repetition to remove, and lifting its folder onto its own line splits a+ // short path across two lines to save nothing.+ if (entries.length === 1) {+ return { prefix: '', groups: [], loose: [{ entry: entries[0], label: entries[0].path }] };+ }++ const prefix = commonDirPrefix(entries.map((e) => e.path));+ // Every key below is relative to `prefix`, so the roll-up can never chew into+ // the part already stated above the list.+ const keyed = entries.map((entry) => {+ const rel = relativeTo(prefix, entry.path);+ return { entry, rel, key: dirOf(rel) };+ });++ const distinct = () => new Set(keyed.map((k) => k.key));+ while (distinct().size > maxGroups) {+ const maxDepth = Math.max(...keyed.map((k) => segments(k.key).length));+ // Everything is already at the root of the prefix: nothing left to trim, so+ // stop rather than spin.+ if (maxDepth === 0) break;+ for (const k of keyed) {+ if (segments(k.key).length === maxDepth) k.key = dirOf(k.key);+ }+ }++ const byKey = new Map<string, WorktreeRowModel[]>();+ for (const { entry, rel, key } of keyed) {+ const rows = byKey.get(key) ?? [];+ rows.push({ entry, label: key === '' ? rel : rel.slice(key.length + 1) });+ byKey.set(key, rows);+ }++ const groups: WorktreeFolderGroup[] = [];+ const loose: WorktreeRowModel[] = [];+ for (const [dir, rows] of byKey) {+ // Rows sitting directly under the hoisted prefix have no folder left to+ // name, and a lone file does not earn a disclosure — both go loose, showing+ // their full remainder so they stay identifiable without a header.+ if (dir === '' || rows.length === 1) {+ for (const row of rows)+ loose.push({ entry: row.entry, label: relativeTo(prefix, row.entry.path) });+ } else {+ groups.push({ dir, rows });+ }+ }++ // Biggest first — the bucket responsible for the noise is the one worth+ // opening. Ties break on path so the order does not shuffle between polls.+ groups.sort((a, b) => b.rows.length - a.rows.length || a.dir.localeCompare(b.dir));+ loose.sort((a, b) => a.entry.path.localeCompare(b.entry.path));+ return { prefix, groups, loose };+}diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.jsonindex d3ffde409..6bf330d3d 100644--- a/packages/app/src/locales/ar/messages.json+++ b/packages/app/src/locales/ar/messages.json@@ -5377,6 +5377,9 @@"wvbc1r": ["تعذّر فتح المستند"],"wxRR0H": ["لوحة Excalidraw"],"wzq9Rv": ["يوجد بالفعل فرع بهذا الاسم. افتح شجرة عمله من المبدِّل بدلًا من ذلك."],+ "x-E_vF": [+ "أنت تدفع تعديلاتك أكثر مما تتحقق من التحديثات. إذا كان آخرون يكتبون في هذا المستودع أيضًا، فسيضطر الدفع غالبًا إلى جلب التغييرات ثم المحاولة مرة أخرى."+ ],"x-fZxg": ["ادفع الفرع ", ["branch"], " إلى GitHub قبل المشاركة."],"x0RE0M": ["هل تريد بالتأكيد حذف «", ["name"], "» ومحتوياته؟"],"x2fr_j": ["الرسم البياني"],diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.poindex 14d79f4d5..87f1d3cc4 100644--- a/packages/app/src/locales/ar/messages.po+++ b/packages/app/src/locales/ar/messages.po@@ -700,6 +700,7 @@ msgid "{failedCount, plural, one {1 file failed to upload} other {{failedCount}msgstr "{failedCount, plural, zero {فشل رفع {failedCount} ملف} one {فشل رفع ملف واحد} two {فشل رفع ملفين} few {فشل رفع {failedCount} ملفات} many {فشل رفع {failedCount} ملفًا} other {فشل رفع {failedCount} ملف}}"#: src/components/ActivityModeContent.tsx+#: src/components/SyncStatusBadge.tsxmsgid "{fileCount, plural, one {# file} other {# files}}"msgstr "{fileCount, plural, zero {# ملف} one {ملف واحد} two {ملفان} few {# ملفات} many {# ملفًا} other {# ملف}}"@@ -1055,6 +1056,7 @@ msgid "+ Add {addChildName}"msgstr "+ إضافة {addChildName}"#: src/components/NavigatorApp.tsx+#: src/components/SyncStatusBadge.tsxmsgid "+{overflowCount} more"msgstr "+{overflowCount} إضافية"@@ -2906,6 +2908,7 @@ msgid "Collaborators see your in-progress edits as soon as they sync."msgstr "يرى المتعاونون تعديلاتك الجارية بمجرد مزامنتها."#: src/components/GraphPanel.tsx+#: src/components/SyncStatusBadge.tsxmsgid "Collapse"msgstr "طيّ"@@ -14975,6 +14978,10 @@ msgstr "اخترت مجلدك الرئيسي. سيفهرس OpenKnowledge كل مmsgid "You're all set up!"msgstr "اكتمل إعدادك!"+#: src/components/settings/SyncSection.tsx+msgid "You're pushing more often than you check for updates. If others write to this repo too, pushes will often have to pull and try again."+msgstr "أنت تدفع تعديلاتك أكثر مما تتحقق من التحديثات. إذا كان آخرون يكتبون في هذا المستودع أيضًا، فسيضطر الدفع غالبًا إلى جلب التغييرات ثم المحاولة مرة أخرى."+#: src/components/SyncStatusBadge.tsxmsgid "You're signed out — sign in to resume syncing."msgstr "أنت خارج تسجيل الدخول — سجّل الدخول لاستئناف المزامنة."diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.jsonindex e0195b4fc..72968aca2 100644--- a/packages/app/src/locales/bn/messages.json+++ b/packages/app/src/locales/bn/messages.json@@ -4589,6 +4589,9 @@"wvbc1r": ["নথি খোলা যায়নি"],"wxRR0H": ["Excalidraw ক্যানভাস"],"wzq9Rv": ["ওই নামে একটি ব্রাঞ্চ আগে থেকেই আছে। বদলে সুইচার থেকে এর ওয়ার্কট্রি খুলুন।"],+ "x-E_vF": [+ "আপনি আপডেট দেখার চেয়ে বেশি ঘন ঘন পুশ করছেন। এই রিপোজিটরিতে অন্যরাও লিখলে, পুশকে প্রায়ই আগে পরিবর্তন টেনে এনে আবার চেষ্টা করতে হবে।"+ ],"x-fZxg": ["শেয়ার করার আগে ", ["branch"], " ব্রাঞ্চটি GitHub-এ পুশ করুন।"],"x0RE0M": ["আপনি কি নিশ্চিত যে আপনি \"", ["name"], "\" এবং এর সমস্ত সামগ্রী মুছে ফেলতে চান?"],"x2fr_j": ["গ্রাফ"],diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.poindex bf451b40b..fb2f444cd 100644--- a/packages/app/src/locales/bn/messages.po+++ b/packages/app/src/locales/bn/messages.po@@ -700,6 +700,7 @@ msgid "{failedCount, plural, one {1 file failed to upload} other {{failedCount}msgstr "{failedCount, plural, one {১টি ফাইল আপলোড করা যায়নি} other {{failedCount}টি ফাইল আপলোড করা যায়নি}}"#: src/components/ActivityModeContent.tsx+#: src/components/SyncStatusBadge.tsxmsgid "{fileCount, plural, one {# file} other {# files}}"msgstr "{fileCount, plural, one {# ফাইল} other {# ফাইল}}"@@ -1051,6 +1052,7 @@ msgid "+ Add {addChildName}"msgstr "+ {addChildName} যোগ করুন"#: src/components/NavigatorApp.tsx+#: src/components/SyncStatusBadge.tsxmsgid "+{overflowCount} more"msgstr "+আরও {overflowCount}"@@ -2902,6 +2904,7 @@ msgid "Collaborators see your in-progress edits as soon as they sync."msgstr "সহযোগীরা সিঙ্ক হওয়ামাত্রই আপনার চলমান সম্পাদনা দেখতে পান।"#: src/components/GraphPanel.tsx+#: src/components/SyncStatusBadge.tsxmsgid "Collapse"msgstr "গুটিয়ে নিন"@@ -14971,6 +14974,10 @@ msgstr "আপনি আপনার হোম ডিরেক্টরি বmsgid "You're all set up!"msgstr "আপনার সব প্রস্তুত!"+#: src/components/settings/SyncSection.tsx+msgid "You're pushing more often than you check for updates. If others write to this repo too, pushes will often have to pull and try again."+msgstr "আপনি আপডেট দেখার চেয়ে বেশি ঘন ঘন পুশ করছেন। এই রিপোজিটরিতে অন্যরাও লিখলে, পুশকে প্রায়ই আগে পরিবর্তন টেনে এনে আবার চেষ্টা করতে হবে।"+#: src/components/SyncStatusBadge.tsxmsgid "You're signed out — sign in to resume syncing."msgstr "আপনি সাইন আউট আছেন — সিঙ্ক আবার শুরু করতে সাইন ইন করুন।"diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex ba105e09e..c91fb6ad9 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -4737,6 +4737,9 @@"wzq9Rv": ["A branch with that name already exists. Open its worktree from the switcher instead."],+ "x-E_vF": [+ "You're pushing more often than you check for updates. If others write to this repo too, pushes will often have to pull and try again."+ ],"x-fZxg": ["Push ", ["branch"], " to GitHub before sharing."],"x0RE0M": ["Are you sure you want to delete \"", ["name"], "\" and its contents?"],"x2fr_j": ["Graph"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 6a473e8fd..a14087ffa 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -700,6 +700,7 @@ msgid "{failedCount, plural, one {1 file failed to upload} other {{failedCount}msgstr "{failedCount, plural, one {1 file failed to upload} other {{failedCount} files failed to upload}}"#: src/components/ActivityModeContent.tsx+#: src/components/SyncStatusBadge.tsxmsgid "{fileCount, plural, one {# file} other {# files}}"msgstr "{fileCount, plural, one {# file} other {# files}}"@@ -1055,6 +1056,7 @@ msgid "+ Add {addChildName}"msgstr "+ Add {addChildName}"#: src/components/NavigatorApp.tsx+#: src/components/SyncStatusBadge.tsxmsgid "+{overflowCount} more"msgstr "+{overflowCount} more"@@ -2906,6 +2908,7 @@ msgid "Collaborators see your in-progress edits as soon as they sync."msgstr "Collaborators see your in-progress edits as soon as they sync."#: src/components/GraphPanel.tsx+#: src/components/SyncStatusBadge.tsxmsgid "Collapse"msgstr "Collapse"@@ -14975,6 +14978,10 @@ msgstr "You picked your home directory. OpenKnowledge will index everything in ymsgid "You're all set up!"msgstr "You're all set up!"+#: src/components/settings/SyncSection.tsx+msgid "You're pushing more often than you check for updates. If others write to this repo too, pushes will often have to pull and try again."+msgstr "You're pushing more often than you check for updates. If others write to this repo too, pushes will often have to pull and try again."+#: src/components/SyncStatusBadge.tsxmsgid "You're signed out — sign in to resume syncing."msgstr "You're signed out — sign in to resume syncing."diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.jsonindex 657570249..de8c77349 100644--- a/packages/app/src/locales/es/messages.json+++ b/packages/app/src/locales/es/messages.json@@ -5461,6 +5461,9 @@"wvbc1r": ["No se pudo abrir el documento"],"wxRR0H": ["Lienzo de Excalidraw"],"wzq9Rv": ["Ya existe una rama con ese nombre. Abre su worktree desde el selector."],+ "x-E_vF": [+ "Estás haciendo push con más frecuencia de la que buscas actualizaciones. Si otras personas también escriben en este repositorio, los push a menudo tendrán que traer los cambios y volver a intentarlo."+ ],"x-fZxg": ["Envía la rama ", ["branch"], " a GitHub antes de compartir."],"x0RE0M": ["¿Seguro que quieres eliminar «", ["name"], "» y su contenido?"],"x2fr_j": ["Grafo"],diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.poindex 52c9f00ad..83dee8591 100644--- a/packages/app/src/locales/es/messages.po+++ b/packages/app/src/locales/es/messages.po@@ -700,6 +700,7 @@ msgid "{failedCount, plural, one {1 file failed to upload} other {{failedCount}msgstr "{failedCount, plural, one {No se pudo subir 1 archivo} many {No se pudieron subir {failedCount} archivos} other {No se pudieron subir {failedCount} archivos}}"#: src/components/ActivityModeContent.tsx+#: src/components/SyncStatusBadge.tsxmsgid "{fileCount, plural, one {# file} other {# files}}"msgstr "{fileCount, plural, one {# archivo} many {# archivos} other {# archivos}}"@@ -1055,6 +1056,7 @@ msgid "+ Add {addChildName}"msgstr "+ Añadir {addChildName}"#: src/components/NavigatorApp.tsx+#: src/components/SyncStatusBadge.tsxmsgid "+{overflowCount} more"msgstr "+{overflowCount} más"@@ -2906,6 +2908,7 @@ msgid "Collaborators see your in-progress edits as soon as they sync."msgstr "Tus colaboradores ven tus ediciones en curso en cuanto se sincronizan."#: src/components/GraphPanel.tsx+#: src/components/SyncStatusBadge.tsxmsgid "Collapse"msgstr "Contraer"@@ -14975,6 +14978,10 @@ msgstr "Elegiste tu carpeta personal. OpenKnowledge indexará todo tu árbol permsgid "You're all set up!"msgstr "¡Ya está todo listo!"+#: src/components/settings/SyncSection.tsx+msgid "You're pushing more often than you check for updates. If others write to this repo too, pushes will often have to pull and try again."+msgstr "Estás haciendo push con más frecuencia de la que buscas actualizaciones. Si otras personas también escriben en este repositorio, los push a menudo tendrán que traer los cambios y volver a intentarlo."+#: src/components/SyncStatusBadge.tsxmsgid "You're signed out — sign in to resume syncing."msgstr "Has cerrado sesión: inicia sesión para reanudar la sincronización."diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.jsonindex 7a322b4d1..f1ae93ac1 100644--- a/packages/app/src/locales/fr/messages.json+++ b/packages/app/src/locales/fr/messages.json@@ -5518,6 +5518,9 @@"wzq9Rv": ["Une branche portant ce nom existe déjà. Ouvrez plutôt son worktree depuis le sélecteur."],+ "x-E_vF": [+ "Vous poussez plus souvent que vous ne recherchez des mises à jour. Si d'autres personnes écrivent aussi dans ce dépôt, les push devront souvent récupérer les modifications et réessayer."+ ],"x-fZxg": ["Envoyez la branche ", ["branch"], " sur GitHub avant de partager."],"x0RE0M": ["Voulez-vous vraiment supprimer « ", ["name"], " » et son contenu ?"],"x2fr_j": ["Graphe"],diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.poindex 20017435a..3df1c0b26 100644--- a/packages/app/src/locales/fr/messages.po+++ b/packages/app/src/locales/fr/messages.po@@ -700,6 +700,7 @@ msgid "{failedCount, plural, one {1 file failed to upload} other {{failedCount}msgstr "{failedCount, plural, one {L'envoi d'un fichier a échoué} many {L'envoi de {failedCount} fichiers a échoué} other {L'envoi de {failedCount} fichiers a échoué}}"#: src/components/ActivityModeContent.tsx+#: src/components/SyncStatusBadge.tsxmsgid "{fileCount, plural, one {# file} other {# files}}"msgstr "{fileCount, plural, one {# fichier} many {# fichiers} other {# fichiers}}"@@ -1055,6 +1056,7 @@ msgid "+ Add {addChildName}"msgstr "+ Ajouter {addChildName}"#: src/components/NavigatorApp.tsx+#: src/components/SyncStatusBadge.tsxmsgid "+{overflowCount} more"msgstr "+{overflowCount} de plus"@@ -2906,6 +2908,7 @@ msgid "Collaborators see your in-progress edits as soon as they sync."msgstr "Les collaborateurs voient vos modifications en cours dès qu'elles se synchronisent."#: src/components/GraphPanel.tsx+#: src/components/SyncStatusBadge.tsxmsgid "Collapse"msgstr "Réduire"@@ -14975,6 +14978,10 @@ msgstr "Vous avez choisi votre répertoire personnel. OpenKnowledge indexera toumsgid "You're all set up!"msgstr "Tout est prêt !"+#: src/components/settings/SyncSection.tsx+msgid "You're pushing more often than you check for updates. If others write to this repo too, pushes will often have to pull and try again."+msgstr "Vous poussez plus souvent que vous ne recherchez des mises à jour. Si d'autres personnes écrivent aussi dans ce dépôt, les push devront souvent récupérer les modifications et réessayer."+#: src/components/SyncStatusBadge.tsxmsgid "You're signed out — sign in to resume syncing."msgstr "Vous êtes déconnecté — connectez-vous pour reprendre la synchronisation."diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.jsonindex 8a9273be6..6e8d74452 100644--- a/packages/app/src/locales/hi/messages.json+++ b/packages/app/src/locales/hi/messages.json@@ -4570,6 +4570,9 @@"wvbc1r": ["दस्तावेज़ नहीं खोला जा सका"],"wxRR0H": ["Excalidraw कैनवास"],"wzq9Rv": ["उस नाम की एक ब्रांच पहले से मौजूद है। इसके बजाय स्विचर से इसका वर्कट्री खोलें।"],+ "x-E_vF": [+ "आप अपडेट जाँचने की तुलना में ज़्यादा बार पुश कर रहे हैं। अगर इस रिपॉज़िटरी में दूसरे लोग भी लिखते हैं, तो पुश को अक्सर पहले बदलाव खींचकर दोबारा कोशिश करनी होगी।"+ ],"x-fZxg": ["साझा करने से पहले ब्रांच ", ["branch"], " को GitHub पर पुश करें।"],"x0RE0M": ["क्या आप वाकई \"", ["name"], "\" और उसकी सामग्री को हटाना चाहते हैं?"],"x2fr_j": ["ग्राफ़"],diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.poindex 7b2d08b41..1ee74521b 100644--- a/packages/app/src/locales/hi/messages.po+++ b/packages/app/src/locales/hi/messages.po@@ -700,6 +700,7 @@ msgid "{failedCount, plural, one {1 file failed to upload} other {{failedCount}msgstr "{failedCount, plural, one {1 फ़ाइल अपलोड नहीं हो सकी} other {{failedCount} फ़ाइलें अपलोड नहीं हो सकीं}}"#: src/components/ActivityModeContent.tsx+#: src/components/SyncStatusBadge.tsxmsgid "{fileCount, plural, one {# file} other {# files}}"msgstr "{fileCount, plural, one {# फ़ाइल} other {# फ़ाइलें}}"@@ -1051,6 +1052,7 @@ msgid "+ Add {addChildName}"msgstr "+ {addChildName} जोड़ें"#: src/components/NavigatorApp.tsx+#: src/components/SyncStatusBadge.tsxmsgid "+{overflowCount} more"msgstr "+{overflowCount} और"@@ -2902,6 +2904,7 @@ msgid "Collaborators see your in-progress edits as soon as they sync."msgstr "सहयोगी आपके चल रहे संपादन सिंक होते ही देख लेते हैं।"#: src/components/GraphPanel.tsx+#: src/components/SyncStatusBadge.tsxmsgid "Collapse"msgstr "समेटें"@@ -14971,6 +14974,10 @@ msgstr "आपने अपनी होम निर्देशिका चmsgid "You're all set up!"msgstr "आपका सब कुछ तैयार है!"+#: src/components/settings/SyncSection.tsx+msgid "You're pushing more often than you check for updates. If others write to this repo too, pushes will often have to pull and try again."+msgstr "आप अपडेट जाँचने की तुलना में ज़्यादा बार पुश कर रहे हैं। अगर इस रिपॉज़िटरी में दूसरे लोग भी लिखते हैं, तो पुश को अक्सर पहले बदलाव खींचकर दोबारा कोशिश करनी होगी।"+#: src/components/SyncStatusBadge.tsxmsgid "You're signed out — sign in to resume syncing."msgstr "आप साइन आउट हैं — सिंक फिर से शुरू करने के लिए साइन इन करें।"diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.jsonindex 36e4b2de1..f393b9a24 100644--- a/packages/app/src/locales/id/messages.json+++ b/packages/app/src/locales/id/messages.json@@ -4739,6 +4739,9 @@"wvbc1r": ["Dokumen tidak bisa dibuka"],"wxRR0H": ["Kanvas Excalidraw"],"wzq9Rv": ["Cabang dengan nama itu sudah ada. Buka worktree-nya dari pengalih saja."],+ "x-E_vF": [+ "Anda melakukan push lebih sering daripada memeriksa pembaruan. Jika orang lain juga menulis di repo ini, push sering kali harus menarik perubahan dulu lalu mencoba lagi."+ ],"x-fZxg": ["Push cabang ", ["branch"], " ke GitHub sebelum berbagi."],"x0RE0M": ["Yakin ingin menghapus \"", ["name"], "\" beserta isinya?"],"x2fr_j": ["Graf"],diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.poindex 53d2560a4..3c3223b99 100644--- a/packages/app/src/locales/id/messages.po+++ b/packages/app/src/locales/id/messages.po@@ -700,6 +700,7 @@ msgid "{failedCount, plural, one {1 file failed to upload} other {{failedCount}msgstr "{failedCount, plural, other {{failedCount} berkas gagal diunggah}}"#: src/components/ActivityModeContent.tsx+#: src/components/SyncStatusBadge.tsxmsgid "{fileCount, plural, one {# file} other {# files}}"msgstr "{fileCount, plural, other {# berkas}}"@@ -1051,6 +1052,7 @@ msgid "+ Add {addChildName}"msgstr "+ Tambah {addChildName}"#: src/components/NavigatorApp.tsx+#: src/components/SyncStatusBadge.tsxmsgid "+{overflowCount} more"msgstr "+{overflowCount} lagi"@@ -2902,6 +2904,7 @@ msgid "Collaborators see your in-progress edits as soon as they sync."msgstr "Kolaborator melihat suntingan Anda yang sedang berjalan begitu tersinkronkan."#: src/components/GraphPanel.tsx+#: src/components/SyncStatusBadge.tsxmsgid "Collapse"msgstr "Ciutkan"@@ -14971,6 +14974,10 @@ msgstr "Anda memilih direktori beranda Anda. OpenKnowledge akan mengindeks semuamsgid "You're all set up!"msgstr "Semuanya sudah siap!"+#: src/components/settings/SyncSection.tsx+msgid "You're pushing more often than you check for updates. If others write to this repo too, pushes will often have to pull and try again."+msgstr "Anda melakukan push lebih sering daripada memeriksa pembaruan. Jika orang lain juga menulis di repo ini, push sering kali harus menarik perubahan dulu lalu mencoba lagi."+#: src/components/SyncStatusBadge.tsxmsgid "You're signed out — sign in to resume syncing."msgstr "Anda sudah keluar — masuk untuk melanjutkan sinkronisasi."diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.jsonindex b19944fe3..28fda1d65 100644--- a/packages/app/src/locales/ko/messages.json+++ b/packages/app/src/locales/ko/messages.json@@ -4538,6 +4538,9 @@"wvbc1r": ["문서를 열지 못했습니다"],"wxRR0H": ["Excalidraw 캔버스"],"wzq9Rv": ["해당 이름의 브랜치가 이미 있습니다. 대신 전환기에서 해당 워크트리를 여세요."],+ "x-E_vF": [+ "업데이트를 확인하는 것보다 더 자주 푸시하고 있습니다. 다른 사람도 이 저장소에 쓴다면, 푸시가 먼저 변경 사항을 가져온 뒤 다시 시도해야 하는 경우가 잦아집니다."+ ],"x-fZxg": ["공유하기 전에 ", ["branch"], "를 GitHub에 푸시하세요."],"x0RE0M": ["정말로 \"", ["name"], "\" 및 해당 내용을 삭제하시겠어요?"],"x2fr_j": ["그래프"],diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.poindex 61393f5ab..265a10497 100644--- a/packages/app/src/locales/ko/messages.po+++ b/packages/app/src/locales/ko/messages.po@@ -700,6 +700,7 @@ msgid "{failedCount, plural, one {1 file failed to upload} other {{failedCount}msgstr "{failedCount, plural, other {{failedCount}개 파일을 업로드하지 못했습니다}}"#: src/components/ActivityModeContent.tsx+#: src/components/SyncStatusBadge.tsxmsgid "{fileCount, plural, one {# file} other {# files}}"msgstr "{fileCount, plural, other {파일 #개}}"@@ -1055,6 +1056,7 @@ msgid "+ Add {addChildName}"msgstr "+ {addChildName} 추가"#: src/components/NavigatorApp.tsx+#: src/components/SyncStatusBadge.tsxmsgid "+{overflowCount} more"msgstr "+{overflowCount}개 더"@@ -2906,6 +2908,7 @@ msgid "Collaborators see your in-progress edits as soon as they sync."msgstr "공동 작업자는 동기화가 완료되면 진행 중인 편집 내용을 바로 볼 수 있습니다."#: src/components/GraphPanel.tsx+#: src/components/SyncStatusBadge.tsxmsgid "Collapse"msgstr "접기"@@ -14975,6 +14978,10 @@ msgstr "홈 디렉터리를 선택했습니다. OpenKnowledge가 홈 트리의msgid "You're all set up!"msgstr "설정이 완료되었습니다!"+#: src/components/settings/SyncSection.tsx+msgid "You're pushing more often than you check for updates. If others write to this repo too, pushes will often have to pull and try again."+msgstr "업데이트를 확인하는 것보다 더 자주 푸시하고 있습니다. 다른 사람도 이 저장소에 쓴다면, 푸시가 먼저 변경 사항을 가져온 뒤 다시 시도해야 하는 경우가 잦아집니다."+#: src/components/SyncStatusBadge.tsxmsgid "You're signed out — sign in to resume syncing."msgstr "로그아웃된 상태입니다. 동기화를 계속하려면 로그인하세요."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex ee2e4ce3d..f53271ca7 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -4737,6 +4737,9 @@"wzq9Rv": ["À ƀŕàńćĥ ŵĩţĥ ţĥàţ ńàḿē àĺŕēàďŷ ēxĩśţś. Ōƥēń ĩţś ŵōŕķţŕēē ƒŕōḿ ţĥē śŵĩţćĥēŕ ĩńśţēàď."],+ "x-E_vF": [+ "Ŷōũ'ŕē ƥũśĥĩńĝ ḿōŕē ōƒţēń ţĥàń ŷōũ ćĥēćķ ƒōŕ ũƥďàţēś. Ĩƒ ōţĥēŕś ŵŕĩţē ţō ţĥĩś ŕēƥō ţōō, ƥũśĥēś ŵĩĺĺ ōƒţēń ĥàvē ţō ƥũĺĺ àńď ţŕŷ àĝàĩń."+ ],"x-fZxg": ["Ƥũśĥ ", ["branch"], " ţō ĜĩţĤũƀ ƀēƒōŕē śĥàŕĩńĝ."],"x0RE0M": ["Àŕē ŷōũ śũŕē ŷōũ ŵàńţ ţō ďēĺēţē \"", ["name"], "\" àńď ĩţś ćōńţēńţś?"],"x2fr_j": ["Ĝŕàƥĥ"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex d7c190e7f..33b13267d 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -700,6 +700,7 @@ msgid "{failedCount, plural, one {1 file failed to upload} other {{failedCount}msgstr ""#: src/components/ActivityModeContent.tsx+#: src/components/SyncStatusBadge.tsxmsgid "{fileCount, plural, one {# file} other {# files}}"msgstr ""@@ -1051,6 +1052,7 @@ msgid "+ Add {addChildName}"msgstr ""#: src/components/NavigatorApp.tsx+#: src/components/SyncStatusBadge.tsxmsgid "+{overflowCount} more"msgstr ""@@ -2902,6 +2904,7 @@ msgid "Collaborators see your in-progress edits as soon as they sync."msgstr ""#: src/components/GraphPanel.tsx+#: src/components/SyncStatusBadge.tsxmsgid "Collapse"msgstr ""@@ -14971,6 +14974,10 @@ msgstr ""msgid "You're all set up!"msgstr ""+#: src/components/settings/SyncSection.tsx+msgid "You're pushing more often than you check for updates. If others write to this repo too, pushes will often have to pull and try again."+msgstr ""+#: src/components/SyncStatusBadge.tsxmsgid "You're signed out — sign in to resume syncing."msgstr ""diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.jsonindex 0c8a57011..928d05980 100644--- a/packages/app/src/locales/pt-BR/messages.json+++ b/packages/app/src/locales/pt-BR/messages.json@@ -5340,6 +5340,9 @@"wvbc1r": ["Não deu para abrir o documento"],"wxRR0H": ["Tela do Excalidraw"],"wzq9Rv": ["Já existe um ramo com esse nome. Abra o worktree dele pelo seletor."],+ "x-E_vF": [+ "Você está enviando com mais frequência do que verifica atualizações. Se outras pessoas também escrevem neste repositório, os pushes muitas vezes terão que buscar as alterações e tentar de novo."+ ],"x-fZxg": ["Envie o ramo ", ["branch"], " para o GitHub antes de compartilhar."],"x0RE0M": ["Tem certeza de que deseja excluir \"", ["name"], "\" e seu conteúdo?"],"x2fr_j": ["Grafo"],diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.poindex e291b03b3..e92366140 100644--- a/packages/app/src/locales/pt-BR/messages.po+++ b/packages/app/src/locales/pt-BR/messages.po@@ -700,6 +700,7 @@ msgid "{failedCount, plural, one {1 file failed to upload} other {{failedCount}msgstr "{failedCount, plural, one {Falha ao enviar 1 arquivo} many {Falha ao enviar {failedCount} arquivos} other {Falha ao enviar {failedCount} arquivos}}"#: src/components/ActivityModeContent.tsx+#: src/components/SyncStatusBadge.tsxmsgid "{fileCount, plural, one {# file} other {# files}}"msgstr "{fileCount, plural, one {# arquivo} many {# arquivos} other {# arquivos}}"@@ -1051,6 +1052,7 @@ msgid "+ Add {addChildName}"msgstr "+ Adicionar {addChildName}"#: src/components/NavigatorApp.tsx+#: src/components/SyncStatusBadge.tsxmsgid "+{overflowCount} more"msgstr "+{overflowCount} mais"@@ -2902,6 +2904,7 @@ msgid "Collaborators see your in-progress edits as soon as they sync."msgstr "Os colaboradores veem suas edições em andamento assim que elas sincronizam."#: src/components/GraphPanel.tsx+#: src/components/SyncStatusBadge.tsxmsgid "Collapse"msgstr "Recolher"@@ -14971,6 +14974,10 @@ msgstr "Você escolheu sua pasta pessoal. O OpenKnowledge vai indexar toda a suamsgid "You're all set up!"msgstr "Está tudo pronto!"+#: src/components/settings/SyncSection.tsx+msgid "You're pushing more often than you check for updates. If others write to this repo too, pushes will often have to pull and try again."+msgstr "Você está enviando com mais frequência do que verifica atualizações. Se outras pessoas também escrevem neste repositório, os pushes muitas vezes terão que buscar as alterações e tentar de novo."+#: src/components/SyncStatusBadge.tsxmsgid "You're signed out — sign in to resume syncing."msgstr "Você saiu da conta — entre para retomar a sincronização."diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.jsonindex 991794d0a..d0eb585e9 100644--- a/packages/app/src/locales/ur/messages.json+++ b/packages/app/src/locales/ur/messages.json@@ -4817,6 +4817,9 @@"wvbc1r": ["دستاویز نہیں کھل سکی"],"wxRR0H": ["Excalidraw کینوس"],"wzq9Rv": ["اس نام کی برانچ پہلے سے موجود ہے۔ اس کے بجائے سوئچر سے اس کا ورک ٹری کھولیں۔"],+ "x-E_vF": [+ "آپ اپ ڈیٹس دیکھنے سے زیادہ بار پُش کر رہے ہیں۔ اگر اس ریپو میں دوسرے لوگ بھی لکھتے ہیں، تو پُش کو اکثر پہلے تبدیلیاں کھینچ کر دوبارہ کوشش کرنی پڑے گی۔"+ ],"x-fZxg": ["شیئر کرنے سے پہلے برانچ ", ["branch"], " کو GitHub پر پش کریں۔"],"x0RE0M": ["کیا آپ واقعی \"", ["name"], "\" اور اس کے تمام مواد کو حذف کرنا چاہتے ہیں؟"],"x2fr_j": ["گراف"],diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.poindex f1856964b..5fc45fc1f 100644--- a/packages/app/src/locales/ur/messages.po+++ b/packages/app/src/locales/ur/messages.po@@ -700,6 +700,7 @@ msgid "{failedCount, plural, one {1 file failed to upload} other {{failedCount}msgstr "{failedCount, plural, one {1 فائل اپ لوڈ نہیں ہو سکی} other {{failedCount} فائلیں اپ لوڈ نہیں ہو سکیں}}"#: src/components/ActivityModeContent.tsx+#: src/components/SyncStatusBadge.tsxmsgid "{fileCount, plural, one {# file} other {# files}}"msgstr "{fileCount, plural, one {# فائل} other {# فائلیں}}"@@ -1055,6 +1056,7 @@ msgid "+ Add {addChildName}"msgstr "+ {addChildName} شامل کریں"#: src/components/NavigatorApp.tsx+#: src/components/SyncStatusBadge.tsxmsgid "+{overflowCount} more"msgstr "+{overflowCount} مزید"@@ -2906,6 +2908,7 @@ msgid "Collaborators see your in-progress edits as soon as they sync."msgstr "ساتھی آپ کی جاری ترامیم مطابقت پذیری ہوتے ہی دیکھ لیتے ہیں۔"#: src/components/GraphPanel.tsx+#: src/components/SyncStatusBadge.tsxmsgid "Collapse"msgstr "سکیڑیں"@@ -14975,6 +14978,10 @@ msgstr "آپ نے اپنی ہوم ڈائریکٹری منتخب کی۔ OpenKnowlmsgid "You're all set up!"msgstr "آپ کا سب کچھ تیار ہے!"+#: src/components/settings/SyncSection.tsx+msgid "You're pushing more often than you check for updates. If others write to this repo too, pushes will often have to pull and try again."+msgstr "آپ اپ ڈیٹس دیکھنے سے زیادہ بار پُش کر رہے ہیں۔ اگر اس ریپو میں دوسرے لوگ بھی لکھتے ہیں، تو پُش کو اکثر پہلے تبدیلیاں کھینچ کر دوبارہ کوشش کرنی پڑے گی۔"+#: src/components/SyncStatusBadge.tsxmsgid "You're signed out — sign in to resume syncing."msgstr "آپ سائن آؤٹ ہیں — مطابقت پذیری جاری رکھنے کے لیے سائن اِن کریں۔"diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.jsonindex dfc954055..fea97edf7 100644--- a/packages/app/src/locales/zh-Hans/messages.json+++ b/packages/app/src/locales/zh-Hans/messages.json@@ -4132,6 +4132,9 @@"wvbc1r": ["无法打开文档"],"wxRR0H": ["Excalidraw 画布"],"wzq9Rv": ["同名分支已存在。请从切换器中打开它的 worktree。"],+ "x-E_vF": [+ "你推送的频率高于检查更新的频率。如果其他人也在这个仓库里写入,推送往往需要先拉取更改再重试。"+ ],"x-fZxg": ["共享前请先将分支 ", ["branch"], " 推送到 GitHub。"],"x0RE0M": ["确定要删除“", ["name"], "”及其内容吗?"],"x2fr_j": ["关系图"],diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.poindex b24af62a2..08f3b568e 100644--- a/packages/app/src/locales/zh-Hans/messages.po+++ b/packages/app/src/locales/zh-Hans/messages.po@@ -700,6 +700,7 @@ msgid "{failedCount, plural, one {1 file failed to upload} other {{failedCount}msgstr "{failedCount, plural, other {{failedCount} 个文件上传失败}}"#: src/components/ActivityModeContent.tsx+#: src/components/SyncStatusBadge.tsxmsgid "{fileCount, plural, one {# file} other {# files}}"msgstr "{fileCount, plural, other {# 个文件}}"@@ -1055,6 +1056,7 @@ msgid "+ Add {addChildName}"msgstr "+ 添加 {addChildName}"#: src/components/NavigatorApp.tsx+#: src/components/SyncStatusBadge.tsxmsgid "+{overflowCount} more"msgstr "+还有 {overflowCount} 个"@@ -2906,6 +2908,7 @@ msgid "Collaborators see your in-progress edits as soon as they sync."msgstr "协作者一同步就能看到你正在进行的编辑。"#: src/components/GraphPanel.tsx+#: src/components/SyncStatusBadge.tsxmsgid "Collapse"msgstr "折叠"@@ -14975,6 +14978,10 @@ msgstr "你选择了主目录。OpenKnowledge 会索引整个主目录树——msgid "You're all set up!"msgstr "全都设置好了!"+#: src/components/settings/SyncSection.tsx+msgid "You're pushing more often than you check for updates. If others write to this repo too, pushes will often have to pull and try again."+msgstr "你推送的频率高于检查更新的频率。如果其他人也在这个仓库里写入,推送往往需要先拉取更改再重试。"+#: src/components/SyncStatusBadge.tsxmsgid "You're signed out — sign in to resume syncing."msgstr "你已退出登录——请登录以继续同步。"diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.jsonindex 9f22f9383..3599e45fc 100644--- a/packages/app/src/locales/zh-Hant/messages.json+++ b/packages/app/src/locales/zh-Hant/messages.json@@ -4162,6 +4162,9 @@"wvbc1r": ["無法開啟文件"],"wxRR0H": ["Excalidraw 畫布"],"wzq9Rv": ["同名的分支已存在。請改從切換器開啟它的 worktree。"],+ "x-E_vF": [+ "你推送的頻率高於檢查更新的頻率。如果其他人也在這個儲存庫裡寫入,推送往往需要先拉取變更再重試。"+ ],"x-fZxg": ["分享前請先將分支 ", ["branch"], " 推送到 GitHub。"],"x0RE0M": ["確定要刪除「", ["name"], "」及其內容嗎?"],"x2fr_j": ["關係圖"],diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.poindex 8ba6d46d2..eea41ee79 100644--- a/packages/app/src/locales/zh-Hant/messages.po+++ b/packages/app/src/locales/zh-Hant/messages.po@@ -700,6 +700,7 @@ msgid "{failedCount, plural, one {1 file failed to upload} other {{failedCount}msgstr "{failedCount, plural, other {{failedCount} 個檔案上傳失敗}}"#: src/components/ActivityModeContent.tsx+#: src/components/SyncStatusBadge.tsxmsgid "{fileCount, plural, one {# file} other {# files}}"msgstr "{fileCount, plural, other {# 個檔案}}"@@ -1055,6 +1056,7 @@ msgid "+ Add {addChildName}"msgstr "+ 新增 {addChildName}"#: src/components/NavigatorApp.tsx+#: src/components/SyncStatusBadge.tsxmsgid "+{overflowCount} more"msgstr "+還有 {overflowCount} 個"@@ -2906,6 +2908,7 @@ msgid "Collaborators see your in-progress edits as soon as they sync."msgstr "協作者一同步就會看到你正在進行的編輯。"#: src/components/GraphPanel.tsx+#: src/components/SyncStatusBadge.tsxmsgid "Collapse"msgstr "摺疊"@@ -14975,6 +14978,10 @@ msgstr "你選了家目錄。OpenKnowledge 會把整個家目錄樹都建立索msgid "You're all set up!"msgstr "全都設定好了!"+#: src/components/settings/SyncSection.tsx+msgid "You're pushing more often than you check for updates. If others write to this repo too, pushes will often have to pull and try again."+msgstr "你推送的頻率高於檢查更新的頻率。如果其他人也在這個儲存庫裡寫入,推送往往需要先拉取變更再重試。"+#: src/components/SyncStatusBadge.tsxmsgid "You're signed out — sign in to resume syncing."msgstr "你已登出——請登入以繼續同步。"diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.tsindex dfd95ef49..d7a845280 100644--- a/packages/core/src/bridge/bind-frontmatter-doc.ts+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts@@ -1,4 +1,3 @@-import type * as Y from 'yjs';import type { Err, Ok, Result } from '../config/result.ts';import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.tsindex 8bfdb40cd..005627195 100644--- a/packages/core/src/bridge/bridge-invariant.ts+++ b/packages/core/src/bridge/bridge-invariant.ts@@ -1,4 +1,3 @@-import { fnv1aDigest } from './hash-util.ts';export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.tsindex 2a597ec3d..f4cc8a286 100644--- a/packages/core/src/bridge/compose.ts+++ b/packages/core/src/bridge/compose.ts@@ -1,4 +1,3 @@-import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';diff --git a/packages/core/src/bridge/divergence-locate.ts b/packages/core/src/bridge/divergence-locate.tsindex d979f4b39..6b505314d 100644--- a/packages/core/src/bridge/divergence-locate.ts+++ b/packages/core/src/bridge/divergence-locate.ts@@ -1,4 +1,3 @@-import { findFirstDivergenceIndex } from './tolerance-telemetry.ts';export const BRIDGE_LINE_KINDS = [diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 01ef76a9f..8fb428b90 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,4 +1,3 @@-import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.tsindex 463e89595..9d9c244b0 100644--- a/packages/core/src/bridge/growth-detect.ts+++ b/packages/core/src/bridge/growth-detect.ts@@ -1,4 +1,3 @@-const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;diff --git a/packages/core/src/bridge/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.tsindex 0939885bb..c43fdd7e7 100644--- a/packages/core/src/bridge/intraline-predicate.ts+++ b/packages/core/src/bridge/intraline-predicate.ts@@ -1,4 +1,3 @@-export function rawLineCounts(doc: string): Map<string, number> {const counts = new Map<string, number>();for (const line of doc.split('\n')) {diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.tsindex c0dc65705..251560a35 100644--- a/packages/core/src/bridge/merge-three-way.ts+++ b/packages/core/src/bridge/merge-three-way.ts@@ -65,7 +65,6 @@ export function tryLineLevelCombine(return { clean: true, merged };}-export type BridgeMergeContentLossSide = 'user' | 'agent';export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.tsindex dcc5b0690..01ac80099 100644--- a/packages/core/src/bridge/normalize.ts+++ b/packages/core/src/bridge/normalize.ts@@ -1,4 +1,3 @@-import { stripFrontmatter } from '../extensions/frontmatter.ts';import { bodyEdgeEmpties } from './doc-boundary-space.ts';diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.tsindex 4f7b79587..bb53e7c7c 100644--- a/packages/core/src/bridge/pm-structural-equivalence.ts+++ b/packages/core/src/bridge/pm-structural-equivalence.ts@@ -32,7 +32,6 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };const BR_LITERAL_RE = /^<br\s*\/?>$/i;-interface DegradeEntry {readonly label: string;readonly severity: ToleranceClassSeverity;@@ -129,7 +128,6 @@ export interface ComparePmStructuralOptions {rawSourceSide?: 'expected';}-/** Rebuild a node with `fn` applied to each child; identity when childless.* Shared by the degrade canonicalizers so none re-implements the walk. */function mapChildren(@@ -255,7 +253,6 @@ function applyDegrades(tree: PmStructuralNode): {return { normalized: current, fired };}-export function comparePmStructural(expected: PmStructuralNode,actual: PmStructuralNode,diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.tsindex dca644141..af20de1e2 100644--- a/packages/core/src/bridge/subsequence.ts+++ b/packages/core/src/bridge/subsequence.ts@@ -1,4 +1,3 @@-/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):* insertions in `haystack` are free; any dropped or substituted `needle` byte* fails. */diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.tsindex a363dfd54..83d47404a 100644--- a/packages/core/src/markdown/callout-transformer.ts+++ b/packages/core/src/markdown/callout-transformer.ts@@ -1,4 +1,3 @@-import type { Blockquote, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.tsindex 4499dbc92..9807a7e82 100644--- a/packages/core/src/markdown/code-fence.ts+++ b/packages/core/src/markdown/code-fence.ts@@ -1,4 +1,3 @@-export function selectFenceChar(info: string): '`' | '~' {return info.includes('`') ? '~' : '`';}diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex 34704165b..7415c474a 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.tsindex b6299a948..ece5c02a1 100644--- a/packages/core/src/markdown/dedent-block-jsx-close.ts+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts@@ -1,4 +1,3 @@-import { findFencedRegions, isInsideFence } from './fence-regions.ts';const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.tsindex acd398aa6..54774764a 100644--- a/packages/core/src/markdown/details-accordion-promoter.ts+++ b/packages/core/src/markdown/details-accordion-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.tsindex ba9b56384..43ecdc709 100644--- a/packages/core/src/markdown/div-align-promoter.ts+++ b/packages/core/src/markdown/div-align-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.tsindex 4513da9bb..6d3f3643e 100644--- a/packages/core/src/markdown/fence-regions.ts+++ b/packages/core/src/markdown/fence-regions.ts@@ -1,4 +1,3 @@-const FENCE_RE = /^(`{3,}|~{3,})/gm;export function findFencedRegions(src: string): Array<[number, number]> {diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.tsindex 6931623c7..00f5771ee 100644--- a/packages/core/src/markdown/fixtures/index.ts+++ b/packages/core/src/markdown/fixtures/index.ts@@ -1,4 +1,3 @@-import { readFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -9,7 +8,6 @@ function fixturePath(...segments: string[]): string {return resolve(FIXTURES_DIR, ...segments);}-interface GfmExample {section: string;markdown: string;@@ -19,7 +17,6 @@ export function loadGfmExamples(): GfmExample[] {return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];}-interface MdxCrashEntry {id: string;input: string;@@ -71,7 +68,6 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {) as LargeEmbedFixture[];}-export function loadPrd6955Before(): string {return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');}@@ -80,7 +76,6 @@ export function loadPrd6955CorruptedTriplicated(): string {return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');}-export interface NgPinnedCase {id: string;name: string;@@ -97,7 +92,6 @@ export function loadNgPinnedCases(): NgPinnedCase[] {) as NgPinnedCase[];}-export function loadLargeRealistic(): string {return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');}diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.tsindex daa3ef82b..8b1eb8519 100644--- a/packages/core/src/markdown/fixtures/perf/generate.ts+++ b/packages/core/src/markdown/fixtures/perf/generate.ts@@ -1,4 +1,3 @@-import { writeFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -11,7 +10,6 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;const SEED = 0xf1de1117;-function mulberry32(seed: number): () => number {let a = seed >>> 0;return () => {@@ -38,7 +36,6 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {return items[items.length - 1][0];}-const WORDS = ['lorem','ipsum',@@ -156,7 +153,6 @@ function mdxBlock(rand: () => number): string {return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;}-type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';const MIX: readonly [BlockKind, number][] = [@@ -195,7 +191,6 @@ function generateDocument(blockCount: number, seed: number): string {return `${blocks.join('\n\n')}\n`;}-function main(): void {for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {const doc = generateDocument(count, SEED);diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.tsindex 32c055c5b..420dc0fe5 100644--- a/packages/core/src/markdown/guard-flanking-matrix.ts+++ b/packages/core/src/markdown/guard-flanking-matrix.ts@@ -7,7 +7,6 @@ import {import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';-export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;export type FlankClass = 'whitespace' | 'punctuation' | 'other';diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.tsindex 283913255..2653473da 100644--- a/packages/core/src/markdown/handler-shadow-audit.ts+++ b/packages/core/src/markdown/handler-shadow-audit.ts@@ -1,4 +1,3 @@-export interface HandlerShadowWitness {input: string;expect: 'byte' | 'byte-and-reparse-type';diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.tsindex 5d1000cc4..da0a81d23 100644--- a/packages/core/src/markdown/highlight-promoter.ts+++ b/packages/core/src/markdown/highlight-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.tsindex 9681c0056..787315157 100644--- a/packages/core/src/markdown/html-to-mdast.ts+++ b/packages/core/src/markdown/html-to-mdast.ts@@ -1,4 +1,3 @@-import type { Element as HastElement, Root as HastRoot } from 'hast';import type { List, Nodes as MdastNodes, Root as MdastRoot } from 'mdast';import rehypeParse from 'rehype-parse';@@ -129,8 +128,7 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRothrow new HtmlPayloadTooLargeError(html.length, maxBytes);}- const processor = unified()- .use(rehypeParse, { fragment: true });+ const processor = unified().use(rehypeParse, { fragment: true });for (const plugin of cleanupPlugins) {processor.use(plugin);diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.tsindex 994eb6917..706fa9afb 100644--- a/packages/core/src/markdown/image-promoter.ts+++ b/packages/core/src/markdown/image-promoter.ts@@ -1,4 +1,3 @@-import type { Image, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.tsindex ec1ac1b7e..779e27500 100644--- a/packages/core/src/markdown/index.ts+++ b/packages/core/src/markdown/index.ts@@ -1,4 +1,3 @@-import {type FromProseMirrorOptions,fromPmMark,@@ -207,7 +206,6 @@ export class MarkdownManager {}}-const registry = createRegistry();function destructureAttrs(@@ -256,7 +254,6 @@ function destructureAttrs(return result;}-function hasDirtyDescendant(node: PmNode): boolean {let found = false;node.descendants((child) => {@@ -279,7 +276,6 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChecreturn freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;}-function isEmptyMdastParagraph(node: MdastNodes): boolean {if (node.type !== 'paragraph') return false;const children = node.children ?? [];@@ -348,7 +344,6 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {return out;}-import {AUDIO_EXTENSIONS,FILE_ATTACHMENT_EXTENSIONS,@@ -601,7 +596,6 @@ function buildMdastToPmHandlers(}));}-if (m.emphasis) {handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({sourceDelimiter: node.data?.sourceDelimiter ?? '*',@@ -682,7 +676,6 @@ function buildMdastToPmHandlers(}));}-if (m.link) {const sourceLiteralMark = m.sourceLiteral;handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {@@ -980,7 +973,6 @@ function buildMdastToPmHandlers(};}-const blockUnknownHandler = (node: {type: string;position?: { start: { offset: number }; end: { offset: number } };@@ -1106,7 +1098,6 @@ function buildMdastToPmHandlers(return handlers as RemarkProseMirrorOptions['handlers'];}-function buildPmToMdastHandlers(schema: Schema,freshness: FreshnessCheckerHolder,diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.tsindex b79e9aef7..fa0be9e86 100644--- a/packages/core/src/markdown/lint/applies-to.ts+++ b/packages/core/src/markdown/lint/applies-to.ts@@ -1,4 +1,3 @@-import picomatch from 'picomatch';import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.tsindex 94b34dee1..312c9c74b 100644--- a/packages/core/src/markdown/lint/config-files.ts+++ b/packages/core/src/markdown/lint/config-files.ts@@ -1,4 +1,3 @@-const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set(['.markdownlint.json','.markdownlint.jsonc',diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.tsindex 7c54c0a73..cc667b93e 100644--- a/packages/core/src/markdown/lint/config-schemas.ts+++ b/packages/core/src/markdown/lint/config-schemas.ts@@ -52,7 +52,6 @@ const fullPluginShape = Object.fromEntries(LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),) as z.ZodRawShape;-export const LinterConfigSchema = z.object({enabled: z.boolean(),plugins: z.object(fullPluginShape),diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.tsindex a51f2ffb0..d48eea5e4 100644--- a/packages/core/src/markdown/lint/default-config.ts+++ b/packages/core/src/markdown/lint/default-config.ts@@ -6,7 +6,6 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSettingMD013: false,};-export function resolveMarkdownlintConfig(rules: Record<string, MarkdownlintRuleSetting> | undefined,): Configuration {diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.tsindex 9c9542661..ef478e268 100644--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts@@ -1,4 +1,3 @@-import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';export interface FrontmatterFieldConstraint {diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.tsindex b0e7833fd..5f953d667 100644--- a/packages/core/src/markdown/lint/frontmatter-validate.ts+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts@@ -1,4 +1,3 @@-import Ajv, { type ValidateFunction } from 'ajv';import Ajv2019 from 'ajv/dist/2019.js';import Ajv2020 from 'ajv/dist/2020.js';diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.tsindex 26fbc2b22..781226a5d 100644--- a/packages/core/src/markdown/lint/index.ts+++ b/packages/core/src/markdown/lint/index.ts@@ -1,4 +1,3 @@-import type { LintPluginFailureReporter } from './plugin-failure.ts';import { isLintPluginSelected, LINT_PLUGINS, type LinterConfig } from './plugins.ts';import type { LintDiagnostic } from './types.ts';@@ -80,8 +79,7 @@ function renderErrorMessage(error: unknown, depth = 0): string {try {const json = JSON.stringify(error);if (json !== undefined) return json;- } catch {- }+ } catch {}}return String(error);}diff --git a/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts b/packages/core/src/markdown/lint/okf-frontmatter/materialize.tsindex f438f1b16..7a5af097e 100644--- a/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts+++ b/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts@@ -1,4 +1,3 @@-import type { OkfRuleId } from '../okf-rule-meta.ts';import { fileNameFor, OKF_SCHEMA_DIR, okfSchemaPathFor } from './paths.ts';import { OKF_FRONTMATTER_REGISTRY } from './registry.ts';diff --git a/packages/core/src/markdown/lint/okf-frontmatter/paths.ts b/packages/core/src/markdown/lint/okf-frontmatter/paths.tsindex c290b6878..1ee913527 100644--- a/packages/core/src/markdown/lint/okf-frontmatter/paths.ts+++ b/packages/core/src/markdown/lint/okf-frontmatter/paths.ts@@ -1,4 +1,3 @@-import type { OkfRuleId } from '../okf-rule-meta.ts';export const OKF_SCHEMA_DIR = '.ok/okf';diff --git a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts b/packages/core/src/markdown/lint/okf-frontmatter/registry.tsindex 53ecb619d..f325fbbb4 100644--- a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts+++ b/packages/core/src/markdown/lint/okf-frontmatter/registry.ts@@ -1,4 +1,3 @@-import { compileAppliesTo } from '../applies-to.ts';import { validateFrontmatterSource } from '../frontmatter-validate.ts';import {diff --git a/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts b/packages/core/src/markdown/lint/okf-frontmatter/schemas.tsindex 89845d3d5..f1c37671b 100644--- a/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts+++ b/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts@@ -1,4 +1,3 @@-// file-level form is deliberate: the sibling `biome-ignore` must sit on the line// oxlint-disable unicorn/no-thenablediff --git a/packages/core/src/markdown/lint/okf-project/rules.ts b/packages/core/src/markdown/lint/okf-project/rules.tsindex 8b476332e..6d691ae2b 100644--- a/packages/core/src/markdown/lint/okf-project/rules.ts+++ b/packages/core/src/markdown/lint/okf-project/rules.ts@@ -1,4 +1,3 @@-import { SUPPORTED_DOC_EXTENSIONS } from '../../../constants/doc-extensions.ts';import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from '../okf-rule-meta.ts';diff --git a/packages/core/src/markdown/lint/okf-rule-meta.ts b/packages/core/src/markdown/lint/okf-rule-meta.tsindex 44913a9dc..4de50d79f 100644--- a/packages/core/src/markdown/lint/okf-rule-meta.ts+++ b/packages/core/src/markdown/lint/okf-rule-meta.ts@@ -1,4 +1,3 @@-export const OKF_RULE_IDS = ['no-wiki-links','log-shape',diff --git a/packages/core/src/markdown/lint/okf-rules.ts b/packages/core/src/markdown/lint/okf-rules.tsindex d0999b62e..1d5538421 100644--- a/packages/core/src/markdown/lint/okf-rules.ts+++ b/packages/core/src/markdown/lint/okf-rules.ts@@ -1,4 +1,3 @@-import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from './okf-rule-meta.ts';import type { OkfRule } from './okf-runner.ts';import { indexShape } from './rules/index-shape.ts';diff --git a/packages/core/src/markdown/lint/okf-runner.ts b/packages/core/src/markdown/lint/okf-runner.tsindex fabb08d6e..de130e3f4 100644--- a/packages/core/src/markdown/lint/okf-runner.ts+++ b/packages/core/src/markdown/lint/okf-runner.ts@@ -1,4 +1,3 @@-import type { Root } from 'mdast';import remarkFrontmatter from 'remark-frontmatter';import remarkGfm from 'remark-gfm';diff --git a/packages/core/src/markdown/lint/plugin-failure.ts b/packages/core/src/markdown/lint/plugin-failure.tsindex 1cd0d2543..e7d694890 100644--- a/packages/core/src/markdown/lint/plugin-failure.ts+++ b/packages/core/src/markdown/lint/plugin-failure.ts@@ -1,4 +1,3 @@-import type { LintPluginId } from './types.ts';export interface LintPluginFailure {diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.tsindex 1dae8316d..e7455ccf7 100644--- a/packages/core/src/markdown/lint/plugins.ts+++ b/packages/core/src/markdown/lint/plugins.ts@@ -1,4 +1,3 @@-import { z } from 'zod';import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';import {@@ -24,7 +23,6 @@ import {type OkfSlice,} from './types.ts';-const MarkdownlintRuleSettingSchema = z.union([z.boolean(),z.enum(MARKDOWNLINT_RULE_SEVERITIES),diff --git a/packages/core/src/markdown/lint/rules/index-shape.ts b/packages/core/src/markdown/lint/rules/index-shape.tsindex fcbb1b56c..59fe9b87d 100644--- a/packages/core/src/markdown/lint/rules/index-shape.ts+++ b/packages/core/src/markdown/lint/rules/index-shape.ts@@ -1,4 +1,3 @@-import type { List, ListItem } from 'mdast';import { EXIT, visit } from 'unist-util-visit';import { defineScopedOkfRule } from '../okf-runner.ts';diff --git a/packages/core/src/markdown/lint/rules/log-shape.ts b/packages/core/src/markdown/lint/rules/log-shape.tsindex 431e4e9c8..e0159519f 100644--- a/packages/core/src/markdown/lint/rules/log-shape.ts+++ b/packages/core/src/markdown/lint/rules/log-shape.ts@@ -1,4 +1,3 @@-import type { Heading } from 'mdast';import { toString as headingText } from 'mdast-util-to-string';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/lint/rules/no-wiki-links.ts b/packages/core/src/markdown/lint/rules/no-wiki-links.tsindex f75a04d15..2123e977f 100644--- a/packages/core/src/markdown/lint/rules/no-wiki-links.ts+++ b/packages/core/src/markdown/lint/rules/no-wiki-links.ts@@ -1,4 +1,3 @@-import type { Point } from 'unist';import { visit } from 'unist-util-visit';import { defineOkfRule } from '../okf-runner.ts';diff --git a/packages/core/src/markdown/lint/rules/reserved-casing.ts b/packages/core/src/markdown/lint/rules/reserved-casing.tsindex c8b4d8f28..89ef3e4a9 100644--- a/packages/core/src/markdown/lint/rules/reserved-casing.ts+++ b/packages/core/src/markdown/lint/rules/reserved-casing.ts@@ -1,4 +1,3 @@-import { SUPPORTED_DOC_EXTENSIONS } from '../../../constants/doc-extensions.ts';import { defineOkfRule } from '../okf-runner.ts';diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.tsindex 594830b88..2cffecae6 100644--- a/packages/core/src/markdown/lint/types.ts+++ b/packages/core/src/markdown/lint/types.ts@@ -1,4 +1,3 @@-import type { BrokenLinkReason } from '../../schemas/api/agent-write.ts';import type { OkfRuleId } from './okf-rule-meta.ts';@@ -113,7 +112,6 @@ export interface OkfSlice {generate?: { index?: boolean };}-interface RuleOptionSpecBase {key: string;description: string;diff --git a/packages/core/src/markdown/lint/validation-counts.ts b/packages/core/src/markdown/lint/validation-counts.tsindex 437cc539a..98238656e 100644--- a/packages/core/src/markdown/lint/validation-counts.ts+++ b/packages/core/src/markdown/lint/validation-counts.ts@@ -1,4 +1,3 @@-export interface ValidationSourceCounts {errorCount: number;warningCount: number;diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.tsindex bd79424c7..a5b511f25 100644--- a/packages/core/src/markdown/math-promoter.ts+++ b/packages/core/src/markdown/math-promoter.ts@@ -1,4 +1,3 @@-import type { Code, Root } from 'mdast';import type { Math as MdastMath } from 'mdast-util-math';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.tsindex 00fbc0035..ed89371d0 100644--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts@@ -1,4 +1,3 @@-import type { Comment, Element, ElementContent, Properties } from 'hast';import type { FootnoteDefinition, FootnoteReference } from 'mdast';import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.tsindex df788a80d..8ce2b2492 100644--- a/packages/core/src/markdown/mdast-to-html.ts+++ b/packages/core/src/markdown/mdast-to-html.ts@@ -1,4 +1,3 @@-import type { Element, Root as HastRoot, Text as HastText } from 'hast';import type { Root as MdastRoot, Text as MdastText } from 'mdast';import type { Handler } from 'mdast-util-to-hast';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex fa3cfcd86..bfd7e3109 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,4 +1,3 @@-import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.tsindex 17ed2b829..1a897fca8 100644--- a/packages/core/src/markdown/mermaid-promoter.ts+++ b/packages/core/src/markdown/mermaid-promoter.ts@@ -1,4 +1,3 @@-import type { Code, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.tsindex 4aa0490c4..d988f4b8b 100644--- a/packages/core/src/markdown/parse-with-fallback.ts+++ b/packages/core/src/markdown/parse-with-fallback.ts@@ -168,7 +168,6 @@ export function parseRecursive(}}-interface VFilePlace {offset?: number;start?: { offset?: number };@@ -187,7 +186,6 @@ function extractErrorOffset(err: unknown): number | undefined {return undefined;}-interface Region {start: number;end: number;@@ -211,7 +209,6 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {return null;}-export interface TagEvent {kind: 'open' | 'close' | 'self-close';name: string;@@ -358,7 +355,6 @@ function findFallbackRegion(src: string, errorOffset: number): Region {return { start: blockStart, end: blockEnd };}-interface SourceBlock {src: string;start: number;@@ -456,7 +452,6 @@ function tryPerBlockFallback(};}-function wholeDocRawText(source: string): JSONContent {return {type: 'doc',diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.tsindex 43d420187..e6ab4fd57 100644--- a/packages/core/src/markdown/parser-drop-closure.ts+++ b/packages/core/src/markdown/parser-drop-closure.ts@@ -1,4 +1,3 @@-export type DroppedTokenAdjudication =| {kind: 'format-dof-axis';diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.tsindex 55736041c..0e3224206 100644--- a/packages/core/src/markdown/pipeline.ts+++ b/packages/core/src/markdown/pipeline.ts@@ -1,4 +1,3 @@-import {type FromProseMirrorOptions,fromProseMirror,diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.tsindex ccf06e94d..91cdf658f 100644--- a/packages/core/src/markdown/position-aware-join.ts+++ b/packages/core/src/markdown/position-aware-join.ts@@ -1,4 +1,3 @@-import type { Join } from 'mdast-util-to-markdown';import type { Position } from 'unist';import { isBlankLineParagraph } from './zero-emission-blocks.ts';diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.tsindex e5b4c9eba..0f399d34c 100644--- a/packages/core/src/markdown/position-slice.ts+++ b/packages/core/src/markdown/position-slice.ts@@ -1,4 +1,3 @@-import type { Nodes, Root } from 'mdast';import { visit } from 'unist-util-visit';import type { VFile } from 'vfile';@@ -477,8 +476,7 @@ export function applyPositionSliceToNode(const first = source[startOff];if (first !== '[' && first !== '<' && !node.title) {node.data.sourceStyle = 'gfm-autolink';- }- else if (first === '[') {+ } else if (first === '[') {const slice = source.slice(startOff, endOff);const closeBracketIdx = slice.lastIndexOf('](');if (closeBracketIdx !== -1) {diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.tsindex ca225ce9b..db10fa54b 100644--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts@@ -1,4 +1,3 @@-import type { Comment, Element, Root, Text } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.tsindex 3a2524a9a..34068d103 100644--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts@@ -1,4 +1,3 @@-import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.tsindex 2279a0189..93151d43b 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.tsindex a0f467c42..188f02d83 100644--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.tsindex 4e8542a21..4ba2c3418 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.tsindex a3c96b24a..1a74b1272 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts@@ -1,4 +1,3 @@-import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.tsindex e95cf43d6..de35e7b79 100644--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts@@ -1,4 +1,3 @@-import type { Comment, Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.tsindex ffdb4d5b5..b4be1b2ea 100644--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts@@ -1,4 +1,3 @@-import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.tsindex e2a96d1a7..3c8d88b7c 100644--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.tsindex 0389575ac..cf2c9da8e 100644--- a/packages/core/src/markdown/resolve-image-url.ts+++ b/packages/core/src/markdown/resolve-image-url.ts@@ -1,4 +1,3 @@-import { isRelativeUrl } from './safe-url.ts';function isDevDiagnosticContext(): boolean {diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 8be632ba4..4d3250d3a 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,4 +1,3 @@-export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');diff --git a/packages/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.tsindex 96304e7a5..0dd54070e 100644--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts@@ -1,4 +1,3 @@-import type { JSONContent } from '@tiptap/core';import type { Nodes } from 'mdast';import { expect } from 'vitest';diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.tsindex 93798cf83..7cac5b042 100644--- a/packages/core/src/markdown/serialize-helpers.ts+++ b/packages/core/src/markdown/serialize-helpers.ts@@ -1,4 +1,3 @@-import type { Node as PmNode } from '@tiptap/pm/model';import type {MdxJsxAttribute,diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.tsindex 8c08b7a04..b012a5aff 100644--- a/packages/core/src/markdown/single-dollar-math-promoter.ts+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts@@ -1,4 +1,3 @@-import type { PhrasingContent, Root, Text } from 'mdast';import type { InlineMath } from 'mdast-util-math';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.tsindex 83d4af672..b50bea5ec 100644--- a/packages/core/src/markdown/to-markdown-handlers.ts+++ b/packages/core/src/markdown/to-markdown-handlers.ts@@ -1,4 +1,3 @@-import type { Nodes, Parents } from 'mdast';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { Handle, Info, State } from 'mdast-util-to-markdown';diff --git a/packages/core/src/markdown/underline-promoter.ts b/packages/core/src/markdown/underline-promoter.tsindex 6e6d73400..0f1b0f27d 100644--- a/packages/core/src/markdown/underline-promoter.ts+++ b/packages/core/src/markdown/underline-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Parent, Root } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.tsindex 932d7d2a8..1a082bda7 100644--- a/packages/core/src/markdown/unknown-mdast-guard.ts+++ b/packages/core/src/markdown/unknown-mdast-guard.ts@@ -1,4 +1,3 @@-import type { Root as MdastRoot } from 'mdast';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.tsindex ac9f5239b..d578476a7 100644--- a/packages/core/src/markdown/whitespace-char-ref.ts+++ b/packages/core/src/markdown/whitespace-char-ref.ts@@ -1,4 +1,3 @@-const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([[0x20, ' '],[0x09, '\t'],diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.tsindex afd9936fe..6dad26200 100644--- a/packages/core/src/markdown/wiki-link-micromark.ts+++ b/packages/core/src/markdown/wiki-link-micromark.ts@@ -17,7 +17,6 @@ declare module 'micromark-util-types' {}}-const CODE_BANG = 33; // !const CODE_LBRACKET = 91; // [const CODE_RBRACKET = 93; // ]@@ -261,7 +260,6 @@ export function wikiLinkSyntax(): Extension {};}-function enterWikiLink(this: CompileContext, token: Token) {this.enter({@@ -387,7 +385,6 @@ export const wikiLinkToMarkdown: {unsafe: [{ character: '[', inConstruct: ['phrasing'] }],};-const MICROMARK_EXT = wikiLinkSyntax();export function remarkWikiLink(this: Processor) {diff --git a/packages/core/src/schemas/api/sync-seed.test.ts b/packages/core/src/schemas/api/sync-seed.test.tsindex bd66e5576..d6b589f2b 100644--- a/packages/core/src/schemas/api/sync-seed.test.ts+++ b/packages/core/src/schemas/api/sync-seed.test.ts@@ -210,6 +210,22 @@ describe('SyncStatusSchema', () => {SyncStatusSchema.safeParse({ ...validStatus, lastPullOutcome: 'error-class' }).success,).toBe(false);});+ test('accepts a populated consecutivePushFailures', () => {+ expect(SyncStatusSchema.safeParse({ ...validStatus, consecutivePushFailures: 6 }).success).toBe(+ true,+ );+ });+ test('consecutivePushFailures is additive: a status without it still parses', () => {+ // Optional for version-skew safety — a payload from an engine predating the+ // split-leg backoff must not fail validation on a newer client.+ expect('consecutivePushFailures' in validStatus).toBe(false);+ expect(SyncStatusSchema.safeParse(validStatus).success).toBe(true);+ });+ test('rejects a negative consecutivePushFailures', () => {+ expect(+ SyncStatusSchema.safeParse({ ...validStatus, consecutivePushFailures: -1 }).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 d717a41e7..184615fdd 100644--- a/packages/core/src/schemas/api/sync-seed.ts+++ b/packages/core/src/schemas/api/sync-seed.ts@@ -205,6 +205,14 @@ export const SyncStatusSchema = zahead: z.number().int().min(0),behind: z.number().int().min(0),consecutiveFailures: z.number().int().min(0),+ /**+ * Push-leg failure streak. Backs an independent backoff from the pull leg:+ * a rejected push must not stretch the pull interval. Optional for+ * version-skew safety, and declared rather than left to `.loose()` for the+ * same reason as `lastPullOkUtc`: the success envelope serializes the+ * validated object, so an undeclared field never reaches the client.+ */+ consecutivePushFailures: z.number().int().min(0).optional(),conflictCount: z.number().int().min(0),hasRemote: z.boolean(),syncEnabled: z.boolean(),diff --git a/packages/server/src/sync-engine.test.ts b/packages/server/src/sync-engine.test.tsindex 878e03485..36f81e778 100644--- a/packages/server/src/sync-engine.test.ts+++ b/packages/server/src/sync-engine.test.ts@@ -21,7 +21,7 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';// narrow to a targeted skip of the specific live-git describe blocks —// do not restore a blanket process.env.CI gate.-import { execFile } from 'node:child_process';+import { execFile, execFileSync } from 'node:child_process';import {chmodSync,existsSync,@@ -44,7 +44,13 @@ import { listNames } from './git-paths.ts';import type { DetectGhAccountsFn, DetectGhFn, ProbeTokenStore } from './github-permissions.ts';import { getLogger } from './logger.ts';import type { CredentialUrlMatchReader } from './share/github-account.ts';-import { classifyFastForwardRefusal, SyncEngine, type SyncState } from './sync-engine.ts';+import {+ CONTENTION_WARN_THRESHOLD,+ classifyFastForwardRefusal,+ isFetchDisprovableFailure,+ SyncEngine,+ type SyncState,+} from './sync-engine.ts';const execFileAsync = promisify(execFile);@@ -2049,6 +2055,83 @@ describe('SyncEngine backoff thresholds via persisted state', () => {await engine.trigger();expect(engine.getStatus().consecutiveFailures).toBe(0);});++ test('consecutivePushFailures is restored independently of the pull leg', async () => {+ persistState({ consecutiveFailures: 2, consecutivePushFailures: 6 });+ const engine = makeEngine({ syncEnabled: false });+ await engine.start();+ expect(engine.getStatus().consecutiveFailures).toBe(2);+ expect(engine.getStatus().consecutivePushFailures).toBe(6);+ });++ test('a state file predating the push leg restores it as 0', async () => {+ // The key is absent, not zero — the shape every state file written before+ // the legs were split still has on disk.+ persistState({ consecutiveFailures: 4 });+ const engine = makeEngine({ syncEnabled: false });+ await engine.start();+ expect(engine.getStatus().consecutiveFailures).toBe(4);+ expect(engine.getStatus().consecutivePushFailures).toBe(0);+ });++ test('the connectivity latch survives a restart, so the release stays available', async () => {+ // The field exists to keep the discharge reachable after a restart mid+ // outage — closing the laptop while offline is the common case. If the+ // write or the read is dropped it reloads `false`, the release never fires,+ // and the user sits out the full tier after reconnecting.+ persistState({ consecutivePushFailures: 4, pushStreakIsConnectivity: true });+ const engine = makeEngine({ syncEnabled: false });+ await engine.start();+ const internals = engine as unknown as { pushStreakIsConnectivity: boolean };+ expect(engine.getStatus().consecutivePushFailures).toBe(4);+ expect(internals.pushStreakIsConnectivity).toBe(true);+ });++ test('the latch round-trips through saveStateNow, not just through a hand-written file', async () => {+ // The two tests around this one seed state with `persistState()`, which is+ // a raw writeFileSync — so neither reaches `saveStateNow`'s serializer.+ // Deleting the write there would leave both green while every restart+ // reloaded `false`, which is the exact regression the field prevents.+ const writer = makeEngine({ syncEnabled: false });+ await writer.start();+ const internals = writer as unknown as {+ consecutivePushFailures: number;+ pushStreakIsConnectivity: boolean;+ saveStateNow(): void;+ };+ internals.consecutivePushFailures = 3;+ internals.pushStreakIsConnectivity = true;+ internals.saveStateNow();+ await writer.stop();++ const reader = makeEngine({ syncEnabled: false });+ await reader.start();+ expect({+ streak: reader.getStatus().consecutivePushFailures,+ latch: (reader as unknown as { pushStreakIsConnectivity: boolean }).pushStreakIsConnectivity,+ }).toEqual({ streak: 3, latch: true });+ await reader.stop();+ });++ test('a state file predating the latch restores it as not-dischargeable', async () => {+ // Absent, not false: a restored streak with no recorded cause must keep its+ // backoff rather than be released on evidence that never covered it.+ persistState({ consecutivePushFailures: 6 });+ const engine = makeEngine({ syncEnabled: false });+ await engine.start();+ const internals = engine as unknown as { pushStreakIsConnectivity: boolean };+ expect(engine.getStatus().consecutivePushFailures).toBe(6);+ expect(internals.pushStreakIsConnectivity).toBe(false);+ });++ test('trigger() resets both legs', async () => {+ persistState({ consecutiveFailures: 5, consecutivePushFailures: 7 });+ const engine = makeEngine({ syncEnabled: false });+ await engine.start();+ await engine.trigger();+ expect(engine.getStatus().consecutiveFailures).toBe(0);+ expect(engine.getStatus().consecutivePushFailures).toBe(0);+ });});// ─── Auth-conditional pull cadence ──────────────────────────────────────────@@ -2592,6 +2675,356 @@ describe('SyncEngine setIntervals()', () => {});});+// ─── Push backoff interval math ─────────────────────────────────────────────++describe('SyncEngine contention warn threshold', () => {+ test('escalates to warn only once the run reaches the threshold', async () => {+ // Both e2e contention tests drive exactly one lost race, so the escalation+ // branch never runs there. A run of contentions is the signal an operator+ // needs — one is routine, a sustained run means the remote is moving faster+ // than this client can land a push.+ const engine = new SyncEngine({+ projectDir,+ contentDir,+ contentFilter: stubContentFilter,+ mode: 'full',+ pullIntervalSeconds: 30,+ pushIntervalSeconds: 60,+ });+ const internals = engine as unknown as {+ consecutiveContentions: number;+ logContention(): void;+ };+ const cap = captureSyncLogs();+ try {+ // Drive the counter through the branch the way the retry path does.+ for (let i = 0; i < CONTENTION_WARN_THRESHOLD + 1; i++) {+ internals.consecutiveContentions = i + 1;+ internals.logContention();+ }+ const levels = cap.entries+ .filter((e) => /contention|contended/i.test(e.msg))+ .map((e) => e.level);+ // Below the threshold it stays info; at and past it, warn.+ expect(levels.slice(0, CONTENTION_WARN_THRESHOLD - 1)).toEqual(+ Array(CONTENTION_WARN_THRESHOLD - 1).fill('info'),+ );+ expect(levels.slice(CONTENTION_WARN_THRESHOLD - 1)).toEqual(['warn', 'warn']);+ } finally {+ cap.restore();+ await engine.stop();+ }+ });+});++describe('SyncEngine runPushCycle pullInFlight guard', () => {+ type GuardInternals = {+ pullInFlight: boolean;+ pushTimer: NodeJS.Timeout | null;+ state: SyncState;+ doPushCycle(retriesLeft?: number): Promise<void>;+ runPushCycle(): Promise<void>;+ };++ /**+ * Put the engine past every guard that sits ABOVE `pullInFlight`, and stub the+ * cycle so the assertions observe the guard rather than its side effects.+ *+ * Five guards precede it: `pushInFlight`, `mode !== 'full'`, `state`+ * dormant/disabled/conflict/auth-error, `conflictCount > 0`, and+ * `isUnbornHead`. All are clear here, but `isUnbornHead` is false because+ * `projectDir` has no `.git` at all (a non-repository returns false early) —+ * NOT because the repo has commits. Add a `git init` to the shared beforeEach+ * and it flips true, which re-arms unconditionally and would quietly move the+ * assertions off this guard.+ *+ * The stub is what makes the contract observable: `runPushCycle`'s `finally`+ * unconditionally clears `pushInFlight` and calls `schedulePush()`, so an+ * assertion on either of those cannot distinguish "never entered" from+ * "entered and exited". `cycles` can.+ */+ function makeGuardEngine() {+ const engine = new SyncEngine({+ projectDir,+ contentDir,+ contentFilter: stubContentFilter,+ mode: 'full',+ pullIntervalSeconds: 30,+ pushIntervalSeconds: 60,+ });+ const internals = engine as unknown as GuardInternals;+ internals.state = 'idle';+ internals.pullInFlight = true;+ const cycles: number[] = [];+ internals.doPushCycle = async (retriesLeft = 0) => {+ cycles.push(retriesLeft);+ };+ return { engine, internals, cycles };+ }++ test('a pull in flight defers the push without running a cycle', async () => {+ const { engine, internals, cycles } = makeGuardEngine();+ await internals.runPushCycle();+ // The contract this block's name promises. Deleting the guard makes this+ // red; the `pushInFlight`/`pushTimer` assertions below cannot say the same,+ // because the `finally` produces the identical end state either way.+ expect(cycles).toEqual([]);+ await engine.stop();+ });++ test('the timer path re-arms, and a press does not clobber a live timer', async () => {+ // `runOneShotPush` has deliberately different re-arm semantics, so its+ // coverage says nothing about this branch. The conditional matters because+ // `pushOnce()` routes a full-mode press through here with a timer still+ // armed — re-arming would push the next scheduled push back a fresh+ // interval every time a press lost this race.+ const timer = makeGuardEngine();+ timer.internals.pushTimer = null;+ await timer.internals.runPushCycle();+ expect(timer.cycles).toEqual([]);+ expect(timer.internals.pushTimer).not.toBeNull();+ await timer.engine.stop();++ const press = makeGuardEngine();+ const armed = setTimeout(() => {}, 60_000);+ press.internals.pushTimer = armed;+ await press.internals.runPushCycle();+ expect(press.cycles).toEqual([]);+ expect(press.internals.pushTimer).toBe(armed);+ clearTimeout(armed);+ await press.engine.stop();+ });+});++describe('SyncEngine push-streak cause tracking', () => {+ type CauseInternals = {+ bumpFailureCount(op: 'push' | 'pull', connectivityClass?: boolean): void;+ consecutivePushFailures: number;+ pushStreakIsConnectivity: boolean;+ };++ function makeEngineForCause() {+ return new SyncEngine({+ projectDir,+ contentDir,+ contentFilter: stubContentFilter,+ mode: 'full',+ pullIntervalSeconds: 30,+ pushIntervalSeconds: 60,+ detectGh: () => ({ available: true, token: 'gh-token' }),+ }) as unknown as CauseInternals;+ }++ test('a streak of pure connectivity failures stays dischargeable', () => {+ const e = makeEngineForCause();+ e.bumpFailureCount('push', true);+ e.bumpFailureCount('push', true);+ expect(e.consecutivePushFailures).toBe(2);+ expect(e.pushStreakIsConnectivity).toBe(true);+ });++ test('one non-connectivity failure latches the streak undischargeable', () => {+ // A fetch disproves an outage; it says nothing about a protected branch. So+ // a single semantic failure has to poison the whole streak, even when a+ // network blip started it and more network blips follow.+ const e = makeEngineForCause();+ e.bumpFailureCount('push', true);+ e.bumpFailureCount('push', false);+ e.bumpFailureCount('push', true);+ expect(e.consecutivePushFailures).toBe(3);+ expect(e.pushStreakIsConnectivity).toBe(false);+ });++ test('the cause defaults to non-connectivity when the caller does not classify', () => {+ const e = makeEngineForCause();+ e.bumpFailureCount('push');+ expect(e.pushStreakIsConnectivity).toBe(false);+ });++ test('the predicate is driven by real classifier output, not a hand-passed flag', () => {+ // Every case below is classified by the production classifier, so a change+ // to the taxonomy or the subclass names turns this red rather than leaving+ // it green while the behaviour inverts.+ // Each row is asserted on its CLASSIFICATION as well as the predicate, so+ // a string that stops reaching the class it is meant to represent fails+ // loudly instead of passing for the wrong reason. The first attempt at this+ // table used `fatal: unable to access: ... error: 429`, which classifies as+ // `local/unknown-local` — the 429 rows proved nothing.+ const cases: Array<[string, string, boolean]> = [+ ['fatal: unable to access: Could not resolve host: github.com', 'network/dns', true],+ [+ 'fatal: unable to access: Failed to connect to github.com port 443: Connection refused',+ 'network/connection-refused',+ true,+ ],+ [+ 'fatal: unable to access: Operation timed out after 30001 milliseconds',+ 'network/timeout',+ true,+ ],+ // The residual network bucket — where most genuine unreachability lands,+ // and what an allowlist of the three named subclasses silently dropped.+ [+ 'fatal: unable to access: Failed to connect: Network is unreachable',+ 'network/unknown-network',+ true,+ ],+ ['fatal: Temporary failure in name resolution', 'network/unknown-network', true],+ // Refusing work, not unreachable: a read cannot disprove either.+ [+ 'error: RPC failed; HTTP 429 curl 22 The requested URL returned error: 429',+ 'network/429',+ false,+ ],+ [+ 'error: RPC failed; HTTP 503 curl 22 The requested URL returned error: 503',+ 'network/5xx',+ false,+ ],+ [+ '! [remote rejected] main -> main (protected branch hook declined)',+ 'semantic/protected-branch',+ false,+ ],+ // Retryable but NOT network. Without this row the table cannot tell a+ // predicate keyed on `class === 'network'` from one keyed on+ // `retryable === true` — both would pass every other row.+ ['error: could not write to index file: No space left on device', 'local/disk-full', false],+ ];+ for (const [stderr, expectedClass, expected] of cases) {+ const classified = classifyGitError(new Error(stderr));+ expect({+ stderr,+ classified: `${classified.class}/${classified.subclass}`,+ disprovable: isFetchDisprovableFailure(classified),+ }).toEqual({ stderr, classified: expectedClass, disprovable: expected });+ }+ });++ test('a rate-limited or 5xx push streak is NOT dischargeable by a fetch', () => {+ // Both share the `network` class, but they describe the remote refusing+ // work rather than being unreachable — and a fetch is a read, so it cannot+ // clear a write-path throttle. Treating them as disproven made a throttled+ // remote the one we retried hardest.+ for (const subclass of ['429', '5xx'] as const) {+ const e = makeEngineForCause();+ const classified = { class: 'network' as const, subclass, retryable: true as const };+ // The shipped predicate, not a copy of it: an inline re-implementation+ // silently goes stale the moment the real one changes, which is exactly+ // what happened when the allowlist became a denylist.+ e.bumpFailureCount('push', isFetchDisprovableFailure(classified));+ expect(e.pushStreakIsConnectivity).toBe(false);+ }+ });++ test('a pull failure never touches the push cause flag', () => {+ const e = makeEngineForCause();+ e.bumpFailureCount('push', true);+ e.bumpFailureCount('pull');+ expect(e.consecutivePushFailures).toBe(1);+ expect(e.pushStreakIsConnectivity).toBe(true);+ });+});++describe('SyncEngine effectivePushDelayMs floors on the configured interval', () => {+ // effectivePushDelayMs() must pick max(backoff, interval), not replace one+ // with the other. With no streak the backoff is 0 and the interval wins;+ // once streak ≥ 3 the 5-min backoff is the floor for short intervals, but a+ // longer configured interval is never cut down to the backoff.++ type PushDelayInternals = {+ effectivePushDelayMs(): number;+ consecutivePushFailures: number;+ };++ function bandP(seconds: number) {+ return { min: seconds * 0.85 * 1000, max: seconds * 1.15 * 1000 };+ }++ function makePushEngine(pushIntervalSeconds: number) {+ return new SyncEngine({+ projectDir,+ contentDir,+ contentFilter: stubContentFilter,+ mode: 'full',+ pullIntervalSeconds: 30,+ pushIntervalSeconds,+ detectGh: () => ({ available: true, token: 'gh-token' }),+ });+ }++ test('with no streak, delay equals the configured push interval', () => {+ const engine = makePushEngine(60);+ const internals = engine as unknown as PushDelayInternals;+ expect(internals.consecutivePushFailures).toBe(0);+ const delayMs = internals.effectivePushDelayMs();+ expect(delayMs).toBeGreaterThanOrEqual(bandP(60).min);+ expect(delayMs).toBeLessThanOrEqual(bandP(60).max);+ });++ test('with streak=3 (5-min backoff) and a short interval, backoff wins', () => {+ const engine = makePushEngine(60);+ const internals = engine as unknown as PushDelayInternals;+ internals.consecutivePushFailures = 3;+ const delayMs = internals.effectivePushDelayMs();+ // 5 min = 300 s > 60 s → backoff is the floor+ expect(delayMs).toBeGreaterThanOrEqual(bandP(300).min);+ expect(delayMs).toBeLessThanOrEqual(bandP(300).max);+ });++ test.each([+ [5, 900],+ [8, 3600],+ ])('streak=%i climbs to the %i-second tier', (streak, tierSeconds) => {+ const engine = makePushEngine(60);+ const internals = engine as unknown as PushDelayInternals;+ internals.consecutivePushFailures = streak;+ const delayMs = internals.effectivePushDelayMs();+ expect(delayMs).toBeGreaterThanOrEqual(bandP(tierSeconds).min);+ expect(delayMs).toBeLessThanOrEqual(bandP(tierSeconds).max);+ });++ test('with streak=3 (5-min backoff) and a long interval, interval wins', () => {+ const engine = makePushEngine(900);+ const internals = engine as unknown as PushDelayInternals;+ internals.consecutivePushFailures = 3;+ const delayMs = internals.effectivePushDelayMs();+ // 900 s > 300 s → interval is already gentler; backoff is not a cap+ expect(delayMs).toBeGreaterThanOrEqual(bandP(900).min);+ expect(delayMs).toBeLessThanOrEqual(bandP(900).max);+ });++ test('with streak=5 (15-min backoff) and a short interval, backoff wins', () => {+ const engine = makePushEngine(60);+ const internals = engine as unknown as PushDelayInternals;+ internals.consecutivePushFailures = 5;+ const delayMs = internals.effectivePushDelayMs();+ // 15 min = 900 s > 60 s → backoff is the floor+ expect(delayMs).toBeGreaterThanOrEqual(bandP(900).min);+ expect(delayMs).toBeLessThanOrEqual(bandP(900).max);+ });++ test('with streak=5 (15-min backoff) and an interval already longer, interval wins', () => {+ const engine = makePushEngine(3600);+ const internals = engine as unknown as PushDelayInternals;+ internals.consecutivePushFailures = 5;+ const delayMs = internals.effectivePushDelayMs();+ // 3600 s > 900 s → configured interval is gentler; backoff must not cap it+ expect(delayMs).toBeGreaterThanOrEqual(bandP(3600).min);+ expect(delayMs).toBeLessThanOrEqual(bandP(3600).max);+ });++ test('with streak=8 (60-min backoff) and a short interval, backoff wins', () => {+ const engine = makePushEngine(60);+ const internals = engine as unknown as PushDelayInternals;+ internals.consecutivePushFailures = 8;+ const delayMs = internals.effectivePushDelayMs();+ // 60 min = 3600 s > 60 s → backoff is the floor+ expect(delayMs).toBeGreaterThanOrEqual(bandP(3600).min);+ expect(delayMs).toBeLessThanOrEqual(bandP(3600).max);+ });+});+// ─── Lifecycle edge cases ───────────────────────────────────────────────────describe('SyncEngine lifecycle edge cases', () => {@@ -3192,7 +3625,8 @@ describe('SyncEngine push cycle stages shareable .ok artifacts (sync scope)', ()const status = engine.getStatus();expect(status.pushError).toContain('Shareable .ok subtree ".ok/schemas"');- expect(status.consecutiveFailures).toBeGreaterThan(0);+ expect(status.consecutivePushFailures).toBeGreaterThan(0);+ expect(status.consecutiveFailures).toBe(0);const detail = cap.entries.find((entry) => entry.msg === '[sync] push cycle: staging error detail',);@@ -3857,7 +4291,8 @@ describe('SyncEngine push cycle stages shareable .ok artifacts (sync scope)', ()const status = engine.getStatus();expect(status.pushError).toContain('Shareable .ok subtree ".ok"');- expect(status.consecutiveFailures).toBeGreaterThan(0);+ expect(status.consecutivePushFailures).toBeGreaterThan(0);+ expect(status.consecutiveFailures).toBe(0);expect((await git.revparse(['HEAD'])).trim()).toBe(headBefore);expect((await git.revparse(['origin/main'])).trim()).toBe(remoteBefore);const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);@@ -3898,7 +4333,8 @@ describe('SyncEngine push cycle stages shareable .ok artifacts (sync scope)', ()const status = engine.getStatus();expect(status.pushError).toContain('Shareable .ok subtree ".ok/schemas"');- expect(status.consecutiveFailures).toBeGreaterThan(0);+ expect(status.consecutivePushFailures).toBeGreaterThan(0);+ expect(status.consecutiveFailures).toBe(0);expect((await git.revparse(['HEAD'])).trim()).toBe(headBefore);expect((await git.revparse(['origin/main'])).trim()).toBe(remoteBefore);const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);@@ -7299,3 +7735,201 @@ describe('SyncEngine blocking-change resolution', () => {}});});++// ─── Black-box: the split-leg backoff against a real remote ──────────────────++describe('SyncEngine split-leg backoff, end to end', () => {+ /**+ * Land a commit on the bare remote from the sister clone.+ *+ * Synchronous by necessity, not by preference: the deterministic seam is+ * `setBatchInProgress`, which the engine calls synchronously, so an awaited+ * push cannot be used there. Both the seed push and the raced push go through+ * this one helper so the tests do not describe the same operation two ways.+ */+ function pushCompeting(sisterDir: string, marker: string): void {+ writeFileSync(join(sisterDir, 'foo.md'), `${marker}\n`, 'utf-8');+ // `stdio: 'pipe'` so routine commit/push chatter stays out of the suite+ // output; a failure still carries git's message on the thrown error.+ execFileSync('git', ['-C', sisterDir, 'commit', '-am', marker], { stdio: 'pipe' });+ execFileSync('git', ['-C', sisterDir, 'push', 'origin', 'main'], { stdio: 'pipe' });+ }++ /** Bare remote + a sister clone that can race the project's pushes. */+ async function setupWithSister(): Promise<{ bareDir: string; sisterDir: string }> {+ const bareDir = join(tmpDir, 'bare.git');+ mkdirSync(bareDir, { recursive: true });+ const bare = simpleGit(bareDir);+ await bare.init(true);+ await bare.raw('symbolic-ref', 'HEAD', 'refs/heads/main');++ 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, 'foo.md'), 'base\n', 'utf-8');+ await sister.add('.');+ await sister.commit('base');+ await sister.addRemote('origin', bareDir);+ await sister.push('origin', 'main');++ rmSync(projectDir, { recursive: true, force: true });+ await simpleGit(tmpDir).clone(bareDir, projectDir);+ mkdirSync(okDir, { recursive: true });+ const project = simpleGit(projectDir);+ await project.raw('config', 'user.name', 'Project');+ await project.raw('config', 'user.email', '[email protected]');+ return { bareDir, sisterDir };+ }++ test('a real DNS-failure push charges the push leg, and a real fetch discharges it', async () => {+ const { bareDir } = await setupWithSister();+ const project = simpleGit(projectDir);++ // A host that cannot resolve, so git emits a real "Could not resolve host"+ // and `classifyGitError` produces the network class this test exists to+ // exercise — the wiring the white-box tests bypass by hand-passing the+ // boolean. `.invalid` is reserved by RFC 2606 and never resolves.+ //+ // NOT a refused connection: curl reports that as "Couldn't connect to+ // server", which no NETWORK_PATTERNS entry matches, so it classifies as+ // non-network today and would make this test assert the wrong thing.+ await project.remote(['set-url', 'origin', 'http://sync-test.invalid/nope.git']);+ writeFileSync(join(projectDir, 'note.md'), 'local\n', 'utf-8');++ const engine = new SyncEngine({+ projectDir,+ contentDir: projectDir,+ contentFilter: stubContentFilter,+ mode: 'full',+ syncEnabled: true,+ });+ try {+ await engine.start();+ await engine.trigger('push');+ expect(engine.getStatus().consecutivePushFailures).toBeGreaterThan(0);++ // Remote reachable again. The discharge lives in the PULL cycle, and+ // `trigger()` zeroes both legs by design, so driving it through the+ // public trigger would pass no matter what. The scheduled loop is the+ // real caller; this reaches it directly rather than waiting on a timer.+ await project.remote(['set-url', 'origin', bareDir]);+ await (engine as unknown as { runPullCycle(): Promise<void> }).runPullCycle();++ expect(engine.getStatus().consecutivePushFailures).toBe(0);+ } finally {+ await engine.stop();+ }+ });++ test('contention releases a connectivity streak and the message it disproved', async () => {+ // The sibling test seeds a non-connectivity streak, so only the do-nothing+ // arm of `if (this.pushStreakIsConnectivity)` runs. The asymmetry between+ // the two arms is the point of that block: the retry's own fetch succeeded,+ // which disproves a connectivity streak and the error text it wrote, but+ // says nothing about a semantic one.+ const { sisterDir } = await setupWithSister();+ writeFileSync(join(projectDir, 'note.md'), 'mine\n', 'utf-8');+ pushCompeting(sisterDir, 'remote-1');++ let raced = false;+ const engine = new SyncEngine({+ projectDir,+ contentDir: projectDir,+ contentFilter: stubContentFilter,+ mode: 'full',+ syncEnabled: true,+ setBatchInProgress: (value: boolean) => {+ // FALSE edge: `true` fires before the retry's fetch, so acting there+ // would only race the fetch+merge+push sequence. `false` fires in the+ // inner finally — after fetch and merge, before the re-push — which is+ // exactly the window that produces a second non-fast-forward.+ if (value || raced) return;+ raced = true;+ pushCompeting(sisterDir, 'remote-2');+ },+ });+ try {+ await engine.start();+ const internals = engine as unknown as {+ consecutivePushFailures: number;+ consecutiveContentions: number;+ pushStreakIsConnectivity: boolean;+ pushError: string | undefined;+ runPushCycle(): Promise<void>;+ };+ internals.consecutivePushFailures = 5;+ internals.pushStreakIsConnectivity = true;+ internals.pushError = 'Connection timed out';++ await internals.runPushCycle();++ expect(raced).toBe(true);+ // The field that separates this branch from an ordinary landed push: a+ // push that succeeds also zeroes the streak, clears the latch and clears+ // the error, so without this the assertions below would pass on the wrong+ // path entirely.+ expect(internals.consecutiveContentions).toBe(1);+ expect(internals.consecutivePushFailures).toBe(0);+ expect(internals.pushStreakIsConnectivity).toBe(false);+ // The same fetch that released the streak disproved this text; keeping it+ // would let the badge show a dead network error for as long as contention+ // keeps any push from landing.+ expect(engine.getStatus().pushError).toBeUndefined();+ } finally {+ await engine.stop();+ }+ });++ test('a double non-fast-forward counts as contention, not as backoff', async () => {+ const { sisterDir } = await setupWithSister();++ writeFileSync(join(projectDir, 'note.md'), 'mine\n', 'utf-8');+ pushCompeting(sisterDir, 'remote-1');++ let raced = false;+ const engine = new SyncEngine({+ projectDir,+ contentDir: projectDir,+ contentFilter: stubContentFilter,+ mode: 'full',+ syncEnabled: true,+ setBatchInProgress: (value: boolean) => {+ // FALSE edge: `true` fires before the retry's fetch, so acting there+ // would race the whole fetch+merge+push sequence instead of landing in+ // the contention window.+ if (value || raced) return;+ raced = true;+ pushCompeting(sisterDir, 'remote-2');+ },+ });+ try {+ await engine.start();++ // Seed a non-zero streak first. `trigger('push')` zeroes both legs before+ // running and both push-success sites zero them again, so asserting 0+ // after the fact would pass whether or not contention accrued. What this+ // pins is that the contention path does not CHARGE the streak, which is+ // only observable against one the cycle inherits.+ const internals = engine as unknown as {+ consecutivePushFailures: number;+ consecutiveContentions: number;+ runPushCycle(): Promise<void>;+ };+ internals.consecutivePushFailures = 4;+ await internals.runPushCycle();++ expect(raced).toBe(true);+ // Unchanged: contention is not an outage, so it neither charges the tier+ // nor releases a streak it did not disprove — 4 was seeded without the+ // connectivity latch, so the discharge must not fire either.+ expect(internals.consecutivePushFailures).toBe(4);+ // Exactly one: a single cycle lost a single race.+ expect(internals.consecutiveContentions).toBe(1);+ } finally {+ await engine.stop();+ }+ });+});diff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.tsindex ba4b50328..b6620142f 100644--- a/packages/server/src/sync-engine.ts+++ b/packages/server/src/sync-engine.ts@@ -254,7 +254,17 @@ interface SyncStatus {lastPullOutcome: PullOutcome | null;ahead: number;behind: number;+ /**+ * Failure streaks, one per direction. Each governs only its own interval's+ * backoff: a rejected push must not stretch the pull interval, because an+ * exhausted push retry hands off to exactly that loop.+ *+ * `consecutiveFailures` is the pull leg, under the name it has always had on+ * the wire. Renaming it to match its sibling would be a deliberate migration,+ * not a field added beside it.+ */consecutiveFailures: number;+ consecutivePushFailures: number;conflictCount: number;/** True when a git remote exists, even if sync is dormant/disabled. */hasRemote: boolean;@@ -385,7 +395,18 @@ interface PersistedSyncState {lastPushOkUtc?: string | null;lastFetchUtc: string | null;lastPushedSha: string | null;+ /** Pull-leg failure streak. Legacy key name; see `SyncStatus`. */consecutiveFailures: number;+ /** Push-leg failure streak. Absent in older state files, which read 0. */+ consecutivePushFailures?: number;+ /**+ * Whether that streak is connectivity-class. Persisted with the counter it+ * gates: without it a restart mid-outage restores the tier but not the+ * evidence that releases it, so the engine sits out the full backoff after+ * the network is demonstrably back — the common case for a desktop app that+ * was closed while offline. Absent in older state files, which read false.+ */+ pushStreakIsConnectivity?: boolean;pausedReason?: string;pausedSinceUtc?: string;inflightConflicts: string[];@@ -537,6 +558,36 @@ function isUnbornHead(projectDir: string): boolean {// ─── Backoff thresholds ──────────────────────────────────────────────────────+/**+ * Consecutive contended pushes before the log escalates to `warn`. Three is one+ * more than a coincidence at any cadence, and still well short of a remote that+ * is merely busy for a moment.+ */+export const CONTENTION_WARN_THRESHOLD = 3;++/**+ * Whether a failure is the kind a later successful fetch disproves.+ *+ * Only transport-level unreachability qualifies. `429` and `5xx` share the+ * `network` class but describe the remote REFUSING work — a fetch is a read and+ * cannot clear a write-path rate limit, so treating them as disproven would+ * give a throttled remote the tightest retry loop of all.+ */+export function isFetchDisprovableFailure(+ classified: Pick<ClassifiedError, 'class' | 'subclass'>,+): boolean {+ // Denylist, not an allowlist. `unknown-network` is the residual bucket in+ // `classifyGitError`, and most genuine unreachability lands there — "network+ // is unreachable", "Temporary failure in name resolution", `ETIMEDOUT`,+ // `EHOSTUNREACH` and SSL handshake failures all miss the narrower+ // sub-branches and fall through to it. None describes a remote refusing+ // work. Naming what a read cannot disprove also keeps a subclass added to the+ // network class later dischargeable by default, which is the correct bias.+ return (+ classified.class === 'network' && classified.subclass !== '429' && classified.subclass !== '5xx'+ );+}+function backoffMs(consecutiveFailures: number): number {if (consecutiveFailures >= 8) return 60 * 60 * 1000; // 60 minif (consecutiveFailures >= 5) return 15 * 60 * 1000; // 15 min@@ -713,7 +764,27 @@ export class SyncEngine {private lastPushedSha: string | null = null;private lastPullUtc: string | null = null;private lastPullOutcome: PullOutcome | null = null;- private consecutiveFailures = 0;+ private consecutivePullFailures = 0;+ private consecutivePushFailures = 0;+ /**+ * Whether the current push streak is connectivity-class (a retryable+ * network/transport failure) rather than semantic or structural.+ *+ * A successful fetch proves the remote is reachable and the credential+ * resolves, which falsifies a connectivity-class streak outright — but says+ * nothing about a protected branch or an unreadable object store. Recording+ * the cause is what lets the fetch discharge only what it disproves.+ */+ private pushStreakIsConnectivity = false;+ /**+ * Consecutive pushes lost to write contention (non-fast-forward surviving the+ * inline fetch+merge retry). Deliberately NOT `consecutivePushFailures`:+ * contention is not an outage and must not accrue backoff. It is counted+ * anyway because a genuinely contended remote otherwise retries forever with+ * no streak, no error, and nothing in the log above `info` — indistinguishable+ * from a push that simply has not run yet.+ */+ private consecutiveContentions = 0;private ahead = 0;private behind = 0;private conflictCount = 0;@@ -1067,7 +1138,13 @@ export class SyncEngine {this.lastFetchUtc,this.currentPullIntervalSeconds(),);- const pushRemainingMs = computeRemainingMs(this.lastSyncUtc, this.pushIntervalSeconds);+ // Use lastPushOkUtc, not lastSyncUtc: lastSyncUtc is stamped by successful+ // pull merges as well, so a repo where pulls keep merging but pushes keep+ // failing would find a fresh lastSyncUtc on restart and arm the push at base+ // cadence — ignoring a restored consecutivePushFailures streak that should+ // gate it. lastPushOkUtc only advances on a landed push, so a failing-push+ // streak correctly survives the restart.+ const pushRemainingMs = computeRemainingMs(this.lastPushOkUtc, this.pushIntervalSeconds);this.schedulePull(pullRemainingMs > 0 ? pullRemainingMs : undefined);this.schedulePush(pushRemainingMs > 0 ? pushRemainingMs : undefined);log.info(@@ -1178,7 +1255,9 @@ export class SyncEngine {this.pausedReason = undefined;this.clearPushError();this.clearPullError();- this.consecutiveFailures = 0;+ this.consecutivePullFailures = 0;+ this.consecutivePushFailures = 0;+ this.pushStreakIsConnectivity = false;if (!this.hasRemote) {this.transitionTo('dormant');@@ -1401,7 +1480,9 @@ export class SyncEngine {this.pausedReason = undefined;this.clearPushError();this.clearPullError();- this.consecutiveFailures = 0;+ this.consecutivePullFailures = 0;+ this.consecutivePushFailures = 0;+ this.pushStreakIsConnectivity = false;// Remote may have changed while the user was signed out; re-detect so we// demote to dormant rather than scheduling cycles against no remote.@@ -1425,8 +1506,8 @@ export class SyncEngine {// ─── Manual trigger ────────────────────────────────────────────────────────/**- * Trigger an immediate push and/or pull (bypasses backoff, resets- * consecutiveFailures). Every `op` runs through a once-primitive, so a+ * Trigger an immediate push and/or pull (bypasses backoff, resets both+ * failure legs). Every `op` runs through a once-primitive, so a* manual-mode project (`off`, no background loop) does real work on an* explicit user act.*/@@ -1438,7 +1519,10 @@ export class SyncEngine {await this.fetchOnly();return;}- this.consecutiveFailures = 0;+ this.consecutivePullFailures = 0;+ this.consecutivePushFailures = 0;+ this.pushStreakIsConnectivity = false;+ this.consecutiveContentions = 0;// Retry clears transient paused reasons; protected-branch etc. stay set.if (this.pausedReason === 'dirty-tree' ||@@ -1837,7 +1921,8 @@ export class SyncEngine {lastPullOutcome: this.lastPullOutcome,ahead: this.ahead,behind: this.behind,- consecutiveFailures: this.consecutiveFailures,+ consecutiveFailures: this.consecutivePullFailures,+ consecutivePushFailures: this.consecutivePushFailures,conflictCount: this.conflictCount,hasRemote: this.hasRemote,syncEnabled: this.mode !== 'off',@@ -1949,7 +2034,9 @@ export class SyncEngine {this.blockingPaths = [];this.pausedReason = undefined;this.clearPullError();- this.consecutiveFailures = 0;+ this.consecutivePullFailures = 0;+ this.consecutivePushFailures = 0;+ this.pushStreakIsConnectivity = false;this.cc1Broadcaster?.signal('sync-status');this.scheduleSaveState();}@@ -2296,7 +2383,9 @@ export class SyncEngine {this.transitionTo('idle'); // fires CC1this.pausedReason = undefined;this.schedulePull();- this.schedulePush();+ // schedulePush(0): the conflict that stopped the push loop is gone, so+ // fire immediately rather than waiting out any accumulated backoff.+ this.schedulePush(0);} else {this.cc1Broadcaster?.signal('sync-status');}@@ -2354,7 +2443,9 @@ export class SyncEngine {this.transitionTo('idle');this.pausedReason = undefined;this.schedulePull();- this.schedulePush();+ // schedulePush(0): the user just resolved the conflict that was blocking+ // the push loop — fire immediately, not after a potential backoff delay.+ this.schedulePush(0);} else {// Partial resolution: state stays `conflict`, but conflictCount// dropped (e.g. 3 → 2). `transitionTo` is the only other site@@ -2386,7 +2477,9 @@ export class SyncEngine {this.pausedReason = undefined;this.transitionTo('idle');this.schedulePull();- this.schedulePush();+ // schedulePush(0): branch just reattached — no reason to wait out any+ // backoff from whatever failures predated the detached-HEAD pause.+ this.schedulePush(0);}}}@@ -2410,7 +2503,7 @@ export class SyncEngine {// 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);+ const delayMs = overrideDelayMs ?? this.effectivePushDelayMs();this.pushTimer = setTimeout(() => {this.pushTimer = null;this.runPushCycle().catch((e) => {@@ -2463,13 +2556,82 @@ export class SyncEngine {}private effectivePullDelayMs(): number {- const bkoff = backoffMs(this.consecutiveFailures);+ const bkoff = backoffMs(this.consecutivePullFailures);// 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);+ // Math.max: the backoff is a floor, not a replacement — if the configured+ // interval is already slower than the backoff tier, keep the configured+ // cadence rather than speeding up (which would invert the purpose of a slow+ // preset for metered connections or rate-limit-sensitive hosts).+ const backoffSeconds = bkoff > 0 ? bkoff / 1000 : 0;+ return jitteredMs(Math.max(backoffSeconds, this.currentPullIntervalSeconds()));+ }++ /**+ * Push delay for the current push-failure streak, mirroring+ * `effectivePullDelayMs`. Without it a remote that keeps rejecting pushes is+ * retried at the full configured cadence indefinitely.+ *+ * Recovery paths that call `schedulePush(0)` bypass this entirely; recovery+ * paths that call `schedulePush()` without an override inherit the backoff,+ * which is intentional for re-arms after an interval change or remote+ * detection (not errors), but recovery sites that cleared the cause of the+ * failure pass `schedulePush(0)` to fire immediately.+ */+ private effectivePushDelayMs(): number {+ const bkoff = backoffMs(this.consecutivePushFailures);+ // Same Math.max rationale as effectivePullDelayMs: backoff is a floor, not+ // a replacement for the configured interval.+ const backoffSeconds = bkoff > 0 ? bkoff / 1000 : 0;+ return jitteredMs(Math.max(backoffSeconds, this.pushIntervalSeconds));+ }++ /**+ * Report a push lost to write contention. One lost race is routine; a run of+ * them means the remote is moving faster than this client can land a push,+ * and an operator needs something above `info` to find.+ */+ private logContention(): void {+ const fields = {+ consecutiveContentions: this.consecutiveContentions,+ consecutivePushFailures: this.consecutivePushFailures,+ releasedConnectivityStreak: this.pushStreakIsConnectivity,+ };+ if (this.consecutiveContentions >= CONTENTION_WARN_THRESHOLD) {+ log.warn(+ fields,+ '[sync] push repeatedly losing to remote contention — not backing off by design',+ );+ } else {+ log.info(+ fields,+ '[sync] push still rejected after retry (contention) — scheduling next push at base cadence',+ );+ }+ }++ /**+ * Charge a failure to the leg that produced it, so each direction backs off+ * on its own streak. Routing on `op` — the direction every caller already+ * carries — is what keeps a push failure from stretching the pull interval.+ */+ private bumpFailureCount(op: 'push' | 'pull', connectivityClass = false): void {+ if (op === 'push') {+ // Any charged push failure ends a contention run: the next contention+ // starts a fresh streak rather than resuming one interrupted by an+ // unrelated outage.+ this.consecutiveContentions = 0;+ this.consecutivePushFailures++;+ // Latches false once any non-connectivity failure joins the streak: a+ // fetch must not discharge a streak that a protected branch contributed+ // to, even if a transient network blip started it.+ this.pushStreakIsConnectivity =+ this.consecutivePushFailures === 1+ ? connectivityClass+ : this.pushStreakIsConnectivity && connectivityClass;+ } else this.consecutivePullFailures++;}// ─── Pull cycle ────────────────────────────────────────────────────────────@@ -2477,7 +2639,7 @@ export class SyncEngine {private async runPullCycle(): Promise<void> {if (this.pullInFlight) return;// `auth-error` mirrors the push-cycle guard below. Auth errors are- // non-retryable and don't increment `consecutiveFailures`, so without this+ // non-retryable and don't increment the pull failure leg, so without this// an authless fetch would re-park in `auth-error` and reschedule at the// base interval forever — a steady busy-loop with no backoff (and, since// each fetch invokes the credential helper, a recurring credential-miss@@ -2536,8 +2698,26 @@ export class SyncEngine {try {await handle.git.fetch('origin');this.lastFetchUtc = new Date().toISOString();- this.consecutiveFailures = 0;+ this.consecutivePullFailures = 0;this.clearPullError();+ // The fetch just proved the remote reachable and the credential good, so+ // a push streak built purely from connectivity failures is disproven —+ // release it and fire, rather than leaving the push parked for up to an+ // hour after the outage it was waiting out has demonstrably ended. A+ // semantic or structural streak keeps its backoff: a fetch says nothing+ // about a protected branch or an unreadable object store.+ if (this.consecutivePushFailures > 0 && this.pushStreakIsConnectivity) {+ log.info(+ { cleared: this.consecutivePushFailures },+ '[sync] fetch succeeded — releasing connectivity-class push backoff',+ );+ this.consecutivePushFailures = 0;+ this.pushStreakIsConnectivity = false;+ // Configured cadence, not 0: the point is to stop waiting out an hour+ // of backoff for an outage that has demonstrably ended, not to promote+ // the push leg to the pull loop's frequency.+ this.schedulePush();+ }} catch (e) {const classified = classifyGitError(e instanceof Error ? e : new Error(String(e)));this.handleError(classified, 'pull');@@ -2695,7 +2875,7 @@ export class SyncEngine {// 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,+ // handleError so the pull failure leg 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 {@@ -2737,7 +2917,7 @@ export class SyncEngine {} 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+ // the pull failure leg increments and the retry backs off instead of// re-firing at the base interval against a persistently locked file.log.warn({ err: e },@@ -3267,6 +3447,28 @@ export class SyncEngine {this.schedulePush();return;}+ // A pull cycle holds the working tree and index for its whole duration —+ // it commits dirty content, may stash, and runs `git merge`. Pushing into+ // that stages files mid-merge against an index another git process owns.+ // Every other push entry point already asserts this; `runPushCycle` was the+ // outlier, so any `schedulePush(0)` added from a pull-side context could+ // reintroduce the interleave. Re-arm rather than return bare: the timer+ // that fired is already cleared, and this is the only chain call.+ if (this.pullInFlight) {+ // The one refusal here that fires during ordinary healthy operation: a+ // pull spans fetch + merge and runs every 30 s by default, so this window+ // is open a meaningful fraction of the time. The guards above gate+ // exceptional states the badge already explains, which is what makes+ // their silence reasonable and this one's not — `pushOnce()` routes a+ // full-mode press through all of them, so a press can land here.+ log.info({ pullInFlight: true }, '[sync] push cycle deferred — a pull cycle holds the tree');+ // Only re-arm when nothing is pending. The timer path nulls `pushTimer`+ // before calling and needs the chain continued; a manual press arrives+ // with one still armed, and `schedulePush()` would clear it and push the+ // next scheduled push back a full fresh interval.+ if (this.pushTimer === null) this.schedulePush();+ return;+ }this.pushInFlight = true;try {@@ -3288,8 +3490,13 @@ export class SyncEngine {// lifetime. The explicit path re-arms on none of them: arming a// background loop the user did not choose is the bug in the other// direction.- // - signal: refusals here are silent by design (a timer fires constantly);- // the explicit path logs every refusal, since a user is waiting on it.+ // - signal: most refusals here are silent by design (a timer fires+ // constantly); the explicit path logs every refusal, since a user is+ // waiting on it. `pushOnce()` routes a full-mode press through EVERY+ // guard below the mode check, so any of them can have a user behind it.+ // `pullInFlight` logs because it is the one that fires during ordinary+ // healthy operation rather than gating an exceptional state; a new guard+ // with that property should log too.// Collapsing them is how the loop-death case gets reintroduced. Change one// side deliberately, and re-read the other before assuming they should match.@@ -3396,6 +3603,9 @@ export class SyncEngine {this.lastPushedSha = headSha;this.lastSyncUtc = new Date().toISOString();this.pushCycleLanded = true;+ this.consecutivePushFailures = 0;+ this.consecutiveContentions = 0;+ this.pushStreakIsConnectivity = false;this.clearPushError();this.transitionTo('idle');return;@@ -3518,6 +3728,9 @@ export class SyncEngine {this.lastSyncUtc = new Date().toISOString();this.pushCycleLanded = true;this.ahead = 0;+ this.consecutivePushFailures = 0;+ this.consecutiveContentions = 0;+ this.pushStreakIsConnectivity = false;this.clearPushError();if (this.state === 'pushing') {this.transitionTo('idle');@@ -3544,8 +3757,13 @@ export class SyncEngine {log.info({}, '[sync] push rejected (non-fast-forward) — fetching, merging, retrying');const retryHandle = this.gitHandle();this.setBatchInProgress?.(true);+ // Track which step threw so the catch can route to the right leg.+ // 'fetch' and 'merge' are pull-leg operations; everything else is+ // push-side assembly (commit, stash restore, overlay restore, persist).+ let retryStage: 'fetch' | 'merge' | 'push' = 'fetch';try {await retryHandle.git.fetch('origin');+ retryStage = 'push';// Commit content-scoped dirty files before merging so the editor// racing against the outer push's `update-ref` doesn't cause// `git merge` to refuse with dirty-tree. `prepareForMerge` then@@ -3561,7 +3779,9 @@ export class SyncEngine {let overlaysRestored = true;try {await this.applyCommitIdentity(retryHandle);+ retryStage = 'merge';await retryHandle.git.merge([`origin/${this.currentBranch}`]);+ retryStage = 'push'; // merge succeeded; subsequent steps are push-side} finally {if (mergePrep.needsStashPop) {stashRestored = await this.popPreMergeStash(retryHandle);@@ -3572,28 +3792,23 @@ export class SyncEngine {if (!overlaysRestored) throw new Error('failed to restore reconciled MCP overlays');await this.persistReconciledMcpEntries(mergePrep.reconciled);} catch (mergeErr) {+ // Routed, NOT rethrown. This catch sits inside the outer catch, so+ // a throw here escapes doPushCycle entirely — past runOneShotPush's+ // catch-less try/finally, out to the fire-and-forget+ // `void engine.trigger()` call sites, where an unhandled rejection+ // terminates the server.const mc = classifyGitError(mergeErr instanceof Error ? mergeErr : new Error(String(mergeErr)),);if (mc.class === 'semantic' && mc.subclass === 'merge-conflict') {await this.handleMergeConflict();- } else if (mergeErr instanceof ShareableOkEnumerationError) {- // Routed, NOT rethrown. This catch sits inside the outer catch, so- // a throw here escapes doPushCycle entirely — past runOneShotPush's- // catch-less try/finally, out to the fire-and-forget- // `void engine.trigger()` call sites, where an unhandled rejection- // terminates the server.- //- // `'push'`, unlike the `else` below: a staging failure is the push- // leg failing to assemble what it would send, so it belongs on- // `pushError` — where the outer catch already puts this same error- // type. The sibling branch says `'pull'` because it handles MERGE- // errors, and the merge is the retry's pull leg. Same catch block,- // genuinely different directions.- log.warn({ err: mergeErr }, '[sync] push retry: staging error detail');- this.handleError(mc, 'push');} else {- this.handleError(mc, 'pull');+ // Route on the step that threw: fetch and merge are pull-leg+ // operations; commit, stash restore, overlay restore, and persist+ // are push-side assembly and belong on pushError.+ const leg = retryStage === 'merge' || retryStage === 'fetch' ? 'pull' : 'push';+ log.warn({ err: mergeErr, stage: retryStage }, '[sync] push retry error detail');+ this.handleError(mc, leg);}this.scheduleSaveState();return;@@ -3604,9 +3819,35 @@ export class SyncEngine {await this.doPushCycle(0);return;}- // Retry exhausted — let the next pull cycle handle it- log.info({}, '[sync] push still rejected after retry — waiting for next pull cycle');- this.consecutiveFailures++;+ // Retry exhausted. The fetch above succeeded, so the remote is reachable+ // and the credential resolves — this is write contention, not network+ // unavailability, and contention must not accrue toward a 60-minute+ // backoff the remote's own reachability disproves. So this path never+ // charges the streak.+ //+ // It discharges one only on the same evidence the fetch-success site+ // uses: a connectivity-class streak is disproven here, a semantic or+ // structural one is not. Zeroing unconditionally would let a single+ // contended push erase a protected-branch backoff that nothing about+ // this cycle contradicts.+ this.consecutiveContentions++;+ this.logContention();+ if (this.pushStreakIsConnectivity) {+ this.consecutivePushFailures = 0;+ this.pushStreakIsConnectivity = false;+ // The retry's own fetch succeeded, so the connectivity message this+ // streak carried is disproven by the same evidence that just+ // released it. Keeping it would let the badge show a dead network+ // error for as long as contention keeps any push from landing.+ // Scoped to this branch: a semantic or structural message is not+ // disproven by a successful read and still stands.+ this.clearPushError();+ }+ // No blanket clear here: this cycle did not land, and a message set by+ // an earlier, unrelated failure is still the best explanation on offer.+ // The connectivity arm above is the one exception — there the retry's+ // own fetch disproved the message, so it clears it. Everything else+ // stands until something replaces it.if (this.state === 'pushing') this.transitionTo('idle');} else {this.handleError(classified, 'push');@@ -3875,7 +4116,13 @@ export class SyncEngine {this.pullErrorCode = undefined;this.pullError = `Sync paused — your local changes to ${display}${rest} conflict with incoming changes. Commit, stash, or discard them before syncing.`;this.pausedReason = 'external-changes-pending';- this.consecutiveFailures = 0;+ // Reset only the pull leg: this pause is triggered by the pull/merge cycle+ // finding blocking paths. The push leg may have its own independent streak;+ // resetting it here would make the push backoff unreachable on exactly the+ // contention scenario it was added for. clearBlockingPause() (the+ // user-driven recovery) resets both legs — that's appropriate because it+ // represents an explicit user act, not an incidental pull-side event.+ this.consecutivePullFailures = 0;this.transitionTo('idle');this.scheduleSaveState();log.warn({ files: blocking }, '[sync] paused — dirty paths overlap incoming merge');@@ -4475,7 +4722,10 @@ export class SyncEngine {this.pullErrorCode = undefined;this.pullError = `Sync paused — couldn't auto-resolve ${display}${rest}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`;this.pausedReason = 'non-content-merge-failure';- this.consecutiveFailures = 0;+ // Reset only the pull leg — same rationale as the blocking-paths pause in+ // prepareForMerge: this is a pull/merge-cycle failure and should not+ // forgive an independent push streak.+ this.consecutivePullFailures = 0;this.transitionTo('idle');this.scheduleSaveState();log.warn(@@ -4644,15 +4894,20 @@ export class SyncEngine {// Self-heal: schedule an immediate push. The push cycle commits// working-tree edits via an isolated index, which reconciles the// tree against HEAD and lets the subsequent merge proceed.- this.consecutiveFailures++;+ this.bumpFailureCount(op);this.transitionTo('idle');this.pausedReason = 'dirty-tree';this.schedulePush(0);} else if (classified.retryable) {- this.consecutiveFailures++;+ // Only transport-level reachability failures are disproven by a later+ // fetch. `429`/`5xx` share the `network` class but describe the remote+ // REFUSING work, not being unreachable — and a fetch is a read, so it+ // cannot clear a write-path rate limit. Treating them as disproven made+ // a throttled remote the one we retried hardest.+ this.bumpFailureCount(op, isFetchDisprovableFailure(classified));this.transitionTo('offline');} else {- this.consecutiveFailures++;+ this.bumpFailureCount(op);this.transitionTo('idle');}}@@ -4722,7 +4977,9 @@ export class SyncEngine {lastPushOkUtc: this.lastPushOkUtc,lastFetchUtc: this.lastFetchUtc,lastPushedSha: this.lastPushedSha,- consecutiveFailures: this.consecutiveFailures,+ consecutiveFailures: this.consecutivePullFailures,+ consecutivePushFailures: this.consecutivePushFailures,+ pushStreakIsConnectivity: this.pushStreakIsConnectivity,pausedReason: persistedReason,pausedSinceUtc: persistedReason ? new Date().toISOString() : undefined,// Persist file paths of any in-flight conflicts so they survive restart@@ -4745,7 +5002,13 @@ export class SyncEngine {this.lastPushOkUtc = data.lastPushOkUtc ?? null;this.lastFetchUtc = data.lastFetchUtc ?? null;this.lastPushedSha = data.lastPushedSha ?? null;- this.consecutiveFailures = data.consecutiveFailures ?? 0;+ this.consecutivePullFailures = data.consecutiveFailures ?? 0;+ this.consecutivePushFailures = data.consecutivePushFailures ?? 0;+ // A state file predating this field restores a streak with no recorded+ // cause. `false` is the safe read: it keeps the backoff until a push+ // actually lands, rather than releasing a streak that may have been+ // semantic on evidence that never covered it.+ this.pushStreakIsConnectivity = data.pushStreakIsConnectivity ?? false;// Defense-in-depth: `saveStateNow` filters `'no-push-permission'` and// `'auth-error'` out, but a state file written by an earlier build (or// hand-edited) could still contain them. Drop both on load so a restart