@equationalapplications/core-llm-wiki 9.16.2 → 9.17.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/db/migrationGate.ts","../src/db/serializedAdapter.ts","../src/repositories/EntryRepository.ts","../src/repositories/OutboxRepository.ts","../src/repositories/SourceRefIndexRepository.ts","../src/repositories/TaskRepository.ts","../src/repositories/EventRepository.ts","../src/utils/monotonicNow.ts","../src/utils/setupDefaults.ts","../src/services/search/ftsQuery.ts","../src/services/search/Fts5IndexStrategy.ts","../src/services/search/MiniSearchIndexStrategy.ts","../src/services/search/createIndexStrategy.ts","../src/utils/config/ontologyJobDefaults.ts","../src/services/MaintenanceScheduler.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/utils/rememberInput.ts","../src/services/RememberService.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/utils/contextBudget.ts","../src/librarianPrompt.ts","../src/index.ts"],"names":["isStaleAfter","deriveTrustTier","rows","assertEntityId","stashed","relatedLinksFor","CONFIDENCE_VALUES","latestVerified"],"mappings":";;;;;;AAMA,IAAM,kBAAA,GAAiD,CAAC,OAAA,EAAS,QAAA,EAAU,MAAM,CAAA;AASjF,eAAsB,qBAAA,CACpB,EAAA,EACA,MAAA,EACA,IAAA,EACA,aAA8B,OAAA,EACf;AAGf,EAAA,IAAI,CAAC,kBAAA,CAAmB,QAAA,CAAS,UAAU,CAAA,EAAG;AAC5C,IAAA,MAAM,IAAI,SAAA,CAAU,CAAA,0BAAA,EAA6B,KAAK,SAAA,CAAU,UAAU,CAAC,CAAA,uCAAA,CAAyC,CAAA;A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AAC9E,EAAA,OAAO,IAAI,UAAA,CAAW,EAAA,EAAI,OAAO,CAAA;AACnC","file":"index.mjs","sourcesContent":["import type { SQLiteAdapter, MigrationPolicy, PendingMigrationWork } from '../types';\nimport type { MetadataRepository } from '../repositories/MetadataRepository';\nimport { probePendingWork } from './sourceRefNormalize';\nimport { setupDatabase } from './schema';\nimport { WikiMigrationRequiredError } from '../types';\n\nconst MIGRATION_POLICIES: readonly MigrationPolicy[] = ['allow', 'refuse', 'auto'];\n\n/**\n * Runs the read-only migration gate, then setupDatabase's every-open DDL.\n * - 'allow': no gate.\n * - 'refuse': any pending work throws before any mutation.\n * - 'auto': a pending schema migration throws; a pending source_ref normalize\n * is let through and run by setup() after the DDL and migrations loop.\n */\nexport async function setupDatabaseWithGate(\n db: SQLiteAdapter,\n prefix: string,\n meta: MetadataRepository,\n migrations: MigrationPolicy = 'allow',\n): Promise<void> {\n // Fail closed: an unrecognized value (e.g. 'Refuse' from env/JSON config) must not\n // silently skip the refusal and run a migration inside a time-critical open.\n if (!MIGRATION_POLICIES.includes(migrations)) {\n throw new TypeError(`Invalid migrations policy ${JSON.stringify(migrations)}; expected 'allow', 'refuse' or 'auto'.`);\n }\n if (migrations !== 'allow') {\n const pending = await probePendingWork(db, meta, prefix);\n if (pending && (migrations === 'refuse' || pending.type === 'schema_migration')) {\n throw new WikiMigrationRequiredError(describePending(pending, migrations), pending);\n }\n }\n return setupDatabase(db, prefix);\n}\n\nfunction describePending(pending: PendingMigrationWork, policy: MigrationPolicy): string {\n const what = pending.type === 'schema_migration'\n ? `schema migration v${pending.fromVersion} -> v${pending.toVersion} is pending`\n : pending.entriesWatermark === 0 && pending.sourceRefIndexWatermark === 0\n ? 'source_ref normalize has not run on this store (normalize stamp missing or outdated; may complete with zero rewrites)'\n : 'source_ref normalize was interrupted and will resume from its watermark';\n return `Migration refused (migrations: '${policy}'): ${what}. ` +\n `Open once with setup({ migrations: 'allow' }) outside any time-critical path to complete it.`;\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, WikiFact, EmbeddingMarkerKind } from '../types';\nimport { WikiGraphNodeOwnershipConflict } from '../types';\nimport { BaseRepository } from './BaseRepository';\nimport { OutboxRepository } from './OutboxRepository';\nimport { parseJsonArray, parseJsonObject } from './rowMappers';\nimport { reanchorRebuildFingerprint } from '../services/search/fts5Progress';\nimport { liveAtSql, type LiveMode } from '../utils/temporal';\nimport { isStaleAfter, deriveTrustTier } from '@equationalapplications/core-okf';\nimport { parseStoredSourcePointer, serializeSourcePointer } from '../utils/sourcePointer';\nimport { parseStoredDerivedEvents, serializeDerivedEvents } from '../utils/derivedEvents';\n\n/** Subset of temporal columns that {@link EntryRepository.setTemporal} may write (spec 2026-09-29 §4.3). */\nexport type TemporalFields = {\n valid_from?: number | null;\n valid_to?: number | null;\n superseded_by?: string | null;\n superseded_at?: number | null;\n prior_valid_to?: number | null;\n};\n\n/** Lightweight projection used by TemporalService for supersession chain walks. */\nexport type TemporalRow = {\n id: string;\n entity_id: string;\n source_type: WikiFact['source_type'];\n deleted_at: number | null;\n created_at: number;\n valid_from: number | null;\n valid_to: number | null;\n superseded_by: string | null;\n prior_valid_to: number | null;\n};\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 const sourcePointer = parseStoredSourcePointer(row.source_pointer);\n const derivedEvents = parseStoredDerivedEvents(row.derived_events);\n\n const mapped = {\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 // Temporal (spec 2026-09-29 §4, §10.8): keys appear only when set so\n // existing deep-equality assertions and host snapshots are unchanged.\n ...(row.valid_from != null ? { valid_from: Number(row.valid_from) } : {}),\n ...(row.valid_to != null ? { valid_to: Number(row.valid_to) } : {}),\n ...(row.superseded_by != null ? { superseded_by: String(row.superseded_by) } : {}),\n ...(row.superseded_at != null ? { superseded_at: Number(row.superseded_at) } : {}),\n ...(row.prior_valid_to != null ? { prior_valid_to: Number(row.prior_valid_to) } : {}),\n // Source pointer (specs/source-pointers): key appears only when non-null,\n // same temporal-fields pattern. Tolerant read: a malformed stored value\n // reads as null without throwing (test 1).\n ...(sourcePointer ? { source_pointer: sourcePointer } : {}),\n // derived_events (specs/inplace-update-provenance §5): present only when\n // non-empty; a malformed stored value reads as absent without throwing.\n ...(derivedEvents ? { derived_events: derivedEvents } : {}),\n };\n return mapped as WikiFact;\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 /**\n * Column list and liveness predicate shared by findMiniSearchRows and\n * findMiniSearchRowsByIds, so the full rebuild and the incremental read\n * can never drift apart (spec 2026-09-28 §4.4: both must produce\n * identical documents).\n */\n private static readonly MINI_SEARCH_COLUMNS = 'id, entity_id, title, body, tags';\n private static readonly MINI_SEARCH_LIVE_WHERE = 'WHERE deleted_at IS NULL';\n\n private chunkSize = 500;\n\n constructor(db: SQLiteAdapter, prefix: string, private outbox: OutboxRepository) {\n super(db, prefix);\n }\n\n /** Whether the entity has any non-deleted row (librarian gate: keyword ranking over zero facts is trivially empty). */\n async hasLiveEntry(entityId: string, 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 entity_id = ? AND deleted_at IS NULL LIMIT 1`,\n [entityId],\n );\n return row != null;\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 source_pointer: string | null;\n derived_events: 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, source_pointer, derived_events\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, source_pointer, derived_events\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 derived_events = CASE WHEN ? THEN excluded.derived_events ELSE derived_events END\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 serializeSourcePointer(fact.source_pointer),\n serializeDerivedEvents(fact.derived_events),\n // derived_events is writable on conflict (the librarian's in-place\n // UPDATE merges events into it), but only when the caller supplied the\n // key: an undefined key leaves a stored list untouched.\n fact.derived_events !== undefined ? 1 : 0,\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 — and source_pointer\n // (insert-only rule, specs/source-pointers §Writes) — so the prior row\n // values win. Re-read those columns from the stored row and overlay them\n // onto the caller-supplied payload before publishing (#90 review; the\n // stored pointer publishes instead of a fabricated null).\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 source_pointer: parseStoredSourcePointer(existingRow.source_pointer),\n ...(fact.derived_events === undefined\n ? (() => {\n const stored = parseStoredDerivedEvents(existingRow.derived_events);\n return stored ? { derived_events: stored } : {};\n })()\n : {}),\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; deleted_at: number | null }>> {\n const executor = this.getExecutor(tx);\n const rows: Array<{ id: string; entity_id: string; updated_at: number; deleted_at: number | 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<any>(\n `SELECT id, entity_id, updated_at, deleted_at FROM ${this.prefix}entries WHERE id IN (${placeholders})`,\n chunk,\n );\n rows.push(...chunkRows.map((row) => ({\n id: row.id,\n entity_id: row.entity_id,\n updated_at: Number(row.updated_at),\n deleted_at: row.deleted_at == null ? null : Number(row.deleted_at),\n })));\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(\n fact: WikiFact,\n tx: SQLiteAdapter,\n sourcePointerPresent = false,\n derivedEventsPresent = false,\n ): 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 // Source pointer (specs/source-pointers §Export, import, and OKF): a\n // static SET list cannot express \"absent means untouched\", so the import\n // path carries a per-row presence flag and the SET clause switches on it.\n // A pre-release dump (flag false) can neither null a stored pointer nor\n // emit a storm of false source_pointer_invalid reports — a deliberate\n // departure from the temporal replace semantics next to it, because a\n // pre-release dump is the exact case this rule exists for. No comments\n // inside the SQL template itself: everything in the backticks is SQL.\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, source_pointer, derived_events\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 source_pointer = CASE WHEN ? THEN excluded.source_pointer ELSE source_pointer END,\n derived_events = CASE WHEN ? THEN excluded.derived_events ELSE derived_events END`,\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 serializeSourcePointer(fact.source_pointer),\n serializeDerivedEvents(fact.derived_events),\n // The presence flag binds to the SET clause's CASE, AFTER the INSERT\n // values above.\n sourcePointerPresent ? 1 : 0,\n // derived_events follows the same presence-flag pattern: a pre-v18\n // dump (no key) never nulls a stored list.\n derivedEventsPresent ? 1 : 0,\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 * Shared JSON match predicate for an event id\n * (specs/forget-by-event-id §D1, widened by specs/inplace-update-provenance\n * §4): a row matches when its `source_pointer` names the event OR its\n * `derived_events` list contains it. Every JSON call sits under its own\n * `json_valid` guard: unguarded JSON functions RAISE on malformed text, and\n * three-valued logic forces evaluation of AND operands after a NULL-guarded\n * term — a two-term form is only as safe as the planner's term-splitting.\n * The `json_each` term additionally requires `json_type = 'array'` (a JSON\n * object or scalar would otherwise iterate its members). The event id binds\n * TWICE (pointer term, then derived_events term); use `eventMatchArgs`.\n * The tombstone guard (`deleted_at IS NULL`) is added per-method.\n */\n static readonly EVENT_MATCH_SQL = `((CASE WHEN json_valid(source_pointer)\n THEN json_type(source_pointer, '$.event_id') = 'text'\n AND json_extract(source_pointer, '$.event_id') = ?\n ELSE 0 END)\n OR\n (CASE WHEN json_valid(derived_events)\n THEN (CASE WHEN json_type(derived_events) = 'array'\n THEN EXISTS (SELECT 1 FROM json_each(derived_events) WHERE json_each.type = 'text' AND json_each.value = ?)\n ELSE 0 END)\n ELSE 0 END))`;\n\n /** Bind values for `EVENT_MATCH_SQL` after an `entity_id = ?` term: the event id twice. */\n static eventMatchArgs(entityId: string, eventId: string): [string, string, string] {\n return [entityId, eventId, eventId];\n }\n\n /** Old name kept as an alias (tests and external references). */\n static readonly POINTER_EVENT_MATCH_SQL = EntryRepository.EVENT_MATCH_SQL;\n\n /**\n * IDs of the entity's entries whose source_pointer names the event id or whose derived_events list contains it.\n * `includeDeleted = true` returns live + tombstoned rows (the forget\n * enumeration superset for index sync and the ledger backstop).\n */\n async findIdsByPointerEvent(\n entityId: string,\n eventId: string,\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 = ? AND ${EntryRepository.POINTER_EVENT_MATCH_SQL}`;\n const args: unknown[] = EntryRepository.eventMatchArgs(entityId, eventId);\n if (!includeDeleted) sql += ` AND deleted_at IS NULL`;\n const rows = await executor.getAllAsync<{ id: string }>(sql, args);\n return rows.map((r) => r.id);\n }\n\n /** Live-row count for the event id — dry-run only (a real call is idempotent over tombstones). */\n async countLiveByPointerEvent(entityId: string, eventId: string, tx?: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ n: number }>(\n `SELECT COUNT(*) AS n FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND ${EntryRepository.POINTER_EVENT_MATCH_SQL}`,\n EntryRepository.eventMatchArgs(entityId, eventId),\n );\n return row?.n ?? 0;\n }\n\n /**\n * Soft-delete the entity's entries whose source_pointer names the event id,\n * within a transaction. Stages a DELETE outbox entry for each row that\n * changed, in the same transaction (parity with softDeleteBySource — synced\n * replicas learn of the tombstones through the outbox). The `deleted_at\n * IS NULL` guard makes the call idempotent: already-tombstoned rows are\n * no-op hits and are not counted. `tx` is REQUIRED.\n * Returns the number of rows deleted.\n */\n async softDeleteByPointerEvent(entityId: string, eventId: string, tx: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n const idsToDelete = await executor.getAllAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND ${EntryRepository.POINTER_EVENT_MATCH_SQL}`,\n EntryRepository.eventMatchArgs(entityId, eventId),\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 AND ${EntryRepository.POINTER_EVENT_MATCH_SQL}`,\n [now, now, ...EntryRepository.eventMatchArgs(entityId, eventId)],\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 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 opts?: { noCutoff?: boolean },\n ): Promise<Array<{ id: string; entity_id: string }>> {\n const executor = this.getExecutor(tx);\n // noCutoff (erase): every soft-deleted row, no timestamp predicate — see\n // getDistinctEntityIds's softDeletedAll note.\n const cutoffPredicate = opts?.noCutoff ? '' : ' AND deleted_at <= ?';\n const args: unknown[] = opts?.noCutoff ? [entityId] : [entityId, cutoff];\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${cutoffPredicate}`,\n args,\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, opts?: { includeDeleted?: boolean }): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n const live = opts?.includeDeleted ? '' : ' AND deleted_at IS NULL';\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries WHERE entity_id = ?${live} 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 now = Date.now();\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 ${liveAtSql('current')}\n AND (heal_checked_at IS NULL OR heal_checked_at <= ?)\n ORDER BY updated_at ASC LIMIT ?`,\n [entityId, now, now, 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 const now = Date.now();\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 ${liveAtSql('current')}\n AND id IN (${placeholders})`,\n [entityId, now, now, ...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 const now = Date.now();\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, now, now, excludeSourceRef, limit] : [entityId, now, now, limit];\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND ${liveAtSql('current')}${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, opts?: { includeDeleted?: boolean }): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n const live = opts?.includeDeleted ? '' : ' AND deleted_at IS NULL';\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries WHERE entity_id = ?${live} 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 opts: { keepUnconfirmedRemovals?: boolean; deletedIds?: string[]; noCutoff?: boolean } = {},\n ): Promise<number> {\n const executor = this.getExecutor(tx);\n // Spec durable-vector-removal §5.6.4: under a removal hook, never hard-delete\n // a fact whose vector-index removal is still owed.\n const guard = opts.keepUnconfirmedRemovals\n ? ` AND NOT EXISTS (SELECT 1 FROM ${this.prefix}vector_removals v WHERE v.fact_id = ${this.prefix}entries.id AND v.confirmed_at IS NULL)`\n : '';\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 // RETURNING names exactly the rows this statement removed: not a row the\n // guard kept, and not a row that was already gone before it ran. deleted_at\n // rides along so the outbox payload stamps the row's real tombstone time —\n // never the sweep cutoff (erase sweeps with a max cutoff, and a payload\n // stamped Number.MAX_SAFE_INTEGER would be nonsense as a timestamp).\n const cutoffPredicate = opts.noCutoff ? '' : ' AND deleted_at <= ?';\n const delArgs: unknown[] = opts.noCutoff ? [entityId, ...chunk] : [entityId, cutoff, ...chunk];\n const deleted = (await executor.getAllAsync<{ id: string; deleted_at: number }>(\n `DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate} AND id IN (${placeholders})${guard} RETURNING id, deleted_at`,\n delArgs,\n )).map((r) => ({ id: r.id, deleted_at: typeof r.deleted_at === 'number' ? r.deleted_at : Number(r.deleted_at) }));\n totalChanges += deleted.length;\n opts.deletedIds?.push(...deleted.map((r) => r.id));\n // Stage outbox entries for permanently deleted records\n if (deleted.length > 0) {\n for (const row of deleted) {\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: row.deleted_at },\n }, tx);\n }\n }\n }\n // Spec #280 Change 3: an engine hard-delete never strands the FTS rebuild fingerprint.\n if (totalChanges > 0) await reanchorRebuildFingerprint(executor, this.prefix, ids);\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 // RETURNING: a row already soft-deleted keeps its deleted_at, so it gets no\n // outbox event carrying a deleted_at the row doesn't have.\n const updated = await executor.getAllAsync<{ id: string }>(\n `UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE id IN (${placeholders}) AND entity_id = ? AND deleted_at IS NULL RETURNING id`,\n [now, now, ...ids, entityId],\n );\n // Stage outbox entries for soft-deleted records\n for (const { id } of updated) {\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 /** Spec §4: write any subset of the five temporal columns. Absent key = untouched; null = clear. */\n async setTemporal(\n id: string,\n entityId: string,\n fields: TemporalFields,\n tx: SQLiteAdapter,\n opts?: { outbox?: boolean },\n ): Promise<number> {\n const keys = (['valid_from', 'valid_to', 'superseded_by', 'superseded_at', 'prior_valid_to'] as const).filter((k) => k in fields);\n if (keys.length === 0) return 0;\n const executor = this.getExecutor(tx);\n const result = await executor.runAsync(\n `UPDATE ${this.prefix}entries SET ${keys.map((k) => `${k} = ?`).join(', ')} WHERE id = ? AND entity_id = ?`,\n [...keys.map((k) => fields[k] ?? null), id, entityId],\n );\n if (result.changes > 0 && opts?.outbox !== false) {\n const payload: Record<string, unknown> = { id, entity_id: entityId };\n for (const k of keys) payload[k] = fields[k] ?? null;\n await this.outbox.push({ entityId, tableName: 'entries', recordId: id, operation: 'UPDATE', payload }, tx);\n }\n return result.changes;\n }\n\n async findTemporalRow(id: string, tx?: SQLiteAdapter): Promise<TemporalRow | null> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<any>(\n `SELECT id, entity_id, source_type, deleted_at, created_at, valid_from, valid_to, superseded_by, prior_valid_to\n FROM ${this.prefix}entries WHERE id = ?`,\n [id],\n );\n if (!row) return null;\n return {\n id: String(row.id),\n entity_id: String(row.entity_id),\n source_type: row.source_type,\n deleted_at: row.deleted_at != null ? Number(row.deleted_at) : null,\n created_at: Number(row.created_at),\n valid_from: row.valid_from != null ? Number(row.valid_from) : null,\n valid_to: row.valid_to != null ? Number(row.valid_to) : null,\n superseded_by: row.superseded_by != null ? String(row.superseded_by) : null,\n prior_valid_to: row.prior_valid_to != null ? Number(row.prior_valid_to) : null,\n };\n }\n\n /**\n * Ids of non-deleted facts NOT live at `t` (spec §4.2). In 'current' mode a\n * row with both validity columns NULL is always live, so the query is\n * restricted to rows that carry a validity column — served by the partial\n * entries_temporal_idx.\n */\n async findNonLiveIdsByEntityIds(\n entityIds: readonly string[],\n mode: LiveMode,\n t: number,\n tx?: SQLiteAdapter,\n ): 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 temporalOnly = mode === 'current' ? ' AND (valid_from IS NOT NULL OR valid_to IS NOT NULL)' : '';\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${temporalOnly}\n AND NOT ${liveAtSql(mode)}`,\n [...entityIds, t, t],\n );\n return new Set(rows.map((r) => r.id));\n }\n\n /**\n * Depth-aware supersession walk for chain forget (spec forget-erasure §3).\n * Probes `maxDepth + 1` levels so a chain longer than the cap is detectable;\n * the returned ids are capped to `maxDepth` per direction (successors nearest first; predecessors are returned farthest-first).\n * No `deleted_at` filter: soft-deleted links still carry the chain.\n */\n async findSupersessionChainWalk(\n entityId: string,\n factId: string,\n maxDepth: number,\n tx?: SQLiteAdapter,\n ): Promise<{ ids: string[]; truncated: boolean }> {\n const { predecessors, successors } = await this.findSupersessionChainIds(entityId, factId, maxDepth + 1, tx);\n // Cap by row DEPTH, not row count: a node with more than `maxDepth` direct\n // predecessors (all depth 1) is a wide fan-in, not a chain longer than the\n // cap — counting rows would set `truncated` and drop reachable rows.\n const truncated = predecessors.some((r) => r.depth > maxDepth) || successors.some((r) => r.depth > maxDepth);\n // predecessors are ordered farthest-first (ORDER BY depth DESC), so the nearest are at the end.\n const pred = predecessors.filter((r) => r.depth <= maxDepth).map((r) => r.id);\n const succ = successors.filter((r) => r.depth <= maxDepth).map((r) => r.id);\n return { ids: Array.from(new Set([...succ, ...pred])), truncated };\n }\n\n async findSupersessionChainIds(\n entityId: string,\n factId: string,\n maxDepth: number,\n tx?: SQLiteAdapter,\n ): Promise<{ predecessors: Array<{ id: string; depth: number }>; successors: Array<{ id: string; depth: number }> }> {\n const executor = this.getExecutor(tx);\n const successors = await executor.getAllAsync<{ id: string; depth: number }>(\n `WITH RECURSIVE fwd(id, depth) AS (\n SELECT superseded_by, 1 FROM ${this.prefix}entries WHERE id = ? AND entity_id = ? AND superseded_by IS NOT NULL\n UNION\n SELECT e.superseded_by, fwd.depth + 1 FROM fwd\n JOIN ${this.prefix}entries e ON e.id = fwd.id AND e.entity_id = ?\n WHERE e.superseded_by IS NOT NULL AND fwd.depth < ?\n )\n SELECT id, depth FROM fwd ORDER BY depth ASC`,\n [factId, entityId, entityId, maxDepth],\n );\n const predecessors = await executor.getAllAsync<{ id: string; depth: number }>(\n `WITH RECURSIVE bwd(id, depth) AS (\n SELECT id, 1 FROM ${this.prefix}entries WHERE entity_id = ? AND superseded_by = ?\n UNION\n SELECT e.id, bwd.depth + 1 FROM bwd\n JOIN ${this.prefix}entries e ON e.entity_id = ? AND e.superseded_by = bwd.id\n WHERE bwd.depth < ?\n )\n SELECT id, depth FROM bwd ORDER BY depth DESC`,\n [entityId, factId, entityId, maxDepth],\n );\n const drop = (rows: Array<{ id: string; depth: number }>) => rows.filter((r) => r.id !== factId);\n return { predecessors: drop(predecessors), successors: drop(successors) };\n }\n\n async findExpiredIds(entityId: string, cutoff: number, tx?: SQLiteAdapter): Promise<string[]> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL AND valid_to IS NOT NULL AND valid_to <= ?\n ORDER BY valid_to ASC`,\n [entityId, cutoff],\n );\n return rows.map((r) => r.id);\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 ${EntryRepository.MINI_SEARCH_COLUMNS} FROM ${this.prefix}entries ${EntryRepository.MINI_SEARCH_LIVE_WHERE} AND entity_id = ?`,\n [entityId],\n );\n }\n return executor.getAllAsync(\n `SELECT ${EntryRepository.MINI_SEARCH_COLUMNS} FROM ${this.prefix}entries ${EntryRepository.MINI_SEARCH_LIVE_WHERE}`,\n );\n }\n\n /**\n * Keyword-index rows for specific ids — the incremental counterpart of\n * {@link findMiniSearchRows}, with identical columns. Soft-deleted rows and\n * rows of other entities are omitted, so a caller can pass every id a write\n * touched and get back exactly what should be indexed. Spec 2026-09-28 §4.4.\n */\n async findMiniSearchRowsByIds(\n entityId: string,\n ids: readonly string[],\n tx?: SQLiteAdapter,\n ): Promise<Array<{ id: string; entity_id: string; title: string; body: string; tags: string }>> {\n if (ids.length === 0) return [];\n const executor = this.getExecutor(tx);\n const rows: Array<{ id: string; entity_id: string; title: string; body: string; tags: string }> = [];\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 rows.push(...(await executor.getAllAsync<{ id: string; entity_id: string; title: string; body: string; tags: string }>(\n `SELECT ${EntryRepository.MINI_SEARCH_COLUMNS} FROM ${this.prefix}entries ${EntryRepository.MINI_SEARCH_LIVE_WHERE} AND entity_id = ? AND id IN (${placeholders})`,\n [entityId, ...chunk],\n )));\n }\n return rows;\n }\n\n /** Returns `changes: 0` when the row is soft-deleted or gone (spec durable-vector-removal §5.7, G10). */\n async updateEmbeddingBlob(id: string, blob: Uint8Array, tx?: SQLiteAdapter): Promise<{ changes: number }> {\n const executor = this.getExecutor(tx);\n const r = 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 = ? AND deleted_at IS NULL`,\n [blob, id],\n );\n return { changes: r?.changes ?? 0 };\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 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 /** Spec source-store §4 three-state: exact pair / stale hash / nothing stored. */\n stored?: { charCount: number; staleHash?: true } | null;\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 stored_hash: string | null;\n stored_chars: number | null;\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 ranked.source_ref,\n ranked.source_hash AS source_hash,\n ranked.fact_count AS fact_count,\n ranked.updated_at AS last_ingested_at,\n d.source_hash AS stored_hash,\n d.char_count AS stored_chars\n FROM ranked\n LEFT JOIN ${this.prefix}source_documents d\n ON d.entity_id = ? AND d.source_ref = ranked.source_ref\n WHERE ranked.rn = 1\n ORDER BY ranked.source_ref COLLATE BINARY`,\n [entityId, 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 // Spec source-store §4: keyed on the ref's own (sourceRef, sourceHash) pair.\n stored:\n r.stored_hash === null || r.stored_hash === undefined\n ? null\n : r.stored_hash === r.source_hash\n ? { charCount: Number(r.stored_chars) }\n : { charCount: Number(r.stored_chars), staleHash: true as const },\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; live?: { mode: LiveMode; t: number } },\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 liveClause = opts?.live ? ` AND ${liveAtSql(opts.live.mode)}` : '';\n const liveArgs = opts?.live ? [opts.live.t, opts.live.t] : [];\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries WHERE entity_id IN (${placeholders}) AND deleted_at IS NULL${draftClause}${liveClause} ORDER BY updated_at DESC LIMIT ?`,\n [...entityIds, ...liveArgs, 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 * The queue sees CURRENT facts only (ontology-curation Task 10): rows whose\n * validity window excludes \"now\" are invisible to typing, matching the\n * read-time liveness definition (utils/temporal.ts).\n */\n async findUntypedByEntityId(entityId: string, limit: number, recheckCutoff: number, tx?: SQLiteAdapter): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n // Validity is evaluated at the current sample time, NOT at recheckCutoff:\n // a fact that became live after the cutoff must still queue, and one that\n // expired since must not (CodeRabbit #441, EntryRepository:1813).\n const now = Date.now();\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 AND ${liveAtSql('current')}\n ORDER BY updated_at ASC LIMIT ?`,\n [entityId, recheckCutoff, now, now, limit],\n );\n return rows.map(mapRowToFact);\n }\n\n /** Counts live untyped facts: eligible (past cooldown) vs deferred (in cooldown). Current facts only, as {@link findUntypedByEntityId}. */\n async countUntypedByEntityId(entityId: string, recheckCutoff: number, tx?: SQLiteAdapter): Promise<{ eligible: number; deferred: number }> {\n const executor = this.getExecutor(tx);\n // Same current-time validity sampling as {@link findUntypedByEntityId}.\n const now = Date.now();\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 AND ${liveAtSql('current')}`,\n [recheckCutoff, recheckCutoff, entityId, now, now],\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 /**\n * Shortlist scoring rows (id, title, okf_type, body) over all live typed\n * facts. Same filters as findTitleIndexByEntityId; okf_type is never NULL\n * in results because the query excludes untyped rows.\n */\n async findShortlistRowsByEntityId(entityId: string, tx?: SQLiteAdapter): Promise<Array<{ id: string; title: string; okf_type: string; body: string }>> {\n const executor = this.getExecutor(tx);\n return executor.getAllAsync<{ id: string; title: string; okf_type: string; body: string }>(\n `SELECT id, title, okf_type, body FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND okf_type IS NOT NULL`,\n [entityId],\n );\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 now = Date.now();\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 AND ${liveAtSql('current')}`,\n [recheckCutoff, recheckCutoff, entityId, now, now],\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 /**\n * Count of live facts for `entityId` with no stored embedding that are still\n * retryable (`embedding_attempts < maxAttempts`). Backs the deferred\n * maintenance pending report's `reembedPending` flag and the reembed job's\n * entity selection (PR-C 2026-09-29).\n */\n async countReembedPending(entityId: string, maxAttempts: number, tx?: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ n: number }>(\n `SELECT COUNT(*) AS n FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL AND embedding_blob IS NULL AND embedding IS NULL AND embedding_attempts < ?`,\n [entityId, maxAttempts],\n );\n return Number(row?.n ?? 0);\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 * Hard-delete every row of the entity, live or soft-deleted (forget clearAll,\n * spec import-followups §6 rev 4). Nothing reads a soft-deleted row and\n * runPrune never sweeps this table, so a wipe leaves no tombstones.\n */\n async deleteByEntityId(entityId: string, tx: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const result = await executor.runAsync(\n `DELETE FROM ${this.prefix}source_ref_index WHERE entity_id = ?`,\n [entityId],\n );\n return result.changes;\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; deleted_at: number | null }>> {\n const executor = this.getExecutor(tx);\n const rows: Array<{ id: string; entity_id: string; updated_at: number; deleted_at: number | null }> = [];\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, deleted_at FROM ${this.prefix}tasks WHERE id IN (${placeholders})`,\n chunk,\n );\n rows.push(...chunkRows.map((row) => ({\n id: row.id,\n entity_id: row.entity_id,\n updated_at: Number(row.updated_at),\n deleted_at: row.deleted_at == null ? null : Number(row.deleted_at),\n })));\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, opts?: { includeDeleted?: boolean }): Promise<WikiTask[]> {\n const executor = this.getExecutor(tx);\n const live = opts?.includeDeleted ? '' : ' AND deleted_at IS NULL';\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}tasks WHERE entity_id = ?${live} 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 opts?: { noCutoff?: boolean },\n ): Promise<number> {\n const executor = this.getExecutor(tx);\n // noCutoff (erase): every soft-deleted row, no timestamp predicate — a\n // nanosecond-epoch or TEXT-valued deleted_at never matches `<= cutoff`.\n const cutoffPredicate = opts?.noCutoff ? '' : ' AND deleted_at <= ?';\n const selectArgs: unknown[] = opts?.noCutoff ? [entityId] : [entityId, cutoff];\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${cutoffPredicate}`,\n selectArgs,\n );\n if (rowsToDelete.length === 0) return 0;\n\n const deleteArgs: unknown[] = opts?.noCutoff ? [entityId] : [entityId, cutoff];\n const result = await executor.runAsync(\n `DELETE FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate}`,\n deleteArgs,\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';\nimport type { LibrarianWatermark } from './MetadataRepository';\n\n/**\n * Strict-after predicate on the (created_at, id) ordering used by the\n * op-based librarian (spec 2026-09-29 §4.1). Three placeholders: `[at, at, id]`.\n */\nexport const AFTER_SQL = '((created_at > ?) OR (created_at = ? AND id > ?))';\n\nexport function afterArgs(wm: LibrarianWatermark): [number, number, string] {\n return [wm.at, wm.at, wm.id];\n}\n\n/**\n * Map a row from the `events` table to the `WikiEvent` shape returned to\n * callers. `occurred_at` is dropped when NULL so legacy librarian prompt\n * bytes are unchanged for the (current default) case where no caller has\n * supplied a real-world timestamp.\n */\nfunction mapEvent(row: WikiEvent): WikiEvent {\n if (row.occurred_at == null) {\n const rest: WikiEvent = { ...row };\n delete (rest as { occurred_at?: number | null }).occurred_at;\n return rest;\n }\n return row;\n}\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, occurred_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 event.occurred_at ?? null,\n ],\n );\n }\n\n /** Insert unless the id already exists. Returns true when a row was inserted. */\n async addIgnoreDuplicate(event: WikiEvent, tx?: SQLiteAdapter): Promise<boolean> {\n const executor = this.getExecutor(tx);\n const result = await executor.runAsync(\n `INSERT OR IGNORE INTO ${this.prefix}events (id, entity_id, event_type, summary, related_entry_id, created_at, occurred_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 event.occurred_at ?? null,\n ],\n );\n return result.changes > 0;\n }\n\n /**\n * The subset of `ids` that exist as events of `entityId` (specs/\n * inplace-update-provenance §3). Chunked so a large batch stays under the\n * bound-variable limit. Pass `tx` to read inside the caller's transaction.\n */\n async findExistingIds(entityId: string, ids: readonly string[], tx?: SQLiteAdapter): Promise<Set<string>> {\n const executor = this.getExecutor(tx);\n const found = new Set<string>();\n for (let i = 0; i < ids.length; i += 500) {\n const chunk = ids.slice(i, i + 500);\n const rows = await executor.getAllAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}events WHERE entity_id = ? AND id IN (${chunk.map(() => '?').join(',')})`,\n [entityId, ...chunk],\n );\n for (const r of rows) found.add(r.id);\n }\n return found;\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 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.map(mapEvent);\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 const rows = await 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 return rows.map(mapEvent);\n }\n\n /** Hard-delete every event of the entity, read or not (requested wipe, spec import-followups §6). */\n async deleteByEntityId(entityId: string, tx: SQLiteAdapter): Promise<{ changes: number }> {\n return tx.runAsync(`DELETE FROM ${this.prefix}events WHERE entity_id = ?`, [entityId]);\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, tx?: SQLiteAdapter): Promise<{ changes: number }> {\n return (tx ?? this.db).runAsync(\n `DELETE FROM ${this.prefix}events WHERE entity_id = ? AND created_at <= ?`,\n [entityId, cutoff],\n );\n }\n\n /**\n * Watermark-guarded prune (spec 2026-09-29 competitive-memory §6): delete\n * events at or before `cutoff` **and** at-or-before the librarian watermark.\n * Events the librarian has not processed yet are retention-held, never\n * deleted. `wm = null` (no watermark yet) deletes nothing.\n * Used by runPrune under the deferred/ops strategies.\n */\n async pruneThrough(entityId: string, cutoff: number, wm: LibrarianWatermark | null, tx?: SQLiteAdapter): Promise<{ changes: number }> {\n if (!wm) return { changes: 0 };\n return (tx ?? this.db).runAsync(\n `DELETE FROM ${this.prefix}events WHERE entity_id = ? AND created_at <= ? AND NOT ${AFTER_SQL}`,\n [entityId, cutoff, ...afterArgs(wm)],\n );\n }\n\n /**\n * Count events at or before `cutoff` that are after the watermark — the\n * retention-held tail `pruneThrough` left in place. `wm = null` counts all\n * events at or before `cutoff` (every one of them is held back).\n */\n async countHeldBack(entityId: string, cutoff: number, wm: LibrarianWatermark | null): Promise<number> {\n const where = wm ? ` AND ${AFTER_SQL}` : '';\n const row = await this.db.getFirstAsync<{ n: number }>(\n `SELECT COUNT(*) AS n FROM ${this.prefix}events WHERE entity_id = ? AND created_at <= ?${where}`,\n [entityId, cutoff, ...(wm ? afterArgs(wm) : [])],\n );\n return Number(row?.n ?? 0);\n }\n\n /**\n * The newest `created_at` stored for an entity, or null when it has no\n * events. `write()` reads it inside its transaction to keep `created_at`\n * strictly increasing per entity (spec ops-auto-first-batch §5).\n */\n async latestCreatedAt(entityId: string, tx?: SQLiteAdapter): Promise<number | null> {\n const row = await (tx ?? this.db).getFirstAsync<{ at: number | null }>(\n `SELECT MAX(created_at) AS at FROM ${this.prefix}events WHERE entity_id = ?`,\n [entityId],\n );\n return row?.at ?? null;\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.map(mapEvent).slice().reverse();\n }\n const rows = await this.db.getAllAsync<WikiEvent>(\n `SELECT * FROM ${this.prefix}events WHERE entity_id = ? ORDER BY created_at ASC`,\n [entityId],\n );\n return rows.map(mapEvent);\n }\n\n /**\n * Return events for `entityId` strictly after the watermark `(at, id)` in\n * chronological (ASC, id-ASC tie-break) order. Pass `wm = null` to read\n * from the beginning of the entity's event log. `limit` caps the result.\n *\n * Used by the op-based librarian (PR-B) to enumerate its unprocessed tail.\n */\n async getAfter(\n entityId: string,\n wm: LibrarianWatermark | null,\n limit?: number,\n ): Promise<WikiEvent[]> {\n const limitClause = limit != null ? ` LIMIT ?` : '';\n const params: unknown[] = wm ? [entityId, wm.at, wm.at, wm.id] : [entityId];\n const where = wm ? `entity_id = ? AND ${AFTER_SQL}` : `entity_id = ?`;\n if (limit != null) params.push(limit);\n const rows = await this.db.getAllAsync<WikiEvent>(\n `SELECT * FROM ${this.prefix}events WHERE ${where} ORDER BY created_at ASC, id ASC${limitClause}`,\n params,\n );\n return rows.map(mapEvent);\n }\n\n /**\n * Count of events for `entityId` strictly after the watermark. Used as\n * the op-based librarian's bounded batch size and by the deferred-maintenance\n * pending report. Pass `wm = null` to count the entity's whole event log\n * (no watermark yet) — mirrors `getAfter` / `sumSummaryCharsAfter`.\n */\n async countAfter(entityId: string, wm: LibrarianWatermark | null): Promise<number> {\n const params: unknown[] = wm ? [entityId, wm.at, wm.at, wm.id] : [entityId];\n const where = wm ? `entity_id = ? AND ${AFTER_SQL}` : `entity_id = ?`;\n const row = await this.db.getFirstAsync<{ count: number }>(\n `SELECT COUNT(*) as count FROM ${this.prefix}events WHERE ${where}`,\n params,\n );\n return row?.count ?? 0;\n }\n\n /**\n * Return the event at a given chronological offset for `entityId` (0-based,\n * oldest first). Used by MaintenanceService.seedLibrarianWatermark to anchor\n * the watermark on a real row when a legacy DB first migrates to the\n * op-based librarian. The offset is clamped and truncated to defend against\n * hostile or fractional callers.\n */\n async getAtOffset(entityId: string, offset: number, tx?: SQLiteAdapter): Promise<WikiEvent | null> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<any>(\n `SELECT * FROM ${this.prefix}events WHERE entity_id = ? ORDER BY created_at ASC, id ASC LIMIT 1 OFFSET ?`,\n [entityId, Math.max(0, Math.trunc(offset))],\n );\n return row ? mapEvent(row) : null;\n }\n\n /**\n * Sum of `summary` lengths (in characters) for events for `entityId`\n * strictly after the watermark. Pass `wm = null` to sum the entity's whole\n * event log (no watermark yet). Used by the op-based librarian's token\n * budget estimator (PR-B) and by the auto-trigger's pending-size check\n * (PR-C). SQLite's `LENGTH` returns character count for UTF-8 text input.\n */\n async sumSummaryCharsAfter(entityId: string, wm: LibrarianWatermark | null, tx?: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const params: unknown[] = wm ? [entityId, wm.at, wm.at, wm.id] : [entityId];\n const where = wm ? `entity_id = ? AND ${AFTER_SQL}` : `entity_id = ?`;\n const row = await executor.getFirstAsync<{ total: number | null }>(\n `SELECT SUM(LENGTH(summary)) as total FROM ${this.prefix}events WHERE ${where}`,\n params,\n );\n return row?.total ?? 0;\n }\n}\n","/** Monotonic clock (ms): a wall-clock step must not stretch or skip a deadline or a cooldown. */\nexport const monotonicNow = (): number =>\n typeof performance !== 'undefined' && typeof performance.now === 'function' ? performance.now() : Date.now();\n","/**\n * Default `setupBudgetMs`: the wall time each keyword-index quantum (one per\n * `setup()` and per no-arg `syncSearchIndex()`) may spend on drain/rebuild\n * chunks, checked between chunk transactions (spec #280 Config surface).\n */\nexport const DEFAULT_SETUP_BUDGET_MS = 1500;\n","// packages/core/src/services/search/ftsQuery.ts\n\nconst TOKEN = /[\\p{L}\\p{N}]+/gu;\n\n/**\n * Turn a free-text query into an FTS5 MATCH expression that can never be a\n * syntax error: every token is a double-quoted string (FTS5 has no escapes\n * inside quotes except `\"\"`, and tokens contain no quotes), followed by `*`\n * for prefix matching. Tokens are ORed, which matches MiniSearch's\n * `prefix: true` and its `combineWith: 'OR'`. Returns `null` when no token\n * survives, and the caller returns no results.\n */\nexport function buildFtsMatchQuery(query: string): string | null {\n const seen = new Set<string>();\n for (const m of query.toLowerCase().matchAll(TOKEN)) seen.add(m[0]);\n if (seen.size === 0) return null;\n return [...seen].map((t) => `\"${t}\"*`).join(' OR ');\n}\n","// packages/core/src/services/search/Fts5IndexStrategy.ts\nimport type { SQLiteAdapter } from '../../types';\nimport type { MetadataRepository } from '../../repositories/MetadataRepository';\nimport type { DrainOptions, IndexDocument, IndexSearchOptions, IndexSearchResult, IndexStrategy, PassageHit } from './IndexStrategy';\nimport {\n FTS5_DRAIN_CHUNK, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, isRetiredTableName, retiredTableName, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY,\n sweepChunkSql, sweepHiSql, windowChunkSql, windowHiSql, drainChunkSql, drainHiSql, entityDrainChunkSql, entityDrainHiSql, fts5PendingIndexesDdl,\n fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, idDrainChunkSql, idReindexChunkSql,\n passageFtsTablesDdl, passageFtsTriggersDdl,\n} from './fts5Sql';\n\nimport { readRebuildProgress, writeRebuildStart, type RebuildProgress, type RebuildWatermark } from './fts5Progress';\nimport { parseJsonArray } from '../../repositories/rowMappers';\nimport { monotonicNow } from '../../utils/monotonicNow';\nimport { DEFAULT_SETUP_BUDGET_MS } from '../../utils/setupDefaults';\nimport { buildFtsMatchQuery } from './ftsQuery';\nimport { extractSqliteCode } from '../../db/sqliteCodes';\n\n/** One passage hit: `id` is the `source_passages.id`. */\nexport interface PassageSearchResult {\n id: string;\n entity_id: string;\n document_id: string;\n score: number;\n}\n\n/**\n * Attach offsets, source pair and passage text to raw hits. Text is sliced in\n * JS from `source_documents.text` (spec section 7); a hit whose passage or\n * document row is gone is dropped.\n */\nexport async function hydratePassageHits(\n db: SQLiteAdapter, prefix: string, raw: readonly PassageSearchResult[],\n): Promise<PassageHit[]> {\n const docs = new Map<string, { source_ref: string; source_hash: string; text: string } | null>();\n const out: PassageHit[] = [];\n for (const r of raw) {\n const pas = await db.getFirstAsync<{ seq: number; start_offset: number; end_offset: number }>(\n `SELECT seq, start_offset, end_offset FROM ${prefix}source_passages WHERE id = ? AND entity_id = ?`, [r.id, r.entity_id]);\n if (!pas) continue;\n const dk = `${r.entity_id}\\u0000${r.document_id}`;\n if (!docs.has(dk)) {\n docs.set(dk, (await db.getFirstAsync<{ source_ref: string; source_hash: string; text: string }>(\n `SELECT source_ref, source_hash, text FROM ${prefix}source_documents WHERE id = ? AND entity_id = ?`, [r.document_id, r.entity_id])) ?? null);\n }\n const doc = docs.get(dk);\n if (!doc) continue;\n const start = Number(pas.start_offset);\n const end = Number(pas.end_offset);\n out.push({\n ...r, seq: Number(pas.seq), start_offset: start, end_offset: end,\n source_ref: doc.source_ref, source_hash: doc.source_hash, text: doc.text.slice(start, end),\n });\n }\n return out;\n}\n\n/**\n * Keyword index stored in SQLite FTS5, kept consistent with `entries` by a\n * trigger-fed ledger (`fts_pending`) that `drain()` applies in bounded, all-SQL\n * chunks. Row text never enters JS, so memory is flat at any database size.\n * Spec 2026-10-05 §PR-2 revision.\n */\nexport class Fts5IndexStrategy implements IndexStrategy {\n constructor(\n private readonly db: SQLiteAdapter,\n private readonly prefix: string,\n private readonly metadataRepo: MetadataRepository,\n private readonly budgetMs: number = DEFAULT_SETUP_BUDGET_MS,\n ) {}\n\n /**\n * Resolves the index state (spec #280 Change 3 transition table). Every\n * read-only probe runs before the one transition transaction, so a probe\n * failure leaves zero mutation (Change 4 ordering).\n */\n async init(opts: { entriesExisted?: boolean } = {}): Promise<void> {\n await this.initEntries(opts);\n // A passage-side failure must not take down fact keyword search (entries FTS is already live).\n try {\n await this.ensurePassageObjects();\n } catch (err) {\n this.passagesDisabled = true;\n console.warn('[WikiMemory] passage index init failed; passage search returns [] until a later open:', err);\n }\n }\n\n /** Set when passage-index init failed; passage drain and search become no-ops. */\n private passagesDisabled = false;\n\n /**\n * Source-store passage index objects (spec source-store §6): created here,\n * the way the entries_fts objects are, never by setupDatabase. Skipped when\n * the store tables are absent (a pre-v17 database).\n */\n private async ensurePassageObjects(): Promise<void> {\n const p = this.prefix;\n if (!(await this.metadataRepo.tableExists(`${p}source_passages`))) return;\n await this.db.withTransactionAsync(async (tx) => {\n await tx.execAsync(passageFtsTablesDdl(p) + passageFtsTriggersDdl(p));\n // Probes and the bootstrap insert run in the SAME transaction as the DDL\n // (CodeRabbit follow-up): a store write committing after the DDL but\n // before the probes would enqueue its document through the new trigger,\n // and the non-empty ledger would then suppress the bootstrap forever —\n // pre-index passages with no row would never enter passage search.\n const mapped = await tx.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_map LIMIT 1`);\n const queued = await tx.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_pending LIMIT 1`);\n if (mapped === null && queued === null) {\n // The virtual table can hold stale content even with an empty map: a\n // detach on a module-less host drops the map/ledger but cannot drop\n // this table (detachFts5 swallows the failure). The re-seeded map's\n // rowids then collide with the surviving rows — every drain fails, or\n // duplicated hits surface. The entries side resets the same way in\n // resetAndRearm. This clear is UNCONDITIONAL on the bootstrap path\n // (every open where map and ledger are both empty runs it) and is\n // harmless when the table is not stale: in that state it is empty\n // too. The bootstrap is the only writer that runs on an empty map.\n await tx.runAsync(`DELETE FROM ${p}source_passages_fts`);\n // After a module-less erase (specs/erase-fts-remediation Path A) the\n // table keeps its fts5 structure record but its segments are gone, so\n // reads hit \"corruption found reading blob\". 'rebuild' discards all\n // index data without reading segments and re-tokenizes from the (empty)\n // content table, leaving a valid empty index; on a healthy empty table\n // it is a no-op.\n await tx.runAsync(`INSERT INTO ${p}source_passages_fts(${p}source_passages_fts) VALUES('rebuild')`);\n await tx.runAsync(\n `INSERT INTO ${p}source_passages_fts_pending (entity_id, doc_id)\n SELECT entity_id, id FROM ${p}source_documents`);\n }\n });\n }\n\n /**\n * Drain the passage ledger one document at a time (spec §6, the stated\n * departure from all-SQL): the document's text is read into JS and sliced at\n * the offsets the cutter stored, so transient memory is bounded by\n * `maxCharsPerSource` for the ONE document, never the store. Each document\n * is one transaction. `entityId` limits the drain to that entity's ledger rows.\n */\n async drainPassages(opts: { entityId?: string; deadline?: number } = {}): Promise<void> {\n if (this.passagesDisabled) return;\n const p = this.prefix;\n if (!(await this.metadataRepo.tableExists(`${p}source_passages_fts_pending`))) return;\n for (;;) {\n if (opts.deadline !== undefined && monotonicNow() >= opts.deadline) return;\n let ran = false;\n await this.db.withTransactionAsync(async (tx) => {\n const first = opts.entityId === undefined\n ? await tx.getFirstAsync<{ doc_id: string; entity_id: string }>(\n `SELECT doc_id, entity_id FROM ${p}source_passages_fts_pending ORDER BY seq LIMIT 1`)\n : await tx.getFirstAsync<{ doc_id: string; entity_id: string }>(\n `SELECT doc_id, entity_id FROM ${p}source_passages_fts_pending WHERE entity_id = ? ORDER BY seq LIMIT 1`,\n [opts.entityId]);\n if (!first) return;\n const docId = first.doc_id;\n const ent = first.entity_id;\n const hi = await tx.getFirstAsync<{ hi: number }>(\n `SELECT max(seq) AS hi FROM ${p}source_passages_fts_pending WHERE doc_id = ? AND entity_id = ?`, [docId, ent]);\n await tx.runAsync(\n `DELETE FROM ${p}source_passages_fts WHERE rowid IN (SELECT fts_rowid FROM ${p}source_passages_fts_map WHERE doc_id = ?)`,\n [docId]);\n await tx.runAsync(`DELETE FROM ${p}source_passages_fts_map WHERE doc_id = ?`, [docId]);\n const doc = await tx.getFirstAsync<{ text: string }>(`SELECT text FROM ${p}source_documents WHERE id = ? AND entity_id = ?`, [docId, ent]);\n if (doc) {\n const rows = await tx.getAllAsync<{ id: string; entity_id: string; start_offset: number; end_offset: number }>(\n `SELECT id, entity_id, start_offset, end_offset FROM ${p}source_passages WHERE document_id = ? AND entity_id = ? ORDER BY seq`, [docId, ent]);\n for (const r of rows) {\n const { lastInsertRowId } = await tx.runAsync(\n `INSERT INTO ${p}source_passages_fts_map (passage_id, doc_id) VALUES (?, ?)`, [r.id, docId]);\n await tx.runAsync(\n `INSERT INTO ${p}source_passages_fts (rowid, passage_id, entity_id, doc_id, text) VALUES (?, ?, ?, ?, ?)`,\n [lastInsertRowId, r.id, r.entity_id, docId, doc.text.slice(Number(r.start_offset), Number(r.end_offset))]);\n }\n }\n await tx.runAsync(\n `DELETE FROM ${p}source_passages_fts_pending WHERE doc_id = ? AND seq <= ?`, [docId, hi?.hi ?? 0]);\n ran = true;\n });\n if (!ran) return;\n }\n }\n\n /**\n * Best-match-first passage search. A hit counts only while its\n * `source_passages` row exists, so a stalled drain never surfaces a deleted\n * passage (spec §5).\n */\n async searchPassages(query: string, options: { entityIds: string[]; limit: number }): Promise<PassageHit[]> {\n if (this.passagesDisabled || options.entityIds.length === 0) return [];\n const match = buildFtsMatchQuery(query);\n if (match === null) return [];\n const p = this.prefix;\n const t = `${p}source_passages_fts`;\n const limit = options.limit >= Number.MAX_SAFE_INTEGER ? -1 : options.limit;\n const raw = await this.db.getAllAsync<PassageSearchResult>(\n `SELECT passage_id AS id, entity_id, doc_id AS document_id, max(0.0, -raw) AS score FROM (\n SELECT passage_id, entity_id, doc_id, bm25(${t}, 0.0, 0.0, 0.0, 1.0) AS raw\n FROM ${t}\n WHERE ${t} MATCH ? AND entity_id IN (SELECT value FROM json_each(?))\n AND passage_id IN (SELECT id FROM ${p}source_passages WHERE entity_id IN (SELECT value FROM json_each(?)))\n ORDER BY raw, passage_id\n LIMIT ?)\n ORDER BY raw, id`,\n [match, JSON.stringify(options.entityIds), JSON.stringify(options.entityIds), limit],\n );\n return hydratePassageHits(this.db, p, raw);\n }\n\n private async initEntries(opts: { entriesExisted?: boolean }): Promise<void> {\n try {\n await this.initOnce(opts);\n } catch (err) {\n const wrapped = unwrapFtsOnly(err);\n const cls = ftsCorruptionClass(wrapped.cause);\n // Corruption confined to FTS tables: entries is untouched, so a reset re-arm is safe (spec #280 Change 4).\n if (cls === 'vtab' || (cls === 'corrupt' && wrapped.ftsOnly)) {\n await this.resetAndRearm();\n return;\n }\n throw wrapped.cause; // generic errors keep the retry -> UnavailableIndexStrategy path; pinned 'fts5' sees them raw\n }\n }\n\n /** Marks errors from statements that touch only FTS tables (entries_fts + shadows). */\n private async ftsOnly<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (err) {\n throw new FtsOnlyStatementError(err);\n }\n }\n\n private async initOnce(opts: { entriesExisted?: boolean }): Promise<void> {\n const p = this.prefix;\n const state = await this.metadataRepo.getMeta(FTS5_STATE_KEY);\n const schema = await this.readSchema();\n const ftsExists = schema.tables.has(`${p}entries_fts`);\n const mapExists = schema.tables.has(`${p}fts_map`);\n const pendingExists = schema.tables.has(`${p}fts_pending`);\n const trig = schema.triggersPresent;\n const ftsDdl = schema.tables.get(`${p}entries_fts`) ?? null;\n const tokenizerOk = ftsDdl === null || /tokenize\\s*=\\s*['\"]porter\\s+unicode61['\"]/i.test(ftsDdl);\n\n if (state === null && opts.entriesExisted === false) {\n // Fresh store: nothing to index yet.\n await this.db.withTransactionAsync(async (tx) => {\n await tx.execAsync(fts5TablesDdl(p) + fts5PendingIndexesDdl(p) + fts5TriggersDdl(p));\n await this.metadataRepo.setMeta(FTS5_STATE_KEY, 'live', tx);\n });\n return;\n }\n if (state === 'detached') return this.resetAndRearm(); // re-attach: the map is untrustworthy\n\n if (!tokenizerOk) return this.resetAndRearm();\n\n const intact = trig && ftsExists && mapExists && pendingExists;\n if (intact && state === 'rebuilding') return; // resume; each quantum re-verifies the fingerprint\n if (intact && state === 'live') {\n await this.ftsOnly(() => this.db.getFirstAsync(`SELECT rowid FROM ${p}entries_fts ORDER BY rowid DESC LIMIT 1`));\n if (await this.liveRowUnindexed()) return this.resetAndRearm();\n return; // fast path\n }\n // Marker lost, a trigger lost, or a table missing.\n if (ftsExists && mapExists && (await this.keepMapConsistent())) {\n await this.db.withTransactionAsync((tx) => this.rearmInTx(tx));\n return;\n }\n return this.resetAndRearm();\n }\n\n /**\n * The index was lost (rev 8 m3 / rev 9 m4): the oldest or the newest live entry is neither mapped nor\n * ledgered, which `live` never allows. The oldest one keeps detection armed after post-loss writes\n * repopulate the map and the ledger (#284 review). Every-open path: each side reads at most\n * FTS5_DRAIN_CHUNK entries rows (final review M1), so an all-soft-deleted store is never fully scanned;\n * a lost index whose oldest and newest rows are all deleted goes undetected.\n */\n private async liveRowUnindexed(): Promise<boolean> {\n const p = this.prefix;\n const edge = (dir: 'ASC' | 'DESC') => `SELECT id FROM (SELECT id FROM (SELECT id, deleted_at FROM ${p}entries`\n + ` ORDER BY rowid ${dir} LIMIT ${FTS5_DRAIN_CHUNK}) WHERE deleted_at IS NULL LIMIT 1)`;\n return (await this.db.getFirstAsync(\n `SELECT 1 AS x FROM (${edge('ASC')} UNION ALL ${edge('DESC')}) e\n WHERE NOT EXISTS (SELECT 1 FROM ${p}fts_map m WHERE m.id = e.id)\n AND NOT EXISTS (SELECT 1 FROM ${p}fts_pending q WHERE q.id = e.id)\n LIMIT 1`)) !== null;\n }\n\n /**\n * Read-only keep-map check (spec DDL note): every surviving entries_fts\n * rowid must have a map row. Max-rowid seek, then docsize vs map counts.\n */\n private async keepMapConsistent(): Promise<boolean> {\n const p = this.prefix;\n const fts = await this.ftsOnly(() => this.db.getFirstAsync<{ rowid: number }>(`SELECT rowid FROM ${p}entries_fts ORDER BY rowid DESC LIMIT 1`));\n const map = await this.db.getFirstAsync<{ hi: number; n: number }>(\n `SELECT coalesce(max(fts_rowid), 0) AS hi, count(*) AS n FROM ${p}fts_map`);\n if ((fts?.rowid ?? 0) > (map?.hi ?? 0)) return false;\n const doc = await this.ftsOnly(() => this.db.getFirstAsync<{ n: number }>(`SELECT count(*) AS n FROM ${p}entries_fts_docsize`));\n return (doc?.n ?? 0) === (map?.n ?? 0);\n }\n\n /** Keep-map re-arm: triggers, empty ledger, rebuild from 0, state rebuilding. One transaction. */\n private async rearmInTx(tx: SQLiteAdapter): Promise<void> {\n const p = this.prefix;\n await tx.execAsync(fts5TablesDdl(p));\n await tx.execAsync(`DELETE FROM ${p}fts_pending;`);\n await tx.execAsync(fts5PendingIndexesDdl(p) + fts5TriggersDdl(p));\n await writeRebuildStart(tx, p, this.metadataRepo);\n await this.metadataRepo.setMeta(FTS5_STATE_KEY, 'rebuilding', tx);\n }\n\n /** Reset path: retire entries_fts, recreate it empty, clear map + ledger, then the re-arm. One transaction. */\n private async resetAndRearm(): Promise<void> {\n const p = this.prefix;\n await this.db.withTransactionAsync(async (tx) => {\n await this.retireFtsTable(tx);\n await tx.execAsync(fts5TablesDdl(p));\n await tx.execAsync(`DELETE FROM ${p}fts_map; DELETE FROM ${p}fts_pending;`);\n await this.rearmInTx(tx);\n });\n }\n\n /** Rename-retire entries_fts (spec #280 rev 11); DROP only when the RENAME throws. */\n private async retireFtsTable(tx: SQLiteAdapter): Promise<void> {\n const p = this.prefix;\n if (!(await this.metadataRepo.tableExists(`${p}entries_fts`, tx))) return;\n const n = Number((await this.metadataRepo.getMeta(FTS5_RETIRED_COUNTER_KEY, tx)) ?? '0') + 1;\n const name = retiredTableName(p, n);\n try {\n await tx.execAsync(`ALTER TABLE ${p}entries_fts RENAME TO ${name}`);\n } catch (err) {\n // Not damage: SQLite may have rolled the transaction back already, so further statements would\n // autocommit one by one. Fail the reset whole instead (#284 review).\n if (isTransientOrTxFatal(err)) throw err;\n // Shadow tables too damaged to rename: today's DROP, with its measured floor, for this case only.\n await tx.execAsync(`DROP TABLE ${p}entries_fts`);\n return;\n }\n await this.metadataRepo.setMeta(FTS5_RETIRED_TABLES_KEY, JSON.stringify([...(await this.retiredList(tx)), name]), tx);\n await this.metadataRepo.setMeta(FTS5_RETIRED_COUNTER_KEY, String(n), tx);\n }\n\n private async retiredList(tx: SQLiteAdapter = this.db): Promise<string[]> {\n const raw = parseJsonArray<unknown>(await this.metadataRepo.getMeta(FTS5_RETIRED_TABLES_KEY, tx), []);\n return raw.filter((n): n is string => isRetiredTableName(this.prefix, n));\n }\n\n async drain(opts: DrainOptions = {}): Promise<void> {\n try {\n await this.drainOnce(opts);\n } catch (err) {\n // SQLITE_CORRUPT_VTAB names the FTS5 table itself, so the reset init() applies is safe here too:\n // without it every drain fails until the next open (#284 review). Other corruption may be in\n // entries, which this cannot repair: it propagates as before.\n if (ftsCorruptionClass(err) !== 'vtab') throw err;\n await this.resetAndRearm();\n // The reset cleared the ledger, so the caller's ids are re-indexed from entries: resolving\n // still means they are searchable (DrainOptions.ids), and the caller may drop them.\n if (opts.ids && opts.ids.length > 0) await this.drainIds(opts.ids, idReindexChunkSql(this.prefix));\n }\n }\n\n private async drainOnce(opts: DrainOptions): Promise<void> {\n const ids = opts.ids ?? [];\n // The caller's own ids are not deadline-bound (DrainOptions.ids): they drain to completion, and the caller drops them from its stash only once this succeeds.\n if (ids.length > 0) await this.drainIds(ids);\n if (opts.mode === 'ledger') {\n // Write turn: at most ONE foreign chunk after the caller's own ids.\n if (ids.length === 0 && opts.entityId !== undefined) await this.drainEntityChunk(opts.entityId);\n else await this.drainLedgerChunk();\n return;\n }\n await this.fullQuantum(opts.deadline ?? monotonicNow() + this.budgetMs);\n }\n\n /**\n * One full quantum (spec #280 Change 3): ledger first (at most half the\n * budget while `rebuilding`); then, while `rebuilding`, ≥1 window unless\n * the ledger drain overran the deadline, one sweep tx, and the flip check;\n * then reclamation. A `live` store reads only the state.\n */\n private async fullQuantum(deadline: number): Promise<void> {\n const rebuilding = (await this.metadataRepo.getMeta(FTS5_STATE_KEY)) === 'rebuilding';\n // While rebuilding, the ledger stops at half the remaining budget, so a steady write backlog cannot\n // starve the windows (#284 review). Overrun is still judged against the full deadline.\n const start = monotonicNow();\n const ledgerRan = await this.drainLedgerUntil(rebuilding ? start + (deadline - start) / 2 : deadline);\n const ledgerOverran = ledgerRan && monotonicNow() >= deadline;\n if (rebuilding) {\n const progress = await readRebuildProgress(this.metadataRepo);\n if (!progress || !(await this.fingerprintValid(progress.wm))) {\n // Windows resume next quantum; reclamation below still runs (#284 review).\n await this.restartRebuild();\n } else {\n if (!ledgerOverran) {\n let step: WindowStep;\n do {\n step = await this.runWindow(progress);\n } while (step === 'more' && monotonicNow() < deadline);\n // 'stale': progress moved under this quantum (a VACUUM restart, a re-anchor, a flip); the next quantum re-reads it.\n if (step !== 'stale') await this.runSweepTx(progress);\n }\n await this.tryFlip();\n }\n }\n try {\n await this.reclaimRetired(deadline);\n } catch (err) {\n // Best-effort for database errors only: a locked retired table stays listed and is retried next quantum,\n // never failing drain() or the flip. A non-SQLite error is a bug and propagates (final review I2).\n if (!isSqliteError(err)) throw err;\n }\n }\n\n /** Listed retired table names (erase step 4 / module-less fallback). */\n async retiredTables(): Promise<string[]> {\n return this.retiredList();\n }\n\n /**\n * Erase step 4: reclaim every retired table to completion (DROP + delist), no\n * deadline. Failures surface (unlike the best-effort quantum path); the\n * SQLITE_CORRUPT_VTAB hollowed-shell exit inside reclaimRetired is designed.\n */\n async reclaimRetiredToCompletion(): Promise<void> {\n await this.reclaimRetired(Number.POSITIVE_INFINITY);\n }\n\n /**\n * Erase step 3: surfaced passage drain, no deadline. Fails only when passage\n * init was disabled AND the ledger still has rows; otherwise warns and continues.\n */\n async drainPassagesStrict(): Promise<void> {\n if (this.passagesDisabled) {\n const p = this.prefix;\n const pending = (await this.metadataRepo.tableExists(`${p}source_passages_fts_pending`))\n && (await this.db.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_pending LIMIT 1`)) !== null;\n if (pending) throw new Error('passage index disabled with pending ledger rows');\n console.warn('[WikiMemory] erase: passage index disabled; nothing pending, continuing');\n return;\n }\n await this.drainPassages({});\n }\n\n /**\n * Erase step 3 (entries side): drain the trigger-fed `fts_pending` ledger store-wide to\n * empty, no deadline, errors surfaced; throws if rows remain afterwards.\n */\n async drainEntriesLedgerStrict(): Promise<void> {\n while (await this.drainLedgerChunk());\n const left = await this.db.getFirstAsync(`SELECT 1 AS x FROM ${this.prefix}fts_pending LIMIT 1`);\n if (left !== null && left !== undefined) throw new Error('entries FTS ledger still has pending rows after drain');\n }\n\n /** Erase step 7: FTS 'optimize' on each FTS table that exists. */\n async optimizeFts(): Promise<void> {\n const p = this.prefix;\n for (const t of [`${p}entries_fts`, `${p}source_passages_fts`]) {\n if (!(await this.metadataRepo.tableExists(t))) continue;\n await this.db.runAsync(`INSERT INTO ${t}(${t}) VALUES('optimize')`);\n }\n }\n\n /** `erase({ rebuild: true })` surface: retire + recreate the entries index and re-arm the rebuild. */\n async rebuildForErase(): Promise<void> {\n await this.resetAndRearm();\n }\n\n /** Bounded reclamation steps, each its own tx, until the deadline or nothing is retired. */\n private async reclaimRetired(deadline: number): Promise<void> {\n while (monotonicNow() < deadline) {\n const [name] = await this.retiredList();\n if (name === undefined) return;\n try {\n // The list and the table are read once per table, not per step (#284 review).\n if (!(await this.metadataRepo.tableExists(name))) {\n await this.delistRetired(name, false);\n continue;\n }\n while (!(await this.reclaimStep(name)) && monotonicNow() < deadline);\n } catch (err) {\n if (ftsCorruptionClass(err) === null) throw err;\n // Persistently corrupt (the corruption reset is what retired it): DROP once and delist; if even\n // the DROP fails, delist anyway so no quantum re-reads its corrupt pages (final review I2).\n try {\n await this.delistRetired(name, true);\n } catch (dropErr) {\n if (!isSqliteError(dropErr)) throw dropErr;\n await this.delistRetired(name, false);\n }\n }\n }\n }\n\n /** (1) delete <=500 rows, else (2) one bounded merge, else (3) DROP + delist. True once delisted. */\n private async reclaimStep(name: string): Promise<boolean> {\n if (await this.db.getFirstAsync(`SELECT rowid FROM ${name} LIMIT 1`)) {\n await this.db.withTransactionAsync(async (tx) => {\n await tx.runAsync(`DELETE FROM ${name} WHERE rowid IN (SELECT rowid FROM ${name} ORDER BY rowid LIMIT ${FTS5_DRAIN_CHUNK})`);\n });\n return false;\n }\n let merged = false;\n await this.db.withTransactionAsync(async (tx) => {\n const before = await tx.getFirstAsync<{ n: number }>(`SELECT total_changes() AS n`);\n await tx.runAsync(`INSERT INTO ${name}(${name}, rank) VALUES('merge', ${FTS5_RECLAIM_MERGE_PAGES})`);\n const after = await tx.getFirstAsync<{ n: number }>(`SELECT total_changes() AS n`);\n merged = (after?.n ?? 0) - (before?.n ?? 0) >= 2; // FTS5 docs: < 2 means the merge did no work\n });\n if (!merged) await this.delistRetired(name, true);\n return !merged;\n }\n\n private async delistRetired(name: string, drop: boolean): Promise<void> {\n await this.db.withTransactionAsync(async (tx) => {\n if (drop) await tx.execAsync(`DROP TABLE IF EXISTS ${name}`);\n const rest = (await this.retiredList(tx)).filter((n) => n !== name);\n await this.metadataRepo.setMeta(FTS5_RETIRED_TABLES_KEY, JSON.stringify(rest), tx);\n });\n }\n\n /** The id at the watermark's rowid still matches. A null id (start, or windows complete) has nothing to check. */\n private async fingerprintValid(wm: RebuildWatermark, tx: SQLiteAdapter = this.db): Promise<boolean> {\n if (wm.id === null) return true;\n const row = await tx.getFirstAsync<{ id: string }>(`SELECT id FROM ${this.prefix}entries WHERE rowid = ?`, [wm.rowid]);\n return row?.id === wm.id;\n }\n\n /** External change under the watermark: start over (same re-arm transaction as a trigger-loss restart). */\n private async restartRebuild(): Promise<void> {\n await this.db.withTransactionAsync((tx) => this.rearmInTx(tx));\n }\n\n /**\n * Progress as stored, re-read inside a window/sweep tx: false when it no\n * longer matches what this quantum assumed (final review I1). Writing a\n * watermark or cursor computed from a stale `pr` would overwrite a\n * concurrent restart (runPrune VACUUM is not on the sync chain).\n */\n private async progressUnchanged(pr: RebuildProgress, tx: SQLiteAdapter): Promise<boolean> {\n if ((await this.metadataRepo.getMeta(FTS5_STATE_KEY, tx)) !== 'rebuilding') return false;\n const cur = await readRebuildProgress(this.metadataRepo, tx);\n return cur !== null && cur.wm.rowid === pr.wm.rowid && cur.wm.id === pr.wm.id && cur.cursor === pr.cursor\n && cur.snapshot.entries === pr.snapshot.entries && cur.snapshot.map === pr.snapshot.map;\n }\n\n /** One window tx. 'done' once no rows remain in (wm, snapshot] (the watermark is then pinned at the snapshot, F9); 'stale' when progress moved under the quantum. */\n private async runWindow(pr: RebuildProgress): Promise<WindowStep> {\n if (pr.wm.rowid >= pr.snapshot.entries) return 'done';\n const p = this.prefix;\n let next: RebuildWatermark = pr.wm;\n let more = false;\n let stale = false;\n await this.db.withTransactionAsync(async (tx) => {\n if (!(await this.progressUnchanged(pr, tx))) { stale = true; return; }\n const row = await tx.getFirstAsync<{ hi: number | null }>(windowHiSql(p), [pr.wm.rowid, pr.snapshot.entries]);\n if (row?.hi == null) {\n next = { rowid: pr.snapshot.entries, id: null };\n } else {\n for (const sql of windowChunkSql(p)) await tx.runAsync(sql, [pr.wm.rowid, row.hi]);\n const fp = await tx.getFirstAsync<{ id: string }>(`SELECT id FROM ${p}entries WHERE rowid = ?`, [row.hi]);\n next = { rowid: row.hi, id: fp!.id };\n more = true;\n }\n await this.metadataRepo.setMeta(FTS5_REBUILD_WM_KEY, JSON.stringify(next), tx);\n });\n if (stale) return 'stale';\n pr.wm = next; // only after the tx resolved\n return more ? 'more' : 'done';\n }\n\n /** At most one bounded sweep tx; the cursor advances in the same tx. */\n private async runSweepTx(pr: RebuildProgress): Promise<void> {\n if (pr.cursor >= pr.snapshot.map) return;\n const p = this.prefix;\n let next = pr.cursor;\n await this.db.withTransactionAsync(async (tx) => {\n if (!(await this.progressUnchanged(pr, tx))) return; // keep pr.cursor; the next quantum re-reads\n const row = await tx.getFirstAsync<{ hi: number | null }>(sweepHiSql(p), [pr.cursor, pr.snapshot.map]);\n const hi = row?.hi ?? pr.snapshot.map;\n for (const sql of sweepChunkSql(p)) await tx.runAsync(sql, [pr.cursor, hi]);\n await this.metadataRepo.setMeta(FTS5_SWEEP_CURSOR_KEY, String(hi), tx);\n next = hi;\n });\n pr.cursor = next;\n }\n\n /** Completion, re-checked inside the flipping tx; the residual ledger (≤ one chunk) drains in it. */\n private async tryFlip(): Promise<void> {\n const p = this.prefix;\n await this.db.withTransactionAsync(async (tx) => {\n if ((await this.metadataRepo.getMeta(FTS5_STATE_KEY, tx)) !== 'rebuilding') return;\n const pr = await readRebuildProgress(this.metadataRepo, tx);\n if (!pr || pr.wm.rowid < pr.snapshot.entries || pr.cursor < pr.snapshot.map) return;\n if (!(await this.fingerprintValid(pr.wm, tx))) return;\n const residual = await tx.getFirstAsync<{ n: number }>(\n `SELECT count(*) AS n FROM (SELECT 1 FROM ${p}fts_pending LIMIT ${FTS5_DRAIN_CHUNK + 1})`);\n if ((residual?.n ?? 0) > FTS5_DRAIN_CHUNK) return;\n const hi = await tx.getFirstAsync<{ hi: number | null }>(drainHiSql(p));\n if (hi?.hi != null) for (const sql of drainChunkSql(p)) await tx.runAsync(sql, [hi.hi]);\n await this.metadataRepo.deleteMeta(FTS5_REBUILD_WM_KEY, tx);\n await this.metadataRepo.deleteMeta(FTS5_REBUILD_SNAPSHOT_KEY, tx);\n await this.metadataRepo.deleteMeta(FTS5_SWEEP_CURSOR_KEY, tx);\n await this.metadataRepo.setMeta(FTS5_STATE_KEY, 'live', tx);\n });\n }\n\n /** Seq-ordered ledger chunks until empty or `stopAt`. True when a chunk ran. */\n private async drainLedgerUntil(stopAt: number): Promise<boolean> {\n let ran = false;\n while (await this.drainLedgerChunk()) {\n ran = true;\n if (monotonicNow() >= stopAt) break;\n }\n return ran;\n }\n\n /** The caller's own ids, to completion, ≤ FTS5_DRAIN_CHUNK per transaction. */\n private async drainIds(ids: readonly string[], chunk: readonly string[] = idDrainChunkSql(this.prefix)): Promise<void> {\n const unique = [...new Set(ids)];\n for (let i = 0; i < unique.length; i += FTS5_DRAIN_CHUNK) {\n const json = JSON.stringify(unique.slice(i, i + FTS5_DRAIN_CHUNK));\n await this.db.withTransactionAsync(async (tx) => {\n for (const sql of chunk) await tx.runAsync(sql, [json]);\n });\n }\n }\n\n /** One seq-ordered chunk. False when the ledger was empty. */\n private async drainLedgerChunk(): Promise<boolean> {\n const hiSql = drainHiSql(this.prefix);\n const chunk = drainChunkSql(this.prefix);\n // A local, not the callback's return value: host adapters may resolve withTransactionAsync to void.\n let ran = false;\n await this.db.withTransactionAsync(async (tx) => {\n const row = await tx.getFirstAsync<{ hi: number | null }>(hiSql);\n if (row?.hi == null) return;\n for (const sql of chunk) await tx.runAsync(sql, [row.hi]);\n ran = true;\n });\n return ran;\n }\n\n /** One entity-targeted chunk (ORDER BY seq, ≤ FTS5_DRAIN_CHUNK). */\n private async drainEntityChunk(entityId: string): Promise<void> {\n const hiSql = entityDrainHiSql(this.prefix);\n const chunk = entityDrainChunkSql(this.prefix);\n await this.db.withTransactionAsync(async (tx) => {\n const row = await tx.getFirstAsync<{ hi: number | null }>(hiSql, [entityId]);\n if (row?.hi == null) return;\n for (const sql of chunk) await tx.runAsync(sql, [entityId, row.hi]);\n });\n }\n\n async replace(entityId: string, ids: readonly string[], documents: readonly IndexDocument[]): Promise<void> {\n assertEntity(entityId, documents);\n const docIds = documents.map((d) => d.id);\n await this.db.withTransactionAsync(async (tx) => {\n // Caller-supplied ids are scoped to the entity; incoming document ids are\n // un-scoped so a doc that previously lived under another entity gets\n // detached (otherwise the fts_map UNIQUE(id) insert would throw).\n await this.deleteByIds(tx, entityId, ids);\n await this.deleteByIds(tx, null, docIds);\n await this.insertDocs(tx, documents);\n });\n }\n\n async replaceEntity(entityId: string, documents: readonly IndexDocument[]): Promise<void> {\n assertEntity(entityId, documents);\n const p = this.prefix;\n await this.db.withTransactionAsync(async (tx) => {\n await tx.runAsync(\n `DELETE FROM ${p}entries_fts WHERE rowid IN (SELECT fts_rowid FROM ${p}fts_map WHERE entity_id = ?)`, [entityId]);\n await tx.runAsync(`DELETE FROM ${p}fts_map WHERE entity_id = ?`, [entityId]);\n await this.insertDocs(tx, documents);\n });\n }\n\n async replaceAll(documents: readonly IndexDocument[]): Promise<void> {\n const p = this.prefix;\n await this.db.withTransactionAsync(async (tx) => {\n await tx.execAsync(`DELETE FROM ${p}entries_fts; DELETE FROM ${p}fts_map; DELETE FROM ${p}fts_pending;`);\n await this.insertDocs(tx, documents);\n });\n }\n\n async search(query: string, options: IndexSearchOptions): Promise<IndexSearchResult[]> {\n if (options.entityIds.length === 0) return [];\n const match = buildFtsMatchQuery(query);\n if (match === null) return [];\n const cap = options.preFilterLimit ?? options.limit;\n const limit = cap >= Number.MAX_SAFE_INTEGER ? -1 : cap;\n const t = `${this.prefix}entries_fts`;\n // bm25 is evaluated once per matching row in the inner query; the outer\n // SELECT only clamps and negates it. The outer ORDER BY is kept because SQL\n // does not guarantee a subquery's order survives into the outer query; it\n // sorts at most `limit` rows.\n return this.db.getAllAsync<IndexSearchResult>(\n `SELECT id, entity_id, max(0.0, -raw) AS score FROM (\n SELECT id, entity_id, bm25(${t}, 0.0, 0.0, 2.0, 1.0, 1.0) AS raw\n FROM ${t}\n WHERE ${t} MATCH ? AND entity_id IN (SELECT value FROM json_each(?))\n ORDER BY raw, id\n LIMIT ?)\n ORDER BY raw, id`,\n [match, JSON.stringify(options.entityIds), limit],\n );\n }\n\n private async deleteByIds(tx: SQLiteAdapter, entityId: string | null, ids: readonly string[]): Promise<void> {\n if (ids.length === 0) return;\n const p = this.prefix;\n const json = JSON.stringify(ids);\n const whereEntity = entityId === null ? '' : ' AND entity_id = ?';\n // `json_each(?)` is the first placeholder; the optional `entity_id = ?` follows it.\n const args: unknown[] = [json];\n if (entityId !== null) args.push(entityId);\n await tx.runAsync(\n `DELETE FROM ${p}entries_fts WHERE rowid IN (\n SELECT fts_rowid FROM ${p}fts_map WHERE id IN (SELECT value FROM json_each(?))${whereEntity})`,\n args);\n await tx.runAsync(\n `DELETE FROM ${p}fts_map WHERE id IN (SELECT value FROM json_each(?))${whereEntity}`, args);\n }\n\n /** One INSERT pair per document: a throw part-way rolls back the whole transaction. */\n private async insertDocs(tx: SQLiteAdapter, documents: readonly IndexDocument[]): Promise<void> {\n const p = this.prefix;\n for (const d of documents) {\n const { lastInsertRowId } = await tx.runAsync(\n `INSERT INTO ${p}fts_map (id, entity_id) VALUES (?, ?)`, [d.id, d.entity_id]);\n await tx.runAsync(\n `INSERT INTO ${p}entries_fts (rowid, id, entity_id, title, body, tags) VALUES (?, ?, ?, ?, ?, ?)`,\n [lastInsertRowId, d.id, d.entity_id, d.title, d.body, d.tags]);\n }\n }\n\n /** The init probes' schema facts in one sqlite_master read (#284 review): FTS tables with their DDL, and the triggers. */\n private async readSchema(): Promise<{ tables: Map<string, string | null>; triggersPresent: boolean }> {\n const p = this.prefix;\n const triggers = fts5TriggerNames(p);\n const names = [`${p}entries_fts`, `${p}fts_map`, `${p}fts_pending`, ...triggers];\n const rows = await this.db.getAllAsync<{ type: string; name: string; sql: string | null }>(\n `SELECT type, name, sql FROM sqlite_master WHERE name IN (${names.map(() => '?').join(', ')})`, names);\n const tables = new Map(rows.filter((r) => r.type === 'table').map((r) => [r.name, r.sql] as const));\n const present = new Set(rows.filter((r) => r.type === 'trigger').map((r) => r.name));\n return { tables, triggersPresent: triggers.every((n) => present.has(n)) };\n }\n}\n\ntype WindowStep = 'more' | 'done' | 'stale';\n\nclass FtsOnlyStatementError extends Error {\n readonly ftsOnlyCause: unknown;\n constructor(cause: unknown) {\n super('FTS-only statement failed');\n this.ftsOnlyCause = cause;\n }\n}\n\n/** Proxy-safe unwrap (issue #96): never `instanceof` a caught value bare. */\nfunction unwrapFtsOnly(err: unknown): { cause: unknown; ftsOnly: boolean } {\n try {\n if (err instanceof FtsOnlyStatementError) return { cause: err.ftsOnlyCause, ftsOnly: true };\n } catch { /* hostile Proxy */ }\n return { cause: err, ftsOnly: false };\n}\n\n/**\n * Proxy-safe extractSqliteCode (issue #96): any trap => undefined. Also reads\n * WikiTransactionError's `sqliteErrorCode`: the serialized adapter wraps every\n * failed transaction in one, so the driver code is not on `code` (#284 review).\n */\nfunction safeSqliteCode(err: unknown): string | undefined {\n try {\n const code = extractSqliteCode(err);\n if (code !== undefined) return code;\n const lifted = (err as { sqliteErrorCode?: unknown } | null | undefined)?.sqliteErrorCode;\n return typeof lifted === 'string' ? lifted : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Busy/locked, or a code after which SQLite may roll the transaction back (sqlite.org/lang_transaction.html). Extended codes match by primary name. */\nconst TRANSIENT_OR_TX_FATAL = ['SQLITE_BUSY', 'SQLITE_LOCKED', 'SQLITE_FULL', 'SQLITE_IOERR', 'SQLITE_NOMEM', 'SQLITE_INTERRUPT', 'SQLITE_ABORT', 'SQLITE_READONLY'];\n\nfunction isTransientOrTxFatal(err: unknown): boolean {\n const code = safeSqliteCode(err);\n return code !== undefined && TRANSIENT_OR_TX_FATAL.some((c) => code === c || code.startsWith(`${c}_`));\n}\n\n/**\n * 'vtab' for SQLITE_CORRUPT_VTAB (extended code 267, any statement), 'corrupt'\n * for another SQLITE_CORRUPT* code, else null. Proxy-safe: any trap => null.\n */\nexport function ftsCorruptionClass(err: unknown): 'vtab' | 'corrupt' | null {\n const code = safeSqliteCode(err);\n if (code === 'SQLITE_CORRUPT_VTAB') return 'vtab';\n if (code?.startsWith('SQLITE_CORRUPT')) return 'corrupt';\n return null;\n}\n\n/** A SQLite error (better-sqlite3 / expo-sqlite shapes): `code` 'SQLITE_*' or an 'Error code N:' message. Proxy-safe: any trap => false. */\nexport function isSqliteError(err: unknown): boolean {\n return safeSqliteCode(err) !== undefined;\n}\n\nfunction assertEntity(entityId: string, documents: readonly IndexDocument[]): void {\n for (const d of documents) {\n if (d.entity_id !== entityId) {\n throw new TypeError(`IndexDocument ${d.id} has entity_id ${d.entity_id}, expected ${entityId}`);\n }\n }\n}\n","// packages/core/src/services/search/MiniSearchIndexStrategy.ts\n\nimport MiniSearch from 'minisearch';\nimport type { SQLiteAdapter } from '../../types';\nimport type {\n IndexDocument,\n IndexSearchOptions,\n IndexSearchResult,\n IndexStrategy,\n PassageHit,\n} from './IndexStrategy';\nimport { hydratePassageHits } from './Fts5IndexStrategy';\n\ninterface PassageDoc { id: string; entity_id: string; document_id: string; text: string }\n\nexport type { PassageSearchResult } from './Fts5IndexStrategy';\n\n/**\n * Passage slices of one entity, cut from `source_documents.text` at the stored\n * UTF-16 offsets. Reads one document at a time.\n */\nasync function loadStoredPassages(db: SQLiteAdapter, prefix: string, entityId: string): Promise<PassageDoc[]> {\n const out: PassageDoc[] = [];\n const docs = await db.getAllAsync<{ id: string }>(`SELECT id FROM ${prefix}source_documents WHERE entity_id = ?`, [entityId]);\n for (const d of docs) {\n const doc = await db.getFirstAsync<{ text: string }>(`SELECT text FROM ${prefix}source_documents WHERE id = ?`, [d.id]);\n if (!doc) continue;\n const rows = await db.getAllAsync<{ id: string; start_offset: number; end_offset: number }>(\n `SELECT id, start_offset, end_offset FROM ${prefix}source_passages WHERE document_id = ? ORDER BY seq`, [d.id]);\n for (const r of rows) {\n out.push({ id: r.id, entity_id: entityId, document_id: d.id, text: doc.text.slice(Number(r.start_offset), Number(r.end_offset)) });\n }\n }\n return out;\n}\n\n/**\n * In-RAM keyword index. Extracted from `SearchService` without behavior\n * change. The strategy owns the MiniSearch instance, the `entryIdsByEntity`\n * tracking map, the `entityIdById` reverse map, and the explicit-vacuum\n * policy (#64).\n *\n * Memory cost: O(total text). The fix for #257 lives in PR-2's FTS5\n * strategy; this one stays for Expo/OPFS environments without FTS5 and for\n * hosts that explicitly pin `WikiConfig.indexStrategy: 'minisearch'`.\n */\nexport class MiniSearchIndexStrategy implements IndexStrategy {\n private index: MiniSearch<IndexDocument>;\n /**\n * Per-entity id set. `replaceEntity()` and `hasIndexedEntity()` read it;\n * `addDocuments()` and `discardIds()` keep it in sync. `SearchService` does\n * not see this map; it only sees `hasIndexedEntity`. The previous\n * `miniSearchEntryIdsByEntity` lived on `SearchService`.\n */\n private entryIdsByEntity = new Map<string, Set<string>>();\n /**\n * Reverse of `entryIdsByEntity`. `replace(entityId, ids, …)` uses it to\n * decide which ids are owned by `entityId` (the only safe membership test\n * — a rebuild that failed between its discard pass and the set replacement\n * can leave the forward set claiming ids the MiniSearch instance does not\n * hold). The pre-extraction `syncEntries` deleted from one set per id, not\n * from every entity's set.\n */\n private entityIdById = new Map<string, string>();\n\n constructor() {\n this.index = this.createIndex();\n }\n\n /**\n * Build a fresh MiniSearch instance with the project's index options.\n * Called from the constructor and from `replaceAll`. We do not use\n * `removeAll()` on an existing instance because that empties the index but\n * leaves `dirtCount` and the vacuum bookkeeping intact, which would trip\n * `syncEntries`' conditional vacuum early after a clear.\n */\n private createIndex(): MiniSearch<IndexDocument> {\n return new MiniSearch({\n fields: ['title', 'body', 'tags'],\n storeFields: ['entity_id'],\n // Vacuuming is driven explicitly at the end of each serialized rebuild\n // (see SearchService.syncEntries). Auto-vacuum fires on its own\n // schedule, asynchronously with respect to the caller, and traversing\n // the tree mid-rebuild is what threw the uncaught TypeError in\n // MiniSearch.performVacuuming (#64).\n autoVacuum: false,\n searchOptions: {\n boost: { title: 2 },\n fuzzy: 0.2,\n prefix: true,\n },\n });\n }\n\n /**\n * Incremental sync. Removes only ids currently tracked under `entityId`\n * (other entities' docs are untouched), then upserts `documents` by id.\n * The same id appearing in both `ids` and `documents` is discarded first\n * so the upsert does not throw on a duplicate id.\n *\n * Every document must carry `entityId` as its `entity_id`; a mismatch is\n * rejected before the write mutates anything. A tracking-only call\n * (`replace(entityId, [], [])`) registers the entity as indexed, matching\n * the interface contract.\n *\n * Atomicity: never awaits between the discard pass and `addDocuments`, so\n * a concurrent `search()` sees the index wholly before or wholly after,\n * never half-updated. This is the precondition the pre-extraction\n * `syncEntries` kept with its \"no await from here to `addAll`\" comment.\n */\n async replace(\n entityId: string,\n ids: readonly string[],\n documents: readonly IndexDocument[],\n ): Promise<void> {\n assertOwnedBy(entityId, documents);\n this.discardIds(ids, entityId);\n if (!this.entryIdsByEntity.has(entityId)) this.entryIdsByEntity.set(entityId, new Set());\n this.addDocuments(documents);\n }\n\n /**\n * Per-entity rebuild. Removes every id tracked under `entityId` (with the\n * `index.has(id)` guard so a stale tracking set cannot make `discard()`\n * throw), then writes `documents`. The entity stays registered as\n * indexed — even when `documents` is empty — so the next `syncEntries`\n * call can take the fast path. Every document must belong to `entityId`.\n */\n async replaceEntity(entityId: string, documents: readonly IndexDocument[]): Promise<void> {\n assertOwnedBy(entityId, documents);\n const previous = this.entryIdsByEntity.get(entityId);\n if (previous) this.discardIds([...previous]);\n // Registered even when empty, so hasIndexedEntity(entityId) === true.\n this.entryIdsByEntity.set(entityId, new Set());\n this.addDocuments(documents);\n }\n\n /**\n * Global rebuild / clear. Replaces the MiniSearch instance and clears both\n * id maps, so `hasIndexedEntity` returns `false` for every entity afterwards.\n * `SearchService.clearAll()` calls `replaceAll([])`.\n */\n async replaceAll(documents: readonly IndexDocument[]): Promise<void> {\n this.index = this.createIndex();\n this.entryIdsByEntity.clear();\n this.entityIdById.clear();\n this.addDocuments(documents);\n }\n\n /**\n * Best-match-first search over the documents whose `entity_id` is in\n * `options.entityIds`. `preFilterLimit` overrides `limit` (hybrid retrieval\n * uses this to over-fetch candidates before the `limit` cap). Scores are\n * raw BM25+ — `SearchService.getKeywordScores` and `searchKeyword` apply\n * any scaling, not the strategy.\n */\n async search(query: string, options: IndexSearchOptions): Promise<IndexSearchResult[]> {\n if (options.entityIds.length === 0) return [];\n const entityIdSet = new Set(options.entityIds);\n const limit = options.preFilterLimit ?? options.limit;\n const raw = this.index.search(query, {\n filter: (r) => entityIdSet.has(r.entity_id as string),\n combineWith: 'OR',\n });\n // Tiebreak equal-score results by id before slicing: MiniSearch breaks\n // ties by internal insertion order, which the strategy's own\n // discard/add changes. Callers truncate to a `limit`, so the ids\n // surviving a tie at the boundary must not depend on write history.\n raw.sort((a, b) => {\n const scoreDiff = b.score - a.score;\n if (!Number.isNaN(scoreDiff) && scoreDiff !== 0) return scoreDiff;\n return a.id.localeCompare(b.id);\n });\n // `storeFields: ['entity_id']` puts entity_id on every result.\n return raw.slice(0, limit).map((r) => ({\n id: r.id,\n entity_id: r.entity_id as string,\n score: r.score,\n }));\n }\n\n // ---- Source-store passage index (spec source-store §6) --------------------\n // A second in-heap instance over the same passage slices as the FTS5 path.\n\n private passageIndex: MiniSearch<PassageDoc> = this.createPassageIndex();\n private passageIdsByEntity = new Map<string, Set<string>>();\n /** Handle `reindexSourcePassages` last indexed from; `searchPassages` hydrates hits through it. */\n private passageSource: { db: SQLiteAdapter; prefix: string } | null = null;\n\n private createPassageIndex(): MiniSearch<PassageDoc> {\n return new MiniSearch({\n fields: ['text'],\n storeFields: ['entity_id', 'document_id'],\n autoVacuum: false, // explicit vacuum below, same reason as the facts instance (#64)\n searchOptions: { fuzzy: 0.2, prefix: true },\n });\n }\n\n /**\n * Re-index stored passages from SQLite: one entity, or every stored entity\n * when `entityId` is omitted (the open-time pass; up to `maxTotalChars` per\n * entity, and the heap grows with the number of stored entities, spec §6).\n * It is also the post-commit sync after forget/clearAll: deleted passages\n * drop out because the reload no longer finds their rows (spec §5).\n * Reads happen first; the discard and add are synchronous, so the swap is\n * atomic (a concurrent search sees the index wholly before or wholly after),\n * and the vacuum runs after the swap.\n */\n async reindexSourcePassages(db: SQLiteAdapter, prefix: string, entityId?: string): Promise<void> {\n this.passageSource = { db, prefix };\n const entityIds = entityId !== undefined\n ? [entityId]\n : [...new Set([\n ...(await db.getAllAsync<{ entity_id: string }>(`SELECT DISTINCT entity_id FROM ${prefix}source_documents`)).map((r) => r.entity_id),\n ...this.passageIdsByEntity.keys(),\n ])];\n for (const id of entityIds) {\n const passages = await loadStoredPassages(db, prefix, id);\n for (const old of this.passageIdsByEntity.get(id) ?? []) {\n if (this.passageIndex.has(old)) this.passageIndex.discard(old);\n }\n const ids = new Set<string>();\n for (const d of passages) { this.passageIndex.add({ ...d }); ids.add(d.id); }\n if (ids.size > 0) this.passageIdsByEntity.set(id, ids);\n else this.passageIdsByEntity.delete(id);\n if (this.passageIndex.dirtCount > 0) await this.passageIndex.vacuum();\n }\n }\n\n /** Best-match-first passage search over the entities in `options.entityIds`. */\n async searchPassages(query: string, options: { entityIds: string[]; limit: number }): Promise<PassageHit[]> {\n if (options.entityIds.length === 0 || !this.passageSource) return [];\n const allowed = new Set(options.entityIds);\n const raw = this.passageIndex.search(query, { filter: (r) => allowed.has(r.entity_id as string), combineWith: 'OR' });\n raw.sort((a, b) => (b.score - a.score) || a.id.localeCompare(b.id));\n // The index may hold rows deleted after it loaded; a hit counts only\n // while its source_passages row exists (spec §5). Drop dead rows BEFORE\n // slicing, so a deleted passage never consumes a limit slot a live one\n // can fill (the FTS5 path's SQL join does the same). One indexed lookup\n // per entity.\n const live = new Set<string>();\n for (const eid of options.entityIds) {\n const rows = await this.passageSource.db.getAllAsync<{ id: string }>(\n `SELECT id FROM ${this.passageSource.prefix}source_passages WHERE entity_id = ?`, [eid]);\n for (const row of rows) live.add(row.id);\n }\n const hits = raw.filter((r) => live.has(r.id as string)).slice(0, options.limit).map((r) => ({\n id: r.id as string, entity_id: r.entity_id as string, document_id: r.document_id as string, score: r.score,\n }));\n return hydratePassageHits(this.passageSource.db, this.passageSource.prefix, hits);\n }\n\n /**\n * Explicit vacuum. MiniSearch 7.2.0's `dirtCount` rule: search after an\n * un-vacuumed discard inverts the relative scores of term-sharing\n * documents at any index size. `SearchService.syncEntries` calls this\n * after a discard-bearing turn. No-op when `dirtCount === 0`.\n */\n async vacuum(): Promise<void> {\n if (this.index.dirtCount > 0) {\n await this.index.vacuum();\n }\n }\n\n /**\n * `true` when `entityId` has been indexed at least once under the current\n * strategy state. Backed by `entryIdsByEntity.has(entityId)`, which is\n * kept in sync by `addDocuments`, `replaceEntity`, and `replaceAll`.\n */\n hasIndexedEntity(entityId: string): boolean {\n return this.entryIdsByEntity.has(entityId);\n }\n\n /**\n * Add `documents` to the MiniSearch instance and register them in\n * `entryIdsByEntity` and `entityIdById`. MiniSearch mutates documents\n * during `add`, so each doc is copied first. `add` throws on an id the\n * index already holds — `replace` and `replaceEntity` discard first for\n * that reason.\n *\n * Adds and registers one document at a time: if a duplicate id throws\n * part-way through, every document already in the index is tracked, so\n * the next rebuild can discard it instead of failing on it again. This is\n * the precondition the per-turn recovery path relies on (#258 review).\n */\n private addDocuments(documents: readonly IndexDocument[]): void {\n for (const d of documents) {\n const doc: IndexDocument = { ...d };\n this.index.add(doc);\n const set = this.entryIdsByEntity.get(doc.entity_id) ?? new Set<string>();\n set.add(doc.id);\n this.entryIdsByEntity.set(doc.entity_id, set);\n this.entityIdById.set(doc.id, doc.entity_id);\n }\n }\n\n /**\n * Discard `ids` from the MiniSearch instance and from both id maps, but\n * only for ids currently owned by `entityId` (the second argument). When\n * `entityId` is omitted (used by `replaceEntity` for the bulk rebuild\n * path), every id is discarded regardless of owning entity.\n *\n * `index.has(id)` is the membership test of record: a rebuild that failed\n * between its own discard pass and the set replacement can leave the\n * tracking set claiming ids the index no longer holds — `discard()` throws\n * on those, so we guard.\n */\n private discardIds(ids: readonly string[], entityId?: string): void {\n for (const id of ids) {\n // Scope check first: an id not owned by `entityId` is silently ignored.\n // Doing the scope check before `index.discard` is what stops a\n // `replace(entityId, ids, …)` call from touching docs under any other\n // entity.\n const owning = this.entityIdById.get(id);\n if (owning === undefined) continue;\n if (entityId !== undefined && owning !== entityId) continue;\n if (this.index.has(id)) this.index.discard(id);\n this.entryIdsByEntity.get(owning)?.delete(id);\n this.entityIdById.delete(id);\n }\n }\n}\n\n/**\n * `replace` and `replaceEntity` write under one entity. A document carrying a\n * different `entity_id` would land in another entity's tracking set (and\n * have no safe discard path), so the write rejects before mutating anything.\n */\nfunction assertOwnedBy(entityId: string, documents: readonly IndexDocument[]): void {\n for (const doc of documents) {\n if (doc.entity_id !== entityId) {\n throw new Error(\n `IndexStrategy write for entity ${entityId} got document ${doc.id} under entity ${doc.entity_id}`,\n );\n }\n }\n}","// packages/core/src/services/search/createIndexStrategy.ts\nimport type { SQLiteAdapter } from '../../types';\nimport type { MetadataRepository } from '../../repositories/MetadataRepository';\nimport type { IndexStrategy } from './IndexStrategy';\nimport { Fts5IndexStrategy } from './Fts5IndexStrategy';\nimport { MiniSearchIndexStrategy } from './MiniSearchIndexStrategy';\nimport { UnavailableIndexStrategy } from './UnavailableIndexStrategy';\nimport { FTS5_STATE_KEY, fts5LedgerDropSql, passageFtsTriggerNames } from './fts5Sql';\n\nexport type IndexStrategyPreference = 'fts5' | 'minisearch' | 'auto';\n\nexport const FTS5_INIT_RETRY_MS = 250;\n\n/** True only for errors meaning the module is genuinely absent (permanent). Proxy-safe. */\nfunction isModuleAbsentError(err: unknown): boolean {\n // Walk a short cause chain: some adapters wrap the SQLite message.\n let cur: unknown = err;\n for (let depth = 0; depth < 3 && cur != null; depth++) {\n let msg = '';\n try { msg = String((cur as { message?: unknown }).message ?? cur); } catch { return false; }\n if (/no such module: fts5/i.test(msg) || /no such function: json_valid/i.test(msg)) return true;\n try { cur = (cur as { cause?: unknown }).cause; } catch { return false; }\n }\n return false;\n}\n\n/**\n * Whether this SQLite build has FTS5 and json1 (the drain needs both). The\n * probe table lives in `temp`, so the database file is never touched.\n * Returns false ONLY when the module is genuinely absent; any other error\n * (SQLITE_IOERR, NOMEM, INTERRUPT, ...) is rethrown so the caller treats it\n * as a transient init failure instead of detaching a healthy store\n * (spec #280 Change 4).\n */\nexport async function probeFts5(db: SQLiteAdapter, prefix: string): Promise<boolean> {\n const name = `temp.${prefix}fts5_probe`;\n try {\n await db.execAsync(`CREATE VIRTUAL TABLE IF NOT EXISTS ${name} USING fts5(x)`);\n const row = await db.getFirstAsync<{ ok: number }>(`SELECT json_valid('[]') AS ok`);\n return row?.ok === 1;\n } catch (err) {\n if (isModuleAbsentError(err)) return false;\n throw err;\n } finally {\n try { await db.execAsync(`DROP TABLE IF EXISTS ${name}`); } catch { /* module absent */ }\n }\n}\n\n/**\n * Stop maintaining the FTS5 ledger: drop the passage-side objects first\n * (triggers, map and ledger in one transaction; the virtual-table drop is\n * module-gated and its failure swallowed — the bootstrap in\n * ensurePassageObjects clears any stale virtual-table content when it\n * re-seeds on re-attach), then the entries-side triggers and ledger, and\n * entries_fts itself. Mark the database detached, so a later FTS5 open\n * rebuilds: the virtual tables are dropped best-effort; without the fts5\n * module they cannot be, and the next FTS5 init recreates them anyway.\n */\nexport async function detachFts5(db: SQLiteAdapter, prefix: string, metadataRepo: MetadataRepository): Promise<void> {\n // Passage-side objects go first, and independently of the entries-side gate\n // (CodeRabbit/T3 follow-up): a store that ran FTS5 keeps the passage triggers\n // live after detach, so every store write enqueues a ledger row nothing ever\n // drains — unbounded growth. On re-attach the bootstrap re-seeds the emptied\n // map/ledger and clears any stale virtual-table content its failed drop left\n // behind (its probes + insert + clear run inside the DDL transaction).\n const passageLedger = await metadataRepo.tableExists(`${prefix}source_passages_fts_pending`);\n if (passageLedger) {\n const [ai, ad] = passageFtsTriggerNames(prefix);\n await db.withTransactionAsync(async (tx) => {\n await tx.execAsync(\n `DROP TRIGGER IF EXISTS ${ai};\\nDROP TRIGGER IF EXISTS ${ad};\\n` +\n `DROP TABLE IF EXISTS ${prefix}source_passages_fts_map;\\nDROP TABLE IF EXISTS ${prefix}source_passages_fts_pending;`);\n });\n // The virtual table needs the fts5 module, like entries_fts below.\n try { await db.execAsync(`DROP TABLE IF EXISTS ${prefix}source_passages_fts`); } catch { /* no fts5 module */ }\n }\n const hasLedger = await metadataRepo.tableExists(`${prefix}fts_pending`);\n const state = await metadataRepo.getMeta(FTS5_STATE_KEY);\n if (!hasLedger && state !== 'live') return;\n await db.withTransactionAsync(async (tx) => {\n await tx.execAsync(fts5LedgerDropSql(prefix));\n await metadataRepo.setMeta(FTS5_STATE_KEY, 'detached', tx);\n });\n try { await db.execAsync(`DROP TABLE IF EXISTS ${prefix}entries_fts`); } catch { /* no fts5 module */ }\n}\n\n/** Resolve the keyword-index strategy for this database. Failure ordering per spec #280 Change 4. */\nexport async function createIndexStrategy(\n db: SQLiteAdapter,\n prefix: string,\n metadataRepo: MetadataRepository,\n preferred: IndexStrategyPreference,\n opts: { setupBudgetMs?: number; entriesExisted?: boolean } = {},\n): Promise<IndexStrategy> {\n if (preferred === 'minisearch') {\n await detachFts5(db, prefix, metadataRepo); // operator's explicit choice\n return new MiniSearchIndexStrategy();\n }\n const attempt = async (): Promise<IndexStrategy | 'absent'> => {\n if (!(await probeFts5(db, prefix))) return 'absent';\n const strategy = new Fts5IndexStrategy(db, prefix, metadataRepo, opts.setupBudgetMs);\n await strategy.init({ entriesExisted: opts.entriesExisted });\n return strategy;\n };\n const absent = async (): Promise<IndexStrategy> => {\n if (preferred === 'fts5') {\n throw new Error(`indexStrategy 'fts5' was requested, but this SQLite build lacks FTS5 or json1.`);\n }\n await detachFts5(db, prefix, metadataRepo); // module genuinely absent: permanent\n return new MiniSearchIndexStrategy();\n };\n\n for (let tries = 1; ; tries++) {\n try {\n const s = await attempt();\n return s === 'absent' ? await absent() : s;\n } catch (err) {\n if (preferred === 'fts5') throw err; // pinned: surface the raw failure\n if (tries === 2) {\n // Never detachFts5 here: a transient failure must not drop the ledger and\n // route a large store into MiniSearch's full sync (measured OOM).\n console.warn('[WikiMemory] FTS5 init failed after retry; keyword search unavailable until a later open or syncSearchIndex():', err);\n return new UnavailableIndexStrategy(err);\n }\n }\n await new Promise((resolve) => setTimeout(resolve, FTS5_INIT_RETRY_MS));\n }\n}\n","import type { OntologyConfig } from '../../types';\n\n/**\n * The one place the ontology-backfill scheduler default is defined\n * (specs/system-one-config §8). Read sites resolve through this so a host\n * that sets nothing gets the same answer everywhere — the same discipline as\n * `engineDefaults.ts` for the 8.0.0 librarian/maintenance defaults.\n */\n\n/** Default batch size for scheduler-driven ontology backfill passes. */\nexport const DEFAULT_ONTOLOGY_JOB_BATCH_SIZE = 50;\n\nexport interface OntologyJobDefaults {\n batchSize: number;\n}\n\n/**\n * Resolve the scheduler's ontology-backfill batch size from\n * `WikiConfig.ontology.schedulerBatchSize`. Invalid values (non-finite, < 1)\n * fall back to the default rather than throwing — a bad config value degrades\n * to the default instead of breaking construction or every run.\n */\nexport function resolveOntologyJobDefaults(ontology: OntologyConfig | undefined): OntologyJobDefaults {\n const raw = ontology?.schedulerBatchSize;\n const batchSize = typeof raw === 'number' && Number.isInteger(raw) && raw >= 1 ? raw : DEFAULT_ONTOLOGY_JOB_BATCH_SIZE;\n return { batchSize };\n}\n","import type {\n SQLiteAdapter,\n WikiOptions,\n PendingMaintenance,\n MaintenanceJob,\n LockedMaintenanceJob,\n MaintenanceStopReason,\n EntityMaintenanceReport,\n RunPendingMaintenanceOptions,\n RunPendingMaintenanceResult,\n HealResult,\n OntologyBackfillResult,\n} from '../types';\nimport { WikiBusyError, isWikiSearchUnavailableError } from '../types';\nimport { MaintenanceService, MAX_EMBED_ATTEMPTS } from './MaintenanceService';\nimport type { LibrarianResult } from './librarian';\nimport { UsageMeter } from '../utils/usage';\nimport { resolveOntologyJobDefaults } from '../utils/config/ontologyJobDefaults';\nimport { MetadataRepository } from '../repositories/MetadataRepository';\nimport { EventRepository } from '../repositories/EventRepository';\nimport { EntryRepository } from '../repositories/EntryRepository';\nimport { JobManager } from './JobManager';\nimport type { VectorRemovalService } from './VectorRemovalService';\nimport type { VectorRemovalRepository } from '../repositories/VectorRemovalRepository';\n\n/**\n * Read-side report for the deferred maintenance mode: which entities have\n * pending work (librarian events behind the watermark, heal backlog, unembedded\n * facts) without running anything. `run` executes the work (PR-C task 4).\n */\nexport class MaintenanceScheduler {\n constructor(\n private db: SQLiteAdapter,\n private options: WikiOptions,\n private maintenanceService: MaintenanceService,\n private metadataRepo: MetadataRepository,\n private eventRepo: EventRepository,\n private entryRepo: EntryRepository,\n private jobManager: JobManager,\n private vectorRemovalService: VectorRemovalService,\n private vectorRemovalRepo: VectorRemovalRepository,\n ) {}\n\n /** Batch size for scheduler-driven ontology passes; resolved once (spec §8). */\n private readonly schedulerBatchSize: number =\n resolveOntologyJobDefaults(this.options.config?.ontology).batchSize;\n\n /**\n * Entities with **any** pending work only, sorted by `pendingEvents` desc\n * then `entityId` asc. Token estimate is ceil(pending summary chars / 4),\n * matching the auto-trigger's estimator (PR-B).\n */\n async getPending(entityIds?: string[]): Promise<PendingMaintenance[]> {\n const ids = entityIds ?? await this.metadataRepo.getDistinctEntityIds();\n const autoHealThreshold = this.options.config?.autoHealThreshold || 100;\n const canEmbed = typeof this.options.llmProvider.embed === 'function';\n const out: PendingMaintenance[] = [];\n const owed = new Map<string, number>();\n if (this.vectorRemovalService.gate() !== 'none' && (await this.vectorRemovalService.ledgerPresent())) {\n const scope = entityIds === undefined ? undefined : new Set(entityIds);\n // Only entities with a row outside backoff: a failing hook must not keep the list non-empty.\n for (const e of await this.vectorRemovalRepo.entitiesWithDuePending(Date.now())) {\n if (scope !== undefined && !scope.has(e)) continue;\n owed.set(e, (await this.vectorRemovalRepo.pendingStats(e)).count);\n }\n }\n const listed = new Set(ids);\n const scan = [...ids, ...[...owed.keys()].filter((e) => !listed.has(e))];\n for (const entityId of scan) {\n const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);\n const pendingEvents = await this.eventRepo.countAfter(entityId, wm);\n const chars = pendingEvents > 0 ? await this.eventRepo.sumSummaryCharsAfter(entityId, wm) : 0;\n const eventCount = await this.eventRepo.count(entityId);\n const cp = await this.metadataRepo.getCheckpoint(entityId, this.db);\n // Same clamp as WriteService.maybeRunHeal: an out-of-range checkpoint\n // (reachable after runPrune deletes events a heal pass already counted)\n // resets to ZERO, not to the event count — both views must agree that\n // the entity is fully unhealed.\n let healCheckpoint = cp.heal ?? 0;\n if (healCheckpoint > eventCount) healCheckpoint = 0;\n const healDue = eventCount - healCheckpoint >= autoHealThreshold;\n const reembedPending = canEmbed && (await this.entryRepo.countReembedPending(entityId, MAX_EMBED_ATTEMPTS)) > 0;\n const owedCount = owed.get(entityId) ?? 0;\n const ontologyBackfillPending = await this.maintenanceService.pendingOntologyBackfill(entityId);\n if (pendingEvents > 0 || healDue || reembedPending || owedCount > 0 || ontologyBackfillPending > 0) {\n out.push({\n entityId, pendingEvents, pendingTokensEstimate: Math.ceil(chars / 4), healDue, reembedPending,\n ...(owedCount > 0 ? { pendingExternalDeletions: owedCount } : {}),\n ...(ontologyBackfillPending > 0 ? { pendingOntologyBackfill: ontologyBackfillPending } : {}),\n });\n }\n }\n return out.sort((x, y) => (y.pendingEvents - x.pendingEvents) || (x.entityId < y.entityId ? -1 : x.entityId > y.entityId ? 1 : 0));\n }\n\n /**\n * Execute pending maintenance (spec §6.2): fair-share rounds of at most one\n * unit per entity (librarian batch, else heal batch, else reembed), entities\n * ordered by `getPending` (pendingEvents desc, id asc). Holds the same\n * per-entity `JobManager` locks a manual run would; a busy entity is skipped\n * and reported, never thrown. Nothing is still running when this resolves.\n *\n * Stop precedence (spec §10 items 3-6): `deadline` > `budget_exhausted` >\n * `budget_too_small` > `complete`. `budget_too_small` means a job's smallest\n * unit needs more than the WHOLE budget — that job is skipped this run and\n * the run continues; `budget_exhausted` means a unit needs more than what\n * REMAINS — the run stops. The token budget meters generation and classify\n * calls; embeddings are never metered.\n */\n async run(opts: RunPendingMaintenanceOptions = {}): Promise<RunPendingMaintenanceResult> {\n if (\n opts.deadlineMs !== undefined &&\n (typeof opts.deadlineMs !== 'number' || !Number.isFinite(opts.deadlineMs) || opts.deadlineMs < 0)\n ) {\n throw new TypeError('deadlineMs must be a finite number >= 0');\n }\n const meter = new UsageMeter(opts.tokenBudget);\n const budget = opts.tokenBudget;\n const deadline = opts.deadlineMs !== undefined ? Date.now() + Math.max(0, opts.deadlineMs) : Infinity;\n const jobs = new Set<MaintenanceJob>(opts.jobs ?? ['librarian', 'heal', 'reembed', 'externalDeletions', 'ontologyBackfill']);\n const externalDeletions = await this.runExternalDeletions(opts.entityIds, jobs.has('externalDeletions'), deadline);\n // Removal-only entities are reported by externalDeletions, not as per-entity maintenance.\n const pending = (await this.getPending(opts.entityIds)).filter((p) => p.pendingEvents > 0 || p.healDue || p.reembedPending || (p.pendingOntologyBackfill ?? 0) > 0);\n\n type State = { p: PendingMaintenance; report: EntityMaintenanceReport; librarian: boolean; heal: boolean; reembed: boolean; ontology: boolean };\n const states: State[] = pending.map((p) => ({\n p,\n report: { entityId: p.entityId, librarianPasses: 0, factsWritten: 0, healPasses: 0, reembedded: false, ontologyBackfillPasses: 0, typed: 0 },\n librarian: jobs.has('librarian') && p.pendingEvents > 0,\n heal: jobs.has('heal') && p.healDue,\n reembed: jobs.has('reembed') && p.reembedPending,\n ontology: jobs.has('ontologyBackfill') && (p.pendingOntologyBackfill ?? 0) > 0,\n }));\n\n let stopped: MaintenanceStopReason = { reason: 'complete' };\n let tooSmall: MaintenanceStopReason | null = null;\n const classify = (job: 'librarian' | 'heal' | 'ontologyBackfill', entityId: string, requiredEstimate: number): 'too_small' | 'exhausted' => {\n if (budget !== undefined && requiredEstimate > budget) {\n tooSmall ??= { reason: 'budget_too_small', job, entityId, requiredEstimate };\n return 'too_small';\n }\n return 'exhausted';\n };\n // A unit that ends with the meter exhausted made real awaited LLM calls,\n // so the deadline may have lapsed mid-unit too. Precedence is deadline\n // first (spec §10): the caller must be told to retry as-is, not to raise\n // the budget. Re-checked here because the between-units deadline check\n // only runs before a unit starts, never after one ends.\n const exhaustedStop = (): MaintenanceStopReason =>\n Date.now() >= deadline ? { reason: 'deadline' } : { reason: 'budget_exhausted' };\n const markBusy = (st: State, job: LockedMaintenanceJob) => { (st.report.busy ??= []).push(job); };\n const markSearchUnavailable = (st: State, job: LockedMaintenanceJob) => { (st.report.searchUnavailable ??= []).push(job); };\n\n // Open job flags across all entities. Flags only ever clear, so a round\n // that clears one (a skip: busy, outage, too small, nothing processed)\n // counts as progress — it must re-run so the entity reaches its later\n // jobs — and the loop still terminates.\n const openJobs = () => states.reduce((n, s) => n + +s.librarian + +s.heal + +s.reembed + +s.ontology, 0);\n\n rounds: for (;;) {\n let progressed = false;\n const openAtStart = openJobs();\n for (const st of states) {\n if (!st.librarian && !st.heal && !st.reembed && !st.ontology) continue;\n if (Date.now() >= deadline) { stopped = { reason: 'deadline' }; break rounds; }\n const entityId = st.p.entityId;\n\n if (st.librarian) {\n if (this.jobManager.isBlocked('librarian', entityId)) { st.librarian = false; markBusy(st, 'librarian'); continue; }\n this.jobManager.acquireLock('librarian', entityId);\n let r: LibrarianResult;\n try {\n r = await this.maintenanceService.runLibrarianPass({ entityId, trigger: 'call', meter });\n } catch (err) {\n // Keyword outage: this entity's pass aborted with its watermark kept.\n // Skip it for this run rather than failing every other entity's work.\n if (!isWikiSearchUnavailableError(err)) throw err;\n st.librarian = false;\n markSearchUnavailable(st, 'librarian');\n continue;\n } finally {\n this.jobManager.releaseLock('librarian', entityId);\n }\n if (r.budgetStop) {\n if (classify('librarian', entityId, r.budgetStop.requiredEstimate) === 'exhausted') { stopped = exhaustedStop(); break rounds; }\n st.librarian = false;\n continue;\n }\n if (!r.processedThrough) { st.librarian = false; continue; }\n st.report.librarianPasses++;\n st.report.factsWritten += r.factsWritten;\n if (r.typing) st.report.typedOnWrite = (st.report.typedOnWrite ?? 0) + r.typing.typed;\n progressed = true;\n // Budget exhausted during write-time typing: the pass wrote its facts and\n // recorded them above; the run stops as exhausted rather than 'complete'.\n if ((r.typing?.unattempted ?? 0) > 0) { stopped = exhaustedStop(); break rounds; }\n const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);\n if ((await this.eventRepo.countAfter(entityId, wm)) === 0) st.librarian = false;\n continue;\n }\n\n if (st.heal) {\n if (this.jobManager.isBlocked('heal', entityId)) { st.heal = false; markBusy(st, 'heal'); continue; }\n this.jobManager.acquireLock('heal', entityId);\n let h: HealResult;\n try {\n h = await this.maintenanceService.doRunHeal(entityId, { trigger: 'call', meter });\n // Write the checkpoint while the heal lock still blocks prune. A\n // prune between the count read and the write would leave heal\n // above the event count, which reads as 0 and starts a full\n // re-heal (spec ops-auto-first-batch §4).\n if (h.remaining === 0 && !(h.budgetStop && h.scanned === 0)) {\n await this.metadataRepo.updateCheckpoint(entityId, { heal: await this.eventRepo.count(entityId) }, this.db);\n }\n } finally {\n this.jobManager.releaseLock('heal', entityId);\n }\n // Defense against future doRunHeal changes: scanned === 0 means the\n // pass bailed before any LLM call, so budgetStop cannot arise there\n // today — but if it ever did, classify it instead of mislabeling a\n // never-started job as exhausted.\n if (h.budgetStop && h.scanned === 0) {\n if (classify('heal', entityId, h.budgetStop.requiredEstimate) === 'exhausted') { stopped = exhaustedStop(); break rounds; }\n st.heal = false;\n continue;\n }\n // Nothing scanned yet candidates remain (e.g. a keyword outage skipped\n // the LLM pass): another round cannot progress, so stop healing this\n // entity for this run instead of looping forever.\n if (h.scanned === 0 && h.remaining > 0) {\n st.heal = false;\n if (h.searchUnavailable) markSearchUnavailable(st, 'heal');\n continue;\n }\n st.report.healPasses++;\n progressed = true;\n if (h.remaining === 0) st.heal = false;\n if (h.budgetStop) { stopped = exhaustedStop(); break rounds; }\n continue;\n }\n\n if (st.reembed) {\n st.reembed = false;\n try {\n await this.maintenanceService.runReembed(entityId);\n st.report.reembedded = true;\n progressed = true;\n } catch (err) {\n if (err instanceof WikiBusyError) markBusy(st, 'reembed');\n else throw err;\n }\n }\n\n if (st.ontology) {\n // The between-units deadline check at the top of the entity\n // iteration ran BEFORE librarian/heal/reembed; an awaited unit can\n // lapse the deadline, and the ontology pass must not start against\n // an expired one. Spec §10 precedence: stop with 'deadline'; the\n // caller retries as-is (nothing was spent here).\n if (Date.now() >= deadline) {\n stopped = { reason: 'deadline' };\n break rounds;\n }\n st.ontology = false;\n if (this.jobManager.isBlocked('ontologyBackfill', entityId)) {\n // Same handling as a busy librarian/heal: a held pass is a real\n // scheduler outcome (the lock is owned by another job right now),\n // so report it and tell the host via `ontology_backfill_held`.\n markBusy(st, 'ontologyBackfill');\n this.maintenanceService.noteOntologyBackfillHeld(entityId);\n progressed = true;\n continue;\n }\n this.jobManager.acquireLock('ontologyBackfill', entityId);\n let r: OntologyBackfillResult;\n try {\n r = await this.maintenanceService.doRunOntologyBackfill(entityId, {\n meter,\n batchSize: this.schedulerBatchSize,\n });\n } finally {\n this.jobManager.releaseLock('ontologyBackfill', entityId);\n }\n st.report.ontologyBackfillPasses++;\n st.report.typed += r.typed;\n progressed = true;\n if (r.budgetStop) {\n if (classify('ontologyBackfill', entityId, r.budgetStop.requiredEstimate) === 'exhausted') {\n // Route through exhaustedStop() like the librarian/heal\n // branches: budget exhaustion is only reported when the budget\n // actually ran out — a deadline that lapsed inside the awaited\n // pass outranks it (spec §10 precedence).\n stopped = exhaustedStop();\n break rounds;\n }\n continue;\n }\n if (r.remaining === 0 || r.typed === 0) {\n // Converged, or this pass typed nothing it can ever type (every\n // candidate failed validation) — a further pass would burn rounds\n // without progress, so stop driving the job for this entity.\n continue;\n }\n // More eligible facts remain and this pass made typing progress; the\n // job stays closed for this run — leftover work waits for the next\n // run() (host convergence signal: getPendingMaintenance).\n }\n }\n if (!progressed && openJobs() === openAtStart) break;\n }\n\n if (stopped.reason === 'complete' && tooSmall) stopped = tooSmall;\n return {\n perEntity: states.map((s) => s.report),\n tokensUsed: meter.used,\n estimated: meter.estimated,\n remaining: budget === undefined ? null : meter.remaining,\n stoppedReason: stopped,\n externalDeletions,\n };\n }\n\n /**\n * Runs first and outside the token budget: delivers owed vector-index\n * removals per entity (wiped entities included), without backoff. Pending is\n * reported even when the job is not listed or no hook is configured.\n */\n private async runExternalDeletions(\n entityIds: string[] | undefined,\n enabled: boolean,\n deadline: number,\n ): Promise<{ confirmed: number; pending: number }> {\n if (!(await this.vectorRemovalService.ledgerPresent())) return { confirmed: 0, pending: 0 };\n const all = await this.vectorRemovalRepo.entitiesWithPending();\n const scope = entityIds === undefined ? undefined : new Set(entityIds);\n const entities = scope === undefined ? all : all.filter((e) => scope.has(e));\n let confirmed = 0;\n let pending = 0;\n // Entities a drain reported on; the drain already counted their pending rows.\n const counted = new Set<string>();\n if (enabled) {\n for (const e of entities) {\n if (Date.now() >= deadline) break;\n const r = await this.vectorRemovalService.drain(\n { entityId: e },\n { trigger: 'call', ...(deadline === Infinity ? {} : { deadlineAt: deadline }) },\n );\n confirmed += r.confirmed;\n if (!r.transient) {\n pending += r.pending;\n counted.add(e);\n }\n if (r.timedOut) break;\n }\n }\n for (const e of entities) {\n if (!counted.has(e)) pending += (await this.vectorRemovalRepo.pendingStats(e)).count;\n }\n return { confirmed, pending };\n }\n}\n","import type { OntologyMode, WriteOntologyPromptContext } 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.\nEach node is a fact. To link two things with an edge, each must exist as its own fact, titled by the same name you use in \\`target_title\\`.`;\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 a node_type, choose the closest type the fact is an example of; omit only when none applies even broadly.'\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\n// ---------------------------------------------------------------------------\n// Write-path appendix (specs/type-on-write §5). Its text equals the backfill\n// appendix above for the same inputs in this step, but it is produced from its\n// OWN constants so a later edit to either site cannot reach the other. The\n// byte-identity and split tests are the guard.\n// ---------------------------------------------------------------------------\n\nconst WRITE_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.\nEach node is a fact. To link two things with an edge, each must exist as its own fact, titled by the same name you use in \\`target_title\\`.`;\n\nconst WRITE_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 buildWriteOntologyAppendix(\n mode: OntologyMode,\n manifestJson: string,\n): WriteOntologyPromptContext {\n const strictRules = mode === 'strict'\n ? 'STRICT MODE: Use ONLY types defined in the manifest. If a fact does not fit a node_type, choose the closest type the fact is an example of; omit only when none applies even broadly.'\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 WRITE_FACT_ONTOLOGY_FIELDS,\n mode === 'emergent' ? WRITE_EMERGENT_EXTRA : '',\n 'Manifest:',\n manifestJson,\n ].filter(Boolean).join('\\n');\n\n return { site: 'write', ontologyManifest: manifestJson, ontologyModeInstructions };\n}\n","import type {\n OntologyConfig,\n OntologyManifest,\n OntologyMode,\n OntologyPromptContext,\n WriteOntologyPromptContext,\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, buildWriteOntologyAppendix } from '../prompts/ontology';\nimport {\n emptyManifest,\n normalizeTitleKey,\n resolveNodeType,\n resolveNodeTypeMatch,\n resolveEdgeDefinitions,\n typeSatisfies,\n validateInlineEdges,\n validateManifest,\n isReservedAbstainSlug,\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 /**\n * Ontology prompt context for the WRITE builders (specs/type-on-write §5).\n * `null` when the mode is `'off'` or when write-time typing is `engaged`\n * (the classifier types the fact, so the manifest leaves the write prompt).\n * Backfill keeps `buildPromptContext`.\n */\n async buildWritePromptContext(\n entityId: string,\n opts: { engaged: boolean },\n ): Promise<WriteOntologyPromptContext | null> {\n const { mode, manifest } = await this.getEffectiveState(entityId);\n if (mode === 'off' || opts.engaged) return null;\n return buildWriteOntologyAppendix(mode, JSON.stringify(manifest, null, 2));\n }\n\n async mergeEmergentUpdates(\n entityId: string,\n updates: OntologyUpdates,\n tx: SQLiteAdapter,\n ): Promise<{ manifest: OntologyManifest; rejected: string[] }> {\n // Reserved abstain slug (specs/system-one-config §5, decree C4): the\n // emergent merge drops it instead of persisting it, so a model proposing\n // 'none_of_these' as a node type can never smuggle the sentinel into the\n // manifest. Write-path reservation lives in WikiMemory.setOntologyManifests;\n // per-read validateManifest is deliberately untouched.\n const filtered: OntologyUpdates = updates.node_types\n ? { ...updates, node_types: updates.node_types.filter((nt) => !isReservedAbstainSlug(nt.type)) }\n : updates;\n const { manifest: merged, rejected } = await this.metadataRepo.mergeManifestUpdates(entityId, filtered, tx);\n this.invalidateCache(entityId);\n return { manifest: merged, rejected };\n }\n\n validateAndNormalizeFact(\n fact: ExtractedFactWithOntology,\n manifest: OntologyManifest,\n opts?: { strict?: boolean; entityId?: string; drops?: EdgeDrop[] },\n ): {\n okf_type: string | null;\n edges: ExtractedFactEdge[];\n /** Resolution evidence. Absent on a miss. Callers must not re-run resolution. */\n match?: { raw: string; canonical: string; via: 'exact' | 'normalize' };\n } {\n const rawType = typeof fact.okf_type === 'string' ? fact.okf_type : '';\n const strict = opts?.strict === true;\n const match = resolveNodeTypeMatch(rawType, manifest);\n if (!match) {\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 canonical = match.slug;\n const edges = validateInlineEdges(canonical, null, fact.edges ?? [], manifest, opts);\n return {\n okf_type: canonical,\n edges,\n match: { raw: rawType, canonical, via: match.via },\n };\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';\nimport { WikiInvalidReadOptions } from '../types';\nimport { isLiveAt } from '../utils/temporal';\nimport { packFactsByBudget, factTokenCost } from '../utils/budget';\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 rawAsOf = options.asOf;\n if (rawAsOf !== undefined && !(typeof rawAsOf === 'number' && Number.isFinite(rawAsOf) && rawAsOf >= 0)) {\n throw new WikiInvalidReadOptions('asOf', 'must be a finite epoch-ms number >= 0');\n }\n const rawTokenBudget = options.tokenBudget;\n if (rawTokenBudget !== undefined && !(typeof rawTokenBudget === 'number' && Number.isFinite(rawTokenBudget) && rawTokenBudget >= 0)) {\n throw new WikiInvalidReadOptions('tokenBudget', 'must be a finite number >= 0');\n }\n const live = rawAsOf === undefined\n ? { mode: 'current' as const, t: Date.now() }\n : { mode: 'asOf' as const, t: Math.trunc(rawAsOf) };\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 live,\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 // Spec §10.7: a non-live anchor returns alone — both endpoints of a\n // walkable edge must be live at the query instant.\n const [anchor] = await this.entryRepo.findByIds([options.sourceId], [entityId]);\n if (anchor && !isLiveAt(anchor, live.mode, live.t)) return { nodes: [anchor], 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 if (options.tokenBudget === undefined) return { nodes, edges: filteredEdges };\n const budget = Math.trunc(options.tokenBudget);\n const [anchorPacked] = packFactsByBudget([nodes[0]], budget).items;\n const kept = [anchorPacked];\n let used = factTokenCost(anchorPacked);\n for (const node of nodes.slice(1)) {\n const cost = factTokenCost(node);\n if (used + cost <= budget) { kept.push(node); used += cost; }\n }\n const keptIds = new Set(kept.map((n) => n.id));\n return { nodes: kept, edges: filteredEdges.filter((e) => keptIds.has(e.source_id) && keptIds.has(e.target_id)) };\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 /** Keyset page of TYPED facts in this entity (id + stored slug). Read-only. \"Typed\" here means the deletion-only scan the edge-violation query uses: soft-deleted and draft rows are out; validity windows are NOT consulted — the count mirrors `pageLiveEdgeViolations` exactly (spec §9, CodeRabbit #441). */\n async pageLiveTypedFacts(entityId: string, afterId: string, limit: number): Promise<Array<{ id: string; okf_type: string }>> {\n return this.db.getAllAsync(\n `SELECT id, okf_type FROM ${this.prefix}entries\n WHERE entity_id = ? AND id > ? AND deleted_at IS NULL\n AND lifecycle_status != 'draft' AND okf_type IS NOT NULL\n ORDER BY id ASC 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, resolveNodeType } 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 // Node-type violations (ontology-curation Task 11): a live fact whose\n // stored okf_type no longer resolves against the effective manifest.\n // Uses the same normalized resolver as the doors, so a stored slug that\n // folds into a manifest entry is not a violation. 0 when ontology is off\n // or the manifest declares no node_types.\n let nodeTypeViolations = 0;\n const nodeTypeViolationIds: string[] = [];\n const nodesConstrained = mode !== 'off' && (manifest.node_types?.length ?? 0) > 0;\n if (nodesConstrained) {\n let after = '';\n for (;;) {\n const page = await this.lintRepo.pageLiveTypedFacts(entityId, after, LINT_PAGE_SIZE);\n for (const f of page) {\n if (resolveNodeType(f.okf_type, manifest) === null) {\n nodeTypeViolations++;\n if (nodeTypeViolationIds.length < LINT_SAMPLE_SIZE) nodeTypeViolationIds.push(f.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 nodeTypeViolations,\n ...health,\n sample: { danglingEdgeIds, manifestViolationEdgeIds, nodeTypeViolationIds },\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 { RememberInput, WikiFact } from '../types';\nimport { assertEntityId } from './entityId';\nimport { generateId } from './ids';\nimport { assertEpochMs } from './temporal';\n\nconst CONFIDENCE_VALUES: ReadonlySet<string> = new Set(['certain', 'inferred', 'tentative']);\nconst SOURCE_TYPE_VALUES: ReadonlySet<string> = new Set(['user_stated', 'user_confirmed']);\n\nexport interface NormalizedRememberInput {\n /** The row to upsert. `okf_type` is null here; RememberService resolves `okfType` against the manifest. */\n fact: WikiFact;\n /** Truncated epoch ms, or undefined when the caller gave none. */\n validFrom?: number;\n /** The caller's raw type slug, or null. */\n okfType: string | null;\n}\n\n/**\n * Every validation rule of remember() (spec §3.2), with no I/O. Throws\n * TypeError; never clips or coerces. `now` is injected so tests are stable.\n */\nexport function normalizeRememberInput(entityId: string, input: RememberInput, now: number): NormalizedRememberInput {\n assertEntityId(entityId);\n if (input === null || typeof input !== 'object' || Array.isArray(input)) {\n throw new TypeError('remember(): input must be a non-null object.');\n }\n if (typeof input.title !== 'string' || input.title.trim() === '') {\n throw new TypeError('remember(): input.title must be a non-empty string.');\n }\n if (typeof input.body !== 'string') {\n throw new TypeError('remember(): input.body must be a string.');\n }\n let tags: string[] = [];\n if (input.tags !== undefined) {\n if (!Array.isArray(input.tags)) {\n throw new TypeError('remember(): input.tags must be an array of strings.');\n }\n // Index-based loop on purpose: Array.prototype.every skips holes, so a\n // sparse array (e.g. new Array(2)) would otherwise pass validation.\n for (let i = 0; i < input.tags.length; i++) {\n if (typeof input.tags[i] !== 'string') {\n throw new TypeError('remember(): input.tags must be an array of strings.');\n }\n }\n tags = [...(input.tags as string[])];\n }\n // null is a supplied value, not absence (spec §3.2: nothing coerced silently);\n // it fails the Set check below with the same message as any other bad value.\n const confidence = input.confidence === undefined ? 'certain' : input.confidence;\n if (!CONFIDENCE_VALUES.has(confidence)) {\n throw new TypeError(`remember(): input.confidence must be certain | inferred | tentative; got ${JSON.stringify(input.confidence)}.`);\n }\n const sourceType = input.source_type === undefined ? 'user_stated' : input.source_type;\n if (!SOURCE_TYPE_VALUES.has(sourceType)) {\n throw new TypeError(`remember(): input.source_type must be user_stated | user_confirmed; got ${JSON.stringify(input.source_type)}.`);\n }\n let okfType: string | null = null;\n if (input.okf_type !== undefined && input.okf_type !== null) {\n if (typeof input.okf_type !== 'string' || input.okf_type.trim() === '') {\n throw new TypeError('remember(): input.okf_type must be a non-empty string or null.');\n }\n okfType = input.okf_type;\n }\n const validFrom = input.valid_from === undefined ? undefined : assertEpochMs('input.valid_from', input.valid_from);\n\n const fact: WikiFact = {\n id: generateId('fact_'),\n entity_id: entityId,\n title: input.title,\n body: input.body,\n tags,\n confidence,\n source_type: sourceType,\n source_hash: null,\n source_ref: null,\n created_at: now,\n updated_at: now,\n last_accessed_at: null,\n access_count: 0,\n deleted_at: null,\n okf_type: null,\n };\n return { fact, validFrom, okfType };\n}\n","import type { SQLiteAdapter, WikiFact, RememberInput, ExtractedFactWithOntology, WikiOptions } from '../types';\nimport type { EntryRepository } from '../repositories/EntryRepository';\nimport type { OntologyService } from './OntologyService';\nimport type { SearchService } from './SearchService';\nimport type { EmbeddingService } from './EmbeddingService';\nimport { normalizeRememberInput } from '../utils/rememberInput';\nimport type { WikiDiagnosticInput } from '../utils/diagnostics';\nimport { emitDiagnostic, shouldEmitOntologyReceipt, nodeTypeReceipts } from '../utils/diagnostics';\n\n/** Direct mutable-fact writes (spec `specs/core-remember/spec.md` §3.3–§3.6). */\nexport class RememberService {\n constructor(\n private db: SQLiteAdapter,\n private entryRepo: EntryRepository,\n private ontologyService: OntologyService,\n private searchService: SearchService,\n private embeddingService: EmbeddingService,\n private options?: Pick<WikiOptions, 'onDiagnostic'>,\n ) {}\n\n async remember(entityId: string, input: RememberInput): Promise<WikiFact> {\n const now = Date.now();\n const { fact, validFrom, okfType } = normalizeRememberInput(entityId, input, now);\n let stored: WikiFact | undefined;\n // Receipts buffer until the transaction COMMITS: a rolled-back write\n // (failed upsert/setTemporal/read-back/commit) must deliver none\n // (CodeRabbit #441; mirrors the DiagnosticBuffer flush-after-commit\n // pattern the other write paths use).\n const pendingReceipts: WikiDiagnosticInput[] = [];\n\n await this.db.withTransactionAsync(async (tx) => {\n if (okfType !== null) {\n const { mode, manifest } = await this.ontologyService.getEffectiveState(entityId, tx);\n // Mode gate (CodeRabbit #441): a host with ontology 'off' sees no\n // ontology behavior at the remember door — the caller's slug is\n // stored verbatim, no fold, no drop, no throw, no receipt\n // (release-surface guarantee). \"Never replace a type a person\n // stated\" extends to the off mode.\n if (mode !== 'off') {\n // Same rule as an upsertGraph node type (IngestionService.upsertGraphCore):\n // canonical slug when the manifest knows it, a throw under strict, null otherwise.\n const factLike = { okf_type: okfType, edges: [] } as unknown as ExtractedFactWithOntology;\n const normalized = this.ontologyService.validateAndNormalizeFact(factLike, manifest, {\n strict: mode === 'strict',\n entityId,\n });\n fact.okf_type = normalized.okf_type;\n // Person-door receipts (spec §4): in strict mode a miss throws inside\n // validateAndNormalizeFact (before any commit — the throw is the only\n // signal, no receipt), so these only fire in the non-strict modes.\n if (shouldEmitOntologyReceipt(mode)) {\n for (const receipt of nodeTypeReceipts(\n { entityId, operation: 'remember', trigger: 'call' },\n fact.id,\n okfType,\n normalized.okf_type,\n normalized.match,\n )) {\n pendingReceipts.push(receipt);\n }\n }\n } else {\n // Off mode: store the caller's slug verbatim — no fold, no drop.\n fact.okf_type = okfType;\n }\n }\n await this.entryRepo.upsert(fact, tx);\n if (validFrom !== undefined) {\n await this.entryRepo.setTemporal(fact.id, entityId, { valid_from: validFrom }, tx);\n }\n // The return value is the stored row, not the literal: defaults the INSERT\n // bound and the read-time isStale / trustTier come from the mapper.\n const [readBack] = await this.entryRepo.findByIds([fact.id], [entityId], tx);\n if (!readBack) {\n throw new Error('remember(): the stored fact could not be read back; the SQLiteAdapter did not perform the write');\n }\n stored = readBack;\n });\n\n // Commit landed — now deliver the buffered receipts.\n for (const receipt of pendingReceipts) {\n emitDiagnostic(this.options ?? {}, receipt);\n }\n\n await this.searchService.syncEntries(entityId, [fact.id]);\n // A delete that lands during the vector call is settled inside\n // storeFactVector (spec durable-vector-removal §5.7, G10).\n await this.embeddingService.embedFact(\n { id: fact.id, entity_id: entityId, title: fact.title, body: fact.body, tags: fact.tags },\n { operation: 'remember', trigger: 'call' },\n );\n this.searchService.evictCache(entityId);\n return stored!;\n }\n\n}\n","import { canEngageWriteTyping } from './services/typing/typeOnWrite';\nimport type { SQLiteAdapter } from './types';\nimport type { WikiOutboxEvent } from './outbox/types';\nimport { emitDiagnostic } from './utils/diagnostics';\nimport { setupDatabaseWithGate } from './db/migrationGate';\nimport { detectSchemaVersion, runSourceRefNormalize, writeNormalizeStamp } from './db/sourceRefNormalize';\nimport { withSerializedTransactions } from './db/serializedAdapter';\nimport { MIGRATIONS, CURRENT_SCHEMA_VERSION, createLegacySourceTypeIndex, createEntriesDeletedIndex } from './db/migrations';\nimport {\n WikiOptions,\n MemoryBundle,\n MemoryDump,\n WikiEvent,\n EntityStatus,\n ReadOptions,\n WikiSourceRefHashCollision,\n WikiDraftNotFound,\n WikiSupersedeError,\n} from './types';\nimport type { DraftPage, MigrationPolicy, ForgetParams, ForgetResult } from './types';\nimport type { PendingSourceStatus, WikiLintReport, WikiInstructions, PendingMaintenance, RunPendingMaintenanceOptions, RunPendingMaintenanceResult } 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 { SourceStoreService } from './services/SourceStoreService';\nimport type { StoreSourceResult, StoredSource, StoredSourceSummary } from './types';\nimport { MiniSearchIndexStrategy } from './services/search/MiniSearchIndexStrategy';\nimport { createIndexStrategy } from './services/search/createIndexStrategy';\nimport { monotonicNow } from './utils/monotonicNow';\nimport { DEFAULT_SETUP_BUDGET_MS } from './utils/setupDefaults';\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, type EraseReport } from './services/MaintenanceService';\nimport { MaintenanceScheduler } from './services/MaintenanceScheduler';\nimport { ImportExportService } from './services/ImportExportService';\nimport { EmbeddingService } from './services/EmbeddingService';\nimport { VectorRemovalService } from './services/VectorRemovalService';\nimport { VectorRemovalRepository } from './repositories/VectorRemovalRepository';\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 { TemporalService } from './services/TemporalService';\nimport { RememberService } from './services/RememberService';\nimport { validateManifest, isReservedAbstainSlug, ONTOLOGY_ABSTAIN_SENTINEL } from './utils/ontology';\nimport { DiagnosticBuffer } from './utils/diagnostics';\nimport type { OntologyManifest, OntologyMode, GraphTraversalOptions, GraphNeighborhood, OntologyBackfillResult, HealResult, IngestDocumentResult, ReembedResult, SupersedeReplacement, WikiFact, RememberInput } from './types';\nimport { resolveLibrarianStrategy, warnChangedDefaultsOnce, resolveContextBudgetOrThrow } from './utils/engineDefaults';\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 * Backoff between failed no-arg syncSearchIndex() re-init attempts (spec #280\n * Change 4): doubles per consecutive failure from the base up to the cap, and\n * is never shorter than SEARCH_REINIT_COST_FACTOR × the failed attempt's own\n * duration, so a slow attempt (backoff + rebuild under the write lock) can\n * take at most ~1/(factor+1) of wall time.\n */\nconst SEARCH_REINIT_COOLDOWN_MS = 5_000;\nconst SEARCH_REINIT_COOLDOWN_MAX_MS = 5 * 60_000;\nconst SEARCH_REINIT_COST_FACTOR = 10;\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 maintenanceScheduler: MaintenanceScheduler;\n retrievalService: RetrievalService;\n searchService: SearchService;\n writeService: WriteService;\n promptService: PromptService;\n graphTraversalService: GraphTraversalService;\n temporalService: TemporalService;\n rememberService: RememberService;\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 vectorRemovalRepo: VectorRemovalRepository;\n private vectorRemovalService: VectorRemovalService;\n private searchService: SearchService;\n private jobManager: JobManager;\n private ingestionService: IngestionService;\n private maintenanceService: MaintenanceService;\n private maintenanceScheduler: MaintenanceScheduler;\n private importExportService: ImportExportService;\n private retrievalService: RetrievalService;\n private writeService: WriteService;\n private sourceStoreService: SourceStoreService;\n private promptService: PromptService;\n private ontologyService: OntologyService;\n private graphTraversalService: GraphTraversalService;\n private lintRepo: LintRepository;\n private lintService: LintService;\n private temporalService: TemporalService;\n private rememberService: RememberService;\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 warnChangedDefaultsOnce(options.config);\n // Fail-fast: an invalid `config.context` section throws at construction,\n // never mid-pass (specs/context-budget T4).\n resolveContextBudgetOrThrow(options.config);\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.vectorRemovalRepo = new VectorRemovalRepository(this.db, this.prefix);\n this.vectorRemovalService = new VectorRemovalService(this.db, this.options, this.vectorRemovalRepo, this.embeddingService, this.metadataRepo);\n this.embeddingService.attachVectorRemoval(this.vectorRemovalService, this.vectorRemovalRepo);\n this.searchService = new SearchService(\n this.entryRepo,\n new MiniSearchIndexStrategy(),\n );\n this.temporalService = new TemporalService(this.db, this.options, this.entryRepo, this.searchService, this.embeddingService);\n this.rememberService = new RememberService(this.db, this.entryRepo, this.ontologyService, this.searchService, this.embeddingService, this.options);\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 this.vectorRemovalService,\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 this.edgeRepo,\n this.vectorRemovalService,\n this.vectorRemovalRepo,\n );\n this.maintenanceScheduler = new MaintenanceScheduler(\n this.db,\n this.options,\n this.maintenanceService,\n this.metadataRepo,\n this.eventRepo,\n this.entryRepo,\n this.jobManager,\n this.vectorRemovalService,\n this.vectorRemovalRepo,\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 this.options,\n this.vectorRemovalService,\n this.prefix,\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.sourceStoreService = new SourceStoreService(this.db, this.prefix, this.options, this.jobManager);\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 maintenanceScheduler: this.maintenanceScheduler,\n retrievalService: this.retrievalService,\n searchService: this.searchService,\n writeService: this.writeService,\n promptService: this.promptService,\n graphTraversalService: this.graphTraversalService,\n temporalService: this.temporalService,\n rememberService: this.rememberService,\n entryRepo: this.entryRepo,\n sourceRefIndexRepo: this.sourceRefIndexRepo,\n metadataRepo: this.metadataRepo,\n jobManager: this.jobManager,\n };\n }\n\n /** Max upsertGraph node and superseded-fact ids held for their post-commit sync (spec #280 id threading). */\n static readonly UPSERT_ID_STASH_CAP = 10_000;\n /**\n * upsertGraph node and superseded-fact ids per entity, awaiting syncSearchIndex(), each with the\n * generation of its latest stash. Ids leave the stash only once a drain\n * succeeded, so a failed drain retries them next call.\n */\n private upsertIdStash = new Map<string, Map<string, number>>();\n /** Total ids across upsertIdStash, kept in step so the cap check is O(1). */\n private upsertIdStashSize = 0;\n /** Bumped per stashed id; a re-stash during an in-flight drain outlives that drain's drop. */\n private upsertIdStashGen = 0;\n\n private stashUpsertIds(entityId: string, ids: readonly string[]): void {\n // Only a ledger strategy drains the search index by id; MiniSearch rebuilds the stale entity instead.\n // (Removal delivery has its own stash, stashRemovalIds, independent of the strategy.)\n if (!this.searchService.hasLedger()) return;\n const cap = (this.constructor as typeof WikiMemory).UPSERT_ID_STASH_CAP;\n const stash = this.upsertIdStash.get(entityId) ?? new Map<string, number>();\n for (const id of ids) {\n if (!stash.has(id)) {\n if (this.upsertIdStashSize >= cap) continue; // overflow: the entity-targeted / full-quantum drain covers the rest\n this.upsertIdStashSize++;\n }\n stash.set(id, ++this.upsertIdStashGen);\n }\n if (stash.size > 0) this.upsertIdStash.set(entityId, stash);\n }\n\n /** Max superseded-fact ids held for post-commit removal delivery. */\n static readonly REMOVAL_STASH_CAP = 10_000;\n /** Superseded fact ids per entity awaiting a post-commit delivery from syncSearchIndex(). */\n private removalStash = new Map<string, Set<string>>();\n private removalStashSize = 0;\n\n /**\n * Overflow past the cap drops the id from the stash only: the trigger already\n * put it on the ledger, so it stays owed and runExternalDeletions or\n * runPendingMaintenance delivers it later.\n */\n private stashRemovalIds(entityId: string, ids: readonly string[]): void {\n const cap = (this.constructor as typeof WikiMemory).REMOVAL_STASH_CAP;\n const stash = this.removalStash.get(entityId) ?? new Set<string>();\n for (const id of ids) {\n if (stash.has(id)) continue;\n if (this.removalStashSize >= cap) continue;\n stash.add(id);\n this.removalStashSize++;\n }\n if (stash.size > 0) this.removalStash.set(entityId, stash);\n }\n\n /** Removes and returns the stashed removal ids (one entity, or all). */\n private takeRemovalIds(entityId?: string): Map<string, string[]> {\n const out = new Map<string, string[]>();\n for (const [e, set] of [...this.removalStash]) {\n if (entityId !== undefined && e !== entityId) continue;\n out.set(e, [...set]);\n this.removalStashSize -= set.size;\n this.removalStash.delete(e);\n }\n return out;\n }\n\n /** Snapshot of the stash (one entity, or all) with generations, without removing anything. */\n private peekStashedIds(entityId?: string): Map<string, Map<string, number>> {\n const snapshot = new Map<string, Map<string, number>>();\n for (const [id, stash] of this.upsertIdStash) {\n if (entityId === undefined || id === entityId) snapshot.set(id, new Map(stash));\n }\n return snapshot;\n }\n\n /**\n * Removes a drained snapshot. An id re-stashed after the peek has a newer\n * generation and stays: the drain may have run before that write committed.\n */\n private dropStashedIds(snapshot: Map<string, Map<string, number>>): void {\n for (const [entityId, drained] of snapshot) {\n const stash = this.upsertIdStash.get(entityId);\n if (!stash) continue;\n for (const [id, gen] of drained) {\n if (stash.get(id) === gen && stash.delete(id)) this.upsertIdStashSize--;\n }\n if (stash.size === 0) this.upsertIdStash.delete(entityId);\n }\n }\n\n /** `config.setupBudgetMs` or the default, validated: a positive finite number. */\n private setupBudgetMs(): number {\n const budget = this.options.config?.setupBudgetMs ?? DEFAULT_SETUP_BUDGET_MS;\n if (typeof budget !== 'number' || !Number.isFinite(budget) || budget <= 0) {\n throw new TypeError(`setupBudgetMs must be a positive finite number; got ${String(budget)}`);\n }\n return budget;\n }\n\n private reinitSearch: Promise<void> | null = null;\n /** Monotonic time before which a no-arg syncSearchIndex() skips the re-init (0 = no cooldown). */\n private reinitRetryAt = 0;\n /** Consecutive failed re-inits; drives the exponential backoff. */\n private reinitFailures = 0;\n\n /**\n * Opens the store: migration gate, DDL, schema migrations, then the stamped\n * source_ref normalize. Await it before any other call on this instance — the\n * normalize commits in chunks, so a sourceRef-keyed call (forget, upsertGraph,\n * hasChanged, ingest) issued before setup() resolves can see partially\n * normalized refs.\n *\n * Pass `{ migrations: 'refuse' }` from inside a writer lease: pending one-time\n * work then throws WikiMigrationRequiredError before any mutation, and the\n * host runs a plain `setup()` outside the lease.\n *\n * Keyword-index catch-up work is bounded by `config.setupBudgetMs`; anything\n * left converges on later opens, and on no-arg `syncSearchIndex()` calls for\n * the entries ledger. Passage-ledger leftover converges on later opens and on\n * passage-store writes for the entity (`storeSource`, `forget`,\n * `importDump`), which drain that entity's rows; no-arg calls do not touch\n * the passage ledger. Not bounded: an index reset (tokenizer change, re-attach\n * after detach, a lost or inconsistent index), which runs as one unchunked\n * transaction.\n */\n async setup(opts?: { migrations?: MigrationPolicy }) {\n // Always-on erasure substrate (forget-erasure spec §1, ruling B): no opt-out, no option.\n // secure_delete is connection-wide and ATTACH-wide: it covers every database on this\n // connection. Hosts whose own code writes wiki tables through a different connection\n // (or re-opens the file) must set `PRAGMA secure_delete=ON` there too.\n // A refusal only warns; the honest failure belongs to erase's step 0, not setup.\n // \"FULL\" is the spec's name for full zeroing; SQLite spells it `ON` (1) — `FULL` is not a\n // SQLite value (reads back 0 on 3.53.4) and `FAST` (2) only zeroes partially.\n await this.db.execAsync('PRAGMA secure_delete=ON');\n const secureDelete = await this.db.getFirstAsync<{ secure_delete: number }>('PRAGMA secure_delete');\n if (!secureDelete || Number(secureDelete.secure_delete) !== 1) {\n console.warn(\n '[WikiMemory] PRAGMA secure_delete=ON (full zeroing) was not honored by this SQLite runtime; ' +\n 'deleted content may remain recoverable in the database file until erase() verifies it.',\n );\n }\n const setupBudgetMs = this.setupBudgetMs();\n // One deadline per open (spec #280 Change 3): captured here, never re-budgeted per turn.\n const openDeadline = monotonicNow() + setupBudgetMs;\n const entriesExistedBeforeSetup = await this.metadataRepo.tableExists(`${this.prefix}entries`);\n\n // The gate runs before any mutation: 'refuse' throws before tables are touched,\n // 'auto' lets only a pending source_ref normalize through (run below), 'allow' just sets up.\n const migrationPolicy = opts?.migrations ?? this.options.config?.migrations ?? 'allow';\n await setupDatabaseWithGate(this.db, this.prefix, this.metadataRepo, migrationPolicy);\n\n let currentVersion: number;\n\n if (!entriesExistedBeforeSetup) {\n // One transaction: a crash must never leave schema_version without its indexes,\n // since no migration would rebuild it on the next open.\n await this.db.withTransactionAsync(async (tx) => {\n await createLegacySourceTypeIndex(tx, this.prefix);\n await createEntriesDeletedIndex(tx, this.prefix);\n await writeNormalizeStamp(this.metadataRepo, tx);\n await this.metadataRepo.setMeta('schema_version', String(CURRENT_SCHEMA_VERSION), tx);\n });\n currentVersion = CURRENT_SCHEMA_VERSION;\n } else {\n currentVersion = await detectSchemaVersion(this.metadataRepo, this.prefix);\n }\n\n // Schema migrations. Under 'refuse'/'auto' the gate has already thrown if any are pending.\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 await this.importExportService.assertNoLegacySourceTypes();\n // Stamped, watermark-resumable normalization; no-op once the stamp matches.\n await runSourceRefNormalize(this.db, this.prefix, this.metadataRepo);\n }\n\n this.searchService.setIndexStrategy(\n await createIndexStrategy(\n this.db,\n this.prefix,\n this.metadataRepo,\n this.options.config?.indexStrategy ?? 'auto',\n { setupBudgetMs, entriesExisted: entriesExistedBeforeSetup },\n ),\n );\n // FTS5: one budgeted quantum (no global read). MiniSearch: full rebuild, as before.\n await this.searchService.sync(undefined, { deadline: openDeadline });\n // Spec source-store §6: FTS5 drains the passage ledger; the fallback re-indexes every stored entity at open.\n await this.searchService.syncPassages(this.db, this.prefix, undefined, openDeadline);\n await this.startSetupRemovalDrain();\n }\n\n private setupRemovalDrain: Promise<void> | null = null;\n\n /** Marks the external index in use, then drains owed removals in the background (spec §5.7). */\n private async startSetupRemovalDrain(): Promise<void> {\n if (this.setupRemovalDrain) return; // a second setup() reuses the running drain\n const gate = this.vectorRemovalService.gate();\n if (gate === 'none') return;\n // Assigned before the first await so a concurrent setup() sees it.\n const prelude = (async (): Promise<{ drain: Promise<void> | null }> => {\n if (gate === 'hook' && !(await this.vectorRemovalService.externalIndexInUse())) {\n await this.db.withTransactionAsync((tx) => this.vectorRemovalService.markExternalIndexInUse(tx));\n }\n if ((await this.vectorRemovalRepo.pendingStats()).count === 0) {\n // Under force nothing is owed, so the marker has nothing left to guard (spec §5.3).\n if (gate === 'force') await this.vectorRemovalService.clearExternalIndexMarker();\n return { drain: null };\n }\n if (this.options.drainExternalDeletionsOnSetup !== true) {\n if (gate === 'hook') await this.vectorRemovalService.emitPending(undefined, 'auto');\n return { drain: null };\n }\n const drain = (async () => {\n try {\n const r = await this.vectorRemovalService.drain(\n { all: true },\n { backoff: true, deadlineAt: Date.now() + 10_000, trigger: 'auto' },\n );\n if (r.pending > 0) await this.vectorRemovalService.emitPending(undefined, 'auto');\n } catch {\n emitDiagnostic(this.options, {\n code: 'background_job_failed', operation: 'externalDeletion', trigger: 'auto', entityId: '', // store-wide drain\n detail: { reason: 'unhandled_rejection' },\n });\n }\n })();\n return { drain };\n })();\n const joined: Promise<void> = prelude.then((r) => r.drain ?? undefined, () => undefined);\n this.setupRemovalDrain = joined;\n void joined.then(() => { if (this.setupRemovalDrain === joined) this.setupRemovalDrain = null; });\n await prelude; // marker or ledger errors surface from setup()\n }\n\n /**\n * Delivers owed vector-index removals now (spec §5.9). No backoff. With an\n * entity id only that entity's rows; otherwise all. `deadlineMs` is a duration.\n * `transient: true` means a ledger read or write could not run (for example,\n * you held a transaction open on the connection); the rows stay pending.\n */\n async runExternalDeletions(\n entityId?: string,\n opts?: { deadlineMs?: number },\n ): Promise<{ confirmed: number; pending: number; failedIds: string[]; timedOut: boolean; transient?: boolean }> {\n if (entityId !== undefined) assertEntityId(entityId);\n const ms = opts?.deadlineMs;\n if (ms !== undefined && (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0)) {\n throw new TypeError('deadlineMs must be a finite number >= 0');\n }\n // A store whose setup() never ran has no ledger: nothing is recorded as owed.\n if (!(await this.vectorRemovalService.ledgerPresent())) {\n return { confirmed: 0, pending: 0, failedIds: [], timedOut: false };\n }\n const r = await this.vectorRemovalService.drain(\n entityId === undefined ? { all: true } : { entityId },\n { trigger: 'call', ...(ms !== undefined ? { deadlineAt: Date.now() + ms } : {}) },\n );\n return {\n confirmed: r.confirmed, pending: r.pending, failedIds: r.failedIds, timedOut: r.timedOut,\n ...(r.transient ? { transient: true } : {}),\n };\n }\n\n /** Removals still owed to the host's vector index (all entities, or one). */\n async getPendingExternalDeletions(\n entityId?: string,\n ): Promise<{ count: number; oldestEnqueuedAt: number | null; maxAttempts: number }> {\n if (entityId !== undefined) assertEntityId(entityId);\n if (!(await this.vectorRemovalService.ledgerPresent())) return { count: 0, oldestEnqueuedAt: null, maxAttempts: 0 };\n return this.vectorRemovalRepo.pendingStats(entityId);\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 `instructions_get` tool (formerly `wiki_get_instructions`). 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 // Write builders get the write context, backfill its own (specs/type-on-write §5).\n // The librarian context reflects write-time typing engagement, so what the host\n // reads is what the pass sends; ingest, heal and backfill are unchanged.\n const state = await this.ontologyService.getEffectiveState(entityId);\n const engaged = canEngageWriteTyping(this.options.config, this.options.llmProvider, state.mode, state.manifest);\n const writeContext = await this.ontologyService.buildWritePromptContext(entityId, { engaged });\n const ingestContext = engaged\n ? await this.ontologyService.buildWritePromptContext(entityId, { engaged: false })\n : writeContext;\n const backfillContext = await this.ontologyService.buildPromptContext(entityId);\n // Specs/librarian-guidance: same resolution as the write paths. A read\n // path that silently drops over-cap guidance would be the one place\n // guidance disappears without a signal, so over-cap emits here too.\n const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);\n if (diagnostic) {\n emitDiagnostic(this.options, {\n code: diagnostic.code,\n operation: 'read',\n trigger: 'call',\n entityId,\n detail: diagnostic.detail,\n });\n }\n return this.promptService.buildInstructionTemplates(writeContext, resolveLibrarianStrategy(this.options.config), guidance, backfillContext, ingestContext);\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 stored?: { charCount: number; staleHash?: true } | null;\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 /**\n * Erase everything soft-deleted, store-wide, and verify it (forget-erasure\n * spec §2). Throws `EraseStepError` (partial report, `verified: false`) when\n * a step fails; skipped entities report `verified: false`.\n * `{ rebuild: true }` additionally restarts the FTS rebuild.\n */\n async erase(options?: { rebuild?: boolean }): Promise<EraseReport> {\n return this.maintenanceService.erase(options);\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 /** Await auto-mode background librarian/heal jobs started by write(), and the removal drain `setup()` started under `drainExternalDeletionsOnSetup`. */\n async drain(): Promise<void> {\n await this.setupRemovalDrain;\n return this.writeService.drain();\n }\n\n /**\n * Report which entities have pending maintenance work (librarian events\n * behind the watermark, heal backlog, unembedded facts) without running\n * anything. Entities with no pending work are omitted; sorted by\n * `pendingEvents` desc then `entityId` asc.\n */\n async getPendingMaintenance(entityIds?: string[]): Promise<PendingMaintenance[]> {\n return this.maintenanceScheduler.getPending(entityIds);\n }\n\n /** Run pending removals, librarian, heal and reembed work under an optional token budget and deadline (spec §6.2). Awaits the setup removal drain first, when `drainExternalDeletionsOnSetup` started one. */\n async runPendingMaintenance(options?: RunPendingMaintenanceOptions): Promise<RunPendingMaintenanceResult> {\n let opts = options;\n const ms = options?.deadlineMs;\n // Reject a bad deadline before waiting: unchecked, it would skip the bounded\n // wait below and block on the whole setup drain before the scheduler throws.\n if (ms !== undefined && (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0)) {\n throw new TypeError('deadlineMs must be a finite number >= 0');\n }\n const setupDrain = this.setupRemovalDrain;\n if (setupDrain) {\n if (ms !== undefined) {\n // Bound the wait by deadlineMs and hand the scheduler only what is left.\n const started = Date.now();\n let handle: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n setupDrain,\n new Promise<void>((resolve) => { handle = setTimeout(resolve, ms); }),\n ]).finally(() => { if (handle) clearTimeout(handle); });\n opts = { ...options, deadlineMs: Math.max(0, ms - (Date.now() - started)) };\n } else {\n await setupDrain;\n }\n }\n return this.maintenanceScheduler.run(opts);\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.guidance` 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?: {\n promptOverride?: string;\n batchSize?: number;\n classifier?: 'auto' | 'llm';\n tokenBudget?: number;\n /** Overrides the default recheck cooldown: facts stamped after this epoch ms stay deferred. */\n recheckCheckedBefore?: number;\n },\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 /**\n * Brings the keyword search index up to date with SQLite after a host\n * transaction that used `upsertGraph` has committed. Core never sees that\n * commit, so without this the nodes stay out of keyword, hybrid and\n * fallback retrieval until the entity's next core write.\n *\n * With `entityId`: drains that entity's pending `upsertGraph` ids (its new\n * nodes and the facts they superseded) first, to completion, then at most\n * one more ledger chunk — so its new nodes are searchable, and the\n * superseded facts gone, when the call resolves, under any backlog. Without an\n * argument: drains every stashed `upsertGraph` id across entities first,\n * then runs one keyword-index quantum bounded by `config.setupBudgetMs`\n * (backlog drain, then rebuild work while the index is rebuilding). Hosts\n * with a long-lived process should call the no-arg form on their own\n * schedule: that is what converges a rebuilding index. While keyword search\n * is unavailable it first retries the index init; after a failed attempt it\n * waits at least 5 s, doubling per consecutive failure up to 5 min (longer\n * when an attempt is itself slow), before retrying again.\n *\n * It also calls the host's removal hook (`onEmbeddingPersisted(…, null)`) for\n * the stashed ids that `upsertGraph` superseded, and can take up to\n * `deletionHookTimeoutMs` per id when the host's index is slow. It never\n * drains an entity's wider removal backlog.\n *\n * Call only after the host's transaction commits: called inside it, the\n * rebuild may index rows that later roll back, or miss them and clear the\n * stale flag anyway. Serialized with core's internal index syncs and takes\n * no maintenance lock. Never rejects for a valid `entityId` — on failure the\n * entity stays stale and the next call retries it. Does not compute\n * embeddings; that remains the maintenance sweep's job.\n *\n * With the FTS5 index strategy this drains the index ledger in its own\n * transactions, so it MUST be called after the host transaction commits,\n * never from inside a `withTransactionAsync` callback. Calling it inside\n * one waits on the transaction mutex that the callback holds.\n *\n * @throws {TypeError} when `entityId` is given but is not a non-empty string.\n */\n async syncSearchIndex(entityId?: string): Promise<void> {\n if (entityId !== undefined) assertEntityId(entityId);\n // Capture the removal ids before the sync; delivery is non-throwing and\n // leaves anything unconfirmed owed on the ledger.\n const removals = this.takeRemovalIds(entityId);\n try {\n await this.syncSearchIndexCore(entityId);\n } catch (err) {\n // Put the ids back so the next call delivers them (the cap still applies;\n // overflow stays owed on the ledger).\n for (const [e, ids] of removals) this.stashRemovalIds(e, ids);\n throw err;\n }\n for (const [e, ids] of removals) {\n await this.vectorRemovalService.deliverRemovals(e, ids, 'upsertGraph', 'call');\n }\n }\n\n private async syncSearchIndexCore(entityId?: string): Promise<void> {\n if (entityId === undefined) {\n // A long-lived host that never re-opens still recovers from a failed init (spec #280 Change 4).\n // After a failed re-init, back off before the next: each attempt costs\n // the 250 ms retry backoff plus up to two rebuild transactions under the\n // write lock, and hosts call this after every write.\n if (!this.searchService.isKeywordAvailable() && monotonicNow() >= this.reinitRetryAt) {\n // One re-init at a time; concurrent callers share it.\n this.reinitSearch ??= (async () => {\n const started = monotonicNow();\n try {\n const strategy = await createIndexStrategy(\n this.db, this.prefix, this.metadataRepo, this.options.config?.indexStrategy ?? 'auto',\n { setupBudgetMs: this.setupBudgetMs() });\n this.searchService.setIndexStrategy(strategy);\n // A new MiniSearch index starts empty and needs the full sync. A ledger\n // strategy gets its one quantum from the syncStale() below (#284 review).\n if (this.searchService.isKeywordAvailable() && !this.searchService.hasLedger()) await this.searchService.sync();\n if (this.searchService.isKeywordAvailable()) await this.searchService.syncPassages(this.db, this.prefix);\n } finally {\n if (this.searchService.isKeywordAvailable()) {\n this.reinitFailures = 0;\n this.reinitRetryAt = 0;\n } else {\n const now = monotonicNow();\n const backoff = Math.min(SEARCH_REINIT_COOLDOWN_MS * 2 ** this.reinitFailures, SEARCH_REINIT_COOLDOWN_MAX_MS);\n this.reinitFailures++;\n this.reinitRetryAt = now + Math.max(backoff, SEARCH_REINIT_COST_FACTOR * (now - started));\n }\n this.reinitSearch = null;\n }\n })();\n await this.reinitSearch;\n }\n const stashed = this.peekStashedIds();\n const ids = [...stashed.values()].flatMap((m) => [...m.keys()]);\n if (await this.syncDrained(this.searchService.syncStale({ ids }))) this.dropStashedIds(stashed);\n return;\n }\n assertEntityId(entityId);\n const stashed = this.peekStashedIds(entityId);\n if (await this.syncDrained(this.searchService.syncEntries(entityId, stashed.get(entityId)?.keys() ?? []))) {\n this.dropStashedIds(stashed);\n }\n }\n\n /**\n * True when a sync applied the stashed ids. While keyword search is\n * unavailable the stand-in strategy's drain is a no-op that reports success,\n * so the ids stay stashed for the first sync after a re-init (#284 review).\n */\n private async syncDrained(sync: Promise<boolean>): Promise<boolean> {\n return (await sync) && this.searchService.isKeywordAvailable();\n }\n\n async exportDump(entityIds?: string[], opts?: { includeForgotten?: boolean }): Promise<MemoryDump> {\n return this.importExportService.exportDump(entityIds, opts);\n }\n\n /**\n * The retention windows `runPrune()` uses when the host runs it (shipped\n * defaults plus host overrides), for GDPR disclosure. Nothing prunes\n * automatically; `erase()` ignores `retainSoftDeletedFor`. Days; `null`\n * means \"keep forever\". Read-only.\n */\n getRetentionPolicy(): {\n retainSoftDeletedFor: number;\n retainEventsFor: number | null;\n pruneSupersededAfter: number | null;\n } {\n const c = this.options.config;\n return {\n retainSoftDeletedFor: c?.pruneRetainSoftDeletedFor ?? 7,\n retainEventsFor: c?.pruneEventsAfter ?? 30,\n pruneSupersededAfter: c?.pruneSupersededAfter ?? null,\n };\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<import('./types').ImportDumpResult> {\n try {\n return await this.importExportService.importDump(dump, opts);\n } finally {\n // Import re-cuts stored sources inside its transaction; index them once it committed (spec §6, §8).\n // Also runs after a failed import (e.g. WikiBusyError): intentional and harmless — it reads committed state and never rejects.\n // Scoped to the dump's entities so MiniSearch does not re-read every stored entity.\n for (const entityId of Object.keys(dump?.entities ?? {})) {\n await this.searchService.syncPassages(this.db, this.prefix, entityId);\n }\n }\n }\n\n /**\n * Soft-delete facts and tasks by id, by source, by source-pointer event id,\n * or all of them (`clearAll`).\n * `clearAll` also deletes the entity's edges and its source-ref index rows.\n * Add `includeEvents: true` to `clearAll` to hard-delete every event too,\n * read or not, and reset the librarian's position: without it a later\n * maintenance run can read the events into facts again. `runPrune()` then\n * hard-deletes the soft-deleted rows once they are older than\n * `retainSoftDeletedFor` (7 days by default; pass 0 to remove them now).\n * `dryRun` previews the counts.\n *\n * With a removal hook (`vectorRanker.onEmbeddingPersisted`), the deleted\n * facts are recorded as owed in the same transaction and then delivered to\n * the hook before this resolves.\n *\n * @throws {WikiExternalDeletionError} when the hook didn't confirm every\n * removal. The local delete stays committed and the rest stay owed; retry,\n * or call `runExternalDeletions()`.\n */\n async forget(\n entityId: string,\n params: ForgetParams,\n opts?: { dryRun?: boolean },\n ): Promise<ForgetResult> {\n try {\n return await this.maintenanceService.forget(entityId, params, opts);\n } finally {\n // Spec §5/§6: removal sync for stored passages, after the delete committed (also when the\n // external-deletion hook threw, since the local delete stays committed; a sync after any other\n // failure is intentional and harmless — it reads committed state and never rejects). clearAll\n // wipes only THIS entity (MaintenanceService deletes WHERE entity_id = ?), so the sync is\n // entity-scoped like every other forget shape; a store-wide sync would drain other entities'\n // ledgers (FTS5) or re-read every stored entity's text (MiniSearch) on an ordinary call.\n if (!opts?.dryRun) {\n await this.searchService.syncPassages(this.db, this.prefix, entityId);\n }\n }\n }\n\n /** Store a source's text (spec source-store §7). Refusals return `stored: false`; a busy lock throws. */\n async storeSource(\n entityId: string,\n params: { sourceRef: string; sourceHash: string; text: string },\n ): Promise<StoreSourceResult> {\n assertEntityId(entityId);\n const result = await this.sourceStoreService.storeSource(entityId, params);\n if (result.stored) await this.searchService.syncPassages(this.db, this.prefix, entityId);\n return result;\n }\n\n async getStoredSource(entityId: string, sourceRef: string): Promise<StoredSource | null> {\n assertEntityId(entityId);\n return this.sourceStoreService.getStoredSource(entityId, sourceRef);\n }\n\n async listStoredSources(entityId: string): Promise<StoredSourceSummary[]> {\n assertEntityId(entityId);\n return this.sourceStoreService.listStoredSources(entityId);\n }\n\n /**\n * End `oldId`'s validity and link it to its replacement (spec §4.3). One\n * transaction. Throws `WikiSupersedeError` for missing, foreign, already\n * superseded, already expired, immutable-document, or cyclic targets, and\n * for an inverted or empty interval (`invalid_interval`). When the old\n * fact carried a future `valid_to`, that scheduled end is overwritten but\n * kept in `prior_valid_to` (restored by `reopen()`) and reported as the\n * `supersede_scheduled_end_replaced` diagnostic.\n */\n async supersede(\n entityId: string,\n oldId: string,\n replacement: SupersedeReplacement,\n options?: { validFrom?: number },\n ): Promise<{ newId: string }> {\n return this.temporalService.supersede(entityId, oldId, replacement, options);\n }\n\n /**\n * End `factId`'s validity without a replacement — an archive, not a\n * deletion (INTENT rule 12). Sets `valid_to` only: `superseded_by`,\n * `superseded_at` and `deleted_at` stay untouched, and an `asOf` read at\n * `T` with `COALESCE(valid_from, created_at) <= T < valid_to` still returns\n * the fact. Throws `WikiSupersedeError` for\n * a missing, foreign, already superseded, immutable-document, or already\n * expired target, and for an inverted or empty interval (`invalid_interval`).\n */\n async expire(entityId: string, factId: string, options?: { at?: number }): Promise<void> {\n return this.temporalService.expire(entityId, factId, options);\n }\n\n /**\n * Return a superseded fact to live once its replacement has been forgotten\n * or hard-deleted (INTENT rule 12). Clears `superseded_by`/`superseded_at`\n * and restores `valid_to` to the scheduled end `supersede()` overwrote\n * (`prior_valid_to`), or null when the fact was open-ended. Resolves with\n * the restored `valid_to`. Throws `WikiSupersedeError` for a missing or\n * foreign fact, one that is not superseded (an `expire()`-ended fact is\n * not reopened), an immutable-document fact, or `successor_live` while the\n * direct replacement is still live. A restored end that has already passed\n * leaves the fact expired.\n */\n async reopen(entityId: string, factId: string): Promise<{ valid_to: number | null }> {\n return this.temporalService.reopen(entityId, factId);\n }\n\n /** The supersession chain containing `factId`, oldest first. [] when unknown. */\n async history(entityId: string, factId: string): Promise<WikiFact[]> {\n return this.temporalService.history(entityId, factId);\n }\n\n /**\n * Store one mutable fact directly, with no LLM step (spec\n * `specs/core-remember/spec.md`). One transaction; resolves with the stored\n * row read back (`id`, timestamps, defaults, `isStale`, `trustTier`). Never\n * starts the librarian or heal and writes no event, in `'auto'` and\n * `'deferred'` mode alike. Embeds through `llmProvider.embed` when present;\n * keyword-only otherwise. Not idempotent. To replace an existing fact use\n * `supersede()` so history is kept. Opens its own transaction: do not call\n * it inside `withTransactionAsync` (the serialized adapter would deadlock).\n *\n * Throws `TypeError` on invalid input and `WikiStrictOntologyViolation` for\n * an `okf_type` the entity's strict manifest does not define; nothing is\n * written in either case.\n */\n async remember(entityId: string, input: RememberInput): Promise<WikiFact> {\n return this.rememberService.remember(entityId, input);\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`, and that transaction must be\n * opened through the adapter given to `createWiki` (the removal ledger is\n * filled by triggers inside it, and a rollback discards the rows). 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). After the\n * transaction commits, call `syncSearchIndex(entityId)` — or\n * `syncSearchIndex()` after writing several entities in one transaction —\n * to make the new nodes keyword-searchable and to deliver, through the\n * host's removal hook, the vectors of any facts the call superseded: both forms drain this call's node ids\n * first, to completion, so the nodes are searchable under any backlog (up to\n * `WikiMemory.UPSERT_ID_STASH_CAP` pending ids; beyond that they converge with\n * the backlog). Embeddings still come from the maintenance\n * sweep (`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 { supersededFactIds, ...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 // Core never sees this commit. Under a ledger strategy the triggers already\n // recorded the rows: stash the node ids and superseded ids for the search\n // drain. The superseded ids also go in the removal stash (any strategy), so\n // the host's post-commit syncSearchIndex() delivers their removals.\n // MiniSearch has no ledger: markStale makes that sync rebuild the entity.\n this.stashUpsertIds(entityId, [...supersededFactIds, ...params.nodes.map((n) => n.id)]);\n this.stashRemovalIds(entityId, supersededFactIds);\n this.searchService.markStale(entityId);\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 // The reserved abstain sentinel is rejected here on the write path\n // (specs/system-one-config §5, decree C4); per-read validateManifest is\n // deliberately untouched so legacy manifests carrying the slug still read.\n for (const entry of entries) {\n validateManifest(entry.manifest);\n for (const nodeType of entry.manifest.node_types ?? []) {\n if (isReservedAbstainSlug(nodeType.type)) {\n throw new Error(\n `Invalid node type '${nodeType.type}': '${ONTOLOGY_ABSTAIN_SENTINEL}' is reserved for classifier abstention and cannot be declared in a manifest`,\n );\n }\n }\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, SourcePassage } 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\nfunction renderSourceLabel(p: SourcePassage, includeEntityId: boolean): string {\n const entity = includeEntityId ? `${p.entityId} ` : '';\n return `${entity}${p.sourceRef} #${p.seq}${p.truncated ? ' (excerpt)' : ''}`;\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?.compact ?? false) && (options?.includeConfidence ?? true),\n includeTags: !(options?.compact ?? false) && (options?.includeTags ?? true),\n includeEntityIds: !(options?.compact ?? false) && (options?.includeEntityIds ?? false),\n includeFactScores: !(options?.compact ?? false) && (options?.includeFactScores ?? false),\n compact: options?.compact ?? 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 // Spec source-store §7: the Sources group prints last, and only when present.\n const sources = bundle.sources ?? [];\n\n if (sortedFacts.length === 0 && sortedTasks.length === 0 && sortedEvents.length === 0 && sources.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\n if (sources.length > 0) {\n lines.push('');\n lines.push('### Sources');\n for (const p of sources) {\n lines.push(`- [${renderSourceLabel(p, opts.includeEntityIds)}] ${p.text.replace(/\\n/g, '\\n ')}`);\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 if (sources.length > 0) {\n lines.push('SOURCES:');\n for (const p of sources) {\n lines.push(`[${renderSourceLabel(p, opts.includeEntityIds)}] ${p.text}`);\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, WikiSourcePointer, 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 { createdAtValue, isUsableDate } from '../services/importEventStamps';\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\n/**\n * Source-pointer frontmatter map (specs/source-pointers §Export, import, and\n * OKF): emitted only when the pointer is non-null; null slots are omitted.\n * An all-null pointer therefore emits an empty map, which parses back to a\n * null pointer with no diagnostic (spec test 9).\n */\nfunction sourcePointerFrontmatter(\n p: WikiSourcePointer | null | undefined,\n): { event_id?: string; ref?: string; quote?: string; position?: { start: number; length: number } } | undefined {\n if (!p) return undefined;\n return {\n ...(p.event_id != null ? { event_id: p.event_id } : {}),\n ...(p.ref != null ? { ref: p.ref } : {}),\n ...(p.quote != null ? { quote: p.quote } : {}),\n ...(p.position != null ? { position: p.position } : {}),\n };\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 // Temporal (spec 2026-09-29 §10.9): flat epoch-ms keys, like created_at.\n ...(f.valid_from != null ? { valid_from: f.valid_from } : {}),\n ...(f.valid_to != null ? { valid_to: f.valid_to } : {}),\n ...(f.superseded_by != null ? { superseded_by: f.superseded_by } : {}),\n ...(f.superseded_at != null ? { superseded_at: f.superseded_at } : {}),\n ...(f.prior_valid_to != null ? { prior_valid_to: f.prior_valid_to } : {}),\n // Source pointer (specs/source-pointers): map only when non-null; null slots omitted.\n ...(sourcePointerFrontmatter(f.source_pointer)\n ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) }\n : {}),\n // derived_events (specs/inplace-update-provenance §5): optional list, only when non-empty.\n ...(f.derived_events && f.derived_events.length > 0 ? { derived_events: f.derived_events } : {}),\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 // Source pointer (specs/source-pointers): same map rule as the v2 path.\n ...(sourcePointerFrontmatter(f.source_pointer)\n ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) }\n : {}),\n // derived_events (specs/inplace-update-provenance §5): optional list, only when non-empty.\n ...(f.derived_events && f.derived_events.length > 0 ? { derived_events: f.derived_events } : {}),\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 // An occurred_at left as text or out of range by an older import would\n // throw in toISOString, and one outside years 0000-9999 (e.g. a\n // microsecond epoch) renders a heading parseOkfBundle cannot read back.\n // Fall back to created_at for those.\n const occurred = createdAtValue(e.occurred_at);\n // A future occurred_at (e.g. an appointment) is not used either: the\n // re-imported entry would look future-dated and be clamped, losing the\n // date. The dates this preserves are past ones (spec §8.2).\n const logTime = e.occurred_at != null && isUsableDate(occurred) && occurred >= OKF_DATE_MIN && occurred <= OKF_DATE_MAX\n && occurred <= e.created_at\n ? occurred\n : e.created_at;\n return { date: formatLogDate(logTime), text: appendEventIdComment(text, e.id) };\n });\n}\n\n/** Epoch-ms range whose ISO date is a four-digit year (0000-01-01 to 9999-12-31), the only headings parseOkfBundle reads. */\nconst OKF_DATE_MIN = -62167219200000;\nconst OKF_DATE_MAX = 253402300799999;\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 { validateSourcePointerValue } from './sourcePointer';\nimport { validateDerivedEventsValue } from './derivedEvents';\nimport type { OkfFile, OkfFrontmatter, OkfFrontmatterValue } from '@equationalapplications/core-okf';\nimport {\n parseConcept,\n parseLogMd,\n parseRootIndexMd,\n parseEntityIndexMd,\n parseEventIdComment,\n createEventIdDeriver,\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\n/** Lone UTF-16 surrogates → U+FFFD, matching how deriveEventId's UTF-8 encoding hashes them. */\nfunction replaceLoneSurrogates(s: string): string {\n let out = '';\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n if (c >= 0xd800 && c <= 0xdbff) {\n const n = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;\n if (n >= 0xdc00 && n <= 0xdfff) { out += s[i] + s[i + 1]; i++; } else out += '\\uFFFD';\n } else if (c >= 0xdc00 && c <= 0xdfff) {\n out += '\\uFFFD';\n } else {\n out += s[i];\n }\n }\n return out;\n}\n\nfunction unescapeLogSummary(summary: string): string {\n return summary.replace(/\\\\\\]/g, ']').replace(/\\\\\\[/g, '[').replace(/\\\\\\\\/g, '\\\\');\n}\n\n// linear: label group cannot start a plain char on `\\` or `[` (closes CodeQL #8); plain branch starts on \\S (closes CodeQL #1)\nconst LOG_LINE_PATTERN = /^\\(([^)]+)\\)\\s*(?:\\[((?:\\\\.|[^\\[\\]\\\\])*)\\]\\(([^)]+)\\)|(\\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 // Producers escape `\\`, `[` and `]` in every summary (profile §7), so the plain form is unescaped too.\n return { event_type, summary: unescapeLogSummary((plainSummary ?? '').trim()) };\n}\n\nfunction frontmatterToFact(\n entityId: string,\n id: string,\n frontmatter: OkfFrontmatter,\n body: string,\n now: number,\n droppedPointerValues: Array<{ factId: string; reason: string }>,\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 ...optionalEpoch('valid_from', (frontmatter as any).valid_from),\n ...optionalEpoch('valid_to', (frontmatter as any).valid_to),\n ...(typeof (frontmatter as any).superseded_by === 'string' ? { superseded_by: (frontmatter as any).superseded_by } : {}),\n ...optionalEpoch('superseded_at', (frontmatter as any).superseded_at),\n ...optionalEpoch('prior_valid_to', (frontmatter as any).prior_valid_to),\n // Source pointer (specs/source-pointers §Export, import, and OKF): the\n // parse path has no diagnostic channel, so it reports through the result.\n // ABSENT key → the property is omitted (not null), so the import\n // presence guard survives the parse. Malformed → the property is omitted\n // AND the drop is reported as entry id + reason slug — never the raw\n // value, which can carry quote text.\n ...(() => {\n const raw = (frontmatter as any).source_pointer;\n if (raw === undefined) return {};\n const v = validateSourcePointerValue(raw);\n if (v === undefined) {\n droppedPointerValues.push({ factId: id, reason: 'malformed' });\n return {};\n }\n return { source_pointer: v };\n })(),\n // derived_events (specs/inplace-update-provenance §5): a well-formed list\n // is restored; absent or empty omits the property (import presence rule);\n // malformed omits it AND is reported by id + slug, never the raw value.\n ...(() => {\n const raw = (frontmatter as any).derived_events;\n if (raw === undefined) return {};\n const v = validateDerivedEventsValue(raw);\n if (v === undefined) {\n droppedPointerValues.push({ factId: id, reason: 'derived_events_malformed' });\n return {};\n }\n return v ? { derived_events: v } : {};\n })(),\n };\n}\n\n/** Temporal epoch-ms frontmatter keys (spec 2026-09-29 §10.9): keep only finite,\n * non-negative numbers; anything else means \"absent\" and the key stays off. */\nfunction optionalEpoch<K extends string>(key: K, v: unknown): Partial<Record<K, number>> {\n return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? ({ [key]: Math.trunc(v) } as Record<K, number>) : {};\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 // Source-pointer parse report (specs/source-pointers): present on the\n // returned MemoryDump only when a malformed `source_pointer` was dropped.\n const droppedPointerValues: Array<{ factId: string; reason: string }> = [];\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, droppedPointerValues));\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 // Id-less lines get a derived id after the whole log is read, so explicit ids\n // anywhere in the file are known first (spec import-followups §3.2).\n const pending: Array<{ index: number; date: string }> = [];\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 if (eventId === undefined) pending.push({ index: events.length, date: entry.date });\n events.push({\n id: eventId ?? '',\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 // Occurrence per (day, type, summary); a derived id already taken by an explicit\n // id or an earlier derived id moves to the next occurrence, so no line is dropped.\n const taken = new Set(events.map(e => e.id).filter(id => id !== ''));\n const nextOccurrence = new Map<string, number>();\n for (const { index, date } of pending) {\n const e = events[index];\n // Keyed by the text the hash sees: lone surrogates hash as U+FFFD, so\n // variants that differ only in them share one count (keeps this linear).\n const key = JSON.stringify([date, e.event_type, replaceLoneSurrogates(e.summary)]);\n let occurrence = nextOccurrence.get(key) ?? 0;\n // Hash the shared fields once: explicit ids can take a long line's whole\n // chain of occurrences, and re-hashing the summary per step is quadratic.\n const derive = createEventIdDeriver({ entityId, date, eventType: e.event_type, summary: e.summary });\n let id = derive(occurrence);\n while (taken.has(id)) {\n occurrence += 1;\n id = derive(occurrence);\n }\n taken.add(id);\n nextOccurrence.set(key, occurrence + 1);\n e.id = id;\n }\n }\n\n return {\n generatedAt: now,\n entities: {\n [entityId]: { facts, tasks, events, edges, summary: entitySummary },\n },\n ...(droppedPointerValues.length > 0 ? { dropped_pointer_values: droppedPointerValues } : {}),\n };\n}\n","/**\n * Context-budget wrapper (specs/context-budget Proposed change 2).\n *\n * Core ships no tokenizer: every estimate is chars/`charsPerToken`. The\n * meter keeps plain `estimateTokens` (chars/4) this PR — metering is out of\n * scope — so `estimateTokensWith` under a legacy budget (`charsPerToken: 4`)\n * is byte-equal to `estimateTokens` for every input, and the wrapper ships\n * unused by metering.\n */\nexport interface ContextBudget {\n mode: 'legacy' | 'declared';\n /** Set iff mode === 'declared'. */\n contextWindowTokens?: number;\n /** 4 under legacy. */\n charsPerToken: number;\n /** 0.9 under legacy (unused in legacy math). */\n safetyFraction: number;\n /** 4000 under legacy (unused in legacy math). */\n outputReserveTokens: number;\n}\n\nexport function estimateTokensWith(budget: ContextBudget, text: string): number {\n return Math.ceil(text.length / budget.charsPerToken);\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 { buildOntologyPromptAppendix } from './prompts/ontology';\nexport { configureRandomSource } from './utils/ids';\nexport { validUsage } from './utils/llmCall';\nexport { chunkText, safeSlice } from './utils/pure';\nexport { DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_CHUNK_OVERLAP } from './utils/chunkingDefaults';\nexport { resolveContextBudget, resolveMaxPromptChars, resolveDefaultChunkLength } from './config/context';\nexport type { ContextBudget } from './utils/contextBudget';\nexport { estimateTokensWith } from './utils/contextBudget';\nexport { DEFAULT_MAX_EMBED_CHARS, EMBED_CHARS_CEILING } from './utils/embedDefaults';\nexport { DEFAULT_SETUP_BUDGET_MS } from './utils/setupDefaults';\nexport * from './librarianPrompt';\nexport { PromptService } from './services/PromptService';\nexport { resolveOntologyJobDefaults, DEFAULT_ONTOLOGY_JOB_BATCH_SIZE } from './utils/config/ontologyJobDefaults';\nexport {\n resolveSystemOneTyping,\n resolveTypingMinConfidence,\n resolveSystemOneEdges,\n resolveEdgesMinConfidence,\n resolveSystemOneResolve,\n resolveResolveMinConfidence,\n resolveSystemOneHealScreen,\n resolveSystemOneTypeOnWrite,\n resolveHealScreenMinConfidence,\n warnOnce,\n DEFAULT_TYPING_MIN_CONFIDENCE,\n} from './utils/engineDefaults';\nexport { ONTOLOGY_ABSTAIN_SENTINEL, isReservedAbstainSlug } from './utils/ontology';\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 CLASSIFIER_MAX_CHOICES,\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 { EraseStepError } from './services/MaintenanceService';\nexport type { EraseReport } from './services/MaintenanceService';\nexport { CheckpointIncompleteError } from './repositories/MetadataRepository';\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/migrationGate.ts","../src/db/serializedAdapter.ts","../src/repositories/EntryRepository.ts","../src/repositories/OutboxRepository.ts","../src/repositories/SourceRefIndexRepository.ts","../src/repositories/TaskRepository.ts","../src/repositories/EventRepository.ts","../src/utils/monotonicNow.ts","../src/utils/setupDefaults.ts","../src/services/search/ftsQuery.ts","../src/services/search/Fts5IndexStrategy.ts","../src/services/search/MiniSearchIndexStrategy.ts","../src/services/search/createIndexStrategy.ts","../src/utils/config/ontologyJobDefaults.ts","../src/services/MaintenanceScheduler.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/utils/rememberInput.ts","../src/services/RememberService.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/utils/contextBudget.ts","../src/librarianPrompt.ts","../src/index.ts"],"names":["isStaleAfter","deriveTrustTier","rows","assertEntityId","stashed","relatedLinksFor","CONFIDENCE_VALUES","latestVerified"],"mappings":";;;;;;AAMA,IAAM,kBAAA,GAAiD,CAAC,OAAA,EAAS,QAAA,EAAU,MAAM,CAAA;AASjF,eAAsB,qBAAA,CACpB,EAAA,EACA,MAAA,EACA,I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,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;;;ACPO,SAAS,UAAA,CAAW,IAAmB,OAAA,EAAkC;AAC9E,EAAA,OAAO,IAAI,UAAA,CAAW,EAAA,EAAI,OAAO,CAAA;AACnC","file":"index.mjs","sourcesContent":["import type { SQLiteAdapter, MigrationPolicy, PendingMigrationWork } from '../types';\nimport type { MetadataRepository } from '../repositories/MetadataRepository';\nimport { probePendingWork } from './sourceRefNormalize';\nimport { setupDatabase } from './schema';\nimport { WikiMigrationRequiredError } from '../types';\n\nconst MIGRATION_POLICIES: readonly MigrationPolicy[] = ['allow', 'refuse', 'auto'];\n\n/**\n * Runs the read-only migration gate, then setupDatabase's every-open DDL.\n * - 'allow': no gate.\n * - 'refuse': any pending work throws before any mutation.\n * - 'auto': a pending schema migration throws; a pending source_ref normalize\n * is let through and run by setup() after the DDL and migrations loop.\n */\nexport async function setupDatabaseWithGate(\n db: SQLiteAdapter,\n prefix: string,\n meta: MetadataRepository,\n migrations: MigrationPolicy = 'allow',\n): Promise<void> {\n // Fail closed: an unrecognized value (e.g. 'Refuse' from env/JSON config) must not\n // silently skip the refusal and run a migration inside a time-critical open.\n if (!MIGRATION_POLICIES.includes(migrations)) {\n throw new TypeError(`Invalid migrations policy ${JSON.stringify(migrations)}; expected 'allow', 'refuse' or 'auto'.`);\n }\n if (migrations !== 'allow') {\n const pending = await probePendingWork(db, meta, prefix);\n if (pending && (migrations === 'refuse' || pending.type === 'schema_migration')) {\n throw new WikiMigrationRequiredError(describePending(pending, migrations), pending);\n }\n }\n return setupDatabase(db, prefix);\n}\n\nfunction describePending(pending: PendingMigrationWork, policy: MigrationPolicy): string {\n const what = pending.type === 'schema_migration'\n ? `schema migration v${pending.fromVersion} -> v${pending.toVersion} is pending`\n : pending.entriesWatermark === 0 && pending.sourceRefIndexWatermark === 0\n ? 'source_ref normalize has not run on this store (normalize stamp missing or outdated; may complete with zero rewrites)'\n : 'source_ref normalize was interrupted and will resume from its watermark';\n return `Migration refused (migrations: '${policy}'): ${what}. ` +\n `Open once with setup({ migrations: 'allow' }) outside any time-critical path to complete it.`;\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, WikiFact, EmbeddingMarkerKind } from '../types';\nimport { WikiGraphNodeOwnershipConflict } from '../types';\nimport { BaseRepository } from './BaseRepository';\nimport { OutboxRepository } from './OutboxRepository';\nimport { parseJsonArray, parseJsonObject } from './rowMappers';\nimport { reanchorRebuildFingerprint } from '../services/search/fts5Progress';\nimport { liveAtSql, type LiveMode } from '../utils/temporal';\nimport { isStaleAfter, deriveTrustTier } from '@equationalapplications/core-okf';\nimport { parseStoredSourcePointer, serializeSourcePointer } from '../utils/sourcePointer';\nimport { parseStoredDerivedEvents, serializeDerivedEvents } from '../utils/derivedEvents';\n\n/** Subset of temporal columns that {@link EntryRepository.setTemporal} may write (spec 2026-09-29 §4.3). */\nexport type TemporalFields = {\n valid_from?: number | null;\n valid_to?: number | null;\n superseded_by?: string | null;\n superseded_at?: number | null;\n prior_valid_to?: number | null;\n};\n\n/** Lightweight projection used by TemporalService for supersession chain walks. */\nexport type TemporalRow = {\n id: string;\n entity_id: string;\n source_type: WikiFact['source_type'];\n deleted_at: number | null;\n created_at: number;\n valid_from: number | null;\n valid_to: number | null;\n superseded_by: string | null;\n prior_valid_to: number | null;\n};\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 const sourcePointer = parseStoredSourcePointer(row.source_pointer);\n const derivedEvents = parseStoredDerivedEvents(row.derived_events);\n\n const mapped = {\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 // Temporal (spec 2026-09-29 §4, §10.8): keys appear only when set so\n // existing deep-equality assertions and host snapshots are unchanged.\n ...(row.valid_from != null ? { valid_from: Number(row.valid_from) } : {}),\n ...(row.valid_to != null ? { valid_to: Number(row.valid_to) } : {}),\n ...(row.superseded_by != null ? { superseded_by: String(row.superseded_by) } : {}),\n ...(row.superseded_at != null ? { superseded_at: Number(row.superseded_at) } : {}),\n ...(row.prior_valid_to != null ? { prior_valid_to: Number(row.prior_valid_to) } : {}),\n // Source pointer (specs/source-pointers): key appears only when non-null,\n // same temporal-fields pattern. Tolerant read: a malformed stored value\n // reads as null without throwing (test 1).\n ...(sourcePointer ? { source_pointer: sourcePointer } : {}),\n // derived_events (specs/inplace-update-provenance §5): present only when\n // non-empty; a malformed stored value reads as absent without throwing.\n ...(derivedEvents ? { derived_events: derivedEvents } : {}),\n };\n return mapped as WikiFact;\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 /**\n * Column list and liveness predicate shared by findMiniSearchRows and\n * findMiniSearchRowsByIds, so the full rebuild and the incremental read\n * can never drift apart (spec 2026-09-28 §4.4: both must produce\n * identical documents).\n */\n private static readonly MINI_SEARCH_COLUMNS = 'id, entity_id, title, body, tags';\n private static readonly MINI_SEARCH_LIVE_WHERE = 'WHERE deleted_at IS NULL';\n\n private chunkSize = 500;\n\n constructor(db: SQLiteAdapter, prefix: string, private outbox: OutboxRepository) {\n super(db, prefix);\n }\n\n /** Whether the entity has any non-deleted row (librarian gate: keyword ranking over zero facts is trivially empty). */\n async hasLiveEntry(entityId: string, 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 entity_id = ? AND deleted_at IS NULL LIMIT 1`,\n [entityId],\n );\n return row != null;\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 source_pointer: string | null;\n derived_events: 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, source_pointer, derived_events\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, source_pointer, derived_events\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 derived_events = CASE WHEN ? THEN excluded.derived_events ELSE derived_events END\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 serializeSourcePointer(fact.source_pointer),\n serializeDerivedEvents(fact.derived_events),\n // derived_events is writable on conflict (the librarian's in-place\n // UPDATE merges events into it), but only when the caller supplied the\n // key: an undefined key leaves a stored list untouched.\n fact.derived_events !== undefined ? 1 : 0,\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 — and source_pointer\n // (insert-only rule, specs/source-pointers §Writes) — so the prior row\n // values win. Re-read those columns from the stored row and overlay them\n // onto the caller-supplied payload before publishing (#90 review; the\n // stored pointer publishes instead of a fabricated null).\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 source_pointer: parseStoredSourcePointer(existingRow.source_pointer),\n ...(fact.derived_events === undefined\n ? (() => {\n const stored = parseStoredDerivedEvents(existingRow.derived_events);\n return stored ? { derived_events: stored } : {};\n })()\n : {}),\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; deleted_at: number | null }>> {\n const executor = this.getExecutor(tx);\n const rows: Array<{ id: string; entity_id: string; updated_at: number; deleted_at: number | 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<any>(\n `SELECT id, entity_id, updated_at, deleted_at FROM ${this.prefix}entries WHERE id IN (${placeholders})`,\n chunk,\n );\n rows.push(...chunkRows.map((row) => ({\n id: row.id,\n entity_id: row.entity_id,\n updated_at: Number(row.updated_at),\n deleted_at: row.deleted_at == null ? null : Number(row.deleted_at),\n })));\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(\n fact: WikiFact,\n tx: SQLiteAdapter,\n sourcePointerPresent = false,\n derivedEventsPresent = false,\n ): 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 // Source pointer (specs/source-pointers §Export, import, and OKF): a\n // static SET list cannot express \"absent means untouched\", so the import\n // path carries a per-row presence flag and the SET clause switches on it.\n // A pre-release dump (flag false) can neither null a stored pointer nor\n // emit a storm of false source_pointer_invalid reports — a deliberate\n // departure from the temporal replace semantics next to it, because a\n // pre-release dump is the exact case this rule exists for. No comments\n // inside the SQL template itself: everything in the backticks is SQL.\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, source_pointer, derived_events\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 source_pointer = CASE WHEN ? THEN excluded.source_pointer ELSE source_pointer END,\n derived_events = CASE WHEN ? THEN excluded.derived_events ELSE derived_events END`,\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 serializeSourcePointer(fact.source_pointer),\n serializeDerivedEvents(fact.derived_events),\n // The presence flag binds to the SET clause's CASE, AFTER the INSERT\n // values above.\n sourcePointerPresent ? 1 : 0,\n // derived_events follows the same presence-flag pattern: a pre-v18\n // dump (no key) never nulls a stored list.\n derivedEventsPresent ? 1 : 0,\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 * Shared JSON match predicate for an event id\n * (specs/forget-by-event-id §D1, widened by specs/inplace-update-provenance\n * §4): a row matches when its `source_pointer` names the event OR its\n * `derived_events` list contains it. Every JSON call sits under its own\n * `json_valid` guard: unguarded JSON functions RAISE on malformed text, and\n * three-valued logic forces evaluation of AND operands after a NULL-guarded\n * term — a two-term form is only as safe as the planner's term-splitting.\n * The `json_each` term additionally requires `json_type = 'array'` (a JSON\n * object or scalar would otherwise iterate its members). The event id binds\n * TWICE (pointer term, then derived_events term); use `eventMatchArgs`.\n * The tombstone guard (`deleted_at IS NULL`) is added per-method.\n */\n static readonly EVENT_MATCH_SQL = `((CASE WHEN json_valid(source_pointer)\n THEN json_type(source_pointer, '$.event_id') = 'text'\n AND json_extract(source_pointer, '$.event_id') = ?\n ELSE 0 END)\n OR\n (CASE WHEN json_valid(derived_events)\n THEN (CASE WHEN json_type(derived_events) = 'array'\n THEN EXISTS (SELECT 1 FROM json_each(derived_events) WHERE json_each.type = 'text' AND json_each.value = ?)\n ELSE 0 END)\n ELSE 0 END))`;\n\n /** Bind values for `EVENT_MATCH_SQL` after an `entity_id = ?` term: the event id twice. */\n static eventMatchArgs(entityId: string, eventId: string): [string, string, string] {\n return [entityId, eventId, eventId];\n }\n\n /** Old name kept as an alias (tests and external references). */\n static readonly POINTER_EVENT_MATCH_SQL = EntryRepository.EVENT_MATCH_SQL;\n\n /**\n * IDs of the entity's entries whose source_pointer names the event id or whose derived_events list contains it.\n * `includeDeleted = true` returns live + tombstoned rows (the forget\n * enumeration superset for index sync and the ledger backstop).\n */\n async findIdsByPointerEvent(\n entityId: string,\n eventId: string,\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 = ? AND ${EntryRepository.POINTER_EVENT_MATCH_SQL}`;\n const args: unknown[] = EntryRepository.eventMatchArgs(entityId, eventId);\n if (!includeDeleted) sql += ` AND deleted_at IS NULL`;\n const rows = await executor.getAllAsync<{ id: string }>(sql, args);\n return rows.map((r) => r.id);\n }\n\n /** Live-row count for the event id — dry-run only (a real call is idempotent over tombstones). */\n async countLiveByPointerEvent(entityId: string, eventId: string, tx?: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ n: number }>(\n `SELECT COUNT(*) AS n FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND ${EntryRepository.POINTER_EVENT_MATCH_SQL}`,\n EntryRepository.eventMatchArgs(entityId, eventId),\n );\n return row?.n ?? 0;\n }\n\n /**\n * Soft-delete the entity's entries whose source_pointer names the event id,\n * within a transaction. Stages a DELETE outbox entry for each row that\n * changed, in the same transaction (parity with softDeleteBySource — synced\n * replicas learn of the tombstones through the outbox). The `deleted_at\n * IS NULL` guard makes the call idempotent: already-tombstoned rows are\n * no-op hits and are not counted. `tx` is REQUIRED.\n * Returns the number of rows deleted.\n */\n async softDeleteByPointerEvent(entityId: string, eventId: string, tx: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const now = Date.now();\n const idsToDelete = await executor.getAllAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND ${EntryRepository.POINTER_EVENT_MATCH_SQL}`,\n EntryRepository.eventMatchArgs(entityId, eventId),\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 AND ${EntryRepository.POINTER_EVENT_MATCH_SQL}`,\n [now, now, ...EntryRepository.eventMatchArgs(entityId, eventId)],\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 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 opts?: { noCutoff?: boolean },\n ): Promise<Array<{ id: string; entity_id: string }>> {\n const executor = this.getExecutor(tx);\n // noCutoff (erase): every soft-deleted row, no timestamp predicate — see\n // getDistinctEntityIds's softDeletedAll note.\n const cutoffPredicate = opts?.noCutoff ? '' : ' AND deleted_at <= ?';\n const args: unknown[] = opts?.noCutoff ? [entityId] : [entityId, cutoff];\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${cutoffPredicate}`,\n args,\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, opts?: { includeDeleted?: boolean }): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n const live = opts?.includeDeleted ? '' : ' AND deleted_at IS NULL';\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries WHERE entity_id = ?${live} 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 now = Date.now();\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 ${liveAtSql('current')}\n AND (heal_checked_at IS NULL OR heal_checked_at <= ?)\n ORDER BY updated_at ASC LIMIT ?`,\n [entityId, now, now, 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 const now = Date.now();\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 ${liveAtSql('current')}\n AND id IN (${placeholders})`,\n [entityId, now, now, ...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 const now = Date.now();\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, now, now, excludeSourceRef, limit] : [entityId, now, now, limit];\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND ${liveAtSql('current')}${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, opts?: { includeDeleted?: boolean }): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n const live = opts?.includeDeleted ? '' : ' AND deleted_at IS NULL';\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries WHERE entity_id = ?${live} 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 opts: { keepUnconfirmedRemovals?: boolean; deletedIds?: string[]; noCutoff?: boolean } = {},\n ): Promise<number> {\n const executor = this.getExecutor(tx);\n // Spec durable-vector-removal §5.6.4: under a removal hook, never hard-delete\n // a fact whose vector-index removal is still owed.\n const guard = opts.keepUnconfirmedRemovals\n ? ` AND NOT EXISTS (SELECT 1 FROM ${this.prefix}vector_removals v WHERE v.fact_id = ${this.prefix}entries.id AND v.confirmed_at IS NULL)`\n : '';\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 // RETURNING names exactly the rows this statement removed: not a row the\n // guard kept, and not a row that was already gone before it ran. deleted_at\n // rides along so the outbox payload stamps the row's real tombstone time —\n // never the sweep cutoff (erase sweeps with a max cutoff, and a payload\n // stamped Number.MAX_SAFE_INTEGER would be nonsense as a timestamp).\n const cutoffPredicate = opts.noCutoff ? '' : ' AND deleted_at <= ?';\n const delArgs: unknown[] = opts.noCutoff ? [entityId, ...chunk] : [entityId, cutoff, ...chunk];\n const deleted = (await executor.getAllAsync<{ id: string; deleted_at: number }>(\n `DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate} AND id IN (${placeholders})${guard} RETURNING id, deleted_at`,\n delArgs,\n )).map((r) => ({ id: r.id, deleted_at: typeof r.deleted_at === 'number' ? r.deleted_at : Number(r.deleted_at) }));\n totalChanges += deleted.length;\n opts.deletedIds?.push(...deleted.map((r) => r.id));\n // Stage outbox entries for permanently deleted records\n if (deleted.length > 0) {\n for (const row of deleted) {\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: row.deleted_at },\n }, tx);\n }\n }\n }\n // Spec #280 Change 3: an engine hard-delete never strands the FTS rebuild fingerprint.\n if (totalChanges > 0) await reanchorRebuildFingerprint(executor, this.prefix, ids);\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 // RETURNING: a row already soft-deleted keeps its deleted_at, so it gets no\n // outbox event carrying a deleted_at the row doesn't have.\n const updated = await executor.getAllAsync<{ id: string }>(\n `UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE id IN (${placeholders}) AND entity_id = ? AND deleted_at IS NULL RETURNING id`,\n [now, now, ...ids, entityId],\n );\n // Stage outbox entries for soft-deleted records\n for (const { id } of updated) {\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 /** Spec §4: write any subset of the five temporal columns. Absent key = untouched; null = clear. */\n async setTemporal(\n id: string,\n entityId: string,\n fields: TemporalFields,\n tx: SQLiteAdapter,\n opts?: { outbox?: boolean },\n ): Promise<number> {\n const keys = (['valid_from', 'valid_to', 'superseded_by', 'superseded_at', 'prior_valid_to'] as const).filter((k) => k in fields);\n if (keys.length === 0) return 0;\n const executor = this.getExecutor(tx);\n const result = await executor.runAsync(\n `UPDATE ${this.prefix}entries SET ${keys.map((k) => `${k} = ?`).join(', ')} WHERE id = ? AND entity_id = ?`,\n [...keys.map((k) => fields[k] ?? null), id, entityId],\n );\n if (result.changes > 0 && opts?.outbox !== false) {\n const payload: Record<string, unknown> = { id, entity_id: entityId };\n for (const k of keys) payload[k] = fields[k] ?? null;\n await this.outbox.push({ entityId, tableName: 'entries', recordId: id, operation: 'UPDATE', payload }, tx);\n }\n return result.changes;\n }\n\n async findTemporalRow(id: string, tx?: SQLiteAdapter): Promise<TemporalRow | null> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<any>(\n `SELECT id, entity_id, source_type, deleted_at, created_at, valid_from, valid_to, superseded_by, prior_valid_to\n FROM ${this.prefix}entries WHERE id = ?`,\n [id],\n );\n if (!row) return null;\n return {\n id: String(row.id),\n entity_id: String(row.entity_id),\n source_type: row.source_type,\n deleted_at: row.deleted_at != null ? Number(row.deleted_at) : null,\n created_at: Number(row.created_at),\n valid_from: row.valid_from != null ? Number(row.valid_from) : null,\n valid_to: row.valid_to != null ? Number(row.valid_to) : null,\n superseded_by: row.superseded_by != null ? String(row.superseded_by) : null,\n prior_valid_to: row.prior_valid_to != null ? Number(row.prior_valid_to) : null,\n };\n }\n\n /**\n * Ids of non-deleted facts NOT live at `t` (spec §4.2). In 'current' mode a\n * row with both validity columns NULL is always live, so the query is\n * restricted to rows that carry a validity column — served by the partial\n * entries_temporal_idx.\n */\n async findNonLiveIdsByEntityIds(\n entityIds: readonly string[],\n mode: LiveMode,\n t: number,\n tx?: SQLiteAdapter,\n ): 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 temporalOnly = mode === 'current' ? ' AND (valid_from IS NOT NULL OR valid_to IS NOT NULL)' : '';\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${temporalOnly}\n AND NOT ${liveAtSql(mode)}`,\n [...entityIds, t, t],\n );\n return new Set(rows.map((r) => r.id));\n }\n\n /**\n * Depth-aware supersession walk for chain forget (spec forget-erasure §3).\n * Probes `maxDepth + 1` levels so a chain longer than the cap is detectable;\n * the returned ids are capped to `maxDepth` per direction (successors nearest first; predecessors are returned farthest-first).\n * No `deleted_at` filter: soft-deleted links still carry the chain.\n */\n async findSupersessionChainWalk(\n entityId: string,\n factId: string,\n maxDepth: number,\n tx?: SQLiteAdapter,\n ): Promise<{ ids: string[]; truncated: boolean }> {\n const { predecessors, successors } = await this.findSupersessionChainIds(entityId, factId, maxDepth + 1, tx);\n // Cap by row DEPTH, not row count: a node with more than `maxDepth` direct\n // predecessors (all depth 1) is a wide fan-in, not a chain longer than the\n // cap — counting rows would set `truncated` and drop reachable rows.\n const truncated = predecessors.some((r) => r.depth > maxDepth) || successors.some((r) => r.depth > maxDepth);\n // predecessors are ordered farthest-first (ORDER BY depth DESC), so the nearest are at the end.\n const pred = predecessors.filter((r) => r.depth <= maxDepth).map((r) => r.id);\n const succ = successors.filter((r) => r.depth <= maxDepth).map((r) => r.id);\n return { ids: Array.from(new Set([...succ, ...pred])), truncated };\n }\n\n async findSupersessionChainIds(\n entityId: string,\n factId: string,\n maxDepth: number,\n tx?: SQLiteAdapter,\n ): Promise<{ predecessors: Array<{ id: string; depth: number }>; successors: Array<{ id: string; depth: number }> }> {\n const executor = this.getExecutor(tx);\n const successors = await executor.getAllAsync<{ id: string; depth: number }>(\n `WITH RECURSIVE fwd(id, depth) AS (\n SELECT superseded_by, 1 FROM ${this.prefix}entries WHERE id = ? AND entity_id = ? AND superseded_by IS NOT NULL\n UNION\n SELECT e.superseded_by, fwd.depth + 1 FROM fwd\n JOIN ${this.prefix}entries e ON e.id = fwd.id AND e.entity_id = ?\n WHERE e.superseded_by IS NOT NULL AND fwd.depth < ?\n )\n SELECT id, depth FROM fwd ORDER BY depth ASC`,\n [factId, entityId, entityId, maxDepth],\n );\n const predecessors = await executor.getAllAsync<{ id: string; depth: number }>(\n `WITH RECURSIVE bwd(id, depth) AS (\n SELECT id, 1 FROM ${this.prefix}entries WHERE entity_id = ? AND superseded_by = ?\n UNION\n SELECT e.id, bwd.depth + 1 FROM bwd\n JOIN ${this.prefix}entries e ON e.entity_id = ? AND e.superseded_by = bwd.id\n WHERE bwd.depth < ?\n )\n SELECT id, depth FROM bwd ORDER BY depth DESC`,\n [entityId, factId, entityId, maxDepth],\n );\n const drop = (rows: Array<{ id: string; depth: number }>) => rows.filter((r) => r.id !== factId);\n return { predecessors: drop(predecessors), successors: drop(successors) };\n }\n\n async findExpiredIds(entityId: string, cutoff: number, tx?: SQLiteAdapter): Promise<string[]> {\n const executor = this.getExecutor(tx);\n const rows = await executor.getAllAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL AND valid_to IS NOT NULL AND valid_to <= ?\n ORDER BY valid_to ASC`,\n [entityId, cutoff],\n );\n return rows.map((r) => r.id);\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 ${EntryRepository.MINI_SEARCH_COLUMNS} FROM ${this.prefix}entries ${EntryRepository.MINI_SEARCH_LIVE_WHERE} AND entity_id = ?`,\n [entityId],\n );\n }\n return executor.getAllAsync(\n `SELECT ${EntryRepository.MINI_SEARCH_COLUMNS} FROM ${this.prefix}entries ${EntryRepository.MINI_SEARCH_LIVE_WHERE}`,\n );\n }\n\n /**\n * Keyword-index rows for specific ids — the incremental counterpart of\n * {@link findMiniSearchRows}, with identical columns. Soft-deleted rows and\n * rows of other entities are omitted, so a caller can pass every id a write\n * touched and get back exactly what should be indexed. Spec 2026-09-28 §4.4.\n */\n async findMiniSearchRowsByIds(\n entityId: string,\n ids: readonly string[],\n tx?: SQLiteAdapter,\n ): Promise<Array<{ id: string; entity_id: string; title: string; body: string; tags: string }>> {\n if (ids.length === 0) return [];\n const executor = this.getExecutor(tx);\n const rows: Array<{ id: string; entity_id: string; title: string; body: string; tags: string }> = [];\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 rows.push(...(await executor.getAllAsync<{ id: string; entity_id: string; title: string; body: string; tags: string }>(\n `SELECT ${EntryRepository.MINI_SEARCH_COLUMNS} FROM ${this.prefix}entries ${EntryRepository.MINI_SEARCH_LIVE_WHERE} AND entity_id = ? AND id IN (${placeholders})`,\n [entityId, ...chunk],\n )));\n }\n return rows;\n }\n\n /** Returns `changes: 0` when the row is soft-deleted or gone (spec durable-vector-removal §5.7, G10). */\n async updateEmbeddingBlob(id: string, blob: Uint8Array, tx?: SQLiteAdapter): Promise<{ changes: number }> {\n const executor = this.getExecutor(tx);\n const r = 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 = ? AND deleted_at IS NULL`,\n [blob, id],\n );\n return { changes: r?.changes ?? 0 };\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 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 /** Spec source-store §4 three-state: exact pair / stale hash / nothing stored. */\n stored?: { charCount: number; staleHash?: true } | null;\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 stored_hash: string | null;\n stored_chars: number | null;\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 ranked.source_ref,\n ranked.source_hash AS source_hash,\n ranked.fact_count AS fact_count,\n ranked.updated_at AS last_ingested_at,\n d.source_hash AS stored_hash,\n d.char_count AS stored_chars\n FROM ranked\n LEFT JOIN ${this.prefix}source_documents d\n ON d.entity_id = ? AND d.source_ref = ranked.source_ref\n WHERE ranked.rn = 1\n ORDER BY ranked.source_ref COLLATE BINARY`,\n [entityId, 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 // Spec source-store §4: keyed on the ref's own (sourceRef, sourceHash) pair.\n stored:\n r.stored_hash === null || r.stored_hash === undefined\n ? null\n : r.stored_hash === r.source_hash\n ? { charCount: Number(r.stored_chars) }\n : { charCount: Number(r.stored_chars), staleHash: true as const },\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; live?: { mode: LiveMode; t: number } },\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 liveClause = opts?.live ? ` AND ${liveAtSql(opts.live.mode)}` : '';\n const liveArgs = opts?.live ? [opts.live.t, opts.live.t] : [];\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}entries WHERE entity_id IN (${placeholders}) AND deleted_at IS NULL${draftClause}${liveClause} ORDER BY updated_at DESC LIMIT ?`,\n [...entityIds, ...liveArgs, 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 * The queue sees CURRENT facts only (ontology-curation Task 10): rows whose\n * validity window excludes \"now\" are invisible to typing, matching the\n * read-time liveness definition (utils/temporal.ts).\n */\n async findUntypedByEntityId(entityId: string, limit: number, recheckCutoff: number, tx?: SQLiteAdapter): Promise<WikiFact[]> {\n const executor = this.getExecutor(tx);\n // Validity is evaluated at the current sample time, NOT at recheckCutoff:\n // a fact that became live after the cutoff must still queue, and one that\n // expired since must not (CodeRabbit #441, EntryRepository:1813).\n const now = Date.now();\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 AND ${liveAtSql('current')}\n ORDER BY updated_at ASC LIMIT ?`,\n [entityId, recheckCutoff, now, now, limit],\n );\n return rows.map(mapRowToFact);\n }\n\n /** Counts live untyped facts: eligible (past cooldown) vs deferred (in cooldown). Current facts only, as {@link findUntypedByEntityId}. */\n async countUntypedByEntityId(entityId: string, recheckCutoff: number, tx?: SQLiteAdapter): Promise<{ eligible: number; deferred: number }> {\n const executor = this.getExecutor(tx);\n // Same current-time validity sampling as {@link findUntypedByEntityId}.\n const now = Date.now();\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 AND ${liveAtSql('current')}`,\n [recheckCutoff, recheckCutoff, entityId, now, now],\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 /**\n * Shortlist scoring rows (id, title, okf_type, body) over all live typed\n * facts. Same filters as findTitleIndexByEntityId; okf_type is never NULL\n * in results because the query excludes untyped rows.\n */\n async findShortlistRowsByEntityId(entityId: string, tx?: SQLiteAdapter): Promise<Array<{ id: string; title: string; okf_type: string; body: string }>> {\n const executor = this.getExecutor(tx);\n return executor.getAllAsync<{ id: string; title: string; okf_type: string; body: string }>(\n `SELECT id, title, okf_type, body FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND okf_type IS NOT NULL`,\n [entityId],\n );\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 now = Date.now();\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 AND ${liveAtSql('current')}`,\n [recheckCutoff, recheckCutoff, entityId, now, now],\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 /**\n * Count of live facts for `entityId` with no stored embedding that are still\n * retryable (`embedding_attempts < maxAttempts`). Backs the deferred\n * maintenance pending report's `reembedPending` flag and the reembed job's\n * entity selection (PR-C 2026-09-29).\n */\n async countReembedPending(entityId: string, maxAttempts: number, tx?: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<{ n: number }>(\n `SELECT COUNT(*) AS n FROM ${this.prefix}entries\n WHERE entity_id = ? AND deleted_at IS NULL AND embedding_blob IS NULL AND embedding IS NULL AND embedding_attempts < ?`,\n [entityId, maxAttempts],\n );\n return Number(row?.n ?? 0);\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 * Hard-delete every row of the entity, live or soft-deleted (forget clearAll,\n * spec import-followups §6 rev 4). Nothing reads a soft-deleted row and\n * runPrune never sweeps this table, so a wipe leaves no tombstones.\n */\n async deleteByEntityId(entityId: string, tx: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const result = await executor.runAsync(\n `DELETE FROM ${this.prefix}source_ref_index WHERE entity_id = ?`,\n [entityId],\n );\n return result.changes;\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; deleted_at: number | null }>> {\n const executor = this.getExecutor(tx);\n const rows: Array<{ id: string; entity_id: string; updated_at: number; deleted_at: number | null }> = [];\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, deleted_at FROM ${this.prefix}tasks WHERE id IN (${placeholders})`,\n chunk,\n );\n rows.push(...chunkRows.map((row) => ({\n id: row.id,\n entity_id: row.entity_id,\n updated_at: Number(row.updated_at),\n deleted_at: row.deleted_at == null ? null : Number(row.deleted_at),\n })));\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, opts?: { includeDeleted?: boolean }): Promise<WikiTask[]> {\n const executor = this.getExecutor(tx);\n const live = opts?.includeDeleted ? '' : ' AND deleted_at IS NULL';\n const rows = await executor.getAllAsync<any>(\n `SELECT * FROM ${this.prefix}tasks WHERE entity_id = ?${live} 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 opts?: { noCutoff?: boolean },\n ): Promise<number> {\n const executor = this.getExecutor(tx);\n // noCutoff (erase): every soft-deleted row, no timestamp predicate — a\n // nanosecond-epoch or TEXT-valued deleted_at never matches `<= cutoff`.\n const cutoffPredicate = opts?.noCutoff ? '' : ' AND deleted_at <= ?';\n const selectArgs: unknown[] = opts?.noCutoff ? [entityId] : [entityId, cutoff];\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${cutoffPredicate}`,\n selectArgs,\n );\n if (rowsToDelete.length === 0) return 0;\n\n const deleteArgs: unknown[] = opts?.noCutoff ? [entityId] : [entityId, cutoff];\n const result = await executor.runAsync(\n `DELETE FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate}`,\n deleteArgs,\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';\nimport type { LibrarianWatermark } from './MetadataRepository';\n\n/**\n * Strict-after predicate on the (created_at, id) ordering used by the\n * op-based librarian (spec 2026-09-29 §4.1). Three placeholders: `[at, at, id]`.\n */\nexport const AFTER_SQL = '((created_at > ?) OR (created_at = ? AND id > ?))';\n\nexport function afterArgs(wm: LibrarianWatermark): [number, number, string] {\n return [wm.at, wm.at, wm.id];\n}\n\n/**\n * Map a row from the `events` table to the `WikiEvent` shape returned to\n * callers. `occurred_at` is dropped when NULL so legacy librarian prompt\n * bytes are unchanged for the (current default) case where no caller has\n * supplied a real-world timestamp.\n */\nfunction mapEvent(row: WikiEvent): WikiEvent {\n if (row.occurred_at == null) {\n const rest: WikiEvent = { ...row };\n delete (rest as { occurred_at?: number | null }).occurred_at;\n return rest;\n }\n return row;\n}\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, occurred_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 event.occurred_at ?? null,\n ],\n );\n }\n\n /** Insert unless the id already exists. Returns true when a row was inserted. */\n async addIgnoreDuplicate(event: WikiEvent, tx?: SQLiteAdapter): Promise<boolean> {\n const executor = this.getExecutor(tx);\n const result = await executor.runAsync(\n `INSERT OR IGNORE INTO ${this.prefix}events (id, entity_id, event_type, summary, related_entry_id, created_at, occurred_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 event.occurred_at ?? null,\n ],\n );\n return result.changes > 0;\n }\n\n /**\n * The subset of `ids` that exist as events of `entityId` (specs/\n * inplace-update-provenance §3). Chunked so a large batch stays under the\n * bound-variable limit. Pass `tx` to read inside the caller's transaction.\n */\n async findExistingIds(entityId: string, ids: readonly string[], tx?: SQLiteAdapter): Promise<Set<string>> {\n const executor = this.getExecutor(tx);\n const found = new Set<string>();\n for (let i = 0; i < ids.length; i += 500) {\n const chunk = ids.slice(i, i + 500);\n const rows = await executor.getAllAsync<{ id: string }>(\n `SELECT id FROM ${this.prefix}events WHERE entity_id = ? AND id IN (${chunk.map(() => '?').join(',')})`,\n [entityId, ...chunk],\n );\n for (const r of rows) found.add(r.id);\n }\n return found;\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 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.map(mapEvent);\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 const rows = await 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 return rows.map(mapEvent);\n }\n\n /** Hard-delete every event of the entity, read or not (requested wipe, spec import-followups §6). */\n async deleteByEntityId(entityId: string, tx: SQLiteAdapter): Promise<{ changes: number }> {\n return tx.runAsync(`DELETE FROM ${this.prefix}events WHERE entity_id = ?`, [entityId]);\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, tx?: SQLiteAdapter): Promise<{ changes: number }> {\n return (tx ?? this.db).runAsync(\n `DELETE FROM ${this.prefix}events WHERE entity_id = ? AND created_at <= ?`,\n [entityId, cutoff],\n );\n }\n\n /**\n * Watermark-guarded prune (spec 2026-09-29 competitive-memory §6): delete\n * events at or before `cutoff` **and** at-or-before the librarian watermark.\n * Events the librarian has not processed yet are retention-held, never\n * deleted. `wm = null` (no watermark yet) deletes nothing.\n * Used by runPrune under the deferred/ops strategies.\n */\n async pruneThrough(entityId: string, cutoff: number, wm: LibrarianWatermark | null, tx?: SQLiteAdapter): Promise<{ changes: number }> {\n if (!wm) return { changes: 0 };\n return (tx ?? this.db).runAsync(\n `DELETE FROM ${this.prefix}events WHERE entity_id = ? AND created_at <= ? AND NOT ${AFTER_SQL}`,\n [entityId, cutoff, ...afterArgs(wm)],\n );\n }\n\n /**\n * Count events at or before `cutoff` that are after the watermark — the\n * retention-held tail `pruneThrough` left in place. `wm = null` counts all\n * events at or before `cutoff` (every one of them is held back).\n */\n async countHeldBack(entityId: string, cutoff: number, wm: LibrarianWatermark | null): Promise<number> {\n const where = wm ? ` AND ${AFTER_SQL}` : '';\n const row = await this.db.getFirstAsync<{ n: number }>(\n `SELECT COUNT(*) AS n FROM ${this.prefix}events WHERE entity_id = ? AND created_at <= ?${where}`,\n [entityId, cutoff, ...(wm ? afterArgs(wm) : [])],\n );\n return Number(row?.n ?? 0);\n }\n\n /**\n * The newest `created_at` stored for an entity, or null when it has no\n * events. `write()` reads it inside its transaction to keep `created_at`\n * strictly increasing per entity (spec ops-auto-first-batch §5).\n */\n async latestCreatedAt(entityId: string, tx?: SQLiteAdapter): Promise<number | null> {\n const row = await (tx ?? this.db).getFirstAsync<{ at: number | null }>(\n `SELECT MAX(created_at) AS at FROM ${this.prefix}events WHERE entity_id = ?`,\n [entityId],\n );\n return row?.at ?? null;\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.map(mapEvent).slice().reverse();\n }\n const rows = await this.db.getAllAsync<WikiEvent>(\n `SELECT * FROM ${this.prefix}events WHERE entity_id = ? ORDER BY created_at ASC`,\n [entityId],\n );\n return rows.map(mapEvent);\n }\n\n /**\n * Return events for `entityId` strictly after the watermark `(at, id)` in\n * chronological (ASC, id-ASC tie-break) order. Pass `wm = null` to read\n * from the beginning of the entity's event log. `limit` caps the result.\n *\n * Used by the op-based librarian (PR-B) to enumerate its unprocessed tail.\n */\n async getAfter(\n entityId: string,\n wm: LibrarianWatermark | null,\n limit?: number,\n ): Promise<WikiEvent[]> {\n const limitClause = limit != null ? ` LIMIT ?` : '';\n const params: unknown[] = wm ? [entityId, wm.at, wm.at, wm.id] : [entityId];\n const where = wm ? `entity_id = ? AND ${AFTER_SQL}` : `entity_id = ?`;\n if (limit != null) params.push(limit);\n const rows = await this.db.getAllAsync<WikiEvent>(\n `SELECT * FROM ${this.prefix}events WHERE ${where} ORDER BY created_at ASC, id ASC${limitClause}`,\n params,\n );\n return rows.map(mapEvent);\n }\n\n /**\n * Count of events for `entityId` strictly after the watermark. Used as\n * the op-based librarian's bounded batch size and by the deferred-maintenance\n * pending report. Pass `wm = null` to count the entity's whole event log\n * (no watermark yet) — mirrors `getAfter` / `sumSummaryCharsAfter`.\n */\n async countAfter(entityId: string, wm: LibrarianWatermark | null): Promise<number> {\n const params: unknown[] = wm ? [entityId, wm.at, wm.at, wm.id] : [entityId];\n const where = wm ? `entity_id = ? AND ${AFTER_SQL}` : `entity_id = ?`;\n const row = await this.db.getFirstAsync<{ count: number }>(\n `SELECT COUNT(*) as count FROM ${this.prefix}events WHERE ${where}`,\n params,\n );\n return row?.count ?? 0;\n }\n\n /**\n * Return the event at a given chronological offset for `entityId` (0-based,\n * oldest first). Used by MaintenanceService.seedLibrarianWatermark to anchor\n * the watermark on a real row when a legacy DB first migrates to the\n * op-based librarian. The offset is clamped and truncated to defend against\n * hostile or fractional callers.\n */\n async getAtOffset(entityId: string, offset: number, tx?: SQLiteAdapter): Promise<WikiEvent | null> {\n const executor = this.getExecutor(tx);\n const row = await executor.getFirstAsync<any>(\n `SELECT * FROM ${this.prefix}events WHERE entity_id = ? ORDER BY created_at ASC, id ASC LIMIT 1 OFFSET ?`,\n [entityId, Math.max(0, Math.trunc(offset))],\n );\n return row ? mapEvent(row) : null;\n }\n\n /**\n * Sum of `summary` lengths (in characters) for events for `entityId`\n * strictly after the watermark. Pass `wm = null` to sum the entity's whole\n * event log (no watermark yet). Used by the op-based librarian's token\n * budget estimator (PR-B) and by the auto-trigger's pending-size check\n * (PR-C). SQLite's `LENGTH` returns character count for UTF-8 text input.\n */\n async sumSummaryCharsAfter(entityId: string, wm: LibrarianWatermark | null, tx?: SQLiteAdapter): Promise<number> {\n const executor = this.getExecutor(tx);\n const params: unknown[] = wm ? [entityId, wm.at, wm.at, wm.id] : [entityId];\n const where = wm ? `entity_id = ? AND ${AFTER_SQL}` : `entity_id = ?`;\n const row = await executor.getFirstAsync<{ total: number | null }>(\n `SELECT SUM(LENGTH(summary)) as total FROM ${this.prefix}events WHERE ${where}`,\n params,\n );\n return row?.total ?? 0;\n }\n}\n","/** Monotonic clock (ms): a wall-clock step must not stretch or skip a deadline or a cooldown. */\nexport const monotonicNow = (): number =>\n typeof performance !== 'undefined' && typeof performance.now === 'function' ? performance.now() : Date.now();\n","/**\n * Default `setupBudgetMs`: the wall time each keyword-index quantum (one per\n * `setup()` and per no-arg `syncSearchIndex()`) may spend on drain/rebuild\n * chunks, checked between chunk transactions (spec #280 Config surface).\n */\nexport const DEFAULT_SETUP_BUDGET_MS = 1500;\n","// packages/core/src/services/search/ftsQuery.ts\n\nconst TOKEN = /[\\p{L}\\p{N}]+/gu;\n\n/**\n * Turn a free-text query into an FTS5 MATCH expression that can never be a\n * syntax error: every token is a double-quoted string (FTS5 has no escapes\n * inside quotes except `\"\"`, and tokens contain no quotes), followed by `*`\n * for prefix matching. Tokens are ORed, which matches MiniSearch's\n * `prefix: true` and its `combineWith: 'OR'`. Returns `null` when no token\n * survives, and the caller returns no results.\n */\nexport function buildFtsMatchQuery(query: string): string | null {\n const seen = new Set<string>();\n for (const m of query.toLowerCase().matchAll(TOKEN)) seen.add(m[0]);\n if (seen.size === 0) return null;\n return [...seen].map((t) => `\"${t}\"*`).join(' OR ');\n}\n","// packages/core/src/services/search/Fts5IndexStrategy.ts\nimport type { SQLiteAdapter } from '../../types';\nimport type { MetadataRepository } from '../../repositories/MetadataRepository';\nimport type { DrainOptions, IndexDocument, IndexSearchOptions, IndexSearchResult, IndexStrategy, PassageHit } from './IndexStrategy';\nimport {\n FTS5_DRAIN_CHUNK, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, isRetiredTableName, retiredTableName, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY,\n sweepChunkSql, sweepHiSql, windowChunkSql, windowHiSql, drainChunkSql, drainHiSql, entityDrainChunkSql, entityDrainHiSql, fts5PendingIndexesDdl,\n fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, idDrainChunkSql, idReindexChunkSql,\n passageFtsTablesDdl, passageFtsTriggersDdl,\n} from './fts5Sql';\n\nimport { readRebuildProgress, writeRebuildStart, type RebuildProgress, type RebuildWatermark } from './fts5Progress';\nimport { parseJsonArray } from '../../repositories/rowMappers';\nimport { monotonicNow } from '../../utils/monotonicNow';\nimport { DEFAULT_SETUP_BUDGET_MS } from '../../utils/setupDefaults';\nimport { buildFtsMatchQuery } from './ftsQuery';\nimport { extractSqliteCode } from '../../db/sqliteCodes';\n\n/** One passage hit: `id` is the `source_passages.id`. */\nexport interface PassageSearchResult {\n id: string;\n entity_id: string;\n document_id: string;\n score: number;\n}\n\n/**\n * Attach offsets, source pair and passage text to raw hits. Text is sliced in\n * JS from `source_documents.text` (spec section 7); a hit whose passage or\n * document row is gone is dropped.\n */\nexport async function hydratePassageHits(\n db: SQLiteAdapter, prefix: string, raw: readonly PassageSearchResult[],\n): Promise<PassageHit[]> {\n const docs = new Map<string, { source_ref: string; source_hash: string; text: string } | null>();\n const out: PassageHit[] = [];\n for (const r of raw) {\n const pas = await db.getFirstAsync<{ seq: number; start_offset: number; end_offset: number }>(\n `SELECT seq, start_offset, end_offset FROM ${prefix}source_passages WHERE id = ? AND entity_id = ?`, [r.id, r.entity_id]);\n if (!pas) continue;\n const dk = `${r.entity_id}\\u0000${r.document_id}`;\n if (!docs.has(dk)) {\n docs.set(dk, (await db.getFirstAsync<{ source_ref: string; source_hash: string; text: string }>(\n `SELECT source_ref, source_hash, text FROM ${prefix}source_documents WHERE id = ? AND entity_id = ?`, [r.document_id, r.entity_id])) ?? null);\n }\n const doc = docs.get(dk);\n if (!doc) continue;\n const start = Number(pas.start_offset);\n const end = Number(pas.end_offset);\n out.push({\n ...r, seq: Number(pas.seq), start_offset: start, end_offset: end,\n source_ref: doc.source_ref, source_hash: doc.source_hash, text: doc.text.slice(start, end),\n });\n }\n return out;\n}\n\n/**\n * Keyword index stored in SQLite FTS5, kept consistent with `entries` by a\n * trigger-fed ledger (`fts_pending`) that `drain()` applies in bounded, all-SQL\n * chunks. Row text never enters JS, so memory is flat at any database size.\n * Spec 2026-10-05 §PR-2 revision.\n */\nexport class Fts5IndexStrategy implements IndexStrategy {\n constructor(\n private readonly db: SQLiteAdapter,\n private readonly prefix: string,\n private readonly metadataRepo: MetadataRepository,\n private readonly budgetMs: number = DEFAULT_SETUP_BUDGET_MS,\n ) {}\n\n /**\n * Resolves the index state (spec #280 Change 3 transition table). Every\n * read-only probe runs before the one transition transaction, so a probe\n * failure leaves zero mutation (Change 4 ordering).\n */\n async init(opts: { entriesExisted?: boolean } = {}): Promise<void> {\n await this.initEntries(opts);\n // A passage-side failure must not take down fact keyword search (entries FTS is already live).\n try {\n await this.ensurePassageObjects();\n } catch (err) {\n this.passagesDisabled = true;\n console.warn('[WikiMemory] passage index init failed; passage search returns [] until a later open:', err);\n }\n }\n\n /** Set when passage-index init failed; passage drain and search become no-ops. */\n private passagesDisabled = false;\n\n /**\n * Source-store passage index objects (spec source-store §6): created here,\n * the way the entries_fts objects are, never by setupDatabase. Skipped when\n * the store tables are absent (a pre-v17 database).\n */\n private async ensurePassageObjects(): Promise<void> {\n const p = this.prefix;\n if (!(await this.metadataRepo.tableExists(`${p}source_passages`))) return;\n await this.db.withTransactionAsync(async (tx) => {\n await tx.execAsync(passageFtsTablesDdl(p) + passageFtsTriggersDdl(p));\n // Probes and the bootstrap insert run in the SAME transaction as the DDL\n // (CodeRabbit follow-up): a store write committing after the DDL but\n // before the probes would enqueue its document through the new trigger,\n // and the non-empty ledger would then suppress the bootstrap forever —\n // pre-index passages with no row would never enter passage search.\n const mapped = await tx.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_map LIMIT 1`);\n const queued = await tx.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_pending LIMIT 1`);\n if (mapped === null && queued === null) {\n // The virtual table can hold stale content even with an empty map: a\n // detach on a module-less host drops the map/ledger but cannot drop\n // this table (detachFts5 swallows the failure). The re-seeded map's\n // rowids then collide with the surviving rows — every drain fails, or\n // duplicated hits surface. The entries side resets the same way in\n // resetAndRearm. This clear is UNCONDITIONAL on the bootstrap path\n // (every open where map and ledger are both empty runs it) and is\n // harmless when the table is not stale: in that state it is empty\n // too. The bootstrap is the only writer that runs on an empty map.\n await tx.runAsync(`DELETE FROM ${p}source_passages_fts`);\n // After a module-less erase (specs/erase-fts-remediation Path A) the\n // table keeps its fts5 structure record but its segments are gone, so\n // reads hit \"corruption found reading blob\". 'rebuild' discards all\n // index data without reading segments and re-tokenizes from the (empty)\n // content table, leaving a valid empty index; on a healthy empty table\n // it is a no-op.\n await tx.runAsync(`INSERT INTO ${p}source_passages_fts(${p}source_passages_fts) VALUES('rebuild')`);\n await tx.runAsync(\n `INSERT INTO ${p}source_passages_fts_pending (entity_id, doc_id)\n SELECT entity_id, id FROM ${p}source_documents`);\n }\n });\n }\n\n /**\n * Drain the passage ledger one document at a time (spec §6, the stated\n * departure from all-SQL): the document's text is read into JS and sliced at\n * the offsets the cutter stored, so transient memory is bounded by\n * `maxCharsPerSource` for the ONE document, never the store. Each document\n * is one transaction. `entityId` limits the drain to that entity's ledger rows.\n */\n async drainPassages(opts: { entityId?: string; deadline?: number } = {}): Promise<void> {\n if (this.passagesDisabled) return;\n const p = this.prefix;\n if (!(await this.metadataRepo.tableExists(`${p}source_passages_fts_pending`))) return;\n for (;;) {\n if (opts.deadline !== undefined && monotonicNow() >= opts.deadline) return;\n let ran = false;\n await this.db.withTransactionAsync(async (tx) => {\n const first = opts.entityId === undefined\n ? await tx.getFirstAsync<{ doc_id: string; entity_id: string }>(\n `SELECT doc_id, entity_id FROM ${p}source_passages_fts_pending ORDER BY seq LIMIT 1`)\n : await tx.getFirstAsync<{ doc_id: string; entity_id: string }>(\n `SELECT doc_id, entity_id FROM ${p}source_passages_fts_pending WHERE entity_id = ? ORDER BY seq LIMIT 1`,\n [opts.entityId]);\n if (!first) return;\n const docId = first.doc_id;\n const ent = first.entity_id;\n const hi = await tx.getFirstAsync<{ hi: number }>(\n `SELECT max(seq) AS hi FROM ${p}source_passages_fts_pending WHERE doc_id = ? AND entity_id = ?`, [docId, ent]);\n await tx.runAsync(\n `DELETE FROM ${p}source_passages_fts WHERE rowid IN (SELECT fts_rowid FROM ${p}source_passages_fts_map WHERE doc_id = ?)`,\n [docId]);\n await tx.runAsync(`DELETE FROM ${p}source_passages_fts_map WHERE doc_id = ?`, [docId]);\n const doc = await tx.getFirstAsync<{ text: string }>(`SELECT text FROM ${p}source_documents WHERE id = ? AND entity_id = ?`, [docId, ent]);\n if (doc) {\n const rows = await tx.getAllAsync<{ id: string; entity_id: string; start_offset: number; end_offset: number }>(\n `SELECT id, entity_id, start_offset, end_offset FROM ${p}source_passages WHERE document_id = ? AND entity_id = ? ORDER BY seq`, [docId, ent]);\n for (const r of rows) {\n const { lastInsertRowId } = await tx.runAsync(\n `INSERT INTO ${p}source_passages_fts_map (passage_id, doc_id) VALUES (?, ?)`, [r.id, docId]);\n await tx.runAsync(\n `INSERT INTO ${p}source_passages_fts (rowid, passage_id, entity_id, doc_id, text) VALUES (?, ?, ?, ?, ?)`,\n [lastInsertRowId, r.id, r.entity_id, docId, doc.text.slice(Number(r.start_offset), Number(r.end_offset))]);\n }\n }\n await tx.runAsync(\n `DELETE FROM ${p}source_passages_fts_pending WHERE doc_id = ? AND seq <= ?`, [docId, hi?.hi ?? 0]);\n ran = true;\n });\n if (!ran) return;\n }\n }\n\n /**\n * Best-match-first passage search. A hit counts only while its\n * `source_passages` row exists, so a stalled drain never surfaces a deleted\n * passage (spec §5).\n */\n async searchPassages(query: string, options: { entityIds: string[]; limit: number }): Promise<PassageHit[]> {\n if (this.passagesDisabled || options.entityIds.length === 0) return [];\n const match = buildFtsMatchQuery(query);\n if (match === null) return [];\n const p = this.prefix;\n const t = `${p}source_passages_fts`;\n const limit = options.limit >= Number.MAX_SAFE_INTEGER ? -1 : options.limit;\n const raw = await this.db.getAllAsync<PassageSearchResult>(\n `SELECT passage_id AS id, entity_id, doc_id AS document_id, max(0.0, -raw) AS score FROM (\n SELECT passage_id, entity_id, doc_id, bm25(${t}, 0.0, 0.0, 0.0, 1.0) AS raw\n FROM ${t}\n WHERE ${t} MATCH ? AND entity_id IN (SELECT value FROM json_each(?))\n AND passage_id IN (SELECT id FROM ${p}source_passages WHERE entity_id IN (SELECT value FROM json_each(?)))\n ORDER BY raw, passage_id\n LIMIT ?)\n ORDER BY raw, id`,\n [match, JSON.stringify(options.entityIds), JSON.stringify(options.entityIds), limit],\n );\n return hydratePassageHits(this.db, p, raw);\n }\n\n private async initEntries(opts: { entriesExisted?: boolean }): Promise<void> {\n try {\n await this.initOnce(opts);\n } catch (err) {\n const wrapped = unwrapFtsOnly(err);\n const cls = ftsCorruptionClass(wrapped.cause);\n // Corruption confined to FTS tables: entries is untouched, so a reset re-arm is safe (spec #280 Change 4).\n if (cls === 'vtab' || (cls === 'corrupt' && wrapped.ftsOnly)) {\n await this.resetAndRearm();\n return;\n }\n throw wrapped.cause; // generic errors keep the retry -> UnavailableIndexStrategy path; pinned 'fts5' sees them raw\n }\n }\n\n /** Marks errors from statements that touch only FTS tables (entries_fts + shadows). */\n private async ftsOnly<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (err) {\n throw new FtsOnlyStatementError(err);\n }\n }\n\n private async initOnce(opts: { entriesExisted?: boolean }): Promise<void> {\n const p = this.prefix;\n const state = await this.metadataRepo.getMeta(FTS5_STATE_KEY);\n const schema = await this.readSchema();\n const ftsExists = schema.tables.has(`${p}entries_fts`);\n const mapExists = schema.tables.has(`${p}fts_map`);\n const pendingExists = schema.tables.has(`${p}fts_pending`);\n const trig = schema.triggersPresent;\n const ftsDdl = schema.tables.get(`${p}entries_fts`) ?? null;\n const tokenizerOk = ftsDdl === null || /tokenize\\s*=\\s*['\"]porter\\s+unicode61['\"]/i.test(ftsDdl);\n\n if (state === null && opts.entriesExisted === false) {\n // Fresh store: nothing to index yet.\n await this.db.withTransactionAsync(async (tx) => {\n await tx.execAsync(fts5TablesDdl(p) + fts5PendingIndexesDdl(p) + fts5TriggersDdl(p));\n await this.metadataRepo.setMeta(FTS5_STATE_KEY, 'live', tx);\n });\n return;\n }\n if (state === 'detached') return this.resetAndRearm(); // re-attach: the map is untrustworthy\n\n if (!tokenizerOk) return this.resetAndRearm();\n\n const intact = trig && ftsExists && mapExists && pendingExists;\n if (intact && state === 'rebuilding') return; // resume; each quantum re-verifies the fingerprint\n if (intact && state === 'live') {\n await this.ftsOnly(() => this.db.getFirstAsync(`SELECT rowid FROM ${p}entries_fts ORDER BY rowid DESC LIMIT 1`));\n if (await this.liveRowUnindexed()) return this.resetAndRearm();\n return; // fast path\n }\n // Marker lost, a trigger lost, or a table missing.\n if (ftsExists && mapExists && (await this.keepMapConsistent())) {\n await this.db.withTransactionAsync((tx) => this.rearmInTx(tx));\n return;\n }\n return this.resetAndRearm();\n }\n\n /**\n * The index was lost (rev 8 m3 / rev 9 m4): the oldest or the newest live entry is neither mapped nor\n * ledgered, which `live` never allows. The oldest one keeps detection armed after post-loss writes\n * repopulate the map and the ledger (#284 review). Every-open path: each side reads at most\n * FTS5_DRAIN_CHUNK entries rows (final review M1), so an all-soft-deleted store is never fully scanned;\n * a lost index whose oldest and newest rows are all deleted goes undetected.\n */\n private async liveRowUnindexed(): Promise<boolean> {\n const p = this.prefix;\n const edge = (dir: 'ASC' | 'DESC') => `SELECT id FROM (SELECT id FROM (SELECT id, deleted_at FROM ${p}entries`\n + ` ORDER BY rowid ${dir} LIMIT ${FTS5_DRAIN_CHUNK}) WHERE deleted_at IS NULL LIMIT 1)`;\n return (await this.db.getFirstAsync(\n `SELECT 1 AS x FROM (${edge('ASC')} UNION ALL ${edge('DESC')}) e\n WHERE NOT EXISTS (SELECT 1 FROM ${p}fts_map m WHERE m.id = e.id)\n AND NOT EXISTS (SELECT 1 FROM ${p}fts_pending q WHERE q.id = e.id)\n LIMIT 1`)) !== null;\n }\n\n /**\n * Read-only keep-map check (spec DDL note): every surviving entries_fts\n * rowid must have a map row. Max-rowid seek, then docsize vs map counts.\n */\n private async keepMapConsistent(): Promise<boolean> {\n const p = this.prefix;\n const fts = await this.ftsOnly(() => this.db.getFirstAsync<{ rowid: number }>(`SELECT rowid FROM ${p}entries_fts ORDER BY rowid DESC LIMIT 1`));\n const map = await this.db.getFirstAsync<{ hi: number; n: number }>(\n `SELECT coalesce(max(fts_rowid), 0) AS hi, count(*) AS n FROM ${p}fts_map`);\n if ((fts?.rowid ?? 0) > (map?.hi ?? 0)) return false;\n const doc = await this.ftsOnly(() => this.db.getFirstAsync<{ n: number }>(`SELECT count(*) AS n FROM ${p}entries_fts_docsize`));\n return (doc?.n ?? 0) === (map?.n ?? 0);\n }\n\n /** Keep-map re-arm: triggers, empty ledger, rebuild from 0, state rebuilding. One transaction. */\n private async rearmInTx(tx: SQLiteAdapter): Promise<void> {\n const p = this.prefix;\n await tx.execAsync(fts5TablesDdl(p));\n await tx.execAsync(`DELETE FROM ${p}fts_pending;`);\n await tx.execAsync(fts5PendingIndexesDdl(p) + fts5TriggersDdl(p));\n await writeRebuildStart(tx, p, this.metadataRepo);\n await this.metadataRepo.setMeta(FTS5_STATE_KEY, 'rebuilding', tx);\n }\n\n /** Reset path: retire entries_fts, recreate it empty, clear map + ledger, then the re-arm. One transaction. */\n private async resetAndRearm(): Promise<void> {\n const p = this.prefix;\n await this.db.withTransactionAsync(async (tx) => {\n await this.retireFtsTable(tx);\n await tx.execAsync(fts5TablesDdl(p));\n await tx.execAsync(`DELETE FROM ${p}fts_map; DELETE FROM ${p}fts_pending;`);\n await this.rearmInTx(tx);\n });\n }\n\n /** Rename-retire entries_fts (spec #280 rev 11); DROP only when the RENAME throws. */\n private async retireFtsTable(tx: SQLiteAdapter): Promise<void> {\n const p = this.prefix;\n if (!(await this.metadataRepo.tableExists(`${p}entries_fts`, tx))) return;\n const n = Number((await this.metadataRepo.getMeta(FTS5_RETIRED_COUNTER_KEY, tx)) ?? '0') + 1;\n const name = retiredTableName(p, n);\n try {\n await tx.execAsync(`ALTER TABLE ${p}entries_fts RENAME TO ${name}`);\n } catch (err) {\n // Not damage: SQLite may have rolled the transaction back already, so further statements would\n // autocommit one by one. Fail the reset whole instead (#284 review).\n if (isTransientOrTxFatal(err)) throw err;\n // Shadow tables too damaged to rename: today's DROP, with its measured floor, for this case only.\n await tx.execAsync(`DROP TABLE ${p}entries_fts`);\n return;\n }\n await this.metadataRepo.setMeta(FTS5_RETIRED_TABLES_KEY, JSON.stringify([...(await this.retiredList(tx)), name]), tx);\n await this.metadataRepo.setMeta(FTS5_RETIRED_COUNTER_KEY, String(n), tx);\n }\n\n private async retiredList(tx: SQLiteAdapter = this.db): Promise<string[]> {\n const raw = parseJsonArray<unknown>(await this.metadataRepo.getMeta(FTS5_RETIRED_TABLES_KEY, tx), []);\n return raw.filter((n): n is string => isRetiredTableName(this.prefix, n));\n }\n\n async drain(opts: DrainOptions = {}): Promise<void> {\n try {\n await this.drainOnce(opts);\n } catch (err) {\n // SQLITE_CORRUPT_VTAB names the FTS5 table itself, so the reset init() applies is safe here too:\n // without it every drain fails until the next open (#284 review). Other corruption may be in\n // entries, which this cannot repair: it propagates as before.\n if (ftsCorruptionClass(err) !== 'vtab') throw err;\n await this.resetAndRearm();\n // The reset cleared the ledger, so the caller's ids are re-indexed from entries: resolving\n // still means they are searchable (DrainOptions.ids), and the caller may drop them.\n if (opts.ids && opts.ids.length > 0) await this.drainIds(opts.ids, idReindexChunkSql(this.prefix));\n }\n }\n\n private async drainOnce(opts: DrainOptions): Promise<void> {\n const ids = opts.ids ?? [];\n // The caller's own ids are not deadline-bound (DrainOptions.ids): they drain to completion, and the caller drops them from its stash only once this succeeds.\n if (ids.length > 0) await this.drainIds(ids);\n if (opts.mode === 'ledger') {\n // Write turn: at most ONE foreign chunk after the caller's own ids.\n if (ids.length === 0 && opts.entityId !== undefined) await this.drainEntityChunk(opts.entityId);\n else await this.drainLedgerChunk();\n return;\n }\n await this.fullQuantum(opts.deadline ?? monotonicNow() + this.budgetMs);\n }\n\n /**\n * One full quantum (spec #280 Change 3): ledger first (at most half the\n * budget while `rebuilding`); then, while `rebuilding`, ≥1 window unless\n * the ledger drain overran the deadline, one sweep tx, and the flip check;\n * then reclamation. A `live` store reads only the state.\n */\n private async fullQuantum(deadline: number): Promise<void> {\n const rebuilding = (await this.metadataRepo.getMeta(FTS5_STATE_KEY)) === 'rebuilding';\n // While rebuilding, the ledger stops at half the remaining budget, so a steady write backlog cannot\n // starve the windows (#284 review). Overrun is still judged against the full deadline.\n const start = monotonicNow();\n const ledgerRan = await this.drainLedgerUntil(rebuilding ? start + (deadline - start) / 2 : deadline);\n const ledgerOverran = ledgerRan && monotonicNow() >= deadline;\n if (rebuilding) {\n const progress = await readRebuildProgress(this.metadataRepo);\n if (!progress || !(await this.fingerprintValid(progress.wm))) {\n // Windows resume next quantum; reclamation below still runs (#284 review).\n await this.restartRebuild();\n } else {\n if (!ledgerOverran) {\n let step: WindowStep;\n do {\n step = await this.runWindow(progress);\n } while (step === 'more' && monotonicNow() < deadline);\n // 'stale': progress moved under this quantum (a VACUUM restart, a re-anchor, a flip); the next quantum re-reads it.\n if (step !== 'stale') await this.runSweepTx(progress);\n }\n await this.tryFlip();\n }\n }\n try {\n await this.reclaimRetired(deadline);\n } catch (err) {\n // Best-effort for database errors only: a locked retired table stays listed and is retried next quantum,\n // never failing drain() or the flip. A non-SQLite error is a bug and propagates (final review I2).\n if (!isSqliteError(err)) throw err;\n }\n }\n\n /** Listed retired table names (erase step 4 / module-less fallback). */\n async retiredTables(): Promise<string[]> {\n return this.retiredList();\n }\n\n /**\n * Erase step 4: reclaim every retired table to completion (DROP + delist), no\n * deadline. Failures surface (unlike the best-effort quantum path); the\n * SQLITE_CORRUPT_VTAB hollowed-shell exit inside reclaimRetired is designed.\n */\n async reclaimRetiredToCompletion(): Promise<void> {\n await this.reclaimRetired(Number.POSITIVE_INFINITY);\n }\n\n /**\n * Erase step 3: surfaced passage drain, no deadline. Fails only when passage\n * init was disabled AND the ledger still has rows; otherwise warns and continues.\n */\n async drainPassagesStrict(): Promise<void> {\n if (this.passagesDisabled) {\n const p = this.prefix;\n const pending = (await this.metadataRepo.tableExists(`${p}source_passages_fts_pending`))\n && (await this.db.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_pending LIMIT 1`)) !== null;\n if (pending) throw new Error('passage index disabled with pending ledger rows');\n console.warn('[WikiMemory] erase: passage index disabled; nothing pending, continuing');\n return;\n }\n await this.drainPassages({});\n }\n\n /**\n * Erase step 3 (entries side): drain the trigger-fed `fts_pending` ledger store-wide to\n * empty, no deadline, errors surfaced; throws if rows remain afterwards.\n */\n async drainEntriesLedgerStrict(): Promise<void> {\n while (await this.drainLedgerChunk());\n const left = await this.db.getFirstAsync(`SELECT 1 AS x FROM ${this.prefix}fts_pending LIMIT 1`);\n if (left !== null && left !== undefined) throw new Error('entries FTS ledger still has pending rows after drain');\n }\n\n /** Erase step 7: FTS 'optimize' on each FTS table that exists. */\n async optimizeFts(): Promise<void> {\n const p = this.prefix;\n for (const t of [`${p}entries_fts`, `${p}source_passages_fts`]) {\n if (!(await this.metadataRepo.tableExists(t))) continue;\n await this.db.runAsync(`INSERT INTO ${t}(${t}) VALUES('optimize')`);\n }\n }\n\n /** `erase({ rebuild: true })` surface: retire + recreate the entries index and re-arm the rebuild. */\n async rebuildForErase(): Promise<void> {\n await this.resetAndRearm();\n }\n\n /** Bounded reclamation steps, each its own tx, until the deadline or nothing is retired. */\n private async reclaimRetired(deadline: number): Promise<void> {\n while (monotonicNow() < deadline) {\n const [name] = await this.retiredList();\n if (name === undefined) return;\n try {\n // The list and the table are read once per table, not per step (#284 review).\n if (!(await this.metadataRepo.tableExists(name))) {\n await this.delistRetired(name, false);\n continue;\n }\n while (!(await this.reclaimStep(name)) && monotonicNow() < deadline);\n } catch (err) {\n if (ftsCorruptionClass(err) === null) throw err;\n // Persistently corrupt (the corruption reset is what retired it): DROP once and delist; if even\n // the DROP fails, delist anyway so no quantum re-reads its corrupt pages (final review I2).\n try {\n await this.delistRetired(name, true);\n } catch (dropErr) {\n if (!isSqliteError(dropErr)) throw dropErr;\n await this.delistRetired(name, false);\n }\n }\n }\n }\n\n /** (1) delete <=500 rows, else (2) one bounded merge, else (3) DROP + delist. True once delisted. */\n private async reclaimStep(name: string): Promise<boolean> {\n if (await this.db.getFirstAsync(`SELECT rowid FROM ${name} LIMIT 1`)) {\n await this.db.withTransactionAsync(async (tx) => {\n await tx.runAsync(`DELETE FROM ${name} WHERE rowid IN (SELECT rowid FROM ${name} ORDER BY rowid LIMIT ${FTS5_DRAIN_CHUNK})`);\n });\n return false;\n }\n let merged = false;\n await this.db.withTransactionAsync(async (tx) => {\n const before = await tx.getFirstAsync<{ n: number }>(`SELECT total_changes() AS n`);\n await tx.runAsync(`INSERT INTO ${name}(${name}, rank) VALUES('merge', ${FTS5_RECLAIM_MERGE_PAGES})`);\n const after = await tx.getFirstAsync<{ n: number }>(`SELECT total_changes() AS n`);\n merged = (after?.n ?? 0) - (before?.n ?? 0) >= 2; // FTS5 docs: < 2 means the merge did no work\n });\n if (!merged) await this.delistRetired(name, true);\n return !merged;\n }\n\n private async delistRetired(name: string, drop: boolean): Promise<void> {\n await this.db.withTransactionAsync(async (tx) => {\n if (drop) await tx.execAsync(`DROP TABLE IF EXISTS ${name}`);\n const rest = (await this.retiredList(tx)).filter((n) => n !== name);\n await this.metadataRepo.setMeta(FTS5_RETIRED_TABLES_KEY, JSON.stringify(rest), tx);\n });\n }\n\n /** The id at the watermark's rowid still matches. A null id (start, or windows complete) has nothing to check. */\n private async fingerprintValid(wm: RebuildWatermark, tx: SQLiteAdapter = this.db): Promise<boolean> {\n if (wm.id === null) return true;\n const row = await tx.getFirstAsync<{ id: string }>(`SELECT id FROM ${this.prefix}entries WHERE rowid = ?`, [wm.rowid]);\n return row?.id === wm.id;\n }\n\n /** External change under the watermark: start over (same re-arm transaction as a trigger-loss restart). */\n private async restartRebuild(): Promise<void> {\n await this.db.withTransactionAsync((tx) => this.rearmInTx(tx));\n }\n\n /**\n * Progress as stored, re-read inside a window/sweep tx: false when it no\n * longer matches what this quantum assumed (final review I1). Writing a\n * watermark or cursor computed from a stale `pr` would overwrite a\n * concurrent restart (runPrune VACUUM is not on the sync chain).\n */\n private async progressUnchanged(pr: RebuildProgress, tx: SQLiteAdapter): Promise<boolean> {\n if ((await this.metadataRepo.getMeta(FTS5_STATE_KEY, tx)) !== 'rebuilding') return false;\n const cur = await readRebuildProgress(this.metadataRepo, tx);\n return cur !== null && cur.wm.rowid === pr.wm.rowid && cur.wm.id === pr.wm.id && cur.cursor === pr.cursor\n && cur.snapshot.entries === pr.snapshot.entries && cur.snapshot.map === pr.snapshot.map;\n }\n\n /** One window tx. 'done' once no rows remain in (wm, snapshot] (the watermark is then pinned at the snapshot, F9); 'stale' when progress moved under the quantum. */\n private async runWindow(pr: RebuildProgress): Promise<WindowStep> {\n if (pr.wm.rowid >= pr.snapshot.entries) return 'done';\n const p = this.prefix;\n let next: RebuildWatermark = pr.wm;\n let more = false;\n let stale = false;\n await this.db.withTransactionAsync(async (tx) => {\n if (!(await this.progressUnchanged(pr, tx))) { stale = true; return; }\n const row = await tx.getFirstAsync<{ hi: number | null }>(windowHiSql(p), [pr.wm.rowid, pr.snapshot.entries]);\n if (row?.hi == null) {\n next = { rowid: pr.snapshot.entries, id: null };\n } else {\n for (const sql of windowChunkSql(p)) await tx.runAsync(sql, [pr.wm.rowid, row.hi]);\n const fp = await tx.getFirstAsync<{ id: string }>(`SELECT id FROM ${p}entries WHERE rowid = ?`, [row.hi]);\n next = { rowid: row.hi, id: fp!.id };\n more = true;\n }\n await this.metadataRepo.setMeta(FTS5_REBUILD_WM_KEY, JSON.stringify(next), tx);\n });\n if (stale) return 'stale';\n pr.wm = next; // only after the tx resolved\n return more ? 'more' : 'done';\n }\n\n /** At most one bounded sweep tx; the cursor advances in the same tx. */\n private async runSweepTx(pr: RebuildProgress): Promise<void> {\n if (pr.cursor >= pr.snapshot.map) return;\n const p = this.prefix;\n let next = pr.cursor;\n await this.db.withTransactionAsync(async (tx) => {\n if (!(await this.progressUnchanged(pr, tx))) return; // keep pr.cursor; the next quantum re-reads\n const row = await tx.getFirstAsync<{ hi: number | null }>(sweepHiSql(p), [pr.cursor, pr.snapshot.map]);\n const hi = row?.hi ?? pr.snapshot.map;\n for (const sql of sweepChunkSql(p)) await tx.runAsync(sql, [pr.cursor, hi]);\n await this.metadataRepo.setMeta(FTS5_SWEEP_CURSOR_KEY, String(hi), tx);\n next = hi;\n });\n pr.cursor = next;\n }\n\n /** Completion, re-checked inside the flipping tx; the residual ledger (≤ one chunk) drains in it. */\n private async tryFlip(): Promise<void> {\n const p = this.prefix;\n await this.db.withTransactionAsync(async (tx) => {\n if ((await this.metadataRepo.getMeta(FTS5_STATE_KEY, tx)) !== 'rebuilding') return;\n const pr = await readRebuildProgress(this.metadataRepo, tx);\n if (!pr || pr.wm.rowid < pr.snapshot.entries || pr.cursor < pr.snapshot.map) return;\n if (!(await this.fingerprintValid(pr.wm, tx))) return;\n const residual = await tx.getFirstAsync<{ n: number }>(\n `SELECT count(*) AS n FROM (SELECT 1 FROM ${p}fts_pending LIMIT ${FTS5_DRAIN_CHUNK + 1})`);\n if ((residual?.n ?? 0) > FTS5_DRAIN_CHUNK) return;\n const hi = await tx.getFirstAsync<{ hi: number | null }>(drainHiSql(p));\n if (hi?.hi != null) for (const sql of drainChunkSql(p)) await tx.runAsync(sql, [hi.hi]);\n await this.metadataRepo.deleteMeta(FTS5_REBUILD_WM_KEY, tx);\n await this.metadataRepo.deleteMeta(FTS5_REBUILD_SNAPSHOT_KEY, tx);\n await this.metadataRepo.deleteMeta(FTS5_SWEEP_CURSOR_KEY, tx);\n await this.metadataRepo.setMeta(FTS5_STATE_KEY, 'live', tx);\n });\n }\n\n /** Seq-ordered ledger chunks until empty or `stopAt`. True when a chunk ran. */\n private async drainLedgerUntil(stopAt: number): Promise<boolean> {\n let ran = false;\n while (await this.drainLedgerChunk()) {\n ran = true;\n if (monotonicNow() >= stopAt) break;\n }\n return ran;\n }\n\n /** The caller's own ids, to completion, ≤ FTS5_DRAIN_CHUNK per transaction. */\n private async drainIds(ids: readonly string[], chunk: readonly string[] = idDrainChunkSql(this.prefix)): Promise<void> {\n const unique = [...new Set(ids)];\n for (let i = 0; i < unique.length; i += FTS5_DRAIN_CHUNK) {\n const json = JSON.stringify(unique.slice(i, i + FTS5_DRAIN_CHUNK));\n await this.db.withTransactionAsync(async (tx) => {\n for (const sql of chunk) await tx.runAsync(sql, [json]);\n });\n }\n }\n\n /** One seq-ordered chunk. False when the ledger was empty. */\n private async drainLedgerChunk(): Promise<boolean> {\n const hiSql = drainHiSql(this.prefix);\n const chunk = drainChunkSql(this.prefix);\n // A local, not the callback's return value: host adapters may resolve withTransactionAsync to void.\n let ran = false;\n await this.db.withTransactionAsync(async (tx) => {\n const row = await tx.getFirstAsync<{ hi: number | null }>(hiSql);\n if (row?.hi == null) return;\n for (const sql of chunk) await tx.runAsync(sql, [row.hi]);\n ran = true;\n });\n return ran;\n }\n\n /** One entity-targeted chunk (ORDER BY seq, ≤ FTS5_DRAIN_CHUNK). */\n private async drainEntityChunk(entityId: string): Promise<void> {\n const hiSql = entityDrainHiSql(this.prefix);\n const chunk = entityDrainChunkSql(this.prefix);\n await this.db.withTransactionAsync(async (tx) => {\n const row = await tx.getFirstAsync<{ hi: number | null }>(hiSql, [entityId]);\n if (row?.hi == null) return;\n for (const sql of chunk) await tx.runAsync(sql, [entityId, row.hi]);\n });\n }\n\n async replace(entityId: string, ids: readonly string[], documents: readonly IndexDocument[]): Promise<void> {\n assertEntity(entityId, documents);\n const docIds = documents.map((d) => d.id);\n await this.db.withTransactionAsync(async (tx) => {\n // Caller-supplied ids are scoped to the entity; incoming document ids are\n // un-scoped so a doc that previously lived under another entity gets\n // detached (otherwise the fts_map UNIQUE(id) insert would throw).\n await this.deleteByIds(tx, entityId, ids);\n await this.deleteByIds(tx, null, docIds);\n await this.insertDocs(tx, documents);\n });\n }\n\n async replaceEntity(entityId: string, documents: readonly IndexDocument[]): Promise<void> {\n assertEntity(entityId, documents);\n const p = this.prefix;\n await this.db.withTransactionAsync(async (tx) => {\n await tx.runAsync(\n `DELETE FROM ${p}entries_fts WHERE rowid IN (SELECT fts_rowid FROM ${p}fts_map WHERE entity_id = ?)`, [entityId]);\n await tx.runAsync(`DELETE FROM ${p}fts_map WHERE entity_id = ?`, [entityId]);\n await this.insertDocs(tx, documents);\n });\n }\n\n async replaceAll(documents: readonly IndexDocument[]): Promise<void> {\n const p = this.prefix;\n await this.db.withTransactionAsync(async (tx) => {\n await tx.execAsync(`DELETE FROM ${p}entries_fts; DELETE FROM ${p}fts_map; DELETE FROM ${p}fts_pending;`);\n await this.insertDocs(tx, documents);\n });\n }\n\n async search(query: string, options: IndexSearchOptions): Promise<IndexSearchResult[]> {\n if (options.entityIds.length === 0) return [];\n const match = buildFtsMatchQuery(query);\n if (match === null) return [];\n const cap = options.preFilterLimit ?? options.limit;\n const limit = cap >= Number.MAX_SAFE_INTEGER ? -1 : cap;\n const t = `${this.prefix}entries_fts`;\n // bm25 is evaluated once per matching row in the inner query; the outer\n // SELECT only clamps and negates it. The outer ORDER BY is kept because SQL\n // does not guarantee a subquery's order survives into the outer query; it\n // sorts at most `limit` rows.\n return this.db.getAllAsync<IndexSearchResult>(\n `SELECT id, entity_id, max(0.0, -raw) AS score FROM (\n SELECT id, entity_id, bm25(${t}, 0.0, 0.0, 2.0, 1.0, 1.0) AS raw\n FROM ${t}\n WHERE ${t} MATCH ? AND entity_id IN (SELECT value FROM json_each(?))\n ORDER BY raw, id\n LIMIT ?)\n ORDER BY raw, id`,\n [match, JSON.stringify(options.entityIds), limit],\n );\n }\n\n private async deleteByIds(tx: SQLiteAdapter, entityId: string | null, ids: readonly string[]): Promise<void> {\n if (ids.length === 0) return;\n const p = this.prefix;\n const json = JSON.stringify(ids);\n const whereEntity = entityId === null ? '' : ' AND entity_id = ?';\n // `json_each(?)` is the first placeholder; the optional `entity_id = ?` follows it.\n const args: unknown[] = [json];\n if (entityId !== null) args.push(entityId);\n await tx.runAsync(\n `DELETE FROM ${p}entries_fts WHERE rowid IN (\n SELECT fts_rowid FROM ${p}fts_map WHERE id IN (SELECT value FROM json_each(?))${whereEntity})`,\n args);\n await tx.runAsync(\n `DELETE FROM ${p}fts_map WHERE id IN (SELECT value FROM json_each(?))${whereEntity}`, args);\n }\n\n /** One INSERT pair per document: a throw part-way rolls back the whole transaction. */\n private async insertDocs(tx: SQLiteAdapter, documents: readonly IndexDocument[]): Promise<void> {\n const p = this.prefix;\n for (const d of documents) {\n const { lastInsertRowId } = await tx.runAsync(\n `INSERT INTO ${p}fts_map (id, entity_id) VALUES (?, ?)`, [d.id, d.entity_id]);\n await tx.runAsync(\n `INSERT INTO ${p}entries_fts (rowid, id, entity_id, title, body, tags) VALUES (?, ?, ?, ?, ?, ?)`,\n [lastInsertRowId, d.id, d.entity_id, d.title, d.body, d.tags]);\n }\n }\n\n /** The init probes' schema facts in one sqlite_master read (#284 review): FTS tables with their DDL, and the triggers. */\n private async readSchema(): Promise<{ tables: Map<string, string | null>; triggersPresent: boolean }> {\n const p = this.prefix;\n const triggers = fts5TriggerNames(p);\n const names = [`${p}entries_fts`, `${p}fts_map`, `${p}fts_pending`, ...triggers];\n const rows = await this.db.getAllAsync<{ type: string; name: string; sql: string | null }>(\n `SELECT type, name, sql FROM sqlite_master WHERE name IN (${names.map(() => '?').join(', ')})`, names);\n const tables = new Map(rows.filter((r) => r.type === 'table').map((r) => [r.name, r.sql] as const));\n const present = new Set(rows.filter((r) => r.type === 'trigger').map((r) => r.name));\n return { tables, triggersPresent: triggers.every((n) => present.has(n)) };\n }\n}\n\ntype WindowStep = 'more' | 'done' | 'stale';\n\nclass FtsOnlyStatementError extends Error {\n readonly ftsOnlyCause: unknown;\n constructor(cause: unknown) {\n super('FTS-only statement failed');\n this.ftsOnlyCause = cause;\n }\n}\n\n/** Proxy-safe unwrap (issue #96): never `instanceof` a caught value bare. */\nfunction unwrapFtsOnly(err: unknown): { cause: unknown; ftsOnly: boolean } {\n try {\n if (err instanceof FtsOnlyStatementError) return { cause: err.ftsOnlyCause, ftsOnly: true };\n } catch { /* hostile Proxy */ }\n return { cause: err, ftsOnly: false };\n}\n\n/**\n * Proxy-safe extractSqliteCode (issue #96): any trap => undefined. Also reads\n * WikiTransactionError's `sqliteErrorCode`: the serialized adapter wraps every\n * failed transaction in one, so the driver code is not on `code` (#284 review).\n */\nfunction safeSqliteCode(err: unknown): string | undefined {\n try {\n const code = extractSqliteCode(err);\n if (code !== undefined) return code;\n const lifted = (err as { sqliteErrorCode?: unknown } | null | undefined)?.sqliteErrorCode;\n return typeof lifted === 'string' ? lifted : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Busy/locked, or a code after which SQLite may roll the transaction back (sqlite.org/lang_transaction.html). Extended codes match by primary name. */\nconst TRANSIENT_OR_TX_FATAL = ['SQLITE_BUSY', 'SQLITE_LOCKED', 'SQLITE_FULL', 'SQLITE_IOERR', 'SQLITE_NOMEM', 'SQLITE_INTERRUPT', 'SQLITE_ABORT', 'SQLITE_READONLY'];\n\nfunction isTransientOrTxFatal(err: unknown): boolean {\n const code = safeSqliteCode(err);\n return code !== undefined && TRANSIENT_OR_TX_FATAL.some((c) => code === c || code.startsWith(`${c}_`));\n}\n\n/**\n * 'vtab' for SQLITE_CORRUPT_VTAB (extended code 267, any statement), 'corrupt'\n * for another SQLITE_CORRUPT* code, else null. Proxy-safe: any trap => null.\n */\nexport function ftsCorruptionClass(err: unknown): 'vtab' | 'corrupt' | null {\n const code = safeSqliteCode(err);\n if (code === 'SQLITE_CORRUPT_VTAB') return 'vtab';\n if (code?.startsWith('SQLITE_CORRUPT')) return 'corrupt';\n return null;\n}\n\n/** A SQLite error (better-sqlite3 / expo-sqlite shapes): `code` 'SQLITE_*' or an 'Error code N:' message. Proxy-safe: any trap => false. */\nexport function isSqliteError(err: unknown): boolean {\n return safeSqliteCode(err) !== undefined;\n}\n\nfunction assertEntity(entityId: string, documents: readonly IndexDocument[]): void {\n for (const d of documents) {\n if (d.entity_id !== entityId) {\n throw new TypeError(`IndexDocument ${d.id} has entity_id ${d.entity_id}, expected ${entityId}`);\n }\n }\n}\n","// packages/core/src/services/search/MiniSearchIndexStrategy.ts\n\nimport MiniSearch from 'minisearch';\nimport type { SQLiteAdapter } from '../../types';\nimport type {\n IndexDocument,\n IndexSearchOptions,\n IndexSearchResult,\n IndexStrategy,\n PassageHit,\n} from './IndexStrategy';\nimport { hydratePassageHits } from './Fts5IndexStrategy';\n\ninterface PassageDoc { id: string; entity_id: string; document_id: string; text: string }\n\nexport type { PassageSearchResult } from './Fts5IndexStrategy';\n\n/**\n * Passage slices of one entity, cut from `source_documents.text` at the stored\n * UTF-16 offsets. Reads one document at a time.\n */\nasync function loadStoredPassages(db: SQLiteAdapter, prefix: string, entityId: string): Promise<PassageDoc[]> {\n const out: PassageDoc[] = [];\n const docs = await db.getAllAsync<{ id: string }>(`SELECT id FROM ${prefix}source_documents WHERE entity_id = ?`, [entityId]);\n for (const d of docs) {\n const doc = await db.getFirstAsync<{ text: string }>(`SELECT text FROM ${prefix}source_documents WHERE id = ?`, [d.id]);\n if (!doc) continue;\n const rows = await db.getAllAsync<{ id: string; start_offset: number; end_offset: number }>(\n `SELECT id, start_offset, end_offset FROM ${prefix}source_passages WHERE document_id = ? ORDER BY seq`, [d.id]);\n for (const r of rows) {\n out.push({ id: r.id, entity_id: entityId, document_id: d.id, text: doc.text.slice(Number(r.start_offset), Number(r.end_offset)) });\n }\n }\n return out;\n}\n\n/**\n * In-RAM keyword index. Extracted from `SearchService` without behavior\n * change. The strategy owns the MiniSearch instance, the `entryIdsByEntity`\n * tracking map, the `entityIdById` reverse map, and the explicit-vacuum\n * policy (#64).\n *\n * Memory cost: O(total text). The fix for #257 lives in PR-2's FTS5\n * strategy; this one stays for Expo/OPFS environments without FTS5 and for\n * hosts that explicitly pin `WikiConfig.indexStrategy: 'minisearch'`.\n */\nexport class MiniSearchIndexStrategy implements IndexStrategy {\n private index: MiniSearch<IndexDocument>;\n /**\n * Per-entity id set. `replaceEntity()` and `hasIndexedEntity()` read it;\n * `addDocuments()` and `discardIds()` keep it in sync. `SearchService` does\n * not see this map; it only sees `hasIndexedEntity`. The previous\n * `miniSearchEntryIdsByEntity` lived on `SearchService`.\n */\n private entryIdsByEntity = new Map<string, Set<string>>();\n /**\n * Reverse of `entryIdsByEntity`. `replace(entityId, ids, …)` uses it to\n * decide which ids are owned by `entityId` (the only safe membership test\n * — a rebuild that failed between its discard pass and the set replacement\n * can leave the forward set claiming ids the MiniSearch instance does not\n * hold). The pre-extraction `syncEntries` deleted from one set per id, not\n * from every entity's set.\n */\n private entityIdById = new Map<string, string>();\n\n constructor() {\n this.index = this.createIndex();\n }\n\n /**\n * Build a fresh MiniSearch instance with the project's index options.\n * Called from the constructor and from `replaceAll`. We do not use\n * `removeAll()` on an existing instance because that empties the index but\n * leaves `dirtCount` and the vacuum bookkeeping intact, which would trip\n * `syncEntries`' conditional vacuum early after a clear.\n */\n private createIndex(): MiniSearch<IndexDocument> {\n return new MiniSearch({\n fields: ['title', 'body', 'tags'],\n storeFields: ['entity_id'],\n // Vacuuming is driven explicitly at the end of each serialized rebuild\n // (see SearchService.syncEntries). Auto-vacuum fires on its own\n // schedule, asynchronously with respect to the caller, and traversing\n // the tree mid-rebuild is what threw the uncaught TypeError in\n // MiniSearch.performVacuuming (#64).\n autoVacuum: false,\n searchOptions: {\n boost: { title: 2 },\n fuzzy: 0.2,\n prefix: true,\n },\n });\n }\n\n /**\n * Incremental sync. Removes only ids currently tracked under `entityId`\n * (other entities' docs are untouched), then upserts `documents` by id.\n * The same id appearing in both `ids` and `documents` is discarded first\n * so the upsert does not throw on a duplicate id.\n *\n * Every document must carry `entityId` as its `entity_id`; a mismatch is\n * rejected before the write mutates anything. A tracking-only call\n * (`replace(entityId, [], [])`) registers the entity as indexed, matching\n * the interface contract.\n *\n * Atomicity: never awaits between the discard pass and `addDocuments`, so\n * a concurrent `search()` sees the index wholly before or wholly after,\n * never half-updated. This is the precondition the pre-extraction\n * `syncEntries` kept with its \"no await from here to `addAll`\" comment.\n */\n async replace(\n entityId: string,\n ids: readonly string[],\n documents: readonly IndexDocument[],\n ): Promise<void> {\n assertOwnedBy(entityId, documents);\n this.discardIds(ids, entityId);\n if (!this.entryIdsByEntity.has(entityId)) this.entryIdsByEntity.set(entityId, new Set());\n this.addDocuments(documents);\n }\n\n /**\n * Per-entity rebuild. Removes every id tracked under `entityId` (with the\n * `index.has(id)` guard so a stale tracking set cannot make `discard()`\n * throw), then writes `documents`. The entity stays registered as\n * indexed — even when `documents` is empty — so the next `syncEntries`\n * call can take the fast path. Every document must belong to `entityId`.\n */\n async replaceEntity(entityId: string, documents: readonly IndexDocument[]): Promise<void> {\n assertOwnedBy(entityId, documents);\n const previous = this.entryIdsByEntity.get(entityId);\n if (previous) this.discardIds([...previous]);\n // Registered even when empty, so hasIndexedEntity(entityId) === true.\n this.entryIdsByEntity.set(entityId, new Set());\n this.addDocuments(documents);\n }\n\n /**\n * Global rebuild / clear. Replaces the MiniSearch instance and clears both\n * id maps, so `hasIndexedEntity` returns `false` for every entity afterwards.\n * `SearchService.clearAll()` calls `replaceAll([])`.\n */\n async replaceAll(documents: readonly IndexDocument[]): Promise<void> {\n this.index = this.createIndex();\n this.entryIdsByEntity.clear();\n this.entityIdById.clear();\n this.addDocuments(documents);\n }\n\n /**\n * Best-match-first search over the documents whose `entity_id` is in\n * `options.entityIds`. `preFilterLimit` overrides `limit` (hybrid retrieval\n * uses this to over-fetch candidates before the `limit` cap). Scores are\n * raw BM25+ — `SearchService.getKeywordScores` and `searchKeyword` apply\n * any scaling, not the strategy.\n */\n async search(query: string, options: IndexSearchOptions): Promise<IndexSearchResult[]> {\n if (options.entityIds.length === 0) return [];\n const entityIdSet = new Set(options.entityIds);\n const limit = options.preFilterLimit ?? options.limit;\n const raw = this.index.search(query, {\n filter: (r) => entityIdSet.has(r.entity_id as string),\n combineWith: 'OR',\n });\n // Tiebreak equal-score results by id before slicing: MiniSearch breaks\n // ties by internal insertion order, which the strategy's own\n // discard/add changes. Callers truncate to a `limit`, so the ids\n // surviving a tie at the boundary must not depend on write history.\n raw.sort((a, b) => {\n const scoreDiff = b.score - a.score;\n if (!Number.isNaN(scoreDiff) && scoreDiff !== 0) return scoreDiff;\n return a.id.localeCompare(b.id);\n });\n // `storeFields: ['entity_id']` puts entity_id on every result.\n return raw.slice(0, limit).map((r) => ({\n id: r.id,\n entity_id: r.entity_id as string,\n score: r.score,\n }));\n }\n\n // ---- Source-store passage index (spec source-store §6) --------------------\n // A second in-heap instance over the same passage slices as the FTS5 path.\n\n private passageIndex: MiniSearch<PassageDoc> = this.createPassageIndex();\n private passageIdsByEntity = new Map<string, Set<string>>();\n /** Handle `reindexSourcePassages` last indexed from; `searchPassages` hydrates hits through it. */\n private passageSource: { db: SQLiteAdapter; prefix: string } | null = null;\n\n private createPassageIndex(): MiniSearch<PassageDoc> {\n return new MiniSearch({\n fields: ['text'],\n storeFields: ['entity_id', 'document_id'],\n autoVacuum: false, // explicit vacuum below, same reason as the facts instance (#64)\n searchOptions: { fuzzy: 0.2, prefix: true },\n });\n }\n\n /**\n * Re-index stored passages from SQLite: one entity, or every stored entity\n * when `entityId` is omitted (the open-time pass; up to `maxTotalChars` per\n * entity, and the heap grows with the number of stored entities, spec §6).\n * It is also the post-commit sync after forget/clearAll: deleted passages\n * drop out because the reload no longer finds their rows (spec §5).\n * Reads happen first; the discard and add are synchronous, so the swap is\n * atomic (a concurrent search sees the index wholly before or wholly after),\n * and the vacuum runs after the swap.\n */\n async reindexSourcePassages(db: SQLiteAdapter, prefix: string, entityId?: string): Promise<void> {\n this.passageSource = { db, prefix };\n const entityIds = entityId !== undefined\n ? [entityId]\n : [...new Set([\n ...(await db.getAllAsync<{ entity_id: string }>(`SELECT DISTINCT entity_id FROM ${prefix}source_documents`)).map((r) => r.entity_id),\n ...this.passageIdsByEntity.keys(),\n ])];\n for (const id of entityIds) {\n const passages = await loadStoredPassages(db, prefix, id);\n for (const old of this.passageIdsByEntity.get(id) ?? []) {\n if (this.passageIndex.has(old)) this.passageIndex.discard(old);\n }\n const ids = new Set<string>();\n for (const d of passages) { this.passageIndex.add({ ...d }); ids.add(d.id); }\n if (ids.size > 0) this.passageIdsByEntity.set(id, ids);\n else this.passageIdsByEntity.delete(id);\n if (this.passageIndex.dirtCount > 0) await this.passageIndex.vacuum();\n }\n }\n\n /** Best-match-first passage search over the entities in `options.entityIds`. */\n async searchPassages(query: string, options: { entityIds: string[]; limit: number }): Promise<PassageHit[]> {\n if (options.entityIds.length === 0 || !this.passageSource) return [];\n const allowed = new Set(options.entityIds);\n const raw = this.passageIndex.search(query, { filter: (r) => allowed.has(r.entity_id as string), combineWith: 'OR' });\n raw.sort((a, b) => (b.score - a.score) || a.id.localeCompare(b.id));\n // The index may hold rows deleted after it loaded; a hit counts only\n // while its source_passages row exists (spec §5). Drop dead rows BEFORE\n // slicing, so a deleted passage never consumes a limit slot a live one\n // can fill (the FTS5 path's SQL join does the same). One indexed lookup\n // per entity.\n const live = new Set<string>();\n for (const eid of options.entityIds) {\n const rows = await this.passageSource.db.getAllAsync<{ id: string }>(\n `SELECT id FROM ${this.passageSource.prefix}source_passages WHERE entity_id = ?`, [eid]);\n for (const row of rows) live.add(row.id);\n }\n const hits = raw.filter((r) => live.has(r.id as string)).slice(0, options.limit).map((r) => ({\n id: r.id as string, entity_id: r.entity_id as string, document_id: r.document_id as string, score: r.score,\n }));\n return hydratePassageHits(this.passageSource.db, this.passageSource.prefix, hits);\n }\n\n /**\n * Explicit vacuum. MiniSearch 7.2.0's `dirtCount` rule: search after an\n * un-vacuumed discard inverts the relative scores of term-sharing\n * documents at any index size. `SearchService.syncEntries` calls this\n * after a discard-bearing turn. No-op when `dirtCount === 0`.\n */\n async vacuum(): Promise<void> {\n if (this.index.dirtCount > 0) {\n await this.index.vacuum();\n }\n }\n\n /**\n * `true` when `entityId` has been indexed at least once under the current\n * strategy state. Backed by `entryIdsByEntity.has(entityId)`, which is\n * kept in sync by `addDocuments`, `replaceEntity`, and `replaceAll`.\n */\n hasIndexedEntity(entityId: string): boolean {\n return this.entryIdsByEntity.has(entityId);\n }\n\n /**\n * Add `documents` to the MiniSearch instance and register them in\n * `entryIdsByEntity` and `entityIdById`. MiniSearch mutates documents\n * during `add`, so each doc is copied first. `add` throws on an id the\n * index already holds — `replace` and `replaceEntity` discard first for\n * that reason.\n *\n * Adds and registers one document at a time: if a duplicate id throws\n * part-way through, every document already in the index is tracked, so\n * the next rebuild can discard it instead of failing on it again. This is\n * the precondition the per-turn recovery path relies on (#258 review).\n */\n private addDocuments(documents: readonly IndexDocument[]): void {\n for (const d of documents) {\n const doc: IndexDocument = { ...d };\n this.index.add(doc);\n const set = this.entryIdsByEntity.get(doc.entity_id) ?? new Set<string>();\n set.add(doc.id);\n this.entryIdsByEntity.set(doc.entity_id, set);\n this.entityIdById.set(doc.id, doc.entity_id);\n }\n }\n\n /**\n * Discard `ids` from the MiniSearch instance and from both id maps, but\n * only for ids currently owned by `entityId` (the second argument). When\n * `entityId` is omitted (used by `replaceEntity` for the bulk rebuild\n * path), every id is discarded regardless of owning entity.\n *\n * `index.has(id)` is the membership test of record: a rebuild that failed\n * between its own discard pass and the set replacement can leave the\n * tracking set claiming ids the index no longer holds — `discard()` throws\n * on those, so we guard.\n */\n private discardIds(ids: readonly string[], entityId?: string): void {\n for (const id of ids) {\n // Scope check first: an id not owned by `entityId` is silently ignored.\n // Doing the scope check before `index.discard` is what stops a\n // `replace(entityId, ids, …)` call from touching docs under any other\n // entity.\n const owning = this.entityIdById.get(id);\n if (owning === undefined) continue;\n if (entityId !== undefined && owning !== entityId) continue;\n if (this.index.has(id)) this.index.discard(id);\n this.entryIdsByEntity.get(owning)?.delete(id);\n this.entityIdById.delete(id);\n }\n }\n}\n\n/**\n * `replace` and `replaceEntity` write under one entity. A document carrying a\n * different `entity_id` would land in another entity's tracking set (and\n * have no safe discard path), so the write rejects before mutating anything.\n */\nfunction assertOwnedBy(entityId: string, documents: readonly IndexDocument[]): void {\n for (const doc of documents) {\n if (doc.entity_id !== entityId) {\n throw new Error(\n `IndexStrategy write for entity ${entityId} got document ${doc.id} under entity ${doc.entity_id}`,\n );\n }\n }\n}","// packages/core/src/services/search/createIndexStrategy.ts\nimport type { SQLiteAdapter } from '../../types';\nimport type { MetadataRepository } from '../../repositories/MetadataRepository';\nimport type { IndexStrategy } from './IndexStrategy';\nimport { Fts5IndexStrategy } from './Fts5IndexStrategy';\nimport { MiniSearchIndexStrategy } from './MiniSearchIndexStrategy';\nimport { UnavailableIndexStrategy } from './UnavailableIndexStrategy';\nimport { FTS5_STATE_KEY, fts5LedgerDropSql, passageFtsTriggerNames } from './fts5Sql';\n\nexport type IndexStrategyPreference = 'fts5' | 'minisearch' | 'auto';\n\nexport const FTS5_INIT_RETRY_MS = 250;\n\n/** True only for errors meaning the module is genuinely absent (permanent). Proxy-safe. */\nfunction isModuleAbsentError(err: unknown): boolean {\n // Walk a short cause chain: some adapters wrap the SQLite message.\n let cur: unknown = err;\n for (let depth = 0; depth < 3 && cur != null; depth++) {\n let msg = '';\n try { msg = String((cur as { message?: unknown }).message ?? cur); } catch { return false; }\n if (/no such module: fts5/i.test(msg) || /no such function: json_valid/i.test(msg)) return true;\n try { cur = (cur as { cause?: unknown }).cause; } catch { return false; }\n }\n return false;\n}\n\n/**\n * Whether this SQLite build has FTS5 and json1 (the drain needs both). The\n * probe table lives in `temp`, so the database file is never touched.\n * Returns false ONLY when the module is genuinely absent; any other error\n * (SQLITE_IOERR, NOMEM, INTERRUPT, ...) is rethrown so the caller treats it\n * as a transient init failure instead of detaching a healthy store\n * (spec #280 Change 4).\n */\nexport async function probeFts5(db: SQLiteAdapter, prefix: string): Promise<boolean> {\n const name = `temp.${prefix}fts5_probe`;\n try {\n await db.execAsync(`CREATE VIRTUAL TABLE IF NOT EXISTS ${name} USING fts5(x)`);\n const row = await db.getFirstAsync<{ ok: number }>(`SELECT json_valid('[]') AS ok`);\n return row?.ok === 1;\n } catch (err) {\n if (isModuleAbsentError(err)) return false;\n throw err;\n } finally {\n try { await db.execAsync(`DROP TABLE IF EXISTS ${name}`); } catch { /* module absent */ }\n }\n}\n\n/**\n * Stop maintaining the FTS5 ledger: drop the passage-side objects first\n * (triggers, map and ledger in one transaction; the virtual-table drop is\n * module-gated and its failure swallowed — the bootstrap in\n * ensurePassageObjects clears any stale virtual-table content when it\n * re-seeds on re-attach), then the entries-side triggers and ledger, and\n * entries_fts itself. Mark the database detached, so a later FTS5 open\n * rebuilds: the virtual tables are dropped best-effort; without the fts5\n * module they cannot be, and the next FTS5 init recreates them anyway.\n */\nexport async function detachFts5(db: SQLiteAdapter, prefix: string, metadataRepo: MetadataRepository): Promise<void> {\n // Passage-side objects go first, and independently of the entries-side gate\n // (CodeRabbit/T3 follow-up): a store that ran FTS5 keeps the passage triggers\n // live after detach, so every store write enqueues a ledger row nothing ever\n // drains — unbounded growth. On re-attach the bootstrap re-seeds the emptied\n // map/ledger and clears any stale virtual-table content its failed drop left\n // behind (its probes + insert + clear run inside the DDL transaction).\n const passageLedger = await metadataRepo.tableExists(`${prefix}source_passages_fts_pending`);\n if (passageLedger) {\n const [ai, ad] = passageFtsTriggerNames(prefix);\n await db.withTransactionAsync(async (tx) => {\n await tx.execAsync(\n `DROP TRIGGER IF EXISTS ${ai};\\nDROP TRIGGER IF EXISTS ${ad};\\n` +\n `DROP TABLE IF EXISTS ${prefix}source_passages_fts_map;\\nDROP TABLE IF EXISTS ${prefix}source_passages_fts_pending;`);\n });\n // The virtual table needs the fts5 module, like entries_fts below.\n try { await db.execAsync(`DROP TABLE IF EXISTS ${prefix}source_passages_fts`); } catch { /* no fts5 module */ }\n }\n const hasLedger = await metadataRepo.tableExists(`${prefix}fts_pending`);\n const state = await metadataRepo.getMeta(FTS5_STATE_KEY);\n if (!hasLedger && state !== 'live') return;\n await db.withTransactionAsync(async (tx) => {\n await tx.execAsync(fts5LedgerDropSql(prefix));\n await metadataRepo.setMeta(FTS5_STATE_KEY, 'detached', tx);\n });\n try { await db.execAsync(`DROP TABLE IF EXISTS ${prefix}entries_fts`); } catch { /* no fts5 module */ }\n}\n\n/** Resolve the keyword-index strategy for this database. Failure ordering per spec #280 Change 4. */\nexport async function createIndexStrategy(\n db: SQLiteAdapter,\n prefix: string,\n metadataRepo: MetadataRepository,\n preferred: IndexStrategyPreference,\n opts: { setupBudgetMs?: number; entriesExisted?: boolean } = {},\n): Promise<IndexStrategy> {\n if (preferred === 'minisearch') {\n await detachFts5(db, prefix, metadataRepo); // operator's explicit choice\n return new MiniSearchIndexStrategy();\n }\n const attempt = async (): Promise<IndexStrategy | 'absent'> => {\n if (!(await probeFts5(db, prefix))) return 'absent';\n const strategy = new Fts5IndexStrategy(db, prefix, metadataRepo, opts.setupBudgetMs);\n await strategy.init({ entriesExisted: opts.entriesExisted });\n return strategy;\n };\n const absent = async (): Promise<IndexStrategy> => {\n if (preferred === 'fts5') {\n throw new Error(`indexStrategy 'fts5' was requested, but this SQLite build lacks FTS5 or json1.`);\n }\n await detachFts5(db, prefix, metadataRepo); // module genuinely absent: permanent\n return new MiniSearchIndexStrategy();\n };\n\n for (let tries = 1; ; tries++) {\n try {\n const s = await attempt();\n return s === 'absent' ? await absent() : s;\n } catch (err) {\n if (preferred === 'fts5') throw err; // pinned: surface the raw failure\n if (tries === 2) {\n // Never detachFts5 here: a transient failure must not drop the ledger and\n // route a large store into MiniSearch's full sync (measured OOM).\n console.warn('[WikiMemory] FTS5 init failed after retry; keyword search unavailable until a later open or syncSearchIndex():', err);\n return new UnavailableIndexStrategy(err);\n }\n }\n await new Promise((resolve) => setTimeout(resolve, FTS5_INIT_RETRY_MS));\n }\n}\n","import type { OntologyConfig } from '../../types';\n\n/**\n * The one place the ontology-backfill scheduler default is defined\n * (specs/system-one-config §8). Read sites resolve through this so a host\n * that sets nothing gets the same answer everywhere — the same discipline as\n * `engineDefaults.ts` for the 8.0.0 librarian/maintenance defaults.\n */\n\n/** Default batch size for scheduler-driven ontology backfill passes. */\nexport const DEFAULT_ONTOLOGY_JOB_BATCH_SIZE = 50;\n\nexport interface OntologyJobDefaults {\n batchSize: number;\n}\n\n/**\n * Resolve the scheduler's ontology-backfill batch size from\n * `WikiConfig.ontology.schedulerBatchSize`. Invalid values (non-finite, < 1)\n * fall back to the default rather than throwing — a bad config value degrades\n * to the default instead of breaking construction or every run.\n */\nexport function resolveOntologyJobDefaults(ontology: OntologyConfig | undefined): OntologyJobDefaults {\n const raw = ontology?.schedulerBatchSize;\n const batchSize = typeof raw === 'number' && Number.isInteger(raw) && raw >= 1 ? raw : DEFAULT_ONTOLOGY_JOB_BATCH_SIZE;\n return { batchSize };\n}\n","import type {\n SQLiteAdapter,\n WikiOptions,\n PendingMaintenance,\n MaintenanceJob,\n LockedMaintenanceJob,\n MaintenanceStopReason,\n EntityMaintenanceReport,\n RunPendingMaintenanceOptions,\n RunPendingMaintenanceResult,\n HealResult,\n OntologyBackfillResult,\n} from '../types';\nimport { WikiBusyError, isWikiSearchUnavailableError } from '../types';\nimport { MaintenanceService, MAX_EMBED_ATTEMPTS } from './MaintenanceService';\nimport type { LibrarianResult } from './librarian';\nimport { UsageMeter } from '../utils/usage';\nimport { resolveOntologyJobDefaults } from '../utils/config/ontologyJobDefaults';\nimport { MetadataRepository } from '../repositories/MetadataRepository';\nimport { EventRepository } from '../repositories/EventRepository';\nimport { EntryRepository } from '../repositories/EntryRepository';\nimport { JobManager } from './JobManager';\nimport type { VectorRemovalService } from './VectorRemovalService';\nimport type { VectorRemovalRepository } from '../repositories/VectorRemovalRepository';\n\n/**\n * Read-side report for the deferred maintenance mode: which entities have\n * pending work (librarian events behind the watermark, heal backlog, unembedded\n * facts) without running anything. `run` executes the work (PR-C task 4).\n */\nexport class MaintenanceScheduler {\n constructor(\n private db: SQLiteAdapter,\n private options: WikiOptions,\n private maintenanceService: MaintenanceService,\n private metadataRepo: MetadataRepository,\n private eventRepo: EventRepository,\n private entryRepo: EntryRepository,\n private jobManager: JobManager,\n private vectorRemovalService: VectorRemovalService,\n private vectorRemovalRepo: VectorRemovalRepository,\n ) {}\n\n /** Batch size for scheduler-driven ontology passes; resolved once (spec §8). */\n private readonly schedulerBatchSize: number =\n resolveOntologyJobDefaults(this.options.config?.ontology).batchSize;\n\n /**\n * Entities with **any** pending work only, sorted by `pendingEvents` desc\n * then `entityId` asc. Token estimate is ceil(pending summary chars / 4),\n * matching the auto-trigger's estimator (PR-B).\n */\n async getPending(entityIds?: string[]): Promise<PendingMaintenance[]> {\n const ids = entityIds ?? await this.metadataRepo.getDistinctEntityIds();\n const autoHealThreshold = this.options.config?.autoHealThreshold || 100;\n const canEmbed = typeof this.options.llmProvider.embed === 'function';\n const out: PendingMaintenance[] = [];\n const owed = new Map<string, number>();\n if (this.vectorRemovalService.gate() !== 'none' && (await this.vectorRemovalService.ledgerPresent())) {\n const scope = entityIds === undefined ? undefined : new Set(entityIds);\n // Only entities with a row outside backoff: a failing hook must not keep the list non-empty.\n for (const e of await this.vectorRemovalRepo.entitiesWithDuePending(Date.now())) {\n if (scope !== undefined && !scope.has(e)) continue;\n owed.set(e, (await this.vectorRemovalRepo.pendingStats(e)).count);\n }\n }\n const listed = new Set(ids);\n const scan = [...ids, ...[...owed.keys()].filter((e) => !listed.has(e))];\n for (const entityId of scan) {\n const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);\n const pendingEvents = await this.eventRepo.countAfter(entityId, wm);\n const chars = pendingEvents > 0 ? await this.eventRepo.sumSummaryCharsAfter(entityId, wm) : 0;\n const eventCount = await this.eventRepo.count(entityId);\n const cp = await this.metadataRepo.getCheckpoint(entityId, this.db);\n // Same clamp as WriteService.maybeRunHeal: an out-of-range checkpoint\n // (reachable after runPrune deletes events a heal pass already counted)\n // resets to ZERO, not to the event count — both views must agree that\n // the entity is fully unhealed.\n let healCheckpoint = cp.heal ?? 0;\n if (healCheckpoint > eventCount) healCheckpoint = 0;\n const healDue = eventCount - healCheckpoint >= autoHealThreshold;\n const reembedPending = canEmbed && (await this.entryRepo.countReembedPending(entityId, MAX_EMBED_ATTEMPTS)) > 0;\n const owedCount = owed.get(entityId) ?? 0;\n const ontologyBackfillPending = await this.maintenanceService.pendingOntologyBackfill(entityId);\n if (pendingEvents > 0 || healDue || reembedPending || owedCount > 0 || ontologyBackfillPending > 0) {\n out.push({\n entityId, pendingEvents, pendingTokensEstimate: Math.ceil(chars / 4), healDue, reembedPending,\n ...(owedCount > 0 ? { pendingExternalDeletions: owedCount } : {}),\n ...(ontologyBackfillPending > 0 ? { pendingOntologyBackfill: ontologyBackfillPending } : {}),\n });\n }\n }\n return out.sort((x, y) => (y.pendingEvents - x.pendingEvents) || (x.entityId < y.entityId ? -1 : x.entityId > y.entityId ? 1 : 0));\n }\n\n /**\n * Execute pending maintenance (spec §6.2): fair-share rounds of at most one\n * unit per entity (librarian batch, else heal batch, else reembed), entities\n * ordered by `getPending` (pendingEvents desc, id asc). Holds the same\n * per-entity `JobManager` locks a manual run would; a busy entity is skipped\n * and reported, never thrown. Nothing is still running when this resolves.\n *\n * Stop precedence (spec §10 items 3-6): `deadline` > `budget_exhausted` >\n * `budget_too_small` > `complete`. `budget_too_small` means a job's smallest\n * unit needs more than the WHOLE budget — that job is skipped this run and\n * the run continues; `budget_exhausted` means a unit needs more than what\n * REMAINS — the run stops. The token budget meters generation and classify\n * calls; embeddings are never metered.\n */\n async run(opts: RunPendingMaintenanceOptions = {}): Promise<RunPendingMaintenanceResult> {\n if (\n opts.deadlineMs !== undefined &&\n (typeof opts.deadlineMs !== 'number' || !Number.isFinite(opts.deadlineMs) || opts.deadlineMs < 0)\n ) {\n throw new TypeError('deadlineMs must be a finite number >= 0');\n }\n const meter = new UsageMeter(opts.tokenBudget);\n const budget = opts.tokenBudget;\n const deadline = opts.deadlineMs !== undefined ? Date.now() + Math.max(0, opts.deadlineMs) : Infinity;\n const jobs = new Set<MaintenanceJob>(opts.jobs ?? ['librarian', 'heal', 'reembed', 'externalDeletions', 'ontologyBackfill']);\n const externalDeletions = await this.runExternalDeletions(opts.entityIds, jobs.has('externalDeletions'), deadline);\n // Removal-only entities are reported by externalDeletions, not as per-entity maintenance.\n const pending = (await this.getPending(opts.entityIds)).filter((p) => p.pendingEvents > 0 || p.healDue || p.reembedPending || (p.pendingOntologyBackfill ?? 0) > 0);\n\n type State = { p: PendingMaintenance; report: EntityMaintenanceReport; librarian: boolean; heal: boolean; reembed: boolean; ontology: boolean };\n const states: State[] = pending.map((p) => ({\n p,\n report: { entityId: p.entityId, librarianPasses: 0, factsWritten: 0, healPasses: 0, reembedded: false, ontologyBackfillPasses: 0, typed: 0 },\n librarian: jobs.has('librarian') && p.pendingEvents > 0,\n heal: jobs.has('heal') && p.healDue,\n reembed: jobs.has('reembed') && p.reembedPending,\n ontology: jobs.has('ontologyBackfill') && (p.pendingOntologyBackfill ?? 0) > 0,\n }));\n\n let stopped: MaintenanceStopReason = { reason: 'complete' };\n let tooSmall: MaintenanceStopReason | null = null;\n const classify = (job: 'librarian' | 'heal' | 'ontologyBackfill', entityId: string, requiredEstimate: number): 'too_small' | 'exhausted' => {\n if (budget !== undefined && requiredEstimate > budget) {\n tooSmall ??= { reason: 'budget_too_small', job, entityId, requiredEstimate };\n return 'too_small';\n }\n return 'exhausted';\n };\n // A unit that ends with the meter exhausted made real awaited LLM calls,\n // so the deadline may have lapsed mid-unit too. Precedence is deadline\n // first (spec §10): the caller must be told to retry as-is, not to raise\n // the budget. Re-checked here because the between-units deadline check\n // only runs before a unit starts, never after one ends.\n const exhaustedStop = (): MaintenanceStopReason =>\n Date.now() >= deadline ? { reason: 'deadline' } : { reason: 'budget_exhausted' };\n const markBusy = (st: State, job: LockedMaintenanceJob) => { (st.report.busy ??= []).push(job); };\n const markSearchUnavailable = (st: State, job: LockedMaintenanceJob) => { (st.report.searchUnavailable ??= []).push(job); };\n\n // Open job flags across all entities. Flags only ever clear, so a round\n // that clears one (a skip: busy, outage, too small, nothing processed)\n // counts as progress — it must re-run so the entity reaches its later\n // jobs — and the loop still terminates.\n const openJobs = () => states.reduce((n, s) => n + +s.librarian + +s.heal + +s.reembed + +s.ontology, 0);\n\n rounds: for (;;) {\n let progressed = false;\n const openAtStart = openJobs();\n for (const st of states) {\n if (!st.librarian && !st.heal && !st.reembed && !st.ontology) continue;\n if (Date.now() >= deadline) { stopped = { reason: 'deadline' }; break rounds; }\n const entityId = st.p.entityId;\n\n if (st.librarian) {\n if (this.jobManager.isBlocked('librarian', entityId)) { st.librarian = false; markBusy(st, 'librarian'); continue; }\n this.jobManager.acquireLock('librarian', entityId);\n let r: LibrarianResult;\n try {\n r = await this.maintenanceService.runLibrarianPass({ entityId, trigger: 'call', meter });\n } catch (err) {\n // Keyword outage: this entity's pass aborted with its watermark kept.\n // Skip it for this run rather than failing every other entity's work.\n if (!isWikiSearchUnavailableError(err)) throw err;\n st.librarian = false;\n markSearchUnavailable(st, 'librarian');\n continue;\n } finally {\n this.jobManager.releaseLock('librarian', entityId);\n }\n if (r.budgetStop) {\n if (classify('librarian', entityId, r.budgetStop.requiredEstimate) === 'exhausted') { stopped = exhaustedStop(); break rounds; }\n st.librarian = false;\n continue;\n }\n if (!r.processedThrough) { st.librarian = false; continue; }\n st.report.librarianPasses++;\n st.report.factsWritten += r.factsWritten;\n if (r.typing) st.report.typedOnWrite = (st.report.typedOnWrite ?? 0) + r.typing.typed;\n progressed = true;\n // Budget exhausted during write-time typing: the pass wrote its facts and\n // recorded them above; the run stops as exhausted rather than 'complete'.\n if ((r.typing?.unattempted ?? 0) > 0) { stopped = exhaustedStop(); break rounds; }\n const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);\n if ((await this.eventRepo.countAfter(entityId, wm)) === 0) st.librarian = false;\n continue;\n }\n\n if (st.heal) {\n if (this.jobManager.isBlocked('heal', entityId)) { st.heal = false; markBusy(st, 'heal'); continue; }\n this.jobManager.acquireLock('heal', entityId);\n let h: HealResult;\n try {\n h = await this.maintenanceService.doRunHeal(entityId, { trigger: 'call', meter });\n // Write the checkpoint while the heal lock still blocks prune. A\n // prune between the count read and the write would leave heal\n // above the event count, which reads as 0 and starts a full\n // re-heal (spec ops-auto-first-batch §4).\n if (h.remaining === 0 && !(h.budgetStop && h.scanned === 0)) {\n await this.metadataRepo.updateCheckpoint(entityId, { heal: await this.eventRepo.count(entityId) }, this.db);\n }\n } finally {\n this.jobManager.releaseLock('heal', entityId);\n }\n // Defense against future doRunHeal changes: scanned === 0 means the\n // pass bailed before any LLM call, so budgetStop cannot arise there\n // today — but if it ever did, classify it instead of mislabeling a\n // never-started job as exhausted.\n if (h.budgetStop && h.scanned === 0) {\n if (classify('heal', entityId, h.budgetStop.requiredEstimate) === 'exhausted') { stopped = exhaustedStop(); break rounds; }\n st.heal = false;\n continue;\n }\n // Nothing scanned yet candidates remain (e.g. a keyword outage skipped\n // the LLM pass): another round cannot progress, so stop healing this\n // entity for this run instead of looping forever.\n if (h.scanned === 0 && h.remaining > 0) {\n st.heal = false;\n if (h.searchUnavailable) markSearchUnavailable(st, 'heal');\n continue;\n }\n st.report.healPasses++;\n progressed = true;\n if (h.remaining === 0) st.heal = false;\n if (h.budgetStop) { stopped = exhaustedStop(); break rounds; }\n continue;\n }\n\n if (st.reembed) {\n st.reembed = false;\n try {\n await this.maintenanceService.runReembed(entityId);\n st.report.reembedded = true;\n progressed = true;\n } catch (err) {\n if (err instanceof WikiBusyError) markBusy(st, 'reembed');\n else throw err;\n }\n }\n\n if (st.ontology) {\n // The between-units deadline check at the top of the entity\n // iteration ran BEFORE librarian/heal/reembed; an awaited unit can\n // lapse the deadline, and the ontology pass must not start against\n // an expired one. Spec §10 precedence: stop with 'deadline'; the\n // caller retries as-is (nothing was spent here).\n if (Date.now() >= deadline) {\n stopped = { reason: 'deadline' };\n break rounds;\n }\n st.ontology = false;\n if (this.jobManager.isBlocked('ontologyBackfill', entityId)) {\n // Same handling as a busy librarian/heal: a held pass is a real\n // scheduler outcome (the lock is owned by another job right now),\n // so report it and tell the host via `ontology_backfill_held`.\n markBusy(st, 'ontologyBackfill');\n this.maintenanceService.noteOntologyBackfillHeld(entityId);\n progressed = true;\n continue;\n }\n this.jobManager.acquireLock('ontologyBackfill', entityId);\n let r: OntologyBackfillResult;\n try {\n r = await this.maintenanceService.doRunOntologyBackfill(entityId, {\n meter,\n batchSize: this.schedulerBatchSize,\n });\n } finally {\n this.jobManager.releaseLock('ontologyBackfill', entityId);\n }\n st.report.ontologyBackfillPasses++;\n st.report.typed += r.typed;\n progressed = true;\n if (r.budgetStop) {\n if (classify('ontologyBackfill', entityId, r.budgetStop.requiredEstimate) === 'exhausted') {\n // Route through exhaustedStop() like the librarian/heal\n // branches: budget exhaustion is only reported when the budget\n // actually ran out — a deadline that lapsed inside the awaited\n // pass outranks it (spec §10 precedence).\n stopped = exhaustedStop();\n break rounds;\n }\n continue;\n }\n if (r.remaining === 0 || r.typed === 0) {\n // Converged, or this pass typed nothing it can ever type (every\n // candidate failed validation) — a further pass would burn rounds\n // without progress, so stop driving the job for this entity.\n continue;\n }\n // More eligible facts remain and this pass made typing progress; the\n // job stays closed for this run — leftover work waits for the next\n // run() (host convergence signal: getPendingMaintenance).\n }\n }\n if (!progressed && openJobs() === openAtStart) break;\n }\n\n if (stopped.reason === 'complete' && tooSmall) stopped = tooSmall;\n return {\n perEntity: states.map((s) => s.report),\n tokensUsed: meter.used,\n estimated: meter.estimated,\n remaining: budget === undefined ? null : meter.remaining,\n stoppedReason: stopped,\n externalDeletions,\n };\n }\n\n /**\n * Runs first and outside the token budget: delivers owed vector-index\n * removals per entity (wiped entities included), without backoff. Pending is\n * reported even when the job is not listed or no hook is configured.\n */\n private async runExternalDeletions(\n entityIds: string[] | undefined,\n enabled: boolean,\n deadline: number,\n ): Promise<{ confirmed: number; pending: number }> {\n if (!(await this.vectorRemovalService.ledgerPresent())) return { confirmed: 0, pending: 0 };\n const all = await this.vectorRemovalRepo.entitiesWithPending();\n const scope = entityIds === undefined ? undefined : new Set(entityIds);\n const entities = scope === undefined ? all : all.filter((e) => scope.has(e));\n let confirmed = 0;\n let pending = 0;\n // Entities a drain reported on; the drain already counted their pending rows.\n const counted = new Set<string>();\n if (enabled) {\n for (const e of entities) {\n if (Date.now() >= deadline) break;\n const r = await this.vectorRemovalService.drain(\n { entityId: e },\n { trigger: 'call', ...(deadline === Infinity ? {} : { deadlineAt: deadline }) },\n );\n confirmed += r.confirmed;\n if (!r.transient) {\n pending += r.pending;\n counted.add(e);\n }\n if (r.timedOut) break;\n }\n }\n for (const e of entities) {\n if (!counted.has(e)) pending += (await this.vectorRemovalRepo.pendingStats(e)).count;\n }\n return { confirmed, pending };\n }\n}\n","import type { OntologyMode, WriteOntologyPromptContext } 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.\nEach node is a fact. To link two things with an edge, each must exist as its own fact, titled by the same name you use in \\`target_title\\`.`;\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 a node_type, choose the closest type the fact is an example of; omit only when none applies even broadly.'\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\n// ---------------------------------------------------------------------------\n// Write-path appendix (specs/type-on-write §5). Its text equals the backfill\n// appendix above for the same inputs in this step, but it is produced from its\n// OWN constants so a later edit to either site cannot reach the other. The\n// byte-identity and split tests are the guard.\n// ---------------------------------------------------------------------------\n\nconst WRITE_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.\nEach node is a fact. To link two things with an edge, each must exist as its own fact, titled by the same name you use in \\`target_title\\`.`;\n\nconst WRITE_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 buildWriteOntologyAppendix(\n mode: OntologyMode,\n manifestJson: string,\n): WriteOntologyPromptContext {\n const strictRules = mode === 'strict'\n ? 'STRICT MODE: Use ONLY types defined in the manifest. If a fact does not fit a node_type, choose the closest type the fact is an example of; omit only when none applies even broadly.'\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 WRITE_FACT_ONTOLOGY_FIELDS,\n mode === 'emergent' ? WRITE_EMERGENT_EXTRA : '',\n 'Manifest:',\n manifestJson,\n ].filter(Boolean).join('\\n');\n\n return { site: 'write', ontologyManifest: manifestJson, ontologyModeInstructions };\n}\n","import type {\n OntologyConfig,\n OntologyManifest,\n OntologyMode,\n OntologyPromptContext,\n WriteOntologyPromptContext,\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, buildWriteOntologyAppendix } from '../prompts/ontology';\nimport {\n emptyManifest,\n normalizeTitleKey,\n resolveNodeType,\n resolveNodeTypeMatch,\n resolveEdgeDefinitions,\n typeSatisfies,\n validateInlineEdges,\n validateManifest,\n isReservedAbstainSlug,\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 /**\n * Ontology prompt context for the WRITE builders (specs/type-on-write §5).\n * `null` when the mode is `'off'` or when write-time typing is `engaged`\n * (the classifier types the fact, so the manifest leaves the write prompt).\n * Backfill keeps `buildPromptContext`.\n */\n async buildWritePromptContext(\n entityId: string,\n opts: { engaged: boolean },\n ): Promise<WriteOntologyPromptContext | null> {\n const { mode, manifest } = await this.getEffectiveState(entityId);\n if (mode === 'off' || opts.engaged) return null;\n return buildWriteOntologyAppendix(mode, JSON.stringify(manifest, null, 2));\n }\n\n async mergeEmergentUpdates(\n entityId: string,\n updates: OntologyUpdates,\n tx: SQLiteAdapter,\n ): Promise<{ manifest: OntologyManifest; rejected: string[] }> {\n // Reserved abstain slug (specs/system-one-config §5, decree C4): the\n // emergent merge drops it instead of persisting it, so a model proposing\n // 'none_of_these' as a node type can never smuggle the sentinel into the\n // manifest. Write-path reservation lives in WikiMemory.setOntologyManifests;\n // per-read validateManifest is deliberately untouched.\n const filtered: OntologyUpdates = updates.node_types\n ? { ...updates, node_types: updates.node_types.filter((nt) => !isReservedAbstainSlug(nt.type)) }\n : updates;\n const { manifest: merged, rejected } = await this.metadataRepo.mergeManifestUpdates(entityId, filtered, tx);\n this.invalidateCache(entityId);\n return { manifest: merged, rejected };\n }\n\n validateAndNormalizeFact(\n fact: ExtractedFactWithOntology,\n manifest: OntologyManifest,\n opts?: { strict?: boolean; entityId?: string; drops?: EdgeDrop[] },\n ): {\n okf_type: string | null;\n edges: ExtractedFactEdge[];\n /** Resolution evidence. Absent on a miss. Callers must not re-run resolution. */\n match?: { raw: string; canonical: string; via: 'exact' | 'normalize' };\n } {\n const rawType = typeof fact.okf_type === 'string' ? fact.okf_type : '';\n const strict = opts?.strict === true;\n const match = resolveNodeTypeMatch(rawType, manifest);\n if (!match) {\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 canonical = match.slug;\n const edges = validateInlineEdges(canonical, null, fact.edges ?? [], manifest, opts);\n return {\n okf_type: canonical,\n edges,\n match: { raw: rawType, canonical, via: match.via },\n };\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';\nimport { WikiInvalidReadOptions } from '../types';\nimport { isLiveAt } from '../utils/temporal';\nimport { packFactsByBudget, factTokenCost } from '../utils/budget';\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 rawAsOf = options.asOf;\n if (rawAsOf !== undefined && !(typeof rawAsOf === 'number' && Number.isFinite(rawAsOf) && rawAsOf >= 0)) {\n throw new WikiInvalidReadOptions('asOf', 'must be a finite epoch-ms number >= 0');\n }\n const rawTokenBudget = options.tokenBudget;\n if (rawTokenBudget !== undefined && !(typeof rawTokenBudget === 'number' && Number.isFinite(rawTokenBudget) && rawTokenBudget >= 0)) {\n throw new WikiInvalidReadOptions('tokenBudget', 'must be a finite number >= 0');\n }\n const live = rawAsOf === undefined\n ? { mode: 'current' as const, t: Date.now() }\n : { mode: 'asOf' as const, t: Math.trunc(rawAsOf) };\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 live,\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 // Spec §10.7: a non-live anchor returns alone — both endpoints of a\n // walkable edge must be live at the query instant.\n const [anchor] = await this.entryRepo.findByIds([options.sourceId], [entityId]);\n if (anchor && !isLiveAt(anchor, live.mode, live.t)) return { nodes: [anchor], 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 if (options.tokenBudget === undefined) return { nodes, edges: filteredEdges };\n const budget = Math.trunc(options.tokenBudget);\n const [anchorPacked] = packFactsByBudget([nodes[0]], budget).items;\n const kept = [anchorPacked];\n let used = factTokenCost(anchorPacked);\n for (const node of nodes.slice(1)) {\n const cost = factTokenCost(node);\n if (used + cost <= budget) { kept.push(node); used += cost; }\n }\n const keptIds = new Set(kept.map((n) => n.id));\n return { nodes: kept, edges: filteredEdges.filter((e) => keptIds.has(e.source_id) && keptIds.has(e.target_id)) };\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 /** Keyset page of TYPED facts in this entity (id + stored slug). Read-only. \"Typed\" here means the deletion-only scan the edge-violation query uses: soft-deleted and draft rows are out; validity windows are NOT consulted — the count mirrors `pageLiveEdgeViolations` exactly (spec §9, CodeRabbit #441). */\n async pageLiveTypedFacts(entityId: string, afterId: string, limit: number): Promise<Array<{ id: string; okf_type: string }>> {\n return this.db.getAllAsync(\n `SELECT id, okf_type FROM ${this.prefix}entries\n WHERE entity_id = ? AND id > ? AND deleted_at IS NULL\n AND lifecycle_status != 'draft' AND okf_type IS NOT NULL\n ORDER BY id ASC 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, resolveNodeType } 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 // Node-type violations (ontology-curation Task 11): a live fact whose\n // stored okf_type no longer resolves against the effective manifest.\n // Uses the same normalized resolver as the doors, so a stored slug that\n // folds into a manifest entry is not a violation. 0 when ontology is off\n // or the manifest declares no node_types.\n let nodeTypeViolations = 0;\n const nodeTypeViolationIds: string[] = [];\n const nodesConstrained = mode !== 'off' && (manifest.node_types?.length ?? 0) > 0;\n if (nodesConstrained) {\n let after = '';\n for (;;) {\n const page = await this.lintRepo.pageLiveTypedFacts(entityId, after, LINT_PAGE_SIZE);\n for (const f of page) {\n if (resolveNodeType(f.okf_type, manifest) === null) {\n nodeTypeViolations++;\n if (nodeTypeViolationIds.length < LINT_SAMPLE_SIZE) nodeTypeViolationIds.push(f.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 nodeTypeViolations,\n ...health,\n sample: { danglingEdgeIds, manifestViolationEdgeIds, nodeTypeViolationIds },\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 { RememberInput, WikiFact } from '../types';\nimport { assertEntityId } from './entityId';\nimport { generateId } from './ids';\nimport { assertEpochMs } from './temporal';\n\nconst CONFIDENCE_VALUES: ReadonlySet<string> = new Set(['certain', 'inferred', 'tentative']);\nconst SOURCE_TYPE_VALUES: ReadonlySet<string> = new Set(['user_stated', 'user_confirmed']);\n\nexport interface NormalizedRememberInput {\n /** The row to upsert. `okf_type` is null here; RememberService resolves `okfType` against the manifest. */\n fact: WikiFact;\n /** Truncated epoch ms, or undefined when the caller gave none. */\n validFrom?: number;\n /** The caller's raw type slug, or null. */\n okfType: string | null;\n}\n\n/**\n * Every validation rule of remember() (spec §3.2), with no I/O. Throws\n * TypeError; never clips or coerces. `now` is injected so tests are stable.\n */\nexport function normalizeRememberInput(entityId: string, input: RememberInput, now: number): NormalizedRememberInput {\n assertEntityId(entityId);\n if (input === null || typeof input !== 'object' || Array.isArray(input)) {\n throw new TypeError('remember(): input must be a non-null object.');\n }\n if (typeof input.title !== 'string' || input.title.trim() === '') {\n throw new TypeError('remember(): input.title must be a non-empty string.');\n }\n if (typeof input.body !== 'string') {\n throw new TypeError('remember(): input.body must be a string.');\n }\n let tags: string[] = [];\n if (input.tags !== undefined) {\n if (!Array.isArray(input.tags)) {\n throw new TypeError('remember(): input.tags must be an array of strings.');\n }\n // Index-based loop on purpose: Array.prototype.every skips holes, so a\n // sparse array (e.g. new Array(2)) would otherwise pass validation.\n for (let i = 0; i < input.tags.length; i++) {\n if (typeof input.tags[i] !== 'string') {\n throw new TypeError('remember(): input.tags must be an array of strings.');\n }\n }\n tags = [...(input.tags as string[])];\n }\n // null is a supplied value, not absence (spec §3.2: nothing coerced silently);\n // it fails the Set check below with the same message as any other bad value.\n const confidence = input.confidence === undefined ? 'certain' : input.confidence;\n if (!CONFIDENCE_VALUES.has(confidence)) {\n throw new TypeError(`remember(): input.confidence must be certain | inferred | tentative; got ${JSON.stringify(input.confidence)}.`);\n }\n const sourceType = input.source_type === undefined ? 'user_stated' : input.source_type;\n if (!SOURCE_TYPE_VALUES.has(sourceType)) {\n throw new TypeError(`remember(): input.source_type must be user_stated | user_confirmed; got ${JSON.stringify(input.source_type)}.`);\n }\n let okfType: string | null = null;\n if (input.okf_type !== undefined && input.okf_type !== null) {\n if (typeof input.okf_type !== 'string' || input.okf_type.trim() === '') {\n throw new TypeError('remember(): input.okf_type must be a non-empty string or null.');\n }\n okfType = input.okf_type;\n }\n const validFrom = input.valid_from === undefined ? undefined : assertEpochMs('input.valid_from', input.valid_from);\n\n const fact: WikiFact = {\n id: generateId('fact_'),\n entity_id: entityId,\n title: input.title,\n body: input.body,\n tags,\n confidence,\n source_type: sourceType,\n source_hash: null,\n source_ref: null,\n created_at: now,\n updated_at: now,\n last_accessed_at: null,\n access_count: 0,\n deleted_at: null,\n okf_type: null,\n };\n return { fact, validFrom, okfType };\n}\n","import type { SQLiteAdapter, WikiFact, RememberInput, ExtractedFactWithOntology, WikiOptions } from '../types';\nimport type { EntryRepository } from '../repositories/EntryRepository';\nimport type { OntologyService } from './OntologyService';\nimport type { SearchService } from './SearchService';\nimport type { EmbeddingService } from './EmbeddingService';\nimport { normalizeRememberInput } from '../utils/rememberInput';\nimport type { WikiDiagnosticInput } from '../utils/diagnostics';\nimport { emitDiagnostic, shouldEmitOntologyReceipt, nodeTypeReceipts } from '../utils/diagnostics';\n\n/** Direct mutable-fact writes (spec `specs/core-remember/spec.md` §3.3–§3.6). */\nexport class RememberService {\n constructor(\n private db: SQLiteAdapter,\n private entryRepo: EntryRepository,\n private ontologyService: OntologyService,\n private searchService: SearchService,\n private embeddingService: EmbeddingService,\n private options?: Pick<WikiOptions, 'onDiagnostic'>,\n ) {}\n\n async remember(entityId: string, input: RememberInput): Promise<WikiFact> {\n const now = Date.now();\n const { fact, validFrom, okfType } = normalizeRememberInput(entityId, input, now);\n let stored: WikiFact | undefined;\n // Receipts buffer until the transaction COMMITS: a rolled-back write\n // (failed upsert/setTemporal/read-back/commit) must deliver none\n // (CodeRabbit #441; mirrors the DiagnosticBuffer flush-after-commit\n // pattern the other write paths use).\n const pendingReceipts: WikiDiagnosticInput[] = [];\n\n await this.db.withTransactionAsync(async (tx) => {\n if (okfType !== null) {\n const { mode, manifest } = await this.ontologyService.getEffectiveState(entityId, tx);\n // Mode gate (CodeRabbit #441): a host with ontology 'off' sees no\n // ontology behavior at the remember door — the caller's slug is\n // stored verbatim, no fold, no drop, no throw, no receipt\n // (release-surface guarantee). \"Never replace a type a person\n // stated\" extends to the off mode.\n if (mode !== 'off') {\n // Same rule as an upsertGraph node type (IngestionService.upsertGraphCore):\n // canonical slug when the manifest knows it, a throw under strict, null otherwise.\n const factLike = { okf_type: okfType, edges: [] } as unknown as ExtractedFactWithOntology;\n const normalized = this.ontologyService.validateAndNormalizeFact(factLike, manifest, {\n strict: mode === 'strict',\n entityId,\n });\n fact.okf_type = normalized.okf_type;\n // Person-door receipts (spec §4): in strict mode a miss throws inside\n // validateAndNormalizeFact (before any commit — the throw is the only\n // signal, no receipt), so these only fire in the non-strict modes.\n if (shouldEmitOntologyReceipt(mode)) {\n for (const receipt of nodeTypeReceipts(\n { entityId, operation: 'remember', trigger: 'call' },\n fact.id,\n okfType,\n normalized.okf_type,\n normalized.match,\n )) {\n pendingReceipts.push(receipt);\n }\n }\n } else {\n // Off mode: store the caller's slug verbatim — no fold, no drop.\n fact.okf_type = okfType;\n }\n }\n await this.entryRepo.upsert(fact, tx);\n if (validFrom !== undefined) {\n await this.entryRepo.setTemporal(fact.id, entityId, { valid_from: validFrom }, tx);\n }\n // The return value is the stored row, not the literal: defaults the INSERT\n // bound and the read-time isStale / trustTier come from the mapper.\n const [readBack] = await this.entryRepo.findByIds([fact.id], [entityId], tx);\n if (!readBack) {\n throw new Error('remember(): the stored fact could not be read back; the SQLiteAdapter did not perform the write');\n }\n stored = readBack;\n });\n\n // Commit landed — now deliver the buffered receipts.\n for (const receipt of pendingReceipts) {\n emitDiagnostic(this.options ?? {}, receipt);\n }\n\n await this.searchService.syncEntries(entityId, [fact.id]);\n // A delete that lands during the vector call is settled inside\n // storeFactVector (spec durable-vector-removal §5.7, G10).\n await this.embeddingService.embedFact(\n { id: fact.id, entity_id: entityId, title: fact.title, body: fact.body, tags: fact.tags },\n { operation: 'remember', trigger: 'call' },\n );\n this.searchService.evictCache(entityId);\n return stored!;\n }\n\n}\n","import { canEngageWriteTyping, canEngageIngestTyping } from './services/typing/typeOnWrite';\nimport type { SQLiteAdapter } from './types';\nimport type { WikiOutboxEvent } from './outbox/types';\nimport { emitDiagnostic } from './utils/diagnostics';\nimport { setupDatabaseWithGate } from './db/migrationGate';\nimport { detectSchemaVersion, runSourceRefNormalize, writeNormalizeStamp } from './db/sourceRefNormalize';\nimport { withSerializedTransactions } from './db/serializedAdapter';\nimport { MIGRATIONS, CURRENT_SCHEMA_VERSION, createLegacySourceTypeIndex, createEntriesDeletedIndex } from './db/migrations';\nimport {\n WikiOptions,\n MemoryBundle,\n MemoryDump,\n WikiEvent,\n EntityStatus,\n ReadOptions,\n WikiSourceRefHashCollision,\n WikiDraftNotFound,\n WikiSupersedeError,\n} from './types';\nimport type { DraftPage, MigrationPolicy, ForgetParams, ForgetResult } from './types';\nimport type { PendingSourceStatus, WikiLintReport, WikiInstructions, PendingMaintenance, RunPendingMaintenanceOptions, RunPendingMaintenanceResult } 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 { SourceStoreService } from './services/SourceStoreService';\nimport type { StoreSourceResult, StoredSource, StoredSourceSummary } from './types';\nimport { MiniSearchIndexStrategy } from './services/search/MiniSearchIndexStrategy';\nimport { createIndexStrategy } from './services/search/createIndexStrategy';\nimport { monotonicNow } from './utils/monotonicNow';\nimport { DEFAULT_SETUP_BUDGET_MS } from './utils/setupDefaults';\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, type EraseReport } from './services/MaintenanceService';\nimport { MaintenanceScheduler } from './services/MaintenanceScheduler';\nimport { ImportExportService } from './services/ImportExportService';\nimport { EmbeddingService } from './services/EmbeddingService';\nimport { VectorRemovalService } from './services/VectorRemovalService';\nimport { VectorRemovalRepository } from './repositories/VectorRemovalRepository';\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 { TemporalService } from './services/TemporalService';\nimport { RememberService } from './services/RememberService';\nimport { validateManifest, isReservedAbstainSlug, ONTOLOGY_ABSTAIN_SENTINEL } from './utils/ontology';\nimport { DiagnosticBuffer } from './utils/diagnostics';\nimport type { OntologyManifest, OntologyMode, GraphTraversalOptions, GraphNeighborhood, OntologyBackfillResult, HealResult, IngestDocumentResult, ReembedResult, SupersedeReplacement, WikiFact, RememberInput } from './types';\nimport { resolveLibrarianStrategy, warnChangedDefaultsOnce, resolveContextBudgetOrThrow } from './utils/engineDefaults';\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 * Backoff between failed no-arg syncSearchIndex() re-init attempts (spec #280\n * Change 4): doubles per consecutive failure from the base up to the cap, and\n * is never shorter than SEARCH_REINIT_COST_FACTOR × the failed attempt's own\n * duration, so a slow attempt (backoff + rebuild under the write lock) can\n * take at most ~1/(factor+1) of wall time.\n */\nconst SEARCH_REINIT_COOLDOWN_MS = 5_000;\nconst SEARCH_REINIT_COOLDOWN_MAX_MS = 5 * 60_000;\nconst SEARCH_REINIT_COST_FACTOR = 10;\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 maintenanceScheduler: MaintenanceScheduler;\n retrievalService: RetrievalService;\n searchService: SearchService;\n writeService: WriteService;\n promptService: PromptService;\n graphTraversalService: GraphTraversalService;\n temporalService: TemporalService;\n rememberService: RememberService;\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 vectorRemovalRepo: VectorRemovalRepository;\n private vectorRemovalService: VectorRemovalService;\n private searchService: SearchService;\n private jobManager: JobManager;\n private ingestionService: IngestionService;\n private maintenanceService: MaintenanceService;\n private maintenanceScheduler: MaintenanceScheduler;\n private importExportService: ImportExportService;\n private retrievalService: RetrievalService;\n private writeService: WriteService;\n private sourceStoreService: SourceStoreService;\n private promptService: PromptService;\n private ontologyService: OntologyService;\n private graphTraversalService: GraphTraversalService;\n private lintRepo: LintRepository;\n private lintService: LintService;\n private temporalService: TemporalService;\n private rememberService: RememberService;\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 warnChangedDefaultsOnce(options.config);\n // Fail-fast: an invalid `config.context` section throws at construction,\n // never mid-pass (specs/context-budget T4).\n resolveContextBudgetOrThrow(options.config);\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.vectorRemovalRepo = new VectorRemovalRepository(this.db, this.prefix);\n this.vectorRemovalService = new VectorRemovalService(this.db, this.options, this.vectorRemovalRepo, this.embeddingService, this.metadataRepo);\n this.embeddingService.attachVectorRemoval(this.vectorRemovalService, this.vectorRemovalRepo);\n this.searchService = new SearchService(\n this.entryRepo,\n new MiniSearchIndexStrategy(),\n );\n this.temporalService = new TemporalService(this.db, this.options, this.entryRepo, this.searchService, this.embeddingService);\n this.rememberService = new RememberService(this.db, this.entryRepo, this.ontologyService, this.searchService, this.embeddingService, this.options);\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 this.vectorRemovalService,\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 this.edgeRepo,\n this.vectorRemovalService,\n this.vectorRemovalRepo,\n );\n this.maintenanceScheduler = new MaintenanceScheduler(\n this.db,\n this.options,\n this.maintenanceService,\n this.metadataRepo,\n this.eventRepo,\n this.entryRepo,\n this.jobManager,\n this.vectorRemovalService,\n this.vectorRemovalRepo,\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 this.options,\n this.vectorRemovalService,\n this.prefix,\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.sourceStoreService = new SourceStoreService(this.db, this.prefix, this.options, this.jobManager);\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 maintenanceScheduler: this.maintenanceScheduler,\n retrievalService: this.retrievalService,\n searchService: this.searchService,\n writeService: this.writeService,\n promptService: this.promptService,\n graphTraversalService: this.graphTraversalService,\n temporalService: this.temporalService,\n rememberService: this.rememberService,\n entryRepo: this.entryRepo,\n sourceRefIndexRepo: this.sourceRefIndexRepo,\n metadataRepo: this.metadataRepo,\n jobManager: this.jobManager,\n };\n }\n\n /** Max upsertGraph node and superseded-fact ids held for their post-commit sync (spec #280 id threading). */\n static readonly UPSERT_ID_STASH_CAP = 10_000;\n /**\n * upsertGraph node and superseded-fact ids per entity, awaiting syncSearchIndex(), each with the\n * generation of its latest stash. Ids leave the stash only once a drain\n * succeeded, so a failed drain retries them next call.\n */\n private upsertIdStash = new Map<string, Map<string, number>>();\n /** Total ids across upsertIdStash, kept in step so the cap check is O(1). */\n private upsertIdStashSize = 0;\n /** Bumped per stashed id; a re-stash during an in-flight drain outlives that drain's drop. */\n private upsertIdStashGen = 0;\n\n private stashUpsertIds(entityId: string, ids: readonly string[]): void {\n // Only a ledger strategy drains the search index by id; MiniSearch rebuilds the stale entity instead.\n // (Removal delivery has its own stash, stashRemovalIds, independent of the strategy.)\n if (!this.searchService.hasLedger()) return;\n const cap = (this.constructor as typeof WikiMemory).UPSERT_ID_STASH_CAP;\n const stash = this.upsertIdStash.get(entityId) ?? new Map<string, number>();\n for (const id of ids) {\n if (!stash.has(id)) {\n if (this.upsertIdStashSize >= cap) continue; // overflow: the entity-targeted / full-quantum drain covers the rest\n this.upsertIdStashSize++;\n }\n stash.set(id, ++this.upsertIdStashGen);\n }\n if (stash.size > 0) this.upsertIdStash.set(entityId, stash);\n }\n\n /** Max superseded-fact ids held for post-commit removal delivery. */\n static readonly REMOVAL_STASH_CAP = 10_000;\n /** Superseded fact ids per entity awaiting a post-commit delivery from syncSearchIndex(). */\n private removalStash = new Map<string, Set<string>>();\n private removalStashSize = 0;\n\n /**\n * Overflow past the cap drops the id from the stash only: the trigger already\n * put it on the ledger, so it stays owed and runExternalDeletions or\n * runPendingMaintenance delivers it later.\n */\n private stashRemovalIds(entityId: string, ids: readonly string[]): void {\n const cap = (this.constructor as typeof WikiMemory).REMOVAL_STASH_CAP;\n const stash = this.removalStash.get(entityId) ?? new Set<string>();\n for (const id of ids) {\n if (stash.has(id)) continue;\n if (this.removalStashSize >= cap) continue;\n stash.add(id);\n this.removalStashSize++;\n }\n if (stash.size > 0) this.removalStash.set(entityId, stash);\n }\n\n /** Removes and returns the stashed removal ids (one entity, or all). */\n private takeRemovalIds(entityId?: string): Map<string, string[]> {\n const out = new Map<string, string[]>();\n for (const [e, set] of [...this.removalStash]) {\n if (entityId !== undefined && e !== entityId) continue;\n out.set(e, [...set]);\n this.removalStashSize -= set.size;\n this.removalStash.delete(e);\n }\n return out;\n }\n\n /** Snapshot of the stash (one entity, or all) with generations, without removing anything. */\n private peekStashedIds(entityId?: string): Map<string, Map<string, number>> {\n const snapshot = new Map<string, Map<string, number>>();\n for (const [id, stash] of this.upsertIdStash) {\n if (entityId === undefined || id === entityId) snapshot.set(id, new Map(stash));\n }\n return snapshot;\n }\n\n /**\n * Removes a drained snapshot. An id re-stashed after the peek has a newer\n * generation and stays: the drain may have run before that write committed.\n */\n private dropStashedIds(snapshot: Map<string, Map<string, number>>): void {\n for (const [entityId, drained] of snapshot) {\n const stash = this.upsertIdStash.get(entityId);\n if (!stash) continue;\n for (const [id, gen] of drained) {\n if (stash.get(id) === gen && stash.delete(id)) this.upsertIdStashSize--;\n }\n if (stash.size === 0) this.upsertIdStash.delete(entityId);\n }\n }\n\n /** `config.setupBudgetMs` or the default, validated: a positive finite number. */\n private setupBudgetMs(): number {\n const budget = this.options.config?.setupBudgetMs ?? DEFAULT_SETUP_BUDGET_MS;\n if (typeof budget !== 'number' || !Number.isFinite(budget) || budget <= 0) {\n throw new TypeError(`setupBudgetMs must be a positive finite number; got ${String(budget)}`);\n }\n return budget;\n }\n\n private reinitSearch: Promise<void> | null = null;\n /** Monotonic time before which a no-arg syncSearchIndex() skips the re-init (0 = no cooldown). */\n private reinitRetryAt = 0;\n /** Consecutive failed re-inits; drives the exponential backoff. */\n private reinitFailures = 0;\n\n /**\n * Opens the store: migration gate, DDL, schema migrations, then the stamped\n * source_ref normalize. Await it before any other call on this instance — the\n * normalize commits in chunks, so a sourceRef-keyed call (forget, upsertGraph,\n * hasChanged, ingest) issued before setup() resolves can see partially\n * normalized refs.\n *\n * Pass `{ migrations: 'refuse' }` from inside a writer lease: pending one-time\n * work then throws WikiMigrationRequiredError before any mutation, and the\n * host runs a plain `setup()` outside the lease.\n *\n * Keyword-index catch-up work is bounded by `config.setupBudgetMs`; anything\n * left converges on later opens, and on no-arg `syncSearchIndex()` calls for\n * the entries ledger. Passage-ledger leftover converges on later opens and on\n * passage-store writes for the entity (`storeSource`, `forget`,\n * `importDump`), which drain that entity's rows; no-arg calls do not touch\n * the passage ledger. Not bounded: an index reset (tokenizer change, re-attach\n * after detach, a lost or inconsistent index), which runs as one unchunked\n * transaction.\n */\n async setup(opts?: { migrations?: MigrationPolicy }) {\n // Always-on erasure substrate (forget-erasure spec §1, ruling B): no opt-out, no option.\n // secure_delete is connection-wide and ATTACH-wide: it covers every database on this\n // connection. Hosts whose own code writes wiki tables through a different connection\n // (or re-opens the file) must set `PRAGMA secure_delete=ON` there too.\n // A refusal only warns; the honest failure belongs to erase's step 0, not setup.\n // \"FULL\" is the spec's name for full zeroing; SQLite spells it `ON` (1) — `FULL` is not a\n // SQLite value (reads back 0 on 3.53.4) and `FAST` (2) only zeroes partially.\n await this.db.execAsync('PRAGMA secure_delete=ON');\n const secureDelete = await this.db.getFirstAsync<{ secure_delete: number }>('PRAGMA secure_delete');\n if (!secureDelete || Number(secureDelete.secure_delete) !== 1) {\n console.warn(\n '[WikiMemory] PRAGMA secure_delete=ON (full zeroing) was not honored by this SQLite runtime; ' +\n 'deleted content may remain recoverable in the database file until erase() verifies it.',\n );\n }\n const setupBudgetMs = this.setupBudgetMs();\n // One deadline per open (spec #280 Change 3): captured here, never re-budgeted per turn.\n const openDeadline = monotonicNow() + setupBudgetMs;\n const entriesExistedBeforeSetup = await this.metadataRepo.tableExists(`${this.prefix}entries`);\n\n // The gate runs before any mutation: 'refuse' throws before tables are touched,\n // 'auto' lets only a pending source_ref normalize through (run below), 'allow' just sets up.\n const migrationPolicy = opts?.migrations ?? this.options.config?.migrations ?? 'allow';\n await setupDatabaseWithGate(this.db, this.prefix, this.metadataRepo, migrationPolicy);\n\n let currentVersion: number;\n\n if (!entriesExistedBeforeSetup) {\n // One transaction: a crash must never leave schema_version without its indexes,\n // since no migration would rebuild it on the next open.\n await this.db.withTransactionAsync(async (tx) => {\n await createLegacySourceTypeIndex(tx, this.prefix);\n await createEntriesDeletedIndex(tx, this.prefix);\n await writeNormalizeStamp(this.metadataRepo, tx);\n await this.metadataRepo.setMeta('schema_version', String(CURRENT_SCHEMA_VERSION), tx);\n });\n currentVersion = CURRENT_SCHEMA_VERSION;\n } else {\n currentVersion = await detectSchemaVersion(this.metadataRepo, this.prefix);\n }\n\n // Schema migrations. Under 'refuse'/'auto' the gate has already thrown if any are pending.\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 await this.importExportService.assertNoLegacySourceTypes();\n // Stamped, watermark-resumable normalization; no-op once the stamp matches.\n await runSourceRefNormalize(this.db, this.prefix, this.metadataRepo);\n }\n\n this.searchService.setIndexStrategy(\n await createIndexStrategy(\n this.db,\n this.prefix,\n this.metadataRepo,\n this.options.config?.indexStrategy ?? 'auto',\n { setupBudgetMs, entriesExisted: entriesExistedBeforeSetup },\n ),\n );\n // FTS5: one budgeted quantum (no global read). MiniSearch: full rebuild, as before.\n await this.searchService.sync(undefined, { deadline: openDeadline });\n // Spec source-store §6: FTS5 drains the passage ledger; the fallback re-indexes every stored entity at open.\n await this.searchService.syncPassages(this.db, this.prefix, undefined, openDeadline);\n await this.startSetupRemovalDrain();\n }\n\n private setupRemovalDrain: Promise<void> | null = null;\n\n /** Marks the external index in use, then drains owed removals in the background (spec §5.7). */\n private async startSetupRemovalDrain(): Promise<void> {\n if (this.setupRemovalDrain) return; // a second setup() reuses the running drain\n const gate = this.vectorRemovalService.gate();\n if (gate === 'none') return;\n // Assigned before the first await so a concurrent setup() sees it.\n const prelude = (async (): Promise<{ drain: Promise<void> | null }> => {\n if (gate === 'hook' && !(await this.vectorRemovalService.externalIndexInUse())) {\n await this.db.withTransactionAsync((tx) => this.vectorRemovalService.markExternalIndexInUse(tx));\n }\n if ((await this.vectorRemovalRepo.pendingStats()).count === 0) {\n // Under force nothing is owed, so the marker has nothing left to guard (spec §5.3).\n if (gate === 'force') await this.vectorRemovalService.clearExternalIndexMarker();\n return { drain: null };\n }\n if (this.options.drainExternalDeletionsOnSetup !== true) {\n if (gate === 'hook') await this.vectorRemovalService.emitPending(undefined, 'auto');\n return { drain: null };\n }\n const drain = (async () => {\n try {\n const r = await this.vectorRemovalService.drain(\n { all: true },\n { backoff: true, deadlineAt: Date.now() + 10_000, trigger: 'auto' },\n );\n if (r.pending > 0) await this.vectorRemovalService.emitPending(undefined, 'auto');\n } catch {\n emitDiagnostic(this.options, {\n code: 'background_job_failed', operation: 'externalDeletion', trigger: 'auto', entityId: '', // store-wide drain\n detail: { reason: 'unhandled_rejection' },\n });\n }\n })();\n return { drain };\n })();\n const joined: Promise<void> = prelude.then((r) => r.drain ?? undefined, () => undefined);\n this.setupRemovalDrain = joined;\n void joined.then(() => { if (this.setupRemovalDrain === joined) this.setupRemovalDrain = null; });\n await prelude; // marker or ledger errors surface from setup()\n }\n\n /**\n * Delivers owed vector-index removals now (spec §5.9). No backoff. With an\n * entity id only that entity's rows; otherwise all. `deadlineMs` is a duration.\n * `transient: true` means a ledger read or write could not run (for example,\n * you held a transaction open on the connection); the rows stay pending.\n */\n async runExternalDeletions(\n entityId?: string,\n opts?: { deadlineMs?: number },\n ): Promise<{ confirmed: number; pending: number; failedIds: string[]; timedOut: boolean; transient?: boolean }> {\n if (entityId !== undefined) assertEntityId(entityId);\n const ms = opts?.deadlineMs;\n if (ms !== undefined && (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0)) {\n throw new TypeError('deadlineMs must be a finite number >= 0');\n }\n // A store whose setup() never ran has no ledger: nothing is recorded as owed.\n if (!(await this.vectorRemovalService.ledgerPresent())) {\n return { confirmed: 0, pending: 0, failedIds: [], timedOut: false };\n }\n const r = await this.vectorRemovalService.drain(\n entityId === undefined ? { all: true } : { entityId },\n { trigger: 'call', ...(ms !== undefined ? { deadlineAt: Date.now() + ms } : {}) },\n );\n return {\n confirmed: r.confirmed, pending: r.pending, failedIds: r.failedIds, timedOut: r.timedOut,\n ...(r.transient ? { transient: true } : {}),\n };\n }\n\n /** Removals still owed to the host's vector index (all entities, or one). */\n async getPendingExternalDeletions(\n entityId?: string,\n ): Promise<{ count: number; oldestEnqueuedAt: number | null; maxAttempts: number }> {\n if (entityId !== undefined) assertEntityId(entityId);\n if (!(await this.vectorRemovalService.ledgerPresent())) return { count: 0, oldestEnqueuedAt: null, maxAttempts: 0 };\n return this.vectorRemovalRepo.pendingStats(entityId);\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 `instructions_get` tool (formerly `wiki_get_instructions`). 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 // Write builders get the write context, backfill its own (specs/type-on-write §5).\n // The librarian context reflects write-time typing engagement, so what the host\n // reads is what the pass sends; ingest reflects `typeOnIngest` the same way; heal and backfill are unchanged.\n const state = await this.ontologyService.getEffectiveState(entityId);\n const engaged = canEngageWriteTyping(this.options.config, this.options.llmProvider, state.mode, state.manifest);\n const writeContext = await this.ontologyService.buildWritePromptContext(entityId, { engaged });\n // Ingest reflects its own engagement (specs/ingest-time-typing §5): engaged -> no\n // manifest block; otherwise today's context (equal to `writeContext` unless the\n // librarian alone is engaged).\n const ingestEngaged = canEngageIngestTyping(this.options.config, this.options.llmProvider, state.mode, state.manifest);\n const ingestContext = ingestEngaged\n ? null\n : engaged\n ? await this.ontologyService.buildWritePromptContext(entityId, { engaged: false })\n : writeContext;\n const backfillContext = await this.ontologyService.buildPromptContext(entityId);\n // Specs/librarian-guidance: same resolution as the write paths. A read\n // path that silently drops over-cap guidance would be the one place\n // guidance disappears without a signal, so over-cap emits here too.\n const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);\n if (diagnostic) {\n emitDiagnostic(this.options, {\n code: diagnostic.code,\n operation: 'read',\n trigger: 'call',\n entityId,\n detail: diagnostic.detail,\n });\n }\n return this.promptService.buildInstructionTemplates(writeContext, resolveLibrarianStrategy(this.options.config), guidance, backfillContext, ingestContext);\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 stored?: { charCount: number; staleHash?: true } | null;\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 /**\n * Erase everything soft-deleted, store-wide, and verify it (forget-erasure\n * spec §2). Throws `EraseStepError` (partial report, `verified: false`) when\n * a step fails; skipped entities report `verified: false`.\n * `{ rebuild: true }` additionally restarts the FTS rebuild.\n */\n async erase(options?: { rebuild?: boolean }): Promise<EraseReport> {\n return this.maintenanceService.erase(options);\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 /** Await auto-mode background librarian/heal jobs started by write(), and the removal drain `setup()` started under `drainExternalDeletionsOnSetup`. */\n async drain(): Promise<void> {\n await this.setupRemovalDrain;\n return this.writeService.drain();\n }\n\n /**\n * Report which entities have pending maintenance work (librarian events\n * behind the watermark, heal backlog, unembedded facts) without running\n * anything. Entities with no pending work are omitted; sorted by\n * `pendingEvents` desc then `entityId` asc.\n */\n async getPendingMaintenance(entityIds?: string[]): Promise<PendingMaintenance[]> {\n return this.maintenanceScheduler.getPending(entityIds);\n }\n\n /** Run pending removals, librarian, heal and reembed work under an optional token budget and deadline (spec §6.2). Awaits the setup removal drain first, when `drainExternalDeletionsOnSetup` started one. */\n async runPendingMaintenance(options?: RunPendingMaintenanceOptions): Promise<RunPendingMaintenanceResult> {\n let opts = options;\n const ms = options?.deadlineMs;\n // Reject a bad deadline before waiting: unchecked, it would skip the bounded\n // wait below and block on the whole setup drain before the scheduler throws.\n if (ms !== undefined && (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0)) {\n throw new TypeError('deadlineMs must be a finite number >= 0');\n }\n const setupDrain = this.setupRemovalDrain;\n if (setupDrain) {\n if (ms !== undefined) {\n // Bound the wait by deadlineMs and hand the scheduler only what is left.\n const started = Date.now();\n let handle: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n setupDrain,\n new Promise<void>((resolve) => { handle = setTimeout(resolve, ms); }),\n ]).finally(() => { if (handle) clearTimeout(handle); });\n opts = { ...options, deadlineMs: Math.max(0, ms - (Date.now() - started)) };\n } else {\n await setupDrain;\n }\n }\n return this.maintenanceScheduler.run(opts);\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.guidance` 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?: {\n promptOverride?: string;\n batchSize?: number;\n classifier?: 'auto' | 'llm';\n tokenBudget?: number;\n /** Overrides the default recheck cooldown: facts stamped after this epoch ms stay deferred. */\n recheckCheckedBefore?: number;\n },\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 /**\n * Brings the keyword search index up to date with SQLite after a host\n * transaction that used `upsertGraph` has committed. Core never sees that\n * commit, so without this the nodes stay out of keyword, hybrid and\n * fallback retrieval until the entity's next core write.\n *\n * With `entityId`: drains that entity's pending `upsertGraph` ids (its new\n * nodes and the facts they superseded) first, to completion, then at most\n * one more ledger chunk — so its new nodes are searchable, and the\n * superseded facts gone, when the call resolves, under any backlog. Without an\n * argument: drains every stashed `upsertGraph` id across entities first,\n * then runs one keyword-index quantum bounded by `config.setupBudgetMs`\n * (backlog drain, then rebuild work while the index is rebuilding). Hosts\n * with a long-lived process should call the no-arg form on their own\n * schedule: that is what converges a rebuilding index. While keyword search\n * is unavailable it first retries the index init; after a failed attempt it\n * waits at least 5 s, doubling per consecutive failure up to 5 min (longer\n * when an attempt is itself slow), before retrying again.\n *\n * It also calls the host's removal hook (`onEmbeddingPersisted(…, null)`) for\n * the stashed ids that `upsertGraph` superseded, and can take up to\n * `deletionHookTimeoutMs` per id when the host's index is slow. It never\n * drains an entity's wider removal backlog.\n *\n * Call only after the host's transaction commits: called inside it, the\n * rebuild may index rows that later roll back, or miss them and clear the\n * stale flag anyway. Serialized with core's internal index syncs and takes\n * no maintenance lock. Never rejects for a valid `entityId` — on failure the\n * entity stays stale and the next call retries it. Does not compute\n * embeddings; that remains the maintenance sweep's job.\n *\n * With the FTS5 index strategy this drains the index ledger in its own\n * transactions, so it MUST be called after the host transaction commits,\n * never from inside a `withTransactionAsync` callback. Calling it inside\n * one waits on the transaction mutex that the callback holds.\n *\n * @throws {TypeError} when `entityId` is given but is not a non-empty string.\n */\n async syncSearchIndex(entityId?: string): Promise<void> {\n if (entityId !== undefined) assertEntityId(entityId);\n // Capture the removal ids before the sync; delivery is non-throwing and\n // leaves anything unconfirmed owed on the ledger.\n const removals = this.takeRemovalIds(entityId);\n try {\n await this.syncSearchIndexCore(entityId);\n } catch (err) {\n // Put the ids back so the next call delivers them (the cap still applies;\n // overflow stays owed on the ledger).\n for (const [e, ids] of removals) this.stashRemovalIds(e, ids);\n throw err;\n }\n for (const [e, ids] of removals) {\n await this.vectorRemovalService.deliverRemovals(e, ids, 'upsertGraph', 'call');\n }\n }\n\n private async syncSearchIndexCore(entityId?: string): Promise<void> {\n if (entityId === undefined) {\n // A long-lived host that never re-opens still recovers from a failed init (spec #280 Change 4).\n // After a failed re-init, back off before the next: each attempt costs\n // the 250 ms retry backoff plus up to two rebuild transactions under the\n // write lock, and hosts call this after every write.\n if (!this.searchService.isKeywordAvailable() && monotonicNow() >= this.reinitRetryAt) {\n // One re-init at a time; concurrent callers share it.\n this.reinitSearch ??= (async () => {\n const started = monotonicNow();\n try {\n const strategy = await createIndexStrategy(\n this.db, this.prefix, this.metadataRepo, this.options.config?.indexStrategy ?? 'auto',\n { setupBudgetMs: this.setupBudgetMs() });\n this.searchService.setIndexStrategy(strategy);\n // A new MiniSearch index starts empty and needs the full sync. A ledger\n // strategy gets its one quantum from the syncStale() below (#284 review).\n if (this.searchService.isKeywordAvailable() && !this.searchService.hasLedger()) await this.searchService.sync();\n if (this.searchService.isKeywordAvailable()) await this.searchService.syncPassages(this.db, this.prefix);\n } finally {\n if (this.searchService.isKeywordAvailable()) {\n this.reinitFailures = 0;\n this.reinitRetryAt = 0;\n } else {\n const now = monotonicNow();\n const backoff = Math.min(SEARCH_REINIT_COOLDOWN_MS * 2 ** this.reinitFailures, SEARCH_REINIT_COOLDOWN_MAX_MS);\n this.reinitFailures++;\n this.reinitRetryAt = now + Math.max(backoff, SEARCH_REINIT_COST_FACTOR * (now - started));\n }\n this.reinitSearch = null;\n }\n })();\n await this.reinitSearch;\n }\n const stashed = this.peekStashedIds();\n const ids = [...stashed.values()].flatMap((m) => [...m.keys()]);\n if (await this.syncDrained(this.searchService.syncStale({ ids }))) this.dropStashedIds(stashed);\n return;\n }\n assertEntityId(entityId);\n const stashed = this.peekStashedIds(entityId);\n if (await this.syncDrained(this.searchService.syncEntries(entityId, stashed.get(entityId)?.keys() ?? []))) {\n this.dropStashedIds(stashed);\n }\n }\n\n /**\n * True when a sync applied the stashed ids. While keyword search is\n * unavailable the stand-in strategy's drain is a no-op that reports success,\n * so the ids stay stashed for the first sync after a re-init (#284 review).\n */\n private async syncDrained(sync: Promise<boolean>): Promise<boolean> {\n return (await sync) && this.searchService.isKeywordAvailable();\n }\n\n async exportDump(entityIds?: string[], opts?: { includeForgotten?: boolean }): Promise<MemoryDump> {\n return this.importExportService.exportDump(entityIds, opts);\n }\n\n /**\n * The retention windows `runPrune()` uses when the host runs it (shipped\n * defaults plus host overrides), for GDPR disclosure. Nothing prunes\n * automatically; `erase()` ignores `retainSoftDeletedFor`. Days; `null`\n * means \"keep forever\". Read-only.\n */\n getRetentionPolicy(): {\n retainSoftDeletedFor: number;\n retainEventsFor: number | null;\n pruneSupersededAfter: number | null;\n } {\n const c = this.options.config;\n return {\n retainSoftDeletedFor: c?.pruneRetainSoftDeletedFor ?? 7,\n retainEventsFor: c?.pruneEventsAfter ?? 30,\n pruneSupersededAfter: c?.pruneSupersededAfter ?? null,\n };\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<import('./types').ImportDumpResult> {\n try {\n return await this.importExportService.importDump(dump, opts);\n } finally {\n // Import re-cuts stored sources inside its transaction; index them once it committed (spec §6, §8).\n // Also runs after a failed import (e.g. WikiBusyError): intentional and harmless — it reads committed state and never rejects.\n // Scoped to the dump's entities so MiniSearch does not re-read every stored entity.\n for (const entityId of Object.keys(dump?.entities ?? {})) {\n await this.searchService.syncPassages(this.db, this.prefix, entityId);\n }\n }\n }\n\n /**\n * Soft-delete facts and tasks by id, by source, by source-pointer event id,\n * or all of them (`clearAll`).\n * `clearAll` also deletes the entity's edges and its source-ref index rows.\n * Add `includeEvents: true` to `clearAll` to hard-delete every event too,\n * read or not, and reset the librarian's position: without it a later\n * maintenance run can read the events into facts again. `runPrune()` then\n * hard-deletes the soft-deleted rows once they are older than\n * `retainSoftDeletedFor` (7 days by default; pass 0 to remove them now).\n * `dryRun` previews the counts.\n *\n * With a removal hook (`vectorRanker.onEmbeddingPersisted`), the deleted\n * facts are recorded as owed in the same transaction and then delivered to\n * the hook before this resolves.\n *\n * @throws {WikiExternalDeletionError} when the hook didn't confirm every\n * removal. The local delete stays committed and the rest stay owed; retry,\n * or call `runExternalDeletions()`.\n */\n async forget(\n entityId: string,\n params: ForgetParams,\n opts?: { dryRun?: boolean },\n ): Promise<ForgetResult> {\n try {\n return await this.maintenanceService.forget(entityId, params, opts);\n } finally {\n // Spec §5/§6: removal sync for stored passages, after the delete committed (also when the\n // external-deletion hook threw, since the local delete stays committed; a sync after any other\n // failure is intentional and harmless — it reads committed state and never rejects). clearAll\n // wipes only THIS entity (MaintenanceService deletes WHERE entity_id = ?), so the sync is\n // entity-scoped like every other forget shape; a store-wide sync would drain other entities'\n // ledgers (FTS5) or re-read every stored entity's text (MiniSearch) on an ordinary call.\n if (!opts?.dryRun) {\n await this.searchService.syncPassages(this.db, this.prefix, entityId);\n }\n }\n }\n\n /** Store a source's text (spec source-store §7). Refusals return `stored: false`; a busy lock throws. */\n async storeSource(\n entityId: string,\n params: { sourceRef: string; sourceHash: string; text: string },\n ): Promise<StoreSourceResult> {\n assertEntityId(entityId);\n const result = await this.sourceStoreService.storeSource(entityId, params);\n if (result.stored) await this.searchService.syncPassages(this.db, this.prefix, entityId);\n return result;\n }\n\n async getStoredSource(entityId: string, sourceRef: string): Promise<StoredSource | null> {\n assertEntityId(entityId);\n return this.sourceStoreService.getStoredSource(entityId, sourceRef);\n }\n\n async listStoredSources(entityId: string): Promise<StoredSourceSummary[]> {\n assertEntityId(entityId);\n return this.sourceStoreService.listStoredSources(entityId);\n }\n\n /**\n * End `oldId`'s validity and link it to its replacement (spec §4.3). One\n * transaction. Throws `WikiSupersedeError` for missing, foreign, already\n * superseded, already expired, immutable-document, or cyclic targets, and\n * for an inverted or empty interval (`invalid_interval`). When the old\n * fact carried a future `valid_to`, that scheduled end is overwritten but\n * kept in `prior_valid_to` (restored by `reopen()`) and reported as the\n * `supersede_scheduled_end_replaced` diagnostic.\n */\n async supersede(\n entityId: string,\n oldId: string,\n replacement: SupersedeReplacement,\n options?: { validFrom?: number },\n ): Promise<{ newId: string }> {\n return this.temporalService.supersede(entityId, oldId, replacement, options);\n }\n\n /**\n * End `factId`'s validity without a replacement — an archive, not a\n * deletion (INTENT rule 12). Sets `valid_to` only: `superseded_by`,\n * `superseded_at` and `deleted_at` stay untouched, and an `asOf` read at\n * `T` with `COALESCE(valid_from, created_at) <= T < valid_to` still returns\n * the fact. Throws `WikiSupersedeError` for\n * a missing, foreign, already superseded, immutable-document, or already\n * expired target, and for an inverted or empty interval (`invalid_interval`).\n */\n async expire(entityId: string, factId: string, options?: { at?: number }): Promise<void> {\n return this.temporalService.expire(entityId, factId, options);\n }\n\n /**\n * Return a superseded fact to live once its replacement has been forgotten\n * or hard-deleted (INTENT rule 12). Clears `superseded_by`/`superseded_at`\n * and restores `valid_to` to the scheduled end `supersede()` overwrote\n * (`prior_valid_to`), or null when the fact was open-ended. Resolves with\n * the restored `valid_to`. Throws `WikiSupersedeError` for a missing or\n * foreign fact, one that is not superseded (an `expire()`-ended fact is\n * not reopened), an immutable-document fact, or `successor_live` while the\n * direct replacement is still live. A restored end that has already passed\n * leaves the fact expired.\n */\n async reopen(entityId: string, factId: string): Promise<{ valid_to: number | null }> {\n return this.temporalService.reopen(entityId, factId);\n }\n\n /** The supersession chain containing `factId`, oldest first. [] when unknown. */\n async history(entityId: string, factId: string): Promise<WikiFact[]> {\n return this.temporalService.history(entityId, factId);\n }\n\n /**\n * Store one mutable fact directly, with no LLM step (spec\n * `specs/core-remember/spec.md`). One transaction; resolves with the stored\n * row read back (`id`, timestamps, defaults, `isStale`, `trustTier`). Never\n * starts the librarian or heal and writes no event, in `'auto'` and\n * `'deferred'` mode alike. Embeds through `llmProvider.embed` when present;\n * keyword-only otherwise. Not idempotent. To replace an existing fact use\n * `supersede()` so history is kept. Opens its own transaction: do not call\n * it inside `withTransactionAsync` (the serialized adapter would deadlock).\n *\n * Throws `TypeError` on invalid input and `WikiStrictOntologyViolation` for\n * an `okf_type` the entity's strict manifest does not define; nothing is\n * written in either case.\n */\n async remember(entityId: string, input: RememberInput): Promise<WikiFact> {\n return this.rememberService.remember(entityId, input);\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`, and that transaction must be\n * opened through the adapter given to `createWiki` (the removal ledger is\n * filled by triggers inside it, and a rollback discards the rows). 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). After the\n * transaction commits, call `syncSearchIndex(entityId)` — or\n * `syncSearchIndex()` after writing several entities in one transaction —\n * to make the new nodes keyword-searchable and to deliver, through the\n * host's removal hook, the vectors of any facts the call superseded: both forms drain this call's node ids\n * first, to completion, so the nodes are searchable under any backlog (up to\n * `WikiMemory.UPSERT_ID_STASH_CAP` pending ids; beyond that they converge with\n * the backlog). Embeddings still come from the maintenance\n * sweep (`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 { supersededFactIds, ...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 // Core never sees this commit. Under a ledger strategy the triggers already\n // recorded the rows: stash the node ids and superseded ids for the search\n // drain. The superseded ids also go in the removal stash (any strategy), so\n // the host's post-commit syncSearchIndex() delivers their removals.\n // MiniSearch has no ledger: markStale makes that sync rebuild the entity.\n this.stashUpsertIds(entityId, [...supersededFactIds, ...params.nodes.map((n) => n.id)]);\n this.stashRemovalIds(entityId, supersededFactIds);\n this.searchService.markStale(entityId);\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 // The reserved abstain sentinel is rejected here on the write path\n // (specs/system-one-config §5, decree C4); per-read validateManifest is\n // deliberately untouched so legacy manifests carrying the slug still read.\n for (const entry of entries) {\n validateManifest(entry.manifest);\n for (const nodeType of entry.manifest.node_types ?? []) {\n if (isReservedAbstainSlug(nodeType.type)) {\n throw new Error(\n `Invalid node type '${nodeType.type}': '${ONTOLOGY_ABSTAIN_SENTINEL}' is reserved for classifier abstention and cannot be declared in a manifest`,\n );\n }\n }\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, SourcePassage } 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\nfunction renderSourceLabel(p: SourcePassage, includeEntityId: boolean): string {\n const entity = includeEntityId ? `${p.entityId} ` : '';\n return `${entity}${p.sourceRef} #${p.seq}${p.truncated ? ' (excerpt)' : ''}`;\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?.compact ?? false) && (options?.includeConfidence ?? true),\n includeTags: !(options?.compact ?? false) && (options?.includeTags ?? true),\n includeEntityIds: !(options?.compact ?? false) && (options?.includeEntityIds ?? false),\n includeFactScores: !(options?.compact ?? false) && (options?.includeFactScores ?? false),\n compact: options?.compact ?? 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 // Spec source-store §7: the Sources group prints last, and only when present.\n const sources = bundle.sources ?? [];\n\n if (sortedFacts.length === 0 && sortedTasks.length === 0 && sortedEvents.length === 0 && sources.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\n if (sources.length > 0) {\n lines.push('');\n lines.push('### Sources');\n for (const p of sources) {\n lines.push(`- [${renderSourceLabel(p, opts.includeEntityIds)}] ${p.text.replace(/\\n/g, '\\n ')}`);\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 if (sources.length > 0) {\n lines.push('SOURCES:');\n for (const p of sources) {\n lines.push(`[${renderSourceLabel(p, opts.includeEntityIds)}] ${p.text}`);\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, WikiSourcePointer, 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 { createdAtValue, isUsableDate } from '../services/importEventStamps';\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\n/**\n * Source-pointer frontmatter map (specs/source-pointers §Export, import, and\n * OKF): emitted only when the pointer is non-null; null slots are omitted.\n * An all-null pointer therefore emits an empty map, which parses back to a\n * null pointer with no diagnostic (spec test 9).\n */\nfunction sourcePointerFrontmatter(\n p: WikiSourcePointer | null | undefined,\n): { event_id?: string; ref?: string; quote?: string; position?: { start: number; length: number } } | undefined {\n if (!p) return undefined;\n return {\n ...(p.event_id != null ? { event_id: p.event_id } : {}),\n ...(p.ref != null ? { ref: p.ref } : {}),\n ...(p.quote != null ? { quote: p.quote } : {}),\n ...(p.position != null ? { position: p.position } : {}),\n };\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 // Temporal (spec 2026-09-29 §10.9): flat epoch-ms keys, like created_at.\n ...(f.valid_from != null ? { valid_from: f.valid_from } : {}),\n ...(f.valid_to != null ? { valid_to: f.valid_to } : {}),\n ...(f.superseded_by != null ? { superseded_by: f.superseded_by } : {}),\n ...(f.superseded_at != null ? { superseded_at: f.superseded_at } : {}),\n ...(f.prior_valid_to != null ? { prior_valid_to: f.prior_valid_to } : {}),\n // Source pointer (specs/source-pointers): map only when non-null; null slots omitted.\n ...(sourcePointerFrontmatter(f.source_pointer)\n ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) }\n : {}),\n // derived_events (specs/inplace-update-provenance §5): optional list, only when non-empty.\n ...(f.derived_events && f.derived_events.length > 0 ? { derived_events: f.derived_events } : {}),\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 // Source pointer (specs/source-pointers): same map rule as the v2 path.\n ...(sourcePointerFrontmatter(f.source_pointer)\n ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) }\n : {}),\n // derived_events (specs/inplace-update-provenance §5): optional list, only when non-empty.\n ...(f.derived_events && f.derived_events.length > 0 ? { derived_events: f.derived_events } : {}),\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 // An occurred_at left as text or out of range by an older import would\n // throw in toISOString, and one outside years 0000-9999 (e.g. a\n // microsecond epoch) renders a heading parseOkfBundle cannot read back.\n // Fall back to created_at for those.\n const occurred = createdAtValue(e.occurred_at);\n // A future occurred_at (e.g. an appointment) is not used either: the\n // re-imported entry would look future-dated and be clamped, losing the\n // date. The dates this preserves are past ones (spec §8.2).\n const logTime = e.occurred_at != null && isUsableDate(occurred) && occurred >= OKF_DATE_MIN && occurred <= OKF_DATE_MAX\n && occurred <= e.created_at\n ? occurred\n : e.created_at;\n return { date: formatLogDate(logTime), text: appendEventIdComment(text, e.id) };\n });\n}\n\n/** Epoch-ms range whose ISO date is a four-digit year (0000-01-01 to 9999-12-31), the only headings parseOkfBundle reads. */\nconst OKF_DATE_MIN = -62167219200000;\nconst OKF_DATE_MAX = 253402300799999;\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 { validateSourcePointerValue } from './sourcePointer';\nimport { validateDerivedEventsValue } from './derivedEvents';\nimport type { OkfFile, OkfFrontmatter, OkfFrontmatterValue } from '@equationalapplications/core-okf';\nimport {\n parseConcept,\n parseLogMd,\n parseRootIndexMd,\n parseEntityIndexMd,\n parseEventIdComment,\n createEventIdDeriver,\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\n/** Lone UTF-16 surrogates → U+FFFD, matching how deriveEventId's UTF-8 encoding hashes them. */\nfunction replaceLoneSurrogates(s: string): string {\n let out = '';\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n if (c >= 0xd800 && c <= 0xdbff) {\n const n = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;\n if (n >= 0xdc00 && n <= 0xdfff) { out += s[i] + s[i + 1]; i++; } else out += '\\uFFFD';\n } else if (c >= 0xdc00 && c <= 0xdfff) {\n out += '\\uFFFD';\n } else {\n out += s[i];\n }\n }\n return out;\n}\n\nfunction unescapeLogSummary(summary: string): string {\n return summary.replace(/\\\\\\]/g, ']').replace(/\\\\\\[/g, '[').replace(/\\\\\\\\/g, '\\\\');\n}\n\n// linear: label group cannot start a plain char on `\\` or `[` (closes CodeQL #8); plain branch starts on \\S (closes CodeQL #1)\nconst LOG_LINE_PATTERN = /^\\(([^)]+)\\)\\s*(?:\\[((?:\\\\.|[^\\[\\]\\\\])*)\\]\\(([^)]+)\\)|(\\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 // Producers escape `\\`, `[` and `]` in every summary (profile §7), so the plain form is unescaped too.\n return { event_type, summary: unescapeLogSummary((plainSummary ?? '').trim()) };\n}\n\nfunction frontmatterToFact(\n entityId: string,\n id: string,\n frontmatter: OkfFrontmatter,\n body: string,\n now: number,\n droppedPointerValues: Array<{ factId: string; reason: string }>,\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 ...optionalEpoch('valid_from', (frontmatter as any).valid_from),\n ...optionalEpoch('valid_to', (frontmatter as any).valid_to),\n ...(typeof (frontmatter as any).superseded_by === 'string' ? { superseded_by: (frontmatter as any).superseded_by } : {}),\n ...optionalEpoch('superseded_at', (frontmatter as any).superseded_at),\n ...optionalEpoch('prior_valid_to', (frontmatter as any).prior_valid_to),\n // Source pointer (specs/source-pointers §Export, import, and OKF): the\n // parse path has no diagnostic channel, so it reports through the result.\n // ABSENT key → the property is omitted (not null), so the import\n // presence guard survives the parse. Malformed → the property is omitted\n // AND the drop is reported as entry id + reason slug — never the raw\n // value, which can carry quote text.\n ...(() => {\n const raw = (frontmatter as any).source_pointer;\n if (raw === undefined) return {};\n const v = validateSourcePointerValue(raw);\n if (v === undefined) {\n droppedPointerValues.push({ factId: id, reason: 'malformed' });\n return {};\n }\n return { source_pointer: v };\n })(),\n // derived_events (specs/inplace-update-provenance §5): a well-formed list\n // is restored; absent or empty omits the property (import presence rule);\n // malformed omits it AND is reported by id + slug, never the raw value.\n ...(() => {\n const raw = (frontmatter as any).derived_events;\n if (raw === undefined) return {};\n const v = validateDerivedEventsValue(raw);\n if (v === undefined) {\n droppedPointerValues.push({ factId: id, reason: 'derived_events_malformed' });\n return {};\n }\n return v ? { derived_events: v } : {};\n })(),\n };\n}\n\n/** Temporal epoch-ms frontmatter keys (spec 2026-09-29 §10.9): keep only finite,\n * non-negative numbers; anything else means \"absent\" and the key stays off. */\nfunction optionalEpoch<K extends string>(key: K, v: unknown): Partial<Record<K, number>> {\n return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? ({ [key]: Math.trunc(v) } as Record<K, number>) : {};\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 // Source-pointer parse report (specs/source-pointers): present on the\n // returned MemoryDump only when a malformed `source_pointer` was dropped.\n const droppedPointerValues: Array<{ factId: string; reason: string }> = [];\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, droppedPointerValues));\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 // Id-less lines get a derived id after the whole log is read, so explicit ids\n // anywhere in the file are known first (spec import-followups §3.2).\n const pending: Array<{ index: number; date: string }> = [];\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 if (eventId === undefined) pending.push({ index: events.length, date: entry.date });\n events.push({\n id: eventId ?? '',\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 // Occurrence per (day, type, summary); a derived id already taken by an explicit\n // id or an earlier derived id moves to the next occurrence, so no line is dropped.\n const taken = new Set(events.map(e => e.id).filter(id => id !== ''));\n const nextOccurrence = new Map<string, number>();\n for (const { index, date } of pending) {\n const e = events[index];\n // Keyed by the text the hash sees: lone surrogates hash as U+FFFD, so\n // variants that differ only in them share one count (keeps this linear).\n const key = JSON.stringify([date, e.event_type, replaceLoneSurrogates(e.summary)]);\n let occurrence = nextOccurrence.get(key) ?? 0;\n // Hash the shared fields once: explicit ids can take a long line's whole\n // chain of occurrences, and re-hashing the summary per step is quadratic.\n const derive = createEventIdDeriver({ entityId, date, eventType: e.event_type, summary: e.summary });\n let id = derive(occurrence);\n while (taken.has(id)) {\n occurrence += 1;\n id = derive(occurrence);\n }\n taken.add(id);\n nextOccurrence.set(key, occurrence + 1);\n e.id = id;\n }\n }\n\n return {\n generatedAt: now,\n entities: {\n [entityId]: { facts, tasks, events, edges, summary: entitySummary },\n },\n ...(droppedPointerValues.length > 0 ? { dropped_pointer_values: droppedPointerValues } : {}),\n };\n}\n","/**\n * Context-budget wrapper (specs/context-budget Proposed change 2).\n *\n * Core ships no tokenizer: every estimate is chars/`charsPerToken`. The\n * meter keeps plain `estimateTokens` (chars/4) this PR — metering is out of\n * scope — so `estimateTokensWith` under a legacy budget (`charsPerToken: 4`)\n * is byte-equal to `estimateTokens` for every input, and the wrapper ships\n * unused by metering.\n */\nexport interface ContextBudget {\n mode: 'legacy' | 'declared';\n /** Set iff mode === 'declared'. */\n contextWindowTokens?: number;\n /** 4 under legacy. */\n charsPerToken: number;\n /** 0.9 under legacy (unused in legacy math). */\n safetyFraction: number;\n /** 4000 under legacy (unused in legacy math). */\n outputReserveTokens: number;\n}\n\nexport function estimateTokensWith(budget: ContextBudget, text: string): number {\n return Math.ceil(text.length / budget.charsPerToken);\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 { buildOntologyPromptAppendix } from './prompts/ontology';\nexport { configureRandomSource } from './utils/ids';\nexport { validUsage } from './utils/llmCall';\nexport { chunkText, safeSlice } from './utils/pure';\nexport { DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_CHUNK_OVERLAP } from './utils/chunkingDefaults';\nexport { resolveContextBudget, resolveMaxPromptChars, resolveDefaultChunkLength } from './config/context';\nexport type { ContextBudget } from './utils/contextBudget';\nexport { estimateTokensWith } from './utils/contextBudget';\nexport { DEFAULT_MAX_EMBED_CHARS, EMBED_CHARS_CEILING } from './utils/embedDefaults';\nexport { DEFAULT_SETUP_BUDGET_MS } from './utils/setupDefaults';\nexport * from './librarianPrompt';\nexport { PromptService } from './services/PromptService';\nexport { resolveOntologyJobDefaults, DEFAULT_ONTOLOGY_JOB_BATCH_SIZE } from './utils/config/ontologyJobDefaults';\nexport {\n resolveSystemOneTyping,\n resolveTypingMinConfidence,\n resolveSystemOneEdges,\n resolveEdgesMinConfidence,\n resolveSystemOneResolve,\n resolveResolveMinConfidence,\n resolveSystemOneHealScreen,\n resolveSystemOneTypeOnWrite,\n resolveSystemOneTypeOnIngest,\n resolveHealScreenMinConfidence,\n warnOnce,\n DEFAULT_TYPING_MIN_CONFIDENCE,\n} from './utils/engineDefaults';\nexport { ONTOLOGY_ABSTAIN_SENTINEL, isReservedAbstainSlug } from './utils/ontology';\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 CLASSIFIER_MAX_CHOICES,\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 { EraseStepError } from './services/MaintenanceService';\nexport type { EraseReport } from './services/MaintenanceService';\nexport { CheckpointIncompleteError } from './repositories/MetadataRepository';\nexport { ONTOLOGY_BACKFILL_SYSTEM_PROMPT } from './prompts';\n\nexport function createWiki(db: SQLiteAdapter, options: WikiOptions): WikiMemory {\n return new WikiMemory(db, options);\n}\n"]}