Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): prevent overlapping sync corruption (PRD-8654) (#4424)
miles-kt-inkeep769b0eea1cb6
diff --git a/.changeset/prevent-overlapping-sync-cycles.md b/.changeset/prevent-overlapping-sync-cycles.mdnew file mode 100644index 000000000..16d73d96f--- /dev/null+++ b/.changeset/prevent-overlapping-sync-cycles.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Prevent overlapping Git sync cycles from committing conflict markers and erasing merge conflict stages. Automatic Git commits now pause while a Git operation or unresolved conflicts need attention. The app shows a localized sync pause with recovery guidance, while edits continue to save locally.diff --git a/docs/content/features/github-sync.mdx b/docs/content/features/github-sync.mdxindex aa5e536cc..0c06023df 100644--- a/docs/content/features/github-sync.mdx+++ b/docs/content/features/github-sync.mdx@@ -153,6 +153,7 @@ A few situations stop sync from completing successfully. In each case the sync s- **Unresolved conflicts.** If even one file has a conflict between your edits and your team's, sync waits. You can keep working on every other doc; only the conflicted files are frozen until you choose a side from the diff view. See [Resolving a conflict](#resolving-a-conflict) above.- **Local changes would be overwritten by an incoming update.** A teammate's update is ready to pull, but a file it touches has uncommitted local changes. Doc edits are committed automatically before merging, so this usually means other tracked files, like configs. Sync pauses rather than clobbering your work. The sync menu lists every blocked file under **Changed here and on the remote**, and **Commit and sync** commits exactly those files and resumes — nothing else in your working tree is touched. If you would rather stash the changes or throw them away, **Resolve in terminal** (desktop app only) opens a terminal on the project so you can run that yourself. OpenKnowledge never discards uncommitted work for you.+- **A Git operation or unresolved conflicts need attention.** Automatic Git commits pause when the repository has an unfinished merge, rebase, cherry-pick, or unresolved conflicts. The sync indicator and **Settings → Sync** explain the pause. Edits continue to save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync. With automatic sync enabled, it retries on its usual schedule and clears the notice once Git is ready.- **Edits made outside the app aren't ready yet.** If you (or another tool) edited a file directly on disk while sync wanted to merge, OpenKnowledge waits until those external edits settle before merging. Usually this clears in a second or two on its own.### Project isn't on a normal branchdiff --git a/packages/app/src/components/SyncStatusBadge.dom.test.tsx b/packages/app/src/components/SyncStatusBadge.dom.test.tsxindex cca0402ea..cca0edac9 100644--- a/packages/app/src/components/SyncStatusBadge.dom.test.tsx+++ b/packages/app/src/components/SyncStatusBadge.dom.test.tsx@@ -492,6 +492,54 @@ describe('SyncStatusBadge runtime behavior', () => {expect(screen.getByRole('button', { name: 'Sync status: Sync paused' })).toBeTruthy();});+ test.each(['full', 'follow', 'off'] as const)(+ '%s displays an actionable Git pause and removes it after recovery',+ async (mode) => {+ status = {+ ...baseStatus,+ state: mode === 'off' ? 'disabled' : 'idle',+ syncMode: mode,+ pausedReason: 'git-operation-in-progress',+ };+ projectLocalConfig = { autoSync: { mode } };+ await renderBadge();+ expect(screen.getByRole('button', { name: 'Sync status: Sync paused' })).toBeTruthy();+ await openPopover();+ const copy =+ 'Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync.';+ expect(screen.getByText(copy)).toBeTruthy();+ expect(screen.getByRole('status').textContent).toBe('');+ expect(screen.getByTestId('sync-popover-pull').hasAttribute('disabled')).toBe(false);+ act(() => {+ status &&= { ...status, pausedReason: undefined };+ forceStatusRender?.();+ });+ expect(screen.queryByText(copy)).toBeNull();+ const label = mode === 'off' ? 'Manual' : mode === 'follow' ? 'Up to date' : 'Synced';+ expect(screen.getByRole('button', { name: `Sync status: ${label}` })).toBeTruthy();+ },+ );++ test('a Git refusal takes display priority over an earlier offline state', async () => {+ status = { ...baseStatus, state: 'offline', pausedReason: 'git-operation-in-progress' };+ await renderBadge();+ expect(screen.getByRole('button', { name: 'Sync status: Sync paused' })).toBeTruthy();+ act(() => {+ status &&= { ...status, pausedReason: undefined };+ forceStatusRender?.();+ });+ expect(screen.getByRole('button', { name: 'Sync status: Offline' })).toBeTruthy();+ });++ test.each([+ ['conflict', 'Conflict', 2],+ ['auth-error', 'Reconnect required', 0],+ ] as const)('a Git pause preserves %s visual priority', async (state, label, conflictCount) => {+ status = { ...baseStatus, state, conflictCount, pausedReason: 'git-operation-in-progress' };+ await renderBadge();+ expect(screen.getByRole('button', { name: `Sync status: ${label}` })).toBeTruthy();+ });+test('a manual (mode off) project stays visible — Manual is a resting mode, not an opt-out', async () => {status = {...baseStatus,diff --git a/packages/app/src/components/SyncStatusBadge.tsx b/packages/app/src/components/SyncStatusBadge.tsxindex 2094ab823..33e856573 100644--- a/packages/app/src/components/SyncStatusBadge.tsx+++ b/packages/app/src/components/SyncStatusBadge.tsx@@ -96,6 +96,12 @@ export function displayState(status: GitSyncStatus): GitSyncStatus['state'] {if (status.state === 'idle' && status.conflictCount > 0) {return 'conflict';}+ if (+ (status.state === 'idle' || status.state === 'offline') &&+ status.pausedReason === 'git-operation-in-progress'+ ) {+ return 'disabled';+ }return status.state;}@@ -190,6 +196,8 @@ function stateLabel(status: GitSyncStatus): string {export function formatPausedReason(reason: string): string {switch (reason) {+ case 'git-operation-in-progress':+ return t`Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync.`;case 'external-changes-pending':return t`Local changes overlap with incoming sync`;case 'dirty-tree':diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.jsonindex 86ee21b66..0275bc249 100644--- a/packages/app/src/locales/ar/messages.json+++ b/packages/app/src/locales/ar/messages.json@@ -4808,6 +4808,9 @@"mHf8mp": ["حذف ملف المخطط ", ["file"]],"mHo0kp": ["انتهت مهلة طلب تفعيل أدوات Open Knowledge. تعمل هذه السلسلة بدونها."],"mI1KPS": ["لا توجد إضافات فحص مفعّلة، لذا تُفحص الروابط فقط."],+ "mJTr6D": [+ "مزامنة Git متوقفة مؤقتًا لأن هناك عملية Git أو تعارضات لم تُحل تحتاج إلى معالجة. ما زالت تعديلاتك تُحفظ محليًا. أكمل العملية أو حل التعارضات في الطرفية، ثم أعد محاولة المزامنة."+ ],"mPoOmg": ["ثبّت مهارة هنا أولاً"],"mPy9lS": ["نظّم مواصفاتي الحالية في فهرس مترابط مجمَّع حسب المجال، وأشِر إلى أي منها انحرف عن الكود الحالي."diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.poindex 19449d2c3..9fd9c1711 100644--- a/packages/app/src/locales/ar/messages.po+++ b/packages/app/src/locales/ar/messages.po@@ -6549,6 +6549,10 @@ msgstr "يحتاج Git إلى أداة مساعدة (مثل git-lfs) غير مثmsgid "Git sync"msgstr "مزامنة Git"+#: src/components/SyncStatusBadge.tsx+msgid "Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync."+msgstr "مزامنة Git متوقفة مؤقتًا لأن هناك عملية Git أو تعارضات لم تُحل تحتاج إلى معالجة. ما زالت تعديلاتك تُحفظ محليًا. أكمل العملية أو حل التعارضات في الطرفية، ثم أعد محاولة المزامنة."+#: src/components/SyncStatusBadge.tsxmsgid "GitHub authentication failed. Try signing in again."msgstr "فشلت مصادقة GitHub. حاول تسجيل الدخول مرة أخرى."diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.jsonindex b886cee47..bec53a2ae 100644--- a/packages/app/src/locales/bn/messages.json+++ b/packages/app/src/locales/bn/messages.json@@ -4090,6 +4090,9 @@"mHf8mp": ["স্কিমা ফাইল ", ["file"], " মুছুন"],"mHo0kp": ["Open Knowledge টুল সক্ষম করার অনুরোধের সময় শেষ হয়েছে। এই থ্রেড সেগুলো ছাড়াই চলবে।"],"mI1KPS": ["কোনো lint প্লাগইন চালু নেই, তাই শুধু লিংক পরীক্ষা করা হয়েছে।"],+ "mJTr6D": [+ "Git-এর একটি কাজ বা অমীমাংসিত দ্বন্দ্বের সমাধান প্রয়োজন হওয়ায় Git সিঙ্ক বিরতি দেওয়া হয়েছে। আপনার সম্পাদনাগুলো এখনও স্থানীয়ভাবে সংরক্ষিত হচ্ছে। টার্মিনালে কাজটি শেষ করুন বা দ্বন্দ্বগুলো মেটান, তারপর আবার সিঙ্ক করার চেষ্টা করুন।"+ ],"mPoOmg": ["প্রথমে এখানে একটি স্কিল ইনস্টল করুন"],"mPy9lS": ["আমার বিদ্যমান স্পেকগুলো এলাকা অনুযায়ী গোষ্ঠীবদ্ধ একটি যুক্ত সূচিতে সাজান, এবং যেগুলো বর্তমান কোডের সঙ্গে মিল হারিয়েছে সেগুলো চিহ্নিত করুন।"diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.poindex 3b3d7eee8..2d3542316 100644--- a/packages/app/src/locales/bn/messages.po+++ b/packages/app/src/locales/bn/messages.po@@ -6545,6 +6545,10 @@ msgstr "Git-এর একটি সহায়ক টুল (যেমন git-lmsgid "Git sync"msgstr "Git সিঙ্ক"+#: src/components/SyncStatusBadge.tsx+msgid "Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync."+msgstr "Git-এর একটি কাজ বা অমীমাংসিত দ্বন্দ্বের সমাধান প্রয়োজন হওয়ায় Git সিঙ্ক বিরতি দেওয়া হয়েছে। আপনার সম্পাদনাগুলো এখনও স্থানীয়ভাবে সংরক্ষিত হচ্ছে। টার্মিনালে কাজটি শেষ করুন বা দ্বন্দ্বগুলো মেটান, তারপর আবার সিঙ্ক করার চেষ্টা করুন।"+#: src/components/SyncStatusBadge.tsxmsgid "GitHub authentication failed. Try signing in again."msgstr "GitHub প্রমাণীকরণ ব্যর্থ। আবার সাইন ইন করে দেখুন।"diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 68420069f..01ee94aaf 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -4216,6 +4216,9 @@"The request to enable Open Knowledge tools timed out. This thread runs without them."],"mI1KPS": ["No lint plugins are enabled, so only links are checked."],+ "mJTr6D": [+ "Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync."+ ],"mPoOmg": ["install a skill here first"],"mPy9lS": ["Organize my existing specs into a linked index grouped by area, and flag any that have drifted out of sync with the current code."diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex c1b59e10a..12b35f3e8 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -6549,6 +6549,10 @@ msgstr "Git needs a helper tool (such as git-lfs) that isn't installed or couldnmsgid "Git sync"msgstr "Git sync"+#: src/components/SyncStatusBadge.tsx+msgid "Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync."+msgstr "Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync."+#: src/components/SyncStatusBadge.tsxmsgid "GitHub authentication failed. Try signing in again."msgstr "GitHub authentication failed. Try signing in again."diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.jsonindex 7873bab84..03890157e 100644--- a/packages/app/src/locales/es/messages.json+++ b/packages/app/src/locales/es/messages.json@@ -4890,6 +4890,9 @@"mI1KPS": ["No hay ningún complemento de análisis activado, así que solo se comprueban los enlaces."],+ "mJTr6D": [+ "La sincronización de Git está en pausa porque una operación de Git o conflictos sin resolver requieren atención. Tus cambios se siguen guardando localmente. Finaliza la operación o resuelve los conflictos en tu terminal y vuelve a intentar la sincronización."+ ],"mPoOmg": ["instala primero una habilidad aquí"],"mPy9lS": ["Organiza mis especificaciones existentes en un índice enlazado y agrupado por área, y señala las que se hayan desincronizado del código actual."diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.poindex 4f24bd41b..afa20249f 100644--- a/packages/app/src/locales/es/messages.po+++ b/packages/app/src/locales/es/messages.po@@ -6549,6 +6549,10 @@ msgstr "Git necesita una herramienta auxiliar (como git-lfs) que no está instalmsgid "Git sync"msgstr "Sincronización con git"+#: src/components/SyncStatusBadge.tsx+msgid "Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync."+msgstr "La sincronización de Git está en pausa porque una operación de Git o conflictos sin resolver requieren atención. Tus cambios se siguen guardando localmente. Finaliza la operación o resuelve los conflictos en tu terminal y vuelve a intentar la sincronización."+#: src/components/SyncStatusBadge.tsxmsgid "GitHub authentication failed. Try signing in again."msgstr "Falló la autenticación con GitHub. Prueba a iniciar sesión de nuevo."diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.jsonindex c80a54802..eafe810c7 100644--- a/packages/app/src/locales/fr/messages.json+++ b/packages/app/src/locales/fr/messages.json@@ -4933,6 +4933,9 @@"La demande d'activation des outils Open Knowledge a expiré. Ce fil fonctionne sans eux."],"mI1KPS": ["Aucun plugin de vérification n'est activé, donc seuls les liens sont contrôlés."],+ "mJTr6D": [+ "La synchronisation Git est en pause, car une opération Git ou des conflits non résolus nécessitent votre attention. Vos modifications continuent d’être enregistrées localement. Terminez l’opération ou résolvez les conflits dans votre terminal, puis réessayez la synchronisation."+ ],"mPoOmg": ["installez d'abord une compétence ici"],"mPy9lS": ["Organise mes spécifications existantes en un index lié, groupé par domaine, et signale celles qui ont divergé du code actuel."diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.poindex db4cf4bd4..27e64b9e9 100644--- a/packages/app/src/locales/fr/messages.po+++ b/packages/app/src/locales/fr/messages.po@@ -6549,6 +6549,10 @@ msgstr "Git a besoin d'un outil auxiliaire (comme git-lfs) qui n'est pas installmsgid "Git sync"msgstr "Synchronisation git"+#: src/components/SyncStatusBadge.tsx+msgid "Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync."+msgstr "La synchronisation Git est en pause, car une opération Git ou des conflits non résolus nécessitent votre attention. Vos modifications continuent d’être enregistrées localement. Terminez l’opération ou résolvez les conflits dans votre terminal, puis réessayez la synchronisation."+#: src/components/SyncStatusBadge.tsxmsgid "GitHub authentication failed. Try signing in again."msgstr "L'authentification GitHub a échoué. Essayez de vous reconnecter."diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.jsonindex f124087f8..b994b0a3f 100644--- a/packages/app/src/locales/hi/messages.json+++ b/packages/app/src/locales/hi/messages.json@@ -4080,6 +4080,9 @@"mHf8mp": ["स्कीमा फ़ाइल ", ["file"], " हटाएँ"],"mHo0kp": ["Open Knowledge टूल सक्षम करने के अनुरोध का समय समाप्त हो गया। यह थ्रेड उनके बिना चलता है।"],"mI1KPS": ["कोई lint प्लगइन सक्षम नहीं है, इसलिए केवल लिंक जाँचे गए।"],+ "mJTr6D": [+ "Git की किसी प्रक्रिया या अनसुलझे टकरावों पर ध्यान देने की ज़रूरत है, इसलिए Git सिंक रुका हुआ है। आपके बदलाव अब भी स्थानीय रूप से सहेजे जाते हैं। अपने टर्मिनल में प्रक्रिया पूरी करें या टकराव सुलझाएँ, फिर सिंक दोबारा आज़माएँ।"+ ],"mPoOmg": ["पहले यहाँ एक स्किल इंस्टॉल करें"],"mPy9lS": ["मेरी मौजूदा स्पेक को क्षेत्र के अनुसार समूहित एक जुड़ी हुई अनुक्रमणिका में व्यवस्थित करें, और जो मौजूदा कोड से तालमेल खो चुकी हों उन्हें चिह्नित करें।"diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.poindex b85dd776c..5f3df1642 100644--- a/packages/app/src/locales/hi/messages.po+++ b/packages/app/src/locales/hi/messages.po@@ -6545,6 +6545,10 @@ msgstr "Git को एक सहायक टूल (जैसे git-lfs) चmsgid "Git sync"msgstr "Git सिंक"+#: src/components/SyncStatusBadge.tsx+msgid "Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync."+msgstr "Git की किसी प्रक्रिया या अनसुलझे टकरावों पर ध्यान देने की ज़रूरत है, इसलिए Git सिंक रुका हुआ है। आपके बदलाव अब भी स्थानीय रूप से सहेजे जाते हैं। अपने टर्मिनल में प्रक्रिया पूरी करें या टकराव सुलझाएँ, फिर सिंक दोबारा आज़माएँ।"+#: src/components/SyncStatusBadge.tsxmsgid "GitHub authentication failed. Try signing in again."msgstr "GitHub प्रमाणीकरण विफल। फिर से साइन इन करके देखें।"diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.jsonindex cfe475b84..4cce664b0 100644--- a/packages/app/src/locales/id/messages.json+++ b/packages/app/src/locales/id/messages.json@@ -4244,6 +4244,9 @@"Permintaan untuk mengaktifkan alat Open Knowledge kedaluwarsa. Utas ini berjalan tanpa alat itu."],"mI1KPS": ["Tidak ada plugin lint yang aktif, jadi hanya tautan yang diperiksa."],+ "mJTr6D": [+ "Sinkronisasi Git dijeda karena ada operasi Git atau konflik yang belum terselesaikan yang perlu ditangani. Perubahan Anda tetap disimpan secara lokal. Selesaikan operasi atau konflik tersebut di terminal, lalu coba sinkronkan lagi."+ ],"mPoOmg": ["instal dulu sebuah skill di sini"],"mPy9lS": ["Tata spesifikasi saya yang sudah ada menjadi indeks tertaut yang dikelompokkan per bidang, dan tandai mana saja yang sudah tidak selaras dengan kode saat ini."diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.poindex bed6ad4bd..671caf258 100644--- a/packages/app/src/locales/id/messages.po+++ b/packages/app/src/locales/id/messages.po@@ -6545,6 +6545,10 @@ msgstr "Git membutuhkan alat bantu (seperti git-lfs) yang belum terpasang atau tmsgid "Git sync"msgstr "Sinkronisasi git"+#: src/components/SyncStatusBadge.tsx+msgid "Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync."+msgstr "Sinkronisasi Git dijeda karena ada operasi Git atau konflik yang belum terselesaikan yang perlu ditangani. Perubahan Anda tetap disimpan secara lokal. Selesaikan operasi atau konflik tersebut di terminal, lalu coba sinkronkan lagi."+#: src/components/SyncStatusBadge.tsxmsgid "GitHub authentication failed. Try signing in again."msgstr "Autentikasi GitHub gagal. Coba masuk lagi."diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.jsonindex 74c5b9cb5..0d36002fa 100644--- a/packages/app/src/locales/ko/messages.json+++ b/packages/app/src/locales/ko/messages.json@@ -4058,6 +4058,9 @@"Open Knowledge 도구 사용 설정 요청 시간이 초과되었습니다. 이 스레드는 도구 없이 실행됩니다."],"mI1KPS": ["lint 플러그인이 활성화되지 않아 링크만 확인합니다."],+ "mJTr6D": [+ "Git 작업이나 해결되지 않은 충돌을 처리해야 하므로 Git 동기화가 일시 중지되었습니다. 편집 내용은 계속 로컬에 저장됩니다. 터미널에서 작업을 완료하거나 충돌을 해결한 후 동기화를 다시 시도하세요."+ ],"mPoOmg": ["여기에 먼저 스킬을 설치하세요"],"mPy9lS": ["기존 사양을 영역별로 그룹화한 연결된 색인으로 정리하고, 현재 코드와 동기화되지 않은 항목을 표시합니다."diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.poindex dcd1ab764..2db622065 100644--- a/packages/app/src/locales/ko/messages.po+++ b/packages/app/src/locales/ko/messages.po@@ -6549,6 +6549,10 @@ msgstr "필요한 Git 도우미 도구(예: git-lfs)를 찾을 수 없습니다.msgid "Git sync"msgstr "Git 동기화"+#: src/components/SyncStatusBadge.tsx+msgid "Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync."+msgstr "Git 작업이나 해결되지 않은 충돌을 처리해야 하므로 Git 동기화가 일시 중지되었습니다. 편집 내용은 계속 로컬에 저장됩니다. 터미널에서 작업을 완료하거나 충돌을 해결한 후 동기화를 다시 시도하세요."+#: src/components/SyncStatusBadge.tsxmsgid "GitHub authentication failed. Try signing in again."msgstr "GitHub 인증에 실패했습니다. 다시 로그인하세요."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 740224ca8..a1521777d 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -4216,6 +4216,9 @@"Ţĥē ŕēǫũēśţ ţō ēńàƀĺē Ōƥēń Ķńōŵĺēďĝē ţōōĺś ţĩḿēď ōũţ. Ţĥĩś ţĥŕēàď ŕũńś ŵĩţĥōũţ ţĥēḿ."],"mI1KPS": ["Ńō ĺĩńţ ƥĺũĝĩńś àŕē ēńàƀĺēď, śō ōńĺŷ ĺĩńķś àŕē ćĥēćķēď."],+ "mJTr6D": [+ "Ĝĩţ śŷńćĩńĝ ĩś ƥàũśēď ƀēćàũśē à Ĝĩţ ōƥēŕàţĩōń ōŕ ũńŕēśōĺvēď ćōńƒĺĩćţś ńēēď àţţēńţĩōń. Ŷōũŕ ēďĩţś śţĩĺĺ śàvē ĺōćàĺĺŷ. Ƒĩńĩśĥ ţĥē ōƥēŕàţĩōń ōŕ ŕēśōĺvē ţĥē ćōńƒĺĩćţś ĩń ŷōũŕ ţēŕḿĩńàĺ, ţĥēń ŕēţŕŷ śŷńć."+ ],"mPoOmg": ["ĩńśţàĺĺ à śķĩĺĺ ĥēŕē ƒĩŕśţ"],"mPy9lS": ["Ōŕĝàńĩźē ḿŷ ēxĩśţĩńĝ śƥēćś ĩńţō à ĺĩńķēď ĩńďēx ĝŕōũƥēď ƀŷ àŕēà, àńď ƒĺàĝ àńŷ ţĥàţ ĥàvē ďŕĩƒţēď ōũţ ōƒ śŷńć ŵĩţĥ ţĥē ćũŕŕēńţ ćōďē."diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 127b269ff..b1fac71b1 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -6545,6 +6545,10 @@ msgstr ""msgid "Git sync"msgstr ""+#: src/components/SyncStatusBadge.tsx+msgid "Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync."+msgstr ""+#: src/components/SyncStatusBadge.tsxmsgid "GitHub authentication failed. Try signing in again."msgstr ""diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.jsonindex 441e61c0f..4b1991a67 100644--- a/packages/app/src/locales/pt-BR/messages.json+++ b/packages/app/src/locales/pt-BR/messages.json@@ -4797,6 +4797,9 @@"O pedido para ativar as ferramentas do Open Knowledge expirou. Esta conversa funciona sem elas."],"mI1KPS": ["Nenhum plugin de análise está ativado, então só os links são verificados."],+ "mJTr6D": [+ "A sincronização do Git está pausada porque uma operação do Git ou conflitos não resolvidos precisam de atenção. Suas alterações continuam sendo salvas localmente. Conclua a operação ou resolva os conflitos no terminal e tente sincronizar novamente."+ ],"mPoOmg": ["instale primeiro uma habilidade aqui"],"mPy9lS": ["Organize minhas especificações existentes em um índice interligado e agrupado por área, e sinalize as que se desencontraram do código atual."diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.poindex 07cdd825c..c6e1fa0ae 100644--- a/packages/app/src/locales/pt-BR/messages.po+++ b/packages/app/src/locales/pt-BR/messages.po@@ -6545,6 +6545,10 @@ msgstr "O git precisa de uma ferramenta auxiliar (como o git-lfs) que não estámsgid "Git sync"msgstr "Sincronização com git"+#: src/components/SyncStatusBadge.tsx+msgid "Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync."+msgstr "A sincronização do Git está pausada porque uma operação do Git ou conflitos não resolvidos precisam de atenção. Suas alterações continuam sendo salvas localmente. Conclua a operação ou resolva os conflitos no terminal e tente sincronizar novamente."+#: src/components/SyncStatusBadge.tsxmsgid "GitHub authentication failed. Try signing in again."msgstr "Falha na autenticação com o GitHub. Tente entrar de novo."diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.jsonindex 729b526c6..43ae324be 100644--- a/packages/app/src/locales/ur/messages.json+++ b/packages/app/src/locales/ur/messages.json@@ -4309,6 +4309,9 @@"Open Knowledge ٹولز فعال کرنے کی درخواست کا وقت ختم ہو گیا۔ یہ تھریڈ ان کے بغیر چلے گا۔"],"mI1KPS": ["کوئی لِنٹ پلگ اِن فعال نہیں، اس لیے صرف لنکس جانچے جاتے ہیں۔"],+ "mJTr6D": [+ "Git کی کسی کارروائی یا حل طلب تضادات پر توجہ درکار ہے، اس لیے Git کی مطابقت پذیری رکی ہوئی ہے۔ آپ کی تبدیلیاں اب بھی مقامی طور پر محفوظ ہوتی ہیں۔ اپنے ٹرمینل میں کارروائی مکمل کریں یا تضادات حل کریں، پھر مطابقت پذیری دوبارہ آزمائیں۔"+ ],"mPoOmg": ["پہلے یہاں ایک اسکل انسٹال کریں"],"mPy9lS": ["میری موجودہ اسپیکس کو شعبے کے لحاظ سے گروپ شدہ ایک مربوط اشاریے میں منظم کریں، اور ان میں سے کسی کو نشان زد کریں جو موجودہ کوڈ سے ہم آہنگ نہ رہی ہو۔"diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.poindex a18f7e2e5..5e0f22d30 100644--- a/packages/app/src/locales/ur/messages.po+++ b/packages/app/src/locales/ur/messages.po@@ -6549,6 +6549,10 @@ msgstr "Git کو ایک معاون ٹول (جیسے git-lfs) درکار ہے جmsgid "Git sync"msgstr "Git مطابقت پذیری"+#: src/components/SyncStatusBadge.tsx+msgid "Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync."+msgstr "Git کی کسی کارروائی یا حل طلب تضادات پر توجہ درکار ہے، اس لیے Git کی مطابقت پذیری رکی ہوئی ہے۔ آپ کی تبدیلیاں اب بھی مقامی طور پر محفوظ ہوتی ہیں۔ اپنے ٹرمینل میں کارروائی مکمل کریں یا تضادات حل کریں، پھر مطابقت پذیری دوبارہ آزمائیں۔"+#: src/components/SyncStatusBadge.tsxmsgid "GitHub authentication failed. Try signing in again."msgstr "GitHub کی توثیق ناکام رہی۔ دوبارہ سائن اِن کر کے دیکھیں۔"diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.jsonindex e4ea2ca7b..0a8b225c2 100644--- a/packages/app/src/locales/zh-Hans/messages.json+++ b/packages/app/src/locales/zh-Hans/messages.json@@ -3695,6 +3695,9 @@"mHf8mp": ["删除架构文件 ", ["file"]],"mHo0kp": ["启用 Open Knowledge 工具的请求已超时。此线程将在没有这些工具的情况下运行。"],"mI1KPS": ["没有启用任何检查插件,所以只检查了链接。"],+ "mJTr6D": [+ "Git 同步已暂停,因为有 Git 操作或未解决的冲突需要处理。你的编辑仍会保存在本地。请在终端中完成该操作或解决冲突,然后重试同步。"+ ],"mPoOmg": ["请先在此处安装一个技能"],"mPy9lS": ["把我现有的规格整理成一个按领域分组的链接索引,并标出与当前代码脱节的部分。"],"mPzgTS": ["打开 ", ["docName"]],diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.poindex 0ed8549b4..d97b5ac06 100644--- a/packages/app/src/locales/zh-Hans/messages.po+++ b/packages/app/src/locales/zh-Hans/messages.po@@ -6549,6 +6549,10 @@ msgstr "Git 需要一个辅助工具(例如 git-lfs),但它未安装或找msgid "Git sync"msgstr "Git 同步"+#: src/components/SyncStatusBadge.tsx+msgid "Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync."+msgstr "Git 同步已暂停,因为有 Git 操作或未解决的冲突需要处理。你的编辑仍会保存在本地。请在终端中完成该操作或解决冲突,然后重试同步。"+#: src/components/SyncStatusBadge.tsxmsgid "GitHub authentication failed. Try signing in again."msgstr "GitHub 身份验证失败。请尝试重新登录。"diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.jsonindex 05720b493..8c80630ef 100644--- a/packages/app/src/locales/zh-Hant/messages.json+++ b/packages/app/src/locales/zh-Hant/messages.json@@ -3713,6 +3713,9 @@"mHf8mp": ["刪除結構描述檔案 ", ["file"]],"mHo0kp": ["啟用 Open Knowledge 工具的請求已逾時。此執行緒將在沒有這些工具的情況下運作。"],"mI1KPS": ["沒有啟用任何檢查外掛,所以只檢查了連結。"],+ "mJTr6D": [+ "Git 同步已暫停,因為有 Git 操作或尚未解決的衝突需要處理。你的編輯仍會儲存在本機。請在終端機中完成該操作或解決衝突,然後重試同步。"+ ],"mPoOmg": ["請先在此處安裝一個技能"],"mPy9lS": ["把我現有的規格整理成一個依領域分組的連結索引,並標出和目前程式碼已經脫節的部分。"],"mPzgTS": ["開啟 ", ["docName"]],diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.poindex 2953cbd77..c34f93f57 100644--- a/packages/app/src/locales/zh-Hant/messages.po+++ b/packages/app/src/locales/zh-Hant/messages.po@@ -6549,6 +6549,10 @@ msgstr "Git 需要一個輔助工具(例如 git-lfs),但它沒有安裝或msgid "Git sync"msgstr "Git 同步"+#: src/components/SyncStatusBadge.tsx+msgid "Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync."+msgstr "Git 同步已暫停,因為有 Git 操作或尚未解決的衝突需要處理。你的編輯仍會儲存在本機。請在終端機中完成該操作或解決衝突,然後重試同步。"+#: src/components/SyncStatusBadge.tsxmsgid "GitHub authentication failed. Try signing in again."msgstr "GitHub 驗證失敗。請試著重新登入。"diff --git a/packages/server/src/sync-engine.test.ts b/packages/server/src/sync-engine.test.tsindex 084a0cb49..b81771bbf 100644--- a/packages/server/src/sync-engine.test.ts+++ b/packages/server/src/sync-engine.test.ts@@ -15,6 +15,7 @@ import { promisify } from 'node:util';import { LOCAL_DIR, type SyncMode, SyncStatusSchema } from '@inkeep/open-knowledge-core';import simpleGit from 'simple-git';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { ConflictStore } from './conflict-storage.ts';import { createContentFilter } from './content-filter.ts';import { classifyGitError } from './error-classification.ts';import type { GitHandle } from './git-handle.ts';@@ -1990,8 +1991,7 @@ describe('SyncEngine unborn-HEAD guard', () => {describe('SyncEngine one-shot push guards', () => {type PushInternals = {- pushInFlight: boolean;- pullInFlight: boolean;+ cycleInFlight: 'pull' | 'push' | null;conflictCount: number;state: string;hasRemote: boolean;@@ -2019,7 +2019,7 @@ describe('SyncEngine one-shot push guards', () => {test('refuses while a pull is in flight rather than racing it', async () => {const { engine, internals, cycles } = makeOneShotEngine();try {- internals.pullInFlight = true;+ internals.cycleInFlight = 'pull';await engine.pushOnce();expect(cycles).toEqual([]);} finally {@@ -2323,9 +2323,9 @@ describe('SyncEngine contention warn threshold', () => {});});-describe('SyncEngine runPushCycle pullInFlight guard', () => {+describe('SyncEngine runPushCycle ownership guard', () => {type GuardInternals = {- pullInFlight: boolean;+ cycleInFlight: 'pull' | 'push' | null;pushTimer: NodeJS.Timeout | null;state: SyncState;doPushCycle(retriesLeft?: number): Promise<void>;@@ -2343,7 +2343,7 @@ describe('SyncEngine runPushCycle pullInFlight guard', () => {});const internals = engine as unknown as GuardInternals;internals.state = 'idle';- internals.pullInFlight = true;+ internals.cycleInFlight = 'pull';const cycles: number[] = [];internals.doPushCycle = async (retriesLeft = 0) => {cycles.push(retriesLeft);@@ -4378,8 +4378,7 @@ interface InternalState {pullError?: string;pushErrorCode?: string;pullErrorCode?: string;- pullInFlight: boolean;- pushInFlight: boolean;+ cycleInFlight: 'pull' | 'push' | null;gitHandle: () => unknown;handleError: (classified: ReturnType<typeof classifyGitError>, op: 'push' | 'pull') => void;}@@ -4457,6 +4456,7 @@ describe('SyncEngine auth-error recovery', () => {});test('a manual trigger clears the identity-ambiguous not-found park', async () => {+ await simpleGit(projectDir).init(['--initial-branch=main']);const engine = makeEngine({ syncEnabled: true });const internal = engine as unknown as InternalState;internal.state = 'auth-error';@@ -4488,6 +4488,7 @@ describe('SyncEngine auth-error recovery', () => {});test('a pull-side not-found park clears on manual trigger too', async () => {+ await simpleGit(projectDir).init(['--initial-branch=main']);const engine = makeEngine({ syncEnabled: true });const internal = engine as unknown as InternalState;internal.state = 'auth-error';@@ -6957,3 +6958,407 @@ describe('SyncEngine split-leg backoff, end to end', () => {}});});++describe('SyncEngine exclusive merge ownership', () => {+ interface CycleInternals {+ state: SyncState;+ hasRemote: boolean;+ pullTimer: NodeJS.Timeout | null;+ pushTimer: NodeJS.Timeout | null;+ conflictCount: number;+ pausedReason?: string;+ pullError?: string;+ pushError?: string;+ gitHandle(): GitHandle;+ commitDirtyContentFilesToHead(handle: GitHandle): Promise<string | null>;+ doPushCycle(retriesLeft?: number): Promise<void>;+ doPullCycle(invocation: 'explicit' | 'sync'): Promise<'up-to-date'>;+ runPullCycle(): Promise<void>;+ refreshAuthTier(): Promise<void>;+ handleError(classified: ReturnType<typeof classifyGitError>, op: 'push' | 'pull'): void;+ }++ async function setup(mode: SyncMode = 'full', signal = vi.fn()) {+ const bareDir = join(tmpDir, 'exclusive.git');+ mkdirSync(bareDir);+ const bare = simpleGit(bareDir);+ await bare.init(true);+ await bare.raw(['symbolic-ref', 'HEAD', 'refs/heads/main']);+ const git = await initGitWithOrigin(bareDir);+ writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '.ok/\n');+ await git.push(['--set-upstream', 'origin', 'main']);+ const engine = new SyncEngine({+ projectDir,+ contentDir: projectDir,+ contentFilter: stubContentFilter,+ mode,+ cc1Broadcaster: { signal },+ });+ const internals = engine as unknown as CycleInternals;+ internals.hasRemote = true;+ internals.state = mode === 'off' ? 'disabled' : 'idle';+ return { engine, internals, git, bareDir };+ }++ async function diverge(bareDir: string) {+ const sisterDir = join(tmpDir, 'exclusive-sister');+ await simpleGit(tmpDir).clone(bareDir, sisterDir);+ const sister = simpleGit(sisterDir);+ await sister.raw(['config', 'user.name', 'Sister']);+ await sister.raw(['config', 'user.email', '[email protected]']);+ writeFileSync(join(sisterDir, 'README.md'), 'theirs\n');+ await sister.add('README.md');+ await sister.commit('remote edit');+ await sister.push('origin', 'main');+ writeFileSync(join(projectDir, 'README.md'), 'ours\n');+ }++ test.each(['mine', 'theirs'] as const)(+ 'a scheduled pull cannot enter a rejected push retry and %s resolves actual side bytes',+ async (strategy) => {+ const { engine, internals, git, bareDir } = await setup();+ await diverge(bareDir);+ const enteredRetry = Promise.withResolvers<void>();+ const releaseRetry = Promise.withResolvers<void>();+ const commitDirty = internals.commitDirtyContentFilesToHead.bind(engine);+ let first = true;+ internals.commitDirtyContentFilesToHead = async (handle) => {+ if (first) {+ first = false;+ enteredRetry.resolve();+ await releaseRetry.promise;+ }+ return commitDirty(handle);+ };+ const push = engine.pushOnce();+ try {+ await enteredRetry.promise;+ const headBeforeMerge = await git.revparse('HEAD');+ await internals.runPullCycle();+ releaseRetry.resolve();+ await push;++ expect(await git.revparse('HEAD')).toBe(headBeforeMerge);+ expect(await git.raw(['show', 'HEAD:README.md'])).toBe('ours\n');+ expect(await git.raw(['show', ':2:README.md'])).toBe('ours\n');+ expect(await git.raw(['show', ':3:README.md'])).toBe('theirs\n');+ expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(true);+ expect(engine.getStatus().state).toBe('conflict');++ await new ConflictStore(projectDir).resolveConflict('README.md', strategy);+ expect(readFileSync(join(projectDir, 'README.md'), 'utf8')).toBe(+ strategy === 'mine' ? 'ours\n' : 'theirs\n',+ );+ expect(await git.raw(['diff', '--name-only', '--diff-filter=U'])).toBe('');+ expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(false);+ } finally {+ releaseRetry.resolve();+ await push;+ await engine.destroy();+ }+ },+ );++ test('a scheduled pull defers, preserves its timer, and resumes after a push', async () => {+ const { engine, internals } = await setup();+ const entered = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ internals.doPushCycle = async () => {+ entered.resolve();+ await release.promise;+ };+ const pull = vi.fn(async () => 'up-to-date' as const);+ internals.doPullCycle = pull;+ const push = engine.pushOnce();+ try {+ await entered.promise;+ await internals.runPullCycle();+ expect(pull).not.toHaveBeenCalled();+ expect(internals.pullTimer).not.toBeNull();+ const deferredTimer = internals.pullTimer;+ await internals.runPullCycle();+ expect(internals.pullTimer).toBe(deferredTimer);+ release.resolve();+ await push;+ await internals.runPullCycle();+ expect(pull).toHaveBeenCalledTimes(1);+ } finally {+ release.resolve();+ await push;+ await engine.destroy();+ }+ });++ test('follow-mode auth refresh holds ownership before its await', async () => {+ const { engine, internals } = await setup('follow');+ const entered = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ internals.refreshAuthTier = async () => {+ entered.resolve();+ await release.promise;+ };+ const pull = vi.fn(async () => 'up-to-date' as const);+ const push = vi.fn(async () => {});+ internals.doPullCycle = pull;+ internals.doPushCycle = push;+ const running = internals.runPullCycle();+ try {+ await entered.promise;+ await engine.pushOnce();+ expect(await engine.pullOnce()).toBe('refused');+ expect(push).not.toHaveBeenCalled();+ expect(pull).not.toHaveBeenCalled();+ release.resolve();+ await running;+ expect(pull).toHaveBeenCalledTimes(1);+ await engine.pushOnce();+ expect(push).toHaveBeenCalledTimes(1);+ } finally {+ release.resolve();+ await running;+ await engine.destroy();+ }+ });++ test.each(['autosave', 'interim'] as const)(+ '%s refuses an unmerged real index even without MERGE_HEAD',+ async (writer) => {+ const { engine, internals, git, bareDir } = await setup();+ await diverge(bareDir);+ await git.add('README.md');+ await git.commit('local edit');+ await git.fetch('origin');+ await expect(git.merge(['origin/main'])).rejects.toThrow();+ rmSync(join(projectDir, '.git', 'MERGE_HEAD'));+ const head = await git.revparse('HEAD');+ const stages = await git.raw(['ls-files', '--unmerged']);+ const working = readFileSync(join(projectDir, 'README.md'), 'utf8');+ try {+ if (writer === 'autosave') {+ await internals.doPushCycle();+ } else {+ await expect(+ internals.commitDirtyContentFilesToHead(internals.gitHandle()),+ ).rejects.toThrow('Git operation');+ }+ expect(await git.revparse('HEAD')).toBe(head);+ expect(await git.raw(['ls-files', '--unmerged'])).toBe(stages);+ expect(readFileSync(join(projectDir, 'README.md'), 'utf8')).toBe(working);+ } finally {+ await engine.destroy();+ }+ },+ );++ test.each(['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'rebase-merge', 'rebase-apply'])(+ 'autosave and interim commits refuse %s with a resolved index',+ async (marker) => {+ const { engine, internals, git } = await setup();+ const head = await git.revparse('HEAD');+ const markerPath = join(projectDir, '.git', marker);+ if (marker.startsWith('rebase-')) mkdirSync(markerPath);+ else writeFileSync(markerPath, head);+ writeFileSync(join(projectDir, 'README.md'), 'resolved but not committed\n');+ const stages = await git.raw(['ls-files', '--stage']);+ try {+ await internals.doPushCycle();+ await expect(+ internals.commitDirtyContentFilesToHead(internals.gitHandle()),+ ).rejects.toThrow('Git operation');+ expect(await git.revparse('HEAD')).toBe(head);+ expect(await git.raw(['ls-files', '--stage'])).toBe(stages);+ expect(existsSync(markerPath)).toBe(true);+ expect(readFileSync(join(projectDir, 'README.md'), 'utf8')).toBe(+ 'resolved but not committed\n',+ );+ } finally {+ await engine.destroy();+ }+ },+ );++ test('an unreadable real index refuses autosave without modifying the repository', async () => {+ const { engine, internals, git } = await setup();+ const head = await git.revparse('HEAD');+ const stages = await git.raw(['ls-files', '--stage']);+ writeFileSync(join(projectDir, 'README.md'), 'unsaved content\n');+ const handle = internals.gitHandle();+ const raw = vi.spyOn(handle.git, 'raw').mockRejectedValue(new Error('index unreadable'));+ const gitHandle = vi.spyOn(internals, 'gitHandle').mockReturnValue(handle);+ try {+ await internals.doPushCycle();+ expect(engine.getStatus().pushError).toContain('index unreadable');+ expect(await git.revparse('HEAD')).toBe(head);+ expect(await git.raw(['ls-files', '--stage'])).toBe(stages);+ expect(readFileSync(join(projectDir, 'README.md'), 'utf8')).toBe('unsaved content\n');+ } finally {+ raw.mockRestore();+ gitHandle.mockRestore();+ await engine.destroy();+ }+ });++ test('autosave resumes after an operation ends and preserves authored marker-like text', async () => {+ const { engine, git } = await setup();+ const content = '<<<<<<< example\nours\n=======\ntheirs\n>>>>>>> documentation\n';+ const markerPath = join(projectDir, '.git', 'CHERRY_PICK_HEAD');+ writeFileSync(markerPath, await git.revparse('HEAD'));+ writeFileSync(join(projectDir, 'README.md'), content);+ try {+ await engine.pushOnce();+ expect(engine.getStatus().pausedReason).toBe('git-operation-in-progress');+ expect(engine.getStatus().pushError).toBeUndefined();+ rmSync(markerPath);+ await engine.pushOnce();+ expect(engine.getStatus().pushError).toBeUndefined();+ expect(await git.raw(['show', 'HEAD:README.md'])).toBe(content);+ expect(await git.revparse('HEAD')).toBe(await git.revparse('origin/main'));+ } finally {+ await engine.destroy();+ }+ });++ test('an idle refusal immediately broadcasts a retryable pause without replacing other errors', async () => {+ const signal = vi.fn();+ const { engine, internals, git } = await setup('full', signal);+ internals.pullError = 'unrelated pull failure';+ const markerPath = join(projectDir, '.git', 'CHERRY_PICK_HEAD');+ writeFileSync(markerPath, await git.revparse('HEAD'));+ try {+ await engine.pushOnce();+ expect(signal).toHaveBeenCalledWith('sync-status');+ expect(engine.getStatus()).toMatchObject({+ state: 'idle',+ pausedReason: 'git-operation-in-progress',+ pullError: 'unrelated pull failure',+ });+ expect(engine.getStatus().pushError).toBeUndefined();+ expect(engine.getStatus().pushErrorCode).toBeUndefined();+ expect(internals.pushTimer).not.toBeNull();+ } finally {+ await engine.destroy();+ }+ });++ test.each(['full', 'follow', 'off'] as const)(+ '%s exposes an operation refusal and a no-op push clears it after external recovery',+ async (mode) => {+ const { engine, git } = await setup(mode);+ const markerPath = join(projectDir, '.git', 'CHERRY_PICK_HEAD');+ const head = await git.revparse('HEAD');+ writeFileSync(markerPath, head);+ try {+ await engine.pushOnce();+ expect(engine.getStatus().pausedReason).toBe('git-operation-in-progress');+ expect(engine.getStatus().pushError).toBeUndefined();+ await engine.pushOnce();+ expect(engine.getStatus().pausedReason).toBe('git-operation-in-progress');+ rmSync(markerPath);+ await engine.pushOnce();+ expect(engine.getStatus().pausedReason).toBeUndefined();+ expect(engine.getStatus().pushError).toBeUndefined();+ expect(engine.getStatus().state).toBe(mode === 'off' ? 'disabled' : 'idle');+ expect(await git.revparse('HEAD')).toBe(head);+ } finally {+ await engine.destroy();+ }+ },+ );++ test.each(['full', 'follow', 'off'] as const)(+ '%s keeps an up-to-date pull paused until Git is ready, then clears the pause',+ async (mode) => {+ const { engine, internals, git } = await setup(mode);+ const markerPath = join(projectDir, '.git', 'CHERRY_PICK_HEAD');+ writeFileSync(markerPath, await git.revparse('HEAD'));+ internals.pausedReason = 'git-operation-in-progress';+ internals.pushError = 'unrelated push failure';+ try {+ expect(await engine.pullOnce()).toBe('refused');+ expect(engine.getStatus().pausedReason).toBe('git-operation-in-progress');+ expect(engine.getStatus().pullError).toBeUndefined();+ rmSync(markerPath);+ expect(await engine.pullOnce()).toBe('up-to-date');+ expect(engine.getStatus().pausedReason).toBeUndefined();+ expect(engine.getStatus().pushError).toBe('unrelated push failure');+ expect(engine.getStatus().state).toBe(mode === 'off' ? 'disabled' : 'idle');+ } finally {+ await engine.destroy();+ }+ },+ );++ test.each(['full', 'off'] as const)(+ '%s preserves a newly discovered pull refusal through one-shot settlement',+ async (mode) => {+ const { engine, git, bareDir } = await setup(mode);+ await diverge(bareDir);+ const markerPath = join(projectDir, '.git', 'CHERRY_PICK_HEAD');+ const head = await git.revparse('HEAD');+ writeFileSync(markerPath, head);+ try {+ expect(await engine.pullOnce('sync')).toBe('refused');+ expect(engine.getStatus().pausedReason).toBe('git-operation-in-progress');+ expect(engine.getStatus().pullError).toBeUndefined();+ expect(engine.getStatus().pullErrorCode).toBeUndefined();+ expect(engine.getStatus().state).toBe(mode === 'off' ? 'disabled' : 'idle');+ expect(await git.revparse('HEAD')).toBe(head);+ expect(existsSync(markerPath)).toBe(true);+ expect(readFileSync(join(projectDir, 'README.md'), 'utf8')).toBe('ours\n');+ } finally {+ await engine.destroy();+ }+ },+ );++ test('a successful safety probe preserves an unrelated pause reason', async () => {+ const { engine, internals } = await setup();+ internals.pausedReason = 'diverged-local-commits';+ try {+ await engine.pushOnce();+ expect(engine.getStatus().pausedReason).toBe('diverged-local-commits');+ } finally {+ await engine.destroy();+ }+ });++ test('an operation refusal preserves tracked-conflict guidance', async () => {+ const { engine, internals, git } = await setup();+ internals.state = 'conflict';+ internals.conflictCount = 1;+ internals.pullError = 'existing conflict guidance';+ internals.pausedReason = 'non-content-merge-failure';+ writeFileSync(join(projectDir, '.git', 'CHERRY_PICK_HEAD'), await git.revparse('HEAD'));+ try {+ await internals.doPushCycle();+ expect(engine.getStatus()).toMatchObject({+ state: 'conflict',+ conflictCount: 1,+ pausedReason: 'non-content-merge-failure',+ pullError: 'existing conflict guidance',+ });+ expect(engine.getStatus().pushError).toBeUndefined();+ } finally {+ await engine.destroy();+ }+ });++ test('a dirty-tree error preserves the conflict state and does not schedule autosave', async () => {+ const { engine, internals } = await setup();+ internals.state = 'conflict';+ internals.conflictCount = 1;+ try {+ internals.handleError(+ classifyGitError(+ new Error('Your local changes to the following files would be overwritten by merge'),+ ),+ 'pull',+ );+ expect(engine.getStatus().state).toBe('conflict');+ expect(internals.conflictCount).toBe(1);+ expect(internals.pushTimer).toBeNull();+ } finally {+ await engine.destroy();+ }+ });+});diff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.tsindex 26d2ddb9e..8df24dc0c 100644--- a/packages/server/src/sync-engine.ts+++ b/packages/server/src/sync-engine.ts@@ -86,6 +86,13 @@ const SHA_HEX_40 = /^[0-9a-f]{40}$/i;const execFileAsync = promisify(execFile);+class GitOperationInProgressError extends Error {+ constructor() {+ super('Sync paused while a Git operation is in progress or the index has unresolved conflicts');+ this.name = 'GitOperationInProgressError';+ }+}+class ShareableOkEnumerationError extends Error {constructor(relDir: string, cause: unknown) {super(`Shareable .ok subtree "${relDir}" could not be fully enumerated; sync staging aborted`, {@@ -230,9 +237,10 @@ type PullInvocation = 'explicit' | 'sync';const BLOCKING_PATHS_CAP = 50;-const FORWARD_ONLY_PAUSES: ReadonlySet<string | undefined> = new Set([+const ONE_SHOT_PAUSES: ReadonlySet<string | undefined> = new Set(['diverged-local-commits','external-changes-pending',+ 'git-operation-in-progress',]);const COMMIT_BLOCKING_MESSAGE = 'Commit local changes before syncing';@@ -393,8 +401,7 @@ export class SyncEngine {private blockingPaths: string[] = [];private currentBranch = 'main';- private pullInFlight = false;- private pushInFlight = false;+ private cycleInFlight: 'pull' | 'push' | null = null;private hasRemote = false;@@ -737,10 +744,10 @@ export class SyncEngine {private async drainInFlightCycles(): Promise<void> {const DRAIN_TIMEOUT_MS = 30_000;const drainStartMs = Date.now();- while (this.pullInFlight || this.pushInFlight) {+ while (this.cycleInFlight !== null) {if (Date.now() - drainStartMs > DRAIN_TIMEOUT_MS) {log.warn(- { pullInFlight: this.pullInFlight, pushInFlight: this.pushInFlight },+ { cycleInFlight: this.cycleInFlight },'[sync] drain: timed out waiting for in-flight cycle',);break;@@ -915,9 +922,9 @@ export class SyncEngine {}private async runOneShotPush(): Promise<void> {- if (this.pushInFlight || this.pullInFlight) {+ if (this.cycleInFlight !== null) {log.info(- { pushInFlight: this.pushInFlight, pullInFlight: this.pullInFlight },+ { cycleInFlight: this.cycleInFlight },'[sync] one-shot push refused — a cycle is already in flight',);return;@@ -943,11 +950,11 @@ export class SyncEngine {}const restingState = this.state;- this.pushInFlight = true;+ this.cycleInFlight = 'push';try {await this.doPushCycle(1);} finally {- this.pushInFlight = false;+ this.cycleInFlight = null;if (this.pushCycleLanded) this.markRun();const settled = this.currentState();if (settled !== 'conflict' && settled !== 'auth-error') {@@ -959,7 +966,7 @@ export class SyncEngine {async fetchOnly(): Promise<boolean> {if (!this.hasRemote || isUnbornHead(this.projectDir)) return false;- if (this.pullInFlight || this.pushInFlight || this.fetchOnlyInFlight) return false;+ if (this.cycleInFlight !== null || this.fetchOnlyInFlight) return false;this.fetchOnlyInFlight = true;const handle = this.gitHandle();@@ -996,9 +1003,9 @@ export class SyncEngine {}private async runOneShotPull(invocation: PullInvocation): Promise<PullOutcome> {- if (this.pullInFlight || this.pushInFlight) {+ if (this.cycleInFlight !== null) {log.info(- { pullInFlight: this.pullInFlight, pushInFlight: this.pushInFlight },+ { cycleInFlight: this.cycleInFlight },'[sync] one-shot pull refused — a cycle is already in flight',);return this.recordPullOutcome('refused');@@ -1021,14 +1028,14 @@ export class SyncEngine {const restingMode = this.mode;const restingState = this.state;const restingPausedReason = this.pausedReason;- this.pullInFlight = true;+ this.cycleInFlight = 'pull';try {return this.recordPullOutcome(await this.doPullCycle(invocation));} finally {- this.pullInFlight = false;+ this.cycleInFlight = null;if (restingMode === 'off') {- if (!FORWARD_ONLY_PAUSES.has(this.pausedReason)) {- if (!FORWARD_ONLY_PAUSES.has(restingPausedReason)) {+ if (!ONE_SHOT_PAUSES.has(this.pausedReason)) {+ if (!ONE_SHOT_PAUSES.has(restingPausedReason)) {this.pausedReason = restingPausedReason;}}@@ -1479,7 +1486,10 @@ export class SyncEngine {}private async runPullCycle(): Promise<void> {- if (this.pullInFlight) return;+ if (this.cycleInFlight !== null) {+ if (this.cycleInFlight === 'push' && this.pullTimer === null) this.schedulePull();+ return;+ }if (this.state === 'dormant' || this.state === 'disabled' || this.state === 'auth-error')return;if (this.state === 'conflict') {@@ -1491,18 +1501,29 @@ export class SyncEngine {return;}- if (this.mode === 'follow') await this.refreshAuthTier();-- this.pullInFlight = true;+ this.cycleInFlight = 'pull';try {+ if (this.mode === 'follow') await this.refreshAuthTier();this.recordPullOutcome(await this.doPullCycle(this.mode === 'full' ? 'sync' : 'explicit'));} finally {- this.pullInFlight = false;+ this.cycleInFlight = null;this.schedulePull();}}private async doPullCycle(invocation: PullInvocation): Promise<PullOutcome> {+ if (this.pausedReason === 'git-operation-in-progress') {+ try {+ await this.assertNoGitOperationInProgress();+ } catch (e) {+ if (e instanceof GitOperationInProgressError) {+ this.handleGitOperationRefusal(e, 'pull');+ return 'refused';+ }+ this.handleError(classifyGitError(e instanceof Error ? e : new Error(String(e))), 'pull');+ return 'error';+ }+ }const handle = this.gitHandle();let branch: string;@@ -1578,6 +1599,10 @@ export class SyncEngine {this.scheduleSaveState();return 'succeeded';} catch (e) {+ if (e instanceof GitOperationInProgressError) {+ this.handleGitOperationRefusal(e, 'pull');+ return 'refused';+ }const classified = classifyGitError(e instanceof Error ? e : new Error(String(e)));if (classified.class === 'semantic' && classified.subclass === 'merge-conflict') {await this.handleMergeConflict();@@ -2024,7 +2049,6 @@ export class SyncEngine {}private async runPushCycle(): Promise<void> {- if (this.pushInFlight) return;if (this.mode !== 'full') return;if (this.state === 'dormant' || this.state === 'disabled') return;if (this.state === 'conflict' || this.state === 'auth-error') return;@@ -2036,17 +2060,16 @@ export class SyncEngine {this.schedulePush();return;}- if (this.pullInFlight) {- log.info({ pullInFlight: true }, '[sync] push cycle deferred — a pull cycle holds the tree');- if (this.pushTimer === null) this.schedulePush();+ if (this.cycleInFlight !== null) {+ if (this.cycleInFlight === 'pull' && this.pushTimer === null) this.schedulePush();return;}- this.pushInFlight = true;+ this.cycleInFlight = 'push';try {await this.doPushCycle(1);} finally {- this.pushInFlight = false;+ this.cycleInFlight = null;if (this.pushCycleLanded) this.markRun();this.schedulePush();}@@ -2057,11 +2080,11 @@ export class SyncEngine {const tmpIndexPath = join(tmpdir(), `ok-sync-idx-${process.pid}-${Date.now()}.idx`);let commitSha: string | null = null;- this.transitionTo('pushing');-try {const contentFiles = this.gatherContentFilesSync();await withParentLock(async () => {+ await this.assertNoGitOperationInProgress();+ this.transitionTo('pushing');const handle = this.gitHandle(tmpIndexPath);if (isUnbornHead(this.projectDir)) {@@ -2238,6 +2261,10 @@ export class SyncEngine {}}} catch (e) {+ if (e instanceof GitOperationInProgressError) {+ this.handleGitOperationRefusal(e, 'push');+ return;+ }const err = e instanceof Error ? e : new Error(String(e));if (err instanceof ShareableOkEnumerationError) {log.warn({ err }, '[sync] push cycle: staging error detail');@@ -2275,6 +2302,10 @@ export class SyncEngine {if (!overlaysRestored) throw new Error('failed to restore reconciled MCP overlays');await this.persistReconciledMcpEntries(mergePrep.reconciled);} catch (mergeErr) {+ if (mergeErr instanceof GitOperationInProgressError) {+ this.handleGitOperationRefusal(mergeErr, 'push');+ return;+ }const mc = classifyGitError(mergeErr instanceof Error ? mergeErr : new Error(String(mergeErr)),);@@ -2314,6 +2345,7 @@ export class SyncEngine {}private async commitDirtyContentFilesToHead(handle: GitHandle): Promise<string | null> {+ await this.assertNoGitOperationInProgress();const status = await handle.git.status();if (status.files.length === 0) return null;@@ -2573,6 +2605,39 @@ export class SyncEngine {}}+ private async assertNoGitOperationInProgress(): Promise<void> {+ if (this.hasGitOperationInProgress()) throw new GitOperationInProgressError();+ const unmerged = await listNames(this.gitHandle().git, [+ 'diff',+ '--name-only',+ '--diff-filter=U',+ ]);+ if (unmerged.length > 0 || this.hasGitOperationInProgress()) {+ throw new GitOperationInProgressError();+ }+ if (this.pausedReason === 'git-operation-in-progress') {+ this.pausedReason = undefined;+ this.cc1Broadcaster?.signal('sync-status');+ this.scheduleSaveState();+ }+ }++ private handleGitOperationRefusal(error: GitOperationInProgressError, op: 'push' | 'pull'): void {+ if (this.state === 'conflict' || this.conflictCount > 0) {+ this.transitionTo('conflict');+ } else {+ this.pausedReason = 'git-operation-in-progress';+ if (op === 'push') this.clearPushError();+ else this.clearPullError();+ if (this.state === 'pushing' || this.state === 'pulling' || this.state === 'fetching') {+ this.transitionTo('idle');+ }+ }+ log.warn({ err: error, op }, '[sync] cycle refused because a Git operation holds the tree');+ this.cc1Broadcaster?.signal('sync-status');+ this.scheduleSaveState();+ }+private hasGitOperationInProgress(): boolean {const gitDir = resolveGitDir(this.projectDir);if (!gitDir) return true;@@ -3101,6 +3166,10 @@ export class SyncEngine {this.pausedReason = 'protected-branch';void this.onAutoDisable?.('protected-branch');} else if (classified.class === 'local' && classified.subclass === 'dirty-tree') {+ if (this.state === 'conflict' || this.conflictCount > 0) {+ this.transitionTo('conflict');+ return;+ }this.bumpFailureCount(op);this.transitionTo('idle');this.pausedReason = 'dirty-tree';