Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): make built-in project skill local-only, not git-tracked (#2665)
Andrew Mikofalvy72aa84e40ea6
diff --git a/.changeset/project-skill-local-only.md b/.changeset/project-skill-local-only.mdnew file mode 100644index 000000000..53ada30e9--- /dev/null+++ b/.changeset/project-skill-local-only.md@@ -0,0 +1,7 @@+---+"@inkeep/open-knowledge": patch+---++Stop OpenKnowledge's built-in `open-knowledge` project skill from causing recurring git sync conflicts. The app regenerates that skill into each editor's host dir (`.claude/skills/open-knowledge/`, `.cursor/…`, `.codex/…`, `.github/…`, `.opencode/…`, `.pi/…`) on every open, and different app builds stamp a different version into it — so when it was committed, teammates on different builds collided under git auto-sync (merge conflicts, or a repeatedly "paused, external changes pending" sync).++It is now treated as a local, per-machine artifact. On `ok init` and on project open, OpenKnowledge writes a committed `.gitignore` entry that always excludes this projection (in both shared and local-only sharing modes, and it travels to every clone so a fresh checkout is protected before the app ever runs). Nothing is lost, since the app regenerates the file on each open. For repos where the skill was already committed, opening the project untracks it automatically via a dedicated, conflict-safe commit; teammates will see it removed on their next pull. Authored skills you place under `.{editor}/skills/<your-name>/` are unaffected and continue to follow your OpenKnowledge sharing setting.diff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.tsindex aa459aa73..e52dbb01a 100644--- a/packages/cli/src/commands/init.test.ts+++ b/packages/cli/src/commands/init.test.ts@@ -1196,7 +1196,7 @@ describe('runInit', () => {expect(output).toContain(`Seeded .gitignore at ${testDir}/.gitignore (.DS_Store)`);});- it('pre-existing .git/ → does NOT touch a hand-authored project-root .gitignore', async () => {+ it('pre-existing .git/ → preserves a hand-authored .gitignore but appends the always-excluded project-skill block', async () => {mkdirSync(join(testDir, '.git'));writeFileSync(join(testDir, '.git/HEAD'), 'ref: refs/heads/main\n');const original = '# user-authored\nnode_modules/\n';@@ -1205,19 +1205,25 @@ describe('runInit', () => {const result = await runInitForTest({ editors: ['claude'] });expect(result.didGitInit).toBe(false);+ // The `.DS_Store` seed (`writeRootGitignoreForNewRepo`) still never+ // touches an existing file — `rootGitignoreCreated` stays false and its+ // disclosure is omitted.expect(result.rootGitignoreCreated).toBe(false);- const after = readFileSync(join(testDir, '.gitignore'), 'utf-8');- expect(after).toBe(original);- // Formatter omits the seed disclosureconst output = formatInitResult(result, testDir);expect(output).not.toContain('Seeded .gitignore');+ // But the built-in project-skill projection block IS appended+ // (append-only) so it can never be committed. User lines are preserved.+ const after = readFileSync(join(testDir, '.gitignore'), 'utf-8');+ expect(after.startsWith(original)).toBe(true);+ expect(after).toContain('.claude/skills/open-knowledge/');+ expect(after).toContain('.pi/skills/open-knowledge/');});- it('fresh tmpdir WITH a pre-existing .gitignore → did-git-init but seed is skipped', async () => {+ it('fresh tmpdir WITH a pre-existing .gitignore → .DS_Store seed skipped, project-skill block appended', async () => {// Edge case: user pre-staged a folder with their own .gitignore but no- // .git/. ensureProjectGit runs `git init`; the seed helper sees the- // existing file and skips. The fresh-git-init disclosure still fires;- // the seed disclosure does not.+ // .git/. ensureProjectGit runs `git init`; the `.DS_Store` seed helper+ // sees the existing file and skips. The always-excluded project-skill+ // block is still appended (append-only).const original = 'secrets.env\n';writeFileSync(join(testDir, '.gitignore'), original, 'utf-8');@@ -1225,9 +1231,11 @@ describe('runInit', () => {expect(result.didGitInit).toBe(true);expect(result.rootGitignoreCreated).toBe(false);- expect(readFileSync(join(testDir, '.gitignore'), 'utf-8')).toBe(original);- // Formatter suppresses the seed disclosure when rootGitignoreCreated is- // false even though didGitInit fired — completes the 2×2 matrix.+ const after = readFileSync(join(testDir, '.gitignore'), 'utf-8');+ expect(after.startsWith(original)).toBe(true);+ expect(after).toContain('.claude/skills/open-knowledge/');+ // Formatter suppresses the `.DS_Store` seed disclosure when+ // rootGitignoreCreated is false even though didGitInit fired.const output = formatInitResult(result, testDir);expect(output).not.toContain('Seeded .gitignore');});diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex 4e3f91323..42165d91d 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -26,6 +26,7 @@ import type {import {BUNDLE_SKILL_NAME,ensureProjectGit,+ ensureProjectSkillGitignore,GitNotAvailableError,GitTooOldError,initContent,@@ -33,6 +34,7 @@ import {MCP_SERVER_NAME,ProjectGitInitError,USER_GLOBAL_BUNDLE_IDS,+ untrackTrackedProjectSkillProjection,writeBundleDecision,writeRootGitignoreForNewRepo,} from '@inkeep/open-knowledge-server';@@ -1661,6 +1663,25 @@ export async function runInit(options: InitCommandOptions = {}): Promise<InitCom}}+ // 1c. Always exclude OK's built-in project-skill projection via the committed+ // `.gitignore` — unconditionally (fresh OR existing repo), since the bundle is+ // a per-machine, per-build artifact that must never be committed. Then heal a+ // repo where it is ALREADY tracked (idempotent no-op otherwise). Both are+ // non-fatal: the project is fully usable even if git is unavailable.+ try {+ ensureProjectSkillGitignore(projectRoot);+ } catch (err) {+ console.warn(+ `[ok] Skipping project-skill .gitignore entry at ${projectRoot}: ${err instanceof Error ? err.message : String(err)}`,+ );+ }+ const untrackResult = await untrackTrackedProjectSkillProjection(projectRoot);+ if (untrackResult.kind === 'untracked') {+ console.warn(+ `[ok] Untracked the OpenKnowledge project skill (${untrackResult.dirs.join(', ')}) — it is now local-only. Teammates will see this as a deletion on their next pull.`,+ );+ }+const scope = await resolveMcpScope({scope: options.scope,mcp: options.mcp,diff --git a/packages/cli/src/commands/removal-plan.ts b/packages/cli/src/commands/removal-plan.tsindex 691f6d2dd..abbcc5551 100644--- a/packages/cli/src/commands/removal-plan.ts+++ b/packages/cli/src/commands/removal-plan.ts@@ -18,6 +18,7 @@import { existsSync, lstatSync, readdirSync, readFileSync, rmSync, unlinkSync } from 'node:fs';import { basename, join, relative, sep } from 'node:path';+import { PROJECT_SKILL_PROJECTION_IGNORE_PATHS } from '@inkeep/open-knowledge-core';import { atomicWriteFileSync } from '@inkeep/open-knowledge-core/server';// `resolveShadowDir` (resolves `<gitdir>/ok/`, worktree-aware; throws on a// malformed/inaccessible .git pointer) lives in the node:fs-importing subpath@@ -198,8 +199,16 @@ export function deinitOps(});// 5. Whole-remove the OK-owned dirs/files — everything in the artifact set- // EXCEPT the surgically-handled MCP configs + launch.json.- for (const rel of getOkArtifactPaths(projectRoot)) {+ // EXCEPT the surgically-handled MCP configs + launch.json, PLUS the+ // built-in `open-knowledge` project-skill projection. That projection was+ // carved OUT of `getOkArtifactPaths` (it is always git-ignored, never in+ // the sharing toggle), but it is still part of OK's footprint, so deinit+ // must sweep it here.+ const removeRelPaths = new Set<string>([+ ...getOkArtifactPaths(projectRoot),+ ...PROJECT_SKILL_PROJECTION_IGNORE_PATHS,+ ]);+ for (const rel of removeRelPaths) {const bare = rel.replace(/\/$/, '');if (mcpRelPaths.has(bare)) continue; // handled surgicallyif (bare === '.claude/launch.json') continue; // handled by launch-entrydiff --git a/packages/cli/src/commands/sharing/sharing.test.ts b/packages/cli/src/commands/sharing/sharing.test.tsindex 5ef00e4e5..0de3f2210 100644--- a/packages/cli/src/commands/sharing/sharing.test.ts+++ b/packages/cli/src/commands/sharing/sharing.test.ts@@ -90,8 +90,10 @@ describe('ok config-sharing unshare → share round-trip', () => {const exclude = readExclude(dir);expect(exclude).toContain('.ok/');expect(exclude).toContain('.mcp.json');- expect(exclude).toContain('.claude/skills/open-knowledge/');expect(exclude).toContain('.claude/launch.json');+ // The built-in project-skill projection is NEVER in the sharing toggle — it+ // is always excluded via the committed `.gitignore` block instead.+ expect(exclude).not.toContain('.claude/skills/open-knowledge/');expect(process.exitCode).not.toBe(1);});diff --git a/packages/cli/src/sharing/git-exclude.test.ts b/packages/cli/src/sharing/git-exclude.test.tsindex fe7713e7b..b9f428251 100644--- a/packages/cli/src/sharing/git-exclude.test.ts+++ b/packages/cli/src/sharing/git-exclude.test.ts@@ -48,7 +48,7 @@ describe('getOkArtifactPaths', () => {rmSync(dir, { recursive: true, force: true });});- it('returns the canonical fourteen-path artifact set when no config.yml exists', () => {+ it('returns the canonical eight-path artifact set (bundle projection carved out) when no config.yml exists', () => {const paths = getOkArtifactPaths(dir);expect(paths).toContain(`${OK_DIR}/`);expect(paths).toContain('.okignore');@@ -56,20 +56,20 @@ describe('getOkArtifactPaths', () => {expect(paths).toContain('.cursor/mcp.json');expect(paths).toContain('.codex/config.toml');expect(paths).toContain('opencode.json');- expect(paths).toContain('.claude/skills/open-knowledge/');- expect(paths).toContain('.cursor/skills/open-knowledge/');- expect(paths).toContain('.codex/skills/open-knowledge/');- expect(paths).toContain('.github/skills/open-knowledge/');- // OpenCode installs into its own `.opencode/skills/` (its own primary dir,- // not a shared `.agents/skills/` write), so it adds a distinct skill path on- // top of its `opencode.json` config.- expect(paths).toContain('.opencode/skills/open-knowledge/');// Pi has no MCP config — its project artifact is the managed bridge- // extension, plus its own `.pi/skills/` primary dir.+ // extension.expect(paths).toContain('.pi/extensions/open-knowledge.ts');- expect(paths).toContain('.pi/skills/open-knowledge/');expect(paths).toContain('.claude/launch.json');- expect(paths).toHaveLength(14);+ // OK's built-in `open-knowledge` project-skill projection is NOT in the+ // sharing-toggle set — it is always excluded via the committed `.gitignore`+ // block, regardless of sharing mode.+ expect(paths).not.toContain('.claude/skills/open-knowledge/');+ expect(paths).not.toContain('.cursor/skills/open-knowledge/');+ expect(paths).not.toContain('.codex/skills/open-knowledge/');+ expect(paths).not.toContain('.github/skills/open-knowledge/');+ expect(paths).not.toContain('.opencode/skills/open-knowledge/');+ expect(paths).not.toContain('.pi/skills/open-knowledge/');+ expect(paths).toHaveLength(8);});it('preserves a stable order so `ok config-sharing status` and unit-test snapshots are deterministic', () => {@@ -92,16 +92,17 @@ describe('getOkArtifactPaths', () => {expect(paths).not.toContain('docs/.ok/');expect(paths).not.toContain('docs/.okignore');expect(paths.some((p) => p.includes('**'))).toBe(false);- // content.dir must not inflate the set — same fourteen paths as the+ // content.dir must not inflate the set — same eight paths as the// no-config case, just never `<contentDir>`-prefixed.- expect(paths).toHaveLength(14);+ expect(paths).toHaveLength(8);});- it('excludes each installed skill projection per the OF3 marker (PRD-6934 C9 fix)', () => {- // The pre-fix set covered only the single hardcoded `open-knowledge`- // bundle, so authored + pack skills leaked in local-only mode. With an- // installed-skills marker present, every projection `.{host}/skills/<name>/`- // is excluded per the hosts it was installed to.+ it('excludes each AUTHORED skill projection per the marker, but never the built-in bundle', () => {+ // Authored + pack skills still follow the shared/local-only toggle. With an+ // installed-skills marker present, every authored projection+ // `.{host}/skills/<name>/` is excluded per the hosts it was installed to.+ // The reserved built-in `open-knowledge` bundle is NEVER added here — it is+ // always git-ignored via the committed `.gitignore` block instead.mkdirSync(join(dir, OK_DIR, 'local'), { recursive: true });writeFileSync(join(dir, OK_DIR, 'local', 'installed-skills.json'),@@ -122,6 +123,15 @@ describe('getOkArtifactPaths', () => {scripts: true,installedAt: '2026-06-05T00:00:00.000Z',},+ // A stray marker entry using the reserved name must be skipped, never+ // re-added to the toggle set.+ 'open-knowledge': {+ hosts: ['claude', 'cursor'],+ contentHash: 'ghi',+ scope: 'project',+ scripts: false,+ installedAt: '2026-06-05T00:00:00.000Z',+ },},}),'utf-8',@@ -131,15 +141,16 @@ describe('getOkArtifactPaths', () => {expect(paths).toContain('.cursor/skills/trip-log/');expect(paths).toContain('.github/skills/trip-log/');expect(paths).toContain('.codex/skills/fishing-pack/'); // codex → .codex- // The shipped bundle excludes remain alongside the authored ones.- expect(paths).toContain('.claude/skills/open-knowledge/');+ // The reserved built-in bundle is carved out in BOTH loops.+ expect(paths).not.toContain('.claude/skills/open-knowledge/');+ expect(paths).not.toContain('.cursor/skills/open-knowledge/');});- it('falls back to the bundle-only set when the marker is absent or corrupt', () => {+ it('falls back to the bundle-carved-out base set when the marker is absent or corrupt', () => {mkdirSync(join(dir, OK_DIR, 'local'), { recursive: true });writeFileSync(join(dir, OK_DIR, 'local', 'installed-skills.json'), '{ corrupt', 'utf-8');const paths = getOkArtifactPaths(dir);- expect(paths).toHaveLength(14); // corrupt marker → fail-soft, no per-skill paths+ expect(paths).toHaveLength(8); // corrupt marker → fail-soft, no per-skill paths});});diff --git a/packages/cli/src/sharing/git-exclude.ts b/packages/cli/src/sharing/git-exclude.tsindex 59d969034..623944f88 100644--- a/packages/cli/src/sharing/git-exclude.ts+++ b/packages/cli/src/sharing/git-exclude.ts@@ -30,6 +30,7 @@ import {INSTALLED_SKILLS_REL,OK_DIR,parseInstalledSkills,+ RESERVED_PROJECT_SKILL_NAME,} from '@inkeep/open-knowledge-core';// `resolveGitDirDetailed` is in the `node:fs`-importing subpath of core —// the barrel deliberately omits it to keep the main entry browser-safe@@ -93,11 +94,19 @@ export type SharingMode = 'shared' | 'local-only' | 'no-git';* - `.mcp.json` — Claude Code project MCP (merged file)* - `.cursor/mcp.json` — Cursor project MCP (merged file)* - `.codex/config.toml` — Codex project MCP (merged file)- * - `.claude/skills/open-knowledge/` — Claude project SKILL.md bundle (whole-tree)- * - `.cursor/skills/open-knowledge/` — Cursor project SKILL.md bundle (whole-tree)- * - `.codex/skills/open-knowledge/` — Codex project SKILL.md bundle (whole-tree)* - `.claude/launch.json` — Claude launcher entry (merged file)*+ * NOT here: OK's built-in `open-knowledge` project-skill projection+ * (`.{host}/skills/open-knowledge/`). That bundle is a LOCAL, per-machine+ * artifact — the app regenerates it on every open and different builds+ * version-stamp it differently — so it is ALWAYS git-excluded via a committed+ * `.gitignore` block (`ensureProjectSkillGitignore` in+ * `@inkeep/open-knowledge-server`), independent of this shared/local-only+ * toggle. Carving it OUT here is what makes the exclusion unconditional:+ * leaving it in would only hide it in local-only mode, and it must be hidden in+ * BOTH modes. Authored skills at `.{host}/skills/<other-name>/` stay in the+ * toggle (handled by the installed-skill marker loop below).+ ** `.ok/` and `.okignore` are emitted UNANCHORED (slash-free). gitignore* matches a slash-free pattern at every depth, so one entry each covers the* project-root `.ok/` (where `config.yml` lives — it is read from@@ -126,32 +135,28 @@ export function getOkArtifactPaths(projectRoot: string): readonly string[] {if (target.projectConfigPath) {paths.push(toProjectRelative(target.projectConfigPath(projectRoot), projectRoot));}- if (target.projectSkillPath) {- // The target points at `<dir>/SKILL.md`; exclude the whole bundle- // dir so future skill assets (manifest, scripts/, etc.) are covered- // by the same line. Equivalent to writing both `SKILL.md` and the- // dir separately, but cleaner in the exclude file.- const skillFile = toProjectRelative(target.projectSkillPath(projectRoot), projectRoot);- paths.push(`${dirnamePosix(skillFile)}/`);- }+ // `target.projectSkillPath` (the built-in `open-knowledge` bundle+ // projection) is deliberately NOT excluded here — it is ALWAYS git-ignored+ // via the committed `.gitignore` block, not this per-machine toggle. See+ // the doc comment above.}paths.push(CLAUDE_LAUNCH_JSON);- // The loop above only excludes the single- // hardcoded `open-knowledge` bundle per editor — authored skills- // (`.{host}/skills/<name>/`) and pack skills would still leak in- // local-only mode. Enumerate the installed-skill set and- // exclude each skill's projection per the hosts it was installed to. A- // blanket `skills/` exclude would over-reach into hand-placed non-OK- // skills, so this is installed-skill-set-aware (only OK-managed- // projections). When no marker exists (nothing installed on this machine),- // only the bundle excludes apply.+ // Authored skills (`.{host}/skills/<name>/`) and pack skills DO follow the+ // shared/local-only toggle. Enumerate the installed-skill set and exclude+ // each skill's projection per the hosts it was installed to. A blanket+ // `skills/` exclude would over-reach into hand-placed non-OK skills, so this+ // is installed-skill-set-aware (only OK-managed projections). The reserved+ // built-in `open-knowledge` bundle is skipped — it is always git-ignored via+ // the committed `.gitignore` block, never this toggle (see doc comment+ // above). When no marker exists, only `.ok/` + config excludes apply.const markerPath = join(projectRoot, ...INSTALLED_SKILLS_REL);if (existsSync(markerPath)) {try {const marker = parseInstalledSkills(readFileSync(markerPath, 'utf-8'));if (marker) {for (const [name, entry] of Object.entries(marker.skills)) {+ if (name === RESERVED_PROJECT_SKILL_NAME) continue;for (const host of entry.hosts) {const root = EDITOR_PROJECT_SKILL_ROOT[host as EditorId];if (root) paths.push(`${root}/${name}/`);@@ -561,13 +566,3 @@ function toProjectRelative(absPath: string, projectRoot: string): string {function toPosix(p: string): string {return sep === '/' ? p : p.split(sep).join('/');}--/**- * Directory-of, POSIX semantics. `dirname('foo/bar')` is `'foo'`. Used to- * shorten an editor's `projectSkillPath` (a file path ending in- * `SKILL.md`) into the bundle dir we exclude as a whole tree.- */-function dirnamePosix(p: string): string {- const ix = p.lastIndexOf('/');- return ix < 0 ? '.' : p.slice(0, ix);-}diff --git a/packages/core/src/constants/editors.ts b/packages/core/src/constants/editors.tsindex 3ac23edfc..6f60f2cf3 100644--- a/packages/core/src/constants/editors.ts+++ b/packages/core/src/constants/editors.ts@@ -127,6 +127,38 @@ export const PROJECT_SKILL_EDITOR_IDS = ALL_EDITOR_IDS.filter((id) => EDITOR_PROJECT_SKILL_ROOT[id] !== null,);+/**+ * Reserved name of OpenKnowledge's built-in project-skill bundle — the ONE skill+ * OK ships and re-projects into every wired editor's host dir on every project+ * open (`.{host}/skills/open-knowledge/`). Mirrors `BUNDLE_SKILL_NAME.project`+ * (and `SHIPPED_SKILL_NAME`) in `@inkeep/open-knowledge-server`; duplicated here+ * because core cannot depend on server, and pinned in lock-step by a server-side+ * test. Authored / pack skills take other names — the reserved `open-knowledge*`+ * prefix keeps them from shadowing this bundle.+ */+export const RESERVED_PROJECT_SKILL_NAME = 'open-knowledge';++/**+ * Per-editor host-dir paths OK re-projects its built-in `open-knowledge` bundle+ * into (`.{host}/skills/open-knowledge/`) — POSIX, trailing slash, derived from+ * `EDITOR_PROJECT_SKILL_ROOT` so a new project-skill editor flows here+ * automatically.+ *+ * This projection is a LOCAL, per-machine artifact: the app regenerates it on+ * every open, and different builds version-stamp its frontmatter differently, so+ * committing it to git makes teammates collide under auto-sync (recurring merge+ * conflicts / "external-changes-pending"). These paths are therefore ALWAYS+ * git-excluded via a committed `.gitignore` block (`ensureProjectSkillGitignore`),+ * independent of the OK shared/local-only sharing toggle. Authored skills at+ * `.{host}/skills/<other-name>/` are NOT here — they still follow the toggle.+ */+export const PROJECT_SKILL_PROJECTION_IGNORE_PATHS: readonly string[] = ALL_EDITOR_IDS.flatMap(+ (id) => {+ const root = EDITOR_PROJECT_SKILL_ROOT[id];+ return root === null ? [] : [`${root}/${RESERVED_PROJECT_SKILL_NAME}/`];+ },+);+/*** Editors that keep a `~/.<host>/skills/<name>/` (and `<projectDir>/.<host>/skills/`)* layout — the single source for the CLI `repair-skills` + desktop `skill-reclaim`diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 942c519df..f810625d2 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -210,6 +210,8 @@ export {type EditorId,HOSTS_WITH_USER_SKILL_DIR,PROJECT_SKILL_EDITOR_IDS,+ PROJECT_SKILL_PROJECTION_IGNORE_PATHS,+ RESERVED_PROJECT_SKILL_NAME,} from './constants/editors.ts';export {detectEmbeddedHostFromBrowser,diff --git a/packages/desktop/src/main/create-new-project.test.ts b/packages/desktop/src/main/create-new-project.test.tsindex 20aa5b86a..96b8f9bd5 100644--- a/packages/desktop/src/main/create-new-project.test.ts+++ b/packages/desktop/src/main/create-new-project.test.ts@@ -291,9 +291,15 @@ describe('runCreateNew — git-root promotion', () => {expect(cfg).not.toMatch(/^\s*dir:\s*notes\/MyProj/m);// Promotion lands on a pre-existing `.git/` (the enclosing repo).- // ensureProjectGit reports didInit=false → seed helper does NOT run,- // and any `.gitignore` the enclosing repo owns is left alone.- expect(existsSync(resolve(repo, '.gitignore'))).toBe(false);+ // ensureProjectGit reports didInit=false → the `.DS_Store` seed helper does+ // NOT run. But the always-excluded project-skill `.gitignore` block IS+ // written (append-only) regardless, so the per-build bundle can never be+ // committed.+ const gi = resolve(repo, '.gitignore');+ expect(existsSync(gi)).toBe(true);+ const giBody = readFileSync(gi, 'utf8');+ expect(giBody).toContain('.claude/skills/open-knowledge/');+ expect(giBody).not.toContain('.DS_Store'); // the DS_Store seed stayed gated});test('no promotion when parent has no enclosing git repo — projectDir === target, content.dir === "."', async () => {diff --git a/packages/desktop/src/main/create-new-project.ts b/packages/desktop/src/main/create-new-project.tsindex 40c270c6a..f4d8ffc89 100644--- a/packages/desktop/src/main/create-new-project.ts+++ b/packages/desktop/src/main/create-new-project.ts@@ -31,6 +31,7 @@ import {coercePackId,type EnsureProjectGitResult,ensureProjectGit,+ ensureProjectSkillGitignore,findEnclosingProjectRoot,initContent,planSeed,@@ -439,6 +440,19 @@ export async function runCreateNew(// throws; per-(editor × integration) failures land in `integrations`.const aiIntegrations = writeProjectAiIntegrations(projectDir, [...editors]);+ // 8b. Always exclude OK's built-in project-skill projection via the committed+ // `.gitignore` (independent of the sharing toggle below) so the+ // per-machine, per-build bundle can never be committed. Non-fatal — a+ // seed failure leaves a valid project. Nothing is tracked yet on a fresh+ // create, so no untrack migration is needed here.+ try {+ ensureProjectSkillGitignore(projectDir);+ } catch (err) {+ console.warn(+ `[create-new-project] skipping project-skill .gitignore entry at ${projectDir}: ${err instanceof Error ? err.message : String(err)}`,+ );+ }+// 9. Sharing-mode transition.// Mirrors the consent-dialog flow in main/index.ts — same single// `addOkPathsToGitExclude` site. A fresh `runCreateNew` cannotdiff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 67f822ca3..1cf6cae9a 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -83,6 +83,7 @@ import {createEphemeralProjectDir,discoverLockDirs,ensureProjectGit,+ ensureProjectSkillGitignore,findEnclosingGitRoot,findEnclosingProjectRoot,getLocalDir,@@ -99,6 +100,7 @@ import {resolveBundledSkillDir,resolveLockDir,USER_GLOBAL_BUNDLE_IDS,+ untrackTrackedProjectSkillProjection,withSpan,writeBundleDecision,writeTargetVersion,@@ -1790,6 +1792,16 @@ async function openProject(aiIntegrationsFailedCount = logAiIntegrationOutcomes(writeProjectAiIntegrations(discovery.projectDir, [...request.editorIds]),);+ // Always exclude OK's built-in project-skill projection via the committed+ // `.gitignore` (independent of the sharing toggle below) so the per-machine,+ // per-build bundle can never be committed. Non-fatal.+ try {+ ensureProjectSkillGitignore(discovery.projectDir);+ } catch (err) {+ console.warn(+ `[onboarding] skipping project-skill .gitignore entry at ${discovery.projectDir}: ${err instanceof Error ? err.message : String(err)}`,+ );+ }// Sharing-mode transition. Runs AFTER every artifact-// writing step so the tracked-files probe inside// `addOkPathsToGitExclude` sees the latest on-disk shape. On a tracked-@@ -1859,6 +1871,38 @@ async function openProject(err: err instanceof Error ? err.message : String(err),});});++ // Heal the git posture of OK's built-in project-skill projection for an+ // existing (managed) repo: (1) ensure the committed `.gitignore` entry so a+ // repo created before this rule gets it, and (2) untrack the projection if+ // it is already tracked upstream — the fix for the recurring-conflict bug+ // where teammates on different app builds restamp the bundle's version+ // line. The untrack is a fire-and-forget dedicated commit that races safely+ // with auto-sync (see `untrackTrackedProjectSkillProjection`); it is a+ // no-op once HEAD no longer tracks the bundle.+ try {+ ensureProjectSkillGitignore(resolvedProjectDir);+ } catch (err) {+ console.warn('[main] project-skill .gitignore ensure failed', {+ err: err instanceof Error ? err.message : String(err),+ });+ }+ void untrackTrackedProjectSkillProjection(resolvedProjectDir)+ .then((result) => {+ if (result.kind === 'untracked') {+ getLogger('project').info(+ { dirs: result.dirs, commitSha: result.commitSha },+ 'untracked OpenKnowledge project-skill projection (now local-only)',+ );+ } else if (result.kind === 'failed') {+ console.warn('[main] project-skill untrack failed', { err: result.error });+ }+ })+ .catch((err) => {+ console.warn('[main] project-skill untrack threw', {+ err: err instanceof Error ? err.message : String(err),+ });+ });}// Emit one onboarding-consent span per completed flow. SDK disabled → no-op.diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex f83ea9503..1fed1fc11 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -213,6 +213,7 @@ export {type BuildConfigYmlOptions,buildConfigYmlContent,CONFIG_FILENAME,+ ensureProjectSkillGitignore,type InitContentOptions,type InitContentResult,initContent,@@ -363,6 +364,11 @@ export {ensureProjectGit,ProjectGitInitError,} from './project-git.ts';+export {+ type UntrackProjectSkillResult,+ type UntrackSkipReason,+ untrackTrackedProjectSkillProjection,+} from './project-skill-git.ts';export {type BlockConflict,CONFLICT_MARKER_RE,diff --git a/packages/server/src/init-project.test.ts b/packages/server/src/init-project.test.tsindex 5dca65452..8bca3f6e5 100644--- a/packages/server/src/init-project.test.ts+++ b/packages/server/src/init-project.test.ts@@ -10,9 +10,14 @@ import {} from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join, resolve } from 'node:path';-import { OK_DIR } from '@inkeep/open-knowledge-core';+import {+ OK_DIR,+ PROJECT_SKILL_PROJECTION_IGNORE_PATHS,+ RESERVED_PROJECT_SKILL_NAME,+} from '@inkeep/open-knowledge-core';import {buildConfigYmlContent,+ ensureProjectSkillGitignore,initContent,OK_OKIGNORE_TEMPLATE,packageVersionMajorMinor,@@ -432,3 +437,64 @@ describe('buildConfigYmlContent', () => {expect(out).not.toContain('~/.ok/config.yml');});});++describe('ensureProjectSkillGitignore', () => {+ let testDir: string;++ beforeEach(() => {+ testDir = resolve(+ tmpdir(),+ `skill-gitignore-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,+ );+ mkdirSync(testDir, { recursive: true });+ });++ afterEach(() => {+ rmSync(testDir, { recursive: true, force: true });+ });++ it('creates a `.gitignore` with every editor-host projection path when absent', () => {+ expect(ensureProjectSkillGitignore(testDir)).toBe('created');+ const body = readFileSync(join(testDir, '.gitignore'), 'utf-8');+ for (const p of PROJECT_SKILL_PROJECTION_IGNORE_PATHS) {+ expect(body).toContain(p);+ }+ // Covers all editor host roots, not just claude.+ expect(body).toContain('.claude/skills/open-knowledge/');+ expect(body).toContain('.cursor/skills/open-knowledge/');+ expect(body).toContain('.codex/skills/open-knowledge/');+ expect(body).toContain('.github/skills/open-knowledge/');+ expect(body).toContain('.opencode/skills/open-knowledge/');+ expect(body).toContain('.pi/skills/open-knowledge/');+ });++ it('appends only the missing projection lines to an existing `.gitignore`, preserving user lines', () => {+ writeFileSync(join(testDir, '.gitignore'), '# user rules\nnode_modules/\n.DS_Store\n', 'utf-8');+ expect(ensureProjectSkillGitignore(testDir)).toBe('updated');+ const body = readFileSync(join(testDir, '.gitignore'), 'utf-8');+ expect(body).toContain('# user rules');+ expect(body).toContain('node_modules/');+ expect(body).toContain('.DS_Store');+ expect(body).toContain('.claude/skills/open-knowledge/');+ });++ it('is idempotent — a second call reports `unchanged` and does not duplicate lines', () => {+ ensureProjectSkillGitignore(testDir);+ expect(ensureProjectSkillGitignore(testDir)).toBe('unchanged');+ const body = readFileSync(join(testDir, '.gitignore'), 'utf-8');+ const occurrences = body.split('.claude/skills/open-knowledge/').length - 1;+ expect(occurrences).toBe(1);+ });++ it('is skill-name-scoped — it never blanket-excludes `.{host}/skills/`', () => {+ ensureProjectSkillGitignore(testDir);+ const body = readFileSync(join(testDir, '.gitignore'), 'utf-8');+ // Every emitted line is the reserved-name bundle dir, never a bare+ // `.{host}/skills/` that would catch authored skills too.+ for (const line of body.split('\n').filter((l) => l.trim() && !l.startsWith('#'))) {+ expect(line).toContain(`/${RESERVED_PROJECT_SKILL_NAME}/`);+ }+ expect(body).not.toContain('.claude/skills/\n');+ expect(body).not.toContain('.cursor/skills/\n');+ });+});diff --git a/packages/server/src/init-project.ts b/packages/server/src/init-project.tsindex 55db784d6..34a1f27ff 100644--- a/packages/server/src/init-project.ts+++ b/packages/server/src/init-project.ts@@ -15,7 +15,12 @@import { existsSync, lstatSync, readFileSync } from 'node:fs';import { join, resolve } from 'node:path';-import { CONFIG_SCHEMA_MAJOR_PATH, LOCAL_DIR, OK_DIR } from '@inkeep/open-knowledge-core';+import {+ CONFIG_SCHEMA_MAJOR_PATH,+ LOCAL_DIR,+ OK_DIR,+ PROJECT_SKILL_PROJECTION_IGNORE_PATHS,+} from '@inkeep/open-knowledge-core';import { tracedMkdirSync, tracedWriteFileSync } from './fs-traced.ts';/**@@ -194,8 +199,9 @@ function writeIfMissing(filePath: string, content: string, label: string): boolefunction ensureGitignoreEntries(filePath: string,scaffoldContent: string,+ label = '.ok/.gitignore',): 'created' | 'updated' | 'unchanged' {- assertNotSymlink(filePath, '.ok/.gitignore');+ assertNotSymlink(filePath, label);if (!existsSync(filePath)) {tracedWriteFileSync(filePath, scaffoldContent, 'utf-8');return 'created';@@ -405,3 +411,45 @@ export function writeRootGitignoreForNewRepo(projectDir: string): 'created' | 's? 'created': 'skipped';}++/**+ * The committed `.gitignore` block that always excludes OK's built-in+ * `open-knowledge` project-skill projection (`.{host}/skills/open-knowledge/`)+ * from git. Header comment plus one line per editor host dir, derived from the+ * single core source `PROJECT_SKILL_PROJECTION_IGNORE_PATHS`.+ *+ * Unlike the OK config sharing toggle (which lives in the per-machine+ * `.git/info/exclude`), this block goes in the COMMITTED project-root+ * `.gitignore` so it travels to every clone. That is what makes it race-free: a+ * fresh clone that runs `git add .` before ever opening the project in OK+ * already has the rule, so the regenerated, version-stamped projection can never+ * be staged.+ */+const PROJECT_SKILL_GITIGNORE_BLOCK = `# OpenKnowledge regenerates its built-in project skill on every open, and+# different app builds version-stamp it differently. It is a per-machine+# artifact — keep it out of git so teammates don't collide under auto-sync.+${PROJECT_SKILL_PROJECTION_IGNORE_PATHS.join('\n')}+`;++/**+ * Ensure the project-root `.gitignore` excludes OK's built-in project-skill+ * projection. Append-if-missing: creates the file when absent, otherwise appends+ * only the lines not already present (preserving every user line). Idempotent+ * and symlink-guarded.+ *+ * Called on EVERY `ok init` / desktop project setup / open — not just fresh+ * `git init` — because a project may have been created before this rule existed+ * or opened inside a pre-existing repo. `writeRootGitignoreForNewRepo` (the+ * `.DS_Store` seed) is fresh-repo-only and user-territory; this block is a+ * correctness requirement, so it runs unconditionally and merges into whatever+ * `.gitignore` already exists.+ */+export function ensureProjectSkillGitignore(+ projectDir: string,+): 'created' | 'updated' | 'unchanged' {+ return ensureGitignoreEntries(+ join(projectDir, '.gitignore'),+ PROJECT_SKILL_GITIGNORE_BLOCK,+ '.gitignore',+ );+}diff --git a/packages/server/src/project-skill-git.test.ts b/packages/server/src/project-skill-git.test.tsnew file mode 100644index 000000000..5c5f5b08b--- /dev/null+++ b/packages/server/src/project-skill-git.test.ts@@ -0,0 +1,172 @@+import { afterEach, beforeEach, describe, expect, it } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { ensureProjectSkillGitignore } from './init-project.ts';+import { untrackTrackedProjectSkillProjection } from './project-skill-git.ts';++function uniqueDir(prefix: string): string {+ return resolve(tmpdir(), `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2)}`);+}++function git(dir: string, ...args: string[]): string {+ return execFileSync('git', args, {+ cwd: dir,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'ignore'],+ });+}++function initRepo(dir: string): void {+ mkdirSync(dir, { recursive: true });+ git(dir, 'init', '--initial-branch=main');+ git(dir, 'config', 'user.email', '[email protected]');+ git(dir, 'config', 'user.name', 'Test User');+}++/** Write + git-add + commit a projected skill's SKILL.md. */+function trackSkill(dir: string, hostRel: string, skillName: string, body: string): void {+ const rel = join(hostRel, 'skills', skillName, 'SKILL.md');+ const abs = join(dir, rel);+ mkdirSync(join(abs, '..'), { recursive: true });+ writeFileSync(abs, body, 'utf-8');+ git(dir, 'add', '--', rel);+}++function tracked(dir: string, pathspec: string): boolean {+ return git(dir, 'ls-files', '--', pathspec).trim().length > 0;+}++describe('untrackTrackedProjectSkillProjection', () => {+ let dir: string;+ beforeEach(() => {+ dir = uniqueDir('untrack-skill-test');+ });+ afterEach(() => {+ rmSync(dir, { recursive: true, force: true });+ });++ it('untracks an already-tracked built-in projection and advances HEAD, keeping the working file', async () => {+ initRepo(dir);+ trackSkill(dir, '.claude', 'open-knowledge', '---\nmetadata:\n version: 1.0.0\n---\nbody\n');+ git(dir, 'commit', '-m', 'seed');+ const headBefore = git(dir, 'rev-parse', 'HEAD').trim();+ expect(tracked(dir, '.claude/skills/open-knowledge/')).toBe(true);++ const result = await untrackTrackedProjectSkillProjection(dir);++ expect(result.kind).toBe('untracked');+ if (result.kind !== 'untracked') throw new Error('unreachable');+ expect(result.dirs).toContain('.claude/skills/open-knowledge');+ // Removed from the tree — no longer tracked.+ expect(tracked(dir, '.claude/skills/open-knowledge/')).toBe(false);+ // Working file remains so the app self-heals on next open.+ expect(existsSync(join(dir, '.claude/skills/open-knowledge/SKILL.md'))).toBe(true);+ // HEAD advanced by exactly one commit whose parent is the old HEAD.+ const headAfter = git(dir, 'rev-parse', 'HEAD').trim();+ expect(headAfter).not.toBe(headBefore);+ expect(git(dir, 'rev-parse', 'HEAD^').trim()).toBe(headBefore);+ // Real index was reset to the new HEAD — no phantom STAGED addition of the+ // now-untracked file (without a `.gitignore` here git reports the working+ // file as merely untracked `??`, which is expected; a stale index would+ // instead show it staged).+ expect(git(dir, 'diff', '--cached', '--name-only').trim()).toBe('');+ });++ it('untracks every editor-host projection at once', async () => {+ initRepo(dir);+ trackSkill(dir, '.claude', 'open-knowledge', 'a\n');+ trackSkill(dir, '.cursor', 'open-knowledge', 'b\n');+ trackSkill(dir, '.codex', 'open-knowledge', 'c\n');+ git(dir, 'commit', '-m', 'seed');++ const result = await untrackTrackedProjectSkillProjection(dir);++ expect(result.kind).toBe('untracked');+ expect(tracked(dir, '.claude/skills/open-knowledge/')).toBe(false);+ expect(tracked(dir, '.cursor/skills/open-knowledge/')).toBe(false);+ expect(tracked(dir, '.codex/skills/open-knowledge/')).toBe(false);+ });++ it('is skill-name-scoped — an authored skill at `.{host}/skills/<other>/` is NOT untracked', async () => {+ initRepo(dir);+ trackSkill(dir, '.claude', 'open-knowledge', 'bundle\n');+ trackSkill(dir, '.claude', 'my-authored-skill', 'authored\n');+ git(dir, 'commit', '-m', 'seed');++ const result = await untrackTrackedProjectSkillProjection(dir);++ expect(result.kind).toBe('untracked');+ // Reserved bundle removed…+ expect(tracked(dir, '.claude/skills/open-knowledge/')).toBe(false);+ // …authored skill preserved.+ expect(tracked(dir, '.claude/skills/my-authored-skill/')).toBe(true);+ });++ it('is idempotent — a second call is a no-op once HEAD no longer tracks the bundle', async () => {+ initRepo(dir);+ trackSkill(dir, '.claude', 'open-knowledge', 'x\n');+ git(dir, 'commit', '-m', 'seed');++ expect((await untrackTrackedProjectSkillProjection(dir)).kind).toBe('untracked');+ const headAfterFirst = git(dir, 'rev-parse', 'HEAD').trim();+ expect((await untrackTrackedProjectSkillProjection(dir)).kind).toBe('nothing-tracked');+ // No second commit created.+ expect(git(dir, 'rev-parse', 'HEAD').trim()).toBe(headAfterFirst);+ });++ it('combined with ensureProjectSkillGitignore, leaves the regenerated file ignored + clean', async () => {+ initRepo(dir);+ trackSkill(dir, '.claude', 'open-knowledge', 'x\n');+ git(dir, 'commit', '-m', 'seed');++ ensureProjectSkillGitignore(dir);+ git(dir, 'add', '--', '.gitignore');+ git(dir, 'commit', '-m', 'gitignore');+ await untrackTrackedProjectSkillProjection(dir);++ // The still-present working file is now ignored, so a full `git status`+ // is clean — no restamp can ever be staged again.+ expect(git(dir, 'status', '--porcelain').trim()).toBe('');+ expect(git(dir, 'check-ignore', '--', '.claude/skills/open-knowledge/SKILL.md').trim()).toBe(+ '.claude/skills/open-knowledge/SKILL.md',+ );+ });++ it('returns nothing-tracked when the projection is untracked', async () => {+ initRepo(dir);+ writeFileSync(join(dir, 'README.md'), '# r\n', 'utf-8');+ git(dir, 'add', '--', 'README.md');+ git(dir, 'commit', '-m', 'init');+ expect((await untrackTrackedProjectSkillProjection(dir)).kind).toBe('nothing-tracked');+ });++ it('skips (no-git) a non-git directory', async () => {+ mkdirSync(dir, { recursive: true });+ const result = await untrackTrackedProjectSkillProjection(dir);+ expect(result).toEqual({ kind: 'skipped', reason: 'no-git' });+ });++ it('skips (detached-head) when HEAD is detached', async () => {+ initRepo(dir);+ trackSkill(dir, '.claude', 'open-knowledge', 'x\n');+ git(dir, 'commit', '-m', 'seed');+ const sha = git(dir, 'rev-parse', 'HEAD').trim();+ git(dir, 'checkout', '--detach', sha);+ const result = await untrackTrackedProjectSkillProjection(dir);+ expect(result).toEqual({ kind: 'skipped', reason: 'detached-head' });+ // Left tracked — nothing committed on a detached HEAD.+ expect(tracked(dir, '.claude/skills/open-knowledge/')).toBe(true);+ });++ it('skips (operation-in-progress) when a merge is mid-flight', async () => {+ initRepo(dir);+ trackSkill(dir, '.claude', 'open-knowledge', 'x\n');+ git(dir, 'commit', '-m', 'seed');+ // Fabricate an in-progress merge marker.+ writeFileSync(join(dir, '.git', 'MERGE_HEAD'), `${git(dir, 'rev-parse', 'HEAD').trim()}\n`);+ const result = await untrackTrackedProjectSkillProjection(dir);+ expect(result).toEqual({ kind: 'skipped', reason: 'operation-in-progress' });+ });+});diff --git a/packages/server/src/project-skill-git.ts b/packages/server/src/project-skill-git.tsnew file mode 100644index 000000000..17d958d70--- /dev/null+++ b/packages/server/src/project-skill-git.ts@@ -0,0 +1,246 @@+/**+ * Migration + reconcile for OK's built-in `open-knowledge` project-skill+ * projection (`.{host}/skills/open-knowledge/`).+ *+ * Two concerns, both driven from the on-open / project-setup paths (CLI+ * `ok init`, desktop create-new + on-open):+ *+ * 1. `ensureProjectSkillGitignore` (in `init-project.ts`) writes the committed+ * `.gitignore` block so the projection is ALWAYS excluded for fresh clones.+ * 2. `untrackTrackedProjectSkillProjection` (here) heals repos where the+ * projection is ALREADY tracked upstream: it removes the bundle from git's+ * tree so it stops causing merge conflicts / "external-changes-pending"+ * when teammates on different app builds restamp its version line.+ *+ * Why a dedicated commit rather than a bare `git rm --cached`: OK's auto-sync+ * push builds its commit from HEAD's tree in an ISOLATED index (it never reads+ * the real index) and only stages content-dir files. A `git rm --cached` left+ * in the real index is therefore invisible to auto-sync — HEAD keeps the+ * projection forever. To actually untrack it we have to advance HEAD to a tree+ * that lacks the projection; auto-sync then carries that new HEAD forward (its+ * `read-tree HEAD` no longer sees the bundle) and pushes it on the normal+ * "local ahead of origin" path.+ *+ * The untrack uses the SAME proven, side-effect-free pattern as auto-sync's push+ * (`sync-engine.ts` doPushCycle): an isolated `GIT_INDEX_FILE`, `read-tree HEAD`,+ * `rm --cached` against that isolated index, `write-tree`, `commit-tree -p HEAD`,+ * then a compare-and-swap `update-ref`. It never touches the user's real index+ * or working tree destructively, never sweeps unrelated staged changes into the+ * commit, and races safely with a concurrent auto-sync push (both take+ * `withParentLock`; the CAS `update-ref` makes the loser abort and retry). It+ * does NOT push — auto-sync (or the user) carries HEAD to origin.+ *+ * The projection working file is left on disk (it is now git-ignored and the app+ * regenerates it on the next open), so the migration self-heals. The+ * teammate-visible deletion on their next pull is the accepted trade-off.+ */++import { existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ PROJECT_SKILL_PROJECTION_IGNORE_PATHS,+ RESERVED_PROJECT_SKILL_NAME,+} from '@inkeep/open-knowledge-core';+import { resolveGitDir } from '@inkeep/open-knowledge-core/shadow-repo-layout';+import { applyGitEnv, createGitInstance, type GitHandle, withParentLock } from './git-handle.ts';+import { resolveGitIdentity } from './git-identity.ts';+import { getLogger } from './logger.ts';++const log = getLogger('project-skill-git');++/** 40-hex validation for a commit SHA returned by `commit-tree`. */+const SHA_HEX_40 = /^[0-9a-f]{40}$/;++/** Projection dirs without the gitignore trailing slash — the form `git` wants. */+const PROJECTION_DIRS = PROJECT_SKILL_PROJECTION_IGNORE_PATHS.map((p) => p.replace(/\/$/, ''));++export type UntrackSkipReason =+ | 'no-git'+ | 'unborn-head'+ | 'detached-head'+ | 'operation-in-progress'+ | 'ref-race';++export type UntrackProjectSkillResult =+ | { kind: 'nothing-tracked' }+ | { kind: 'untracked'; dirs: string[]; commitSha: string }+ | { kind: 'skipped'; reason: UntrackSkipReason }+ | { kind: 'failed'; error: string };++/**+ * Untrack the built-in project-skill projection when it is tracked upstream.+ * Best-effort and idempotent: once HEAD no longer tracks the bundle a later+ * call sees `nothing-tracked` and no-ops. Never throws — failures resolve to a+ * typed `failed` / `skipped` result the caller can log.+ */+export async function untrackTrackedProjectSkillProjection(+ projectDir: string,+): Promise<UntrackProjectSkillResult> {+ const gitDir = resolveGitDir(projectDir);+ if (gitDir === null) return { kind: 'skipped', reason: 'no-git' };++ // An in-progress merge / rebase owns the index and HEAD; never inject a+ // migration commit into that state. Re-attempted on a later clean open.+ if (isOperationInProgress(gitDir)) {+ return { kind: 'skipped', reason: 'operation-in-progress' };+ }++ const handle = createGitInstance(projectDir);++ const trackedDirs = await listTrackedProjectionDirs(handle);+ if (trackedDirs.length === 0) return { kind: 'nothing-tracked' };++ try {+ return await withParentLock(async () => {+ // Re-read state INSIDE the lock so a concurrent auto-sync commit that+ // landed between detection and here is reflected in `headSha`.+ const branch = await currentBranch(handle);+ if (branch === null) return { kind: 'skipped', reason: 'detached-head' };+ const headSha = await revparseHead(handle);+ if (headSha === null) return { kind: 'skipped', reason: 'unborn-head' };++ // Re-list under the lock — the winning writer of a race may have already+ // untracked the projection.+ const dirsNow = await listTrackedProjectionDirs(handle);+ if (dirsNow.length === 0) return { kind: 'nothing-tracked' };++ const tmpIndex = join(tmpdir(), `ok-untrack-idx-${process.pid}-${Date.now()}.idx`);+ const iso = createGitInstance(projectDir, { gitIndexFile: tmpIndex });++ // Seed the isolated index from HEAD, drop the projection dirs, write the+ // reduced tree. `--ignore-unmatch` tolerates a dir that vanished from the+ // tree between the two ls-files calls.+ await iso.git.raw(['read-tree', headSha]);+ await iso.git.raw(['rm', '--cached', '-r', '--ignore-unmatch', '--', ...dirsNow]);+ const newTree = (await iso.git.raw(['write-tree'])).trim();+ const headTree = await revparseTree(handle, headSha);+ if (headTree !== null && headTree === newTree) {+ // Nothing actually changed (the projection wasn't in HEAD's tree after+ // all). Leave HEAD untouched.+ return { kind: 'nothing-tracked' };+ }++ const identity = await resolveGitIdentity(projectDir);+ const authorName = identity?.name ?? 'OpenKnowledge';+ const authorEmail = identity?.email ?? '[email protected]';+ applyGitEnv(iso, {+ GIT_AUTHOR_NAME: authorName,+ GIT_AUTHOR_EMAIL: authorEmail,+ GIT_COMMITTER_NAME: authorName,+ GIT_COMMITTER_EMAIL: authorEmail,+ });++ const message = `Stop tracking the OpenKnowledge project skill\n\nThe \`${RESERVED_PROJECT_SKILL_NAME}\` skill is regenerated per machine and version-stamped per app build, so tracking it causes recurring sync conflicts. It is now git-ignored.`;+ const newCommit = (+ await iso.git.raw(['commit-tree', newTree, '-p', headSha, '-m', message])+ ).trim();+ if (!SHA_HEX_40.test(newCommit)) {+ log.warn({ raw: newCommit }, 'commit-tree returned invalid SHA — aborting untrack');+ return { kind: 'failed', error: 'commit-tree returned invalid SHA' };+ }++ // Compare-and-swap: only advance the branch if HEAD is still `headSha`.+ // A concurrent push that moved HEAD makes this fail; we abort and let the+ // next open retry rather than clobber the other writer's commit.+ try {+ await handle.git.raw(['update-ref', `refs/heads/${branch}`, newCommit, headSha]);+ } catch (err) {+ log.info(+ { branch, err: errText(err) },+ 'update-ref CAS failed — ref moved, retry next open',+ );+ return { kind: 'skipped', reason: 'ref-race' };+ }++ // Sync the real index to the new HEAD for the untracked paths so+ // `git status` doesn't report them as phantom staged additions (the real+ // index still held the old HEAD's entries). Best-effort — the working+ // files are git-ignored, so a stale index entry is cosmetic, not+ // corrupting.+ try {+ await handle.git.raw(['reset', '-q', newCommit, '--', ...dirsNow]);+ } catch (err) {+ log.info({ err: errText(err) }, 'real-index reset after untrack failed (cosmetic)');+ }++ log.info({ dirs: dirsNow, commitSha: newCommit }, 'untracked project-skill projection');+ return { kind: 'untracked', dirs: dirsNow, commitSha: newCommit };+ });+ } catch (err) {+ return { kind: 'failed', error: errText(err) };+ }+}++// ---------------------------------------------------------------------------+// Internal helpers+// ---------------------------------------------------------------------------++/**+ * The subset of the projection dirs that currently have at least one tracked+ * file in the index. `git ls-files -- <dir>` lists tracked files under a+ * directory pathspec; a non-empty result means the dir is tracked.+ */+async function listTrackedProjectionDirs(handle: GitHandle): Promise<string[]> {+ const tracked: string[] = [];+ for (const dir of PROJECTION_DIRS) {+ let out = '';+ try {+ out = (await handle.git.raw(['ls-files', '--', dir])).trim();+ } catch {+ // `ls-files` fails on a non-git dir or an unborn repo with no index; treat+ // as "not tracked" — the higher-level guards handle those states.+ out = '';+ }+ if (out.length > 0) tracked.push(dir);+ }+ return tracked;+}++/** Current branch name, or `null` when HEAD is detached / unresolvable. */+async function currentBranch(handle: GitHandle): Promise<string | null> {+ try {+ const b = (await handle.git.raw(['rev-parse', '--abbrev-ref', 'HEAD'])).trim();+ return b.length === 0 || b === 'HEAD' ? null : b;+ } catch {+ return null;+ }+}++/** HEAD commit SHA, or `null` when the repo has no commits yet. */+async function revparseHead(handle: GitHandle): Promise<string | null> {+ try {+ const sha = (await handle.git.raw(['rev-parse', '--verify', 'HEAD'])).trim();+ return SHA_HEX_40.test(sha) ? sha : null;+ } catch {+ return null;+ }+}++/** The tree SHA of a commit, or `null` when it can't be resolved. */+async function revparseTree(handle: GitHandle, commitSha: string): Promise<string | null> {+ try {+ const tree = (await handle.git.raw(['rev-parse', `${commitSha}^{tree}`])).trim();+ return SHA_HEX_40.test(tree) ? tree : null;+ } catch {+ return null;+ }+}++/**+ * True when a merge or rebase is mid-flight in the resolved gitdir. Those states+ * own the index + HEAD, so the migration must stay out until the repo is clean.+ */+function isOperationInProgress(gitDir: string): boolean {+ return (+ existsSync(join(gitDir, 'MERGE_HEAD')) ||+ existsSync(join(gitDir, 'rebase-merge')) ||+ existsSync(join(gitDir, 'rebase-apply')) ||+ existsSync(join(gitDir, 'CHERRY_PICK_HEAD')) ||+ existsSync(join(gitDir, 'REVERT_HEAD'))+ );+}++function errText(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}diff --git a/packages/server/src/skill-bundles.test.ts b/packages/server/src/skill-bundles.test.tsindex a54de64bc..639a6aebe 100644--- a/packages/server/src/skill-bundles.test.ts+++ b/packages/server/src/skill-bundles.test.ts@@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test';import { existsSync, readFileSync } from 'node:fs';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';+import { RESERVED_PROJECT_SKILL_NAME } from '@inkeep/open-knowledge-core';import { BUNDLE_IDS, BUNDLE_SKILL_NAME, bundleSkillMdPath } from './skill-bundles.ts';// Repo root = three levels up from this file (packages/server/src → root).@@ -28,6 +29,13 @@ describe('skill-bundles (single source of truth)', () => {}});+ test("core's RESERVED_PROJECT_SKILL_NAME stays in lock-step with BUNDLE_SKILL_NAME.project", () => {+ // Core can't depend on server, so it duplicates the reserved project-skill+ // name. This pins the two so a bundle rename can't silently break the+ // git-exclude carve-out / `.gitignore` block that key off the core copy.+ expect(RESERVED_PROJECT_SKILL_NAME).toBe(BUNDLE_SKILL_NAME.project);+ });+test('write-skill description is within the skill contract (≤1024, no XML tags)', () => {const raw = readFileSync(join(REPO_ROOT, bundleSkillMdPath('write-skill')), 'utf-8');const desc = /description:\s*"([\s\S]*?)"\n/.exec(raw)?.[1] ?? '';