Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): give new projects an initial commit (PRD-7310) (#3335)

Andrew Mikofalvy4cef9c5a587d
diff --git a/.changeset/new-project-initial-commit.md b/.changeset/new-project-initial-commit.md
new file mode 100644
index 000000000..c723031a8
--- /dev/null
+++ b/.changeset/new-project-initial-commit.md
@@ -0,0 +1,10 @@
+---
+'@inkeep/open-knowledge-server': patch
+'@inkeep/open-knowledge-desktop': patch
+'@inkeep/open-knowledge-core': patch
+'@inkeep/open-knowledge-app': patch
+---
+
+A new project now starts with a commit, so its default branch actually exists. Setting up a project ran `git init` but never committed, which left the repository with no commits at all: `main` pointed at nothing, and anything that had to resolve it failed. The most visible casualty was New worktree, which died with `Couldn't create the worktree. Try a different name.` no matter what name you typed, because the real error was `fatal: invalid reference: main` and no branch name could have fixed it. Projects that OK sets up now get an empty `Initial commit`, so `main` resolves. Your content is untouched: the commit is deliberately empty, so nothing of yours is staged or committed on your behalf, and a repository you created yourself is never committed into.
+
+Worktree failures now say what actually went wrong. A repository with no commits gets its own message instead of the advice to pick a different name, and git's own error text appears under the dialog, so an unrelated failure like a lock file or a permissions problem is legible instead of reading as a bad branch name.
diff --git a/packages/app/src/components/NewWorktreeDialog.dom.test.tsx b/packages/app/src/components/NewWorktreeDialog.dom.test.tsx
index 0385fc6d5..9ca437140 100644
--- a/packages/app/src/components/NewWorktreeDialog.dom.test.tsx
+++ b/packages/app/src/components/NewWorktreeDialog.dom.test.tsx
@@ -141,6 +141,70 @@ describe('NewWorktreeDialog', () => {
expect(bridge.project.open).not.toHaveBeenCalled();
});
+ test('explains an empty repo instead of blaming the branch name', async () => {
+ const bridge = createBridge({
+ ok: false,
+ reason: 'empty-repo',
+ message: 'fatal: invalid reference: main',
+ });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ />,
+ );
+ fireEvent.change(await screen.findByTestId('new-worktree-branch'), {
+ target: { value: 'dev' },
+ });
+ fireEvent.click(screen.getByTestId('new-worktree-create'));
+ const err = await screen.findByTestId('new-worktree-error');
+ expect(err.textContent).toContain('no commits yet');
+ // The condition no branch name can fix must stop suggesting a new name.
+ expect(err.textContent).not.toContain('different name');
+ });
+
+ test('surfaces the underlying git error alongside the copy', async () => {
+ const bridge = createBridge({
+ ok: false,
+ reason: 'error',
+ message: 'fatal: could not lock ref: Unable to create lock file',
+ });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ />,
+ );
+ fireEvent.change(await screen.findByTestId('new-worktree-branch'), {
+ target: { value: 'dev' },
+ });
+ fireEvent.click(screen.getByTestId('new-worktree-create'));
+ const detail = await screen.findByTestId('new-worktree-error-detail');
+ expect(detail.textContent).toContain('could not lock ref');
+ });
+
+ test('omits the detail line when the failure carries no git message', async () => {
+ const bridge = createBridge({ ok: false, reason: 'branch-exists' });
+ render(
+ <NewWorktreeDialog
+ open={true}
+ onOpenChange={noop}
+ bridge={bridge as never}
+ currentBranch="main"
+ />,
+ );
+ fireEvent.change(await screen.findByTestId('new-worktree-branch'), {
+ target: { value: 'dev' },
+ });
+ fireEvent.click(screen.getByTestId('new-worktree-create'));
+ await screen.findByTestId('new-worktree-error');
+ expect(screen.queryByTestId('new-worktree-error-detail')).toBeNull();
+ });
+
test('checks out an existing branch (createBranch false, no base) and refreshes the cache', async () => {
const bridge = createBridge({
ok: true,
diff --git a/packages/app/src/components/NewWorktreeDialog.tsx b/packages/app/src/components/NewWorktreeDialog.tsx
index 904e0388a..c0fb64bf8 100644
--- a/packages/app/src/components/NewWorktreeDialog.tsx
+++ b/packages/app/src/components/NewWorktreeDialog.tsx
@@ -135,6 +135,8 @@ function createErrorCopy(reason: string): MessageDescriptor {
return msg`Enter a valid branch name (no spaces, no leading dot, no "..").`;
case 'no-git':
return msg`This project isn't a git repository, so worktrees aren't available.`;
+ case 'empty-repo':
+ return msg`This project has no commits yet, so there's no branch to base a worktree on. Make a first commit, then try again.`;
case 'helper-not-found':
return msg`Git needs a helper tool (such as git-lfs) that isn't installed or couldn't be found. Install it, then try again.`;
default:
@@ -142,6 +144,19 @@ function createErrorCopy(reason: string): MessageDescriptor {
}
}
+/**
+ * An inline create failure: translated copy plus git's own words.
+ *
+ * `detail` carries the raw stderr the main process captured. It is diagnostic
+ * data, not copy — deliberately not translated, and shown verbatim so a failure
+ * the reason taxonomy doesn't model (a lock file, a permissions error) is
+ * legible instead of being flattened into the generic retry message.
+ */
+interface CreateFailure {
+ readonly copy: MessageDescriptor;
+ readonly detail?: string;
+}
+
export function NewWorktreeDialog({
open,
onOpenChange,
@@ -167,7 +182,7 @@ export function NewWorktreeDialog({
const [baseOpen, setBaseOpen] = useState(false);
const [baseQuery, setBaseQuery] = useState('');
const [busy, setBusy] = useState(false);
- const [error, setError] = useState<MessageDescriptor | null>(null);
+ const [error, setError] = useState<CreateFailure | null>(null);
const inputRef = useRef<HTMLInputElement | null>(null);
const baseSearchRef = useRef<HTMLInputElement | null>(null);
@@ -282,7 +297,7 @@ export function NewWorktreeDialog({
};
const result = await bridge.worktree.create(request);
if (!result.ok) {
- setError(createErrorCopy(result.reason));
+ setError({ copy: createErrorCopy(result.reason), detail: result.message });
setBusy(false);
return;
}
@@ -632,14 +647,19 @@ export function NewWorktreeDialog({
</div>
) : null}
{error !== null ? (
- <p
- id={errorId}
- role="alert"
- className="text-1sm text-destructive"
- data-testid="new-worktree-error"
- >
- {t(error)}
- </p>
+ <div id={errorId} role="alert">
+ <p className="text-1sm text-destructive" data-testid="new-worktree-error">
+ {t(error.copy)}
+ </p>
+ {error.detail !== undefined && error.detail.length > 0 ? (
+ <p
+ className="mt-1 break-words font-mono text-xs text-muted-foreground"
+ data-testid="new-worktree-error-detail"
+ >
+ {error.detail}
+ </p>
+ ) : null}
+ </div>
) : null}
</form>
</DialogBody>
diff --git a/packages/app/src/components/ShareBranchSwitchDialog.tsx b/packages/app/src/components/ShareBranchSwitchDialog.tsx
index 3965c5737..e0fec881f 100644
--- a/packages/app/src/components/ShareBranchSwitchDialog.tsx
+++ b/packages/app/src/components/ShareBranchSwitchDialog.tsx
@@ -486,6 +486,13 @@ export function ShareBranchSwitchDialog({
case 'no-git':
toast.error(t`This project isn't a git repository, so worktrees aren't available.`);
return;
+ case 'empty-repo':
+ // Same wording as the New-worktree dialog, so the two surfaces share one
+ // catalog entry rather than drifting apart per-locale.
+ toast.error(
+ t`This project has no commits yet, so there's no branch to base a worktree on. Make a first commit, then try again.`,
+ );
+ return;
case 'invalid-branch':
toast.error(t`${shareBranch} isn't a valid branch name.`);
return;
diff --git a/packages/app/src/lib/share/branch-switch-flow.test.ts b/packages/app/src/lib/share/branch-switch-flow.test.ts
index 2ddcc5939..99a1b6c94 100644
--- a/packages/app/src/lib/share/branch-switch-flow.test.ts
+++ b/packages/app/src/lib/share/branch-switch-flow.test.ts
@@ -712,6 +712,7 @@ describe('applyWorktreeCheckoutOutcome (worktree leg)', () => {
'already-checked-out',
'path-exists',
'no-git',
+ 'empty-repo',
'error',
] as const;
for (const reason of reasons) {
diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.json
index 33b2ca7a2..af13bc0a0 100644
--- a/packages/app/src/locales/ar/messages.json
+++ b/packages/app/src/locales/ar/messages.json
@@ -424,6 +424,9 @@
"5GKMSz": ["زد أو قلّل إزاحة عنصر القائمة الحالي."],
"5GRxoA": ["ابحث في ملفات مساحة العمل الحالية ومجلداتها وأوامرها."],
"5HJpFY": ["ينتظر في الطابور خلف الدور الجاري"],
+ "5IgYAM": [
+ "لا يحتوي هذا المشروع على أي إيداعات بعد، لذا لا يوجد فرع لبناء worktree عليه. أنشئ أول إيداع ثم أعد المحاولة."
+ ],
"5LXwX8": [
"يزيل هذا ",
["path"],
diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.po
index b85a85d30..b51a2e068 100644
--- a/packages/app/src/locales/ar/messages.po
+++ b/packages/app/src/locales/ar/messages.po
@@ -12357,6 +12357,11 @@ msgstr "يزيل هذا {path} نهائيًا. ستفشل الوكلاء الت
msgid "This project"
msgstr "هذا المشروع"
+#: src/components/NewWorktreeDialog.tsx
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "This project has no commits yet, so there's no branch to base a worktree on. Make a first commit, then try again."
+msgstr "لا يحتوي هذا المشروع على أي إيداعات بعد، لذا لا يوجد فرع لبناء worktree عليه. أنشئ أول إيداع ثم أعد المحاولة."
+
#: src/components/settings/SharingSection.tsx
msgid "This project has no git repository — sharing mode does not apply. Initialize a repo to enable the toggle."
msgstr "هذا المشروع بلا مستودع git — لا ينطبق وضع المشاركة. هيّئ مستودعًا لتفعيل المبدّل."
diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.json
index 4fab2776e..7ae606194 100644
--- a/packages/app/src/locales/bn/messages.json
+++ b/packages/app/src/locales/bn/messages.json
@@ -361,6 +361,9 @@
"5GKMSz": ["বর্তমান তালিকা আইটেমটি ভেতরে বা বাইরে নিন।"],
"5GRxoA": ["বর্তমান ওয়ার্কস্পেসের ফাইল, ফোল্ডার ও কমান্ড খুঁজুন।"],
"5HJpFY": ["চলমান টার্নের পিছনে সারিতে থাকে"],
+ "5IgYAM": [
+ "এই প্রকল্পে এখনও কোনো কমিট নেই, তাই worktree-এর ভিত্তি হিসেবে কোনো ব্রাঞ্চ নেই। প্রথমে একটি কমিট করুন, তারপর আবার চেষ্টা করুন।"
+ ],
"5LXwX8": [
"এটি ",
["path"],
diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.po
index dd33076cc..45be87caa 100644
--- a/packages/app/src/locales/bn/messages.po
+++ b/packages/app/src/locales/bn/messages.po
@@ -12353,6 +12353,11 @@ msgstr "এটি {path}-কে স্থায়ীভাবে সরিয
msgid "This project"
msgstr "এই প্রকল্প"
+#: src/components/NewWorktreeDialog.tsx
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "This project has no commits yet, so there's no branch to base a worktree on. Make a first commit, then try again."
+msgstr "এই প্রকল্পে এখনও কোনো কমিট নেই, তাই worktree-এর ভিত্তি হিসেবে কোনো ব্রাঞ্চ নেই। প্রথমে একটি কমিট করুন, তারপর আবার চেষ্টা করুন।"
+
#: src/components/settings/SharingSection.tsx
msgid "This project has no git repository — sharing mode does not apply. Initialize a repo to enable the toggle."
msgstr "এই প্রকল্পে কোনো git রিপোজিটরি নেই — ভাগাভাগির মোড প্রযোজ্য নয়। টগলটি চালু করতে একটি রিপোজিটরি চালু করুন।"
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 1e4ccf61b..59b1029c7 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -370,6 +370,9 @@
"5GKMSz": ["Indent or outdent the current list item."],
"5GRxoA": ["Search files, folders, and commands for the current workspace."],
"5HJpFY": ["Queues behind the running turn"],
+ "5IgYAM": [
+ "This project has no commits yet, so there's no branch to base a worktree on. Make a first commit, then try again."
+ ],
"5LXwX8": [
"This permanently removes ",
["path"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 283f3e9b7..3c99ed7bc 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -12357,6 +12357,11 @@ msgstr "This permanently removes {path}. Agents that reference this template by
msgid "This project"
msgstr "This project"
+#: src/components/NewWorktreeDialog.tsx
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "This project has no commits yet, so there's no branch to base a worktree on. Make a first commit, then try again."
+msgstr "This project has no commits yet, so there's no branch to base a worktree on. Make a first commit, then try again."
+
#: src/components/settings/SharingSection.tsx
msgid "This project has no git repository — sharing mode does not apply. Initialize a repo to enable the toggle."
msgstr "This project has no git repository — sharing mode does not apply. Initialize a repo to enable the toggle."
diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.json
index bce567989..7ffb4ae71 100644
--- a/packages/app/src/locales/es/messages.json
+++ b/packages/app/src/locales/es/messages.json
@@ -437,6 +437,9 @@
"5GKMSz": ["Aumenta o reduce la sangría del elemento de lista actual."],
"5GRxoA": ["Busca archivos, carpetas y comandos del espacio de trabajo actual."],
"5HJpFY": ["Se pone en cola detrás del turno en curso"],
+ "5IgYAM": [
+ "Este proyecto aún no tiene commits, así que no hay ninguna rama en la que basar un worktree. Haz un primer commit y vuelve a intentarlo."
+ ],
"5LXwX8": [
"Esto elimina definitivamente ",
["path"],
diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.po
index e67013398..47f4dc400 100644
--- a/packages/app/src/locales/es/messages.po
+++ b/packages/app/src/locales/es/messages.po
@@ -12357,6 +12357,11 @@ msgstr "Esto elimina definitivamente {path}. Los agentes que hagan referencia a
msgid "This project"
msgstr "Este proyecto"
+#: src/components/NewWorktreeDialog.tsx
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "This project has no commits yet, so there's no branch to base a worktree on. Make a first commit, then try again."
+msgstr "Este proyecto aún no tiene commits, así que no hay ninguna rama en la que basar un worktree. Haz un primer commit y vuelve a intentarlo."
+
#: src/components/settings/SharingSection.tsx
msgid "This project has no git repository — sharing mode does not apply. Initialize a repo to enable the toggle."
msgstr "Este proyecto no tiene repositorio de git, así que el modo de compartición no aplica. Inicializa un repositorio para habilitar el interruptor."
diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.json
index 4d0dc44ed..7e4bdf63f 100644
--- a/packages/app/src/locales/fr/messages.json
+++ b/packages/app/src/locales/fr/messages.json
@@ -457,6 +457,9 @@
"Recherchez des fichiers, des dossiers et des commandes dans l'espace de travail actuel."
],
"5HJpFY": ["Se met en file derrière le tour en cours"],
+ "5IgYAM": [
+ "Ce projet n'a encore aucun commit, il n'y a donc aucune branche sur laquelle baser un worktree. Faites un premier commit, puis réessayez."
+ ],
"5LXwX8": [
"Ceci retire définitivement ",
["path"],
diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.po
index 6e7425d3c..99c3d8843 100644
--- a/packages/app/src/locales/fr/messages.po
+++ b/packages/app/src/locales/fr/messages.po
@@ -12357,6 +12357,11 @@ msgstr "Ceci retire définitivement {path}. Les agents qui référencent ce mod
msgid "This project"
msgstr "Ce projet"
+#: src/components/NewWorktreeDialog.tsx
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "This project has no commits yet, so there's no branch to base a worktree on. Make a first commit, then try again."
+msgstr "Ce projet n'a encore aucun commit, il n'y a donc aucune branche sur laquelle baser un worktree. Faites un premier commit, puis réessayez."
+
#: src/components/settings/SharingSection.tsx
msgid "This project has no git repository — sharing mode does not apply. Initialize a repo to enable the toggle."
msgstr "Ce projet n'a pas de dépôt git — le mode de partage ne s'applique pas. Initialisez un dépôt pour activer le commutateur."
diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.json
index 82a0a921a..1cde0801b 100644
--- a/packages/app/src/locales/hi/messages.json
+++ b/packages/app/src/locales/hi/messages.json
@@ -359,6 +359,9 @@
"5GKMSz": ["मौजूदा सूची आइटम को अंदर या बाहर करें।"],
"5GRxoA": ["मौजूदा कार्यक्षेत्र के लिए फ़ाइलें, फ़ोल्डर और कमांड खोजें।"],
"5HJpFY": ["चल रही बारी के पीछे क़तार में लगता है"],
+ "5IgYAM": [
+ "इस प्रोजेक्ट में अभी तक कोई कमिट नहीं है, इसलिए worktree को आधार देने के लिए कोई ब्रांच नहीं है। पहला कमिट करें, फिर दोबारा कोशिश करें।"
+ ],
"5LXwX8": [
"यह ",
["path"],
diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.po
index 7dd14f101..6fd4f077c 100644
--- a/packages/app/src/locales/hi/messages.po
+++ b/packages/app/src/locales/hi/messages.po
@@ -12353,6 +12353,11 @@ msgstr "यह {path} को स्थायी रूप से हटा द
msgid "This project"
msgstr "यह प्रोजेक्ट"
+#: src/components/NewWorktreeDialog.tsx
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "This project has no commits yet, so there's no branch to base a worktree on. Make a first commit, then try again."
+msgstr "इस प्रोजेक्ट में अभी तक कोई कमिट नहीं है, इसलिए worktree को आधार देने के लिए कोई ब्रांच नहीं है। पहला कमिट करें, फिर दोबारा कोशिश करें।"
+
#: src/components/settings/SharingSection.tsx
msgid "This project has no git repository — sharing mode does not apply. Initialize a repo to enable the toggle."
msgstr "इस प्रोजेक्ट में कोई git रिपॉज़िटरी नहीं है — साझाकरण मोड लागू नहीं होता। टॉगल सक्षम करने के लिए एक रिपॉज़िटरी आरंभ करें।"
diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.json
index 851b961fc..7da50056c 100644
--- a/packages/app/src/locales/id/messages.json
+++ b/packages/app/src/locales/id/messages.json
@@ -371,6 +371,9 @@
"5GKMSz": ["Menambah atau mengurangi indentasi item daftar saat ini."],
"5GRxoA": ["Mencari berkas, folder, dan perintah untuk ruang kerja saat ini."],
"5HJpFY": ["Mengantre di belakang giliran yang sedang berjalan"],
+ "5IgYAM": [
+ "Proyek ini belum memiliki commit, jadi tidak ada cabang untuk dijadikan dasar worktree. Buat commit pertama, lalu coba lagi."
+ ],
"5LXwX8": [
"Ini menghapus ",
["path"],
diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.po
index 76645c775..32568ee6f 100644
--- a/packages/app/src/locales/id/messages.po
+++ b/packages/app/src/locales/id/messages.po
@@ -12353,6 +12353,11 @@ msgstr "Ini menghapus {path} secara permanen. Agen yang merujuk templat ini berd
msgid "This project"
msgstr "Proyek ini"
+#: src/components/NewWorktreeDialog.tsx
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "This project has no commits yet, so there's no branch to base a worktree on. Make a first commit, then try again."
+msgstr "Proyek ini belum memiliki commit, jadi tidak ada cabang untuk dijadikan dasar worktree. Buat commit pertama, lalu coba lagi."
+
#: src/components/settings/SharingSection.tsx
msgid "This project has no git repository — sharing mode does not apply. Initialize a repo to enable the toggle."
msgstr "Proyek ini tidak punya repositori git — mode berbagi tidak berlaku. Inisialisasi sebuah repo untuk mengaktifkan sakelarnya."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index f30c724c6..fdce5c31b 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -370,6 +370,9 @@
"5GKMSz": ["Ĩńďēńţ ōŕ ōũţďēńţ ţĥē ćũŕŕēńţ ĺĩśţ ĩţēḿ."],
"5GRxoA": ["Śēàŕćĥ ƒĩĺēś, ƒōĺďēŕś, àńď ćōḿḿàńďś ƒōŕ ţĥē ćũŕŕēńţ ŵōŕķśƥàćē."],
"5HJpFY": ["Ǫũēũēś ƀēĥĩńď ţĥē ŕũńńĩńĝ ţũŕń"],
+ "5IgYAM": [
+ "Ţĥĩś ƥŕōĴēćţ ĥàś ńō ćōḿḿĩţś ŷēţ, śō ţĥēŕē'ś ńō ƀŕàńćĥ ţō ƀàśē à ŵōŕķţŕēē ōń. Ḿàķē à ƒĩŕśţ ćōḿḿĩţ, ţĥēń ţŕŷ àĝàĩń."
+ ],
"5LXwX8": [
"Ţĥĩś ƥēŕḿàńēńţĺŷ ŕēḿōvēś ",
["path"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 1347a56ee..54ab646cc 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -12353,6 +12353,11 @@ msgstr ""
msgid "This project"
msgstr ""
+#: src/components/NewWorktreeDialog.tsx
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "This project has no commits yet, so there's no branch to base a worktree on. Make a first commit, then try again."
+msgstr ""
+
#: src/components/settings/SharingSection.tsx
msgid "This project has no git repository — sharing mode does not apply. Initialize a repo to enable the toggle."
msgstr ""
diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.json
index 094e48a40..bf68d39de 100644
--- a/packages/app/src/locales/pt-BR/messages.json
+++ b/packages/app/src/locales/pt-BR/messages.json
@@ -435,6 +435,9 @@
"5GKMSz": ["Aumenta ou diminui o recuo do item de lista atual."],
"5GRxoA": ["Busca arquivos, pastas e comandos do espaço de trabalho atual."],
"5HJpFY": ["Entra na fila atrás do turno em andamento"],
+ "5IgYAM": [
+ "Este projeto ainda não tem commits, portanto não há nenhum ramo no qual basear um worktree. Faça um primeiro commit e tente novamente."
+ ],
"5LXwX8": [
"Isto remove definitivamente ",
["path"],
diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.po
index 525bc773c..94749ef34 100644
--- a/packages/app/src/locales/pt-BR/messages.po
+++ b/packages/app/src/locales/pt-BR/messages.po
@@ -12353,6 +12353,11 @@ msgstr "Isto remove definitivamente {path}. Os agentes que citarem este modelo p
msgid "This project"
msgstr "Este projeto"
+#: src/components/NewWorktreeDialog.tsx
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "This project has no commits yet, so there's no branch to base a worktree on. Make a first commit, then try again."
+msgstr "Este projeto ainda não tem commits, portanto não há nenhum ramo no qual basear um worktree. Faça um primeiro commit e tente novamente."
+
#: src/components/settings/SharingSection.tsx
msgid "This project has no git repository — sharing mode does not apply. Initialize a repo to enable the toggle."
msgstr "Este projeto não tem repositório git — o modo de compartilhamento não se aplica. Inicialize um repositório para habilitar a chave."
diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.json
index c0154cbfc..cdcb15b17 100644
--- a/packages/app/src/locales/ur/messages.json
+++ b/packages/app/src/locales/ur/messages.json
@@ -377,6 +377,9 @@
"5GKMSz": ["موجودہ فہرست آئٹم کی اندروں یا باہر کی جگہ بدلیں۔"],
"5GRxoA": ["موجودہ ورک اسپیس کی فائلیں، فولڈرز اور کمانڈز تلاش کریں۔"],
"5HJpFY": ["جاری باری کے پیچھے قطار میں لگتا ہے"],
+ "5IgYAM": [
+ "اس پروجیکٹ میں ابھی تک کوئی کمٹ نہیں ہے، اس لیے worktree کی بنیاد بنانے کے لیے کوئی برانچ نہیں ہے۔ پہلا کمٹ کریں، پھر دوبارہ کوشش کریں۔"
+ ],
"5LXwX8": [
"یہ ",
["path"],
diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.po
index 79026baa6..d670fe0dd 100644
--- a/packages/app/src/locales/ur/messages.po
+++ b/packages/app/src/locales/ur/messages.po
@@ -12357,6 +12357,11 @@ msgstr "یہ {path} کو مستقل طور پر ہٹا دیتا ہے۔ جو ای
msgid "This project"
msgstr "یہ پروجیکٹ"
+#: src/components/NewWorktreeDialog.tsx
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "This project has no commits yet, so there's no branch to base a worktree on. Make a first commit, then try again."
+msgstr "اس پروجیکٹ میں ابھی تک کوئی کمٹ نہیں ہے، اس لیے worktree کی بنیاد بنانے کے لیے کوئی برانچ نہیں ہے۔ پہلا کمٹ کریں، پھر دوبارہ کوشش کریں۔"
+
#: src/components/settings/SharingSection.tsx
msgid "This project has no git repository — sharing mode does not apply. Initialize a repo to enable the toggle."
msgstr "اس پروجیکٹ کی کوئی git ریپازٹری نہیں — اشتراک کا موڈ لاگو نہیں ہوتا۔ ٹوگل فعال کرنے کے لیے کوئی ریپو بنائیں۔"
diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.json
index ce367bf93..79f07eddb 100644
--- a/packages/app/src/locales/zh-Hans/messages.json
+++ b/packages/app/src/locales/zh-Hans/messages.json
@@ -338,6 +338,9 @@
"5GKMSz": ["增加或减少当前列表项的缩进。"],
"5GRxoA": ["在当前工作区中搜索文件、文件夹和命令。"],
"5HJpFY": ["排在当前回合之后"],
+ "5IgYAM": [
+ "此项目还没有任何提交,因此没有可作为 worktree 基础的分支。请先创建第一个提交,然后重试。"
+ ],
"5LXwX8": [
"这会永久移除 ",
["path"],
diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.po
index e922df860..bd4a33cc0 100644
--- a/packages/app/src/locales/zh-Hans/messages.po
+++ b/packages/app/src/locales/zh-Hans/messages.po
@@ -12357,6 +12357,11 @@ msgstr "这会永久移除 {path}。在重新创建它,或者由上级文件
msgid "This project"
msgstr "本项目"
+#: src/components/NewWorktreeDialog.tsx
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "This project has no commits yet, so there's no branch to base a worktree on. Make a first commit, then try again."
+msgstr "此项目还没有任何提交,因此没有可作为 worktree 基础的分支。请先创建第一个提交,然后重试。"
+
#: src/components/settings/SharingSection.tsx
msgid "This project has no git repository — sharing mode does not apply. Initialize a repo to enable the toggle."
msgstr "这个项目没有 git 仓库,因此共享模式不适用。初始化一个仓库即可启用该开关。"
diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.json
index 5169447fd..3134770d3 100644
--- a/packages/app/src/locales/zh-Hant/messages.json
+++ b/packages/app/src/locales/zh-Hant/messages.json
@@ -340,6 +340,9 @@
"5GKMSz": ["增加或減少目前清單項目的縮排。"],
"5GRxoA": ["在目前的工作區中搜尋檔案、資料夾和指令。"],
"5HJpFY": ["排在目前回合之後"],
+ "5IgYAM": [
+ "此專案還沒有任何提交,因此沒有可作為 worktree 基礎的分支。請先建立第一個提交,然後再試一次。"
+ ],
"5LXwX8": [
"這會永久移除 ",
["path"],
diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.po
index ab5aa77f8..41afc16b2 100644
--- a/packages/app/src/locales/zh-Hant/messages.po
+++ b/packages/app/src/locales/zh-Hant/messages.po
@@ -12357,6 +12357,11 @@ msgstr "這會永久移除 {path}。在重新建立它,或由上層資料夾
msgid "This project"
msgstr "這個專案"
+#: src/components/NewWorktreeDialog.tsx
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "This project has no commits yet, so there's no branch to base a worktree on. Make a first commit, then try again."
+msgstr "此專案還沒有任何提交,因此沒有可作為 worktree 基礎的分支。請先建立第一個提交,然後再試一次。"
+
#: src/components/settings/SharingSection.tsx
msgid "This project has no git repository — sharing mode does not apply. Initialize a repo to enable the toggle."
msgstr "這個專案沒有 git 儲存庫,所以分享模式不適用。初始化一個儲存庫就能啟用這個開關。"
diff --git a/packages/app/tests/integration/agent-write-batch.test.ts b/packages/app/tests/integration/agent-write-batch.test.ts
index 869242325..f58fa2a1d 100644
--- a/packages/app/tests/integration/agent-write-batch.test.ts
+++ b/packages/app/tests/integration/agent-write-batch.test.ts
@@ -20,7 +20,7 @@ import { execFileSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { AgentWriteBatchSuccessSchema } from '@inkeep/open-knowledge-core';
-import { resolveShadowDir } from '@inkeep/open-knowledge-core/shadow-repo-layout';
+import { parseWriterId, resolveShadowDir } from '@inkeep/open-knowledge-core/shadow-repo-layout';
import { afterEach, describe, expect, test } from 'vitest';
import { createTestServer, getServerState, type TestServer } from './test-harness';
@@ -65,13 +65,32 @@ async function postBatch(
});
}
+/**
+ * WIP refs belonging to SESSION writers (agent / principal) only.
+ *
+ * `refs/wip/` also carries classified service writers, notably `git-upstream`,
+ * which exists as soon as the project repo has history to import. Counting
+ * those conflates "these writes produced a shadow commit" with "the repo has
+ * commits at all", which is not what the assertions below mean. Mirrors the
+ * production filter in `shadow-repo-stats.ts`, including its ref parsing.
+ */
function listWipRefs(contentDir: string): string[] {
const shadowDir = resolveShadowDir(contentDir);
const raw = execFileSync('git', ['for-each-ref', '--format=%(refname)', 'refs/wip/'], {
env: { ...process.env, GIT_DIR: shadowDir },
encoding: 'utf-8',
});
- return raw.trim().split('\n').filter(Boolean);
+ return raw
+ .trim()
+ .split('\n')
+ .filter(Boolean)
+ .filter((refname) => {
+ // refs/wip/<branch>/<writerId> — writerId may itself contain slashes.
+ const writerId = refname.split('/').slice(3).join('/');
+ if (!writerId) return false;
+ const { classification } = parseWriterId(writerId);
+ return classification === 'agent' || classification === 'principal';
+ });
}
function countCommits(contentDir: string, ref: string): number {
diff --git a/packages/app/tests/integration/agent-write-commit-coalescing.test.ts b/packages/app/tests/integration/agent-write-commit-coalescing.test.ts
index 86a869a44..b58f7e3cb 100644
--- a/packages/app/tests/integration/agent-write-commit-coalescing.test.ts
+++ b/packages/app/tests/integration/agent-write-commit-coalescing.test.ts
@@ -15,7 +15,7 @@
*/
import { execFileSync } from 'node:child_process';
-import { resolveShadowDir } from '@inkeep/open-knowledge-core/shadow-repo-layout';
+import { parseWriterId, resolveShadowDir } from '@inkeep/open-knowledge-core/shadow-repo-layout';
import { afterEach, describe, expect, test } from 'vitest';
import { agentWriteMd, createTestServer, type TestServer } from './test-harness';
@@ -30,13 +30,32 @@ afterEach(async () => {
server = undefined;
});
+/**
+ * WIP refs belonging to SESSION writers (agent / principal) only.
+ *
+ * `refs/wip/` also carries classified service writers, notably `git-upstream`,
+ * which exists as soon as the project repo has history to import. Counting
+ * those conflates "these writes produced a shadow commit" with "the repo has
+ * commits at all", which is not what the assertions below mean. Mirrors the
+ * production filter in `shadow-repo-stats.ts`, including its ref parsing.
+ */
function listWipRefs(contentDir: string): string[] {
const shadowDir = resolveShadowDir(contentDir);
const raw = execFileSync('git', ['for-each-ref', '--format=%(refname)', 'refs/wip/'], {
env: { ...process.env, GIT_DIR: shadowDir },
encoding: 'utf-8',
});
- return raw.trim().split('\n').filter(Boolean);
+ return raw
+ .trim()
+ .split('\n')
+ .filter(Boolean)
+ .filter((refname) => {
+ // refs/wip/<branch>/<writerId> — writerId may itself contain slashes.
+ const writerId = refname.split('/').slice(3).join('/');
+ if (!writerId) return false;
+ const { classification } = parseWriterId(writerId);
+ return classification === 'agent' || classification === 'principal';
+ });
}
describe('agent-write L2 commit coalescing', () => {
diff --git a/packages/core/src/git/worktree-selector-model.ts b/packages/core/src/git/worktree-selector-model.ts
index 36f570600..43a38215e 100644
--- a/packages/core/src/git/worktree-selector-model.ts
+++ b/packages/core/src/git/worktree-selector-model.ts
@@ -164,6 +164,14 @@ export type WorktreeCreateResult =
| 'path-exists'
| 'no-git'
| 'branch-not-found'
+ /**
+ * The repository exists but has no commits, so no branch is a
+ * resolvable ref and `git worktree add` fails with
+ * `fatal: invalid reference: <base>`. Distinct from `no-git` (not a
+ * repository at all) and from `branch-not-found` (a repository with
+ * history where that particular branch is missing).
+ */
+ | 'empty-repo'
| 'error';
readonly message?: string;
readonly helper?: never;
diff --git a/packages/desktop/src/main/create-new-project.test.ts b/packages/desktop/src/main/create-new-project.test.ts
index f5a7b14a7..8ff5d5418 100644
--- a/packages/desktop/src/main/create-new-project.test.ts
+++ b/packages/desktop/src/main/create-new-project.test.ts
@@ -1,3 +1,4 @@
+import { execFileSync } from 'node:child_process';
import {
chmodSync,
existsSync,
@@ -195,6 +196,38 @@ describe('runCreateNew — happy paths', () => {
expect(result.variant).toBe('create-new-default');
});
+ test('leaves a project whose default branch can base a worktree', async () => {
+ // The reported symptom, pinned at the entry point that reported it: the
+ // repo used to be left with an unborn HEAD, so the New-worktree dialog's
+ // `git worktree add -b <name> <path> -- main` died with
+ // `fatal: invalid reference: main`. `ensureProjectGit` is the shared fix
+ // site; this guards the create-new path against ever short-circuiting it.
+ const result = await runCreateNew({
+ parent: tmpRoot,
+ name: 'Worktree Base',
+ editors: [...ALL_EDITOR_IDS],
+ });
+
+ expect(() =>
+ execFileSync('git', ['rev-parse', '--verify', 'HEAD'], { cwd: result.projectDir }),
+ ).not.toThrow();
+ expect(() =>
+ execFileSync(
+ 'git',
+ [
+ 'worktree',
+ 'add',
+ '-b',
+ 'wt-1',
+ join(result.projectDir, '.ok/worktrees/wt-1'),
+ '--',
+ 'main',
+ ],
+ { cwd: result.projectDir },
+ ),
+ ).not.toThrow();
+ });
+
test('records customized variant when a subset of editors is supplied', async () => {
const result = await runCreateNew({
parent: tmpRoot,
diff --git a/packages/desktop/src/main/worktree-service.test.ts b/packages/desktop/src/main/worktree-service.test.ts
index 0480f6157..d0dd668c3 100644
--- a/packages/desktop/src/main/worktree-service.test.ts
+++ b/packages/desktop/src/main/worktree-service.test.ts
@@ -202,6 +202,77 @@ describe('worktree-service', () => {
expect(res.reason).toBe('invalid-branch');
});
+ test('createWorktree reports empty-repo (not the generic arm) on a repo with no commits', async () => {
+ // A repo that never got a root commit: `main` is not a resolvable ref, so
+ // `git worktree add ... -- main` fails with `fatal: invalid reference: main`
+ // — stderr indistinguishable from a genuinely missing branch. Reporting the
+ // generic arm here is what produced "Try a different name" for a condition
+ // no branch name can fix.
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'wt-svc-empty-')));
+ try {
+ await git(root, 'init', '--initial-branch=main', '.');
+ const res = await createWorktree({
+ anchorPath: root,
+ branch: 'wt-1',
+ createBranch: true,
+ baseBranch: 'main',
+ });
+ expect(res.ok).toBe(false);
+ if (res.ok) return;
+ expect(res.reason).toBe('empty-repo');
+ // git's own words survive to the renderer rather than being swallowed.
+ expect(res.message).toContain('invalid reference');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ test('createWorktree still reports the generic arm when the repo HAS commits', async () => {
+ // Guards the empty-repo probe against over-claiming: a repo with history
+ // whose add fails for some other reason must not be relabelled empty-repo.
+ handle = await makeRepo();
+ const res = await createWorktree({
+ anchorPath: handle.mainRepo,
+ branch: 'wt-1',
+ createBranch: true,
+ baseBranch: 'no-such-base',
+ });
+ expect(res.ok).toBe(false);
+ if (res.ok) return;
+ expect(res.reason).not.toBe('empty-repo');
+ });
+
+ test('a repo with history on another branch is not called empty when the base is unborn', async () => {
+ // `rev-parse --verify HEAD` answers only for the CURRENT branch, so it
+ // reports "no commits" for a repo whose history sits on another branch
+ // while the requested base is unborn — telling the user "this project has
+ // no commits yet" about a repo full of them.
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'wt-svc-other-branch-')));
+ try {
+ await git(root, 'init', '--initial-branch=other', '.');
+ await git(root, 'config', 'user.email', '[email protected]');
+ await git(root, 'config', 'user.name', 'Test');
+ await git(root, 'commit', '--allow-empty', '-m', 'real history');
+ // Leave the history on `other` and point HEAD at an unborn `main`.
+ await git(root, 'symbolic-ref', 'HEAD', 'refs/heads/main');
+
+ const res = await createWorktree({
+ anchorPath: root,
+ branch: 'wt-1',
+ createBranch: true,
+ baseBranch: 'main',
+ });
+
+ expect(res.ok).toBe(false);
+ if (res.ok) return;
+ expect(res.reason).not.toBe('empty-repo');
+ // The generic arm still carries git's own words.
+ expect(res.message).toContain('invalid reference');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
test('listWorktreeSelector on a non-git dir returns no-git', async () => {
const tmp = realpathSync(mkdtempSync(join(tmpdir(), 'wt-svc-nogit-')));
try {
diff --git a/packages/desktop/src/main/worktree-service.ts b/packages/desktop/src/main/worktree-service.ts
index 0fd51c49d..e599b7bbe 100644
--- a/packages/desktop/src/main/worktree-service.ts
+++ b/packages/desktop/src/main/worktree-service.ts
@@ -201,7 +201,16 @@ export async function createWorktree(args: CreateWorktreeArgs): Promise<Worktree
try {
await execFileAsync('git', addArgs, { cwd: args.anchorPath, env: gitSpawnEnv() });
} catch (err) {
- return { ok: false, ...classifyAddError(err) };
+ const classified = classifyAddError(err);
+ // A repo with no commits has no resolvable base ref, so git rejects the add
+ // with `fatal: invalid reference: <base>` — indistinguishable by stderr from
+ // a genuinely missing branch. Probing the repo tells them apart. Only on the
+ // generic arm, so the happy path and every classified failure spawn nothing
+ // extra.
+ if (classified.reason === 'error' && !(await repoHasAnyRef(args.anchorPath))) {
+ return { ok: false, reason: 'empty-repo', message: classified.message };
+ }
+ return { ok: false, ...classified };
}
// The worktree now exists on disk — capture success before any post-create
@@ -540,6 +549,31 @@ function ensureWorktreesExcluded(anchorPath: string): void {
}
}
+/**
+ * True when the repo at `cwd` holds any ref at all.
+ *
+ * Deliberately NOT `rev-parse --verify HEAD`, which answers only for the
+ * CURRENT branch: a repo whose history sits on another branch while the
+ * requested base is unborn does have commits, and reporting `empty-repo`
+ * there would tell the user "this project has no commits yet" about a repo
+ * full of them. Those fall to the generic arm instead, which now surfaces
+ * git's own `invalid reference` text. Same question, same answer, as
+ * `hasAnyRef` in `project-git.ts`.
+ */
+async function repoHasAnyRef(cwd: string): Promise<boolean> {
+ try {
+ const { stdout } = await execFileAsync('git', ['for-each-ref', '--count=1', 'refs/'], {
+ cwd,
+ env: gitSpawnEnv(),
+ });
+ return stdout.trim().length > 0;
+ } catch {
+ // Unreadable refs — prefer the generic arm (which carries git's stderr)
+ // over asserting the repo is empty.
+ return true;
+ }
+}
+
/** Synchronous git read that returns the trimmed stdout, or null on failure. */
function execFileSyncTrim(cmd: string, cmdArgs: string[], cwd: string): string | null {
try {
diff --git a/packages/server/src/project-git.test.ts b/packages/server/src/project-git.test.ts
index 56cbbc018..9b6d560aa 100644
--- a/packages/server/src/project-git.test.ts
+++ b/packages/server/src/project-git.test.ts
@@ -167,3 +167,165 @@ describe('ensureProjectGit', () => {
}
});
});
+
+describe('ensureProjectGit — initial commit', () => {
+ /** True when `git rev-parse --verify HEAD` resolves (the repo has >=1 commit). */
+ async function headResolves(cwd: string): Promise<boolean> {
+ try {
+ await execFileAsync('git', ['rev-parse', '--verify', 'HEAD'], { cwd });
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
+ test('leaves a repo whose HEAD resolves after a fresh init', async () => {
+ const projectRoot = resolve(tmpDir, 'fresh');
+ mkdirSync(projectRoot, { recursive: true });
+
+ const result = await ensureProjectGit(projectRoot);
+
+ expect(result.didInit).toBe(true);
+ await expect(headResolves(projectRoot)).resolves.toBe(true);
+ });
+
+ test('leaves `main` resolvable, so `git worktree add ... -- main` succeeds', async () => {
+ // The user-visible symptom: the New-worktree dialog runs
+ // `git worktree add -b <branch> <path> -- main`, and git rejects an unborn
+ // `main` with `fatal: invalid reference: main`.
+ const projectRoot = resolve(tmpDir, 'worktree-base');
+ mkdirSync(projectRoot, { recursive: true });
+
+ await ensureProjectGit(projectRoot);
+
+ const worktreePath = resolve(projectRoot, '.ok/worktrees/wt-1');
+ await expect(
+ execFileAsync('git', ['worktree', 'add', '-b', 'wt-1', worktreePath, '--', 'main'], {
+ cwd: projectRoot,
+ }),
+ ).resolves.toBeDefined();
+ });
+
+ test('backfills a root commit on a repo already stranded with an unborn HEAD', async () => {
+ // Every project shipped OK created before this fix is in this state, and
+ // nothing else backfills it. They are the population that reported the bug,
+ // so a forward-only fix would leave them broken forever.
+ const projectRoot = resolve(tmpDir, 'stranded');
+ mkdirSync(projectRoot, { recursive: true });
+ await execFileAsync('git', ['init', '--initial-branch=main', projectRoot]);
+ await expect(headResolves(projectRoot)).resolves.toBe(false);
+
+ const result = await ensureProjectGit(projectRoot);
+
+ // No `git init` ran — the repo already existed; only its root commit was
+ // missing.
+ expect(result.didInit).toBe(false);
+ await expect(headResolves(projectRoot)).resolves.toBe(true);
+ });
+
+ test('never grafts a root commit onto a repo that holds any history', async () => {
+ // The safety bound. A repo whose history sits on some other branch has an
+ // unborn `main`, and committing there would create a root disjoint from
+ // everything already in it.
+ const projectRoot = resolve(tmpDir, 'history-elsewhere');
+ mkdirSync(projectRoot, { recursive: true });
+ await execFileAsync('git', ['init', '--initial-branch=other', projectRoot]);
+ await execFileAsync(
+ 'git',
+ ['-c', 'user.name=T', '-c', '[email protected]', 'commit', '--allow-empty', '-m', 'existing'],
+ { cwd: projectRoot },
+ );
+ const before = await execFileAsync('git', ['rev-parse', 'HEAD'], { cwd: projectRoot });
+ // Point HEAD at an unborn branch, leaving the real history on `other`.
+ await execFileAsync('git', ['symbolic-ref', 'HEAD', 'refs/heads/main'], { cwd: projectRoot });
+ await expect(headResolves(projectRoot)).resolves.toBe(false);
+
+ await ensureProjectGit(projectRoot);
+
+ // `main` stays unborn and `other` is untouched — no disjoint root appeared.
+ await expect(headResolves(projectRoot)).resolves.toBe(false);
+ const after = await execFileAsync('git', ['rev-parse', 'other'], { cwd: projectRoot });
+ expect(after.stdout.trim()).toBe(before.stdout.trim());
+ });
+
+ test('commits after repairing a partial .git/ (shell-`.git/` regression class)', async () => {
+ const projectRoot = resolve(tmpDir, 'shell-git-commit');
+ mkdirSync(resolve(projectRoot, '.git/ok'), { recursive: true });
+
+ const result = await ensureProjectGit(projectRoot);
+
+ expect(result.repaired).toBe(true);
+ await expect(headResolves(projectRoot)).resolves.toBe(true);
+ });
+
+ test('commits even when git can resolve no identity at all', async () => {
+ // OK Desktop targets note-takers, not only developers — git installed with
+ // `user.email` unset is a realistic first-run state, and project creation
+ // must not depend on the user having configured one.
+ //
+ // `useConfigOnly` is what makes this test real: without it git happily
+ // auto-derives `user@host`, the commit succeeds on its own, and the test
+ // would pass on machines that never exercise the fallback at all.
+ const projectRoot = resolve(tmpDir, 'no-identity');
+ mkdirSync(projectRoot, { recursive: true });
+ const emptyConfig = resolve(tmpDir, 'gitconfig-no-identity');
+ writeFileSync(emptyConfig, '[user]\n\tuseConfigOnly = true\n');
+
+ const saved = { ...process.env };
+ process.env.GIT_CONFIG_GLOBAL = emptyConfig;
+ process.env.GIT_CONFIG_SYSTEM = '/dev/null';
+ for (const key of Object.keys(process.env)) {
+ if (key.startsWith('GIT_AUTHOR_') || key.startsWith('GIT_COMMITTER_')) {
+ delete process.env[key];
+ }
+ }
+ try {
+ // Guard the guard: prove git really cannot commit unaided here, so a
+ // future change to identity resolution can't quietly hollow this out.
+ await expect(
+ execFileAsync('git', ['var', 'GIT_COMMITTER_IDENT'], { cwd: projectRoot }),
+ ).rejects.toBeDefined();
+
+ await ensureProjectGit(projectRoot);
+ await expect(headResolves(projectRoot)).resolves.toBe(true);
+
+ const author = await execFileAsync('git', ['log', '-1', '--format=%an <%ae>'], {
+ cwd: projectRoot,
+ });
+ expect(author.stdout.trim()).toBe('Open Knowledge <[email protected]>');
+ } finally {
+ for (const key of Object.keys(process.env)) {
+ if (!(key in saved)) delete process.env[key];
+ }
+ Object.assign(process.env, saved);
+ }
+ });
+
+ test('uses the configured identity when there is one, never the fallback', async () => {
+ const projectRoot = resolve(tmpDir, 'real-identity');
+ mkdirSync(projectRoot, { recursive: true });
+ const realConfig = resolve(tmpDir, 'gitconfig-real');
+ writeFileSync(realConfig, '[user]\n\tname = Real Person\n\temail = [email protected]\n');
+
+ const saved = { ...process.env };
+ process.env.GIT_CONFIG_GLOBAL = realConfig;
+ process.env.GIT_CONFIG_SYSTEM = '/dev/null';
+ for (const key of Object.keys(process.env)) {
+ if (key.startsWith('GIT_AUTHOR_') || key.startsWith('GIT_COMMITTER_')) {
+ delete process.env[key];
+ }
+ }
+ try {
+ await ensureProjectGit(projectRoot);
+ const author = await execFileAsync('git', ['log', '-1', '--format=%an <%ae>'], {
+ cwd: projectRoot,
+ });
+ expect(author.stdout.trim()).toBe('Real Person <[email protected]>');
+ } finally {
+ for (const key of Object.keys(process.env)) {
+ if (!(key in saved)) delete process.env[key];
+ }
+ Object.assign(process.env, saved);
+ }
+ });
+});
diff --git a/packages/server/src/project-git.ts b/packages/server/src/project-git.ts
index d93ba6d6c..31be15fce 100644
--- a/packages/server/src/project-git.ts
+++ b/packages/server/src/project-git.ts
@@ -13,7 +13,7 @@
* subfolder of an existing repo does not create a nested repo.
*/
import { execFile } from 'node:child_process';
-import { existsSync, statSync } from 'node:fs';
+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { resolve } from 'node:path';
import { promisify } from 'node:util';
import { withHiddenWindowsConsole } from './child-process-windows-hide.ts';
@@ -49,6 +49,171 @@ export interface EnsureProjectGitResult {
repaired?: boolean;
}
+/**
+ * Identity for the root commit, used ONLY when the machine has none
+ * configured. OK Desktop is a notes app before it is a developer tool, so an
+ * unset `user.email` is a realistic first-run state; failing over it would
+ * strand the user with the very unborn-HEAD repo this commit exists to
+ * prevent. A configured identity is always preferred and never overridden.
+ */
+const FALLBACK_COMMIT_NAME = 'Open Knowledge';
+// Matches the identity the shadow repo already commits under, so OK's own
+// writes read the same wherever they land.
+const FALLBACK_COMMIT_EMAIL = '[email protected]';
+
+/**
+ * True when git can resolve a committer identity here.
+ *
+ * Exit code only, never the message: git localizes its failure text (a German
+ * locale reports "Bitte geben Sie an, wer Sie sind"), so matching English
+ * phrases would silently skip the fallback for exactly the non-developer,
+ * non-English users the fallback exists for.
+ */
+async function hasCommitterIdentity(gitBin: string, cwd: string): Promise<boolean> {
+ try {
+ await execFileAsync(
+ gitBin,
+ ['var', 'GIT_COMMITTER_IDENT'],
+ withHiddenWindowsConsole({ cwd, encoding: 'utf-8' }),
+ );
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * True when the repo holds at least one ref.
+ *
+ * Broader than `rev-parse --verify HEAD`, which answers only for the CURRENT
+ * branch: a salvaged `.git/` can carry history on some other branch while
+ * `main` is unborn, and committing there would graft a root commit disjoint
+ * from everything already in the repo.
+ */
+async function hasAnyRef(gitBin: string, cwd: string): Promise<boolean> {
+ try {
+ const { stdout } = await execFileAsync(
+ gitBin,
+ ['for-each-ref', '--count=1', 'refs/'],
+ withHiddenWindowsConsole({ cwd, encoding: 'utf-8' }),
+ );
+ return stdout.trim().length > 0;
+ } catch (err) {
+ // Unreadable refs — assume history exists rather than risk a disjoint root.
+ // Logged because this is the guard the repair path turns on: a transient
+ // failure here silently skips the backfill and leaves the user in exactly
+ // the unborn-HEAD state this code exists to clear.
+ log.warn(
+ { path: cwd, stderr: spawnErrorText(err) },
+ 'could not list refs — assuming history exists and skipping the initial commit',
+ );
+ return true;
+ }
+}
+
+/**
+ * Conservative fast-path: does this repo have a branch?
+ *
+ * Deliberately narrower than the full ref namespace — it reads only
+ * `refs/heads/` and `packed-refs`, so a repo carrying nothing but tags or
+ * remotes answers `false`. That costs one wasted git spawn and nothing more,
+ * because `hasAnyRef` re-asks authoritatively over all of `refs/` before any
+ * commit is written. Its whole job is to keep the common already-populated
+ * case from invoking git or paying the preflight. Not a standalone
+ * "does this repo have refs" oracle — do not use it as one.
+ */
+function hasRefsOnDisk(gitDir: string): boolean {
+ const packed = resolve(gitDir, 'packed-refs');
+ if (existsSync(packed)) {
+ try {
+ const body = readFileSync(packed, 'utf-8');
+ if (body.split('\n').some((line) => line.trim() !== '' && !line.startsWith('#'))) return true;
+ } catch {
+ return true;
+ }
+ }
+ try {
+ return readdirSync(resolve(gitDir, 'refs/heads')).length > 0;
+ } catch {
+ // Absent refs/heads on a real repo means no branches have been created.
+ return false;
+ }
+}
+
+/** stderr of a failed spawn, falling back to the error message. */
+function spawnErrorText(err: unknown): string {
+ const e =
+ typeof err === 'object' && err !== null
+ ? (err as { stderr?: unknown; message?: unknown })
+ : null;
+ const raw = e?.stderr;
+ if (raw !== undefined && raw !== null) {
+ return Buffer.isBuffer(raw) ? raw.toString('utf-8') : String(raw);
+ }
+ return String(e?.message ?? err);
+}
+
+/**
+ * Give a freshly-initialized repo a root commit so its default branch is a
+ * resolvable ref.
+ *
+ * `git init` alone leaves an unborn HEAD: `.git/HEAD` points at
+ * `refs/heads/main` while no such ref exists, so every `main`-relative command
+ * fails — most visibly `git worktree add -b <name> <path> -- main`, which dies
+ * with `fatal: invalid reference: main`.
+ *
+ * The commit is deliberately EMPTY. `ensureProjectGit` runs before any
+ * scaffolding at all of its call sites, and several of them (`ok init`, the
+ * pick-existing consent flow, the utility-process boot) can target a folder
+ * that already holds the user's un-versioned files. Staging those would put a
+ * whole notes tree under version control in a commit nobody asked for. An
+ * empty root commit restores the invariant while touching no content.
+ *
+ * Best-effort by contract: a failure leaves a valid repo that merely still
+ * can't resolve its default branch, which the worktree-create path reports as
+ * `empty-repo`. Project setup must not fail over it.
+ */
+async function createInitialCommit(gitBin: string, cwd: string): Promise<void> {
+ // Never graft a root commit onto a repo that already holds anything.
+ if (await hasAnyRef(gitBin, cwd)) return;
+
+ // `--no-verify` and `--no-gpg-sign`: this is OK's own bookkeeping commit, not
+ // the user's work. A pre-commit hook inherited from `init.templateDir`, or a
+ // signing key the packaged app's minimal PATH can't reach, must not be able
+ // to fail project setup.
+ const commitArgs = [
+ 'commit',
+ '--allow-empty',
+ '--no-verify',
+ '--no-gpg-sign',
+ '-m',
+ 'Initial commit',
+ ];
+
+ // Supply a fallback identity ONLY when git can't resolve one. `-c` overrides
+ // configured values, so passing it unconditionally would misattribute the
+ // commit for every user who does have an identity set.
+ const identified = await hasCommitterIdentity(gitBin, cwd);
+ const args = identified
+ ? commitArgs
+ : [
+ '-c',
+ `user.name=${FALLBACK_COMMIT_NAME}`,
+ '-c',
+ `user.email=${FALLBACK_COMMIT_EMAIL}`,
+ ...commitArgs,
+ ];
+
+ try {
+ await execFileAsync(gitBin, args, withHiddenWindowsConsole({ cwd, encoding: 'utf-8' }));
+ if (!identified) {
+ log.info({ path: cwd }, 'created initial commit with fallback identity (git identity unset)');
+ }
+ } catch (err) {
+ log.warn({ path: cwd, stderr: spawnErrorText(err) }, 'could not create initial commit');
+ }
+}
+
async function isInsideExistingWorkTree(gitBin: string, cwd: string): Promise<boolean> {
try {
const { stdout } = await execFileAsync(
@@ -87,18 +252,31 @@ export async function ensureProjectGit(projectRoot: string): Promise<EnsureProje
const headPath = resolve(gitPath, 'HEAD');
let needsRepair = false;
+ // A repo that has HEAD but not a single ref never got a root commit, so its
+ // default branch does not resolve. Projects that shipped OK created before
+ // the initial-commit fix are all in this state, and nothing else backfills
+ // them — they stay broken forever otherwise, and they are precisely the
+ // population that reported the bug. Adopting one costs nothing: with zero
+ // refs there is no history to conflict with or diverge from.
+ let strandedUnborn = false;
if (existsSync(gitPath)) {
if (!statSync(gitPath).isDirectory()) {
// Worktree-pointer file (`gitdir: ...`) — not a real `.git/`, no HEAD to check.
return { didInit: false };
}
if (existsSync(headPath)) {
- return { didInit: false };
+ // Filesystem probe first: an already-populated repo (the common case)
+ // still returns here without invoking git or paying the preflight.
+ if (hasRefsOnDisk(gitPath)) {
+ return { didInit: false };
+ }
+ strandedUnborn = true;
+ } else {
+ // Directory present without `HEAD` — `git init` is idempotent and leaves
+ // foreign subtrees (e.g. `.git/ok/`) untouched.
+ log.info({}, 'detected partial .git/ — running git init to repair');
+ needsRepair = true;
}
- // Directory present without `HEAD` — `git init` is idempotent and leaves
- // foreign subtrees (e.g. `.git/ok/`) untouched.
- log.info({}, 'detected partial .git/ — running git init to repair');
- needsRepair = true;
}
// We will invoke git from here on (rev-parse and/or init). Validate that git
@@ -142,6 +320,14 @@ export async function ensureProjectGit(projectRoot: string): Promise<EnsureProje
}
const gitBin = detected.resolvedPath;
+ // Backfill the root commit on an already-initialized but ref-less repo. No
+ // `git init` runs here, so `didInit` stays false — the repo existed; only its
+ // missing root commit is supplied.
+ if (strandedUnborn) {
+ await createInitialCommit(gitBin, abs);
+ return { didInit: false };
+ }
+
// Only walk up to an ancestor repo when `.git` is absent here (needsRepair is
// set only when a partial `.git/` is present, which we must re-init in place).
if (!needsRepair && (await isInsideExistingWorkTree(gitBin, abs))) {
@@ -174,6 +360,10 @@ export async function ensureProjectGit(projectRoot: string): Promise<EnsureProje
);
}
+ // Internally guarded on "the repo holds no refs", so the salvaged-`.git/`
+ // repair path can never graft a root disjoint from recovered history.
+ await createInitialCommit(gitBin, abs);
+
if (needsRepair) {
log.info({ path: abs }, 'backfilled missing .git/HEAD');
return { didInit: true, repaired: true };