Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
sync(oss): mirror inkeep/open-knowledge#1781: Exclude a git dir that resolves inside the shadow work tree (#5073)
inkeep-oss-sync[bot]74eae1b13fe7
diff --git a/.changeset/shadow-excludes-symlinked-git-dir.md b/.changeset/shadow-excludes-symlinked-git-dir.mdnew file mode 100644index 000000000..40a18d31b--- /dev/null+++ b/.changeset/shadow-excludes-symlinked-git-dir.md@@ -0,0 +1,6 @@+---+"@inkeep/open-knowledge": patch+"@inkeep/open-knowledge-server": patch+---++Stop OpenKnowledge's saved version history from growing without bound when your project's `.git` resolves to a directory inside the project, such as a `.git.nosync` symlink or a separate git directory. That directory is now kept out of every new version.diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex 138494fee..85d7a8280 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -167,7 +167,7 @@ The app runs a collaboration server for the open project. It writes runtime stat| `.ok/local/terminal/claude-settings-{mcp,tools,mcp-tools}.json` | Windows-only Claude launch settings written when **Open in Claude** requests MCP or tool preapproval; one of three possible files, overwritten rather than appended on each launch that uses that combination. macOS and Linux pass the same settings inline | In-project, gitignored || `.ok/local/comments/` | [Comments](/docs/features/comments) left on documents, one JSON file each — the note, the passage it quotes, and whether it has been sent | In-project, gitignored || `.ok/worktrees/<branch>/` | Git worktree checkout created when you open a branch in its own window (project switcher); the path is also added to `.git/info/exclude` | In-project, gitignored |-| `.git/ok/` — or `.git/worktrees/<name>/ok/` in a linked worktree, or the enclosing repo's `.git/ok-<slug>/` when your project is a subfolder of a larger repo | Shadow git repo holding per-writer work-in-progress refs; always inside a git admin dir, never in your content tree. Its own `info/exclude` file, written when OpenKnowledge opens the repo, keeps machine-local runtime state — `.ok/local/` and `.ok/worktrees/`, plus the pre-`.ok/local/` equivalents that older projects still keep at the `.ok/` root (`.ok/principal.json`, `.ok/server.lock`, `.ok/cache/`, …) — and the `.tmp.<uuid>` files an in-flight atomic write leaves behind out of every saved version, the way `.ok/.gitignore` keeps them out of git | In-project, gitignored (inside `.git/`) |+| `.git/ok/` — or `.git/worktrees/<name>/ok/` in a linked worktree, or the enclosing repo's `.git/ok-<slug>/` when your project is a subfolder of a larger repo | Shadow git repo holding per-writer work-in-progress refs; always inside a git admin dir, never in your content tree. Its own `info/exclude` file, written when OpenKnowledge opens the repo, keeps machine-local runtime state — `.ok/local/` and `.ok/worktrees/`, plus the pre-`.ok/local/` equivalents that older projects still keep at the `.ok/` root (`.ok/principal.json`, `.ok/server.lock`, `.ok/cache/`, …) — the `.tmp.<uuid>` files an in-flight atomic write leaves behind, and your project's `.git` when it resolves to a directory inside the project under another name (a `.git.nosync` symlink or a separate git dir), out of every saved version, the way `.ok/.gitignore` keeps them out of git | In-project, gitignored (inside `.git/`) |Diagnostic logs and telemetry are **on by default but local-only** — credential-bearing attributes are redacted (`[REDACTED]`) before anything is written, the files rotate at the size caps above, and nothing leaves the machine until you explicitly run `ok diagnose bundle`. Turn the local sink off with `telemetry.localSink.enabled: false`; see [Configuration](./configuration.mdx).@@ -306,7 +306,7 @@ On Windows, Claude Desktop and OpenCode configs live under `%APPDATA%\Claude\` a| `.ok/local/agent-skill/open-knowledge/` | Runtime copy of the OpenKnowledge project skill (`SKILL.md` and `references/`), refreshed before in-app agent processes start. New in-app agent sessions receive this guidance automatically, even when the skill is not installed into an editor | In-project, gitignored with the `local/` ignore rule || `.ok/local/skill-move-retained.json` | Bookkeeping for a skill move between Project and Global scope that could not finish: which destination copy was kept, why, and what the source looked like at the time. Keyed by scope and skill name, one record each. A record clears when a later move of that skill completes, when the copy at the destination stops matching the one recorded, or when you delete that skill at that scope. No document content | In-project, gitignored || `.ok/local/comments/` | [Comments](/docs/features/comments) left on documents, one JSON file each — the note, the passage it quotes, and whether it has been sent | In-project, gitignored |-| `.git/ok/` — or `.git/worktrees/<name>/ok/` in a linked worktree, or the enclosing repo's `.git/ok-<slug>/` when your project is a subfolder of a larger repo | Shadow git repo holding per-writer work-in-progress refs (powers the timeline); always inside a git admin dir, never in your content tree. Its own `info/exclude` file, written when OpenKnowledge opens the repo, keeps machine-local runtime state — `.ok/local/` and `.ok/worktrees/`, plus the pre-`.ok/local/` equivalents that older projects still keep at the `.ok/` root (`.ok/principal.json`, `.ok/server.lock`, `.ok/cache/`, …) — and the `.tmp.<uuid>` files an in-flight atomic write leaves behind out of every saved version, the way `.ok/.gitignore` keeps them out of git | In-project, gitignored (inside `.git/`) |+| `.git/ok/` — or `.git/worktrees/<name>/ok/` in a linked worktree, or the enclosing repo's `.git/ok-<slug>/` when your project is a subfolder of a larger repo | Shadow git repo holding per-writer work-in-progress refs (powers the timeline); always inside a git admin dir, never in your content tree. Its own `info/exclude` file, written when OpenKnowledge opens the repo, keeps machine-local runtime state — `.ok/local/` and `.ok/worktrees/`, plus the pre-`.ok/local/` equivalents that older projects still keep at the `.ok/` root (`.ok/principal.json`, `.ok/server.lock`, `.ok/cache/`, …) — the `.tmp.<uuid>` files an in-flight atomic write leaves behind, and your project's `.git` when it resolves to a directory inside the project under another name (a `.git.nosync` symlink or a separate git dir), out of every saved version, the way `.ok/.gitignore` keeps them out of git | In-project, gitignored (inside `.git/`) |Diagnostic logs and telemetry are **on by default but local-only** — credential-bearing attributes are redacted (`[REDACTED]`) before anything is written, the files rotate at the size caps above, and nothing leaves the machine until you explicitly run `ok diagnose bundle`. Turn the local sink off with `telemetry.localSink.enabled: false`; see [Configuration](./configuration.mdx).@@ -352,7 +352,7 @@ Beta writes the `~/.ok/` entries below under `~/.ok-beta/` instead, except the s## Versions saved before the shadow exclusions-The shadow repo's `info/exclude` is forward-only. Versions saved by an earlier OpenKnowledge build, and the work-in-progress commits folded into them, still carry the machine-local paths in their trees: the contents of `.ok/local/`, including `principal.json` and `server.lock`, and the caches and logs beside them. A project that predates `.ok/local/` carries the same runtime state at the `.ok/` root instead — `.ok/principal.json`, `.ok/state.json`, `.ok/server.lock`, `.ok/ui.lock`, `.ok/sync-state.json`, `.ok/conflicts.json` and `.ok/last-spawn-error.log`, alongside `.ok/cache/` and `.ok/tmp/`. Opening the project on a current build drops those paths from the shadow repo's staging index and stops adding them to new versions; it does not rewrite the versions already written, and those older commits stay reachable from the versions that folded them.+The shadow repo's `info/exclude` is forward-only. Versions saved by an earlier OpenKnowledge build, and the work-in-progress commits folded into them, still carry the machine-local paths in their trees: the contents of `.ok/local/`, including `principal.json` and `server.lock`, and the caches and logs beside them. A project that predates `.ok/local/` carries the same runtime state at the `.ok/` root instead — `.ok/principal.json`, `.ok/state.json`, `.ok/server.lock`, `.ok/ui.lock`, `.ok/sync-state.json`, `.ok/conflicts.json` and `.ok/last-spawn-error.log`, alongside `.ok/cache/` and `.ok/tmp/`. Opening the project on a current build drops those paths from the shadow repo's staging index and stops adding them to new versions; it does not rewrite the versions already written, and those older commits stay reachable from the versions that folded them. The same forward-only rule covers a git dir that resolves inside your project under a name other than `.git` (a `.git.nosync` symlink or a separate git dir): a current build stops staging it and drops it from the index, but versions an earlier build already wrote keep its contents.All of it stays in the shadow git repo inside your own `.git/` directory, which OpenKnowledge never pushes anywhere. A version you saved yourself is kept rather than expired, so this does not age out on its own. `ok deinit` removes the shadow repo along with the rest of a project's OpenKnowledge state.diff --git a/packages/server/src/content/generated-index-git-attributes.ts b/packages/server/src/content/generated-index-git-attributes.tsindex c457b949c..919639ec5 100644--- a/packages/server/src/content/generated-index-git-attributes.ts+++ b/packages/server/src/content/generated-index-git-attributes.ts@@ -1,8 +1,9 @@import { spawnSync } from 'node:child_process';-import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';+import { existsSync, lstatSync, readFileSync } from 'node:fs';import { relative, resolve, sep } from 'node:path';import { atomicWriteFile } from '@inkeep/open-knowledge-core/server';import { normalizeFsPath, tracedAtomicFs, tracedRm } from '../fs-traced.ts';+import { escapeGitPatternSegment, realpathOrResolved } from '../git-paths.ts';import { getLogger } from '../logger.ts';const MANAGED_BLOCK_START = '# BEGIN OpenKnowledge generated indexes';@@ -67,15 +68,8 @@ function gitContext(: { state: 'unavailable' };}- const canonical = (path: string): string => {- try {- return realpathSync(path);- } catch {- return resolve(path);- }- };- const gitRoot = canonical(String(rootResult.stdout).trim());- const canonicalContentDir = canonical(contentDir);+ const gitRoot = realpathOrResolved(String(rootResult.stdout).trim());+ const canonicalContentDir = realpathOrResolved(contentDir);const contentRelative = relative(gitRoot, canonicalContentDir);if (contentRelative === '..' || contentRelative.startsWith(`..${sep}`)) {return { state: 'not-applicable' };@@ -94,7 +88,7 @@ function gitContext(const escapedContentPath = contentRelative.split(sep).filter(Boolean)- .map(escapeAttributePatternSegment)+ .map(escapeGitPatternSegment).join('/');const prefix = escapedContentPath.length > 0 ? `/${escapedContentPath}` : '';const patterns = [@@ -117,10 +111,6 @@ function gitContext(};}-function escapeAttributePatternSegment(segment: string): string {- return segment.replace(/[\\!?*[\]]/g, (character) => `\\${character}`);-}-function formatAttributePattern(pattern: string): string {if (!/\s/.test(pattern)) return pattern;return `"${pattern.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;diff --git a/packages/server/src/git-paths.ts b/packages/server/src/git-paths.tsindex 90d787fb5..d0025590e 100644--- a/packages/server/src/git-paths.ts+++ b/packages/server/src/git-paths.ts@@ -1,5 +1,19 @@+import { realpathSync } from 'node:fs';+import { resolve } from 'node:path';import type { SimpleGit } from 'simple-git';+export function realpathOrResolved(path: string): string {+ try {+ return realpathSync(path);+ } catch {+ return resolve(path);+ }+}++export function escapeGitPatternSegment(segment: string): string {+ return segment.replace(/[\\!?*[\]]/g, (character) => `\\${character}`);+}+export const PORCELAIN_STATUS_ARGS = ['status', '--porcelain', '-uall'];export function splitNulSeparatedPaths(out: string): string[] {diff --git a/packages/server/src/shadow-repo.test.ts b/packages/server/src/shadow-repo.test.tsindex 75229737c..fa478d41e 100644--- a/packages/server/src/shadow-repo.test.ts+++ b/packages/server/src/shadow-repo.test.ts@@ -26,6 +26,7 @@ import {DEFAULT_CHECKPOINT_RETENTION,FANOUT_INDEX_NAME,GIT_UPSTREAM_WRITER,+ gitDirExcludePatterns,type InMemoryCheckpointParams,initShadowRepo,isShadowExcludesDegraded,@@ -2338,7 +2339,7 @@ describe('shadow repo excludes OpenKnowledge machine-local state', () => {expect(warnings.some((message) =>message.includes(- '[shadow-repo] could not read the index to clear machine-local entries — none were dropped and an unknown number are still staged',+ '[shadow-repo] could not read the index to clear excluded entries — none were dropped and an unknown number are still staged',),),).toBe(true);@@ -2378,9 +2379,7 @@ describe('shadow repo excludes OpenKnowledge machine-local state', () => {const infos = infoSpy.mock.calls.map((call) => String(call[1] ?? ''));expect(infos.some((message) =>- message.includes(- '[shadow-repo] dropped machine-local entries a previous build had staged',- ),+ message.includes('[shadow-repo] dropped excluded entries a previous build had staged'),),).toBe(false);} finally {@@ -2552,3 +2551,177 @@ describe('shadow repo excludes OpenKnowledge machine-local state', () => {expect(status).not.toContain('.ok/local/');});});++describe('shadow repo excludes a git dir that lives inside the work tree under another name', () => {+ let projectRoot: string;+ let shadow: ShadowHandle;++ const writer: WriterIdentity = {+ id: 'human-ada',+ name: 'Ada Lovelace',+ email: '[email protected]',+ };++ function treePaths(handle: ShadowHandle, ref: string): string[] {+ return execFileSync('git', ['ls-tree', '-r', '--name-only', ref], {+ cwd: handle.workTree,+ env: { ...process.env, GIT_DIR: handle.gitDir },+ encoding: 'utf-8',+ })+ .split('\n')+ .map((path) => path.trim())+ .filter((path) => path.length > 0);+ }++ beforeEach(async () => {+ projectRoot = resolve(tmpDir, 'project');+ mkdirSync(projectRoot, { recursive: true });+ const git = simpleGit(projectRoot);+ await git.init();+ await git.raw('config', 'user.name', 'Test');+ await git.raw('config', 'user.email', '[email protected]');+ execFileSync('mv', ['.git', '.git.nosync'], { cwd: projectRoot });+ symlinkSync('.git.nosync', resolve(projectRoot, '.git'));+ writeFileSync(resolve(projectRoot, 'intro.md'), '# Hello\n');+ shadow = await initShadowRepo(projectRoot);+ });++ test('derives anchored excludes for the symlink target and the shadow dir', () => {+ expect(gitDirExcludePatterns(shadow)).toEqual(['/.git.nosync/', '/.git.nosync/ok/']);+ const exclude = readFileSync(resolve(shadow.gitDir, 'info/exclude'), 'utf-8');+ expect(exclude).toContain('/.git.nosync/\n');+ });++ test('a regular .git directory needs no extra excludes', async () => {+ const plainRoot = resolve(tmpDir, 'plain');+ mkdirSync(plainRoot, { recursive: true });+ await simpleGit(plainRoot).init();+ const plainShadow = await initShadowRepo(plainRoot);+ expect(gitDirExcludePatterns(plainShadow)).toEqual([]);+ });++ test('WIP commits never stage the shadow repo or the project git dir', async () => {+ await commitWip(shadow, writer, '.', 'WIP: first');+ writeFileSync(resolve(projectRoot, 'intro.md'), '# Hello again\n');+ await commitWip(shadow, writer, '.', 'WIP: second');++ const paths = treePaths(shadow, `refs/wip/main/${writer.id}`);+ expect(paths).toContain('intro.md');+ expect(paths.filter((path) => path.startsWith('.git.nosync/'))).toEqual([]);+ });++ test('the fan-out tree never stages the shadow repo or the project git dir', async () => {+ await commitWip(shadow, writer, '.', 'WIP: seed objects');+ const tree = await buildWipTree(shadow, '.');+ const paths = treePaths(shadow, tree);+ expect(paths).toContain('intro.md');+ expect(paths.filter((path) => path.startsWith('.git.nosync/'))).toEqual([]);+ });++ test('a fan-out index that already staged the git dir is swept on the next build', async () => {+ const fanoutIndex = resolve(shadow.gitDir, FANOUT_INDEX_NAME);+ const excludeFile = resolve(shadow.gitDir, 'info/exclude');+ const realExclude = readFileSync(excludeFile, 'utf-8');+ writeFileSync(excludeFile, '');+ try {+ execFileSync('git', ['add', '-A', '.'], {+ cwd: shadow.workTree,+ env: {+ ...process.env,+ GIT_DIR: shadow.gitDir,+ GIT_WORK_TREE: shadow.workTree,+ GIT_INDEX_FILE: fanoutIndex,+ },+ });+ } finally {+ writeFileSync(excludeFile, realExclude);+ }++ const tree = await buildWipTree(shadow, '.');+ expect(treePaths(shadow, tree).filter((path) => path.startsWith('.git.nosync/'))).toEqual([]);+ });++ test('a git dir reached through a `.git` pointer file is fully excluded from staging', async () => {+ const pointerRoot = resolve(tmpDir, 'pointer-project');+ mkdirSync(pointerRoot, { recursive: true });+ const gitData = resolve(pointerRoot, '.gitdata');+ execFileSync('git', ['init', `--separate-git-dir=${gitData}`, pointerRoot]);+ execFileSync('git', ['config', 'user.name', 'Test'], {+ cwd: pointerRoot,+ env: { ...process.env, GIT_DIR: gitData },+ });+ execFileSync('git', ['config', 'user.email', '[email protected]'], {+ cwd: pointerRoot,+ env: { ...process.env, GIT_DIR: gitData },+ });+ writeFileSync(resolve(pointerRoot, 'intro.md'), '# Hello\n');+ const pointerShadow = await initShadowRepo(pointerRoot);++ expect(gitDirExcludePatterns(pointerShadow)).toEqual(['/.gitdata/', '/.gitdata/ok/']);++ await commitWip(pointerShadow, writer, '.', 'WIP: pointer');+ const paths = treePaths(pointerShadow, `refs/wip/main/${writer.id}`);+ expect(paths).toContain('intro.md');+ expect(paths.filter((path) => path.startsWith('.gitdata/'))).toEqual([]);+ });++ test('a git dir that resolves outside the work tree contributes no excludes', async () => {+ const externalRoot = resolve(tmpDir, 'external-project');+ mkdirSync(externalRoot, { recursive: true });+ const externalGitDir = resolve(tmpDir, 'external-store');+ execFileSync('git', ['init', `--separate-git-dir=${externalGitDir}`, externalRoot]);+ execFileSync('git', ['config', 'user.name', 'Test'], {+ cwd: externalRoot,+ env: { ...process.env, GIT_DIR: externalGitDir },+ });+ execFileSync('git', ['config', 'user.email', '[email protected]'], {+ cwd: externalRoot,+ env: { ...process.env, GIT_DIR: externalGitDir },+ });+ writeFileSync(resolve(externalRoot, 'intro.md'), '# Hello\n');+ const externalShadow = await initShadowRepo(externalRoot);++ expect(gitDirExcludePatterns(externalShadow)).toEqual([]);+ const exclude = readFileSync(resolve(externalShadow.gitDir, 'info/exclude'), 'utf-8');+ expect(exclude).not.toContain('/../');+ });++ test('a git dir named with a glob metacharacter still lets other content stage', async () => {+ const metaRoot = resolve(tmpDir, 'meta-project');+ mkdirSync(metaRoot, { recursive: true });+ const git = simpleGit(metaRoot);+ await git.init();+ await git.raw('config', 'user.name', 'Test');+ await git.raw('config', 'user.email', '[email protected]');+ execFileSync('mv', ['.git', '*'], { cwd: metaRoot });+ symlinkSync('*', resolve(metaRoot, '.git'));+ mkdirSync(resolve(metaRoot, 'docs'), { recursive: true });+ writeFileSync(resolve(metaRoot, 'docs/note.md'), '# Note\n');+ writeFileSync(resolve(metaRoot, 'intro.md'), '# Hello\n');+ const metaShadow = await initShadowRepo(metaRoot);++ expect(gitDirExcludePatterns(metaShadow)).toEqual(['/\\*/', '/\\*/ok/']);++ await commitWip(metaShadow, writer, '.', 'WIP: meta');+ const paths = treePaths(metaShadow, `refs/wip/main/${writer.id}`);+ expect(paths).toContain('docs/note.md');+ expect(paths).toContain('intro.md');+ expect(paths.some((path) => path.startsWith('*/'))).toBe(false);+ });++ test('a git dir name containing a newline is skipped, not written as a broken pattern', async () => {+ const nlRoot = resolve(tmpDir, 'newline-project');+ mkdirSync(nlRoot, { recursive: true });+ const git = simpleGit(nlRoot);+ await git.init();+ await git.raw('config', 'user.name', 'Test');+ await git.raw('config', 'user.email', '[email protected]');+ const weird = 'git\nweird';+ execFileSync('mv', ['.git', weird], { cwd: nlRoot });+ symlinkSync(weird, resolve(nlRoot, '.git'));+ writeFileSync(resolve(nlRoot, 'intro.md'), '# Hello\n');+ const nlShadow = await initShadowRepo(nlRoot);++ expect(gitDirExcludePatterns(nlShadow)).toEqual([]);+ });+});diff --git a/packages/server/src/shadow-repo.ts b/packages/server/src/shadow-repo.tsindex f10dee01f..3e2e4d186 100644--- a/packages/server/src/shadow-repo.ts+++ b/packages/server/src/shadow-repo.ts@@ -1,6 +1,6 @@import { randomUUID } from 'node:crypto';import { existsSync, readdirSync, rmSync } from 'node:fs';-import { resolve } from 'node:path';+import { isAbsolute, relative, resolve, sep } from 'node:path';import {OK_DIR,OK_MACHINE_LOCAL_ROOT_DIRS,@@ -24,13 +24,14 @@ import {type ParsedCheckpoint,parseCheckpoint,parseWriterId,+ resolveGitDir,resolveShadowDir,type WriterClassification,} from '@inkeep/open-knowledge-core/shadow-repo-layout';import simpleGit from 'simple-git';import { resolveCheckpointChainAnchors } from './checkpoint-chain.ts';import { tracedMkdirSync, tracedRenameSync, tracedWriteFileSync } from './fs-traced.ts';-import { listTreeLongEntries } from './git-paths.ts';+import { escapeGitPatternSegment, listTreeLongEntries, realpathOrResolved } from './git-paths.ts';import { assertNotSymlink, ensureGitignoreEntries, SymlinkRefusedError } from './init-project.ts';import { getLogger } from './logger.ts';import {@@ -93,11 +94,30 @@ const SHADOW_EXCLUDE_PATTERNS: readonly string[] = [ATOMIC_TEMP_GLOB,];-const SHADOW_EXCLUDE_CONTENT = `# OpenKnowledge machine-local state and in-flight atomic writes: never part of a version, never staged.-${SHADOW_EXCLUDE_PATTERNS.join('\n')}-`;+export function gitDirExcludePatterns(shadow: ShadowHandle): string[] {+ const workTreeReal = realpathOrResolved(shadow.workTree);+ const patterns = new Set<string>();+ for (const candidate of [resolveGitDir(shadow.workTree), shadow.gitDir]) {+ if (!candidate || !existsSync(candidate)) continue;+ const rel = relative(workTreeReal, realpathOrResolved(candidate));+ if (rel === '' || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) continue;+ const segments = rel.split(sep);+ if (segments.includes('.git')) continue;+ if (segments.some((segment) => /[\r\n]/.test(segment))) continue;+ patterns.add(`/${segments.map(escapeGitPatternSegment).join('/')}/`);+ }+ return [...patterns];+}-const EXCLUDE_PATTERN_ARGS = SHADOW_EXCLUDE_PATTERNS.flatMap((pattern) => ['-x', pattern]);+function shadowExcludePatterns(shadow: ShadowHandle): string[] {+ return [...SHADOW_EXCLUDE_PATTERNS, ...gitDirExcludePatterns(shadow)];+}++function shadowExcludeContent(shadow: ShadowHandle): string {+ return `# OpenKnowledge machine-local state, in-flight atomic writes, and any git dir inside the work tree: never part of a version, never staged.+${shadowExcludePatterns(shadow).join('\n')}+`;+}const UPDATE_INDEX_ARGV_BUDGET_BYTES = 8000;@@ -138,7 +158,8 @@ async function dropExcludedIndexEntries(let dropped = 0;let listedCount: number | undefined;try {- const listed = await sg.env(env).raw('ls-files', '-z', '-i', '-c', ...EXCLUDE_PATTERN_ARGS);+ const excludeArgs = shadowExcludePatterns(shadow).flatMap((pattern) => ['-x', pattern]);+ const listed = await sg.env(env).raw('ls-files', '-z', '-i', '-c', ...excludeArgs);const stale = listed.split('\0').filter((p) => p.length > 0);listedCount = stale.length;for (const chunk of chunkByArgvBudget(stale, UPDATE_INDEX_ARGV_BUDGET_BYTES)) {@@ -149,7 +170,7 @@ async function dropExcludedIndexEntries(incrementShadowExcludeIndexEntriesDropped(dropped);log.info({ count: dropped },- '[shadow-repo] dropped machine-local entries a previous build had staged',+ '[shadow-repo] dropped excluded entries a previous build had staged',);}return { failed: false };@@ -159,8 +180,8 @@ async function dropExcludedIndexEntries(log.warn({ err: e, dropped, leftStaged: leftStaged ?? 'unknown' },leftStaged === undefined- ? '[shadow-repo] could not read the index to clear machine-local entries — none were dropped and an unknown number are still staged (non-fatal)'- : `[shadow-repo] could not finish clearing machine-local entries from the index — dropped ${dropped}, left ${leftStaged} still staged (non-fatal)`,+ ? '[shadow-repo] could not read the index to clear excluded entries — none were dropped and an unknown number are still staged (non-fatal)'+ : `[shadow-repo] could not finish clearing excluded entries from the index — dropped ${dropped}, left ${leftStaged} still staged (non-fatal)`,);return { failed: true };}@@ -174,7 +195,7 @@ async function ensureShadowExcludes(shadow: ShadowHandle): Promise<void> {tracedMkdirSync(infoDir, { recursive: true });const outcome = ensureGitignoreEntries(excludeFile,- SHADOW_EXCLUDE_CONTENT,+ shadowExcludeContent(shadow),'shadow info/exclude',);shadowExcludesWritten.set(shadow.gitDir, true);@@ -189,7 +210,7 @@ async function ensureShadowExcludes(shadow: ShadowHandle): Promise<void> {} else {log.warn({ err: e, excludeFile },- '[shadow-repo] could not write the shadow exclude file — machine-local state stays out of versions only through the index sweep',+ '[shadow-repo] could not write the shadow exclude file — excluded paths stay out of versions only through the index sweep',);}}