@equationalapplications/core-llm-wiki 7.5.0 → 7.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +93 -0
- package/dist/{chunk-3P7FAKJA.mjs → chunk-VOSMYISQ.mjs} +243 -41
- package/dist/chunk-VOSMYISQ.mjs.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +434 -41
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +196 -5
- package/dist/index.mjs.map +1 -1
- package/dist/{testing-ClpOUiLI.d.mts → testing-A4Sofxyo.d.mts} +136 -4
- package/dist/{testing-ClpOUiLI.d.ts → testing-A4Sofxyo.d.ts} +136 -4
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +236 -38
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-3P7FAKJA.mjs.map +0 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/db/schema.ts","../src/db/serializedAdapter.ts","../src/db/migrations.ts","../src/repositories/rowMappers.ts","../src/repositories/EntryRepository.ts","../src/repositories/OutboxRepository.ts","../src/repositories/SourceRefIndexRepository.ts","../src/repositories/TaskRepository.ts","../src/repositories/EventRepository.ts","../src/repositories/EdgeRepository.ts","../src/prompts/ontology.ts","../src/services/OntologyService.ts","../src/services/GraphTraversalService.ts","../src/db/okf-trust-writes.ts","../src/WikiMemory.ts","../src/utils/formatContext.ts","../src/utils/formatGraphContext.ts","../src/utils/sanitizeForFilename.ts","../src/utils/formatMemoryDump.ts","../src/utils/formatOkfBundle.ts","../src/utils/parseOkfBundle.ts","../src/librarianPrompt.ts","../src/index.ts"],"names":["isStaleAfter","deriveTrustTier","relatedLinksFor","latestVerified"],"mappings":";;;;;AAEA,eAAsB,aAAA,CAAc,IAAmB,MAAA,EAAgB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,QAAA,CAAS,aAAa,CAAA,EAAG;AACrC,IAAA,QAAA,CAAS,KAAK,yFAAyF,CAAA;AAAA,EACzG;AACA,EAAA,IAAI,CAAC,QAAA,CAAS,QAAA,CAAS,WAAW,CAAA,EAAG;AACnC,IAAA,QAAA,CAAS,KAAK,2FAA2F,CAAA;AAAA,EAC3G;AACA,EAAA,IAAI,QAAQ,SAAA,GAAY,CAAA,IAAK,CAAC,QAAA,CAAS,QAAA,CAAS,WAAW,CAAA,EAAG;AAC5D,IAAA,QAAA,CAAS,KAAK,oFAAoF,CAAA;AAAA,EACpG;AACA,EAAA,OAAO,QAAA;AACT;AAEO,SAAS,iCACd,OAAA,EACgE;AAChE,EAAA,MAAM,cAA8E,EAAC;AACrF,EAAA,IAAI,OAAA,CAAQ,aAAA,KAAkB,MAAA,EAAW,WAAA,CAAY,cAAc,OAAA,CAAQ,aAAA;AAC3E,EAAA,IAAI,OAAA,CAAQ,8BAA8B,MAAA,EAAW;AACnD,IAAA,WAAA,CAAY,4BAA4B,OAAA,CAAQ,yBAAA;AAAA,EAClD;AACA,EAAA,OAAO,WAAA;AACT;;;ACjCO,SAAS,UAAA,CAAW,IAAmB,OAAA,EAAkC;AAC9E,EAAA,OAAO,IAAI,UAAA,CAAW,EAAA,EAAI,OAAO,CAAA;AACnC","file":"index.mjs","sourcesContent":["import type { SQLiteAdapter } from '../types';\n\nexport async function setupDatabase(db: SQLiteAdapter, prefix: string) {\n await db.execAsync(`\n CREATE TABLE IF NOT EXISTS ${prefix}entries (\n id TEXT PRIMARY KEY,\n entity_id TEXT NOT NULL,\n title TEXT NOT NULL,\n body TEXT NOT NULL,\n tags TEXT NOT NULL DEFAULT '[]',\n confidence TEXT NOT NULL DEFAULT 'inferred',\n source_type TEXT NOT NULL DEFAULT 'librarian_inferred',\n source_hash TEXT,\n source_ref TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n last_accessed_at INTEGER,\n access_count INTEGER NOT NULL DEFAULT 0,\n deleted_at INTEGER,\n embedding TEXT,\n embedding_blob BLOB,\n okf_type TEXT,\n ontology_checked_at INTEGER,\n heal_checked_at INTEGER,\n lifecycle_status TEXT NOT NULL DEFAULT 'stable',\n stale_after INTEGER,\n generated_by TEXT,\n last_verified_at INTEGER,\n last_verified_by TEXT,\n okf_sources TEXT,\n okf_verified TEXT,\n okf_usage_window TEXT,\n embedding_failed_at INTEGER,\n embedding_failure_kind TEXT,\n embedding_attempts INTEGER NOT NULL DEFAULT 0\n );\n\n CREATE INDEX IF NOT EXISTS ${prefix}entries_entity_idx ON ${prefix}entries(entity_id);\n CREATE INDEX IF NOT EXISTS ${prefix}entries_source_ref_idx ON ${prefix}entries(entity_id, source_ref);\n CREATE INDEX IF NOT EXISTS ${prefix}entries_source_hash_idx ON ${prefix}entries(entity_id, source_hash) WHERE source_hash IS NOT NULL;\n CREATE INDEX IF NOT EXISTS ${prefix}entries_updated_idx ON ${prefix}entries(updated_at DESC);\n\n -- source_ref_index: per-(entity, source_hash) record of the canonical sourceRef\n -- currently holding that hash. The partial UNIQUE index on (entity_id, source_hash)\n -- WHERE deleted_at IS NULL enforces the sourceRef-level TOCTOU-race invariant;\n -- entries-level uniqueness cannot express it because a single ingestDocument call\n -- writes N facts that all share (entity_id, source_ref, source_hash). See\n -- docs/superpowers/specs/2026-08-07-dependabot-concurrency-release-hygiene-design.md §B1.\n CREATE TABLE IF NOT EXISTS ${prefix}source_ref_index (\n id TEXT PRIMARY KEY,\n entity_id TEXT NOT NULL,\n source_hash TEXT NOT NULL,\n source_ref TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n deleted_at INTEGER\n );\n CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_ref_hash\n ON ${prefix}source_ref_index (entity_id, source_hash)\n WHERE deleted_at IS NULL;\n\n CREATE TABLE IF NOT EXISTS ${prefix}tasks (\n id TEXT PRIMARY KEY,\n entity_id TEXT NOT NULL,\n description TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'pending',\n priority INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n resolved_at INTEGER,\n deleted_at INTEGER,\n okf_type TEXT,\n lifecycle_status TEXT NOT NULL DEFAULT 'stable',\n stale_after INTEGER,\n generated_by TEXT,\n last_verified_at INTEGER,\n last_verified_by TEXT,\n okf_sources TEXT,\n okf_verified TEXT,\n okf_usage_window TEXT\n );\n\n CREATE INDEX IF NOT EXISTS ${prefix}tasks_entity_idx ON ${prefix}tasks(entity_id, status);\n\n CREATE TABLE IF NOT EXISTS ${prefix}edges (\n id TEXT PRIMARY KEY,\n entity_id TEXT NOT NULL,\n source_id TEXT NOT NULL,\n target_id TEXT NOT NULL,\n edge_type TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n UNIQUE(entity_id, source_id, target_id, edge_type)\n );\n\n CREATE INDEX IF NOT EXISTS ${prefix}edges_entity_idx ON ${prefix}edges(entity_id);\n\n CREATE TABLE IF NOT EXISTS ${prefix}events (\n id TEXT PRIMARY KEY,\n entity_id TEXT NOT NULL,\n event_type TEXT NOT NULL,\n summary TEXT NOT NULL,\n related_entry_id TEXT,\n created_at INTEGER NOT NULL\n );\n\n CREATE INDEX IF NOT EXISTS ${prefix}events_entity_idx ON ${prefix}events(entity_id, created_at DESC);\n\n CREATE TABLE IF NOT EXISTS ${prefix}checkpoints (\n entity_id TEXT PRIMARY KEY,\n heal_checkpoint INTEGER NOT NULL DEFAULT 0,\n memory_checkpoint INTEGER NOT NULL DEFAULT 0\n );\n\n CREATE TABLE IF NOT EXISTS ${prefix}entity_manifests (\n entity_id TEXT PRIMARY KEY,\n mode TEXT NOT NULL DEFAULT 'off',\n manifest_json TEXT NOT NULL DEFAULT '{\"node_types\":[],\"edge_types\":[]}',\n updated_at INTEGER NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS ${prefix}meta (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS ${prefix}outbox (\n id TEXT PRIMARY KEY,\n entity_id TEXT NOT NULL,\n table_name TEXT NOT NULL,\n record_id TEXT NOT NULL,\n operation TEXT NOT NULL,\n payload TEXT NOT NULL,\n created_at INTEGER NOT NULL\n );\n\n CREATE INDEX IF NOT EXISTS ${prefix}outbox_entity_id_created_at\n ON ${prefix}outbox (entity_id, created_at);\n\n CREATE INDEX IF NOT EXISTS ${prefix}outbox_created_at\n ON ${prefix}outbox (created_at);\n `);\n\n // OKF v0.2 indexes — gated on column existence so we never try to create an\n // index on a column that hasn't been added yet (upgrade-from-pre-v10 case).\n // The columns themselves are in the CREATE TABLE above (fresh installs get\n // them directly) and in migration v10 (upgrades get them via ALTER TABLE).\n // The migration also creates these same indexes, so the IF NOT EXISTS guard\n // makes either path safe.\n await createOkfV02IndexesIfColumnsExist(db, prefix);\n}\n\nasync function createOkfV02IndexesIfColumnsExist(db: SQLiteAdapter, prefix: string): Promise<void> {\n for (const table of ['entries', 'tasks'] as const) {\n const cols = await db.getAllAsync<{ name: string }>(\n `PRAGMA table_info(${prefix}${table})`\n );\n const colNames = new Set(cols.map((c) => c.name));\n if (colNames.has('lifecycle_status')) {\n await db.execAsync(`CREATE INDEX IF NOT EXISTS ${prefix}${table}_lifecycle_status_idx ON ${prefix}${table}(lifecycle_status);`);\n }\n if (colNames.has('stale_after')) {\n await db.execAsync(`CREATE INDEX IF NOT EXISTS ${prefix}${table}_stale_after_idx ON ${prefix}${table}(stale_after);`);\n }\n if (colNames.has('last_verified_at')) {\n await db.execAsync(`CREATE INDEX IF NOT EXISTS ${prefix}${table}_last_verified_at_idx ON ${prefix}${table}(last_verified_at);`);\n }\n }\n}\n","import type { SQLiteAdapter } from '../types';\nimport { WikiTransactionError } from '../types';\nimport { extractSqliteCode } from './sqliteCodes';\n\nexport { extractSqliteCode };\n\n/** True when `err` carries a parseable SQLite code — gates whether the wrapper re-wraps. */\nexport function isDriverError(err: unknown): boolean {\n return extractSqliteCode(err) !== undefined;\n}\n\n/**\n * Returns an adapter with the given methods overridden, delegating everything else\n * (own or class-prototype methods) to `target`.\n *\n * Uses a `Proxy` rather than `Object.create`/object-spread: delegated methods are\n * bound to `target` before being returned, so their receiver (`this`) stays the\n * original adapter instance. That keeps ES `#private` fields and `instanceof`/identity\n * checks inside those methods working — `Object.create` would invoke them with the\n * wrapper as `this` and break both.\n */\nfunction withOverrides(target: SQLiteAdapter, overrides: Partial<SQLiteAdapter>): SQLiteAdapter {\n return new Proxy(target, {\n get(obj, prop, receiver) {\n if (prop in overrides) return Reflect.get(overrides, prop, receiver);\n const value = Reflect.get(obj, prop, obj);\n return typeof value === 'function' ? value.bind(obj) : value;\n },\n }) as SQLiteAdapter;\n}\n\n/**\n * Returns the same adapter with `withTransactionAsync` overridden to throw. Injected\n * by the serialized wrapper onto the `tx` handed to every callback so a *nested*\n * transaction fails loudly instead of deadlocking against the mutex.\n */\nexport function guardReentrancy(tx: SQLiteAdapter): SQLiteAdapter {\n return withOverrides(tx, {\n withTransactionAsync() {\n throw new Error(\n 'Nested withTransactionAsync is not supported: you are already ' +\n 'inside a transaction. Pass the current `tx` down instead of ' +\n 'opening a new transaction.'\n );\n },\n });\n}\n\nconst DEADLOCK_WARN_MS = 10_000;\n\n/**\n * Wraps `withTransactionAsync` in a promise-chain mutex so transactions on the\n * single shared connection run one at a time. Non-transactional reads/writes are\n * untouched. Applied once in the WikiMemory constructor before the adapter reaches\n * any repository or service.\n */\nexport function withSerializedTransactions(db: SQLiteAdapter): SQLiteAdapter {\n let queue: Promise<unknown> = Promise.resolve();\n return withOverrides(db, {\n withTransactionAsync<T>(fn: (tx: SQLiteAdapter) => Promise<T>): Promise<T> {\n // Warns if a call waits >10s for the lock — the signature of the closure-capture\n // deadlock (calling the outer `db` instead of `tx` inside a callback). Cleared the\n // instant the lock is acquired, so it measures queue wait only.\n const warn = setTimeout(() => {\n console.warn(\n '[core-llm-wiki] Transaction queued >10s — possible deadlock. ' +\n 'Inside a transaction callback, use the `tx` parameter, never the ' +\n 'outer database handle.'\n );\n }, DEADLOCK_WARN_MS);\n\n const run = queue\n .catch(() => undefined) // proceed from a settled state; swallow prior outcome\n .then(() => {\n clearTimeout(warn);\n // Re-wrap the tx so a nested withTransactionAsync throws synchronously.\n // Some adapters invoke the callback with no tx handle; fall back to the\n // outer db (same connection). The guard still blocks nested transactions.\n return db.withTransactionAsync((tx) => fn(guardReentrancy(tx ?? db)));\n })\n .catch((e) => {\n // Wrap only driver errors; domain errors reach the caller with instanceof intact.\n throw isDriverError(e)\n ? new WikiTransactionError('Transaction failed', { cause: e })\n : e;\n });\n\n queue = run; // advance the tail; next caller's leading .catch() absorbs this rejection\n return run as Promise<T>;\n },\n });\n}\n","import type { SQLiteAdapter } from '../types';\n\nexport interface Migration {\n version: number;\n description: string;\n run: (db: SQLiteAdapter, prefix: string) => Promise<void>;\n}\n\nexport const MIGRATIONS: Migration[] = [\n {\n version: 1,\n description: 'Rebuild FTS5 with porter unicode61 tokenizer (superseded by v2)',\n run: async (_db, _prefix) => {\n // This migration is superseded by v2 which drops FTS5 entirely.\n // It is kept as a no-op so upgrade paths from v0 do not require FTS5 support.\n },\n },\n {\n version: 2,\n description: 'Remove FTS5; add embedding column for semantic retrieval',\n run: async (db, prefix) => {\n // Drop FTS5 artifacts in a transaction.\n await db.withTransactionAsync(async (tx) => {\n await tx.execAsync(`\n DROP TRIGGER IF EXISTS ${prefix}entries_ai;\n DROP TRIGGER IF EXISTS ${prefix}entries_ad;\n DROP TRIGGER IF EXISTS ${prefix}entries_au;\n DROP TABLE IF EXISTS ${prefix}entries_fts;\n `);\n });\n // ALTER TABLE ADD COLUMN must run outside any explicit transaction —\n // SQLite (and expo-sqlite) do not permit schema alterations inside\n // a BEGIN...COMMIT block.\n const cols = await db.getAllAsync<{ name: string }>(\n `PRAGMA table_info(${prefix}entries)`\n );\n if (!cols.some(c => c.name === 'embedding')) {\n await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN embedding TEXT`);\n }\n },\n },\n {\n version: 3,\n description: 'Add embedding_blob BLOB column for Float32Array vector storage',\n run: async (db, prefix) => {\n const cols = await db.getAllAsync<{ name: string }>(\n `PRAGMA table_info(${prefix}entries)`\n );\n if (!cols.some(c => c.name === 'embedding_blob')) {\n await db.execAsync(\n `ALTER TABLE ${prefix}entries ADD COLUMN embedding_blob BLOB`\n );\n }\n },\n },\n {\n version: 4,\n description: 'Create outbox table for change data capture',\n run: async (db, prefix) => {\n await db.execAsync(`\n CREATE TABLE IF NOT EXISTS ${prefix}outbox (\n id TEXT PRIMARY KEY,\n entity_id TEXT NOT NULL,\n table_name TEXT NOT NULL,\n record_id TEXT NOT NULL,\n operation TEXT NOT NULL,\n payload TEXT NOT NULL,\n created_at INTEGER NOT NULL\n );\n CREATE INDEX IF NOT EXISTS ${prefix}outbox_entity_id_created_at\n ON ${prefix}outbox (entity_id, created_at);\n `);\n },\n },\n {\n version: 5,\n description: 'Add okf_type to entries/tasks for OKF type fidelity; create edges table for OKF graph import',\n run: async (db, prefix) => {\n for (const table of ['entries', 'tasks'] as const) {\n const cols = await db.getAllAsync<{ name: string }>(\n `PRAGMA table_info(${prefix}${table})`\n );\n if (!cols.some(c => c.name === 'okf_type')) {\n await db.execAsync(`ALTER TABLE ${prefix}${table} ADD COLUMN okf_type TEXT`);\n }\n }\n await db.execAsync(`\n CREATE TABLE IF NOT EXISTS ${prefix}edges (\n id TEXT PRIMARY KEY,\n entity_id TEXT NOT NULL,\n source_id TEXT NOT NULL,\n target_id TEXT NOT NULL,\n edge_type TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n UNIQUE(entity_id, source_id, target_id, edge_type)\n );\n CREATE INDEX IF NOT EXISTS ${prefix}edges_entity_idx ON ${prefix}edges (entity_id);\n `);\n },\n },\n {\n version: 6,\n description: 'Add entity_manifests table for per-entity ontology state',\n run: async (db, prefix) => {\n await db.execAsync(`\n CREATE TABLE IF NOT EXISTS ${prefix}entity_manifests (\n entity_id TEXT PRIMARY KEY,\n mode TEXT NOT NULL DEFAULT 'off',\n manifest_json TEXT NOT NULL DEFAULT '{\"node_types\":[],\"edge_types\":[]}',\n updated_at INTEGER NOT NULL\n );\n `);\n },\n },\n {\n version: 7,\n description: 'Add ontology_checked_at to entries for ontology backfill recheck cooldown',\n run: async (db, prefix) => {\n // ALTER TABLE ADD COLUMN must run outside any explicit transaction —\n // SQLite (and expo-sqlite) do not permit schema alterations inside\n // a BEGIN...COMMIT block. Same pattern as v2/v3/v5.\n const cols = await db.getAllAsync<{ name: string }>(\n `PRAGMA table_info(${prefix}entries)`\n );\n if (!cols.some(c => c.name === 'ontology_checked_at')) {\n await db.execAsync(\n `ALTER TABLE ${prefix}entries ADD COLUMN ontology_checked_at INTEGER`\n );\n }\n },\n },\n {\n version: 8,\n description: 'Add heal_checked_at to entries for heal recheck cooldown',\n run: async (db, prefix) => {\n // ALTER TABLE ADD COLUMN must run outside any explicit transaction —\n // SQLite (and expo-sqlite) do not permit schema alterations inside\n // a BEGIN...COMMIT block. Same pattern as v2/v3/v5/v7.\n const cols = await db.getAllAsync<{ name: string }>(\n `PRAGMA table_info(${prefix}entries)`\n );\n if (!cols.some(c => c.name === 'heal_checked_at')) {\n await db.execAsync(\n `ALTER TABLE ${prefix}entries ADD COLUMN heal_checked_at INTEGER`\n );\n }\n },\n },\n {\n version: 9,\n description: 'add_source_ref_index',\n run: async (db, prefix) => {\n // Defense-in-depth safety net for the #79 TOCTOU race fix. The original\n // design put a UNIQUE index on `entries(entity_id, source_hash)`, but\n // that conflates per-fact and per-sourceRef granularity: a single\n // `ingestDocument` writes N facts that all share\n // (entity_id, source_ref, source_hash), and the 2nd–Nth inserts hit\n // SQLITE_CONSTRAINT_UNIQUE inside the normal multi-fact path. The\n // correct invariant is \"at most one sourceRef per (entity, hash)\", so\n // the constraint lives on a dedicated per-(entity, hash) table that\n // records the canonical sourceRef for each hash. See\n // docs/superpowers/specs/2026-08-07-dependabot-concurrency-release-hygiene-design.md §B1.\n //\n // Abort path: if any (entity_id, source_hash) already has live rows\n // under multiple distinct source_refs, a previous race beat the new\n // app-level guard. The migration aborts with an actionable error\n // rather than auto-resolving — auto-resolving would either destroy\n // facts or pick a wrong canonical, both worse than failing safe. The\n // thrown error escapes setup() BEFORE the CREATE TABLE runs, so the\n // new table is never created and schema_version is never advanced.\n const duplicates = await db.getAllAsync<{ entity_id: string; source_hash: string; n_refs: number }>(\n `SELECT entity_id, source_hash, COUNT(DISTINCT source_ref) AS n_refs\n FROM ${prefix}entries\n WHERE deleted_at IS NULL AND source_hash IS NOT NULL\n GROUP BY entity_id, source_hash\n HAVING COUNT(DISTINCT source_ref) > 1`\n );\n if (duplicates.length > 0) {\n const sample = duplicates\n .slice(0, 5)\n .map(d => `(entity_id=${d.entity_id}, source_hash=${d.source_hash.slice(0, 12)}…, n_refs=${d.n_refs})`)\n .join(', ');\n throw new Error(\n `Migration v9 (add_source_ref_index) failed: existing live rows have multiple sourceRefs sharing a hash. ` +\n `Found ${duplicates.length} duplicate (entity_id, source_hash) groups. ` +\n `First ${Math.min(5, duplicates.length)}: ${sample}. ` +\n `Resolve each by calling forget({ sourceRef: <loser> }) for the offending sourceRef, then re-run setup.`\n );\n }\n await db.execAsync(\n `CREATE TABLE IF NOT EXISTS ${prefix}source_ref_index (\n id TEXT PRIMARY KEY,\n entity_id TEXT NOT NULL,\n source_hash TEXT NOT NULL,\n source_ref TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n deleted_at INTEGER\n );\n CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_ref_hash\n ON ${prefix}source_ref_index (entity_id, source_hash)\n WHERE deleted_at IS NULL;`\n );\n // Backfill: for each (entity_id, source_hash) group with live entries,\n // pick the sourceRef of the entry that wins\n // `ROW_NUMBER() OVER (PARTITION BY entity_id, source_hash ORDER BY updated_at ASC, id ASC) = 1`.\n // The tie-breaker `id ASC` matches `findLatestSourceHash` ordering so\n // the canonical row is deterministic. INSERT OR IGNORE with a\n // deterministic ID (`sri_<entity_id>:<source_hash>`) makes the backfill\n // idempotent — re-running v9 is a no-op.\n await db.execAsync(\n `INSERT OR IGNORE INTO ${prefix}source_ref_index (id, entity_id, source_hash, source_ref, created_at, deleted_at)\n SELECT\n 'sri:' || entity_id || ':' || source_hash,\n entity_id,\n source_hash,\n source_ref,\n updated_at,\n NULL\n FROM (\n SELECT\n entity_id, source_hash, source_ref, updated_at,\n ROW_NUMBER() OVER (\n PARTITION BY entity_id, source_hash\n ORDER BY updated_at ASC, id ASC\n ) AS rn\n FROM ${prefix}entries\n WHERE deleted_at IS NULL\n AND source_hash IS NOT NULL\n AND source_ref IS NOT NULL\n ) ranked\n WHERE rn = 1;`\n );\n },\n },\n {\n version: 10,\n description: 'OKF v0.2: add lifecycle_status, stale_after, generated_by, last_verified_*, okf_sources, okf_verified, okf_usage_window to entries and tasks',\n run: async (db, prefix) => {\n // ALTER TABLE ADD COLUMN must run outside any explicit transaction — same constraint\n // as v2/v3/v5/v7/v8. We do all eight columns per table, then indexes, inside\n // a single execAsync batch where possible. SQLite ALTER on the same table from\n // separate statements is fine; we just can't wrap it in BEGIN...COMMIT.\n for (const table of ['entries', 'tasks'] as const) {\n const cols = await db.getAllAsync<{ name: string }>(\n `PRAGMA table_info(${prefix}${table})`\n );\n const existing = new Set(cols.map((c) => c.name));\n const adds: Array<[string, string]> = [\n ['lifecycle_status', `ALTER TABLE ${prefix}${table} ADD COLUMN lifecycle_status TEXT NOT NULL DEFAULT 'stable'`],\n ['stale_after', `ALTER TABLE ${prefix}${table} ADD COLUMN stale_after INTEGER`],\n ['generated_by', `ALTER TABLE ${prefix}${table} ADD COLUMN generated_by TEXT`],\n ['last_verified_at', `ALTER TABLE ${prefix}${table} ADD COLUMN last_verified_at INTEGER`],\n ['last_verified_by', `ALTER TABLE ${prefix}${table} ADD COLUMN last_verified_by TEXT`],\n ['okf_sources', `ALTER TABLE ${prefix}${table} ADD COLUMN okf_sources TEXT`],\n ['okf_verified', `ALTER TABLE ${prefix}${table} ADD COLUMN okf_verified TEXT`],\n ['okf_usage_window', `ALTER TABLE ${prefix}${table} ADD COLUMN okf_usage_window TEXT`],\n ];\n for (const [name, sql] of adds) {\n if (!existing.has(name)) await db.execAsync(sql);\n }\n }\n await db.execAsync(`\n CREATE INDEX IF NOT EXISTS ${prefix}entries_lifecycle_status_idx ON ${prefix}entries(lifecycle_status);\n CREATE INDEX IF NOT EXISTS ${prefix}entries_stale_after_idx ON ${prefix}entries(stale_after);\n CREATE INDEX IF NOT EXISTS ${prefix}entries_last_verified_at_idx ON ${prefix}entries(last_verified_at);\n CREATE INDEX IF NOT EXISTS ${prefix}tasks_lifecycle_status_idx ON ${prefix}tasks(lifecycle_status);\n CREATE INDEX IF NOT EXISTS ${prefix}tasks_stale_after_idx ON ${prefix}tasks(stale_after);\n CREATE INDEX IF NOT EXISTS ${prefix}tasks_last_verified_at_idx ON ${prefix}tasks(last_verified_at);\n `);\n },\n },\n {\n version: 11,\n description: 'Add embedding_failed_at, embedding_failure_kind, embedding_attempts to entries for embed retry state',\n run: async (db, prefix) => {\n // ALTER TABLE ADD COLUMN must run outside any explicit transaction —\n // SQLite (and expo-sqlite) do not permit schema alterations inside\n // a BEGIN...COMMIT block. Same pattern as v2/v3/v5/v7/v8/v10.\n // Only the entries table gets these columns — tasks are never embedded.\n const cols = await db.getAllAsync<{ name: string }>(\n `PRAGMA table_info(${prefix}entries)`\n );\n const existing = new Set(cols.map((c) => c.name));\n const adds: Array<[string, string]> = [\n ['embedding_failed_at', `ALTER TABLE ${prefix}entries ADD COLUMN embedding_failed_at INTEGER`],\n ['embedding_failure_kind', `ALTER TABLE ${prefix}entries ADD COLUMN embedding_failure_kind TEXT`],\n ['embedding_attempts', `ALTER TABLE ${prefix}entries ADD COLUMN embedding_attempts INTEGER NOT NULL DEFAULT 0`],\n ];\n for (const [name, sql] of adds) {\n if (!existing.has(name)) await db.execAsync(sql);\n }\n },\n },\n];\n\n// Verify MIGRATIONS are in strictly ascending version order at module load time.\n// This prevents skipped or repeated migrations caused by out-of-order entries.\nfor (let i = 1; i < MIGRATIONS.length; i++) {\n if (MIGRATIONS[i].version <= MIGRATIONS[i - 1].version) {\n throw new Error(\n `migrations.ts: MIGRATIONS must be in strictly ascending version order. ` +\n `Found version ${MIGRATIONS[i].version} after ${MIGRATIONS[i - 1].version} at index ${i}.`\n );\n }\n}\n\n// Derived from the last (highest) migration version so it never drifts out of sync.\nexport const CURRENT_SCHEMA_VERSION =\n MIGRATIONS.length > 0 ? MIGRATIONS[MIGRATIONS.length - 1].version : 0;\n","/**\n * Shared JSON column parsers for repository row mappers.\n *\n * SQLite JSON1 columns return a string when read; in-memory callers expect the\n * parsed value. The parsers tolerate both shapes so callers stay\n * implementation-agnostic (e.g. tests pass arrays directly, drivers return\n * strings). Hoisted to module scope so each row mapping doesn't reallocate\n * two closures (was the case before refactor — see #90 review).\n */\n\nexport function parseJsonArray<T>(s: unknown, fallback: T[]): T[] {\n if (Array.isArray(s)) return s as T[];\n if (typeof s === 'string' && s.length > 0) {\n try {\n const p = JSON.parse(s);\n if (Array.isArray(p)) return p as T[];\n } catch {\n // fall through to fallback\n }\n }\n return fallback;\n}\n\n/**\n * Arrays are rejected in both branches: `typeof [] === 'object'`, so a\n * malformed `okf_usage_window` of `[]` would otherwise be handed back as an\n * object and re-exported with an invalid shape (see #90 review).\n */\nexport function parseJsonObject<T>(s: unknown, fallback: T | null = null): T | null {\n if (s && typeof s === 'object' && !Array.isArray(s)) return s as T;\n if (typeof s === 'string' && s.length > 0) {\n try {\n const p = JSON.parse(s);\n if (p && typeof p === 'object' && !Array.isArray(p)) return p as T;\n } catch {\n // fall through to fallback\n }\n }\n return fallback;\n}\n","import type { SQLiteAdapter, WikiFact, EmbeddingMarkerKind } from '../types';\nimport { WikiGraphNodeOwnershipConflict } from '../types';\nimport { BaseRepository } from './BaseRepository';\nimport { OutboxRepository } from './OutboxRepository';\nimport { parseJsonArray, parseJsonObject } from './rowMappers';\nimport { isStaleAfter, deriveTrustTier } from '@equationalapplications/core-okf';\n\nexport type EntryRowMetadata = {\n id: string;\n entity_id: string;\n updated_at: number | null;\n access_count: number | null;\n};\n\nexport type EntryRowWithEmbeddings = EntryRowMetadata & {\n embedding_blob: Uint8Array | null;\n embedding: string | null;\n};\n\n/**\n * One row of the reembed candidate scan. `findAllForReembed` does `SELECT *`,\n * so the marker columns come back at runtime; naming them here makes that\n * dependency visible to the compiler instead of hiding it behind a cast in\n * MaintenanceService.runReembed (spec §4.4).\n */\nexport type ReembedCandidateRow = WikiFact & {\n embedding_blob?: Uint8Array | null;\n embedding_failed_at?: number | null;\n embedding_failure_kind?: string | null;\n embedding_attempts?: number | null;\n};\n\nfunction mapRowToFact(row: any): WikiFact {\n const tags: string[] = (() => {\n if (Array.isArray(row.tags)) return row.tags;\n try { const p = JSON.parse(row.tags as string); if (Array.isArray(p)) return p; } catch {}\n return [];\n })();\n\n const okf_verified = parseJsonArray<NonNullable<WikiFact['okf_verified']>[number]>(row.okf_verified, []);\n // Hydrate per spec §2.7 + §5.3: surface isStale/trustTier so hosts don't have to\n // re-call the core-okf helpers. Sampled once per row rather than once per call\n // because `now` here means \"as of this hydration\" — using a stable per-call\n // value would shift staleness while we're mapping sibling rows in the same\n // read. Date.now() is cheap enough that per-row sampling is fine.\n const now = Date.now();\n const staleAfterRaw = row.stale_after != null ? Number(row.stale_after) : null;\n\n return {\n id: row.id,\n entity_id: row.entity_id,\n title: row.title,\n body: row.body,\n tags,\n confidence: row.confidence,\n source_type: row.source_type,\n source_hash: row.source_hash ?? null,\n source_ref: row.source_ref ?? null,\n created_at: Number(row.created_at),\n updated_at: Number(row.updated_at),\n last_accessed_at: (row.last_accessed_at === null || row.last_accessed_at === undefined)\n ? null\n : Number(row.last_accessed_at),\n deleted_at: row.deleted_at != null ? Number(row.deleted_at) : null,\n access_count: Number(row.access_count ?? 0),\n okf_type: row.okf_type ?? null,\n // OKF v0.2\n lifecycle_status: (row.lifecycle_status ?? 'stable') as WikiFact['lifecycle_status'],\n stale_after: staleAfterRaw,\n generated_by: row.generated_by ?? null,\n okf_sources: parseJsonArray<NonNullable<WikiFact['okf_sources']>[number]>(row.okf_sources, []),\n okf_verified,\n okf_usage_window: parseJsonObject<NonNullable<WikiFact['okf_usage_window']>>(row.okf_usage_window),\n last_verified_at: row.last_verified_at != null ? Number(row.last_verified_at) : null,\n last_verified_by: row.last_verified_by ?? null,\n // Spec §2.7 + §5.3: hydrate so read() consumers don't re-call the helpers.\n isStale: isStaleAfter(staleAfterRaw, now),\n trustTier: deriveTrustTier(okf_verified),\n };\n}\n\nfunction normalizeEmbeddingBlobValue(blob: unknown): Uint8Array | null {\n if (blob instanceof Uint8Array) return blob;\n if (blob !== null && blob !== undefined && typeof blob === 'object') {\n const obj = blob as Record<string, unknown>;\n if (obj['type'] === 'Buffer' && Array.isArray(obj['data'])) {\n return new Uint8Array(obj['data'] as number[]);\n }\n const entries = Object.keys(obj);\n if (entries.length > 0 && entries.every((k) => /^\\d+$/.test(k))) {\n const len = entries.length;\n const arr = new Uint8Array(len);\n for (let i = 0; i < len; i++) arr[i] = (obj[String(i)] as number) ?? 0;\n return arr;\n }\n }\n return null;\n}\n\n/** Mapper that preserves embedding_blob for export/import round-tripping. */\nfunction mapRowToFactWithBlobs(row: any): WikiFact {\n const base = mapRowToFact(row);\n const embeddingBlob = normalizeEmbeddingBlobValue(row.embedding_blob);\n return embeddingBlob ? { ...base, embedding_blob: embeddingBlob } : base;\n}\n\n\nexport class EntryRepository extends BaseRepository {\n private chunkSize = 500;\n\n constructor(db: SQLiteAdapter, prefix: string, private outbox: OutboxRepository) {\n super(db, prefix);\n }\n\n /**\n * Fetch facts by IDs, optionally scoped to entity IDs.\n * Returns facts in the order of the input IDs (first match wins).\n */\n async findByIds(\n ids: readonly string[],\n scopedEntityIds?: readonly string[],\n tx?: SQLiteAdapter,\n ): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n const rows: any[] = [];\n const entityClause = scopedEntityIds && scopedEntityIds.length > 0\n ? ` AND entity_id IN (${scopedEntityIds.map(() => '?').join(',')})`\n : '';\n const entityParams = scopedEntityIds ?? [];\n\n for (let i = 0; i < ids.length; i += this.chunkSize) {\n const chunk = ids.slice(i, i + this.chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n const chunkRows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries WHERE id IN (${placeholders})${entityClause} AND deleted_at IS NULL`,\n [...chunk, ...entityParams],\n );\n rows.push(...chunkRows);\n }\n\n const byId = new Map(rows.map(r => [r.id, r]));\n return ids\n .map(id => byId.get(id))\n .filter((r): r is any => r !== undefined)\n .map(mapRowToFact);\n }\n\n /**\n * Upsert a WikiFact. Nullable fields set to null when fact value is null.\n * Returns { changes, lastInsertRowId }.\n * `tx` is REQUIRED to ensure atomic outbox staging.\n *\n * OKF metadata discipline (spec §2.5 + DAO checklist §8): content writes\n * MUST NOT silently overwrite OKF metadata that a caller didn't supply. The\n * previous CASE WHEN IS NULL guards around `lifecycle_status`, etc. were\n * dead because the bind always supplied a non-null value (notably\n * `fact.lifecycle_status ?? 'stable'`), so excluded.X was never NULL and\n * an UPDATE rewrote an existing `deprecated` row to `stable`. We now omit\n * these columns from the SET clause entirely — SQLite's ON CONFLICT UPDATE\n * leaves untouched columns at their existing row value, which is exactly\n * the preservation semantics we want for content writes. Callers that\n * intentionally want to overwrite OKF metadata should use\n * {@link upsertForImport} (always-replace semantics for that path).\n * New-row INSERTs still bind a value so the column is populated; if the\n * caller supplied nothing, the schema DEFAULT 'stable' applies when the\n * bind is bound as 'stable' explicitly here.\n *\n * Marker discipline (spec §4.1): a conflict carrying a real\n * `embedding_blob` clears the embedding failure markers, because the row now\n * HAS a valid embedding and a surviving marker would be a self-contradictory\n * diagnostic that inflates runReembed's permanentlyFailed counter. A conflict\n * with no blob leaves marker state alone, matching the \"absent means don't\n * touch\" semantics used for embedding_blob itself.\n *\n * Graph node ownership (spec §2.4 + §3, REQ-OWN-01 + REQ-GRAPH-01): entry\n * IDs share one database-wide namespace, so an ID stays owned by its\n * existing entity for as long as the row exists — soft deletion included.\n * The pre-write lookup already reads the existing row for OKF metadata; we\n * project `entity_id` off that same SELECT and reject the write before\n * any outbox payload construction when the stored owner differs from\n * `fact.entity_id`. Soft-deleted foreign rows keep their IDs reserved;\n * permanent reservation is NOT introduced, so a physically absent ID may\n * still be inserted under the requested entity. The ON CONFLICT UPDATE SET\n * clause carries a final `WHERE entries.entity_id = excluded.entity_id`\n * guard so the database itself refuses a cross-owner row overwrite even if\n * a future caller bypasses the pre-write check. When `runAsync` reports\n * 0 changes (a legitimate conflict-suppressed write, OR an adapter that\n * under-reports a permitted write) we re-read the stored owner; only a\n * foreign owner throws — this is local defensive behavior, not permission\n * for adapters to under-report. The thrown error is\n * `WikiGraphNodeOwnershipConflict` (no owner, node ID, or stored content\n * is disclosed). Upserts that pass both gates retain existing same-entity\n * update + resurrection semantics.\n */\n async upsert(fact: WikiFact, tx: SQLiteAdapter): Promise<{ changes: number; lastInsertRowId: number }> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n const tagsJson = JSON.stringify(fact.tags);\n const embeddingBlob = this.normalizeEmbeddingBlob(fact.embedding_blob);\n\n const existingRow = await executor.getFirstAsync<{\n id: string;\n entity_id: string;\n lifecycle_status: string;\n stale_after: number | null;\n generated_by: string | null;\n okf_sources: string | null;\n okf_verified: string | null;\n okf_usage_window: string | null;\n last_verified_at: number | null;\n last_verified_by: string | null;\n }>(\n `SELECT id, entity_id, lifecycle_status, stale_after, generated_by,\n okf_sources, okf_verified, okf_usage_window,\n last_verified_at, last_verified_by\n FROM ${this.prefix}entries WHERE id = ?`,\n [fact.id],\n );\n\n // Entry IDs share one global namespace, so an ID stays owned by its\n // existing entity for as long as the row exists — soft deletion included.\n // Reject here, before any write or outbox payload construction. This costs\n // one extra column on a SELECT the method already ran, not a new query.\n if (existingRow && existingRow.entity_id !== fact.entity_id) {\n throw new WikiGraphNodeOwnershipConflict();\n }\n\n const operation = fact.deleted_at ? 'DELETE' : (existingRow ? 'UPDATE' : 'INSERT');\n\n const result = await executor.runAsync(\n `INSERT INTO ${this.prefix}entries (\n id, entity_id, title, body, tags, confidence, source_type,\n source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,\n deleted_at, embedding_blob, embedding, okf_type,\n lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,\n okf_sources, okf_verified, okf_usage_window\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n title = excluded.title,\n body = excluded.body,\n tags = excluded.tags,\n confidence = excluded.confidence,\n source_type = excluded.source_type,\n source_hash = excluded.source_hash,\n source_ref = excluded.source_ref,\n updated_at = excluded.updated_at,\n last_accessed_at = excluded.last_accessed_at,\n access_count = excluded.access_count,\n deleted_at = excluded.deleted_at,\n embedding_blob = CASE WHEN excluded.embedding_blob IS NULL THEN embedding_blob ELSE excluded.embedding_blob END,\n embedding = NULL,\n embedding_failed_at = CASE WHEN excluded.embedding_blob IS NOT NULL THEN NULL ELSE embedding_failed_at END,\n embedding_failure_kind = CASE WHEN excluded.embedding_blob IS NOT NULL THEN NULL ELSE embedding_failure_kind END,\n embedding_attempts = CASE WHEN excluded.embedding_blob IS NOT NULL THEN 0 ELSE embedding_attempts END,\n okf_type = excluded.okf_type\n WHERE ${this.prefix}entries.entity_id = excluded.entity_id`,\n [\n fact.id,\n fact.entity_id,\n fact.title,\n fact.body,\n tagsJson,\n fact.confidence,\n fact.source_type,\n fact.source_hash,\n fact.source_ref,\n fact.created_at,\n now,\n fact.last_accessed_at === null ? null : fact.last_accessed_at,\n fact.access_count,\n fact.deleted_at ?? null,\n embeddingBlob ?? null,\n null,\n fact.okf_type ?? null,\n // OKF v0.2 metadata — bound for INSERT only; ON CONFLICT UPDATE\n // preserves the existing row values (these columns are intentionally\n // absent from the SET clause above).\n fact.lifecycle_status ?? 'stable',\n fact.stale_after ?? null,\n fact.generated_by ?? null,\n fact.last_verified_at ?? null,\n fact.last_verified_by ?? null,\n fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,\n fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,\n fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,\n ],\n );\n\n // A suppressed conflict-update reports 0 (see the SQLiteAdapter contract).\n // A permitted write that an adapter under-reports as 0 also lands here, so\n // confirm ownership from the stored row rather than inferring it from the\n // count. A foreign owner rejects; a missing row means the adapter dropped\n // the write (impossible under real SQLite), so fail rather than publish an\n // outbox event for state that does not exist.\n if (result.changes === 0) {\n const stored = await tx.getFirstAsync<{ entity_id: string }>(\n `SELECT entity_id FROM ${this.prefix}entries WHERE id = ?`,\n [fact.id],\n );\n if (!stored) {\n throw new Error('Entry upsert reported no change and stored no row; the SQLiteAdapter did not perform the write');\n }\n if (stored.entity_id !== fact.entity_id) {\n throw new WikiGraphNodeOwnershipConflict();\n }\n }\n\n // Outbox payload mirrors what is actually persisted. On UPDATE, the SET\n // clause intentionally omits the OKF metadata columns so the prior row\n // values win — so `fact.X` here would describe state we did NOT write.\n // Re-read those columns from the stored row and overlay them onto the\n // caller-supplied payload before publishing (#90 review).\n const persistedOkf = existingRow\n ? {\n lifecycle_status: (existingRow.lifecycle_status ?? 'stable') as WikiFact['lifecycle_status'],\n stale_after: existingRow.stale_after != null ? Number(existingRow.stale_after) : null,\n generated_by: existingRow.generated_by ?? null,\n okf_sources: parseJsonArray<NonNullable<WikiFact['okf_sources']>[number]>(existingRow.okf_sources, []),\n okf_verified: parseJsonArray<NonNullable<WikiFact['okf_verified']>[number]>(existingRow.okf_verified, []),\n okf_usage_window: parseJsonObject<NonNullable<WikiFact['okf_usage_window']>>(existingRow.okf_usage_window),\n last_verified_at: existingRow.last_verified_at != null ? Number(existingRow.last_verified_at) : null,\n last_verified_by: existingRow.last_verified_by ?? null,\n }\n : null;\n await this.outbox.push({\n entityId: fact.entity_id,\n tableName: 'entries',\n recordId: fact.id,\n operation,\n payload: persistedOkf ? { ...fact, ...persistedOkf } : fact,\n }, tx);\n\n return result;\n }\n\n /**\n * Normalize an embedding blob value to Uint8Array or null.\n */\n private normalizeEmbeddingBlob(blob: unknown): Uint8Array | null {\n return normalizeEmbeddingBlobValue(blob);\n }\n\n /**\n * Fetch existing rows by IDs and return id/entity_id/updated_at for import collision resolution.\n */\n async findExistingMetadataByIds(\n ids: readonly string[],\n tx?: SQLiteAdapter,\n ): Promise<Array<{ id: string; entity_id: string; updated_at: number }>> {\n const executor = this.getExecutor(tx);\n const rows: Array<{ id: string; entity_id: string; updated_at: number }> = [];\n for (let i = 0; i < ids.length; i += this.chunkSize) {\n const chunk = ids.slice(i, i + this.chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n const chunkRows = await executor.getAllAsync<any>(\n `SELECT id, entity_id, updated_at FROM ${this.prefix}entries WHERE id IN (${placeholders})`,\n chunk,\n );\n rows.push(...chunkRows.map((row) => ({ id: row.id, entity_id: row.entity_id, updated_at: Number(row.updated_at) })));\n }\n return rows;\n }\n\n async findIdById(id: string, entityId: string, tx?: SQLiteAdapter): Promise<string | null> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}entries WHERE id = ? AND entity_id = ?`,\n [id, entityId],\n );\n return row?.id ?? null;\n }\n\n async findIdsBySource(\n entityId: string,\n sourceRef: string | null,\n sourceHash: string | null,\n tx?: SQLiteAdapter,\n includeDeleted = false,\n ): Promise<string[]> {\n const executor = this.getExecutor(tx);\n let sql = `SELECT id FROM ${this.prefix}entries WHERE entity_id = ?`;\n const args: unknown[] = [entityId];\n if (sourceRef !== null) {\n sql += ` AND source_ref = ?`;\n args.push(sourceRef);\n }\n if (sourceHash !== null) {\n sql += ` AND source_hash = ?`;\n args.push(sourceHash);\n }\n if (!includeDeleted) {\n sql += ` AND deleted_at IS NULL`;\n }\n const rows = await executor.getAllAsync<{ id: string }>(sql, args);\n return rows.map((row) => row.id);\n }\n\n async upsertForImport(fact: WikiFact, tx: SQLiteAdapter): Promise<{ changes: number; lastInsertRowId: number }> {\n const executor = this.getExecutor(tx);\n const tagsJson = JSON.stringify(fact.tags);\n const embeddingBlob = this.normalizeEmbeddingBlob(fact.embedding_blob);\n\n // Import is replace semantics: a re-imported fact whose OKF metadata\n // cleared (stale_after removed, generated_by removed, etc.) MUST overwrite\n // the prior row's value. The previous CASE WHEN IS NULL guards preserved\n // the old database values instead, so an \"absent in dump\" never cleared.\n // Direct `= excluded.X` ensures the dump is authoritative.\n //\n // WARNING: unlike `upsert`, this SQL re-parents a conflicting row\n // (`entity_id = excluded.entity_id`, no owner predicate). It is safe only\n // because ImportExportService skips foreign-owned IDs before calling it.\n // Do not model a new write path on this method; use `upsert`.\n const result = await executor.runAsync(\n `INSERT INTO ${this.prefix}entries (\n id, entity_id, title, body, tags, confidence, source_type,\n source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,\n deleted_at, embedding_blob, embedding, okf_type,\n lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,\n okf_sources, okf_verified, okf_usage_window\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n entity_id = excluded.entity_id,\n title = excluded.title,\n body = excluded.body,\n tags = excluded.tags,\n confidence = excluded.confidence,\n source_type = excluded.source_type,\n source_hash = excluded.source_hash,\n source_ref = excluded.source_ref,\n created_at = excluded.created_at,\n updated_at = excluded.updated_at,\n last_accessed_at = excluded.last_accessed_at,\n access_count = excluded.access_count,\n deleted_at = excluded.deleted_at,\n embedding_blob = excluded.embedding_blob,\n embedding = NULL,\n embedding_failed_at = CASE WHEN excluded.embedding_blob IS NOT NULL THEN NULL ELSE embedding_failed_at END,\n embedding_failure_kind = CASE WHEN excluded.embedding_blob IS NOT NULL THEN NULL ELSE embedding_failure_kind END,\n embedding_attempts = CASE WHEN excluded.embedding_blob IS NOT NULL THEN 0 ELSE embedding_attempts END,\n okf_type = excluded.okf_type,\n lifecycle_status = excluded.lifecycle_status,\n stale_after = excluded.stale_after,\n generated_by = excluded.generated_by,\n last_verified_at = excluded.last_verified_at,\n last_verified_by = excluded.last_verified_by,\n okf_sources = excluded.okf_sources,\n okf_verified = excluded.okf_verified,\n okf_usage_window = excluded.okf_usage_window`,\n [\n fact.id,\n fact.entity_id,\n fact.title,\n fact.body,\n tagsJson,\n fact.confidence,\n fact.source_type,\n fact.source_hash,\n fact.source_ref,\n fact.created_at,\n fact.updated_at,\n fact.last_accessed_at === null ? null : fact.last_accessed_at,\n fact.access_count,\n fact.deleted_at ?? null,\n embeddingBlob ?? null,\n null,\n fact.okf_type ?? null,\n // Same NOT NULL DEFAULT note as in upsert above.\n fact.lifecycle_status ?? 'stable',\n fact.stale_after ?? null,\n fact.generated_by ?? null,\n fact.last_verified_at ?? null,\n fact.last_verified_by ?? null,\n fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,\n fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,\n fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,\n ],\n );\n\n return result;\n }\n\n /**\n * Soft-delete a single entry by ID scoped to entityId. Sets deleted_at + updated_at.\n * `tx` is REQUIRED to ensure atomic outbox staging.\n */\n async softDelete(entryId: string, entityId: string, tx: SQLiteAdapter): Promise<{ changes: number }> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n const result = await executor.runAsync(\n `UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,\n [now, now, entryId, entityId],\n );\n\n await this.outbox.push({\n entityId,\n tableName: 'entries',\n recordId: entryId,\n operation: 'DELETE',\n payload: { id: entryId, entity_id: entityId, deleted_at: now },\n }, tx);\n\n return result;\n }\n\n /**\n * Soft-delete entries by source_ref and/or source_hash within a transaction.\n * Stages a DELETE outbox entry for each row in the same transaction.\n * `tx` is REQUIRED.\n * Returns the number of rows deleted.\n */\n async softDeleteBySource(\n entityId: string,\n tx: SQLiteAdapter,\n sourceRef?: string | null,\n sourceHash?: string | null,\n ): Promise<number> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n\n let q = `UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE entity_id = ? AND deleted_at IS NULL`;\n const args: any[] = [now, now, entityId];\n if (sourceRef) {\n q += ` AND source_ref = ?`;\n args.push(sourceRef);\n }\n if (sourceHash) {\n q += ` AND source_hash = ?`;\n args.push(sourceHash);\n }\n\n // Build a separate SELECT query to get affected IDs before updating\n let selectQ = `SELECT id FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL`;\n const selectArgs: any[] = [entityId];\n if (sourceRef) {\n selectQ += ` AND source_ref = ?`;\n selectArgs.push(sourceRef);\n }\n if (sourceHash) {\n selectQ += ` AND source_hash = ?`;\n selectArgs.push(sourceHash);\n }\n\n const idsToDelete = await executor.getAllAsync<{ id: string }>(selectQ, selectArgs);\n\n const result = await executor.runAsync(q, args);\n\n for (const row of idsToDelete) {\n await this.outbox.push({\n entityId,\n tableName: 'entries',\n recordId: row.id,\n operation: 'DELETE',\n payload: { id: row.id, entity_id: entityId, deleted_at: now },\n }, tx);\n }\n\n return result.changes;\n }\n\n /**\n * Fetch IDs + entity_ids of soft-deleted rows older than cutoff for a given entity.\n * Used by runPrune().\n */\n async getPrunableMetadata(\n entityId: string,\n cutoff: number,\n tx?: SQLiteAdapter,\n ): Promise<Array<{ id: string; entity_id: string }>> {\n const executor = this.getExecutor(tx);\n return executor.getAllAsync<{ id: string; entity_id: string }>(\n `SELECT id, entity_id FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ?`,\n [entityId, cutoff],\n );\n }\n\n /**\n * Fetch all non-deleted entries for an entity, ordered by updated_at DESC.\n * Used by _getFullBundle().\n */\n async findAllByEntityId(entityId: string, tx?: SQLiteAdapter): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL ORDER BY updated_at DESC`,\n [entityId],\n );\n return rows.map(mapRowToFact);\n }\n\n /**\n * Fetch live, mutable entries for an entity — everything heal is allowed to\n * downgrade or delete — oldest first, capped at `limit`, skipping anything\n * stamped inside the recheck cooldown (heal_checked_at > recheckCutoff).\n *\n * Oldest-first rather than newest-first: with a cooldown in place, newest-first\n * would keep re-selecting recently-touched facts every pass while older ones\n * wait indefinitely to even enter a batch.\n */\n async findHealCandidatesByEntityId(\n entityId: string,\n limit: number,\n recheckCutoff: number,\n tx?: SQLiteAdapter,\n ): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL AND source_type != 'immutable_document'\n AND (heal_checked_at IS NULL OR heal_checked_at <= ?)\n ORDER BY updated_at ASC LIMIT ?`,\n [entityId, recheckCutoff, limit],\n );\n return rows.map(mapRowToFact);\n }\n\n /**\n * Resolve search hits to document anchors. The MiniSearch index holds every\n * fact, not only immutable_document rows, so the source-type restriction has\n * to be applied here, after retrieval.\n */\n async findAnchorRowsByIds(\n entityId: string,\n ids: readonly string[],\n tx?: SQLiteAdapter,\n ): Promise<Array<{ id: string; title: string; source_ref: string | null }>> {\n if (ids.length === 0) return [];\n const executor = this.getExecutor(tx);\n const rows: Array<{ id: string; title: string; source_ref: string | null }> = [];\n // Chunked like every other multi-id read here. The current caller stays well\n // under SQLITE_MAX_VARIABLE_NUMBER, but that is a property of the caller,\n // not of this method.\n for (let i = 0; i < ids.length; i += this.chunkSize) {\n const chunk = ids.slice(i, i + this.chunkSize);\n const placeholders = chunk.map(() => '?').join(', ');\n const chunkRows = await executor.getAllAsync<{ id: string; title: string; source_ref: string | null }>(\n `SELECT id, title, source_ref FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL\n AND source_type = 'immutable_document'\n AND id IN (${placeholders})`,\n [entityId, ...chunk],\n );\n rows.push(...chunkRows);\n }\n return rows;\n }\n\n /**\n * Fetch recent non-deleted entries for an entity (limited), ordered by updated_at DESC.\n * Used by MaintenanceService.doRunLibrarian().\n *\n * When `excludeSourceRef` is supplied, the WHERE clause filters out that\n * sourceRef BEFORE applying LIMIT. The caller in IngestionService is\n * `findRecentByEntityId(entityId, 500, tx)` — it discards same-sourceRef\n * rows after the read to build a cross-sourceRef title index. If those\n * rows are filtered out in SQL, the limit applies to usable rows only\n * and a re-ingest where the caller's sourceRef owns most recent facts\n * still leaves cross-sourceRef entries in the index.\n */\n async findRecentByEntityId(\n entityId: string,\n limit: number,\n tx?: SQLiteAdapter,\n excludeSourceRef?: string,\n ): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n // `IS NULL OR !=` keeps NULL-source_ref rows (e.g. librarian_inferred facts)\n // in the cross-sourceRef title index. The intent of `excludeSourceRef` is\n // \"drop THIS sourceRef's rows\"; NULL rows belong to neither the current\n // sourceRef nor the replacement set, and excluding them causes edges\n // targeting legacy/non-document facts to fail to resolve.\n const excludeClause = excludeSourceRef ? ` AND (source_ref IS NULL OR source_ref != ?)` : '';\n const args: unknown[] = excludeSourceRef ? [entityId, excludeSourceRef, limit] : [entityId, limit];\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL${excludeClause} ORDER BY updated_at DESC LIMIT ?`,\n args,\n );\n return rows.map(mapRowToFact);\n }\n\n /**\n * Fetch all non-deleted entries for an entity with embedding blobs preserved.\n * Used by ImportExportService for export/import round-tripping.\n */\n async findAllByEntityIdWithBlobs(entityId: string, tx?: SQLiteAdapter): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL ORDER BY updated_at DESC`,\n [entityId],\n );\n return rows.map(mapRowToFactWithBlobs);\n }\n\n /**\n * Count non-deleted entries for the given entities whose embedding_blob dimension\n * doesn't match queryVecLength. Used by read() to detect model-switch mismatches.\n */\n async countDimensionMismatched(\n entityIds: readonly string[],\n queryVecLength: number,\n tx?: SQLiteAdapter,\n ): Promise<number> {\n if (entityIds.length === 0) return 0;\n const executor = this.getExecutor(tx);\n const placeholders = entityIds.map(() => '?').join(',');\n const row = await executor.getFirstAsync<{ cnt: number }>(\n `SELECT COUNT(*) AS cnt FROM ${this.prefix}entries\n WHERE entity_id IN (${placeholders}) AND deleted_at IS NULL\n AND embedding_blob IS NOT NULL\n AND (CAST(length(embedding_blob) AS INTEGER) % 4 = 0)\n AND (CAST(length(embedding_blob) AS INTEGER) / 4) != ?`,\n [...entityIds, queryVecLength],\n );\n return row?.cnt ?? 0;\n }\n\n /**\n * Count non-deleted entries for entityId that are stale relative to targetDim\n * (either no blob or wrong dimension). Used by runReembed() per-entity skip logic.\n */\n async countStaleForEntity(entityId: string, targetDim: number, tx?: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ cnt: number }>(\n `SELECT COUNT(*) AS cnt FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL\n AND (\n embedding_blob IS NULL\n OR (CAST(length(embedding_blob) AS INTEGER) / 4) != ?\n )`,\n [entityId, targetDim],\n );\n return row?.cnt ?? 0;\n }\n\n /**\n * Count non-deleted entries with stale or unconverted embeddings relative to `dim`.\n * Used by _reconcileEmbeddingDimension() to decide when to promote the pending\n * embedding_dimension value.\n */\n async countStaleEmbeddings(dim: number, tx?: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ cnt: number }>(\n `SELECT COUNT(*) AS cnt FROM ${this.prefix}entries\n WHERE deleted_at IS NULL\n AND (\n (embedding_blob IS NOT NULL AND (CAST(length(embedding_blob) AS INTEGER) / 4) != ?)\n OR (embedding_blob IS NULL AND embedding IS NOT NULL)\n )`,\n [dim],\n );\n return row?.cnt ?? 0;\n }\n\n /**\n * Bulk delete pruned entries (already soft-deleted) by IDs.\n * Used by runPrune(). Returns total number of deleted rows.\n * `tx` is REQUIRED so outbox deletion events are staged atomically.\n */\n async bulkDeletePruned(\n entityId: string,\n cutoff: number,\n ids: string[],\n tx: SQLiteAdapter,\n ): Promise<number> {\n const executor = this.getExecutor(tx);\n let totalChanges = 0;\n const chunkSize = 500;\n for (let i = 0; i < ids.length; i += chunkSize) {\n const chunk = ids.slice(i, i + chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n const result = await executor.runAsync(\n `DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ? AND id IN (${placeholders})`,\n [entityId, cutoff, ...chunk],\n );\n totalChanges += result.changes;\n // Stage outbox entries for permanently deleted records\n if (result.changes > 0) {\n for (const id of chunk) {\n await this.outbox.push({\n entityId,\n tableName: 'entries',\n recordId: id,\n operation: 'DELETE',\n payload: { id, entity_id: entityId, deleted_at: cutoff },\n }, tx);\n }\n }\n }\n return totalChanges;\n }\n\n /**\n * Mark orphaned entries (never accessed, old) as deleted.\n * Used by MaintenanceService.doRunHeal().\n */\n async markOrphaned(\n entityId: string,\n orphanThreshold: number,\n tx: SQLiteAdapter,\n ): Promise<string[]> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n const updatedRows = await executor.getAllAsync<{ id: string }>(\n `UPDATE ${this.prefix}entries\n SET deleted_at = ?, updated_at = ?\n WHERE entity_id = ? AND access_count = 0 AND created_at <= ? AND source_type != 'immutable_document' AND deleted_at IS NULL\n RETURNING id`,\n [now, now, entityId, orphanThreshold],\n );\n for (const row of updatedRows) {\n await this.outbox.push({\n entityId,\n tableName: 'entries',\n recordId: row.id,\n operation: 'DELETE',\n payload: { id: row.id, entity_id: entityId, deleted_at: now },\n }, tx);\n }\n return updatedRows.map(r => r.id);\n }\n\n /**\n * Downgrade stale inferred entries to 'tentative'.\n * Used by MaintenanceService.doRunHeal().\n *\n * Returns the ids it downgraded so the caller can fold them into\n * {@link HealResult.downgraded} without double-counting a fact the model also\n * downgraded in the same pass.\n */\n async downgradeStaleInferred(\n entityId: string,\n staleThreshold: number,\n tx: SQLiteAdapter,\n ): Promise<string[]> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n const eligibleRows = await executor.getAllAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}entries\n WHERE entity_id = ? AND confidence = 'inferred'\n AND (last_accessed_at <= ? OR (last_accessed_at IS NULL AND created_at <= ?))\n AND source_type != 'immutable_document' AND deleted_at IS NULL`,\n [entityId, staleThreshold, staleThreshold],\n );\n if (eligibleRows.length === 0) return [];\n await executor.runAsync(\n `UPDATE ${this.prefix}entries\n SET confidence = 'tentative', updated_at = ?\n WHERE entity_id = ? AND confidence = 'inferred' AND (last_accessed_at <= ? OR (last_accessed_at IS NULL AND created_at <= ?)) AND source_type != 'immutable_document' AND deleted_at IS NULL`,\n [now, entityId, staleThreshold, staleThreshold],\n );\n for (const row of eligibleRows) {\n await this.outbox.push({\n entityId,\n tableName: 'entries',\n recordId: row.id,\n operation: 'UPDATE',\n payload: { id: row.id, entity_id: entityId, confidence: 'tentative', updated_at: now },\n }, tx);\n }\n return eligibleRows.map(r => r.id);\n }\n\n /**\n * Downgrade specific entries to 'tentative' by IDs.\n * Used by MaintenanceService.doRunHeal().\n */\n async downgradeByIds(\n ids: string[],\n entityId: string,\n tx: SQLiteAdapter,\n ): Promise<void> {\n if (ids.length === 0) return;\n const executor = this.getExecutor(tx);\n const now = Date.now();\n const placeholders = ids.map(() => '?').join(',');\n await executor.runAsync(\n `UPDATE ${this.prefix}entries SET confidence = 'tentative', updated_at = ? WHERE id IN (${placeholders}) AND entity_id = ?`,\n [now, ...ids, entityId],\n );\n // Stage outbox entries for downgraded records\n for (const id of ids) {\n await this.outbox.push({\n entityId,\n tableName: 'entries',\n recordId: id,\n operation: 'UPDATE',\n payload: { id, entity_id: entityId, confidence: 'tentative', updated_at: now },\n }, tx);\n }\n }\n\n /**\n * Soft-delete specific entries by IDs.\n * Used by MaintenanceService.doRunHeal().\n */\n async softDeleteByIds(\n ids: string[],\n entityId: string,\n tx: SQLiteAdapter,\n ): Promise<void> {\n if (ids.length === 0) return;\n const executor = this.getExecutor(tx);\n const now = Date.now();\n const placeholders = ids.map(() => '?').join(',');\n await executor.runAsync(\n `UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE id IN (${placeholders}) AND entity_id = ?`,\n [now, now, ...ids, entityId],\n );\n // Stage outbox entries for soft-deleted records\n for (const id of ids) {\n await this.outbox.push({\n entityId,\n tableName: 'entries',\n recordId: id,\n operation: 'DELETE',\n payload: { id, entity_id: entityId, deleted_at: now },\n }, tx);\n }\n }\n\n /**\n * Bulk soft-delete all entries for an entity.\n * Stages DELETE outbox entries for each row in the same transaction.\n * `tx` is REQUIRED.\n */\n async bulkSoftDeleteByEntityId(entityId: string, tx: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n // Get IDs before updating for outbox staging\n const idsToDelete = await executor.getAllAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL`,\n [entityId],\n );\n const result = await executor.runAsync(\n `UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE entity_id = ? AND deleted_at IS NULL`,\n [now, now, entityId],\n );\n // Stage outbox entries for each deleted record\n for (const row of idsToDelete) {\n await this.outbox.push({\n entityId,\n tableName: 'entries',\n recordId: row.id,\n operation: 'DELETE',\n payload: { id: row.id, entity_id: entityId, deleted_at: now },\n }, tx);\n }\n return result.changes;\n }\n\n async findMiniSearchRows(\n entityId?: string,\n tx?: SQLiteAdapter,\n ): Promise<Array<{ id: string; entity_id: string; title: string; body: string; tags: string }>> {\n const executor = this.getExecutor(tx);\n if (entityId !== undefined) {\n return executor.getAllAsync(\n `SELECT id, entity_id, title, body, tags FROM ${this.prefix}entries WHERE deleted_at IS NULL AND entity_id = ?`,\n [entityId],\n );\n }\n return executor.getAllAsync(\n `SELECT id, entity_id, title, body, tags FROM ${this.prefix}entries WHERE deleted_at IS NULL`,\n );\n }\n\n async updateEmbeddingBlob(id: string, blob: Uint8Array, tx?: SQLiteAdapter): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `UPDATE ${this.prefix}entries\n SET embedding_blob = ?,\n embedding = NULL,\n embedding_failed_at = NULL,\n embedding_failure_kind = NULL,\n embedding_attempts = 0\n WHERE id = ?`,\n [blob, id],\n );\n }\n\n /**\n * Record a failed embedding attempt. Deliberately does NOT touch updated_at\n * (import merge is last-write-wins on it) and pushes no outbox event —\n * embedding lifecycle is local state, not replicated. Same discipline as\n * updateEmbeddingBlob. See spec §3.5.\n *\n * Only marker-eligible kinds (spec §3.3) are accepted: `no_provider` never\n * marks and `storage_error` never marks, so retry/permanent-failure policy\n * built on these rows only ever sees real embed failures.\n */\n async markEmbeddingFailure(\n id: string,\n kind: EmbeddingMarkerKind,\n now: number,\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `UPDATE ${this.prefix}entries\n SET embedding_failed_at = ?,\n embedding_failure_kind = ?,\n embedding_attempts = embedding_attempts + 1\n WHERE id = ?`,\n [now, kind, id],\n );\n }\n\n /**\n * Clear marker state for every marked row. Called when the embedding\n * dimension is promoted: a new model produces different vectors, so past\n * failures — including `float32_overflow`, which is otherwise terminal —\n * no longer predict future ones (spec §2.3).\n *\n * Same discipline as markEmbeddingFailure: no `updated_at` touch and no\n * outbox event, because embedding lifecycle is local state, not replicated.\n * Returns the number of rows cleared.\n */\n async clearEmbeddingFailureMarkers(tx?: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const result = await executor.runAsync(\n `UPDATE ${this.prefix}entries\n SET embedding_failed_at = NULL,\n embedding_failure_kind = NULL,\n embedding_attempts = 0\n WHERE embedding_failed_at IS NOT NULL`,\n );\n return result.changes;\n }\n\n async hasLegacySourceTypes(tx?: SQLiteAdapter): Promise<boolean> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ one: number }>(\n `SELECT 1 AS one FROM ${this.prefix}entries WHERE source_type IN ('user_document', 'agent_inferred') LIMIT 1`,\n [],\n );\n return row != null;\n }\n\n async countLegacySourceTypes(tx?: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ count: number }>(\n `SELECT COUNT(*) as count FROM ${this.prefix}entries WHERE source_type IN ('user_document', 'agent_inferred')`,\n [],\n );\n return row?.count ?? 0;\n }\n\n async findAllForReembed(entityId?: string, tx?: SQLiteAdapter): Promise<ReembedCandidateRow[]> {\n const executor = this.getExecutor(tx);\n if (entityId !== undefined) {\n return executor.getAllAsync(\n `SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL`,\n [entityId],\n );\n }\n return executor.getAllAsync(\n `SELECT * FROM ${this.prefix}entries WHERE deleted_at IS NULL`,\n );\n }\n\n async findRowsForSourceRefMigration(tx?: SQLiteAdapter): Promise<Array<{ rowid: number; source_ref: string }>> {\n const executor = this.getExecutor(tx);\n return executor.getAllAsync(\n `SELECT rowid, source_ref FROM ${this.prefix}entries\n WHERE source_ref IS NOT NULL\n AND (\n TRIM(source_ref) != source_ref\n OR INSTR(source_ref, '/') > 0\n OR INSTR(source_ref, '\\\\') > 0\n OR INSTR(source_ref, CHAR(0)) > 0\n OR source_ref GLOB '*[^-A-Za-z0-9._ ]*'\n )`,\n );\n }\n\n async updateSourceRefByRowid(rowid: number, sourceRef: string | null, tx: SQLiteAdapter): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `UPDATE ${this.prefix}entries SET source_ref = ? WHERE rowid = ?`,\n [sourceRef, rowid],\n );\n }\n\n async findLatestSourceHash(entityId: string, sourceRef: string, tx?: SQLiteAdapter): Promise<string | null> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ source_hash: string | null }>(\n `SELECT source_hash FROM ${this.prefix}entries\n WHERE entity_id = ? AND source_ref = ? AND deleted_at IS NULL\n ORDER BY updated_at DESC, id ASC\n LIMIT 1`,\n [entityId, sourceRef],\n );\n return row?.source_hash ?? null;\n }\n\n /**\n * Batch version of {@link findLatestSourceHash}. Returns a Map covering every\n * requested ref, where the value is the source_hash from the row with the\n * most-recently-updated live fact for that ref, or null when no live row exists.\n *\n * The SQL uses ROW_NUMBER() OVER (PARTITION BY source_ref ORDER BY updated_at\n * DESC, id ASC) — NOT MAX(source_hash). Aggregation with MAX(source_hash) is\n * wrong because MAX computes independently across grouped rows; the hash must\n * come from the exact row that wins MAX(updated_at). The `id ASC` tie-break\n * keeps selection deterministic when two live rows share `updated_at`.\n *\n * Source refs are de-duplicated and processed in chunks so the per-query bind\n * parameter count stays under SQLite's `SQLITE_MAX_VARIABLE_NUMBER` (default\n * 999, leaving one slot for `entity_id`).\n *\n * Empty input is a synchronous early return with zero SQL calls.\n */\n async findLatestSourceHashes(\n entityId: string,\n sourceRefs: readonly string[],\n tx?: SQLiteAdapter,\n ): Promise<Map<string, string | null>> {\n const out = new Map<string, string | null>();\n if (sourceRefs.length === 0) return out;\n // Pre-populate with null for every requested ref so callers can distinguish\n // \"no live row\" (null) from \"row with a null source_hash\" (also null in this\n // shape, but at least the key is guaranteed present).\n const dedupedRefs = Array.from(new Set(sourceRefs));\n for (const ref of dedupedRefs) {\n out.set(ref, null);\n }\n const executor = this.getExecutor(tx);\n // 1 bind parameter for entity_id; remaining slots for source_ref placeholders.\n const chunkLimit = Math.max(1, this.chunkSize - 1);\n for (let i = 0; i < dedupedRefs.length; i += chunkLimit) {\n const chunk = dedupedRefs.slice(i, i + chunkLimit);\n const placeholders = chunk.map(() => '?').join(',');\n const rows = await executor.getAllAsync<{ source_ref: string; source_hash: string | null }>(\n `WITH ranked AS (\n SELECT source_ref, source_hash,\n ROW_NUMBER() OVER (\n PARTITION BY source_ref\n ORDER BY updated_at DESC, id ASC\n ) as rn\n FROM ${this.prefix}entries\n WHERE entity_id = ? AND source_ref IN (${placeholders}) AND deleted_at IS NULL\n )\n SELECT source_ref, source_hash\n FROM ranked\n WHERE rn = 1`,\n [entityId, ...chunk],\n );\n for (const r of rows) {\n out.set(r.source_ref, r.source_hash);\n }\n }\n return out;\n }\n\n /**\n * Return the live source_refs for an entity that hold the given source_hash.\n * Used by the ingestDocument duplicate-hash guard and by hosts auditing\n * duplicate-content collisions. Sorted `COLLATE BINARY` so the canonical\n * ref (the code-unit-minimum of the set) is stable across deploys.\n */\n async findSourceRefsByHash(\n entityId: string,\n sourceHash: string,\n tx?: SQLiteAdapter,\n ): Promise<string[]> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<{ source_ref: string }>(\n `SELECT source_ref FROM ${this.prefix}entries\n WHERE entity_id = ? AND source_hash = ? AND deleted_at IS NULL\n AND source_ref IS NOT NULL\n GROUP BY source_ref\n ORDER BY source_ref COLLATE BINARY`,\n [entityId, sourceHash],\n );\n return rows.map(r => r.source_ref);\n }\n\n /**\n * Per-sourceRef rollup for an entity: one row per live source_ref, with the\n * most-recently-updated live hash (NOT the lexically-max hash) and a live\n * fact count.\n *\n * The hash comes from the same row that wins ROW_NUMBER() over updated_at\n * DESC, so a ref with multiple live hashes (e.g. from import) reports the\n * latest one — matching single-doc `findLatestSourceHash` semantics.\n *\n * Sort is COLLATE BINARY: locale-dependent ordering re-mints identity on\n * every deploy, which is the bug this whole section exists to prevent.\n */\n async listSourceRefs(\n entityId: string,\n tx?: SQLiteAdapter,\n ): Promise<Array<{\n sourceRef: string;\n sourceHash: string | null;\n factCount: number;\n lastIngestedAt: number;\n }>> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<{\n source_ref: string;\n source_hash: string | null;\n fact_count: number;\n last_ingested_at: number;\n }>(\n `WITH ranked AS (\n SELECT source_ref, source_hash, updated_at,\n ROW_NUMBER() OVER (\n PARTITION BY source_ref\n ORDER BY updated_at DESC, id ASC\n ) AS rn,\n COUNT(*) OVER (PARTITION BY source_ref) AS fact_count\n FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL AND source_ref IS NOT NULL\n )\n SELECT source_ref,\n source_hash AS source_hash,\n fact_count AS fact_count,\n updated_at AS last_ingested_at\n FROM ranked\n WHERE rn = 1\n ORDER BY source_ref COLLATE BINARY`,\n [entityId],\n );\n return rows.map(r => ({\n sourceRef: r.source_ref,\n sourceHash: r.source_hash,\n factCount: Number(r.fact_count),\n lastIngestedAt: Number(r.last_ingested_at),\n }));\n }\n\n /**\n * Count live entries for an entity across all source_refs/source_hashes.\n * Used by forget({ dryRun, clearAll: true }).\n */\n async countLiveByEntityId(entityId: string, tx?: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ cnt: number }>(\n `SELECT COUNT(*) AS cnt FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL`,\n [entityId],\n );\n return row?.cnt ?? 0;\n }\n\n /**\n * Count live entries matching a source filter (either or both may be null).\n * Used by forget({ dryRun: true }) with sourceRef/sourceHash.\n */\n async countLiveBySource(\n entityId: string,\n sourceRef: string | null,\n sourceHash: string | null,\n tx?: SQLiteAdapter,\n ): Promise<number> {\n const executor = this.getExecutor(tx);\n let q = `SELECT COUNT(*) AS cnt FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL`;\n const args: unknown[] = [entityId];\n if (sourceRef !== null) { q += ` AND source_ref = ?`; args.push(sourceRef); }\n if (sourceHash !== null) { q += ` AND source_hash = ?`; args.push(sourceHash); }\n const row = await executor.getFirstAsync<{ cnt: number }>(q, args);\n return row?.cnt ?? 0;\n }\n\n async findMetadataByIds(ids: readonly string[], tx?: SQLiteAdapter): Promise<EntryRowMetadata[]> {\n if (ids.length === 0) return [];\n const executor = this.getExecutor(tx);\n const rows: EntryRowMetadata[] = [];\n for (let i = 0; i < ids.length; i += this.chunkSize) {\n const chunk = ids.slice(i, i + this.chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n const chunkRows = await executor.getAllAsync<EntryRowMetadata>(\n `SELECT id, entity_id, updated_at, access_count FROM ${this.prefix}entries WHERE id IN (${placeholders}) AND deleted_at IS NULL`,\n chunk,\n );\n rows.push(...chunkRows);\n }\n return rows;\n }\n\n async findWithEmbeddingsByIds(ids: readonly string[], tx?: SQLiteAdapter): Promise<EntryRowWithEmbeddings[]> {\n if (ids.length === 0) return [];\n const executor = this.getExecutor(tx);\n const rows: EntryRowWithEmbeddings[] = [];\n for (let i = 0; i < ids.length; i += this.chunkSize) {\n const chunk = ids.slice(i, i + this.chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n const chunkRows = await executor.getAllAsync<EntryRowWithEmbeddings>(\n `SELECT id, entity_id, embedding_blob, embedding, updated_at, access_count FROM ${this.prefix}entries WHERE id IN (${placeholders}) AND deleted_at IS NULL`,\n chunk,\n );\n rows.push(...chunkRows);\n }\n return rows;\n }\n\n async findMetadataByEntityIds(entityIds: readonly string[], tx?: SQLiteAdapter): Promise<EntryRowMetadata[]> {\n if (entityIds.length === 0) return [];\n const executor = this.getExecutor(tx);\n const placeholders = entityIds.map(() => '?').join(',');\n return executor.getAllAsync<EntryRowMetadata>(\n `SELECT id, entity_id, updated_at, access_count FROM ${this.prefix}entries WHERE entity_id IN (${placeholders}) AND deleted_at IS NULL`,\n [...entityIds],\n );\n }\n\n async findWithEmbeddingsByEntityIds(entityIds: readonly string[], tx?: SQLiteAdapter): Promise<EntryRowWithEmbeddings[]> {\n if (entityIds.length === 0) return [];\n const executor = this.getExecutor(tx);\n const placeholders = entityIds.map(() => '?').join(',');\n return executor.getAllAsync<EntryRowWithEmbeddings>(\n `SELECT id, entity_id, embedding_blob, embedding, updated_at, access_count FROM ${this.prefix}entries WHERE entity_id IN (${placeholders}) AND deleted_at IS NULL`,\n [...entityIds],\n );\n }\n\n async findEmbeddingsByIds(\n ids: readonly string[],\n tx?: SQLiteAdapter,\n ): Promise<Array<{ id: string; embedding_blob: Uint8Array | null; embedding: string | null }>> {\n if (ids.length === 0) return [];\n const executor = this.getExecutor(tx);\n const rows: Array<{ id: string; embedding_blob: Uint8Array | null; embedding: string | null }> = [];\n for (let i = 0; i < ids.length; i += this.chunkSize) {\n const chunk = ids.slice(i, i + this.chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n const chunkRows = await executor.getAllAsync<{ id: string; embedding_blob: Uint8Array | null; embedding: string | null }>(\n `SELECT id, embedding_blob, embedding FROM ${this.prefix}entries WHERE id IN (${placeholders}) AND deleted_at IS NULL`,\n chunk,\n );\n rows.push(...chunkRows);\n }\n return rows;\n }\n\n async trackAccess(ids: readonly string[], now: number, tx?: SQLiteAdapter): Promise<void> {\n if (ids.length === 0) return;\n const executor = this.getExecutor(tx);\n for (let i = 0; i < ids.length; i += this.chunkSize) {\n const chunk = ids.slice(i, i + this.chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n await executor.runAsync(\n `UPDATE ${this.prefix}entries SET access_count = access_count + 1, last_accessed_at = ? WHERE id IN (${placeholders})`,\n [now, ...chunk],\n );\n }\n }\n\n getLegacyMigrationSQL(): string {\n return [\n `-- Migrate legacy source_type values (targets your WikiMemory prefix: ${this.prefix})`,\n `UPDATE ${this.prefix}entries SET source_type = 'immutable_document' WHERE source_type = 'user_document';`,\n `UPDATE ${this.prefix}entries SET source_type = 'librarian_inferred' WHERE source_type = 'agent_inferred';`,\n ].join('\\n');\n }\n\n async findRecentByEntityIds(\n entityIds: readonly string[],\n limit: number,\n tx?: SQLiteAdapter,\n opts?: { excludeDrafts?: boolean },\n ): Promise<WikiFact[]> {\n if (entityIds.length === 0) return [];\n const executor = this.getExecutor(tx);\n const placeholders = entityIds.map(() => '?').join(',');\n const draftClause = opts?.excludeDrafts === true ? ` AND lifecycle_status != 'draft'` : '';\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries WHERE entity_id IN (${placeholders}) AND deleted_at IS NULL${draftClause} ORDER BY updated_at DESC LIMIT ?`,\n [...entityIds, limit],\n );\n return rows.map(mapRowToFact);\n }\n\n /** IDs of live draft facts for the given entities (spec §5.1). Callers pass ≤ 100 entity ids. */\n async findDraftIdsByEntityIds(entityIds: readonly string[], tx?: SQLiteAdapter): Promise<Set<string>> {\n if (entityIds.length === 0) return new Set();\n const executor = this.getExecutor(tx);\n const placeholders = entityIds.map(() => '?').join(',');\n const rows = await executor.getAllAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}entries\n WHERE entity_id IN (${placeholders}) AND deleted_at IS NULL AND lifecycle_status = 'draft'`,\n [...entityIds],\n );\n return new Set(rows.map((r) => r.id));\n }\n\n /** Live drafts for one entity, newest first, keyset-paged by (created_at, id). */\n async listDraftsByEntityId(\n entityId: string,\n limit: number,\n after: { createdAt: number; id: string } | null,\n tx?: SQLiteAdapter,\n ): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n const afterClause = after ? ` AND (created_at < ? OR (created_at = ? AND id < ?))` : '';\n const args: unknown[] = after\n ? [entityId, after.createdAt, after.createdAt, after.id, limit]\n : [entityId, limit];\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL AND lifecycle_status = 'draft'${afterClause}\n ORDER BY created_at DESC, id DESC LIMIT ?`,\n args,\n );\n return rows.map(mapRowToFact);\n }\n\n /** True iff `entryId` is a live draft owned by `entityId`. */\n async isLiveDraft(entryId: string, entityId: string, tx?: SQLiteAdapter): Promise<boolean> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}entries\n WHERE id = ? AND entity_id = ? AND deleted_at IS NULL AND lifecycle_status = 'draft'`,\n [entryId, entityId],\n );\n return row != null;\n }\n\n /**\n * Live untyped facts eligible for ontology backfill, oldest first.\n * Skips facts checked within the recheck cooldown (ontology_checked_at > recheckCutoff).\n */\n async findUntypedByEntityId(entityId: string, limit: number, recheckCutoff: number, tx?: SQLiteAdapter): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries\n WHERE entity_id = ? AND okf_type IS NULL AND deleted_at IS NULL\n AND (ontology_checked_at IS NULL OR ontology_checked_at <= ?)\n ORDER BY updated_at ASC LIMIT ?`,\n [entityId, recheckCutoff, limit],\n );\n return rows.map(mapRowToFact);\n }\n\n /** Counts live untyped facts: eligible (past cooldown) vs deferred (in cooldown). */\n async countUntypedByEntityId(entityId: string, recheckCutoff: number, tx?: SQLiteAdapter): Promise<{ eligible: number; deferred: number }> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ eligible: number | null; deferred: number | null }>(\n `SELECT\n SUM(CASE WHEN ontology_checked_at IS NULL OR ontology_checked_at <= ? THEN 1 ELSE 0 END) AS eligible,\n SUM(CASE WHEN ontology_checked_at IS NOT NULL AND ontology_checked_at > ? THEN 1 ELSE 0 END) AS deferred\n FROM ${this.prefix}entries\n WHERE entity_id = ? AND okf_type IS NULL AND deleted_at IS NULL`,\n [recheckCutoff, recheckCutoff, entityId],\n );\n return { eligible: Number(row?.eligible ?? 0), deferred: Number(row?.deferred ?? 0) };\n }\n\n /**\n * Sets okf_type only when currently NULL — additive by construction: a\n * concurrently-typed fact is never overwritten. Returns changes for the caller\n * to distinguish applied vs skipped.\n */\n async updateOkfType(id: string, entityId: string, okfType: string, tx: SQLiteAdapter): Promise<{ changes: number }> {\n const result = await tx.runAsync(\n `UPDATE ${this.prefix}entries SET okf_type = ?\n WHERE id = ? AND entity_id = ? AND okf_type IS NULL AND deleted_at IS NULL`,\n [okfType, id, entityId],\n );\n return { changes: result.changes };\n }\n\n /**\n * Stamps the backfill recheck cooldown. NEVER touches updated_at — import\n * merge resolution is last-write-wins on updated_at and a bump here would\n * make an unchanged local fact beat a genuinely newer remote edit.\n */\n async markOntologyChecked(ids: string[], entityId: string, now: number, tx: SQLiteAdapter): Promise<void> {\n if (ids.length === 0) return;\n for (let i = 0; i < ids.length; i += this.chunkSize) {\n const chunk = ids.slice(i, i + this.chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n await tx.runAsync(\n `UPDATE ${this.prefix}entries SET ontology_checked_at = ?\n WHERE id IN (${placeholders}) AND entity_id = ? AND deleted_at IS NULL`,\n [now, ...chunk, entityId],\n );\n }\n }\n\n /**\n * Lightweight full-breadth title index (id, title, okf_type) over all live\n * typed facts. Used by ontology backfill edge resolution — a recent-N window\n * would miss an old fact's contemporaries. Untyped rows are excluded: they\n * can never pass the edge target-type check, and batch facts typed during\n * the run are re-added to the in-memory index by the caller.\n */\n async findTitleIndexByEntityId(entityId: string, tx?: SQLiteAdapter): Promise<Array<{ id: string; title: string; okf_type: string | null }>> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<{ id: string; title: string; okf_type: string | null }>(\n `SELECT id, title, okf_type FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND okf_type IS NOT NULL`,\n [entityId],\n );\n return rows.map(r => ({ id: r.id, title: r.title, okf_type: r.okf_type ?? null }));\n }\n\n /** Counts live mutable facts: eligible (past cooldown) vs deferred (in cooldown). */\n async countHealCandidatesByEntityId(\n entityId: string,\n recheckCutoff: number,\n tx?: SQLiteAdapter,\n ): Promise<{ eligible: number; deferred: number }> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ eligible: number | null; deferred: number | null }>(\n `SELECT\n SUM(CASE WHEN heal_checked_at IS NULL OR heal_checked_at <= ? THEN 1 ELSE 0 END) AS eligible,\n SUM(CASE WHEN heal_checked_at IS NOT NULL AND heal_checked_at > ? THEN 1 ELSE 0 END) AS deferred\n FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL AND source_type != 'immutable_document'`,\n [recheckCutoff, recheckCutoff, entityId],\n );\n return { eligible: Number(row?.eligible ?? 0), deferred: Number(row?.deferred ?? 0) };\n }\n\n /**\n * Stamps the heal recheck cooldown. NEVER touches updated_at — import merge\n * resolution is last-write-wins on updated_at and a bump here would make an\n * unchanged local fact beat a genuinely newer remote edit.\n *\n * Soft-deleted rows are skipped: a candidate heal deleted earlier in the same\n * transaction is no longer a candidate under any future pass, so its cooldown\n * value is irrelevant. This means the stamped count can be lower than the\n * offered-candidate count.\n */\n async markHealChecked(ids: string[], entityId: string, now: number, tx: SQLiteAdapter): Promise<void> {\n if (ids.length === 0) return;\n for (let i = 0; i < ids.length; i += this.chunkSize) {\n const chunk = ids.slice(i, i + this.chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n await tx.runAsync(\n `UPDATE ${this.prefix}entries SET heal_checked_at = ?\n WHERE id IN (${placeholders}) AND entity_id = ? AND deleted_at IS NULL`,\n [now, ...chunk, entityId],\n );\n }\n }\n\n /**\n * Lightweight full-breadth index (id, title) over all live librarian_inferred\n * facts. This is heal's fuzzy-dedupe corpus, deliberately kept independent of\n * the bounded candidate window: seeding dedupe from a batchSize-limited read\n * would let a synthesized fact duplicating a fact outside the window pass the\n * Jaccard check, and a convergence loop would multiply those duplicates across\n * passes. Mirrors findTitleIndexByEntityId — full breadth, two columns, cheap.\n */\n async findInferredTitlesByEntityId(\n entityId: string,\n tx?: SQLiteAdapter,\n ): Promise<Array<{ id: string; title: string }>> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<{ id: string; title: string }>(\n `SELECT id, title FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL AND source_type = 'librarian_inferred'`,\n [entityId],\n );\n return rows.map(r => ({ id: r.id, title: r.title }));\n }\n}\n","import { BaseRepository } from './BaseRepository';\nimport type { SQLiteAdapter } from '../types';\nimport { generateId } from '../utils/ids';\n\nexport class OutboxRepository extends BaseRepository {\n private enableOutbox: boolean;\n\n constructor(db: SQLiteAdapter, prefix: string, enableOutbox = false) {\n super(db, prefix);\n this.enableOutbox = enableOutbox;\n }\n\n /**\n * Insert a new outbox event within the provided transaction.\n * No-op when enableOutbox is false.\n * `tx` is required — callers must always pass the active transaction\n * so the write is atomic with the main table mutation.\n */\n async push(\n params: {\n entityId: string;\n tableName: string;\n recordId: string;\n operation: 'INSERT' | 'UPDATE' | 'DELETE';\n payload: any;\n },\n tx: SQLiteAdapter,\n ): Promise<void> {\n if (!this.enableOutbox) return;\n const executor = this.getExecutor(tx);\n const id = generateId('out_');\n const now = Date.now();\n await executor.runAsync(\n `INSERT INTO ${this.prefix}outbox (id, entity_id, table_name, record_id, operation, payload, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)`,\n [id, params.entityId, params.tableName, params.recordId, params.operation, JSON.stringify(params.payload), now],\n );\n }\n\n /**\n * Fetch pending outbox rows ordered by created_at ASC, rowid ASC.\n * Reads directly from `this.db` (not a transaction).\n */\n async fetchPending(limit = 50): Promise<any[]> {\n return this.db.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}outbox ORDER BY created_at ASC, rowid ASC LIMIT ?`,\n [limit],\n );\n }\n\n /**\n * Delete acknowledged outbox rows by their IDs.\n * No-op when `ids` is empty.\n * Deletes directly from `this.db` (not a transaction).\n */\n async acknowledge(ids: string[]): Promise<void> {\n if (ids.length === 0) return;\n const chunkSize = 500;\n for (let i = 0; i < ids.length; i += chunkSize) {\n const chunk = ids.slice(i, i + chunkSize);\n const placeholders = chunk.map(() => '?').join(', ');\n await this.db.runAsync(\n `DELETE FROM ${this.prefix}outbox WHERE id IN (${placeholders})`,\n chunk,\n );\n }\n }\n}\n","import type { SQLiteAdapter } from '../types';\nimport { BaseRepository } from './BaseRepository';\nimport { generateId } from '../utils/ids';\n\n/**\n * Per-(entity_id, source_hash) record of the canonical sourceRef currently\n * holding that hash. The partial UNIQUE index on (entity_id, source_hash)\n * WHERE deleted_at IS NULL enforces the sourceRef-level TOCTOU-race invariant\n * for the #79 fix. See\n * docs/superpowers/specs/2026-08-07-dependabot-concurrency-release-hygiene-design.md §B1.\n *\n * The entries table cannot express this invariant directly because a single\n * `ingestDocument` call writes N facts that all share\n * (entity_id, source_ref, source_hash); a UNIQUE index on\n * `entries(entity_id, source_hash)` would block the 2nd–Nth fact inserts in\n * the normal multi-fact path. The per-(entity, hash) granularity of\n * source_ref_index matches the TOCTOU invariant exactly.\n *\n * No outbox events: this is an internal index table whose state is fully\n * derivable from `entries`. Hosts that need CDC continue to read `entries`\n * outbox events; the index is not part of the user-visible contract.\n */\nexport class SourceRefIndexRepository extends BaseRepository {\n /**\n * Idempotent insert: the partial UNIQUE index catches concurrent inserts for\n * the same (entity_id, source_hash). The caller (IngestionService) catches\n * the resulting SQLITE_CONSTRAINT_UNIQUE and translates it to the per-mode\n * duplicate-hash outcome. Runtime IDs use the `sri_` prefix to avoid\n * collision with the deterministic `sri:<entity>:<hash>` IDs used by the v9\n * backfill (the colon separator keeps the two ID spaces disjoint).\n */\n async upsert(\n entityId: string,\n sourceHash: string,\n sourceRef: string,\n tx: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `INSERT INTO ${this.prefix}source_ref_index (id, entity_id, source_hash, source_ref, created_at, deleted_at)\n VALUES (?, ?, ?, ?, ?, NULL)`,\n [generateId('sri_'), entityId, sourceHash, sourceRef, Date.now()],\n );\n }\n\n /**\n * Idempotent soft-delete of the live row for (entity_id, source_ref).\n * Called at the start of every ingestDocument to remove the prior run's\n * index row, so the new upsert doesn't collide with itself. No-op when the\n * row is already soft-deleted or never existed.\n */\n async softDeleteByEntityAndSourceRef(\n entityId: string,\n sourceRef: string,\n tx: SQLiteAdapter,\n ): Promise<number> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n const result = await executor.runAsync(\n `UPDATE ${this.prefix}source_ref_index\n SET deleted_at = ?, created_at = ?\n WHERE entity_id = ? AND source_ref = ? AND deleted_at IS NULL`,\n [now, now, entityId, sourceRef],\n );\n return result.changes;\n }\n\n /**\n * Returns the live sourceRef holding the given hash, or null when no live\n * row exists. Used by the IngestionService pre-check (line 82) and the\n * catch-and-translate canonical lookup (line 212).\n */\n async findActiveByEntityAndHash(\n entityId: string,\n sourceHash: string,\n tx?: SQLiteAdapter,\n ): Promise<string | null> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ source_ref: string }>(\n `SELECT source_ref FROM ${this.prefix}source_ref_index\n WHERE entity_id = ? AND source_hash = ? AND deleted_at IS NULL`,\n [entityId, sourceHash],\n );\n return row?.source_ref ?? null;\n }\n}\n","import { BaseRepository } from './BaseRepository';\nimport { OutboxRepository } from './OutboxRepository';\nimport type { WikiTask, SQLiteAdapter } from '../types';\nimport { parseJsonArray, parseJsonObject } from './rowMappers';\nimport { isStaleAfter, deriveTrustTier } from '@equationalapplications/core-okf';\n\nfunction mapRowToTask(row: any): WikiTask {\n const okf_verified = parseJsonArray<NonNullable<WikiTask['okf_verified']>[number]>(row.okf_verified, []);\n // Mirror EntryRepository.mapRowToFact — see that file for the rationale on\n // per-row Date.now() sampling vs. a shared per-call value.\n const now = Date.now();\n const staleAfterRaw = row.stale_after != null ? Number(row.stale_after) : null;\n\n return {\n id: row.id,\n entity_id: row.entity_id,\n description: row.description,\n status: row.status,\n priority: Number(row.priority),\n created_at: Number(row.created_at),\n updated_at: Number(row.updated_at),\n resolved_at: row.resolved_at != null ? Number(row.resolved_at) : null,\n deleted_at: row.deleted_at != null ? Number(row.deleted_at) : null,\n okf_type: row.okf_type ?? null,\n // OKF v0.2\n lifecycle_status: (row.lifecycle_status ?? 'stable') as WikiTask['lifecycle_status'],\n stale_after: staleAfterRaw,\n generated_by: row.generated_by ?? null,\n okf_sources: parseJsonArray<NonNullable<WikiTask['okf_sources']>[number]>(row.okf_sources, []),\n okf_verified,\n okf_usage_window: parseJsonObject<NonNullable<WikiTask['okf_usage_window']>>(row.okf_usage_window),\n last_verified_at: row.last_verified_at != null ? Number(row.last_verified_at) : null,\n last_verified_by: row.last_verified_by ?? null,\n // Spec §2.7 + §5.3: hydrate so read() consumers don't re-call the helpers.\n isStale: isStaleAfter(staleAfterRaw, now),\n trustTier: deriveTrustTier(okf_verified),\n };\n}\n\nexport class TaskRepository extends BaseRepository {\n constructor(\n db: SQLiteAdapter,\n prefix: string,\n private outbox: OutboxRepository,\n ) {\n super(db, prefix);\n }\n\n /**\n * Fetch a single task by ID. Returns null if not found or soft-deleted.\n */\n async findById(id: string): Promise<WikiTask | null> {\n const row = await this.db.getFirstAsync<any>(\n `SELECT * FROM ${this.prefix}tasks WHERE id = ? AND deleted_at IS NULL`,\n [id],\n );\n return row ? mapRowToTask(row) : null;\n }\n\n /**\n * Fetch all pending/in_progress tasks for the given entity IDs.\n * Returns empty array when entityIds is empty.\n */\n async findAllPending(entityIds: string[], limit?: number): Promise<WikiTask[]> {\n if (entityIds.length === 0) return [];\n const placeholders = entityIds.map(() => '?').join(', ');\n const sql =\n `SELECT * FROM ${this.prefix}tasks ` +\n `WHERE entity_id IN (${placeholders}) AND status IN ('pending', 'in_progress') AND deleted_at IS NULL ` +\n `ORDER BY priority DESC, created_at ASC` +\n (limit != null ? ` LIMIT ?` : '');\n const params: unknown[] = limit != null ? [...entityIds, limit] : [...entityIds];\n const rows = await this.db.getAllAsync<any>(sql, params);\n return rows.map(mapRowToTask);\n }\n\n async findExistingMetadataByIds(\n ids: readonly string[],\n tx?: SQLiteAdapter,\n ): Promise<Array<{ id: string; entity_id: string; updated_at: number }>> {\n const executor = this.getExecutor(tx);\n const rows: Array<{ id: string; entity_id: string; updated_at: number }> = [];\n const chunkSize = 500;\n for (let i = 0; i < ids.length; i += chunkSize) {\n const chunk = ids.slice(i, i + chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n const chunkRows = await executor.getAllAsync<any>(\n `SELECT id, entity_id, updated_at FROM ${this.prefix}tasks WHERE id IN (${placeholders})`,\n chunk,\n );\n rows.push(...chunkRows.map((row) => ({ id: row.id, entity_id: row.entity_id, updated_at: Number(row.updated_at) })));\n }\n return rows;\n }\n\n /**\n * Upsert a WikiTask within the provided transaction.\n * Uses ON CONFLICT(id) DO UPDATE (not INSERT OR REPLACE).\n * Stages an outbox entry in the same transaction.\n * `tx` is REQUIRED.\n *\n * OKF metadata (lifecycle_status, sources, etc.) is intentionally excluded\n * from the SET clause so content writes preserve any existing row values.\n * See {@link EntryRepository.upsert} for the rationale — the same applies\n * symmetrically to tasks (spec §2.5). Callers that need to overwrite OKF\n * metadata should use {@link upsertForImport}.\n */\n async upsert(task: WikiTask, tx: SQLiteAdapter, updatedAt?: number): Promise<void> {\n const executor = this.getExecutor(tx);\n const now = Number.isFinite(updatedAt) ? updatedAt : Date.now();\n\n const existingRow = await executor.getFirstAsync<{\n id: string;\n lifecycle_status: string;\n stale_after: number | null;\n generated_by: string | null;\n okf_sources: string | null;\n okf_verified: string | null;\n okf_usage_window: string | null;\n last_verified_at: number | null;\n last_verified_by: string | null;\n }>(\n `SELECT id, lifecycle_status, stale_after, generated_by,\n okf_sources, okf_verified, okf_usage_window,\n last_verified_at, last_verified_by\n FROM ${this.prefix}tasks WHERE id = ?`,\n [task.id],\n );\n const operation = task.deleted_at != null ? 'DELETE' : (existingRow ? 'UPDATE' : 'INSERT');\n\n await executor.runAsync(\n `INSERT INTO ${this.prefix}tasks (\n id, entity_id, description, status, priority,\n created_at, updated_at, resolved_at, deleted_at,\n lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,\n okf_sources, okf_verified, okf_usage_window\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n entity_id = excluded.entity_id,\n description = excluded.description,\n status = excluded.status,\n priority = excluded.priority,\n updated_at = excluded.updated_at,\n resolved_at = excluded.resolved_at,\n deleted_at = excluded.deleted_at`,\n [\n task.id,\n task.entity_id,\n task.description,\n task.status,\n task.priority,\n task.created_at,\n now, // updated_at set by repo or import override\n task.resolved_at ?? null,\n task.deleted_at ?? null,\n // OKF v0.2 metadata — bound for INSERT only; ON CONFLICT UPDATE\n // preserves the existing row values (these columns are intentionally\n // absent from the SET clause above).\n task.lifecycle_status ?? 'stable',\n task.stale_after ?? null,\n task.generated_by ?? null,\n task.last_verified_at ?? null,\n task.last_verified_by ?? null,\n task.okf_sources ? JSON.stringify(task.okf_sources) : null,\n task.okf_verified ? JSON.stringify(task.okf_verified) : null,\n task.okf_usage_window ? JSON.stringify(task.okf_usage_window) : null,\n ],\n );\n\n // Outbox payload mirrors what is actually persisted. On UPDATE, the SET\n // clause intentionally omits OKF metadata so prior row values win, but\n // the caller-supplied `task` would still describe state we did NOT write.\n // Re-read those columns from the stored row and overlay them onto the\n // caller-supplied payload before publishing (#90 review).\n const persistedOkf = existingRow\n ? {\n lifecycle_status: (existingRow.lifecycle_status ?? 'stable') as WikiTask['lifecycle_status'],\n stale_after: existingRow.stale_after != null ? Number(existingRow.stale_after) : null,\n generated_by: existingRow.generated_by ?? null,\n okf_sources: parseJsonArray<NonNullable<WikiTask['okf_sources']>[number]>(existingRow.okf_sources, []),\n okf_verified: parseJsonArray<NonNullable<WikiTask['okf_verified']>[number]>(existingRow.okf_verified, []),\n okf_usage_window: parseJsonObject<NonNullable<WikiTask['okf_usage_window']>>(existingRow.okf_usage_window),\n last_verified_at: existingRow.last_verified_at != null ? Number(existingRow.last_verified_at) : null,\n last_verified_by: existingRow.last_verified_by ?? null,\n }\n : null;\n await this.outbox.push(\n {\n entityId: task.entity_id,\n tableName: 'tasks',\n recordId: task.id,\n operation,\n payload: persistedOkf ? { ...task, ...persistedOkf } : task,\n },\n tx,\n );\n }\n\n async upsertForImport(task: WikiTask, tx: SQLiteAdapter, updatedAt?: number): Promise<void> {\n const executor = this.getExecutor(tx);\n const now = Number.isFinite(updatedAt) ? updatedAt : Date.now();\n\n // Import is replace semantics, mirroring EntryRepository.upsertForImport.\n // Dump is authoritative: a re-import that cleared stale_after, generated_by,\n // or verification mirrors must overwrite, not preserve.\n await executor.runAsync(\n `INSERT INTO ${this.prefix}tasks (\n id, entity_id, description, status, priority,\n created_at, updated_at, resolved_at, deleted_at, okf_type,\n lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,\n okf_sources, okf_verified, okf_usage_window\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n entity_id = excluded.entity_id,\n description = excluded.description,\n status = excluded.status,\n priority = excluded.priority,\n updated_at = excluded.updated_at,\n resolved_at = excluded.resolved_at,\n deleted_at = excluded.deleted_at,\n okf_type = excluded.okf_type,\n lifecycle_status = excluded.lifecycle_status,\n stale_after = excluded.stale_after,\n generated_by = excluded.generated_by,\n last_verified_at = excluded.last_verified_at,\n last_verified_by = excluded.last_verified_by,\n okf_sources = excluded.okf_sources,\n okf_verified = excluded.okf_verified,\n okf_usage_window = excluded.okf_usage_window`,\n [\n task.id,\n task.entity_id,\n task.description,\n task.status,\n task.priority,\n task.created_at,\n now,\n task.resolved_at ?? null,\n task.deleted_at ?? null,\n task.okf_type ?? null,\n task.lifecycle_status ?? 'stable',\n task.stale_after ?? null,\n task.generated_by ?? null,\n task.last_verified_at ?? null,\n task.last_verified_by ?? null,\n task.okf_sources ? JSON.stringify(task.okf_sources) : null,\n task.okf_verified ? JSON.stringify(task.okf_verified) : null,\n task.okf_usage_window ? JSON.stringify(task.okf_usage_window) : null,\n ],\n );\n }\n\n /**\n * Soft-delete a task by ID. Sets deleted_at and updated_at.\n * Stages a DELETE outbox entry in the same transaction.\n * `tx` is REQUIRED.\n */\n async softDelete(id: string, entityId: string, tx: SQLiteAdapter): Promise<void> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n await executor.runAsync(\n `UPDATE ${this.prefix}tasks SET deleted_at = ?, updated_at = ? WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,\n [now, now, id, entityId],\n );\n await this.outbox.push(\n {\n entityId,\n tableName: 'tasks',\n recordId: id,\n operation: 'DELETE',\n payload: { id, entity_id: entityId, deleted_at: now },\n },\n tx,\n );\n }\n\n /**\n * Fetch all non-deleted tasks for an entity, ordered by priority DESC, created_at ASC.\n * Used by _getFullBundle().\n */\n async findAllByEntityId(entityId: string, tx?: SQLiteAdapter): Promise<WikiTask[]> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NULL ORDER BY priority DESC, created_at ASC`,\n [entityId],\n );\n return rows.map(mapRowToTask);\n }\n\n /**\n * Bulk delete pruned tasks (already soft-deleted) by cutoff date.\n * Used by runPrune(). Returns number of deleted rows.\n */\n async bulkDeletePruned(\n entityId: string,\n cutoff: number,\n tx: SQLiteAdapter,\n ): Promise<number> {\n const executor = this.getExecutor(tx);\n const rowsToDelete = await executor.getAllAsync<{ id: string; deleted_at: number }>(\n `SELECT id, deleted_at FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ?`,\n [entityId, cutoff],\n );\n if (rowsToDelete.length === 0) return 0;\n\n const result = await executor.runAsync(\n `DELETE FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ?`,\n [entityId, cutoff],\n );\n\n for (const row of rowsToDelete) {\n await this.outbox.push(\n {\n entityId,\n tableName: 'tasks',\n recordId: row.id,\n operation: 'DELETE',\n payload: { id: row.id, entity_id: entityId, deleted_at: row.deleted_at },\n },\n tx,\n );\n }\n\n return result.changes;\n }\n\n /**\n * Soft-delete a task by ID within a transaction.\n * Stages a DELETE outbox entry in the same transaction.\n * `tx` is REQUIRED.\n */\n async softDeleteById(\n id: string,\n entityId: string,\n tx: SQLiteAdapter,\n ): Promise<{ changes: number }> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n const result = await executor.runAsync(\n `UPDATE ${this.prefix}tasks SET deleted_at = ?, updated_at = ? WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,\n [now, now, id, entityId],\n );\n if (result.changes > 0) {\n await this.outbox.push(\n {\n entityId,\n tableName: 'tasks',\n recordId: id,\n operation: 'DELETE',\n payload: { id, entity_id: entityId, deleted_at: now },\n },\n tx,\n );\n }\n return result;\n }\n\n /**\n * Bulk soft-delete all tasks for an entity.\n * Stages DELETE outbox entries for each row in the same transaction.\n * `tx` is REQUIRED.\n */\n async bulkSoftDeleteByEntityId(entityId: string, tx: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n // Get IDs before updating for outbox staging\n const idsToDelete = await executor.getAllAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NULL`,\n [entityId],\n );\n const result = await executor.runAsync(\n `UPDATE ${this.prefix}tasks SET deleted_at = ?, updated_at = ? WHERE entity_id = ? AND deleted_at IS NULL`,\n [now, now, entityId],\n );\n // Stage outbox entries for each deleted record\n for (const row of idsToDelete) {\n await this.outbox.push({\n entityId,\n tableName: 'tasks',\n recordId: row.id,\n operation: 'DELETE',\n payload: { id: row.id, entity_id: entityId, deleted_at: now },\n }, tx);\n }\n return result.changes;\n }\n\n /**\n * Count live tasks for an entity. Used by forget({ dryRun, clearAll: true }).\n */\n async countLiveByEntityId(entityId: string, tx?: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ cnt: number }>(\n `SELECT COUNT(*) AS cnt FROM ${this.prefix}tasks\n WHERE entity_id = ? AND deleted_at IS NULL`,\n [entityId],\n );\n return row?.cnt ?? 0;\n }\n}\n","import { BaseRepository } from './BaseRepository';\nimport type { WikiEvent, SQLiteAdapter } from '../types';\n\nexport class EventRepository extends BaseRepository {\n /**\n * Insert a new event row.\n * Pass `tx` to participate in a caller-owned transaction; omit to run against the default db.\n */\n async add(event: WikiEvent, tx?: SQLiteAdapter): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `INSERT INTO ${this.prefix}events (id, entity_id, event_type, summary, related_entry_id, created_at)\n VALUES (?, ?, ?, ?, ?, ?)`,\n [\n event.id,\n event.entity_id,\n event.event_type,\n event.summary,\n event.related_entry_id ?? null,\n event.created_at,\n ],\n );\n }\n\n async addIgnoreDuplicate(event: WikiEvent, tx?: SQLiteAdapter): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `INSERT OR IGNORE INTO ${this.prefix}events (id, entity_id, event_type, summary, related_entry_id, created_at)\n VALUES (?, ?, ?, ?, ?, ?)`,\n [\n event.id,\n event.entity_id,\n event.event_type,\n event.summary,\n event.related_entry_id ?? null,\n event.created_at,\n ],\n );\n }\n\n /**\n * Return the most recent events for an entity, newest first.\n * Defaults to a limit of 50.\n */\n async getRecent(entityId: string, limit = 50): Promise<WikiEvent[]> {\n return this.db.getAllAsync<WikiEvent>(\n `SELECT * FROM ${this.prefix}events WHERE entity_id = ? ORDER BY created_at DESC LIMIT ?`,\n [entityId, limit],\n );\n }\n\n /**\n * Return the most recent events for the given entity IDs, newest first.\n * Defaults to a limit of 50.\n */\n async getRecentForEntities(entityIds: string[], limit = 50): Promise<WikiEvent[]> {\n if (entityIds.length === 0) return [];\n const placeholders = entityIds.map(() => '?').join(', ');\n return this.db.getAllAsync<WikiEvent>(\n `SELECT * FROM ${this.prefix}events WHERE entity_id IN (${placeholders}) ORDER BY created_at DESC LIMIT ?`,\n [...entityIds, limit],\n );\n }\n\n /**\n * Delete events for an entity that were created at or before the given cutoff timestamp.\n * Returns the number of deleted rows.\n */\n async prune(entityId: string, cutoff: number): Promise<{ changes: number }> {\n return this.db.runAsync(\n `DELETE FROM ${this.prefix}events WHERE entity_id = ? AND created_at <= ?`,\n [entityId, cutoff],\n );\n }\n\n /**\n * Return the total number of events stored for an entity.\n * `tx` is optional — pass an active transaction handle for atomic reads.\n */\n async count(entityId: string, tx?: SQLiteAdapter): Promise<number> {\n const executor = tx ?? this.db;\n const row = await executor.getFirstAsync<{ count: number }>(\n `SELECT COUNT(*) as count FROM ${this.prefix}events WHERE entity_id = ?`,\n [entityId],\n );\n return row?.count ?? 0;\n }\n\n /**\n * Return all events for an entity in chronological (ASC) order.\n * When limit is provided, fetches newest-first then reverses to preserve chronological order.\n */\n async getByEntityId(entityId: string, limit?: number): Promise<WikiEvent[]> {\n if (limit != null) {\n const rows = await this.db.getAllAsync<WikiEvent>(\n `SELECT * FROM ${this.prefix}events WHERE entity_id = ? ORDER BY created_at DESC LIMIT ?`,\n [entityId, limit],\n );\n return rows.slice().reverse();\n }\n return this.db.getAllAsync<WikiEvent>(\n `SELECT * FROM ${this.prefix}events WHERE entity_id = ? ORDER BY created_at ASC`,\n [entityId],\n );\n }\n}\n","import { BaseRepository } from './BaseRepository';\nimport type { WikiEdge, SQLiteAdapter } from '../types';\n\nexport interface NeighborhoodQueryOptions {\n maxDepth: number; // already clamped to [1,3] by the caller (GraphTraversalService)\n direction: 'inbound' | 'outbound' | 'both';\n edgeTypes?: string[]; // undefined = no filter; [] = match nothing (short-circuits)\n minConfidence: 'certain' | 'inferred' | 'tentative';\n excludeSourceTypes: string[];\n maxNodes: number;\n /**\n * When true, draft facts are dead-ends for *discovered* nodes — the recursive\n * walk will not step onto a draft, and will not step *past* one either, since\n * a draft's neighbours are unreachable through it. The anchor node is exempt\n * (it is validated up-front and never gated by this flag), so callers can\n * intentionally start from a draft. Default false (drafts visible).\n */\n excludeDrafts?: boolean;\n}\n\nconst CONFIDENCE_RANK: Record<'tentative' | 'inferred' | 'certain', number> = {\n tentative: 0,\n inferred: 1,\n certain: 2,\n};\n\nexport class EdgeRepository extends BaseRepository {\n /**\n * Insert an edge, silently skipping on primary-key or uniqueness conflicts.\n * Returns true when a row was inserted, false when skipped as a duplicate.\n * Throws when the insert was skipped due to an id collision with a different edge tuple.\n */\n async addIgnoreDuplicate(edge: WikiEdge, tx?: SQLiteAdapter): Promise<boolean> {\n const executor = this.getExecutor(tx);\n const result = await executor.runAsync(\n `INSERT OR IGNORE INTO ${this.prefix}edges (id, entity_id, source_id, target_id, edge_type, created_at)\n VALUES (?, ?, ?, ?, ?, ?)`,\n [edge.id, edge.entity_id, edge.source_id, edge.target_id, edge.edge_type, edge.created_at],\n );\n\n if (result.changes > 0) return true;\n\n const existing = await executor.getFirstAsync<{\n entity_id: string;\n source_id: string;\n target_id: string;\n edge_type: string;\n }>(\n `SELECT entity_id, source_id, target_id, edge_type FROM ${this.prefix}edges WHERE id = ?`,\n [edge.id],\n );\n\n if (!existing) return false;\n\n if (\n String(existing.entity_id) !== edge.entity_id ||\n String(existing.source_id) !== edge.source_id ||\n String(existing.target_id) !== edge.target_id ||\n String(existing.edge_type) !== edge.edge_type\n ) {\n throw new Error(\n `Edge id collision: ${JSON.stringify(edge.id)} already exists with a different (entity_id, source_id, target_id, edge_type) tuple`,\n );\n }\n\n return false;\n }\n\n async getByEntityId(entityId: string, tx?: SQLiteAdapter): Promise<WikiEdge[]> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}edges WHERE entity_id = ? ORDER BY created_at ASC`,\n [entityId],\n );\n return rows.map(mapRowToEdge);\n }\n\n /** Hard delete — edges have no soft-delete concept, only presence/absence. `tx` is REQUIRED. */\n async bulkDeleteByEntityId(entityId: string, tx: SQLiteAdapter): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(`DELETE FROM ${this.prefix}edges WHERE entity_id = ?`, [entityId]);\n }\n\n /**\n * Hard-delete every edge whose `source_id` is in `sourceFactIds`, scoped to\n * `entityId`. Returns the number of rows deleted. Edges have no soft-delete\n * concept; this method is named `softDeleteBySourceFactIds` for symmetry with\n * `EntryRepository.softDeleteBySource` (which IS a soft delete), but its\n * semantics are immediate presence/absence removal. Use ONLY inside an open\n * transaction — the method requires `tx` and performs no autocommit.\n *\n * Used by `IngestionService.upsertGraphCore` to retire the prior parse's\n * edges whose source facts are being superseded by `softDeleteBySource`.\n */\n async softDeleteBySourceFactIds(\n entityId: string,\n sourceFactIds: readonly string[],\n tx: SQLiteAdapter,\n ): Promise<number> {\n if (sourceFactIds.length === 0) return 0;\n const executor = this.getExecutor(tx);\n // SQLite's SQLITE_MAX_VARIABLE_NUMBER defaults to 32,766; binding\n // `entityId` plus every ID in one statement would overflow once a\n // single sourceRef accumulates tens of thousands of facts. Chunk to\n // stay well under the limit, reusing the supplied tx executor.\n const chunkSize = 500;\n let totalChanges = 0;\n for (let i = 0; i < sourceFactIds.length; i += chunkSize) {\n const chunk = sourceFactIds.slice(i, i + chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n const result = await executor.runAsync(\n `DELETE FROM ${this.prefix}edges\n WHERE entity_id = ? AND source_id IN (${placeholders})`,\n [entityId, ...chunk],\n );\n totalChanges += result.changes;\n }\n return totalChanges;\n }\n\n /**\n * Multi-hop traversal from `sourceId` via SQLite `WITH RECURSIVE`. All filtering,\n * dead-ending, cycle-guarding, capping, and ordering happens in this one query.\n * The anchor is validated (exists, right entity, not soft-deleted) but never gated\n * by confidence/source_type — only nodes discovered beyond it are.\n */\n async getNeighborhood(\n entityId: string,\n sourceId: string,\n opts: NeighborhoodQueryOptions,\n tx?: SQLiteAdapter,\n ): Promise<{ nodeIds: string[]; edges: WikiEdge[] }> {\n const executor = this.getExecutor(tx);\n\n if (opts.edgeTypes && opts.edgeTypes.length === 0) {\n const anchor = await executor.getFirstAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}entries WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,\n [sourceId, entityId],\n );\n return { nodeIds: anchor ? [anchor.id] : [], edges: [] };\n }\n\n const edgeTypesClause = opts.edgeTypes\n ? `e.edge_type IN (${opts.edgeTypes.map(() => '?').join(',')})`\n : '1=1';\n const excludeSourceTypesPlaceholders = opts.excludeSourceTypes.map(() => '?').join(',');\n const minConfidenceRank = CONFIDENCE_RANK[opts.minConfidence];\n\n const sql = `\n WITH RECURSIVE walk(node_id, depth, visited) AS (\n SELECT id, 0, ',' || id || ','\n FROM ${this.prefix}entries\n WHERE id = ? AND entity_id = ? AND deleted_at IS NULL\n\n UNION\n\n SELECT\n CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END,\n w.depth + 1,\n w.visited || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ','\n FROM walk w\n JOIN ${this.prefix}edges e\n ON e.entity_id = ?\n AND (\n (? != 'inbound' AND e.source_id = w.node_id) OR\n (? != 'outbound' AND e.target_id = w.node_id)\n )\n AND (${edgeTypesClause})\n JOIN ${this.prefix}entries n\n ON n.id = (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END)\n AND n.entity_id = ?\n AND n.deleted_at IS NULL\n AND (\n CASE n.confidence\n WHEN 'tentative' THEN 0\n WHEN 'inferred' THEN 1\n WHEN 'certain' THEN 2\n ELSE -1\n END\n ) >= ?\n AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})\n AND (? = 0 OR n.lifecycle_status != 'draft')\n WHERE w.depth < ?\n AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0\n )\n SELECT node_id, MIN(depth) AS depth\n FROM walk\n GROUP BY node_id\n ORDER BY depth ASC, (SELECT updated_at FROM ${this.prefix}entries WHERE id = node_id) DESC\n LIMIT ?\n `;\n\n const params: unknown[] = [\n sourceId, entityId,\n entityId,\n opts.direction, opts.direction,\n ...(opts.edgeTypes ?? []),\n entityId,\n minConfidenceRank,\n ...opts.excludeSourceTypes,\n opts.excludeDrafts === true ? 1 : 0,\n opts.maxDepth,\n opts.maxNodes,\n ];\n\n const rows = await executor.getAllAsync<{ node_id: string; depth: number }>(sql, params);\n const nodeIds = rows.map((r) => r.node_id);\n if (nodeIds.length === 0) return { nodeIds: [], edges: [] };\n\n const valueRows = nodeIds.map(() => '(?)').join(', ');\n const edgeRows = await executor.getAllAsync<any>(\n `WITH neighborhood(node_id) AS (VALUES ${valueRows})\n SELECT e.* FROM ${this.prefix}edges e\n JOIN neighborhood ns ON e.source_id = ns.node_id\n JOIN neighborhood nt ON e.target_id = nt.node_id\n WHERE e.entity_id = ?`,\n [...nodeIds, entityId],\n );\n\n return { nodeIds, edges: edgeRows.map(mapRowToEdge) };\n }\n}\n\nfunction mapRowToEdge(row: any): WikiEdge {\n return {\n id: String(row.id),\n entity_id: String(row.entity_id),\n source_id: String(row.source_id),\n target_id: String(row.target_id),\n edge_type: String(row.edge_type),\n created_at: Number(row.created_at),\n };\n}\n","import type { OntologyMode } from '../types';\n\nconst FACT_ONTOLOGY_FIELDS = `\nEach fact may optionally include:\n- \"okf_type\": string — must be one of the node_types in the manifest\n- \"edges\": [{ \"edge_type\": string, \"target_title\": string }] — target_title must match another fact's title in this response or existing memory\n- An edge_type may appear in the manifest multiple times with different source_type/target_type; use the row whose types match your fact and target.`;\n\nconst EMERGENT_EXTRA = `\nYou may also return \"ontology_updates\" to propose new types:\n\"ontology_updates\": {\n \"node_types\": [{ \"type\": \"slug\", \"description\": \"...\", \"parent_type\": \"optional existing slug\" }],\n \"edge_types\": [{ \"type\": \"slug\", \"source_type\": \"...\", \"target_type\": \"...\", \"description\": \"...\" }]\n}\nOnly propose types not already in the manifest. Do not redefine existing types.`;\n\nexport function buildOntologyPromptAppendix(\n mode: OntologyMode,\n manifestJson: string,\n): { ontologyManifest: string; ontologyModeInstructions: string } {\n const strictRules = mode === 'strict'\n ? 'STRICT MODE: Use ONLY types defined in the manifest. If a fact does not fit any node_type, omit okf_type and edges entirely.'\n : 'EMERGENT MODE: Prefer manifest types. You may propose new types via ontology_updates when necessary.';\n\n const fallback = 'If okf_type or an edge is invalid, omit them rather than inventing unlisted types.';\n\n const ontologyModeInstructions = [\n '## Ontology constraints',\n strictRules,\n fallback,\n FACT_ONTOLOGY_FIELDS,\n mode === 'emergent' ? EMERGENT_EXTRA : '',\n 'Manifest:',\n manifestJson,\n ].filter(Boolean).join('\\n');\n\n return { ontologyManifest: manifestJson, ontologyModeInstructions };\n}\n","import type {\n OntologyConfig,\n OntologyManifest,\n OntologyMode,\n OntologyPromptContext,\n OntologyUpdates,\n ExtractedFactWithOntology,\n ExtractedFactEdge,\n SQLiteAdapter,\n WikiEdge,\n} from '../types';\nimport { WikiStrictOntologyViolation } from '../types';\nimport type { MetadataRepository } from '../repositories/MetadataRepository';\nimport type { EdgeRepository } from '../repositories/EdgeRepository';\nimport { buildOntologyPromptAppendix } from '../prompts/ontology';\nimport {\n emptyManifest,\n normalizeTitleKey,\n resolveNodeType,\n resolveEdgeDefinitions,\n typeSatisfies,\n validateInlineEdges,\n validateManifest,\n type EdgeDrop,\n} from '../utils/ontology';\nimport { generateId } from '../utils/ids';\n\nexport type TitleIndexEntry = { id: string; okf_type: string | null };\n\n/**\n * Coordinates ontology mode resolution, manifest caching, LLM output validation, and edge persistence.\n * Cache is per WikiMemory instance (single-process); not shared across instances.\n */\nexport class OntologyService {\n private cache = new Map<string, { mode: OntologyMode; manifest: OntologyManifest }>();\n\n constructor(\n private metadataRepo: MetadataRepository,\n private edgeRepo: EdgeRepository,\n private ontologyConfig?: OntologyConfig,\n ) {}\n\n resolveMode(storedMode?: OntologyMode): OntologyMode {\n return storedMode ?? this.ontologyConfig?.mode ?? 'off';\n }\n\n invalidateCache(entityId: string): void {\n this.cache.delete(entityId);\n }\n\n async getEffectiveState(entityId: string, tx?: SQLiteAdapter): Promise<{\n mode: OntologyMode;\n manifest: OntologyManifest;\n }> {\n if (!tx) {\n const cached = this.cache.get(entityId);\n if (cached) return cached;\n }\n\n const row = await this.metadataRepo.getManifest(entityId, tx);\n if (row) {\n const state = { mode: this.resolveMode(row.mode), manifest: row.manifest };\n if (!tx) this.cache.set(entityId, state);\n return state;\n }\n\n const seed = this.ontologyConfig?.seedManifests?.[entityId];\n if (seed) {\n // D11: the tx branch validates via setManifest; the cache branch did not.\n validateManifest(seed.manifest);\n const state = {\n mode: this.resolveMode(seed.mode),\n manifest: seed.manifest,\n };\n if (tx) {\n await this.metadataRepo.setManifest(entityId, state, tx);\n } else {\n this.cache.set(entityId, state);\n }\n return state;\n }\n\n return { mode: 'off', manifest: emptyManifest() };\n }\n\n async buildPromptContext(entityId: string): Promise<OntologyPromptContext | null> {\n const { mode, manifest } = await this.getEffectiveState(entityId);\n if (mode === 'off') return null;\n const manifestJson = JSON.stringify(manifest, null, 2);\n return buildOntologyPromptAppendix(mode, manifestJson);\n }\n\n async mergeEmergentUpdates(\n entityId: string,\n updates: OntologyUpdates,\n tx: SQLiteAdapter,\n ): Promise<OntologyManifest> {\n const merged = await this.metadataRepo.mergeManifestUpdates(entityId, updates, tx);\n this.invalidateCache(entityId);\n return merged;\n }\n\n validateAndNormalizeFact(\n fact: ExtractedFactWithOntology,\n manifest: OntologyManifest,\n opts?: { strict?: boolean; entityId?: string; drops?: EdgeDrop[] },\n ): { okf_type: string | null; edges: ExtractedFactEdge[] } {\n const rawType = typeof fact.okf_type === 'string' ? fact.okf_type : '';\n const strict = opts?.strict === true;\n const canonical = resolveNodeType(rawType, manifest);\n if (!canonical) {\n if (strict) throw new WikiStrictOntologyViolation(opts?.entityId ?? '', 'node', rawType);\n if (opts?.drops && Array.isArray(fact.edges)) {\n for (const edge of fact.edges) {\n opts.drops.push({\n reason: 'no_source_type',\n sourceId: null,\n edgeType: typeof edge?.edge_type === 'string' ? edge.edge_type : null,\n sourceNodeType: null,\n targetNodeType: null,\n });\n }\n }\n return { okf_type: null, edges: [] };\n }\n const edges = validateInlineEdges(canonical, null, fact.edges ?? [], manifest, opts);\n return { okf_type: canonical, edges };\n }\n\n /**\n * Pure resolver: given a source type, LLM-supplied edges, the manifest,\n * and a title index, return a list of concrete `WikiEdge` objects ready\n * for persistence. Performs no DB writes. Used by callers that batch edge\n * writes inside their own transaction (e.g. `IngestionService.ingestDocument`\n * when delegating to `upsertGraphCore`).\n */\n resolveEdges(\n entityId: string,\n sourceId: string,\n sourceType: string | null,\n edges: ExtractedFactEdge[],\n manifest: OntologyManifest,\n titleIndex: Map<string, TitleIndexEntry>,\n now: number,\n drops?: EdgeDrop[],\n ): WikiEdge[] {\n if (edges.length === 0) return [];\n if (!sourceType) {\n for (const edge of edges) {\n drops?.push({ reason: 'no_source_type', sourceId, edgeType: edge.edge_type, sourceNodeType: null, targetNodeType: null });\n }\n return [];\n }\n const out: WikiEdge[] = [];\n for (const edge of edges) {\n const candidates = resolveEdgeDefinitions(edge.edge_type, manifest)\n .filter(d => typeSatisfies(d.source_type, sourceType, manifest));\n if (candidates.length === 0) {\n drops?.push({ reason: 'type_not_in_manifest', sourceId, edgeType: edge.edge_type, sourceNodeType: sourceType, targetNodeType: null });\n continue;\n }\n\n const targetKey = normalizeTitleKey(edge.target_title);\n const target = titleIndex.get(targetKey);\n if (!target) {\n drops?.push({ reason: 'target_not_found', sourceId, edgeType: edge.edge_type, sourceNodeType: sourceType, targetNodeType: null });\n continue;\n }\n\n const targetType = (target.okf_type ?? '').trim().toLowerCase();\n const def = candidates.find(d => d.target_type.trim().toLowerCase() === targetType)\n ?? candidates.find(d => typeSatisfies(d.target_type, targetType, manifest));\n if (!def) {\n drops?.push({\n reason: 'target_type_mismatch', sourceId, edgeType: edge.edge_type,\n sourceNodeType: sourceType, targetNodeType: target.okf_type ?? null,\n });\n continue;\n }\n\n out.push({\n id: generateId(),\n entity_id: entityId,\n source_id: sourceId,\n target_id: target.id,\n edge_type: def.type,\n created_at: now,\n });\n }\n return out;\n }\n\n /**\n * Backwards-compatible wrapper: resolves edges via {@link resolveEdges},\n * then persists each via `edgeRepo.addIgnoreDuplicate` in the supplied\n * transaction. Returns the number of edges persisted. Used by paths that\n * want self-contained edge persistence (e.g. MaintenanceService heal /\n * backfill callers that do not have a separate edge-write step).\n */\n async resolveAndPersistEdges(\n entityId: string,\n sourceId: string,\n sourceType: string | null,\n edges: ExtractedFactEdge[],\n manifest: OntologyManifest,\n titleIndex: Map<string, TitleIndexEntry>,\n tx: SQLiteAdapter,\n now: number,\n drops?: EdgeDrop[],\n ): Promise<number> {\n const resolved = this.resolveEdges(entityId, sourceId, sourceType, edges, manifest, titleIndex, now, drops);\n let persisted = 0;\n for (const edge of resolved) {\n const inserted = await this.edgeRepo.addIgnoreDuplicate(edge, tx);\n if (inserted) persisted++;\n }\n return persisted;\n }\n}\n","import type { EdgeRepository, NeighborhoodQueryOptions } from '../repositories/EdgeRepository';\nimport type { EntryRepository } from '../repositories/EntryRepository';\nimport type { GraphTraversalOptions, GraphNeighborhood, WikiConfig } from '../types';\n\n/**\n * Pure orchestrator — no SQL. Merges WikiConfig defaults with per-call options,\n * delegates the recursive walk to EdgeRepository, then hydrates node IDs into facts.\n */\nexport class GraphTraversalService {\n constructor(\n private edgeRepo: EdgeRepository,\n private entryRepo: EntryRepository,\n private config: WikiConfig,\n ) {}\n\n async traverseGraph(entityId: string, options: GraphTraversalOptions): Promise<GraphNeighborhood> {\n const fallbackMaxNodes = 20;\n const rawConfigDefault = this.config.maxTraversalNodes ?? fallbackMaxNodes;\n const defaultMaxNodes =\n Number.isFinite(rawConfigDefault) && rawConfigDefault >= 1\n ? Math.floor(rawConfigDefault)\n : fallbackMaxNodes;\n const rawMaxNodes = options.maxTraversalNodes ?? defaultMaxNodes;\n const maxNodes =\n Number.isFinite(rawMaxNodes) && rawMaxNodes >= 1 ? Math.floor(rawMaxNodes) : defaultMaxNodes;\n\n const opts: NeighborhoodQueryOptions = {\n maxDepth: Math.max(1, Math.min(options.maxDepth ?? 1, 3)),\n direction: options.direction ?? this.config.traversalDirection ?? 'both',\n edgeTypes: options.edgeTypes,\n minConfidence: options.minTraversalConfidence ?? this.config.minTraversalConfidence ?? 'tentative',\n excludeSourceTypes: options.excludeSourceTypes ?? this.config.excludeSourceTypes ?? [],\n excludeDrafts: options.excludeDrafts ?? this.config.excludeDrafts ?? false,\n maxNodes,\n };\n\n const { nodeIds, edges } = await this.edgeRepo.getNeighborhood(entityId, options.sourceId, opts);\n if (nodeIds.length === 0) return { nodes: [], edges: [] };\n\n // findByIds() returns facts in input-ID order (Map-based lookup,\n // see packages/core/src/repositories/EntryRepository.ts:104-108) — no re-sort needed.\n const nodes = await this.entryRepo.findByIds(nodeIds, [entityId]);\n const hydratedIds = new Set(nodes.map((node) => node.id));\n const filteredEdges = edges.filter(\n (edge) => hydratedIds.has(edge.source_id) && hydratedIds.has(edge.target_id),\n );\n return { nodes, edges: filteredEdges };\n }\n}\n","import type { SQLiteAdapter } from '../types';\nimport {\n formatSourcesJson,\n formatVerifiedJson,\n latestVerified,\n} from '@equationalapplications/core-okf';\n\nexport type OkfSource = {\n id?: string;\n resource: string;\n title?: string;\n author?: string;\n usage_count?: number;\n last_modified?: string;\n usage_window?: { from: string; to: string };\n};\nexport type OkfVerifiedEntry = { by: string; at: string };\n\n/**\n * DAO discipline (spec §8): only knowledge-content writes may bump `updated_at`.\n * Trust / provenance / lifecycle / freshness writes MUST NOT touch it. Every\n * `UPDATE` in this class is a non-content metadata write. Tests in\n * `__tests__/daoDiscipline.test.ts` and `__tests__/okfTrustWrites.test.ts`\n * snapshot the SQL via a logging adapter and assert the SET clause omits\n * `updated_at`.\n *\n * Deliberately does NOT push an outbox event, unlike `EntryRepository.upsert`\n * / `TaskRepository.upsert` (spec §8 \"Outbox/transaction scope\" note): outbox\n * delivery exists for *content* sync, and these writes are metadata, not\n * content, by the same reasoning that exempts them from `updated_at`. A\n * downstream sync consumer will not learn about a new verifier until the\n * next full re-export/re-import — accepted for v0.2.\n */\nexport class OkfTrustWritesRepository {\n constructor(private db: SQLiteAdapter, private prefix: string) {}\n\n private getExecutor(tx?: SQLiteAdapter): SQLiteAdapter {\n return tx ?? this.db;\n }\n\n /**\n * Append one or more verification events to a fact's `okf_verified` JSON\n * array, atomically, in a single SQL statement.\n *\n * The implementation uses json_each over the existing array UNION ALL'd\n * with json_each over the new events wrapped in json_group_array — a single\n * UPDATE expression. SQLite serializes this against concurrent writers on\n * the same row, so two callers appending simultaneously cannot lose each\n * other's events (the previous implementation serialized only the supplied\n * array and overwrote, dropping any pre-existing history).\n *\n * Sets the `last_verified_*` convenience columns from the latest event in\n * the union (computed in code; see {@link latestVerified}).\n */\n async writeOkfTrust(\n entryId: string,\n entityId: string,\n verified: OkfVerifiedEntry[],\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n if (verified.length === 0) return;\n const latest = latestVerified(verified, Date.now());\n const newEventsJson = JSON.stringify(verified);\n await executor.runAsync(\n `UPDATE ${this.prefix}entries\n SET okf_verified = COALESCE(\n (SELECT json_group_array(json_object('by', s.by_val, 'at', s.at_val))\n FROM (\n SELECT json_extract(value, '$.by') AS by_val,\n json_extract(value, '$.at') AS at_val\n FROM json_each(okf_verified)\n UNION ALL\n SELECT json_extract(value, '$.by'),\n json_extract(value, '$.at')\n FROM json_each(?)\n ) AS s\n ORDER BY s.at_val),\n '[]'\n ),\n last_verified_by = ?,\n last_verified_at = ?\n WHERE id = ? AND entity_id = ?`,\n [newEventsJson, latest?.by ?? null, latest?.at ?? null, entryId, entityId],\n );\n }\n\n /** Replace the `sources` list (provenance). */\n async writeOkfSources(\n entryId: string,\n entityId: string,\n sources: OkfSource[],\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n const json = formatSourcesJson(sources);\n await executor.runAsync(\n `UPDATE ${this.prefix}entries\n SET okf_sources = ?\n WHERE id = ? AND entity_id = ?`,\n [json, entryId, entityId],\n );\n }\n\n /** Set the OKF v0.2 lifecycle status. */\n async setLifecycleStatus(\n entryId: string,\n entityId: string,\n status: 'draft' | 'stable' | 'deprecated',\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `UPDATE ${this.prefix}entries\n SET lifecycle_status = ?\n WHERE id = ? AND entity_id = ?`,\n [status, entryId, entityId],\n );\n }\n\n /** Set the absolute cutoff (epoch ms) for staleness, or NULL to clear. */\n async setStaleAfter(\n entryId: string,\n entityId: string,\n date: number | null,\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `UPDATE ${this.prefix}entries\n SET stale_after = ?\n WHERE id = ? AND entity_id = ?`,\n [date, entryId, entityId],\n );\n }\n\n /** Set the producer / verifier actor string. Rare. */\n async setGeneratedBy(\n entryId: string,\n entityId: string,\n actor: string,\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `UPDATE ${this.prefix}entries\n SET generated_by = ?\n WHERE id = ? AND entity_id = ?`,\n [actor, entryId, entityId],\n );\n }\n\n // The same five methods exist for tasks, with `tasks` instead of `entries`.\n // Tasks are symmetric per spec §2.5.\n\n /** Atomic append, task variant — mirrors {@link writeOkfTrust}. */\n async writeOkfTrustTask(\n taskId: string,\n entityId: string,\n verified: OkfVerifiedEntry[],\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n if (verified.length === 0) return;\n const latest = latestVerified(verified, Date.now());\n const newEventsJson = JSON.stringify(verified);\n await executor.runAsync(\n `UPDATE ${this.prefix}tasks\n SET okf_verified = COALESCE(\n (SELECT json_group_array(json_object('by', s.by_val, 'at', s.at_val))\n FROM (\n SELECT json_extract(value, '$.by') AS by_val,\n json_extract(value, '$.at') AS at_val\n FROM json_each(okf_verified)\n UNION ALL\n SELECT json_extract(value, '$.by'),\n json_extract(value, '$.at')\n FROM json_each(?)\n ) AS s\n ORDER BY s.at_val),\n '[]'\n ),\n last_verified_by = ?,\n last_verified_at = ?\n WHERE id = ? AND entity_id = ?`,\n [newEventsJson, latest?.by ?? null, latest?.at ?? null, taskId, entityId],\n );\n }\n\n async writeOkfSourcesTask(\n taskId: string,\n entityId: string,\n sources: OkfSource[],\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n const json = formatSourcesJson(sources);\n await executor.runAsync(\n `UPDATE ${this.prefix}tasks\n SET okf_sources = ?\n WHERE id = ? AND entity_id = ?`,\n [json, taskId, entityId],\n );\n }\n\n async setLifecycleStatusTask(\n taskId: string,\n entityId: string,\n status: 'draft' | 'stable' | 'deprecated',\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `UPDATE ${this.prefix}tasks\n SET lifecycle_status = ?\n WHERE id = ? AND entity_id = ?`,\n [status, taskId, entityId],\n );\n }\n\n async setStaleAfterTask(\n taskId: string,\n entityId: string,\n date: number | null,\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `UPDATE ${this.prefix}tasks\n SET stale_after = ?\n WHERE id = ? AND entity_id = ?`,\n [date, taskId, entityId],\n );\n }\n\n async setGeneratedByTask(\n taskId: string,\n entityId: string,\n actor: string,\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `UPDATE ${this.prefix}tasks\n SET generated_by = ?\n WHERE id = ? AND entity_id = ?`,\n [actor, taskId, entityId],\n );\n }\n}\n","import type { SQLiteAdapter } from './types';\nimport type { WikiOutboxEvent } from './outbox/types';\nimport { setupDatabase } from './db/schema';\nimport { withSerializedTransactions } from './db/serializedAdapter';\nimport { MIGRATIONS, CURRENT_SCHEMA_VERSION } from './db/migrations';\nimport {\n WikiOptions,\n MemoryBundle,\n MemoryDump,\n WikiEvent,\n EntityStatus,\n ReadOptions,\n WikiSourceRefHashCollision,\n WikiDraftNotFound,\n} from './types';\nimport type { DraftPage } from './types';\nimport { EntryRepository } from './repositories/EntryRepository';\nimport { OutboxRepository } from './repositories/OutboxRepository';\nimport { SourceRefIndexRepository } from './repositories/SourceRefIndexRepository';\nimport { TaskRepository } from './repositories/TaskRepository';\nimport { EventRepository } from './repositories/EventRepository';\nimport { EdgeRepository } from './repositories/EdgeRepository';\nimport { MetadataRepository, entitySummaryMetaKey } from './repositories/MetadataRepository';\nimport { SearchService } from './services/SearchService';\nimport { JobManager } from './services/JobManager';\nimport { normalizeSourceRef, normalizeSourceHash, validateFact, validateTask, clip, chunkText } from './utils/pure';\nimport { IngestionService } from './services/IngestionService';\nimport { MaintenanceService } from './services/MaintenanceService';\nimport { ImportExportService } from './services/ImportExportService';\nimport { EmbeddingService } from './services/EmbeddingService';\nimport { RetrievalService } from './services/RetrievalService';\nimport { WriteService } from './services/WriteService';\nimport { PromptService } from './services/PromptService';\nimport { OntologyService } from './services/OntologyService';\nimport { GraphTraversalService } from './services/GraphTraversalService';\nimport { OkfTrustWritesRepository } from './db/okf-trust-writes';\nimport { validateManifest } from './utils/ontology';\nimport { DiagnosticBuffer } from './utils/diagnostics';\nimport type { OntologyManifest, OntologyMode, GraphTraversalOptions, GraphNeighborhood, OntologyBackfillResult, HealResult, IngestDocumentResult, ReembedResult } from './types';\n\nexport { WikiBusyError, WikiTransactionError, PrunePartialFailureError, HOOK_TIMEOUT_MARKER, WikiStrictOntologyViolation, WikiSourceRefHashCollision, WikiParseError, WikiIngestEmptyError, WikiGraphNodeOwnershipConflict } from './types';\n\nconst TABLE_PREFIX_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,30}_$/;\n\n/** Typed escape hatch for tests — not part of the supported consumer API. */\nexport interface WikiMemoryTestAccess {\n embeddingService: EmbeddingService;\n importExportService: ImportExportService;\n ingestionService: IngestionService;\n maintenanceService: MaintenanceService;\n retrievalService: RetrievalService;\n searchService: SearchService;\n writeService: WriteService;\n promptService: PromptService;\n graphTraversalService: GraphTraversalService;\n entryRepo: EntryRepository;\n sourceRefIndexRepo: SourceRefIndexRepository;\n metadataRepo: MetadataRepository;\n jobManager: JobManager;\n}\n\n/** `listDrafts` cursors are `${created_at}:${id}`; opaque to callers. */\nfunction decodeDraftCursor(cursor: unknown): { createdAt: number; id: string } {\n const sep = typeof cursor === 'string' ? cursor.indexOf(':') : -1;\n const createdAt = sep > 0 ? Number((cursor as string).slice(0, sep)) : Number.NaN;\n const id = sep > 0 ? (cursor as string).slice(sep + 1) : '';\n if (!Number.isSafeInteger(createdAt) || id.length === 0) {\n throw new TypeError('Invalid listDrafts cursor.');\n }\n return { createdAt, id };\n}\n\nexport class WikiMemory {\n /** Emits `__testAccess` console warning at most once per instance when NODE_ENV ≠ \"test\". */\n #testAccessNonTestEnvWarned = false;\n\n private db: SQLiteAdapter;\n private prefix: string;\n private options: WikiOptions;\n private entryRepo: EntryRepository;\n private outboxRepo: OutboxRepository;\n private sourceRefIndexRepo: SourceRefIndexRepository;\n private taskRepo: TaskRepository;\n private eventRepo: EventRepository;\n private edgeRepo: EdgeRepository;\n private metadataRepo: MetadataRepository;\n private embeddingService: EmbeddingService;\n private searchService: SearchService;\n private jobManager: JobManager;\n private ingestionService: IngestionService;\n private maintenanceService: MaintenanceService;\n private importExportService: ImportExportService;\n private retrievalService: RetrievalService;\n private writeService: WriteService;\n private promptService: PromptService;\n private ontologyService: OntologyService;\n private graphTraversalService: GraphTraversalService;\n private readonly okfTrustWrites: OkfTrustWritesRepository;\n\n constructor(db: SQLiteAdapter, options: WikiOptions) {\n // Serialize transactions on the single shared connection before the adapter\n // reaches any repository or service. See docs/superpowers/specs/2026-07-09-transaction-serialization-spec.md.\n this.db = withSerializedTransactions(db);\n this.options = options;\n this.prefix = options.config?.tablePrefix ?? 'llm_wiki_';\n if (!TABLE_PREFIX_PATTERN.test(this.prefix)) {\n throw new Error(\n `Invalid tablePrefix: ${JSON.stringify(this.prefix)}. ` +\n `Must match ${TABLE_PREFIX_PATTERN} (letter, then alphanumeric/underscore, ending in \"_\", max 32 chars total).`,\n );\n }\n this.outboxRepo = new OutboxRepository(this.db, this.prefix, !!options.config?.enableOutbox);\n this.entryRepo = new EntryRepository(this.db, this.prefix, this.outboxRepo);\n this.sourceRefIndexRepo = new SourceRefIndexRepository(this.db, this.prefix);\n this.taskRepo = new TaskRepository(this.db, this.prefix, this.outboxRepo);\n this.eventRepo = new EventRepository(this.db, this.prefix);\n this.edgeRepo = new EdgeRepository(this.db, this.prefix);\n this.metadataRepo = new MetadataRepository(this.db, this.prefix);\n this.ontologyService = new OntologyService(\n this.metadataRepo,\n this.edgeRepo,\n options.config?.ontology,\n );\n this.embeddingService = new EmbeddingService(this.db, this.options, this.entryRepo, this.metadataRepo);\n this.searchService = new SearchService(this.entryRepo);\n this.jobManager = new JobManager(this.prefix);\n this.promptService = new PromptService(options.config?.prompts);\n this.ingestionService = new IngestionService(\n this.db,\n this.prefix,\n this.options,\n this.entryRepo,\n this.sourceRefIndexRepo,\n this.metadataRepo,\n this.edgeRepo,\n this.searchService,\n this.jobManager,\n this.embeddingService,\n this.promptService,\n this.ontologyService,\n );\n this.maintenanceService = new MaintenanceService(\n this.db,\n this.prefix,\n this.options,\n this.entryRepo,\n this.sourceRefIndexRepo,\n this.taskRepo,\n this.eventRepo,\n this.metadataRepo,\n this.searchService,\n this.jobManager,\n this.embeddingService,\n this.promptService,\n this.ontologyService,\n );\n this.importExportService = new ImportExportService(\n this.db,\n this.entryRepo,\n this.taskRepo,\n this.eventRepo,\n this.edgeRepo,\n this.metadataRepo,\n this.searchService,\n this.jobManager,\n this.embeddingService,\n );\n this.retrievalService = new RetrievalService(\n this.options,\n this.entryRepo,\n this.taskRepo,\n this.eventRepo,\n this.metadataRepo,\n this.searchService,\n );\n this.writeService = new WriteService(\n this.db,\n this.options,\n this.entryRepo,\n this.eventRepo,\n this.metadataRepo,\n this.jobManager,\n this.maintenanceService,\n );\n this.graphTraversalService = new GraphTraversalService(\n this.edgeRepo,\n this.entryRepo,\n this.options.config ?? {},\n );\n this.okfTrustWrites = new OkfTrustWritesRepository(this.db, this.prefix);\n }\n\n /**\n * Explicit escape hatch for test suites: typed access to composed services for mocks/spies.\n * If `NODE_ENV` is not `\"test\"`, emits a single `console.warn` per instance (skipped when `process` is undefined).\n */\n get __testAccess(): WikiMemoryTestAccess {\n const processEnv = typeof globalThis !== 'undefined'\n ? (globalThis as any).process?.env\n : undefined;\n\n if (\n processEnv !== undefined &&\n processEnv.NODE_ENV !== 'test' &&\n !this.#testAccessNonTestEnvWarned\n ) {\n this.#testAccessNonTestEnvWarned = true;\n console.warn('Warning: WikiMemory.__testAccess is intended for tests (NODE_ENV !== \"test\").');\n }\n return {\n embeddingService: this.embeddingService,\n importExportService: this.importExportService,\n ingestionService: this.ingestionService,\n maintenanceService: this.maintenanceService,\n retrievalService: this.retrievalService,\n searchService: this.searchService,\n writeService: this.writeService,\n promptService: this.promptService,\n graphTraversalService: this.graphTraversalService,\n entryRepo: this.entryRepo,\n sourceRefIndexRepo: this.sourceRefIndexRepo,\n metadataRepo: this.metadataRepo,\n jobManager: this.jobManager,\n };\n }\n\n async setup() {\n const entriesExistedBeforeSetup = await this.metadataRepo.tableExists(`${this.prefix}entries`);\n\n await setupDatabase(this.db, this.prefix);\n\n let currentVersion: number;\n\n if (!entriesExistedBeforeSetup) {\n await this.metadataRepo.setMeta('schema_version', String(CURRENT_SCHEMA_VERSION), this.db);\n currentVersion = CURRENT_SCHEMA_VERSION;\n } else {\n const schemaVersionValue = await this.metadataRepo.getMeta('schema_version');\n\n if (schemaVersionValue) {\n currentVersion = parseInt(schemaVersionValue, 10);\n if (!Number.isFinite(currentVersion)) currentVersion = 0;\n } else {\n const ftsDdl = await this.metadataRepo.getTableDdl(`${this.prefix}entries_fts`);\n const hasPorter = /tokenize\\s*=\\s*['\"]porter\\s+unicode61['\"]/i.test(ftsDdl ?? '');\n currentVersion = hasPorter ? 1 : 0;\n }\n }\n\n for (const migration of MIGRATIONS) {\n if (migration.version > currentVersion) {\n await migration.run(this.db, this.prefix);\n await this.metadataRepo.setMeta('schema_version', String(migration.version), this.db);\n currentVersion = migration.version;\n }\n }\n\n if (entriesExistedBeforeSetup) {\n const schemaVersionCheck = await this.metadataRepo.getMeta('schema_version');\n if (!schemaVersionCheck) {\n await this.metadataRepo.setMeta('schema_version', String(currentVersion), this.db);\n }\n }\n\n if (entriesExistedBeforeSetup) {\n await this.importExportService.assertNoLegacySourceTypes();\n }\n\n const rows = await this.entryRepo.findRowsForSourceRefMigration();\n await this.db.withTransactionAsync(async (tx) => {\n for (const row of rows) {\n const normalized = normalizeSourceRef(row.source_ref);\n if (normalized !== row.source_ref) {\n await this.entryRepo.updateSourceRefByRowid(row.rowid, normalized, tx);\n }\n }\n });\n\n await this.searchService.sync();\n }\n\n async hasChanged(\n entityId: string,\n sourceRef: string,\n sourceHash: string,\n ): Promise<boolean>;\n /**\n * Batched overload.\n *\n * `duplicateOf`, when present, is the canonical stored DIFFERENT `source_ref`\n * holding the same hash — never the incoming ref itself (the incoming ref is\n * excluded from the canonical-sort set so a self-reference is impossible).\n * `duplicateOf` reflects the *DB-side* normalized spelling; `sourceRef` in\n * each result echoes the raw caller value. Hosts should not compare these\n * two fields directly to infer canonical status.\n */\n async hasChanged(\n entityId: string,\n entries: Array<{ sourceRef: string; sourceHash: string }>,\n ): Promise<Array<{ sourceRef: string; changed: boolean; duplicateOf?: string }>>;\n async hasChanged(\n entityId: string,\n sourceRefOrEntries: string | Array<{ sourceRef: string; sourceHash: string }>,\n sourceHashArg?: string,\n ): Promise<boolean | Array<{ sourceRef: string; changed: boolean; duplicateOf?: string }>> {\n // Single-doc path: delegate to existing semantics.\n if (typeof sourceRefOrEntries === 'string') {\n const sourceRef = normalizeSourceRef(sourceRefOrEntries);\n if (!sourceRef) {\n throw new Error(`Invalid sourceRef: ${JSON.stringify(sourceRefOrEntries)}`);\n }\n const sourceHash = normalizeSourceHash(sourceHashArg!);\n if (!sourceHash) {\n throw new Error('Invalid sourceHash: must be a 64-character hex string (normalized to lowercase)');\n }\n const storedHash = await this.entryRepo.findLatestSourceHash(entityId, sourceRef);\n if (storedHash === null) return true;\n const normalizedStoredHash = normalizeSourceHash(storedHash);\n return normalizedStoredHash !== sourceHash;\n }\n\n // Batched path: empty input -> empty result, zero SQL calls.\n const entries = sourceRefOrEntries;\n if (entries.length === 0) return [];\n\n // Normalize all inputs (validation up front). Preserve the raw ref so the\n // result echoes the caller's spelling (DB refs are normalized on setup,\n // but the caller hasn't seen that normalization yet).\n const normalized = entries.map(e => {\n const r = normalizeSourceRef(e.sourceRef);\n if (!r) throw new Error(`Invalid sourceRef: ${JSON.stringify(e.sourceRef)}`);\n const h = normalizeSourceHash(e.sourceHash);\n if (!h) throw new Error('Invalid sourceHash: must be a 64-character hex string (normalized to lowercase)');\n return { rawSourceRef: e.sourceRef, sourceRef: r, sourceHash: h };\n });\n\n // 1 + H SQL queries: one batched latest-hash lookup, plus one source_ref_index\n // lookup per distinct input hash. Lookups are issued in parallel — the bound\n // is the SQL-query count, not the await count.\n const latestHashes = await this.entryRepo.findLatestSourceHashes(entityId, normalized.map(e => e.sourceRef));\n\n const distinctHashes = Array.from(new Set(normalized.map(e => e.sourceHash)));\n const dupRefs = await Promise.all(\n distinctHashes.map(h => this.sourceRefIndexRepo.findActiveByEntityAndHash(entityId, h)),\n );\n const dupMap = new Map<string, string | null>(); // hash -> canonical sourceRef (or null)\n for (let i = 0; i < distinctHashes.length; i++) {\n dupMap.set(distinctHashes[i], dupRefs[i]);\n }\n\n return normalized.map(e => {\n const stored = latestHashes.get(e.sourceRef);\n const changed = stored === undefined || stored === null || normalizeSourceHash(stored) !== e.sourceHash;\n const canonical = dupMap.get(e.sourceHash) ?? null;\n if (canonical === null || canonical === e.sourceRef) {\n return { sourceRef: e.rawSourceRef, changed };\n }\n // Canonical: the single sourceRef from source_ref_index that holds\n // this hash, if any. Because the partial UNIQUE index allows at most\n // one live row per (entity, hash), the canonical cannot be the\n // incoming ref (it would be the same sourceRef) — we filter that out\n // above. Non-ASCII sourceRefs are still compared by the DB's\n // source_ref index, so the canonical matches the DB ordering.\n return { sourceRef: e.rawSourceRef, changed, duplicateOf: canonical };\n });\n }\n\n /**\n * Returns the live source_refs for an entity, one row per ref, with the most\n * recently-updated live `source_hash` and a live fact count. Refs are sorted\n * `COLLATE BINARY` (no locale dependency). Used by hosts to reconcile stored\n * state against a live source, or audit duplicate-hash collisions via\n * `findSourceRefsByHash`.\n */\n async listSourceRefs(entityId: string): Promise<Array<{\n sourceRef: string;\n sourceHash: string | null;\n factCount: number;\n lastIngestedAt: number;\n }>> {\n return this.entryRepo.listSourceRefs(entityId);\n }\n\n /**\n * Returns the live source_refs for an entity that hold the given source_hash.\n * With v9, source_ref_index is the source of truth for the sourceRef-level\n * TOCTOU-race invariant: at most one sourceRef can hold a given\n * (entity_id, source_hash). The result is either a single-element array\n * (one canonical ref) or empty (no live ref holds the hash). Returned as\n * an array to preserve the existing public-API shape used by hosts\n * auditing duplicate-content collisions.\n */\n async findSourceRefsByHash(entityId: string, sourceHash: string): Promise<string[]> {\n const canonical = await this.sourceRefIndexRepo.findActiveByEntityAndHash(entityId, sourceHash);\n return canonical === null ? [] : [canonical];\n }\n\n /**\n * Returns the set of `entity_id` values with at least one row in this\n * database, INCLUDING entities whose only remaining rows are soft-deleted\n * — sorted ascending `entity_id COLLATE BINARY`. Empty array when the\n * database has no entities.\n *\n * The deliberate inclusion of soft-deleted-only entities closes the\n * decommissioned-scope leak: a scoped namespace whose documents have all\n * been forgotten or superseded must still appear so host maintenance\n * sweeps (`runLibrarian`, `runHeal`, `runOntologyBackfill`, `runPrune`)\n * can visit it and reap the soft-deleted rows.\n *\n * Read-only. Never acquires a lock. Never opens a transaction. Propagates\n * underlying read errors.\n *\n * @param options.prefix - Optional string filter applied as\n * `id.startsWith(prefix)`. O(n) over distinct ids because the\n * `(entity_id, source_ref)` index is not seekable on `entity_id`-only\n * prefix. Empty-string prefix matches every id.\n *\n * Note: this widens the coverage of `exportDump` (which delegates to\n * `MetadataRepository.getDistinctEntityIds`); exported dumps now include\n * orphaned entities. This is a deliberate widening for backup/migration\n * coverage, not a breaking change to `exportDump`'s return shape.\n */\n async listEntityIds(options?: { prefix?: string }): Promise<string[]> {\n const ids = await this.metadataRepo.getDistinctEntityIds();\n if (options?.prefix === undefined) return ids;\n return ids.filter(id => id.startsWith(options.prefix!));\n }\n\n async runPrune(\n entityId: string,\n options?: {\n retainSoftDeletedFor?: number | null;\n retainEventsFor?: number | null;\n vacuum?: boolean;\n },\n ): Promise<{ entries: number; tasks: number; events: number }> {\n return this.maintenanceService.runPrune(entityId, options);\n }\n\n async read(entityId: string | string[], query: string, options?: ReadOptions): Promise<MemoryBundle> {\n return this.retrievalService.read(entityId, query, options);\n }\n\n async traverseGraph(entityId: string, options: GraphTraversalOptions): Promise<GraphNeighborhood> {\n return this.graphTraversalService.traverseGraph(entityId, options);\n }\n\n async getMemoryBundle(entityId: string): Promise<MemoryBundle> {\n return this.importExportService.getFullBundle(entityId, { maxEvents: 10 });\n }\n\n async write(entityId: string, event: Omit<WikiEvent, 'id' | 'entity_id' | 'created_at'>): Promise<void> {\n return this.writeService.write(entityId, event);\n }\n\n /**\n * @param options.promptOverride - Applies only to this manual call. Does NOT affect\n * WriteService-triggered auto-runs. For persistent prompt customization across auto-runs,\n * set `options.config.prompts.librarianSystemPrompt` at WikiMemory construction time.\n */\n async runLibrarian(entityId: string, options?: { promptOverride?: string }): Promise<void> {\n return this.maintenanceService.runLibrarian(entityId, options);\n }\n\n /**\n * Reviews stored facts with the LLM: removes orphans, downgrades stale\n * inferences, synthesizes corrections.\n *\n * Bounded per call: covers at most `batchSize` candidates (default 25), so\n * one call no longer sweeps the whole entity. Hosts own the cadence; loop\n * `while (result.remaining > 0)` for convergence.\n *\n * `remaining === 0` means \"every mutable fact is inside the 7-day recheck\n * cooldown\", not \"there is no more work\" — heal's candidate set is the live\n * mutable corpus, not a draining backlog, so it climbs back as the cooldown\n * lapses and as new facts are written. Do not write a loop expecting a drain.\n *\n * @param options.promptOverride - Applies only to this manual call. Does NOT affect\n * WriteService-triggered auto-runs. For persistent prompt customization across auto-runs,\n * set `options.config.prompts.healSystemPrompt` at WikiMemory construction time.\n * @param options.batchSize - Candidates per run (default 25) for providers with\n * tighter context limits.\n */\n async runHeal(\n entityId: string,\n options?: { promptOverride?: string; batchSize?: number },\n ): Promise<HealResult> {\n return this.maintenanceService.runHeal(entityId, options);\n }\n\n /**\n * Types already-persisted untyped facts (okf_type IS NULL) in place via one\n * librarian-style LLM call. Strictly additive: never creates, deletes, or\n * rewrites facts; never overwrites an existing okf_type. Free when there is\n * nothing to do (ontology off, or zero eligible untyped facts).\n *\n * Hosts own the trigger cadence (e.g. after each sync); loop `while\n * result.remaining > 0` for convergence. Throws WikiBusyError when another\n * backfill (or conflicting maintenance op) is running for the entity.\n *\n * @param options.promptOverride - Applies only to this call. For persistent\n * customization set `options.config.prompts.ontologyBackfillSystemPrompt`.\n * @param options.batchSize - Facts per run (default 25) for providers with\n * tighter context limits.\n */\n async runOntologyBackfill(\n entityId: string,\n options?: { promptOverride?: string; batchSize?: number; classifier?: 'auto' | 'llm' },\n ): Promise<OntologyBackfillResult> {\n return this.maintenanceService.runOntologyBackfill(entityId, options);\n }\n\n async runReembed(\n entityId?: string,\n opts?: { force?: boolean; skipExisting?: boolean },\n ): Promise<ReembedResult> {\n return this.maintenanceService.runReembed(entityId, opts);\n }\n\n getEntityStatus(entityId: string): EntityStatus {\n return this.jobManager.getEntityStatus(entityId);\n }\n\n subscribeEntityStatus(\n entityId: string,\n callback: (status: EntityStatus) => void,\n ): () => void {\n return this.jobManager.subscribeEntityStatus(entityId, callback);\n }\n\n clearVectorCache(): void {\n this.searchService.evictCache();\n }\n\n async exportDump(entityIds?: string[]): Promise<MemoryDump> {\n return this.importExportService.exportDump(entityIds);\n }\n\n /** Entity summary prose persisted from an OKF profile ≥ 1 import; null when none stored. */\n async getEntitySummary(entityId: string): Promise<string | null> {\n return this.metadataRepo.getMeta(entitySummaryMetaKey(entityId));\n }\n\n async importDump(dump: MemoryDump, opts?: { merge?: boolean }): Promise<void> {\n return this.importExportService.importDump(dump, opts);\n }\n\n async forget(\n entityId: string,\n params: { entryId?: string; taskId?: string; sourceRef?: string; sourceHash?: string; clearAll?: boolean },\n opts?: { dryRun?: boolean },\n ): Promise<{ deleted: { entries: number; tasks: number }; metadataReset?: boolean }> {\n return this.maintenanceService.forget(entityId, params, opts);\n }\n\n /**\n * Full and partial ingestion both reject foreign-owned generated fact IDs with\n * `WikiGraphNodeOwnershipConflict`. Such collisions are unexpected. Ingestion\n * may already have persisted ontology or other state before rejection; unlike\n * direct graph preflight, it relies on transaction rollback for atomicity.\n *\n * @param params.promptOverride - Overrides the system prompt for this ingest call only.\n * For persistent customization, set `options.config.prompts.ingestSystemPrompt` at\n * WikiMemory construction time.\n */\n async ingestDocument(\n entityId: string,\n params: {\n sourceRef: string;\n sourceHash: string;\n documentChunk: string;\n maxChunkLength?: number;\n chunkOverlap?: number;\n chunkConcurrency?: number;\n promptOverride?: string;\n },\n opts?: { onDuplicateHash?: 'ingest' | 'skip' | 'throw' },\n ): Promise<IngestDocumentResult> {\n return this.ingestionService.ingestDocument(entityId, params, opts);\n }\n\n /**\n * Deterministic write path into the graph. Accepts caller-supplied\n * `(nodes, edges)` and writes them under `(sourceRef, sourceHash)`\n * semantics identical to `ingestDocument`, minus the LLM extraction step.\n *\n * MUST be called from inside an open `db.withTransactionAsync` callback —\n * the third argument is the caller's `tx`. The method does not open a\n * nested transaction, does not acquire any lock, and does not perform\n * post-commit work (search sync, embedding, cache eviction). Hosts that\n * want embeddings synced should drive the existing maintenance sweep\n * (`runLibrarian` / `runHeal` / `runOntologyBackfill` / `runPrune`,\n * scoped via `listEntityIds`).\n *\n * Contract (full pre-flight validation lives inside\n * `IngestionService.upsertGraphCore`, which this method delegates to):\n * - C2: no-op when `(entityId, sourceHash)` is already mapped to\n * `params.sourceRef`; throws `WikiSourceRefHashCollision` if mapped to\n * a different `sourceRef`.\n * - C3: edges with dangling `targetId` are stored verbatim (no FK, no\n * resolution).\n * - C4: under persisted ontology mode `'strict'`, an out-of-manifest node\n * or edge `type` throws `WikiStrictOntologyViolation` (pre-flight,\n * all-or-nothing — NONE written on failure).\n *\n * Entry IDs share one database-wide namespace. Existing rows, including\n * soft-deleted rows, reserve their IDs for their entity; same-entity updates\n * and resurrection remain supported. Hosts authenticate callers and select\n * the authorized entity ID; entity-qualified IDs are optional, not required.\n * After the live-only C2 probe above, a foreign node ID throws the fixed,\n * privacy-preserving `WikiGraphNodeOwnershipConflict` before persistent writes\n * (including seed manifests). Deleted source mappings do not trigger C2.\n *\n * Propagate later failures to roll back the host transaction. In particular,\n * foreign edge-ID collisions remain late bare `Error`s: the foreign edge is\n * not overwritten, but catching and committing can retain earlier writes.\n * This method neither commits nor rolls back the caller's transaction.\n *\n * @returns Counts: nodesWritten (validated nodes persisted), edgesWritten\n * (manifest-valid edges persisted), superseded (prior facts soft-deleted\n * plus prior source-ref edges hard-deleted).\n */\n async upsertGraph(\n entityId: string,\n params: {\n sourceRef: string;\n sourceHash: string;\n nodes: readonly { id: string; type: string; title: string; body?: string }[];\n edges: readonly { type: string; sourceId: string; targetId: string; id?: string }[];\n },\n adapter: SQLiteAdapter,\n ): Promise<{ nodesWritten: number; edgesWritten: number; superseded: number }> {\n const sourceRef = normalizeSourceRef(params.sourceRef);\n if (!sourceRef) throw new Error('Invalid sourceRef');\n const sourceHash = normalizeSourceHash(params.sourceHash);\n if (!sourceHash) throw new Error('Invalid sourceHash (must be 64-char hex string)');\n\n // C2 probe — runs inside the caller's tx so it sees the in-flight state.\n const canonical = await this.sourceRefIndexRepo.findActiveByEntityAndHash(entityId, sourceHash, adapter);\n if (canonical !== null && canonical === sourceRef) {\n return { nodesWritten: 0, edgesWritten: 0, superseded: 0 };\n }\n if (canonical !== null && canonical !== sourceRef) {\n throw new WikiSourceRefHashCollision({\n entityId,\n sourceHash,\n existingSourceRef: canonical,\n attemptedSourceRef: sourceRef,\n });\n }\n\n // Delegate to upsertGraphCore for steps a–j (manifest read, validation,\n // supersession, writes, returns counts). No opts.strict override — let\n // the persisted ontology mode drive strictness per the spec.\n // The host owns this transaction and core never sees its commit, so\n // diagnostics are delivered when upsertGraph resolves (spec §4.2.4).\n // Hosts that roll back should disregard them.\n const diagBuffer = new DiagnosticBuffer();\n const result = await this.ingestionService.upsertGraphCore(\n entityId,\n { sourceRef, sourceHash, nodes: params.nodes, edges: params.edges },\n adapter,\n { diag: { buffer: diagBuffer, operation: 'upsertGraph' } },\n );\n diagBuffer.flush(this.options);\n return result;\n }\n\n /**\n * Returns up to `limit` unprocessed outbox events, oldest first.\n * Works regardless of enableOutbox value — allows draining after disabling.\n */\n async getUnprocessedOutboxEvents(limit = 100): Promise<WikiOutboxEvent[]> {\n if (Number.isFinite(limit) && limit <= 0) return [];\n const safeLimit = Number.isFinite(limit) && limit >= 1 ? Math.trunc(limit) : 100;\n const rows = await this.outboxRepo.fetchPending(safeLimit);\n return rows.map(row => {\n let payload: unknown = null;\n try {\n payload = JSON.parse(row.payload);\n } catch {\n // corrupted row — surface null payload rather than poisoning the batch\n }\n return { ...row, payload } as WikiOutboxEvent;\n });\n }\n\n /**\n * Deletes the given event IDs from the outbox table.\n * Call after successfully committing events to the external system.\n */\n async markOutboxEventsProcessed(eventIds: string[]): Promise<void> {\n await this.outboxRepo.acknowledge(eventIds);\n }\n\n /**\n * Returns the effective ontology mode and manifest for an entity.\n * Resolution order: persisted DB row → `WikiConfig.ontology.seedManifests[entityId]` → `null`.\n */\n async getOntologyManifest(entityId: string): Promise<{\n mode: OntologyMode;\n manifest: OntologyManifest;\n } | null> {\n const row = await this.metadataRepo.getManifest(entityId);\n if (row) return { mode: this.ontologyService.resolveMode(row.mode), manifest: row.manifest };\n const seed = this.options.config?.ontology?.seedManifests?.[entityId];\n if (seed) {\n return {\n mode: this.ontologyService.resolveMode(seed.mode),\n manifest: seed.manifest,\n };\n }\n return null;\n }\n\n /**\n * Seeds or replaces an entity's ontology manifest and optional mode override.\n * Validates manifest invariants (unique type slugs, edge endpoints reference node types).\n * Invalidates the in-memory ontology cache for this entity.\n *\n * Delegates to `setOntologyManifests` so there is a single write path. The\n * observable contract is unchanged: same upsert semantics, same cache\n * invalidation, same `void` result.\n */\n async setOntologyManifest(\n entityId: string,\n manifest: OntologyManifest,\n options?: { mode?: OntologyMode },\n ): Promise<void> {\n await this.setOntologyManifests([{ entityId, manifest, mode: options?.mode }]);\n }\n\n /**\n * Write several entities' ontology manifests in a single transaction.\n *\n * All succeed or none do. The transaction is opened on this instance's\n * serialized adapter — callers pass data, never a transaction handle, because\n * a consumer holds the unwrapped adapter and a transaction opened on it would\n * bypass the serialization mutex applied in the constructor.\n *\n * Returns which entities were written. `skipped` is only ever non-empty under\n * `opts.ifAbsent`.\n *\n * Sharp edge: `ifAbsent` checks for a PERSISTED row, not for an effective\n * manifest. An entity whose manifest currently comes from\n * `WikiConfig.ontology.seedManifests` has no row until the seed is\n * materialized on first access that supplies a transaction (in practice, an\n * ingest). Until then `ifAbsent` treats the entity as absent, writes the new\n * manifest over the configured seed, and reports it in `written`; the same\n * call after the seed has been materialized reports it in `skipped`. See the\n * `ifAbsent` notes in the package README.\n */\n async setOntologyManifests(\n entries: Array<{\n entityId: string;\n manifest: OntologyManifest;\n mode?: OntologyMode;\n }>,\n opts?: { ifAbsent?: boolean },\n ): Promise<{ written: string[]; skipped: string[] }> {\n // Nothing to do — and deliberately no transaction, so an empty batch never\n // takes the serialization mutex.\n if (entries.length === 0) return { written: [], skipped: [] };\n\n // Two entries naming one entity express ambiguous intent. Applying the last\n // one silently would hide a caller bug whose symptom — a manifest that is\n // not the one the caller believed it wrote — surfaces far from its cause.\n const seen = new Set<string>();\n for (const entry of entries) {\n if (seen.has(entry.entityId)) {\n throw new Error(`Duplicate entityId in batch: ${entry.entityId}`);\n }\n seen.add(entry.entityId);\n }\n\n // Validate every manifest BEFORE opening the transaction, so a doomed batch\n // never reaches the database and never takes the mutex. `setManifest`\n // validates again inside the transaction; that is the invariant protecting\n // every other repository caller, and is not redundant with this gate.\n for (const entry of entries) {\n validateManifest(entry.manifest);\n }\n\n const written: string[] = [];\n const skipped: string[] = [];\n\n await this.db.withTransactionAsync(async (tx) => {\n for (const entry of entries) {\n const mode = entry.mode ?? this.ontologyService.resolveMode();\n const wrote = await this.metadataRepo.setManifest(\n entry.entityId,\n { mode, manifest: entry.manifest },\n tx,\n { ifAbsent: opts?.ifAbsent === true },\n );\n (wrote ? written : skipped).push(entry.entityId);\n }\n });\n\n // After a successful commit, and for EVERY entry rather than just the\n // written ones: under `ifAbsent` a skipped entry means another writer won\n // the race, so this instance's cached copy may be stale and dropping it is\n // more correct than keeping it. A failed transaction throws above and never\n // reaches this loop, which is fine — a rolled-back batch changed nothing,\n // so the cache is still consistent with the database. Invalidating is cheap\n // either way: it only drops a cached copy, and the next read reloads from\n // the database.\n for (const entry of entries) {\n this.ontologyService.invalidateCache(entry.entityId);\n }\n\n return { written, skipped };\n }\n\n /** Append a verification event to a fact. Does NOT touch `updated_at`. */\n async writeOkfTrust(entryId: string, entityId: string, verified: { by: string; at: string }[]): Promise<void> {\n return this.okfTrustWrites.writeOkfTrust(entryId, entityId, verified);\n }\n\n /** Replace a fact's source list. Does NOT touch `updated_at`. */\n async writeOkfSources(entryId: string, entityId: string, sources: Array<{ resource: string; [k: string]: unknown }>): Promise<void> {\n return this.okfTrustWrites.writeOkfSources(entryId, entityId, sources as any);\n }\n\n /** Set a fact's OKF v0.2 lifecycle status. Does NOT touch `updated_at`. */\n async setLifecycleStatus(entryId: string, entityId: string, status: 'draft' | 'stable' | 'deprecated'): Promise<void> {\n return this.okfTrustWrites.setLifecycleStatus(entryId, entityId, status);\n }\n\n /**\n * Live draft facts for one entity, newest first (spec §5.2). Default page\n * size 50, clamped to [1, 500]. Pass `nextCursor` back unchanged for the next page.\n */\n async listDrafts(entityId: string, options?: { limit?: number; cursor?: string }): Promise<DraftPage> {\n const rawLimit = options?.limit;\n const limit = typeof rawLimit === 'number' && Number.isFinite(rawLimit)\n ? Math.min(500, Math.max(1, Math.floor(rawLimit)))\n : 50;\n const after = options?.cursor === undefined ? null : decodeDraftCursor(options.cursor);\n const rows = await this.entryRepo.listDraftsByEntityId(entityId, limit + 1, after);\n const facts = rows.slice(0, limit);\n const last = facts[facts.length - 1];\n return {\n facts,\n nextCursor: rows.length > limit && last ? `${last.created_at}:${last.id}` : null,\n };\n }\n\n /**\n * Promote a draft to `stable` and record who reviewed it, atomically\n * (spec §5.2). Metadata writes only: `updated_at` is not bumped and no\n * outbox event is pushed. Pass `by: 'human:<id>'` so `trustTier` becomes\n * `'human-reviewed'`.\n *\n * @throws WikiDraftNotFound when no live draft with that id exists for the entity.\n */\n async promoteDraft(entryId: string, entityId: string, reviewer: { by: string }): Promise<void> {\n const by = reviewer?.by;\n if (typeof by !== 'string' || by.trim().length === 0) {\n throw new TypeError('promoteDraft requires reviewer.by to be a non-empty string.');\n }\n await this.db.withTransactionAsync(async (tx) => {\n if (!(await this.entryRepo.isLiveDraft(entryId, entityId, tx))) {\n throw new WikiDraftNotFound();\n }\n await this.okfTrustWrites.setLifecycleStatus(entryId, entityId, 'stable', tx);\n await this.okfTrustWrites.writeOkfTrust(entryId, entityId, [{ by, at: new Date().toISOString() }], tx);\n });\n }\n\n /** Set a fact's stale_after (epoch ms) or clear it. Does NOT touch `updated_at`. */\n async setStaleAfter(entryId: string, entityId: string, date: number | null): Promise<void> {\n return this.okfTrustWrites.setStaleAfter(entryId, entityId, date);\n }\n\n /** Set a fact's generated_by actor string. Does NOT touch `updated_at`. */\n async setGeneratedBy(entryId: string, entityId: string, actor: string): Promise<void> {\n return this.okfTrustWrites.setGeneratedBy(entryId, entityId, actor);\n }\n\n /** Task variants of the same five DAO methods. Symmetric per spec §2.5. */\n async writeOkfTrustTask(taskId: string, entityId: string, verified: { by: string; at: string }[]): Promise<void> {\n return this.okfTrustWrites.writeOkfTrustTask(taskId, entityId, verified);\n }\n async writeOkfSourcesTask(taskId: string, entityId: string, sources: Array<{ resource: string; [k: string]: unknown }>): Promise<void> {\n return this.okfTrustWrites.writeOkfSourcesTask(taskId, entityId, sources as any);\n }\n async setLifecycleStatusTask(taskId: string, entityId: string, status: 'draft' | 'stable' | 'deprecated'): Promise<void> {\n return this.okfTrustWrites.setLifecycleStatusTask(taskId, entityId, status);\n }\n async setStaleAfterTask(taskId: string, entityId: string, date: number | null): Promise<void> {\n return this.okfTrustWrites.setStaleAfterTask(taskId, entityId, date);\n }\n async setGeneratedByTask(taskId: string, entityId: string, actor: string): Promise<void> {\n return this.okfTrustWrites.setGeneratedByTask(taskId, entityId, actor);\n }\n}\n\nexport const __testables = { validateFact, validateTask, clip, chunkText };\n","import type { MemoryBundle, WikiFact, WikiTask, WikiEvent, FormatContextOptions } from '../types';\n\nfunction validateMaxOption(value: number, name: string): void {\n if (!isFinite(value) || value < 0) {\n throw new Error(`Invalid ${name}: must be a non-negative finite number`);\n }\n}\n\nconst CONFIDENCE_WEIGHT: Record<string, number> = {\n certain: 1.0,\n inferred: 0.6,\n tentative: 0.3,\n};\n\nfunction scoreFactFor(\n fact: WikiFact,\n weights: Required<NonNullable<FormatContextOptions['factWeights']>>,\n now: number\n): number {\n const confW = CONFIDENCE_WEIGHT[fact.confidence] ?? 0.3;\n const ageDays = (now - fact.updated_at) / 86400000;\n const recencyDecay = Math.exp(-ageDays / 30);\n return (\n confW * weights.confidence +\n Math.log(1 + fact.access_count) * weights.accessCount +\n recencyDecay * weights.recency\n );\n}\n\nfunction renderFactMarkdown(\n fact: WikiFact,\n includeConfidence: boolean,\n includeTags: boolean,\n includeEntityIds: boolean,\n score: number | undefined,\n): string {\n const confPart = includeConfidence ? ` (${fact.confidence})` : '';\n const tagPart = includeTags && fact.tags.length > 0 ? ` [${fact.tags.join(', ')}]` : '';\n const sourcePart = includeEntityIds ? ` {entity_id=${fact.entity_id}}` : '';\n const scorePart = score !== undefined ? ` {score=${score.toFixed(4)}}` : '';\n return `- **${fact.title}**${confPart}${tagPart}${sourcePart}${scorePart}\\n ${fact.body.replace(/\\n/g, '\\n ')}`;\n}\n\nfunction renderFactPlain(\n fact: WikiFact,\n includeConfidence: boolean,\n includeTags: boolean,\n includeEntityIds: boolean,\n score: number | undefined,\n): string {\n const confPart = includeConfidence ? ` (${fact.confidence})` : '';\n const tagPart = includeTags && fact.tags.length > 0 ? ` [${fact.tags.join(', ')}]` : '';\n const sourcePart = includeEntityIds ? ` {entity_id=${fact.entity_id}}` : '';\n const scorePart = score !== undefined ? ` {score=${score.toFixed(4)}}` : '';\n return `${fact.title}${confPart}${tagPart}${sourcePart}${scorePart}: ${fact.body}`;\n}\n\nfunction renderTaskMarkdown(task: WikiTask): string {\n return `- [P${task.priority}] ${task.description.replace(/\\n/g, '\\n ')} (${task.status})`;\n}\n\nfunction renderTaskPlain(task: WikiTask): string {\n return `[P${task.priority}] ${task.description} (${task.status})`;\n}\n\nfunction renderEventMarkdown(event: WikiEvent): string {\n const ts = new Date(event.created_at).toISOString();\n return `- [${event.event_type} @ ${ts}] ${event.summary.replace(/\\n/g, '\\n ')}`;\n}\n\nfunction renderEventPlain(event: WikiEvent): string {\n const ts = new Date(event.created_at).toISOString();\n return `[${event.event_type} @ ${ts}] ${event.summary}`;\n}\n\nexport function formatContext(\n bundle: MemoryBundle,\n options?: FormatContextOptions\n): string {\n const opts: Required<FormatContextOptions> = {\n format: options?.format ?? 'markdown',\n maxFacts: options?.maxFacts ?? 10,\n maxTasks: options?.maxTasks ?? 10,\n maxEvents: options?.maxEvents ?? 10,\n includeConfidence: options?.includeConfidence ?? true,\n includeTags: options?.includeTags ?? true,\n includeEntityIds: options?.includeEntityIds ?? false,\n includeFactScores: options?.includeFactScores ?? false,\n factWeights: {\n confidence: options?.factWeights?.confidence ?? 1.0,\n accessCount: options?.factWeights?.accessCount ?? 0.3,\n recency: options?.factWeights?.recency ?? 0.5,\n },\n };\n\n validateMaxOption(opts.maxFacts, 'maxFacts');\n validateMaxOption(opts.maxTasks, 'maxTasks');\n validateMaxOption(opts.maxEvents, 'maxEvents');\n\n const weights = opts.factWeights as Required<NonNullable<FormatContextOptions['factWeights']>>;\n\n const now = Date.now();\n const sortedFacts = bundle.factScores\n ? [...bundle.facts].slice(0, opts.maxFacts)\n : [...bundle.facts]\n .sort((a, b) => scoreFactFor(b, weights, now) - scoreFactFor(a, weights, now))\n .slice(0, opts.maxFacts);\n\n const sortedTasks = [...bundle.tasks]\n .sort((a, b) => b.priority - a.priority || a.created_at - b.created_at)\n .slice(0, opts.maxTasks);\n\n const sortedEvents = [...bundle.events]\n .sort((a, b) => b.created_at - a.created_at)\n .slice(0, opts.maxEvents);\n\n if (sortedFacts.length === 0 && sortedTasks.length === 0 && sortedEvents.length === 0) {\n return '';\n }\n\n const isMarkdown = opts.format === 'markdown';\n const lines: string[] = [];\n\n if (isMarkdown) {\n lines.push('## Memory');\n\n if (sortedFacts.length > 0) {\n lines.push('');\n lines.push('### Known Facts');\n for (const fact of sortedFacts) {\n lines.push(renderFactMarkdown(fact, opts.includeConfidence, opts.includeTags, opts.includeEntityIds, opts.includeFactScores ? bundle.factScores?.[fact.id] : undefined));\n }\n }\n\n if (sortedTasks.length > 0) {\n lines.push('');\n lines.push('### Open Tasks');\n for (const task of sortedTasks) {\n lines.push(renderTaskMarkdown(task));\n }\n }\n\n if (sortedEvents.length > 0) {\n lines.push('');\n lines.push('### Recent Events');\n for (const event of sortedEvents) {\n lines.push(renderEventMarkdown(event));\n }\n }\n } else {\n if (sortedFacts.length > 0) {\n lines.push('KNOWN FACTS:');\n for (const fact of sortedFacts) {\n lines.push(renderFactPlain(fact, opts.includeConfidence, opts.includeTags, opts.includeEntityIds, opts.includeFactScores ? bundle.factScores?.[fact.id] : undefined));\n }\n }\n if (sortedTasks.length > 0) {\n lines.push('OPEN TASKS:');\n for (const task of sortedTasks) {\n lines.push(renderTaskPlain(task));\n }\n }\n if (sortedEvents.length > 0) {\n lines.push('RECENT EVENTS:');\n for (const event of sortedEvents) {\n lines.push(renderEventPlain(event));\n }\n }\n }\n\n return lines.join('\\n');\n}\n","import type { GraphNeighborhood, WikiEdge } from '../types';\n\n/**\n * Pure presenter — dense text serialization of a GraphNeighborhood for LLM prompt\n * injection. Deterministic: same input always produces byte-identical output\n * (matters for prompt caching).\n */\nexport function formatGraphContext(neighborhood: GraphNeighborhood): string {\n const { nodes, edges } = neighborhood;\n if (nodes.length === 0) return '';\n\n const nodeById = new Map(nodes.map((n) => [n.id, n]));\n const nodeIndex = new Map(nodes.map((n, i) => [n.id, i]));\n const lines: string[] = [];\n\n for (const node of nodes) {\n lines.push(`[${node.okf_type ?? 'fact'}] ${node.title} (ID: ${node.id})`);\n\n const outbound = edgesByDirection(edges, node.id, 'source_id', nodeById, nodeIndex);\n const inbound = edgesByDirection(edges, node.id, 'target_id', nodeById, nodeIndex);\n\n for (const { edge, other } of outbound) {\n lines.push(` -[${edge.edge_type}]-> [${other.okf_type ?? 'fact'}] ${other.title}`);\n }\n for (const { edge, other } of inbound) {\n lines.push(` <-[${edge.edge_type}]- [${other.okf_type ?? 'fact'}] ${other.title}`);\n }\n }\n\n return lines.join('\\n');\n}\n\nfunction edgesByDirection(\n edges: WikiEdge[],\n nodeId: string,\n endpoint: 'source_id' | 'target_id',\n nodeById: Map<string, GraphNeighborhood['nodes'][number]>,\n nodeIndex: Map<string, number>,\n) {\n const otherEndpoint = endpoint === 'source_id' ? 'target_id' : 'source_id';\n return edges\n .filter((e) => e[endpoint] === nodeId)\n .filter((e) => {\n const otherId = e[otherEndpoint];\n const selfIdx = nodeIndex.get(nodeId)!;\n const otherIdx = nodeIndex.get(otherId);\n return otherIdx !== undefined && selfIdx < otherIdx;\n })\n .map((edge) => ({ edge, other: nodeById.get(edge[otherEndpoint])! }))\n .sort(\n (a, b) =>\n a.edge.edge_type.localeCompare(b.edge.edge_type) ||\n a.other.title.localeCompare(b.other.title) ||\n a.other.id.localeCompare(b.other.id) ||\n a.edge.id.localeCompare(b.edge.id),\n );\n}\n","function shortHash(value: string): string {\n let h1 = 5381;\n let h2 = 52711;\n for (let i = 0; i < value.length; i += 1) {\n const c = value.charCodeAt(i);\n h1 = Math.imul(h1, 33) ^ c;\n h2 = Math.imul(h2, 31) ^ c;\n }\n return (h1 >>> 0).toString(16).padStart(8, '0') + (h2 >>> 0).toString(16).padStart(8, '0');\n}\n\nconst OKF_RESERVED_CONCEPT_NAMES = new Set(['index', 'log']);\n\nconst WINDOWS_RESERVED_NAMES = new Set([\n 'con',\n 'prn',\n 'aux',\n 'nul',\n 'com1',\n 'com2',\n 'com3',\n 'com4',\n 'com5',\n 'com6',\n 'com7',\n 'com8',\n 'com9',\n 'lpt1',\n 'lpt2',\n 'lpt3',\n 'lpt4',\n 'lpt5',\n 'lpt6',\n 'lpt7',\n 'lpt8',\n 'lpt9',\n]);\n\nfunction isWindowsReservedName(name: string): boolean {\n const base = name.split('.')[0];\n return WINDOWS_RESERVED_NAMES.has(base.toLowerCase());\n}\n\nexport function sanitizeForFilename(value: string): string {\n const normalized = value.normalize('NFKC');\n const sanitized = normalized\n .replace(/[^A-Za-z0-9._-]+/g, '_')\n .replace(/^\\.+/, '_')\n .replace(/_+/g, '_')\n .replace(/^[_-]+|[_-]+$/g, '');\n\n // Enforce a max base-name length so the final filename stays within typical\n // filesystem limits (~255 bytes). Reserve ~20 chars for `-<16hexchars>`.\n const MAX_BASE = 200;\n const trimmed = sanitized.length > MAX_BASE ? sanitized.slice(0, MAX_BASE) : sanitized;\n\n let baseName = trimmed && trimmed !== '.' && trimmed !== '..' ? trimmed : 'entity';\n\n // Windows disallows trailing dots and spaces in filenames.\n const withoutTrailingDotSpace = baseName.replace(/[. ]+$/, '');\n const hadTrailingDotSpace = withoutTrailingDotSpace !== baseName;\n if (hadTrailingDotSpace) {\n baseName = withoutTrailingDotSpace || 'entity';\n }\n\n const windowsReserved = isWindowsReservedName(baseName);\n const needsSuffix =\n baseName !== value || sanitized.length > MAX_BASE || hadTrailingDotSpace || windowsReserved;\n\n if (!needsSuffix) return baseName;\n\n const suffix = `-${shortHash(value)}`;\n return `${baseName}${suffix}`;\n}\n\n/** Sanitize a fact/task id for use as a concept filename (without .md). */\nexport function sanitizeConceptId(id: string): string {\n const sanitized = sanitizeForFilename(id);\n if (OKF_RESERVED_CONCEPT_NAMES.has(sanitized.toLowerCase())) {\n return `${sanitized}-${shortHash(id)}`;\n }\n return sanitized;\n}\n","import type { MemoryDump, FormattedMemoryDump, MemoryBundle, WikiFact, WikiTask, WikiEvent } from '../types';\nimport { sanitizeForFilename } from './sanitizeForFilename';\n\nfunction renderFact(f: WikiFact): string {\n const tags = (f.tags || []).join(', ');\n const source = f.source_ref ?? f.source_type;\n return `### ${f.title}\n**Tags:** ${tags}\n**Confidence:** ${f.confidence}\n**Source:** ${source}\n\n${f.body}\n\n---\n`;\n}\n\nfunction renderTask(t: WikiTask): string {\n const checked = t.status === 'done' ? 'x' : ' ';\n const note = t.status === 'done' ? ' (done)'\n : t.status === 'abandoned' ? ' (abandoned)'\n : t.status === 'in_progress' ? ' (in progress)'\n : '';\n return `- [${checked}] ${t.description}${note}\\n`;\n}\n\nfunction renderEvent(e: WikiEvent): string {\n const ts = new Date(e.created_at).toISOString();\n return `- [${ts}] (${e.event_type}) ${e.summary}\\n`;\n}\n\nfunction renderEntity(entityId: string, bundle: MemoryBundle, generatedAt: number): string {\n const lines: string[] = [];\n lines.push(`# Memory Dump: ${entityId}`);\n lines.push(`Generated: ${new Date(generatedAt).toISOString()}`);\n lines.push('');\n lines.push('## Facts');\n lines.push('');\n if (bundle.facts.length === 0) {\n lines.push('_(none)_\\n');\n } else {\n for (const f of bundle.facts) lines.push(renderFact(f));\n }\n lines.push('## Tasks');\n lines.push('');\n if (bundle.tasks.length === 0) {\n lines.push('_(none)_\\n');\n } else {\n for (const t of bundle.tasks) lines.push(renderTask(t));\n }\n lines.push('');\n lines.push('## Recent Events');\n lines.push('');\n if (bundle.events.length === 0) {\n lines.push('_(none)_\\n');\n } else {\n for (const e of bundle.events) lines.push(renderEvent(e));\n }\n return lines.join('\\n');\n}\n\nfunction formatEntityFileName(entityId: string): string {\n return `${sanitizeForFilename(entityId)}.md`;\n}\n\nexport function formatMemoryDump(dump: MemoryDump): FormattedMemoryDump {\n const files = Object.entries(dump.entities).map(([entityId, bundle]) => ({\n name: formatEntityFileName(entityId),\n content: renderEntity(entityId, bundle, dump.generatedAt),\n }));\n\n // Strip embedding_blob from each fact before JSON-serialising the manifest.\n // exportDump() now includes raw Uint8Array blobs for importDump() round-trips,\n // but those binaries serve no purpose in a human-readable manifest and can\n // massively inflate its size for non-trivial datasets.\n const manifestDump: MemoryDump = {\n generatedAt: dump.generatedAt,\n entities: Object.fromEntries(\n Object.entries(dump.entities).map(([entityId, bundle]) => [\n entityId,\n {\n ...bundle,\n facts: bundle.facts.map(f => {\n const { embedding_blob: _blob, ...rest } = f as WikiFact & { embedding_blob?: unknown };\n return rest as WikiFact;\n }),\n },\n ])\n ),\n };\n\n return {\n manifest: JSON.stringify(manifestDump, null, 2),\n files,\n };\n}\n","import type { MemoryDump, WikiEdge, WikiFact, WikiTask, WikiEvent } from '../types';\nimport {\n appendEventIdComment,\n appendRelatedSection,\n buildConceptDocument,\n buildEntityIndexMd,\n buildRootIndexMd,\n buildLogMd,\n serializeActorString,\n type OkfFile,\n type OkfFrontmatter,\n type OkfIndexEntry,\n type OkfIndexSection,\n type OkfLogEntry,\n} from '@equationalapplications/core-okf';\nimport { sanitizeConceptId, sanitizeForFilename } from './sanitizeForFilename';\n\nexport type OkfFormatProfile = 'llm-wiki/1' | 'llm-wiki/2';\n\nexport interface FormatOkfBundleOptions {\n /** Defaults to 'llm-wiki/2'. Pass 'llm-wiki/1' to force the v0.1 subset. */\n profile?: OkfFormatProfile;\n}\n\nconst DEFAULT_PROFILE: OkfFormatProfile = 'llm-wiki/2';\n\n/**\n * Format an epoch-ms timestamp as ISO 8601 with a double fallback:\n * 1. NaN / Infinity / non-finite -> epoch (0).\n * 2. Outside JS Date's representable range (e.g. 1e300) -> epoch.\n * `new Date(finite).toISOString()` throws RangeError only when the value is\n * outside the supported range; a finite but absurd number still throws. We\n * validate the constructed Date before calling toISOString so the helper\n * never aborts the bundle export.\n */\nfunction isoOrFallback(updatedAt: number): string {\n if (!Number.isFinite(updatedAt)) return new Date(0).toISOString();\n const d = new Date(updatedAt);\n if (!Number.isFinite(d.getTime())) return new Date(0).toISOString();\n return d.toISOString();\n}\n\nfunction isoDateOrOmit(ms: number | null | undefined): string | undefined {\n if (ms == null || !Number.isFinite(ms)) return undefined;\n const d = new Date(ms);\n if (!Number.isFinite(d.getTime())) return undefined;\n return d.toISOString().slice(0, 10);\n}\n\nfunction factFrontmatterV2(f: WikiFact): OkfFrontmatter {\n return {\n type: f.okf_type ?? 'fact',\n title: f.title,\n tags: f.tags,\n // `timestamp` rides along deliberately even on the v0.2 path — a naive\n // consumer that only understands the v0.1 key still gets a readable date\n // without needing flow-mapping support. `generated.at` is the canonical\n // v0.2 field and always wins on import when both are present (spec §2.4).\n timestamp: isoOrFallback(f.updated_at),\n resource: f.source_ref ?? undefined,\n id: f.id,\n entity_id: f.entity_id,\n confidence: f.confidence,\n source_type: f.source_type,\n source_hash: f.source_hash,\n created_at: f.created_at,\n access_count: f.access_count,\n last_accessed_at: f.last_accessed_at,\n deleted_at: f.deleted_at,\n // OKF v0.2\n status: f.lifecycle_status ?? 'stable',\n ...(isoDateOrOmit(f.stale_after) ? { stale_after: isoDateOrOmit(f.stale_after) } : {}),\n // Omit `generated` entirely when there's no actor on record — never\n // fabricate a `generated_by` (mirrors the import side's rule in §4.8:\n // it never invents one either, so export must not manufacture one that\n // would then round-trip back in as if it had always been asserted).\n ...(f.generated_by ? { generated: { by: f.generated_by, at: isoOrFallback(f.updated_at) } } : {}),\n // Omit `verified`/`sources` when empty — an emitted `[]` is not the same\n // shape as an absent key (spec §5.3 derives `unverified` from \"no\n // `verified` key\", not from \"empty `verified` list\").\n ...(f.okf_verified && f.okf_verified.length > 0 ? { verified: f.okf_verified } : {}),\n ...(f.okf_sources && f.okf_sources.length > 0 ? { sources: f.okf_sources } : {}),\n ...(f.okf_usage_window ? { usage_window: f.okf_usage_window } : {}),\n };\n}\n\nfunction taskFrontmatterV2(t: WikiTask): OkfFrontmatter {\n return {\n type: t.okf_type ?? 'task',\n title: t.description,\n timestamp: isoOrFallback(t.updated_at), // see factFrontmatterV2 comment — deliberate back-compat duplication\n id: t.id,\n entity_id: t.entity_id,\n status: t.lifecycle_status ?? 'stable', // OKF v0.2 lifecycle\n execution_status: t.status, // execution state under renamed key\n priority: t.priority,\n created_at: t.created_at,\n resolved_at: t.resolved_at,\n deleted_at: t.deleted_at,\n // OKF v0.2 — symmetric with facts (spec §2.5): stale_after applies to\n // tasks too (a hallucinated task needs a freshness signal as much as a\n // hallucinated fact does).\n ...(isoDateOrOmit(t.stale_after) ? { stale_after: isoDateOrOmit(t.stale_after) } : {}),\n ...(t.generated_by ? { generated: { by: t.generated_by, at: isoOrFallback(t.updated_at) } } : {}),\n ...(t.okf_verified && t.okf_verified.length > 0 ? { verified: t.okf_verified } : {}),\n ...(t.okf_sources && t.okf_sources.length > 0 ? { sources: t.okf_sources } : {}),\n ...(t.okf_usage_window ? { usage_window: t.okf_usage_window } : {}),\n };\n}\n\nfunction factFrontmatterV1(f: WikiFact): OkfFrontmatter {\n return {\n type: f.okf_type ?? 'fact',\n title: f.title,\n tags: f.tags,\n timestamp: isoOrFallback(f.updated_at),\n resource: f.source_ref ?? undefined,\n id: f.id,\n entity_id: f.entity_id,\n confidence: f.confidence,\n source_type: f.source_type,\n source_hash: f.source_hash,\n created_at: f.created_at,\n access_count: f.access_count,\n last_accessed_at: f.last_accessed_at,\n deleted_at: f.deleted_at,\n };\n}\n\nfunction taskFrontmatterV1(t: WikiTask): OkfFrontmatter {\n return {\n type: t.okf_type ?? 'task',\n title: t.description,\n timestamp: isoOrFallback(t.updated_at),\n id: t.id,\n entity_id: t.entity_id,\n status: t.status,\n priority: t.priority,\n created_at: t.created_at,\n resolved_at: t.resolved_at,\n deleted_at: t.deleted_at,\n };\n}\n\nfunction formatLogDate(timestampMs: number): string {\n return new Date(timestampMs).toISOString().slice(0, 10);\n}\n\nfunction conceptRelativePath(sourceFilePath: string, targetFilePath: string): string {\n const sourceDir = sourceFilePath.slice(0, sourceFilePath.lastIndexOf('/'));\n const targetDir = targetFilePath.slice(0, targetFilePath.lastIndexOf('/'));\n const targetName = targetFilePath.slice(targetFilePath.lastIndexOf('/') + 1);\n if (sourceDir === targetDir) return `./${targetName}`;\n if (sourceDir.endsWith('/facts') && targetDir.endsWith('/tasks')) return `../tasks/${targetName}`;\n if (sourceDir.endsWith('/tasks') && targetDir.endsWith('/facts')) return `../facts/${targetName}`;\n return targetFilePath.replace(/^entities\\/[^/]+\\//, '');\n}\n\nfunction buildEventLogEntries(\n events: WikiEvent[],\n factIdToFilename: Map<string, string>,\n): OkfLogEntry[] {\n return events.map(e => {\n const factFilename = e.related_entry_id ? factIdToFilename.get(e.related_entry_id) : undefined;\n const summary = e.summary\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\\[/g, '\\\\[')\n .replace(/\\]/g, '\\\\]')\n .replace(/\\r?\\n/g, ' ');\n\n const text = factFilename\n ? `(${e.event_type}) [${summary}](./facts/${factFilename}.md)`\n : `(${e.event_type}) ${summary}`;\n return { date: formatLogDate(e.created_at), text: appendEventIdComment(text, e.id) };\n });\n}\n\nexport function formatOkfBundle(\n dump: MemoryDump,\n options?: FormatOkfBundleOptions,\n): { files: OkfFile[] } {\n const profile: OkfFormatProfile = options?.profile ?? DEFAULT_PROFILE;\n const okfVersion = profile === 'llm-wiki/2' ? '0.2' : '0.1';\n const factFm = profile === 'llm-wiki/2' ? factFrontmatterV2 : factFrontmatterV1;\n const taskFm = profile === 'llm-wiki/2' ? taskFrontmatterV2 : taskFrontmatterV1;\n\n const files: OkfFile[] = [];\n const rootEntries: OkfIndexEntry[] = [];\n\n for (const [entityId, bundle] of Object.entries(dump.entities)) {\n const dir = sanitizeForFilename(entityId);\n const factIdToFilename = new Map(\n bundle.facts.map(f => [f.id, sanitizeConceptId(f.id)] as const),\n );\n\n const idToConceptPath = new Map<string, string>();\n for (const f of bundle.facts) {\n idToConceptPath.set(f.id, `entities/${dir}/facts/${factIdToFilename.get(f.id)!}.md`);\n }\n for (const t of bundle.tasks) {\n idToConceptPath.set(t.id, `entities/${dir}/tasks/${sanitizeConceptId(t.id)}.md`);\n }\n\n const edgesBySource = new Map<string, WikiEdge[]>();\n for (const edge of bundle.edges ?? []) {\n const group = edgesBySource.get(edge.source_id) ?? [];\n group.push(edge);\n edgesBySource.set(edge.source_id, group);\n }\n\n function relatedLinksFor(sourcePath: string, sourceId: string) {\n return (edgesBySource.get(sourceId) ?? [])\n .map(edge => {\n const targetPath = idToConceptPath.get(edge.target_id);\n if (!targetPath) return null;\n return { edge_type: edge.edge_type, path: conceptRelativePath(sourcePath, targetPath) };\n })\n .filter((link): link is { edge_type: string; path: string } => link != null);\n }\n\n const factEntries: OkfIndexEntry[] = bundle.facts.map(f => ({\n path: `facts/${factIdToFilename.get(f.id)!}.md`,\n title: f.title,\n }));\n for (const f of bundle.facts) {\n const factPath = `entities/${dir}/facts/${factIdToFilename.get(f.id)!}.md`;\n const factBody = appendRelatedSection(f.body, relatedLinksFor(factPath, f.id));\n files.push({\n path: factPath,\n content: buildConceptDocument(factFm(f), factBody),\n });\n }\n\n const taskEntries: OkfIndexEntry[] = bundle.tasks.map(t => ({\n path: `tasks/${sanitizeConceptId(t.id)}.md`,\n title: t.description,\n }));\n for (const t of bundle.tasks) {\n const taskPath = `entities/${dir}/tasks/${sanitizeConceptId(t.id)}.md`;\n const taskBody = appendRelatedSection('', relatedLinksFor(taskPath, t.id));\n files.push({\n path: taskPath,\n content: buildConceptDocument(taskFm(t), taskBody),\n });\n }\n\n files.push({\n path: `entities/${dir}/log.md`,\n content: buildLogMd(buildEventLogEntries(bundle.events, factIdToFilename)),\n });\n\n const entityIndexSections: OkfIndexSection[] = [\n { heading: 'Facts', entries: factEntries },\n { heading: 'Tasks', entries: taskEntries },\n ];\n files.push({\n path: `entities/${dir}/index.md`,\n content: buildEntityIndexMd({\n summary: bundle.summary,\n sections: entityIndexSections,\n }),\n });\n\n rootEntries.push({ path: `entities/${dir}/index.md`, title: entityId });\n }\n\n files.push({\n path: 'index.md',\n content: buildRootIndexMd(\n okfVersion,\n rootEntries.length > 0 ? [{ heading: 'Entities', entries: rootEntries }] : [],\n { profile },\n ),\n });\n\n return { files };\n}","import type { MemoryDump, WikiFact, WikiTask, WikiEvent, WikiEdge } from '../types';\nimport type { OkfFile, OkfFrontmatter, OkfFrontmatterValue } from '@equationalapplications/core-okf';\nimport {\n parseConcept,\n parseLogMd,\n parseRootIndexMd,\n parseEntityIndexMd,\n parseEventIdComment,\n splitRelatedSection,\n isAllowedOkfPath,\n extractMarkdownLinks,\n parseVerifiedFlexible,\n parseCitationsList,\n latestVerified,\n formatVerifiedJson,\n formatSourcesJson,\n type OkfSource,\n type OkfVerified,\n} from '@equationalapplications/core-okf';\nimport { generateId } from './ids';\n\nexport interface OkfImportOptions {\n typeMapping?: Record<string, 'fact' | 'task' | 'ignore'>;\n defaultSchema?: 'fact' | 'task' | 'ignore';\n}\n\ntype Route = 'fact' | 'task' | 'ignore';\n\nconst CONFIDENCE_VALUES = new Set(['certain', 'inferred', 'tentative']);\nconst SOURCE_TYPES = new Set([\n 'user_stated',\n 'librarian_inferred',\n 'user_confirmed',\n 'immutable_document',\n]);\nconst TASK_STATUSES = new Set(['pending', 'in_progress', 'done', 'abandoned']);\nconst EVENT_TYPES = new Set(['observation', 'decision', 'action', 'outcome']);\n\nfunction basenameMd(filePath: string): string {\n const name = filePath.slice(filePath.lastIndexOf('/') + 1);\n return name.endsWith('.md') ? name.slice(0, -3) : name;\n}\n\nfunction isConceptFile(filePath: string): boolean {\n if (!filePath.endsWith('.md')) return false;\n if (filePath.endsWith('/index.md') || filePath === 'index.md') return false;\n if (filePath.endsWith('/log.md') || filePath === 'log.md') return false;\n return true;\n}\n\nfunction isStructuralPath(filePath: string): boolean {\n return (\n filePath.endsWith('/index.md') ||\n filePath === 'index.md' ||\n filePath.endsWith('/log.md') ||\n filePath === 'log.md'\n );\n}\n\nfunction posixDirname(filePath: string): string {\n const idx = filePath.lastIndexOf('/');\n return idx === -1 ? '' : filePath.slice(0, idx);\n}\n\nfunction resolveRelativePath(fromFile: string, linkPath: string): string {\n const baseDir = posixDirname(fromFile);\n const segments = [...(baseDir ? baseDir.split('/') : []), ...linkPath.split('/')];\n const resolved: string[] = [];\n for (const seg of segments) {\n if (seg === '' || seg === '.') continue;\n if (seg === '..') {\n resolved.pop();\n continue;\n }\n resolved.push(seg);\n }\n return resolved.join('/');\n}\n\nfunction decodeLinkPath(path: string): string {\n if (!path.includes('%')) return path;\n try {\n return decodeURIComponent(path);\n } catch {\n return path;\n }\n}\n\nfunction addPathAliases(map: Map<string, string>, filePath: string, resolvedId: string): void {\n map.set(filePath, resolvedId);\n const withoutDot = filePath.replace(/^\\.\\//, '');\n if (withoutDot !== filePath) map.set(withoutDot, resolvedId);\n const entityRelative = filePath.replace(/^entities\\/[^/]+\\//, '');\n if (entityRelative !== filePath) {\n map.set(entityRelative, resolvedId);\n map.set(`./${entityRelative}`, resolvedId);\n }\n}\n\nfunction lookupResolvedId(map: Map<string, string>, path: string): string | undefined {\n const normalized = path.replace(/^\\.\\//, '');\n return map.get(path) ?? map.get(normalized) ?? map.get(`./${normalized}`);\n}\n\nfunction stripLinkSuffix(linkPath: string): string {\n const hashIdx = linkPath.indexOf('#');\n const queryIdx = linkPath.indexOf('?');\n if (hashIdx === -1 && queryIdx === -1) return linkPath;\n const cut =\n hashIdx === -1 ? queryIdx : queryIdx === -1 ? hashIdx : Math.min(hashIdx, queryIdx);\n return linkPath.slice(0, cut);\n}\n\nfunction resolveRoute(filePath: string, frontmatterType: string, options?: OkfImportOptions): Route {\n if (\n options?.typeMapping &&\n Object.prototype.hasOwnProperty.call(options.typeMapping, frontmatterType)\n ) {\n return options.typeMapping[frontmatterType]!;\n }\n if (filePath.includes('/facts/')) return 'fact';\n if (filePath.includes('/tasks/')) return 'task';\n return options?.defaultSchema ?? 'fact';\n}\n\nfunction parseFrontmatterTimestamp(value: OkfFrontmatterValue | undefined, fallback: number): number {\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n if (typeof value === 'string') {\n const parsed = Date.parse(value);\n if (Number.isFinite(parsed)) return parsed;\n }\n return fallback;\n}\n\n/**\n * Parse an OKF v0.2 `stale_after` YYYY-MM-DD wire string into an epoch ms\n * value. Returns null on non-string, regex mismatch, or a calendar-invalid\n * date — the previous inline regex accepted any three numeric components, so\n * `2026-13-45` would yield NaN and crash the SQLite bind downstream.\n */\nfunction parseStaleAfterRaw(raw: unknown): number | null {\n if (typeof raw !== 'string') return null;\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(raw);\n if (!m) return null;\n const year = Number(m[1]);\n const month = Number(m[2]);\n const day = Number(m[3]);\n const ms = Date.UTC(year, month - 1, day);\n if (!Number.isFinite(ms)) return null;\n // Reject calendar-invalid dates that Date.UTC silently normalizes (e.g.\n // 2025-02-29 → 2025-03-01). Compare the round-tripped components.\n const d = new Date(ms);\n if (\n d.getUTCFullYear() !== year ||\n d.getUTCMonth() + 1 !== month ||\n d.getUTCDate() !== day\n ) {\n return null;\n }\n return ms;\n}\n\nfunction unescapeLogSummary(summary: string): string {\n return summary.replace(/\\\\\\]/g, ']').replace(/\\\\\\[/g, '[').replace(/\\\\\\\\/g, '\\\\');\n}\n\nconst LOG_LINE_PATTERN = /^\\(([^)]+)\\)\\s*(?:\\[((?:\\\\.|[^\\]])*)\\]\\(([^)]+)\\)|(.+))$/;\n\nfunction parseLogEntryText(text: string): {\n event_type: WikiEvent['event_type'];\n summary: string;\n linkPath?: string;\n} | null {\n const match = LOG_LINE_PATTERN.exec(text.trim());\n if (!match) return null;\n const [, rawType, linkedSummary, linkPath, plainSummary] = match;\n const event_type = EVENT_TYPES.has(rawType) ? (rawType as WikiEvent['event_type']) : 'observation';\n if (linkPath) {\n return { event_type, summary: unescapeLogSummary(linkedSummary), linkPath };\n }\n return { event_type, summary: (plainSummary ?? '').trim() };\n}\n\nfunction frontmatterToFact(\n entityId: string,\n id: string,\n frontmatter: OkfFrontmatter,\n body: string,\n now: number,\n): WikiFact {\n const created_at = parseFrontmatterTimestamp(frontmatter.created_at, now);\n // Precedence (spec §2.4): v0.2 `generated.at` -> v0.1 `timestamp` -> legacy\n // `updated_at` -> `now`. The previous order swapped `updated_at` ahead of\n // the other two, so a present-but-finite `updated_at` clobbered\n // `generated.at`. We nest the fallbacks so the first finite wins.\n const updated_at = parseFrontmatterTimestamp(\n (frontmatter as any).generated?.at,\n parseFrontmatterTimestamp(\n frontmatter.timestamp,\n parseFrontmatterTimestamp(frontmatter.updated_at, now),\n ),\n );\n\n const verified: OkfVerified = parseVerifiedFlexible((frontmatter as any).verified);\n const rawSources = (frontmatter as any).sources;\n const hasSourcesKey = rawSources !== undefined;\n const sources: OkfSource[] = Array.isArray(rawSources) ? rawSources as OkfSource[] : [];\n const usageWindow = (frontmatter as any).usage_window && typeof (frontmatter as any).usage_window === 'object'\n ? (frontmatter as any).usage_window as { from: string; to: string }\n : null;\n const lastV = latestVerified(verified, now);\n const lifecycleRaw = (frontmatter as any).status;\n const lifecycle_status: 'draft' | 'stable' | 'deprecated' =\n lifecycleRaw === 'draft' || lifecycleRaw === 'stable' || lifecycleRaw === 'deprecated'\n ? lifecycleRaw : 'stable';\n const staleAfterRaw = (frontmatter as any).stale_after;\n const stale_after = parseStaleAfterRaw(staleAfterRaw);\n const generated_by = (frontmatter as any).generated?.by ?? null;\n\n // Spec §13.1 fallback (applies to v0.1, profile-0, AND v0.2 paths): body\n // `# Citations` -> synthetic sources, one entry per URL. The fallback only\n // fires when the `sources` key is ABSENT — a bundle that explicitly declares\n // `sources: []` (an author clearing provenance) MUST NOT have body citations\n // silently synthesized back into it. `hasSourcesKey` distinguishes absent\n // from explicitly-empty.\n if (!hasSourcesKey) {\n const urls = parseCitationsList(body);\n for (const url of urls) {\n sources.push({ resource: url });\n }\n }\n\n return {\n id,\n entity_id: entityId,\n title: typeof frontmatter.title === 'string' ? frontmatter.title : '',\n body,\n tags: Array.isArray(frontmatter.tags)\n ? frontmatter.tags.filter((t): t is string => typeof t === 'string')\n : [],\n confidence: CONFIDENCE_VALUES.has(String(frontmatter.confidence))\n ? (frontmatter.confidence as WikiFact['confidence'])\n : 'tentative',\n source_type: SOURCE_TYPES.has(String(frontmatter.source_type))\n ? (frontmatter.source_type as WikiFact['source_type'])\n : 'user_stated',\n source_hash: typeof frontmatter.source_hash === 'string' ? frontmatter.source_hash : null,\n source_ref: typeof frontmatter.resource === 'string' ? frontmatter.resource : null,\n created_at,\n updated_at,\n last_accessed_at:\n frontmatter.last_accessed_at != null\n ? parseFrontmatterTimestamp(frontmatter.last_accessed_at, now)\n : null,\n access_count: typeof frontmatter.access_count === 'number' ? frontmatter.access_count : 0,\n deleted_at:\n frontmatter.deleted_at != null ? parseFrontmatterTimestamp(frontmatter.deleted_at, 0) : null,\n okf_type: frontmatter.type,\n // OKF v0.2\n lifecycle_status,\n stale_after,\n generated_by,\n okf_sources: sources,\n okf_verified: verified,\n okf_usage_window: usageWindow,\n last_verified_at: lastV?.at ?? null,\n last_verified_by: lastV?.by ?? null,\n };\n}\n\nfunction frontmatterToTask(\n entityId: string,\n id: string,\n frontmatter: OkfFrontmatter,\n now: number,\n // Treat profile-1 explicit and version-only legacy the same: in both cases\n // `status` on the wire is the v0.1 execution state. Profile-2 (and unknown\n // profile with okf_version 0.2) uses the v0.2 rename rule.\n usesV1StatusRule: boolean,\n): WikiTask {\n const created_at = parseFrontmatterTimestamp(frontmatter.created_at, now);\n // Precedence (spec §2.4) — same nested-fallback chain as frontmatterToFact.\n const updated_at = parseFrontmatterTimestamp(\n (frontmatter as any).generated?.at,\n parseFrontmatterTimestamp(\n frontmatter.timestamp,\n parseFrontmatterTimestamp(frontmatter.updated_at, now),\n ),\n );\n\n const verified: OkfVerified = parseVerifiedFlexible((frontmatter as any).verified);\n const sources: OkfSource[] = Array.isArray((frontmatter as any).sources) ? (frontmatter as any).sources as OkfSource[] : [];\n const usageWindow = (frontmatter as any).usage_window && typeof (frontmatter as any).usage_window === 'object'\n ? (frontmatter as any).usage_window as { from: string; to: string }\n : null;\n const lastV = latestVerified(verified, now);\n const lifecycleRaw = (frontmatter as any).status;\n const lifecycle_status: 'draft' | 'stable' | 'deprecated' =\n lifecycleRaw === 'draft' || lifecycleRaw === 'stable' || lifecycleRaw === 'deprecated'\n ? lifecycleRaw : 'stable';\n // stale_after is symmetric with facts (spec §2.5) — parsed the same way,\n // not hardcoded to null.\n const staleAfterRaw = (frontmatter as any).stale_after;\n const stale_after = parseStaleAfterRaw(staleAfterRaw);\n\n // Status rename rule (spec §2.3):\n // - v0.2: wire `status` = lifecycle (already in lifecycle_status above);\n // wire `execution_status` = execution -> `task.status`.\n // - v0.1 / profile 0: wire `status` = execution -> `task.status`; lifecycle\n // is implicit 'stable'. Profile-1 bundles are explicit about being v0.1\n // (`profile: llm-wiki/1`); profile-0 (no profile key, `okf_version: 0.1`)\n // is the version-only fallback; both MUST use the v0.1 rule.\n const executionRaw = (frontmatter as any).execution_status;\n let executionState: WikiTask['status'];\n if (usesV1StatusRule) {\n executionState = TASK_STATUSES.has(String(frontmatter.status))\n ? (frontmatter.status as WikiTask['status']) : 'pending';\n } else {\n // v0.2 (or unknown profile — best-effort per spec §6 \"profile key unknown\").\n executionState = TASK_STATUSES.has(String(executionRaw))\n ? (executionRaw as WikiTask['status'])\n : TASK_STATUSES.has(String(frontmatter.status))\n ? (frontmatter.status as WikiTask['status'])\n : 'pending';\n }\n\n return {\n id,\n entity_id: entityId,\n description: typeof frontmatter.title === 'string' ? frontmatter.title : '',\n status: executionState,\n priority: typeof frontmatter.priority === 'number' ? frontmatter.priority : 0,\n created_at,\n updated_at,\n resolved_at:\n frontmatter.resolved_at != null\n ? parseFrontmatterTimestamp(frontmatter.resolved_at, now)\n : null,\n deleted_at:\n frontmatter.deleted_at != null ? parseFrontmatterTimestamp(frontmatter.deleted_at, 0) : null,\n okf_type: frontmatter.type,\n // OKF v0.2\n lifecycle_status,\n stale_after,\n generated_by: (frontmatter as any).generated?.by ?? null,\n okf_sources: sources,\n okf_verified: verified,\n okf_usage_window: usageWindow,\n last_verified_at: lastV?.at ?? null,\n last_verified_by: lastV?.by ?? null,\n };\n}\n\nfunction findLogMdPath(files: OkfFile[]): string | undefined {\n return files.find(f => f.path.endsWith('/log.md') || f.path === 'log.md')?.path;\n}\n\nfunction extractEdgesFromLinks(\n filePath: string,\n resolvedId: string,\n links: Array<{ text: string; path: string }>,\n pathToResolvedId: Map<string, string>,\n entityId: string,\n now: number,\n seenEdges: Set<string>,\n edges: WikiEdge[],\n): void {\n for (const link of links) {\n const strippedPath = stripLinkSuffix(decodeLinkPath(link.path));\n const directTargetId = lookupResolvedId(pathToResolvedId, strippedPath);\n const resolvedTargetPath = resolveRelativePath(filePath, strippedPath);\n if (isStructuralPath(strippedPath) || isStructuralPath(resolvedTargetPath)) continue;\n const targetId = directTargetId ?? lookupResolvedId(pathToResolvedId, resolvedTargetPath);\n if (!targetId) continue;\n const edgeKey = `${resolvedId}\\u0000${targetId}\\u0000${link.text}`;\n if (seenEdges.has(edgeKey)) continue;\n seenEdges.add(edgeKey);\n edges.push({\n id: generateId(),\n entity_id: entityId,\n source_id: resolvedId,\n target_id: targetId,\n edge_type: link.text,\n created_at: now,\n });\n }\n}\n\nexport function parseOkfBundle(\n entityId: string,\n files: OkfFile[],\n options?: OkfImportOptions,\n): MemoryDump {\n const now = Date.now();\n const normalizeOkfPath = (p: string) => p.replace(/^\\.\\//, '').replace(/\\\\/g, '/');\n\n const normalizedFiles = files.map(f => ({ ...f, path: normalizeOkfPath(f.path) }));\n\n const allowlistedFiles = normalizedFiles.filter(f => isAllowedOkfPath(f.path));\n\n const entityDirs = new Set(\n allowlistedFiles\n .map(f => /^entities\\/([^/]+)\\//.exec(f.path)?.[1])\n .filter((dir): dir is string => !!dir),\n );\n if (entityDirs.size > 1) {\n throw new Error(\n `parseOkfBundle: expected a single-entity bundle for \"${entityId}\", found entities: ${Array.from(entityDirs).join(', ')}`,\n );\n }\n const entityDir = entityDirs.values().next().value ?? entityId;\n const entityPrefix = `entities/${entityDir}/`;\n\n const allowedFiles = allowlistedFiles.filter(\n f => f.path === 'index.md' || f.path.startsWith(entityPrefix),\n );\n const rootIndex = allowedFiles.find(f => f.path === 'index.md');\n const profileMeta = rootIndex ? parseRootIndexMd(rootIndex.content) : {};\n const okfVersion = profileMeta.okf_version;\n const profile = profileMeta.profile;\n const isProfile1 = profile === 'llm-wiki/1';\n const isProfile2 = profile === 'llm-wiki/2';\n const isLegacyV1 = profile === undefined && okfVersion === '0.1';\n\n // Entity summary is a profile >= 1 feature (§4 of the profile doc). The\n // documented detection order (§4.8 detection plan) names four v0.1 and v0.2\n // entry points: explicit profile, version-only v0.1, version-only v0.2, and\n // unknown-profile v0.2 (best-effort). All four should pick up the summary.\n const isVersionOnlyV2 = profile === undefined && okfVersion === '0.2';\n const isUnknownProfileV2 = profile !== undefined && profile !== 'llm-wiki/1' && profile !== 'llm-wiki/2' && okfVersion === '0.2';\n const summaryEligible = isProfile1 || isProfile2 || isLegacyV1 || isVersionOnlyV2 || isUnknownProfileV2;\n let entitySummary: string | undefined;\n const entityIndex = allowedFiles.find(f => f.path === `${entityPrefix}index.md`);\n if (summaryEligible && entityIndex) {\n const summary = parseEntityIndexMd(entityIndex.content).summary;\n entitySummary = summary || undefined;\n }\n\n const pathToResolvedId = new Map<string, string>();\n\n for (const file of allowedFiles) {\n if (!isConceptFile(file.path)) continue;\n const { frontmatter } = parseConcept(file.content);\n const route = resolveRoute(file.path, frontmatter.type ?? '', options);\n if (route === 'ignore') continue;\n const resolvedId =\n typeof frontmatter.id === 'string' && frontmatter.id ? frontmatter.id : basenameMd(file.path);\n addPathAliases(pathToResolvedId, file.path, resolvedId);\n }\n\n const facts: WikiFact[] = [];\n const tasks: WikiTask[] = [];\n const edges: WikiEdge[] = [];\n let logContent: string | null = null;\n const logMdPath = findLogMdPath(allowedFiles);\n\n for (const file of allowedFiles) {\n if (file.path.endsWith('/log.md') || file.path === 'log.md') {\n logContent = file.content;\n continue;\n }\n if (!isConceptFile(file.path)) continue;\n\n const { frontmatter, body } = parseConcept(file.content);\n const route = resolveRoute(file.path, frontmatter.type ?? '', options);\n if (route === 'ignore') continue;\n\n const resolvedId =\n typeof frontmatter.id === 'string' && frontmatter.id ? frontmatter.id : basenameMd(file.path);\n\n const { body: storedBody, relatedLinks } = splitRelatedSection(body);\n const edgeLinks = (isProfile1 || isLegacyV1)\n ? relatedLinks\n : [...relatedLinks, ...extractMarkdownLinks(storedBody)];\n\n // Task status rename rule (spec §2.3) — v0.1 wire uses `status` as\n // execution state; v0.2 wire uses `status` as lifecycle and adds\n // `execution_status`. The flag we pass below is true when we are NOT\n // reading this task as a v0.2-style bundle.\n const usesV1StatusRule = isProfile1 || isLegacyV1 || (profile === undefined && okfVersion === undefined);\n\n if (route === 'fact') {\n facts.push(frontmatterToFact(entityId, resolvedId, frontmatter, storedBody, now));\n } else {\n tasks.push(frontmatterToTask(entityId, resolvedId, frontmatter, now, usesV1StatusRule));\n }\n\n const seenEdges = new Set<string>();\n extractEdgesFromLinks(\n file.path,\n resolvedId,\n edgeLinks,\n pathToResolvedId,\n entityId,\n now,\n seenEdges,\n edges,\n );\n }\n\n const events: WikiEvent[] = [];\n if (logContent != null) {\n const logPath = logMdPath ?? `entities/${entityId}/log.md`;\n for (const entry of parseLogMd(logContent)) {\n const { text, eventId } = parseEventIdComment(entry.text);\n const parsed = parseLogEntryText(text);\n if (!parsed) continue;\n let related_entry_id: string | null = null;\n if (parsed.linkPath) {\n const targetPath = resolveRelativePath(\n logPath,\n stripLinkSuffix(decodeLinkPath(parsed.linkPath)),\n );\n if (!isStructuralPath(targetPath) && targetPath.includes('/facts/')) {\n related_entry_id = lookupResolvedId(pathToResolvedId, targetPath) ?? null;\n }\n }\n const created_at = new Date(`${entry.date}T00:00:00.000Z`).getTime();\n if (!Number.isFinite(created_at)) continue;\n\n events.push({\n id: eventId ?? generateId('evt_'),\n entity_id: entityId,\n event_type: parsed.event_type,\n summary: parsed.summary,\n related_entry_id,\n created_at,\n });\n }\n }\n\n return {\n generatedAt: now,\n entities: {\n [entityId]: { facts, tasks, events, edges, summary: entitySummary },\n },\n };\n}\n","import type { ReadOptions } from './types';\n\nexport interface LibrarianOptions {\n /** If provided, replaces the default Librarian system instructions. */\n systemPrompt?: string;\n /** entity_id -> score multiplier, forwarded to WikiMemory.read() as tierWeights. */\n entityWeights?: Record<string, number>;\n /** Forwarded to WikiMemory.read() for zero-weight filler context. */\n includeZeroWeightEntities?: boolean;\n temperature?: number;\n}\n\nexport interface LibrarianPromptVariables {\n context: string;\n tasks: string;\n query: string;\n}\n\nexport const DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT = `You are a careful memory synthesis assistant.\nUse only the retrieved context when answering the request.\nPreserve source provenance when facts come from different entity namespaces.\n\nRequest:\n{{query}}\n\nRetrieved context:\n{{context}}\n\nOpen tasks:\n{{tasks}}`;\n\nexport function hydrateLibrarianPrompt(\n template: string,\n variables: LibrarianPromptVariables,\n): string {\n return template.replace(/\\{\\{(context|tasks|query)\\}\\}/g, (_, key) => variables[key as keyof LibrarianPromptVariables]);\n}\n\nexport function validateLibrarianPromptTemplate(\n template: string,\n options: { custom: boolean; taskCount: number },\n): string[] {\n if (!options.custom) return [];\n\n const warnings: string[] = [];\n if (!template.includes('{{context}}')) {\n warnings.push('Custom Librarian systemPrompt omits {{context}}; retrieved memory will not be injected.');\n }\n if (!template.includes('{{query}}')) {\n warnings.push('Custom Librarian systemPrompt omits {{query}}; the original request will not be injected.');\n }\n if (options.taskCount > 0 && !template.includes('{{tasks}}')) {\n warnings.push('Custom Librarian systemPrompt omits {{tasks}} while retrieved tasks are available.');\n }\n return warnings;\n}\n\nexport function mapLibrarianOptionsToReadOptions(\n options: LibrarianOptions,\n): Pick<ReadOptions, 'tierWeights' | 'includeZeroWeightEntities'> {\n const readOptions: Pick<ReadOptions, 'tierWeights' | 'includeZeroWeightEntities'> = {};\n if (options.entityWeights !== undefined) readOptions.tierWeights = options.entityWeights;\n if (options.includeZeroWeightEntities !== undefined) {\n readOptions.includeZeroWeightEntities = options.includeZeroWeightEntities;\n }\n return readOptions;\n}\n","import { WikiMemory } from './WikiMemory';\nimport type { SQLiteAdapter, WikiOptions } from './types';\n\nexport * from './types';\nexport type { WikiOutboxEvent } from './outbox/types';\nexport { WikiMemory } from './WikiMemory';\nexport type { WikiMemoryTestAccess } from './WikiMemory';\nexport { formatContext } from './utils/formatContext';\nexport { formatGraphContext } from './utils/formatGraphContext';\nexport { formatMemoryDump } from './utils/formatMemoryDump';\nexport { formatOkfBundle, type FormatOkfBundleOptions, type OkfFormatProfile } from './utils/formatOkfBundle';\nexport { parseOkfBundle, type OkfImportOptions } from './utils/parseOkfBundle';\nexport { parseEmbedding } from './utils/embedding';\nexport { validateManifest } from './utils/ontology';\nexport { configureRandomSource } from './utils/ids';\nexport { chunkText, safeSlice } from './utils/pure';\nexport { DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_CHUNK_OVERLAP } from './utils/chunkingDefaults';\nexport { DEFAULT_MAX_EMBED_CHARS, EMBED_CHARS_CEILING } from './utils/embedDefaults';\nexport * from './librarianPrompt';\nexport { PromptService } from './services/PromptService';\nexport type { EmbedFactResult, EmbedFailureKind } from './services/EmbeddingService';\nexport {\n ONTOLOGY_BACKFILL_BATCH_SIZE,\n ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS,\n ONTOLOGY_BACKFILL_RECHECK_MS,\n HEAL_ANCHORS_PER_CANDIDATE,\n HEAL_BATCH_SIZE,\n HEAL_MAX_FACT_BODY_CHARS_L3,\n HEAL_MAX_TASKS,\n HEAL_RECHECK_MS,\n} from './services/MaintenanceService';\nexport { ONTOLOGY_BACKFILL_SYSTEM_PROMPT } from './prompts';\n\nexport function createWiki(db: SQLiteAdapter, options: WikiOptions): WikiMemory {\n return new WikiMemory(db, options);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/db/schema.ts","../src/db/serializedAdapter.ts","../src/db/migrations.ts","../src/repositories/rowMappers.ts","../src/repositories/EntryRepository.ts","../src/repositories/OutboxRepository.ts","../src/repositories/SourceRefIndexRepository.ts","../src/repositories/TaskRepository.ts","../src/repositories/EventRepository.ts","../src/repositories/EdgeRepository.ts","../src/prompts/ontology.ts","../src/services/OntologyService.ts","../src/services/GraphTraversalService.ts","../src/repositories/LintRepository.ts","../src/services/LintService.ts","../src/db/okf-trust-writes.ts","../src/WikiMemory.ts","../src/utils/formatContext.ts","../src/utils/formatGraphContext.ts","../src/utils/sanitizeForFilename.ts","../src/utils/formatMemoryDump.ts","../src/utils/formatOkfBundle.ts","../src/utils/parseOkfBundle.ts","../src/librarianPrompt.ts","../src/index.ts"],"names":["isStaleAfter","deriveTrustTier","relatedLinksFor","latestVerified"],"mappings":";;;;;AAEA,eAAsB,aAAA,CAAc,IAAmB,MAAA,EAAgB;AACrE,EAAA,MAAM,GAAG,SAAA,CAAU;AAAA,+BAAA,EACY,MAAM,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA,+BAAA,EAiCN,MAAM,yBAAyB,MAAM,CAAA;AAAA,+BAAA,EACrC,MAAM,6BAA6B,MAAM,CAAA;AAAA,+BAAA,EACzC,MAAM,8BAA8B,MAAM,CAAA;AAAA,+BAAA,EAC1C,MAAM,0BAA0B,MAAM,CAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,+BAAA,EAQtC,MAAM,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sCAAA,EAQC,MAAM,CAAA;AAAA,SAAA,EACnC,MAAM,CAAA;AAAA;;AAAA,+BAAA,EAGgB,MAAM,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA,+BAAA,EAqBN,MAAM,uBAAuB,MAAM,CAAA;;AAAA,+BAAA,EAEnC,MAAM,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA,+BAAA,EAUN,MAAM,uBAAuB,MAAM,CAAA;;AAAA,+BAAA,EAEnC,MAAM,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA,+BAAA,EASN,MAAM,wBAAwB,MAA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,IAAI,UAAA,CAAW,EAAA,EAAI,OAAO,CAAA;AACnC","file":"index.mjs","sourcesContent":["import type { SQLiteAdapter } from '../types';\n\nexport async function setupDatabase(db: SQLiteAdapter, prefix: string) {\n await db.execAsync(`\n CREATE TABLE IF NOT EXISTS ${prefix}entries (\n id TEXT PRIMARY KEY,\n entity_id TEXT NOT NULL,\n title TEXT NOT NULL,\n body TEXT NOT NULL,\n tags TEXT NOT NULL DEFAULT '[]',\n confidence TEXT NOT NULL DEFAULT 'inferred',\n source_type TEXT NOT NULL DEFAULT 'librarian_inferred',\n source_hash TEXT,\n source_ref TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n last_accessed_at INTEGER,\n access_count INTEGER NOT NULL DEFAULT 0,\n deleted_at INTEGER,\n embedding TEXT,\n embedding_blob BLOB,\n okf_type TEXT,\n ontology_checked_at INTEGER,\n heal_checked_at INTEGER,\n lifecycle_status TEXT NOT NULL DEFAULT 'stable',\n stale_after INTEGER,\n generated_by TEXT,\n last_verified_at INTEGER,\n last_verified_by TEXT,\n okf_sources TEXT,\n okf_verified TEXT,\n okf_usage_window TEXT,\n embedding_failed_at INTEGER,\n embedding_failure_kind TEXT,\n embedding_attempts INTEGER NOT NULL DEFAULT 0\n );\n\n CREATE INDEX IF NOT EXISTS ${prefix}entries_entity_idx ON ${prefix}entries(entity_id);\n CREATE INDEX IF NOT EXISTS ${prefix}entries_source_ref_idx ON ${prefix}entries(entity_id, source_ref);\n CREATE INDEX IF NOT EXISTS ${prefix}entries_source_hash_idx ON ${prefix}entries(entity_id, source_hash) WHERE source_hash IS NOT NULL;\n CREATE INDEX IF NOT EXISTS ${prefix}entries_updated_idx ON ${prefix}entries(updated_at DESC);\n\n -- source_ref_index: per-(entity, source_hash) record of the canonical sourceRef\n -- currently holding that hash. The partial UNIQUE index on (entity_id, source_hash)\n -- WHERE deleted_at IS NULL enforces the sourceRef-level TOCTOU-race invariant;\n -- entries-level uniqueness cannot express it because a single ingestDocument call\n -- writes N facts that all share (entity_id, source_ref, source_hash). See\n -- docs/superpowers/specs/2026-08-07-dependabot-concurrency-release-hygiene-design.md §B1.\n CREATE TABLE IF NOT EXISTS ${prefix}source_ref_index (\n id TEXT PRIMARY KEY,\n entity_id TEXT NOT NULL,\n source_hash TEXT NOT NULL,\n source_ref TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n deleted_at INTEGER\n );\n CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_ref_hash\n ON ${prefix}source_ref_index (entity_id, source_hash)\n WHERE deleted_at IS NULL;\n\n CREATE TABLE IF NOT EXISTS ${prefix}tasks (\n id TEXT PRIMARY KEY,\n entity_id TEXT NOT NULL,\n description TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'pending',\n priority INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n resolved_at INTEGER,\n deleted_at INTEGER,\n okf_type TEXT,\n lifecycle_status TEXT NOT NULL DEFAULT 'stable',\n stale_after INTEGER,\n generated_by TEXT,\n last_verified_at INTEGER,\n last_verified_by TEXT,\n okf_sources TEXT,\n okf_verified TEXT,\n okf_usage_window TEXT\n );\n\n CREATE INDEX IF NOT EXISTS ${prefix}tasks_entity_idx ON ${prefix}tasks(entity_id, status);\n\n CREATE TABLE IF NOT EXISTS ${prefix}edges (\n id TEXT PRIMARY KEY,\n entity_id TEXT NOT NULL,\n source_id TEXT NOT NULL,\n target_id TEXT NOT NULL,\n edge_type TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n UNIQUE(entity_id, source_id, target_id, edge_type)\n );\n\n CREATE INDEX IF NOT EXISTS ${prefix}edges_entity_idx ON ${prefix}edges(entity_id);\n\n CREATE TABLE IF NOT EXISTS ${prefix}events (\n id TEXT PRIMARY KEY,\n entity_id TEXT NOT NULL,\n event_type TEXT NOT NULL,\n summary TEXT NOT NULL,\n related_entry_id TEXT,\n created_at INTEGER NOT NULL\n );\n\n CREATE INDEX IF NOT EXISTS ${prefix}events_entity_idx ON ${prefix}events(entity_id, created_at DESC);\n\n CREATE TABLE IF NOT EXISTS ${prefix}checkpoints (\n entity_id TEXT PRIMARY KEY,\n heal_checkpoint INTEGER NOT NULL DEFAULT 0,\n memory_checkpoint INTEGER NOT NULL DEFAULT 0\n );\n\n CREATE TABLE IF NOT EXISTS ${prefix}entity_manifests (\n entity_id TEXT PRIMARY KEY,\n mode TEXT NOT NULL DEFAULT 'off',\n manifest_json TEXT NOT NULL DEFAULT '{\"node_types\":[],\"edge_types\":[]}',\n updated_at INTEGER NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS ${prefix}meta (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS ${prefix}outbox (\n id TEXT PRIMARY KEY,\n entity_id TEXT NOT NULL,\n table_name TEXT NOT NULL,\n record_id TEXT NOT NULL,\n operation TEXT NOT NULL,\n payload TEXT NOT NULL,\n created_at INTEGER NOT NULL\n );\n\n CREATE INDEX IF NOT EXISTS ${prefix}outbox_entity_id_created_at\n ON ${prefix}outbox (entity_id, created_at);\n\n CREATE INDEX IF NOT EXISTS ${prefix}outbox_created_at\n ON ${prefix}outbox (created_at);\n `);\n\n // OKF v0.2 indexes — gated on column existence so we never try to create an\n // index on a column that hasn't been added yet (upgrade-from-pre-v10 case).\n // The columns themselves are in the CREATE TABLE above (fresh installs get\n // them directly) and in migration v10 (upgrades get them via ALTER TABLE).\n // The migration also creates these same indexes, so the IF NOT EXISTS guard\n // makes either path safe.\n await createOkfV02IndexesIfColumnsExist(db, prefix);\n}\n\nasync function createOkfV02IndexesIfColumnsExist(db: SQLiteAdapter, prefix: string): Promise<void> {\n for (const table of ['entries', 'tasks'] as const) {\n const cols = await db.getAllAsync<{ name: string }>(\n `PRAGMA table_info(${prefix}${table})`\n );\n const colNames = new Set(cols.map((c) => c.name));\n if (colNames.has('lifecycle_status')) {\n await db.execAsync(`CREATE INDEX IF NOT EXISTS ${prefix}${table}_lifecycle_status_idx ON ${prefix}${table}(lifecycle_status);`);\n }\n if (colNames.has('stale_after')) {\n await db.execAsync(`CREATE INDEX IF NOT EXISTS ${prefix}${table}_stale_after_idx ON ${prefix}${table}(stale_after);`);\n }\n if (colNames.has('last_verified_at')) {\n await db.execAsync(`CREATE INDEX IF NOT EXISTS ${prefix}${table}_last_verified_at_idx ON ${prefix}${table}(last_verified_at);`);\n }\n }\n}\n","import type { SQLiteAdapter } from '../types';\nimport { WikiTransactionError } from '../types';\nimport { extractSqliteCode } from './sqliteCodes';\n\nexport { extractSqliteCode };\n\n/** True when `err` carries a parseable SQLite code — gates whether the wrapper re-wraps. */\nexport function isDriverError(err: unknown): boolean {\n return extractSqliteCode(err) !== undefined;\n}\n\n/**\n * Returns an adapter with the given methods overridden, delegating everything else\n * (own or class-prototype methods) to `target`.\n *\n * Uses a `Proxy` rather than `Object.create`/object-spread: delegated methods are\n * bound to `target` before being returned, so their receiver (`this`) stays the\n * original adapter instance. That keeps ES `#private` fields and `instanceof`/identity\n * checks inside those methods working — `Object.create` would invoke them with the\n * wrapper as `this` and break both.\n */\nfunction withOverrides(target: SQLiteAdapter, overrides: Partial<SQLiteAdapter>): SQLiteAdapter {\n return new Proxy(target, {\n get(obj, prop, receiver) {\n if (prop in overrides) return Reflect.get(overrides, prop, receiver);\n const value = Reflect.get(obj, prop, obj);\n return typeof value === 'function' ? value.bind(obj) : value;\n },\n }) as SQLiteAdapter;\n}\n\n/**\n * Returns the same adapter with `withTransactionAsync` overridden to throw. Injected\n * by the serialized wrapper onto the `tx` handed to every callback so a *nested*\n * transaction fails loudly instead of deadlocking against the mutex.\n */\nexport function guardReentrancy(tx: SQLiteAdapter): SQLiteAdapter {\n return withOverrides(tx, {\n withTransactionAsync() {\n throw new Error(\n 'Nested withTransactionAsync is not supported: you are already ' +\n 'inside a transaction. Pass the current `tx` down instead of ' +\n 'opening a new transaction.'\n );\n },\n });\n}\n\nconst DEADLOCK_WARN_MS = 10_000;\n\n/**\n * Wraps `withTransactionAsync` in a promise-chain mutex so transactions on the\n * single shared connection run one at a time. Non-transactional reads/writes are\n * untouched. Applied once in the WikiMemory constructor before the adapter reaches\n * any repository or service.\n */\nexport function withSerializedTransactions(db: SQLiteAdapter): SQLiteAdapter {\n let queue: Promise<unknown> = Promise.resolve();\n return withOverrides(db, {\n withTransactionAsync<T>(fn: (tx: SQLiteAdapter) => Promise<T>): Promise<T> {\n // Warns if a call waits >10s for the lock — the signature of the closure-capture\n // deadlock (calling the outer `db` instead of `tx` inside a callback). Cleared the\n // instant the lock is acquired, so it measures queue wait only.\n const warn = setTimeout(() => {\n console.warn(\n '[core-llm-wiki] Transaction queued >10s — possible deadlock. ' +\n 'Inside a transaction callback, use the `tx` parameter, never the ' +\n 'outer database handle.'\n );\n }, DEADLOCK_WARN_MS);\n\n const run = queue\n .catch(() => undefined) // proceed from a settled state; swallow prior outcome\n .then(() => {\n clearTimeout(warn);\n // Re-wrap the tx so a nested withTransactionAsync throws synchronously.\n // Some adapters invoke the callback with no tx handle; fall back to the\n // outer db (same connection). The guard still blocks nested transactions.\n return db.withTransactionAsync((tx) => fn(guardReentrancy(tx ?? db)));\n })\n .catch((e) => {\n // Wrap only driver errors; domain errors reach the caller with instanceof intact.\n throw isDriverError(e)\n ? new WikiTransactionError('Transaction failed', { cause: e })\n : e;\n });\n\n queue = run; // advance the tail; next caller's leading .catch() absorbs this rejection\n return run as Promise<T>;\n },\n });\n}\n","import type { SQLiteAdapter } from '../types';\n\nexport interface Migration {\n version: number;\n description: string;\n run: (db: SQLiteAdapter, prefix: string) => Promise<void>;\n}\n\nexport const MIGRATIONS: Migration[] = [\n {\n version: 1,\n description: 'Rebuild FTS5 with porter unicode61 tokenizer (superseded by v2)',\n run: async (_db, _prefix) => {\n // This migration is superseded by v2 which drops FTS5 entirely.\n // It is kept as a no-op so upgrade paths from v0 do not require FTS5 support.\n },\n },\n {\n version: 2,\n description: 'Remove FTS5; add embedding column for semantic retrieval',\n run: async (db, prefix) => {\n // Drop FTS5 artifacts in a transaction.\n await db.withTransactionAsync(async (tx) => {\n await tx.execAsync(`\n DROP TRIGGER IF EXISTS ${prefix}entries_ai;\n DROP TRIGGER IF EXISTS ${prefix}entries_ad;\n DROP TRIGGER IF EXISTS ${prefix}entries_au;\n DROP TABLE IF EXISTS ${prefix}entries_fts;\n `);\n });\n // ALTER TABLE ADD COLUMN must run outside any explicit transaction —\n // SQLite (and expo-sqlite) do not permit schema alterations inside\n // a BEGIN...COMMIT block.\n const cols = await db.getAllAsync<{ name: string }>(\n `PRAGMA table_info(${prefix}entries)`\n );\n if (!cols.some(c => c.name === 'embedding')) {\n await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN embedding TEXT`);\n }\n },\n },\n {\n version: 3,\n description: 'Add embedding_blob BLOB column for Float32Array vector storage',\n run: async (db, prefix) => {\n const cols = await db.getAllAsync<{ name: string }>(\n `PRAGMA table_info(${prefix}entries)`\n );\n if (!cols.some(c => c.name === 'embedding_blob')) {\n await db.execAsync(\n `ALTER TABLE ${prefix}entries ADD COLUMN embedding_blob BLOB`\n );\n }\n },\n },\n {\n version: 4,\n description: 'Create outbox table for change data capture',\n run: async (db, prefix) => {\n await db.execAsync(`\n CREATE TABLE IF NOT EXISTS ${prefix}outbox (\n id TEXT PRIMARY KEY,\n entity_id TEXT NOT NULL,\n table_name TEXT NOT NULL,\n record_id TEXT NOT NULL,\n operation TEXT NOT NULL,\n payload TEXT NOT NULL,\n created_at INTEGER NOT NULL\n );\n CREATE INDEX IF NOT EXISTS ${prefix}outbox_entity_id_created_at\n ON ${prefix}outbox (entity_id, created_at);\n `);\n },\n },\n {\n version: 5,\n description: 'Add okf_type to entries/tasks for OKF type fidelity; create edges table for OKF graph import',\n run: async (db, prefix) => {\n for (const table of ['entries', 'tasks'] as const) {\n const cols = await db.getAllAsync<{ name: string }>(\n `PRAGMA table_info(${prefix}${table})`\n );\n if (!cols.some(c => c.name === 'okf_type')) {\n await db.execAsync(`ALTER TABLE ${prefix}${table} ADD COLUMN okf_type TEXT`);\n }\n }\n await db.execAsync(`\n CREATE TABLE IF NOT EXISTS ${prefix}edges (\n id TEXT PRIMARY KEY,\n entity_id TEXT NOT NULL,\n source_id TEXT NOT NULL,\n target_id TEXT NOT NULL,\n edge_type TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n UNIQUE(entity_id, source_id, target_id, edge_type)\n );\n CREATE INDEX IF NOT EXISTS ${prefix}edges_entity_idx ON ${prefix}edges (entity_id);\n `);\n },\n },\n {\n version: 6,\n description: 'Add entity_manifests table for per-entity ontology state',\n run: async (db, prefix) => {\n await db.execAsync(`\n CREATE TABLE IF NOT EXISTS ${prefix}entity_manifests (\n entity_id TEXT PRIMARY KEY,\n mode TEXT NOT NULL DEFAULT 'off',\n manifest_json TEXT NOT NULL DEFAULT '{\"node_types\":[],\"edge_types\":[]}',\n updated_at INTEGER NOT NULL\n );\n `);\n },\n },\n {\n version: 7,\n description: 'Add ontology_checked_at to entries for ontology backfill recheck cooldown',\n run: async (db, prefix) => {\n // ALTER TABLE ADD COLUMN must run outside any explicit transaction —\n // SQLite (and expo-sqlite) do not permit schema alterations inside\n // a BEGIN...COMMIT block. Same pattern as v2/v3/v5.\n const cols = await db.getAllAsync<{ name: string }>(\n `PRAGMA table_info(${prefix}entries)`\n );\n if (!cols.some(c => c.name === 'ontology_checked_at')) {\n await db.execAsync(\n `ALTER TABLE ${prefix}entries ADD COLUMN ontology_checked_at INTEGER`\n );\n }\n },\n },\n {\n version: 8,\n description: 'Add heal_checked_at to entries for heal recheck cooldown',\n run: async (db, prefix) => {\n // ALTER TABLE ADD COLUMN must run outside any explicit transaction —\n // SQLite (and expo-sqlite) do not permit schema alterations inside\n // a BEGIN...COMMIT block. Same pattern as v2/v3/v5/v7.\n const cols = await db.getAllAsync<{ name: string }>(\n `PRAGMA table_info(${prefix}entries)`\n );\n if (!cols.some(c => c.name === 'heal_checked_at')) {\n await db.execAsync(\n `ALTER TABLE ${prefix}entries ADD COLUMN heal_checked_at INTEGER`\n );\n }\n },\n },\n {\n version: 9,\n description: 'add_source_ref_index',\n run: async (db, prefix) => {\n // Defense-in-depth safety net for the #79 TOCTOU race fix. The original\n // design put a UNIQUE index on `entries(entity_id, source_hash)`, but\n // that conflates per-fact and per-sourceRef granularity: a single\n // `ingestDocument` writes N facts that all share\n // (entity_id, source_ref, source_hash), and the 2nd–Nth inserts hit\n // SQLITE_CONSTRAINT_UNIQUE inside the normal multi-fact path. The\n // correct invariant is \"at most one sourceRef per (entity, hash)\", so\n // the constraint lives on a dedicated per-(entity, hash) table that\n // records the canonical sourceRef for each hash. See\n // docs/superpowers/specs/2026-08-07-dependabot-concurrency-release-hygiene-design.md §B1.\n //\n // Abort path: if any (entity_id, source_hash) already has live rows\n // under multiple distinct source_refs, a previous race beat the new\n // app-level guard. The migration aborts with an actionable error\n // rather than auto-resolving — auto-resolving would either destroy\n // facts or pick a wrong canonical, both worse than failing safe. The\n // thrown error escapes setup() BEFORE the CREATE TABLE runs, so the\n // new table is never created and schema_version is never advanced.\n const duplicates = await db.getAllAsync<{ entity_id: string; source_hash: string; n_refs: number }>(\n `SELECT entity_id, source_hash, COUNT(DISTINCT source_ref) AS n_refs\n FROM ${prefix}entries\n WHERE deleted_at IS NULL AND source_hash IS NOT NULL\n GROUP BY entity_id, source_hash\n HAVING COUNT(DISTINCT source_ref) > 1`\n );\n if (duplicates.length > 0) {\n const sample = duplicates\n .slice(0, 5)\n .map(d => `(entity_id=${d.entity_id}, source_hash=${d.source_hash.slice(0, 12)}…, n_refs=${d.n_refs})`)\n .join(', ');\n throw new Error(\n `Migration v9 (add_source_ref_index) failed: existing live rows have multiple sourceRefs sharing a hash. ` +\n `Found ${duplicates.length} duplicate (entity_id, source_hash) groups. ` +\n `First ${Math.min(5, duplicates.length)}: ${sample}. ` +\n `Resolve each by calling forget({ sourceRef: <loser> }) for the offending sourceRef, then re-run setup.`\n );\n }\n await db.execAsync(\n `CREATE TABLE IF NOT EXISTS ${prefix}source_ref_index (\n id TEXT PRIMARY KEY,\n entity_id TEXT NOT NULL,\n source_hash TEXT NOT NULL,\n source_ref TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n deleted_at INTEGER\n );\n CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_ref_hash\n ON ${prefix}source_ref_index (entity_id, source_hash)\n WHERE deleted_at IS NULL;`\n );\n // Backfill: for each (entity_id, source_hash) group with live entries,\n // pick the sourceRef of the entry that wins\n // `ROW_NUMBER() OVER (PARTITION BY entity_id, source_hash ORDER BY updated_at ASC, id ASC) = 1`.\n // The tie-breaker `id ASC` matches `findLatestSourceHash` ordering so\n // the canonical row is deterministic. INSERT OR IGNORE with a\n // deterministic ID (`sri_<entity_id>:<source_hash>`) makes the backfill\n // idempotent — re-running v9 is a no-op.\n await db.execAsync(\n `INSERT OR IGNORE INTO ${prefix}source_ref_index (id, entity_id, source_hash, source_ref, created_at, deleted_at)\n SELECT\n 'sri:' || entity_id || ':' || source_hash,\n entity_id,\n source_hash,\n source_ref,\n updated_at,\n NULL\n FROM (\n SELECT\n entity_id, source_hash, source_ref, updated_at,\n ROW_NUMBER() OVER (\n PARTITION BY entity_id, source_hash\n ORDER BY updated_at ASC, id ASC\n ) AS rn\n FROM ${prefix}entries\n WHERE deleted_at IS NULL\n AND source_hash IS NOT NULL\n AND source_ref IS NOT NULL\n ) ranked\n WHERE rn = 1;`\n );\n },\n },\n {\n version: 10,\n description: 'OKF v0.2: add lifecycle_status, stale_after, generated_by, last_verified_*, okf_sources, okf_verified, okf_usage_window to entries and tasks',\n run: async (db, prefix) => {\n // ALTER TABLE ADD COLUMN must run outside any explicit transaction — same constraint\n // as v2/v3/v5/v7/v8. We do all eight columns per table, then indexes, inside\n // a single execAsync batch where possible. SQLite ALTER on the same table from\n // separate statements is fine; we just can't wrap it in BEGIN...COMMIT.\n for (const table of ['entries', 'tasks'] as const) {\n const cols = await db.getAllAsync<{ name: string }>(\n `PRAGMA table_info(${prefix}${table})`\n );\n const existing = new Set(cols.map((c) => c.name));\n const adds: Array<[string, string]> = [\n ['lifecycle_status', `ALTER TABLE ${prefix}${table} ADD COLUMN lifecycle_status TEXT NOT NULL DEFAULT 'stable'`],\n ['stale_after', `ALTER TABLE ${prefix}${table} ADD COLUMN stale_after INTEGER`],\n ['generated_by', `ALTER TABLE ${prefix}${table} ADD COLUMN generated_by TEXT`],\n ['last_verified_at', `ALTER TABLE ${prefix}${table} ADD COLUMN last_verified_at INTEGER`],\n ['last_verified_by', `ALTER TABLE ${prefix}${table} ADD COLUMN last_verified_by TEXT`],\n ['okf_sources', `ALTER TABLE ${prefix}${table} ADD COLUMN okf_sources TEXT`],\n ['okf_verified', `ALTER TABLE ${prefix}${table} ADD COLUMN okf_verified TEXT`],\n ['okf_usage_window', `ALTER TABLE ${prefix}${table} ADD COLUMN okf_usage_window TEXT`],\n ];\n for (const [name, sql] of adds) {\n if (!existing.has(name)) await db.execAsync(sql);\n }\n }\n await db.execAsync(`\n CREATE INDEX IF NOT EXISTS ${prefix}entries_lifecycle_status_idx ON ${prefix}entries(lifecycle_status);\n CREATE INDEX IF NOT EXISTS ${prefix}entries_stale_after_idx ON ${prefix}entries(stale_after);\n CREATE INDEX IF NOT EXISTS ${prefix}entries_last_verified_at_idx ON ${prefix}entries(last_verified_at);\n CREATE INDEX IF NOT EXISTS ${prefix}tasks_lifecycle_status_idx ON ${prefix}tasks(lifecycle_status);\n CREATE INDEX IF NOT EXISTS ${prefix}tasks_stale_after_idx ON ${prefix}tasks(stale_after);\n CREATE INDEX IF NOT EXISTS ${prefix}tasks_last_verified_at_idx ON ${prefix}tasks(last_verified_at);\n `);\n },\n },\n {\n version: 11,\n description: 'Add embedding_failed_at, embedding_failure_kind, embedding_attempts to entries for embed retry state',\n run: async (db, prefix) => {\n // ALTER TABLE ADD COLUMN must run outside any explicit transaction —\n // SQLite (and expo-sqlite) do not permit schema alterations inside\n // a BEGIN...COMMIT block. Same pattern as v2/v3/v5/v7/v8/v10.\n // Only the entries table gets these columns — tasks are never embedded.\n const cols = await db.getAllAsync<{ name: string }>(\n `PRAGMA table_info(${prefix}entries)`\n );\n const existing = new Set(cols.map((c) => c.name));\n const adds: Array<[string, string]> = [\n ['embedding_failed_at', `ALTER TABLE ${prefix}entries ADD COLUMN embedding_failed_at INTEGER`],\n ['embedding_failure_kind', `ALTER TABLE ${prefix}entries ADD COLUMN embedding_failure_kind TEXT`],\n ['embedding_attempts', `ALTER TABLE ${prefix}entries ADD COLUMN embedding_attempts INTEGER NOT NULL DEFAULT 0`],\n ];\n for (const [name, sql] of adds) {\n if (!existing.has(name)) await db.execAsync(sql);\n }\n },\n },\n];\n\n// Verify MIGRATIONS are in strictly ascending version order at module load time.\n// This prevents skipped or repeated migrations caused by out-of-order entries.\nfor (let i = 1; i < MIGRATIONS.length; i++) {\n if (MIGRATIONS[i].version <= MIGRATIONS[i - 1].version) {\n throw new Error(\n `migrations.ts: MIGRATIONS must be in strictly ascending version order. ` +\n `Found version ${MIGRATIONS[i].version} after ${MIGRATIONS[i - 1].version} at index ${i}.`\n );\n }\n}\n\n// Derived from the last (highest) migration version so it never drifts out of sync.\nexport const CURRENT_SCHEMA_VERSION =\n MIGRATIONS.length > 0 ? MIGRATIONS[MIGRATIONS.length - 1].version : 0;\n","/**\n * Shared JSON column parsers for repository row mappers.\n *\n * SQLite JSON1 columns return a string when read; in-memory callers expect the\n * parsed value. The parsers tolerate both shapes so callers stay\n * implementation-agnostic (e.g. tests pass arrays directly, drivers return\n * strings). Hoisted to module scope so each row mapping doesn't reallocate\n * two closures (was the case before refactor — see #90 review).\n */\n\nexport function parseJsonArray<T>(s: unknown, fallback: T[]): T[] {\n if (Array.isArray(s)) return s as T[];\n if (typeof s === 'string' && s.length > 0) {\n try {\n const p = JSON.parse(s);\n if (Array.isArray(p)) return p as T[];\n } catch {\n // fall through to fallback\n }\n }\n return fallback;\n}\n\n/**\n * Arrays are rejected in both branches: `typeof [] === 'object'`, so a\n * malformed `okf_usage_window` of `[]` would otherwise be handed back as an\n * object and re-exported with an invalid shape (see #90 review).\n */\nexport function parseJsonObject<T>(s: unknown, fallback: T | null = null): T | null {\n if (s && typeof s === 'object' && !Array.isArray(s)) return s as T;\n if (typeof s === 'string' && s.length > 0) {\n try {\n const p = JSON.parse(s);\n if (p && typeof p === 'object' && !Array.isArray(p)) return p as T;\n } catch {\n // fall through to fallback\n }\n }\n return fallback;\n}\n","import type { SQLiteAdapter, WikiFact, EmbeddingMarkerKind } from '../types';\nimport { WikiGraphNodeOwnershipConflict } from '../types';\nimport { BaseRepository } from './BaseRepository';\nimport { OutboxRepository } from './OutboxRepository';\nimport { parseJsonArray, parseJsonObject } from './rowMappers';\nimport { isStaleAfter, deriveTrustTier } from '@equationalapplications/core-okf';\n\nexport type EntryRowMetadata = {\n id: string;\n entity_id: string;\n updated_at: number | null;\n access_count: number | null;\n};\n\nexport type EntryRowWithEmbeddings = EntryRowMetadata & {\n embedding_blob: Uint8Array | null;\n embedding: string | null;\n};\n\n/**\n * One row of the reembed candidate scan. `findAllForReembed` does `SELECT *`,\n * so the marker columns come back at runtime; naming them here makes that\n * dependency visible to the compiler instead of hiding it behind a cast in\n * MaintenanceService.runReembed (spec §4.4).\n */\nexport type ReembedCandidateRow = WikiFact & {\n embedding_blob?: Uint8Array | null;\n embedding_failed_at?: number | null;\n embedding_failure_kind?: string | null;\n embedding_attempts?: number | null;\n};\n\nfunction mapRowToFact(row: any): WikiFact {\n const tags: string[] = (() => {\n if (Array.isArray(row.tags)) return row.tags;\n try { const p = JSON.parse(row.tags as string); if (Array.isArray(p)) return p; } catch {}\n return [];\n })();\n\n const okf_verified = parseJsonArray<NonNullable<WikiFact['okf_verified']>[number]>(row.okf_verified, []);\n // Hydrate per spec §2.7 + §5.3: surface isStale/trustTier so hosts don't have to\n // re-call the core-okf helpers. Sampled once per row rather than once per call\n // because `now` here means \"as of this hydration\" — using a stable per-call\n // value would shift staleness while we're mapping sibling rows in the same\n // read. Date.now() is cheap enough that per-row sampling is fine.\n const now = Date.now();\n const staleAfterRaw = row.stale_after != null ? Number(row.stale_after) : null;\n\n return {\n id: row.id,\n entity_id: row.entity_id,\n title: row.title,\n body: row.body,\n tags,\n confidence: row.confidence,\n source_type: row.source_type,\n source_hash: row.source_hash ?? null,\n source_ref: row.source_ref ?? null,\n created_at: Number(row.created_at),\n updated_at: Number(row.updated_at),\n last_accessed_at: (row.last_accessed_at === null || row.last_accessed_at === undefined)\n ? null\n : Number(row.last_accessed_at),\n deleted_at: row.deleted_at != null ? Number(row.deleted_at) : null,\n access_count: Number(row.access_count ?? 0),\n okf_type: row.okf_type ?? null,\n // OKF v0.2\n lifecycle_status: (row.lifecycle_status ?? 'stable') as WikiFact['lifecycle_status'],\n stale_after: staleAfterRaw,\n generated_by: row.generated_by ?? null,\n okf_sources: parseJsonArray<NonNullable<WikiFact['okf_sources']>[number]>(row.okf_sources, []),\n okf_verified,\n okf_usage_window: parseJsonObject<NonNullable<WikiFact['okf_usage_window']>>(row.okf_usage_window),\n last_verified_at: row.last_verified_at != null ? Number(row.last_verified_at) : null,\n last_verified_by: row.last_verified_by ?? null,\n // Spec §2.7 + §5.3: hydrate so read() consumers don't re-call the helpers.\n isStale: isStaleAfter(staleAfterRaw, now),\n trustTier: deriveTrustTier(okf_verified),\n };\n}\n\nfunction normalizeEmbeddingBlobValue(blob: unknown): Uint8Array | null {\n if (blob instanceof Uint8Array) return blob;\n if (blob !== null && blob !== undefined && typeof blob === 'object') {\n const obj = blob as Record<string, unknown>;\n if (obj['type'] === 'Buffer' && Array.isArray(obj['data'])) {\n return new Uint8Array(obj['data'] as number[]);\n }\n const entries = Object.keys(obj);\n if (entries.length > 0 && entries.every((k) => /^\\d+$/.test(k))) {\n const len = entries.length;\n const arr = new Uint8Array(len);\n for (let i = 0; i < len; i++) arr[i] = (obj[String(i)] as number) ?? 0;\n return arr;\n }\n }\n return null;\n}\n\n/** Mapper that preserves embedding_blob for export/import round-tripping. */\nfunction mapRowToFactWithBlobs(row: any): WikiFact {\n const base = mapRowToFact(row);\n const embeddingBlob = normalizeEmbeddingBlobValue(row.embedding_blob);\n return embeddingBlob ? { ...base, embedding_blob: embeddingBlob } : base;\n}\n\n\nexport class EntryRepository extends BaseRepository {\n private chunkSize = 500;\n\n constructor(db: SQLiteAdapter, prefix: string, private outbox: OutboxRepository) {\n super(db, prefix);\n }\n\n /**\n * Fetch facts by IDs, optionally scoped to entity IDs.\n * Returns facts in the order of the input IDs (first match wins).\n */\n async findByIds(\n ids: readonly string[],\n scopedEntityIds?: readonly string[],\n tx?: SQLiteAdapter,\n ): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n const rows: any[] = [];\n const entityClause = scopedEntityIds && scopedEntityIds.length > 0\n ? ` AND entity_id IN (${scopedEntityIds.map(() => '?').join(',')})`\n : '';\n const entityParams = scopedEntityIds ?? [];\n\n for (let i = 0; i < ids.length; i += this.chunkSize) {\n const chunk = ids.slice(i, i + this.chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n const chunkRows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries WHERE id IN (${placeholders})${entityClause} AND deleted_at IS NULL`,\n [...chunk, ...entityParams],\n );\n rows.push(...chunkRows);\n }\n\n const byId = new Map(rows.map(r => [r.id, r]));\n return ids\n .map(id => byId.get(id))\n .filter((r): r is any => r !== undefined)\n .map(mapRowToFact);\n }\n\n /**\n * Upsert a WikiFact. Nullable fields set to null when fact value is null.\n * Returns { changes, lastInsertRowId }.\n * `tx` is REQUIRED to ensure atomic outbox staging.\n *\n * OKF metadata discipline (spec §2.5 + DAO checklist §8): content writes\n * MUST NOT silently overwrite OKF metadata that a caller didn't supply. The\n * previous CASE WHEN IS NULL guards around `lifecycle_status`, etc. were\n * dead because the bind always supplied a non-null value (notably\n * `fact.lifecycle_status ?? 'stable'`), so excluded.X was never NULL and\n * an UPDATE rewrote an existing `deprecated` row to `stable`. We now omit\n * these columns from the SET clause entirely — SQLite's ON CONFLICT UPDATE\n * leaves untouched columns at their existing row value, which is exactly\n * the preservation semantics we want for content writes. Callers that\n * intentionally want to overwrite OKF metadata should use\n * {@link upsertForImport} (always-replace semantics for that path).\n * New-row INSERTs still bind a value so the column is populated; if the\n * caller supplied nothing, the schema DEFAULT 'stable' applies when the\n * bind is bound as 'stable' explicitly here.\n *\n * Marker discipline (spec §4.1): a conflict carrying a real\n * `embedding_blob` clears the embedding failure markers, because the row now\n * HAS a valid embedding and a surviving marker would be a self-contradictory\n * diagnostic that inflates runReembed's permanentlyFailed counter. A conflict\n * with no blob leaves marker state alone, matching the \"absent means don't\n * touch\" semantics used for embedding_blob itself.\n *\n * Graph node ownership (spec §2.4 + §3, REQ-OWN-01 + REQ-GRAPH-01): entry\n * IDs share one database-wide namespace, so an ID stays owned by its\n * existing entity for as long as the row exists — soft deletion included.\n * The pre-write lookup already reads the existing row for OKF metadata; we\n * project `entity_id` off that same SELECT and reject the write before\n * any outbox payload construction when the stored owner differs from\n * `fact.entity_id`. Soft-deleted foreign rows keep their IDs reserved;\n * permanent reservation is NOT introduced, so a physically absent ID may\n * still be inserted under the requested entity. The ON CONFLICT UPDATE SET\n * clause carries a final `WHERE entries.entity_id = excluded.entity_id`\n * guard so the database itself refuses a cross-owner row overwrite even if\n * a future caller bypasses the pre-write check. When `runAsync` reports\n * 0 changes (a legitimate conflict-suppressed write, OR an adapter that\n * under-reports a permitted write) we re-read the stored owner; only a\n * foreign owner throws — this is local defensive behavior, not permission\n * for adapters to under-report. The thrown error is\n * `WikiGraphNodeOwnershipConflict` (no owner, node ID, or stored content\n * is disclosed). Upserts that pass both gates retain existing same-entity\n * update + resurrection semantics.\n */\n async upsert(fact: WikiFact, tx: SQLiteAdapter): Promise<{ changes: number; lastInsertRowId: number }> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n const tagsJson = JSON.stringify(fact.tags);\n const embeddingBlob = this.normalizeEmbeddingBlob(fact.embedding_blob);\n\n const existingRow = await executor.getFirstAsync<{\n id: string;\n entity_id: string;\n lifecycle_status: string;\n stale_after: number | null;\n generated_by: string | null;\n okf_sources: string | null;\n okf_verified: string | null;\n okf_usage_window: string | null;\n last_verified_at: number | null;\n last_verified_by: string | null;\n }>(\n `SELECT id, entity_id, lifecycle_status, stale_after, generated_by,\n okf_sources, okf_verified, okf_usage_window,\n last_verified_at, last_verified_by\n FROM ${this.prefix}entries WHERE id = ?`,\n [fact.id],\n );\n\n // Entry IDs share one global namespace, so an ID stays owned by its\n // existing entity for as long as the row exists — soft deletion included.\n // Reject here, before any write or outbox payload construction. This costs\n // one extra column on a SELECT the method already ran, not a new query.\n if (existingRow && existingRow.entity_id !== fact.entity_id) {\n throw new WikiGraphNodeOwnershipConflict();\n }\n\n const operation = fact.deleted_at ? 'DELETE' : (existingRow ? 'UPDATE' : 'INSERT');\n\n const result = await executor.runAsync(\n `INSERT INTO ${this.prefix}entries (\n id, entity_id, title, body, tags, confidence, source_type,\n source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,\n deleted_at, embedding_blob, embedding, okf_type,\n lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,\n okf_sources, okf_verified, okf_usage_window\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n title = excluded.title,\n body = excluded.body,\n tags = excluded.tags,\n confidence = excluded.confidence,\n source_type = excluded.source_type,\n source_hash = excluded.source_hash,\n source_ref = excluded.source_ref,\n updated_at = excluded.updated_at,\n last_accessed_at = excluded.last_accessed_at,\n access_count = excluded.access_count,\n deleted_at = excluded.deleted_at,\n embedding_blob = CASE WHEN excluded.embedding_blob IS NULL THEN embedding_blob ELSE excluded.embedding_blob END,\n embedding = NULL,\n embedding_failed_at = CASE WHEN excluded.embedding_blob IS NOT NULL THEN NULL ELSE embedding_failed_at END,\n embedding_failure_kind = CASE WHEN excluded.embedding_blob IS NOT NULL THEN NULL ELSE embedding_failure_kind END,\n embedding_attempts = CASE WHEN excluded.embedding_blob IS NOT NULL THEN 0 ELSE embedding_attempts END,\n okf_type = excluded.okf_type\n WHERE ${this.prefix}entries.entity_id = excluded.entity_id`,\n [\n fact.id,\n fact.entity_id,\n fact.title,\n fact.body,\n tagsJson,\n fact.confidence,\n fact.source_type,\n fact.source_hash,\n fact.source_ref,\n fact.created_at,\n now,\n fact.last_accessed_at === null ? null : fact.last_accessed_at,\n fact.access_count,\n fact.deleted_at ?? null,\n embeddingBlob ?? null,\n null,\n fact.okf_type ?? null,\n // OKF v0.2 metadata — bound for INSERT only; ON CONFLICT UPDATE\n // preserves the existing row values (these columns are intentionally\n // absent from the SET clause above).\n fact.lifecycle_status ?? 'stable',\n fact.stale_after ?? null,\n fact.generated_by ?? null,\n fact.last_verified_at ?? null,\n fact.last_verified_by ?? null,\n fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,\n fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,\n fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,\n ],\n );\n\n // A suppressed conflict-update reports 0 (see the SQLiteAdapter contract).\n // A permitted write that an adapter under-reports as 0 also lands here, so\n // confirm ownership from the stored row rather than inferring it from the\n // count. A foreign owner rejects; a missing row means the adapter dropped\n // the write (impossible under real SQLite), so fail rather than publish an\n // outbox event for state that does not exist.\n if (result.changes === 0) {\n const stored = await tx.getFirstAsync<{ entity_id: string }>(\n `SELECT entity_id FROM ${this.prefix}entries WHERE id = ?`,\n [fact.id],\n );\n if (!stored) {\n throw new Error('Entry upsert reported no change and stored no row; the SQLiteAdapter did not perform the write');\n }\n if (stored.entity_id !== fact.entity_id) {\n throw new WikiGraphNodeOwnershipConflict();\n }\n }\n\n // Outbox payload mirrors what is actually persisted. On UPDATE, the SET\n // clause intentionally omits the OKF metadata columns so the prior row\n // values win — so `fact.X` here would describe state we did NOT write.\n // Re-read those columns from the stored row and overlay them onto the\n // caller-supplied payload before publishing (#90 review).\n const persistedOkf = existingRow\n ? {\n lifecycle_status: (existingRow.lifecycle_status ?? 'stable') as WikiFact['lifecycle_status'],\n stale_after: existingRow.stale_after != null ? Number(existingRow.stale_after) : null,\n generated_by: existingRow.generated_by ?? null,\n okf_sources: parseJsonArray<NonNullable<WikiFact['okf_sources']>[number]>(existingRow.okf_sources, []),\n okf_verified: parseJsonArray<NonNullable<WikiFact['okf_verified']>[number]>(existingRow.okf_verified, []),\n okf_usage_window: parseJsonObject<NonNullable<WikiFact['okf_usage_window']>>(existingRow.okf_usage_window),\n last_verified_at: existingRow.last_verified_at != null ? Number(existingRow.last_verified_at) : null,\n last_verified_by: existingRow.last_verified_by ?? null,\n }\n : null;\n await this.outbox.push({\n entityId: fact.entity_id,\n tableName: 'entries',\n recordId: fact.id,\n operation,\n payload: persistedOkf ? { ...fact, ...persistedOkf } : fact,\n }, tx);\n\n return result;\n }\n\n /**\n * Normalize an embedding blob value to Uint8Array or null.\n */\n private normalizeEmbeddingBlob(blob: unknown): Uint8Array | null {\n return normalizeEmbeddingBlobValue(blob);\n }\n\n /**\n * Fetch existing rows by IDs and return id/entity_id/updated_at for import collision resolution.\n */\n async findExistingMetadataByIds(\n ids: readonly string[],\n tx?: SQLiteAdapter,\n ): Promise<Array<{ id: string; entity_id: string; updated_at: number }>> {\n const executor = this.getExecutor(tx);\n const rows: Array<{ id: string; entity_id: string; updated_at: number }> = [];\n for (let i = 0; i < ids.length; i += this.chunkSize) {\n const chunk = ids.slice(i, i + this.chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n const chunkRows = await executor.getAllAsync<any>(\n `SELECT id, entity_id, updated_at FROM ${this.prefix}entries WHERE id IN (${placeholders})`,\n chunk,\n );\n rows.push(...chunkRows.map((row) => ({ id: row.id, entity_id: row.entity_id, updated_at: Number(row.updated_at) })));\n }\n return rows;\n }\n\n async findIdById(id: string, entityId: string, tx?: SQLiteAdapter): Promise<string | null> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}entries WHERE id = ? AND entity_id = ?`,\n [id, entityId],\n );\n return row?.id ?? null;\n }\n\n async findIdsBySource(\n entityId: string,\n sourceRef: string | null,\n sourceHash: string | null,\n tx?: SQLiteAdapter,\n includeDeleted = false,\n ): Promise<string[]> {\n const executor = this.getExecutor(tx);\n let sql = `SELECT id FROM ${this.prefix}entries WHERE entity_id = ?`;\n const args: unknown[] = [entityId];\n if (sourceRef !== null) {\n sql += ` AND source_ref = ?`;\n args.push(sourceRef);\n }\n if (sourceHash !== null) {\n sql += ` AND source_hash = ?`;\n args.push(sourceHash);\n }\n if (!includeDeleted) {\n sql += ` AND deleted_at IS NULL`;\n }\n const rows = await executor.getAllAsync<{ id: string }>(sql, args);\n return rows.map((row) => row.id);\n }\n\n async upsertForImport(fact: WikiFact, tx: SQLiteAdapter): Promise<{ changes: number; lastInsertRowId: number }> {\n const executor = this.getExecutor(tx);\n const tagsJson = JSON.stringify(fact.tags);\n const embeddingBlob = this.normalizeEmbeddingBlob(fact.embedding_blob);\n\n // Import is replace semantics: a re-imported fact whose OKF metadata\n // cleared (stale_after removed, generated_by removed, etc.) MUST overwrite\n // the prior row's value. The previous CASE WHEN IS NULL guards preserved\n // the old database values instead, so an \"absent in dump\" never cleared.\n // Direct `= excluded.X` ensures the dump is authoritative.\n //\n // WARNING: unlike `upsert`, this SQL re-parents a conflicting row\n // (`entity_id = excluded.entity_id`, no owner predicate). It is safe only\n // because ImportExportService skips foreign-owned IDs before calling it.\n // Do not model a new write path on this method; use `upsert`.\n const result = await executor.runAsync(\n `INSERT INTO ${this.prefix}entries (\n id, entity_id, title, body, tags, confidence, source_type,\n source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,\n deleted_at, embedding_blob, embedding, okf_type,\n lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,\n okf_sources, okf_verified, okf_usage_window\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n entity_id = excluded.entity_id,\n title = excluded.title,\n body = excluded.body,\n tags = excluded.tags,\n confidence = excluded.confidence,\n source_type = excluded.source_type,\n source_hash = excluded.source_hash,\n source_ref = excluded.source_ref,\n created_at = excluded.created_at,\n updated_at = excluded.updated_at,\n last_accessed_at = excluded.last_accessed_at,\n access_count = excluded.access_count,\n deleted_at = excluded.deleted_at,\n embedding_blob = excluded.embedding_blob,\n embedding = NULL,\n embedding_failed_at = CASE WHEN excluded.embedding_blob IS NOT NULL THEN NULL ELSE embedding_failed_at END,\n embedding_failure_kind = CASE WHEN excluded.embedding_blob IS NOT NULL THEN NULL ELSE embedding_failure_kind END,\n embedding_attempts = CASE WHEN excluded.embedding_blob IS NOT NULL THEN 0 ELSE embedding_attempts END,\n okf_type = excluded.okf_type,\n lifecycle_status = excluded.lifecycle_status,\n stale_after = excluded.stale_after,\n generated_by = excluded.generated_by,\n last_verified_at = excluded.last_verified_at,\n last_verified_by = excluded.last_verified_by,\n okf_sources = excluded.okf_sources,\n okf_verified = excluded.okf_verified,\n okf_usage_window = excluded.okf_usage_window`,\n [\n fact.id,\n fact.entity_id,\n fact.title,\n fact.body,\n tagsJson,\n fact.confidence,\n fact.source_type,\n fact.source_hash,\n fact.source_ref,\n fact.created_at,\n fact.updated_at,\n fact.last_accessed_at === null ? null : fact.last_accessed_at,\n fact.access_count,\n fact.deleted_at ?? null,\n embeddingBlob ?? null,\n null,\n fact.okf_type ?? null,\n // Same NOT NULL DEFAULT note as in upsert above.\n fact.lifecycle_status ?? 'stable',\n fact.stale_after ?? null,\n fact.generated_by ?? null,\n fact.last_verified_at ?? null,\n fact.last_verified_by ?? null,\n fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,\n fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,\n fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,\n ],\n );\n\n return result;\n }\n\n /**\n * Soft-delete a single entry by ID scoped to entityId. Sets deleted_at + updated_at.\n * `tx` is REQUIRED to ensure atomic outbox staging.\n */\n async softDelete(entryId: string, entityId: string, tx: SQLiteAdapter): Promise<{ changes: number }> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n const result = await executor.runAsync(\n `UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,\n [now, now, entryId, entityId],\n );\n\n await this.outbox.push({\n entityId,\n tableName: 'entries',\n recordId: entryId,\n operation: 'DELETE',\n payload: { id: entryId, entity_id: entityId, deleted_at: now },\n }, tx);\n\n return result;\n }\n\n /**\n * Soft-delete entries by source_ref and/or source_hash within a transaction.\n * Stages a DELETE outbox entry for each row in the same transaction.\n * `tx` is REQUIRED.\n * Returns the number of rows deleted.\n */\n async softDeleteBySource(\n entityId: string,\n tx: SQLiteAdapter,\n sourceRef?: string | null,\n sourceHash?: string | null,\n ): Promise<number> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n\n let q = `UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE entity_id = ? AND deleted_at IS NULL`;\n const args: any[] = [now, now, entityId];\n if (sourceRef) {\n q += ` AND source_ref = ?`;\n args.push(sourceRef);\n }\n if (sourceHash) {\n q += ` AND source_hash = ?`;\n args.push(sourceHash);\n }\n\n // Build a separate SELECT query to get affected IDs before updating\n let selectQ = `SELECT id FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL`;\n const selectArgs: any[] = [entityId];\n if (sourceRef) {\n selectQ += ` AND source_ref = ?`;\n selectArgs.push(sourceRef);\n }\n if (sourceHash) {\n selectQ += ` AND source_hash = ?`;\n selectArgs.push(sourceHash);\n }\n\n const idsToDelete = await executor.getAllAsync<{ id: string }>(selectQ, selectArgs);\n\n const result = await executor.runAsync(q, args);\n\n for (const row of idsToDelete) {\n await this.outbox.push({\n entityId,\n tableName: 'entries',\n recordId: row.id,\n operation: 'DELETE',\n payload: { id: row.id, entity_id: entityId, deleted_at: now },\n }, tx);\n }\n\n return result.changes;\n }\n\n /**\n * Fetch IDs + entity_ids of soft-deleted rows older than cutoff for a given entity.\n * Used by runPrune().\n */\n async getPrunableMetadata(\n entityId: string,\n cutoff: number,\n tx?: SQLiteAdapter,\n ): Promise<Array<{ id: string; entity_id: string }>> {\n const executor = this.getExecutor(tx);\n return executor.getAllAsync<{ id: string; entity_id: string }>(\n `SELECT id, entity_id FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ?`,\n [entityId, cutoff],\n );\n }\n\n /**\n * Fetch all non-deleted entries for an entity, ordered by updated_at DESC.\n * Used by _getFullBundle().\n */\n async findAllByEntityId(entityId: string, tx?: SQLiteAdapter): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL ORDER BY updated_at DESC`,\n [entityId],\n );\n return rows.map(mapRowToFact);\n }\n\n /**\n * Fetch live, mutable entries for an entity — everything heal is allowed to\n * downgrade or delete — oldest first, capped at `limit`, skipping anything\n * stamped inside the recheck cooldown (heal_checked_at > recheckCutoff).\n *\n * Oldest-first rather than newest-first: with a cooldown in place, newest-first\n * would keep re-selecting recently-touched facts every pass while older ones\n * wait indefinitely to even enter a batch.\n */\n async findHealCandidatesByEntityId(\n entityId: string,\n limit: number,\n recheckCutoff: number,\n tx?: SQLiteAdapter,\n ): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL AND source_type != 'immutable_document'\n AND (heal_checked_at IS NULL OR heal_checked_at <= ?)\n ORDER BY updated_at ASC LIMIT ?`,\n [entityId, recheckCutoff, limit],\n );\n return rows.map(mapRowToFact);\n }\n\n /**\n * Resolve search hits to document anchors. The MiniSearch index holds every\n * fact, not only immutable_document rows, so the source-type restriction has\n * to be applied here, after retrieval.\n */\n async findAnchorRowsByIds(\n entityId: string,\n ids: readonly string[],\n tx?: SQLiteAdapter,\n opts?: { withBody?: boolean },\n ): Promise<Array<{ id: string; title: string; source_ref: string | null; body?: string; lifecycle_status?: string }>> {\n if (ids.length === 0) return [];\n const executor = this.getExecutor(tx);\n // Bodies and status are read only for heal grounding (spec §6.3, rev 7);\n // the default projection is unchanged.\n const columns = opts?.withBody ? 'id, title, source_ref, body, lifecycle_status' : 'id, title, source_ref';\n const rows: Array<{ id: string; title: string; source_ref: string | null; body?: string; lifecycle_status?: string }> = [];\n // Chunked like every other multi-id read here. The current caller stays well\n // under SQLITE_MAX_VARIABLE_NUMBER, but that is a property of the caller,\n // not of this method.\n for (let i = 0; i < ids.length; i += this.chunkSize) {\n const chunk = ids.slice(i, i + this.chunkSize);\n const placeholders = chunk.map(() => '?').join(', ');\n const chunkRows = await executor.getAllAsync<{ id: string; title: string; source_ref: string | null; body?: string; lifecycle_status?: string }>(\n `SELECT ${columns} FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL\n AND source_type = 'immutable_document'\n AND id IN (${placeholders})`,\n [entityId, ...chunk],\n );\n rows.push(...chunkRows);\n }\n return rows;\n }\n\n /**\n * Fetch recent non-deleted entries for an entity (limited), ordered by updated_at DESC.\n * Used by MaintenanceService.doRunLibrarian().\n *\n * When `excludeSourceRef` is supplied, the WHERE clause filters out that\n * sourceRef BEFORE applying LIMIT. The caller in IngestionService is\n * `findRecentByEntityId(entityId, 500, tx)` — it discards same-sourceRef\n * rows after the read to build a cross-sourceRef title index. If those\n * rows are filtered out in SQL, the limit applies to usable rows only\n * and a re-ingest where the caller's sourceRef owns most recent facts\n * still leaves cross-sourceRef entries in the index.\n */\n async findRecentByEntityId(\n entityId: string,\n limit: number,\n tx?: SQLiteAdapter,\n excludeSourceRef?: string,\n ): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n // `IS NULL OR !=` keeps NULL-source_ref rows (e.g. librarian_inferred facts)\n // in the cross-sourceRef title index. The intent of `excludeSourceRef` is\n // \"drop THIS sourceRef's rows\"; NULL rows belong to neither the current\n // sourceRef nor the replacement set, and excluding them causes edges\n // targeting legacy/non-document facts to fail to resolve.\n const excludeClause = excludeSourceRef ? ` AND (source_ref IS NULL OR source_ref != ?)` : '';\n const args: unknown[] = excludeSourceRef ? [entityId, excludeSourceRef, limit] : [entityId, limit];\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL${excludeClause} ORDER BY updated_at DESC LIMIT ?`,\n args,\n );\n return rows.map(mapRowToFact);\n }\n\n /**\n * Fetch all non-deleted entries for an entity with embedding blobs preserved.\n * Used by ImportExportService for export/import round-tripping.\n */\n async findAllByEntityIdWithBlobs(entityId: string, tx?: SQLiteAdapter): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL ORDER BY updated_at DESC`,\n [entityId],\n );\n return rows.map(mapRowToFactWithBlobs);\n }\n\n /**\n * Count non-deleted entries for the given entities whose embedding_blob dimension\n * doesn't match queryVecLength. Used by read() to detect model-switch mismatches.\n */\n async countDimensionMismatched(\n entityIds: readonly string[],\n queryVecLength: number,\n tx?: SQLiteAdapter,\n ): Promise<number> {\n if (entityIds.length === 0) return 0;\n const executor = this.getExecutor(tx);\n const placeholders = entityIds.map(() => '?').join(',');\n const row = await executor.getFirstAsync<{ cnt: number }>(\n `SELECT COUNT(*) AS cnt FROM ${this.prefix}entries\n WHERE entity_id IN (${placeholders}) AND deleted_at IS NULL\n AND embedding_blob IS NOT NULL\n AND (CAST(length(embedding_blob) AS INTEGER) % 4 = 0)\n AND (CAST(length(embedding_blob) AS INTEGER) / 4) != ?`,\n [...entityIds, queryVecLength],\n );\n return row?.cnt ?? 0;\n }\n\n /**\n * Count non-deleted entries for entityId that are stale relative to targetDim\n * (either no blob or wrong dimension). Used by runReembed() per-entity skip logic.\n */\n async countStaleForEntity(entityId: string, targetDim: number, tx?: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ cnt: number }>(\n `SELECT COUNT(*) AS cnt FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL\n AND (\n embedding_blob IS NULL\n OR (CAST(length(embedding_blob) AS INTEGER) / 4) != ?\n )`,\n [entityId, targetDim],\n );\n return row?.cnt ?? 0;\n }\n\n /**\n * Count non-deleted entries with stale or unconverted embeddings relative to `dim`.\n * Used by _reconcileEmbeddingDimension() to decide when to promote the pending\n * embedding_dimension value.\n */\n async countStaleEmbeddings(dim: number, tx?: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ cnt: number }>(\n `SELECT COUNT(*) AS cnt FROM ${this.prefix}entries\n WHERE deleted_at IS NULL\n AND (\n (embedding_blob IS NOT NULL AND (CAST(length(embedding_blob) AS INTEGER) / 4) != ?)\n OR (embedding_blob IS NULL AND embedding IS NOT NULL)\n )`,\n [dim],\n );\n return row?.cnt ?? 0;\n }\n\n /**\n * Bulk delete pruned entries (already soft-deleted) by IDs.\n * Used by runPrune(). Returns total number of deleted rows.\n * `tx` is REQUIRED so outbox deletion events are staged atomically.\n */\n async bulkDeletePruned(\n entityId: string,\n cutoff: number,\n ids: string[],\n tx: SQLiteAdapter,\n ): Promise<number> {\n const executor = this.getExecutor(tx);\n let totalChanges = 0;\n const chunkSize = 500;\n for (let i = 0; i < ids.length; i += chunkSize) {\n const chunk = ids.slice(i, i + chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n const result = await executor.runAsync(\n `DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ? AND id IN (${placeholders})`,\n [entityId, cutoff, ...chunk],\n );\n totalChanges += result.changes;\n // Stage outbox entries for permanently deleted records\n if (result.changes > 0) {\n for (const id of chunk) {\n await this.outbox.push({\n entityId,\n tableName: 'entries',\n recordId: id,\n operation: 'DELETE',\n payload: { id, entity_id: entityId, deleted_at: cutoff },\n }, tx);\n }\n }\n }\n return totalChanges;\n }\n\n /**\n * Mark orphaned entries (never accessed, old) as deleted.\n * Used by MaintenanceService.doRunHeal().\n */\n async markOrphaned(\n entityId: string,\n orphanThreshold: number,\n tx: SQLiteAdapter,\n ): Promise<string[]> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n const updatedRows = await executor.getAllAsync<{ id: string }>(\n `UPDATE ${this.prefix}entries\n SET deleted_at = ?, updated_at = ?\n WHERE entity_id = ? AND access_count = 0 AND created_at <= ? AND source_type != 'immutable_document' AND deleted_at IS NULL\n RETURNING id`,\n [now, now, entityId, orphanThreshold],\n );\n for (const row of updatedRows) {\n await this.outbox.push({\n entityId,\n tableName: 'entries',\n recordId: row.id,\n operation: 'DELETE',\n payload: { id: row.id, entity_id: entityId, deleted_at: now },\n }, tx);\n }\n return updatedRows.map(r => r.id);\n }\n\n /**\n * Downgrade stale inferred entries to 'tentative'.\n * Used by MaintenanceService.doRunHeal().\n *\n * Returns the ids it downgraded so the caller can fold them into\n * {@link HealResult.downgraded} without double-counting a fact the model also\n * downgraded in the same pass.\n */\n async downgradeStaleInferred(\n entityId: string,\n staleThreshold: number,\n tx: SQLiteAdapter,\n ): Promise<string[]> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n const eligibleRows = await executor.getAllAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}entries\n WHERE entity_id = ? AND confidence = 'inferred'\n AND (last_accessed_at <= ? OR (last_accessed_at IS NULL AND created_at <= ?))\n AND source_type != 'immutable_document' AND deleted_at IS NULL`,\n [entityId, staleThreshold, staleThreshold],\n );\n if (eligibleRows.length === 0) return [];\n await executor.runAsync(\n `UPDATE ${this.prefix}entries\n SET confidence = 'tentative', updated_at = ?\n WHERE entity_id = ? AND confidence = 'inferred' AND (last_accessed_at <= ? OR (last_accessed_at IS NULL AND created_at <= ?)) AND source_type != 'immutable_document' AND deleted_at IS NULL`,\n [now, entityId, staleThreshold, staleThreshold],\n );\n for (const row of eligibleRows) {\n await this.outbox.push({\n entityId,\n tableName: 'entries',\n recordId: row.id,\n operation: 'UPDATE',\n payload: { id: row.id, entity_id: entityId, confidence: 'tentative', updated_at: now },\n }, tx);\n }\n return eligibleRows.map(r => r.id);\n }\n\n /**\n * Downgrade specific entries to 'tentative' by IDs.\n * Used by MaintenanceService.doRunHeal().\n */\n async downgradeByIds(\n ids: string[],\n entityId: string,\n tx: SQLiteAdapter,\n ): Promise<void> {\n if (ids.length === 0) return;\n const executor = this.getExecutor(tx);\n const now = Date.now();\n const placeholders = ids.map(() => '?').join(',');\n await executor.runAsync(\n `UPDATE ${this.prefix}entries SET confidence = 'tentative', updated_at = ? WHERE id IN (${placeholders}) AND entity_id = ?`,\n [now, ...ids, entityId],\n );\n // Stage outbox entries for downgraded records\n for (const id of ids) {\n await this.outbox.push({\n entityId,\n tableName: 'entries',\n recordId: id,\n operation: 'UPDATE',\n payload: { id, entity_id: entityId, confidence: 'tentative', updated_at: now },\n }, tx);\n }\n }\n\n /**\n * Soft-delete specific entries by IDs.\n * Used by MaintenanceService.doRunHeal().\n */\n async softDeleteByIds(\n ids: string[],\n entityId: string,\n tx: SQLiteAdapter,\n ): Promise<void> {\n if (ids.length === 0) return;\n const executor = this.getExecutor(tx);\n const now = Date.now();\n const placeholders = ids.map(() => '?').join(',');\n await executor.runAsync(\n `UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE id IN (${placeholders}) AND entity_id = ?`,\n [now, now, ...ids, entityId],\n );\n // Stage outbox entries for soft-deleted records\n for (const id of ids) {\n await this.outbox.push({\n entityId,\n tableName: 'entries',\n recordId: id,\n operation: 'DELETE',\n payload: { id, entity_id: entityId, deleted_at: now },\n }, tx);\n }\n }\n\n /**\n * Bulk soft-delete all entries for an entity.\n * Stages DELETE outbox entries for each row in the same transaction.\n * `tx` is REQUIRED.\n */\n async bulkSoftDeleteByEntityId(entityId: string, tx: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n // Get IDs before updating for outbox staging\n const idsToDelete = await executor.getAllAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL`,\n [entityId],\n );\n const result = await executor.runAsync(\n `UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE entity_id = ? AND deleted_at IS NULL`,\n [now, now, entityId],\n );\n // Stage outbox entries for each deleted record\n for (const row of idsToDelete) {\n await this.outbox.push({\n entityId,\n tableName: 'entries',\n recordId: row.id,\n operation: 'DELETE',\n payload: { id: row.id, entity_id: entityId, deleted_at: now },\n }, tx);\n }\n return result.changes;\n }\n\n async findMiniSearchRows(\n entityId?: string,\n tx?: SQLiteAdapter,\n ): Promise<Array<{ id: string; entity_id: string; title: string; body: string; tags: string }>> {\n const executor = this.getExecutor(tx);\n if (entityId !== undefined) {\n return executor.getAllAsync(\n `SELECT id, entity_id, title, body, tags FROM ${this.prefix}entries WHERE deleted_at IS NULL AND entity_id = ?`,\n [entityId],\n );\n }\n return executor.getAllAsync(\n `SELECT id, entity_id, title, body, tags FROM ${this.prefix}entries WHERE deleted_at IS NULL`,\n );\n }\n\n async updateEmbeddingBlob(id: string, blob: Uint8Array, tx?: SQLiteAdapter): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `UPDATE ${this.prefix}entries\n SET embedding_blob = ?,\n embedding = NULL,\n embedding_failed_at = NULL,\n embedding_failure_kind = NULL,\n embedding_attempts = 0\n WHERE id = ?`,\n [blob, id],\n );\n }\n\n /**\n * Record a failed embedding attempt. Deliberately does NOT touch updated_at\n * (import merge is last-write-wins on it) and pushes no outbox event —\n * embedding lifecycle is local state, not replicated. Same discipline as\n * updateEmbeddingBlob. See spec §3.5.\n *\n * Only marker-eligible kinds (spec §3.3) are accepted: `no_provider` never\n * marks and `storage_error` never marks, so retry/permanent-failure policy\n * built on these rows only ever sees real embed failures.\n */\n async markEmbeddingFailure(\n id: string,\n kind: EmbeddingMarkerKind,\n now: number,\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `UPDATE ${this.prefix}entries\n SET embedding_failed_at = ?,\n embedding_failure_kind = ?,\n embedding_attempts = embedding_attempts + 1\n WHERE id = ?`,\n [now, kind, id],\n );\n }\n\n /**\n * Clear marker state for every marked row. Called when the embedding\n * dimension is promoted: a new model produces different vectors, so past\n * failures — including `float32_overflow`, which is otherwise terminal —\n * no longer predict future ones (spec §2.3).\n *\n * Same discipline as markEmbeddingFailure: no `updated_at` touch and no\n * outbox event, because embedding lifecycle is local state, not replicated.\n * Returns the number of rows cleared.\n */\n async clearEmbeddingFailureMarkers(tx?: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const result = await executor.runAsync(\n `UPDATE ${this.prefix}entries\n SET embedding_failed_at = NULL,\n embedding_failure_kind = NULL,\n embedding_attempts = 0\n WHERE embedding_failed_at IS NOT NULL`,\n );\n return result.changes;\n }\n\n async hasLegacySourceTypes(tx?: SQLiteAdapter): Promise<boolean> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ one: number }>(\n `SELECT 1 AS one FROM ${this.prefix}entries WHERE source_type IN ('user_document', 'agent_inferred') LIMIT 1`,\n [],\n );\n return row != null;\n }\n\n async countLegacySourceTypes(tx?: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ count: number }>(\n `SELECT COUNT(*) as count FROM ${this.prefix}entries WHERE source_type IN ('user_document', 'agent_inferred')`,\n [],\n );\n return row?.count ?? 0;\n }\n\n async findAllForReembed(entityId?: string, tx?: SQLiteAdapter): Promise<ReembedCandidateRow[]> {\n const executor = this.getExecutor(tx);\n if (entityId !== undefined) {\n return executor.getAllAsync(\n `SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL`,\n [entityId],\n );\n }\n return executor.getAllAsync(\n `SELECT * FROM ${this.prefix}entries WHERE deleted_at IS NULL`,\n );\n }\n\n async findRowsForSourceRefMigration(tx?: SQLiteAdapter): Promise<Array<{ rowid: number; source_ref: string }>> {\n const executor = this.getExecutor(tx);\n return executor.getAllAsync(\n `SELECT rowid, source_ref FROM ${this.prefix}entries\n WHERE source_ref IS NOT NULL\n AND (\n TRIM(source_ref) != source_ref\n OR INSTR(source_ref, '/') > 0\n OR INSTR(source_ref, '\\\\') > 0\n OR INSTR(source_ref, CHAR(0)) > 0\n OR source_ref GLOB '*[^-A-Za-z0-9._ ]*'\n )`,\n );\n }\n\n async updateSourceRefByRowid(rowid: number, sourceRef: string | null, tx: SQLiteAdapter): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `UPDATE ${this.prefix}entries SET source_ref = ? WHERE rowid = ?`,\n [sourceRef, rowid],\n );\n }\n\n async findLatestSourceHash(entityId: string, sourceRef: string, tx?: SQLiteAdapter): Promise<string | null> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ source_hash: string | null }>(\n `SELECT source_hash FROM ${this.prefix}entries\n WHERE entity_id = ? AND source_ref = ? AND deleted_at IS NULL\n ORDER BY updated_at DESC, id ASC\n LIMIT 1`,\n [entityId, sourceRef],\n );\n return row?.source_hash ?? null;\n }\n\n /**\n * Batch version of {@link findLatestSourceHash}. Returns a Map covering every\n * requested ref, where the value is the source_hash from the row with the\n * most-recently-updated live fact for that ref, or null when no live row exists.\n *\n * The SQL uses ROW_NUMBER() OVER (PARTITION BY source_ref ORDER BY updated_at\n * DESC, id ASC) — NOT MAX(source_hash). Aggregation with MAX(source_hash) is\n * wrong because MAX computes independently across grouped rows; the hash must\n * come from the exact row that wins MAX(updated_at). The `id ASC` tie-break\n * keeps selection deterministic when two live rows share `updated_at`.\n *\n * Source refs are de-duplicated and processed in chunks so the per-query bind\n * parameter count stays under SQLite's `SQLITE_MAX_VARIABLE_NUMBER` (default\n * 999, leaving one slot for `entity_id`).\n *\n * Empty input is a synchronous early return with zero SQL calls.\n */\n async findLatestSourceHashes(\n entityId: string,\n sourceRefs: readonly string[],\n tx?: SQLiteAdapter,\n ): Promise<Map<string, string | null>> {\n const out = new Map<string, string | null>();\n if (sourceRefs.length === 0) return out;\n // Pre-populate with null for every requested ref so callers can distinguish\n // \"no live row\" (null) from \"row with a null source_hash\" (also null in this\n // shape, but at least the key is guaranteed present).\n const dedupedRefs = Array.from(new Set(sourceRefs));\n for (const ref of dedupedRefs) {\n out.set(ref, null);\n }\n const executor = this.getExecutor(tx);\n // 1 bind parameter for entity_id; remaining slots for source_ref placeholders.\n const chunkLimit = Math.max(1, this.chunkSize - 1);\n for (let i = 0; i < dedupedRefs.length; i += chunkLimit) {\n const chunk = dedupedRefs.slice(i, i + chunkLimit);\n const placeholders = chunk.map(() => '?').join(',');\n const rows = await executor.getAllAsync<{ source_ref: string; source_hash: string | null }>(\n `WITH ranked AS (\n SELECT source_ref, source_hash,\n ROW_NUMBER() OVER (\n PARTITION BY source_ref\n ORDER BY updated_at DESC, id ASC\n ) as rn\n FROM ${this.prefix}entries\n WHERE entity_id = ? AND source_ref IN (${placeholders}) AND deleted_at IS NULL\n )\n SELECT source_ref, source_hash\n FROM ranked\n WHERE rn = 1`,\n [entityId, ...chunk],\n );\n for (const r of rows) {\n out.set(r.source_ref, r.source_hash);\n }\n }\n return out;\n }\n\n /**\n * Per source ref, the hash of the latest live row (same ordering as\n * {@link findLatestSourceHashes}) and whether ANY live row carries a hash.\n * Refs with no live row are absent. Chunked under the bind-variable limit.\n */\n async findSourceStates(\n entityId: string,\n sourceRefs: readonly string[],\n tx?: SQLiteAdapter,\n ): Promise<Map<string, { latestHash: string | null; anyHashed: boolean }>> {\n const out = new Map<string, { latestHash: string | null; anyHashed: boolean }>();\n const deduped = Array.from(new Set(sourceRefs));\n if (deduped.length === 0) return out;\n const executor = this.getExecutor(tx);\n const chunkLimit = Math.max(1, this.chunkSize - 1);\n for (let i = 0; i < deduped.length; i += chunkLimit) {\n const chunk = deduped.slice(i, i + chunkLimit);\n const placeholders = chunk.map(() => '?').join(',');\n const rows = await executor.getAllAsync<{ source_ref: string; source_hash: string | null; any_hashed: number }>(\n `WITH ranked AS (\n SELECT source_ref, source_hash,\n ROW_NUMBER() OVER (PARTITION BY source_ref ORDER BY updated_at DESC, id ASC) AS rn,\n MAX(CASE WHEN source_hash IS NOT NULL THEN 1 ELSE 0 END) OVER (PARTITION BY source_ref) AS any_hashed\n FROM ${this.prefix}entries\n WHERE entity_id = ? AND source_ref IN (${placeholders}) AND deleted_at IS NULL\n )\n SELECT source_ref, source_hash, any_hashed FROM ranked WHERE rn = 1`,\n [entityId, ...chunk],\n );\n for (const r of rows) out.set(r.source_ref, { latestHash: r.source_hash, anyHashed: Number(r.any_hashed) === 1 });\n }\n return out;\n }\n\n /**\n * Return the live source_refs for an entity that hold the given source_hash.\n * Used by the ingestDocument duplicate-hash guard and by hosts auditing\n * duplicate-content collisions. Sorted `COLLATE BINARY` so the canonical\n * ref (the code-unit-minimum of the set) is stable across deploys.\n */\n async findSourceRefsByHash(\n entityId: string,\n sourceHash: string,\n tx?: SQLiteAdapter,\n ): Promise<string[]> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<{ source_ref: string }>(\n `SELECT source_ref FROM ${this.prefix}entries\n WHERE entity_id = ? AND source_hash = ? AND deleted_at IS NULL\n AND source_ref IS NOT NULL\n GROUP BY source_ref\n ORDER BY source_ref COLLATE BINARY`,\n [entityId, sourceHash],\n );\n return rows.map(r => r.source_ref);\n }\n\n /**\n * Per-sourceRef rollup for an entity: one row per live source_ref, with the\n * most-recently-updated live hash (NOT the lexically-max hash) and a live\n * fact count.\n *\n * The hash comes from the same row that wins ROW_NUMBER() over updated_at\n * DESC, so a ref with multiple live hashes (e.g. from import) reports the\n * latest one — matching single-doc `findLatestSourceHash` semantics.\n *\n * Sort is COLLATE BINARY: locale-dependent ordering re-mints identity on\n * every deploy, which is the bug this whole section exists to prevent.\n */\n async listSourceRefs(\n entityId: string,\n tx?: SQLiteAdapter,\n ): Promise<Array<{\n sourceRef: string;\n sourceHash: string | null;\n factCount: number;\n lastIngestedAt: number;\n }>> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<{\n source_ref: string;\n source_hash: string | null;\n fact_count: number;\n last_ingested_at: number;\n }>(\n `WITH ranked AS (\n SELECT source_ref, source_hash, updated_at,\n ROW_NUMBER() OVER (\n PARTITION BY source_ref\n ORDER BY updated_at DESC, id ASC\n ) AS rn,\n COUNT(*) OVER (PARTITION BY source_ref) AS fact_count\n FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL AND source_ref IS NOT NULL\n )\n SELECT source_ref,\n source_hash AS source_hash,\n fact_count AS fact_count,\n updated_at AS last_ingested_at\n FROM ranked\n WHERE rn = 1\n ORDER BY source_ref COLLATE BINARY`,\n [entityId],\n );\n return rows.map(r => ({\n sourceRef: r.source_ref,\n sourceHash: r.source_hash,\n factCount: Number(r.fact_count),\n lastIngestedAt: Number(r.last_ingested_at),\n }));\n }\n\n /**\n * Count live entries for an entity across all source_refs/source_hashes.\n * Used by forget({ dryRun, clearAll: true }).\n */\n async countLiveByEntityId(entityId: string, tx?: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ cnt: number }>(\n `SELECT COUNT(*) AS cnt FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL`,\n [entityId],\n );\n return row?.cnt ?? 0;\n }\n\n /**\n * Count live entries matching a source filter (either or both may be null).\n * Used by forget({ dryRun: true }) with sourceRef/sourceHash.\n */\n async countLiveBySource(\n entityId: string,\n sourceRef: string | null,\n sourceHash: string | null,\n tx?: SQLiteAdapter,\n ): Promise<number> {\n const executor = this.getExecutor(tx);\n let q = `SELECT COUNT(*) AS cnt FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL`;\n const args: unknown[] = [entityId];\n if (sourceRef !== null) { q += ` AND source_ref = ?`; args.push(sourceRef); }\n if (sourceHash !== null) { q += ` AND source_hash = ?`; args.push(sourceHash); }\n const row = await executor.getFirstAsync<{ cnt: number }>(q, args);\n return row?.cnt ?? 0;\n }\n\n async findMetadataByIds(ids: readonly string[], tx?: SQLiteAdapter): Promise<EntryRowMetadata[]> {\n if (ids.length === 0) return [];\n const executor = this.getExecutor(tx);\n const rows: EntryRowMetadata[] = [];\n for (let i = 0; i < ids.length; i += this.chunkSize) {\n const chunk = ids.slice(i, i + this.chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n const chunkRows = await executor.getAllAsync<EntryRowMetadata>(\n `SELECT id, entity_id, updated_at, access_count FROM ${this.prefix}entries WHERE id IN (${placeholders}) AND deleted_at IS NULL`,\n chunk,\n );\n rows.push(...chunkRows);\n }\n return rows;\n }\n\n async findWithEmbeddingsByIds(ids: readonly string[], tx?: SQLiteAdapter): Promise<EntryRowWithEmbeddings[]> {\n if (ids.length === 0) return [];\n const executor = this.getExecutor(tx);\n const rows: EntryRowWithEmbeddings[] = [];\n for (let i = 0; i < ids.length; i += this.chunkSize) {\n const chunk = ids.slice(i, i + this.chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n const chunkRows = await executor.getAllAsync<EntryRowWithEmbeddings>(\n `SELECT id, entity_id, embedding_blob, embedding, updated_at, access_count FROM ${this.prefix}entries WHERE id IN (${placeholders}) AND deleted_at IS NULL`,\n chunk,\n );\n rows.push(...chunkRows);\n }\n return rows;\n }\n\n async findMetadataByEntityIds(entityIds: readonly string[], tx?: SQLiteAdapter): Promise<EntryRowMetadata[]> {\n if (entityIds.length === 0) return [];\n const executor = this.getExecutor(tx);\n const placeholders = entityIds.map(() => '?').join(',');\n return executor.getAllAsync<EntryRowMetadata>(\n `SELECT id, entity_id, updated_at, access_count FROM ${this.prefix}entries WHERE entity_id IN (${placeholders}) AND deleted_at IS NULL`,\n [...entityIds],\n );\n }\n\n async findWithEmbeddingsByEntityIds(entityIds: readonly string[], tx?: SQLiteAdapter): Promise<EntryRowWithEmbeddings[]> {\n if (entityIds.length === 0) return [];\n const executor = this.getExecutor(tx);\n const placeholders = entityIds.map(() => '?').join(',');\n return executor.getAllAsync<EntryRowWithEmbeddings>(\n `SELECT id, entity_id, embedding_blob, embedding, updated_at, access_count FROM ${this.prefix}entries WHERE entity_id IN (${placeholders}) AND deleted_at IS NULL`,\n [...entityIds],\n );\n }\n\n async findEmbeddingsByIds(\n ids: readonly string[],\n tx?: SQLiteAdapter,\n ): Promise<Array<{ id: string; embedding_blob: Uint8Array | null; embedding: string | null }>> {\n if (ids.length === 0) return [];\n const executor = this.getExecutor(tx);\n const rows: Array<{ id: string; embedding_blob: Uint8Array | null; embedding: string | null }> = [];\n for (let i = 0; i < ids.length; i += this.chunkSize) {\n const chunk = ids.slice(i, i + this.chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n const chunkRows = await executor.getAllAsync<{ id: string; embedding_blob: Uint8Array | null; embedding: string | null }>(\n `SELECT id, embedding_blob, embedding FROM ${this.prefix}entries WHERE id IN (${placeholders}) AND deleted_at IS NULL`,\n chunk,\n );\n rows.push(...chunkRows);\n }\n return rows;\n }\n\n async trackAccess(ids: readonly string[], now: number, tx?: SQLiteAdapter): Promise<void> {\n if (ids.length === 0) return;\n const executor = this.getExecutor(tx);\n for (let i = 0; i < ids.length; i += this.chunkSize) {\n const chunk = ids.slice(i, i + this.chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n await executor.runAsync(\n `UPDATE ${this.prefix}entries SET access_count = access_count + 1, last_accessed_at = ? WHERE id IN (${placeholders})`,\n [now, ...chunk],\n );\n }\n }\n\n getLegacyMigrationSQL(): string {\n return [\n `-- Migrate legacy source_type values (targets your WikiMemory prefix: ${this.prefix})`,\n `UPDATE ${this.prefix}entries SET source_type = 'immutable_document' WHERE source_type = 'user_document';`,\n `UPDATE ${this.prefix}entries SET source_type = 'librarian_inferred' WHERE source_type = 'agent_inferred';`,\n ].join('\\n');\n }\n\n async findRecentByEntityIds(\n entityIds: readonly string[],\n limit: number,\n tx?: SQLiteAdapter,\n opts?: { excludeDrafts?: boolean },\n ): Promise<WikiFact[]> {\n if (entityIds.length === 0) return [];\n const executor = this.getExecutor(tx);\n const placeholders = entityIds.map(() => '?').join(',');\n const draftClause = opts?.excludeDrafts === true ? ` AND lifecycle_status != 'draft'` : '';\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries WHERE entity_id IN (${placeholders}) AND deleted_at IS NULL${draftClause} ORDER BY updated_at DESC LIMIT ?`,\n [...entityIds, limit],\n );\n return rows.map(mapRowToFact);\n }\n\n /** IDs of live draft facts for the given entities (spec §5.1). Callers pass ≤ 100 entity ids. */\n async findDraftIdsByEntityIds(entityIds: readonly string[], tx?: SQLiteAdapter): Promise<Set<string>> {\n if (entityIds.length === 0) return new Set();\n const executor = this.getExecutor(tx);\n const placeholders = entityIds.map(() => '?').join(',');\n const rows = await executor.getAllAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}entries\n WHERE entity_id IN (${placeholders}) AND deleted_at IS NULL AND lifecycle_status = 'draft'`,\n [...entityIds],\n );\n return new Set(rows.map((r) => r.id));\n }\n\n /** Live drafts for one entity, newest first, keyset-paged by (created_at, id). */\n async listDraftsByEntityId(\n entityId: string,\n limit: number,\n after: { createdAt: number; id: string } | null,\n tx?: SQLiteAdapter,\n ): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n const afterClause = after ? ` AND (created_at < ? OR (created_at = ? AND id < ?))` : '';\n const args: unknown[] = after\n ? [entityId, after.createdAt, after.createdAt, after.id, limit]\n : [entityId, limit];\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL AND lifecycle_status = 'draft'${afterClause}\n ORDER BY created_at DESC, id DESC LIMIT ?`,\n args,\n );\n return rows.map(mapRowToFact);\n }\n\n /** True iff `entryId` is a live draft owned by `entityId`. */\n async isLiveDraft(entryId: string, entityId: string, tx?: SQLiteAdapter): Promise<boolean> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}entries\n WHERE id = ? AND entity_id = ? AND deleted_at IS NULL AND lifecycle_status = 'draft'`,\n [entryId, entityId],\n );\n return row != null;\n }\n\n /**\n * Live untyped facts eligible for ontology backfill, oldest first.\n * Skips facts checked within the recheck cooldown (ontology_checked_at > recheckCutoff).\n */\n async findUntypedByEntityId(entityId: string, limit: number, recheckCutoff: number, tx?: SQLiteAdapter): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries\n WHERE entity_id = ? AND okf_type IS NULL AND deleted_at IS NULL\n AND (ontology_checked_at IS NULL OR ontology_checked_at <= ?)\n ORDER BY updated_at ASC LIMIT ?`,\n [entityId, recheckCutoff, limit],\n );\n return rows.map(mapRowToFact);\n }\n\n /** Counts live untyped facts: eligible (past cooldown) vs deferred (in cooldown). */\n async countUntypedByEntityId(entityId: string, recheckCutoff: number, tx?: SQLiteAdapter): Promise<{ eligible: number; deferred: number }> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ eligible: number | null; deferred: number | null }>(\n `SELECT\n SUM(CASE WHEN ontology_checked_at IS NULL OR ontology_checked_at <= ? THEN 1 ELSE 0 END) AS eligible,\n SUM(CASE WHEN ontology_checked_at IS NOT NULL AND ontology_checked_at > ? THEN 1 ELSE 0 END) AS deferred\n FROM ${this.prefix}entries\n WHERE entity_id = ? AND okf_type IS NULL AND deleted_at IS NULL`,\n [recheckCutoff, recheckCutoff, entityId],\n );\n return { eligible: Number(row?.eligible ?? 0), deferred: Number(row?.deferred ?? 0) };\n }\n\n /**\n * Sets okf_type only when currently NULL — additive by construction: a\n * concurrently-typed fact is never overwritten. Returns changes for the caller\n * to distinguish applied vs skipped.\n */\n async updateOkfType(id: string, entityId: string, okfType: string, tx: SQLiteAdapter): Promise<{ changes: number }> {\n const result = await tx.runAsync(\n `UPDATE ${this.prefix}entries SET okf_type = ?\n WHERE id = ? AND entity_id = ? AND okf_type IS NULL AND deleted_at IS NULL`,\n [okfType, id, entityId],\n );\n return { changes: result.changes };\n }\n\n /**\n * Stamps the backfill recheck cooldown. NEVER touches updated_at — import\n * merge resolution is last-write-wins on updated_at and a bump here would\n * make an unchanged local fact beat a genuinely newer remote edit.\n */\n async markOntologyChecked(ids: string[], entityId: string, now: number, tx: SQLiteAdapter): Promise<void> {\n if (ids.length === 0) return;\n for (let i = 0; i < ids.length; i += this.chunkSize) {\n const chunk = ids.slice(i, i + this.chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n await tx.runAsync(\n `UPDATE ${this.prefix}entries SET ontology_checked_at = ?\n WHERE id IN (${placeholders}) AND entity_id = ? AND deleted_at IS NULL`,\n [now, ...chunk, entityId],\n );\n }\n }\n\n /**\n * Lightweight full-breadth title index (id, title, okf_type) over all live\n * typed facts. Used by ontology backfill edge resolution — a recent-N window\n * would miss an old fact's contemporaries. Untyped rows are excluded: they\n * can never pass the edge target-type check, and batch facts typed during\n * the run are re-added to the in-memory index by the caller.\n */\n async findTitleIndexByEntityId(entityId: string, tx?: SQLiteAdapter): Promise<Array<{ id: string; title: string; okf_type: string | null }>> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<{ id: string; title: string; okf_type: string | null }>(\n `SELECT id, title, okf_type FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND okf_type IS NOT NULL`,\n [entityId],\n );\n return rows.map(r => ({ id: r.id, title: r.title, okf_type: r.okf_type ?? null }));\n }\n\n /** Counts live mutable facts: eligible (past cooldown) vs deferred (in cooldown). */\n async countHealCandidatesByEntityId(\n entityId: string,\n recheckCutoff: number,\n tx?: SQLiteAdapter,\n ): Promise<{ eligible: number; deferred: number }> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ eligible: number | null; deferred: number | null }>(\n `SELECT\n SUM(CASE WHEN heal_checked_at IS NULL OR heal_checked_at <= ? THEN 1 ELSE 0 END) AS eligible,\n SUM(CASE WHEN heal_checked_at IS NOT NULL AND heal_checked_at > ? THEN 1 ELSE 0 END) AS deferred\n FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL AND source_type != 'immutable_document'`,\n [recheckCutoff, recheckCutoff, entityId],\n );\n return { eligible: Number(row?.eligible ?? 0), deferred: Number(row?.deferred ?? 0) };\n }\n\n /**\n * Stamps the heal recheck cooldown. NEVER touches updated_at — import merge\n * resolution is last-write-wins on updated_at and a bump here would make an\n * unchanged local fact beat a genuinely newer remote edit.\n *\n * Soft-deleted rows are skipped: a candidate heal deleted earlier in the same\n * transaction is no longer a candidate under any future pass, so its cooldown\n * value is irrelevant. This means the stamped count can be lower than the\n * offered-candidate count.\n */\n async markHealChecked(ids: string[], entityId: string, now: number, tx: SQLiteAdapter): Promise<void> {\n if (ids.length === 0) return;\n for (let i = 0; i < ids.length; i += this.chunkSize) {\n const chunk = ids.slice(i, i + this.chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n await tx.runAsync(\n `UPDATE ${this.prefix}entries SET heal_checked_at = ?\n WHERE id IN (${placeholders}) AND entity_id = ? AND deleted_at IS NULL`,\n [now, ...chunk, entityId],\n );\n }\n }\n\n /**\n * Lightweight full-breadth index (id, title) over all live librarian_inferred\n * facts. This is heal's fuzzy-dedupe corpus, deliberately kept independent of\n * the bounded candidate window: seeding dedupe from a batchSize-limited read\n * would let a synthesized fact duplicating a fact outside the window pass the\n * Jaccard check, and a convergence loop would multiply those duplicates across\n * passes. Mirrors findTitleIndexByEntityId — full breadth, two columns, cheap.\n */\n async findInferredTitlesByEntityId(\n entityId: string,\n tx?: SQLiteAdapter,\n ): Promise<Array<{ id: string; title: string }>> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<{ id: string; title: string }>(\n `SELECT id, title FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL AND source_type = 'librarian_inferred'`,\n [entityId],\n );\n return rows.map(r => ({ id: r.id, title: r.title }));\n }\n}\n","import { BaseRepository } from './BaseRepository';\nimport type { SQLiteAdapter } from '../types';\nimport { generateId } from '../utils/ids';\n\nexport class OutboxRepository extends BaseRepository {\n private enableOutbox: boolean;\n\n constructor(db: SQLiteAdapter, prefix: string, enableOutbox = false) {\n super(db, prefix);\n this.enableOutbox = enableOutbox;\n }\n\n /**\n * Insert a new outbox event within the provided transaction.\n * No-op when enableOutbox is false.\n * `tx` is required — callers must always pass the active transaction\n * so the write is atomic with the main table mutation.\n */\n async push(\n params: {\n entityId: string;\n tableName: string;\n recordId: string;\n operation: 'INSERT' | 'UPDATE' | 'DELETE';\n payload: any;\n },\n tx: SQLiteAdapter,\n ): Promise<void> {\n if (!this.enableOutbox) return;\n const executor = this.getExecutor(tx);\n const id = generateId('out_');\n const now = Date.now();\n await executor.runAsync(\n `INSERT INTO ${this.prefix}outbox (id, entity_id, table_name, record_id, operation, payload, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)`,\n [id, params.entityId, params.tableName, params.recordId, params.operation, JSON.stringify(params.payload), now],\n );\n }\n\n /**\n * Fetch pending outbox rows ordered by created_at ASC, rowid ASC.\n * Reads directly from `this.db` (not a transaction).\n */\n async fetchPending(limit = 50): Promise<any[]> {\n return this.db.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}outbox ORDER BY created_at ASC, rowid ASC LIMIT ?`,\n [limit],\n );\n }\n\n /**\n * Delete acknowledged outbox rows by their IDs.\n * No-op when `ids` is empty.\n * Deletes directly from `this.db` (not a transaction).\n */\n async acknowledge(ids: string[]): Promise<void> {\n if (ids.length === 0) return;\n const chunkSize = 500;\n for (let i = 0; i < ids.length; i += chunkSize) {\n const chunk = ids.slice(i, i + chunkSize);\n const placeholders = chunk.map(() => '?').join(', ');\n await this.db.runAsync(\n `DELETE FROM ${this.prefix}outbox WHERE id IN (${placeholders})`,\n chunk,\n );\n }\n }\n}\n","import type { SQLiteAdapter } from '../types';\nimport { BaseRepository } from './BaseRepository';\nimport { generateId } from '../utils/ids';\n\n/**\n * Per-(entity_id, source_hash) record of the canonical sourceRef currently\n * holding that hash. The partial UNIQUE index on (entity_id, source_hash)\n * WHERE deleted_at IS NULL enforces the sourceRef-level TOCTOU-race invariant\n * for the #79 fix. See\n * docs/superpowers/specs/2026-08-07-dependabot-concurrency-release-hygiene-design.md §B1.\n *\n * The entries table cannot express this invariant directly because a single\n * `ingestDocument` call writes N facts that all share\n * (entity_id, source_ref, source_hash); a UNIQUE index on\n * `entries(entity_id, source_hash)` would block the 2nd–Nth fact inserts in\n * the normal multi-fact path. The per-(entity, hash) granularity of\n * source_ref_index matches the TOCTOU invariant exactly.\n *\n * No outbox events: this is an internal index table whose state is fully\n * derivable from `entries`. Hosts that need CDC continue to read `entries`\n * outbox events; the index is not part of the user-visible contract.\n */\nexport class SourceRefIndexRepository extends BaseRepository {\n /**\n * Idempotent insert: the partial UNIQUE index catches concurrent inserts for\n * the same (entity_id, source_hash). The caller (IngestionService) catches\n * the resulting SQLITE_CONSTRAINT_UNIQUE and translates it to the per-mode\n * duplicate-hash outcome. Runtime IDs use the `sri_` prefix to avoid\n * collision with the deterministic `sri:<entity>:<hash>` IDs used by the v9\n * backfill (the colon separator keeps the two ID spaces disjoint).\n */\n async upsert(\n entityId: string,\n sourceHash: string,\n sourceRef: string,\n tx: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `INSERT INTO ${this.prefix}source_ref_index (id, entity_id, source_hash, source_ref, created_at, deleted_at)\n VALUES (?, ?, ?, ?, ?, NULL)`,\n [generateId('sri_'), entityId, sourceHash, sourceRef, Date.now()],\n );\n }\n\n /**\n * Idempotent soft-delete of the live row for (entity_id, source_ref).\n * Called at the start of every ingestDocument to remove the prior run's\n * index row, so the new upsert doesn't collide with itself. No-op when the\n * row is already soft-deleted or never existed.\n */\n async softDeleteByEntityAndSourceRef(\n entityId: string,\n sourceRef: string,\n tx: SQLiteAdapter,\n ): Promise<number> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n const result = await executor.runAsync(\n `UPDATE ${this.prefix}source_ref_index\n SET deleted_at = ?, created_at = ?\n WHERE entity_id = ? AND source_ref = ? AND deleted_at IS NULL`,\n [now, now, entityId, sourceRef],\n );\n return result.changes;\n }\n\n /**\n * Returns the live sourceRef holding the given hash, or null when no live\n * row exists. Used by the IngestionService pre-check (line 82) and the\n * catch-and-translate canonical lookup (line 212).\n */\n async findActiveByEntityAndHash(\n entityId: string,\n sourceHash: string,\n tx?: SQLiteAdapter,\n ): Promise<string | null> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ source_ref: string }>(\n `SELECT source_ref FROM ${this.prefix}source_ref_index\n WHERE entity_id = ? AND source_hash = ? AND deleted_at IS NULL`,\n [entityId, sourceHash],\n );\n return row?.source_ref ?? null;\n }\n}\n","import { BaseRepository } from './BaseRepository';\nimport { OutboxRepository } from './OutboxRepository';\nimport type { WikiTask, SQLiteAdapter } from '../types';\nimport { parseJsonArray, parseJsonObject } from './rowMappers';\nimport { isStaleAfter, deriveTrustTier } from '@equationalapplications/core-okf';\n\nfunction mapRowToTask(row: any): WikiTask {\n const okf_verified = parseJsonArray<NonNullable<WikiTask['okf_verified']>[number]>(row.okf_verified, []);\n // Mirror EntryRepository.mapRowToFact — see that file for the rationale on\n // per-row Date.now() sampling vs. a shared per-call value.\n const now = Date.now();\n const staleAfterRaw = row.stale_after != null ? Number(row.stale_after) : null;\n\n return {\n id: row.id,\n entity_id: row.entity_id,\n description: row.description,\n status: row.status,\n priority: Number(row.priority),\n created_at: Number(row.created_at),\n updated_at: Number(row.updated_at),\n resolved_at: row.resolved_at != null ? Number(row.resolved_at) : null,\n deleted_at: row.deleted_at != null ? Number(row.deleted_at) : null,\n okf_type: row.okf_type ?? null,\n // OKF v0.2\n lifecycle_status: (row.lifecycle_status ?? 'stable') as WikiTask['lifecycle_status'],\n stale_after: staleAfterRaw,\n generated_by: row.generated_by ?? null,\n okf_sources: parseJsonArray<NonNullable<WikiTask['okf_sources']>[number]>(row.okf_sources, []),\n okf_verified,\n okf_usage_window: parseJsonObject<NonNullable<WikiTask['okf_usage_window']>>(row.okf_usage_window),\n last_verified_at: row.last_verified_at != null ? Number(row.last_verified_at) : null,\n last_verified_by: row.last_verified_by ?? null,\n // Spec §2.7 + §5.3: hydrate so read() consumers don't re-call the helpers.\n isStale: isStaleAfter(staleAfterRaw, now),\n trustTier: deriveTrustTier(okf_verified),\n };\n}\n\nexport class TaskRepository extends BaseRepository {\n constructor(\n db: SQLiteAdapter,\n prefix: string,\n private outbox: OutboxRepository,\n ) {\n super(db, prefix);\n }\n\n /**\n * Fetch a single task by ID. Returns null if not found or soft-deleted.\n */\n async findById(id: string): Promise<WikiTask | null> {\n const row = await this.db.getFirstAsync<any>(\n `SELECT * FROM ${this.prefix}tasks WHERE id = ? AND deleted_at IS NULL`,\n [id],\n );\n return row ? mapRowToTask(row) : null;\n }\n\n /**\n * Fetch all pending/in_progress tasks for the given entity IDs.\n * Returns empty array when entityIds is empty.\n */\n async findAllPending(entityIds: string[], limit?: number): Promise<WikiTask[]> {\n if (entityIds.length === 0) return [];\n const placeholders = entityIds.map(() => '?').join(', ');\n const sql =\n `SELECT * FROM ${this.prefix}tasks ` +\n `WHERE entity_id IN (${placeholders}) AND status IN ('pending', 'in_progress') AND deleted_at IS NULL ` +\n `ORDER BY priority DESC, created_at ASC` +\n (limit != null ? ` LIMIT ?` : '');\n const params: unknown[] = limit != null ? [...entityIds, limit] : [...entityIds];\n const rows = await this.db.getAllAsync<any>(sql, params);\n return rows.map(mapRowToTask);\n }\n\n async findExistingMetadataByIds(\n ids: readonly string[],\n tx?: SQLiteAdapter,\n ): Promise<Array<{ id: string; entity_id: string; updated_at: number }>> {\n const executor = this.getExecutor(tx);\n const rows: Array<{ id: string; entity_id: string; updated_at: number }> = [];\n const chunkSize = 500;\n for (let i = 0; i < ids.length; i += chunkSize) {\n const chunk = ids.slice(i, i + chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n const chunkRows = await executor.getAllAsync<any>(\n `SELECT id, entity_id, updated_at FROM ${this.prefix}tasks WHERE id IN (${placeholders})`,\n chunk,\n );\n rows.push(...chunkRows.map((row) => ({ id: row.id, entity_id: row.entity_id, updated_at: Number(row.updated_at) })));\n }\n return rows;\n }\n\n /**\n * Upsert a WikiTask within the provided transaction.\n * Uses ON CONFLICT(id) DO UPDATE (not INSERT OR REPLACE).\n * Stages an outbox entry in the same transaction.\n * `tx` is REQUIRED.\n *\n * OKF metadata (lifecycle_status, sources, etc.) is intentionally excluded\n * from the SET clause so content writes preserve any existing row values.\n * See {@link EntryRepository.upsert} for the rationale — the same applies\n * symmetrically to tasks (spec §2.5). Callers that need to overwrite OKF\n * metadata should use {@link upsertForImport}.\n */\n async upsert(task: WikiTask, tx: SQLiteAdapter, updatedAt?: number): Promise<void> {\n const executor = this.getExecutor(tx);\n const now = Number.isFinite(updatedAt) ? updatedAt : Date.now();\n\n const existingRow = await executor.getFirstAsync<{\n id: string;\n lifecycle_status: string;\n stale_after: number | null;\n generated_by: string | null;\n okf_sources: string | null;\n okf_verified: string | null;\n okf_usage_window: string | null;\n last_verified_at: number | null;\n last_verified_by: string | null;\n }>(\n `SELECT id, lifecycle_status, stale_after, generated_by,\n okf_sources, okf_verified, okf_usage_window,\n last_verified_at, last_verified_by\n FROM ${this.prefix}tasks WHERE id = ?`,\n [task.id],\n );\n const operation = task.deleted_at != null ? 'DELETE' : (existingRow ? 'UPDATE' : 'INSERT');\n\n await executor.runAsync(\n `INSERT INTO ${this.prefix}tasks (\n id, entity_id, description, status, priority,\n created_at, updated_at, resolved_at, deleted_at,\n lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,\n okf_sources, okf_verified, okf_usage_window\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n entity_id = excluded.entity_id,\n description = excluded.description,\n status = excluded.status,\n priority = excluded.priority,\n updated_at = excluded.updated_at,\n resolved_at = excluded.resolved_at,\n deleted_at = excluded.deleted_at`,\n [\n task.id,\n task.entity_id,\n task.description,\n task.status,\n task.priority,\n task.created_at,\n now, // updated_at set by repo or import override\n task.resolved_at ?? null,\n task.deleted_at ?? null,\n // OKF v0.2 metadata — bound for INSERT only; ON CONFLICT UPDATE\n // preserves the existing row values (these columns are intentionally\n // absent from the SET clause above).\n task.lifecycle_status ?? 'stable',\n task.stale_after ?? null,\n task.generated_by ?? null,\n task.last_verified_at ?? null,\n task.last_verified_by ?? null,\n task.okf_sources ? JSON.stringify(task.okf_sources) : null,\n task.okf_verified ? JSON.stringify(task.okf_verified) : null,\n task.okf_usage_window ? JSON.stringify(task.okf_usage_window) : null,\n ],\n );\n\n // Outbox payload mirrors what is actually persisted. On UPDATE, the SET\n // clause intentionally omits OKF metadata so prior row values win, but\n // the caller-supplied `task` would still describe state we did NOT write.\n // Re-read those columns from the stored row and overlay them onto the\n // caller-supplied payload before publishing (#90 review).\n const persistedOkf = existingRow\n ? {\n lifecycle_status: (existingRow.lifecycle_status ?? 'stable') as WikiTask['lifecycle_status'],\n stale_after: existingRow.stale_after != null ? Number(existingRow.stale_after) : null,\n generated_by: existingRow.generated_by ?? null,\n okf_sources: parseJsonArray<NonNullable<WikiTask['okf_sources']>[number]>(existingRow.okf_sources, []),\n okf_verified: parseJsonArray<NonNullable<WikiTask['okf_verified']>[number]>(existingRow.okf_verified, []),\n okf_usage_window: parseJsonObject<NonNullable<WikiTask['okf_usage_window']>>(existingRow.okf_usage_window),\n last_verified_at: existingRow.last_verified_at != null ? Number(existingRow.last_verified_at) : null,\n last_verified_by: existingRow.last_verified_by ?? null,\n }\n : null;\n await this.outbox.push(\n {\n entityId: task.entity_id,\n tableName: 'tasks',\n recordId: task.id,\n operation,\n payload: persistedOkf ? { ...task, ...persistedOkf } : task,\n },\n tx,\n );\n }\n\n async upsertForImport(task: WikiTask, tx: SQLiteAdapter, updatedAt?: number): Promise<void> {\n const executor = this.getExecutor(tx);\n const now = Number.isFinite(updatedAt) ? updatedAt : Date.now();\n\n // Import is replace semantics, mirroring EntryRepository.upsertForImport.\n // Dump is authoritative: a re-import that cleared stale_after, generated_by,\n // or verification mirrors must overwrite, not preserve.\n await executor.runAsync(\n `INSERT INTO ${this.prefix}tasks (\n id, entity_id, description, status, priority,\n created_at, updated_at, resolved_at, deleted_at, okf_type,\n lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,\n okf_sources, okf_verified, okf_usage_window\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n entity_id = excluded.entity_id,\n description = excluded.description,\n status = excluded.status,\n priority = excluded.priority,\n updated_at = excluded.updated_at,\n resolved_at = excluded.resolved_at,\n deleted_at = excluded.deleted_at,\n okf_type = excluded.okf_type,\n lifecycle_status = excluded.lifecycle_status,\n stale_after = excluded.stale_after,\n generated_by = excluded.generated_by,\n last_verified_at = excluded.last_verified_at,\n last_verified_by = excluded.last_verified_by,\n okf_sources = excluded.okf_sources,\n okf_verified = excluded.okf_verified,\n okf_usage_window = excluded.okf_usage_window`,\n [\n task.id,\n task.entity_id,\n task.description,\n task.status,\n task.priority,\n task.created_at,\n now,\n task.resolved_at ?? null,\n task.deleted_at ?? null,\n task.okf_type ?? null,\n task.lifecycle_status ?? 'stable',\n task.stale_after ?? null,\n task.generated_by ?? null,\n task.last_verified_at ?? null,\n task.last_verified_by ?? null,\n task.okf_sources ? JSON.stringify(task.okf_sources) : null,\n task.okf_verified ? JSON.stringify(task.okf_verified) : null,\n task.okf_usage_window ? JSON.stringify(task.okf_usage_window) : null,\n ],\n );\n }\n\n /**\n * Soft-delete a task by ID. Sets deleted_at and updated_at.\n * Stages a DELETE outbox entry in the same transaction.\n * `tx` is REQUIRED.\n */\n async softDelete(id: string, entityId: string, tx: SQLiteAdapter): Promise<void> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n await executor.runAsync(\n `UPDATE ${this.prefix}tasks SET deleted_at = ?, updated_at = ? WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,\n [now, now, id, entityId],\n );\n await this.outbox.push(\n {\n entityId,\n tableName: 'tasks',\n recordId: id,\n operation: 'DELETE',\n payload: { id, entity_id: entityId, deleted_at: now },\n },\n tx,\n );\n }\n\n /**\n * Fetch all non-deleted tasks for an entity, ordered by priority DESC, created_at ASC.\n * Used by _getFullBundle().\n */\n async findAllByEntityId(entityId: string, tx?: SQLiteAdapter): Promise<WikiTask[]> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NULL ORDER BY priority DESC, created_at ASC`,\n [entityId],\n );\n return rows.map(mapRowToTask);\n }\n\n /**\n * Bulk delete pruned tasks (already soft-deleted) by cutoff date.\n * Used by runPrune(). Returns number of deleted rows.\n */\n async bulkDeletePruned(\n entityId: string,\n cutoff: number,\n tx: SQLiteAdapter,\n ): Promise<number> {\n const executor = this.getExecutor(tx);\n const rowsToDelete = await executor.getAllAsync<{ id: string; deleted_at: number }>(\n `SELECT id, deleted_at FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ?`,\n [entityId, cutoff],\n );\n if (rowsToDelete.length === 0) return 0;\n\n const result = await executor.runAsync(\n `DELETE FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ?`,\n [entityId, cutoff],\n );\n\n for (const row of rowsToDelete) {\n await this.outbox.push(\n {\n entityId,\n tableName: 'tasks',\n recordId: row.id,\n operation: 'DELETE',\n payload: { id: row.id, entity_id: entityId, deleted_at: row.deleted_at },\n },\n tx,\n );\n }\n\n return result.changes;\n }\n\n /**\n * Soft-delete a task by ID within a transaction.\n * Stages a DELETE outbox entry in the same transaction.\n * `tx` is REQUIRED.\n */\n async softDeleteById(\n id: string,\n entityId: string,\n tx: SQLiteAdapter,\n ): Promise<{ changes: number }> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n const result = await executor.runAsync(\n `UPDATE ${this.prefix}tasks SET deleted_at = ?, updated_at = ? WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,\n [now, now, id, entityId],\n );\n if (result.changes > 0) {\n await this.outbox.push(\n {\n entityId,\n tableName: 'tasks',\n recordId: id,\n operation: 'DELETE',\n payload: { id, entity_id: entityId, deleted_at: now },\n },\n tx,\n );\n }\n return result;\n }\n\n /**\n * Bulk soft-delete all tasks for an entity.\n * Stages DELETE outbox entries for each row in the same transaction.\n * `tx` is REQUIRED.\n */\n async bulkSoftDeleteByEntityId(entityId: string, tx: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n // Get IDs before updating for outbox staging\n const idsToDelete = await executor.getAllAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NULL`,\n [entityId],\n );\n const result = await executor.runAsync(\n `UPDATE ${this.prefix}tasks SET deleted_at = ?, updated_at = ? WHERE entity_id = ? AND deleted_at IS NULL`,\n [now, now, entityId],\n );\n // Stage outbox entries for each deleted record\n for (const row of idsToDelete) {\n await this.outbox.push({\n entityId,\n tableName: 'tasks',\n recordId: row.id,\n operation: 'DELETE',\n payload: { id: row.id, entity_id: entityId, deleted_at: now },\n }, tx);\n }\n return result.changes;\n }\n\n /**\n * Count live tasks for an entity. Used by forget({ dryRun, clearAll: true }).\n */\n async countLiveByEntityId(entityId: string, tx?: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ cnt: number }>(\n `SELECT COUNT(*) AS cnt FROM ${this.prefix}tasks\n WHERE entity_id = ? AND deleted_at IS NULL`,\n [entityId],\n );\n return row?.cnt ?? 0;\n }\n}\n","import { BaseRepository } from './BaseRepository';\nimport type { WikiEvent, SQLiteAdapter } from '../types';\n\nexport class EventRepository extends BaseRepository {\n /**\n * Insert a new event row.\n * Pass `tx` to participate in a caller-owned transaction; omit to run against the default db.\n */\n async add(event: WikiEvent, tx?: SQLiteAdapter): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `INSERT INTO ${this.prefix}events (id, entity_id, event_type, summary, related_entry_id, created_at)\n VALUES (?, ?, ?, ?, ?, ?)`,\n [\n event.id,\n event.entity_id,\n event.event_type,\n event.summary,\n event.related_entry_id ?? null,\n event.created_at,\n ],\n );\n }\n\n async addIgnoreDuplicate(event: WikiEvent, tx?: SQLiteAdapter): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `INSERT OR IGNORE INTO ${this.prefix}events (id, entity_id, event_type, summary, related_entry_id, created_at)\n VALUES (?, ?, ?, ?, ?, ?)`,\n [\n event.id,\n event.entity_id,\n event.event_type,\n event.summary,\n event.related_entry_id ?? null,\n event.created_at,\n ],\n );\n }\n\n /**\n * Return the most recent events for an entity, newest first.\n * Defaults to a limit of 50.\n */\n async getRecent(entityId: string, limit = 50): Promise<WikiEvent[]> {\n return this.db.getAllAsync<WikiEvent>(\n `SELECT * FROM ${this.prefix}events WHERE entity_id = ? ORDER BY created_at DESC LIMIT ?`,\n [entityId, limit],\n );\n }\n\n /**\n * Return the most recent events for the given entity IDs, newest first.\n * Defaults to a limit of 50.\n */\n async getRecentForEntities(entityIds: string[], limit = 50): Promise<WikiEvent[]> {\n if (entityIds.length === 0) return [];\n const placeholders = entityIds.map(() => '?').join(', ');\n return this.db.getAllAsync<WikiEvent>(\n `SELECT * FROM ${this.prefix}events WHERE entity_id IN (${placeholders}) ORDER BY created_at DESC LIMIT ?`,\n [...entityIds, limit],\n );\n }\n\n /**\n * Delete events for an entity that were created at or before the given cutoff timestamp.\n * Returns the number of deleted rows.\n */\n async prune(entityId: string, cutoff: number): Promise<{ changes: number }> {\n return this.db.runAsync(\n `DELETE FROM ${this.prefix}events WHERE entity_id = ? AND created_at <= ?`,\n [entityId, cutoff],\n );\n }\n\n /**\n * Return the total number of events stored for an entity.\n * `tx` is optional — pass an active transaction handle for atomic reads.\n */\n async count(entityId: string, tx?: SQLiteAdapter): Promise<number> {\n const executor = tx ?? this.db;\n const row = await executor.getFirstAsync<{ count: number }>(\n `SELECT COUNT(*) as count FROM ${this.prefix}events WHERE entity_id = ?`,\n [entityId],\n );\n return row?.count ?? 0;\n }\n\n /**\n * Return all events for an entity in chronological (ASC) order.\n * When limit is provided, fetches newest-first then reverses to preserve chronological order.\n */\n async getByEntityId(entityId: string, limit?: number): Promise<WikiEvent[]> {\n if (limit != null) {\n const rows = await this.db.getAllAsync<WikiEvent>(\n `SELECT * FROM ${this.prefix}events WHERE entity_id = ? ORDER BY created_at DESC LIMIT ?`,\n [entityId, limit],\n );\n return rows.slice().reverse();\n }\n return this.db.getAllAsync<WikiEvent>(\n `SELECT * FROM ${this.prefix}events WHERE entity_id = ? ORDER BY created_at ASC`,\n [entityId],\n );\n }\n}\n","import { BaseRepository } from './BaseRepository';\nimport type { WikiEdge, SQLiteAdapter } from '../types';\n\nexport interface NeighborhoodQueryOptions {\n maxDepth: number; // already clamped to [1,3] by the caller (GraphTraversalService)\n direction: 'inbound' | 'outbound' | 'both';\n edgeTypes?: string[]; // undefined = no filter; [] = match nothing (short-circuits)\n minConfidence: 'certain' | 'inferred' | 'tentative';\n excludeSourceTypes: string[];\n maxNodes: number;\n /**\n * When true, draft facts are dead-ends for *discovered* nodes — the recursive\n * walk will not step onto a draft, and will not step *past* one either, since\n * a draft's neighbours are unreachable through it. The anchor node is exempt\n * (it is validated up-front and never gated by this flag), so callers can\n * intentionally start from a draft. Default false (drafts visible).\n */\n excludeDrafts?: boolean;\n}\n\nconst CONFIDENCE_RANK: Record<'tentative' | 'inferred' | 'certain', number> = {\n tentative: 0,\n inferred: 1,\n certain: 2,\n};\n\nexport class EdgeRepository extends BaseRepository {\n /**\n * Insert an edge, silently skipping on primary-key or uniqueness conflicts.\n * Returns true when a row was inserted, false when skipped as a duplicate.\n * Throws when the insert was skipped due to an id collision with a different edge tuple.\n */\n async addIgnoreDuplicate(edge: WikiEdge, tx?: SQLiteAdapter): Promise<boolean> {\n const executor = this.getExecutor(tx);\n const result = await executor.runAsync(\n `INSERT OR IGNORE INTO ${this.prefix}edges (id, entity_id, source_id, target_id, edge_type, created_at)\n VALUES (?, ?, ?, ?, ?, ?)`,\n [edge.id, edge.entity_id, edge.source_id, edge.target_id, edge.edge_type, edge.created_at],\n );\n\n if (result.changes > 0) return true;\n\n const existing = await executor.getFirstAsync<{\n entity_id: string;\n source_id: string;\n target_id: string;\n edge_type: string;\n }>(\n `SELECT entity_id, source_id, target_id, edge_type FROM ${this.prefix}edges WHERE id = ?`,\n [edge.id],\n );\n\n if (!existing) return false;\n\n if (\n String(existing.entity_id) !== edge.entity_id ||\n String(existing.source_id) !== edge.source_id ||\n String(existing.target_id) !== edge.target_id ||\n String(existing.edge_type) !== edge.edge_type\n ) {\n throw new Error(\n `Edge id collision: ${JSON.stringify(edge.id)} already exists with a different (entity_id, source_id, target_id, edge_type) tuple`,\n );\n }\n\n return false;\n }\n\n async getByEntityId(entityId: string, tx?: SQLiteAdapter): Promise<WikiEdge[]> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}edges WHERE entity_id = ? ORDER BY created_at ASC`,\n [entityId],\n );\n return rows.map(mapRowToEdge);\n }\n\n /** Hard delete — edges have no soft-delete concept, only presence/absence. `tx` is REQUIRED. */\n async bulkDeleteByEntityId(entityId: string, tx: SQLiteAdapter): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(`DELETE FROM ${this.prefix}edges WHERE entity_id = ?`, [entityId]);\n }\n\n /**\n * Hard-delete every edge whose `source_id` is in `sourceFactIds`, scoped to\n * `entityId`. Returns the number of rows deleted. Edges have no soft-delete\n * concept; this method is named `softDeleteBySourceFactIds` for symmetry with\n * `EntryRepository.softDeleteBySource` (which IS a soft delete), but its\n * semantics are immediate presence/absence removal. Use ONLY inside an open\n * transaction — the method requires `tx` and performs no autocommit.\n *\n * Used by `IngestionService.upsertGraphCore` to retire the prior parse's\n * edges whose source facts are being superseded by `softDeleteBySource`.\n */\n async softDeleteBySourceFactIds(\n entityId: string,\n sourceFactIds: readonly string[],\n tx: SQLiteAdapter,\n ): Promise<number> {\n if (sourceFactIds.length === 0) return 0;\n const executor = this.getExecutor(tx);\n // SQLite's SQLITE_MAX_VARIABLE_NUMBER defaults to 32,766; binding\n // `entityId` plus every ID in one statement would overflow once a\n // single sourceRef accumulates tens of thousands of facts. Chunk to\n // stay well under the limit, reusing the supplied tx executor.\n const chunkSize = 500;\n let totalChanges = 0;\n for (let i = 0; i < sourceFactIds.length; i += chunkSize) {\n const chunk = sourceFactIds.slice(i, i + chunkSize);\n const placeholders = chunk.map(() => '?').join(',');\n const result = await executor.runAsync(\n `DELETE FROM ${this.prefix}edges\n WHERE entity_id = ? AND source_id IN (${placeholders})`,\n [entityId, ...chunk],\n );\n totalChanges += result.changes;\n }\n return totalChanges;\n }\n\n /**\n * Multi-hop traversal from `sourceId` via SQLite `WITH RECURSIVE`. All filtering,\n * dead-ending, cycle-guarding, capping, and ordering happens in this one query.\n * The anchor is validated (exists, right entity, not soft-deleted) but never gated\n * by confidence/source_type — only nodes discovered beyond it are.\n */\n async getNeighborhood(\n entityId: string,\n sourceId: string,\n opts: NeighborhoodQueryOptions,\n tx?: SQLiteAdapter,\n ): Promise<{ nodeIds: string[]; edges: WikiEdge[] }> {\n const executor = this.getExecutor(tx);\n\n if (opts.edgeTypes && opts.edgeTypes.length === 0) {\n const anchor = await executor.getFirstAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}entries WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,\n [sourceId, entityId],\n );\n return { nodeIds: anchor ? [anchor.id] : [], edges: [] };\n }\n\n const edgeTypesClause = opts.edgeTypes\n ? `e.edge_type IN (${opts.edgeTypes.map(() => '?').join(',')})`\n : '1=1';\n const excludeSourceTypesPlaceholders = opts.excludeSourceTypes.map(() => '?').join(',');\n const minConfidenceRank = CONFIDENCE_RANK[opts.minConfidence];\n\n const sql = `\n WITH RECURSIVE walk(node_id, depth, visited) AS (\n SELECT id, 0, ',' || id || ','\n FROM ${this.prefix}entries\n WHERE id = ? AND entity_id = ? AND deleted_at IS NULL\n\n UNION\n\n SELECT\n CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END,\n w.depth + 1,\n w.visited || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ','\n FROM walk w\n JOIN ${this.prefix}edges e\n ON e.entity_id = ?\n AND (\n (? != 'inbound' AND e.source_id = w.node_id) OR\n (? != 'outbound' AND e.target_id = w.node_id)\n )\n AND (${edgeTypesClause})\n JOIN ${this.prefix}entries n\n ON n.id = (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END)\n AND n.entity_id = ?\n AND n.deleted_at IS NULL\n AND (\n CASE n.confidence\n WHEN 'tentative' THEN 0\n WHEN 'inferred' THEN 1\n WHEN 'certain' THEN 2\n ELSE -1\n END\n ) >= ?\n AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})\n AND (? = 0 OR n.lifecycle_status != 'draft')\n WHERE w.depth < ?\n AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0\n )\n SELECT node_id, MIN(depth) AS depth\n FROM walk\n GROUP BY node_id\n ORDER BY depth ASC, (SELECT updated_at FROM ${this.prefix}entries WHERE id = node_id) DESC\n LIMIT ?\n `;\n\n const params: unknown[] = [\n sourceId, entityId,\n entityId,\n opts.direction, opts.direction,\n ...(opts.edgeTypes ?? []),\n entityId,\n minConfidenceRank,\n ...opts.excludeSourceTypes,\n opts.excludeDrafts === true ? 1 : 0,\n opts.maxDepth,\n opts.maxNodes,\n ];\n\n const rows = await executor.getAllAsync<{ node_id: string; depth: number }>(sql, params);\n const nodeIds = rows.map((r) => r.node_id);\n if (nodeIds.length === 0) return { nodeIds: [], edges: [] };\n\n const valueRows = nodeIds.map(() => '(?)').join(', ');\n const edgeRows = await executor.getAllAsync<any>(\n `WITH neighborhood(node_id) AS (VALUES ${valueRows})\n SELECT e.* FROM ${this.prefix}edges e\n JOIN neighborhood ns ON e.source_id = ns.node_id\n JOIN neighborhood nt ON e.target_id = nt.node_id\n WHERE e.entity_id = ?`,\n [...nodeIds, entityId],\n );\n\n return { nodeIds, edges: edgeRows.map(mapRowToEdge) };\n }\n}\n\nfunction mapRowToEdge(row: any): WikiEdge {\n return {\n id: String(row.id),\n entity_id: String(row.entity_id),\n source_id: String(row.source_id),\n target_id: String(row.target_id),\n edge_type: String(row.edge_type),\n created_at: Number(row.created_at),\n };\n}\n","import type { OntologyMode } from '../types';\n\nconst FACT_ONTOLOGY_FIELDS = `\nEach fact may optionally include:\n- \"okf_type\": string — must be one of the node_types in the manifest\n- \"edges\": [{ \"edge_type\": string, \"target_title\": string }] — target_title must match another fact's title in this response or existing memory\n- An edge_type may appear in the manifest multiple times with different source_type/target_type; use the row whose types match your fact and target.`;\n\nconst EMERGENT_EXTRA = `\nYou may also return \"ontology_updates\" to propose new types:\n\"ontology_updates\": {\n \"node_types\": [{ \"type\": \"slug\", \"description\": \"...\", \"parent_type\": \"optional existing slug\" }],\n \"edge_types\": [{ \"type\": \"slug\", \"source_type\": \"...\", \"target_type\": \"...\", \"description\": \"...\" }]\n}\nOnly propose types not already in the manifest. Do not redefine existing types.`;\n\nexport function buildOntologyPromptAppendix(\n mode: OntologyMode,\n manifestJson: string,\n): { ontologyManifest: string; ontologyModeInstructions: string } {\n const strictRules = mode === 'strict'\n ? 'STRICT MODE: Use ONLY types defined in the manifest. If a fact does not fit any node_type, omit okf_type and edges entirely.'\n : 'EMERGENT MODE: Prefer manifest types. You may propose new types via ontology_updates when necessary.';\n\n const fallback = 'If okf_type or an edge is invalid, omit them rather than inventing unlisted types.';\n\n const ontologyModeInstructions = [\n '## Ontology constraints',\n strictRules,\n fallback,\n FACT_ONTOLOGY_FIELDS,\n mode === 'emergent' ? EMERGENT_EXTRA : '',\n 'Manifest:',\n manifestJson,\n ].filter(Boolean).join('\\n');\n\n return { ontologyManifest: manifestJson, ontologyModeInstructions };\n}\n","import type {\n OntologyConfig,\n OntologyManifest,\n OntologyMode,\n OntologyPromptContext,\n OntologyUpdates,\n ExtractedFactWithOntology,\n ExtractedFactEdge,\n SQLiteAdapter,\n WikiEdge,\n} from '../types';\nimport { WikiStrictOntologyViolation } from '../types';\nimport type { MetadataRepository } from '../repositories/MetadataRepository';\nimport type { EdgeRepository } from '../repositories/EdgeRepository';\nimport { buildOntologyPromptAppendix } from '../prompts/ontology';\nimport {\n emptyManifest,\n normalizeTitleKey,\n resolveNodeType,\n resolveEdgeDefinitions,\n typeSatisfies,\n validateInlineEdges,\n validateManifest,\n type EdgeDrop,\n} from '../utils/ontology';\nimport { generateId } from '../utils/ids';\n\nexport type TitleIndexEntry = { id: string; okf_type: string | null };\n\n/**\n * Coordinates ontology mode resolution, manifest caching, LLM output validation, and edge persistence.\n * Cache is per WikiMemory instance (single-process); not shared across instances.\n */\nexport class OntologyService {\n private cache = new Map<string, { mode: OntologyMode; manifest: OntologyManifest }>();\n\n constructor(\n private metadataRepo: MetadataRepository,\n private edgeRepo: EdgeRepository,\n private ontologyConfig?: OntologyConfig,\n ) {}\n\n resolveMode(storedMode?: OntologyMode): OntologyMode {\n return storedMode ?? this.ontologyConfig?.mode ?? 'off';\n }\n\n invalidateCache(entityId: string): void {\n this.cache.delete(entityId);\n }\n\n async getEffectiveState(entityId: string, tx?: SQLiteAdapter): Promise<{\n mode: OntologyMode;\n manifest: OntologyManifest;\n }> {\n if (!tx) {\n const cached = this.cache.get(entityId);\n if (cached) return cached;\n }\n\n const row = await this.metadataRepo.getManifest(entityId, tx);\n if (row) {\n const state = { mode: this.resolveMode(row.mode), manifest: row.manifest };\n if (!tx) this.cache.set(entityId, state);\n return state;\n }\n\n const seed = this.ontologyConfig?.seedManifests?.[entityId];\n if (seed) {\n // D11: the tx branch validates via setManifest; the cache branch did not.\n validateManifest(seed.manifest);\n const state = {\n mode: this.resolveMode(seed.mode),\n manifest: seed.manifest,\n };\n if (tx) {\n await this.metadataRepo.setManifest(entityId, state, tx);\n } else {\n this.cache.set(entityId, state);\n }\n return state;\n }\n\n return { mode: 'off', manifest: emptyManifest() };\n }\n\n async buildPromptContext(entityId: string): Promise<OntologyPromptContext | null> {\n const { mode, manifest } = await this.getEffectiveState(entityId);\n if (mode === 'off') return null;\n const manifestJson = JSON.stringify(manifest, null, 2);\n return buildOntologyPromptAppendix(mode, manifestJson);\n }\n\n async mergeEmergentUpdates(\n entityId: string,\n updates: OntologyUpdates,\n tx: SQLiteAdapter,\n ): Promise<OntologyManifest> {\n const merged = await this.metadataRepo.mergeManifestUpdates(entityId, updates, tx);\n this.invalidateCache(entityId);\n return merged;\n }\n\n validateAndNormalizeFact(\n fact: ExtractedFactWithOntology,\n manifest: OntologyManifest,\n opts?: { strict?: boolean; entityId?: string; drops?: EdgeDrop[] },\n ): { okf_type: string | null; edges: ExtractedFactEdge[] } {\n const rawType = typeof fact.okf_type === 'string' ? fact.okf_type : '';\n const strict = opts?.strict === true;\n const canonical = resolveNodeType(rawType, manifest);\n if (!canonical) {\n if (strict) throw new WikiStrictOntologyViolation(opts?.entityId ?? '', 'node', rawType);\n if (opts?.drops && Array.isArray(fact.edges)) {\n for (const edge of fact.edges) {\n opts.drops.push({\n reason: 'no_source_type',\n sourceId: null,\n edgeType: typeof edge?.edge_type === 'string' ? edge.edge_type : null,\n sourceNodeType: null,\n targetNodeType: null,\n });\n }\n }\n return { okf_type: null, edges: [] };\n }\n const edges = validateInlineEdges(canonical, null, fact.edges ?? [], manifest, opts);\n return { okf_type: canonical, edges };\n }\n\n /**\n * Pure resolver: given a source type, LLM-supplied edges, the manifest,\n * and a title index, return a list of concrete `WikiEdge` objects ready\n * for persistence. Performs no DB writes. Used by callers that batch edge\n * writes inside their own transaction (e.g. `IngestionService.ingestDocument`\n * when delegating to `upsertGraphCore`).\n */\n resolveEdges(\n entityId: string,\n sourceId: string,\n sourceType: string | null,\n edges: ExtractedFactEdge[],\n manifest: OntologyManifest,\n titleIndex: Map<string, TitleIndexEntry>,\n now: number,\n drops?: EdgeDrop[],\n ): WikiEdge[] {\n if (edges.length === 0) return [];\n if (!sourceType) {\n for (const edge of edges) {\n drops?.push({ reason: 'no_source_type', sourceId, edgeType: edge.edge_type, sourceNodeType: null, targetNodeType: null });\n }\n return [];\n }\n const out: WikiEdge[] = [];\n for (const edge of edges) {\n const candidates = resolveEdgeDefinitions(edge.edge_type, manifest)\n .filter(d => typeSatisfies(d.source_type, sourceType, manifest));\n if (candidates.length === 0) {\n drops?.push({ reason: 'type_not_in_manifest', sourceId, edgeType: edge.edge_type, sourceNodeType: sourceType, targetNodeType: null });\n continue;\n }\n\n const targetKey = normalizeTitleKey(edge.target_title);\n const target = titleIndex.get(targetKey);\n if (!target) {\n drops?.push({ reason: 'target_not_found', sourceId, edgeType: edge.edge_type, sourceNodeType: sourceType, targetNodeType: null });\n continue;\n }\n\n const targetType = (target.okf_type ?? '').trim().toLowerCase();\n const def = candidates.find(d => d.target_type.trim().toLowerCase() === targetType)\n ?? candidates.find(d => typeSatisfies(d.target_type, targetType, manifest));\n if (!def) {\n drops?.push({\n reason: 'target_type_mismatch', sourceId, edgeType: edge.edge_type,\n sourceNodeType: sourceType, targetNodeType: target.okf_type ?? null,\n });\n continue;\n }\n\n out.push({\n id: generateId(),\n entity_id: entityId,\n source_id: sourceId,\n target_id: target.id,\n edge_type: def.type,\n created_at: now,\n });\n }\n return out;\n }\n\n /**\n * Backwards-compatible wrapper: resolves edges via {@link resolveEdges},\n * then persists each via `edgeRepo.addIgnoreDuplicate` in the supplied\n * transaction. Returns the number of edges persisted. Used by paths that\n * want self-contained edge persistence (e.g. MaintenanceService heal /\n * backfill callers that do not have a separate edge-write step).\n */\n async resolveAndPersistEdges(\n entityId: string,\n sourceId: string,\n sourceType: string | null,\n edges: ExtractedFactEdge[],\n manifest: OntologyManifest,\n titleIndex: Map<string, TitleIndexEntry>,\n tx: SQLiteAdapter,\n now: number,\n drops?: EdgeDrop[],\n ): Promise<number> {\n const resolved = this.resolveEdges(entityId, sourceId, sourceType, edges, manifest, titleIndex, now, drops);\n let persisted = 0;\n for (const edge of resolved) {\n const inserted = await this.edgeRepo.addIgnoreDuplicate(edge, tx);\n if (inserted) persisted++;\n }\n return persisted;\n }\n}\n","import type { EdgeRepository, NeighborhoodQueryOptions } from '../repositories/EdgeRepository';\nimport type { EntryRepository } from '../repositories/EntryRepository';\nimport type { GraphTraversalOptions, GraphNeighborhood, WikiConfig } from '../types';\n\n/**\n * Pure orchestrator — no SQL. Merges WikiConfig defaults with per-call options,\n * delegates the recursive walk to EdgeRepository, then hydrates node IDs into facts.\n */\nexport class GraphTraversalService {\n constructor(\n private edgeRepo: EdgeRepository,\n private entryRepo: EntryRepository,\n private config: WikiConfig,\n ) {}\n\n async traverseGraph(entityId: string, options: GraphTraversalOptions): Promise<GraphNeighborhood> {\n const fallbackMaxNodes = 20;\n const rawConfigDefault = this.config.maxTraversalNodes ?? fallbackMaxNodes;\n const defaultMaxNodes =\n Number.isFinite(rawConfigDefault) && rawConfigDefault >= 1\n ? Math.floor(rawConfigDefault)\n : fallbackMaxNodes;\n const rawMaxNodes = options.maxTraversalNodes ?? defaultMaxNodes;\n const maxNodes =\n Number.isFinite(rawMaxNodes) && rawMaxNodes >= 1 ? Math.floor(rawMaxNodes) : defaultMaxNodes;\n\n const opts: NeighborhoodQueryOptions = {\n maxDepth: Math.max(1, Math.min(options.maxDepth ?? 1, 3)),\n direction: options.direction ?? this.config.traversalDirection ?? 'both',\n edgeTypes: options.edgeTypes,\n minConfidence: options.minTraversalConfidence ?? this.config.minTraversalConfidence ?? 'tentative',\n excludeSourceTypes: options.excludeSourceTypes ?? this.config.excludeSourceTypes ?? [],\n excludeDrafts: options.excludeDrafts ?? this.config.excludeDrafts ?? false,\n maxNodes,\n };\n\n const { nodeIds, edges } = await this.edgeRepo.getNeighborhood(entityId, options.sourceId, opts);\n if (nodeIds.length === 0) return { nodes: [], edges: [] };\n\n // findByIds() returns facts in input-ID order (Map-based lookup,\n // see packages/core/src/repositories/EntryRepository.ts:104-108) — no re-sort needed.\n const nodes = await this.entryRepo.findByIds(nodeIds, [entityId]);\n const hydratedIds = new Set(nodes.map((node) => node.id));\n const filteredEdges = edges.filter(\n (edge) => hydratedIds.has(edge.source_id) && hydratedIds.has(edge.target_id),\n );\n return { nodes, edges: filteredEdges };\n }\n}\n","import { BaseRepository } from './BaseRepository';\n\n/** Read-only queries for `lint` (spec §8.1). Every statement is entity-scoped. */\nexport class LintRepository extends BaseRepository {\n async countFactHealth(entityId: string): Promise<{ untypedFacts: number; drafts: number; unverifiedInferred: number }> {\n const row = await this.db.getFirstAsync<{ untyped: number | null; drafts: number | null; unverified: number | null }>(\n `SELECT\n SUM(CASE WHEN okf_type IS NULL THEN 1 ELSE 0 END) AS untyped,\n SUM(CASE WHEN lifecycle_status = 'draft' THEN 1 ELSE 0 END) AS drafts,\n SUM(CASE WHEN source_type = 'librarian_inferred'\n AND COALESCE(json_array_length(CASE WHEN json_valid(okf_verified) THEN okf_verified END), 0) = 0\n THEN 1 ELSE 0 END) AS unverified\n FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL`,\n [entityId],\n );\n return {\n untypedFacts: Number(row?.untyped ?? 0),\n drafts: Number(row?.drafts ?? 0),\n unverifiedInferred: Number(row?.unverified ?? 0),\n };\n }\n\n private danglingWhere(): string {\n const live = (col: string) =>\n `EXISTS (SELECT 1 FROM ${this.prefix}entries n WHERE n.id = e.${col} AND n.entity_id = e.entity_id AND n.deleted_at IS NULL)`;\n return `e.entity_id = ? AND (NOT ${live('source_id')} OR NOT ${live('target_id')})`;\n }\n\n async countDanglingEdges(entityId: string): Promise<number> {\n const row = await this.db.getFirstAsync<{ n: number }>(\n `SELECT COUNT(*) AS n FROM ${this.prefix}edges e WHERE ${this.danglingWhere()}`,\n [entityId],\n );\n return Number(row?.n ?? 0);\n }\n\n async sampleDanglingEdgeIds(entityId: string, limit: number): Promise<string[]> {\n const rows = await this.db.getAllAsync<{ id: string }>(\n `SELECT e.id FROM ${this.prefix}edges e WHERE ${this.danglingWhere()} ORDER BY e.id ASC LIMIT ?`,\n [entityId, limit],\n );\n return rows.map((r) => r.id);\n }\n\n /** Keyset page of edges whose endpoints are both live in this entity, with endpoint types. */\n async pageLiveEdges(\n entityId: string,\n afterId: string,\n limit: number,\n ): Promise<Array<{ id: string; edge_type: string; source_type: string | null; target_type: string | null }>> {\n return this.db.getAllAsync(\n `SELECT e.id, e.edge_type, s.okf_type AS source_type, t.okf_type AS target_type\n FROM ${this.prefix}edges e\n JOIN ${this.prefix}entries s ON s.id = e.source_id AND s.entity_id = e.entity_id AND s.deleted_at IS NULL\n JOIN ${this.prefix}entries t ON t.id = e.target_id AND t.entity_id = e.entity_id AND t.deleted_at IS NULL\n WHERE e.entity_id = ? AND e.id > ?\n ORDER BY e.id ASC\n LIMIT ?`,\n [entityId, afterId, limit],\n );\n }\n}\n","import type { WikiLintReport } from '../types';\nimport type { LintRepository } from '../repositories/LintRepository';\nimport type { OntologyService } from './OntologyService';\nimport { edgeTripleAllowed } from '../utils/ontology';\n\nconst LINT_SAMPLE_SIZE = 20;\nconst LINT_PAGE_SIZE = 500;\n\nexport class LintService {\n constructor(private lintRepo: LintRepository, private ontologyService: OntologyService) {}\n\n /**\n * Read-only (spec §8.1). Manifest violations stream the entity's live-endpoint\n * edges in keyset pages and check each triple in JS against the effective\n * manifest. `getEffectiveState` is called without a transaction, so a seed\n * manifest is cached, never persisted. Counts come from separate statements,\n * not one snapshot.\n */\n async lint(entityId: string): Promise<WikiLintReport> {\n const health = await this.lintRepo.countFactHealth(entityId);\n const danglingEdges = await this.lintRepo.countDanglingEdges(entityId);\n const danglingEdgeIds = danglingEdges > 0 ? await this.lintRepo.sampleDanglingEdgeIds(entityId, LINT_SAMPLE_SIZE) : [];\n\n const { mode, manifest } = await this.ontologyService.getEffectiveState(entityId);\n const constrained = mode !== 'off'\n && ((manifest.node_types?.length ?? 0) > 0 || (manifest.edge_types?.length ?? 0) > 0);\n let manifestViolations = 0;\n const manifestViolationEdgeIds: string[] = [];\n if (constrained) {\n let after = '';\n for (;;) {\n const page = await this.lintRepo.pageLiveEdges(entityId, after, LINT_PAGE_SIZE);\n for (const e of page) {\n if (!edgeTripleAllowed(manifest, e.edge_type, e.source_type ?? '', e.target_type ?? '')) {\n manifestViolations++;\n if (manifestViolationEdgeIds.length < LINT_SAMPLE_SIZE) manifestViolationEdgeIds.push(e.id);\n }\n }\n if (page.length < LINT_PAGE_SIZE) break;\n after = page[page.length - 1].id;\n }\n }\n\n return {\n danglingEdges,\n manifestViolations,\n ...health,\n sample: { danglingEdgeIds, manifestViolationEdgeIds },\n };\n }\n}\n","import type { SQLiteAdapter } from '../types';\nimport {\n formatSourcesJson,\n formatVerifiedJson,\n latestVerified,\n} from '@equationalapplications/core-okf';\n\nexport type OkfSource = {\n id?: string;\n resource: string;\n title?: string;\n author?: string;\n usage_count?: number;\n last_modified?: string;\n usage_window?: { from: string; to: string };\n};\nexport type OkfVerifiedEntry = { by: string; at: string };\n\n/**\n * DAO discipline (spec §8): only knowledge-content writes may bump `updated_at`.\n * Trust / provenance / lifecycle / freshness writes MUST NOT touch it. Every\n * `UPDATE` in this class is a non-content metadata write. Tests in\n * `__tests__/daoDiscipline.test.ts` and `__tests__/okfTrustWrites.test.ts`\n * snapshot the SQL via a logging adapter and assert the SET clause omits\n * `updated_at`.\n *\n * Deliberately does NOT push an outbox event, unlike `EntryRepository.upsert`\n * / `TaskRepository.upsert` (spec §8 \"Outbox/transaction scope\" note): outbox\n * delivery exists for *content* sync, and these writes are metadata, not\n * content, by the same reasoning that exempts them from `updated_at`. A\n * downstream sync consumer will not learn about a new verifier until the\n * next full re-export/re-import — accepted for v0.2.\n */\nexport class OkfTrustWritesRepository {\n constructor(private db: SQLiteAdapter, private prefix: string) {}\n\n private getExecutor(tx?: SQLiteAdapter): SQLiteAdapter {\n return tx ?? this.db;\n }\n\n /**\n * Append one or more verification events to a fact's `okf_verified` JSON\n * array, atomically, in a single SQL statement.\n *\n * The implementation uses json_each over the existing array UNION ALL'd\n * with json_each over the new events wrapped in json_group_array — a single\n * UPDATE expression. SQLite serializes this against concurrent writers on\n * the same row, so two callers appending simultaneously cannot lose each\n * other's events (the previous implementation serialized only the supplied\n * array and overwrote, dropping any pre-existing history).\n *\n * Sets the `last_verified_*` convenience columns from the latest event in\n * the union (computed in code; see {@link latestVerified}).\n */\n async writeOkfTrust(\n entryId: string,\n entityId: string,\n verified: OkfVerifiedEntry[],\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n if (verified.length === 0) return;\n const latest = latestVerified(verified, Date.now());\n const newEventsJson = JSON.stringify(verified);\n await executor.runAsync(\n `UPDATE ${this.prefix}entries\n SET okf_verified = COALESCE(\n (SELECT json_group_array(json_object('by', s.by_val, 'at', s.at_val))\n FROM (\n SELECT json_extract(value, '$.by') AS by_val,\n json_extract(value, '$.at') AS at_val\n FROM json_each(okf_verified)\n UNION ALL\n SELECT json_extract(value, '$.by'),\n json_extract(value, '$.at')\n FROM json_each(?)\n ) AS s\n ORDER BY s.at_val),\n '[]'\n ),\n last_verified_by = ?,\n last_verified_at = ?\n WHERE id = ? AND entity_id = ?`,\n [newEventsJson, latest?.by ?? null, latest?.at ?? null, entryId, entityId],\n );\n }\n\n /** Replace the `sources` list (provenance). */\n async writeOkfSources(\n entryId: string,\n entityId: string,\n sources: OkfSource[],\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n const json = formatSourcesJson(sources);\n await executor.runAsync(\n `UPDATE ${this.prefix}entries\n SET okf_sources = ?\n WHERE id = ? AND entity_id = ?`,\n [json, entryId, entityId],\n );\n }\n\n /** Set the OKF v0.2 lifecycle status. */\n async setLifecycleStatus(\n entryId: string,\n entityId: string,\n status: 'draft' | 'stable' | 'deprecated',\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `UPDATE ${this.prefix}entries\n SET lifecycle_status = ?\n WHERE id = ? AND entity_id = ?`,\n [status, entryId, entityId],\n );\n }\n\n /** Set the absolute cutoff (epoch ms) for staleness, or NULL to clear. */\n async setStaleAfter(\n entryId: string,\n entityId: string,\n date: number | null,\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `UPDATE ${this.prefix}entries\n SET stale_after = ?\n WHERE id = ? AND entity_id = ?`,\n [date, entryId, entityId],\n );\n }\n\n /** Set the producer / verifier actor string. Rare. */\n async setGeneratedBy(\n entryId: string,\n entityId: string,\n actor: string,\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `UPDATE ${this.prefix}entries\n SET generated_by = ?\n WHERE id = ? AND entity_id = ?`,\n [actor, entryId, entityId],\n );\n }\n\n // The same five methods exist for tasks, with `tasks` instead of `entries`.\n // Tasks are symmetric per spec §2.5.\n\n /** Atomic append, task variant — mirrors {@link writeOkfTrust}. */\n async writeOkfTrustTask(\n taskId: string,\n entityId: string,\n verified: OkfVerifiedEntry[],\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n if (verified.length === 0) return;\n const latest = latestVerified(verified, Date.now());\n const newEventsJson = JSON.stringify(verified);\n await executor.runAsync(\n `UPDATE ${this.prefix}tasks\n SET okf_verified = COALESCE(\n (SELECT json_group_array(json_object('by', s.by_val, 'at', s.at_val))\n FROM (\n SELECT json_extract(value, '$.by') AS by_val,\n json_extract(value, '$.at') AS at_val\n FROM json_each(okf_verified)\n UNION ALL\n SELECT json_extract(value, '$.by'),\n json_extract(value, '$.at')\n FROM json_each(?)\n ) AS s\n ORDER BY s.at_val),\n '[]'\n ),\n last_verified_by = ?,\n last_verified_at = ?\n WHERE id = ? AND entity_id = ?`,\n [newEventsJson, latest?.by ?? null, latest?.at ?? null, taskId, entityId],\n );\n }\n\n async writeOkfSourcesTask(\n taskId: string,\n entityId: string,\n sources: OkfSource[],\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n const json = formatSourcesJson(sources);\n await executor.runAsync(\n `UPDATE ${this.prefix}tasks\n SET okf_sources = ?\n WHERE id = ? AND entity_id = ?`,\n [json, taskId, entityId],\n );\n }\n\n async setLifecycleStatusTask(\n taskId: string,\n entityId: string,\n status: 'draft' | 'stable' | 'deprecated',\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `UPDATE ${this.prefix}tasks\n SET lifecycle_status = ?\n WHERE id = ? AND entity_id = ?`,\n [status, taskId, entityId],\n );\n }\n\n async setStaleAfterTask(\n taskId: string,\n entityId: string,\n date: number | null,\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `UPDATE ${this.prefix}tasks\n SET stale_after = ?\n WHERE id = ? AND entity_id = ?`,\n [date, taskId, entityId],\n );\n }\n\n async setGeneratedByTask(\n taskId: string,\n entityId: string,\n actor: string,\n tx?: SQLiteAdapter,\n ): Promise<void> {\n const executor = this.getExecutor(tx);\n await executor.runAsync(\n `UPDATE ${this.prefix}tasks\n SET generated_by = ?\n WHERE id = ? AND entity_id = ?`,\n [actor, taskId, entityId],\n );\n }\n}\n","import type { SQLiteAdapter } from './types';\nimport type { WikiOutboxEvent } from './outbox/types';\nimport { setupDatabase } from './db/schema';\nimport { withSerializedTransactions } from './db/serializedAdapter';\nimport { MIGRATIONS, CURRENT_SCHEMA_VERSION } from './db/migrations';\nimport {\n WikiOptions,\n MemoryBundle,\n MemoryDump,\n WikiEvent,\n EntityStatus,\n ReadOptions,\n WikiSourceRefHashCollision,\n WikiDraftNotFound,\n} from './types';\nimport type { DraftPage } from './types';\nimport type { PendingSourceStatus, WikiLintReport, WikiInstructions } from './types';\nimport { EntryRepository } from './repositories/EntryRepository';\nimport { OutboxRepository } from './repositories/OutboxRepository';\nimport { SourceRefIndexRepository } from './repositories/SourceRefIndexRepository';\nimport { TaskRepository } from './repositories/TaskRepository';\nimport { EventRepository } from './repositories/EventRepository';\nimport { EdgeRepository } from './repositories/EdgeRepository';\nimport { MetadataRepository, entitySummaryMetaKey } from './repositories/MetadataRepository';\nimport { SearchService } from './services/SearchService';\nimport { JobManager } from './services/JobManager';\nimport { normalizeSourceRef, normalizeSourceHash, validateFact, validateTask, clip, chunkText } from './utils/pure';\nimport { resolveGrounding } from './utils/grounding';\nimport { IngestionService } from './services/IngestionService';\nimport { MaintenanceService } from './services/MaintenanceService';\nimport { ImportExportService } from './services/ImportExportService';\nimport { EmbeddingService } from './services/EmbeddingService';\nimport { RetrievalService } from './services/RetrievalService';\nimport { WriteService } from './services/WriteService';\nimport { PromptService } from './services/PromptService';\nimport { OntologyService } from './services/OntologyService';\nimport { GraphTraversalService } from './services/GraphTraversalService';\nimport { LintRepository } from './repositories/LintRepository';\nimport { LintService } from './services/LintService';\nimport { OkfTrustWritesRepository } from './db/okf-trust-writes';\nimport { validateManifest } from './utils/ontology';\nimport { DiagnosticBuffer } from './utils/diagnostics';\nimport type { OntologyManifest, OntologyMode, GraphTraversalOptions, GraphNeighborhood, OntologyBackfillResult, HealResult, IngestDocumentResult, ReembedResult } from './types';\n\nexport { WikiBusyError, WikiTransactionError, PrunePartialFailureError, HOOK_TIMEOUT_MARKER, WikiStrictOntologyViolation, WikiSourceRefHashCollision, WikiParseError, WikiIngestEmptyError, WikiGraphNodeOwnershipConflict } from './types';\n\nconst TABLE_PREFIX_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,30}_$/;\n\n/** Typed escape hatch for tests — not part of the supported consumer API. */\nexport interface WikiMemoryTestAccess {\n embeddingService: EmbeddingService;\n importExportService: ImportExportService;\n ingestionService: IngestionService;\n maintenanceService: MaintenanceService;\n retrievalService: RetrievalService;\n searchService: SearchService;\n writeService: WriteService;\n promptService: PromptService;\n graphTraversalService: GraphTraversalService;\n entryRepo: EntryRepository;\n sourceRefIndexRepo: SourceRefIndexRepository;\n metadataRepo: MetadataRepository;\n jobManager: JobManager;\n}\n\n/** `listDrafts` cursors are `${created_at}:${id}`; opaque to callers. */\nfunction decodeDraftCursor(cursor: unknown): { createdAt: number; id: string } {\n const sep = typeof cursor === 'string' ? cursor.indexOf(':') : -1;\n const createdAt = sep > 0 ? Number((cursor as string).slice(0, sep)) : Number.NaN;\n const id = sep > 0 ? (cursor as string).slice(sep + 1) : '';\n if (!Number.isSafeInteger(createdAt) || id.length === 0) {\n throw new TypeError('Invalid listDrafts cursor.');\n }\n return { createdAt, id };\n}\n\nexport class WikiMemory {\n /** Emits `__testAccess` console warning at most once per instance when NODE_ENV ≠ \"test\". */\n #testAccessNonTestEnvWarned = false;\n\n private db: SQLiteAdapter;\n private prefix: string;\n private options: WikiOptions;\n private entryRepo: EntryRepository;\n private outboxRepo: OutboxRepository;\n private sourceRefIndexRepo: SourceRefIndexRepository;\n private taskRepo: TaskRepository;\n private eventRepo: EventRepository;\n private edgeRepo: EdgeRepository;\n private metadataRepo: MetadataRepository;\n private embeddingService: EmbeddingService;\n private searchService: SearchService;\n private jobManager: JobManager;\n private ingestionService: IngestionService;\n private maintenanceService: MaintenanceService;\n private importExportService: ImportExportService;\n private retrievalService: RetrievalService;\n private writeService: WriteService;\n private promptService: PromptService;\n private ontologyService: OntologyService;\n private graphTraversalService: GraphTraversalService;\n private lintRepo: LintRepository;\n private lintService: LintService;\n private readonly okfTrustWrites: OkfTrustWritesRepository;\n\n constructor(db: SQLiteAdapter, options: WikiOptions) {\n // Serialize transactions on the single shared connection before the adapter\n // reaches any repository or service. See docs/superpowers/specs/2026-07-09-transaction-serialization-spec.md.\n this.db = withSerializedTransactions(db);\n this.options = options;\n this.prefix = options.config?.tablePrefix ?? 'llm_wiki_';\n if (!TABLE_PREFIX_PATTERN.test(this.prefix)) {\n throw new Error(\n `Invalid tablePrefix: ${JSON.stringify(this.prefix)}. ` +\n `Must match ${TABLE_PREFIX_PATTERN} (letter, then alphanumeric/underscore, ending in \"_\", max 32 chars total).`,\n );\n }\n this.outboxRepo = new OutboxRepository(this.db, this.prefix, !!options.config?.enableOutbox);\n this.entryRepo = new EntryRepository(this.db, this.prefix, this.outboxRepo);\n this.sourceRefIndexRepo = new SourceRefIndexRepository(this.db, this.prefix);\n this.taskRepo = new TaskRepository(this.db, this.prefix, this.outboxRepo);\n this.eventRepo = new EventRepository(this.db, this.prefix);\n this.edgeRepo = new EdgeRepository(this.db, this.prefix);\n this.metadataRepo = new MetadataRepository(this.db, this.prefix);\n this.lintRepo = new LintRepository(this.db, this.prefix);\n this.ontologyService = new OntologyService(\n this.metadataRepo,\n this.edgeRepo,\n options.config?.ontology,\n );\n this.lintService = new LintService(this.lintRepo, this.ontologyService);\n this.embeddingService = new EmbeddingService(this.db, this.options, this.entryRepo, this.metadataRepo);\n this.searchService = new SearchService(this.entryRepo);\n this.jobManager = new JobManager(this.prefix);\n this.promptService = new PromptService(options.config?.prompts, resolveGrounding(options.config?.grounding));\n this.ingestionService = new IngestionService(\n this.db,\n this.prefix,\n this.options,\n this.entryRepo,\n this.sourceRefIndexRepo,\n this.metadataRepo,\n this.edgeRepo,\n this.searchService,\n this.jobManager,\n this.embeddingService,\n this.promptService,\n this.ontologyService,\n );\n this.maintenanceService = new MaintenanceService(\n this.db,\n this.prefix,\n this.options,\n this.entryRepo,\n this.sourceRefIndexRepo,\n this.taskRepo,\n this.eventRepo,\n this.metadataRepo,\n this.searchService,\n this.jobManager,\n this.embeddingService,\n this.promptService,\n this.ontologyService,\n );\n this.importExportService = new ImportExportService(\n this.db,\n this.entryRepo,\n this.taskRepo,\n this.eventRepo,\n this.edgeRepo,\n this.metadataRepo,\n this.searchService,\n this.jobManager,\n this.embeddingService,\n );\n this.retrievalService = new RetrievalService(\n this.options,\n this.entryRepo,\n this.taskRepo,\n this.eventRepo,\n this.metadataRepo,\n this.searchService,\n );\n this.writeService = new WriteService(\n this.db,\n this.options,\n this.entryRepo,\n this.eventRepo,\n this.metadataRepo,\n this.jobManager,\n this.maintenanceService,\n );\n this.graphTraversalService = new GraphTraversalService(\n this.edgeRepo,\n this.entryRepo,\n this.options.config ?? {},\n );\n this.okfTrustWrites = new OkfTrustWritesRepository(this.db, this.prefix);\n }\n\n /**\n * Explicit escape hatch for test suites: typed access to composed services for mocks/spies.\n * If `NODE_ENV` is not `\"test\"`, emits a single `console.warn` per instance (skipped when `process` is undefined).\n */\n get __testAccess(): WikiMemoryTestAccess {\n const processEnv = typeof globalThis !== 'undefined'\n ? (globalThis as any).process?.env\n : undefined;\n\n if (\n processEnv !== undefined &&\n processEnv.NODE_ENV !== 'test' &&\n !this.#testAccessNonTestEnvWarned\n ) {\n this.#testAccessNonTestEnvWarned = true;\n console.warn('Warning: WikiMemory.__testAccess is intended for tests (NODE_ENV !== \"test\").');\n }\n return {\n embeddingService: this.embeddingService,\n importExportService: this.importExportService,\n ingestionService: this.ingestionService,\n maintenanceService: this.maintenanceService,\n retrievalService: this.retrievalService,\n searchService: this.searchService,\n writeService: this.writeService,\n promptService: this.promptService,\n graphTraversalService: this.graphTraversalService,\n entryRepo: this.entryRepo,\n sourceRefIndexRepo: this.sourceRefIndexRepo,\n metadataRepo: this.metadataRepo,\n jobManager: this.jobManager,\n };\n }\n\n async setup() {\n const entriesExistedBeforeSetup = await this.metadataRepo.tableExists(`${this.prefix}entries`);\n\n await setupDatabase(this.db, this.prefix);\n\n let currentVersion: number;\n\n if (!entriesExistedBeforeSetup) {\n await this.metadataRepo.setMeta('schema_version', String(CURRENT_SCHEMA_VERSION), this.db);\n currentVersion = CURRENT_SCHEMA_VERSION;\n } else {\n const schemaVersionValue = await this.metadataRepo.getMeta('schema_version');\n\n if (schemaVersionValue) {\n currentVersion = parseInt(schemaVersionValue, 10);\n if (!Number.isFinite(currentVersion)) currentVersion = 0;\n } else {\n const ftsDdl = await this.metadataRepo.getTableDdl(`${this.prefix}entries_fts`);\n const hasPorter = /tokenize\\s*=\\s*['\"]porter\\s+unicode61['\"]/i.test(ftsDdl ?? '');\n currentVersion = hasPorter ? 1 : 0;\n }\n }\n\n for (const migration of MIGRATIONS) {\n if (migration.version > currentVersion) {\n await migration.run(this.db, this.prefix);\n await this.metadataRepo.setMeta('schema_version', String(migration.version), this.db);\n currentVersion = migration.version;\n }\n }\n\n if (entriesExistedBeforeSetup) {\n const schemaVersionCheck = await this.metadataRepo.getMeta('schema_version');\n if (!schemaVersionCheck) {\n await this.metadataRepo.setMeta('schema_version', String(currentVersion), this.db);\n }\n }\n\n if (entriesExistedBeforeSetup) {\n await this.importExportService.assertNoLegacySourceTypes();\n }\n\n const rows = await this.entryRepo.findRowsForSourceRefMigration();\n await this.db.withTransactionAsync(async (tx) => {\n for (const row of rows) {\n const normalized = normalizeSourceRef(row.source_ref);\n if (normalized !== row.source_ref) {\n await this.entryRepo.updateSourceRefByRowid(row.rowid, normalized, tx);\n }\n }\n });\n\n await this.searchService.sync();\n }\n\n async hasChanged(\n entityId: string,\n sourceRef: string,\n sourceHash: string,\n ): Promise<boolean>;\n /**\n * Batched overload.\n *\n * `duplicateOf`, when present, is the canonical stored DIFFERENT `source_ref`\n * holding the same hash — never the incoming ref itself (the incoming ref is\n * excluded from the canonical-sort set so a self-reference is impossible).\n * `duplicateOf` reflects the *DB-side* normalized spelling; `sourceRef` in\n * each result echoes the raw caller value. Hosts should not compare these\n * two fields directly to infer canonical status.\n */\n async hasChanged(\n entityId: string,\n entries: Array<{ sourceRef: string; sourceHash: string }>,\n ): Promise<Array<{ sourceRef: string; changed: boolean; duplicateOf?: string }>>;\n async hasChanged(\n entityId: string,\n sourceRefOrEntries: string | Array<{ sourceRef: string; sourceHash: string }>,\n sourceHashArg?: string,\n ): Promise<boolean | Array<{ sourceRef: string; changed: boolean; duplicateOf?: string }>> {\n // Single-doc path: delegate to existing semantics.\n if (typeof sourceRefOrEntries === 'string') {\n const sourceRef = normalizeSourceRef(sourceRefOrEntries);\n if (!sourceRef) {\n throw new Error(`Invalid sourceRef: ${JSON.stringify(sourceRefOrEntries)}`);\n }\n const sourceHash = normalizeSourceHash(sourceHashArg!);\n if (!sourceHash) {\n throw new Error('Invalid sourceHash: must be a 64-character hex string (normalized to lowercase)');\n }\n const storedHash = await this.entryRepo.findLatestSourceHash(entityId, sourceRef);\n if (storedHash === null) return true;\n const normalizedStoredHash = normalizeSourceHash(storedHash);\n return normalizedStoredHash !== sourceHash;\n }\n\n // Batched path: empty input -> empty result, zero SQL calls.\n const entries = sourceRefOrEntries;\n if (entries.length === 0) return [];\n\n // Normalize all inputs (validation up front). Preserve the raw ref so the\n // result echoes the caller's spelling (DB refs are normalized on setup,\n // but the caller hasn't seen that normalization yet).\n const normalized = entries.map(e => {\n const r = normalizeSourceRef(e.sourceRef);\n if (!r) throw new Error(`Invalid sourceRef: ${JSON.stringify(e.sourceRef)}`);\n const h = normalizeSourceHash(e.sourceHash);\n if (!h) throw new Error('Invalid sourceHash: must be a 64-character hex string (normalized to lowercase)');\n return { rawSourceRef: e.sourceRef, sourceRef: r, sourceHash: h };\n });\n\n // 1 + H SQL queries: one batched latest-hash lookup, plus one source_ref_index\n // lookup per distinct input hash. Lookups are issued in parallel — the bound\n // is the SQL-query count, not the await count.\n const latestHashes = await this.entryRepo.findLatestSourceHashes(entityId, normalized.map(e => e.sourceRef));\n\n const distinctHashes = Array.from(new Set(normalized.map(e => e.sourceHash)));\n const dupRefs = await Promise.all(\n distinctHashes.map(h => this.sourceRefIndexRepo.findActiveByEntityAndHash(entityId, h)),\n );\n const dupMap = new Map<string, string | null>(); // hash -> canonical sourceRef (or null)\n for (let i = 0; i < distinctHashes.length; i++) {\n dupMap.set(distinctHashes[i], dupRefs[i]);\n }\n\n return normalized.map(e => {\n const stored = latestHashes.get(e.sourceRef);\n const changed = stored === undefined || stored === null || normalizeSourceHash(stored) !== e.sourceHash;\n const canonical = dupMap.get(e.sourceHash) ?? null;\n if (canonical === null || canonical === e.sourceRef) {\n return { sourceRef: e.rawSourceRef, changed };\n }\n // Canonical: the single sourceRef from source_ref_index that holds\n // this hash, if any. Because the partial UNIQUE index allows at most\n // one live row per (entity, hash), the canonical cannot be the\n // incoming ref (it would be the same sourceRef) — we filter that out\n // above. Non-ASCII sourceRefs are still compared by the DB's\n // source_ref index, so the canonical matches the DB ordering.\n return { sourceRef: e.rawSourceRef, changed, duplicateOf: canonical };\n });\n }\n\n /**\n * Batch pending state per source (spec §8.2). `current` exactly when\n * `hasChanged` is false; `partial` when live rows exist but none carries a\n * hash (a first ingest with a failed chunk, or imported rows without a\n * hash). A failed re-ingest of an already-hashed ref reports `changed`. Validation and raw-ref echo match\n * batched `hasChanged`. Input order and duplicates are preserved. A\n * non-array `sources`, or an entry that is not an object (including a hole\n * in a sparse array), throws a `TypeError` before any SQL runs.\n */\n async pendingSources(\n entityId: string,\n sources: Array<{ sourceRef: string; sourceHash: string }>,\n ): Promise<Array<{ sourceRef: string; status: PendingSourceStatus }>> {\n assertEntityId(entityId);\n if (!Array.isArray(sources)) {\n throw new TypeError('Invalid sources: must be an array of { sourceRef, sourceHash } objects.');\n }\n if (sources.length === 0) return [];\n // Array.from visits holes as undefined, so a sparse array fails the entry check.\n const normalized = Array.from(sources, (s: unknown, i) => {\n if (s === null || typeof s !== 'object') {\n throw new TypeError(`Invalid sources[${i}]: must be a { sourceRef, sourceHash } object.`);\n }\n const { sourceRef: rawSourceRef, sourceHash: rawSourceHash } = s as { sourceRef: string; sourceHash: string };\n const sourceRef = normalizeSourceRef(rawSourceRef);\n if (!sourceRef) {\n // JSON.stringify throws on a bigint; name the type for non-strings instead.\n const shown = typeof rawSourceRef === 'string' ? JSON.stringify(rawSourceRef) : `<${typeof rawSourceRef}>`;\n throw new Error(`Invalid sourceRef: ${shown}`);\n }\n const sourceHash = normalizeSourceHash(rawSourceHash);\n if (!sourceHash) throw new Error('Invalid sourceHash: must be a 64-character hex string (normalized to lowercase)');\n return { rawSourceRef, sourceRef, sourceHash };\n });\n const states = await this.entryRepo.findSourceStates(entityId, normalized.map((n) => n.sourceRef));\n return normalized.map((n) => {\n const state = states.get(n.sourceRef);\n let status: PendingSourceStatus;\n if (!state) status = 'new';\n else if (!state.anyHashed) status = 'partial';\n else if (state.latestHash !== null && normalizeSourceHash(state.latestHash) === n.sourceHash) status = 'current';\n else status = 'changed';\n return { sourceRef: n.rawSourceRef, status };\n });\n }\n\n /** Read-only maintenance report for one entity (spec §8.1). Reports, never repairs. */\n async lint(entityId: string): Promise<WikiLintReport> {\n assertEntityId(entityId);\n return this.lintService.lint(entityId);\n }\n\n /**\n * Effective system prompts for ingest, librarian, heal and ontology backfill\n * (spec §8.3). Backs the `wiki_get_instructions` tool. Templates only;\n * overrides are returned verbatim, so keep secrets out of `WikiConfig.prompts`.\n */\n async getInstructions(entityId: string): Promise<WikiInstructions> {\n assertEntityId(entityId);\n const ontologyContext = await this.ontologyService.buildPromptContext(entityId);\n return this.promptService.buildInstructionTemplates(ontologyContext);\n }\n\n /**\n * Returns the live source_refs for an entity, one row per ref, with the most\n * recently-updated live `source_hash` and a live fact count. Refs are sorted\n * `COLLATE BINARY` (no locale dependency). Used by hosts to reconcile stored\n * state against a live source, or audit duplicate-hash collisions via\n * `findSourceRefsByHash`.\n */\n async listSourceRefs(entityId: string): Promise<Array<{\n sourceRef: string;\n sourceHash: string | null;\n factCount: number;\n lastIngestedAt: number;\n }>> {\n return this.entryRepo.listSourceRefs(entityId);\n }\n\n /**\n * Returns the live source_refs for an entity that hold the given source_hash.\n * With v9, source_ref_index is the source of truth for the sourceRef-level\n * TOCTOU-race invariant: at most one sourceRef can hold a given\n * (entity_id, source_hash). The result is either a single-element array\n * (one canonical ref) or empty (no live ref holds the hash). Returned as\n * an array to preserve the existing public-API shape used by hosts\n * auditing duplicate-content collisions.\n */\n async findSourceRefsByHash(entityId: string, sourceHash: string): Promise<string[]> {\n const canonical = await this.sourceRefIndexRepo.findActiveByEntityAndHash(entityId, sourceHash);\n return canonical === null ? [] : [canonical];\n }\n\n /**\n * Returns the set of `entity_id` values with at least one row in this\n * database, INCLUDING entities whose only remaining rows are soft-deleted\n * — sorted ascending `entity_id COLLATE BINARY`. Empty array when the\n * database has no entities.\n *\n * The deliberate inclusion of soft-deleted-only entities closes the\n * decommissioned-scope leak: a scoped namespace whose documents have all\n * been forgotten or superseded must still appear so host maintenance\n * sweeps (`runLibrarian`, `runHeal`, `runOntologyBackfill`, `runPrune`)\n * can visit it and reap the soft-deleted rows.\n *\n * Read-only. Never acquires a lock. Never opens a transaction. Propagates\n * underlying read errors.\n *\n * @param options.prefix - Optional string filter applied as\n * `id.startsWith(prefix)`. O(n) over distinct ids because the\n * `(entity_id, source_ref)` index is not seekable on `entity_id`-only\n * prefix. Empty-string prefix matches every id.\n *\n * Note: this widens the coverage of `exportDump` (which delegates to\n * `MetadataRepository.getDistinctEntityIds`); exported dumps now include\n * orphaned entities. This is a deliberate widening for backup/migration\n * coverage, not a breaking change to `exportDump`'s return shape.\n */\n async listEntityIds(options?: { prefix?: string }): Promise<string[]> {\n const ids = await this.metadataRepo.getDistinctEntityIds();\n if (options?.prefix === undefined) return ids;\n return ids.filter(id => id.startsWith(options.prefix!));\n }\n\n async runPrune(\n entityId: string,\n options?: {\n retainSoftDeletedFor?: number | null;\n retainEventsFor?: number | null;\n vacuum?: boolean;\n },\n ): Promise<{ entries: number; tasks: number; events: number }> {\n return this.maintenanceService.runPrune(entityId, options);\n }\n\n async read(entityId: string | string[], query: string, options?: ReadOptions): Promise<MemoryBundle> {\n return this.retrievalService.read(entityId, query, options);\n }\n\n async traverseGraph(entityId: string, options: GraphTraversalOptions): Promise<GraphNeighborhood> {\n return this.graphTraversalService.traverseGraph(entityId, options);\n }\n\n async getMemoryBundle(entityId: string): Promise<MemoryBundle> {\n return this.importExportService.getFullBundle(entityId, { maxEvents: 10 });\n }\n\n async write(entityId: string, event: Omit<WikiEvent, 'id' | 'entity_id' | 'created_at'>): Promise<void> {\n return this.writeService.write(entityId, event);\n }\n\n /**\n * @param options.promptOverride - Applies only to this manual call. Does NOT affect\n * WriteService-triggered auto-runs. For persistent prompt customization across auto-runs,\n * set `options.config.prompts.librarianSystemPrompt` at WikiMemory construction time.\n */\n async runLibrarian(entityId: string, options?: { promptOverride?: string }): Promise<void> {\n return this.maintenanceService.runLibrarian(entityId, options);\n }\n\n /**\n * Reviews stored facts with the LLM: removes orphans, downgrades stale\n * inferences, synthesizes corrections.\n *\n * Bounded per call: covers at most `batchSize` candidates (default 25), so\n * one call no longer sweeps the whole entity. Hosts own the cadence; loop\n * `while (result.remaining > 0)` for convergence.\n *\n * `remaining === 0` means \"every mutable fact is inside the 7-day recheck\n * cooldown\", not \"there is no more work\" — heal's candidate set is the live\n * mutable corpus, not a draining backlog, so it climbs back as the cooldown\n * lapses and as new facts are written. Do not write a loop expecting a drain.\n *\n * @param options.promptOverride - Applies only to this manual call. Does NOT affect\n * WriteService-triggered auto-runs. For persistent prompt customization across auto-runs,\n * set `options.config.prompts.healSystemPrompt` at WikiMemory construction time.\n * @param options.batchSize - Candidates per run (default 25) for providers with\n * tighter context limits.\n */\n async runHeal(\n entityId: string,\n options?: { promptOverride?: string; batchSize?: number },\n ): Promise<HealResult> {\n return this.maintenanceService.runHeal(entityId, options);\n }\n\n /**\n * Types already-persisted untyped facts (okf_type IS NULL) in place via one\n * librarian-style LLM call. Strictly additive: never creates, deletes, or\n * rewrites facts; never overwrites an existing okf_type. Free when there is\n * nothing to do (ontology off, or zero eligible untyped facts).\n *\n * Hosts own the trigger cadence (e.g. after each sync); loop `while\n * result.remaining > 0` for convergence. Throws WikiBusyError when another\n * backfill (or conflicting maintenance op) is running for the entity.\n *\n * @param options.promptOverride - Applies only to this call. For persistent\n * customization set `options.config.prompts.ontologyBackfillSystemPrompt`.\n * @param options.batchSize - Facts per run (default 25) for providers with\n * tighter context limits.\n */\n async runOntologyBackfill(\n entityId: string,\n options?: { promptOverride?: string; batchSize?: number; classifier?: 'auto' | 'llm' },\n ): Promise<OntologyBackfillResult> {\n return this.maintenanceService.runOntologyBackfill(entityId, options);\n }\n\n async runReembed(\n entityId?: string,\n opts?: { force?: boolean; skipExisting?: boolean },\n ): Promise<ReembedResult> {\n return this.maintenanceService.runReembed(entityId, opts);\n }\n\n getEntityStatus(entityId: string): EntityStatus {\n return this.jobManager.getEntityStatus(entityId);\n }\n\n subscribeEntityStatus(\n entityId: string,\n callback: (status: EntityStatus) => void,\n ): () => void {\n return this.jobManager.subscribeEntityStatus(entityId, callback);\n }\n\n clearVectorCache(): void {\n this.searchService.evictCache();\n }\n\n async exportDump(entityIds?: string[]): Promise<MemoryDump> {\n return this.importExportService.exportDump(entityIds);\n }\n\n /** Entity summary prose persisted from an OKF profile ≥ 1 import; null when none stored. */\n async getEntitySummary(entityId: string): Promise<string | null> {\n return this.metadataRepo.getMeta(entitySummaryMetaKey(entityId));\n }\n\n async importDump(dump: MemoryDump, opts?: { merge?: boolean }): Promise<void> {\n return this.importExportService.importDump(dump, opts);\n }\n\n async forget(\n entityId: string,\n params: { entryId?: string; taskId?: string; sourceRef?: string; sourceHash?: string; clearAll?: boolean },\n opts?: { dryRun?: boolean },\n ): Promise<{ deleted: { entries: number; tasks: number }; metadataReset?: boolean }> {\n return this.maintenanceService.forget(entityId, params, opts);\n }\n\n /**\n * Full and partial ingestion both reject foreign-owned generated fact IDs with\n * `WikiGraphNodeOwnershipConflict`. Such collisions are unexpected. Ingestion\n * may already have persisted ontology or other state before rejection; unlike\n * direct graph preflight, it relies on transaction rollback for atomicity.\n *\n * @param params.promptOverride - Overrides the system prompt for this ingest call only.\n * For persistent customization, set `options.config.prompts.ingestSystemPrompt` at\n * WikiMemory construction time.\n */\n async ingestDocument(\n entityId: string,\n params: {\n sourceRef: string;\n sourceHash: string;\n documentChunk: string;\n maxChunkLength?: number;\n chunkOverlap?: number;\n chunkConcurrency?: number;\n promptOverride?: string;\n },\n opts?: { onDuplicateHash?: 'ingest' | 'skip' | 'throw' },\n ): Promise<IngestDocumentResult> {\n return this.ingestionService.ingestDocument(entityId, params, opts);\n }\n\n /**\n * Deterministic write path into the graph. Accepts caller-supplied\n * `(nodes, edges)` and writes them under `(sourceRef, sourceHash)`\n * semantics identical to `ingestDocument`, minus the LLM extraction step.\n *\n * MUST be called from inside an open `db.withTransactionAsync` callback —\n * the third argument is the caller's `tx`. The method does not open a\n * nested transaction, does not acquire any lock, and does not perform\n * post-commit work (search sync, embedding, cache eviction). Hosts that\n * want embeddings synced should drive the existing maintenance sweep\n * (`runLibrarian` / `runHeal` / `runOntologyBackfill` / `runPrune`,\n * scoped via `listEntityIds`).\n *\n * Contract (full pre-flight validation lives inside\n * `IngestionService.upsertGraphCore`, which this method delegates to):\n * - C2: no-op when `(entityId, sourceHash)` is already mapped to\n * `params.sourceRef`; throws `WikiSourceRefHashCollision` if mapped to\n * a different `sourceRef`.\n * - C3: edges with dangling `targetId` are stored verbatim (no FK, no\n * resolution).\n * - C4: under persisted ontology mode `'strict'`, an out-of-manifest node\n * or edge `type` throws `WikiStrictOntologyViolation` (pre-flight,\n * all-or-nothing — NONE written on failure).\n *\n * Entry IDs share one database-wide namespace. Existing rows, including\n * soft-deleted rows, reserve their IDs for their entity; same-entity updates\n * and resurrection remain supported. Hosts authenticate callers and select\n * the authorized entity ID; entity-qualified IDs are optional, not required.\n * After the live-only C2 probe above, a foreign node ID throws the fixed,\n * privacy-preserving `WikiGraphNodeOwnershipConflict` before persistent writes\n * (including seed manifests). Deleted source mappings do not trigger C2.\n *\n * Propagate later failures to roll back the host transaction. In particular,\n * foreign edge-ID collisions remain late bare `Error`s: the foreign edge is\n * not overwritten, but catching and committing can retain earlier writes.\n * This method neither commits nor rolls back the caller's transaction.\n *\n * @returns Counts: nodesWritten (validated nodes persisted), edgesWritten\n * (manifest-valid edges persisted), superseded (prior facts soft-deleted\n * plus prior source-ref edges hard-deleted).\n */\n async upsertGraph(\n entityId: string,\n params: {\n sourceRef: string;\n sourceHash: string;\n nodes: readonly { id: string; type: string; title: string; body?: string }[];\n edges: readonly { type: string; sourceId: string; targetId: string; id?: string }[];\n },\n adapter: SQLiteAdapter,\n ): Promise<{ nodesWritten: number; edgesWritten: number; superseded: number }> {\n const sourceRef = normalizeSourceRef(params.sourceRef);\n if (!sourceRef) throw new Error('Invalid sourceRef');\n const sourceHash = normalizeSourceHash(params.sourceHash);\n if (!sourceHash) throw new Error('Invalid sourceHash (must be 64-char hex string)');\n\n // C2 probe — runs inside the caller's tx so it sees the in-flight state.\n const canonical = await this.sourceRefIndexRepo.findActiveByEntityAndHash(entityId, sourceHash, adapter);\n if (canonical !== null && canonical === sourceRef) {\n return { nodesWritten: 0, edgesWritten: 0, superseded: 0 };\n }\n if (canonical !== null && canonical !== sourceRef) {\n throw new WikiSourceRefHashCollision({\n entityId,\n sourceHash,\n existingSourceRef: canonical,\n attemptedSourceRef: sourceRef,\n });\n }\n\n // Delegate to upsertGraphCore for steps a–j (manifest read, validation,\n // supersession, writes, returns counts). No opts.strict override — let\n // the persisted ontology mode drive strictness per the spec.\n // The host owns this transaction and core never sees its commit, so\n // diagnostics are delivered when upsertGraph resolves (spec §4.2.4).\n // Hosts that roll back should disregard them.\n const diagBuffer = new DiagnosticBuffer();\n const result = await this.ingestionService.upsertGraphCore(\n entityId,\n { sourceRef, sourceHash, nodes: params.nodes, edges: params.edges },\n adapter,\n { diag: { buffer: diagBuffer, operation: 'upsertGraph' } },\n );\n diagBuffer.flush(this.options);\n return result;\n }\n\n /**\n * Returns up to `limit` unprocessed outbox events, oldest first.\n * Works regardless of enableOutbox value — allows draining after disabling.\n */\n async getUnprocessedOutboxEvents(limit = 100): Promise<WikiOutboxEvent[]> {\n if (Number.isFinite(limit) && limit <= 0) return [];\n const safeLimit = Number.isFinite(limit) && limit >= 1 ? Math.trunc(limit) : 100;\n const rows = await this.outboxRepo.fetchPending(safeLimit);\n return rows.map(row => {\n let payload: unknown = null;\n try {\n payload = JSON.parse(row.payload);\n } catch {\n // corrupted row — surface null payload rather than poisoning the batch\n }\n return { ...row, payload } as WikiOutboxEvent;\n });\n }\n\n /**\n * Deletes the given event IDs from the outbox table.\n * Call after successfully committing events to the external system.\n */\n async markOutboxEventsProcessed(eventIds: string[]): Promise<void> {\n await this.outboxRepo.acknowledge(eventIds);\n }\n\n /**\n * Returns the effective ontology mode and manifest for an entity.\n * Resolution order: persisted DB row → `WikiConfig.ontology.seedManifests[entityId]` → `null`.\n */\n async getOntologyManifest(entityId: string): Promise<{\n mode: OntologyMode;\n manifest: OntologyManifest;\n } | null> {\n const row = await this.metadataRepo.getManifest(entityId);\n if (row) return { mode: this.ontologyService.resolveMode(row.mode), manifest: row.manifest };\n const seed = this.options.config?.ontology?.seedManifests?.[entityId];\n if (seed) {\n return {\n mode: this.ontologyService.resolveMode(seed.mode),\n manifest: seed.manifest,\n };\n }\n return null;\n }\n\n /**\n * Seeds or replaces an entity's ontology manifest and optional mode override.\n * Validates manifest invariants (unique type slugs, edge endpoints reference node types).\n * Invalidates the in-memory ontology cache for this entity.\n *\n * Delegates to `setOntologyManifests` so there is a single write path. The\n * observable contract is unchanged: same upsert semantics, same cache\n * invalidation, same `void` result.\n */\n async setOntologyManifest(\n entityId: string,\n manifest: OntologyManifest,\n options?: { mode?: OntologyMode },\n ): Promise<void> {\n await this.setOntologyManifests([{ entityId, manifest, mode: options?.mode }]);\n }\n\n /**\n * Write several entities' ontology manifests in a single transaction.\n *\n * All succeed or none do. The transaction is opened on this instance's\n * serialized adapter — callers pass data, never a transaction handle, because\n * a consumer holds the unwrapped adapter and a transaction opened on it would\n * bypass the serialization mutex applied in the constructor.\n *\n * Returns which entities were written. `skipped` is only ever non-empty under\n * `opts.ifAbsent`.\n *\n * Sharp edge: `ifAbsent` checks for a PERSISTED row, not for an effective\n * manifest. An entity whose manifest currently comes from\n * `WikiConfig.ontology.seedManifests` has no row until the seed is\n * materialized on first access that supplies a transaction (in practice, an\n * ingest). Until then `ifAbsent` treats the entity as absent, writes the new\n * manifest over the configured seed, and reports it in `written`; the same\n * call after the seed has been materialized reports it in `skipped`. See the\n * `ifAbsent` notes in the package README.\n */\n async setOntologyManifests(\n entries: Array<{\n entityId: string;\n manifest: OntologyManifest;\n mode?: OntologyMode;\n }>,\n opts?: { ifAbsent?: boolean },\n ): Promise<{ written: string[]; skipped: string[] }> {\n // Nothing to do — and deliberately no transaction, so an empty batch never\n // takes the serialization mutex.\n if (entries.length === 0) return { written: [], skipped: [] };\n\n // Two entries naming one entity express ambiguous intent. Applying the last\n // one silently would hide a caller bug whose symptom — a manifest that is\n // not the one the caller believed it wrote — surfaces far from its cause.\n const seen = new Set<string>();\n for (const entry of entries) {\n if (seen.has(entry.entityId)) {\n throw new Error(`Duplicate entityId in batch: ${entry.entityId}`);\n }\n seen.add(entry.entityId);\n }\n\n // Validate every manifest BEFORE opening the transaction, so a doomed batch\n // never reaches the database and never takes the mutex. `setManifest`\n // validates again inside the transaction; that is the invariant protecting\n // every other repository caller, and is not redundant with this gate.\n for (const entry of entries) {\n validateManifest(entry.manifest);\n }\n\n const written: string[] = [];\n const skipped: string[] = [];\n\n await this.db.withTransactionAsync(async (tx) => {\n for (const entry of entries) {\n const mode = entry.mode ?? this.ontologyService.resolveMode();\n const wrote = await this.metadataRepo.setManifest(\n entry.entityId,\n { mode, manifest: entry.manifest },\n tx,\n { ifAbsent: opts?.ifAbsent === true },\n );\n (wrote ? written : skipped).push(entry.entityId);\n }\n });\n\n // After a successful commit, and for EVERY entry rather than just the\n // written ones: under `ifAbsent` a skipped entry means another writer won\n // the race, so this instance's cached copy may be stale and dropping it is\n // more correct than keeping it. A failed transaction throws above and never\n // reaches this loop, which is fine — a rolled-back batch changed nothing,\n // so the cache is still consistent with the database. Invalidating is cheap\n // either way: it only drops a cached copy, and the next read reloads from\n // the database.\n for (const entry of entries) {\n this.ontologyService.invalidateCache(entry.entityId);\n }\n\n return { written, skipped };\n }\n\n /** Append a verification event to a fact. Does NOT touch `updated_at`. */\n async writeOkfTrust(entryId: string, entityId: string, verified: { by: string; at: string }[]): Promise<void> {\n return this.okfTrustWrites.writeOkfTrust(entryId, entityId, verified);\n }\n\n /** Replace a fact's source list. Does NOT touch `updated_at`. */\n async writeOkfSources(entryId: string, entityId: string, sources: Array<{ resource: string; [k: string]: unknown }>): Promise<void> {\n return this.okfTrustWrites.writeOkfSources(entryId, entityId, sources as any);\n }\n\n /** Set a fact's OKF v0.2 lifecycle status. Does NOT touch `updated_at`. */\n async setLifecycleStatus(entryId: string, entityId: string, status: 'draft' | 'stable' | 'deprecated'): Promise<void> {\n return this.okfTrustWrites.setLifecycleStatus(entryId, entityId, status);\n }\n\n /**\n * Live draft facts for one entity, newest first (spec §5.2). Default page\n * size 50, clamped to [1, 500]. Pass `nextCursor` back unchanged for the next page.\n */\n async listDrafts(entityId: string, options?: { limit?: number; cursor?: string }): Promise<DraftPage> {\n const rawLimit = options?.limit;\n const limit = typeof rawLimit === 'number' && Number.isFinite(rawLimit)\n ? Math.min(500, Math.max(1, Math.floor(rawLimit)))\n : 50;\n const after = options?.cursor === undefined ? null : decodeDraftCursor(options.cursor);\n const rows = await this.entryRepo.listDraftsByEntityId(entityId, limit + 1, after);\n const facts = rows.slice(0, limit);\n const last = facts[facts.length - 1];\n return {\n facts,\n nextCursor: rows.length > limit && last ? `${last.created_at}:${last.id}` : null,\n };\n }\n\n /**\n * Promote a draft to `stable` and record who reviewed it, atomically\n * (spec §5.2). Metadata writes only: `updated_at` is not bumped and no\n * outbox event is pushed. Pass `by: 'human:<id>'` so `trustTier` becomes\n * `'human-reviewed'`.\n *\n * @throws WikiDraftNotFound when no live draft with that id exists for the entity.\n */\n async promoteDraft(entryId: string, entityId: string, reviewer: { by: string }): Promise<void> {\n const by = reviewer?.by;\n if (typeof by !== 'string' || by.trim().length === 0) {\n throw new TypeError('promoteDraft requires reviewer.by to be a non-empty string.');\n }\n await this.db.withTransactionAsync(async (tx) => {\n if (!(await this.entryRepo.isLiveDraft(entryId, entityId, tx))) {\n throw new WikiDraftNotFound();\n }\n await this.okfTrustWrites.setLifecycleStatus(entryId, entityId, 'stable', tx);\n await this.okfTrustWrites.writeOkfTrust(entryId, entityId, [{ by, at: new Date().toISOString() }], tx);\n });\n }\n\n /** Set a fact's stale_after (epoch ms) or clear it. Does NOT touch `updated_at`. */\n async setStaleAfter(entryId: string, entityId: string, date: number | null): Promise<void> {\n return this.okfTrustWrites.setStaleAfter(entryId, entityId, date);\n }\n\n /** Set a fact's generated_by actor string. Does NOT touch `updated_at`. */\n async setGeneratedBy(entryId: string, entityId: string, actor: string): Promise<void> {\n return this.okfTrustWrites.setGeneratedBy(entryId, entityId, actor);\n }\n\n /** Task variants of the same five DAO methods. Symmetric per spec §2.5. */\n async writeOkfTrustTask(taskId: string, entityId: string, verified: { by: string; at: string }[]): Promise<void> {\n return this.okfTrustWrites.writeOkfTrustTask(taskId, entityId, verified);\n }\n async writeOkfSourcesTask(taskId: string, entityId: string, sources: Array<{ resource: string; [k: string]: unknown }>): Promise<void> {\n return this.okfTrustWrites.writeOkfSourcesTask(taskId, entityId, sources as any);\n }\n async setLifecycleStatusTask(taskId: string, entityId: string, status: 'draft' | 'stable' | 'deprecated'): Promise<void> {\n return this.okfTrustWrites.setLifecycleStatusTask(taskId, entityId, status);\n }\n async setStaleAfterTask(taskId: string, entityId: string, date: number | null): Promise<void> {\n return this.okfTrustWrites.setStaleAfterTask(taskId, entityId, date);\n }\n async setGeneratedByTask(taskId: string, entityId: string, actor: string): Promise<void> {\n return this.okfTrustWrites.setGeneratedByTask(taskId, entityId, actor);\n }\n}\n\n/**\n * Shape check for the read-only reports. Deliberately looser than `write()`'s\n * rule: ingestDocument and upsertGraph accept any string id, so a report must\n * too. The value is never echoed; JSON.stringify throws on a bigint.\n */\nfunction assertEntityId(entityId: unknown): asserts entityId is string {\n if (typeof entityId !== 'string' || entityId.length === 0) {\n throw new TypeError('Invalid entityId: must be a non-empty string.');\n }\n}\n\nexport const __testables = { validateFact, validateTask, clip, chunkText };\n","import type { MemoryBundle, WikiFact, WikiTask, WikiEvent, FormatContextOptions } from '../types';\n\nfunction validateMaxOption(value: number, name: string): void {\n if (!isFinite(value) || value < 0) {\n throw new Error(`Invalid ${name}: must be a non-negative finite number`);\n }\n}\n\nconst CONFIDENCE_WEIGHT: Record<string, number> = {\n certain: 1.0,\n inferred: 0.6,\n tentative: 0.3,\n};\n\nfunction scoreFactFor(\n fact: WikiFact,\n weights: Required<NonNullable<FormatContextOptions['factWeights']>>,\n now: number\n): number {\n const confW = CONFIDENCE_WEIGHT[fact.confidence] ?? 0.3;\n const ageDays = (now - fact.updated_at) / 86400000;\n const recencyDecay = Math.exp(-ageDays / 30);\n return (\n confW * weights.confidence +\n Math.log(1 + fact.access_count) * weights.accessCount +\n recencyDecay * weights.recency\n );\n}\n\nfunction renderFactMarkdown(\n fact: WikiFact,\n includeConfidence: boolean,\n includeTags: boolean,\n includeEntityIds: boolean,\n score: number | undefined,\n): string {\n const confPart = includeConfidence ? ` (${fact.confidence})` : '';\n const tagPart = includeTags && fact.tags.length > 0 ? ` [${fact.tags.join(', ')}]` : '';\n const sourcePart = includeEntityIds ? ` {entity_id=${fact.entity_id}}` : '';\n const scorePart = score !== undefined ? ` {score=${score.toFixed(4)}}` : '';\n return `- **${fact.title}**${confPart}${tagPart}${sourcePart}${scorePart}\\n ${fact.body.replace(/\\n/g, '\\n ')}`;\n}\n\nfunction renderFactPlain(\n fact: WikiFact,\n includeConfidence: boolean,\n includeTags: boolean,\n includeEntityIds: boolean,\n score: number | undefined,\n): string {\n const confPart = includeConfidence ? ` (${fact.confidence})` : '';\n const tagPart = includeTags && fact.tags.length > 0 ? ` [${fact.tags.join(', ')}]` : '';\n const sourcePart = includeEntityIds ? ` {entity_id=${fact.entity_id}}` : '';\n const scorePart = score !== undefined ? ` {score=${score.toFixed(4)}}` : '';\n return `${fact.title}${confPart}${tagPart}${sourcePart}${scorePart}: ${fact.body}`;\n}\n\nfunction renderTaskMarkdown(task: WikiTask): string {\n return `- [P${task.priority}] ${task.description.replace(/\\n/g, '\\n ')} (${task.status})`;\n}\n\nfunction renderTaskPlain(task: WikiTask): string {\n return `[P${task.priority}] ${task.description} (${task.status})`;\n}\n\nfunction renderEventMarkdown(event: WikiEvent): string {\n const ts = new Date(event.created_at).toISOString();\n return `- [${event.event_type} @ ${ts}] ${event.summary.replace(/\\n/g, '\\n ')}`;\n}\n\nfunction renderEventPlain(event: WikiEvent): string {\n const ts = new Date(event.created_at).toISOString();\n return `[${event.event_type} @ ${ts}] ${event.summary}`;\n}\n\nexport function formatContext(\n bundle: MemoryBundle,\n options?: FormatContextOptions\n): string {\n const opts: Required<FormatContextOptions> = {\n format: options?.format ?? 'markdown',\n maxFacts: options?.maxFacts ?? 10,\n maxTasks: options?.maxTasks ?? 10,\n maxEvents: options?.maxEvents ?? 10,\n includeConfidence: options?.includeConfidence ?? true,\n includeTags: options?.includeTags ?? true,\n includeEntityIds: options?.includeEntityIds ?? false,\n includeFactScores: options?.includeFactScores ?? false,\n factWeights: {\n confidence: options?.factWeights?.confidence ?? 1.0,\n accessCount: options?.factWeights?.accessCount ?? 0.3,\n recency: options?.factWeights?.recency ?? 0.5,\n },\n };\n\n validateMaxOption(opts.maxFacts, 'maxFacts');\n validateMaxOption(opts.maxTasks, 'maxTasks');\n validateMaxOption(opts.maxEvents, 'maxEvents');\n\n const weights = opts.factWeights as Required<NonNullable<FormatContextOptions['factWeights']>>;\n\n const now = Date.now();\n const sortedFacts = bundle.factScores\n ? [...bundle.facts].slice(0, opts.maxFacts)\n : [...bundle.facts]\n .sort((a, b) => scoreFactFor(b, weights, now) - scoreFactFor(a, weights, now))\n .slice(0, opts.maxFacts);\n\n const sortedTasks = [...bundle.tasks]\n .sort((a, b) => b.priority - a.priority || a.created_at - b.created_at)\n .slice(0, opts.maxTasks);\n\n const sortedEvents = [...bundle.events]\n .sort((a, b) => b.created_at - a.created_at)\n .slice(0, opts.maxEvents);\n\n if (sortedFacts.length === 0 && sortedTasks.length === 0 && sortedEvents.length === 0) {\n return '';\n }\n\n const isMarkdown = opts.format === 'markdown';\n const lines: string[] = [];\n\n if (isMarkdown) {\n lines.push('## Memory');\n\n if (sortedFacts.length > 0) {\n lines.push('');\n lines.push('### Known Facts');\n for (const fact of sortedFacts) {\n lines.push(renderFactMarkdown(fact, opts.includeConfidence, opts.includeTags, opts.includeEntityIds, opts.includeFactScores ? bundle.factScores?.[fact.id] : undefined));\n }\n }\n\n if (sortedTasks.length > 0) {\n lines.push('');\n lines.push('### Open Tasks');\n for (const task of sortedTasks) {\n lines.push(renderTaskMarkdown(task));\n }\n }\n\n if (sortedEvents.length > 0) {\n lines.push('');\n lines.push('### Recent Events');\n for (const event of sortedEvents) {\n lines.push(renderEventMarkdown(event));\n }\n }\n } else {\n if (sortedFacts.length > 0) {\n lines.push('KNOWN FACTS:');\n for (const fact of sortedFacts) {\n lines.push(renderFactPlain(fact, opts.includeConfidence, opts.includeTags, opts.includeEntityIds, opts.includeFactScores ? bundle.factScores?.[fact.id] : undefined));\n }\n }\n if (sortedTasks.length > 0) {\n lines.push('OPEN TASKS:');\n for (const task of sortedTasks) {\n lines.push(renderTaskPlain(task));\n }\n }\n if (sortedEvents.length > 0) {\n lines.push('RECENT EVENTS:');\n for (const event of sortedEvents) {\n lines.push(renderEventPlain(event));\n }\n }\n }\n\n return lines.join('\\n');\n}\n","import type { GraphNeighborhood, WikiEdge } from '../types';\n\n/**\n * Pure presenter — dense text serialization of a GraphNeighborhood for LLM prompt\n * injection. Deterministic: same input always produces byte-identical output\n * (matters for prompt caching).\n */\nexport function formatGraphContext(neighborhood: GraphNeighborhood): string {\n const { nodes, edges } = neighborhood;\n if (nodes.length === 0) return '';\n\n const nodeById = new Map(nodes.map((n) => [n.id, n]));\n const nodeIndex = new Map(nodes.map((n, i) => [n.id, i]));\n const lines: string[] = [];\n\n for (const node of nodes) {\n lines.push(`[${node.okf_type ?? 'fact'}] ${node.title} (ID: ${node.id})`);\n\n const outbound = edgesByDirection(edges, node.id, 'source_id', nodeById, nodeIndex);\n const inbound = edgesByDirection(edges, node.id, 'target_id', nodeById, nodeIndex);\n\n for (const { edge, other } of outbound) {\n lines.push(` -[${edge.edge_type}]-> [${other.okf_type ?? 'fact'}] ${other.title}`);\n }\n for (const { edge, other } of inbound) {\n lines.push(` <-[${edge.edge_type}]- [${other.okf_type ?? 'fact'}] ${other.title}`);\n }\n }\n\n return lines.join('\\n');\n}\n\nfunction edgesByDirection(\n edges: WikiEdge[],\n nodeId: string,\n endpoint: 'source_id' | 'target_id',\n nodeById: Map<string, GraphNeighborhood['nodes'][number]>,\n nodeIndex: Map<string, number>,\n) {\n const otherEndpoint = endpoint === 'source_id' ? 'target_id' : 'source_id';\n return edges\n .filter((e) => e[endpoint] === nodeId)\n .filter((e) => {\n const otherId = e[otherEndpoint];\n const selfIdx = nodeIndex.get(nodeId)!;\n const otherIdx = nodeIndex.get(otherId);\n return otherIdx !== undefined && selfIdx < otherIdx;\n })\n .map((edge) => ({ edge, other: nodeById.get(edge[otherEndpoint])! }))\n .sort(\n (a, b) =>\n a.edge.edge_type.localeCompare(b.edge.edge_type) ||\n a.other.title.localeCompare(b.other.title) ||\n a.other.id.localeCompare(b.other.id) ||\n a.edge.id.localeCompare(b.edge.id),\n );\n}\n","function shortHash(value: string): string {\n let h1 = 5381;\n let h2 = 52711;\n for (let i = 0; i < value.length; i += 1) {\n const c = value.charCodeAt(i);\n h1 = Math.imul(h1, 33) ^ c;\n h2 = Math.imul(h2, 31) ^ c;\n }\n return (h1 >>> 0).toString(16).padStart(8, '0') + (h2 >>> 0).toString(16).padStart(8, '0');\n}\n\nconst OKF_RESERVED_CONCEPT_NAMES = new Set(['index', 'log']);\n\nconst WINDOWS_RESERVED_NAMES = new Set([\n 'con',\n 'prn',\n 'aux',\n 'nul',\n 'com1',\n 'com2',\n 'com3',\n 'com4',\n 'com5',\n 'com6',\n 'com7',\n 'com8',\n 'com9',\n 'lpt1',\n 'lpt2',\n 'lpt3',\n 'lpt4',\n 'lpt5',\n 'lpt6',\n 'lpt7',\n 'lpt8',\n 'lpt9',\n]);\n\nfunction isWindowsReservedName(name: string): boolean {\n const base = name.split('.')[0];\n return WINDOWS_RESERVED_NAMES.has(base.toLowerCase());\n}\n\nexport function sanitizeForFilename(value: string): string {\n const normalized = value.normalize('NFKC');\n const sanitized = normalized\n .replace(/[^A-Za-z0-9._-]+/g, '_')\n .replace(/^\\.+/, '_')\n .replace(/_+/g, '_')\n .replace(/^[_-]+|[_-]+$/g, '');\n\n // Enforce a max base-name length so the final filename stays within typical\n // filesystem limits (~255 bytes). Reserve ~20 chars for `-<16hexchars>`.\n const MAX_BASE = 200;\n const trimmed = sanitized.length > MAX_BASE ? sanitized.slice(0, MAX_BASE) : sanitized;\n\n let baseName = trimmed && trimmed !== '.' && trimmed !== '..' ? trimmed : 'entity';\n\n // Windows disallows trailing dots and spaces in filenames.\n const withoutTrailingDotSpace = baseName.replace(/[. ]+$/, '');\n const hadTrailingDotSpace = withoutTrailingDotSpace !== baseName;\n if (hadTrailingDotSpace) {\n baseName = withoutTrailingDotSpace || 'entity';\n }\n\n const windowsReserved = isWindowsReservedName(baseName);\n const needsSuffix =\n baseName !== value || sanitized.length > MAX_BASE || hadTrailingDotSpace || windowsReserved;\n\n if (!needsSuffix) return baseName;\n\n const suffix = `-${shortHash(value)}`;\n return `${baseName}${suffix}`;\n}\n\n/** Sanitize a fact/task id for use as a concept filename (without .md). */\nexport function sanitizeConceptId(id: string): string {\n const sanitized = sanitizeForFilename(id);\n if (OKF_RESERVED_CONCEPT_NAMES.has(sanitized.toLowerCase())) {\n return `${sanitized}-${shortHash(id)}`;\n }\n return sanitized;\n}\n","import type { MemoryDump, FormattedMemoryDump, MemoryBundle, WikiFact, WikiTask, WikiEvent } from '../types';\nimport { sanitizeForFilename } from './sanitizeForFilename';\n\nfunction renderFact(f: WikiFact): string {\n const tags = (f.tags || []).join(', ');\n const source = f.source_ref ?? f.source_type;\n return `### ${f.title}\n**Tags:** ${tags}\n**Confidence:** ${f.confidence}\n**Source:** ${source}\n\n${f.body}\n\n---\n`;\n}\n\nfunction renderTask(t: WikiTask): string {\n const checked = t.status === 'done' ? 'x' : ' ';\n const note = t.status === 'done' ? ' (done)'\n : t.status === 'abandoned' ? ' (abandoned)'\n : t.status === 'in_progress' ? ' (in progress)'\n : '';\n return `- [${checked}] ${t.description}${note}\\n`;\n}\n\nfunction renderEvent(e: WikiEvent): string {\n const ts = new Date(e.created_at).toISOString();\n return `- [${ts}] (${e.event_type}) ${e.summary}\\n`;\n}\n\nfunction renderEntity(entityId: string, bundle: MemoryBundle, generatedAt: number): string {\n const lines: string[] = [];\n lines.push(`# Memory Dump: ${entityId}`);\n lines.push(`Generated: ${new Date(generatedAt).toISOString()}`);\n lines.push('');\n lines.push('## Facts');\n lines.push('');\n if (bundle.facts.length === 0) {\n lines.push('_(none)_\\n');\n } else {\n for (const f of bundle.facts) lines.push(renderFact(f));\n }\n lines.push('## Tasks');\n lines.push('');\n if (bundle.tasks.length === 0) {\n lines.push('_(none)_\\n');\n } else {\n for (const t of bundle.tasks) lines.push(renderTask(t));\n }\n lines.push('');\n lines.push('## Recent Events');\n lines.push('');\n if (bundle.events.length === 0) {\n lines.push('_(none)_\\n');\n } else {\n for (const e of bundle.events) lines.push(renderEvent(e));\n }\n return lines.join('\\n');\n}\n\nfunction formatEntityFileName(entityId: string): string {\n return `${sanitizeForFilename(entityId)}.md`;\n}\n\nexport function formatMemoryDump(dump: MemoryDump): FormattedMemoryDump {\n const files = Object.entries(dump.entities).map(([entityId, bundle]) => ({\n name: formatEntityFileName(entityId),\n content: renderEntity(entityId, bundle, dump.generatedAt),\n }));\n\n // Strip embedding_blob from each fact before JSON-serialising the manifest.\n // exportDump() now includes raw Uint8Array blobs for importDump() round-trips,\n // but those binaries serve no purpose in a human-readable manifest and can\n // massively inflate its size for non-trivial datasets.\n const manifestDump: MemoryDump = {\n generatedAt: dump.generatedAt,\n entities: Object.fromEntries(\n Object.entries(dump.entities).map(([entityId, bundle]) => [\n entityId,\n {\n ...bundle,\n facts: bundle.facts.map(f => {\n const { embedding_blob: _blob, ...rest } = f as WikiFact & { embedding_blob?: unknown };\n return rest as WikiFact;\n }),\n },\n ])\n ),\n };\n\n return {\n manifest: JSON.stringify(manifestDump, null, 2),\n files,\n };\n}\n","import type { MemoryDump, WikiEdge, WikiFact, WikiTask, WikiEvent } from '../types';\nimport {\n appendEventIdComment,\n appendRelatedSection,\n buildConceptDocument,\n buildEntityIndexMd,\n buildRootIndexMd,\n buildLogMd,\n serializeActorString,\n type OkfFile,\n type OkfFrontmatter,\n type OkfIndexEntry,\n type OkfIndexSection,\n type OkfLogEntry,\n} from '@equationalapplications/core-okf';\nimport { sanitizeConceptId, sanitizeForFilename } from './sanitizeForFilename';\n\nexport type OkfFormatProfile = 'llm-wiki/1' | 'llm-wiki/2';\n\nexport interface FormatOkfBundleOptions {\n /** Defaults to 'llm-wiki/2'. Pass 'llm-wiki/1' to force the v0.1 subset. */\n profile?: OkfFormatProfile;\n}\n\nconst DEFAULT_PROFILE: OkfFormatProfile = 'llm-wiki/2';\n\n/**\n * Format an epoch-ms timestamp as ISO 8601 with a double fallback:\n * 1. NaN / Infinity / non-finite -> epoch (0).\n * 2. Outside JS Date's representable range (e.g. 1e300) -> epoch.\n * `new Date(finite).toISOString()` throws RangeError only when the value is\n * outside the supported range; a finite but absurd number still throws. We\n * validate the constructed Date before calling toISOString so the helper\n * never aborts the bundle export.\n */\nfunction isoOrFallback(updatedAt: number): string {\n if (!Number.isFinite(updatedAt)) return new Date(0).toISOString();\n const d = new Date(updatedAt);\n if (!Number.isFinite(d.getTime())) return new Date(0).toISOString();\n return d.toISOString();\n}\n\nfunction isoDateOrOmit(ms: number | null | undefined): string | undefined {\n if (ms == null || !Number.isFinite(ms)) return undefined;\n const d = new Date(ms);\n if (!Number.isFinite(d.getTime())) return undefined;\n return d.toISOString().slice(0, 10);\n}\n\nfunction factFrontmatterV2(f: WikiFact): OkfFrontmatter {\n return {\n type: f.okf_type ?? 'fact',\n title: f.title,\n tags: f.tags,\n // `timestamp` rides along deliberately even on the v0.2 path — a naive\n // consumer that only understands the v0.1 key still gets a readable date\n // without needing flow-mapping support. `generated.at` is the canonical\n // v0.2 field and always wins on import when both are present (spec §2.4).\n timestamp: isoOrFallback(f.updated_at),\n resource: f.source_ref ?? undefined,\n id: f.id,\n entity_id: f.entity_id,\n confidence: f.confidence,\n source_type: f.source_type,\n source_hash: f.source_hash,\n created_at: f.created_at,\n access_count: f.access_count,\n last_accessed_at: f.last_accessed_at,\n deleted_at: f.deleted_at,\n // OKF v0.2\n status: f.lifecycle_status ?? 'stable',\n ...(isoDateOrOmit(f.stale_after) ? { stale_after: isoDateOrOmit(f.stale_after) } : {}),\n // Omit `generated` entirely when there's no actor on record — never\n // fabricate a `generated_by` (mirrors the import side's rule in §4.8:\n // it never invents one either, so export must not manufacture one that\n // would then round-trip back in as if it had always been asserted).\n ...(f.generated_by ? { generated: { by: f.generated_by, at: isoOrFallback(f.updated_at) } } : {}),\n // Omit `verified`/`sources` when empty — an emitted `[]` is not the same\n // shape as an absent key (spec §5.3 derives `unverified` from \"no\n // `verified` key\", not from \"empty `verified` list\").\n ...(f.okf_verified && f.okf_verified.length > 0 ? { verified: f.okf_verified } : {}),\n ...(f.okf_sources && f.okf_sources.length > 0 ? { sources: f.okf_sources } : {}),\n ...(f.okf_usage_window ? { usage_window: f.okf_usage_window } : {}),\n };\n}\n\nfunction taskFrontmatterV2(t: WikiTask): OkfFrontmatter {\n return {\n type: t.okf_type ?? 'task',\n title: t.description,\n timestamp: isoOrFallback(t.updated_at), // see factFrontmatterV2 comment — deliberate back-compat duplication\n id: t.id,\n entity_id: t.entity_id,\n status: t.lifecycle_status ?? 'stable', // OKF v0.2 lifecycle\n execution_status: t.status, // execution state under renamed key\n priority: t.priority,\n created_at: t.created_at,\n resolved_at: t.resolved_at,\n deleted_at: t.deleted_at,\n // OKF v0.2 — symmetric with facts (spec §2.5): stale_after applies to\n // tasks too (a hallucinated task needs a freshness signal as much as a\n // hallucinated fact does).\n ...(isoDateOrOmit(t.stale_after) ? { stale_after: isoDateOrOmit(t.stale_after) } : {}),\n ...(t.generated_by ? { generated: { by: t.generated_by, at: isoOrFallback(t.updated_at) } } : {}),\n ...(t.okf_verified && t.okf_verified.length > 0 ? { verified: t.okf_verified } : {}),\n ...(t.okf_sources && t.okf_sources.length > 0 ? { sources: t.okf_sources } : {}),\n ...(t.okf_usage_window ? { usage_window: t.okf_usage_window } : {}),\n };\n}\n\nfunction factFrontmatterV1(f: WikiFact): OkfFrontmatter {\n return {\n type: f.okf_type ?? 'fact',\n title: f.title,\n tags: f.tags,\n timestamp: isoOrFallback(f.updated_at),\n resource: f.source_ref ?? undefined,\n id: f.id,\n entity_id: f.entity_id,\n confidence: f.confidence,\n source_type: f.source_type,\n source_hash: f.source_hash,\n created_at: f.created_at,\n access_count: f.access_count,\n last_accessed_at: f.last_accessed_at,\n deleted_at: f.deleted_at,\n };\n}\n\nfunction taskFrontmatterV1(t: WikiTask): OkfFrontmatter {\n return {\n type: t.okf_type ?? 'task',\n title: t.description,\n timestamp: isoOrFallback(t.updated_at),\n id: t.id,\n entity_id: t.entity_id,\n status: t.status,\n priority: t.priority,\n created_at: t.created_at,\n resolved_at: t.resolved_at,\n deleted_at: t.deleted_at,\n };\n}\n\nfunction formatLogDate(timestampMs: number): string {\n return new Date(timestampMs).toISOString().slice(0, 10);\n}\n\nfunction conceptRelativePath(sourceFilePath: string, targetFilePath: string): string {\n const sourceDir = sourceFilePath.slice(0, sourceFilePath.lastIndexOf('/'));\n const targetDir = targetFilePath.slice(0, targetFilePath.lastIndexOf('/'));\n const targetName = targetFilePath.slice(targetFilePath.lastIndexOf('/') + 1);\n if (sourceDir === targetDir) return `./${targetName}`;\n if (sourceDir.endsWith('/facts') && targetDir.endsWith('/tasks')) return `../tasks/${targetName}`;\n if (sourceDir.endsWith('/tasks') && targetDir.endsWith('/facts')) return `../facts/${targetName}`;\n return targetFilePath.replace(/^entities\\/[^/]+\\//, '');\n}\n\nfunction buildEventLogEntries(\n events: WikiEvent[],\n factIdToFilename: Map<string, string>,\n): OkfLogEntry[] {\n return events.map(e => {\n const factFilename = e.related_entry_id ? factIdToFilename.get(e.related_entry_id) : undefined;\n const summary = e.summary\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\\[/g, '\\\\[')\n .replace(/\\]/g, '\\\\]')\n .replace(/\\r?\\n/g, ' ');\n\n const text = factFilename\n ? `(${e.event_type}) [${summary}](./facts/${factFilename}.md)`\n : `(${e.event_type}) ${summary}`;\n return { date: formatLogDate(e.created_at), text: appendEventIdComment(text, e.id) };\n });\n}\n\nexport function formatOkfBundle(\n dump: MemoryDump,\n options?: FormatOkfBundleOptions,\n): { files: OkfFile[] } {\n const profile: OkfFormatProfile = options?.profile ?? DEFAULT_PROFILE;\n const okfVersion = profile === 'llm-wiki/2' ? '0.2' : '0.1';\n const factFm = profile === 'llm-wiki/2' ? factFrontmatterV2 : factFrontmatterV1;\n const taskFm = profile === 'llm-wiki/2' ? taskFrontmatterV2 : taskFrontmatterV1;\n\n const files: OkfFile[] = [];\n const rootEntries: OkfIndexEntry[] = [];\n\n for (const [entityId, bundle] of Object.entries(dump.entities)) {\n const dir = sanitizeForFilename(entityId);\n const factIdToFilename = new Map(\n bundle.facts.map(f => [f.id, sanitizeConceptId(f.id)] as const),\n );\n\n const idToConceptPath = new Map<string, string>();\n for (const f of bundle.facts) {\n idToConceptPath.set(f.id, `entities/${dir}/facts/${factIdToFilename.get(f.id)!}.md`);\n }\n for (const t of bundle.tasks) {\n idToConceptPath.set(t.id, `entities/${dir}/tasks/${sanitizeConceptId(t.id)}.md`);\n }\n\n const edgesBySource = new Map<string, WikiEdge[]>();\n for (const edge of bundle.edges ?? []) {\n const group = edgesBySource.get(edge.source_id) ?? [];\n group.push(edge);\n edgesBySource.set(edge.source_id, group);\n }\n\n function relatedLinksFor(sourcePath: string, sourceId: string) {\n return (edgesBySource.get(sourceId) ?? [])\n .map(edge => {\n const targetPath = idToConceptPath.get(edge.target_id);\n if (!targetPath) return null;\n return { edge_type: edge.edge_type, path: conceptRelativePath(sourcePath, targetPath) };\n })\n .filter((link): link is { edge_type: string; path: string } => link != null);\n }\n\n const factEntries: OkfIndexEntry[] = bundle.facts.map(f => ({\n path: `facts/${factIdToFilename.get(f.id)!}.md`,\n title: f.title,\n }));\n for (const f of bundle.facts) {\n const factPath = `entities/${dir}/facts/${factIdToFilename.get(f.id)!}.md`;\n const factBody = appendRelatedSection(f.body, relatedLinksFor(factPath, f.id));\n files.push({\n path: factPath,\n content: buildConceptDocument(factFm(f), factBody),\n });\n }\n\n const taskEntries: OkfIndexEntry[] = bundle.tasks.map(t => ({\n path: `tasks/${sanitizeConceptId(t.id)}.md`,\n title: t.description,\n }));\n for (const t of bundle.tasks) {\n const taskPath = `entities/${dir}/tasks/${sanitizeConceptId(t.id)}.md`;\n const taskBody = appendRelatedSection('', relatedLinksFor(taskPath, t.id));\n files.push({\n path: taskPath,\n content: buildConceptDocument(taskFm(t), taskBody),\n });\n }\n\n files.push({\n path: `entities/${dir}/log.md`,\n content: buildLogMd(buildEventLogEntries(bundle.events, factIdToFilename)),\n });\n\n const entityIndexSections: OkfIndexSection[] = [\n { heading: 'Facts', entries: factEntries },\n { heading: 'Tasks', entries: taskEntries },\n ];\n files.push({\n path: `entities/${dir}/index.md`,\n content: buildEntityIndexMd({\n summary: bundle.summary,\n sections: entityIndexSections,\n }),\n });\n\n rootEntries.push({ path: `entities/${dir}/index.md`, title: entityId });\n }\n\n files.push({\n path: 'index.md',\n content: buildRootIndexMd(\n okfVersion,\n rootEntries.length > 0 ? [{ heading: 'Entities', entries: rootEntries }] : [],\n { profile },\n ),\n });\n\n return { files };\n}","import type { MemoryDump, WikiFact, WikiTask, WikiEvent, WikiEdge } from '../types';\nimport type { OkfFile, OkfFrontmatter, OkfFrontmatterValue } from '@equationalapplications/core-okf';\nimport {\n parseConcept,\n parseLogMd,\n parseRootIndexMd,\n parseEntityIndexMd,\n parseEventIdComment,\n splitRelatedSection,\n isAllowedOkfPath,\n extractMarkdownLinks,\n parseVerifiedFlexible,\n parseCitationsList,\n latestVerified,\n formatVerifiedJson,\n formatSourcesJson,\n type OkfSource,\n type OkfVerified,\n} from '@equationalapplications/core-okf';\nimport { generateId } from './ids';\n\nexport interface OkfImportOptions {\n typeMapping?: Record<string, 'fact' | 'task' | 'ignore'>;\n defaultSchema?: 'fact' | 'task' | 'ignore';\n}\n\ntype Route = 'fact' | 'task' | 'ignore';\n\nconst CONFIDENCE_VALUES = new Set(['certain', 'inferred', 'tentative']);\nconst SOURCE_TYPES = new Set([\n 'user_stated',\n 'librarian_inferred',\n 'user_confirmed',\n 'immutable_document',\n]);\nconst TASK_STATUSES = new Set(['pending', 'in_progress', 'done', 'abandoned']);\nconst EVENT_TYPES = new Set(['observation', 'decision', 'action', 'outcome']);\n\nfunction basenameMd(filePath: string): string {\n const name = filePath.slice(filePath.lastIndexOf('/') + 1);\n return name.endsWith('.md') ? name.slice(0, -3) : name;\n}\n\nfunction isConceptFile(filePath: string): boolean {\n if (!filePath.endsWith('.md')) return false;\n if (filePath.endsWith('/index.md') || filePath === 'index.md') return false;\n if (filePath.endsWith('/log.md') || filePath === 'log.md') return false;\n return true;\n}\n\nfunction isStructuralPath(filePath: string): boolean {\n return (\n filePath.endsWith('/index.md') ||\n filePath === 'index.md' ||\n filePath.endsWith('/log.md') ||\n filePath === 'log.md'\n );\n}\n\nfunction posixDirname(filePath: string): string {\n const idx = filePath.lastIndexOf('/');\n return idx === -1 ? '' : filePath.slice(0, idx);\n}\n\nfunction resolveRelativePath(fromFile: string, linkPath: string): string {\n const baseDir = posixDirname(fromFile);\n const segments = [...(baseDir ? baseDir.split('/') : []), ...linkPath.split('/')];\n const resolved: string[] = [];\n for (const seg of segments) {\n if (seg === '' || seg === '.') continue;\n if (seg === '..') {\n resolved.pop();\n continue;\n }\n resolved.push(seg);\n }\n return resolved.join('/');\n}\n\nfunction decodeLinkPath(path: string): string {\n if (!path.includes('%')) return path;\n try {\n return decodeURIComponent(path);\n } catch {\n return path;\n }\n}\n\nfunction addPathAliases(map: Map<string, string>, filePath: string, resolvedId: string): void {\n map.set(filePath, resolvedId);\n const withoutDot = filePath.replace(/^\\.\\//, '');\n if (withoutDot !== filePath) map.set(withoutDot, resolvedId);\n const entityRelative = filePath.replace(/^entities\\/[^/]+\\//, '');\n if (entityRelative !== filePath) {\n map.set(entityRelative, resolvedId);\n map.set(`./${entityRelative}`, resolvedId);\n }\n}\n\nfunction lookupResolvedId(map: Map<string, string>, path: string): string | undefined {\n const normalized = path.replace(/^\\.\\//, '');\n return map.get(path) ?? map.get(normalized) ?? map.get(`./${normalized}`);\n}\n\nfunction stripLinkSuffix(linkPath: string): string {\n const hashIdx = linkPath.indexOf('#');\n const queryIdx = linkPath.indexOf('?');\n if (hashIdx === -1 && queryIdx === -1) return linkPath;\n const cut =\n hashIdx === -1 ? queryIdx : queryIdx === -1 ? hashIdx : Math.min(hashIdx, queryIdx);\n return linkPath.slice(0, cut);\n}\n\nfunction resolveRoute(filePath: string, frontmatterType: string, options?: OkfImportOptions): Route {\n if (\n options?.typeMapping &&\n Object.prototype.hasOwnProperty.call(options.typeMapping, frontmatterType)\n ) {\n return options.typeMapping[frontmatterType]!;\n }\n if (filePath.includes('/facts/')) return 'fact';\n if (filePath.includes('/tasks/')) return 'task';\n return options?.defaultSchema ?? 'fact';\n}\n\nfunction parseFrontmatterTimestamp(value: OkfFrontmatterValue | undefined, fallback: number): number {\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n if (typeof value === 'string') {\n const parsed = Date.parse(value);\n if (Number.isFinite(parsed)) return parsed;\n }\n return fallback;\n}\n\n/**\n * Parse an OKF v0.2 `stale_after` YYYY-MM-DD wire string into an epoch ms\n * value. Returns null on non-string, regex mismatch, or a calendar-invalid\n * date — the previous inline regex accepted any three numeric components, so\n * `2026-13-45` would yield NaN and crash the SQLite bind downstream.\n */\nfunction parseStaleAfterRaw(raw: unknown): number | null {\n if (typeof raw !== 'string') return null;\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(raw);\n if (!m) return null;\n const year = Number(m[1]);\n const month = Number(m[2]);\n const day = Number(m[3]);\n const ms = Date.UTC(year, month - 1, day);\n if (!Number.isFinite(ms)) return null;\n // Reject calendar-invalid dates that Date.UTC silently normalizes (e.g.\n // 2025-02-29 → 2025-03-01). Compare the round-tripped components.\n const d = new Date(ms);\n if (\n d.getUTCFullYear() !== year ||\n d.getUTCMonth() + 1 !== month ||\n d.getUTCDate() !== day\n ) {\n return null;\n }\n return ms;\n}\n\nfunction unescapeLogSummary(summary: string): string {\n return summary.replace(/\\\\\\]/g, ']').replace(/\\\\\\[/g, '[').replace(/\\\\\\\\/g, '\\\\');\n}\n\nconst LOG_LINE_PATTERN = /^\\(([^)]+)\\)\\s*(?:\\[((?:\\\\.|[^\\]])*)\\]\\(([^)]+)\\)|(.+))$/;\n\nfunction parseLogEntryText(text: string): {\n event_type: WikiEvent['event_type'];\n summary: string;\n linkPath?: string;\n} | null {\n const match = LOG_LINE_PATTERN.exec(text.trim());\n if (!match) return null;\n const [, rawType, linkedSummary, linkPath, plainSummary] = match;\n const event_type = EVENT_TYPES.has(rawType) ? (rawType as WikiEvent['event_type']) : 'observation';\n if (linkPath) {\n return { event_type, summary: unescapeLogSummary(linkedSummary), linkPath };\n }\n return { event_type, summary: (plainSummary ?? '').trim() };\n}\n\nfunction frontmatterToFact(\n entityId: string,\n id: string,\n frontmatter: OkfFrontmatter,\n body: string,\n now: number,\n): WikiFact {\n const created_at = parseFrontmatterTimestamp(frontmatter.created_at, now);\n // Precedence (spec §2.4): v0.2 `generated.at` -> v0.1 `timestamp` -> legacy\n // `updated_at` -> `now`. The previous order swapped `updated_at` ahead of\n // the other two, so a present-but-finite `updated_at` clobbered\n // `generated.at`. We nest the fallbacks so the first finite wins.\n const updated_at = parseFrontmatterTimestamp(\n (frontmatter as any).generated?.at,\n parseFrontmatterTimestamp(\n frontmatter.timestamp,\n parseFrontmatterTimestamp(frontmatter.updated_at, now),\n ),\n );\n\n const verified: OkfVerified = parseVerifiedFlexible((frontmatter as any).verified);\n const rawSources = (frontmatter as any).sources;\n const hasSourcesKey = rawSources !== undefined;\n const sources: OkfSource[] = Array.isArray(rawSources) ? rawSources as OkfSource[] : [];\n const usageWindow = (frontmatter as any).usage_window && typeof (frontmatter as any).usage_window === 'object'\n ? (frontmatter as any).usage_window as { from: string; to: string }\n : null;\n const lastV = latestVerified(verified, now);\n const lifecycleRaw = (frontmatter as any).status;\n const lifecycle_status: 'draft' | 'stable' | 'deprecated' =\n lifecycleRaw === 'draft' || lifecycleRaw === 'stable' || lifecycleRaw === 'deprecated'\n ? lifecycleRaw : 'stable';\n const staleAfterRaw = (frontmatter as any).stale_after;\n const stale_after = parseStaleAfterRaw(staleAfterRaw);\n const generated_by = (frontmatter as any).generated?.by ?? null;\n\n // Spec §13.1 fallback (applies to v0.1, profile-0, AND v0.2 paths): body\n // `# Citations` -> synthetic sources, one entry per URL. The fallback only\n // fires when the `sources` key is ABSENT — a bundle that explicitly declares\n // `sources: []` (an author clearing provenance) MUST NOT have body citations\n // silently synthesized back into it. `hasSourcesKey` distinguishes absent\n // from explicitly-empty.\n if (!hasSourcesKey) {\n const urls = parseCitationsList(body);\n for (const url of urls) {\n sources.push({ resource: url });\n }\n }\n\n return {\n id,\n entity_id: entityId,\n title: typeof frontmatter.title === 'string' ? frontmatter.title : '',\n body,\n tags: Array.isArray(frontmatter.tags)\n ? frontmatter.tags.filter((t): t is string => typeof t === 'string')\n : [],\n confidence: CONFIDENCE_VALUES.has(String(frontmatter.confidence))\n ? (frontmatter.confidence as WikiFact['confidence'])\n : 'tentative',\n source_type: SOURCE_TYPES.has(String(frontmatter.source_type))\n ? (frontmatter.source_type as WikiFact['source_type'])\n : 'user_stated',\n source_hash: typeof frontmatter.source_hash === 'string' ? frontmatter.source_hash : null,\n source_ref: typeof frontmatter.resource === 'string' ? frontmatter.resource : null,\n created_at,\n updated_at,\n last_accessed_at:\n frontmatter.last_accessed_at != null\n ? parseFrontmatterTimestamp(frontmatter.last_accessed_at, now)\n : null,\n access_count: typeof frontmatter.access_count === 'number' ? frontmatter.access_count : 0,\n deleted_at:\n frontmatter.deleted_at != null ? parseFrontmatterTimestamp(frontmatter.deleted_at, 0) : null,\n okf_type: frontmatter.type,\n // OKF v0.2\n lifecycle_status,\n stale_after,\n generated_by,\n okf_sources: sources,\n okf_verified: verified,\n okf_usage_window: usageWindow,\n last_verified_at: lastV?.at ?? null,\n last_verified_by: lastV?.by ?? null,\n };\n}\n\nfunction frontmatterToTask(\n entityId: string,\n id: string,\n frontmatter: OkfFrontmatter,\n now: number,\n // Treat profile-1 explicit and version-only legacy the same: in both cases\n // `status` on the wire is the v0.1 execution state. Profile-2 (and unknown\n // profile with okf_version 0.2) uses the v0.2 rename rule.\n usesV1StatusRule: boolean,\n): WikiTask {\n const created_at = parseFrontmatterTimestamp(frontmatter.created_at, now);\n // Precedence (spec §2.4) — same nested-fallback chain as frontmatterToFact.\n const updated_at = parseFrontmatterTimestamp(\n (frontmatter as any).generated?.at,\n parseFrontmatterTimestamp(\n frontmatter.timestamp,\n parseFrontmatterTimestamp(frontmatter.updated_at, now),\n ),\n );\n\n const verified: OkfVerified = parseVerifiedFlexible((frontmatter as any).verified);\n const sources: OkfSource[] = Array.isArray((frontmatter as any).sources) ? (frontmatter as any).sources as OkfSource[] : [];\n const usageWindow = (frontmatter as any).usage_window && typeof (frontmatter as any).usage_window === 'object'\n ? (frontmatter as any).usage_window as { from: string; to: string }\n : null;\n const lastV = latestVerified(verified, now);\n const lifecycleRaw = (frontmatter as any).status;\n const lifecycle_status: 'draft' | 'stable' | 'deprecated' =\n lifecycleRaw === 'draft' || lifecycleRaw === 'stable' || lifecycleRaw === 'deprecated'\n ? lifecycleRaw : 'stable';\n // stale_after is symmetric with facts (spec §2.5) — parsed the same way,\n // not hardcoded to null.\n const staleAfterRaw = (frontmatter as any).stale_after;\n const stale_after = parseStaleAfterRaw(staleAfterRaw);\n\n // Status rename rule (spec §2.3):\n // - v0.2: wire `status` = lifecycle (already in lifecycle_status above);\n // wire `execution_status` = execution -> `task.status`.\n // - v0.1 / profile 0: wire `status` = execution -> `task.status`; lifecycle\n // is implicit 'stable'. Profile-1 bundles are explicit about being v0.1\n // (`profile: llm-wiki/1`); profile-0 (no profile key, `okf_version: 0.1`)\n // is the version-only fallback; both MUST use the v0.1 rule.\n const executionRaw = (frontmatter as any).execution_status;\n let executionState: WikiTask['status'];\n if (usesV1StatusRule) {\n executionState = TASK_STATUSES.has(String(frontmatter.status))\n ? (frontmatter.status as WikiTask['status']) : 'pending';\n } else {\n // v0.2 (or unknown profile — best-effort per spec §6 \"profile key unknown\").\n executionState = TASK_STATUSES.has(String(executionRaw))\n ? (executionRaw as WikiTask['status'])\n : TASK_STATUSES.has(String(frontmatter.status))\n ? (frontmatter.status as WikiTask['status'])\n : 'pending';\n }\n\n return {\n id,\n entity_id: entityId,\n description: typeof frontmatter.title === 'string' ? frontmatter.title : '',\n status: executionState,\n priority: typeof frontmatter.priority === 'number' ? frontmatter.priority : 0,\n created_at,\n updated_at,\n resolved_at:\n frontmatter.resolved_at != null\n ? parseFrontmatterTimestamp(frontmatter.resolved_at, now)\n : null,\n deleted_at:\n frontmatter.deleted_at != null ? parseFrontmatterTimestamp(frontmatter.deleted_at, 0) : null,\n okf_type: frontmatter.type,\n // OKF v0.2\n lifecycle_status,\n stale_after,\n generated_by: (frontmatter as any).generated?.by ?? null,\n okf_sources: sources,\n okf_verified: verified,\n okf_usage_window: usageWindow,\n last_verified_at: lastV?.at ?? null,\n last_verified_by: lastV?.by ?? null,\n };\n}\n\nfunction findLogMdPath(files: OkfFile[]): string | undefined {\n return files.find(f => f.path.endsWith('/log.md') || f.path === 'log.md')?.path;\n}\n\nfunction extractEdgesFromLinks(\n filePath: string,\n resolvedId: string,\n links: Array<{ text: string; path: string }>,\n pathToResolvedId: Map<string, string>,\n entityId: string,\n now: number,\n seenEdges: Set<string>,\n edges: WikiEdge[],\n): void {\n for (const link of links) {\n const strippedPath = stripLinkSuffix(decodeLinkPath(link.path));\n const directTargetId = lookupResolvedId(pathToResolvedId, strippedPath);\n const resolvedTargetPath = resolveRelativePath(filePath, strippedPath);\n if (isStructuralPath(strippedPath) || isStructuralPath(resolvedTargetPath)) continue;\n const targetId = directTargetId ?? lookupResolvedId(pathToResolvedId, resolvedTargetPath);\n if (!targetId) continue;\n const edgeKey = `${resolvedId}\\u0000${targetId}\\u0000${link.text}`;\n if (seenEdges.has(edgeKey)) continue;\n seenEdges.add(edgeKey);\n edges.push({\n id: generateId(),\n entity_id: entityId,\n source_id: resolvedId,\n target_id: targetId,\n edge_type: link.text,\n created_at: now,\n });\n }\n}\n\nexport function parseOkfBundle(\n entityId: string,\n files: OkfFile[],\n options?: OkfImportOptions,\n): MemoryDump {\n const now = Date.now();\n const normalizeOkfPath = (p: string) => p.replace(/^\\.\\//, '').replace(/\\\\/g, '/');\n\n const normalizedFiles = files.map(f => ({ ...f, path: normalizeOkfPath(f.path) }));\n\n const allowlistedFiles = normalizedFiles.filter(f => isAllowedOkfPath(f.path));\n\n const entityDirs = new Set(\n allowlistedFiles\n .map(f => /^entities\\/([^/]+)\\//.exec(f.path)?.[1])\n .filter((dir): dir is string => !!dir),\n );\n if (entityDirs.size > 1) {\n throw new Error(\n `parseOkfBundle: expected a single-entity bundle for \"${entityId}\", found entities: ${Array.from(entityDirs).join(', ')}`,\n );\n }\n const entityDir = entityDirs.values().next().value ?? entityId;\n const entityPrefix = `entities/${entityDir}/`;\n\n const allowedFiles = allowlistedFiles.filter(\n f => f.path === 'index.md' || f.path.startsWith(entityPrefix),\n );\n const rootIndex = allowedFiles.find(f => f.path === 'index.md');\n const profileMeta = rootIndex ? parseRootIndexMd(rootIndex.content) : {};\n const okfVersion = profileMeta.okf_version;\n const profile = profileMeta.profile;\n const isProfile1 = profile === 'llm-wiki/1';\n const isProfile2 = profile === 'llm-wiki/2';\n const isLegacyV1 = profile === undefined && okfVersion === '0.1';\n\n // Entity summary is a profile >= 1 feature (§4 of the profile doc). The\n // documented detection order (§4.8 detection plan) names four v0.1 and v0.2\n // entry points: explicit profile, version-only v0.1, version-only v0.2, and\n // unknown-profile v0.2 (best-effort). All four should pick up the summary.\n const isVersionOnlyV2 = profile === undefined && okfVersion === '0.2';\n const isUnknownProfileV2 = profile !== undefined && profile !== 'llm-wiki/1' && profile !== 'llm-wiki/2' && okfVersion === '0.2';\n const summaryEligible = isProfile1 || isProfile2 || isLegacyV1 || isVersionOnlyV2 || isUnknownProfileV2;\n let entitySummary: string | undefined;\n const entityIndex = allowedFiles.find(f => f.path === `${entityPrefix}index.md`);\n if (summaryEligible && entityIndex) {\n const summary = parseEntityIndexMd(entityIndex.content).summary;\n entitySummary = summary || undefined;\n }\n\n const pathToResolvedId = new Map<string, string>();\n\n for (const file of allowedFiles) {\n if (!isConceptFile(file.path)) continue;\n const { frontmatter } = parseConcept(file.content);\n const route = resolveRoute(file.path, frontmatter.type ?? '', options);\n if (route === 'ignore') continue;\n const resolvedId =\n typeof frontmatter.id === 'string' && frontmatter.id ? frontmatter.id : basenameMd(file.path);\n addPathAliases(pathToResolvedId, file.path, resolvedId);\n }\n\n const facts: WikiFact[] = [];\n const tasks: WikiTask[] = [];\n const edges: WikiEdge[] = [];\n let logContent: string | null = null;\n const logMdPath = findLogMdPath(allowedFiles);\n\n for (const file of allowedFiles) {\n if (file.path.endsWith('/log.md') || file.path === 'log.md') {\n logContent = file.content;\n continue;\n }\n if (!isConceptFile(file.path)) continue;\n\n const { frontmatter, body } = parseConcept(file.content);\n const route = resolveRoute(file.path, frontmatter.type ?? '', options);\n if (route === 'ignore') continue;\n\n const resolvedId =\n typeof frontmatter.id === 'string' && frontmatter.id ? frontmatter.id : basenameMd(file.path);\n\n const { body: storedBody, relatedLinks } = splitRelatedSection(body);\n const edgeLinks = (isProfile1 || isLegacyV1)\n ? relatedLinks\n : [...relatedLinks, ...extractMarkdownLinks(storedBody)];\n\n // Task status rename rule (spec §2.3) — v0.1 wire uses `status` as\n // execution state; v0.2 wire uses `status` as lifecycle and adds\n // `execution_status`. The flag we pass below is true when we are NOT\n // reading this task as a v0.2-style bundle.\n const usesV1StatusRule = isProfile1 || isLegacyV1 || (profile === undefined && okfVersion === undefined);\n\n if (route === 'fact') {\n facts.push(frontmatterToFact(entityId, resolvedId, frontmatter, storedBody, now));\n } else {\n tasks.push(frontmatterToTask(entityId, resolvedId, frontmatter, now, usesV1StatusRule));\n }\n\n const seenEdges = new Set<string>();\n extractEdgesFromLinks(\n file.path,\n resolvedId,\n edgeLinks,\n pathToResolvedId,\n entityId,\n now,\n seenEdges,\n edges,\n );\n }\n\n const events: WikiEvent[] = [];\n if (logContent != null) {\n const logPath = logMdPath ?? `entities/${entityId}/log.md`;\n for (const entry of parseLogMd(logContent)) {\n const { text, eventId } = parseEventIdComment(entry.text);\n const parsed = parseLogEntryText(text);\n if (!parsed) continue;\n let related_entry_id: string | null = null;\n if (parsed.linkPath) {\n const targetPath = resolveRelativePath(\n logPath,\n stripLinkSuffix(decodeLinkPath(parsed.linkPath)),\n );\n if (!isStructuralPath(targetPath) && targetPath.includes('/facts/')) {\n related_entry_id = lookupResolvedId(pathToResolvedId, targetPath) ?? null;\n }\n }\n const created_at = new Date(`${entry.date}T00:00:00.000Z`).getTime();\n if (!Number.isFinite(created_at)) continue;\n\n events.push({\n id: eventId ?? generateId('evt_'),\n entity_id: entityId,\n event_type: parsed.event_type,\n summary: parsed.summary,\n related_entry_id,\n created_at,\n });\n }\n }\n\n return {\n generatedAt: now,\n entities: {\n [entityId]: { facts, tasks, events, edges, summary: entitySummary },\n },\n };\n}\n","import type { ReadOptions } from './types';\n\nexport interface LibrarianOptions {\n /** If provided, replaces the default Librarian system instructions. */\n systemPrompt?: string;\n /** entity_id -> score multiplier, forwarded to WikiMemory.read() as tierWeights. */\n entityWeights?: Record<string, number>;\n /** Forwarded to WikiMemory.read() for zero-weight filler context. */\n includeZeroWeightEntities?: boolean;\n temperature?: number;\n}\n\nexport interface LibrarianPromptVariables {\n context: string;\n tasks: string;\n query: string;\n}\n\nexport const DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT = `You are a careful memory synthesis assistant.\nUse only the retrieved context when answering the request.\nPreserve source provenance when facts come from different entity namespaces.\n\nRequest:\n{{query}}\n\nRetrieved context:\n{{context}}\n\nOpen tasks:\n{{tasks}}`;\n\nexport function hydrateLibrarianPrompt(\n template: string,\n variables: LibrarianPromptVariables,\n): string {\n return template.replace(/\\{\\{(context|tasks|query)\\}\\}/g, (_, key) => variables[key as keyof LibrarianPromptVariables]);\n}\n\nexport function validateLibrarianPromptTemplate(\n template: string,\n options: { custom: boolean; taskCount: number },\n): string[] {\n if (!options.custom) return [];\n\n const warnings: string[] = [];\n if (!template.includes('{{context}}')) {\n warnings.push('Custom Librarian systemPrompt omits {{context}}; retrieved memory will not be injected.');\n }\n if (!template.includes('{{query}}')) {\n warnings.push('Custom Librarian systemPrompt omits {{query}}; the original request will not be injected.');\n }\n if (options.taskCount > 0 && !template.includes('{{tasks}}')) {\n warnings.push('Custom Librarian systemPrompt omits {{tasks}} while retrieved tasks are available.');\n }\n return warnings;\n}\n\nexport function mapLibrarianOptionsToReadOptions(\n options: LibrarianOptions,\n): Pick<ReadOptions, 'tierWeights' | 'includeZeroWeightEntities'> {\n const readOptions: Pick<ReadOptions, 'tierWeights' | 'includeZeroWeightEntities'> = {};\n if (options.entityWeights !== undefined) readOptions.tierWeights = options.entityWeights;\n if (options.includeZeroWeightEntities !== undefined) {\n readOptions.includeZeroWeightEntities = options.includeZeroWeightEntities;\n }\n return readOptions;\n}\n","import { WikiMemory } from './WikiMemory';\nimport type { SQLiteAdapter, WikiOptions } from './types';\n\nexport * from './types';\nexport type { WikiOutboxEvent } from './outbox/types';\nexport { WikiMemory } from './WikiMemory';\nexport type { WikiMemoryTestAccess } from './WikiMemory';\nexport { formatContext } from './utils/formatContext';\nexport { formatGraphContext } from './utils/formatGraphContext';\nexport { formatMemoryDump } from './utils/formatMemoryDump';\nexport { formatOkfBundle, type FormatOkfBundleOptions, type OkfFormatProfile } from './utils/formatOkfBundle';\nexport { parseOkfBundle, type OkfImportOptions } from './utils/parseOkfBundle';\nexport { parseEmbedding } from './utils/embedding';\nexport { validateManifest } from './utils/ontology';\nexport { configureRandomSource } from './utils/ids';\nexport { chunkText, safeSlice } from './utils/pure';\nexport { DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_CHUNK_OVERLAP } from './utils/chunkingDefaults';\nexport { DEFAULT_MAX_EMBED_CHARS, EMBED_CHARS_CEILING } from './utils/embedDefaults';\nexport * from './librarianPrompt';\nexport { PromptService } from './services/PromptService';\nexport type { EmbedFactResult, EmbedFailureKind } from './services/EmbeddingService';\nexport {\n ONTOLOGY_BACKFILL_BATCH_SIZE,\n ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS,\n ONTOLOGY_BACKFILL_RECHECK_MS,\n HEAL_ANCHORS_PER_CANDIDATE,\n HEAL_BATCH_SIZE,\n HEAL_MAX_FACT_BODY_CHARS_L3,\n HEAL_MAX_TASKS,\n HEAL_RECHECK_MS,\n} from './services/MaintenanceService';\nexport { ONTOLOGY_BACKFILL_SYSTEM_PROMPT } from './prompts';\n\nexport function createWiki(db: SQLiteAdapter, options: WikiOptions): WikiMemory {\n return new WikiMemory(db, options);\n}\n"]}
|