Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): treat content paths as literal git pathspecs (PRD-8638) (#4363)
shagun-singh-inkeepcfeb6e3d4e01
diff --git a/.changeset/literal-git-pathspecs.md b/.changeset/literal-git-pathspecs.mdnew file mode 100644index 000000000..9eb138c13--- /dev/null+++ b/.changeset/literal-git-pathspecs.md@@ -0,0 +1,9 @@+---+'@inkeep/open-knowledge': patch+---++Documents, folders and skills whose names begin with `:` or contain `*` or `?` now sync, show history and report share status the same way any other name does.++Git reads the file names Open Knowledge passes it as a pattern language, not as plain names, and the app was handing them over unprotected. A note named `:scratch.md` failed the whole push cycle, so nothing in that cycle reached your remote. A note named `:!draft.md` was read as an instruction to *exclude* files, so it was quietly dropped from the commit it belonged to and never left your machine — with no error to suggest anything was missing. Names containing `*` or `?` matched siblings instead of themselves, so version history, share freshness, share target status, document rename and skill restore could answer about the wrong file, and switching a wildcard-named skill to local-only could be blocked by a remediation list for a file that was never tracked.++Every place the app hands a file name to git now marks it as a literal name. Documents that were skipped will sync on the next push, and no renaming is needed.diff --git a/knip.config.ts b/knip.config.tsindex 9e6547bf1..e67c1c1cd 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -63,6 +63,7 @@ export default {'packages/app/src/editor/typing-burst-detector.ts': ['exports', 'types'],'packages/server/src/bridge-intake.ts': ['types'],'packages/core/src/schemas/api.type-tests.ts': ['files'],+ 'packages/core/src/git-pathspec.type-tests.ts': ['files'],'packages/server/src/http/request-validation.ts': ['exports', 'types'],'packages/server/src/http/error-response.ts': ['exports'],'packages/app/src/editor/http-client.ts': ['types'],@@ -138,9 +139,7 @@ export default {'packages/server': {entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],project: 'src/**',- ignoreDependencies: [- '@types/shell-quote',- ],+ ignoreDependencies: ['@types/shell-quote'],},'packages/cli': {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],diff --git a/lint-plugins/ok-rules/README.md b/lint-plugins/ok-rules/README.mdindex 262745173..07a94b438 100644--- a/lint-plugins/ok-rules/README.md+++ b/lint-plugins/ok-rules/README.md@@ -609,6 +609,34 @@ Included: `packages/app/src/**/*.tsx`, `packages/desktop/src/**/*.tsx`, `packageRule: [`lint-plugins/ok-rules/rules/no-demoted-dialog-confirm.mjs`](rules/no-demoted-dialog-confirm.mjs). Fixture: [`lint-plugins/ok-rules/__fixtures__/no-demoted-dialog-confirm.fixture.tsx`](__fixtures__/no-demoted-dialog-confirm.fixture.tsx). Test: [`packages/app/tests/lint-plugins/no-demoted-dialog-confirm.test.ts`](../../packages/app/tests/lint-plugins/no-demoted-dialog-confirm.test.ts). See [PRECEDENTS.md #42](../../PRECEDENTS.md#custom-lint-enforcement-precedent-42) for the custom-rule convention.+### `no-unconverted-git-pathspec`++Git pathspec discipline. Fires on a hand-written `'--'` string literal in an array literal, or as a direct argument of a `.raw(...)` varargs call, anywhere under `packages/{core,server,cli,desktop}/src/**` — unless the argv's leading non-flag token is one of the four verbs whose `--` operands are not pathspecs. The array branch consults no git token of any kind; see the over-catch note below. The tail after the separator is built with `pathspecArgs(paths)` from [`packages/core/src/git-pathspec.ts`](../../packages/core/src/git-pathspec.ts), which emits the separator and the `:(literal)` conversion together.++**Why.** git parses a pathspec argument position as a pattern language, and `--` does not disable that parsing: it stops option parsing only. A filesystem path handed over bare is therefore reinterpreted whenever its first path segment carries a metacharacter. PRD-8638 is what that costs: a doc named `:colon.md` fatals the push cycle, a doc named `:!bang.md` reads as exclusion magic and is silently subtracted from the set it was meant to join, and a wildcard-named skill directory makes `ls-files --error-unmatch` report an untracked file as tracked. Thirty-six `pathspecArgs` call sites across fourteen files now carry the conversion. That count is post-fix call sites, not pre-fix `--` literals: the two differ because one `sync-engine.ts` staging loop collapsed two pre-fix literals into a single call, and four `shadow-repo.ts` / `persistence.ts` sites had no `--` to count in the first place. Every converted site that did carry a `--` already had it, which is what made the omission look handled. The pattern is not a regression: three of those sites are present verbatim in the initial Copybara mirror-import commit `6bd7d8ba7d`.++**Prior art in the dependency.** `[email protected]` ships a `pathspec(...)` helper (`@simple-git/[email protected]`), and its `suffixPathsPlugin` — registered unconditionally in `gitInstanceFactory` — already routes marked arguments, and everything after a `'--'`, into the command suffix and re-emits exactly one separator. The separator half of `pathspecArgs`'s contract is therefore something simple-git already guarantees for every `sg.raw(...)` site here. The helper adds no magic word, so `pathspec(':colon.md')` still reaches git bare: the `:(literal)` half, which is the half PRD-8638 is about, is not available from it. `pathspecArgs` is also package-agnostic, covering the two converted sites the plugin never sees — `rename-log.ts`'s `spawn` and `git-exclude.ts`'s `execFileSync`. The rule deliberately does **not** treat `pathspec(...)` as a non-violation, because accepting it would wave through an unconverted operand. (Same check as the `require-windowshide-on-spawn` note above, which records what `simple-git` already covers.)++**A fail-closed allowlist, not suppressions.** Four verbs take `--` operands that genuinely are not pathspecs, and the rule carries them in `NON_PATHSPEC_VERBS` rather than asking four production files to suppress it: `hash-object` takes file arguments, `clone` takes a URL and a directory, `worktree add` takes a commit-ish, and `mv` takes literal source and destination paths (verified against real git 2.49.0: `git mv -- ':(literal):colon.md' moved.md` reports `fatal: bad source, source=:(literal):colon.md, destination=moved.md`, so converting that operand would break the case-only rename it implements). This README treats an `oxlint-disable` header as a backlog marker, so a permanent legitimate use is a semantic mismatch there. The verb is resolved positionally — the first token that is not a flag, skipping the value of a `-c` / `-C` pair, so `clone` is still recognised behind a `-c core.symlinks=false` prefix — rather than by membership anywhere in the argv, so a path operand or a commit message that happens to read `mv` cannot exempt the argv it sits in. Each argv array is judged on its own: an array of argvs is not flattened into one bag, so one allowlisted row cannot disarm its siblings. The polarity is deliberate: a verb the rule has never seen fires rather than silently passing, so a new git surface is opted in by a reviewer rather than by omission.++**Scope** (`RULE_SCOPES['no-unconverted-git-pathspec']` in [`scope.mjs`](scope.mjs)). The four packages that build git argvs today. `git-pathspec.ts` is excluded because it is the one sanctioned emitter of the separator. Tests and test helpers are excluded per the `no-raw-html-interactive-element` precedent: fixture code that seeds a hostile filename deliberately passes a correct `:(literal)` pathspec by hand, and that is the control proving git can do the right thing, not a production argv.++Included: `packages/core/src/**/*.ts`, `packages/server/src/**/*.ts`, `packages/cli/src/**/*.ts`, `packages/desktop/src/**/*.ts`, `lint-plugins/ok-rules/__fixtures__/no-unconverted-git-pathspec.fixture.tsx`. Excluded: `packages/core/src/git-pathspec.ts`, `**/*.test.ts`, `**/*.test-helper.ts`.++The rule does NOT catch:++- **A pathspec operand passed with no `--` at all.** `sg.raw('add', contentRoot)` is the shape four positions in `shadow-repo.ts` and `persistence.ts` used, and the predicate is keyed on the separator, so it is structurally invisible. That shape is also invisible to a `'--'` source grep, which is how it survived the original enumeration. The same blindness covers `simple-git`'s typed path-taking methods — `.add` / `.rm` / `.checkout` / `.mv` take a pathspec operand with no separator to key on. The only production instance today is the benign constant `git.add('.')` at [`packages/cli/src/commands/share/publish.ts`](../../packages/cli/src/commands/share/publish.ts).+- **`GIT_LITERAL_PATHSPECS` / `--literal-pathspecs`.** Under that setting git takes the string `:(literal)x` as a filename and matches nothing, so it is mutually exclusive with everything this rule steers callers toward. Nothing detects it; adopting it would silently break every converted operand in the tree. An operator who already exports it can restore magic parsing per invocation with `git --no-literal-pathspecs` (shipped in git 1.8.2, so it predates this project's `MIN_GIT_VERSION` floor rather than being bounded by it) or `GIT_LITERAL_PATHSPECS=0`.+- **A separator assembled at runtime** — a variable, a template literal, or a concatenation holding `--`. No single node carries the value. Defeatable on purpose rather than by accident.+- **A varargs `'--'` passed to anything other than `.raw`.** `simple-git`'s `raw` is the only varargs git API in the tree; a new one would need adding to the predicate.+- **Whether the operand was already converted.** The rule enforces the boundary, not the spelling — double conversion is closed at compile time instead, by `toPathspec`'s parameter type and `pathspecArgs`'s branded return type both rejecting an already-converted argument. That closure is pinned inside the typecheck program by [`packages/core/src/git-pathspec.type-tests.ts`](../../packages/core/src/git-pathspec.type-tests.ts); a `*.test.ts` file cannot carry the pin, because every package tsconfig excludes tests from the program and an unevaluated `@ts-expect-error` reds nothing.++It also over-catches, in the same direction. The array branch fires on any array literal in those packages holding a bare `'--'`, git argv or not, so `const seps = ['--', '=='];` draws a diagnostic whose message names `pathspecArgs`. That is the price of the polarity above: a predicate narrow enough to prove an array is a git argv would also let an unrecognised git surface through.++The behavioural backstop is [`packages/server/src/git-pathspec-name-invariance.test.ts`](../../packages/server/src/git-pathspec-name-invariance.test.ts) and its CLI sibling, which drive real git over hostile filenames end to end.++Rule: [`lint-plugins/ok-rules/rules/no-unconverted-git-pathspec.mjs`](rules/no-unconverted-git-pathspec.mjs). Fixture: [`lint-plugins/ok-rules/__fixtures__/no-unconverted-git-pathspec.fixture.tsx`](__fixtures__/no-unconverted-git-pathspec.fixture.tsx). Test: [`packages/app/tests/lint-plugins/no-unconverted-git-pathspec.test.ts`](../../packages/app/tests/lint-plugins/no-unconverted-git-pathspec.test.ts). See [PRECEDENTS.md #42](../../PRECEDENTS.md#custom-lint-enforcement-precedent-42) for the custom-rule convention.+## SuppressionInline `// oxlint-disable-next-line` comments silence individual diagnostics. The form names the plugin, the rule and the reason:diff --git a/lint-plugins/ok-rules/__fixtures__/no-unconverted-git-pathspec.fixture.tsx b/lint-plugins/ok-rules/__fixtures__/no-unconverted-git-pathspec.fixture.tsxnew file mode 100644index 000000000..0dc40b0dc--- /dev/null+++ b/lint-plugins/ok-rules/__fixtures__/no-unconverted-git-pathspec.fixture.tsx@@ -0,0 +1,94 @@+// FIXTURE — drives `no-unconverted-git-pathspec.test.ts` via shell-out to `pnpm exec oxlint`. Not+// part of the main lint: `__fixtures__/` is in `oxlint.config.ts#ignorePatterns`, and+// `__fixtures__/oxlint.fixtures.json` re-enables the rules for the test.+//+// Pairs 5 positive cases (rule MUST fire) with negative cases (rule must NOT fire). Every positive+// is a real pre-fix argv from PRD-8638 rather than a synthetic one: the bug supplied them.+//+// The negatives are the precision boundary, not clean code. Four are the verbs whose `--` operands+// genuinely are not pathspecs (`hash-object` takes file arguments, `clone` takes a URL and a+// directory, `worktree add` takes a commit-ish, `mv` takes literal source and destination paths) —+// these prove the in-rule allowlist works from any position in the argv and through a nested+// conditional tail. Two are `parse-command.ts`'s string comparisons against the `--` token, which+// are not argv construction at all and are the shape most likely to draw a widened pattern.+//+// The fixture test asserts the diagnostic count with exact equality (`toBe(7)`) so both a weakened+// pattern (drops below 7) and a widened pattern that catches a negative (rises above 7) fail the+// gate.+//+// P6 and P7 pin the two fail-open holes an earlier position-blind predicate had: it exempted an+// argv as soon as ANY collected string matched an allowlisted verb, from any position, and it+// merged an array-of-argvs into one bag so one allowlisted row disarmed its siblings.+declare const batch: readonly string[];+declare const chunk: readonly string[];+declare const p: string;+declare const rel: string;+declare const branch: string;+declare const worktreePath: string;+declare const baseBranch: string | undefined;+declare const docPath: string | undefined;+declare const url: string;+declare const tmp: string;+declare const arg: string;+declare const value: string;+declare const git: { raw(...args: unknown[]): Promise<string> };+declare function execFileSync(cmd: string, args: readonly string[]): string;+declare function execFileAsync(cmd: string, args: readonly string[]): Promise<string>;+declare function listNames(g: typeof git, args: readonly string[]): Promise<string[]>;+declare function pathspecArgs(paths: readonly string[]): string[];++async function positives() {+ // P1: the diagnosed line at sync-engine.ts:2766, verbatim.+ await git.raw(['add', '--', ...batch]);+ // P2: the CLI tracked-path probe at git-exclude.ts:260.+ execFileSync('git', ['ls-files', '--error-unmatch', '--', p]);+ // P3: the varargs form at skill-reimport.ts:214.+ await git.raw('ls-files', '--', rel);+ // P4: a conditional tail (timeline-query.ts:551). One diagnostic on the outer argv, not two.+ await git.raw(['log', '--format=%H', ...(docPath ? ['--', docPath] : [])]);+ // P5: the multiline array form (sync-engine.ts:1106).+ await listNames(git, ['diff', '--cached', '--name-only', '--', ...batch]);+ // P6: an allowlisted verb appearing as a PATH operand must not exempt the argv it sits in.+ await git.raw(['add', '--', 'worktree']);+ // P7: an array of argvs. The `add` row fires; the `worktree` row beside it stays exempt, and+ // does not disarm its sibling.+ const rows = [+ ['add', '--', p],+ ['worktree', 'add', worktreePath, '--', branch],+ ];+ return rows;+}++async function negatives() {+ // N1: `hash-object` takes file arguments, in the varargs form (shadow-repo.ts:1289).+ await git.raw('hash-object', '-w', '--', ...chunk);+ // N2: `clone` takes a URL and a directory, and is not the first element (fetch.ts:114).+ await execFileAsync('git', ['-c', 'core.symlinks=false', 'clone', '-q', '--', url, tmp]);+ // N3: `worktree add` takes a commit-ish (worktree-service.ts:240).+ const added = ['worktree', 'add', worktreePath, '--', branch];+ // N4: the same, with the separator in a nested conditional tail (worktree-service.ts:237).+ const created = [+ 'worktree',+ 'add',+ '-b',+ branch,+ worktreePath,+ ...(baseBranch ? ['--', baseBranch] : []),+ ];+ // N5: `git mv` takes literal path arguments, not pathspecs (api-extension.ts:1412). Verified+ // against real git 2.49.0: `git mv -- ':(literal):colon.md' moved.md` reports+ // `fatal: bad source, source=:(literal):colon.md, destination=moved.md`, so converting this+ // operand would break the case-only rename it implements.+ await git.raw('mv', '--', p, rel);+ // N6: a string comparison against the token, not argv construction (parse-command.ts:55).+ const isFlag = arg.startsWith('--');+ // N7: an equality test against the token (parse-command.ts:220).+ const isSeparator = value === '--';+ // N8: the converted shape the fix installs.+ await git.raw(['add', ...pathspecArgs([...batch])]);+ // N9: flags that merely begin with the separator's characters.+ const flags = ['diff', '--name-only', '--cached'];+ return { added, created, isFlag, isSeparator, flags };+}++export { negatives, positives };diff --git a/lint-plugins/ok-rules/__fixtures__/oxlint.fixtures.json b/lint-plugins/ok-rules/__fixtures__/oxlint.fixtures.jsonindex 9824ff812..ed5fde4c3 100644--- a/lint-plugins/ok-rules/__fixtures__/oxlint.fixtures.json+++ b/lint-plugins/ok-rules/__fixtures__/oxlint.fixtures.json@@ -17,6 +17,7 @@"ok/no-roundtrip-identity-oracle": "error","ok/no-split-suggestion-dispatch": "error","ok/no-themeless-pierre-diff": "error",+ "ok/no-unconverted-git-pathspec": "error","ok/no-uninstall-forbidden-import": "error","ok/no-unportaled-editor-content": "error","ok/no-unwrapped-user-facing-string": "error",diff --git a/lint-plugins/ok-rules/index.mjs b/lint-plugins/ok-rules/index.mjsindex 0b5b8dc27..6830736b6 100644--- a/lint-plugins/ok-rules/index.mjs+++ b/lint-plugins/ok-rules/index.mjs@@ -16,6 +16,7 @@ import { noResolvedValueThemeSource } from './rules/no-resolved-value-theme-sourimport { noRoundtripIdentityOracle } from './rules/no-roundtrip-identity-oracle.mjs';import { noSplitSuggestionDispatch } from './rules/no-split-suggestion-dispatch.mjs';import { noThemelessPierreDiff } from './rules/no-themeless-pierre-diff.mjs';+import { noUnconvertedGitPathspec } from './rules/no-unconverted-git-pathspec.mjs';import { noUninstallForbiddenImport } from './rules/no-uninstall-forbidden-import.mjs';import { noUnportaledEditorContent } from './rules/no-unportaled-editor-content.mjs';import { noUnwrappedUserFacingString } from './rules/no-unwrapped-user-facing-string.mjs';@@ -46,6 +47,7 @@ const declared = {'no-roundtrip-identity-oracle': noRoundtripIdentityOracle,'no-split-suggestion-dispatch': noSplitSuggestionDispatch,'no-themeless-pierre-diff': noThemelessPierreDiff,+ 'no-unconverted-git-pathspec': noUnconvertedGitPathspec,'no-uninstall-forbidden-import': noUninstallForbiddenImport,'no-unportaled-editor-content': noUnportaledEditorContent,'no-unwrapped-user-facing-string': noUnwrappedUserFacingString,diff --git a/lint-plugins/ok-rules/rules/no-unconverted-git-pathspec.mjs b/lint-plugins/ok-rules/rules/no-unconverted-git-pathspec.mjsnew file mode 100644index 000000000..6805d7c2b--- /dev/null+++ b/lint-plugins/ok-rules/rules/no-unconverted-git-pathspec.mjs@@ -0,0 +1,108 @@+import { docsUrl } from '../docs.mjs';++const URL = docsUrl('no-unconverted-git-pathspec');++const MESSAGE = `Hand-written \`'--'\` in a git argv leaves the operands after it as bare paths, and git parses a pathspec position as a pattern language — \`--\` stops option parsing, not pathspec-magic parsing. Build the tail with \`pathspecArgs(paths)\` from @inkeep/open-knowledge-core, which emits the separator and the \`:(literal)\` conversion together. If this verb's \`--\` operands are not pathspecs (as for clone, hash-object, mv and worktree), add the verb to \`NON_PATHSPEC_VERBS\` in this rule rather than suppressing. See ${URL}`;++export const NON_PATHSPEC_VERBS = ['clone', 'hash-object', 'mv', 'worktree'];++const ALLOWED = new Set(NON_PATHSPEC_VERBS);++const SEPARATOR = '--';++const CONFIG_FLAGS = new Set(['-c', '-C']);++function collectFragment(node, out) {+ if (!node) return;+ if (node.type === 'Literal' && typeof node.value === 'string') {+ out.push(node.value);+ return;+ }+ if (node.type === 'SpreadElement') {+ collectFragment(node.argument, out);+ return;+ }+ if (node.type === 'ConditionalExpression') {+ collectFragment(node.consequent, out);+ collectFragment(node.alternate, out);+ return;+ }+ if (node.type === 'ArrayExpression') {+ collectArgv(node, out);+ return;+ }+ out.push(null);+}++function collectArgv(node, out) {+ for (const element of node.elements) {+ if (element?.type === 'ArrayExpression') continue;+ collectFragment(element, out);+ }+}++function verbOf(tokens) {+ for (let i = 0; i < tokens.length; i += 1) {+ const token = tokens[i];+ if (typeof token !== 'string') return undefined;+ if (CONFIG_FLAGS.has(token)) {+ i += 1;+ continue;+ }+ if (!token.startsWith('-')) return token;+ }+ return undefined;+}++function violates(tokens) {+ return tokens.includes(SEPARATOR) && !ALLOWED.has(verbOf(tokens));+}++function isArgvFragment(node) {+ let parent = node.parent;+ let unwrapped = false;+ while (parent && (parent.type === 'SpreadElement' || parent.type === 'ConditionalExpression')) {+ parent = parent.parent;+ unwrapped = true;+ }+ return unwrapped && parent?.type === 'ArrayExpression';+}++function isRawCall(node) {+ const callee = node.callee;+ return callee?.type === 'MemberExpression' && callee.property?.name === 'raw';+}++function hasDirectSeparatorArgument(node) {+ return node.arguments.some(+ (argument) => argument.type === 'Literal' && argument.value === SEPARATOR,+ );+}++export const noUnconvertedGitPathspec = {+ meta: {+ type: 'problem',+ docs: {+ description: 'Git pathspec operands must be built with pathspecArgs, not a hand-written --.',+ url: URL,+ },+ },+ create(context) {+ return {+ ArrayExpression(node) {+ if (isArgvFragment(node)) return;+ const tokens = [];+ collectArgv(node, tokens);+ if (violates(tokens)) context.report({ node, message: MESSAGE });+ },+ CallExpression(node) {+ if (!isRawCall(node) || !hasDirectSeparatorArgument(node)) return;+ const tokens = [];+ for (const argument of node.arguments) {+ collectFragment(argument, tokens);+ }+ if (violates(tokens)) context.report({ node, message: MESSAGE });+ },+ };+ },+};diff --git a/lint-plugins/ok-rules/scope.mjs b/lint-plugins/ok-rules/scope.mjsindex 81c1f8e8b..aea8c6bf6 100644--- a/lint-plugins/ok-rules/scope.mjs+++ b/lint-plugins/ok-rules/scope.mjs@@ -96,6 +96,16 @@ export const RULE_SCOPES = {'!packages/app/src/uninstall/**/*.dom.test.tsx','lint-plugins/ok-rules/__fixtures__/no-uninstall-forbidden-import.fixture.tsx',],+ 'no-unconverted-git-pathspec': [+ 'packages/core/src/**/*.ts',+ 'packages/server/src/**/*.ts',+ 'packages/cli/src/**/*.ts',+ 'packages/desktop/src/**/*.ts',+ '!packages/core/src/git-pathspec.ts',+ '!**/*.test.ts',+ '!**/*.test-helper.ts',+ 'lint-plugins/ok-rules/__fixtures__/no-unconverted-git-pathspec.fixture.tsx',+ ],'no-raw-html-interactive-element': ['packages/app/src/**/*.tsx','packages/desktop/src/**/*.tsx',diff --git a/oxlint.config.ts b/oxlint.config.tsindex 9ab3b57d5..37ef515fe 100644--- a/oxlint.config.ts+++ b/oxlint.config.ts@@ -65,6 +65,7 @@ export default defineConfig({'ok/no-roundtrip-identity-oracle': 'error','ok/no-split-suggestion-dispatch': 'error','ok/no-themeless-pierre-diff': 'error',+ 'ok/no-unconverted-git-pathspec': 'error','ok/no-uninstall-forbidden-import': 'error','ok/no-unportaled-editor-content': 'error','ok/no-unwrapped-user-facing-string': 'error',diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.tsindex a28cc2b18..8a60e5826 100644--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts@@ -1,4 +1,3 @@-import { readFileSync } from 'node:fs';import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';diff --git a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.tsindex 4fc2c11f9..6fcdc23f2 100644--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { normalizeBridge } from '@inkeep/open-knowledge-core';import { updateYFragment } from '@tiptap/y-tiptap';diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.tsindex 9f2f6feb6..40b5cdfd6 100644--- a/packages/app/tests/integration/interior-edit-freshness.test.ts+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.tsindex 2a085742b..93666af70 100644--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.tsindex 878d5196b..867598d34 100644--- a/packages/app/tests/integration/producer-guard-wiring.test.ts+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.tsindex 4ada3cf26..0970ac12f 100644--- a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts+++ b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts@@ -1,4 +1,3 @@-import { randomUUID } from 'node:crypto';import { afterEach, describe, expect, test } from 'vitest';import { agentWriteMd, createTestServer, type TestServer } from './test-harness';diff --git a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts b/packages/app/tests/integration/qa-045-restore-after-gc.test.tsindex cbe2b705f..b632185e1 100644--- a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts+++ b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts@@ -1,4 +1,3 @@-import { execFileSync } from 'node:child_process';import { randomUUID } from 'node:crypto';import { join } from 'node:path';diff --git a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.tsindex 89bc9b4d9..c530ce4ba 100644--- a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts+++ b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts@@ -1,4 +1,3 @@-import { randomUUID } from 'node:crypto';import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';import type * as Y from 'yjs';diff --git a/packages/app/tests/integration/undo-after-rollback.test.ts b/packages/app/tests/integration/undo-after-rollback.test.tsindex a78aeb0e4..d3767adc9 100644--- a/packages/app/tests/integration/undo-after-rollback.test.ts+++ b/packages/app/tests/integration/undo-after-rollback.test.ts@@ -1,4 +1,3 @@-import { ROLLBACK_ORIGIN } from '@inkeep/open-knowledge-server';import { afterAll, beforeAll, describe, expect, test } from 'vitest';import * as Y from 'yjs';diff --git a/packages/app/tests/integration/undo-recycle-reset.test.ts b/packages/app/tests/integration/undo-recycle-reset.test.tsindex e7cc69c3f..b076f955c 100644--- a/packages/app/tests/integration/undo-recycle-reset.test.ts+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts@@ -1,4 +1,3 @@-import { writeFileSync } from 'node:fs';import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';diff --git a/packages/app/tests/integration/undo-rederive-survival.test.ts b/packages/app/tests/integration/undo-rederive-survival.test.tsindex 9ddcd0730..7935e35f8 100644--- a/packages/app/tests/integration/undo-rederive-survival.test.ts+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts@@ -1,4 +1,3 @@-import { prependFrontmatter } from '@inkeep/open-knowledge-core';import { Plugin, PluginKey } from '@tiptap/pm/state';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';diff --git a/packages/app/tests/lint-plugins/no-unconverted-git-pathspec.test.ts b/packages/app/tests/lint-plugins/no-unconverted-git-pathspec.test.tsnew file mode 100644index 000000000..a652fab31--- /dev/null+++ b/packages/app/tests/lint-plugins/no-unconverted-git-pathspec.test.ts@@ -0,0 +1,72 @@+/** The `no-unconverted-git-pathspec` oxlint rule fixture test, per precedent #42. */++import { spawnSync } from 'node:child_process';+import { join } from 'node:path';+import { describe, expect, test } from 'vitest';+import { NON_PATHSPEC_VERBS } from '../../../../lint-plugins/ok-rules/rules/no-unconverted-git-pathspec.mjs';+import {+ oxlintFixtureArgs,+ parseOxlintDiagnostics,+ readEnabledRuleIds,+ readRegisteredRuleNames,+ readRuleScope,+} from '../../../../test-support/read-ok-rules-config.test-helper';++const REPO_ROOT = join(__dirname, '..', '..', '..', '..');+const FIXTURE_REL = 'lint-plugins/ok-rules/__fixtures__/no-unconverted-git-pathspec.fixture.tsx';+const RULE_CODE = 'ok(no-unconverted-git-pathspec)';++function runFixture(): { status: number | null; output: string } {+ const result = spawnSync('pnpm', oxlintFixtureArgs(FIXTURE_REL), {+ cwd: REPO_ROOT,+ encoding: 'utf-8',+ });+ expect(result.error).toBeUndefined();+ return { status: result.status, output: `${result.stdout}\n${result.stderr}` };+}++describe('no-unconverted-git-pathspec oxlint rule', () => {+ test('fires on exactly 7 planted positives (and on no negative case)', () => {+ const { status, output } = runFixture();+ expect(status).not.toBe(0);+ const fires = parseOxlintDiagnostics(output).filter((d) => d.code === RULE_CODE);+ expect(fires.length).toBe(7);+ });++ test('its message names the fix and links this rule section of the README', () => {+ const [first] = parseOxlintDiagnostics(runFixture().output).filter((d) => d.code === RULE_CODE);+ expect(first?.message).toContain('pathspecArgs(paths)');+ expect(first?.message).toMatch(/https?:\/\/[^\s]+/);+ expect(first?.message).toContain('lint-plugins/ok-rules/README.md#no-unconverted-git-pathspec');+ });++ test('rule is registered, enabled, and scoped via its RULE_SCOPES entry', async () => {+ expect(await readRegisteredRuleNames(REPO_ROOT)).toContain('no-unconverted-git-pathspec');+ expect(await readEnabledRuleIds(REPO_ROOT)).toContain('ok/no-unconverted-git-pathspec');+ expect(readRuleScope(REPO_ROOT, 'no-unconverted-git-pathspec')).not.toEqual([]);+ });++ test('its scope table still carries every include and exclude the rule depends on', () => {+ const scope = readRuleScope(REPO_ROOT, 'no-unconverted-git-pathspec');+ expect(scope).toContain(FIXTURE_REL);+ for (const included of [+ 'packages/core/src/**/*.ts',+ 'packages/server/src/**/*.ts',+ 'packages/cli/src/**/*.ts',+ 'packages/desktop/src/**/*.ts',+ ]) {+ expect(scope).toContain(included);+ }+ for (const excluded of [+ '!packages/core/src/git-pathspec.ts',+ '!**/*.test.ts',+ '!**/*.test-helper.ts',+ ]) {+ expect(scope).toContain(excluded);+ }+ });++ test('exempts every verb whose "--" operands are not pathspecs, and nothing else', () => {+ expect([...NON_PATHSPEC_VERBS].sort()).toEqual(['clone', 'hash-object', 'mv', 'worktree']);+ });+});diff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.tsindex f2ed869f1..152f0730c 100644--- a/packages/cli/src/commands/init.test.ts+++ b/packages/cli/src/commands/init.test.ts@@ -3087,7 +3087,7 @@ describe('runInit — sharing mode', () => {expect(result.sharing.kind).toBe('refused-tracked');if (result.sharing.kind !== 'refused-tracked') throw new Error('expected refused-tracked');expect(result.sharing.tracked).toContain('.mcp.json');- expect(result.sharing.remediation).toContain('git rm --cached .mcp.json');+ expect(result.sharing.remediation).toContain('git rm --cached -- .mcp.json');expect(existsSync(join(testDir, '.mcp.json'))).toBe(true);});diff --git a/packages/cli/src/commands/sharing/sharing.test.ts b/packages/cli/src/commands/sharing/sharing.test.tsindex 62ee42d22..3b3180cf9 100644--- a/packages/cli/src/commands/sharing/sharing.test.ts+++ b/packages/cli/src/commands/sharing/sharing.test.ts@@ -188,7 +188,7 @@ describe('ok config-sharing unshare — §5.5 tracked-files refusal', () => {});expect(process.exitCode).toBe(1);expect(stderr).toContain('Cannot switch OpenKnowledge to local-only');- expect(stderr).toContain('git rm --cached .mcp.json');+ expect(stderr).toContain('git rm --cached -- .mcp.json');expect(stderr).toContain('your teammates will see a deletion on their next pull');const after = readExclude(dir);diff --git a/packages/cli/src/sharing/git-exclude.test.ts b/packages/cli/src/sharing/git-exclude.test.tsindex e1d97ffb3..6bb392221 100644--- a/packages/cli/src/sharing/git-exclude.test.ts+++ b/packages/cli/src/sharing/git-exclude.test.ts@@ -257,7 +257,7 @@ describe('addOkPathsToGitExclude', () => {if (result.kind !== 'refused-tracked') throw new Error('unreachable');expect(result.tracked).toEqual(['.mcp.json']);expect(result.remediation).toContain('Cannot switch OpenKnowledge to local-only');- expect(result.remediation).toContain('git rm --cached .mcp.json');+ expect(result.remediation).toContain('git rm --cached -- .mcp.json');expect(readExclude(dir)).toBe('');});@@ -515,13 +515,30 @@ describe('probeTrackedOkPaths', () => {});});+function quoteForPlatform(value: string): string {+ return process.platform === 'win32' ? `"${value}"` : `'${value}'`;+}+describe('formatTrackedRemediation', () => {it('lists tracked paths and emits a `git rm --cached` for each — `-r` for dirs', () => {const out = formatTrackedRemediation(['.mcp.json', '.claude/skills/open-knowledge/']);expect(out).toContain(' .mcp.json');expect(out).toContain(' .claude/skills/open-knowledge/');- expect(out).toContain('git rm --cached .mcp.json');- expect(out).toContain('git rm --cached -r .claude/skills/open-knowledge');+ expect(out).toContain('git rm --cached -- .mcp.json');+ expect(out).toContain('git rm --cached -r -- .claude/skills/open-knowledge');+ });++ it('leaves a shell- and pathspec-safe name bare, so the line pastes into any shell', () => {+ const out = formatTrackedRemediation(['.mcp.json']);+ const commandLine = out.split('\n').find((l) => l.includes('git rm --cached'));+ expect(commandLine?.trim()).toBe('git rm --cached -- .mcp.json');+ });++ it('converts and quotes a name git would read as a pattern', () => {+ const out = formatTrackedRemediation(['star*.md', ':colon.md', ':!bang.md']);+ for (const name of ['star*.md', ':colon.md', ':!bang.md']) {+ expect(out).toContain(`git rm --cached -- ${quoteForPlatform(`:(literal)${name}`)}`);+ }});it('warns about the teammate-side-effect of `git rm --cached`', () => {@@ -566,7 +583,7 @@ describe('shared -> local-only transition with tracked shareable .ok artifacts',expect(result.kind).toBe('refused-tracked');if (result.kind !== 'refused-tracked') throw new Error('unreachable');expect(result.tracked).toEqual(['.ok/']);- expect(result.remediation).toContain('git rm --cached -r .ok');+ expect(result.remediation).toContain('git rm --cached -r -- .ok');expect(result.remediation).toContain('your teammates will see a deletion on their next pull');expect(readExclude(dir)).toBe('');expect(readSharingMode(dir)).toBe('shared');diff --git a/packages/cli/src/sharing/git-exclude.ts b/packages/cli/src/sharing/git-exclude.tsindex c24ce963a..bc46561b0 100644--- a/packages/cli/src/sharing/git-exclude.ts+++ b/packages/cli/src/sharing/git-exclude.ts@@ -8,7 +8,9 @@ import {LEGACY_SKILL_STORE_ROOT,OK_DIR,parseInstalledSkills,+ pathspecArgs,RESERVED_PROJECT_SKILL_NAME,+ toPathspec,} from '@inkeep/open-knowledge-core';import { discoverGitRepository } from '@inkeep/open-knowledge-core/git-repository';import { withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';@@ -257,7 +259,7 @@ export function probeTrackedOkPaths(try {execFileSync('git',- ['ls-files', '--error-unmatch', '--', p],+ ['ls-files', '--error-unmatch', ...pathspecArgs([p])],withHiddenWindowsConsole({cwd: projectRoot,stdio: ['ignore', 'ignore', 'ignore'],@@ -269,6 +271,17 @@ export function probeTrackedOkPaths(return { tracked };}+const SHELL_AND_PATHSPEC_SAFE = /^[\w.\-/]+$/;++function shellQuote(value: string): string {+ if (process.platform === 'win32') return `"${value.replaceAll('"', '')}"`;+ return `'${value.replaceAll("'", "'\\''")}'`;+}++function remediationOperand(path: string): string {+ return SHELL_AND_PATHSPEC_SAFE.test(path) ? path : shellQuote(toPathspec(path));+}+export function formatTrackedRemediation(tracked: readonly string[]): string {const lines: string[] = [];lines.push('Cannot switch OpenKnowledge to local-only — these OK files are tracked upstream:');@@ -282,7 +295,7 @@ export function formatTrackedRemediation(tracked: readonly string[]): string {for (const p of tracked) {const arg = p.replace(/\/$/, '');const recursive = p.endsWith('/') ? '-r ' : '';- lines.push(` git rm --cached ${recursive}${arg}`);+ lines.push(` git rm --cached ${recursive}-- ${remediationOperand(arg)}`);}lines.push('');lines.push(diff --git a/packages/cli/src/sharing/git-pathspec-name-invariance.test.ts b/packages/cli/src/sharing/git-pathspec-name-invariance.test.tsnew file mode 100644index 000000000..db63aed5e--- /dev/null+++ b/packages/cli/src/sharing/git-pathspec-name-invariance.test.ts@@ -0,0 +1,57 @@+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { probeTrackedOkPaths } from './git-exclude.ts';++let projectRoot = '';++function git(args: string[]): string {+ return execFileSync('git', args, {+ cwd: projectRoot,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'pipe'],+ }).trim();+}++function writeSkillFile(name: string, body: string): string {+ const rel = `.ok/skills/${name}/SKILL.md`;+ mkdirSync(join(projectRoot, '.ok', 'skills', name), { recursive: true });+ writeFileSync(join(projectRoot, rel), body, 'utf-8');+ return rel;+}++beforeEach(() => {+ projectRoot = mkdtempSync(join(tmpdir(), 'ok-cli-pathspec-'));+ git(['init', '-q', '-b', 'main', '.']);+ git(['config', 'user.name', 'Test']);+ git(['config', 'user.email', '[email protected]']);+ writeFileSync(join(projectRoot, 'README.md'), '# seed\n', 'utf-8');+ git(['add', '--', 'README.md']);+ git(['commit', '-qm', 'seed']);+});++afterEach(() => {+ rmSync(projectRoot, { recursive: true, force: true });+});++describe('probeTrackedOkPaths — pathspec name invariance (site 14)', () => {+ it('does not report an untracked wildcard-named skill file as tracked', () => {+ const trackedSibling = writeSkillFile('starfish', '# starfish\n');+ git(['add', '--', trackedSibling]);+ git(['commit', '-qm', 'track the sibling skill']);++ const untracked = writeSkillFile('star*', '# wildcard\n');++ expect(probeTrackedOkPaths(projectRoot, [untracked])).toEqual({ tracked: [] });+ });++ it('reports a tracked wildcard-named skill file as tracked', () => {+ const wildcard = writeSkillFile('star*', '# wildcard\n');+ git(['add', '--', `:(literal)${wildcard}`]);+ git(['commit', '-qm', 'track the wildcard skill']);++ expect(probeTrackedOkPaths(projectRoot, [wildcard])).toEqual({ tracked: [wildcard] });+ });+});diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.tsindex 2a597ec3d..f4cc8a286 100644--- a/packages/core/src/bridge/compose.ts+++ b/packages/core/src/bridge/compose.ts@@ -1,4 +1,3 @@-import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 01ef76a9f..8fb428b90 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,4 +1,3 @@-import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';diff --git a/packages/core/src/git-pathspec.test.ts b/packages/core/src/git-pathspec.test.tsnew file mode 100644index 000000000..95e25e809--- /dev/null+++ b/packages/core/src/git-pathspec.test.ts@@ -0,0 +1,106 @@+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import { pathspecArgs, stripPathspecMagic, toPathspec } from './git-pathspec.ts';++const HOSTILE_NAMES = [':colon.md', ':!bang.md', 'star*.md'] as const;+const PLAIN_NAMES = ['plain.md', 'starfish.md'] as const;++let repo: string;++function git(args: readonly string[], cwd = repo): string {+ return execFileSync('git', args, { cwd, encoding: 'utf-8' });+}++beforeAll(() => {+ repo = mkdtempSync(join(tmpdir(), 'ok-git-pathspec-'));+ git(['init', '--initial-branch=main']);+ git(['config', 'user.email', '[email protected]']);+ git(['config', 'user.name', 'Test']);+ for (const name of [...HOSTILE_NAMES, ...PLAIN_NAMES]) {+ writeFileSync(join(repo, name), `${name}\n`, 'utf-8');+ }+ mkdirSync(join(repo, 'sub'), { recursive: true });+ writeFileSync(join(repo, 'sub', 'nested.md'), 'nested\n', 'utf-8');+});++afterAll(() => {+ rmSync(repo, { recursive: true, force: true });+});++describe('toPathspec', () => {+ test('prefixes the literal magic word', () => {+ expect(toPathspec('x')).toBe(':(literal)x');+ expect(toPathspec(':colon.md')).toBe(':(literal):colon.md');+ });++ test('refuses an empty path rather than widening to every tracked path', () => {+ expect(() => toPathspec('')).toThrow(/empty path/);+ });+});++describe('stripPathspecMagic', () => {+ test('round-trips a converted operand back to the path it came from', () => {+ expect(stripPathspecMagic(toPathspec(':colon.md'))).toBe(':colon.md');+ });++ test('removes the magic word git echoes back in its own message text', () => {+ expect(+ stripPathspecMagic("fatal: pathspec ':(literal)notes/plan.md' did not match any files"),+ ).toBe("fatal: pathspec 'notes/plan.md' did not match any files");+ });+});++describe('pathspecArgs', () => {+ test('owns the -- separator and converts every operand', () => {+ expect(pathspecArgs(['a', 'b'])).toEqual(['--', ':(literal)a', ':(literal)b']);+ });++ test('refuses an empty list rather than emitting an unrestricted bare separator', () => {+ expect(() => pathspecArgs([])).toThrow(/empty path list/);+ });+});++describe('real git selection', () => {+ test('a leading-colon name is staged as data, not read as magic', () => {+ git(['reset']);+ git(['add', ...pathspecArgs([':colon.md'])]);+ expect(git(['diff', '--cached', '--name-only']).trim()).toBe(':colon.md');+ });++ test('a leading-":!" name stages itself instead of subtracting everything', () => {+ git(['reset']);+ git(['add', ...pathspecArgs([':!bang.md'])]);+ expect(git(['diff', '--cached', '--name-only']).trim()).toBe(':!bang.md');+ });++ test('a wildcard name selects only itself', () => {+ expect(git(['ls-files', '--others', ...pathspecArgs(['star*.md'])]).trim()).toBe('star*.md');+ });++ test('an unconverted wildcard name over-matches its sibling', () => {+ expect(git(['ls-files', '--others', '--', 'star*.md']).trim().split('\n')).toEqual([+ 'star*.md',+ 'starfish.md',+ ]);+ });++ test('the "." scope sentinel selects the same set converted or bare', () => {+ const bare = git(['ls-files', '--others', '--', '.']);+ const converted = git(['ls-files', '--others', ...pathspecArgs(['.'])]);+ expect(converted).toBe(bare);+ });++ test('a directory operand still scopes by prefix', () => {+ expect(git(['ls-files', '--others', ...pathspecArgs(['sub'])]).trim()).toBe('sub/nested.md');+ });++ test('git echoes plain paths regardless of the operand form', () => {+ git(['reset']);+ git(['add', ...pathspecArgs([':colon.md'])]);+ expect(git(['ls-files', '--cached', ...pathspecArgs([':colon.md'])]).trim()).toBe(':colon.md');+ git(['reset']);+ });+});diff --git a/packages/core/src/git-pathspec.ts b/packages/core/src/git-pathspec.tsnew file mode 100644index 000000000..537e72fe6--- /dev/null+++ b/packages/core/src/git-pathspec.ts@@ -0,0 +1,31 @@+export type Pathspec = string & { readonly __brand: 'Pathspec' };++type Assert<T extends true> = T;++type _RawStringIsNotAPathspec = Assert<string extends Pathspec ? false : true>;++const LITERAL_MAGIC = ':(literal)';++export function toPathspec(path: string & { readonly __brand?: undefined }): Pathspec {+ if (path === '') {+ throw new Error(+ 'toPathspec: empty path. ":(literal)" is an empty pattern that matches every tracked path; pass "." if you meant the repo root.',+ );+ }+ return `${LITERAL_MAGIC}${path}` as Pathspec;+}++export function pathspecArgs(+ paths: readonly (string & { readonly __brand?: undefined })[],+): [string, ...Pathspec[]] {+ if (paths.length === 0) {+ throw new Error(+ 'pathspecArgs: empty path list. A bare "--" removes the pathspec restriction rather than selecting nothing.',+ );+ }+ return ['--', ...paths.map((p) => toPathspec(p))];+}++export function stripPathspecMagic(text: string): string {+ return text.replaceAll(LITERAL_MAGIC, '');+}diff --git a/packages/core/src/git-pathspec.type-tests.ts b/packages/core/src/git-pathspec.type-tests.tsnew file mode 100644index 000000000..196a8e10f--- /dev/null+++ b/packages/core/src/git-pathspec.type-tests.ts@@ -0,0 +1,14 @@+import { pathspecArgs, toPathspec } from './git-pathspec.ts';+import type { Bcp47Tag } from './i18n/bcp47.ts';++// @ts-expect-error -- a Pathspec is already converted; re-converting yields ':(literal):(literal)x', which matches nothing.+const _doubleConverted = toPathspec(toPathspec('x'));+void _doubleConverted;++// @ts-expect-error -- pathspecArgs returns branded operands, so re-feeding its result would convert the separator too.+const _reConvertedArgs = pathspecArgs(pathspecArgs(['a']));+void _reConvertedArgs;++// @ts-expect-error -- a sibling brand is not a raw path; pins the cross-brand rejection so a future brand declared with a different key cannot be accepted as an unconverted path.+const _siblingBrand = toPathspec('en-US' as Bcp47Tag);+void _siblingBrand;diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 0cb8c232c..af71f8289 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -683,6 +683,12 @@ export {type WorktreeSelectorEntry,type WorktreeSelectorModel,} from './git/worktree-selector-model.ts';+export {+ type Pathspec,+ pathspecArgs,+ stripPathspecMagic,+ toPathspec,+} from './git-pathspec.ts';export {type AssembleHandoffPromptInput,assembleHandoffPrompt,diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex 20a68d2a1..bfbd5a2e8 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex fa3cfcd86..bfd7e3109 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,4 +1,3 @@-import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 8be632ba4..4d3250d3a 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,4 +1,3 @@-export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex bf1a4db68..94c995a78 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -59,6 +59,7 @@ import {type Principal,type ProblemType,parseFrontmatterRecord,+ pathspecArgs,type ReLintFailure,readFmMap,SKILL_NAME_REGEX,@@ -1194,7 +1195,7 @@ function renamePathOnDisk(sourcePath: string, destinationPath: string): void {}}-async function renameTrackedPathInGit(+export async function renameTrackedPathInGit(projectDir: string | undefined,sourcePath: string,destinationPath: string,@@ -1208,7 +1209,7 @@ async function renameTrackedPathInGit(const pg = simpleGit({ baseDir: projectDir, timeout: { block: 15_000 } });let tracked = '';try {- tracked = (await pg.raw('ls-files', '--', sourceRel)).trim();+ tracked = (await pg.raw('ls-files', ...pathspecArgs([sourceRel]))).trim();} catch (err) {log.warn({ err }, '[renameTrackedPathInGit] git ls-files failed, falling back to fs rename');return false;@@ -4384,7 +4385,7 @@ export function createApiExtension(return (await sg.raw('rev-parse', mine)).trim();};const treeHas = async (sha: string, rel: string): Promise<boolean> => {- const out = await sg.raw('ls-tree', '-r', '--name-only', sha, '--', rel);+ const out = await sg.raw('ls-tree', '-r', '--name-only', sha, ...pathspecArgs([rel]));return out.trim().length > 0;};let sha = await readMine();diff --git a/packages/server/src/conflict-storage.ts b/packages/server/src/conflict-storage.tsindex ea9e2be53..6310170c9 100644--- a/packages/server/src/conflict-storage.ts+++ b/packages/server/src/conflict-storage.ts@@ -1,5 +1,6 @@import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';+import { pathspecArgs } from '@inkeep/open-knowledge-core';import { getLocalDir } from './config/paths.ts';import { NoConflictTrackedError } from './conflict-errors.ts';import { requireConflictResolutionContent } from './conflict-resolution-input.ts';@@ -158,13 +159,13 @@ export class ConflictStore {switch (strategy) {case 'mine':- await handle.git.raw(['checkout', '--ours', '--', file]);- await handle.git.raw(['add', '--', file]);+ await handle.git.raw(['checkout', '--ours', ...pathspecArgs([file])]);+ await handle.git.raw(['add', ...pathspecArgs([file])]);break;case 'theirs':- await handle.git.raw(['checkout', '--theirs', '--', file]);- await handle.git.raw(['add', '--', file]);+ await handle.git.raw(['checkout', '--theirs', ...pathspecArgs([file])]);+ await handle.git.raw(['add', ...pathspecArgs([file])]);break;case 'content': {@@ -178,12 +179,12 @@ export class ConflictStore {allowShareableOkArtifact: isShareableOkArtifact,});tracedWriteFileSync(target, resolved, 'utf-8');- await handle.git.raw(['add', '--', file]);+ await handle.git.raw(['add', ...pathspecArgs([file])]);break;}case 'delete': {- await handle.git.raw(['rm', '--', file]);+ await handle.git.raw(['rm', ...pathspecArgs([file])]);break;}diff --git a/packages/server/src/content/project-log.ts b/packages/server/src/content/project-log.tsindex 37a8f8b52..ecb487ea8 100644--- a/packages/server/src/content/project-log.ts+++ b/packages/server/src/content/project-log.ts@@ -1,5 +1,6 @@import { statSync } from 'node:fs';import { resolve } from 'node:path';+import { pathspecArgs } from '@inkeep/open-knowledge-core';import simpleGit, { type SimpleGit } from 'simple-git';export interface GitCommit {@@ -45,8 +46,7 @@ export async function readProjectGitLog(`-${Math.max(1, limit)}`,'--format=%H|%aI|%an|%s','--follow',- '--',- relPath,+ ...pathspecArgs([relPath]),);} catch {return { commits: [], source: 'git' };diff --git a/packages/server/src/content/shadow-log.ts b/packages/server/src/content/shadow-log.tsindex cb6457062..951e27aaf 100644--- a/packages/server/src/content/shadow-log.ts+++ b/packages/server/src/content/shadow-log.ts@@ -1,5 +1,5 @@import { resolve } from 'node:path';-import type { ShadowContributor } from '@inkeep/open-knowledge-core';+import { pathspecArgs, type ShadowContributor } from '@inkeep/open-knowledge-core';import {getShadowRepoPath,getWipRefPattern,@@ -70,8 +70,7 @@ async function logOnRef(ref,`-${Math.max(1, limit * 2)}`,'--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e',- '--',- relPath,+ ...pathspecArgs([relPath]),);} catch {return [];@@ -128,8 +127,7 @@ async function checkpointAncestryFallback(...anchors,`-${Math.max(need * 3, 20)}`,'--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e',- '--',- relPath,+ ...pathspecArgs([relPath]),);} catch (err) {getLogger('shadow-log').warn(diff --git a/packages/server/src/error-classification.test.ts b/packages/server/src/error-classification.test.tsindex 22791afba..dd997462b 100644--- a/packages/server/src/error-classification.test.ts+++ b/packages/server/src/error-classification.test.ts@@ -513,6 +513,15 @@ describe('classifyGitError', () => {expect(r.userFacingCode).toBeNull();});+ test('the raw-passthrough message drops literal-pathspec magic but rawStderr keeps it', () => {+ const raw = "fatal: pathspec ':(literal)notes/plan.md' did not match any files";+ const r = classifyGitError(mkErr(raw, raw));+ expect(r.subclass).toBe('unknown-local');+ expect(r.userFacingCode).toBeNull();+ expect(r.message).toBe("fatal: pathspec 'notes/plan.md' did not match any files");+ expect(r.rawStderr).toContain(':(literal)');+ });+test('userFacingCode is either a bounded enum value or null on every classification', () => {const validCodes = new Set(['auth-403',diff --git a/packages/server/src/error-classification.ts b/packages/server/src/error-classification.tsindex 9005d33a5..4b52001b2 100644--- a/packages/server/src/error-classification.ts+++ b/packages/server/src/error-classification.ts@@ -2,6 +2,7 @@ import {classifyGitAuthError,type GitAuthFailureSubclass,type SyncErrorCode,+ stripPathspecMagic,} from '@inkeep/open-knowledge-core';type NetworkSubclass = 'dns' | 'timeout' | '5xx' | '429' | 'connection-refused' | 'unknown-network';@@ -394,7 +395,7 @@ function classifyGitErrorBase(error: Error | unknown): ClassifiedErrorBase {class: 'local',subclass: 'unknown-local',retryable: true,- message: err.message || 'Unknown git error',+ message: stripPathspecMagic(err.message) || 'Unknown git error',rawStderr: raw,};}diff --git a/packages/server/src/git-pathspec-name-invariance.test.ts b/packages/server/src/git-pathspec-name-invariance.test.tsnew file mode 100644index 000000000..be212a9b4--- /dev/null+++ b/packages/server/src/git-pathspec-name-invariance.test.ts@@ -0,0 +1,613 @@+import { execFileSync } from 'node:child_process';+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { LOCAL_DIR } from '@inkeep/open-knowledge-core';+import simpleGit from 'simple-git';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { renameTrackedPathInGit } from './api-extension.ts';+import { ConflictStore } from './conflict-storage.ts';+import { readProjectGitLog } from './content/project-log.ts';+import { readShadowLog } from './content/shadow-log.ts';+import { TRACKED_MCP_CONFIG_TARGETS } from './mcp-config-reconciler.ts';+import { logSeededReachable } from './rename-log.ts';+import {+ commitWip,+ initShadowRepo,+ type ShadowHandle,+ saveVersion,+ type WriterIdentity,+} from './shadow-repo.ts';+import { computeShareFreshness } from './share/freshness.ts';+import { createGitTriangle, type GitTriangle } from './share/git-fixture.test-helper.ts';+import { computeShareTargetStatus } from './share/target-status.ts';+import { restoreSkillVersion } from './skill-restore.ts';+import { SyncEngine } from './sync-engine.ts';+import { getDocumentHistory } from './timeline-query.ts';++const MAGIC_PREFIX_DOC = ':colon.md';+const EXCLUDE_MAGIC_DOC = ':!bang.md';+const PLAIN_DOC = 'plain.md';++const stubContentFilter = {+ isExcluded: (_path: string) => false,+ isDirExcluded: (_path: string) => false,+};++function git(cwd: string, args: string[]): string {+ return execFileSync('git', args, {+ cwd,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'pipe'],+ }).trim();+}++function addByLiteralPathspec(cwd: string, relPaths: string[]): void {+ git(cwd, ['add', '--', ...relPaths.map((p) => `:(literal)${p}`)]);+}++function originTreePaths(bareDir: string): string[] {+ const out = git(bareDir, ['ls-tree', '-r', '--name-only', 'main']);+ return out === '' ? [] : out.split('\n');+}++let tmpDir = '';+let projectDir = '';+let okDir = '';++beforeEach(async () => {+ tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-pathspec-invariance-'));+ projectDir = join(tmpDir, 'project');+ okDir = join(projectDir, '.ok', LOCAL_DIR);+ mkdirSync(okDir, { recursive: true });+});++afterEach(async () => {+ await rm(tmpDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+});++const triangles: GitTriangle[] = [];++function newTriangle(): GitTriangle {+ const t = createGitTriangle();+ triangles.push(t);+ return t;+}++afterEach(() => {+ for (const t of triangles.splice(0)) t.cleanup();+});++async function initProjectWithBareRemote(): Promise<string> {+ const bareDir = join(tmpDir, 'bare.git');+ mkdirSync(bareDir, { recursive: true });+ await simpleGit(bareDir).init(true);+ await simpleGit(bareDir).raw('symbolic-ref', 'HEAD', 'refs/heads/main');++ const g = simpleGit(projectDir);+ await g.init(['--initial-branch=main']);+ await g.raw('config', 'user.name', 'Test');+ await g.raw('config', 'user.email', '[email protected]');+ writeFileSync(join(projectDir, 'README.md'), '# seed\n', 'utf-8');+ await g.add('.');+ await g.commit('seed');+ await g.addRemote('origin', bareDir);+ await g.push(['--set-upstream', 'origin', 'main']);+ return bareDir;+}++function makePushEngine(): SyncEngine {+ return new SyncEngine({+ projectDir,+ contentDir: projectDir,+ contentFilter: stubContentFilter,+ syncEnabled: true,+ });+}++describe('pathspec name invariance — sync-engine stageContentFiles (site 1)', () => {+ test('a doc whose name starts with ":" is pushed, and does not strand its plain siblings', async () => {+ const bareDir = await initProjectWithBareRemote();+ writeFileSync(join(projectDir, MAGIC_PREFIX_DOC), 'colon body\n', 'utf-8');+ writeFileSync(join(projectDir, PLAIN_DOC), 'plain body\n', 'utf-8');++ const engine = makePushEngine();+ try {+ await engine.start();+ await engine.trigger('push');++ expect(engine.getStatus().pushError).toBeUndefined();+ expect(originTreePaths(bareDir)).toEqual(+ expect.arrayContaining([MAGIC_PREFIX_DOC, PLAIN_DOC]),+ );+ expect(git(projectDir, ['status', '--porcelain'])).toBe('');+ } finally {+ await engine.destroy();+ }+ });++ test('a doc whose name starts with ":!" is pushed rather than silently dropped', async () => {+ const bareDir = await initProjectWithBareRemote();+ writeFileSync(join(projectDir, EXCLUDE_MAGIC_DOC), 'exclusion-magic body\n', 'utf-8');+ writeFileSync(join(projectDir, PLAIN_DOC), 'plain body\n', 'utf-8');++ const engine = makePushEngine();+ try {+ await engine.start();+ await engine.trigger('push');++ expect(engine.getStatus().pushError).toBeUndefined();+ expect(originTreePaths(bareDir)).toEqual(+ expect.arrayContaining([EXCLUDE_MAGIC_DOC, PLAIN_DOC]),+ );+ } finally {+ await engine.destroy();+ }+ });+});++describe('pathspec name invariance — share freshness probes (site 2)', () => {+ test('an uncommitted edit to a ":"-named doc reads stale, exactly as a plain doc does', async () => {+ const t = newTriangle();+ t.writeWorkingTree(MAGIC_PREFIX_DOC, 'v1\n');+ t.writeWorkingTree(PLAIN_DOC, 'v1\n');+ addByLiteralPathspec(t.senderDir, [MAGIC_PREFIX_DOC, PLAIN_DOC]);+ t.git(t.senderDir, ['commit', '-m', 'seed both']);+ t.git(t.senderDir, ['push', 'origin', t.branch]);++ t.writeWorkingTree(MAGIC_PREFIX_DOC, 'v2 local edit\n');+ t.writeWorkingTree(PLAIN_DOC, 'v2 local edit\n');++ expect(await computeShareFreshness(t.senderDir, t.branch, PLAIN_DOC, 'doc')).toBe('stale');+ expect(await computeShareFreshness(t.senderDir, t.branch, MAGIC_PREFIX_DOC, 'doc')).toBe(+ 'stale',+ );+ });++ test('an untracked doc inside a ":"-named folder makes that folder stale', async () => {+ const t = newTriangle();+ t.writeWorkingTree(':folder/a.md', 'a\n');+ addByLiteralPathspec(t.senderDir, [':folder/a.md']);+ t.git(t.senderDir, ['commit', '-m', 'seed colon folder']);+ t.git(t.senderDir, ['push', 'origin', t.branch]);++ t.writeWorkingTree(':folder/new.md', 'brand new, unstaged\n');++ expect(await computeShareFreshness(t.senderDir, t.branch, ':folder', 'folder')).toBe('stale');+ });+});++describe('pathspec name invariance — share target status (site 12)', () => {+ test('a ":"-named doc deleted on origin reads deleted, not never-on-branch', async () => {+ const t = newTriangle();+ t.writeWorkingTree(MAGIC_PREFIX_DOC, '# will be removed with no successor\n');+ addByLiteralPathspec(t.senderDir, [MAGIC_PREFIX_DOC]);+ t.git(t.senderDir, ['commit', '-m', 'seed colon doc']);+ t.git(t.senderDir, ['push', 'origin', t.branch]);++ const receiver = t.cloneReceiver();++ t.git(t.senderDir, ['rm', '--', `:(literal)${MAGIC_PREFIX_DOC}`]);+ t.git(t.senderDir, ['commit', '-m', 'delete colon doc']);+ t.git(t.senderDir, ['push', 'origin', t.branch]);++ const status = await computeShareTargetStatus(receiver, t.branch, MAGIC_PREFIX_DOC, 'doc', {+ credentialConfig: [],+ });+ expect(status.verdict).toBe('deleted');+ });+});++describe('pathspec name invariance — project git log (site 10)', () => {+ test('a ":"-named doc has its commit history, not an empty list', async () => {+ await initProjectWithBareRemote();+ writeFileSync(join(projectDir, MAGIC_PREFIX_DOC), 'colon v1\n', 'utf-8');+ writeFileSync(join(projectDir, PLAIN_DOC), 'plain v1\n', 'utf-8');+ addByLiteralPathspec(projectDir, [MAGIC_PREFIX_DOC, PLAIN_DOC]);+ git(projectDir, ['commit', '-m', 'add both docs']);++ const plain = await readProjectGitLog(projectDir, PLAIN_DOC, 5);+ const magic = await readProjectGitLog(projectDir, MAGIC_PREFIX_DOC, 5);++ expect(plain.source).toBe('git');+ expect(plain.commits.length).toBe(1);+ expect(magic.source).toBe('git');+ expect(magic.commits.length).toBe(1);+ expect(magic.commits[0]?.subject).toBe('add both docs');+ });+});++describe('pathspec name invariance — conflict resolution (site 8)', () => {+ test("resolving a ':'-named index conflict with 'theirs' clears the unmerged entry", async () => {+ await initProjectWithBareRemote();+ writeFileSync(join(projectDir, MAGIC_PREFIX_DOC), 'base\n', 'utf-8');+ addByLiteralPathspec(projectDir, [MAGIC_PREFIX_DOC]);+ git(projectDir, ['commit', '-m', 'base colon doc']);++ git(projectDir, ['checkout', '-b', 'side']);+ writeFileSync(join(projectDir, MAGIC_PREFIX_DOC), 'their version\n', 'utf-8');+ addByLiteralPathspec(projectDir, [MAGIC_PREFIX_DOC]);+ git(projectDir, ['commit', '-m', 'side edit']);++ git(projectDir, ['checkout', 'main']);+ writeFileSync(join(projectDir, MAGIC_PREFIX_DOC), 'my version\n', 'utf-8');+ addByLiteralPathspec(projectDir, [MAGIC_PREFIX_DOC]);+ git(projectDir, ['commit', '-m', 'main edit']);++ try {+ git(projectDir, ['merge', 'side']);+ } catch {}+ expect(git(projectDir, ['ls-files', '-u'])).not.toBe('');++ const store = new ConflictStore(projectDir, 'main');+ store.addConflict({ file: MAGIC_PREFIX_DOC, detectedAt: new Date().toISOString() });++ await expect(store.resolveConflict(MAGIC_PREFIX_DOC, 'theirs')).resolves.toBeUndefined();++ expect(git(projectDir, ['ls-files', '-u'])).toBe('');+ expect(store.count()).toBe(0);+ });+});++describe('pathspec name invariance — commitBlockingPaths (site 3)', () => {+ const BLOCKING_NAME = ':colon.json';++ const markdownOnlyFilter = {+ isExcluded: (path: string) => !path.endsWith('.md'),+ isDirExcluded: (_path: string) => false,+ };++ async function setupColonNamedOverlap(): Promise<void> {+ const bareDir = join(tmpDir, 'bare.git');+ mkdirSync(bareDir, { recursive: true });+ const bare = simpleGit(bareDir);+ await bare.init(true);+ await bare.raw('symbolic-ref', 'HEAD', 'refs/heads/main');++ const sisterDir = join(tmpDir, 'sister');+ mkdirSync(sisterDir, { recursive: true });+ const sister = simpleGit(sisterDir);+ await sister.init(['--initial-branch=main']);+ await sister.raw('config', 'user.name', 'Sister');+ await sister.raw('config', 'user.email', '[email protected]');+ writeFileSync(join(sisterDir, BLOCKING_NAME), '{"a":1}\n', 'utf-8');+ writeFileSync(join(sisterDir, 'foo.md'), 'base\n', 'utf-8');+ await sister.add('-A');+ await sister.commit('base');+ await sister.addRemote('origin', bareDir);+ await sister.push('origin', 'main');++ rmSync(projectDir, { recursive: true, force: true });+ await simpleGit(tmpDir).clone(bareDir, projectDir);+ mkdirSync(okDir, { recursive: true });+ const project = simpleGit(projectDir);+ await project.raw('config', 'user.name', 'Project');+ await project.raw('config', 'user.email', '[email protected]');++ writeFileSync(join(sisterDir, BLOCKING_NAME), '{"a":99}\n', 'utf-8');+ await sister.add('-A');+ await sister.commit('remote edit');+ await sister.push('origin', 'main');++ writeFileSync(join(projectDir, BLOCKING_NAME), '{"a":2}\n', 'utf-8');+ }++ test('a ":"-named blocking path is committed on request and the pause is cleared', async () => {+ await setupColonNamedOverlap();+ const engine = new SyncEngine({+ projectDir,+ contentDir: projectDir,+ contentFilter: markdownOnlyFilter,+ mode: 'full',+ });+ try {+ await engine.start();+ await engine.pullOnce('sync');+ expect(engine.getStatus().blockingPaths).toEqual([BLOCKING_NAME]);++ await expect(engine.commitBlockingPaths()).resolves.not.toBeNull();+ expect(git(projectDir, ['show', `HEAD:${BLOCKING_NAME}`])).toBe('{"a":2}');+ expect(engine.getStatus().blockingPaths).toBeUndefined();+ } finally {+ await engine.destroy();+ }+ });+});++describe('pathspec name invariance — shadow-repo per-path history (sites 9, 10, 11)', () => {+ const human: WriterIdentity = {+ id: 'human-ada',+ name: 'Ada Lovelace',+ email: '[email protected]',+ };++ async function shadowWithBothDocs(): Promise<{ shadow: ShadowHandle; wipSha: string }> {+ const g = simpleGit(projectDir);+ await g.init(['--initial-branch=main']);+ await g.raw('config', 'user.name', 'Test');+ await g.raw('config', 'user.email', '[email protected]');+ writeFileSync(join(projectDir, 'README.md'), '# seed\n', 'utf-8');+ await g.add('README.md');+ await g.commit('seed');++ const shadow = await initShadowRepo(projectDir);+ writeFileSync(join(projectDir, MAGIC_PREFIX_DOC), 'colon v1\n', 'utf-8');+ writeFileSync(join(projectDir, PLAIN_DOC), 'plain v1\n', 'utf-8');+ const wipSha = await commitWip(shadow, human, '.', 'WIP: edit both docs', 'main');+ return { shadow, wipSha };+ }++ test('getDocumentHistory returns the WIP entry for a ":"-named doc (site 9)', async () => {+ const { shadow } = await shadowWithBothDocs();++ const plain = await getDocumentHistory(shadow, { docName: 'plain' }, '.');+ const magic = await getDocumentHistory(shadow, { docName: ':colon' }, '.');++ expect(plain.entries.length).toBe(1);+ expect(magic.entries.length).toBe(1);+ expect(magic.entries[0]?.type).toBe('wip');+ });++ test('readShadowLog returns the WIP commit for a ":"-named doc (site 10)', async () => {+ await shadowWithBothDocs();++ const plain = await readShadowLog(projectDir, PLAIN_DOC, 5);+ const magic = await readShadowLog(projectDir, MAGIC_PREFIX_DOC, 5);++ expect(plain.source).toBe('shadow-repo');+ expect(plain.commits.length).toBe(1);+ expect(magic.source).toBe('shadow-repo');+ expect(magic.commits.length).toBe(1);+ });++ test('logSeededReachable finds commits touching a ":"-named doc (site 11)', async () => {+ const { shadow, wipSha } = await shadowWithBothDocs();++ const plain = await logSeededReachable(shadow, ['--format=%H'], [wipSha], PLAIN_DOC);+ const magic = await logSeededReachable(shadow, ['--format=%H'], [wipSha], MAGIC_PREFIX_DOC);++ expect(plain.trim()).not.toBe('');+ expect(magic.trim()).not.toBe('');+ });+});++describe('pathspec name invariance — index removal of vanished paths (site 4)', () => {+ test('the deletion of a ":"-named doc is committed and pushed', async () => {+ const bareDir = await initProjectWithBareRemote();+ writeFileSync(join(projectDir, MAGIC_PREFIX_DOC), 'colon body\n', 'utf-8');+ writeFileSync(join(projectDir, PLAIN_DOC), 'plain body\n', 'utf-8');+ addByLiteralPathspec(projectDir, [MAGIC_PREFIX_DOC, PLAIN_DOC]);+ git(projectDir, ['commit', '-m', 'add both docs']);+ git(projectDir, ['push', 'origin', 'main']);++ rmSync(join(projectDir, MAGIC_PREFIX_DOC));++ const engine = makePushEngine();+ try {+ await engine.start();+ await engine.trigger('push');++ expect(engine.getStatus().pushError).toBeUndefined();+ const landed = originTreePaths(bareDir);+ expect(landed).toContain(PLAIN_DOC);+ expect(landed).not.toContain(MAGIC_PREFIX_DOC);+ } finally {+ await engine.destroy();+ }+ });+});++describe('pathspec name invariance — non-content merge auto-resolve (site 5)', () => {+ const NON_CONTENT_NAME = ':colon.json';++ async function setupNonContentDivergence(fileName: string): Promise<void> {+ const bareDir = join(tmpDir, 'bare.git');+ mkdirSync(bareDir, { recursive: true });+ const bare = simpleGit(bareDir);+ await bare.init(true);+ await bare.raw('symbolic-ref', 'HEAD', 'refs/heads/main');++ const sisterDir = join(tmpDir, 'sister');+ mkdirSync(sisterDir, { recursive: true });+ const sister = simpleGit(sisterDir);+ await sister.init(['--initial-branch=main']);+ await sister.raw('config', 'user.name', 'Sister');+ await sister.raw('config', 'user.email', '[email protected]');+ writeFileSync(join(sisterDir, fileName), '{"a":1}\n', 'utf-8');+ writeFileSync(join(sisterDir, 'foo.md'), 'base\n', 'utf-8');+ await sister.add('-A');+ await sister.commit('base');+ await sister.addRemote('origin', bareDir);+ await sister.push('origin', 'main');++ rmSync(projectDir, { recursive: true, force: true });+ await simpleGit(tmpDir).clone(bareDir, projectDir);+ mkdirSync(okDir, { recursive: true });+ const project = simpleGit(projectDir);+ await project.raw('config', 'user.name', 'Project');+ await project.raw('config', 'user.email', '[email protected]');++ writeFileSync(join(sisterDir, fileName), '{"a":99}\n', 'utf-8');+ await sister.add('-A');+ await sister.commit('modify on remote');+ await sister.push('origin', 'main');++ writeFileSync(join(projectDir, fileName), '{"a":2}\n', 'utf-8');+ await project.add('-A');+ await project.commit('modify locally');+ }++ test('a modify/modify conflict on a ":"-named non-content file auto-resolves to theirs', async () => {+ await setupNonContentDivergence(NON_CONTENT_NAME);++ const engine = new SyncEngine({+ projectDir,+ contentDir: projectDir,+ contentFilter: stubContentFilter,+ syncEnabled: true,+ });+ try {+ await engine.start();+ await engine.pullOnce('sync');++ const status = engine.getStatus();+ expect(status.pausedReason).toBeUndefined();+ expect(status.pullError ?? '').toBe('');+ expect(git(projectDir, ['ls-files', '-u'])).toBe('');+ } finally {+ await engine.destroy();+ }+ });+});++describe('pathspec name invariance — pull-only overlay restore (site 6)', () => {+ interface OverlayOutcome {+ outcome: string;+ pullErrorEmpty: boolean;+ pausedReason: string | undefined;+ onDisk: string;+ }++ async function pullOnlyOverlayScenario(label: string, docName: string): Promise<OverlayOutcome> {+ const root = join(tmpDir, label);+ const bareDir = join(root, 'bare.git');+ const sisterDir = join(root, 'sister');+ const cloneDir = join(root, 'project');+ mkdirSync(bareDir, { recursive: true });+ mkdirSync(sisterDir, { recursive: true });++ const bare = simpleGit(bareDir);+ await bare.init(true);+ await bare.raw('symbolic-ref', 'HEAD', 'refs/heads/main');++ const sister = simpleGit(sisterDir);+ await sister.init(['--initial-branch=main']);+ await sister.raw('config', 'user.name', 'Sister');+ await sister.raw('config', 'user.email', '[email protected]');+ writeFileSync(join(sisterDir, docName), 'v1\n', 'utf-8');+ await sister.add('-A');+ await sister.commit('base');+ await sister.addRemote('origin', bareDir);+ await sister.push('origin', 'main');++ await simpleGit(root).clone(bareDir, cloneDir);+ mkdirSync(join(cloneDir, '.ok', LOCAL_DIR), { recursive: true });+ const project = simpleGit(cloneDir);+ await project.raw('config', 'user.name', 'Project');+ await project.raw('config', 'user.email', '[email protected]');++ writeFileSync(join(sisterDir, docName), 'v2 remote\n', 'utf-8');+ await sister.add('-A');+ await sister.commit('remote edit');+ await sister.push('origin', 'main');++ writeFileSync(join(cloneDir, docName), 'v2 local overlay\n', 'utf-8');++ const engine = new SyncEngine({+ projectDir: cloneDir,+ contentDir: cloneDir,+ contentFilter: stubContentFilter,+ syncEnabled: true,+ mode: 'pull-only',+ });+ try {+ await engine.start();+ const outcome = await engine.pullOnce('pull');+ const status = engine.getStatus();+ return {+ outcome,+ pullErrorEmpty: (status.pullError ?? '') === '',+ pausedReason: status.pausedReason,+ onDisk: readFileSync(join(cloneDir, docName), 'utf-8'),+ };+ } finally {+ await engine.destroy();+ }+ }++ test('a ":"-named overlapping overlay pulls exactly as a plain-named one does', async () => {+ const plain = await pullOnlyOverlayScenario('plain-arm', PLAIN_DOC);+ expect(plain.outcome).not.toBe('error');+ expect(plain.onDisk).toBe(+ '<<<<<<< HEAD\nv2 local overlay\n=======\nv2 remote\n>>>>>>> origin/main\n',+ );++ const magic = await pullOnlyOverlayScenario('magic-arm', MAGIC_PREFIX_DOC);+ expect(magic).toEqual(plain);+ });+});++describe('pathspec name invariance — tracked-path rename probe (site 15)', () => {+ test('a ":"-named doc renames through git instead of degrading to a filesystem rename', async () => {+ await initProjectWithBareRemote();+ writeFileSync(join(projectDir, MAGIC_PREFIX_DOC), 'colon body\n', 'utf-8');+ writeFileSync(join(projectDir, PLAIN_DOC), 'plain body\n', 'utf-8');+ addByLiteralPathspec(projectDir, [MAGIC_PREFIX_DOC, PLAIN_DOC]);+ git(projectDir, ['commit', '-m', 'add both docs']);++ const plain = await renameTrackedPathInGit(+ projectDir,+ join(projectDir, PLAIN_DOC),+ join(projectDir, 'plain-renamed.md'),+ );+ const magic = await renameTrackedPathInGit(+ projectDir,+ join(projectDir, MAGIC_PREFIX_DOC),+ join(projectDir, 'colon-renamed.md'),+ );++ expect(plain).toBe(true);+ expect(magic).toBe(true);+ expect(git(projectDir, ['status', '--porcelain']).split('\n').sort()).toEqual([+ 'R :colon.md -> colon-renamed.md',+ 'R plain.md -> plain-renamed.md',+ ]);+ });+});++describe('pathspec argv sites with no product-producible hostile input today', () => {+ const human: WriterIdentity = {+ id: 'human-ada',+ name: 'Ada Lovelace',+ email: '[email protected]',+ };+ const WILDCARD_SKILL = 'star*';+ const SIBLING_SKILL = 'starfish';++ test('restoring a wildcard-named skill restores only its own files', async () => {+ const g = simpleGit(projectDir);+ await g.init(['--initial-branch=main']);+ await g.raw('config', 'user.name', 'Test');+ await g.raw('config', 'user.email', '[email protected]');+ writeFileSync(join(projectDir, 'README.md'), '# seed\n', 'utf-8');+ await g.add('README.md');+ await g.commit('seed');++ const shadow = await initShadowRepo(projectDir);+ for (const name of [WILDCARD_SKILL, SIBLING_SKILL]) {+ mkdirSync(join(projectDir, '.ok', 'skills', name), { recursive: true });+ writeFileSync(join(projectDir, '.ok', 'skills', name, 'SKILL.md'), `# ${name}\n`, 'utf-8');+ }+ const saved = await saveVersion(shadow, '.', [human], 'main', 'seed skills');+ expect(saved.checkpointRef).toBeTruthy();++ const restored = await restoreSkillVersion({+ shadow,+ contentDir: projectDir,+ contentRoot: '.',+ name: WILDCARD_SKILL,+ version: saved.checkpointRef,+ });++ expect(restored.ok).toBe(true);+ if (restored.ok) expect(restored.restoredFiles).toEqual(['SKILL.md']);+ });++ test('every tracked MCP config target is free of pathspec magic (sites 6b, 7)', () => {+ for (const target of TRACKED_MCP_CONFIG_TARGETS) {+ expect(target.startsWith(':')).toBe(false);+ expect(/[*?[\]]/.test(target)).toBe(false);+ }+ });+});diff --git a/packages/server/src/http/error-response.test.ts b/packages/server/src/http/error-response.test.tsindex 287cb8938..b7f60bd02 100644--- a/packages/server/src/http/error-response.test.ts+++ b/packages/server/src/http/error-response.test.ts@@ -278,6 +278,25 @@ describe('errorResponse — defense-in-depth branches', () => {expect(body.instance).not.toBe('attacker-controlled');expect(body.colliding).toEqual([{ existing: 'a.md', incoming: 'A.md', to: 'A.md' }]);});++ test('the :(literal) pathspec marker is scrubbed from title and detail', () => {+ const { res, endCalls } = makeMockRes();+ errorResponse(+ res,+ 500,+ 'urn:ok:error:storage-error',+ "Failed to read version abc123: fatal: pathspec ':(literal):colon.md' did not match any files",+ {+ handler: 'test',+ detail: "pathspec ':(literal)star*/SKILL.md' did not match",+ },+ );+ const body = JSON.parse(endCalls[0]);+ expect(body.title).not.toContain(':(literal)');+ expect(body.detail).not.toContain(':(literal)');+ expect(body.title).toContain("pathspec ':colon.md' did not match any files");+ expect(body.detail).toContain("pathspec 'star*/SKILL.md' did not match");+ });});describe('streamingProblemEvent — defense-in-depth fallback', () => {diff --git a/packages/server/src/http/error-response.ts b/packages/server/src/http/error-response.tsindex c83b9e754..d5403c2b8 100644--- a/packages/server/src/http/error-response.ts+++ b/packages/server/src/http/error-response.ts@@ -6,6 +6,7 @@ import {type ProblemType,type StreamingProblemEvent,StreamingProblemEventSchema,+ stripPathspecMagic,} from '@inkeep/open-knowledge-core';import type { Counter } from '@opentelemetry/api';import { getLogger } from '../logger.ts';@@ -91,10 +92,10 @@ export function errorResponse(const body: ProblemDetails = {type,- title,+ title: stripPathspecMagic(title),status,instance,- detail: options.detail ?? undefined,+ detail: options.detail === undefined ? undefined : stripPathspecMagic(options.detail),};const validated = ProblemDetailsSchema.safeParse(body);if (!validated.success) {@@ -204,10 +205,10 @@ export function streamingProblemEvent(const instance = options.instance ?? `urn:uuid:${randomUUID()}`;const problem: ProblemDetails = {type,- title,+ title: stripPathspecMagic(title),status,instance,- detail: options.detail ?? undefined,+ detail: options.detail === undefined ? undefined : stripPathspecMagic(options.detail),};const event: StreamingProblemEvent = { type: 'error', problem };const validated = StreamingProblemEventSchema.safeParse(event);diff --git a/packages/server/src/persistence.ts b/packages/server/src/persistence.tsindex e5a179aa5..4f629ebfd 100644--- a/packages/server/src/persistence.ts+++ b/packages/server/src/persistence.ts@@ -13,6 +13,7 @@ import {fragmentHoldsPendingContent,normalizeBridge,type Principal,+ pathspecArgs,pendingContentLines,prependFrontmatter,stripFrontmatter,@@ -343,7 +344,7 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis}const projectDir = options?.projectDir ?? process.cwd();const shadowRef = options?.shadowRef;- const contentRoot = options?.contentRoot ?? (toPosix(relative(projectDir, contentDir)) || '.');+ const contentRoot = options?.contentRoot || toPosix(relative(projectDir, contentDir)) || '.';const derivedDocumentIndex = options?.derivedDocumentIndex;const getPrincipal = options?.getPrincipal;const onAgentCommit = options?.onAgentCommit;@@ -590,7 +591,7 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis}}- await sg.env(env).raw('add', contentRoot);+ await sg.env(env).raw('add', ...pathspecArgs([contentRoot]));const treeSha = (await sg.env(env).raw('write-tree')).trim();let parentSha: string | null = null;diff --git a/packages/server/src/rename-log.ts b/packages/server/src/rename-log.tsindex 5dc010f4c..6b3f7e6be 100644--- a/packages/server/src/rename-log.ts+++ b/packages/server/src/rename-log.ts@@ -2,6 +2,7 @@ import { spawn } from 'node:child_process';import { createHash } from 'node:crypto';import { existsSync, readFileSync, statSync } from 'node:fs';import { resolve } from 'node:path';+import { pathspecArgs } from '@inkeep/open-knowledge-core';import { parseOkActors } from '@inkeep/open-knowledge-core/shadow-repo-layout';import { withHiddenWindowsConsole } from './child-process-windows-hide.ts';import {@@ -461,12 +462,12 @@ export async function logSeededReachable(if (seeds.length === 0) return '';const argBytes = seeds.reduce((acc, s) => acc + s.length + 1, 0);if (argBytes < REV_LIST_STDIN_THRESHOLD_BYTES) {- const args = [...flags, ...seeds, ...(pathspec ? ['--', pathspec] : [])];+ const args = [...flags, ...seeds, ...(pathspec ? pathspecArgs([pathspec]) : [])];return shadowGit(shadow).raw('log', ...args);}const timeoutMs = parseGitTimeoutMs();return new Promise<string>((resolvePromise, rejectPromise) => {- const args = ['log', '--stdin', ...flags, ...(pathspec ? ['--', pathspec] : [])];+ const args = ['log', '--stdin', ...flags, ...(pathspec ? pathspecArgs([pathspec]) : [])];const child = spawn('git',args,diff --git a/packages/server/src/services/skill-reimport.ts b/packages/server/src/services/skill-reimport.tsindex ea52af73e..45f76ab49 100644--- a/packages/server/src/services/skill-reimport.ts+++ b/packages/server/src/services/skill-reimport.ts@@ -1,6 +1,10 @@import { existsSync } from 'node:fs';import { relative, resolve, sep } from 'node:path';-import { RENAMED_PACK_SKILLS, type SkillReimportSuccessSchema } from '@inkeep/open-knowledge-core';+import {+ pathspecArgs,+ RENAMED_PACK_SKILLS,+ type SkillReimportSuccessSchema,+} from '@inkeep/open-knowledge-core';import {acquiredBundleTooLarge,packMarkerOf,@@ -214,7 +218,7 @@ export function createSkillReimportService(deps: SkillReimportDeps): SkillReimpotry {const pg = simpleGit({ baseDir: deps.projectDir, timeout: { block: 15_000 } });const rel = relative(deps.projectDir, resolve(skillsRoot, name)).split(sep).join('/');- gitTracked = (await pg.raw('ls-files', '--', rel)).trim().length > 0;+ gitTracked = (await pg.raw('ls-files', ...pathspecArgs([rel]))).trim().length > 0;} catch {gitTracked = undefined;}diff --git a/packages/server/src/shadow-repo.test.ts b/packages/server/src/shadow-repo.test.tsindex dca4d2429..09e47b412 100644--- a/packages/server/src/shadow-repo.test.ts+++ b/packages/server/src/shadow-repo.test.ts@@ -174,7 +174,42 @@ describe('buildWipTree contentRoot pathspec', () => {writeFileSync(resolve(projectRoot, 'AGENTS.md'), '# hello\n');const shadow = await initShadowRepo(projectRoot);- expect(buildWipTree(shadow, 'content')).rejects.toThrow(/pathspec 'content'/);+ await expect(buildWipTree(shadow, 'content')).rejects.toThrow(/pathspec ':\(literal\)content'/);+ });++ test('a ":"-prefixed contentRoot scopes to that subtree instead of over-matching', async () => {+ const projectRoot = resolve(tmpDir, 'project');+ mkdirSync(resolve(projectRoot, ':vault'), { recursive: true });+ writeFileSync(resolve(projectRoot, ':vault', 'a.md'), '# a\n');+ writeFileSync(resolve(projectRoot, 'sibling.md'), '# sibling\n');+ const shadow = await initShadowRepo(projectRoot);++ const sha = await buildWipTree(shadow, ':vault');+ const listed = await simpleGit(projectRoot)+ .env({ GIT_DIR: shadow.gitDir, GIT_WORK_TREE: projectRoot })+ .raw(['ls-tree', '-r', '--name-only', sha]);+ const entries = listed.trim().split('\n').filter(Boolean);++ expect(entries).toContain(':vault/a.md');+ expect(entries).not.toContain('sibling.md');+ });++ test('a wildcard-bearing contentRoot selects only its own subtree', async () => {+ const projectRoot = resolve(tmpDir, 'project');+ mkdirSync(resolve(projectRoot, 'star*'), { recursive: true });+ mkdirSync(resolve(projectRoot, 'starfish'), { recursive: true });+ writeFileSync(resolve(projectRoot, 'star*', 'a.md'), '# a\n');+ writeFileSync(resolve(projectRoot, 'starfish', 'b.md'), '# b\n');+ const shadow = await initShadowRepo(projectRoot);++ const sha = await buildWipTree(shadow, 'star*');+ const listed = await simpleGit(projectRoot)+ .env({ GIT_DIR: shadow.gitDir, GIT_WORK_TREE: projectRoot })+ .raw(['ls-tree', '-r', '--name-only', sha]);+ const entries = listed.trim().split('\n').filter(Boolean);++ expect(entries).toContain('star*/a.md');+ expect(entries).not.toContain('starfish/b.md');});});diff --git a/packages/server/src/shadow-repo.ts b/packages/server/src/shadow-repo.tsindex 52d4c432d..aeb15ebac 100644--- a/packages/server/src/shadow-repo.ts+++ b/packages/server/src/shadow-repo.ts@@ -1,7 +1,7 @@import { randomUUID } from 'node:crypto';import { existsSync, readdirSync, rmSync } from 'node:fs';import { resolve } from 'node:path';-import { SYSTEM_WRITER_DISPLAY_NAMES } from '@inkeep/open-knowledge-core';+import { pathspecArgs, SYSTEM_WRITER_DISPLAY_NAMES } from '@inkeep/open-knowledge-core';import {type AutoConsolidationTrigger,CHECKPOINT_KIND_REGISTRY,@@ -316,7 +316,7 @@ async function commitWipInner(GIT_WORK_TREE: shadow.workTree,GIT_INDEX_FILE: tmpIndex,})- .raw('add', gitPathspec);+ .raw('add', ...pathspecArgs([gitPathspec]));const treeSha = (await sg.env({ GIT_DIR: shadow.gitDir, GIT_INDEX_FILE: tmpIndex }).raw('write-tree')).trim();@@ -393,7 +393,7 @@ async function buildWipTreeWithIndex(GIT_WORK_TREE: shadow.workTree,GIT_INDEX_FILE: indexFile,})- .raw('add', gitPathspec);+ .raw('add', ...pathspecArgs([gitPathspec]));return (await sg.env({ GIT_DIR: shadow.gitDir, GIT_INDEX_FILE: indexFile }).raw('write-tree')).trim();@@ -1444,7 +1444,7 @@ async function saveVersionInner(GIT_WORK_TREE: shadow.workTree,GIT_INDEX_FILE: shadowTmpIndex,})- .raw('add', gitPathspec);+ .raw('add', ...pathspecArgs([gitPathspec]));const shadowTreeSha = (await sg.env({ GIT_DIR: shadow.gitDir, GIT_INDEX_FILE: shadowTmpIndex }).raw('write-tree')).trim();diff --git a/packages/server/src/share/freshness.ts b/packages/server/src/share/freshness.tsindex 5b5cfb968..5e2d927eb 100644--- a/packages/server/src/share/freshness.ts+++ b/packages/server/src/share/freshness.ts@@ -1,4 +1,4 @@-import type { ShareFreshness } from '@inkeep/open-knowledge-core';+import { pathspecArgs, type ShareFreshness } from '@inkeep/open-knowledge-core';import { truncateError } from '../error-format.ts';import { createGitInstance } from '../git-handle.ts';import { getLogger } from '../logger.ts';@@ -20,15 +20,15 @@ export async function computeShareFreshness(await git.raw(['rev-parse', '--verify', ref]);- const pathspec = gitPath === '' ? '.' : gitPath;+ const scope = pathspecArgs([gitPath === '' ? '.' : gitPath]);const [present, trackedDiff, untracked] = await Promise.all([git.raw(['cat-file', '-e', `${ref}:${gitPath}`]).then(() => true).catch(() => false),- git.raw(['diff', '--name-only', ref, '--', pathspec]),- git.raw(['status', '--porcelain', '--untracked-files=all', '--', pathspec]),+ git.raw(['diff', '--name-only', ref, ...scope]),+ git.raw(['status', '--porcelain', '--untracked-files=all', ...scope]),]);if (!present) {diff --git a/packages/server/src/share/target-status.ts b/packages/server/src/share/target-status.tsindex 85e125557..ecfecbefb 100644--- a/packages/server/src/share/target-status.ts+++ b/packages/server/src/share/target-status.ts@@ -1,6 +1,6 @@import { existsSync } from 'node:fs';import { join } from 'node:path';-import type { ShareTargetStatusResponse } from '@inkeep/open-knowledge-core';+import { pathspecArgs, type ShareTargetStatusResponse } from '@inkeep/open-knowledge-core';import { truncateError } from '../error-format.ts';import { createGitInstance } from '../git-handle.ts';import { listNameStatus, type NameStatusRow } from '../git-paths.ts';@@ -90,7 +90,15 @@ export async function computeShareTargetStatus(return emit({ verdict: 'on-origin' });}- const removingCommit = (await git.raw(['log', '-1', '--format=%H', ref, '--', gitPath])).trim();+ const removingCommit = (+ await git.raw([+ 'log',+ '-1',+ '--format=%H',+ ref,+ ...pathspecArgs([gitPath === '' ? '.' : gitPath]),+ ])+ ).trim();if (removingCommit === '') return emit({ verdict: 'never-on-branch' });const rows = await listNameStatus(git, [diff --git a/packages/server/src/skill-restore.ts b/packages/server/src/skill-restore.tsindex 8dcf20f60..4ac50c9b6 100644--- a/packages/server/src/skill-restore.ts+++ b/packages/server/src/skill-restore.ts@@ -1,5 +1,6 @@import { existsSync } from 'node:fs';import { dirname, resolve, sep } from 'node:path';+import { pathspecArgs } from '@inkeep/open-knowledge-core';import { tracedMkdirSync, tracedRmSync, tracedWriteFileSync } from './fs-traced.ts';import { listNames } from './git-paths.ts';import { type ShadowHandle, shadowGit } from './shadow-repo.ts';@@ -49,8 +50,7 @@ export async function restoreSkillVersion(opts: {'-r','--name-only',version,- '--',- candidatePath,+ ...pathspecArgs([candidatePath]),]);if (found.length > 0) {files = found;diff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.tsindex 8df24dc0c..9c89059d1 100644--- a/packages/server/src/sync-engine.ts+++ b/packages/server/src/sync-engine.ts@@ -14,6 +14,7 @@ import { promisify } from 'node:util';import {OK_DIR,type PullOutcome,+ pathspecArgs,type SyncMode,type SyncModeChangeSource,tryLineLevelCombine,@@ -1105,18 +1106,22 @@ export class SyncEngine {return withParentLock(async () => {await this.applyCommitIdentity(handle);try {- await handle.git.raw(['add', '--', ...paths]);+ await handle.git.raw(['add', ...pathspecArgs(paths)]);const staged = await listNames(handle.git, ['diff','--cached','--name-only',- '--',- ...paths,+ ...pathspecArgs(paths),]);if (staged.length === 0) return null;- await handle.git.raw(['commit', '-m', COMMIT_BLOCKING_MESSAGE, '--', ...paths]);+ await handle.git.raw(['commit', '-m', COMMIT_BLOCKING_MESSAGE, ...pathspecArgs(paths)]);} catch (err) {- await handle.git.raw(['reset', '--', ...paths]).catch(() => {});+ await handle.git.raw(['reset', ...pathspecArgs(paths)]).catch((resetErr: unknown) => {+ log.warn(+ { resetErr, files: paths.length },+ '[sync] blocking-path index reset failed; paths may remain staged',+ );+ });log.error({ err, files: paths.length }, '[sync] commit of blocking paths failed');throw err;}@@ -1678,8 +1683,7 @@ export class SyncEngine {'--source=HEAD','--staged','--worktree',- '--',- ...overlapping,+ ...pathspecArgs(overlapping),]);} catch (e) {log.warn(@@ -2541,8 +2545,7 @@ export class SyncEngine {'--source=HEAD','--staged','--worktree',- '--',- ...reconciled.map((item) => item.path),+ ...pathspecArgs(reconciled.map((item) => item.path)),]);} catch (err) {log.warn({ err }, '[sync] could not isolate reconciled MCP paths from pre-merge stash');@@ -2680,7 +2683,11 @@ export class SyncEngine {});if (commitRaw === null) throw new Error(`cannot edit tracked MCP path: ${item.path}`);- const treeLine = await isolated.git.raw(['ls-tree', headSha, '--', item.path]);+ const treeLine = await isolated.git.raw([+ 'ls-tree',+ headSha,+ ...pathspecArgs([item.path]),+ ]);const mode = treeLine.match(/^(100644|100755)\s/)?.[1];if (!mode) throw new Error(`unsafe tracked MCP mode: ${item.path}`);@@ -2803,8 +2810,7 @@ export class SyncEngine {'--others','--ignored','--exclude-standard',- '--',- ...batch,+ ...pathspecArgs(batch),]);for (const p of ignored) refused.add(p);} catch (err) {@@ -2823,12 +2829,12 @@ export class SyncEngine {const forced = probeOk ? stageable.filter((f) => hasOkSegment(f.projectRelPath)) : [];const plain = probeOk ? stageable.filter((f) => !hasOkSegment(f.projectRelPath)) : stageable;for (const [addArgs, group] of [- [['add', '--'], plain],- [['add', '-f', '--'], forced],+ [['add'], plain],+ [['add', '-f'], forced],] as const) {for (let i = 0; i < group.length; i += BATCH) {const batch = group.slice(i, i + BATCH).map((f) => f.projectRelPath);- await handle.git.raw([...addArgs, ...batch]);+ await handle.git.raw([...addArgs, ...pathspecArgs(batch)]);}}return stageable;@@ -2938,7 +2944,7 @@ export class SyncEngine {const BATCH = 100;for (let i = 0; i < unique.length; i += BATCH) {const batch = unique.slice(i, i + BATCH);- await handle.git.raw(['rm', '--cached', '--', ...batch]);+ await handle.git.raw(['rm', '--cached', ...pathspecArgs(batch)]);}}@@ -2950,8 +2956,13 @@ export class SyncEngine {for (let i = 0; i < unique.length; i += BATCH) {const batch = unique.slice(i, i + BATCH);try {- await realIndexHandle.git.raw(['reset', 'HEAD', '--', ...batch]);- } catch {}+ await realIndexHandle.git.raw(['reset', 'HEAD', ...pathspecArgs(batch)]);+ } catch (resetErr: unknown) {+ log.warn(+ { resetErr, files: batch.length },+ '[sync] real-index reset failed; paths may remain staged',+ );+ }}}@@ -3005,8 +3016,8 @@ export class SyncEngine {);for (const file of nonContentConflicts) {try {- await handle.git.raw(['checkout', '--theirs', '--', file]);- await handle.git.raw(['add', '--', file]);+ await handle.git.raw(['checkout', '--theirs', ...pathspecArgs([file])]);+ await handle.git.raw(['add', ...pathspecArgs([file])]);if (file.toLowerCase() === projectConfigRelPath.toLowerCase()) {log.warn({ file },diff --git a/packages/server/src/timeline-query.ts b/packages/server/src/timeline-query.tsindex a3d3c8fc0..66b0c7e79 100644--- a/packages/server/src/timeline-query.ts+++ b/packages/server/src/timeline-query.ts@@ -1,5 +1,5 @@import { existsSync } from 'node:fs';-import type { EntryType, TimelineEntry } from '@inkeep/open-knowledge-core';+import { type EntryType, pathspecArgs, type TimelineEntry } from '@inkeep/open-knowledge-core';import {isSurfacedCheckpointKind,parseCheckpoint,@@ -548,7 +548,7 @@ export async function getDocumentHistory('-n',String(walkCap),...allStartRefs,- ...(docPath ? ['--', docPath] : []),+ ...(docPath ? pathspecArgs([docPath]) : []),);wipEntries = parseGitLogOutput(currentRaw);if (wipEntries.length >= walkCap) windowSaturated = true;@@ -700,8 +700,7 @@ export async function getFolderTimeline('-n',String(walkCap),...startRefs,- '--',- okPath,+ ...pathspecArgs([okPath]),);const parsedFolderEntries = parseGitLogOutput(raw);const windowSaturated = parsedFolderEntries.length >= walkCap;