Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Fix Windows template inheritance (PRD-9862) (#7392)
tim-inkeep211fe8d60ed2
diff --git a/.changeset/windows-template-inheritance.md b/.changeset/windows-template-inheritance.mdnew file mode 100644index 000000000..f4b2d7af5--- /dev/null+++ b/.changeset/windows-template-inheritance.md@@ -0,0 +1,5 @@+---+'@inkeep/open-knowledge': patch+---++Fix inherited templates missing from nested folders on Windows.diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 50d3ab46f..d00a51dbd 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -4600,7 +4600,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {});return null;}- return { folderRel, resolvedContentDir };+ return {+ folderRel: relative(resolvedContentDir, candidateAbs).split(sep).join('/'),+ resolvedContentDir,+ };}function checkSkillDocConflictGate(diff --git a/packages/server/src/api-folder-template-composition.test.ts b/packages/server/src/api-folder-template-composition.test.tsindex 66f8d2a56..9f7350797 100644--- a/packages/server/src/api-folder-template-composition.test.ts+++ b/packages/server/src/api-folder-template-composition.test.ts@@ -10,7 +10,7 @@ import {} from 'node:fs';import { mkdtemp, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';-import { resolve } from 'node:path';+import { join, resolve, sep } from 'node:path';import { afterAll, beforeAll, describe, expect, test } from 'vitest';import type { BootedServer } from './boot.ts';import { bootCompositionRig, parseProblem, rawRequest } from './composition-rig.test-helper.ts';@@ -72,6 +72,65 @@ describe('folder-template group over the composed listener — served natively',expect(((await res.json()) as { type?: string }).type).toBe('urn:ok:error:template-not-found');});+ test.each([+ { label: 'slash', folder: 'Setup/Results' },+ { label: 'native', folder: join('Setup', 'Results') },+ ])(+ 'GET /api/template inherits the nearest template for $label folder input',+ async ({ folder }) => {+ mkdirSync(resolve(contentDir, 'Setup', 'Results'), { recursive: true });+ for (const [ancestor, title] of [+ ['', 'Root categories'],+ ['Setup', 'Setup categories'],+ ]) {+ const templates = resolve(contentDir, ancestor, '.ok', 'templates');+ mkdirSync(templates, { recursive: true });+ writeFileSync(+ resolve(templates, 'setup-categories.md'),+ `---\ntitle: ${title}\n---\n# ${title}\n`,+ );+ }++ const res = await fetch(+ `http://127.0.0.1:${server.port}/api/template?name=setup-categories&folder=${encodeURIComponent(folder)}`,+ );+ const body: unknown = await res.json();++ expect(res.status).toBe(200);+ expect(body).toMatchObject({+ template: { frontmatter: { title: 'Setup categories' }, body: '# Setup categories\n' },+ });+ },+ );++ test.skipIf(sep !== '/')(+ 'GET /api/template keeps a literal-backslash folder distinct from a nested folder',+ async () => {+ for (const [folder, title] of [+ ['Native/Target', 'Nested target'],+ ['Native\\Target', 'Literal target'],+ ]) {+ const templates = resolve(contentDir, folder, '.ok', 'templates');+ mkdirSync(templates, { recursive: true });+ writeFileSync(resolve(templates, 'identity.md'), `---\ntitle: ${title}\n---\n# ${title}\n`);+ }++ for (const [folder, title] of [+ ['Native/Target', 'Nested target'],+ ['Native\\Target', 'Literal target'],+ ]) {+ const res = await fetch(+ `http://127.0.0.1:${server.port}/api/template?name=identity&folder=${encodeURIComponent(folder)}`,+ );+ const body: unknown = await res.json();+ expect(res.status).toBe(200);+ expect(body).toMatchObject({+ template: { folder, scope: 'local', frontmatter: { title }, body: `# ${title}\n` },+ });+ }+ },+ );+test('template name validation survives the lift (bad name → 400)', async () => {const res = await fetch(`http://127.0.0.1:${server.port}/api/template?name=${encodeURIComponent('bad.name')}&folder=`,diff --git a/packages/server/src/api-folder-template.windows-path.test.ts b/packages/server/src/api-folder-template.windows-path.test.tsnew file mode 100644index 000000000..974927aaf--- /dev/null+++ b/packages/server/src/api-folder-template.windows-path.test.ts@@ -0,0 +1,114 @@+import { mkdirSync, writeFileSync } from 'node:fs';+import { resolve, sep } from 'node:path';+import { describe, expect, test, vi } from 'vitest';+import { withTempDir } from '../../../test-support/temp-dir.test-helper.ts';+import { bootCompositionRig } from './composition-rig.test-helper.ts';++const importedEdges = vi.hoisted<string[]>(() => []);++vi.mock('./mcp/tools/path-safety.ts', async () => {+ const { createRequire, registerHooks } = await import('node:module');+ const safetyUrl = new URL('./mcp/tools/path-safety.ts', import.meta.url).href;+ const replacement = new URL('./win32-relative-path.test-helper.ts', import.meta.url).href;+ const hooks = registerHooks({+ resolve(specifier, context, nextResolve) {+ if (context.parentURL === safetyUrl && specifier === 'node:path') {+ importedEdges.push(context.parentURL);+ return nextResolve(replacement, context);+ }+ return nextResolve(specifier, context);+ },+ });+ try {+ const actual: typeof import('./mcp/tools/path-safety.ts') = createRequire(import.meta.url)(+ './mcp/tools/path-safety.ts',+ );+ return actual;+ } finally {+ hooks.deregister();+ }+});++describe('folder-config HTTP with importer-scoped Node win32 relative paths', () => {+ test('lists the nearest ancestor templates for a slash request while scanning the native target', async () => {+ await withTempDir('ok-folder-config-win32-', async (contentDir) => {+ mkdirSync(resolve(contentDir, 'Setup', 'Results'), { recursive: true });+ writeFileSync(+ resolve(contentDir, 'Setup', 'Results', 'result.md'),+ '---\ntitle: Result\n---\n# Content\n',+ );+ for (const [folder, name, title] of [+ ['', 'setup-categories', 'Root categories'],+ ['', 'global', 'Global'],+ ['Setup', 'setup-categories', 'Setup categories'],+ ['Sibling', 'sibling-only', 'Sibling only'],+ ]) {+ const directory = resolve(contentDir, folder, '.ok', 'templates');+ mkdirSync(directory, { recursive: true });+ writeFileSync(resolve(directory, `${name}.md`), `---\ntitle: ${title}\n---\n# ${title}\n`);+ }++ const server = await bootCompositionRig(contentDir);+ try {+ await server.ready;+ expect(importedEdges).toEqual([+ new URL('./mcp/tools/path-safety.ts', import.meta.url).href,+ ]);+ expect(sep).toBe(process.platform === 'win32' ? '\\' : '/');++ const folder = 'Setup/Results';+ const res = await fetch(+ `http://127.0.0.1:${server.port}/api/folder-config?path=${encodeURIComponent(folder)}`,+ );+ const body: unknown = await res.json();+ expect(res.status).toBe(200);+ expect(body).toMatchObject({+ folder: {+ directMdCount: 1,+ recursiveMdCount: 1,+ childDirCount: 0,+ mostRecentMd: { title: 'Result' },+ },+ });+ expect.soft(body).toHaveProperty('folder.path', folder);+ expect.soft(body).toMatchObject({+ folder: {+ templates_available: expect.arrayContaining([+ {+ name: 'setup-categories',+ title: 'Setup categories',+ path: 'Setup/.ok/templates/setup-categories.md',+ source_folder: 'Setup',+ scope: 'inherited',+ },+ {+ name: 'global',+ title: 'Global',+ path: '.ok/templates/global.md',+ source_folder: '',+ scope: 'inherited',+ },+ ]),+ },+ });+ expect.soft(body).toHaveProperty('folder.templates_available.length', 2);++ const template = await fetch(+ `http://127.0.0.1:${server.port}/api/template?name=setup-categories&folder=${encodeURIComponent(folder)}`,+ );+ const templateBody: unknown = await template.json();+ expect(template.status).toBe(200);+ expect(templateBody).toMatchObject({+ template: {+ folder: 'Setup',+ scope: 'inherited',+ frontmatter: { title: 'Setup categories' },+ body: '# Setup categories\n',+ },+ });+ } finally {+ await server.destroy();+ }+ });+ });+});diff --git a/packages/server/src/api-template-ancestry.windows.test.ts b/packages/server/src/api-template-ancestry.windows.test.tsnew file mode 100644index 000000000..46e8dfd77--- /dev/null+++ b/packages/server/src/api-template-ancestry.windows.test.ts@@ -0,0 +1,90 @@+import { createServer } from 'node:http';+import { tmpdir } from 'node:os';+import { describe, expect, test, vi } from 'vitest';+import { createApiExtension } from './api-extension.test-helper.ts';+import { listenOnLoopback } from './loopback-rig-test-helpers.ts';++const fixture = await vi.hoisted(async () => {+ const path = await vi.importActual<typeof import('node:path')>('node:path');+ const fs = await vi.importActual<typeof import('node:fs')>('node:fs');+ const state = { directory: '' };+ return {+ path,+ fs,+ state,+ toHost: (file: string) =>+ path.resolve(state.directory, ...path.win32.relative('C:\\project', file).split('\\')),+ };+});++vi.mock('node:path', () => ({ ...fixture.path, ...fixture.path.win32 }));++vi.mock('node:fs', () => {+ const realpath = (file: string) =>+ fixture.path.win32.resolve(+ 'C:\\project',+ fixture.path.relative(fixture.state.directory, fixture.fs.realpathSync(fixture.toHost(file))),+ );+ return {+ ...fixture.fs,+ existsSync: (file: string) => fixture.fs.existsSync(fixture.toHost(file)),+ lstatSync: (file: string) => fixture.fs.lstatSync(fixture.toHost(file)),+ statSync: (file: string) => fixture.fs.statSync(fixture.toHost(file)),+ realpathSync: Object.assign(realpath, { native: realpath }),+ };+});++vi.mock('node:fs/promises', async (importOriginal) => {+ const fs = await importOriginal<typeof import('node:fs/promises')>();+ return {+ ...fs,+ readFile: (file: string, encoding: BufferEncoding) =>+ fs.readFile(fixture.toHost(file), encoding),+ };+});++describe('GET /api/template with Node win32 paths', () => {+ test('does not inherit templates from a cancelled folder segment', async () => {+ const directory = fixture.fs.mkdtempSync(fixture.path.join(tmpdir(), 'ok-template-ancestry-'));+ fixture.state.directory = fixture.fs.realpathSync(directory);+ try {+ const templates = fixture.path.join(directory, 'Setup', '.ok', 'templates');+ fixture.fs.mkdirSync(templates, { recursive: true });+ fixture.fs.mkdirSync(fixture.path.join(directory, 'Results'));+ fixture.fs.writeFileSync(fixture.path.join(templates, 'setup-only.md'), '# Setup only\n');++ const extension = createApiExtension({+ hocuspocus: {} as Parameters<typeof createApiExtension>[0]['hocuspocus'],+ sessionManager: {} as Parameters<typeof createApiExtension>[0]['sessionManager'],+ contentDir: 'C:\\project',+ serverInstanceId: 'test-template-ancestry',+ getFileIndex: () => new Map(),+ });+ const server = createServer(async (request, response) => {+ await extension.nativeApi.dispatch(request, response);+ });+ try {+ const { baseUrl } = await listenOnLoopback(server);+ const local = await fetch(`${baseUrl}/api/template?name=setup-only&folder=Setup`);+ expect(local.status).toBe(200);+ expect(await local.json()).toMatchObject({ template: { body: '# Setup only\n' } });++ const target = await fetch(`${baseUrl}/api/template?name=setup-only&folder=Results`);+ expect(target.status).toBe(404);+ await target.json();++ const cancelled = await fetch(+ `${baseUrl}/api/template?name=setup-only&folder=${encodeURIComponent('Setup\\..\\Results')}`,+ );+ const body: unknown = await cancelled.json();+ expect(cancelled.status).toBe(404);+ expect(body).toMatchObject({ type: 'urn:ok:error:template-not-found' });+ } finally {+ await server[Symbol.asyncDispose]();+ await extension.shutdownLocalOps();+ }+ } finally {+ fixture.fs.rmSync(directory, { recursive: true, force: true });+ }+ });+});diff --git a/packages/server/src/content/enrichment.windows-path.test.ts b/packages/server/src/content/enrichment.windows-path.test.tsnew file mode 100644index 000000000..6dcaa30cd--- /dev/null+++ b/packages/server/src/content/enrichment.windows-path.test.ts@@ -0,0 +1,81 @@+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, test, vi } from 'vitest';+import { withTempDir } from '../../../../test-support/temp-dir.test-helper.ts';+import { enrichDirectory, enrichPath } from './enrichment.ts';++vi.mock('node:path', async (importOriginal) => {+ const path = await importOriginal<typeof import('node:path')>();+ return { ...path, relative: path.win32.relative, sep: path.win32.sep };+});++function writeTemplate(projectDir: string, folder: string, name: string, title: string) {+ const directory = join(projectDir, folder, '.ok', 'templates');+ mkdirSync(directory, { recursive: true });+ writeFileSync(join(directory, `${name}.md`), `---\ntitle: ${title}\n---\n# ${title}\n`);+}++describe('enrichment with win32 relative paths and native filesystem paths', () => {+ test('lists an intermediate ancestor template for a nested directory', async () => {+ await withTempDir('ok-enrichment-path-', async (projectDir) => {+ mkdirSync(join(projectDir, 'Setup', 'Results'), { recursive: true });+ writeTemplate(projectDir, 'Setup', 'setup-categories', 'Setup categories');++ const directory = await enrichDirectory('Setup/Results', { projectDir });++ expect(directory.templates_available).toEqual([+ {+ name: 'setup-categories',+ title: 'Setup categories',+ path: 'Setup/.ok/templates/setup-categories.md',+ source_folder: 'Setup',+ scope: 'inherited',+ },+ ]);+ expect(directory.path).toBe('Setup/Results');+ });+ });++ test('prefers the nearest ancestor while retaining root templates and excluding siblings', async () => {+ await withTempDir('ok-enrichment-precedence-', async (projectDir) => {+ mkdirSync(join(projectDir, 'Setup', 'Results'), { recursive: true });+ writeTemplate(projectDir, '', 'setup-categories', 'Root categories');+ writeTemplate(projectDir, '', 'global', 'Global');+ writeTemplate(projectDir, 'Setup', 'setup-categories', 'Setup categories');+ writeTemplate(projectDir, 'Sibling', 'sibling-only', 'Sibling only');++ const directory = await enrichDirectory('Setup/Results', { projectDir });++ expect(directory.templates_available).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ name: 'global', source_folder: '', scope: 'inherited' }),+ expect.objectContaining({+ name: 'setup-categories',+ title: 'Setup categories',+ source_folder: 'Setup',+ scope: 'inherited',+ }),+ ]),+ );+ expect(directory.templates_available).toHaveLength(2);+ });+ });++ test('publishes a slash document identifier without losing its frontmatter', async () => {+ await withTempDir('ok-enrichment-document-', async (projectDir) => {+ mkdirSync(join(projectDir, 'Setup', 'Results'), { recursive: true });+ writeFileSync(+ join(projectDir, 'Setup', 'Results', 'result.md'),+ '---\ntitle: Result\n---\n# Content\n',+ );++ const document = await enrichPath('Setup/Results/result.md', { projectDir });++ expect(document).toMatchObject({+ path: 'Setup/Results/result.md',+ title: 'Result',+ frontmatter: { title: 'Result' },+ });+ });+ });+});diff --git a/packages/server/src/mcp/tools/path-safety.posix.test.ts b/packages/server/src/mcp/tools/path-safety.posix.test.tsnew file mode 100644index 000000000..ba436018b--- /dev/null+++ b/packages/server/src/mcp/tools/path-safety.posix.test.ts@@ -0,0 +1,17 @@+import { describe, expect, test, vi } from 'vitest';+import { resolveWithinRoot } from './path-safety.ts';++vi.mock('node:path', async (importOriginal) => {+ const path = await importOriginal<typeof import('node:path')>();+ return { ...path, ...path.posix };+});++describe('resolveWithinRoot with Node posix path operations', () => {+ test('preserves a literal backslash in the native target and logical identifier', () => {+ expect(resolveWithinRoot('/project', 'Setup\\Results')).toEqual({+ ok: true,+ abs: '/project/Setup\\Results',+ rel: 'Setup\\Results',+ });+ });+});diff --git a/packages/server/src/mcp/tools/path-safety.ts b/packages/server/src/mcp/tools/path-safety.tsindex 425013a7b..6c5be7424 100644--- a/packages/server/src/mcp/tools/path-safety.ts+++ b/packages/server/src/mcp/tools/path-safety.ts@@ -1,4 +1,4 @@-import { isAbsolute, relative, resolve } from 'node:path';+import { isAbsolute, relative, resolve, sep } from 'node:path';interface ContainmentOk {ok: true;@@ -40,5 +40,5 @@ export function resolveWithinRoot(root: string, candidate: string): ContainmentRreason: `path "${candidate}" escapes the configured root`,};}- return { ok: true, abs, rel };+ return { ok: true, abs, rel: rel.split(sep).join('/') };}diff --git a/packages/server/src/mcp/tools/path-safety.windows.test.ts b/packages/server/src/mcp/tools/path-safety.windows.test.tsnew file mode 100644index 000000000..d08c1cb4c--- /dev/null+++ b/packages/server/src/mcp/tools/path-safety.windows.test.ts@@ -0,0 +1,38 @@+import { describe, expect, test, vi } from 'vitest';+import { resolveWithinRoot } from './path-safety.ts';++vi.mock('node:path', async (importOriginal) => {+ const path = await importOriginal<typeof import('node:path')>();+ return { ...path, ...path.win32 };+});++describe('resolveWithinRoot with Node win32 path operations', () => {+ test.each([+ { label: 'slash input', root: 'C:\\project', input: 'Setup/Results' },+ { label: 'backslash input', root: 'C:\\project', input: 'Setup\\Results' },+ { label: 'absolute input', root: 'C:\\project', input: 'C:\\project\\Setup\\Results' },+ { label: 'UNC root', root: '\\\\server\\share', input: 'Setup/Results' },+ ])('returns a slash content identifier for $label', ({ root, input }) => {+ expect(resolveWithinRoot(root, input)).toEqual({+ ok: true,+ abs: `${root}\\Setup\\Results`,+ rel: 'Setup/Results',+ });+ });++ test('keeps the project root identifier empty', () => {+ expect(resolveWithinRoot('C:\\project', '.')).toEqual({+ ok: true,+ abs: 'C:\\project',+ rel: '',+ });+ });++ test.each([+ { label: 'parent traversal', input: '..\\outside' },+ { label: 'different drive', input: 'D:\\outside' },+ { label: 'different UNC share', input: '\\\\server\\other\\outside' },+ ])('rejects $label', ({ input }) => {+ expect(resolveWithinRoot('C:\\project', input)).toMatchObject({ ok: false });+ });+});diff --git a/packages/server/src/win32-relative-path.test-helper.ts b/packages/server/src/win32-relative-path.test-helper.tsnew file mode 100644index 000000000..39221c804--- /dev/null+++ b/packages/server/src/win32-relative-path.test-helper.ts@@ -0,0 +1,2 @@+export { isAbsolute, resolve } from 'node:path';+export { relative, sep } from 'node:path/win32';