From 51d4b1dc8c4b11276df37be89a016d65109431eb Mon Sep 17 00:00:00 2001 From: d-oit Date: Wed, 18 Nov 2026 19:11:41 +0100 Subject: [PATCH 1/7] feat(studio): data integrity, storage health, and shared core (plans/217 #1155-#1159,#1170) Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- e2e/storage-health.spec.ts | 75 ++++ package.json | 11 +- packages/dks-core/package.json | 54 +++ packages/dks-core/src/backup.test.ts | 274 +++++++++++ packages/dks-core/src/backup.ts | 424 ++++++++++++++++++ packages/dks-core/src/bundle-load.test.ts | 170 +++++++ packages/dks-core/src/bundle-load.ts | 99 ++++ packages/dks-core/src/frontmatter.test.ts | 89 ++++ packages/dks-core/src/frontmatter.ts | 320 +++++++++++++ packages/dks-core/src/graph-path.test.ts | 65 +++ packages/dks-core/src/graph-path.ts | 140 ++++++ packages/dks-core/src/import-services.test.ts | 140 ++++++ packages/dks-core/src/index.ts | 114 +++++ packages/dks-core/src/io.ts | 85 ++++ packages/dks-core/src/library-index.test.ts | 117 +++++ packages/dks-core/src/library-index.ts | 204 +++++++++ packages/dks-core/src/markdown-export.test.ts | 57 +++ packages/dks-core/src/markdown-export.ts | 77 ++++ packages/dks-core/src/markdown.test.ts | 101 +++++ packages/dks-core/src/markdown.ts | 402 +++++++++++++++++ packages/dks-core/src/okf-export.test.ts | 89 ++++ packages/dks-core/src/okf-export.ts | 251 +++++++++++ packages/dks-core/src/okf-parse.test.ts | 156 +++++++ packages/dks-core/src/okf-parse.ts | 359 +++++++++++++++ packages/dks-core/src/pwa-retrieval.test.ts | 62 +++ packages/dks-core/src/pwa-retrieval.ts | 384 ++++++++++++++++ packages/dks-core/src/types.ts | 108 +++++ packages/dks-core/src/zip.test.ts | 116 +++++ packages/dks-core/src/zip.ts | 108 +++++ packages/dks-core/tsconfig.build.json | 11 + packages/dks-core/tsconfig.json | 16 + packages/dks-core/vitest.config.ts | 8 + plans/217-open-issues-2026-11-17.md | 75 ++++ pnpm-lock.yaml | 77 +++- scripts/corpus-fingerprint.mjs | 12 +- .../studio/views/export-helpers.test.ts | 105 ++++- src/components/studio/views/export-helpers.ts | 41 +- .../studio/views/import-staging.test.ts | 24 + src/components/studio/views/import-staging.ts | 8 + .../studio/views/settings-view.test.tsx | 155 ++++++- src/components/studio/views/settings-view.tsx | 162 ++++++- src/lib/i18n/messages/settings.ts | 47 ++ src/lib/import/markdown-import.test.ts | 27 +- src/lib/import/markdown-import.ts | 357 ++++----------- src/lib/import/vault-zip.ts | 7 +- src/lib/okf/bundle.ts | 283 +----------- src/lib/okf/import.ts | 256 ++--------- src/lib/search/retrieval.ts | 408 +---------------- src/lib/studio/merge-entities.test.ts | 157 ++++++- src/lib/studio/revision-model.test.ts | 73 +++ src/lib/studio/revision-model.ts | 12 +- src/lib/studio/revision-storage.test.ts | 9 +- src/lib/studio/revisions-store.test.ts | 34 ++ src/lib/studio/slices/entities-slice.ts | 87 ++-- src/lib/studio/storage-report.test.ts | 180 +++++++- src/lib/studio/storage-report.ts | 147 ++++++ tests/corpus-fingerprint.bats | 17 + 57 files changed, 6225 insertions(+), 1221 deletions(-) create mode 100644 e2e/storage-health.spec.ts create mode 100644 packages/dks-core/package.json create mode 100644 packages/dks-core/src/backup.test.ts create mode 100644 packages/dks-core/src/backup.ts create mode 100644 packages/dks-core/src/bundle-load.test.ts create mode 100644 packages/dks-core/src/bundle-load.ts create mode 100644 packages/dks-core/src/frontmatter.test.ts create mode 100644 packages/dks-core/src/frontmatter.ts create mode 100644 packages/dks-core/src/graph-path.test.ts create mode 100644 packages/dks-core/src/graph-path.ts create mode 100644 packages/dks-core/src/import-services.test.ts create mode 100644 packages/dks-core/src/index.ts create mode 100644 packages/dks-core/src/io.ts create mode 100644 packages/dks-core/src/library-index.test.ts create mode 100644 packages/dks-core/src/library-index.ts create mode 100644 packages/dks-core/src/markdown-export.test.ts create mode 100644 packages/dks-core/src/markdown-export.ts create mode 100644 packages/dks-core/src/markdown.test.ts create mode 100644 packages/dks-core/src/markdown.ts create mode 100644 packages/dks-core/src/okf-export.test.ts create mode 100644 packages/dks-core/src/okf-export.ts create mode 100644 packages/dks-core/src/okf-parse.test.ts create mode 100644 packages/dks-core/src/okf-parse.ts create mode 100644 packages/dks-core/src/pwa-retrieval.test.ts create mode 100644 packages/dks-core/src/pwa-retrieval.ts create mode 100644 packages/dks-core/src/types.ts create mode 100644 packages/dks-core/src/zip.test.ts create mode 100644 packages/dks-core/src/zip.ts create mode 100644 packages/dks-core/tsconfig.build.json create mode 100644 packages/dks-core/tsconfig.json create mode 100644 packages/dks-core/vitest.config.ts create mode 100644 plans/217-open-issues-2026-11-17.md diff --git a/e2e/storage-health.spec.ts b/e2e/storage-health.spec.ts new file mode 100644 index 000000000..4a7a22223 --- /dev/null +++ b/e2e/storage-health.spec.ts @@ -0,0 +1,75 @@ +import { test, expect, type Page } from '@playwright/test'; +import { waitForAppReady, navClick } from './helpers/navigation'; + +/** + * Settings → Origin storage panel (issue #1156). + * + * Verifies the storage-health UI end to end in a real Chromium: the estimate + * rows render from `navigator.storage.estimate()`, the persistent-storage + * status renders from `navigator.storage.persisted()`, and the request action + * either gets granted or is declined by the browser — the panel must render + * the outcome either way, never crash, and never claim persistence is a + * backup. + */ +test.describe('Settings origin storage health', () => { + const openSettings = async (page: Page) => { + await page.goto('/'); + await waitForAppReady(page); + await navClick(page, /settings/i); + await expect(page.getByRole('heading', { name: 'Origin storage' })).toBeVisible(); + await expect( + page.getByText( + /Estimated usage|does not expose origin storage diagnostics|did not return usable storage measurements/i, + ), + ).toBeVisible(); + }; + + test('renders storage diagnostics or the browser-supported fallback', async ({ page }) => { + await openSettings(page); + + const estimate = page.getByText(/Estimated usage/i); + if ((await estimate.count()) > 0) { + await expect(estimate).toBeVisible(); + await expect(page.getByText(/Estimated quota/i)).toBeVisible(); + // Estimates are labeled as estimates, never exact disk usage. + await expect(page.getByText(/browser estimates, not exact disk usage/i)).toBeVisible(); + // The panel is explicit that this is one aggregate browser estimate, not + // per-store byte accounting. + await expect(page.getByText(/everything this site stores here/i)).toBeVisible(); + } else { + await expect( + page.getByText(/does not expose origin storage diagnostics|did not return usable storage measurements/i), + ).toBeVisible(); + } + // This is visible even when storage diagnostics are unsupported. + await expect(page.getByText(/not a backup/i)).toBeVisible(); + await expect(page.getByRole('link', { name: /back up your library/i })).toBeVisible(); + }); + + test('allows requesting persistent storage and renders the outcome', async ({ page }) => { + await openSettings(page); + + const requestButton = page.getByRole('button', { name: /request persistent storage/i }); + if ((await requestButton.count()) > 0) { + // Not protected yet: ask the browser for persistence. The browser either + // grants or declines; the panel must explain either outcome and keep + // working — never crash, never claim a backup was made. + await requestButton.click(); + await expect( + page.getByText(/persistent storage granted|declined persistent storage/i), + ).toBeVisible(); + await expect(page.getByRole('heading', { name: 'Origin storage' })).toBeVisible(); + await expect( + page.locator('span').filter({ hasText: /Not granted|Granted/ }), + ).toBeVisible(); + } else if ((await page.getByText(/^Granted/).count()) > 0) { + // Already protected: the request control is gone and the status says so. + await expect(page.getByText(/^Granted/)).toBeVisible(); + } else { + // The browser may lack persistence support or all origin storage diagnostics. + await expect( + page.getByText(/cannot request persistent storage|does not expose origin storage diagnostics/i), + ).toBeVisible(); + } + }); +}); diff --git a/package.json b/package.json index c23de628f..90d9467da 100644 --- a/package.json +++ b/package.json @@ -9,17 +9,17 @@ }, "scripts": { "prepare": "./scripts/install-hooks.sh", - "dev": "next dev -p 3000 2>&1 | tee dev.log", - "build": "next build && node scripts/generate-precache-manifest.mjs", + "dev": "pnpm --filter dks-core build && next dev -p 3000 2>&1 | tee dev.log", + "build": "pnpm --filter dks-core build && next build && node scripts/generate-precache-manifest.mjs", "start": "next start", "lint": "eslint .", "docs:check": "node scripts/check-doc-consistency.mjs", "workflows:check": "./scripts/check-workflow-hygiene.sh", - "typecheck": "next typegen && tsc --noEmit -p tsconfig.app.json && pnpm --filter dks-mcp typecheck", + "typecheck": "pnpm --filter dks-core build && next typegen && tsc --noEmit -p tsconfig.app.json && pnpm --filter dks-core typecheck && pnpm --filter dks-mcp typecheck", "typecheck:test": "tsc --noEmit -p tsconfig.test.json", "typecheck:e2e": "tsc --noEmit -p tsconfig.e2e.json", "propagate:version": "bash scripts/propagate-version.sh", - "test": "vitest run && pnpm --filter dks-mcp test", + "test": "pnpm --filter dks-core build && vitest run && pnpm --filter dks-core test && pnpm --filter dks-mcp test", "test:mutation": "stryker run && node scripts/check-mutation-score.mjs < reports/mutation.json", "test:properties:nightly": "FAST_CHECK_PROFILE=nightly vitest run", "test:coverage": "vitest run --coverage", @@ -88,7 +88,8 @@ "yaml": "^2.9.1", "yjs": "^13.6.33", "zod": "^4.6.7", - "zustand": "^5.0.15" + "zustand": "^5.0.15", + "dks-core": "workspace:*" }, "devDependencies": { "@axe-core/playwright": "^4.13.0", diff --git a/packages/dks-core/package.json b/packages/dks-core/package.json new file mode 100644 index 000000000..4c06b99b7 --- /dev/null +++ b/packages/dks-core/package.json @@ -0,0 +1,54 @@ +{ + "name": "dks-core", + "version": "0.1.0", + "private": true, + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + }, + "./frontmatter": { + "types": "./dist/frontmatter.d.ts", + "import": "./dist/frontmatter.js" + }, + "./graph-path": { + "types": "./dist/graph-path.d.ts", + "import": "./dist/graph-path.js" + }, + "./markdown": { + "types": "./dist/markdown.d.ts", + "import": "./dist/markdown.js" + }, + "./okf-export": { + "types": "./dist/okf-export.d.ts", + "import": "./dist/okf-export.js" + }, + "./okf-parse": { + "types": "./dist/okf-parse.d.ts", + "import": "./dist/okf-parse.js" + }, + "./pwa-retrieval": { + "types": "./dist/pwa-retrieval.d.ts", + "import": "./dist/pwa-retrieval.js" + } + }, + "description": "Framework-neutral Knowledge Studio domain services shared by the dks CLI and the optional MCP adapter. No React/Next/MCP dependencies.", + "scripts": { + "build": "tsc -p tsconfig.build.json", + "typecheck": "tsc --noEmit -p tsconfig.json", + "test": "vitest run" + }, + "dependencies": { + "yaml": "^2.9.1" + }, + "devDependencies": { + "typescript": "^6", + "vitest": "4.1.11" + }, + "engines": { + "node": ">=22.12.0 <27.0.0" + } +} diff --git a/packages/dks-core/src/backup.test.ts b/packages/dks-core/src/backup.test.ts new file mode 100644 index 000000000..4e0c2ace6 --- /dev/null +++ b/packages/dks-core/src/backup.test.ts @@ -0,0 +1,274 @@ +import { describe, expect, it } from 'vitest' +import { + BACKUP_FILE_PATHS, + BACKUP_FORMAT, + BACKUP_FORMAT_VERSION, + BACKUP_KDF_ITERATIONS, + verifyBackupArchive, +} from './backup.js' + +/** Builds a plain archive envelope fixture. */ +const makeEnvelope = async ( + overrides: { manifest?: Record; files?: Record; envelope?: Record } = {}, +): Promise => { + const files = overrides.files ?? { + [BACKUP_FILE_PATHS.entities]: JSON.stringify({ entities: [] }), + [BACKUP_FILE_PATHS.claims]: JSON.stringify({ claims: [] }), + [BACKUP_FILE_PATHS.canvas]: JSON.stringify({ graph: null, mindMap: null, links: null, tags: [] }), + } + const manifest = overrides.manifest ?? { + format: BACKUP_FORMAT, + formatVersion: BACKUP_FORMAT_VERSION, + schemaVersion: 1, + appVersion: '0.2.0', + exportedAt: '2026-11-17T00:00:00.000Z', + counts: { + entities: 0, + claims: 0, + graphNodes: 0, + graphEdges: 0, + mindMapNodes: 0, + mindMapEdges: 0, + links: 0, + tags: 0, + }, + files: await Promise.all( + Object.entries(files).map(async ([path, content]) => ({ + path, + bytes: new TextEncoder().encode(content).length, + sha256: await sha256Hex(content), + })), + ), + } + const envelope = { + format: BACKUP_FORMAT, + formatVersion: BACKUP_FORMAT_VERSION, + encryption: null, + manifest, + files, + ciphertext: null, + ...(overrides.envelope ?? {}), + } + return JSON.stringify(envelope) +} + +/** Computes hex sha256 (mirrors the core helper for fixtures). */ +const sha256Hex = async (text: string): Promise => { + const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)) + return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('') +} + +/** Builds a valid plain archive with the given entities/claims. */ +const makeValidArchive = async ( + entities: Array>, + claims: Array>, +): Promise => { + const files = { + [BACKUP_FILE_PATHS.entities]: JSON.stringify({ entities }), + [BACKUP_FILE_PATHS.claims]: JSON.stringify({ claims }), + [BACKUP_FILE_PATHS.canvas]: JSON.stringify({ graph: null, mindMap: null, links: null, tags: [] }), + } + const manifest = { + format: BACKUP_FORMAT, + formatVersion: BACKUP_FORMAT_VERSION, + schemaVersion: 1, + appVersion: '0.2.0', + exportedAt: '2026-11-17T00:00:00.000Z', + counts: { + entities: entities.length, + claims: claims.length, + graphNodes: 0, + graphEdges: 0, + mindMapNodes: 0, + mindMapEdges: 0, + links: 0, + tags: 0, + }, + files: await Promise.all( + Object.entries(files).map(async ([path, content]) => ({ + path, + bytes: new TextEncoder().encode(content).length, + sha256: await sha256Hex(content), + })), + ), + } + return JSON.stringify({ + format: BACKUP_FORMAT, + formatVersion: BACKUP_FORMAT_VERSION, + encryption: null, + manifest, + files, + ciphertext: null, + }) +} + +describe('verifyBackupArchive (plain)', () => { + it('verifies a valid empty archive', async () => { + const r = await verifyBackupArchive(await makeValidArchive([], [])) + expect(r.ok).toBe(true) + if (!r.ok) return + expect(r.entityCount).toBe(0) + expect(r.claimCount).toBe(0) + expect(r.encrypted).toBe(false) + }) + + it('verifies counts and references for a populated archive', async () => { + const archive = await makeValidArchive( + [{ id: 'e1', name: 'One' }], + [{ id: 'c1', entityId: 'e1', statement: 'S' }], + ) + const r = await verifyBackupArchive(archive) + expect(r.ok).toBe(true) + if (!r.ok) return + expect(r.entityCount).toBe(1) + expect(r.claimCount).toBe(1) + }) + + it('fails on non-JSON input', async () => { + const r = await verifyBackupArchive('not json') + expect(r.ok).toBe(false) + if (r.ok) return + expect(r.code).toBe('unreadable') + }) + + it('fails on a wrong format marker', async () => { + const r = await verifyBackupArchive(JSON.stringify({ format: 'other' })) + expect(r.ok).toBe(false) + if (r.ok) return + expect(r.code).toBe('format') + }) + + it('fails on a future format version', async () => { + const r = await verifyBackupArchive(await makeEnvelope({ envelope: { formatVersion: 99 } })) + expect(r.ok).toBe(false) + if (r.ok) return + expect(r.code).toBe('format-version') + }) + + it('fails on a checksum mismatch', async () => { + const envelope = JSON.parse(await makeEnvelope()) as { manifest: { files: Array<{ sha256: string }> } } + envelope.manifest.files[0] = { ...envelope.manifest.files[0]!, sha256: '0'.repeat(64) } + const r = await verifyBackupArchive(JSON.stringify(envelope)) + expect(r.ok).toBe(false) + if (r.ok) return + expect(r.code).toBe('checksum') + }) + + it('fails when a payload file is missing', async () => { + const files = { + [BACKUP_FILE_PATHS.entities]: JSON.stringify({ entities: [] }), + [BACKUP_FILE_PATHS.claims]: JSON.stringify({ claims: [] }), + } + const r = await verifyBackupArchive(await makeEnvelope({ files })) + expect(r.ok).toBe(false) + if (r.ok) return + expect(r.code).toBe('manifest') + }) + + it('fails on manifest count mismatches', async () => { + const archive = await makeValidArchive([{ id: 'e1', name: 'One' }], []) + const envelope = JSON.parse(archive) as { manifest: { counts: { entities: number } } } + envelope.manifest.counts.entities = 5 + const r = await verifyBackupArchive(JSON.stringify(envelope)) + expect(r.ok).toBe(false) + if (r.ok) return + expect(r.code).toBe('counts') + }) + + it('fails when a claim references a missing entity', async () => { + const archive = await makeValidArchive([], [{ id: 'c1', entityId: 'ghost', statement: 'S' }]) + const r = await verifyBackupArchive(archive) + expect(r.ok).toBe(false) + if (r.ok) return + expect(r.code).toBe('references') + }) + + it('fails on duplicate entity ids', async () => { + const archive = await makeValidArchive( + [ + { id: 'e1', name: 'One' }, + { id: 'e1', name: 'Two' }, + ], + [], + ) + const r = await verifyBackupArchive(archive) + expect(r.ok).toBe(false) + if (r.ok) return + expect(r.code).toBe('references') + }) +}) + +/** Minimal encryptor mirroring the studio archive crypto parameters. */ +const encryptFixture = async (plaintext: string, passphrase: string): Promise<{ salt: string; iv: string; ciphertext: string; ciphertextSha256: string }> => { + const subtle = globalThis.crypto.subtle + const salt = globalThis.crypto.getRandomValues(new Uint8Array(16)) + const iv = globalThis.crypto.getRandomValues(new Uint8Array(12)) + const b64 = (bytes: Uint8Array): string => { + let bin = '' + for (const b of bytes) bin += String.fromCharCode(b) + return btoa(bin) + } + const keyMaterial = await subtle.importKey('raw', new TextEncoder().encode(passphrase), 'PBKDF2', false, ['deriveKey']) + const key = await subtle.deriveKey( + { name: 'PBKDF2', hash: 'SHA-256', salt, iterations: BACKUP_KDF_ITERATIONS }, + keyMaterial, + { name: 'AES-GCM', length: 256 }, + false, + ['encrypt'], + ) + const ciphertext = new Uint8Array(await subtle.encrypt({ name: 'AES-GCM', iv, tagLength: 128 }, key, new TextEncoder().encode(plaintext))) + const digest = new Uint8Array(await subtle.digest('SHA-256', ciphertext)) + return { + salt: b64(salt), + iv: b64(iv), + ciphertext: b64(ciphertext), + ciphertextSha256: [...digest].map((b) => b.toString(16).padStart(2, '0')).join(''), + } +} + +describe('verifyBackupArchive (encrypted)', () => { + const makeEncrypted = async (passphrase: string): Promise => { + const plain = await makeValidArchive([], []) + const inner = JSON.parse(plain) as { manifest: unknown; files: unknown } + const enc = await encryptFixture(JSON.stringify({ manifest: inner.manifest, files: inner.files }), passphrase) + return JSON.stringify({ + format: BACKUP_FORMAT, + formatVersion: BACKUP_FORMAT_VERSION, + encryption: { + algorithm: 'AES-256-GCM', + kdf: 'PBKDF2-HMAC-SHA256', + iterations: BACKUP_KDF_ITERATIONS, + salt: enc.salt, + iv: enc.iv, + ciphertextSha256: enc.ciphertextSha256, + }, + manifest: null, + files: null, + ciphertext: enc.ciphertext, + }) + } + + it('verifies an encrypted archive with the correct passphrase', async () => { + const archive = await makeEncrypted('correct horse') + const r = await verifyBackupArchive(archive, 'correct horse') + expect(r.ok).toBe(true) + if (!r.ok) return + expect(r.encrypted).toBe(true) + }) + + it('requires a passphrase', async () => { + const archive = await makeEncrypted('correct horse') + const r = await verifyBackupArchive(archive) + expect(r.ok).toBe(false) + if (r.ok) return + expect(r.code).toBe('passphrase-required') + }) + + it('fails with a wrong passphrase', async () => { + const archive = await makeEncrypted('correct horse') + const r = await verifyBackupArchive(archive, 'wrong') + expect(r.ok).toBe(false) + if (r.ok) return + expect(r.code).toBe('decrypt-failed') + }) +}) diff --git a/packages/dks-core/src/backup.ts b/packages/dks-core/src/backup.ts new file mode 100644 index 000000000..c15f033c8 --- /dev/null +++ b/packages/dks-core/src/backup.ts @@ -0,0 +1,424 @@ +/** + * Backup archive verification (mirrors the studio's `src/lib/backup/ + * archive.ts` flow): a `.dksb` archive is a single UTF-8 JSON envelope + * whose format/version, optional PBKDF2/AES-256-GCM ciphertext hash, payload + * inventory, per-file SHA-256 checksums, record counts, and references are + * all verified before anything is reported as valid. This core service is + * dependency-free and uses the standard WebCrypto API available in both + * browsers and Node 22+. + */ + +/** Marker stored in every backup archive. */ +export const BACKUP_FORMAT = 'do-knowledge-studio-backup' as const +/** Current archive format version. */ +export const BACKUP_FORMAT_VERSION = 1 +/** Oldest payload schema this build can verify without guessing. */ +export const MIN_SUPPORTED_SCHEMA_VERSION = 1 +/** PBKDF2-HMAC-SHA256 iterations for passphrase encryption. */ +export const BACKUP_KDF_ITERATIONS = 310_000 + +/** Payload file paths inside the archive. */ +export const BACKUP_FILE_PATHS = { + entities: 'data/entities.json', + claims: 'data/claims.json', + canvas: 'data/canvas.json', +} as const + +/** Structured failure codes (identical names to the studio UI labels). */ +export type BackupErrorCode = + | 'unreadable' + | 'format' + | 'format-version' + | 'schema-version' + | 'passphrase-required' + | 'decrypt-failed' + | 'checksum' + | 'manifest' + | 'payload' + | 'counts' + | 'references' + +/** A backup verification failure. */ +export interface BackupFailure { + ok: false + code: BackupErrorCode + errors: string[] +} + +/** Verified archive summary (payload bodies are not returned). */ +export interface VerifiedBackupSummary { + ok: true + formatVersion: number + schemaVersion: number + appVersion: string + exportedAt: string + encrypted: boolean + entityCount: number + claimCount: number + graphEdgeCount: number + mindMapEdgeCount: number + linkCount: number + tagCount: number + graphViewCount: number +} + +/** Result of verification: either a summary or a structured failure. */ +export type BackupVerifyResult = VerifiedBackupSummary | BackupFailure + +/** Computes the hex SHA-256 of bytes. */ +const sha256Hex = async (bytes: Uint8Array): Promise => { + const digest = await globalThis.crypto.subtle.digest('SHA-256', bytes) + return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('') +} + +/** Decodes base64 into bytes; throws on malformed input. */ +const fromBase64 = (text: string): Uint8Array => { + const binary = atob(text) + const out = new Uint8Array(binary.length) + for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i) + return out +} + +/** Parses JSON; returns undefined on any parse failure. */ +const parseJson = (text: string): unknown => { + try { + return JSON.parse(text) + } catch { + return undefined + } +} + +const failure = (code: BackupErrorCode, errors: string[]): BackupFailure => ({ ok: false, code, errors }) + +/** Structural checks on the manifest object (no third-party schema lib). */ +const validateManifest = (value: unknown): BackupFailure | { ok: true; manifest: Record } => { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + return failure('format', ['backup manifest is not an object']) + } + const m = value as Record + if (m.format !== BACKUP_FORMAT) return failure('format', ['backup manifest format marker is missing']) + if (typeof m.formatVersion !== 'number' || !Number.isInteger(m.formatVersion) || m.formatVersion <= 0) { + return failure('format', ['backup format version is invalid']) + } + if (typeof m.schemaVersion !== 'number' || !Number.isInteger(m.schemaVersion) || m.schemaVersion <= 0) { + return failure('format', ['backup schema version is invalid']) + } + if (typeof m.appVersion !== 'string' || m.appVersion === '') { + return failure('format', ['backup app version is invalid']) + } + if (typeof m.exportedAt !== 'string' || m.exportedAt === '') { + return failure('format', ['backup exportedAt is invalid']) + } + if (typeof m.counts !== 'object' || m.counts === null || Array.isArray(m.counts)) { + return failure('format', ['backup counts are invalid']) + } + const counts = m.counts as Record + for (const key of ['entities', 'claims', 'graphNodes', 'graphEdges', 'mindMapNodes', 'mindMapEdges', 'links', 'tags']) { + const v = counts[key] + if (typeof v !== 'number' || !Number.isInteger(v) || v < 0) { + return failure('format', [`backup count "${key}" is invalid`]) + } + } + if (!Array.isArray(m.files) || m.files.length === 0) { + return failure('format', ['backup manifest file inventory is missing']) + } + const hex64 = /^[0-9a-f]{64}$/ + for (const f of m.files) { + if (typeof f !== 'object' || f === null) return failure('format', ['backup file entry is invalid']) + const fe = f as Record + if ( + typeof fe.path !== 'string' || fe.path === '' || + typeof fe.bytes !== 'number' || !Number.isInteger(fe.bytes) || fe.bytes < 0 || + typeof fe.sha256 !== 'string' || !hex64.test(fe.sha256) + ) { + return failure('format', ['backup file entry is invalid']) + } + } + return { ok: true, manifest: m } +} + +/** Validates the encryption header when present. */ +const validateEncryptionHeader = (value: unknown): BackupFailure | { ok: true; header: Record } => { + if (value === null) return { ok: true, header: {} } + if (typeof value !== 'object' || Array.isArray(value)) { + return failure('format', ['backup encryption header is invalid']) + } + const h = value as Record + if (h.algorithm !== 'AES-256-GCM' || h.kdf !== 'PBKDF2-HMAC-SHA256') { + return failure('format', ['backup encryption algorithm is unsupported']) + } + if (typeof h.iterations !== 'number' || !Number.isInteger(h.iterations) || h.iterations < 100_000 || h.iterations > 10_000_000) { + return failure('format', ['backup KDF iterations are out of range']) + } + if (typeof h.salt !== 'string' || h.salt === '' || typeof h.iv !== 'string' || h.iv === '') { + return failure('format', ['backup encryption salt/iv are invalid']) + } + if (typeof h.ciphertextSha256 !== 'string' || !/^[0-9a-f]{64}$/.test(h.ciphertextSha256)) { + return failure('format', ['backup ciphertext hash is invalid']) + } + return { ok: true, header: h } +} + +/** Decrypts the archive payload; mirrors the studio crypto parameters. */ +const decryptArchivePayload = async ( + ciphertext: Uint8Array, + header: Record, + passphrase: string, +): Promise => { + const subtle = globalThis.crypto.subtle + const keyMaterial = await subtle.importKey( + 'raw', + new TextEncoder().encode(passphrase), + 'PBKDF2', + false, + ['deriveKey'], + ) + const key = await subtle.deriveKey( + { + name: 'PBKDF2', + hash: 'SHA-256', + salt: fromBase64(String(header.salt)), + iterations: Number(header.iterations), + }, + keyMaterial, + { name: 'AES-GCM', length: 256 }, + false, + ['decrypt'], + ) + const plaintext = await subtle.decrypt( + { name: 'AES-GCM', iv: fromBase64(String(header.iv)), tagLength: 128 }, + key, + ciphertext, + ) + return new TextDecoder('utf-8', { fatal: true }).decode(plaintext) +} + +/** Verifies manifest-declared hashes against the payload files. */ +const verifyFileHashes = async ( + manifest: Record, + files: Record, +): Promise => { + const entries = manifest.files as Array> + for (const entry of entries) { + const path = String(entry.path) + const content = files[path] + if (content === undefined) return failure('checksum', [`missing payload file: ${path}`]) + const bytes = new TextEncoder().encode(content) + if (bytes.length !== Number(entry.bytes)) { + return failure('checksum', [`payload size mismatch: ${path}`]) + } + if ((await sha256Hex(bytes)) !== String(entry.sha256)) { + return failure('checksum', [`payload checksum mismatch: ${path}`]) + } + } + return { ok: true } +} + +/** Verifies record counts and references against parsed payload files. */ +const validatePayload = ( + files: Record, + manifest: Record, +): BackupFailure | { ok: true; entityCount: number; claimCount: number; graphEdgeCount: number; mindMapEdgeCount: number; linkCount: number; tagCount: number; graphViewCount: number } => { + const expected = new Set(Object.values(BACKUP_FILE_PATHS)) + const actual = new Set(Object.keys(files)) + if (actual.size !== expected.size || [...expected].some((p) => !actual.has(p))) { + return failure('manifest', ['backup payload file inventory is incomplete or unexpected']) + } + const entitiesFile = parseJson(files[BACKUP_FILE_PATHS.entities] ?? '') as { entities?: unknown } | undefined + const claimsFile = parseJson(files[BACKUP_FILE_PATHS.claims] ?? '') as { claims?: unknown } | undefined + const canvasFile = parseJson(files[BACKUP_FILE_PATHS.canvas] ?? '') as Record | undefined + if (entitiesFile === undefined || claimsFile === undefined || canvasFile === undefined) { + return failure('payload', ['payload file is not valid JSON']) + } + const entities = entitiesFile.entities + const claims = claimsFile.claims + if (!Array.isArray(entities) || !Array.isArray(claims)) { + return failure('payload', ['entities/claims payload arrays are invalid']) + } + const entityIds = new Set() + for (const entity of entities) { + const id = (entity as Record | null)?.id + if (typeof id !== 'string' || id === '') return failure('payload', ['entity record is missing an id']) + if (entityIds.has(id)) return failure('references', [`duplicate entity id: ${id}`]) + entityIds.add(id) + } + const claimIds = new Set() + for (const claim of claims) { + const record = claim as Record | null + const id = record?.id + const entityId = record?.entityId + if (typeof id !== 'string' || typeof entityId !== 'string') { + return failure('payload', ['claim record is missing an id or entityId']) + } + if (claimIds.has(id) || entityIds.has(id)) { + return failure('references', [`duplicate record id: ${id}`]) + } + claimIds.add(id) + if (!entityIds.has(entityId)) { + return failure('references', [`claim ${id} references a missing entity: ${entityId}`]) + } + } + + const checkEdges = (value: unknown, label: string): BackupFailure | { ok: true; count: number } => { + if (value === undefined || value === null) return { ok: true, count: 0 } + if (!Array.isArray(value)) return failure('references', [`${label} is not an array`]) + for (const edge of value) { + const rec = edge as Record | null + const source = rec?.source ?? rec?.sourceId + const target = rec?.target ?? rec?.targetId + if ((typeof source !== 'string' || !entityIds.has(source)) || (typeof target !== 'string' || !entityIds.has(target))) { + return failure('references', [`${label} edge references a missing entity`]) + } + } + return { ok: true, count: value.length } + } + + const graph = canvasFile.graph + const mindMap = canvasFile.mindMap + const links = canvasFile.links + const tags = canvasFile.tags ?? [] + const graphViews = canvasFile.graphViews ?? [] + const graphEdges = typeof graph === 'object' && graph !== null ? (graph as Record).edges : graph + const mindMapEdges = typeof mindMap === 'object' && mindMap !== null ? (mindMap as Record).edges : mindMap + const g = checkEdges(graphEdges, 'graph') + if (!g.ok) return g + const m = checkEdges(mindMapEdges, 'mindMap') + if (!m.ok) return m + const l = checkEdges(links, 'links') + if (!l.ok) return l + if (!Array.isArray(tags) || !Array.isArray(graphViews)) { + return failure('payload', ['canvas tags/graphViews are not arrays']) + } + + const manifestCounts = (manifest.counts as Record) + const counts = { + entities: entities.length, + claims: claims.length, + graphNodes: typeof graph === 'object' && graph !== null ? ((graph as Record).nodes as unknown[] | undefined)?.length ?? 0 : 0, + graphEdges: g.count, + mindMapNodes: typeof mindMap === 'object' && mindMap !== null ? ((mindMap as Record).nodes as unknown[] | undefined)?.length ?? 0 : 0, + mindMapEdges: m.count, + links: l.count, + tags: tags.length, + } + if (JSON.stringify(counts) !== JSON.stringify(manifestCounts)) { + return failure('counts', ['manifest record counts do not match the payload']) + } + return { ok: true, + entityCount: entities.length, + claimCount: claims.length, + graphEdgeCount: g.count, + mindMapEdgeCount: m.count, + linkCount: l.count, + tagCount: tags.length, + graphViewCount: graphViews.length, + } +} + +/** + * Verifies a backup archive. Corrupt, truncated, tampered, future-version, + * and wrong-passphrase archives all fail before anything is reported valid. + * @param raw - Archive text (UTF-8 JSON). + * @param passphrase - Passphrase for encrypted archives (optional). + * @returns A verified summary, or a structured failure. + */ +export const verifyBackupArchive = async (raw: string, passphrase?: string): Promise => { + const envelopeValue = parseJson(raw) + if (envelopeValue === undefined) return failure('unreadable', ['backup file is not valid JSON']) + if (typeof envelopeValue !== 'object' || envelopeValue === null || Array.isArray(envelopeValue)) { + return failure('format', ['backup envelope is not an object']) + } + const envelope = envelopeValue as Record + if (envelope.format !== BACKUP_FORMAT) { + return failure('format', ['not a do-knowledge-studio backup archive']) + } + if (typeof envelope.formatVersion !== 'number' || !Number.isInteger(envelope.formatVersion) || envelope.formatVersion <= 0) { + return failure('format', ['backup format version is invalid']) + } + if (envelope.formatVersion > BACKUP_FORMAT_VERSION) { + return failure('format-version', [ + `unsupported backup format version ${envelope.formatVersion}; this build supports ${BACKUP_FORMAT_VERSION}`, + ]) + } + + const headerCheck = validateEncryptionHeader(envelope.encryption) + if (!headerCheck.ok) return headerCheck + const encrypted = envelope.encryption !== null + + let manifest: Record + let files: Record + if (encrypted) { + if (typeof envelope.ciphertext !== 'string' || envelope.ciphertext === '') { + return failure('format', ['encrypted backup is missing its ciphertext']) + } + if (!passphrase) { + return failure('passphrase-required', ['this backup is encrypted; pass a passphrase to verify it']) + } + let ciphertext: Uint8Array + try { + ciphertext = fromBase64(envelope.ciphertext) + } catch { + return failure('unreadable', ['backup ciphertext is not valid base64']) + } + if ((await sha256Hex(ciphertext)) !== String(headerCheck.header.ciphertextSha256)) { + return failure('checksum', ['backup ciphertext checksum mismatch']) + } + let plaintext: string + try { + plaintext = await decryptArchivePayload(ciphertext, headerCheck.header, passphrase) + } catch { + return failure('decrypt-failed', [ + 'backup could not be decrypted; the passphrase is wrong or the archive was tampered with', + ]) + } + const inner = parseJson(plaintext) as { manifest?: unknown; files?: unknown } | undefined + if (inner === undefined || inner.manifest === undefined || inner.files === undefined) { + return failure('format', ['decrypted backup payload is malformed']) + } + if (typeof inner.files !== 'object' || inner.files === null || Array.isArray(inner.files)) { + return failure('payload', ['decrypted payload files are malformed']) + } + const innerManifest = validateManifest(inner.manifest) + if (!innerManifest.ok) return innerManifest + manifest = innerManifest.manifest + files = inner.files as Record + } else { + if (envelope.manifest === undefined || envelope.files === undefined) { + return failure('format', ['unencrypted backup is missing its manifest or files']) + } + if (typeof envelope.files !== 'object' || envelope.files === null || Array.isArray(envelope.files)) { + return failure('payload', ['payload files are malformed']) + } + const manifestCheck = validateManifest(envelope.manifest) + if (!manifestCheck.ok) return manifestCheck + manifest = manifestCheck.manifest + files = envelope.files as Record + } + + if (Number(manifest.schemaVersion) > Number.MAX_SAFE_INTEGER || Number(manifest.schemaVersion) < MIN_SUPPORTED_SCHEMA_VERSION) { + return failure('schema-version', [ + `backup schema version ${manifest.schemaVersion} is not supported by this build`, + ]) + } + + const hashes = await verifyFileHashes(manifest, files) + if (!hashes.ok) return hashes + const payload = validatePayload(files, manifest) + if (!payload.ok) return payload + + return { + ok: true, + formatVersion: Number(manifest.formatVersion), + schemaVersion: Number(manifest.schemaVersion), + appVersion: String(manifest.appVersion), + exportedAt: String(manifest.exportedAt), + encrypted, + entityCount: payload.entityCount, + claimCount: payload.claimCount, + graphEdgeCount: payload.graphEdgeCount, + mindMapEdgeCount: payload.mindMapEdgeCount, + linkCount: payload.linkCount, + tagCount: payload.tagCount, + graphViewCount: payload.graphViewCount, + } +} diff --git a/packages/dks-core/src/bundle-load.test.ts b/packages/dks-core/src/bundle-load.test.ts new file mode 100644 index 000000000..ece793f20 --- /dev/null +++ b/packages/dks-core/src/bundle-load.test.ts @@ -0,0 +1,170 @@ +import { deflateRawSync } from 'node:zlib' +import { describe, expect, it } from 'vitest' +import { loadBundleFromDisk } from './bundle-load.js' +import type { DirEntry, FsPort } from './io.js' + +/** In-memory filesystem double: paths are plain keys; dirs end with "/". */ +const makeMemoryFs = (files: Record): FsPort => { + const blob = new Map() + const dirs = new Set(['/']) + for (const [path, text] of Object.entries(files)) { + blob.set(path, typeof text === 'string' ? new TextEncoder().encode(text) : text) + const parts = path.split('/').filter(Boolean).slice(0, -1) + let acc = '/' + for (const part of parts) { + acc += part + dirs.add(acc) + acc += '/' + } + } + return { + isDirectory(path) { + return dirs.has(path.endsWith('/') ? path : `${path}/`) || dirs.has(path) + }, + readFileBytes(path) { + const bytes = blob.get(path) + if (!bytes) throw new Error(`ENOENT: ${path}`) + return bytes + }, + readDirEntries(path) { + const prefix = path.endsWith('/') ? path : `${path}/` + const names = new Set() + for (const key of blob.keys()) { + if (!key.startsWith(prefix)) continue + const top = key.slice(prefix.length).split('/')[0] + if (top) names.add(top) + } + for (const dir of dirs) { + if (!dir.startsWith(prefix) || dir === prefix) continue + const top = dir.slice(prefix.length).split('/')[0] + if (top) names.add(top) + } + const entries: DirEntry[] = [] + for (const name of names) { + entries.push({ name, isDirectory: dirs.has(`${prefix}${name}`) || dirs.has(`${prefix}${name}/`) }) + } + return entries.sort((a, b) => a.name.localeCompare(b.name)) + }, + } +} + +/** Minimal zip builder for the zip-input tests. */ +const buildZip = (entries: Array<{ name: string; data: Uint8Array; method?: 0 | 8 }>): Uint8Array => { + const encoder = new TextEncoder() + const locals: Uint8Array[] = [] + const central: Uint8Array[] = [] + let offset = 0 + for (const entry of entries) { + const nameBytes = encoder.encode(entry.name) + const method = entry.method ?? 8 + const data = method === 8 ? deflateRawSync(entry.data) : entry.data + const local = new Uint8Array(30 + nameBytes.length + data.length) + const lv = new DataView(local.buffer) + lv.setUint32(0, 0x04034b50, true) + lv.setUint16(4, 20, true) + lv.setUint16(8, method, true) + lv.setUint32(14, data.length, true) + lv.setUint32(18, entry.data.length, true) + lv.setUint16(26, nameBytes.length, true) + local.set(nameBytes, 30) + local.set(data, 30 + nameBytes.length) + locals.push(local) + const cd = new Uint8Array(46 + nameBytes.length) + const cv = new DataView(cd.buffer) + cv.setUint32(0, 0x02014b50, true) + cv.setUint16(4, 20, true) + cv.setUint16(6, 20, true) + cv.setUint16(10, method, true) + cv.setUint32(20, data.length, true) + cv.setUint32(24, entry.data.length, true) + cv.setUint16(28, nameBytes.length, true) + cv.setUint32(42, offset, true) + cd.set(nameBytes, 46) + central.push(cd) + offset += local.length + } + const cdStart = locals.reduce((acc, l) => acc + l.length, 0) + const cdBytes = new Uint8Array(central.reduce((acc, c) => acc + c.length, 0)) + let pos = 0 + for (const c of central) { + cdBytes.set(c, pos) + pos += c.length + } + const eocd = new Uint8Array(22) + const ev = new DataView(eocd.buffer) + ev.setUint32(0, 0x06054b50, true) + ev.setUint16(8, entries.length, true) + ev.setUint16(10, entries.length, true) + ev.setUint32(12, cdBytes.length, true) + ev.setUint32(16, cdStart, true) + const out = new Uint8Array(cdStart + cdBytes.length + 22) + pos = 0 + for (const l of locals) { + out.set(l, pos) + pos += l.length + } + out.set(cdBytes, pos) + out.set(eocd, pos + cdBytes.length) + return out +} + +const INDEX = `---\nokf_version: '0.2'\n---\n\n# Index\n` +const ALPHA = `---\ntype: Project\ntitle: Alpha\nverified:\n by: human:ada\n---\nAlpha body.\n# Claims\n\n- Alpha works\n` +const BETA = `---\ntype: Concept\ntitle: Beta\n---\nBeta body.\n` + +describe('loadBundleFromDisk (directory)', () => { + it('loads a directory tree with reserved-file handling', () => { + const fs = makeMemoryFs({ + '/bundle/index.md': INDEX, + '/bundle/log.md': '# Log\n', + '/bundle/concepts/alpha.md': ALPHA, + '/bundle/concepts/beta.md': BETA, + '/bundle/assets/logo.png': 'not markdown', + }) + const loaded = loadBundleFromDisk(fs, '/bundle') + expect(loaded.concepts.map((c) => c.id)).toEqual(['concepts/alpha', 'concepts/beta']) + expect(loaded.concepts[0]?.trustTier).toBe('human-reviewed') + }) + + it('skips unsafe relative paths', () => { + const fs = makeMemoryFs({ + '/bundle/index.md': INDEX, + '/bundle/concepts/alpha.md': ALPHA, + '/bundle/../escape.md': '# escape\n', + }) + const loaded = loadBundleFromDisk(fs, '/bundle') + expect(loaded.concepts.map((c) => c.id)).toEqual(['concepts/alpha']) + }) + + it('throws when the target is missing', () => { + const fs = makeMemoryFs({}) + expect(() => loadBundleFromDisk(fs, '/nope')).toThrow() + }) + + it('throws on bundles without a valid index', () => { + const fs = makeMemoryFs({ '/bundle/concepts/alpha.md': ALPHA }) + expect(() => loadBundleFromDisk(fs, '/bundle')).toThrow(/index\.md with okf_version/) + }) +}) + +describe('loadBundleFromDisk (zip)', () => { + const zipBytes = buildZip([ + { name: 'okf-bundle/index.md', data: new TextEncoder().encode(INDEX) }, + { name: 'okf-bundle/log.md', data: new TextEncoder().encode('# Log\n') }, + { name: 'okf-bundle/concepts/alpha.md', data: new TextEncoder().encode(ALPHA) }, + { name: 'okf-bundle/concepts/beta.md', data: new TextEncoder().encode(BETA) }, + { name: 'okf-bundle/assets/logo.png', data: new TextEncoder().encode('PNG'), method: 0 }, + ]) + + it('loads a zip bundle and strips the export prefix', () => { + const fs = makeMemoryFs({ '/bundle.zip': zipBytes }) + const loaded = loadBundleFromDisk(fs, '/bundle.zip') + expect(loaded.concepts.map((c) => c.id)).toEqual(['concepts/alpha', 'concepts/beta']) + }) + + it('rejects oversized zips', () => { + const big = new Uint8Array(11_000_000) + const fs = makeMemoryFs({ '/big.zip': big }) + expect(() => loadBundleFromDisk(fs, '/big.zip')).toThrow(/too large/) + }) +}) diff --git a/packages/dks-core/src/bundle-load.ts b/packages/dks-core/src/bundle-load.ts new file mode 100644 index 000000000..dd3d8e014 --- /dev/null +++ b/packages/dks-core/src/bundle-load.ts @@ -0,0 +1,99 @@ +/** + * Loads an OKF bundle from disk (zip file or directory) through an + * {@link FsPort}. Size, entry-count, decompressed-total, and path-safety + * guards mirror the studio vault-zip caps; every guard fails closed before + * any concept is parsed. + */ + +import type { FsPort } from './io.js' +import { isSafePath, parseBundleFiles } from './okf-parse.js' +import { + EXPORT_PREFIX, + MAX_BUNDLE_ENTRIES, + MAX_BUNDLE_UNCOMPRESSED_BYTES, + MAX_BUNDLE_ZIP_BYTES, + MAX_CONCEPT_BYTES, +} from './types.js' +import type { LoadedBundle } from './types.js' +import { readZip } from './zip.js' + +/** Decodes UTF-8 bytes; null when the payload is not valid UTF-8. */ +const decodeUtf8 = (bytes: Uint8Array): string | null => { + try { + return new TextDecoder('utf-8', { fatal: true }).decode(bytes) + } catch { + return null + } +} + +/** Reads zip entries into a bundle-relative path → UTF-8 content map. */ +const readZipEntries = (buffer: Uint8Array): Map => { + if (buffer.byteLength > MAX_BUNDLE_ZIP_BYTES) { + throw new Error(`Bundle zip is too large; limited to ${MAX_BUNDLE_ZIP_BYTES} bytes compressed.`) + } + const entries = readZip(buffer) + if (entries.size > MAX_BUNDLE_ENTRIES) { + throw new Error(`Too many entries in the bundle; limited to ${MAX_BUNDLE_ENTRIES} files.`) + } + const files = new Map() + let total = 0 + for (const [name, bytes] of entries) { + if (name.endsWith('/')) continue + total += bytes.byteLength + if (bytes.byteLength > MAX_CONCEPT_BYTES || total > MAX_BUNDLE_UNCOMPRESSED_BYTES) { + throw new Error('Decompressed bundle exceeds the safety limit; refusing to serve.') + } + const stripped = name.startsWith(EXPORT_PREFIX) ? name.slice(EXPORT_PREFIX.length) : name + if (!stripped || !isSafePath(stripped)) continue + if (!stripped.endsWith('.md')) continue + // Decode only markdown entries; binary siblings (images, assets) are + // ignored and must not fail the bundle over a non-UTF-8 payload. + const text = decodeUtf8(bytes) + if (text !== null) files.set(stripped, text) + } + return files +} + +/** Reads a directory tree into a bundle-relative path → content map. */ +const readDirectoryEntries = (port: FsPort, dir: string): Map => { + const files = new Map() + let total = 0 + const walk = (current: string, prefix: string): void => { + const names = port.readDirEntries(current) + for (const entry of names) { + const rel = prefix ? `${prefix}/${entry.name}` : entry.name + if (!isSafePath(rel)) continue + if (entry.isDirectory) { + walk(`${current}/${entry.name}`, rel) + } else if (entry.name.endsWith('.md')) { + const content = decodeUtf8(port.readFileBytes(`${current}/${entry.name}`)) + if (content === null) continue + total += content.length + if (content.length > MAX_CONCEPT_BYTES || total > MAX_BUNDLE_UNCOMPRESSED_BYTES) { + throw new Error('Bundle exceeds the safety limit; refusing to serve.') + } + if (files.size >= MAX_BUNDLE_ENTRIES) { + throw new Error(`Too many files in the bundle; limited to ${MAX_BUNDLE_ENTRIES}.`) + } + files.set(rel, content) + } + } + } + walk(dir, '') + return files +} + +/** + * Loads and parses a bundle from a zip file or a directory. + * Fail-closed: unreadable input, missing/incompatible index, or guard + * violations throw before any concept is served. + * @param port - Filesystem port (Node or test double). + * @param target - Path to a `.zip` bundle or a directory of `.md` files. + * @returns The loaded concepts plus non-fatal warnings. + */ +export const loadBundleFromDisk = (port: FsPort, target: string): LoadedBundle => { + const files = port.isDirectory(target) + ? readDirectoryEntries(port, target) + : readZipEntries(port.readFileBytes(target)) + return parseBundleFiles(files) +} diff --git a/packages/dks-core/src/frontmatter.test.ts b/packages/dks-core/src/frontmatter.test.ts new file mode 100644 index 000000000..3d3e04479 --- /dev/null +++ b/packages/dks-core/src/frontmatter.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from 'vitest' +import { parseFrontmatter, splitFrontmatter } from './frontmatter.js' + +describe('parseFrontmatter', () => { + it('parses scalars, booleans, numbers, and null', () => { + const r = parseFrontmatter('title: Alpha\ndescription: A project\ncount: 3\nflag: true\nnone: null\n') + expect(r).toEqual({ + ok: true, + data: { title: 'Alpha', description: 'A project', count: 3, flag: true, none: null }, + }) + }) + + it('parses quoted strings with escapes', () => { + const r = parseFrontmatter('title: "He said \\"hi\\""\nnote: \'it\'s fine\'\n') + expect(r.ok).toBe(true) + if (!r.ok) return + expect(r.data.title).toBe('He said "hi"') + expect(r.data.note).toBe("it's fine") + }) + + it('parses block lists and nested maps', () => { + const text = [ + 'tags:', + ' - research', + ' - alpha', + 'sources:', + ' - id: src-1', + ' resource: https://example.com', + ' title: Paper', + 'verified:', + ' by: human:ada', + ' at: 2026-01-02T00:00:00.000Z', + ].join('\n') + const r = parseFrontmatter(text) + expect(r.ok).toBe(true) + if (!r.ok) return + expect(r.data.tags).toEqual(['research', 'alpha']) + expect(r.data.sources).toEqual([{ id: 'src-1', resource: 'https://example.com', title: 'Paper' }]) + expect(r.data.verified).toEqual({ by: 'human:ada', at: '2026-01-02T00:00:00.000Z' }) + }) + + it('parses inline flow arrays', () => { + const r = parseFrontmatter('aliases: [Foo, Bar]\n') + expect(r.ok).toBe(true) + if (!r.ok) return + expect(r.data.aliases).toEqual(['Foo', 'Bar']) + }) + + it('keeps URLs with fragments intact (no comment stripping inside tokens)', () => { + const r = parseFrontmatter('resource: https://example.com/#frag\n') + expect(r.ok).toBe(true) + if (!r.ok) return + expect(r.data.resource).toBe('https://example.com/#frag') + }) + + it('ignores full-line comments and trailing comments after values', () => { + const r = parseFrontmatter('# a comment\ntitle: Alpha # trailing\n') + expect(r.ok).toBe(true) + if (!r.ok) return + expect(r.data.title).toBe('Alpha') + }) + + it('rejects tabs in indentation', () => { + const r = parseFrontmatter('tags:\n\t- a\n') + expect(r.ok).toBe(false) + }) + + it('rejects non-mapping documents', () => { + expect(parseFrontmatter('- a\n- b\n').ok).toBe(false) + }) + + it('rejects scalar entries in a mapping document', () => { + expect(parseFrontmatter('[unclosed').ok).toBe(false) + }) +}) + +describe('splitFrontmatter', () => { + it('splits frontmatter from body', () => { + const { frontmatter, body } = splitFrontmatter('---\ntitle: Alpha\n---\nBody text.\n') + expect(frontmatter).toBe('title: Alpha') + expect(body).toBe('Body text.\n') + }) + + it('returns null frontmatter without fences', () => { + const { frontmatter, body } = splitFrontmatter('Just body.\n') + expect(frontmatter).toBeNull() + expect(body).toBe('Just body.\n') + }) +}) diff --git a/packages/dks-core/src/frontmatter.ts b/packages/dks-core/src/frontmatter.ts new file mode 100644 index 000000000..bd99b3f15 --- /dev/null +++ b/packages/dks-core/src/frontmatter.ts @@ -0,0 +1,320 @@ +/** + * Minimal YAML-subset frontmatter parser. + * + * Core services are dependency-free and run in Node with no third-party + * packages, so this parser covers the YAML subset actually used by OKF + * concept frontmatter and Markdown vault notes: + * - `key: scalar` (string, number, boolean, null) + * - single/double quoted strings with common escapes + * - inline flow arrays `[a, b]` + * - block lists `- item` / `- key: value` / nested maps + * - full-line comments and trailing comments after values + * - nested maps by indentation (sources, verified, generated) + * Anything outside this subset either yields a parse error (fail-closed) or + * is preserved as a raw string. The studio app uses the full `yaml` + * package; this subset is tested against the same fixtures and is documented + * as a deliberate, bounded implementation. + */ + +/** A parsed value node: plain JSON values plus nested maps/arrays. */ +export type FmValue = string | number | boolean | null | FmValue[] | { [key: string]: FmValue } + +/** Result of parsing a frontmatter block. */ +export type FmResult = { ok: true; data: Record } | { ok: false; error: string } + +/** Strips a trailing comment (` # ...`) from a value; URLs keep their `#`. */ +const stripTrailingComment = (raw: string): string => { + const idx = raw.indexOf(' #') + return idx !== -1 ? raw.slice(0, idx).trimEnd() : raw.trimEnd() +} + +/** Splits a line into indent and content; tabs are refused (fail-closed). */ +const indentOf = (line: string): { indent: number; content: string } => { + let indent = 0 + for (const ch of line) { + if (ch === ' ') indent += 1 + else if (ch === '\t') return { indent: -1, content: line.trimStart() } + else break + } + return { indent, content: line.slice(indent) } +} + +/** Unquotes a quoted string, handling common escapes. */ +const unquote = (raw: string): string => { + const quote = raw[0] + if (quote !== "'" && quote !== '"') return raw + const body = raw.slice(1, -1) + if (quote === "'") { + // Single-quoted YAML doubles `''` as an escaped quote; no other escapes. + return body.replace(/''/g, "'") + } + let out = '' + for (let i = 0; i < body.length; i += 1) { + const ch = body[i] ?? '' + if (ch !== '\\') { + out += ch + continue + } + const next = body[i + 1] ?? '' + i += 1 + switch (next) { + case 'n': out += '\n'; break + case 't': out += '\t'; break + case 'r': out += '\r'; break + case '\\': out += '\\'; break + case '"': out += '"'; break + case "'": out += "'"; break + case '0': out += '\0'; break + case 'u': { + const hex = body.slice(i + 1, i + 5) + if (/^[0-9a-fA-F]{4}$/.test(hex)) { + out += String.fromCharCode(Number.parseInt(hex, 16)) + i += 4 + } else { + out += '\\u' + } + break + } + default: out += next + } + } + return out +} + +/** Parses a scalar value; returns the raw string when not a known literal. */ +const parseScalar = (raw: string): FmValue => { + const trimmed = raw.trim() + if (trimmed === '') return '' + if (trimmed === 'true') return true + if (trimmed === 'false') return false + if (trimmed === 'null' || trimmed === '~') return null + if ( + (trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length >= 2) || + (trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length >= 2) + ) { + return unquote(trimmed) + } + if (/^-?\d+$/.test(trimmed)) { + const n = Number(trimmed) + if (Number.isSafeInteger(n)) return n + } + if (/^-?\d+\.\d+$/.test(trimmed)) { + const n = Number(trimmed) + if (Number.isFinite(n)) return n + } + return trimmed +} + +const parseFlowArray = (raw: string): FmValue[] | null => { + const trimmed = raw.trim() + if (!trimmed.startsWith('[') || !trimmed.endsWith(']')) return null + const inner = trimmed.slice(1, -1).trim() + if (inner === '') return [] + let inQuote: string | null = null + let depth = 0 + let current = '' + const elements: FmValue[] = [] + for (const ch of inner) { + if (inQuote) { + current += ch + if (ch === inQuote) inQuote = null + continue + } + if (ch === "'" || ch === '"') { + inQuote = ch + current += ch + continue + } + if (ch === '[' || ch === '{') depth += 1 + else if (ch === ']' || ch === '}') depth -= 1 + if (ch === ',' && depth === 0) { + elements.push(parseScalar(current)) + current = '' + continue + } + current += ch + } + // Unterminated quotes/brackets mean a malformed flow array (fail-closed). + if (inQuote !== null || depth !== 0) return null + elements.push(parseScalar(current)) + return elements +} + +/** Parses the inline value after `key:` or `- `; empty string when empty. */ +const parseInlineValue = (raw: string): FmValue => { + const trimmed = raw.trim() + if (trimmed === '') return '' + if (trimmed.startsWith('[')) { + const flow = parseFlowArray(trimmed) + if (flow) return flow + throw new Error(`Malformed flow array: ${trimmed}`) + } + const quoted = trimmed.startsWith('"') || trimmed.startsWith("'") + return parseScalar(quoted ? trimmed : stripTrailingComment(trimmed)) +} + +/** True when `rest` is an inline mapping entry like `id: src-1`. */ +const isInlineMap = (rest: string): boolean => + /^[A-Za-z_][A-Za-z0-9_-]*:(?:\s|$)/.test(rest) + +/** A line tokenizer step. */ +interface Line { + indent: number + content: string +} + +/** + * Parses a block of lines at a given indentation. The block is a mapping + * when its first meaningful line is `key: …`, or an array when it starts + * with `- …`. + */ +const parseBlock = ( + lines: Line[], + start: number, + indent: number, +): { node: FmValue; next: number } => { + let i = start + // Skip blank/comment lines before deciding the block kind. + while (i < lines.length) { + const line = lines[i] ?? { indent: 0, content: '' } + if (line.indent < 0) throw new Error('Tabs are not supported in frontmatter indentation') + if (line.indent < indent) return { node: {}, next: i } + if (line.indent > indent) throw new Error(`Unexpected indentation at line ${i + 1}`) + const content = line.content + if (content !== '' && !content.startsWith('#')) break + i += 1 + } + const first = lines[i] + if (!first) return { node: {}, next: i } + + if (first.content.startsWith('- ')) { + // Array block. + const items: FmValue[] = [] + while (i < lines.length) { + const itemLine = lines[i] ?? { indent: 0, content: '' } + if (itemLine.indent < 0) throw new Error('Tabs are not supported in frontmatter indentation') + if (itemLine.indent !== indent || !itemLine.content.startsWith('- ')) break + const rest = itemLine.content.slice(2).trimStart() + if (rest === '' || rest.startsWith('#')) { + items.push('') + i += 1 + continue + } + const nextLine = lines[i + 1] + const hasNested = nextLine !== undefined && nextLine.indent > indent && nextLine.indent >= 0 + if (hasNested && isInlineMap(rest)) { + const colon = rest.indexOf(':') + const key = rest.slice(0, colon).trim() + const restValue = rest.slice(colon + 1).trim() + const nested = parseBlock(lines, i + 1, nextLine.indent) + if (restValue === '') { + // `key:` with a nested block — the block itself is the value. + items.push({ [key]: nested.node }) + } else if ( + typeof nested.node === 'object' && nested.node !== null && !Array.isArray(nested.node) + ) { + // `key: value` followed by more keys at a deeper indent — merge them + // into one item map instead of nesting the remainder under the key. + const item: Record = { [key]: parseInlineValue(restValue) } + Object.assign(item, nested.node) + items.push(item) + } else { + items.push({ [key]: parseInlineValue(restValue) }) + } + i = nested.next + continue + } + if (hasNested) { + const nested = parseBlock(lines, i + 1, nextLine.indent) + items.push(nested.node) + i = nested.next + continue + } + if (isInlineMap(rest)) { + const colon = rest.indexOf(':') + const key = rest.slice(0, colon).trim() + items.push({ [key]: parseInlineValue(rest.slice(colon + 1)) }) + } else { + items.push(parseInlineValue(rest)) + } + i += 1 + } + return { node: items, next: i } + } + + // Mapping block. + const map: Record = {} + while (i < lines.length) { + const line = lines[i] ?? { indent: 0, content: '' } + if (line.indent < 0) throw new Error('Tabs are not supported in frontmatter indentation') + if (line.indent < indent) break + if (line.indent > indent) throw new Error(`Unexpected indentation at line ${i + 1}`) + const content = line.content + if (content === '' || content.startsWith('#')) { + i += 1 + continue + } + if (content.startsWith('- ')) { + // A list inside a mapping block belongs to the previous key's value; + // reaching it here means the caller sent us to the wrong indent. + throw new Error(`List item at line ${i + 1} has no containing key`) + } + const colon = content.indexOf(':') + if (colon === -1) { + throw new Error(`Expected a mapping entry at line ${i + 1}`) + } + const key = content.slice(0, colon).trim() + const rest = content.slice(colon + 1).trimStart() + if (key === '') throw new Error(`Empty key at line ${i + 1}`) + const nextLine = lines[i + 1] + const hasNested = nextLine !== undefined && nextLine.indent > indent && nextLine.indent >= 0 + if (rest === '' || rest.startsWith('#')) { + if (hasNested) { + const nested = parseBlock(lines, i + 1, nextLine.indent) + map[key] = nested.node + i = nested.next + } else { + map[key] = '' + i += 1 + } + continue + } + map[key] = parseInlineValue(rest) + i += 1 + } + return { node: map, next: i } +} + +/** + * Parses a YAML-subset frontmatter document (no `---` fences). + * @param text - Frontmatter text between the fences. + * @returns Parsed object, or an error description. + */ +export const parseFrontmatter = (text: string): FmResult => { + const lines: Line[] = [] + for (const raw of text.split('\n')) { + const { indent, content } = indentOf(raw) + lines.push({ indent, content }) + } + try { + const { node, next } = parseBlock(lines, 0, 0) + if (next < lines.length) { + return { ok: false, error: `Unexpected content after frontmatter block (line ${next + 1})` } + } + if (typeof node !== 'object' || node === null || Array.isArray(node)) { + return { ok: false, error: 'Frontmatter must be a mapping' } + } + return { ok: true, data: node } + } catch (err) { + return { ok: false, error: err instanceof Error ? err.message : 'invalid frontmatter' } + } +} + +/** Splits markdown into frontmatter and body; null frontmatter when absent. */ +export const splitFrontmatter = ( + content: string, +): { frontmatter: string | null; body: string } => { + const match = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(content) + if (!match) return { frontmatter: null, body: content } + return { frontmatter: match[1] ?? '', body: match[2] ?? '' } +} diff --git a/packages/dks-core/src/graph-path.test.ts b/packages/dks-core/src/graph-path.test.ts new file mode 100644 index 000000000..ef6131ec4 --- /dev/null +++ b/packages/dks-core/src/graph-path.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest' +import { + buildUndirectedAdjacency, + findShortestPath, + pathEdgeKeys, + pathNodeNames, + undirectedEdgeKey, + type PwaGraphEntityLike, +} from './graph-path.js' + +const graph: PwaGraphEntityLike[] = [ + { id: 'a', name: 'Alpha', links: [{ targetId: 'b', relation: 'related' }] }, + { id: 'b', name: 'Beta', links: [{ targetId: 'c', relation: 'related' }] }, + { id: 'c', name: 'Gamma', links: [] }, + { id: 'iso', name: 'Isolated', links: [] }, +] + +describe('graph-path', () => { + it('normalizes undirected edge keys', () => { + expect(undirectedEdgeKey('b', 'a')).toBe('a|b') + expect(undirectedEdgeKey('a', 'b')).toBe('a|b') + }) + + it('builds sorted undirected adjacency', () => { + const adjacency = buildUndirectedAdjacency(graph) + expect(adjacency.get('a')?.map((e) => e.target)).toEqual(['b']) + expect(adjacency.get('b')?.length).toBe(2) + }) + + it('finds the shortest path with hops', () => { + const result = findShortestPath(graph, 'a', 'c') + expect(result.found).toBe(true) + if (!result.found) return + expect(result.nodeIds).toEqual(['a', 'b', 'c']) + expect(result.edges).toEqual([ + { from: 'a', to: 'b', relation: 'related' }, + { from: 'b', to: 'c', relation: 'related' }, + ]) + expect(pathEdgeKeys(result.edges)).toEqual(new Set(['a|b', 'b|c'])) + }) + + it('returns a single-node path for identical endpoints', () => { + expect(findShortestPath(graph, 'a', 'a')).toEqual({ found: true, nodeIds: ['a'], edges: [] }) + }) + + it('reports no-path for disconnected pairs', () => { + expect(findShortestPath(graph, 'a', 'iso')).toEqual({ found: false, reason: 'no-path' }) + }) + + it('reports unknown-entity for missing endpoints', () => { + expect(findShortestPath(graph, 'a', 'ghost')).toEqual({ found: false, reason: 'unknown-entity' }) + }) + + it('terminates on cycles', () => { + const cyclic: PwaGraphEntityLike[] = [ + { id: 'x', name: 'X', links: [{ targetId: 'y' }] }, + { id: 'y', name: 'Y', links: [{ targetId: 'x' }] }, + ] + expect(findShortestPath(cyclic, 'x', 'y').found).toBe(true) + }) + + it('resolves display names in path order, skipping unknown ids', () => { + expect(pathNodeNames(graph, ['a', 'b', 'ghost'])).toEqual(['Alpha', 'Beta']) + }) +}) diff --git a/packages/dks-core/src/graph-path.ts b/packages/dks-core/src/graph-path.ts new file mode 100644 index 000000000..43cc24ac5 --- /dev/null +++ b/packages/dks-core/src/graph-path.ts @@ -0,0 +1,140 @@ +/** + * Undirected graph traversal — the PWA's shortest-path semantics, + * single-sourced here. + * + * This module is a framework-neutral port of the path portion of + * `src/lib/studio/graph-query.ts` (`findShortestPath`, `pathNodeNames`, + * `pathEdgeKeys`, `undirectedEdgeKey`, adjacency builder). The PWA file + * re-exports these from here; the `dks` CLI and MCP adapter call the same + * functions. Connections are treated as undirected (the way the studio + * canvas draws them), and paths are deterministic: neighbor buckets are + * sorted by display name. + */ + +/** Minimal structural shape of a graph entity (PWA `Entity` satisfies it). */ +export interface PwaGraphEntityLike { + id: string + name: string + links?: ReadonlyArray<{ targetId: string; relation?: string }> +} + +/** A connection as drawn on the canvas, oriented from its source entity. */ +export interface PathEdge { + id: string + source: string + target: string + relation: string +} + +/** A node in a recovered path, with the display name resolved by the caller. */ +export interface PathHop { + from: string + to: string + relation: string +} + +/** Outcome of a path query: the shortest route, or why there is none. */ +export type GraphPathResult = + | { found: true; nodeIds: string[]; edges: PathHop[] } + | { found: false; reason: 'unknown-entity' | 'no-path' } + +/** Canonical key for a connection, independent of traversal direction. */ +export const undirectedEdgeKey = (a: string, b: string): string => + a < b ? `${a}|${b}` : `${b}|${a}` + +/** The endpoint of an edge other than `id`. */ +const otherEnd = (edge: PathEdge, id: string): string => + edge.source === id ? edge.target : edge.source + +/** Builds undirected adjacency, sorted by the neighbour's display name. */ +export const buildUndirectedAdjacency = ( + entities: PwaGraphEntityLike[], +): Map => { + const nameOf = new Map(entities.map((entity) => [entity.id, entity.name])) + const adjacency = new Map() + const add = (id: string, edge: PathEdge): void => { + const bucket = adjacency.get(id) + if (bucket) bucket.push(edge) + else adjacency.set(id, [edge]) + } + for (const entity of entities) { + for (const link of entity.links ?? []) { + const edge: PathEdge = { + id: `${entity.id}->${link.targetId}`, + source: entity.id, + target: link.targetId, + relation: link.relation ?? '', + } + add(entity.id, edge) + add(link.targetId, edge) + } + } + const compare = (a: PathEdge, b: PathEdge, id: string): number => + (nameOf.get(otherEnd(a, id)) ?? '').localeCompare(nameOf.get(otherEnd(b, id)) ?? '') + for (const [id, bucket] of adjacency) { + bucket.sort((a, b) => compare(a, b, id)) + } + return adjacency +} + +/** + * Breadth-first shortest path between two entities over `links`, treating + * connections as undirected (the same way the canvas draws them). + * + * Cycles terminate because each node is enqueued once; a disconnected target + * reports `no-path` instead of an empty list. + */ +export const findShortestPath = ( + entities: PwaGraphEntityLike[], + fromId: string, + toId: string, +): GraphPathResult => { + const known = new Set(entities.map((entity) => entity.id)) + if (!known.has(fromId) || !known.has(toId)) return { found: false, reason: 'unknown-entity' } + if (fromId === toId) return { found: true, nodeIds: [fromId], edges: [] } + + const adjacency = buildUndirectedAdjacency(entities) + const cameFrom = new Map() + const visited = new Set([fromId]) + const queue: string[] = [fromId] + + for (const current of queue) { + for (const edge of adjacency.get(current) ?? []) { + const next = otherEnd(edge, current) + if (visited.has(next)) continue + visited.add(next) + cameFrom.set(next, edge) + queue.push(next) + } + } + + if (!cameFrom.has(toId)) return { found: false, reason: 'no-path' } + + const nodeIds = [toId] + const edges: PathHop[] = [] + let cursor = toId + while (cursor !== fromId) { + const edge = cameFrom.get(cursor) + if (!edge) return { found: false, reason: 'no-path' } + const prev = otherEnd(edge, cursor) + edges.push({ from: prev, to: cursor, relation: edge.relation }) + cursor = prev + nodeIds.push(cursor) + } + edges.reverse() + nodeIds.reverse() + return { found: true, nodeIds, edges } +} + +/** Display names for path node ids, in path order, skipping unknown ids. */ +export const pathNodeNames = (entities: PwaGraphEntityLike[], nodeIds: string[]): string[] => { + const nameOf = new Map(entities.map((entity) => [entity.id, entity.name])) + return nodeIds.flatMap((id) => { + const name = nameOf.get(id) + return name === undefined ? [] : [name] + }) +} + +/** Canonical undirected keys for the connections along a path. */ +export const pathEdgeKeys = (edges: PathHop[]): Set => + new Set(edges.map((edge) => undirectedEdgeKey(edge.from, edge.to))) diff --git a/packages/dks-core/src/import-services.test.ts b/packages/dks-core/src/import-services.test.ts new file mode 100644 index 000000000..e2ecead0f --- /dev/null +++ b/packages/dks-core/src/import-services.test.ts @@ -0,0 +1,140 @@ +import { describe, expect, it } from 'vitest' +import { parseMarkdownImport, parseOkfImportBundle } from './index.js' + +const INDEX = `---\nokf_version: '0.2'\n---\n\n# Index\n` +const ALPHA = `--- +type: Project +title: Alpha +description: First project +tags: + - research +sources: + - id: src-1 + resource: https://example.com/alpha + title: Alpha paper +verified: + by: human:ada +--- + +Alpha body. + +# Claims + +- Alpha scales linearly[^src-1] + +[^src-1]: Alpha paper +` +const BETA = `---\ntype: Concept\ntitle: Beta\n---\n\nBeta body.\n` + +describe('parseOkfImportBundle (shared service)', () => { + it('parses entities/claims with trust and provenance', () => { + const result = parseOkfImportBundle(new Map([ + ['index.md', INDEX], + ['log.md', '# Log\n'], + ['concepts/alpha.md', ALPHA], + ['concepts/beta.md', BETA], + ])) + expect(result.errors).toEqual([]) + expect(result.entities.map((e) => e.id)).toEqual(['concepts/alpha', 'concepts/beta']) + const alpha = result.entities[0] + expect(alpha?.type).toBe('project') + expect(alpha?.name).toBe('Alpha') + expect(alpha?.tags).toEqual(['research']) + expect(alpha?.content).toContain('Alpha body.') + expect(result.claims).toEqual([ + { + entityId: 'concepts/alpha', + statement: 'Alpha scales linearly', + verification: 'verified', + confidence: 1, + source: 'https://example.com/alpha', + evidence: 'Alpha paper', + createdAt: alpha?.createdAt, + updatedAt: alpha?.updatedAt, + version: 1, + }, + ]) + }) + + it('collects non-fatal errors for rooted paths and broken files', () => { + const result = parseOkfImportBundle(new Map([ + ['C:/evil.md', '---\ntype: Note\n---\n'], + ['concepts/plain.md', 'no frontmatter\n'], + ['concepts/ok.md', BETA], + ])) + expect(result.errors.some((e) => e.includes('not a bundle-relative path'))).toBe(true) + expect(result.errors.some((e) => e.includes('missing or unparseable frontmatter'))).toBe(true) + expect(result.entities.map((e) => e.id)).toEqual(['concepts/ok']) + }) + + it('reports missing/unsupported index versions', () => { + const missing = parseOkfImportBundle(new Map([ + ['index.md', '# Knowledge Bundle'], + ['concepts/a.md', BETA], + ])) + expect(missing.errors.some((e) => e.includes('missing okf_version'))).toBe(true) + const unsupported = parseOkfImportBundle(new Map([ + ['index.md', "---\nokf_version: '0.3'\n---\n"], + ['concepts/a.md', BETA], + ])) + expect(unsupported.errors.some((e) => e.includes('unsupported okf_version'))).toBe(true) + }) +}) + +const VAULT = new Map([ + ['notes/alpha.md', [ + '---', + 'title: Alpha', + 'type: concept', + 'tags:', + ' - research', + 'aliases:', + ' - A', + 'description: First concept', + '---', + '', + 'Alpha body with #tag #research.', + '', + 'See [[Beta]] and [[Gamma|G]].', + '', + 'Also [Beta](/notes/beta.md).', + ].join('\n')], + ['notes/beta.md', '---\ntitle: Beta\n---\n\nBeta body.\n'], + ['notes/plain.md', 'no frontmatter\n'], +]) + +describe('parseMarkdownImport (shared service)', () => { + it('parses drafts with frontmatter, tags, and scanned link spans', () => { + const result = parseMarkdownImport(VAULT) + expect(result.success).toBe(true) + if (!result.success) return + expect(result.drafts.map((d) => d.id)).toEqual(['notes/alpha', 'notes/beta', 'notes/plain']) + const alpha = result.drafts[0] + expect(alpha?.name).toBe('Alpha') + expect(alpha?.type).toBe('concept') + expect(alpha?.aliases).toEqual(['A']) + expect(alpha?.tags).toEqual(['research', 'tag']) + expect(alpha?.wikilinks.map((w) => w.name)).toEqual(['Beta', 'Gamma']) + expect(alpha?.wikilinks[1]?.display).toBe('G') + expect(alpha?.relativeLinks.map((r) => r.target)).toEqual(['notes/beta.md']) + }) + + it('warns on unknown keys, unknown types, and bad created dates', () => { + const files = new Map([ + ['a.md', '---\ntitle: A\ncustom: x\ntype: widget\ncreated: not-a-date\n---\n'], + ]) + const result = parseMarkdownImport(files) + expect(result.success).toBe(true) + if (!result.success) return + expect(result.warnings.some((w) => w.includes('custom'))).toBe(true) + expect(result.warnings.some((w) => w.includes('unknown type "widget"'))).toBe(true) + expect(result.warnings.some((w) => w.includes('unparseable created date'))).toBe(true) + expect(result.drafts[0]?.type).toBe('concept') + }) + + it('fails closed on limits (shared with the CLI path)', () => { + const big = new Map([['a.md', 'x'.repeat(1_048_577)]]) + const result = parseMarkdownImport(big) + expect(result.success).toBe(false) + }) +}) diff --git a/packages/dks-core/src/index.ts b/packages/dks-core/src/index.ts new file mode 100644 index 000000000..d2e5bc604 --- /dev/null +++ b/packages/dks-core/src/index.ts @@ -0,0 +1,114 @@ +/** + * dks-core: framework-neutral Knowledge Studio domain services shared by the + * `dks` CLI, the optional MCP adapter, and the PWA (via re-export facades). + * This module is the single public surface of the core; it imports no React, + * Next.js, or MCP SDK types. + */ + +export { + parseFrontmatter, + splitFrontmatter, + type FmResult, + type FmValue, +} from './frontmatter.js' +export { + deriveTrustTier, + extractClaimLines, + isSafePath, + parseBundleFiles, + parseConcept, + parseIndexFrontmatterVersion, + parseIndexVersion, + parseOkfImportBundle, + type ClaimLine, + type ImportedClaimLike, + type ImportedEntityLike, + type OkfImportServiceResult, +} from './okf-parse.js' +export { LibraryIndex, DEFAULT_LIMIT, type SearchHit } from './library-index.js' +export { + checkVaultLimits, + isMarkdownPath, + MAX_MARKDOWN_FILES, + MAX_MARKDOWN_FILE_BYTES, + MAX_MARKDOWN_TOTAL_BYTES, + MARKDOWN_EXTENSIONS, + parseMarkdownBundle, + parseMarkdownImport, + slug, + stripMarkdownExtension, + scanMarkdownLinks, + type MarkdownLinkSpans, + type MarkdownImportDraft, + type MarkdownImportResult, + type MarkdownImportServiceResult, + type RelativeLinkSpan, + type WikiLinkSpan, +} from './markdown.js' +export { + buildOkfBundle, + type CoreExportClaim, + type CoreExportEdge, + type CoreExportEntity, + type OkfBundle, + type OkfBundleFile, +} from './okf-export.js' +export { buildMarkdownExport, type MarkdownExportFile } from './markdown-export.js' +export { + search as pwaSearch, + getEntityMap as pwaGetEntityMap, + resetSearchCache as pwaResetSearchCache, + MAX_CACHE_ENTRIES, + type FilterableDoc, + type PwaClaimLike, + type PwaEntityLike, + type SearchFilter, + type SearchResult, +} from './pwa-retrieval.js' +export { + buildUndirectedAdjacency, + findShortestPath, + pathEdgeKeys, + pathNodeNames, + undirectedEdgeKey, + type GraphPathResult, + type PathEdge, + type PathHop, + type PwaGraphEntityLike, +} from './graph-path.js' +export { + BACKUP_FORMAT, + BACKUP_FORMAT_VERSION, + BACKUP_FILE_PATHS, + BACKUP_KDF_ITERATIONS, + MIN_SUPPORTED_SCHEMA_VERSION, + verifyBackupArchive, + type BackupErrorCode, + type BackupFailure, + type BackupVerifyResult, + type VerifiedBackupSummary, +} from './backup.js' +export type { + BundleClaim, + BundleConcept, + BundleSource, + CoreClaim, + CoreEntity, + LoadedBundle, + TrustTier, +} from './types.js' +export { + EXPORT_PREFIX, + MAX_BUNDLE_ENTRIES, + MAX_BUNDLE_UNCOMPRESSED_BYTES, + MAX_BUNDLE_ZIP_BYTES, + MAX_CONCEPT_BYTES, + SUPPORTED_OKF_MAJOR, +} from './types.js' +export { loadBundleFromDisk } from './bundle-load.js' +export { + nodeFsPort, + nodeFsWriterPort, + type FsPort, + type FsWriterPort, +} from './io.js' diff --git a/packages/dks-core/src/io.ts b/packages/dks-core/src/io.ts new file mode 100644 index 000000000..6da867a7a --- /dev/null +++ b/packages/dks-core/src/io.ts @@ -0,0 +1,85 @@ +/** + * Filesystem port: the boundary between core domain services and the + * Node.js environment. Core services never touch `node:fs` directly; a + * caller (CLI or MCP) supplies a port, which keeps every core unit test + * runnable without real disk access. Browser persistence stays entirely + * outside this port and outside the core. + */ +import { randomUUID } from 'node:crypto' +import { mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs' +import { mkdir, open, rename, unlink, type FileHandle } from 'node:fs/promises' +import { dirname } from 'node:path' + + +/** A directory entry as seen by the core. */ +export interface DirEntry { + name: string + isDirectory: boolean +} + +/** Typed filesystem operations the core requires. */ +export interface FsPort { + /** True when the path resolves to a directory; false for files. */ + isDirectory(path: string): boolean + /** Reads a whole file as bytes; throws when unreadable. */ + readFileBytes(path: string): Uint8Array + /** Lists a directory's entries, sorted by name (stable order). */ + readDirEntries(path: string): DirEntry[] +} + +/** Node.js implementation of {@link FsPort}. */ +export const nodeFsPort: FsPort = { + isDirectory(path) { + try { + return statSync(path).isDirectory() + } catch { + return false + } + }, + readFileBytes(path) { + return readFileSync(path) + }, + readDirEntries(path) { + return readdirSync(path, { withFileTypes: true }) + .map((e) => ({ name: e.name, isDirectory: e.isDirectory() })) + .sort((a, b) => a.name.localeCompare(b.name)) + }, +} + +/** Typed filesystem write operations (atomic file writes). */ +export interface FsWriterPort { + /** Creates a directory tree recursively. */ + mkdirRecursive(dir: string): void + /** Writes a file atomically (temp file + rename; no partial finals). */ + writeFileAtomically(path: string, content: string, signal?: AbortSignal): Promise +} + +/** Node.js implementation of {@link FsWriterPort}. */ +export const nodeFsWriterPort: FsWriterPort = { + mkdirRecursive(dir) { + mkdirSync(dir, { recursive: true }) + }, + async writeFileAtomically(path, content, signal) { + await mkdir(dirname(path), { recursive: true }) + const tempPath = `${path}.${randomUUID()}.dks-tmp` + let created = false + let handle: FileHandle | undefined + try { + handle = await open(tempPath, 'wx') + created = true + await handle.writeFile(content, { encoding: 'utf8', signal }) + await handle.close() + handle = undefined + if (signal?.aborted) { + const error = new Error('The operation was aborted') + error.name = 'AbortError' + throw error + } + await rename(tempPath, path) + } catch (error) { + if (handle) await handle.close().catch(() => undefined) + if (created) await unlink(tempPath).catch(() => undefined) + throw error + } + }, +} diff --git a/packages/dks-core/src/library-index.test.ts b/packages/dks-core/src/library-index.test.ts new file mode 100644 index 000000000..87fba94db --- /dev/null +++ b/packages/dks-core/src/library-index.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, it } from 'vitest' +import { LibraryIndex } from './library-index.js' +import { pwaResetSearchCache } from './index.js' +import type { BundleConcept } from './types.js' + +/** Builds a concept fixture with overridable fields. */ +const concept = (overrides: Partial & { id: string; name: string }): BundleConcept => ({ + type: 'Concept', + description: '', + content: '', + tags: [], + trustTier: 'unverified', + sources: [], + claims: [], + relatedIds: [], + ...overrides, +}) + +/** Three-concept library: Alpha links Beta; two share a name. */ +const concepts = [ + concept({ id: 'a', name: 'Alpha', type: 'Project', description: 'First project', content: 'alpha body', tags: ['research'], relatedIds: ['b'] }), + concept({ id: 'b', name: 'Beta', content: 'plain beta', tags: ['shared'] }), + concept({ id: 'c', name: 'Alpha', content: 'unrelated gamma content' }), +] + +const index = new LibraryIndex(concepts) + +describe('LibraryIndex', () => { + it('resolves ids, unique names, ambiguity, and absence', () => { + const resolveId = (name: string): string | undefined => { + const result = index.resolve(name) + return 'concept' in result ? result.concept.id : undefined + } + expect(resolveId('a')).toBe('a') + expect(resolveId('Beta')).toBe('b') + const ambiguous = index.resolve('Alpha') + expect('error' in ambiguous && ambiguous.error).toContain('2 concepts') + const missing = index.resolve('ghost') + expect('error' in missing && missing.error).toContain('No concept found') + }) + + it('ranks both name-sharing concepts deterministically (shared BM25 engine)', () => { + const hits = index.search('alpha', 10) + expect(hits.map((h) => h.concept.id).sort()).toEqual(['a', 'c']) + expect(hits[0]?.score).toBeGreaterThanOrEqual(hits[1]?.score ?? 0) + expect(hits.every((h) => h.score > 0)).toBe(true) + }) + + it('searches plain body tokens', () => { + const hits = index.search('beta', 10) + expect(hits.map((h) => h.concept.id)).toEqual(['b']) + }) + + it('searches claim statements embedded in concept text', () => { + const withClaims = new LibraryIndex([ + concept({ id: 'd', name: 'Delta', claims: [{ statement: 'delta claim', verification: 'unverified' }] }), + concept({ id: 'e', name: 'Echo' }), + ]) + const hits = withClaims.search('delta claim', 100) + expect(hits[0]?.concept.id).toBe('d') + expect(withClaims.search('echo', 0)).toHaveLength(0) + expect(withClaims.search('echo', 1)).toHaveLength(1) + }) + + it('is stop-word aware (shared engine)', () => { + // "the" is a stop word: it matches nothing. + expect(index.search('the', 10)).toHaveLength(0) + }) + + it('censuses tags by count then name', () => { + const tags = index.tags() + expect(tags[0]).toEqual({ tag: 'shared', count: 1 }) + expect(tags.length).toBe(2) + }) + + it('finds the shortest related path and reports disconnected pairs', () => { + const path = index.shortestPath('a', 'b') + expect(path).toEqual({ found: true, ids: ['a', 'b'] }) + const none = index.shortestPath('a', 'c') + expect(none).toEqual({ found: false, reason: 'no-path' }) + const self = index.shortestPath('a', 'a') + expect(self).toEqual({ found: true, ids: ['a'] }) + }) + + it('terminates on a related-link cycle', () => { + const cyclic = new LibraryIndex([ + concept({ id: 'x', name: 'X', relatedIds: ['y'] }), + concept({ id: 'y', name: 'Y', relatedIds: ['x'] }), + ]) + expect(cyclic.shortestPath('x', 'y').found).toBe(true) + }) + + it('builds one-hop neighborhoods and drops dangling targets', () => { + const nb = index.neighborhood('a') + expect(nb.outgoing.map((c) => c.id)).toEqual(['b']) + expect(nb.incoming).toEqual([]) + const dangling = new LibraryIndex([ + concept({ id: 'p', name: 'P', relatedIds: ['q', 'ghost'] }), + concept({ id: 'q', name: 'Q', relatedIds: ['p'] }), + ]) + expect(dangling.neighborhood('p').outgoing.map((c) => c.id)).toEqual(['q']) + }) + + it('computes bounded graph statistics', () => { + const stats = index.stats() + expect(stats.concepts).toBe(3) + expect(stats.edges).toBe(1) + expect(stats.components).toBe(2) + expect(stats.largestComponent).toBe(2) + expect(stats.avgDegree).toBeCloseTo(2 / 3) + }) + + it('resetSearchCache is exposed for the shared engine', () => { + pwaResetSearchCache() + expect(index.search('alpha', 10).length).toBe(2) + }) +}) diff --git a/packages/dks-core/src/library-index.ts b/packages/dks-core/src/library-index.ts new file mode 100644 index 000000000..0d0d488eb --- /dev/null +++ b/packages/dks-core/src/library-index.ts @@ -0,0 +1,204 @@ +/** + * Read-only bundle index shared by the `dks` CLI and the MCP adapter. + * + * Lookup/tag census bookkeeping lives here, but every ranking and every + * graph traversal delegates to the single shared engines (`pwa-retrieval` + * and `graph-path`), which are the same implementations the PWA uses via its + * re-export facades. There is no second search/graph implementation. + */ + +import { buildUndirectedAdjacency, findShortestPath } from './graph-path.js' +import { search as pwaSearch, type PwaEntityLike } from './pwa-retrieval.js' +import type { BundleConcept } from './types.js' + +/** Default result cap when the caller passes no limit. */ +export const DEFAULT_LIMIT = 5 + +/** A scored concept returned by search. */ +export interface SearchHit { + /** The matched concept. */ + concept: BundleConcept + /** BM25 score (higher ranks first). */ + score: number +} + +/** Adapts a concept to the shared retrieval engine's entity shape. */ +const toEntityDoc = (c: BundleConcept): PwaEntityLike => ({ + id: c.id, + name: c.name, + type: c.type, + description: c.description, + content: `${c.content}\n${c.claims.map((cl) => cl.statement).join('\n')}`, + tags: c.tags, +}) + +/** Read-only index over bundle concepts. */ +export class LibraryIndex { + /** Concepts in bundle order. */ + private readonly concepts: BundleConcept[] + /** Concept by id. */ + private readonly byId = new Map() + /** Concept ids by lowercase name. */ + private readonly idsByName = new Map() + /** Concept docs laid out for the shared retrieval engine. */ + private readonly docs: PwaEntityLike[] + /** Graph entities for the shared traversal engine. */ + private readonly graphEntities: Array<{ id: string; name: string; links: Array<{ targetId: string; relation: string }> }> + + /** Builds the index; keeps bundle order for stable ties. */ + constructor(concepts: BundleConcept[]) { + this.concepts = [...concepts] + this.docs = concepts.map(toEntityDoc) + this.graphEntities = concepts.map((c) => ({ + id: c.id, + name: c.name, + links: c.relatedIds.map((targetId) => ({ targetId, relation: 'related' })), + })) + for (const c of concepts) { + this.byId.set(c.id, c) + const key = c.name.toLowerCase() + this.idsByName.set(key, [...(this.idsByName.get(key) ?? []), c.id]) + } + } + + /** Number of indexed concepts. */ + get size(): number { + return this.concepts.length + } + + /** Finds a concept by exact id. */ + getById(id: string): BundleConcept | undefined { + return this.byId.get(id) + } + + /** Finds concept ids sharing a case-insensitive name. */ + getIdsByName(name: string): string[] { + return this.idsByName.get(name.toLowerCase()) ?? [] + } + + /** + * Resolves an `id-or-name` reference: exact id first, then unique name. + * @param ref - Concept id or name. + * @returns The concept, or an error describing ambiguity/absence. + */ + resolve(ref: string): { concept: BundleConcept } | { error: string } { + const byId = this.byId.get(ref) + if (byId) return { concept: byId } + const ids = this.getIdsByName(ref) + if (ids.length === 1) { + const found = this.byId.get(ids[0] ?? '') + if (found) return { concept: found } + } + if (ids.length > 1) { + return { error: `"${ref}" names ${ids.length} concepts; pass an id instead: ${ids.join(', ')}.` } + } + return { error: `No concept found for "${ref}".` } + } + + /** All concepts in bundle order. */ + all(): BundleConcept[] { + return [...this.concepts] + } + + /** Tag census sorted by count desc, then name descending. */ + tags(): Array<{ tag: string; count: number }> { + const counts = new Map() + for (const c of this.concepts) { + for (const t of new Set(c.tags)) counts.set(t, (counts.get(t) ?? 0) + 1) + } + return [...counts.entries()] + .map(([tag, count]) => ({ tag, count })) + .sort((a, b) => b.count - a.count || b.tag.localeCompare(a.tag)) + } + + /** + * Ranks concepts with the shared lexical engine (BM25, stop-word aware). + * One hit per concept; the concept text includes claim statements. + * @param query - Raw query text. + * @param limit - Max hits. + * @returns Hits ordered by score desc, bundle order breaking ties. + */ + search(query: string, limit = DEFAULT_LIMIT): SearchHit[] { + const capped = Math.max(Math.floor(limit), 0) + const results = pwaSearch(this.docs, [], query, capped) + const hits: SearchHit[] = [] + for (const result of results) { + const concept = this.byId.get(result.id) + if (concept) hits.push({ concept, score: result.score }) + } + return hits + } + + /** + * Breadth-first shortest path between two concepts over related links, + * computed by the shared traversal engine (undirected, name-sorted). + * @param fromId - Start concept id. + * @param toId - Target concept id. + * @returns Ordered ids, or `no-path` when nothing connects the pair. + */ + shortestPath( + fromId: string, + toId: string, + ): { found: true; ids: string[] } | { found: false; reason: 'no-path' } { + const result = findShortestPath(this.graphEntities, fromId, toId) + if (!result.found) return { found: false, reason: 'no-path' } + return { found: true, ids: result.nodeIds } + } + + /** + * One-hop neighborhood: concepts this concept links to plus concepts + * linking back, with dangling targets dropped. + * @param id - Concept id. + * @returns Outgoing and incoming neighbors. + */ + neighborhood(id: string): { outgoing: BundleConcept[]; incoming: BundleConcept[] } { + const outgoing: BundleConcept[] = [] + for (const target of this.byId.get(id)?.relatedIds ?? []) { + const found = this.byId.get(target) + if (found) outgoing.push(found) + } + const incoming = this.concepts.filter( + (c) => c.id !== id && c.relatedIds.includes(id), + ) + return { outgoing, incoming } + } + + /** + * Graph statistics over the shared undirected adjacency: nodes, edges, + * components, and the largest component. Bounded: O(V+E). + */ + stats(): { + concepts: number + edges: number + components: number + largestComponent: number + avgDegree: number + } { + const adjacency = buildUndirectedAdjacency(this.graphEntities) + let edges = 0 + for (const bucket of adjacency.values()) edges += bucket.length + edges /= 2 + const seen = new Set() + let components = 0 + let largestComponent = 0 + for (const concept of this.concepts) { + if (seen.has(concept.id)) continue + components += 1 + let size = 0 + const queue = [concept.id] + seen.add(concept.id) + for (const current of queue) { + size += 1 + for (const edge of adjacency.get(current) ?? []) { + const next = edge.source === current ? edge.target : edge.source + if (seen.has(next)) continue + seen.add(next) + queue.push(next) + } + } + if (size > largestComponent) largestComponent = size + } + const degree = this.concepts.length > 0 ? (2 * edges) / this.concepts.length : 0 + return { concepts: this.concepts.length, edges, components, largestComponent, avgDegree: degree } + } +} diff --git a/packages/dks-core/src/markdown-export.test.ts b/packages/dks-core/src/markdown-export.test.ts new file mode 100644 index 000000000..4707b5259 --- /dev/null +++ b/packages/dks-core/src/markdown-export.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from 'vitest' +import { buildMarkdownExport } from './markdown-export.js' +import { parseMarkdownBundle } from './markdown.js' +import type { CoreEntity } from './types.js' + +const entities: CoreEntity[] = [ + { + id: 'notes/alpha', + name: 'Alpha', + type: 'concept', + description: 'First', + content: 'Alpha body.', + tags: ['research'], + aliases: ['A'], + links: [{ targetId: 'notes/beta', relation: 'related' }], + }, + { + id: 'notes/beta', + name: 'Beta', + type: 'note', + description: '', + content: 'Beta body.', + tags: [], + }, +] + +describe('buildMarkdownExport', () => { + it('serializes entities with frontmatter and wikilinks', () => { + const files = buildMarkdownExport(entities) + const alpha = files.find((f) => f.path === 'alpha.md') + expect(alpha?.content).toContain('title: Alpha') + expect(alpha?.content).toContain('type: concept') + expect(alpha?.content).toContain('aliases:') + expect(alpha?.content).toContain('[[Beta]]') + expect(files.map((f) => f.path)).toEqual(['alpha.md', 'beta.md']) + }) + + it('round-trips through the markdown parser', () => { + const files = buildMarkdownExport(entities) + const map = new Map(files.map((f) => [f.path, f.content])) + const r = parseMarkdownBundle(map) + const parsedEntities = r.success ? r.entities : [] + expect(r.success).toBe(true) + expect(parsedEntities[0]?.aliases).toEqual(['A']) + expect(parsedEntities[0]?.tags).toEqual(['research']) + expect(parsedEntities[0]?.links).toEqual([{ targetId: 'beta', relation: 'related' }]) + }) + + it('disambiguates duplicate slugs', () => { + const dupes: CoreEntity[] = [ + { id: 'a', name: 'Same', type: 'concept', description: '', content: '', tags: [] }, + { id: 'b', name: 'Same', type: 'concept', description: '', content: '', tags: [] }, + ] + const paths = buildMarkdownExport(dupes).map((f) => f.path) + expect(paths).toEqual(['same.md', 'same-2.md']) + }) +}) diff --git a/packages/dks-core/src/markdown-export.ts b/packages/dks-core/src/markdown-export.ts new file mode 100644 index 000000000..f4b8d0b9f --- /dev/null +++ b/packages/dks-core/src/markdown-export.ts @@ -0,0 +1,77 @@ +/** + * Markdown export: serializes core entities into a directory of `.md` + * files (frontmatter + body + `[[Wikilink]]` related links). This is the + * inverse of {@link parseMarkdownBundle}: the round trip is stable for the + * supported field subset. + */ + +import { slug } from './markdown.js' +import type { CoreEntity } from './types.js' + +/** A markdown export file: vault-relative path plus content. */ +export interface MarkdownExportFile { + path: string + content: string +} + +/** Renders a scalar frontmatter value safely. */ +const formatFmValue = (value: string): string => { + if (/[\n"'#:]|^\s|\s$/.test(value)) { + return JSON.stringify(value) + } + return value +} + +/** Renders a list frontmatter value as indented items. */ +const formatFmList = (values: string[]): string => + values.map((v) => ` - ${formatFmValue(v)}`).join('\n') + +/** Serializes one entity into a markdown file. */ +const buildNoteDoc = (e: CoreEntity, nameById: Map): string => { + const fmLines: string[] = [] + fmLines.push(`title: ${formatFmValue(e.name)}`) + fmLines.push(`type: ${formatFmValue(e.type)}`) + if (e.description !== '') fmLines.push(`description: ${formatFmValue(e.description)}`) + if (e.tags.length > 0) { + fmLines.push('tags:') + fmLines.push(formatFmList(e.tags)) + } + if (e.aliases && e.aliases.length > 0) { + fmLines.push('aliases:') + fmLines.push(formatFmList(e.aliases)) + } + const body = e.content.trim() + const related = (e.links ?? []) + .map((l) => nameById.get(l.targetId) ?? l.targetId) + .filter((t, i, all) => all.indexOf(t) === i) + const parts: string[] = [] + if (body !== '') parts.push(body) + if (related.length > 0) { + parts.push(related.map((name) => `[[${name}]]`).join(' ')) + } + return `---\n${fmLines.join('\n')}\n---\n\n${parts.join('\n\n')}\n` +} + +/** + * Exports entities to a markdown file set. Paths are unique slugs under the + * vault root; duplicate slugs get numeric suffixes. + * @param entities - Entities to serialize. + * @returns The markdown files (path → content). + */ +export const buildMarkdownExport = (entities: CoreEntity[]): MarkdownExportFile[] => { + const used = new Set() + const files: MarkdownExportFile[] = [] + const nameById = new Map(entities.map((e) => [e.id, e.name])) + for (const e of entities) { + const base = `${slug(e.name)}.md` + let path = base + let n = 2 + while (used.has(path)) { + path = base.replace(/\.md$/, `-${n}.md`) + n += 1 + } + used.add(path) + files.push({ path, content: buildNoteDoc(e, nameById) }) + } + return files +} diff --git a/packages/dks-core/src/markdown.test.ts b/packages/dks-core/src/markdown.test.ts new file mode 100644 index 000000000..0e87d03f4 --- /dev/null +++ b/packages/dks-core/src/markdown.test.ts @@ -0,0 +1,101 @@ +import { describe, expect, it } from 'vitest' +import { checkVaultLimits, parseMarkdownBundle, slug, stripMarkdownExtension } from './markdown.js' + +describe('slug', () => { + it('kebab-cases names', () => { + expect(slug('Hello World')).toBe('hello-world') + expect(slug(' Spaced ')).toBe('spaced') + expect(slug('!!!')).toBe('untitled') + }) +}) + +describe('stripMarkdownExtension', () => { + it('strips .md and .markdown', () => { + expect(stripMarkdownExtension('notes/a.md')).toBe('notes/a') + expect(stripMarkdownExtension('notes/a.markdown')).toBe('notes/a') + expect(stripMarkdownExtension('notes/a.txt')).toBe('notes/a.txt') + }) +}) + +describe('checkVaultLimits', () => { + it('fails closed on empty, oversized, and over-count batches', () => { + expect(checkVaultLimits(new Map())).toMatch(/No Markdown files/) + const many = new Map() + for (let i = 0; i < 501; i += 1) many.set(`f${i}.md`, 'x') + expect(checkVaultLimits(many)).toMatch(/Too many files/) + const huge = new Map([['a.md', 'x'.repeat(1_048_577)]]) + expect(checkVaultLimits(huge)).toMatch(/too large/) + }) +}) + +const VAULT = new Map([ + ['notes/alpha.md', [ + '---', + 'title: Alpha', + 'type: concept', + 'tags:', + ' - research', + 'aliases:', + ' - A', + 'description: First concept', + '---', + '', + 'Alpha body with #tag #research.', + '', + 'See [[Beta]] and [[Gamma|G]].', + ].join('\n')], + ['notes/beta.md', [ + '---', + 'title: Beta', + '---', + '', + 'Beta body.', + ].join('\n')], + ['notes/plain.md', 'no frontmatter\n'], +]) + +describe('parseMarkdownBundle', () => { + it('parses entities with aliases, tags, and wikilink resolution', () => { + const r = parseMarkdownBundle(VAULT) + expect(r.success).toBe(true) + if (!r.success) return + const alpha = r.entities.find((e) => e.id === 'notes/alpha') + expect(alpha?.name).toBe('Alpha') + expect(alpha?.type).toBe('concept') + expect(alpha?.aliases).toEqual(['A']) + expect(alpha?.tags).toEqual(['research', 'tag']) + expect(alpha?.links).toEqual([{ targetId: 'notes/beta', relation: 'related' }, { targetId: 'gamma', relation: 'related' }]) + expect(r.stubNames).toEqual(['Gamma']) + expect(r.conflicts).toEqual([]) + const stub = r.entities.find((e) => e.id === 'gamma') + expect(stub?.name).toBe('Gamma') + expect(stub?.description).toMatch(/Stub/) + const plain = r.entities.find((e) => e.id === 'notes/plain') + expect(plain?.name).toBe('plain') + expect(plain?.content).toBe('no frontmatter') + }) + + it('reports name conflicts', () => { + const files = new Map([ + ['a.md', '---\ntitle: Same\n---\n'], + ['b.md', '---\ntitle: Same\n---\n'], + ]) + const r = parseMarkdownBundle(files) + expect(r.success).toBe(true) + if (!r.success) return + expect(r.conflicts.length).toBe(1) + }) + + it('collects unknown frontmatter key warnings', () => { + const files = new Map([['a.md', '---\ntitle: A\ncustom: x\n---\n']]) + const r = parseMarkdownBundle(files) + if (!r.success) return + expect(r.warnings.some((w) => w.includes('custom'))).toBe(true) + }) + + it('fails closed on limit violations', () => { + const files = new Map([['a.md', 'x'.repeat(1_048_577)]]) + const r = parseMarkdownBundle(files) + expect(r.success).toBe(false) + }) +}) diff --git a/packages/dks-core/src/markdown.ts b/packages/dks-core/src/markdown.ts new file mode 100644 index 000000000..4c9545998 --- /dev/null +++ b/packages/dks-core/src/markdown.ts @@ -0,0 +1,402 @@ +/** + * Markdown / Obsidian-vault import service shared by the PWA and the CLI. + * + * The service is responsible for every validation and parsing rule: + * fail-closed batch limits, vault-relative path guards, frontmatter mapping + * (title/type/description/tags/aliases/created), `#tag` extraction, and + * link-span scanning (`[[Wikilinks]]` + relative `.md` links). The PWA + * adapter calls {@link parseMarkdownImport} and keeps only editor-specific + * presentation (mention-token rendering, claim extraction, UUID stub + * minting) on its side; the CLI uses {@link parseMarkdownBundle} directly. + */ + +import { parseFrontmatter, splitFrontmatter } from './frontmatter.js' +import type { CoreEntity } from './types.js' + +/** Maximum `.md` files accepted in one import batch. */ +export const MAX_MARKDOWN_FILES = 500 +/** Maximum characters read from a single `.md` file. */ +export const MAX_MARKDOWN_FILE_BYTES = 1_048_576 +/** Maximum total characters across all `.md` files in one batch. */ +export const MAX_MARKDOWN_TOTAL_BYTES = 20_971_520 +/** File extensions treated as importable notes. */ +export const MARKDOWN_EXTENSIONS = ['.md', '.markdown'] + +/** Frontmatter keys mapped onto entity fields; others are warned and ignored. */ +const KNOWN_FRONTMATTER_KEYS: Record = { + title: true, + tags: true, + aliases: true, + type: true, + created: true, + description: true, +} + +/** Obsidian type strings mapped onto entity types (unknown → concept). */ +const VAULT_TYPE_MAP: Record = { + note: 'note', + concept: 'concept', + person: 'person', + project: 'project', +} + +/** Matches a `[[Wikilink]]` token (optionally with an alias after `|`). */ +const WIKILINK_PATTERN = /\[\[([^[\]|]+)(?:\|([^[\]]+))?\]\]/g +/** Matches `#tag` tokens (unicode-aware); headings are filtered by caller. */ +const HASHTAG_PATTERN = /(^|\s)#([\p{L}\p{N}_][\p{L}\p{N}_-]*)/gu +/** A Markdown heading line — `#tag` on such a line is a heading, not a tag. */ +const HEADING_LINE_PATTERN = /^\s*#{1,6}(?:\s|$)/ +/** Matches a relative Markdown link `[text](target)`; images are filtered by caller. */ +const RELATIVE_LINK_PATTERN = /\[([^\]]*)\]\(([^)\s]+)\)/g + +/** Result of parsing a Markdown / vault batch (CLI shape). */ +export type MarkdownImportResult = + | { + success: true + entities: CoreEntity[] + /** Names that resolved to nothing; stub entities were minted for them. */ + stubNames: string[] + /** Names shared by several ids (imported anyway — names are not keys). */ + conflicts: string[] + /** Non-fatal per-file skips and ignored frontmatter keys. */ + warnings: string[] + } + | { success: false; error: string } + +/** A `[[Wikilink]]` span inside a note body. */ +export interface WikiLinkSpan { + start: number + end: number + name: string + display?: string +} + +/** A relative `[text](target)` span inside a note body. */ +export interface RelativeLinkSpan { + start: number + end: number + text: string + /** Decoded target without its fragment. */ + target: string +} + + +/** Shared link spans for PWA presentation and other Markdown adapters. */ +export interface MarkdownLinkSpans { + wikilinks: WikiLinkSpan[] + relativeLinks: RelativeLinkSpan[] +} +/** A parsed note before link presentation (shared PWA/CLI draft). */ +export interface MarkdownImportDraft { + id: string + name: string + type: string + description: string + /** Trimmed body without frontmatter; link rendering is presentation work. */ + content: string + tags: string[] + /** Source buckets let adapters preserve their historical tag ordering. */ + frontmatterTags: string[] + bodyTags: string[] + aliases?: string[] + createdAt: string + updatedAt: string + /** Span offsets refer to `content`. */ + wikilinks: WikiLinkSpan[] + relativeLinks: RelativeLinkSpan[] +} + +/** Batch result of the shared Markdown import service. */ +export type MarkdownImportServiceResult = + | { success: true; drafts: MarkdownImportDraft[]; warnings: string[] } + | { success: false; error: string } + +/** Slugs a name into a safe, lowercase, kebab-case id. */ +export const slug = (s: string): string => + s + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, '') || 'untitled' + +/** Strips a Markdown extension (`.md` / `.markdown`) from a vault path. */ +export const stripMarkdownExtension = (path: string): string => + path.replace(/\.markdown$/i, '').replace(/\.md$/i, '') + +/** True when the path points at an importable note file. */ +export const isMarkdownPath = (path: string): boolean => + MARKDOWN_EXTENSIONS.some((ext) => path.toLowerCase().endsWith(ext)) + +/** Coerces a frontmatter list-ish value (list, string, or flow array). */ +const coerceStringList = (value: unknown): string[] => { + if (Array.isArray(value)) return value.filter((v): v is string => typeof v === 'string') + if (typeof value === 'string') return value.split(/[,\s]+/).filter((v) => v !== '') + return [] +} + +/** Extracts `#tags` from a body, skipping headings and fenced/inline code. */ +const extractHashtags = (body: string): string[] => { + const tags: string[] = [] + const seen = new Set() + let inFence: string | null = null + for (const line of body.split('\n')) { + const fence = /^\s*(```|~~~)/.exec(line) + if (fence) { + const marker = fence[1] ?? '' + if (inFence === null) inFence = marker + else if (inFence === marker) inFence = null + continue + } + if (inFence !== null || HEADING_LINE_PATTERN.test(line)) continue + const withoutInline = line.replace(/`[^`]*`/g, '') + HASHTAG_PATTERN.lastIndex = 0 + let match = HASHTAG_PATTERN.exec(withoutInline) + while (match !== null) { + const tag = match[2] ?? '' + if (tag !== '' && !seen.has(tag)) { + seen.add(tag) + tags.push(tag) + } + match = HASHTAG_PATTERN.exec(withoutInline) + } + } + return tags +} + +/** Decodes a link target and strips its fragment; raw text on bad escapes. */ +const decodeTarget = (target: string): string => { + try { + return decodeURIComponent(target).split('#')[0] ?? '' + } catch { + return target.split('#')[0] ?? '' + } +} + +/** Scans a body for wikilink and relative-link spans. */ +export const scanMarkdownLinks = (body: string): MarkdownLinkSpans => { + const wikilinks: WikiLinkSpan[] = [] + WIKILINK_PATTERN.lastIndex = 0 + let m = WIKILINK_PATTERN.exec(body) + while (m !== null) { + const name = (m[1] ?? '').trim() + if (name !== '') { + const display = (m[2] ?? '').trim() + wikilinks.push(display !== '' ? { start: m.index, end: m.index + m[0].length, name, display } : { start: m.index, end: m.index + m[0].length, name }) + } + m = WIKILINK_PATTERN.exec(body) + } + const relativeLinks: RelativeLinkSpan[] = [] + RELATIVE_LINK_PATTERN.lastIndex = 0 + let r = RELATIVE_LINK_PATTERN.exec(body) + while (r !== null) { + if (body[r.index - 1] !== '!' && !/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(r[2] ?? '')) { + relativeLinks.push({ + start: r.index, + end: r.index + r[0].length, + text: r[1] ?? '', + target: decodeTarget(r[2] ?? '').replace(/^\/+/, ''), + }) + } + r = RELATIVE_LINK_PATTERN.exec(body) + } + return { wikilinks, relativeLinks } +} + +/** + * Fails closed on batch limits before any parsing happens. + * @param files - Vault-relative path → raw content. + * @returns An error message, or null when the batch is within limits. + */ +export const checkVaultLimits = (files: Map): string | null => { + if (files.size === 0) return 'No Markdown files found to import.' + if (files.size > MAX_MARKDOWN_FILES) { + return `Too many files (${files.size}); at most ${MAX_MARKDOWN_FILES} Markdown files can be imported at once.` + } + let total = 0 + for (const [path, content] of files) { + const bytes = content.length + if (bytes > MAX_MARKDOWN_FILE_BYTES) { + return `"${path}" is too large (${bytes} characters); files are limited to ${MAX_MARKDOWN_FILE_BYTES} characters.` + } + total += bytes + if (total > MAX_MARKDOWN_TOTAL_BYTES) { + return `Import is too large; Markdown batches are limited to ${MAX_MARKDOWN_TOTAL_BYTES} characters in total.` + } + } + return null +} + +/** Parses one vault file into a shared draft; never throws. */ +const parseDraftFile = ( + path: string, + content: string, + nowIso: string, + warnings: string[], +): MarkdownImportDraft | null => { + const split = splitFrontmatter(content) + const fileName = stripMarkdownExtension(path.split('/').pop() ?? path) + let name = fileName + let type = 'concept' + let description = '' + let createdAt = nowIso + let fm: Record = {} + + if (split.frontmatter !== null) { + const parsed = parseFrontmatter(split.frontmatter) + if (!parsed.ok) { + warnings.push(`${path}: invalid YAML frontmatter — ${parsed.error}`) + return null + } + fm = parsed.data as Record + for (const key of Object.keys(fm)) { + if (!KNOWN_FRONTMATTER_KEYS[key]) { + warnings.push(`${path}: ignoring unknown frontmatter key "${key}"`) + } + } + if (typeof fm.title === 'string' && fm.title.trim() !== '') name = fm.title.trim() + if (typeof fm.type === 'string') { + const mapped = VAULT_TYPE_MAP[fm.type.trim().toLowerCase()] + if (mapped) type = mapped + else warnings.push(`${path}: unknown type "${fm.type}" — imported as concept`) + } + if (typeof fm.description === 'string') description = fm.description + if (typeof fm.created === 'string') { + const parsedDate = new Date(fm.created) + if (Number.isNaN(parsedDate.getTime())) { + warnings.push(`${path}: ignoring unparseable created date "${fm.created}"`) + } else { + createdAt = parsedDate.toISOString() + } + } + } + + const frontmatterTags = coerceStringList(fm.tags) + const bodyTags = extractHashtags(split.body) + const aliases = coerceStringList(fm.aliases) + const seen = new Set() + const tags: string[] = [] + for (const tag of [...frontmatterTags, ...bodyTags]) { + const clean = tag.trim() + if (clean !== '' && !seen.has(clean)) { + seen.add(clean) + tags.push(clean) + } + } + const trimmedContent = split.body.trim() + const { wikilinks, relativeLinks } = scanMarkdownLinks(trimmedContent) + const draft: MarkdownImportDraft = { + id: stripMarkdownExtension(path), + name, + type, + description, + content: trimmedContent, + tags, + frontmatterTags, + bodyTags, + createdAt, + updatedAt: nowIso, + wikilinks, + relativeLinks, + } + if (aliases.length > 0) draft.aliases = aliases + return draft +} + +/** + * Shared Markdown import service: validates the batch and parses every note + * into a neutral draft. No mention tokens, claims, or stubs are minted here. + */ +export const parseMarkdownImport = (files: Map): MarkdownImportServiceResult => { + const limitError = checkVaultLimits(files) + if (limitError) return { success: false, error: limitError } + const nowIso = new Date().toISOString() + const warnings: string[] = [] + const drafts: MarkdownImportDraft[] = [] + for (const [path, content] of files) { + if (!isMarkdownPath(path)) continue + if (/^[A-Za-z]:[\\/]/.test(path) || /^[\\/]/.test(path)) { + warnings.push(`${path}: not a vault-relative path — file skipped`) + continue + } + const draft = parseDraftFile(path, content, nowIso, warnings) + if (draft) drafts.push(draft) + } + if (drafts.length === 0) { + return { success: false, error: `No importable notes found. ${warnings.join('; ')}`.trim() } + } + return { success: true, drafts, warnings } +} + +/** + * Parses a Markdown vault batch into entities, minting stub entities for + * unresolved `[[Wikilinks]]`. Deterministic: stubs and conflicts are + * reported in first-seen order (CLI-facing aggregate). + */ +export const parseMarkdownBundle = (files: Map): MarkdownImportResult => { + const service = parseMarkdownImport(files) + if (!service.success) return { success: false, error: service.error } + + const drafts = service.drafts + const byName = new Map() + for (const draft of drafts) { + const key = draft.name.toLowerCase() + byName.set(key, [...(byName.get(key) ?? []), draft.id]) + } + const conflicts: string[] = [] + for (const ids of byName.values()) { + if (ids.length > 1) conflicts.push(ids.join(', ')) + } + + const entities: CoreEntity[] = drafts.map((d) => ({ + id: d.id, + name: d.name, + type: d.type, + description: d.description, + content: d.content, + tags: d.tags, + ...(d.aliases ? { aliases: d.aliases } : {}), + })) + const stubNames: string[] = [] + const ids = new Set(drafts.map((d) => d.id)) + const stubs = new Map() + + const resolveName = (name: string): string | null => { + const matched = byName.get(name.toLowerCase()) ?? [] + if (matched.length === 1) return matched[0] ?? null + if (matched.length > 1) { + if (!conflicts.includes(name)) conflicts.push(name) + return matched[0] ?? null + } + const existing = stubs.get(name.toLowerCase()) + if (existing) return existing.id + const stubId = slug(name) + const unique = ids.has(stubId) ? `${stubId}-${stubs.size + 1}` : stubId + ids.add(unique) + stubs.set(name.toLowerCase(), { id: unique, name }) + stubNames.push(name) + return unique + } + + for (const draft of drafts) { + const links: Array<{ targetId: string; relation: string }> = [] + for (const link of draft.wikilinks) { + const targetId = resolveName(link.name) + if (targetId) links.push({ targetId, relation: 'related' }) + } + if (links.length > 0) { + const entity = entities.find((e) => e.id === draft.id) + if (entity) entity.links = links + } + } + for (const { id, name } of stubs.values()) { + entities.push({ + id, + name, + type: 'concept', + description: 'Stub entity minted from an unresolved [[Wikilink]].', + content: '', + tags: [], + }) + } + + return { success: true, entities, stubNames, conflicts, warnings: service.warnings } +} diff --git a/packages/dks-core/src/okf-export.test.ts b/packages/dks-core/src/okf-export.test.ts new file mode 100644 index 000000000..49ccef537 --- /dev/null +++ b/packages/dks-core/src/okf-export.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from 'vitest' +import { buildOkfBundle } from './okf-export.js' +import { parseBundleFiles } from './okf-parse.js' +import type { CoreExportClaim, CoreExportEntity } from './okf-export.js' + +const entities: CoreExportEntity[] = [ + { + id: 'concepts/alpha', + name: 'Alpha Project', + type: 'project', + description: 'First project', + content: 'Alpha body.', + tags: ['research', 'alpha'], + }, + { + id: 'concepts/beta', + name: 'Beta', + type: 'concept', + description: '', + content: 'Beta body.', + tags: [], + }, +] + +const claims: CoreExportClaim[] = [ + { + entityId: 'concepts/alpha', + statement: 'Alpha scales linearly', + source: 'https://example.com/alpha', + evidence: 'Alpha paper', + }, + { + entityId: 'concepts/beta', + statement: 'Beta is stable', + }, +] + +describe('buildOkfBundle', () => { + it('walks a bundle with index, log, and concept files (PWA-identical)', () => { + const bundle = buildOkfBundle(entities, claims, [{ source: 'concepts/alpha', target: 'concepts/beta' }], '0.2.0', new Date('2026-11-17T00:00:00Z')) + const paths = bundle.files.map((f) => f.path) + expect(paths).toEqual(['index.md', 'log.md', 'projects/alpha-project.md', 'concepts/beta.md']) + const alpha = bundle.files.find((f) => f.path === 'projects/alpha-project.md') + expect(alpha?.content).toContain('type: Project') + expect(alpha?.content).toContain('title: Alpha Project') + expect(alpha?.content).toContain('description: First project') + expect(alpha?.content).toContain('status: stable') + expect(alpha?.content).toContain('generated:') + expect(alpha?.content).toContain('do-knowledge-studio/0.2.0') + expect(alpha?.content).toContain('sources:') + expect(alpha?.content).toContain('- id: src-1') + expect(alpha?.content).toContain('- Alpha scales linearly[^src-1]') + expect(alpha?.content).toContain('[^src-1]: Alpha paper') + expect(alpha?.content).toContain('* [Beta](/concepts/beta.md)') + const index = bundle.files.find((f) => f.path === 'index.md') + expect(index?.content).toContain('okf_version: "0.2"') + expect(index?.content).toContain('# Knowledge Bundle') + expect(index?.content).toContain('# Projects') + expect(index?.content).toContain('* [Alpha Project](/projects/alpha-project.md) - First project') + expect(index?.content).toContain('# Concepts') + const log = bundle.files.find((f) => f.path === 'log.md') + expect(log?.content).toContain('## 2026-11-17') + }) + + it('round-trips through the parser', () => { + const bundle = buildOkfBundle(entities, claims, [{ source: 'concepts/alpha', target: 'concepts/beta' }]) + const files = new Map(bundle.files.map((f) => [f.path, f.content])) + const loaded = parseBundleFiles(files) + const alpha = loaded.concepts.find((c) => c.id === 'projects/alpha-project') + expect(alpha?.name).toBe('Alpha Project') + expect(alpha?.type).toBe('Project') + expect(alpha?.tags).toEqual(['research', 'alpha']) + expect(alpha?.claims).toEqual([ + { statement: 'Alpha scales linearly', verification: 'unverified', source: 'https://example.com/alpha', evidence: 'Alpha paper' }, + ]) + expect(alpha?.relatedIds).toEqual(['concepts/beta']) + expect(alpha?.content).toBe('Alpha body.') + }) + + it('disambiguates duplicate slugs', () => { + const dupes: CoreExportEntity[] = [ + { id: 'a', name: 'Hello World', type: 'concept', description: '', content: '', tags: [] }, + { id: 'b', name: 'Hello World', type: 'concept', description: '', content: '', tags: [] }, + ] + const bundle = buildOkfBundle(dupes, []) + const paths = bundle.files.map((f) => f.path).filter((p) => p.startsWith('concepts/')) + expect(paths).toEqual(['concepts/hello-world.md', 'concepts/hello-world-2.md']) + }) +}) diff --git a/packages/dks-core/src/okf-export.ts b/packages/dks-core/src/okf-export.ts new file mode 100644 index 000000000..0deaea6c0 --- /dev/null +++ b/packages/dks-core/src/okf-export.ts @@ -0,0 +1,251 @@ +/** + * OKF v0.2 bundle serialization — single-sourced from the PWA. + * + * This module is a framework-neutral port of `src/lib/okf/bundle.ts` (the + * PWA's OKF exporter) with the studio types replaced by structural inputs. + * The PWA file re-exports from here, so one implementation produces every + * OKF bundle: the studio export view and the `dks` CLI. Frontmatter is + * rendered with `yaml` exactly like the PWA. + */ + +import yaml from 'yaml' +import { slug } from './markdown.js' + +/** Minimal structural shape of an entity to export (PWA `Entity` satisfies it). */ +export interface CoreExportEntity { + id: string + name: string + type: string + description: string + content: string + tags: readonly string[] +} + +/** Minimal structural shape of a claim to export (PWA `Claim` satisfies it). */ +export interface CoreExportClaim { + entityId: string + statement: string + source?: string + evidence?: string + updatedAt?: string +} + +/** A typed graph edge exported as a related link (PWA `GraphEdge` satisfies it). */ +export interface CoreExportEdge { + source: string + target: string +} + +/** A bundle file: bundle-relative path plus content. */ +export interface OkfBundleFile { + path: string + content: string +} + +/** An OKF v0.2 bundle: index, log, and concept files. */ +export interface OkfBundle { + files: OkfBundleFile[] + okfVersion: '0.2' +} + +/** §4.1: type values are not centrally registered; pick descriptive strings. */ +const OKF_TYPE_MAP: Record = { + note: 'Note', + concept: 'Concept', + person: 'Person', + project: 'Project', +} + +/** §3.1: index.md / log.md are reserved and must not be used for concepts. */ +const RESERVED = new Set(['index', 'log']) + +/** Computes the bundle-relative concept file path for an entity. */ +const conceptPath = (e: CoreExportEntity): string => { + const typeName = OKF_TYPE_MAP[e.type] ?? 'Concept' + let name = slug(e.name) + if (RESERVED.has(name)) name = `${name}-concept` // never collide with reserved filenames + return `${typeName.toLowerCase()}s/${name}.md` +} + +/** Ensures a bundle-relative concept path is unique, appending a suffix. */ +const uniquePath = (base: string, used: Set): string => { + if (!used.has(base)) { + used.add(base) + return base + } + const stem = base.replace(/\.md$/, '') + let n = 2 + let candidate = `${stem}-${n}.md` + while (used.has(candidate)) { + n += 1 + candidate = `${stem}-${n}.md` + } + used.add(candidate) + return candidate +} + +/** §5.1 provenance: a claim source entry with a STABLE id for footnotes. */ +interface SourceEntry { + id: string + resource: string + title?: string + last_modified?: string +} + +/** Builds §5.1 provenance entries from claims that carry a source. */ +const buildSources = ( + claims: CoreExportClaim[], +): { sources: SourceEntry[]; sourceIdByResource: Map } => { + const sources: SourceEntry[] = [] + const sourceIdByResource = new Map() + for (const c of claims) { + if (!c.source) continue + let id = sourceIdByResource.get(c.source) + if (!id) { + id = `src-${sources.length + 1}` + sourceIdByResource.set(c.source, id) + sources.push({ + id, + resource: c.source, + ...(c.evidence !== undefined ? { title: c.evidence } : {}), + ...(c.updatedAt !== undefined ? { last_modified: c.updatedAt.slice(0, 10) } : {}), + }) + } + } + return { sources, sourceIdByResource } +} + +/** Builds the concept body: content, a "# Claims" list, and footnotes. */ +const buildConceptBody = ( + e: CoreExportEntity, + claims: CoreExportClaim[], + sourceIdByResource: Map, + sources: SourceEntry[], +): string => { + const lines = [ + e.content ?? '', + claims.length ? '\n# Claims\n' : '', + ...claims.map((c) => { + const id = c.source ? sourceIdByResource.get(c.source) : undefined + return `- ${c.statement}${id ? `[^${id}]` : ''}` + }), + claims.length ? '' : '', + ...sources.map((s) => `[^${s.id}]: ${s.title ?? s.resource}`), + ] + return lines.filter((line) => line !== '').join('\n') +} + +/** Renders a single concept file (frontmatter + body) per §4.1/§5. */ +const buildConceptDoc = (e: CoreExportEntity, claims: CoreExportClaim[], studioVersion: string, now: Date): string => { + const { sources, sourceIdByResource } = buildSources(claims) + const frontmatter: Record = { + type: OKF_TYPE_MAP[e.type] ?? 'Concept', + title: e.name, + description: e.description, + tags: e.tags, + status: 'stable', + generated: { by: `do-knowledge-studio/${studioVersion}`, at: now.toISOString() }, + } + if (sources.length) { + frontmatter.sources = sources + } + const body = buildConceptBody(e, claims, sourceIdByResource, sources) + return `---\n${yaml.stringify(frontmatter)}---\n\n${body}\n` +} + +/** Renders one index section (e.g. "# Concepts") from its bundle file entries. */ +const buildIndexSection = ( + dir: string, + items: { title: string; href: string; desc: string }[], +): string => + [ + `# ${dir.charAt(0).toUpperCase() + dir.slice(1)}`, + '', + ...items.map((i) => `* [${i.title}](${i.href}) - ${i.desc}`), + ].join('\n') + +/** Builds the root index.md: §8 allows okf_version frontmatter on the index only. */ +const buildIndex = (files: OkfBundleFile[], entityByPath: Map): string => { + const byDir = new Map() + for (const f of files) { + if (f.path === 'index.md' || f.path === 'log.md') continue + const parts = f.path.split('/') + const dir = parts[0] ?? '' + const entity = entityByPath.get(f.path) + const entries = byDir.get(dir) ?? [] + entries.push({ + title: entity?.name ?? f.path, + href: `/${f.path}`, + desc: entity?.description ?? '', + }) + byDir.set(dir, entries) + } + const sections = [...byDir.entries()] + .map(([dir, items]) => buildIndexSection(dir, items)) + .join('\n\n') + return `---\nokf_version: "0.2"\n---\n\n# Knowledge Bundle\n\n${sections}\n` +} + +/** Builds log.md: §9 date headings MUST be ISO YYYY-MM-DD, newest first. */ +const buildLog = (now: Date): string => { + const day = now.toISOString().slice(0, 10) + return `# Directory Update Log\n\n## ${day}\n* **Export**: Bundle generated by do-knowledge-studio.\n` +} + +/** Rewrites edges as bundle-relative markdown links under "# Related". */ +const appendRelatedLinks = ( + conceptFiles: OkfBundleFile[], + edges: CoreExportEdge[], + entityById: Map, + pathByEntityId: Map, +): void => { + for (const edge of edges) { + const from = conceptFiles.find((f) => f.path === pathByEntityId.get(edge.source)?.slice(1)) + const toPath = pathByEntityId.get(edge.target) + if (from && toPath && !from.content.includes(`](${toPath})`)) { + from.content = from.content.replace( + /\n?$/, + `\n\n# Related\n\n* [${entityById.get(edge.target)?.name ?? toPath}](${toPath})\n`, + ) + } + } +} + +/** + * Builds an OKF v0.2 bundle from core entities and claims. + * @param entities - Entities to export as concept files. + * @param claims - Claims attributed to entities. + * @param edges - Graph edges rendered as related links. + * @param studioVersion - Producer version recorded in generated metadata. + * @param now - Timestamp for generated/log metadata. + * @returns The assembled OKF bundle. + */ +export const buildOkfBundle = ( + entities: CoreExportEntity[], + claims: CoreExportClaim[], + edges: CoreExportEdge[] = [], + studioVersion = '0.2.0', + now: Date = new Date(), +): OkfBundle => { + const claimsByEntity = new Map() + for (const c of claims) { + claimsByEntity.set(c.entityId, [...(claimsByEntity.get(c.entityId) ?? []), c]) + } + + const usedPaths = new Set() + const conceptFiles: OkfBundleFile[] = entities.map((e) => ({ + path: uniquePath(conceptPath(e), usedPaths), + content: buildConceptDoc(e, claimsByEntity.get(e.id) ?? [], studioVersion, now), + })) + + const pathByEntityId = new Map( + entities.map((e, i) => [e.id, `/${conceptFiles[i]?.path ?? ''}`]), + ) + const entityByPath = new Map(entities.map((e, i) => [conceptFiles[i]?.path ?? '', e])) + const entityById = new Map(entities.map((e) => [e.id, e])) + appendRelatedLinks(conceptFiles, edges, entityById, pathByEntityId) + + const files: OkfBundleFile[] = [{ path: 'log.md', content: buildLog(now) }, ...conceptFiles] + files.unshift({ path: 'index.md', content: buildIndex(conceptFiles, entityByPath) }) + return { files, okfVersion: '0.2' } +} diff --git a/packages/dks-core/src/okf-parse.test.ts b/packages/dks-core/src/okf-parse.test.ts new file mode 100644 index 000000000..a623b2743 --- /dev/null +++ b/packages/dks-core/src/okf-parse.test.ts @@ -0,0 +1,156 @@ +import { describe, expect, it } from 'vitest' +import { deriveTrustTier, parseBundleFiles, parseConcept, parseIndexVersion } from './okf-parse.js' + +/** Minimal valid index file. */ +const INDEX = `---\nokf_version: '0.2'\n---\n\n# Index\n` + +/** Concept reviewed by a human, with claims, sources, aliases, and a related link. */ +const ALPHA = `--- +type: Project +title: Alpha Project +description: First project +tags: + - research + - alpha +aliases: + - AP +sources: + - id: src-1 + resource: https://example.com/alpha + title: Alpha paper + author: human:ada +verified: + by: human:ada + at: '2026-01-02T00:00:00.000Z' +unknown_future_key: tolerated +--- + +Body text about alpha. + +# Claims + +- Alpha scales linearly[^src-1] +- Alpha is cheap + +[^src-1]: Alpha paper + +# Related + +* [Beta](/concepts/beta) +* [Ghost](/concepts/ghost) +` + +/** Machine-confirmed concept with no claims. */ +const BETA = `--- +type: Concept +title: Beta +verified: + by: process:import +--- + +Beta body. +` + +describe('deriveTrustTier', () => { + it('treats missing verification as unverified', () => { + expect(deriveTrustTier(undefined)).toBe('unverified') + expect(deriveTrustTier(null)).toBe('unverified') + }) + + it('treats a human verifier as human-reviewed', () => { + expect(deriveTrustTier({ by: 'human:ada' })).toBe('human-reviewed') + expect(deriveTrustTier([{ by: 'human:ada' }, { by: 'process:import' }])).toBe('human-reviewed') + }) + + it('treats machine actors as machine-confirmed', () => { + expect(deriveTrustTier({ by: 'process:import' })).toBe('machine-confirmed') + expect(deriveTrustTier([{ by: 'producer/1.0' }])).toBe('machine-confirmed') + }) + + it('ignores non-object verdict entries', () => { + expect(deriveTrustTier(['human:ada'])).toBe('unverified') + }) +}) + +describe('parseConcept', () => { + it('parses a full concept with claims, sources, aliases, and related ids', () => { + const c = parseConcept('concepts/alpha', ALPHA) + expect(c).not.toBeNull() + if (!c) return + expect(c.id).toBe('concepts/alpha') + expect(c.name).toBe('Alpha Project') + expect(c.type).toBe('Project') + expect(c.description).toBe('First project') + expect(c.tags).toEqual(['research', 'alpha']) + expect(c.aliases).toEqual(['AP']) + expect(c.trustTier).toBe('human-reviewed') + expect(c.sources).toEqual([ + { id: 'src-1', resource: 'https://example.com/alpha', title: 'Alpha paper', author: 'human:ada' }, + ]) + expect(c.claims).toEqual([ + { statement: 'Alpha scales linearly', verification: 'verified', source: 'https://example.com/alpha', evidence: 'Alpha paper' }, + { statement: 'Alpha is cheap', verification: 'verified' }, + ]) + expect(c.relatedIds).toEqual(['concepts/beta', 'concepts/ghost']) + expect(c.content).toBe('Body text about alpha.') + }) + + it('returns null without frontmatter', () => { + expect(parseConcept('notes/plain', 'Just body.\n')).toBeNull() + }) + + it('returns null on invalid frontmatter', () => { + expect(parseConcept('notes/bad', '---\ntitle: [unterminated\n---\nbody\n')).toBeNull() + }) + + it('maps a missing title to the file name', () => { + const c = parseConcept('concepts/no-title', '---\ntype: Note\n---\nbody\n') + expect(c?.name).toBe('no-title') + expect(c?.type).toBe('Note') + }) +}) + +describe('parseBundleFiles', () => { + const files = new Map([ + ['index.md', INDEX], + ['log.md', '# Log\n'], + ['concepts/alpha', ALPHA], + ['concepts/beta', BETA], + ['notes/plain', 'no frontmatter\n'], + ]) + + it('parses concepts, ignores reserved files, and warns on skipped files', () => { + const loaded = parseBundleFiles(files) + expect(loaded.concepts.map((c) => c.id)).toEqual(['concepts/alpha', 'concepts/beta']) + expect(loaded.concepts[1]?.trustTier).toBe('machine-confirmed') + expect(loaded.warnings).toEqual(['notes/plain: no readable frontmatter and was skipped.']) + }) + + it('throws without an index declaring okf_version', () => { + expect(() => parseBundleFiles(new Map([['concepts/a', BETA]]))).toThrow(/index\.md with okf_version/) + }) + + it('throws on an unsupported okf_version', () => { + const bad = new Map([ + ['index.md', "---\nokf_version: '0.3'\n---\n"], + ['concepts/a', BETA], + ]) + expect(() => parseBundleFiles(bad)).toThrow(/Unsupported okf_version/) + }) + + it('throws when the bundle holds no parseable concepts', () => { + const empty = new Map([ + ['index.md', INDEX], + ['notes/plain', 'no frontmatter\n'], + ]) + expect(() => parseBundleFiles(empty)).toThrow(/no parseable concepts/) + }) +}) + +describe('parseIndexVersion', () => { + it('reads quoted and unquoted versions', () => { + expect(parseIndexVersion("---\nokf_version: '0.2'\n---\n")).toBe('0.2') + expect(parseIndexVersion('---\nokf_version: 0.2.1\n---\n')).toBe('0.2.1') + expect(parseIndexVersion('---\ntitle: x\n---\n')).toBeNull() + }) +}) diff --git a/packages/dks-core/src/okf-parse.ts b/packages/dks-core/src/okf-parse.ts new file mode 100644 index 000000000..c70ad3da0 --- /dev/null +++ b/packages/dks-core/src/okf-parse.ts @@ -0,0 +1,359 @@ +/** + * OKF v0.2 bundle parsing (mirrors the studio's `src/lib/okf/import.ts` + * semantics): reserved `index.md` / `log.md` handling, `# Claims` footnote + * joins, trust-tier derivation, and `# Related` link extraction. This is + * the single implementation shared by the `dks` CLI and the MCP adapter. + */ + +import { parseFrontmatter, splitFrontmatter } from './frontmatter.js' +import type { + BundleClaim, + BundleConcept, + BundleSource, + LoadedBundle, + TrustTier, +} from './types.js' + +/** + * Derives the trust tier from frontmatter `verified` (mirrors trustTier). + * @param verified - Raw verified value (single entry or list). + * @returns The tier; anything without a human verifier stays below reviewed. + */ +export const deriveTrustTier = (verified: unknown): TrustTier => { + if (!verified) return 'unverified' + const raw: unknown[] = Array.isArray(verified) ? verified : [verified] + // Non-object entries are schema-invalid; they verify nothing and must not + // crash the `by` access or masquerade as machine confirmation. + const events = raw.filter((v): v is { by?: unknown } => typeof v === 'object' && v !== null) + if (events.length === 0) return 'unverified' + if (events.some((v) => typeof v.by === 'string' && v.by.startsWith('human:'))) { + return 'human-reviewed' + } + return 'machine-confirmed' +} + +/** Reads a string field, falling back to `fallback` for any other shape. */ +const asString = (value: unknown, fallback: string): string => + typeof value === 'string' ? value : fallback + +/** Reads a string array, dropping non-string entries. */ +const asStringArray = (value: unknown): string[] => + Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : [] + +/** Reads source entries, dropping entries without a resource. */ +const asSources = (value: unknown): BundleSource[] => { + if (!Array.isArray(value)) return [] + const sources: BundleSource[] = [] + for (const s of value) { + if (typeof s !== 'object' || s === null) continue + const record = s as Record + if (typeof record.resource !== 'string' || record.resource.length === 0) continue + const source: BundleSource = { resource: record.resource } + if (typeof record.id === 'string') source.id = record.id + if (typeof record.title === 'string') source.title = record.title + if (typeof record.author === 'string') source.author = record.author + sources.push(source) + } + return sources +} + +/** + * Parses one `- statement[^id]` claim line. Phrased as a slice + anchored + * footnote match rather than one backtracking pattern, so a long line of + * `-`/`[^` characters cannot drive exponential matching. + * @param line - A single body line. + * @returns The statement and footnote label, or null when not a claim line. + */ +const parseClaimLine = (line: string): { text: string; footnoteId?: string } | null => { + if (!line.startsWith('- ')) return null + let text = line.slice(2).trim() + let footnoteId: string | undefined + const tail = /\[\^([\w-]+)\]$/.exec(text) + if (tail) { + const [, label = ''] = tail + footnoteId = label + text = text.slice(0, tail.index).trim() + } + return footnoteId ? { text, footnoteId } : { text } +} + +/** A parsed claim line: statement plus optional footnote label. */ +export interface ClaimLine { + statement: string + footnoteId?: string +} + +/** + * Extracts `- statement[^id]` claim lines from a concept body. This is the + * shared rule for the PWA importer and the CLI/MCP bundle reader. + * @param body - Concept markdown body. + * @returns The claim lines in body order. + */ +export const extractClaimLines = (body: string): ClaimLine[] => { + const claims: ClaimLine[] = [] + for (const line of body.split('\n')) { + const parsed = parseClaimLine(line) + if (!parsed) continue + const text = parsed.text + if (text.startsWith('[^') || text.includes('Related') || text.includes('# Claims')) { + continue + } + claims.push(parsed.footnoteId ? { statement: text, footnoteId: parsed.footnoteId } : { statement: text }) + } + return claims +} + +/** + * Extracts claims from a concept body (mirrors `parseClaims` in app code). + * @param body - Concept markdown body. + * @param sources - Frontmatter sources for the footnote join. + * @param verified - Whether the concept is human-reviewed. + * @returns The recovered claims. + */ +const parseClaims = ( + body: string, + sources: BundleSource[], + verified: boolean, +): BundleClaim[] => { + const sourceById = new Map() + for (const s of sources) { + if (s.id) sourceById.set(s.id, s) + } + const claims: BundleClaim[] = [] + for (const line of extractClaimLines(body)) { + const source = line.footnoteId ? sourceById.get(line.footnoteId) : undefined + const claim: BundleClaim = { + statement: line.statement, + verification: verified ? 'verified' : 'unverified', + } + if (source?.resource) claim.source = source.resource + if (source?.title) claim.evidence = source.title + claims.push(claim) + } + return claims +} + +/** + * Extracts `# Related` markdown links as bundle-relative target ids. + * Exported form is `* [Name](/path/to.md)` where the path is slash-rooted. + * @param body - Concept markdown body. + * @returns Target ids (path minus leading slash and `.md`). + */ +const parseRelatedIds = (body: string): string[] => { + const section = /# Related\n([\s\S]*?)(?:\n# |$)/.exec(body) + const [, block = ''] = section ?? [] + const ids: string[] = [] + for (const m of block.matchAll(/\[[^\]]*\]\(([^)\s]+)\)/g)) { + const [, linked = ''] = m + const target = linked.replace(/^\/+/, '').replace(/\.md$/, '') + if (target && !ids.includes(target)) ids.push(target) + } + return ids +} + +/** + * Strips the `# Claims` and `# Related` sections from display content. + * @param body - Concept markdown body. + * @returns The body without machine sections. + */ +const stripMachineSections = (body: string): string => + body + // `(?:^|\n)` keeps a section heading that opens the body strippable too. + .replace(/(?:^|\n)# Claims\n[\s\S]*?(?=\n# |$)/, '') + .replace(/(?:^|\n)# Related\n[\s\S]*?(?=\n# |$)/, '') + .trim() + +/** + * Parses one concept file into a BundleConcept. + * @param path - Bundle-relative path (id is the path minus `.md`). + * @param content - Raw file content. + * @returns The concept, or null when the file is not a valid concept. + */ +export const parseConcept = (path: string, content: string): BundleConcept | null => { + const split = splitFrontmatter(content) + if (!split.frontmatter) return null + const parsed = parseFrontmatter(split.frontmatter) + if (!parsed.ok) return null + const fm = parsed.data + const fileName = path.split('/').pop() ?? path + const sources = asSources(fm.sources) + const tier = deriveTrustTier(fm.verified) + const name = asString(fm.title, fileName.replace(/\.md$/, '')) + const concept: BundleConcept = { + id: path.replace(/\.md$/, ''), + name, + type: asString(fm.type, 'Concept'), + description: asString(fm.description, ''), + content: stripMachineSections(split.body), + tags: asStringArray(fm.tags), + trustTier: tier, + sources, + claims: parseClaims(split.body, sources, tier === 'human-reviewed'), + relatedIds: parseRelatedIds(split.body), + } + const aliases = asStringArray(fm.aliases) + if (aliases.length > 0) concept.aliases = aliases + return concept +} + +/** + * Rejects paths that escape the bundle namespace (mirrors the app importer). + * @param path - Candidate bundle-relative path. + * @returns True when the path is safe to consume. + */ +export const isSafePath = (path: string): boolean => { + if (!path || path.includes('\0')) return false + if (/^[A-Za-z]:[\\/]/.test(path) || /^[\\/]/.test(path)) return false + if (path.split('/').includes('..')) return false + return true +} + +/** Declared `okf_version` from an index file, or null when absent. */ +export const parseIndexVersion = (content: string): string | null => { + const m = /okf_version:\s*['"]?([\w.]+)['"]?/.exec(content) + return m?.[1] ?? null +} +/** Declared `okf_version` from an index file's frontmatter (shared rule). */ +export const parseIndexFrontmatterVersion = (content: string): string | null => { + const split = splitFrontmatter(content) + if (!split.frontmatter) return null + const parsed = parseFrontmatter(split.frontmatter) + if (!parsed.ok) return null + const version = parsed.data.okf_version + return typeof version === 'string' ? version : null +} +/** Neutral entity produced by the shared OKF import service. */ +export interface ImportedEntityLike { + id: string + name: string + type: string + description: string + content: string + tags: string[] + createdAt: string + updatedAt: string +} + +/** Neutral claim produced by the shared OKF import service. */ +export interface ImportedClaimLike { + entityId: string + statement: string + verification: 'verified' | 'unverified' + confidence: number + source?: string + evidence?: string + createdAt: string + updatedAt: string + version: number +} + +/** Result of the shared OKF import service. */ +export interface OkfImportServiceResult { + entities: ImportedEntityLike[] + claims: ImportedClaimLike[] + errors: string[] +} + +/** Maps OKF type strings back to studio entity types (unknown types → 'concept'). */ +const OKF_TYPE_REVERSE: Record = { + Note: 'note', + Concept: 'concept', + Person: 'person', + Project: 'project', +} + +/** + * Shared OKF import service: validates a bundle and parses every concept + * into neutral entities/claims. Reserved-file handling, version checks, + * path guards, and per-file validation all live here; the PWA adapter maps + * the neutral output onto studio records (UUIDs, presentation). + */ +export const parseOkfImportBundle = ( + files: Map, + nowIso = new Date().toISOString(), +): OkfImportServiceResult => { + const result: OkfImportServiceResult = { entities: [], claims: [], errors: [] } + for (const [path, content] of files) { + if (/^[A-Za-z]:[\\/]/.test(path) || /^[\\/]/.test(path)) { + result.errors.push(`${path}: not a bundle-relative path (drive-rooted, absolute, or root-backslash names are invalid per §2)`) + continue + } + if (/(^|\/)index\.md$/.test(path)) { + const declared = parseIndexFrontmatterVersion(content) + if (!declared) { + result.errors.push('index.md: missing okf_version — not a valid OKF bundle') + } else if (declared !== '0.2' && !declared.startsWith('0.2.')) { + result.errors.push(`index.md: unsupported okf_version "${declared}" (expected 0.2.x)`) + } + continue + } + if (/(^|\/)log\.md$/.test(path)) continue + const concept = parseConcept(path, content) + if (!concept) { + result.errors.push(`${path}: missing or unparseable frontmatter`) + continue + } + const split = splitFrontmatter(content) + const rawBody = split.frontmatter !== null ? split.body : content + const entity: ImportedEntityLike = { + id: concept.id, + name: concept.name, + type: OKF_TYPE_REVERSE[concept.type] ?? 'concept', + description: concept.description, + content: rawBody.trim(), + tags: concept.tags, + createdAt: nowIso, + updatedAt: nowIso, + } + result.entities.push(entity) + for (const claim of concept.claims) { + const imported: ImportedClaimLike = { + entityId: entity.id, + statement: claim.statement, + verification: claim.verification, + confidence: 1.0, + createdAt: nowIso, + updatedAt: nowIso, + version: 1, + } + if (claim.source) imported.source = claim.source + if (claim.evidence) imported.evidence = claim.evidence + result.claims.push(imported) + } + } + return result +} + +/** + * Parses a bundle from a normalized file map (bundle-relative path → + * content). Fail-closed: an incompatible or missing index throws before any + * concept is served. + * @param files - Bundle-relative path → UTF-8 content. + * @returns The loaded concepts plus non-fatal warnings. + */ +export const parseBundleFiles = (files: Map): LoadedBundle => { + const indexEntry = [...files.keys()].find((p) => /(^|\/)index\.md$/.test(p)) + const declared = indexEntry ? parseIndexVersion(files.get(indexEntry) ?? '') : null + if (!declared) { + throw new Error('Not a valid OKF bundle: index.md with okf_version is required.') + } + if (declared !== '0.2' && !declared.startsWith('0.2.')) { + throw new Error(`Unsupported okf_version "${declared}" (expected 0.2.x).`) + } + + const concepts: BundleConcept[] = [] + const warnings: string[] = [] + for (const [path, content] of files) { + if (/(^|\/)index\.md$/.test(path) || /(^|\/)log\.md$/.test(path)) continue + const concept = parseConcept(path, content) + if (!concept) { + warnings.push(`${path}: no readable frontmatter and was skipped.`) + continue + } + concepts.push(concept) + } + if (concepts.length === 0) { + throw new Error('Bundle holds no parseable concepts; refusing to serve an empty library.') + } + return { concepts, warnings } +} diff --git a/packages/dks-core/src/pwa-retrieval.test.ts b/packages/dks-core/src/pwa-retrieval.test.ts new file mode 100644 index 000000000..fbfd56431 --- /dev/null +++ b/packages/dks-core/src/pwa-retrieval.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from 'vitest' +import { + MAX_CACHE_ENTRIES, + getEntityMap, + resetSearchCache, + search, + type PwaClaimLike, + type PwaEntityLike, +} from './pwa-retrieval.js' + +const entities: PwaEntityLike[] = [ + { id: 'e1', name: 'Alpha', type: 'concept', description: 'First project', content: 'alpha body about graphs', tags: ['research'] }, + { id: 'e2', name: 'Beta', type: 'concept', description: '', content: 'plain beta text', tags: [] }, + { id: 'e3', name: 'Gamma', type: 'concept', description: '', content: 'unrelated gamma content', tags: [] }, +] + +const claims: PwaClaimLike[] = [ + { id: 'c1', entityId: 'e1', statement: 'Alpha scales linearly', evidence: 'Paper', source: 'https://example.com' }, +] + +describe('pwa-retrieval search', () => { + it('ranks name matches above body matches deterministically', () => { + const results = search(entities, claims, 'alpha', 10) + expect(results.length).toBeGreaterThan(0) + expect(results[0]?.id).toBe('e1') + }) + + it('searches claim statements', () => { + const results = search(entities, claims, 'scales', 10) + expect(results.some((r) => r.type === 'claim' && r.entityId === 'e1')).toBe(true) + }) + + it('is stop-word aware', () => { + expect(search(entities, claims, 'the', 10)).toHaveLength(0) + }) + + it('returns snippets bounded to 140 chars', () => { + const big: PwaEntityLike[] = [ + { id: 'big', name: 'X'.repeat(200), type: 'note', description: '', content: 'y'.repeat(400), tags: [] }, + ] + const results = search(big, [], 'x', 1) + expect(results[0]?.snippet.length).toBeLessThanOrEqual(141) + }) + + it('supports filters narrowing candidates before ranking', () => { + const results = search(entities, claims, 'alpha', 10, (doc) => doc.type === 'claim') + expect(results.every((r) => r.type === 'claim')).toBe(true) + }) + + it('respects the limit', () => { + const results = search(entities, claims, 'a', 1) + expect(results.length).toBeLessThanOrEqual(1) + }) + + it('clears caches via resetSearchCache', () => { + resetSearchCache() + const before = getEntityMap(entities, claims) + expect(before.has('e1')).toBe(true) + resetSearchCache() + expect(MAX_CACHE_ENTRIES).toBeGreaterThan(0) + }) +}) diff --git a/packages/dks-core/src/pwa-retrieval.ts b/packages/dks-core/src/pwa-retrieval.ts new file mode 100644 index 000000000..d3a74a425 --- /dev/null +++ b/packages/dks-core/src/pwa-retrieval.ts @@ -0,0 +1,384 @@ +/** + * Lexical BM25 retrieval — the PWA's search engine, single-sourced here. + * + * This module is a framework-neutral port of `src/lib/search/retrieval.ts` + * (K1=1.5, B=0.75, Intl.Segmenter tokenization with ASCII fallback, English + * stop words, per-entry token memoization, and reference-based caching). The + * PWA file re-exports from here, and the `dks` CLI / MCP adapter call the + * same functions, so one implementation serves every consumer. The only + * changes from the PWA source are structural input interfaces (no `@/` + * alias imports) and a no-op logger (logging side effects are not part of + * the retrieval contract). + */ + +/** Minimal structural shape of an entity document (PWA `Entity` satisfies it). */ +export interface PwaEntityLike { + id: string + name: string + type: string + description: string + content: string + tags: readonly string[] +} + +/** Minimal structural shape of a claim document (PWA `Claim` satisfies it). */ +export interface PwaClaimLike { + id: string + entityId: string + statement: string + evidence?: string + source?: string +} + +/** BM25 tuning constant for term frequency saturation. */ +const K1 = 1.5 +/** BM25 tuning constant for document length normalization. */ +const B = 0.75 +/** Common English stop words excluded from indexing. */ +const STOP_WORDS = new Set([ + 'the', 'a', 'an', 'and', 'or', 'but', 'if', 'then', 'else', 'when', + 'while', 'of', 'at', 'by', 'for', 'with', 'about', 'against', 'between', + 'into', 'through', 'during', 'before', 'after', 'above', 'below', 'to', + 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', + 'further', 'then', 'once', 'here', 'there', 'all', 'any', 'both', 'each', + 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not', 'only', + 'own', 'same', 'so', 'than', 'too', 'very', 's', 't', 'can', 'will', + 'just', 'don', 'should', 'now', 'is', 'are', 'was', 'were', 'be', 'been', + 'being', 'has', 'have', 'had', 'having', 'does', 'did', 'doing', 'would', + 'could', 'ought', 'i', 'you', 'he', 'she', 'it', 'we', 'they', 'them', + 'his', 'her', 'its', 'our', 'their', 'my', 'your', 'me', 'him', 'us', +]) + +/** A single search result with relevance score and snippet. */ +export interface SearchResult { + id: string + type: 'entity' | 'claim' + name: string + snippet: string + score: number + entityId?: string + entityName?: string +} + +/** Minimal document metadata a search filter predicate can inspect. */ +export interface FilterableDoc { + id: string + type: 'entity' | 'claim' + entityId?: string + entityName?: string + entityType?: string +} + +/** Predicate that keeps only the documents matching the caller's criteria. */ +export type SearchFilter = (doc: FilterableDoc) => boolean + +interface IndexEntry extends FilterableDoc { + tokenCount: number + tfMap: Map + fullText: string +} + +/** No-op logger (PWA uses a structured logger; retrieval itself logs nothing). */ +const log: { warn(...args: unknown[]): void } = { warn() {} } + +// Lazy, runtime-locale word segmenter (Intl.Segmenter, granularity 'word'). +let segmenter: Intl.Segmenter | null = null +let segmenterUnavailable = false +let segmenterFallbackLogged = false + +/** Lazy per-runtime word segmenter with a defensive ASCII fallback. */ +const getSegmenter = (): Intl.Segmenter | null => { + if (segmenterUnavailable) return null + try { + if (segmenter === null) { + const segmenterConstructor = Intl.Segmenter + if (typeof segmenterConstructor !== 'function') return null + segmenter = new segmenterConstructor(undefined, { granularity: 'word' }) + } + return segmenter + } catch { + segmenterUnavailable = true + return null + } +} + +/** ASCII-only fallback used when Intl.Segmenter is unavailable. */ +const tokenizeAsciiFallback = (text: string): string[] => + text + .toLowerCase() + .replace(/[^a-z0-9\s]/g, ' ') + .split(/\s+/) + .filter((w) => !STOP_WORDS.has(w)) + +const tokenize = (text: string): string[] => { + const tokens: string[] = [] + const seg = getSegmenter() + if (seg === null) { + if (!segmenterFallbackLogged) { + segmenterFallbackLogged = true + log.warn('Intl.Segmenter unavailable — falling back to ASCII tokenizer') + } + return tokenizeAsciiFallback(text) + } + try { + for (const part of seg.segment(text)) { + if (!part.isWordLike) continue + const token = part.segment.normalize('NFC').toLowerCase() + if (!STOP_WORDS.has(token)) { + tokens.push(token) + } + } + } catch { + segmenter = null + segmenterUnavailable = true + if (!segmenterFallbackLogged) { + segmenterFallbackLogged = true + log.warn('Intl.Segmenter failed — falling back to ASCII tokenizer') + } + return tokenizeAsciiFallback(text) + } + return tokens +} + +function buildTfMap(tokens: string[]): Map { + const tfMap = new Map() + for (const t of tokens) { + tfMap.set(t, (tfMap.get(t) ?? 0) + 1) + } + return tfMap +} + +/** The token-dependent half of a corpus entry, reusable across rebuilds. */ +interface TokenizedEntry { + tokenCount: number + tfMap: Map + fullText: string +} + +const tokenizedById = new Map() + +const tokenizeCached = (id: string, text: string): TokenizedEntry => { + const cached = tokenizedById.get(id) + if (cached !== undefined && cached.fullText === text) { + return cached + } + const tokens = tokenize(text) + const next: TokenizedEntry = { + tokenCount: tokens.length, + tfMap: buildTfMap(tokens), + fullText: text, + } + tokenizedById.set(id, next) + return next +} + +/** Drop memoized tokenizations whose id is no longer in the corpus. */ +const pruneTokenCache = (liveIds: Set): void => { + for (const id of tokenizedById.keys()) { + if (!liveIds.has(id)) tokenizedById.delete(id) + } +} + +function buildIndex( + entities: PwaEntityLike[], + claims: PwaClaimLike[], + entityMap: Map, +): IndexEntry[] { + const entries: IndexEntry[] = [] + const liveIds = new Set() + + for (const e of entities) { + const text = `${e.name} ${e.description} ${e.content} ${e.tags.join(' ')}` + liveIds.add(e.id) + entries.push({ + id: e.id, + type: 'entity', + entityType: e.type, + ...tokenizeCached(e.id, text), + }) + } + + for (const c of claims) { + const entity = entityMap.get(c.entityId) + const text = `${c.statement} ${c.evidence ?? ''} ${c.source ?? ''}` + liveIds.add(c.id) + entries.push({ + id: c.id, + type: 'claim', + entityId: c.entityId, + ...(entity?.name !== undefined ? { entityName: entity.name } : {}), + ...(entity?.type !== undefined ? { entityType: entity.type } : {}), + ...tokenizeCached(c.id, text), + }) + } + + pruneTokenCache(liveIds) + return entries +} + +function computeIDF(entries: IndexEntry[], queryTokens: string[]): Map { + const N = entries.length + const idf = new Map() + for (const qt of queryTokens) { + let df = 0 + for (const e of entries) { + for (const token of e.tfMap.keys()) { + if (token === qt || token.startsWith(qt)) { + df++ + break + } + } + } + idf.set(qt, Math.log((N - df + 0.5) / (df + 0.5) + 1)) + } + return idf +} + +function bm25Score( + entry: IndexEntry, + queryTokens: string[], + idf: Map, + avgDl: number, +): number { + let score = 0 + const dl = entry.tokenCount + const tfMap = entry.tfMap + const bDenom = K1 * (1 - B + B * (dl / avgDl)) + for (const qt of queryTokens) { + const idfVal = idf.get(qt) ?? 0 + if (idfVal === 0) continue + let termFreq = 0 + for (const [token, freq] of tfMap) { + if (token === qt || token.startsWith(qt)) termFreq += freq + } + if (termFreq === 0) continue + const numerator = termFreq * (K1 + 1) + const denominator = termFreq + bDenom + score += idfVal * (numerator / denominator) + } + return score +} + +function getSnippet(entry: IndexEntry, maxLength: number = 140): string { + const text = entry.fullText.trim() + if (text.length <= maxLength) return text + return `${text.slice(0, maxLength)}…` +} + +let lastEntities: PwaEntityLike[] | null = null +let lastClaims: PwaClaimLike[] | null = null +let cachedEntityMap = new Map() +let cachedEntries: IndexEntry[] = [] +let cachedAvgDl = 0 + +/** Combined entity + claim entries above which the reference cache is bypassed. */ +export const MAX_CACHE_ENTRIES = 20_000 + +/** Clears the module-level reference cache so the next search rebuilds the index. */ +export const resetSearchCache = (): void => { + lastEntities = null + lastClaims = null + cachedEntityMap = new Map() + cachedEntries = [] + cachedAvgDl = 0 + tokenizedById.clear() +} + +interface SearchIndex { + entityMap: Map + entries: IndexEntry[] + avgDl: number +} + +const buildEntityMap = (entities: PwaEntityLike[]): Map => { + const entityMap = new Map() + for (const e of entities) { + entityMap.set(e.id, e) + } + return entityMap +} + +/** Returns the cached index when inputs are referentially unchanged, otherwise rebuilds it. */ +const getIndex = (entities: PwaEntityLike[], claims: PwaClaimLike[]): SearchIndex => { + if (entities === lastEntities && claims === lastClaims) { + return { + entityMap: cachedEntityMap, + entries: cachedEntries, + avgDl: cachedAvgDl, + } + } + + const entityMap = buildEntityMap(entities) + const entries = buildIndex(entities, claims, entityMap) + const totalLength = entries.reduce((sum, e) => sum + e.tokenCount, 0) + const avgDl = entries.length > 0 ? totalLength / entries.length : 0 + + if (entries.length <= MAX_CACHE_ENTRIES) { + lastEntities = entities + lastClaims = claims + cachedEntityMap = entityMap + cachedEntries = entries + cachedAvgDl = avgDl + } else { + resetSearchCache() + } + + return { entityMap, entries, avgDl } +} + +/** + * Get entities by id from the retrieval index. The returned view is read-only + * and reuses the cached entity map for unchanged corpus references. + */ +export const getEntityMap = (entities: PwaEntityLike[], claims: PwaClaimLike[]): ReadonlyMap => + getIndex(entities, claims).entityMap + +/** Mean document length over the entries being ranked. */ +const averageTokenCount = (entries: IndexEntry[]): number => { + if (entries.length === 0) return 0 + return entries.reduce((sum, entry) => sum + entry.tokenCount, 0) / entries.length +} + +/** + * Run a BM25 full-text search over entities and claims. Each query token + * matches document tokens that equal it or begin with it (prefix matching). + */ +export const search = ( + entities: PwaEntityLike[], + claims: PwaClaimLike[], + query: string, + limit = 5, + filter?: SearchFilter, +): SearchResult[] => { + const { entityMap, entries: allEntries, avgDl: corpusAvgDl } = getIndex(entities, claims) + const entries = filter === undefined ? allEntries : allEntries.filter(filter) + + if (entries.length === 0) return [] + + const queryTokens = tokenize(query) + if (queryTokens.length === 0) return [] + + const idf = computeIDF(entries, queryTokens) + const avgDl = filter === undefined ? corpusAvgDl : averageTokenCount(entries) + + const scored = entries + .map((entry) => ({ + entry, + score: bm25Score(entry, queryTokens, idf, avgDl), + })) + .filter((s) => s.score > 0) + .sort((a, b) => b.score - a.score) + .slice(0, limit) + + return scored.map(({ entry, score }) => ({ + id: entry.id, + type: entry.type, + name: entry.type === 'entity' + ? (entityMap.get(entry.id)?.name ?? entry.id) + : (entry.entityName ?? entry.id), + snippet: getSnippet(entry), + score, + ...(entry.entityId !== undefined ? { entityId: entry.entityId } : {}), + ...(entry.entityName !== undefined ? { entityName: entry.entityName } : {}), + })) +} diff --git a/packages/dks-core/src/types.ts b/packages/dks-core/src/types.ts new file mode 100644 index 000000000..c1e35a53c --- /dev/null +++ b/packages/dks-core/src/types.ts @@ -0,0 +1,108 @@ +/** + * Shared domain types and safety limits for the framework-neutral core. + * These types are the single contract between the `dks` CLI and the + * optional MCP adapter; neither layer re-implements parsing or indexing. + */ + +/** Largest accepted bundle zip (mirrors the vault-zip compressed cap). */ +export const MAX_BUNDLE_ZIP_BYTES = 10_485_760 +/** Largest accepted decompressed total (mirrors the vault-zip safety cap). */ +export const MAX_BUNDLE_UNCOMPRESSED_BYTES = 52_428_800 +/** Largest accepted entry count (mirrors the vault-zip entry cap). */ +export const MAX_BUNDLE_ENTRIES = 2_000 +/** Largest accepted single concept file (fail-closed before parsing). */ +export const MAX_CONCEPT_BYTES = 5_242_880 +/** Zip prefix used by the studio OKF export; stripped to bundle paths. */ +export const EXPORT_PREFIX = 'okf-bundle/' +/** OKF bundle format versions this core understands. */ +export const SUPPORTED_OKF_MAJOR = '0.2' + +/** Provenance source entry from concept frontmatter. */ +export interface BundleSource { + /** Stable join key for `[^id]` footnote attribution. */ + id?: string + /** REQUIRED within an entry: the cited resource. */ + resource: string + /** Human-readable title or evidence label. */ + title?: string + /** Actor convention `human:` | `process:` | `/`. */ + author?: string +} + +/** Actor event from concept frontmatter (`generated` / `verified`). */ +export interface BundleActorEvent { + by: string + at?: string +} + +/** Trust tier derived from frontmatter `verified` (mirrors trustTier). */ +export type TrustTier = 'unverified' | 'machine-confirmed' | 'human-reviewed' + +/** A claim recovered from a concept's `# Claims` list. */ +export interface BundleClaim { + /** The claim statement text. */ + statement: string + /** Derived from the concept's trust tier, never upgraded. */ + verification: 'verified' | 'unverified' + /** Source resource joined through the footnote label, when present. */ + source?: string + /** Source title joined through the footnote label, when present. */ + evidence?: string +} + +/** A parsed bundle concept. */ +export interface BundleConcept { + /** Concept id: bundle-relative path minus `.md`. */ + id: string + /** Human-readable title or evidence label. */ + name: string + /** OKF concept type string (e.g. `Note`, `Concept`). */ + type: string + /** One-line summary of the item. */ + description: string + /** Markdown body without the `# Claims` / `# Related` sections. */ + content: string + /** Optional tags payload. */ + tags: string[] + /** Optional aliases (Markdown frontmatter `aliases`). */ + aliases?: string[] + /** Concept trust tier from frontmatter `verified`. */ + trustTier: TrustTier + /** Provenance source entries. */ + sources: BundleSource[] + /** Claims recovered from the `# Claims` list. */ + claims: BundleClaim[] + /** Related-concept links (`# Related` section): target bundle ids. */ + relatedIds: string[] +} + +/** A loaded bundle: concepts plus non-fatal warnings. */ +export interface LoadedBundle { + /** Parsed concepts in bundle order. */ + concepts: BundleConcept[] + /** Non-fatal notes (skipped entries, unknown keys are tolerated). */ + warnings: string[] +} + +/** A minimal entity shape (id, name, type, description, content, tags, aliases). */ +export interface CoreEntity { + id: string + name: string + type: string + description: string + content: string + tags: string[] + aliases?: string[] + /** Outgoing typed relations. */ + links?: Array<{ targetId: string; relation: string }> +} + +/** A minimal claim shape used by export/backup services. */ +export interface CoreClaim { + id: string + entityId: string + statement: string + verification: 'verified' | 'unverified' | 'disputed' + source?: string + evidence?: string +} diff --git a/packages/dks-core/src/zip.test.ts b/packages/dks-core/src/zip.test.ts new file mode 100644 index 000000000..b793db494 --- /dev/null +++ b/packages/dks-core/src/zip.test.ts @@ -0,0 +1,116 @@ +import { deflateRawSync } from 'node:zlib' +import { describe, expect, it } from 'vitest' +import { readZip } from './zip.js' + +/** Minimal zip builder for fixtures: stored or raw-deflate entries. */ +const buildZip = (entries: Array<{ name: string; data: Uint8Array; method?: 0 | 8 }>): Uint8Array => { + const encoder = new TextEncoder() + + const locals: Uint8Array[] = [] + const central: Uint8Array[] = [] + let offset = 0 + for (const entry of entries) { + const nameBytes = encoder.encode(entry.name) + const method = entry.method ?? 8 + const data = method === 8 ? deflateRawSync(entry.data) : entry.data + const local = new Uint8Array(30 + nameBytes.length + data.length) + const lv = new DataView(local.buffer) + lv.setUint32(0, 0x04034b50, true) + lv.setUint16(4, 20, true) // version needed + lv.setUint16(6, 0, true) // flags + lv.setUint16(8, method, true) + lv.setUint32(14, data.length, true) + lv.setUint32(18, entry.data.length, true) + lv.setUint16(26, nameBytes.length, true) + local.set(nameBytes, 30) + local.set(data, 30 + nameBytes.length) + locals.push(local) + + const cd = new Uint8Array(46 + nameBytes.length) + const cv = new DataView(cd.buffer) + cv.setUint32(0, 0x02014b50, true) + cv.setUint16(4, 20, true) + cv.setUint16(6, 20, true) + cv.setUint16(8, 0, true) + cv.setUint16(10, method, true) + cv.setUint32(20, data.length, true) + cv.setUint32(24, entry.data.length, true) + cv.setUint16(28, nameBytes.length, true) + cv.setUint32(42, offset, true) + cd.set(nameBytes, 46) + central.push(cd) + offset += local.length + } + const cdStart = locals.reduce((acc, l) => acc + l.length, 0) + const cdBytes = new Uint8Array(central.reduce((acc, c) => acc + c.length, 0)) + let pos = 0 + for (const c of central) { + cdBytes.set(c, pos) + pos += c.length + } + const eocd = new Uint8Array(22) + const ev = new DataView(eocd.buffer) + ev.setUint32(0, 0x06054b50, true) + ev.setUint16(8, entries.length, true) + ev.setUint16(10, entries.length, true) + ev.setUint32(12, cdBytes.length, true) + ev.setUint32(16, cdStart, true) + + const out = new Uint8Array(cdStart + cdBytes.length + 22) + pos = 0 + for (const l of locals) { + out.set(l, pos) + pos += l.length + } + out.set(cdBytes, pos) + out.set(eocd, pos + cdBytes.length) + return out +} + +/** Locates the central directory start (used to corrupt header fields). */ +const findCentralDirectory = (zip: Uint8Array): number => { + for (let i = 0; i <= zip.length - 46; i += 1) { + if (zip[i] === 0x50 && zip[i + 1] === 0x4b && zip[i + 2] === 0x01 && zip[i + 3] === 0x02) return i + } + throw new Error('central directory not found') +} +describe('readZip', () => { + it('reads stored and deflated entries in order', () => { + const zip = buildZip([ + { name: 'a.txt', data: new TextEncoder().encode('hello'), method: 0 }, + { name: 'b.txt', data: new TextEncoder().encode('world world world'), method: 8 }, + ]) + const entries = readZip(zip) + expect([...entries.keys()]).toEqual(['a.txt', 'b.txt']) + expect(new TextDecoder().decode(entries.get('a.txt'))).toBe('hello') + expect(new TextDecoder().decode(entries.get('b.txt'))).toBe('world world world') + }) + + it('returns an empty map for an archive with no entries', () => { + expect(readZip(buildZip([])).size).toBe(0) + }) + + it('throws on truncated input', () => { + const zip = buildZip([{ name: 'a.txt', data: new TextEncoder().encode('x') }]) + expect(() => readZip(zip.slice(0, 12))).toThrow() + }) + + it('throws on unsupported compression methods', () => { + const zip = buildZip([{ name: 'a.txt', data: new TextEncoder().encode('x'), method: 8 }]) + // Patch the method to 99 in both headers (local + central). + const patched = zip.slice() + const cd = findCentralDirectory(patched) + patched[8] = 99 + patched[cd + 10] = 99 + expect(() => readZip(patched)).toThrow(/unsupported compression method/) + }) + + it('throws when the decompressed size does not match the header', () => { + const zip = buildZip([{ name: 'a.txt', data: new TextEncoder().encode('x'), method: 8 }]) + // Corrupt the uncompressed-size field in the central directory header. + const patched = zip.slice() + const cd = findCentralDirectory(patched) + patched[cd + 24] = 0xff + expect(() => readZip(patched)).toThrow(/size mismatch/) + }) +}) diff --git a/packages/dks-core/src/zip.ts b/packages/dks-core/src/zip.ts new file mode 100644 index 000000000..5208a3f59 --- /dev/null +++ b/packages/dks-core/src/zip.ts @@ -0,0 +1,108 @@ +/** + * Minimal dependency-free ZIP reader used to open OKF bundle archives. + * + * Supports the two compression methods used by the studio's OKF export + * (fflate writes raw deflate): method 0 (stored) and method 8 (deflate). + * Anything else fails closed. Zip64 is not supported; all accepted inputs + * are bounded well below 4 GiB by the caller's caps. + */ + +import { inflateRawSync } from 'node:zlib' + +/** Central directory file header signature. */ +const CD_ENTRY_SIG = 0x02014b50 +/** End of central directory signature. */ +const EOCD_SIG = 0x06054b50 +/** Local file header signature. */ +const LOCAL_HEADER_SIG = 0x04034b50 + +/** A single zip entry name → decompressed bytes. */ +export type ZipEntries = Map + +/** Reads a 16-bit little-endian unsigned int at `offset`. */ +const u16 = (b: Uint8Array, offset: number): number => + (b[offset] ?? 0) | ((b[offset + 1] ?? 0) << 8) + +/** Reads a 32-bit little-endian unsigned int at `offset`. */ +const u32 = (b: Uint8Array, offset: number): number => + ((b[offset] ?? 0) | + ((b[offset + 1] ?? 0) << 8) | + ((b[offset + 2] ?? 0) << 16) | + ((b[offset + 3] ?? 0) << 24)) >>> + 0 + +/** Locates the end-of-central-directory record from the buffer tail. */ +const findEocd = (buffer: Uint8Array): { offset: number; count: number } => { + const max = Math.min(buffer.length, 65_557) + for (let i = buffer.length - 22; i >= buffer.length - max; i -= 1) { + if (i < 0) break + if (u32(buffer, i) === EOCD_SIG) { + const count = u16(buffer, i + 10) + const cdOffset = u32(buffer, i + 16) + return { offset: cdOffset, count } + } + } + throw new Error('Not a valid zip archive (missing end-of-central-directory record).') +} + +/** Decodes the UTF-8 name of an entry, rejecting malformed sequences. */ +const decodeName = (bytes: Uint8Array): string => { + try { + return new TextDecoder('utf-8', { fatal: true }).decode(bytes) + } catch { + throw new Error('Zip entry name is not valid UTF-8.') + } +} + +/** + * Reads all entries from a zip buffer. Path traversal and size caps are the + * caller's responsibility (they own the bundle safety limits). + * @param buffer - Raw zip bytes. + * @returns Entry name → decompressed bytes, in archive order. + */ +export const readZip = (buffer: Uint8Array): ZipEntries => { + const eocd = findEocd(buffer) + if (eocd.count === 0) return new Map() + let cursor = eocd.offset + const entries: ZipEntries = new Map() + for (let n = 0; n < eocd.count; n += 1) { + if (u32(buffer, cursor) !== CD_ENTRY_SIG) { + throw new Error('Zip central directory is corrupted.') + } + const method = u16(buffer, cursor + 10) + const compressedSize = u32(buffer, cursor + 20) + const uncompressedSize = u32(buffer, cursor + 24) + const nameLen = u16(buffer, cursor + 28) + const extraLen = u16(buffer, cursor + 30) + const commentLen = u16(buffer, cursor + 32) + const localOffset = u32(buffer, cursor + 42) + const name = decodeName(buffer.subarray(cursor + 46, cursor + 46 + nameLen)) + cursor += 46 + nameLen + extraLen + commentLen + + if (u32(buffer, localOffset) !== LOCAL_HEADER_SIG) { + throw new Error(`Zip local header is corrupted for entry "${name}".`) + } + const localNameLen = u16(buffer, localOffset + 26) + const localExtraLen = u16(buffer, localOffset + 28) + const dataStart = localOffset + 30 + localNameLen + localExtraLen + const data = buffer.subarray(dataStart, dataStart + compressedSize) + + let out: Uint8Array + if (method === 0) { + out = data + } else if (method === 8) { + try { + out = inflateRawSync(data) + } catch { + throw new Error(`Zip entry "${name}" failed to decompress.`) + } + } else { + throw new Error(`Zip entry "${name}" uses unsupported compression method ${method}.`) + } + if (out.byteLength !== uncompressedSize) { + throw new Error(`Zip entry "${name}" size mismatch after decompression.`) + } + entries.set(name, out) + } + return entries +} diff --git a/packages/dks-core/tsconfig.build.json b/packages/dks-core/tsconfig.build.json new file mode 100644 index 000000000..eaeac4c6c --- /dev/null +++ b/packages/dks-core/tsconfig.build.json @@ -0,0 +1,11 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "declaration": true, + "noEmit": false, + "noEmitOnError": true, + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src"] +} diff --git a/packages/dks-core/tsconfig.json b/packages/dks-core/tsconfig.json new file mode 100644 index 000000000..55c1cf7ea --- /dev/null +++ b/packages/dks-core/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "skipLibCheck": true, + "noEmit": true, + "types": ["node"] + }, + "include": ["src"] +} diff --git a/packages/dks-core/vitest.config.ts b/packages/dks-core/vitest.config.ts new file mode 100644 index 000000000..ceafc2412 --- /dev/null +++ b/packages/dks-core/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + environment: 'node', + include: ['src/**/*.test.ts'], + }, +}) diff --git a/plans/217-open-issues-2026-11-17.md b/plans/217-open-issues-2026-11-17.md new file mode 100644 index 000000000..7cdea94b9 --- /dev/null +++ b/plans/217-open-issues-2026-11-17.md @@ -0,0 +1,75 @@ +# Plan 217 — Open GitHub Issues (2026-11-17) + +## Goal + +Resolve the 20 open issues #1155–#1174 with issue-linked, reviewable PRs and merge eligible PRs in order only after CI, including Codacy, passes. + +## Constraints + +- Preserve local-first architecture and existing data-safety, accessibility, and security invariants. +- Use separate coherent PRs; do not combine unrelated product areas merely to close issues together. +- The four issues labeled `duplicate` (#1168, #1172–#1174) still have distinct acceptance criteria; cover their actual scope before closing them against canonical work. +- No live-workspace encryption migration without accepted threat model, plaintext-surface inventory, and real-browser shadow/canary evidence (ADR 048). +- Do not claim hardware/browser compatibility that was not measured. + +## Issue groups and dependencies + +1. **Import and data integrity** — #1155 aggregate Markdown import limit; #1157 alias revisions; #1158 latest-state entity merge; #1159 evidence-based legacy-backup compatibility decision. Preserve staged, fail-closed import and cross-tab/undo semantics. + - #1159 history: public tags v0.1.1, v0.1.2, and v0.2.0 emitted the flat v1 JSON export shape; their + parser treated an absent `version` as v1. Compatibility is restricted to that recognized flat shape + and validated through the current schema. +2. **Storage diagnostics** — #1156 quota and persistence status/request UI; depends on no corpus schema change and must remain local-only. +3. **Graph** — #1163 reproducible measurement and optimizations first; #1164 visual query composition on the existing validated graph-query model and saved views. +4. **Runtime/toolchain/security** — #1165 Node matrix and evidence; #1166 pnpm upgrade only after frozen installs and quality checks; #1167 CSP audit without weakening policy absent production-browser evidence. +5. **Portable Agent Skills** — #1168 inventory/spec audit; #1174 catalog/package/install/update tooling; #1172 validation and local/CI behavioral checks; #1173 CLI-backed workflows after CLI capabilities exist. +6. **CLI architecture** — #1170 shared domain boundaries before #1169 CLI commands; #1171 stable JSON/exit-code contract before workflows; #1160 MCP remains optional and delegates to shared services; #1161 architecture/product docs follow shipped interfaces. +7. **At-rest encryption** — #1162 remains gated by ADR 048's explicit product/security exit criteria. Do not wire a persistence migration until those criteria and the real-corpus lifecycle are satisfied. + +## Execution gates + +- Bugs: reproduce, add a regression that fails before the fix, then run the narrowest relevant test. +- Persistence/hydration/sync changes: follow `persistence-data-safety`; record real-corpus evidence in this plan before promotion. +- UI/graph/search/export changes: targeted tests plus the relevant browser E2E and keyboard/accessibility verification. +- Toolchain changes: official release-note references, frozen install, and aligned CI/developer configuration. +- Before every PR merge: all checks pass (including Codacy), review threads are resolved, `code-review-assistant` completes with no unresolved P1/P2, and the local quality gate is green. Merge with squash in dependency/creation order; never use `--admin`. +- Planned PR order: local data integrity/storage (#1155–#1159); graph performance/query UI (#1163–#1164); runtime/security baseline (#1165, #1167); portable Agent Skills/CLI/MCP plus pnpm (#1160–#1161, #1166, #1168–#1174, excluding deferred #1162). Keep PRs coherent and refresh later branches after each ordered merge. + +## Official references + +- [pnpm 12.17.0 release notes](https://github.com/pnpm/pnpm/releases/tag/v12.17.0) +- [pnpm installation and Node.js compatibility](https://pnpm.io/installation) +- [Node.js release status and schedule](https://nodejs.org/en/about/previous-releases) +- [Agent Skills specification](https://agentskills.io/specification) +- [Next.js CSP guidance](https://nextjs.org/docs/app/guides/content-security-policy) +- [Next.js response-header configuration](https://nextjs.org/docs/app/api-reference/config/next-config-js/headers) + +## Progress + +- [x] Enumerated 20 open issues and read their descriptions/duplicate notices. +- [x] PR #1175 merged before #1176; every non-skipped check, including Codacy Static Code Analysis, passed on both; E2E was skipped. +- [x] #1155 — aggregate Markdown import cap; targeted regression failed before the guard, then all 3 import-staging tests passed. + +- [x] #1152 corpus-fingerprint regression reproduced: different root `exportedAt` timestamps produced different hashes for identical corpus content; added a regression and fixed the metadata exclusion, then all 6 BATS tests passed. +- [x] User chose deferral for #1162; leave it open until ADR 048's threat model, plaintext inventory, and real-browser shadow/canary exit criteria are satisfied. +- [x] #1163 graph filter/query CPU budget checks passed across 1k/5k/10k (6 tests); #1164 browser builder E2E passed (6/6); 1k/5k/10k frame sweep remains pending. +- [x] Data-safety import/revision/storage focused suite: 8 Vitest files, 126 tests passed after fixing a parser identifier collision and storage test mocks/format expectation. +- [x] Shared-core Markdown parser tests passed (7/7) after separating frontmatter aliases from tags and preserving wikilink stub display casing. +- [x] Shared-core suite: 12 files/93 tests passed; PWA OKF adapter suite: 14/14 passed. Fixed archive result discriminants and preserved the PWA's index-less legacy-import behavior. +- [x] CLI package suite: 48/48 tests passed, including nested `skills list`, `skills validate`, and `skills test`; MCP adapter suite: 9/9 passed. +- [x] Package typechecks passed for `dks-core`, `dks-cli`, and `dks-mcp`. + +- [x] Chromium browser lifecycle with a deterministic 500-entity/500-claim corpus: imported through the UI, IndexedDB held 500/500 records after two full reloads, and the exported 499,140-byte JSON fingerprint stayed `c3207e7521bce035c22006fd5ab762d48bcde6bc4dd736549812edf27ad2679c` across the reload/export cycle. Generated fixture, not a user's corpus. +- [x] Shared-core browser integration: the app compiles and renders through compiled browser-safe package subpaths; this avoids bundling the package's Node-only IO exports into the client. +- [x] Shared-core PWA Markdown adapter preserves historical tag order while persisting aliases; malformed frontmatter and graph-tree-path regressions pass. Focused app suite: 7 files/120 tests; workspace typechecks pass. +- [x] #1164 graph builder Chromium E2E: 6/6 passed with live preview, nested OR query, invalid-group handling, saved views, and keyboard/screen-reader checks. +- [x] Follow-up mobile graph query E2E passed (1/1) after capping the mobile controls panel and preserving a minimum canvas; tablet semantic-search E2E passed (3/3) after timeout adjustment. Full E2E and frame sweep remain pending. +- [x] Fixed the sweep's missing pan summary; 1k Chromium frame E2E passed (pan p50/p95 33.2/266.6 ms; zoom 33.3/320.0 ms; heap API unavailable). 5k/10k timing remains in progress. +- [x] #1163 full 1k/5k/10k frame sweep recorded 2026-11-18 (pan p50/p95 16.7/166.7, 33.3/638.4, 66.7/1246.6 ms; zoom 16.7/200.9, 33.3/694.1, 49.9/910.8 ms; all inside the 120/1500 ms ceilings; environment and heap metadata printed by the runner and recorded in plans/perf-baselines.md). +- [x] Full browser E2E suite passed: 937 passed (+2 flaky passed on retry) across chromium/mobile/tablet/desktop-xl; the two contentions-era failures (frame timeline, graph-comparison) pass in isolation on a quiet machine. + +- [x] 2026-11-18 re-verification pass: gate (lint, typecheck, unit, build) green after fixing three stale graph-builder component tests (preview edge count matched the two directed fixture relations; remove control renamed to the accessible per-clause label; clause list given an accessible name so the validation list no longer collides) and restoring the graph-layout bench guard that a bench-config edit had silently dropped. +- [x] #1159 gap closed: added a legacy v1 import → export fingerprint round-trip test pinning the legacy path to the `scripts/corpus-fingerprint.mjs` canonicalization, and documented the compatibility window/deprecation boundary in README (Import compatibility section). + +- [ ] Implement and verify remaining issue groups. +- [ ] Resolve/close issues only when their acceptance criteria are covered or the issue's own evidence-based not-planned path is justified. +- [ ] Review and merge PRs in order after every merge gate is green. diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 32a4db71c..7ea3b2f95 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -123,6 +123,9 @@ importers: date-fns: specifier: ^4.1.0 version: 4.4.0 + dks-core: + specifier: workspace:* + version: link:packages/dks-core docx: specifier: ^9.10.0 version: 9.10.0 @@ -293,6 +296,19 @@ importers: specifier: 4.1.11 version: 4.1.11(@types/node@22.20.5)(@vitest/coverage-v8@4.1.11)(jsdom@30.1.2)(vite@8.2.4(@types/node@22.20.5)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.0)(yaml@2.9.1)) + packages/dks-core: + dependencies: + yaml: + specifier: ^2.9.1 + version: 2.9.1 + devDependencies: + typescript: + specifier: ^6 + version: 6.0.3 + vitest: + specifier: 4.1.11 + version: 4.1.11(@types/node@26.6.5)(@vitest/coverage-v8@4.1.11)(jsdom@30.1.2)(vite@8.2.4(@types/node@26.6.5)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.0)(yaml@2.9.1)) + packages/dks-mcp: dependencies: '@modelcontextprotocol/sdk': @@ -1245,9 +1261,6 @@ packages: resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} engines: {node: '>=6.0.0'} - '@jridgewell/sourcemap-codec@1.5.5': - resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} - '@jridgewell/sourcemap-codec@1.6.0': resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} @@ -6635,8 +6648,6 @@ snapshots: '@jridgewell/resolve-uri@3.1.2': {} - '@jridgewell/sourcemap-codec@1.5.5': {} - '@jridgewell/sourcemap-codec@1.6.0': {} '@jridgewell/trace-mapping@0.3.31': @@ -8270,7 +8281,7 @@ snapshots: obug: 2.1.3 std-env: 4.2.0 tinyrainbow: 3.1.0 - vitest: 4.1.11(@types/node@22.20.5)(@vitest/coverage-v8@4.1.11)(jsdom@30.1.2)(vite@8.2.4(@types/node@22.20.5)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.0)(yaml@2.9.1)) + vitest: 4.1.11(@types/node@26.6.5)(@vitest/coverage-v8@4.1.11)(jsdom@30.1.2)(vite@8.2.4(@types/node@26.6.5)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.0)(yaml@2.9.1)) '@vitest/expect@4.1.11': dependencies: @@ -8289,6 +8300,14 @@ snapshots: optionalDependencies: vite: 8.2.4(@types/node@22.20.5)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.0)(yaml@2.9.1) + '@vitest/mocker@4.1.11(vite@8.2.4(@types/node@26.6.5)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.0)(yaml@2.9.1))': + dependencies: + '@vitest/spy': 4.1.11 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 8.2.4(@types/node@26.6.5)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.0)(yaml@2.9.1) + '@vitest/pretty-format@4.1.11': dependencies: tinyrainbow: 3.1.0 @@ -9898,7 +9917,7 @@ snapshots: magic-string@0.30.21: dependencies: - '@jridgewell/sourcemap-codec': 1.5.5 + '@jridgewell/sourcemap-codec': 1.6.0 magic-string@1.4.5: dependencies: @@ -11546,6 +11565,21 @@ snapshots: tsx: 4.23.0 yaml: 2.9.1 + vite@8.2.4(@types/node@26.6.5)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.0)(yaml@2.9.1): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.31 + rolldown: 1.2.14 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 26.6.5 + esbuild: 0.28.1 + fsevents: 2.3.3 + jiti: 2.7.0 + tsx: 4.23.0 + yaml: 2.9.1 + vitest@4.1.11(@types/node@22.20.5)(@vitest/coverage-v8@4.1.11)(jsdom@30.1.2)(vite@8.2.4(@types/node@22.20.5)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.0)(yaml@2.9.1)): dependencies: '@vitest/expect': 4.1.11 @@ -11575,6 +11609,35 @@ snapshots: transitivePeerDependencies: - msw + vitest@4.1.11(@types/node@26.6.5)(@vitest/coverage-v8@4.1.11)(jsdom@30.1.2)(vite@8.2.4(@types/node@26.6.5)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.0)(yaml@2.9.1)): + dependencies: + '@vitest/expect': 4.1.11 + '@vitest/mocker': 4.1.11(vite@8.2.4(@types/node@26.6.5)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.0)(yaml@2.9.1)) + '@vitest/pretty-format': 4.1.11 + '@vitest/runner': 4.1.11 + '@vitest/snapshot': 4.1.11 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 + es-module-lexer: 2.3.0 + expect-type: 1.4.0 + magic-string: 0.30.21 + obug: 2.1.3 + pathe: 2.0.3 + picomatch: 4.0.7 + std-env: 4.2.0 + tinybench: 2.9.0 + tinyexec: 1.2.4 + tinyglobby: 0.2.17 + tinyrainbow: 3.1.0 + vite: 8.2.4(@types/node@26.6.5)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.0)(yaml@2.9.1) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 26.6.5 + '@vitest/coverage-v8': 4.1.11(vitest@4.1.11) + jsdom: 30.1.2 + transitivePeerDependencies: + - msw + w3c-xmlserializer@6.0.0: dependencies: xml-name-validator: 5.0.0 diff --git a/scripts/corpus-fingerprint.mjs b/scripts/corpus-fingerprint.mjs index beddf8338..8478a9860 100755 --- a/scripts/corpus-fingerprint.mjs +++ b/scripts/corpus-fingerprint.mjs @@ -2,9 +2,9 @@ // scripts/corpus-fingerprint.mjs — stable sha256 of a JSON corpus export (#1152). // // Shadow comparisons for persistence work: export the store before and after -// a migration (or a kill-the-tab-mid-write run), fingerprint both files, and -// compare. Key order and insignificant whitespace do not affect the hash; -// array order does (arrays are ordered data). +// a migration or interrupted write, then fingerprint both files. +// Root-level exportedAt timestamps are metadata and excluded; key order and +// insignificant whitespace do not affect the hash, but array order does. // // Usage: // node scripts/corpus-fingerprint.mjs @@ -21,18 +21,20 @@ import { readTextFile } from "./lib/read-text.mjs"; const EXPECT_FLAG = "--expect"; const STDIN_FLAG = "--stdin"; const CORPUS_EXTENSION = ".json"; +const EXPORT_TIMESTAMP_FIELD = "exportedAt"; function fail(message) { process.stderr.write(`corpus-fingerprint: ${message}\n`); process.exit(1); } -function canonicalize(value) { +function canonicalize(value, isTopLevel = false) { if (Array.isArray(value)) { return `[${value.map((item) => canonicalize(item)).join(",")}]`; } if (value !== null && typeof value === "object") { const entries = Object.entries(value) + .filter(([key]) => !isTopLevel || key !== EXPORT_TIMESTAMP_FIELD) .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)) .map(([key, child]) => `${JSON.stringify(key)}:${canonicalize(child)}`); return `{${entries.join(",")}}`; @@ -47,7 +49,7 @@ function fingerprint(text, label) { } catch { fail(`invalid JSON in ${label}`); } - return createHash("sha256").update(canonicalize(parsed)).digest("hex"); + return createHash("sha256").update(canonicalize(parsed, true)).digest("hex"); } async function main() { diff --git a/src/components/studio/views/export-helpers.test.ts b/src/components/studio/views/export-helpers.test.ts index 2ac0fbbff..51a39d868 100644 --- a/src/components/studio/views/export-helpers.test.ts +++ b/src/components/studio/views/export-helpers.test.ts @@ -11,6 +11,7 @@ import { todayStamp } from './export-types' import { buildPdfExport, buildDocxExport } from './export-documents' import { buildMentionToken } from '@/lib/editor/mention' import { escapeHtml } from '@/lib/security' +import { EXPORT_SCHEMA_VERSION } from '@/lib/studio/constants' import type { Entity, Claim } from '@/lib/studio/types' import type { ValidatedGraph, ValidatedMindMap, ValidatedLink, ValidatedTag } from '@/lib/studio/schema' @@ -58,6 +59,17 @@ const SAMPLE_TAGS: ValidatedTag[] = [ { id: 't1', name: 'important', color: '#ff0000' }, ] +/** Sanitized flat v1 export shape accepted by releases before strict version checks. */ +const VERSIONLESS_V1_EXPORT_FIXTURE = { + exportedAt: '2026-08-12T00:00:00.000Z', + entities: SAMPLE_ENTITIES, + claims: SAMPLE_CLAIMS, + graph: SAMPLE_GRAPH, + mindMap: SAMPLE_MIND_MAP, + links: SAMPLE_LINKS, + tags: SAMPLE_TAGS, +} + /** * Assembled from parts so the fixture never contains a literal script-URL * scheme — static analyzers flag those literals as eval-style URLs even when @@ -311,11 +323,48 @@ describe('checkImportSize', () => { }) describe('parseImportFile', () => { - it('rejects a payload with no version field', () => { - const result = parseImportFile('{"entities":[],"claims":[]}') + it('accepts the historically supported versionless v1 export shape', () => { + // Released tags emitted the flat v1 shape; their parser mapped an absent version to v1. + const result = parseImportFile(JSON.stringify(VERSIONLESS_V1_EXPORT_FIXTURE)) + + expect(result.success).toBe(true) + if (result.success) { + expect(result.entities).toHaveLength(1) + expect(result.claims).toHaveLength(1) + expect(result.entities[0]?.aliases).toEqual([]) + expect(result.graph).toEqual(SAMPLE_GRAPH) + expect(result.mindMap).toEqual(SAMPLE_MIND_MAP) + expect(result.links).toEqual(SAMPLE_LINKS) + expect(result.tags).toEqual(SAMPLE_TAGS) + } + }) + + it('rejects an unversioned persistence envelope that is not a recognized export', () => { + const result = parseImportFile(JSON.stringify({ state: { entities: SAMPLE_ENTITIES, claims: SAMPLE_CLAIMS } })) expect(result.success).toBe(false) if (!result.success) { - expect(result.errors[0].path).toBe('version') + expect(result.errors[0]?.path).toBe('version') + } + }) + + it('rejects a versionless flat payload with unknown fields', () => { + const legacyPayload: Record = { ...VERSIONLESS_V1_EXPORT_FIXTURE } + legacyPayload.futureField = true + + const result = parseImportFile(JSON.stringify(legacyPayload)) + + expect(result.success).toBe(false) + if (!result.success) { + expect(result.errors[0]?.path).toBe('version') + } + }) + + it('requires the historical claims and timestamp fields for versionless exports', () => { + const result = parseImportFile(JSON.stringify({ entities: SAMPLE_ENTITIES })) + + expect(result.success).toBe(false) + if (!result.success) { + expect(result.errors[0]?.path).toBe('version') } }) @@ -440,3 +489,53 @@ describe('buildDocxExport', () => { expect(blob.size).toBeGreaterThan(0) }) }) + +describe('legacy v1 import fingerprint round trip (#1159)', () => { + // Mirrors the canonicalization of scripts/corpus-fingerprint.mjs (sorted + // keys, top-level exportedAt excluded) so the legacy import path is pinned + // to the same fingerprint the shadow persistence checks compare. + const canonicalize = (value: unknown, isTopLevel = false): string => { + if (Array.isArray(value)) return `[${value.map((item) => canonicalize(item)).join(',')}]` + if (value !== null && typeof value === 'object') { + const entries = Object.entries(value as Record) + .filter(([key]) => !isTopLevel || key !== 'exportedAt') + .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)) + .map(([key, child]) => `${JSON.stringify(key)}:${canonicalize(child)}`) + return `{${entries.join(',')}}` + } + return JSON.stringify(value) ?? 'null' + } + + const fingerprint = async (json: string): Promise => { + const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(canonicalize(JSON.parse(json), true))) + return Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, '0')).join('') + } + + it('lands a recognized legacy v1 import on the same canonical corpus as its modern equivalent', async () => { + const legacyResult = parseImportFile(JSON.stringify(VERSIONLESS_V1_EXPORT_FIXTURE)) + expect(legacyResult.success).toBe(true) + if (!legacyResult.success) return + + // Same corpus data under the modern versioned envelope with a different + // export timestamp: the fingerprint must not be able to tell them apart. + const modernEquivalent = { + ...VERSIONLESS_V1_EXPORT_FIXTURE, + version: EXPORT_SCHEMA_VERSION, + exportedAt: '2026-11-18T00:00:00.000Z', + } + const modernResult = parseImportFile(JSON.stringify(modernEquivalent)) + expect(modernResult.success).toBe(true) + if (!modernResult.success) return + + const exportOptions = { + graph: legacyResult.graph, + mindMap: legacyResult.mindMap, + links: legacyResult.links, + tags: legacyResult.tags, + } + const legacyJson = buildJsonExport(legacyResult.entities, legacyResult.claims, exportOptions) + const modernJson = buildJsonExport(modernResult.entities, modernResult.claims, exportOptions) + + expect(await fingerprint(legacyJson)).toBe(await fingerprint(modernJson)) + }) +}) diff --git a/src/components/studio/views/export-helpers.ts b/src/components/studio/views/export-helpers.ts index 558fdb6ac..9fd57b3a7 100644 --- a/src/components/studio/views/export-helpers.ts +++ b/src/components/studio/views/export-helpers.ts @@ -187,6 +187,27 @@ export const buildHtmlExport = (entities: Entity[], claims: Claim[]): string => ` } +/** Top-level fields in the flat JSON export format emitted by released v1 builds. */ +const LEGACY_VERSIONLESS_EXPORT_FIELDS: Record = { + entities: true, + claims: true, + exportedAt: true, + graph: true, + mindMap: true, + links: true, + tags: true, +} + +/** + * Recognizes only the historical flat export shape. Unknown keys, nested + * persistence envelopes, and malformed optional fields remain unsupported. + */ +const isRecognizedVersionlessExport = (root: Record): boolean => { + if (Object.hasOwn(root, 'version') || !Array.isArray(root.entities)) return false + if (!Array.isArray(root.claims) || typeof root.exportedAt !== 'string') return false + return Object.keys(root).every((field) => Object.hasOwn(LEGACY_VERSIONLESS_EXPORT_FIELDS, field)) +} + /** Parses and validates an imported JSON export file. */ export const parseImportFile = (text: string): ImportResult => { let data: unknown @@ -200,14 +221,22 @@ export const parseImportFile = (text: string): ImportResult => { } const root = data as Record - if (typeof root.version !== 'number') { - return { success: false, errors: [{ path: 'version', message: 'Missing version: file has no version field (legacy v1 files must be re-exported).' }] } + let version: number + if (typeof root.version === 'number') { + version = root.version + } else if (isRecognizedVersionlessExport(root)) { + version = EXPORT_SCHEMA_VERSION + } else { + return { + success: false, + errors: [{ path: 'version', message: 'Missing or invalid version: only the recognized flat version-less v1 export format is supported.' }], + } } - if (root.version !== EXPORT_SCHEMA_VERSION) { - return { success: false, errors: [{ path: 'version', message: `Unsupported version ${String(root.version)}: this app reads version ${String(EXPORT_SCHEMA_VERSION)}.` }] } + if (version !== EXPORT_SCHEMA_VERSION) { + return { success: false, errors: [{ path: 'version', message: `Unsupported version ${String(version)}: this app reads version ${String(EXPORT_SCHEMA_VERSION)}.` }] } } const payload = { - version: root.version, + version, exportedAt: typeof root.exportedAt === 'string' ? root.exportedAt : new Date().toISOString(), entities: root.entities ?? [], claims: root.claims ?? [], @@ -239,5 +268,5 @@ export const parseImportFile = (text: string): ImportResult => { } } - return { success: true, entities, claims, version: root.version, graph, mindMap, links, tags } + return { success: true, entities, claims, version, graph, mindMap, links, tags } } diff --git a/src/components/studio/views/import-staging.test.ts b/src/components/studio/views/import-staging.test.ts index 577f3ee2f..a727bfb8a 100644 --- a/src/components/studio/views/import-staging.test.ts +++ b/src/components/studio/views/import-staging.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it, vi } from 'vitest' import type { ImportPreview } from './export-types' import { stagePickedNonJsonFiles } from './import-staging' +import { toast } from 'sonner' +import { MAX_IMPORT_BYTES } from '@/lib/studio/constants' vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }, @@ -38,4 +40,26 @@ describe('stagePickedNonJsonFiles', () => { expect(handled).toBe(false) expect(preview?.entities).toHaveLength(0) }) + + it('rejects a Markdown batch over the aggregate import limit before reading files', async () => { + const files = [ + new File(['---\ntitle: First\n---\n\nbody'], 'first.md'), + new File(['---\ntitle: Second\n---\n\nbody'], 'second.md'), + ] + const perFileBytes = Math.floor(MAX_IMPORT_BYTES / 2) + 1 + for (const file of files) { + Object.defineProperty(file, 'size', { value: perFileBytes }) + } + const textReads = files.map((file) => vi.spyOn(file, 'text')) + const setImportPreview = vi.fn() + + await stagePickedNonJsonFiles(files, [], setImportPreview) + + expect(toast.error).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ description: expect.stringContaining('limit') }), + ) + expect(textReads.every((read) => read.mock.calls.length === 0)).toBe(true) + expect(setImportPreview).not.toHaveBeenCalled() + }) }) diff --git a/src/components/studio/views/import-staging.ts b/src/components/studio/views/import-staging.ts index f06b2761b..feae34033 100644 --- a/src/components/studio/views/import-staging.ts +++ b/src/components/studio/views/import-staging.ts @@ -8,6 +8,7 @@ import { parseVaultFiles, type MarkdownImportResult, } from '@/lib/import/markdown-import' +import { checkImportSize } from './export-helpers' import { readVaultZip } from '@/lib/import/vault-zip' /** @@ -162,6 +163,13 @@ export const stagePickedNonJsonFiles = async ( /** The picked Markdown notes. */ const markdownFiles = selected.filter((file) => isMarkdownPath(file.name)) + /** Total Markdown payload size, rejected before any file is read. */ + const totalBytes = markdownFiles.reduce((total, file) => total + file.size, 0) + const sizeError = checkImportSize(totalBytes) + if (sizeError !== null) { + toast.error(exportT('export.import.failed'), { description: sizeError }) + return true + } try { /** The path → content batch. */ const batch = new Map() diff --git a/src/components/studio/views/settings-view.test.tsx b/src/components/studio/views/settings-view.test.tsx index 43e779524..a5388e50c 100644 --- a/src/components/studio/views/settings-view.test.tsx +++ b/src/components/studio/views/settings-view.test.tsx @@ -1,10 +1,12 @@ -import { render, screen, waitFor } from '@testing-library/react' +import { fireEvent, render, screen, waitFor } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { ModelCacheUsage } from '@/lib/studio/storage-report' +import { formatBytes, type ModelCacheUsage } from '@/lib/studio/storage-report' const mocks = vi.hoisted(() => ({ readModelCacheUsage: vi.fn(), clearModelCache: vi.fn(), + readOriginStorage: vi.fn(), + requestPersistence: vi.fn(), resetSemanticCache: vi.fn(), getSemanticIndexProgress: vi.fn(), getMemoryBytes: vi.fn(), @@ -20,6 +22,8 @@ vi.mock('@/lib/studio/storage-report', async () => { ...actual, readModelCacheUsage: mocks.readModelCacheUsage, clearModelCache: mocks.clearModelCache, + readOriginStorage: mocks.readOriginStorage, + requestPersistence: mocks.requestPersistence, } }) @@ -49,10 +53,18 @@ const usage = (overrides: Partial = {}): ModelCacheUsage => ({ beforeEach(() => { mocks.readModelCacheUsage.mockResolvedValue(usage()) mocks.clearModelCache.mockResolvedValue(true) + mocks.readOriginStorage.mockResolvedValue({ + supported: true, + estimate: { usageBytes: 200 * MB, quotaBytes: 1000 * MB }, + persisted: false, + persistenceRequestSupported: true, + }) + mocks.requestPersistence.mockResolvedValue({ supported: true, granted: true }) mocks.getSemanticIndexProgress.mockReturnValue({ status: 'ready', completed: 42, total: 42 }) mocks.getMemoryBytes.mockReturnValue(2 * MB) mocks.toastSuccess.mockClear() mocks.toastInfo.mockClear() + mocks.requestPersistence.mockClear() mocks.resetSemanticCache.mockClear() }) @@ -84,7 +96,7 @@ describe('SettingsView', () => { expect(screen.getByText('42')).toBeDefined() }) - screen.getByRole('button', { name: /rebuild index/i }).click() + fireEvent.click(screen.getByRole('button', { name: /rebuild index/i })) expect(mocks.resetSemanticCache).toHaveBeenCalledOnce() expect(mocks.toastSuccess).toHaveBeenCalledWith('Semantic index cleared') @@ -101,7 +113,7 @@ describe('SettingsView', () => { expect(screen.getByText('3')).toBeDefined() }) - screen.getByRole('button', { name: /clear model cache/i }).click() + fireEvent.click(screen.getByRole('button', { name: /clear model cache/i })) await waitFor(() => { expect(mocks.toastInfo).toHaveBeenCalledWith('No cached model files') @@ -121,4 +133,139 @@ describe('SettingsView', () => { ).toBeDefined() }) }) + + it('reports estimated origin usage, quota and persistence status', async () => { + render() + + await waitFor(() => { + expect(screen.getByText('Estimated usage')).toBeDefined() + }) + expect(screen.getByText('200 MB')).toBeDefined() + expect(screen.getByText(formatBytes(1000 * MB))).toBeDefined() + expect(screen.getByText(/Not granted/)).toBeDefined() + expect(screen.getByText(/everything this site stores here/)).toBeDefined() + expect(screen.getByText(/not a backup/)).toBeDefined() + expect(screen.getByRole('region', { name: 'Origin storage' })).toBeDefined() + expect(screen.getByRole('region', { name: 'Semantic index' })).toBeDefined() + expect(screen.getByRole('region', { name: 'Model cache' })).toBeDefined() + }) + + it('does not warn while usage stays under the threshold', async () => { + render() + + await waitFor(() => { + expect(screen.getByText('Estimated usage')).toBeDefined() + }) + expect(screen.queryByText(/back up anything you cannot recreate/)).toBeNull() + }) + + it('warns when the origin approaches its reported quota', async () => { + mocks.readOriginStorage.mockResolvedValue({ + supported: true, + estimate: { usageBytes: 900 * MB, quotaBytes: 1000 * MB }, + persisted: false, + persistenceRequestSupported: true, + }) + render() + + await waitFor(() => { + expect(screen.getByText(/90%/)).toBeDefined() + }) + }) + + it('requests persistence and reports a grant', async () => { + render() + await waitFor(() => { + expect(screen.getByRole('button', { name: /request persistent storage/i })).toBeDefined() + }) + + fireEvent.click(screen.getByRole('button', { name: /request persistent storage/i })) + + await waitFor(() => { + expect(mocks.requestPersistence).toHaveBeenCalledOnce() + }) + await waitFor(() => { + expect(mocks.toastSuccess).toHaveBeenCalledWith('Persistent storage granted') + }) + }) + + it('explains when the browser declines persistence', async () => { + mocks.requestPersistence.mockResolvedValue({ supported: true, granted: false }) + render() + await waitFor(() => { + expect(screen.getByRole('button', { name: /request persistent storage/i })).toBeDefined() + }) + + fireEvent.click(screen.getByRole('button', { name: /request persistent storage/i })) + + await waitFor(() => { + expect(mocks.toastInfo).toHaveBeenCalledWith( + 'The browser declined persistent storage. Your data may still be evicted.', + ) + }) + }) + + it('hides the request button once persistence is already granted', async () => { + mocks.readOriginStorage.mockResolvedValue({ + supported: true, + estimate: { usageBytes: 1, quotaBytes: 10 }, + persisted: true, + persistenceRequestSupported: true, + }) + render() + + await waitFor(() => { + expect(screen.getByText(/^Granted/)).toBeDefined() + }) + expect(screen.queryByRole('button', { name: /request persistent storage/i })).toBeNull() + }) + + it('degrades gracefully when the Storage API is missing', async () => { + mocks.readOriginStorage.mockResolvedValue({ + supported: false, + estimate: null, + persisted: null, + persistenceRequestSupported: false, + }) + render() + + await waitFor(() => { + expect( + screen.getByText('This browser does not expose origin storage diagnostics.'), + ).toBeDefined() + }) + expect(screen.getByText(/not a backup/)).toBeDefined() + expect(screen.getByRole('link', { name: /back up your library/i })).toBeDefined() + }) + + it('shows a usable message when the estimate call fails', async () => { + mocks.readOriginStorage.mockResolvedValue({ + supported: true, + estimate: null, + persisted: false, + persistenceRequestSupported: true, + }) + render() + + await waitFor(() => { + expect(screen.getByText('Your browser did not return usable storage measurements.')).toBeDefined() + }) + }) + + it('keeps unknown origin estimates visibly unknown', async () => { + mocks.readOriginStorage.mockResolvedValue({ + supported: true, + estimate: { usageBytes: null, quotaBytes: null }, + persisted: null, + persistenceRequestSupported: false, + }) + render() + + await waitFor(() => { + expect(screen.getAllByText('Unavailable')).toHaveLength(2) + }) + expect(screen.queryByText('0 B')).toBeNull() + expect(screen.getByText('This browser cannot request persistent storage.')).toBeDefined() + }) }) + diff --git a/src/components/studio/views/settings-view.tsx b/src/components/studio/views/settings-view.tsx index 508b63a22..8ba3138e0 100644 --- a/src/components/studio/views/settings-view.tsx +++ b/src/components/studio/views/settings-view.tsx @@ -1,16 +1,21 @@ 'use client' import { useCallback, useEffect, useState } from 'react' -import { Database, HardDrive, RefreshCw, Trash2 } from 'lucide-react' +import { Database, Gauge, HardDrive, RefreshCw, ShieldAlert, ShieldCheck, Trash2 } from 'lucide-react' import { toast } from 'sonner' import { ViewHeader, VIEW_CONTAINER_CLASS } from '../ui/shared-primitives' import { cn } from '@/lib/utils' import { translate as t } from '@/lib/i18n/messages/settings' import { clearModelCache, + estimateUsagePercent, formatBytes, + isNearQuota, readModelCacheUsage, + readOriginStorage, + requestPersistence, type ModelCacheUsage, + type OriginStorageState, } from '@/lib/studio/storage-report' import { defaultVectorStore, @@ -48,22 +53,24 @@ const UsageList = ({ ) -/** Card header shared by the semantic-index and model-cache sections. */ +/** Card header shared by the semantic-index, origin-storage and model-cache sections. */ const SectionHeading = ({ icon: Icon, title, description, + headingId, }: { icon: typeof Database title: string description: string + headingId?: string }) => (
-

{title}

+

{title}

{description}

@@ -74,16 +81,20 @@ const PanelButton = ({ icon: Icon, label, onClick, + disabled = false, }: { icon: typeof Trash2 label: string onClick: () => void + disabled?: boolean }) => (