@ponythewhite/base-context 1.0.7 → 1.0.9

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.
Files changed (138) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/base-context-runtime/pyproject.toml +1 -1
  3. package/dist/base-context-runtime/src/rlm/__init__.py +3 -0
  4. package/dist/base-context-runtime/src/rlm/harness.py +86 -48
  5. package/dist/base-context-runtime/test/test_harness.py +215 -140
  6. package/dist/base-context-runtime/uv.lock +1 -1
  7. package/dist/build-info.json +1 -1
  8. package/dist/bundle/amazon-bedrock.js +3 -3
  9. package/dist/bundle/{anthropic-UV5GZDGU.js → anthropic-5PSCZEER.js} +2 -7
  10. package/dist/bundle/{azure-openai-responses-WSNPXLYC.js → azure-openai-responses-AYTLJR33.js} +2 -2
  11. package/dist/bundle/{bundled-modules-PS66L3IT.js → bundled-modules-5JRM6P4T.js} +5 -5
  12. package/dist/bundle/{chunk-UPVDERMD.js → chunk-2IPDSTDR.js} +11 -9
  13. package/dist/bundle/chunk-D3KOF57W.js +22040 -0
  14. package/dist/bundle/{chunk-VSIYFWYI.js → chunk-KT2BNEPE.js} +21 -8
  15. package/dist/bundle/{chunk-VCW3YDFF.js → chunk-NEHLB7JV.js} +1548 -574
  16. package/dist/bundle/{chunk-KTNETTHI.js → chunk-Q3MBSBEB.js} +3 -101
  17. package/dist/bundle/{chunk-LFPWHI42.js → chunk-QKIFBA7N.js} +2 -2
  18. package/dist/bundle/{chunk-PFROC4EV.js → chunk-VVI3UKGR.js} +12 -9
  19. package/dist/bundle/{cli-main-MMHTK7EB.js → cli-main-YUDBEYE2.js} +4 -4
  20. package/dist/bundle/cli.js +1 -1
  21. package/dist/bundle/{google-T32FMD4G.js → google-HTMCUJ7X.js} +2 -2
  22. package/dist/bundle/{google-vertex-56KP6I3B.js → google-vertex-ZQO65AXF.js} +2 -2
  23. package/dist/bundle/{main-XAIVH4Y7.js → main-ZLGGAAGU.js} +5 -5
  24. package/dist/bundle/{mistral-WGBMYIVU.js → mistral-SB7LU56G.js} +1 -1
  25. package/dist/bundle/{openai-codex-responses-PIV2RQ3G.js → openai-codex-responses-5CEW4VN3.js} +53 -27
  26. package/dist/bundle/{openai-completions-64C3JPR4.js → openai-completions-BAZJQSS2.js} +1 -1
  27. package/dist/bundle/{openai-responses-UI7RSTDV.js → openai-responses-VHOE427P.js} +48 -5
  28. package/dist/core/agent-session.d.ts +9 -1
  29. package/dist/core/agent-session.d.ts.map +1 -1
  30. package/dist/core/agent-session.js +225 -29
  31. package/dist/core/agent-session.js.map +1 -1
  32. package/dist/core/canonical-context.d.ts +8 -0
  33. package/dist/core/canonical-context.d.ts.map +1 -1
  34. package/dist/core/canonical-context.js +37 -5
  35. package/dist/core/canonical-context.js.map +1 -1
  36. package/dist/core/compaction/compaction.d.ts +2 -2
  37. package/dist/core/compaction/compaction.d.ts.map +1 -1
  38. package/dist/core/compaction/compaction.js +31 -13
  39. package/dist/core/compaction/compaction.js.map +1 -1
  40. package/dist/core/context-epoch.d.ts +1 -1
  41. package/dist/core/context-epoch.d.ts.map +1 -1
  42. package/dist/core/context-epoch.js +2 -1
  43. package/dist/core/context-epoch.js.map +1 -1
  44. package/dist/core/extensions/types.d.ts +2 -2
  45. package/dist/core/extensions/types.d.ts.map +1 -1
  46. package/dist/core/extensions/types.js.map +1 -1
  47. package/dist/core/history-index-worker.d.ts.map +1 -1
  48. package/dist/core/history-index-worker.js +29 -8
  49. package/dist/core/history-index-worker.js.map +1 -1
  50. package/dist/core/history-index.d.ts +11 -1
  51. package/dist/core/history-index.d.ts.map +1 -1
  52. package/dist/core/history-index.js +2 -1
  53. package/dist/core/history-index.js.map +1 -1
  54. package/dist/core/inference-coordinator.d.ts +1 -1
  55. package/dist/core/inference-coordinator.d.ts.map +1 -1
  56. package/dist/core/inference-coordinator.js +110 -15
  57. package/dist/core/inference-coordinator.js.map +1 -1
  58. package/dist/core/kernel/bootstrap.d.ts.map +1 -1
  59. package/dist/core/kernel/bootstrap.js +97 -107
  60. package/dist/core/kernel/bootstrap.js.map +1 -1
  61. package/dist/core/kernel/repl-manager.d.ts.map +1 -1
  62. package/dist/core/kernel/repl-manager.js +11 -0
  63. package/dist/core/kernel/repl-manager.js.map +1 -1
  64. package/dist/core/kernel/shared.d.ts +2 -0
  65. package/dist/core/kernel/shared.d.ts.map +1 -1
  66. package/dist/core/kernel/shared.js.map +1 -1
  67. package/dist/core/messages.d.ts.map +1 -1
  68. package/dist/core/messages.js +4 -1
  69. package/dist/core/messages.js.map +1 -1
  70. package/dist/core/prompts/rlm.d.ts.map +1 -1
  71. package/dist/core/prompts/rlm.js +4 -2
  72. package/dist/core/prompts/rlm.js.map +1 -1
  73. package/dist/core/public-context.d.ts.map +1 -1
  74. package/dist/core/public-context.js +16 -0
  75. package/dist/core/public-context.js.map +1 -1
  76. package/dist/core/refinement/refinement.d.ts +19 -5
  77. package/dist/core/refinement/refinement.d.ts.map +1 -1
  78. package/dist/core/refinement/refinement.js +90 -35
  79. package/dist/core/refinement/refinement.js.map +1 -1
  80. package/dist/core/request-view-selection.d.ts +13 -3
  81. package/dist/core/request-view-selection.d.ts.map +1 -1
  82. package/dist/core/request-view-selection.js +239 -101
  83. package/dist/core/request-view-selection.js.map +1 -1
  84. package/dist/core/retained-tool-output.d.ts +28 -0
  85. package/dist/core/retained-tool-output.d.ts.map +1 -0
  86. package/dist/core/retained-tool-output.js +102 -0
  87. package/dist/core/retained-tool-output.js.map +1 -0
  88. package/dist/core/selective-recovery.d.ts +47 -3
  89. package/dist/core/selective-recovery.d.ts.map +1 -1
  90. package/dist/core/selective-recovery.js +428 -109
  91. package/dist/core/selective-recovery.js.map +1 -1
  92. package/dist/core/session-history-index.d.ts +3 -1
  93. package/dist/core/session-history-index.d.ts.map +1 -1
  94. package/dist/core/session-history-index.js +1 -1
  95. package/dist/core/session-history-index.js.map +1 -1
  96. package/dist/core/session-manager.d.ts +2 -0
  97. package/dist/core/session-manager.d.ts.map +1 -1
  98. package/dist/core/session-manager.js +38 -13
  99. package/dist/core/session-manager.js.map +1 -1
  100. package/dist/core/settings-manager.d.ts +5 -0
  101. package/dist/core/settings-manager.d.ts.map +1 -1
  102. package/dist/core/settings-manager.js +3 -0
  103. package/dist/core/settings-manager.js.map +1 -1
  104. package/dist/core/system-prompt.d.ts +3 -1
  105. package/dist/core/system-prompt.d.ts.map +1 -1
  106. package/dist/core/system-prompt.js +3 -3
  107. package/dist/core/system-prompt.js.map +1 -1
  108. package/dist/core/task-frame.d.ts +1 -1
  109. package/dist/core/task-frame.d.ts.map +1 -1
  110. package/dist/core/task-frame.js +21 -1
  111. package/dist/core/task-frame.js.map +1 -1
  112. package/dist/core/task-state-reader.d.ts +10 -2
  113. package/dist/core/task-state-reader.d.ts.map +1 -1
  114. package/dist/core/task-state-reader.js +75 -9
  115. package/dist/core/task-state-reader.js.map +1 -1
  116. package/dist/core/tools/ipython.d.ts +5 -0
  117. package/dist/core/tools/ipython.d.ts.map +1 -1
  118. package/dist/core/tools/ipython.js +59 -17
  119. package/dist/core/tools/ipython.js.map +1 -1
  120. package/dist/core/tools/prime-context.d.ts.map +1 -1
  121. package/dist/core/tools/prime-context.js +1 -1
  122. package/dist/core/tools/prime-context.js.map +1 -1
  123. package/dist/core/view-units.d.ts +4 -0
  124. package/dist/core/view-units.d.ts.map +1 -1
  125. package/dist/core/view-units.js +28 -19
  126. package/dist/core/view-units.js.map +1 -1
  127. package/dist/installer.mjs +98 -77
  128. package/dist/modes/interactive/components/refinement-outcome-message.d.ts.map +1 -1
  129. package/dist/modes/interactive/components/refinement-outcome-message.js.map +1 -1
  130. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  131. package/dist/modes/interactive/interactive-mode.js +5 -5
  132. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  133. package/dist/skills/skill-creator/SKILL.md +18 -1
  134. package/docs/settings.md +45 -0
  135. package/docs/skills.md +77 -2
  136. package/package.json +4 -4
  137. package/skills/skill-creator/SKILL.md +18 -1
  138. package/dist/bundle/chunk-W46VZFI6.js +0 -21681
@@ -1 +1 @@
1
- {"version":3,"file":"history-index-worker.d.ts","sourceRoot":"","sources":["../../src/core/history-index-worker.ts"],"names":[],"mappings":"","sourcesContent":["import { fstatSync, mkdirSync, openSync, statSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { DatabaseSync } from \"node:sqlite\";\nimport type { Usage } from \"@ponythewhite/base-context-ai\";\nimport { stringifyBoundedJson } from \"./bounded-json.js\";\nimport { type CanonicalPayloadParts, readCanonicalPayloadFragment } from \"./canonical-payload-parts.js\";\nimport { GOAL_STATE_CUSTOM_TYPE, isPersistedGoalState } from \"./goals.js\";\nimport type {\n\tBranchBootstrapState,\n\tContextManifestCursor,\n\tContextManifestPage,\n\tContextRef,\n\tContextUpdateRef,\n\tContextUpdates,\n\tContextUpdateTarget,\n\tHistoryIndexRequest,\n\tHistoryPayloadReadOptions,\n\tIndexedSourceEvent,\n\tIndexedTaskEvidence,\n\tIpythonSentMessagesCursor,\n\tIpythonSentMessagesPage,\n\tParentPathCursor,\n\tParentPathPage,\n\tSessionCatalogIndexResult,\n\tSourceBootstrapState,\n\tTaskEvidencePage,\n} from \"./history-index.js\";\nimport {\n\tprojectSessionSourceEvent,\n\treadSessionSource,\n\ttype SessionSourceEntry,\n\ttype SourceIndexCursor,\n\tvalidateIndexedCatalogSource,\n} from \"./history-source.js\";\nimport { withJournalDescriptorSync } from \"./journal-io.js\";\nimport {\n\tIPYTHON_SENT_AGENT_MESSAGE_CUSTOM_ENTRY,\n\tparsePersistedIpythonSentAgentMessage,\n} from \"./session-context-updates.js\";\nimport {\n\tCatalogProjectionUnsupportedError,\n\tdecodeSessionCatalog,\n\temptySessionCatalog,\n\tfoldSessionCatalog,\n\ttype SessionCatalogProjection,\n} from \"./session-info-projection.js\";\nimport type { SessionJournalState } from \"./session-journal-owner.js\";\nimport type { FileEntry } from \"./session-manager.js\";\nimport { getTaskStateImportCoverage, projectTaskStateSource } from \"./task-state.js\";\nimport { addAssistantUsage, cloneUsage, emptyUsage, sessionUsageSummaryFrom, subtractAssistantUsage } from \"./usage.js\";\n\nprocess.umask(0o077);\nconst readOnly = process.argv[3] === \"--read-only\";\nasync function openIndex() {\n\tlet opened: DatabaseSync | undefined;\n\tlet unsupported = false;\n\ttry {\n\t\tconst [major, minor] = process.versions.node.split(\".\").map(Number);\n\t\t// The API was backported to 22.12; early 23.x can also ignore the option.\n\t\tif (readOnly && (major < 22 || (major === 22 && minor < 12) || (major === 23 && minor < 3))) {\n\t\t\tunsupported = true;\n\t\t\tthrow new Error(\"Read-only catalog requires Node 22.12+ (23.x requires 23.3+)\");\n\t\t}\n\t\tif (!readOnly) mkdirSync(dirname(process.argv[2]), { recursive: true, mode: 0o700 });\n\t\tconst database = new DatabaseSync(process.argv[2], { readOnly });\n\t\topened = database;\n\t\tconst applicationId = Number(database.prepare(\"PRAGMA application_id\").get()?.application_id ?? 0);\n\t\tconst schemaVersion = Number(database.prepare(\"PRAGMA user_version\").get()?.user_version ?? 0);\n\t\tconst hasTables = !!database.prepare(\"SELECT 1 FROM sqlite_master WHERE type='table' LIMIT 1\").get();\n\t\tif (\n\t\t\t(applicationId !== 0x42435458 && (applicationId !== 0 || hasTables)) ||\n\t\t\t![0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16].includes(schemaVersion) ||\n\t\t\t(readOnly && (applicationId !== 0x42435458 || schemaVersion !== 16))\n\t\t) {\n\t\t\tunsupported = true;\n\t\t\tthrow new Error(\n\t\t\t\treadOnly\n\t\t\t\t\t? \"Catalog requires supported history-index schema 16; read-only discovery does not migrate\"\n\t\t\t\t\t: \"Not a supported Base Context history index\",\n\t\t\t);\n\t\t}\n\t\treturn { db: database, schemaVersion };\n\t} catch (error) {\n\t\tlet failure = error;\n\t\ttry {\n\t\t\topened?.close();\n\t\t} catch (cleanup) {\n\t\t\tunsupported = false;\n\t\t\tfailure = new AggregateError(\n\t\t\t\t[error, cleanup],\n\t\t\t\t`Index open and close failed: ${String(error)}; ${String(cleanup)}`,\n\t\t\t);\n\t\t}\n\t\tif (readOnly && process.connected)\n\t\t\tawait new Promise<void>((resolveSent) => {\n\t\t\t\ttry {\n\t\t\t\t\tprocess.send?.(\n\t\t\t\t\t\t{ startupError: failure instanceof Error ? failure.message : String(failure), unsupported },\n\t\t\t\t\t\t() => resolveSent(),\n\t\t\t\t\t);\n\t\t\t\t} catch {\n\t\t\t\t\tresolveSent();\n\t\t\t\t}\n\t\t\t});\n\t\tthrow failure;\n\t}\n}\nconst { db, schemaVersion } = await openIndex();\nif (!readOnly)\n\tdb.exec(`\n\tPRAGMA application_id=1111708760;\n\tPRAGMA journal_mode=WAL;\n\tPRAGMA synchronous=FULL;\n\tPRAGMA busy_timeout=5000;\n\tPRAGMA cache_size=-2048;\n\tCREATE TABLE IF NOT EXISTS source_event (\n\t\tsession TEXT NOT NULL, id TEXT NOT NULL, sequence INTEGER NOT NULL,\n\t\tparent_id TEXT, kind TEXT NOT NULL, authority TEXT NOT NULL,\n\t\tlocator TEXT NOT NULL, revision TEXT NOT NULL, text TEXT NOT NULL, text_complete INTEGER NOT NULL, retention TEXT, qualification TEXT,\n\t\tPRIMARY KEY(session,id), UNIQUE(session,sequence)\n\t);\n\tCREATE TABLE IF NOT EXISTS coverage(session TEXT PRIMARY KEY, sequence INTEGER NOT NULL);\n\tCREATE TABLE IF NOT EXISTS source_cursor (\n\t\tsession TEXT PRIMARY KEY, frontier TEXT NOT NULL, header_bytes INTEGER NOT NULL, header_checksum TEXT NOT NULL,\n\t\tsource_leaf TEXT,source_session_info TEXT,source_session_state TEXT,\n\t\tsource_compaction_count INTEGER NOT NULL DEFAULT 0,source_content_prefix INTEGER NOT NULL DEFAULT 0,\n\t\tsource_has_user_content INTEGER NOT NULL DEFAULT 0\n\t);\n\tCREATE TABLE IF NOT EXISTS source_term (\n\t\tsession TEXT NOT NULL, term TEXT NOT NULL, sequence INTEGER NOT NULL,\n\t\tPRIMARY KEY(session,term,sequence DESC)\n\t);\n\tCREATE TABLE IF NOT EXISTS term_count (\n\t\tsession TEXT NOT NULL, term TEXT NOT NULL, count INTEGER NOT NULL,\n\t\tPRIMARY KEY(session,term)\n\t);\n`);\n\nconst TASK_PAGE_BYTES = 1024 * 1024 - 1024;\nconst MAX_JUMP_LEVELS = 53;\nconst MAX_PARENT_LOOKUPS = 128;\nconst DERIVED_TABLES = [\n\t\"source_catalog_usage\",\n\t\"context_update\",\n\t\"context_node\",\n\t\"source_ancestry\",\n\t\"source_jump\",\n\t\"source_term\",\n\t\"term_count\",\n\t\"task_import_loss\",\n\t\"task_evidence\",\n\t\"source_event\",\n\t\"source_payload\",\n\t\"coverage\",\n\t\"source_cursor\",\n];\nif (!readOnly)\n\ttransaction(() => {\n\t\tdb.exec(`CREATE TABLE IF NOT EXISTS task_evidence (\n session TEXT NOT NULL, sequence INTEGER NOT NULL, ordinal INTEGER NOT NULL,\n task_key TEXT, item_id TEXT, source_ref TEXT NOT NULL, projection TEXT,\n PRIMARY KEY(session,sequence,ordinal)\n );\n CREATE INDEX IF NOT EXISTS task_item ON task_evidence(session,task_key,item_id,sequence,ordinal);\n CREATE TABLE IF NOT EXISTS source_payload (\n session TEXT NOT NULL, sequence INTEGER NOT NULL, parts TEXT NOT NULL, PRIMARY KEY(session,sequence)\n );\n CREATE TABLE IF NOT EXISTS task_import_loss (\n session TEXT NOT NULL, sequence INTEGER NOT NULL, task_key TEXT, PRIMARY KEY(session,sequence)\n );\n CREATE TABLE IF NOT EXISTS source_ancestry (\n session TEXT NOT NULL, id TEXT NOT NULL, depth INTEGER, PRIMARY KEY(session,id)\n );\n CREATE TABLE IF NOT EXISTS source_jump (\n session TEXT NOT NULL, id TEXT NOT NULL, level INTEGER NOT NULL, ancestor_id TEXT NOT NULL,\n PRIMARY KEY(session,id,level)\n );\n CREATE TABLE IF NOT EXISTS context_node (\n session TEXT NOT NULL,id TEXT NOT NULL,visible_head TEXT,previous_visible TEXT,visible_count INTEGER,latest_compaction TEXT,first_kept_id TEXT,\n latest_model TEXT,latest_thinking TEXT,latest_service_tier TEXT,latest_goal TEXT,has_session_message INTEGER,goal_seedable INTEGER,\n latest_rlm_max_depth TEXT,has_branch_message INTEGER,context_usage_assistant TEXT,latest_git_state TEXT,latest_agent_status TEXT,PRIMARY KEY(session,id)\n );\n CREATE TABLE IF NOT EXISTS context_update (\n session TEXT NOT NULL,event_id TEXT NOT NULL,update_kind TEXT NOT NULL,target_key TEXT NOT NULL,sequence INTEGER NOT NULL,\n PRIMARY KEY(session,update_kind,event_id)\n );\n CREATE INDEX IF NOT EXISTS context_update_target ON context_update(session,update_kind,target_key,sequence);\n CREATE TABLE IF NOT EXISTS source_catalog_usage (\n session TEXT NOT NULL,category INTEGER NOT NULL,id TEXT NOT NULL,sequence INTEGER NOT NULL,usage TEXT NOT NULL,\n PRIMARY KEY(session,category,id)\n );\n CREATE INDEX IF NOT EXISTS source_catalog_usage_order ON source_catalog_usage(session,category,sequence);`);\n\t\t// Old labels/projections cannot survive unchanged source identities across this upgrade.\n\t\tif (schemaVersion !== 16) {\n\t\t\tif (\n\t\t\t\t!db\n\t\t\t\t\t.prepare(\"PRAGMA table_info(source_event)\")\n\t\t\t\t\t.all()\n\t\t\t\t\t.some((column) => column.name === \"retention\")\n\t\t\t)\n\t\t\t\tdb.exec(\"ALTER TABLE source_event ADD COLUMN retention TEXT\");\n\t\t\tif (\n\t\t\t\t!db\n\t\t\t\t\t.prepare(\"PRAGMA table_info(source_event)\")\n\t\t\t\t\t.all()\n\t\t\t\t\t.some((column) => column.name === \"qualification\")\n\t\t\t)\n\t\t\t\tdb.exec(\"ALTER TABLE source_event ADD COLUMN qualification TEXT\");\n\t\t\tif (\n\t\t\t\t!db\n\t\t\t\t\t.prepare(\"PRAGMA table_info(context_node)\")\n\t\t\t\t\t.all()\n\t\t\t\t\t.some((column) => column.name === \"latest_model\")\n\t\t\t)\n\t\t\t\tdb.exec(`\n ALTER TABLE context_node ADD COLUMN latest_model TEXT;\n ALTER TABLE context_node ADD COLUMN latest_thinking TEXT;\n ALTER TABLE context_node ADD COLUMN latest_service_tier TEXT;\n ALTER TABLE context_node ADD COLUMN latest_goal TEXT;\n ALTER TABLE context_node ADD COLUMN has_session_message INTEGER;\n ALTER TABLE context_node ADD COLUMN goal_seedable INTEGER;\n `);\n\t\t\tif (\n\t\t\t\t!db\n\t\t\t\t\t.prepare(\"PRAGMA table_info(context_node)\")\n\t\t\t\t\t.all()\n\t\t\t\t\t.some((column) => column.name === \"latest_rlm_max_depth\")\n\t\t\t)\n\t\t\t\tdb.exec(`\n ALTER TABLE context_node ADD COLUMN latest_rlm_max_depth TEXT;\n ALTER TABLE context_node ADD COLUMN has_branch_message INTEGER;\n `);\n\t\t\tif (\n\t\t\t\t!db\n\t\t\t\t\t.prepare(\"PRAGMA table_info(context_node)\")\n\t\t\t\t\t.all()\n\t\t\t\t\t.some((column) => column.name === \"context_usage_assistant\")\n\t\t\t)\n\t\t\t\tdb.exec(\"ALTER TABLE context_node ADD COLUMN context_usage_assistant TEXT\");\n\t\t\tif (\n\t\t\t\t!db\n\t\t\t\t\t.prepare(\"PRAGMA table_info(context_node)\")\n\t\t\t\t\t.all()\n\t\t\t\t\t.some((column) => column.name === \"latest_git_state\")\n\t\t\t)\n\t\t\t\tdb.exec(`ALTER TABLE context_node ADD COLUMN latest_git_state TEXT;\n ALTER TABLE context_node ADD COLUMN latest_agent_status TEXT;`);\n\t\t\tif (\n\t\t\t\t!db\n\t\t\t\t\t.prepare(\"PRAGMA table_info(source_cursor)\")\n\t\t\t\t\t.all()\n\t\t\t\t\t.some((column) => column.name === \"source_leaf\")\n\t\t\t)\n\t\t\t\tdb.exec(`ALTER TABLE source_cursor ADD COLUMN source_leaf TEXT;\n ALTER TABLE source_cursor ADD COLUMN source_session_info TEXT;\n ALTER TABLE source_cursor ADD COLUMN source_session_state TEXT;\n ALTER TABLE source_cursor ADD COLUMN source_compaction_count INTEGER NOT NULL DEFAULT 0;\n ALTER TABLE source_cursor ADD COLUMN source_content_prefix INTEGER NOT NULL DEFAULT 0;\n ALTER TABLE source_cursor ADD COLUMN source_has_user_content INTEGER NOT NULL DEFAULT 0;`);\n\t\t\tif (\n\t\t\t\t!db\n\t\t\t\t\t.prepare(\"PRAGMA table_info(source_cursor)\")\n\t\t\t\t\t.all()\n\t\t\t\t\t.some((column) => column.name === \"catalog_summary\")\n\t\t\t)\n\t\t\t\tdb.exec(\"ALTER TABLE source_cursor ADD COLUMN catalog_summary TEXT\");\n\t\t\tfor (const table of DERIVED_TABLES) db.exec(`DELETE FROM ${table}`);\n\t\t}\n\t\tdb.exec(`\n CREATE INDEX IF NOT EXISTS source_incomplete ON source_event(session,sequence) WHERE text_complete=0;\n CREATE INDEX IF NOT EXISTS task_sequence ON task_evidence(session,task_key,sequence,ordinal);\n CREATE INDEX IF NOT EXISTS task_item_sequence ON task_evidence(session,item_id,sequence,ordinal);\n CREATE INDEX IF NOT EXISTS task_loss_key ON task_import_loss(session,task_key,sequence);\n `);\n\t\tdb.exec(\"PRAGMA user_version=16\");\n\t});\n\n// Node22.8 ships SQLite without FTS5. A normal SQLite posting index keeps the\n// declared floor and bounded lookups without loading a platform extension.\nfunction terms(text: string): string[] {\n\treturn [\n\t\t...new Set(\n\t\t\ttext\n\t\t\t\t.normalize(\"NFC\")\n\t\t\t\t.toLowerCase()\n\t\t\t\t.match(/[\\p{L}\\p{M}\\p{N}_]+/gu) ?? [],\n\t\t),\n\t];\n}\nconst insertTerm = db.prepare(\"INSERT INTO source_term VALUES (?,?,?)\");\nconst countTerm = db.prepare(\n\t\"INSERT INTO term_count VALUES (?,?,1) ON CONFLICT(session,term) DO UPDATE SET count=count+1\",\n);\n\ntype Row = {\n\tid: string;\n\tsequence: number;\n\tparent_id: string | null;\n\tkind: string;\n\tauthority: IndexedSourceEvent[\"authority\"];\n\tlocator: string;\n\trevision: string;\n\ttext: string;\n\ttext_complete: number;\n\tretention: IndexedSourceEvent[\"retention\"] | null;\n\tqualification: IndexedSourceEvent[\"qualification\"] | null;\n};\nfunction event(row: Row): IndexedSourceEvent {\n\treturn {\n\t\tid: row.id,\n\t\tsequence: row.sequence,\n\t\tparentId: row.parent_id,\n\t\tkind: row.kind,\n\t\tauthority: row.authority,\n\t\tlocator: JSON.parse(row.locator) as IndexedSourceEvent[\"locator\"],\n\t\trevision: row.revision,\n\t\t...(row.retention === null ? {} : { retention: row.retention }),\n\t\t...(row.qualification === null ? {} : { qualification: row.qualification }),\n\t\ttext: row.text,\n\t\ttextComplete: row.text_complete === 1,\n\t};\n}\nfunction transaction(action: () => void): void {\n\tdb.exec(\"BEGIN IMMEDIATE\");\n\ttry {\n\t\taction();\n\t\tdb.exec(\"COMMIT\");\n\t} catch (error) {\n\t\ttry {\n\t\t\tdb.exec(\"ROLLBACK\");\n\t\t} catch {\n\t\t\t/* SQLite may already have rolled back a failed write. */\n\t\t}\n\t\tthrow error;\n\t}\n}\nfunction insertEvent(sessionId: string, item: IndexedSourceEvent): void {\n\tif (item.retention !== undefined && item.retention !== \"retained-import\")\n\t\tthrow new Error(\"Unsupported indexed source retention\");\n\tif (\n\t\titem.qualification !== undefined &&\n\t\titem.qualification !== \"native-admission\" &&\n\t\titem.qualification !== \"native-recovery\" &&\n\t\titem.qualification !== \"native-context-epoch\" &&\n\t\titem.qualification !== \"native-tool-execution\"\n\t)\n\t\tthrow new Error(\"Unsupported indexed source qualification\");\n\tdb.prepare(\"INSERT INTO source_event VALUES (?,?,?,?,?,?,?,?,?,?,?,?)\").run(\n\t\tsessionId,\n\t\titem.id,\n\t\titem.sequence,\n\t\titem.parentId,\n\t\titem.kind,\n\t\titem.authority,\n\t\tJSON.stringify(item.locator),\n\t\titem.revision,\n\t\titem.text,\n\t\titem.textComplete ? 1 : 0,\n\t\titem.retention ?? null,\n\t\titem.qualification ?? null,\n\t);\n\tfor (const term of terms(item.text)) {\n\t\tinsertTerm.run(sessionId, term, item.sequence);\n\t\tcountTerm.run(sessionId, term);\n\t}\n}\nconst sourceParent = db.prepare(\n\t\"SELECT a.depth FROM source_event e JOIN source_ancestry a ON a.session=e.session AND a.id=e.id WHERE e.session=? AND e.id=? AND e.sequence<?\",\n);\nconst insertDepth = db.prepare(\"INSERT INTO source_ancestry VALUES (?,?,?)\");\nconst insertJump = db.prepare(\"INSERT INTO source_jump VALUES (?,?,?,?)\");\nconst ancestorJump = db.prepare(\"SELECT ancestor_id FROM source_jump WHERE session=? AND id=? AND level=?\");\nfunction insertAncestry(sessionId: string, item: IndexedSourceEvent): number | null {\n\tconst parent = item.parentId === null ? undefined : sourceParent.get(sessionId, item.parentId, item.sequence);\n\tconst depth = item.parentId === null ? 0 : parent?.depth == null ? null : Number(parent.depth) + 1;\n\tinsertDepth.run(sessionId, item.id, depth);\n\tif (depth === null || depth === 0) return depth;\n\tlet ancestorId = item.parentId!;\n\tfor (let level = 0; level < MAX_JUMP_LEVELS && 2 ** level <= depth; level++) {\n\t\tif (level > 0) ancestorId = String(ancestorJump.get(sessionId, ancestorId, level - 1)!.ancestor_id);\n\t\tinsertJump.run(sessionId, item.id, level, ancestorId);\n\t}\n\treturn depth;\n}\ntype ContextState = {\n\tvisible_head: string | null;\n\tprevious_visible: string | null;\n\tvisible_count: number | null;\n\tlatest_compaction: string | null;\n\tfirst_kept_id: string | null;\n};\ntype BootstrapColumns = {\n\tlatest_model: string | null;\n\tlatest_thinking: string | null;\n\tlatest_service_tier: string | null;\n\tlatest_goal: string | null;\n\thas_session_message: number;\n\tgoal_seedable: number;\n\tlatest_rlm_max_depth: string | null;\n\thas_branch_message: number;\n\tcontext_usage_assistant: string | null;\n\tlatest_git_state: string | null;\n\tlatest_agent_status: string | null;\n};\nfunction isPersistedRlmMaxDepthState(value: unknown): boolean {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst maxDepth = (value as { maxDepth?: unknown }).maxDepth;\n\treturn typeof maxDepth === \"number\" && Number.isSafeInteger(maxDepth) && maxDepth >= 0;\n}\nconst contextParent = db.prepare(\"SELECT * FROM context_node WHERE session=? AND id=?\");\nconst insertContextNode = db.prepare(\"INSERT INTO context_node VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\");\nfunction insertContext(\n\tsessionId: string,\n\titem: IndexedSourceEvent,\n\tentry: SessionSourceEntry,\n\tdepth: number | null,\n): void {\n\tconst parent =\n\t\titem.parentId === null\n\t\t\t? undefined\n\t\t\t: (contextParent.get(sessionId, item.parentId) as (ContextState & BootstrapColumns) | undefined);\n\tif (depth !== null && item.parentId !== null && parent?.visible_count == null)\n\t\tthrow new Error(\"Context ancestry metadata is incomplete\");\n\t// Match buildSessionContext before provider filtering: !! bash/UI-only messages remain ordering barriers.\n\tconst visible =\n\t\tentry.type === \"message\" ||\n\t\tentry.type === \"custom_message\" ||\n\t\t(entry.type === \"branch_summary\" && !!entry.summary);\n\tconst head = parent?.visible_head ?? null;\n\tconst count = depth === null ? null : Number(parent?.visible_count ?? 0) + (visible ? 1 : 0);\n\tconst compaction = entry.type === \"compaction\";\n\tconst firstKept =\n\t\tcompaction &&\n\t\ttypeof entry.firstKeptEntryId === \"string\" &&\n\t\tentry.firstKeptEntryId.length > 0 &&\n\t\tentry.firstKeptEntryId.length <= 512\n\t\t\t? entry.firstKeptEntryId\n\t\t\t: null;\n\tconst message = entry.message as { role?: unknown; stopReason?: unknown } | null;\n\tconst modelProducer = entry.type === \"model_change\" || (entry.type === \"message\" && message?.role === \"assistant\");\n\tconst contextUsageAssistant =\n\t\tentry.type === \"message\" &&\n\t\tmessage?.role === \"assistant\" &&\n\t\tmessage.stopReason !== \"aborted\" &&\n\t\tmessage.stopReason !== \"error\";\n\tconst eligibleGoal =\n\t\tentry.type === \"custom\" &&\n\t\tentry.customType === GOAL_STATE_CUSTOM_TYPE &&\n\t\titem.retention !== \"retained-import\" &&\n\t\tisPersistedGoalState(entry.data);\n\tconst eligibleRlmMaxDepth =\n\t\tentry.type === \"custom\" && entry.customType === \"rlm_max_depth_state\" && isPersistedRlmMaxDepthState(entry.data);\n\tconst seedControl =\n\t\tentry.type === \"model_change\" || entry.type === \"thinking_level_change\" || entry.type === \"service_tier_change\";\n\t// A manifest ref exists for a message envelope even when its message value is falsy.\n\tconst hasSessionMessage = entry.type === \"message\" ? !!entry.message : visible;\n\tinsertContextNode.run(\n\t\tsessionId,\n\t\titem.id,\n\t\tvisible ? item.id : head,\n\t\tvisible ? head : null,\n\t\tcount,\n\t\tcompaction ? item.id : (parent?.latest_compaction ?? null),\n\t\tfirstKept,\n\t\tmodelProducer ? item.id : (parent?.latest_model ?? null),\n\t\tentry.type === \"thinking_level_change\" ? item.id : (parent?.latest_thinking ?? null),\n\t\tentry.type === \"service_tier_change\" ? item.id : (parent?.latest_service_tier ?? null),\n\t\teligibleGoal ? item.id : (parent?.latest_goal ?? null),\n\t\tparent?.has_session_message === 1 || hasSessionMessage ? 1 : 0,\n\t\tseedControl && (item.parentId === null || parent?.goal_seedable === 1) ? 1 : 0,\n\t\teligibleRlmMaxDepth ? item.id : (parent?.latest_rlm_max_depth ?? null),\n\t\tparent?.has_branch_message === 1 || entry.type === \"message\" ? 1 : 0,\n\t\tcompaction ? null : contextUsageAssistant ? item.id : (parent?.context_usage_assistant ?? null),\n\t\tentry.type === \"git_state\" ? item.id : (parent?.latest_git_state ?? null),\n\t\tentry.type === \"agent_status\" ? item.id : (parent?.latest_agent_status ?? null),\n\t);\n}\n// Only bounded relation keys and source refs live here; never usage or sent-message bodies.\nconst MAX_CONTEXT_UPDATE_KEY = 8192;\nconst MAX_CONTEXT_UPDATE_CANDIDATES = 128;\nconst insertUpdate = db.prepare(\"INSERT INTO context_update VALUES (?,?,?,?,?)\");\nfunction insertContextUpdates(sessionId: string, item: IndexedSourceEvent, entry: SessionSourceEntry): void {\n\tif (entry.type === \"message\" && (entry.message as { role?: unknown } | null)?.role === \"assistant\") {\n\t\tinsertUpdate.run(sessionId, item.id, \"assistant-target\", item.id, item.sequence);\n\t} else if (\n\t\tentry.type === \"child_usage_attributed\" &&\n\t\ttypeof entry.targetId === \"string\" &&\n\t\tentry.targetId.length <= 512\n\t) {\n\t\t// The source aggregate is intentionally not validated or replaced by an older value.\n\t\tinsertUpdate.run(sessionId, item.id, \"assistant-usage\", entry.targetId, item.sequence);\n\t} else if (entry.type === \"label\" && typeof entry.targetId === \"string\" && entry.targetId.length <= 512) {\n\t\tinsertUpdate.run(sessionId, item.id, \"label\", entry.targetId, item.sequence);\n\t} else if (entry.type === \"custom\" && entry.customType === IPYTHON_SENT_AGENT_MESSAGE_CUSTOM_ENTRY) {\n\t\tconst parsed = parsePersistedIpythonSentAgentMessage(entry.data);\n\t\tif (parsed && parsed.toolCallId.length <= MAX_CONTEXT_UPDATE_KEY) {\n\t\t\tinsertUpdate.run(sessionId, item.id, \"ipython-sent-message\", parsed.toolCallId, item.sequence);\n\t\t\tif (parsed.message.id.length <= MAX_CONTEXT_UPDATE_KEY)\n\t\t\t\tinsertUpdate.run(\n\t\t\t\t\tsessionId,\n\t\t\t\t\titem.id,\n\t\t\t\t\t\"ipython-sent-message-id\",\n\t\t\t\t\tJSON.stringify([parsed.toolCallId, parsed.message.id]),\n\t\t\t\t\titem.sequence,\n\t\t\t\t);\n\t\t}\n\t}\n}\n\nfunction clearSession(sessionId: string): void {\n\tfor (const table of DERIVED_TABLES) db.prepare(`DELETE FROM ${table} WHERE session=?`).run(sessionId);\n}\ninterface SourceBootstrapColumns {\n\tsource_leaf: string | null;\n\tsource_session_info: string | null;\n\tsource_session_state: string | null;\n\tsource_compaction_count: number;\n\tsource_content_prefix: number;\n\tsource_has_user_content: number;\n}\nconst SOURCE_CONTENT_TYPES = new Set([\n\t\"message\",\n\t\"custom_message\",\n\t\"custom\",\n\t\"model_change\",\n\t\"thinking_level_change\",\n\t\"service_tier_change\",\n\t\"session_info\",\n\t\"label\",\n\t\"compaction\",\n\t\"branch_summary\",\n\t\"tool_intent\",\n\t\"request\",\n]);\nconst SOURCE_CREATION_PREFIX = [\"model_change\", \"thinking_level_change\", \"service_tier_change\"];\nfunction foldSourceBootstrap(state: SourceBootstrapColumns, entry: SessionSourceEntry): void {\n\tif (entry.type === \"session\") return;\n\tif (entry.type !== \"request\") state.source_leaf = entry.id;\n\tif (entry.type === \"session_info\") state.source_session_info = entry.id;\n\tif (entry.type === \"compaction\") state.source_compaction_count++;\n\tif (entry.type === \"session_state\") {\n\t\tconst status = (entry.state as { status?: unknown } | null)?.status;\n\t\tif (\n\t\t\tstatus === \"active\" ||\n\t\t\tstatus === \"archived\" ||\n\t\t\tstatus === \"crash\" ||\n\t\t\tstatus === \"hidden\" ||\n\t\t\tstatus === \"sleep\"\n\t\t)\n\t\t\tstate.source_session_state = entry.id;\n\t}\n\tif (state.source_has_user_content === 0 && SOURCE_CONTENT_TYPES.has(entry.type)) {\n\t\twhile (\n\t\t\tstate.source_content_prefix < SOURCE_CREATION_PREFIX.length &&\n\t\t\tentry.type !== SOURCE_CREATION_PREFIX[state.source_content_prefix]\n\t\t)\n\t\t\tstate.source_content_prefix++;\n\t\tif (state.source_content_prefix < SOURCE_CREATION_PREFIX.length) state.source_content_prefix++;\n\t\telse state.source_has_user_content = 1;\n\t}\n}\n\n/** Numeric derived metadata only, in canonical source order; no message bodies. */\nfunction catalogUsage(value: Usage): string {\n\tlet usage: Usage;\n\ttry {\n\t\tusage = cloneUsage(value);\n\t} catch (error) {\n\t\tif (error instanceof TypeError) throw new CatalogProjectionUnsupportedError(\"Missing catalog usage fields\");\n\t\tthrow error;\n\t}\n\tconst values = [\n\t\tusage.input,\n\t\tusage.output,\n\t\tusage.cacheRead,\n\t\tusage.cacheWrite,\n\t\tusage.totalTokens,\n\t\tusage.cost.input,\n\t\tusage.cost.output,\n\t\tusage.cost.cacheRead,\n\t\tusage.cost.cacheWrite,\n\t\tusage.cost.total,\n\t];\n\tif (values.some((part) => typeof part !== \"number\" || !Number.isFinite(part)))\n\t\tthrow new CatalogProjectionUnsupportedError(\"Non-finite or incomplete catalog usage is unsupported\");\n\treturn stringifyBoundedJson(usage, 4096);\n}\nfunction foldCatalogUsage(sessionId: string, entry: FileEntry, sequence: number): boolean {\n\tconst insert = (category: number, value: Usage) =>\n\t\tdb\n\t\t\t.prepare(\"INSERT INTO source_catalog_usage VALUES (?,?,?,?,?)\")\n\t\t\t.run(sessionId, category, entry.id, sequence, catalogUsage(value));\n\tif (entry.type === \"message\" && entry.message?.role === \"assistant\" && (entry.message as { usage?: Usage }).usage)\n\t\tinsert(0, (entry.message as { usage: Usage }).usage);\n\telse if ((entry.type === \"compaction\" || entry.type === \"branch_summary\") && entry.usage) insert(1, entry.usage);\n\telse if (entry.type === \"child_usage_attributed\") {\n\t\tconst prior = db\n\t\t\t.prepare(\"SELECT usage FROM source_catalog_usage WHERE session=? AND category=0 AND id=?\")\n\t\t\t.get(sessionId, entry.targetId);\n\t\tif (!prior) return false; // Same source-order target eligibility as the original fold.\n\t\tconst aggregate = catalogUsage(entry.aggregateUsage);\n\t\tconst child = catalogUsage(entry.childUsage);\n\t\tdb.prepare(\"UPDATE source_catalog_usage SET usage=? WHERE session=? AND category=0 AND id=?\").run(\n\t\t\taggregate,\n\t\t\tsessionId,\n\t\t\tentry.targetId,\n\t\t);\n\t\tdb.prepare(\"INSERT INTO source_catalog_usage VALUES (?,?,?,?,?)\").run(sessionId, 2, entry.id, sequence, child);\n\t} else return false;\n\treturn true;\n}\nfunction catalogUsageTotal(sessionId: string) {\n\tconst total = emptyUsage();\n\tconst page = db.prepare(\n\t\t\"SELECT sequence,usage FROM source_catalog_usage WHERE session=? AND category=? AND sequence>? ORDER BY sequence LIMIT 128\",\n\t);\n\t// Preserve assistant insertion order, then summaries, then ordered clamped\n\t// child subtraction. Incremental replacement never subtracts a stale aggregate.\n\tfor (const category of [0, 1, 2]) {\n\t\tlet after = 0;\n\t\tfor (;;) {\n\t\t\tconst rows = page.all(sessionId, category, after);\n\t\t\tif (!rows.length) break;\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst usage = JSON.parse(String(row.usage)) as Usage;\n\t\t\t\tif (category === 2) subtractAssistantUsage(total, usage);\n\t\t\t\telse addAssistantUsage(total, usage);\n\t\t\t\tafter = Number(row.sequence);\n\t\t\t}\n\t\t}\n\t}\n\tcatalogUsage(total); // Unsupported arithmetic is never persisted as JSON null/zero.\n\tconst summary = sessionUsageSummaryFrom(total);\n\tif (summary && ![summary.inputTokens, summary.outputTokens, summary.cost].every(Number.isFinite))\n\t\tthrow new CatalogProjectionUnsupportedError(\"Catalog usage total is not finite\");\n\treturn summary;\n}\n\nasync function syncSource(sessionId: string, snapshot: SessionJournalState) {\n\tconst row = db.prepare(\"SELECT * FROM source_cursor WHERE session=?\").get(sessionId);\n\tlet previous: SourceIndexCursor | undefined = row\n\t\t? {\n\t\t\t\tfrontier: JSON.parse(String(row.frontier)),\n\t\t\t\theaderByteLength: Number(row.header_bytes),\n\t\t\t\theaderChecksum: String(row.header_checksum),\n\t\t\t}\n\t\t: undefined;\n\tif (\n\t\tprevious &&\n\t\t(previous.frontier.journalPath !== snapshot.journalPath ||\n\t\t\tprevious.frontier.dev !== snapshot.dev ||\n\t\t\tprevious.frontier.ino !== snapshot.ino ||\n\t\t\tprevious.frontier.byteLength > snapshot.byteLength ||\n\t\t\tprevious.frontier.nextSequence > snapshot.nextSequence)\n\t)\n\t\tprevious = undefined;\n\tconst sourceState: SourceBootstrapColumns = previous\n\t\t? ({ ...row } as unknown as SourceBootstrapColumns)\n\t\t: {\n\t\t\t\tsource_leaf: null,\n\t\t\t\tsource_session_info: null,\n\t\t\t\tsource_session_state: null,\n\t\t\t\tsource_compaction_count: 0,\n\t\t\t\tsource_content_prefix: 0,\n\t\t\t\tsource_has_user_content: 0,\n\t\t\t};\n\tlet usageChanged = !previous;\n\tconst catalog: SessionCatalogProjection = previous\n\t\t? decodeSessionCatalog(JSON.parse(String(row?.catalog_summary)))\n\t\t: emptySessionCatalog();\n\tdb.exec(\"BEGIN IMMEDIATE\");\n\ttry {\n\t\tif (!previous) clearSession(sessionId);\n\t\tconst indexed = await readSessionSource(\n\t\t\tsessionId,\n\t\t\tsnapshot,\n\t\t\tprevious,\n\t\t\t(entry, sequence, locator, revision, parts, retention, qualification, json) => {\n\t\t\t\tfoldSourceBootstrap(sourceState, entry);\n\t\t\t\tif (!catalog.unsupported) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (json === undefined) throw new Error(\"Catalog source JSON is unavailable\");\n\t\t\t\t\t\t// The source envelope type retains the full canonical payload's fields.\n\t\t\t\t\t\tconst catalogEntry = entry as SessionSourceEntry & FileEntry;\n\t\t\t\t\t\tif (foldCatalogUsage(sessionId, catalogEntry, sequence)) usageChanged = true;\n\t\t\t\t\t\tfoldSessionCatalog(catalog, catalogEntry, json);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!(error instanceof CatalogProjectionUnsupportedError)) throw error;\n\t\t\t\t\t\tcatalog.unsupported = error.message;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst item = projectSessionSourceEvent(entry, sequence, locator, revision);\n\t\t\t\tif (retention !== undefined) item.retention = retention;\n\t\t\t\tif (qualification !== undefined) item.qualification = qualification;\n\t\t\t\tinsertEvent(sessionId, item);\n\t\t\t\tconst depth = insertAncestry(sessionId, item);\n\t\t\t\tinsertContext(sessionId, item, entry, depth);\n\t\t\t\tinsertContextUpdates(sessionId, item, entry);\n\t\t\t\tdb.prepare(\"INSERT INTO source_payload VALUES (?,?,?)\").run(sessionId, sequence, JSON.stringify(parts));\n\t\t\t\tconst source = { sessionId, sequence, entry, locator, revision, retention, qualification };\n\t\t\t\tconst imported = getTaskStateImportCoverage(source);\n\t\t\t\tif (imported)\n\t\t\t\t\tdb.prepare(\"INSERT INTO task_import_loss VALUES (?,?,?)\").run(\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tsequence,\n\t\t\t\t\t\timported.taskKey ?? null,\n\t\t\t\t\t);\n\t\t\t\tlet ordinal = 0;\n\t\t\t\tfor (const projection of projectTaskStateSource(source)) {\n\t\t\t\t\tlet payload: string | null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tpayload = stringifyBoundedJson(projection, TASK_PAGE_BYTES);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!(error instanceof Error) || error.message !== \"JSON byte limit exceeded\") throw error;\n\t\t\t\t\t\t// The original canonical field is recoverable; never clip its item or text.\n\t\t\t\t\t\tpayload = null;\n\t\t\t\t\t}\n\t\t\t\t\tdb.prepare(\"INSERT INTO task_evidence VALUES (?,?,?,?,?,?,?)\").run(\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tsequence,\n\t\t\t\t\t\tordinal++,\n\t\t\t\t\t\tprojection.taskKey ?? null,\n\t\t\t\t\t\tprojection.itemId ?? null,\n\t\t\t\t\t\tJSON.stringify(projection.source),\n\t\t\t\t\t\tpayload,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t\tif (usageChanged && !catalog.unsupported) {\n\t\t\ttry {\n\t\t\t\tcatalog.usage = catalogUsageTotal(sessionId);\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof CatalogProjectionUnsupportedError)) throw error;\n\t\t\t\tcatalog.unsupported = error.message;\n\t\t\t}\n\t\t}\n\t\tdb.prepare(\"INSERT INTO coverage VALUES (?,?) ON CONFLICT(session) DO UPDATE SET sequence=excluded.sequence\").run(\n\t\t\tsessionId,\n\t\t\tindexed.frontier.indexedThrough,\n\t\t);\n\t\tdb.prepare(\n\t\t\t\"INSERT INTO source_cursor VALUES (?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(session) DO UPDATE SET frontier=excluded.frontier,header_bytes=excluded.header_bytes,header_checksum=excluded.header_checksum,source_leaf=excluded.source_leaf,source_session_info=excluded.source_session_info,source_session_state=excluded.source_session_state,source_compaction_count=excluded.source_compaction_count,source_content_prefix=excluded.source_content_prefix,source_has_user_content=excluded.source_has_user_content,catalog_summary=excluded.catalog_summary\",\n\t\t).run(\n\t\t\tsessionId,\n\t\t\tJSON.stringify(indexed.frontier),\n\t\t\tindexed.headerByteLength,\n\t\t\tindexed.headerChecksum,\n\t\t\tsourceState.source_leaf,\n\t\t\tsourceState.source_session_info,\n\t\t\tsourceState.source_session_state,\n\t\t\tsourceState.source_compaction_count,\n\t\t\tsourceState.source_content_prefix,\n\t\t\tsourceState.source_has_user_content,\n\t\t\tstringifyBoundedJson(catalog, TASK_PAGE_BYTES),\n\t\t);\n\t\tdb.exec(\"COMMIT\");\n\t\treturn indexed.frontier;\n\t} catch (error) {\n\t\ttry {\n\t\t\tdb.exec(\"ROLLBACK\");\n\t\t} catch {\n\t\t\t/* Preserve the failed derived-index operation. */\n\t\t}\n\t\tthrow error;\n\t}\n}\nfunction apply(sessionId: string, events: IndexedSourceEvent[], committedThrough: number): void {\n\tif (events.length > 128 || !Number.isSafeInteger(committedThrough) || committedThrough < 0)\n\t\tthrow new Error(\"Invalid bounded index batch\");\n\ttransaction(() => {\n\t\tdb.prepare(\"DELETE FROM source_cursor WHERE session=?\").run(sessionId);\n\t\tdb.prepare(\"DELETE FROM source_ancestry WHERE session=?\").run(sessionId);\n\t\tdb.prepare(\"DELETE FROM source_jump WHERE session=?\").run(sessionId);\n\t\tdb.prepare(\"DELETE FROM context_node WHERE session=?\").run(sessionId);\n\t\tdb.prepare(\"DELETE FROM context_update WHERE session=?\").run(sessionId);\n\t\tconst current = db.prepare(\"SELECT sequence FROM coverage WHERE session=?\").get(sessionId)?.sequence ?? 0;\n\t\tif (committedThrough < Number(current)) throw new Error(\"Index coverage cannot move backwards\");\n\t\tlet expected = Number(current) + 1;\n\t\tfor (const item of events) {\n\t\t\tif (Buffer.byteLength(item.text) > 8192 || Buffer.byteLength(JSON.stringify(item.locator)) > 8192)\n\t\t\t\tthrow new Error(\"Index text/locator limit exceeded; use bounded source parts\");\n\t\t\tif (!Number.isSafeInteger(item.sequence) || item.sequence <= 0 || item.sequence > committedThrough)\n\t\t\t\tthrow new Error(\"Invalid committed source sequence\");\n\t\t\tconst existing = db\n\t\t\t\t.prepare(\"SELECT revision,sequence FROM source_event WHERE session=? AND id=?\")\n\t\t\t\t.get(sessionId, item.id);\n\t\t\tif (existing) {\n\t\t\t\tif (existing.revision !== item.revision || existing.sequence !== item.sequence)\n\t\t\t\t\tthrow new Error(\"Conflicting immutable source identity\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (item.sequence !== expected) throw new Error(\"Missing source sequence before index publication\");\n\t\t\texpected++;\n\t\t\t// Metadata-only apply cannot mint canonical producer qualification.\n\t\t\tinsertEvent(sessionId, { ...item, qualification: undefined });\n\t\t}\n\t\tif (expected - 1 !== committedThrough) throw new Error(\"Index cannot advertise unindexed source coverage\");\n\t\tdb.prepare(\"INSERT INTO coverage VALUES (?,?) ON CONFLICT(session) DO UPDATE SET sequence=excluded.sequence\").run(\n\t\t\tsessionId,\n\t\t\tcommittedThrough,\n\t\t);\n\t});\n}\ntype BranchNode = Pick<Row, \"id\" | \"parent_id\"> & { depth: number | null };\nconst branchNode = db.prepare(\n\t\"SELECT e.id,e.parent_id,a.depth FROM source_event e LEFT JOIN source_ancestry a ON a.session=e.session AND a.id=e.id WHERE e.session=? AND e.id=? AND e.sequence<=?\",\n);\nfunction validateBranchScope(\n\tsessionId: string,\n\tthrough: number,\n\tscope: { leafId: string | null },\n): BranchNode | undefined {\n\tif (\n\t\t!(scope.leafId === null || (typeof scope.leafId === \"string\" && scope.leafId.length <= 512)) ||\n\t\t!Number.isSafeInteger(through) ||\n\t\tthrough < 0\n\t)\n\t\tthrow new Error(\"Invalid history branch scope\");\n\tconst leaf =\n\t\tscope.leafId === null ? undefined : (branchNode.get(sessionId, scope.leafId, through) as BranchNode | undefined);\n\tif (scope.leafId !== null && !leaf) throw new Error(\"History branch leaf is outside the indexed prefix\");\n\treturn leaf;\n}\nfunction resolvedAncestor(sessionId: string, leaf: BranchNode, target: BranchNode): boolean {\n\tlet difference = leaf.depth! - target.depth!;\n\tif (difference < 0) return false;\n\tlet ancestorId = leaf.id;\n\tfor (let level = 0; difference > 0 && level < MAX_JUMP_LEVELS; level++) {\n\t\tif (difference % 2 === 1) {\n\t\t\tconst jump = ancestorJump.get(sessionId, ancestorId, level);\n\t\t\tif (!jump) throw new Error(\"History branch ancestry metadata is incomplete\");\n\t\t\tancestorId = String(jump.ancestor_id);\n\t\t}\n\t\tdifference = Math.floor(difference / 2);\n\t}\n\treturn ancestorId === target.id;\n}\nfunction pointEvent(\n\tsessionId: string,\n\teventId: string,\n\tscope?: { leafId: string | null; through: number },\n): Row | undefined {\n\tif (!scope)\n\t\treturn db.prepare(\"SELECT * FROM source_event WHERE session=? AND id=?\").get(sessionId, eventId) as\n\t\t\t| Row\n\t\t\t| undefined;\n\tconst leaf = validateBranchScope(sessionId, scope.through, scope);\n\tconst row = db\n\t\t.prepare(\"SELECT * FROM source_event WHERE session=? AND id=? AND sequence<=?\")\n\t\t.get(sessionId, eventId, scope.through) as Row | undefined;\n\tif (!row || !leaf) return undefined;\n\tconst targets = row.kind === \"request\" && row.parent_id !== null ? [row.id, row.parent_id] : [row.id];\n\tif (targets.includes(leaf.id)) return row;\n\tif (leaf.depth !== null) {\n\t\tlet unknown = false;\n\t\tfor (const id of targets) {\n\t\t\tconst target = branchNode.get(sessionId, id, scope.through) as BranchNode | undefined;\n\t\t\tif (target?.depth == null) unknown = true;\n\t\t\telse if (resolvedAncestor(sessionId, leaf, target)) return row;\n\t\t}\n\t\tif (!unknown) return undefined;\n\t}\n\t// Arbitrary SDK/legacy links stay intact; unknown ancestry is never reported as absence.\n\tconst visited = new Set<string>();\n\tlet current = leaf;\n\tlet lookups = 0;\n\tfor (;;) {\n\t\tif (targets.includes(current.id)) return row;\n\t\tvisited.add(current.id);\n\t\tif (current.parent_id === null) return undefined;\n\t\tif (visited.has(current.parent_id)) throw new Error(\"History branch ancestry contains a cycle\");\n\t\tif (lookups === MAX_PARENT_LOOKUPS) throw new Error(\"History branch ancestry parent lookup budget exceeded\");\n\t\tlookups++;\n\t\tconst parent = branchNode.get(sessionId, current.parent_id, scope.through) as BranchNode | undefined;\n\t\tif (!parent) throw new Error(\"History branch ancestry has a missing parent in the indexed prefix\");\n\t\tcurrent = parent;\n\t}\n}\ntype QueryCandidate = Pick<Row, \"id\" | \"parent_id\" | \"kind\" | \"sequence\">;\nconst MAX_QUERY_CANDIDATES = 256;\nconst queryCandidate = db.prepare(\"SELECT id,parent_id,kind,sequence FROM source_event WHERE session=? AND sequence=?\");\nfunction sourceCandidate(sessionId: string, sequence: number): QueryCandidate {\n\tconst row = queryCandidate.get(sessionId, sequence) as QueryCandidate | undefined;\n\tif (!row) throw new Error(\"History query source metadata is unavailable\");\n\treturn row;\n}\nfunction branchFilter(sessionId: string, through: number, scope?: { leafId: string | null }) {\n\tif (!scope) return { empty: false, matches: (_row: QueryCandidate) => true };\n\tconst leaf = validateBranchScope(sessionId, through, scope);\n\tif (!leaf) return { empty: true, matches: (_row: QueryCandidate) => false };\n\tif (leaf.depth !== null)\n\t\treturn {\n\t\t\tempty: false,\n\t\t\tmatches: (row: QueryCandidate) => pointEvent(sessionId, row.id, { ...scope, through }) !== undefined,\n\t\t};\n\t// A short arbitrary SDK/apply branch can be proved, but an unfinished walk is never empty ancestry.\n\tconst ancestors = new Set<string>([leaf.id]);\n\tlet current = leaf;\n\tlet lookups = 0;\n\twhile (current.parent_id !== null) {\n\t\tif (ancestors.has(current.parent_id)) throw new Error(\"History branch ancestry contains a cycle\");\n\t\tif (lookups++ === MAX_PARENT_LOOKUPS) throw new Error(\"History branch ancestry parent lookup budget exceeded\");\n\t\tconst parent = branchNode.get(sessionId, current.parent_id, through) as BranchNode | undefined;\n\t\tif (!parent) throw new Error(\"History branch ancestry has a missing parent in the indexed prefix\");\n\t\tancestors.add(parent.id);\n\t\tcurrent = parent;\n\t}\n\treturn {\n\t\tempty: false,\n\t\tmatches: (row: QueryCandidate) =>\n\t\t\tancestors.has(row.id) || (row.kind === \"request\" && row.parent_id !== null && ancestors.has(row.parent_id)),\n\t};\n}\nfunction selectCandidates<T>(\n\trows: T[],\n\tmatches: (row: T) => boolean,\n\tlimit: number,\n\tlabel: string,\n\tbudget = { remaining: MAX_QUERY_CANDIDATES },\n): T[] {\n\tconst selected: T[] = [];\n\tfor (const row of rows) {\n\t\tif (budget.remaining === 0) throw new Error(`${label} candidate budget exceeded`);\n\t\tbudget.remaining--;\n\t\tif (matches(row)) selected.push(row);\n\t\tif (selected.length === limit + 1) break;\n\t}\n\treturn selected;\n}\nfunction query(request: Extract<HistoryIndexRequest, { action: \"page\" | \"search\" }>) {\n\tif (!Number.isSafeInteger(request.limit) || request.limit < 1 || request.limit > 128)\n\t\tthrow new Error(\"Index page limit must be between1 and128\");\n\tif (\n\t\t!Number.isSafeInteger(request.through) ||\n\t\trequest.through < 0 ||\n\t\t(request.action === \"page\" && (!Number.isSafeInteger(request.after) || request.after < 0))\n\t)\n\t\tthrow new Error(\"Invalid history query source range\");\n\tconst indexedThrough = Number(\n\t\tdb.prepare(\"SELECT sequence FROM coverage WHERE session=?\").get(request.sessionId)?.sequence ?? 0,\n\t);\n\tconst branch = branchFilter(request.sessionId, request.through, request.scope);\n\tlet rows: QueryCandidate[];\n\tif (request.action === \"page\") {\n\t\tconst candidates = branch.empty\n\t\t\t? []\n\t\t\t: (db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"SELECT id,parent_id,kind,sequence FROM source_event INDEXED BY sqlite_autoindex_source_event_2 WHERE session=? AND sequence>? AND sequence<=? ORDER BY sequence LIMIT ?\",\n\t\t\t\t\t)\n\t\t\t\t\t.all(request.sessionId, request.after, request.through, MAX_QUERY_CANDIDATES + 1) as QueryCandidate[]);\n\t\trows = selectCandidates(candidates, branch.matches, request.limit, \"History page selection\");\n\t} else {\n\t\tif (Buffer.byteLength(request.query) > 8192) throw new Error(\"Index query limit exceeded\");\n\t\tconst queryTerms = terms(request.query);\n\t\tif (queryTerms.length > 32) throw new Error(\"Index query term limit exceeded\");\n\t\tconst queryTermCount = db.prepare(\"SELECT count FROM term_count WHERE session=? AND term=?\");\n\t\tconst counted = queryTerms.map((term) => ({\n\t\t\tterm,\n\t\t\tcount: Number(queryTermCount.get(request.sessionId, term)?.count ?? 0),\n\t\t}));\n\t\tcounted.sort((left, right) => left.count - right.count);\n\t\tconst [first, ...rest] = counted.map(({ term }) => term);\n\t\tconst postings =\n\t\t\tfirst && !branch.empty\n\t\t\t\t? db\n\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\"SELECT sequence FROM source_term INDEXED BY sqlite_autoindex_source_term_1 WHERE session=? AND term=? AND sequence<=? ORDER BY sequence DESC LIMIT ?\",\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.all(request.sessionId, first, request.through, MAX_QUERY_CANDIDATES + 1)\n\t\t\t\t: [];\n\t\tconst requiredTerm = db.prepare(\"SELECT 1 FROM source_term WHERE session=? AND term=? AND sequence=?\");\n\t\tconst selected = selectCandidates(\n\t\t\tpostings,\n\t\t\t(posting) => {\n\t\t\t\tconst sequence = Number(posting.sequence);\n\t\t\t\treturn (\n\t\t\t\t\trest.every((term) => !!requiredTerm.get(request.sessionId, term, sequence)) &&\n\t\t\t\t\tbranch.matches(sourceCandidate(request.sessionId, sequence))\n\t\t\t\t);\n\t\t\t},\n\t\t\trequest.limit,\n\t\t\t\"History search selection\",\n\t\t);\n\t\trows = selected.map((posting) => sourceCandidate(request.sessionId, Number(posting.sequence)));\n\t}\n\tlet incompleteText = false;\n\tif (request.action === \"search\" && !branch.empty) {\n\t\tconst candidates = db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT id,parent_id,kind,sequence FROM source_event INDEXED BY source_incomplete WHERE session=? AND text_complete=0 AND sequence<=? ORDER BY sequence LIMIT ?\",\n\t\t\t)\n\t\t\t.all(request.sessionId, request.through, MAX_QUERY_CANDIDATES + 1) as QueryCandidate[];\n\t\tincompleteText = selectCandidates(candidates, branch.matches, 0, \"History search coverage\").length > 0;\n\t}\n\tconst events: IndexedSourceEvent[] = [];\n\tlet bytes = 0;\n\tconst content = db.prepare(\"SELECT * FROM source_event WHERE session=? AND sequence=?\");\n\tfor (const row of rows.slice(0, request.limit)) {\n\t\tconst indexed = event(content.get(request.sessionId, row.sequence) as Row);\n\t\tbytes += Buffer.byteLength(JSON.stringify(indexed));\n\t\tif (bytes > 1024 * 1024) break;\n\t\tevents.push(indexed);\n\t}\n\tconst truncated = events.length < rows.length;\n\treturn {\n\t\tevents,\n\t\tindexedThrough,\n\t\tcoverage: indexedThrough < request.through || incompleteText ? \"partial\" : \"complete\",\n\t\ttruncated,\n\t\tnextAfter: request.action === \"page\" && truncated ? (events[events.length - 1]?.sequence ?? request.after) : null,\n\t};\n}\nfunction taskEvidence(request: Extract<HistoryIndexRequest, { action: \"task_evidence\" }>): TaskEvidencePage {\n\tconst { sessionId, scope, options } = request;\n\tconst limit = options.limit ?? 64;\n\tconst after = options.after ?? { sequence: 0, ordinal: -1 };\n\tif (\n\t\t!Number.isSafeInteger(limit) ||\n\t\tlimit < 1 ||\n\t\tlimit > 128 ||\n\t\t!Number.isSafeInteger(after.sequence) ||\n\t\tafter.sequence < 0 ||\n\t\t!Number.isSafeInteger(after.ordinal) ||\n\t\tafter.ordinal < -1 ||\n\t\t(options.itemId !== undefined && typeof options.itemId !== \"string\") ||\n\t\t(options.taskKey !== undefined && typeof options.taskKey !== \"string\")\n\t)\n\t\tthrow new Error(\"Invalid bounded task-evidence selection\");\n\tconst cursor = db.prepare(\"SELECT frontier FROM source_cursor WHERE session=?\").get(sessionId);\n\tconst page: TaskEvidencePage = {\n\t\tentries: [],\n\t\tindexedThrough: cursor ? Number(JSON.parse(String(cursor.frontier)).indexedThrough) : 0,\n\t\tcoverage: \"partial\",\n\t\tstructuredOnly: true,\n\t\tselective: true,\n\t\ttruncated: false,\n\t\tnextAfter: null,\n\t};\n\tif (!cursor) return page;\n\tconst branch = branchFilter(sessionId, scope.through, scope);\n\tconst coverageBudget = { remaining: MAX_QUERY_CANDIDATES };\n\tconst lossKeys = options.taskKey === undefined ? [undefined] : [null, options.taskKey];\n\tlet importedLoss = false;\n\tif (!branch.empty)\n\t\tfor (const key of lossKeys) {\n\t\t\tconst keyed = key !== undefined;\n\t\t\tconst loss = db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT sequence FROM task_import_loss ${keyed ? \"INDEXED BY task_loss_key\" : \"INDEXED BY sqlite_autoindex_task_import_loss_1\"} WHERE session=? AND sequence<=?${keyed ? \" AND task_key IS ?\" : \"\"} ORDER BY sequence LIMIT ?`,\n\t\t\t\t)\n\t\t\t\t.all(sessionId, scope.through, ...(key === undefined ? [] : [key]), coverageBudget.remaining + 1);\n\t\t\tif (\n\t\t\t\tselectCandidates(\n\t\t\t\t\tloss,\n\t\t\t\t\t(row) => branch.matches(sourceCandidate(sessionId, Number(row.sequence))),\n\t\t\t\t\t0,\n\t\t\t\t\t\"Task evidence coverage\",\n\t\t\t\t\tcoverageBudget,\n\t\t\t\t).length\n\t\t\t) {\n\t\t\t\timportedLoss = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\tpage.coverage = page.indexedThrough >= scope.through && !importedLoss ? \"complete\" : \"partial\";\n\tconst task = options.taskKey === undefined ? \"\" : \" AND task_key=?\";\n\tconst item = options.itemId === undefined ? \"\" : \" AND item_id=?\";\n\tconst indexName =\n\t\toptions.taskKey !== undefined\n\t\t\t? options.itemId !== undefined\n\t\t\t\t? \"task_item\"\n\t\t\t\t: \"task_sequence\"\n\t\t\t: options.itemId !== undefined\n\t\t\t\t? \"task_item_sequence\"\n\t\t\t\t: \"sqlite_autoindex_task_evidence_1\";\n\t// Each filter shape has an ordered index seek; SQL LIMIT is before branch filtering.\n\tconst candidates = branch.empty\n\t\t? []\n\t\t: db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT sequence,ordinal FROM task_evidence INDEXED BY ${indexName} WHERE session=?${task}${item} AND (sequence,ordinal)>(?,?) AND sequence<=? ORDER BY sequence,ordinal LIMIT ?`,\n\t\t\t\t)\n\t\t\t\t.all(\n\t\t\t\t\tsessionId,\n\t\t\t\t\t...(options.taskKey === undefined ? [] : [options.taskKey]),\n\t\t\t\t\t...(options.itemId === undefined ? [] : [options.itemId]),\n\t\t\t\t\tafter.sequence,\n\t\t\t\t\tafter.ordinal,\n\t\t\t\t\tscope.through,\n\t\t\t\t\tMAX_QUERY_CANDIDATES + 1,\n\t\t\t\t);\n\tconst rows = selectCandidates(\n\t\tcandidates,\n\t\t(row) => branch.matches(sourceCandidate(sessionId, Number(row.sequence))),\n\t\tlimit,\n\t\t\"Task evidence selection\",\n\t);\n\tconst content = db.prepare(\n\t\t\"SELECT source_ref,projection FROM task_evidence WHERE session=? AND sequence=? AND ordinal=?\",\n\t);\n\tconst itemIdentity = db.prepare(\n\t\t\"SELECT CASE WHEN length(CAST(item_id AS BLOB))<=? THEN item_id END AS item_id,item_id IS NOT NULL AS has_item FROM task_evidence WHERE session=? AND sequence=? AND ordinal=?\",\n\t);\n\tconst fits = (entry: IndexedTaskEvidence, entries = page.entries) =>\n\t\tBuffer.byteLength(\n\t\t\tJSON.stringify({\n\t\t\t\t...page,\n\t\t\t\tentries: [...entries, entry],\n\t\t\t\tnextAfter: { sequence: entry.sequence, ordinal: entry.ordinal },\n\t\t\t}),\n\t\t) <= TASK_PAGE_BYTES;\n\tfor (const row of rows.slice(0, limit)) {\n\t\tconst position = { sequence: Number(row.sequence), ordinal: Number(row.ordinal) };\n\t\tconst stored = content.get(sessionId, position.sequence, position.ordinal)!;\n\t\tconst sourceReference = (): Extract<IndexedTaskEvidence, { truncated: true }> => {\n\t\t\tconst identity = itemIdentity.get(TASK_PAGE_BYTES, sessionId, position.sequence, position.ordinal)!;\n\t\t\tconst reference: Extract<IndexedTaskEvidence, { truncated: true }> = {\n\t\t\t\t...position,\n\t\t\t\tsource: JSON.parse(String(stored.source_ref)),\n\t\t\t\ttruncated: true,\n\t\t\t\t...(identity.item_id !== null\n\t\t\t\t\t? { itemId: String(identity.item_id) }\n\t\t\t\t\t: identity.has_item\n\t\t\t\t\t\t? { itemIdOmitted: true as const }\n\t\t\t\t\t\t: {}),\n\t\t\t};\n\t\t\tif (!fits(reference, []) && reference.itemId !== undefined) {\n\t\t\t\tdelete reference.itemId;\n\t\t\t\treference.itemIdOmitted = true;\n\t\t\t}\n\t\t\treturn reference;\n\t\t};\n\t\tlet entry: IndexedTaskEvidence =\n\t\t\tstored.projection === null\n\t\t\t\t? sourceReference()\n\t\t\t\t: {\n\t\t\t\t\t\t...position,\n\t\t\t\t\t\tprojection: JSON.parse(String(stored.projection)),\n\t\t\t\t\t\ttruncated: false,\n\t\t\t\t\t};\n\t\tif (!fits(entry)) {\n\t\t\tif (page.entries.length) break;\n\t\t\tentry = sourceReference();\n\t\t}\n\t\tpage.entries.push(entry);\n\t}\n\tconst more = page.entries.length < rows.length;\n\tpage.truncated = more || page.entries.some((entry) => entry.truncated);\n\tif (more && page.entries.length) {\n\t\tconst last = page.entries[page.entries.length - 1];\n\t\tpage.nextAfter = { sequence: last.sequence, ordinal: last.ordinal };\n\t}\n\treturn page;\n}\n\ntype ContextNode = BranchNode &\n\tContextState &\n\tPick<Row, \"sequence\" | \"kind\" | \"locator\" | \"revision\" | \"authority\" | \"qualification\" | \"retention\">;\nconst manifestNode =\n\tdb.prepare(`SELECT e.id,e.parent_id,e.sequence,e.kind,e.locator,e.revision,e.authority,e.qualification,e.retention,a.depth,c.visible_head,c.previous_visible,c.visible_count,c.latest_compaction,c.first_kept_id\n FROM source_event e JOIN context_node c ON c.session=e.session AND c.id=e.id\n LEFT JOIN source_ancestry a ON a.session=e.session AND a.id=e.id\n WHERE e.session=? AND e.id=? AND e.sequence<=?`);\nconst visibleJump = db.prepare(`SELECT j.ancestor_id,c.visible_count FROM source_jump j\n JOIN context_node c ON c.session=j.session AND c.id=j.ancestor_id\n WHERE j.session=? AND j.id=? AND j.level=?`);\nfunction contextRef(node: ContextNode): ContextRef {\n\treturn {\n\t\tentryId: node.id,\n\t\tsequence: node.sequence,\n\t\tauthority: node.authority,\n\t\t...(node.qualification === null ? {} : { qualification: node.qualification }),\n\t\t...(node.retention === null ? {} : { retention: node.retention }),\n\t\tkind: node.kind as ContextRef[\"kind\"],\n\t\tlocator: JSON.parse(node.locator) as ContextRef[\"locator\"],\n\t\trevision: node.revision,\n\t};\n}\nfunction parentPath(request: Extract<HistoryIndexRequest, { action: \"parent_path\" }>): ParentPathPage {\n\tconst { sessionId, scope, options } = request;\n\tconst limit = options.limit ?? 64;\n\tif (!Number.isSafeInteger(limit) || limit < 1 || limit > 128)\n\t\tthrow new Error(\"Parent path limit must be between1 and128\");\n\tconst saved = db.prepare(\"SELECT * FROM source_cursor WHERE session=?\").get(sessionId);\n\tif (!saved) throw new Error(\"Parent path index is unavailable; synchronize the source first\");\n\tconst snapshot = JSON.parse(String(saved.frontier)) as SessionJournalState & { indexedThrough: number };\n\tif (snapshot.format !== \"framed\" || snapshot.indexedThrough < scope.through)\n\t\tthrow new Error(\"Parent path index has not reached the requested source prefix\");\n\tconst leaf = validateBranchScope(sessionId, scope.through, scope);\n\tif (leaf?.depth === null) throw new Error(\"Parent path lineage is unresolved\");\n\tconst revision =\n\t\tscope.through === 0\n\t\t\t? saved.header_checksum\n\t\t\t: db.prepare(\"SELECT revision FROM source_event WHERE session=? AND sequence=?\").get(sessionId, scope.through)\n\t\t\t\t\t?.revision;\n\tif (typeof revision !== \"string\") throw new Error(\"Parent path source prefix is unavailable\");\n\tconst anchor: Omit<ParentPathCursor, \"nextDepth\"> = {\n\t\tversion: 1,\n\t\tsessionId,\n\t\tjournalPath: snapshot.journalPath,\n\t\tdev: snapshot.dev,\n\t\tino: snapshot.ino,\n\t\tleafId: scope.leafId,\n\t\tthrough: scope.through,\n\t\tthroughRevision: revision,\n\t};\n\tconst cursor = options.cursor;\n\tif (\n\t\tcursor &&\n\t\t(cursor.version !== 1 ||\n\t\t\tcursor.sessionId !== sessionId ||\n\t\t\tcursor.journalPath !== snapshot.journalPath ||\n\t\t\tcursor.dev !== snapshot.dev ||\n\t\t\tcursor.ino !== snapshot.ino ||\n\t\t\tcursor.leafId !== scope.leafId ||\n\t\t\tcursor.through !== scope.through ||\n\t\t\tcursor.throughRevision !== revision)\n\t)\n\t\tthrow new Error(\"Parent path cursor mismatch\");\n\tconst count = leaf ? leaf.depth! + 1 : 0;\n\tconst start = cursor ? cursor.nextDepth : 0;\n\tif (!Number.isSafeInteger(start) || start < 0 || start > count)\n\t\tthrow new Error(\"Invalid parent path cursor position\");\n\tconst page: ParentPathPage = { events: [], nextCursor: null, totalEntries: count };\n\tif (start === count) return page;\n\tconst end = Math.min(start + limit - 1, count - 1);\n\tlet id = leaf!.id;\n\tlet difference = leaf!.depth! - end;\n\tfor (let level = 0; difference > 0 && level < MAX_JUMP_LEVELS; level++) {\n\t\tif (difference % 2 === 1) {\n\t\t\tconst jump = ancestorJump.get(sessionId, id, level);\n\t\t\tif (!jump) throw new Error(\"Parent path ancestry metadata is incomplete\");\n\t\t\tid = String(jump.ancestor_id);\n\t\t}\n\t\tdifference = Math.floor(difference / 2);\n\t}\n\t// Reverse only this bounded page of IDs, then load metadata in chronological order.\n\tconst ids: string[] = [];\n\tfor (let depth = end; depth >= start; depth--) {\n\t\tconst node = branchNode.get(sessionId, id, scope.through) as BranchNode | undefined;\n\t\tif (!node || node.depth !== depth) throw new Error(\"Parent path ancestry metadata is incomplete\");\n\t\tids.push(node.id);\n\t\tif (depth > start) {\n\t\t\tif (node.parent_id === null) throw new Error(\"Parent path parent reference is missing\");\n\t\t\tid = node.parent_id;\n\t\t}\n\t}\n\tids.reverse();\n\tconst content = db.prepare(\"SELECT * FROM source_event WHERE session=? AND id=? AND sequence<=?\");\n\tlet bytes = Buffer.byteLength(\n\t\tJSON.stringify({ ...page, nextCursor: { ...anchor, nextDepth: Number.MAX_SAFE_INTEGER } }),\n\t);\n\tfor (const entryId of ids) {\n\t\tconst row = content.get(sessionId, entryId, scope.through) as Row | undefined;\n\t\tif (!row) throw new Error(\"Parent path source metadata is unavailable; rebuild the derived index\");\n\t\tconst item = event(row);\n\t\tconst addition = Buffer.byteLength(JSON.stringify(item)) + (page.events.length ? 1 : 0);\n\t\tif (bytes + addition > 1024 * 1024 - 1024) break;\n\t\tpage.events.push(item);\n\t\tbytes += addition;\n\t}\n\tif (page.events.length === 0) throw new Error(\"Parent path metadata exceeds the page byte limit\");\n\tconst next = start + page.events.length;\n\tpage.nextCursor = next < count ? { ...anchor, nextDepth: next } : null;\n\treturn page;\n}\nfunction ipythonSentMessages(\n\trequest: Extract<HistoryIndexRequest, { action: \"ipython_sent_messages\" }>,\n): IpythonSentMessagesPage {\n\tconst { sessionId, scope, toolCallId, options } = request;\n\tconst limit = options.limit ?? 64;\n\tif (!Number.isSafeInteger(limit) || limit < 1 || limit > 128)\n\t\tthrow new Error(\"IPython sent-message limit must be between1 and128\");\n\tif (\n\t\ttypeof toolCallId !== \"string\" ||\n\t\ttoolCallId.length > MAX_CONTEXT_UPDATE_KEY ||\n\t\t(options.messageId !== undefined &&\n\t\t\t(typeof options.messageId !== \"string\" || options.messageId.length > MAX_CONTEXT_UPDATE_KEY))\n\t)\n\t\tthrow new Error(\"IPython sent-message key limit exceeded\");\n\tconst saved = db.prepare(\"SELECT * FROM source_cursor WHERE session=?\").get(sessionId);\n\tif (!saved) throw new Error(\"IPython sent-message index is unavailable; synchronize the source first\");\n\tconst snapshot = JSON.parse(String(saved.frontier)) as SessionJournalState & { indexedThrough: number };\n\tif (snapshot.format !== \"framed\" || snapshot.indexedThrough < scope.through)\n\t\tthrow new Error(\"IPython sent-message index has not reached the requested source prefix\");\n\tconst leaf = validateBranchScope(sessionId, scope.through, scope);\n\tif (leaf?.depth === null) throw new Error(\"IPython sent-message branch lineage is unresolved\");\n\tconst revision =\n\t\tscope.through === 0\n\t\t\t? saved.header_checksum\n\t\t\t: db.prepare(\"SELECT revision FROM source_event WHERE session=? AND sequence=?\").get(sessionId, scope.through)\n\t\t\t\t\t?.revision;\n\tif (typeof revision !== \"string\") throw new Error(\"IPython sent-message source prefix is unavailable\");\n\tconst messageId = options.messageId ?? null;\n\tconst anchor: Omit<IpythonSentMessagesCursor, \"after\"> = {\n\t\tversion: 1,\n\t\tsessionId,\n\t\tjournalPath: snapshot.journalPath,\n\t\tdev: snapshot.dev,\n\t\tino: snapshot.ino,\n\t\tleafId: scope.leafId,\n\t\tthrough: scope.through,\n\t\tthroughRevision: revision,\n\t\ttoolCallId,\n\t\tmessageId,\n\t};\n\tconst cursor = options.cursor;\n\tif (\n\t\tcursor &&\n\t\t(cursor.version !== 1 ||\n\t\t\tcursor.sessionId !== sessionId ||\n\t\t\tcursor.journalPath !== snapshot.journalPath ||\n\t\t\tcursor.dev !== snapshot.dev ||\n\t\t\tcursor.ino !== snapshot.ino ||\n\t\t\tcursor.leafId !== scope.leafId ||\n\t\t\tcursor.through !== scope.through ||\n\t\t\tcursor.throughRevision !== revision ||\n\t\t\tcursor.toolCallId !== toolCallId ||\n\t\t\tcursor.messageId !== messageId)\n\t)\n\t\tthrow new Error(\"IPython sent-message cursor mismatch\");\n\tlet after = cursor ? cursor.after : 0;\n\tif (!Number.isSafeInteger(after) || after < 0 || after > scope.through)\n\t\tthrow new Error(\"Invalid IPython sent-message cursor position\");\n\tconst page: IpythonSentMessagesPage = { refs: [], nextCursor: null };\n\tif (!leaf) return page;\n\tconst kind = messageId === null ? \"ipython-sent-message\" : \"ipython-sent-message-id\";\n\tconst key = messageId === null ? toolCallId : JSON.stringify([toolCallId, messageId]);\n\tconst candidates = db\n\t\t.prepare(`SELECT event_id AS id,sequence FROM context_update\n WHERE session=? AND update_kind=? AND target_key=? AND sequence>? AND sequence<=?\n ORDER BY sequence LIMIT ?`)\n\t\t.all(sessionId, kind, key, after, scope.through, MAX_CONTEXT_UPDATE_CANDIDATES + 1) as {\n\t\tid: string;\n\t\tsequence: number;\n\t}[];\n\tlet bytes = Buffer.byteLength(\n\t\tJSON.stringify({ ...page, nextCursor: { ...anchor, after: Number.MAX_SAFE_INTEGER } }),\n\t);\n\tconst content = db.prepare(\n\t\t\"SELECT id,sequence,kind,locator,revision FROM source_event WHERE session=? AND id=? AND sequence<=?\",\n\t);\n\tfor (const candidate of candidates.slice(0, MAX_CONTEXT_UPDATE_CANDIDATES)) {\n\t\tif (page.refs.length >= limit) break;\n\t\tconst node = branchNode.get(sessionId, candidate.id, scope.through) as BranchNode | undefined;\n\t\tif (!node) throw new Error(\"IPython sent-message source metadata is unavailable\");\n\t\tif (node.depth !== null && resolvedAncestor(sessionId, leaf, node)) {\n\t\t\tconst row = content.get(sessionId, candidate.id, scope.through) as SourceRefRow | undefined;\n\t\t\tif (!row) throw new Error(\"IPython sent-message source metadata is unavailable\");\n\t\t\tconst ref = contextUpdateRef(row);\n\t\t\tconst addition = Buffer.byteLength(JSON.stringify(ref)) + (page.refs.length ? 1 : 0);\n\t\t\tif (bytes + addition > TASK_PAGE_BYTES) {\n\t\t\t\tif (page.refs.length === 0) throw new Error(\"IPython sent-message ref exceeds the page byte limit\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tpage.refs.push(ref);\n\t\t\tbytes += addition;\n\t\t}\n\t\tafter = candidate.sequence;\n\t}\n\tif (candidates.length > 0 && after < candidates[candidates.length - 1].sequence)\n\t\tpage.nextCursor = { ...anchor, after };\n\treturn page;\n}\nfunction currentSourceBootstrap(\n\trequest: Extract<HistoryIndexRequest, { action: \"current_source_bootstrap\" }>,\n): SourceBootstrapState {\n\tconst { sessionId, snapshot } = request;\n\tconst saved = db.prepare(\"SELECT * FROM source_cursor WHERE session=?\").get(sessionId);\n\tif (!saved) throw new Error(\"Current source bootstrap is unavailable; synchronize the source first\");\n\tconst current = JSON.parse(String(saved.frontier)) as SessionJournalState & { indexedThrough: number };\n\tif (\n\t\tcurrent.format !== \"framed\" ||\n\t\tsnapshot.format !== \"framed\" ||\n\t\tcurrent.journalPath !== snapshot.journalPath ||\n\t\tcurrent.dev !== snapshot.dev ||\n\t\tcurrent.ino !== snapshot.ino ||\n\t\tcurrent.byteLength !== snapshot.byteLength ||\n\t\tcurrent.nextSequence !== snapshot.nextSequence ||\n\t\tcurrent.checksum !== snapshot.checksum ||\n\t\tcurrent.indexedThrough !== snapshot.nextSequence - 1\n\t)\n\t\tthrow new Error(\"Current source bootstrap snapshot mismatch\");\n\tconst reference = (id: unknown): IndexedSourceEvent | null => {\n\t\tif (id === null) return null;\n\t\tconst row = db\n\t\t\t.prepare(\"SELECT * FROM source_event WHERE session=? AND id=? AND sequence<=?\")\n\t\t\t.get(sessionId, String(id), current.indexedThrough) as Row | undefined;\n\t\tif (!row) throw new Error(\"Current source bootstrap metadata is unavailable; rebuild the derived index\");\n\t\treturn event(row);\n\t};\n\treturn {\n\t\tleaf: reference(saved.source_leaf),\n\t\tsessionInfo: reference(saved.source_session_info),\n\t\tsessionState: reference(saved.source_session_state),\n\t\tcompactionCount: Number(saved.source_compaction_count),\n\t\tcontentPrefix: Number(saved.source_content_prefix),\n\t\thasUserContent: saved.source_has_user_content === 1,\n\t};\n}\nfunction sourceRelation(\n\trequest: Extract<HistoryIndexRequest, { action: \"source_label\" | \"source_assistant_usage\" }>,\n): IndexedSourceEvent | undefined {\n\tconst { sessionId, targetId, through } = request;\n\tif (typeof targetId !== \"string\" || targetId.length > 512) throw new Error(\"Source relation target limit exceeded\");\n\tif (!Number.isSafeInteger(through) || through < 0) throw new Error(\"Invalid history source prefix\");\n\tconst saved = db.prepare(\"SELECT frontier FROM source_cursor WHERE session=?\").get(sessionId);\n\tif (!saved) throw new Error(\"Canonical source index is unavailable; synchronize the source first\");\n\tconst snapshot = JSON.parse(String(saved.frontier)) as SessionJournalState & { indexedThrough: number };\n\tif (snapshot.format !== \"framed\" || snapshot.indexedThrough < through)\n\t\tthrow new Error(\"Canonical source index has not reached the requested source prefix\");\n\tconst kind = request.action === \"source_label\" ? \"label\" : \"assistant-usage\";\n\tconst row = db\n\t\t.prepare(`SELECT e.* FROM context_update u JOIN source_event e\n ON e.session=u.session AND e.id=u.event_id\n WHERE u.session=? AND u.update_kind=? AND u.target_key=? AND u.sequence<=?\n ORDER BY u.sequence DESC LIMIT 1`)\n\t\t.get(sessionId, kind, targetId, through) as Row | undefined;\n\treturn row ? event(row) : undefined;\n}\nfunction branchBootstrap(request: Extract<HistoryIndexRequest, { action: \"branch_bootstrap\" }>): BranchBootstrapState {\n\tconst { sessionId, scope } = request;\n\tconst saved = db.prepare(\"SELECT frontier FROM source_cursor WHERE session=?\").get(sessionId);\n\tif (!saved) throw new Error(\"Branch bootstrap index is unavailable; synchronize the source first\");\n\tconst snapshot = JSON.parse(String(saved.frontier)) as SessionJournalState & { indexedThrough: number };\n\tif (snapshot.format !== \"framed\" || snapshot.indexedThrough < scope.through)\n\t\tthrow new Error(\"Branch bootstrap index has not reached the requested source prefix\");\n\tconst leaf = validateBranchScope(sessionId, scope.through, scope);\n\tif (leaf?.depth === null) throw new Error(\"Branch bootstrap branch lineage is unresolved\");\n\tif (\n\t\tscope.through > 0 &&\n\t\t!db.prepare(\"SELECT 1 FROM source_event WHERE session=? AND sequence=?\").get(sessionId, scope.through)\n\t)\n\t\tthrow new Error(\"Branch bootstrap source prefix is unavailable\");\n\tconst state = leaf\n\t\t? (contextParent.get(sessionId, leaf.id) as (ContextState & BootstrapColumns) | undefined)\n\t\t: undefined;\n\tif (leaf && !state) throw new Error(\"Branch bootstrap metadata is unavailable; rebuild the derived index\");\n\tconst reference = (id: string | null | undefined): IndexedSourceEvent | null => {\n\t\tif (id == null) return null;\n\t\tconst row = db\n\t\t\t.prepare(\"SELECT * FROM source_event WHERE session=? AND id=? AND sequence<=?\")\n\t\t\t.get(sessionId, id, scope.through) as Row | undefined;\n\t\tif (!row) throw new Error(\"Branch bootstrap source metadata is unavailable; rebuild the derived index\");\n\t\treturn event(row);\n\t};\n\treturn {\n\t\tmodel: reference(state?.latest_model),\n\t\tthinkingLevel: reference(state?.latest_thinking),\n\t\tserviceTier: reference(state?.latest_service_tier),\n\t\tgoalState: reference(state?.latest_goal),\n\t\trlmMaxDepth: reference(state?.latest_rlm_max_depth),\n\t\tlatestCompaction: reference(state?.latest_compaction),\n\t\tcontextUsageAssistant: reference(state?.context_usage_assistant),\n\t\tgitState: reference(state?.latest_git_state),\n\t\tagentStatus: reference(state?.latest_agent_status),\n\t\thasBranchMessage: state?.has_branch_message === 1,\n\t\thasContextMessages: !!state && (state.has_session_message === 1 || state.latest_compaction !== null),\n\t\tgoalSeedable: !state || state.goal_seedable === 1,\n\t};\n}\nfunction contextManifest(request: Extract<HistoryIndexRequest, { action: \"context_manifest\" }>): ContextManifestPage {\n\tconst { sessionId, scope, options } = request;\n\tconst limit = options.limit ?? 64;\n\tif (!Number.isSafeInteger(limit) || limit < 1 || limit > 128)\n\t\tthrow new Error(\"Context manifest limit must be between1 and128\");\n\tconst saved = db.prepare(\"SELECT * FROM source_cursor WHERE session=?\").get(sessionId);\n\tif (!saved) throw new Error(\"Context manifest index is unavailable; synchronize the source first\");\n\tconst snapshot = JSON.parse(String(saved.frontier)) as SessionJournalState & { indexedThrough: number };\n\tif (snapshot.format !== \"framed\" || snapshot.indexedThrough < scope.through)\n\t\tthrow new Error(\"Context manifest index has not reached the requested source prefix\");\n\tvalidateBranchScope(sessionId, scope.through, scope);\n\tconst revision =\n\t\tscope.through === 0\n\t\t\t? saved.header_checksum\n\t\t\t: db.prepare(\"SELECT revision FROM source_event WHERE session=? AND sequence=?\").get(sessionId, scope.through)\n\t\t\t\t\t?.revision;\n\tif (typeof revision !== \"string\") throw new Error(\"Context manifest source prefix is unavailable\");\n\tconst anchor: Omit<ContextManifestCursor, \"nextOrdinal\"> = {\n\t\tversion: 1,\n\t\tsessionId,\n\t\tjournalPath: snapshot.journalPath,\n\t\tdev: snapshot.dev,\n\t\tino: snapshot.ino,\n\t\tleafId: scope.leafId,\n\t\tthrough: scope.through,\n\t\tthroughRevision: revision,\n\t};\n\tconst cursor = options.cursor;\n\tif (\n\t\tcursor &&\n\t\t(cursor.version !== 1 ||\n\t\t\tcursor.sessionId !== sessionId ||\n\t\t\tcursor.journalPath !== snapshot.journalPath ||\n\t\t\tcursor.dev !== snapshot.dev ||\n\t\t\tcursor.ino !== snapshot.ino ||\n\t\t\tcursor.leafId !== scope.leafId ||\n\t\t\tcursor.through !== scope.through ||\n\t\t\tcursor.throughRevision !== revision)\n\t)\n\t\tthrow new Error(\"Context manifest cursor mismatch\");\n\tif (cursor && (!Number.isSafeInteger(cursor.nextOrdinal) || cursor.nextOrdinal < 1))\n\t\tthrow new Error(\"Invalid context manifest cursor ordinal\");\n\tconst result: Extract<ContextManifestPage, { selection: \"known\" }> = {\n\t\tselection: \"known\",\n\t\tsummaryRef: null,\n\t\tactiveBase: 0,\n\t\tretainedMessageCount: 0,\n\t\tactiveMessageCount: 0,\n\t\trefs: [],\n\t\torder: \"source\",\n\t\tnextCursor: null,\n\t};\n\tconst node = (id: string): ContextNode => {\n\t\tconst value = manifestNode.get(sessionId, id, scope.through) as ContextNode | undefined;\n\t\tif (!value) throw new Error(\"Context manifest metadata is unavailable; rebuild the derived index\");\n\t\treturn value;\n\t};\n\tconst qualified = (selection: \"unresolved-lineage\" | \"invalid-first-kept\"): ContextManifestPage => ({\n\t\tselection,\n\t\tsummaryRef: result.summaryRef,\n\t\trefs: [],\n\t\torder: \"source\",\n\t\tnextCursor: null,\n\t});\n\tconst leaf = scope.leafId === null ? undefined : node(scope.leafId);\n\tif (leaf && (leaf.depth === null || leaf.visible_count === null)) return qualified(\"unresolved-lineage\");\n\tconst total = leaf?.visible_count ?? 0;\n\tif (leaf?.latest_compaction) {\n\t\tconst compaction = node(leaf.latest_compaction);\n\t\tif (compaction.kind !== \"compaction\" || compaction.depth === null || compaction.visible_count === null)\n\t\t\tthrow new Error(\"Context manifest compaction metadata is incomplete\");\n\t\tresult.summaryRef = contextRef(compaction);\n\t\tif (!compaction.first_kept_id) return qualified(\"invalid-first-kept\");\n\t\tconst first = manifestNode.get(sessionId, compaction.first_kept_id, scope.through) as ContextNode | undefined;\n\t\t// Exact parent-chain membership, never the broader evidence/request-parent scope rule.\n\t\tif (\n\t\t\t!first ||\n\t\t\tfirst.depth === null ||\n\t\t\tfirst.visible_count === null ||\n\t\t\tfirst.depth >= compaction.depth ||\n\t\t\t!resolvedAncestor(sessionId, compaction, first)\n\t\t)\n\t\t\treturn qualified(\"invalid-first-kept\");\n\t\tresult.activeBase = first.visible_count - (first.visible_head === first.id ? 1 : 0);\n\t\tresult.retainedMessageCount = compaction.visible_count - result.activeBase;\n\t}\n\tresult.activeMessageCount = total - result.activeBase;\n\tconst start = cursor?.nextOrdinal ?? result.activeBase + 1;\n\tif (start < result.activeBase + 1 || start > total + 1)\n\t\tthrow new Error(\"Context manifest cursor ordinal is outside active selection\");\n\tif (start === total + 1) return result;\n\tconst end = Math.min(start + limit - 1, total);\n\tlet seekId = leaf!.id;\n\t// Locate page END using physical ancestry jumps and monotonic visible counts, then reverse only this bounded page.\n\tfor (let level = MAX_JUMP_LEVELS - 1; level >= 0; level--) {\n\t\tconst jump = visibleJump.get(sessionId, seekId, level);\n\t\tif (jump && jump.visible_count !== null && Number(jump.visible_count) >= end) seekId = String(jump.ancestor_id);\n\t}\n\tconst seek = node(seekId);\n\tif (seek.visible_head === null) throw new Error(\"Context manifest visible metadata is incomplete\");\n\tlet current = seek.visible_head === seek.id ? seek : node(seek.visible_head);\n\tconst refs: (ContextRef & { ordinal: number })[] = [];\n\tfor (let ordinal = end; ordinal >= start; ordinal--) {\n\t\tif (current.visible_count !== ordinal || current.visible_head !== current.id)\n\t\t\tthrow new Error(\"Context manifest visible ordinal metadata is incomplete\");\n\t\trefs.push({ ...contextRef(current), ordinal });\n\t\tif (ordinal > start) {\n\t\t\tif (current.previous_visible === null) throw new Error(\"Context manifest previous visible ref is missing\");\n\t\t\tcurrent = node(current.previous_visible);\n\t\t}\n\t}\n\trefs.reverse();\n\t// Include the largest continuation envelope in the byte count; never advance over an unreturned ref.\n\tconst pageBytes = 1024 * 1024 - 1024;\n\tlet bytes = Buffer.byteLength(\n\t\tJSON.stringify({ ...result, nextCursor: { ...anchor, nextOrdinal: Number.MAX_SAFE_INTEGER } }),\n\t);\n\tfor (const ref of refs) {\n\t\tconst addition = Buffer.byteLength(JSON.stringify(ref)) + (result.refs.length ? 1 : 0);\n\t\tif (bytes + addition > pageBytes) break;\n\t\tresult.refs.push(ref);\n\t\tbytes += addition;\n\t}\n\tif (result.refs.length === 0) throw new Error(\"Context manifest metadata exceeds the page byte limit\");\n\tconst next = result.refs[result.refs.length - 1].ordinal + 1;\n\tresult.nextCursor = next <= total ? { ...anchor, nextOrdinal: next } : null;\n\treturn result;\n}\n\ntype SourceRefRow = Pick<Row, \"id\" | \"sequence\" | \"kind\" | \"locator\" | \"revision\">;\ntype ContextUpdateScope = { leafId: string | null; through: number };\nconst latestUsageUpdate = db.prepare(`SELECT e.id,e.sequence,e.kind,e.locator,e.revision FROM context_update u\n JOIN source_event e ON e.session=u.session AND e.id=u.event_id\n WHERE u.session=? AND u.update_kind='assistant-usage' AND u.target_key=? AND u.sequence<=?\n ORDER BY u.sequence DESC LIMIT 1`);\nconst ipythonUpdates = db.prepare(`SELECT e.id,e.sequence,e.kind,e.locator,e.revision FROM context_update u\n JOIN source_event e ON e.session=u.session AND e.id=u.event_id\n WHERE u.session=? AND u.update_kind='ipython-sent-message' AND u.target_key=? AND u.sequence<=?\n ORDER BY u.sequence LIMIT ?`);\nfunction contextUpdateSource(sessionId: string, scope: ContextUpdateScope) {\n\tconst saved = db.prepare(\"SELECT * FROM source_cursor WHERE session=?\").get(sessionId);\n\tif (!saved) throw new Error(\"Context update index is unavailable; synchronize the source first\");\n\tconst snapshot = JSON.parse(String(saved.frontier)) as SessionJournalState & { indexedThrough: number };\n\tif (snapshot.format !== \"framed\" || snapshot.indexedThrough < scope.through)\n\t\tthrow new Error(\"Context update index has not reached the requested source prefix\");\n\tconst leaf = validateBranchScope(sessionId, scope.through, scope);\n\tif (leaf?.depth === null) throw new Error(\"Context update branch lineage is unresolved\");\n\tif (\n\t\tscope.through > 0 &&\n\t\t!db.prepare(\"SELECT 1 FROM source_event WHERE session=? AND sequence=?\").get(sessionId, scope.through)\n\t)\n\t\tthrow new Error(\"Context update source prefix is unavailable\");\n\treturn snapshot;\n}\nfunction contextUpdateKey(sessionId: string, scope: ContextUpdateScope, target: ContextUpdateTarget): string {\n\tif (target.kind !== \"assistant-usage\" && target.kind !== \"ipython-sent-message\")\n\t\tthrow new Error(\"Invalid context update target\");\n\tconst key = target.kind === \"assistant-usage\" ? target.targetId : target.toolCallId;\n\tif (typeof key !== \"string\" || key.length > (target.kind === \"assistant-usage\" ? 512 : MAX_CONTEXT_UPDATE_KEY))\n\t\tthrow new Error(\"Context update target key limit exceeded\");\n\tif (target.kind === \"assistant-usage\") {\n\t\tconst assistant = db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT 1 FROM context_update WHERE session=? AND update_kind='assistant-target' AND target_key=? AND sequence<=?\",\n\t\t\t)\n\t\t\t.get(sessionId, key, scope.through);\n\t\tif (!assistant || !pointEvent(sessionId, key, scope))\n\t\t\tthrow new Error(\"Context update target is not an assistant message on the captured branch\");\n\t}\n\treturn key;\n}\nfunction contextUpdateRef(row: SourceRefRow): ContextUpdateRef {\n\treturn {\n\t\tentryId: row.id,\n\t\tsequence: row.sequence,\n\t\tkind: row.kind as ContextUpdateRef[\"kind\"],\n\t\tlocator: JSON.parse(row.locator) as ContextUpdateRef[\"locator\"],\n\t\trevision: row.revision,\n\t};\n}\nfunction contextUpdates(request: Extract<HistoryIndexRequest, { action: \"context_updates\" }>): ContextUpdates {\n\tconst { sessionId, scope, target } = request;\n\tcontextUpdateSource(sessionId, scope);\n\tconst key = contextUpdateKey(sessionId, scope, target);\n\tlet rows: SourceRefRow[];\n\tif (target.kind === \"assistant-usage\") {\n\t\tconst latest = latestUsageUpdate.get(sessionId, key, scope.through) as SourceRefRow | undefined;\n\t\trows = latest ? [latest] : [];\n\t} else {\n\t\trows =\n\t\t\tscope.leafId === null\n\t\t\t\t? []\n\t\t\t\t: (ipythonUpdates.all(sessionId, key, scope.through, MAX_CONTEXT_UPDATE_CANDIDATES + 1) as SourceRefRow[]);\n\t\tif (rows.length > MAX_CONTEXT_UPDATE_CANDIDATES) throw new Error(\"Context update candidate budget exceeded\");\n\t\trows = rows.filter((row) => pointEvent(sessionId, row.id, scope) !== undefined);\n\t}\n\tconst result: ContextUpdates = { refs: rows.map(contextUpdateRef), order: \"source\" };\n\ttry {\n\t\tstringifyBoundedJson(result, TASK_PAGE_BYTES);\n\t} catch (error) {\n\t\tif (!(error instanceof Error) || error.message !== \"JSON byte limit exceeded\") throw error;\n\t\tthrow new Error(\"Context update refs exceed the byte budget\");\n\t}\n\treturn result;\n}\nfunction readContextUpdatePayload(request: Extract<HistoryIndexRequest, { action: \"read_context_update_payload\" }>) {\n\tconst { sessionId, eventId, scope, target, options } = request;\n\tconst snapshot = contextUpdateSource(sessionId, scope);\n\tconst key = contextUpdateKey(sessionId, scope, target);\n\tlet row: SourceRefRow | undefined;\n\tif (target.kind === \"assistant-usage\") {\n\t\trow = latestUsageUpdate.get(sessionId, key, scope.through) as SourceRefRow | undefined;\n\t\tif (row?.id !== eventId) return undefined;\n\t} else {\n\t\tconst related = db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT 1 FROM context_update WHERE session=? AND update_kind='ipython-sent-message' AND event_id=? AND target_key=? AND sequence<=?\",\n\t\t\t)\n\t\t\t.get(sessionId, eventId, key, scope.through);\n\t\tif (!related) return undefined;\n\t\trow = pointEvent(sessionId, eventId, scope);\n\t}\n\treturn row ? readPayloadRow(sessionId, row, snapshot, options) : undefined;\n}\n\nfunction readPayload(request: Extract<HistoryIndexRequest, { action: \"read_payload\" }>) {\n\tconst saved = db.prepare(\"SELECT frontier FROM source_cursor WHERE session=?\").get(request.sessionId);\n\tif (!saved) throw new Error(\"Canonical payload index is unavailable; synchronize the source first\");\n\tconst snapshot = JSON.parse(String(saved.frontier)) as SessionJournalState & { indexedThrough: number };\n\tif (snapshot.format !== \"framed\" || snapshot.indexedThrough < request.scope.through)\n\t\tthrow new Error(\"Canonical payload index has not reached the requested source prefix\");\n\tconst row = pointEvent(request.sessionId, request.eventId, request.scope);\n\tif (!row) return undefined;\n\treturn readPayloadRow(request.sessionId, row, snapshot, request.options);\n}\nfunction selectSourceEvent(request: Extract<HistoryIndexRequest, { action: \"get_source\" | \"read_source_payload\" }>) {\n\tconst { sessionId, eventId, through } = request;\n\tif (!Number.isSafeInteger(through) || through < 0) throw new Error(\"Invalid history source prefix\");\n\tconst saved = db.prepare(\"SELECT frontier FROM source_cursor WHERE session=?\").get(sessionId);\n\tif (!saved) throw new Error(\"Canonical source index is unavailable; synchronize the source first\");\n\tconst snapshot = JSON.parse(String(saved.frontier)) as SessionJournalState & { indexedThrough: number };\n\tif (snapshot.format !== \"framed\" || snapshot.indexedThrough < through)\n\t\tthrow new Error(\"Canonical source index has not reached the requested source prefix\");\n\tconst row = db\n\t\t.prepare(\"SELECT * FROM source_event WHERE session=? AND id=? AND sequence<=?\")\n\t\t.get(sessionId, eventId, through) as Row | undefined;\n\treturn { row, snapshot };\n}\nfunction readPayloadRow(\n\tsessionId: string,\n\trow: SourceRefRow,\n\tsnapshot: SessionJournalState,\n\toptions: HistoryPayloadReadOptions,\n) {\n\tconst savedParts = db\n\t\t.prepare(\"SELECT parts FROM source_payload WHERE session=? AND sequence=?\")\n\t\t.get(sessionId, row.sequence);\n\tif (!savedParts) throw new Error(\"Canonical payload parts are unavailable; rebuild the derived index\");\n\tconst parts = JSON.parse(String(savedParts.parts)) as CanonicalPayloadParts;\n\tconst locator = JSON.parse(row.locator) as IndexedSourceEvent[\"locator\"];\n\tif (\n\t\tlocator.path !== snapshot.journalPath ||\n\t\tparts.source.dev !== snapshot.dev ||\n\t\tparts.source.ino !== snapshot.ino ||\n\t\tparts.frameOffset !== locator.offset ||\n\t\tparts.frameChecksum !== row.revision ||\n\t\tparts.payloadOffset < locator.offset ||\n\t\tparts.payloadOffset + parts.byteLength > locator.offset + locator.length\n\t)\n\t\tthrow new Error(\"Canonical payload metadata does not match the verified source frame\");\n\tconst identity = (current: { dev: number; ino: number; size: number }) => {\n\t\tif (current.dev !== snapshot.dev || current.ino !== snapshot.ino || current.size < snapshot.byteLength)\n\t\t\tthrow new Error(\"Canonical payload source identity or acknowledged length changed\");\n\t};\n\treturn withJournalDescriptorSync(openSync(snapshot.journalPath, \"r\"), (fd) => {\n\t\tidentity(fstatSync(fd));\n\t\tconst fragment = readCanonicalPayloadFragment(fd, parts, options.cursor, options.maxBytes);\n\t\tidentity(statSync(snapshot.journalPath));\n\t\treturn fragment;\n\t});\n}\n\nlet catalogTransaction = false;\nlet catalogReadScope: { sessionId: string; through: number } | undefined;\nasync function sessionCatalog(\n\trequest: Extract<HistoryIndexRequest, { action: \"catalog\" }>,\n): Promise<SessionCatalogIndexResult> {\n\tif (!readOnly) throw new Error(\"Catalog discovery requires a read-only index connection\");\n\tcatalogReadScope = undefined;\n\tif (!catalogTransaction) {\n\t\tdb.exec(\"BEGIN\");\n\t\tcatalogTransaction = true;\n\t}\n\tconst saved = db.prepare(\"SELECT * FROM source_cursor WHERE session=?\").get(request.sessionId);\n\tif (!saved || saved.catalog_summary === null)\n\t\treturn { selection: \"unavailable\", reason: \"No owner-maintained catalog projection covers this source\" };\n\tconst frontier = JSON.parse(String(saved.frontier)) as SourceIndexCursor[\"frontier\"];\n\tconst covered = db.prepare(\"SELECT sequence FROM coverage WHERE session=?\").get(request.sessionId);\n\tif (!covered || covered.sequence !== frontier.indexedThrough)\n\t\treturn { selection: \"stale\", reason: \"Catalog index coverage is incomplete\" };\n\tconst bySequence = (sequence: number) =>\n\t\tdb.prepare(\"SELECT * FROM source_event WHERE session=? AND sequence=?\").get(request.sessionId, sequence) as\n\t\t\t| Row\n\t\t\t| undefined;\n\tconst tail = frontier.indexedThrough > 0 ? bySequence(frontier.indexedThrough) : undefined;\n\tconst previous = frontier.indexedThrough > 1 ? bySequence(frontier.indexedThrough - 1) : undefined;\n\tif (frontier.indexedThrough > 1 && !previous) throw new Error(\"Catalog predecessor metadata is unavailable\");\n\tconst indexed: SourceIndexCursor = {\n\t\tfrontier,\n\t\theaderByteLength: Number(saved.header_bytes),\n\t\theaderChecksum: String(saved.header_checksum),\n\t};\n\tif (\n\t\t!(await validateIndexedCatalogSource(\n\t\t\trequest.sessionId,\n\t\t\trequest.source,\n\t\t\tindexed,\n\t\t\ttail ? event(tail) : null,\n\t\t\tprevious?.revision ?? indexed.headerChecksum,\n\t\t))\n\t)\n\t\treturn { selection: \"stale\", reason: \"Catalog does not cover the current canonical source\" };\n\tconst projection = decodeSessionCatalog(JSON.parse(String(saved.catalog_summary)));\n\tif (projection.unsupported) return { selection: \"unsupported\", reason: projection.unsupported };\n\tconst reference = (id: string | null) => {\n\t\tif (id === null) return null;\n\t\tconst row = db\n\t\t\t.prepare(\"SELECT * FROM source_event WHERE session=? AND id=? AND sequence<=?\")\n\t\t\t.get(request.sessionId, id, frontier.indexedThrough) as Row | undefined;\n\t\tif (!row) throw new Error(\"Catalog source reference is unavailable\");\n\t\treturn event(row);\n\t};\n\tcatalogReadScope = { sessionId: request.sessionId, through: frontier.indexedThrough };\n\treturn {\n\t\tselection: \"covered\",\n\t\tfrontier,\n\t\tprojection,\n\t\trefs: {\n\t\t\tfirstMessage:\n\t\t\t\tprojection.firstMessage && \"id\" in projection.firstMessage ? reference(projection.firstMessage.id) : null,\n\t\t\tname: reference(projection.nameId),\n\t\t\tagentStatus: reference(projection.agentStatusId),\n\t\t},\n\t};\n}\n\nasync function dispatch(request: HistoryIndexRequest): Promise<unknown> {\n\tif (readOnly && ![\"catalog\", \"get_source\", \"read_source_payload\", \"close\"].includes(request.action))\n\t\tthrow new Error(\"Read-only catalog index does not admit this operation\");\n\tif (\n\t\treadOnly &&\n\t\t(request.action === \"get_source\" || request.action === \"read_source_payload\") &&\n\t\t(!catalogReadScope ||\n\t\t\trequest.sessionId !== catalogReadScope.sessionId ||\n\t\t\trequest.through !== catalogReadScope.through)\n\t)\n\t\tthrow new Error(\"Catalog payload read is outside its covered snapshot\");\n\tswitch (request.action) {\n\t\tcase \"catalog\":\n\t\t\treturn sessionCatalog(request);\n\t\tcase \"sync_source\":\n\t\t\treturn syncSource(request.sessionId, request.snapshot);\n\t\tcase \"ipython_sent_messages\":\n\t\t\treturn ipythonSentMessages(request);\n\t\tcase \"current_source_bootstrap\":\n\t\t\treturn currentSourceBootstrap(request);\n\t\tcase \"source_label\":\n\t\tcase \"source_assistant_usage\":\n\t\t\treturn sourceRelation(request);\n\t\tcase \"task_evidence\":\n\t\t\treturn taskEvidence(request);\n\t\tcase \"read_payload\":\n\t\t\treturn readPayload(request);\n\t\tcase \"parent_path\":\n\t\t\treturn parentPath(request);\n\t\tcase \"branch_bootstrap\":\n\t\t\treturn branchBootstrap(request);\n\t\tcase \"context_manifest\":\n\t\t\treturn contextManifest(request);\n\t\tcase \"context_updates\":\n\t\t\treturn contextUpdates(request);\n\t\tcase \"read_context_update_payload\":\n\t\t\treturn readContextUpdatePayload(request);\n\t\tcase \"apply\":\n\t\t\tapply(request.sessionId, request.events, request.committedThrough);\n\t\t\treturn;\n\t\tcase \"get\": {\n\t\t\tconst row = pointEvent(request.sessionId, request.eventId, request.scope);\n\t\t\treturn row ? event(row) : undefined;\n\t\t}\n\t\tcase \"get_source\": {\n\t\t\tconst { row } = selectSourceEvent(request);\n\t\t\treturn row ? event(row) : undefined;\n\t\t}\n\t\tcase \"read_source_payload\": {\n\t\t\tconst { row, snapshot } = selectSourceEvent(request);\n\t\t\treturn row ? readPayloadRow(request.sessionId, row, snapshot, request.options) : undefined;\n\t\t}\n\t\tcase \"page\":\n\t\tcase \"search\":\n\t\t\treturn query(request);\n\t\tcase \"clear\":\n\t\t\ttransaction(() => clearSession(request.sessionId));\n\t\t\treturn;\n\t\tcase \"close\":\n\t\t\tdb.close();\n\t\t\treturn;\n\t}\n}\nlet queue: Promise<void> = Promise.resolve();\nlet accepting = true;\nlet pendingBytes = 0;\nlet pendingOperations = 0;\nprocess.on(\"message\", (input: HistoryIndexRequest) => {\n\tlet bytes: number;\n\ttry {\n\t\tbytes = Buffer.byteLength(stringifyBoundedJson(input, 2 * 1024 * 1024));\n\t} catch (error) {\n\t\tprocess.send?.({ id: input.id, error: String(error) });\n\t\treturn;\n\t}\n\tif (!accepting || pendingOperations >= 32 || pendingBytes + bytes > 4 * 1024 * 1024) {\n\t\tprocess.send?.({ id: input.id, error: \"History-index queue is closing or full\" });\n\t\treturn;\n\t}\n\tif (input.action === \"close\") accepting = false;\n\tpendingOperations++;\n\tpendingBytes += bytes;\n\tconst operation = queue.then(() => dispatch(input));\n\tqueue = operation.then(\n\t\t() => undefined,\n\t\t() => undefined,\n\t);\n\tvoid operation\n\t\t.then(\n\t\t\t(result) => {\n\t\t\t\tif (process.connected)\n\t\t\t\t\tprocess.send?.({ id: input.id, result }, () => {\n\t\t\t\t\t\tif (input.action === \"close\") process.disconnect();\n\t\t\t\t\t});\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tif (process.connected)\n\t\t\t\t\tprocess.send?.({ id: input.id, error: error instanceof Error ? error.message : String(error) });\n\t\t\t},\n\t\t)\n\t\t.finally(() => {\n\t\t\tpendingOperations--;\n\t\t\tpendingBytes -= bytes;\n\t\t});\n});\nprocess.on(\"disconnect\", () => {\n\taccepting = false;\n\tvoid queue.finally(() => {\n\t\ttry {\n\t\t\tdb.close();\n\t\t} catch {}\n\t});\n});\nprocess.send?.({ ready: true });\n"]}
1
+ {"version":3,"file":"history-index-worker.d.ts","sourceRoot":"","sources":["../../src/core/history-index-worker.ts"],"names":[],"mappings":"","sourcesContent":["import { fstatSync, mkdirSync, openSync, statSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { DatabaseSync } from \"node:sqlite\";\nimport type { Usage } from \"@ponythewhite/base-context-ai\";\nimport { stringifyBoundedJson } from \"./bounded-json.js\";\nimport { type CanonicalPayloadParts, readCanonicalPayloadFragment } from \"./canonical-payload-parts.js\";\nimport { GOAL_STATE_CUSTOM_TYPE, isPersistedGoalState } from \"./goals.js\";\nimport type {\n\tBranchBootstrapState,\n\tContextManifestCursor,\n\tContextManifestPage,\n\tContextRef,\n\tContextUpdateRef,\n\tContextUpdates,\n\tContextUpdateTarget,\n\tHistoryIndexRequest,\n\tHistoryPayloadReadOptions,\n\tIndexedSourceEvent,\n\tIndexedTaskEvidence,\n\tIpythonSentMessagesCursor,\n\tIpythonSentMessagesPage,\n\tParentPathCursor,\n\tParentPathPage,\n\tSessionCatalogIndexResult,\n\tSourceBootstrapState,\n\tTaskEvidencePage,\n} from \"./history-index.js\";\nimport {\n\tprojectSessionSourceEvent,\n\treadSessionSource,\n\ttype SessionSourceEntry,\n\ttype SourceIndexCursor,\n\tvalidateIndexedCatalogSource,\n} from \"./history-source.js\";\nimport { withJournalDescriptorSync } from \"./journal-io.js\";\nimport {\n\tIPYTHON_SENT_AGENT_MESSAGE_CUSTOM_ENTRY,\n\tparsePersistedIpythonSentAgentMessage,\n} from \"./session-context-updates.js\";\nimport {\n\tCatalogProjectionUnsupportedError,\n\tdecodeSessionCatalog,\n\temptySessionCatalog,\n\tfoldSessionCatalog,\n\ttype SessionCatalogProjection,\n} from \"./session-info-projection.js\";\nimport type { SessionJournalState } from \"./session-journal-owner.js\";\nimport type { FileEntry } from \"./session-manager.js\";\nimport { getTaskStateImportCoverage, projectTaskStateSource } from \"./task-state.js\";\nimport { addAssistantUsage, cloneUsage, emptyUsage, sessionUsageSummaryFrom, subtractAssistantUsage } from \"./usage.js\";\n\nprocess.umask(0o077);\nconst readOnly = process.argv[3] === \"--read-only\";\nasync function openIndex() {\n\tlet opened: DatabaseSync | undefined;\n\tlet unsupported = false;\n\ttry {\n\t\tconst [major, minor] = process.versions.node.split(\".\").map(Number);\n\t\t// The API was backported to 22.12; early 23.x can also ignore the option.\n\t\tif (readOnly && (major < 22 || (major === 22 && minor < 12) || (major === 23 && minor < 3))) {\n\t\t\tunsupported = true;\n\t\t\tthrow new Error(\"Read-only catalog requires Node 22.12+ (23.x requires 23.3+)\");\n\t\t}\n\t\tif (!readOnly) mkdirSync(dirname(process.argv[2]), { recursive: true, mode: 0o700 });\n\t\tconst database = new DatabaseSync(process.argv[2], { readOnly });\n\t\topened = database;\n\t\tconst applicationId = Number(database.prepare(\"PRAGMA application_id\").get()?.application_id ?? 0);\n\t\tconst schemaVersion = Number(database.prepare(\"PRAGMA user_version\").get()?.user_version ?? 0);\n\t\tconst hasTables = !!database.prepare(\"SELECT 1 FROM sqlite_master WHERE type='table' LIMIT 1\").get();\n\t\tif (\n\t\t\t(applicationId !== 0x42435458 && (applicationId !== 0 || hasTables)) ||\n\t\t\t![0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16].includes(schemaVersion) ||\n\t\t\t(readOnly && (applicationId !== 0x42435458 || schemaVersion !== 16))\n\t\t) {\n\t\t\tunsupported = true;\n\t\t\tthrow new Error(\n\t\t\t\treadOnly\n\t\t\t\t\t? \"Catalog requires supported history-index schema 16; read-only discovery does not migrate\"\n\t\t\t\t\t: \"Not a supported Base Context history index\",\n\t\t\t);\n\t\t}\n\t\treturn { db: database, schemaVersion };\n\t} catch (error) {\n\t\tlet failure = error;\n\t\ttry {\n\t\t\topened?.close();\n\t\t} catch (cleanup) {\n\t\t\tunsupported = false;\n\t\t\tfailure = new AggregateError(\n\t\t\t\t[error, cleanup],\n\t\t\t\t`Index open and close failed: ${String(error)}; ${String(cleanup)}`,\n\t\t\t);\n\t\t}\n\t\tif (readOnly && process.connected)\n\t\t\tawait new Promise<void>((resolveSent) => {\n\t\t\t\ttry {\n\t\t\t\t\tprocess.send?.(\n\t\t\t\t\t\t{ startupError: failure instanceof Error ? failure.message : String(failure), unsupported },\n\t\t\t\t\t\t() => resolveSent(),\n\t\t\t\t\t);\n\t\t\t\t} catch {\n\t\t\t\t\tresolveSent();\n\t\t\t\t}\n\t\t\t});\n\t\tthrow failure;\n\t}\n}\nconst { db, schemaVersion } = await openIndex();\nif (!readOnly)\n\tdb.exec(`\n\tPRAGMA application_id=1111708760;\n\tPRAGMA journal_mode=WAL;\n\tPRAGMA synchronous=FULL;\n\tPRAGMA busy_timeout=5000;\n\tPRAGMA cache_size=-2048;\n\tCREATE TABLE IF NOT EXISTS source_event (\n\t\tsession TEXT NOT NULL, id TEXT NOT NULL, sequence INTEGER NOT NULL,\n\t\tparent_id TEXT, kind TEXT NOT NULL, authority TEXT NOT NULL,\n\t\tlocator TEXT NOT NULL, revision TEXT NOT NULL, text TEXT NOT NULL, text_complete INTEGER NOT NULL, retention TEXT, qualification TEXT,\n\t\tPRIMARY KEY(session,id), UNIQUE(session,sequence)\n\t);\n\tCREATE TABLE IF NOT EXISTS coverage(session TEXT PRIMARY KEY, sequence INTEGER NOT NULL);\n\tCREATE TABLE IF NOT EXISTS source_cursor (\n\t\tsession TEXT PRIMARY KEY, frontier TEXT NOT NULL, header_bytes INTEGER NOT NULL, header_checksum TEXT NOT NULL,\n\t\tsource_leaf TEXT,source_session_info TEXT,source_session_state TEXT,\n\t\tsource_compaction_count INTEGER NOT NULL DEFAULT 0,source_content_prefix INTEGER NOT NULL DEFAULT 0,\n\t\tsource_has_user_content INTEGER NOT NULL DEFAULT 0\n\t);\n\tCREATE TABLE IF NOT EXISTS source_term (\n\t\tsession TEXT NOT NULL, term TEXT NOT NULL, sequence INTEGER NOT NULL,\n\t\tPRIMARY KEY(session,term,sequence DESC)\n\t);\n\tCREATE TABLE IF NOT EXISTS term_count (\n\t\tsession TEXT NOT NULL, term TEXT NOT NULL, count INTEGER NOT NULL,\n\t\tPRIMARY KEY(session,term)\n\t);\n`);\n\nconst TASK_PAGE_BYTES = 1024 * 1024 - 1024;\nconst MAX_JUMP_LEVELS = 53;\nconst MAX_PARENT_LOOKUPS = 128;\nconst DERIVED_TABLES = [\n\t\"source_catalog_usage\",\n\t\"context_update\",\n\t\"context_node\",\n\t\"source_ancestry\",\n\t\"source_jump\",\n\t\"source_term\",\n\t\"term_count\",\n\t\"task_import_loss\",\n\t\"task_evidence\",\n\t\"source_event\",\n\t\"source_payload\",\n\t\"coverage\",\n\t\"source_cursor\",\n];\nif (!readOnly)\n\ttransaction(() => {\n\t\tdb.exec(`CREATE TABLE IF NOT EXISTS task_evidence (\n session TEXT NOT NULL, sequence INTEGER NOT NULL, ordinal INTEGER NOT NULL,\n task_key TEXT, item_id TEXT, source_ref TEXT NOT NULL, projection TEXT,\n PRIMARY KEY(session,sequence,ordinal)\n );\n CREATE INDEX IF NOT EXISTS task_item ON task_evidence(session,task_key,item_id,sequence,ordinal);\n CREATE TABLE IF NOT EXISTS source_payload (\n session TEXT NOT NULL, sequence INTEGER NOT NULL, parts TEXT NOT NULL, PRIMARY KEY(session,sequence)\n );\n CREATE TABLE IF NOT EXISTS task_import_loss (\n session TEXT NOT NULL, sequence INTEGER NOT NULL, task_key TEXT, PRIMARY KEY(session,sequence)\n );\n CREATE TABLE IF NOT EXISTS source_ancestry (\n session TEXT NOT NULL, id TEXT NOT NULL, depth INTEGER, PRIMARY KEY(session,id)\n );\n CREATE TABLE IF NOT EXISTS source_jump (\n session TEXT NOT NULL, id TEXT NOT NULL, level INTEGER NOT NULL, ancestor_id TEXT NOT NULL,\n PRIMARY KEY(session,id,level)\n );\n CREATE TABLE IF NOT EXISTS context_node (\n session TEXT NOT NULL,id TEXT NOT NULL,visible_head TEXT,previous_visible TEXT,visible_count INTEGER,latest_compaction TEXT,first_kept_id TEXT,\n latest_model TEXT,latest_thinking TEXT,latest_service_tier TEXT,latest_goal TEXT,has_session_message INTEGER,goal_seedable INTEGER,\n latest_rlm_max_depth TEXT,has_branch_message INTEGER,context_usage_assistant TEXT,latest_git_state TEXT,latest_agent_status TEXT,PRIMARY KEY(session,id)\n );\n CREATE TABLE IF NOT EXISTS context_update (\n session TEXT NOT NULL,event_id TEXT NOT NULL,update_kind TEXT NOT NULL,target_key TEXT NOT NULL,sequence INTEGER NOT NULL,\n PRIMARY KEY(session,update_kind,event_id)\n );\n CREATE INDEX IF NOT EXISTS context_update_target ON context_update(session,update_kind,target_key,sequence);\n CREATE TABLE IF NOT EXISTS source_catalog_usage (\n session TEXT NOT NULL,category INTEGER NOT NULL,id TEXT NOT NULL,sequence INTEGER NOT NULL,usage TEXT NOT NULL,\n PRIMARY KEY(session,category,id)\n );\n CREATE INDEX IF NOT EXISTS source_catalog_usage_order ON source_catalog_usage(session,category,sequence);`);\n\t\t// Old labels/projections cannot survive unchanged source identities across this upgrade.\n\t\tif (schemaVersion !== 16) {\n\t\t\tif (\n\t\t\t\t!db\n\t\t\t\t\t.prepare(\"PRAGMA table_info(source_event)\")\n\t\t\t\t\t.all()\n\t\t\t\t\t.some((column) => column.name === \"retention\")\n\t\t\t)\n\t\t\t\tdb.exec(\"ALTER TABLE source_event ADD COLUMN retention TEXT\");\n\t\t\tif (\n\t\t\t\t!db\n\t\t\t\t\t.prepare(\"PRAGMA table_info(source_event)\")\n\t\t\t\t\t.all()\n\t\t\t\t\t.some((column) => column.name === \"qualification\")\n\t\t\t)\n\t\t\t\tdb.exec(\"ALTER TABLE source_event ADD COLUMN qualification TEXT\");\n\t\t\tif (\n\t\t\t\t!db\n\t\t\t\t\t.prepare(\"PRAGMA table_info(context_node)\")\n\t\t\t\t\t.all()\n\t\t\t\t\t.some((column) => column.name === \"latest_model\")\n\t\t\t)\n\t\t\t\tdb.exec(`\n ALTER TABLE context_node ADD COLUMN latest_model TEXT;\n ALTER TABLE context_node ADD COLUMN latest_thinking TEXT;\n ALTER TABLE context_node ADD COLUMN latest_service_tier TEXT;\n ALTER TABLE context_node ADD COLUMN latest_goal TEXT;\n ALTER TABLE context_node ADD COLUMN has_session_message INTEGER;\n ALTER TABLE context_node ADD COLUMN goal_seedable INTEGER;\n `);\n\t\t\tif (\n\t\t\t\t!db\n\t\t\t\t\t.prepare(\"PRAGMA table_info(context_node)\")\n\t\t\t\t\t.all()\n\t\t\t\t\t.some((column) => column.name === \"latest_rlm_max_depth\")\n\t\t\t)\n\t\t\t\tdb.exec(`\n ALTER TABLE context_node ADD COLUMN latest_rlm_max_depth TEXT;\n ALTER TABLE context_node ADD COLUMN has_branch_message INTEGER;\n `);\n\t\t\tif (\n\t\t\t\t!db\n\t\t\t\t\t.prepare(\"PRAGMA table_info(context_node)\")\n\t\t\t\t\t.all()\n\t\t\t\t\t.some((column) => column.name === \"context_usage_assistant\")\n\t\t\t)\n\t\t\t\tdb.exec(\"ALTER TABLE context_node ADD COLUMN context_usage_assistant TEXT\");\n\t\t\tif (\n\t\t\t\t!db\n\t\t\t\t\t.prepare(\"PRAGMA table_info(context_node)\")\n\t\t\t\t\t.all()\n\t\t\t\t\t.some((column) => column.name === \"latest_git_state\")\n\t\t\t)\n\t\t\t\tdb.exec(`ALTER TABLE context_node ADD COLUMN latest_git_state TEXT;\n ALTER TABLE context_node ADD COLUMN latest_agent_status TEXT;`);\n\t\t\tif (\n\t\t\t\t!db\n\t\t\t\t\t.prepare(\"PRAGMA table_info(source_cursor)\")\n\t\t\t\t\t.all()\n\t\t\t\t\t.some((column) => column.name === \"source_leaf\")\n\t\t\t)\n\t\t\t\tdb.exec(`ALTER TABLE source_cursor ADD COLUMN source_leaf TEXT;\n ALTER TABLE source_cursor ADD COLUMN source_session_info TEXT;\n ALTER TABLE source_cursor ADD COLUMN source_session_state TEXT;\n ALTER TABLE source_cursor ADD COLUMN source_compaction_count INTEGER NOT NULL DEFAULT 0;\n ALTER TABLE source_cursor ADD COLUMN source_content_prefix INTEGER NOT NULL DEFAULT 0;\n ALTER TABLE source_cursor ADD COLUMN source_has_user_content INTEGER NOT NULL DEFAULT 0;`);\n\t\t\tif (\n\t\t\t\t!db\n\t\t\t\t\t.prepare(\"PRAGMA table_info(source_cursor)\")\n\t\t\t\t\t.all()\n\t\t\t\t\t.some((column) => column.name === \"catalog_summary\")\n\t\t\t)\n\t\t\t\tdb.exec(\"ALTER TABLE source_cursor ADD COLUMN catalog_summary TEXT\");\n\t\t\tfor (const table of DERIVED_TABLES) db.exec(`DELETE FROM ${table}`);\n\t\t}\n\t\tdb.exec(`\n CREATE INDEX IF NOT EXISTS source_incomplete ON source_event(session,sequence) WHERE text_complete=0;\n CREATE INDEX IF NOT EXISTS task_sequence ON task_evidence(session,task_key,sequence,ordinal);\n CREATE INDEX IF NOT EXISTS task_item_sequence ON task_evidence(session,item_id,sequence,ordinal);\n CREATE INDEX IF NOT EXISTS task_loss_key ON task_import_loss(session,task_key,sequence);\n `);\n\t\tdb.exec(\"PRAGMA user_version=16\");\n\t});\n\n// Node22.8 ships SQLite without FTS5. A normal SQLite posting index keeps the\n// declared floor and bounded lookups without loading a platform extension.\nfunction terms(text: string): string[] {\n\treturn [\n\t\t...new Set(\n\t\t\ttext\n\t\t\t\t.normalize(\"NFC\")\n\t\t\t\t.toLowerCase()\n\t\t\t\t.match(/[\\p{L}\\p{M}\\p{N}_]+/gu) ?? [],\n\t\t),\n\t];\n}\nconst insertSourceEvent = db.prepare(\"INSERT INTO source_event VALUES (?,?,?,?,?,?,?,?,?,?,?,?)\");\nconst insertSourcePayload = db.prepare(\"INSERT INTO source_payload VALUES (?,?,?)\");\nconst insertTaskImportLoss = db.prepare(\"INSERT INTO task_import_loss VALUES (?,?,?)\");\nconst insertTaskEvidence = db.prepare(\"INSERT INTO task_evidence VALUES (?,?,?,?,?,?,?)\");\nconst insertTerm = db.prepare(\"INSERT INTO source_term VALUES (?,?,?)\");\nconst countTerm = db.prepare(\n\t\"INSERT INTO term_count VALUES (?,?,1) ON CONFLICT(session,term) DO UPDATE SET count=count+1\",\n);\n\ntype Row = {\n\tid: string;\n\tsequence: number;\n\tparent_id: string | null;\n\tkind: string;\n\tauthority: IndexedSourceEvent[\"authority\"];\n\tlocator: string;\n\trevision: string;\n\ttext: string;\n\ttext_complete: number;\n\tretention: IndexedSourceEvent[\"retention\"] | null;\n\tqualification: IndexedSourceEvent[\"qualification\"] | null;\n};\nfunction event(row: Row): IndexedSourceEvent {\n\treturn {\n\t\tid: row.id,\n\t\tsequence: row.sequence,\n\t\tparentId: row.parent_id,\n\t\tkind: row.kind,\n\t\tauthority: row.authority,\n\t\tlocator: JSON.parse(row.locator) as IndexedSourceEvent[\"locator\"],\n\t\trevision: row.revision,\n\t\t...(row.retention === null ? {} : { retention: row.retention }),\n\t\t...(row.qualification === null ? {} : { qualification: row.qualification }),\n\t\ttext: row.text,\n\t\ttextComplete: row.text_complete === 1,\n\t};\n}\nfunction transaction(action: () => void): void {\n\tdb.exec(\"BEGIN IMMEDIATE\");\n\ttry {\n\t\taction();\n\t\tdb.exec(\"COMMIT\");\n\t} catch (error) {\n\t\ttry {\n\t\t\tdb.exec(\"ROLLBACK\");\n\t\t} catch {\n\t\t\t/* SQLite may already have rolled back a failed write. */\n\t\t}\n\t\tthrow error;\n\t}\n}\nfunction insertEvent(sessionId: string, item: IndexedSourceEvent): void {\n\tif (item.retention !== undefined && item.retention !== \"retained-import\")\n\t\tthrow new Error(\"Unsupported indexed source retention\");\n\tif (\n\t\titem.qualification !== undefined &&\n\t\titem.qualification !== \"native-admission\" &&\n\t\titem.qualification !== \"native-recovery\" &&\n\t\titem.qualification !== \"native-context-epoch\" &&\n\t\titem.qualification !== \"native-tool-execution\"\n\t)\n\t\tthrow new Error(\"Unsupported indexed source qualification\");\n\tinsertSourceEvent.run(\n\t\tsessionId,\n\t\titem.id,\n\t\titem.sequence,\n\t\titem.parentId,\n\t\titem.kind,\n\t\titem.authority,\n\t\tJSON.stringify(item.locator),\n\t\titem.revision,\n\t\titem.text,\n\t\titem.textComplete ? 1 : 0,\n\t\titem.retention ?? null,\n\t\titem.qualification ?? null,\n\t);\n\tfor (const term of terms(item.text)) {\n\t\tinsertTerm.run(sessionId, term, item.sequence);\n\t\tcountTerm.run(sessionId, term);\n\t}\n}\nconst sourceParent = db.prepare(\n\t\"SELECT a.depth FROM source_event e JOIN source_ancestry a ON a.session=e.session AND a.id=e.id WHERE e.session=? AND e.id=? AND e.sequence<?\",\n);\nconst insertDepth = db.prepare(\"INSERT INTO source_ancestry VALUES (?,?,?)\");\nconst insertJump = db.prepare(\"INSERT INTO source_jump VALUES (?,?,?,?)\");\nconst ancestorJump = db.prepare(\"SELECT ancestor_id FROM source_jump WHERE session=? AND id=? AND level=?\");\nfunction insertAncestry(sessionId: string, item: IndexedSourceEvent): number | null {\n\tconst parent = item.parentId === null ? undefined : sourceParent.get(sessionId, item.parentId, item.sequence);\n\tconst depth = item.parentId === null ? 0 : parent?.depth == null ? null : Number(parent.depth) + 1;\n\tinsertDepth.run(sessionId, item.id, depth);\n\tif (depth === null || depth === 0) return depth;\n\tlet ancestorId = item.parentId!;\n\tfor (let level = 0; level < MAX_JUMP_LEVELS && 2 ** level <= depth; level++) {\n\t\tif (level > 0) ancestorId = String(ancestorJump.get(sessionId, ancestorId, level - 1)!.ancestor_id);\n\t\tinsertJump.run(sessionId, item.id, level, ancestorId);\n\t}\n\treturn depth;\n}\ntype ContextState = {\n\tvisible_head: string | null;\n\tprevious_visible: string | null;\n\tvisible_count: number | null;\n\tlatest_compaction: string | null;\n\tfirst_kept_id: string | null;\n};\ntype BootstrapColumns = {\n\tlatest_model: string | null;\n\tlatest_thinking: string | null;\n\tlatest_service_tier: string | null;\n\tlatest_goal: string | null;\n\thas_session_message: number;\n\tgoal_seedable: number;\n\tlatest_rlm_max_depth: string | null;\n\thas_branch_message: number;\n\tcontext_usage_assistant: string | null;\n\tlatest_git_state: string | null;\n\tlatest_agent_status: string | null;\n};\nfunction isPersistedRlmMaxDepthState(value: unknown): boolean {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst maxDepth = (value as { maxDepth?: unknown }).maxDepth;\n\treturn typeof maxDepth === \"number\" && Number.isSafeInteger(maxDepth) && maxDepth >= 0;\n}\nconst contextParent = db.prepare(\"SELECT * FROM context_node WHERE session=? AND id=?\");\nconst insertContextNode = db.prepare(\"INSERT INTO context_node VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\");\nfunction insertContext(\n\tsessionId: string,\n\titem: IndexedSourceEvent,\n\tentry: SessionSourceEntry,\n\tdepth: number | null,\n): void {\n\tconst parent =\n\t\titem.parentId === null\n\t\t\t? undefined\n\t\t\t: (contextParent.get(sessionId, item.parentId) as (ContextState & BootstrapColumns) | undefined);\n\tif (depth !== null && item.parentId !== null && parent?.visible_count == null)\n\t\tthrow new Error(\"Context ancestry metadata is incomplete\");\n\t// Match buildSessionContext before provider filtering: !! bash/UI-only messages remain ordering barriers.\n\tconst visible =\n\t\tentry.type === \"message\" ||\n\t\tentry.type === \"custom_message\" ||\n\t\t(entry.type === \"branch_summary\" && !!entry.summary);\n\tconst head = parent?.visible_head ?? null;\n\tconst count = depth === null ? null : Number(parent?.visible_count ?? 0) + (visible ? 1 : 0);\n\tconst compaction = entry.type === \"compaction\";\n\tconst firstKept =\n\t\tcompaction &&\n\t\ttypeof entry.firstKeptEntryId === \"string\" &&\n\t\tentry.firstKeptEntryId.length > 0 &&\n\t\tentry.firstKeptEntryId.length <= 512\n\t\t\t? entry.firstKeptEntryId\n\t\t\t: null;\n\tconst message = entry.message as { role?: unknown; stopReason?: unknown } | null;\n\tconst modelProducer = entry.type === \"model_change\" || (entry.type === \"message\" && message?.role === \"assistant\");\n\tconst contextUsageAssistant =\n\t\tentry.type === \"message\" &&\n\t\tmessage?.role === \"assistant\" &&\n\t\tmessage.stopReason !== \"aborted\" &&\n\t\tmessage.stopReason !== \"error\";\n\tconst eligibleGoal =\n\t\tentry.type === \"custom\" &&\n\t\tentry.customType === GOAL_STATE_CUSTOM_TYPE &&\n\t\titem.retention !== \"retained-import\" &&\n\t\tisPersistedGoalState(entry.data);\n\tconst eligibleRlmMaxDepth =\n\t\tentry.type === \"custom\" && entry.customType === \"rlm_max_depth_state\" && isPersistedRlmMaxDepthState(entry.data);\n\tconst seedControl =\n\t\tentry.type === \"model_change\" || entry.type === \"thinking_level_change\" || entry.type === \"service_tier_change\";\n\t// A manifest ref exists for a message envelope even when its message value is falsy.\n\tconst hasSessionMessage = entry.type === \"message\" ? !!entry.message : visible;\n\tinsertContextNode.run(\n\t\tsessionId,\n\t\titem.id,\n\t\tvisible ? item.id : head,\n\t\tvisible ? head : null,\n\t\tcount,\n\t\tcompaction ? item.id : (parent?.latest_compaction ?? null),\n\t\tfirstKept,\n\t\tmodelProducer ? item.id : (parent?.latest_model ?? null),\n\t\tentry.type === \"thinking_level_change\" ? item.id : (parent?.latest_thinking ?? null),\n\t\tentry.type === \"service_tier_change\" ? item.id : (parent?.latest_service_tier ?? null),\n\t\teligibleGoal ? item.id : (parent?.latest_goal ?? null),\n\t\tparent?.has_session_message === 1 || hasSessionMessage ? 1 : 0,\n\t\tseedControl && (item.parentId === null || parent?.goal_seedable === 1) ? 1 : 0,\n\t\teligibleRlmMaxDepth ? item.id : (parent?.latest_rlm_max_depth ?? null),\n\t\tparent?.has_branch_message === 1 || entry.type === \"message\" ? 1 : 0,\n\t\tcompaction ? null : contextUsageAssistant ? item.id : (parent?.context_usage_assistant ?? null),\n\t\tentry.type === \"git_state\" ? item.id : (parent?.latest_git_state ?? null),\n\t\tentry.type === \"agent_status\" ? item.id : (parent?.latest_agent_status ?? null),\n\t);\n}\n// Only bounded relation keys and source refs live here; never usage or sent-message bodies.\nconst MAX_CONTEXT_UPDATE_KEY = 8192;\nconst MAX_CONTEXT_UPDATE_CANDIDATES = 128;\nconst insertUpdate = db.prepare(\"INSERT INTO context_update VALUES (?,?,?,?,?)\");\nfunction insertContextUpdates(sessionId: string, item: IndexedSourceEvent, entry: SessionSourceEntry): void {\n\tif (entry.type === \"message\" && (entry.message as { role?: unknown } | null)?.role === \"assistant\") {\n\t\tinsertUpdate.run(sessionId, item.id, \"assistant-target\", item.id, item.sequence);\n\t} else if (\n\t\tentry.type === \"child_usage_attributed\" &&\n\t\ttypeof entry.targetId === \"string\" &&\n\t\tentry.targetId.length <= 512\n\t) {\n\t\t// The source aggregate is intentionally not validated or replaced by an older value.\n\t\tinsertUpdate.run(sessionId, item.id, \"assistant-usage\", entry.targetId, item.sequence);\n\t} else if (entry.type === \"label\" && typeof entry.targetId === \"string\" && entry.targetId.length <= 512) {\n\t\tinsertUpdate.run(sessionId, item.id, \"label\", entry.targetId, item.sequence);\n\t} else if (entry.type === \"custom\" && entry.customType === IPYTHON_SENT_AGENT_MESSAGE_CUSTOM_ENTRY) {\n\t\tconst parsed = parsePersistedIpythonSentAgentMessage(entry.data);\n\t\tif (parsed && parsed.toolCallId.length <= MAX_CONTEXT_UPDATE_KEY) {\n\t\t\tinsertUpdate.run(sessionId, item.id, \"ipython-sent-message\", parsed.toolCallId, item.sequence);\n\t\t\tif (parsed.message.id.length <= MAX_CONTEXT_UPDATE_KEY)\n\t\t\t\tinsertUpdate.run(\n\t\t\t\t\tsessionId,\n\t\t\t\t\titem.id,\n\t\t\t\t\t\"ipython-sent-message-id\",\n\t\t\t\t\tJSON.stringify([parsed.toolCallId, parsed.message.id]),\n\t\t\t\t\titem.sequence,\n\t\t\t\t);\n\t\t}\n\t}\n}\n\nfunction clearSession(sessionId: string): void {\n\tfor (const table of DERIVED_TABLES) db.prepare(`DELETE FROM ${table} WHERE session=?`).run(sessionId);\n}\ninterface SourceBootstrapColumns {\n\tsource_leaf: string | null;\n\tsource_session_info: string | null;\n\tsource_session_state: string | null;\n\tsource_compaction_count: number;\n\tsource_content_prefix: number;\n\tsource_has_user_content: number;\n}\nconst SOURCE_CONTENT_TYPES = new Set([\n\t\"message\",\n\t\"custom_message\",\n\t\"custom\",\n\t\"model_change\",\n\t\"thinking_level_change\",\n\t\"service_tier_change\",\n\t\"session_info\",\n\t\"label\",\n\t\"compaction\",\n\t\"branch_summary\",\n\t\"tool_intent\",\n\t\"request\",\n]);\nconst SOURCE_CREATION_PREFIX = [\"model_change\", \"thinking_level_change\", \"service_tier_change\"];\nfunction foldSourceBootstrap(state: SourceBootstrapColumns, entry: SessionSourceEntry): void {\n\tif (entry.type === \"session\") return;\n\tif (entry.type !== \"request\") state.source_leaf = entry.id;\n\tif (entry.type === \"session_info\") state.source_session_info = entry.id;\n\tif (entry.type === \"compaction\") state.source_compaction_count++;\n\tif (entry.type === \"session_state\") {\n\t\tconst status = (entry.state as { status?: unknown } | null)?.status;\n\t\tif (\n\t\t\tstatus === \"active\" ||\n\t\t\tstatus === \"archived\" ||\n\t\t\tstatus === \"crash\" ||\n\t\t\tstatus === \"hidden\" ||\n\t\t\tstatus === \"sleep\"\n\t\t)\n\t\t\tstate.source_session_state = entry.id;\n\t}\n\tif (state.source_has_user_content === 0 && SOURCE_CONTENT_TYPES.has(entry.type)) {\n\t\twhile (\n\t\t\tstate.source_content_prefix < SOURCE_CREATION_PREFIX.length &&\n\t\t\tentry.type !== SOURCE_CREATION_PREFIX[state.source_content_prefix]\n\t\t)\n\t\t\tstate.source_content_prefix++;\n\t\tif (state.source_content_prefix < SOURCE_CREATION_PREFIX.length) state.source_content_prefix++;\n\t\telse state.source_has_user_content = 1;\n\t}\n}\n\n/** Numeric derived metadata only, in canonical source order; no message bodies. */\nfunction catalogUsage(value: Usage): string {\n\tlet usage: Usage;\n\ttry {\n\t\tusage = cloneUsage(value);\n\t} catch (error) {\n\t\tif (error instanceof TypeError) throw new CatalogProjectionUnsupportedError(\"Missing catalog usage fields\");\n\t\tthrow error;\n\t}\n\tconst values = [\n\t\tusage.input,\n\t\tusage.output,\n\t\tusage.cacheRead,\n\t\tusage.cacheWrite,\n\t\tusage.totalTokens,\n\t\tusage.cost.input,\n\t\tusage.cost.output,\n\t\tusage.cost.cacheRead,\n\t\tusage.cost.cacheWrite,\n\t\tusage.cost.total,\n\t];\n\tif (values.some((part) => typeof part !== \"number\" || !Number.isFinite(part)))\n\t\tthrow new CatalogProjectionUnsupportedError(\"Non-finite or incomplete catalog usage is unsupported\");\n\treturn stringifyBoundedJson(usage, 4096);\n}\nfunction foldCatalogUsage(sessionId: string, entry: FileEntry, sequence: number): boolean {\n\tconst insert = (category: number, value: Usage) =>\n\t\tdb\n\t\t\t.prepare(\"INSERT INTO source_catalog_usage VALUES (?,?,?,?,?)\")\n\t\t\t.run(sessionId, category, entry.id, sequence, catalogUsage(value));\n\tif (entry.type === \"message\" && entry.message?.role === \"assistant\" && (entry.message as { usage?: Usage }).usage)\n\t\tinsert(0, (entry.message as { usage: Usage }).usage);\n\telse if ((entry.type === \"compaction\" || entry.type === \"branch_summary\") && entry.usage) insert(1, entry.usage);\n\telse if (entry.type === \"child_usage_attributed\") {\n\t\tconst prior = db\n\t\t\t.prepare(\"SELECT usage FROM source_catalog_usage WHERE session=? AND category=0 AND id=?\")\n\t\t\t.get(sessionId, entry.targetId);\n\t\tif (!prior) return false; // Same source-order target eligibility as the original fold.\n\t\tconst aggregate = catalogUsage(entry.aggregateUsage);\n\t\tconst child = catalogUsage(entry.childUsage);\n\t\tdb.prepare(\"UPDATE source_catalog_usage SET usage=? WHERE session=? AND category=0 AND id=?\").run(\n\t\t\taggregate,\n\t\t\tsessionId,\n\t\t\tentry.targetId,\n\t\t);\n\t\tdb.prepare(\"INSERT INTO source_catalog_usage VALUES (?,?,?,?,?)\").run(sessionId, 2, entry.id, sequence, child);\n\t} else return false;\n\treturn true;\n}\nfunction catalogUsageTotal(sessionId: string) {\n\tconst total = emptyUsage();\n\tconst page = db.prepare(\n\t\t\"SELECT sequence,usage FROM source_catalog_usage WHERE session=? AND category=? AND sequence>? ORDER BY sequence LIMIT 128\",\n\t);\n\t// Preserve assistant insertion order, then summaries, then ordered clamped\n\t// child subtraction. Incremental replacement never subtracts a stale aggregate.\n\tfor (const category of [0, 1, 2]) {\n\t\tlet after = 0;\n\t\tfor (;;) {\n\t\t\tconst rows = page.all(sessionId, category, after);\n\t\t\tif (!rows.length) break;\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst usage = JSON.parse(String(row.usage)) as Usage;\n\t\t\t\tif (category === 2) subtractAssistantUsage(total, usage);\n\t\t\t\telse addAssistantUsage(total, usage);\n\t\t\t\tafter = Number(row.sequence);\n\t\t\t}\n\t\t}\n\t}\n\tcatalogUsage(total); // Unsupported arithmetic is never persisted as JSON null/zero.\n\tconst summary = sessionUsageSummaryFrom(total);\n\tif (summary && ![summary.inputTokens, summary.outputTokens, summary.cost].every(Number.isFinite))\n\t\tthrow new CatalogProjectionUnsupportedError(\"Catalog usage total is not finite\");\n\treturn summary;\n}\n\nasync function syncSource(sessionId: string, snapshot: SessionJournalState) {\n\tconst row = db.prepare(\"SELECT * FROM source_cursor WHERE session=?\").get(sessionId);\n\tlet previous: SourceIndexCursor | undefined = row\n\t\t? {\n\t\t\t\tfrontier: JSON.parse(String(row.frontier)),\n\t\t\t\theaderByteLength: Number(row.header_bytes),\n\t\t\t\theaderChecksum: String(row.header_checksum),\n\t\t\t}\n\t\t: undefined;\n\tif (\n\t\tprevious &&\n\t\t(previous.frontier.journalPath !== snapshot.journalPath ||\n\t\t\tprevious.frontier.dev !== snapshot.dev ||\n\t\t\tprevious.frontier.ino !== snapshot.ino ||\n\t\t\tprevious.frontier.byteLength > snapshot.byteLength ||\n\t\t\tprevious.frontier.nextSequence > snapshot.nextSequence)\n\t)\n\t\tprevious = undefined;\n\tconst sourceState: SourceBootstrapColumns = previous\n\t\t? ({ ...row } as unknown as SourceBootstrapColumns)\n\t\t: {\n\t\t\t\tsource_leaf: null,\n\t\t\t\tsource_session_info: null,\n\t\t\t\tsource_session_state: null,\n\t\t\t\tsource_compaction_count: 0,\n\t\t\t\tsource_content_prefix: 0,\n\t\t\t\tsource_has_user_content: 0,\n\t\t\t};\n\t// The session owner coalesces queued ACK snapshots; this whole ready suffix shares one transaction.\n\t// Coverage and the source cursor become visible only with that transaction's COMMIT.\n\tlet usageChanged = !previous;\n\tconst catalog: SessionCatalogProjection = previous\n\t\t? decodeSessionCatalog(JSON.parse(String(row?.catalog_summary)))\n\t\t: emptySessionCatalog();\n\tdb.exec(\"BEGIN IMMEDIATE\");\n\ttry {\n\t\tif (!previous) clearSession(sessionId);\n\t\tconst indexed = await readSessionSource(\n\t\t\tsessionId,\n\t\t\tsnapshot,\n\t\t\tprevious,\n\t\t\t(entry, sequence, locator, revision, parts, retention, qualification, json) => {\n\t\t\t\tfoldSourceBootstrap(sourceState, entry);\n\t\t\t\tif (!catalog.unsupported) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (json === undefined) throw new Error(\"Catalog source JSON is unavailable\");\n\t\t\t\t\t\t// The source envelope type retains the full canonical payload's fields.\n\t\t\t\t\t\tconst catalogEntry = entry as SessionSourceEntry & FileEntry;\n\t\t\t\t\t\tif (foldCatalogUsage(sessionId, catalogEntry, sequence)) usageChanged = true;\n\t\t\t\t\t\tfoldSessionCatalog(catalog, catalogEntry, json);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!(error instanceof CatalogProjectionUnsupportedError)) throw error;\n\t\t\t\t\t\tcatalog.unsupported = error.message;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst item = projectSessionSourceEvent(entry, sequence, locator, revision);\n\t\t\t\tif (retention !== undefined) item.retention = retention;\n\t\t\t\tif (qualification !== undefined) item.qualification = qualification;\n\t\t\t\tinsertEvent(sessionId, item);\n\t\t\t\tconst depth = insertAncestry(sessionId, item);\n\t\t\t\tinsertContext(sessionId, item, entry, depth);\n\t\t\t\tinsertContextUpdates(sessionId, item, entry);\n\t\t\t\tinsertSourcePayload.run(sessionId, sequence, JSON.stringify(parts));\n\t\t\t\tconst source = { sessionId, sequence, entry, locator, revision, retention, qualification };\n\t\t\t\tconst imported = getTaskStateImportCoverage(source);\n\t\t\t\tif (imported) insertTaskImportLoss.run(sessionId, sequence, imported.taskKey ?? null);\n\t\t\t\tlet ordinal = 0;\n\t\t\t\tfor (const projection of projectTaskStateSource(source)) {\n\t\t\t\t\tlet payload: string | null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tpayload = stringifyBoundedJson(projection, TASK_PAGE_BYTES);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!(error instanceof Error) || error.message !== \"JSON byte limit exceeded\") throw error;\n\t\t\t\t\t\t// The original canonical field is recoverable; never clip its item or text.\n\t\t\t\t\t\tpayload = null;\n\t\t\t\t\t}\n\t\t\t\t\tinsertTaskEvidence.run(\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tsequence,\n\t\t\t\t\t\tordinal++,\n\t\t\t\t\t\tprojection.taskKey ?? null,\n\t\t\t\t\t\tprojection.itemId ?? null,\n\t\t\t\t\t\tJSON.stringify(projection.source),\n\t\t\t\t\t\tpayload,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t\tif (usageChanged && !catalog.unsupported) {\n\t\t\ttry {\n\t\t\t\tcatalog.usage = catalogUsageTotal(sessionId);\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof CatalogProjectionUnsupportedError)) throw error;\n\t\t\t\tcatalog.unsupported = error.message;\n\t\t\t}\n\t\t}\n\t\tdb.prepare(\"INSERT INTO coverage VALUES (?,?) ON CONFLICT(session) DO UPDATE SET sequence=excluded.sequence\").run(\n\t\t\tsessionId,\n\t\t\tindexed.frontier.indexedThrough,\n\t\t);\n\t\tdb.prepare(\n\t\t\t\"INSERT INTO source_cursor VALUES (?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(session) DO UPDATE SET frontier=excluded.frontier,header_bytes=excluded.header_bytes,header_checksum=excluded.header_checksum,source_leaf=excluded.source_leaf,source_session_info=excluded.source_session_info,source_session_state=excluded.source_session_state,source_compaction_count=excluded.source_compaction_count,source_content_prefix=excluded.source_content_prefix,source_has_user_content=excluded.source_has_user_content,catalog_summary=excluded.catalog_summary\",\n\t\t).run(\n\t\t\tsessionId,\n\t\t\tJSON.stringify(indexed.frontier),\n\t\t\tindexed.headerByteLength,\n\t\t\tindexed.headerChecksum,\n\t\t\tsourceState.source_leaf,\n\t\t\tsourceState.source_session_info,\n\t\t\tsourceState.source_session_state,\n\t\t\tsourceState.source_compaction_count,\n\t\t\tsourceState.source_content_prefix,\n\t\t\tsourceState.source_has_user_content,\n\t\t\tstringifyBoundedJson(catalog, TASK_PAGE_BYTES),\n\t\t);\n\t\tdb.exec(\"COMMIT\");\n\t\treturn indexed.frontier;\n\t} catch (error) {\n\t\ttry {\n\t\t\tdb.exec(\"ROLLBACK\");\n\t\t} catch {\n\t\t\t/* Preserve the failed derived-index operation. */\n\t\t}\n\t\tthrow error;\n\t}\n}\nfunction apply(sessionId: string, events: IndexedSourceEvent[], committedThrough: number): void {\n\tif (events.length > 128 || !Number.isSafeInteger(committedThrough) || committedThrough < 0)\n\t\tthrow new Error(\"Invalid bounded index batch\");\n\ttransaction(() => {\n\t\tdb.prepare(\"DELETE FROM source_cursor WHERE session=?\").run(sessionId);\n\t\tdb.prepare(\"DELETE FROM source_ancestry WHERE session=?\").run(sessionId);\n\t\tdb.prepare(\"DELETE FROM source_jump WHERE session=?\").run(sessionId);\n\t\tdb.prepare(\"DELETE FROM context_node WHERE session=?\").run(sessionId);\n\t\tdb.prepare(\"DELETE FROM context_update WHERE session=?\").run(sessionId);\n\t\tconst current = db.prepare(\"SELECT sequence FROM coverage WHERE session=?\").get(sessionId)?.sequence ?? 0;\n\t\tif (committedThrough < Number(current)) throw new Error(\"Index coverage cannot move backwards\");\n\t\tlet expected = Number(current) + 1;\n\t\tfor (const item of events) {\n\t\t\tif (Buffer.byteLength(item.text) > 8192 || Buffer.byteLength(JSON.stringify(item.locator)) > 8192)\n\t\t\t\tthrow new Error(\"Index text/locator limit exceeded; use bounded source parts\");\n\t\t\tif (!Number.isSafeInteger(item.sequence) || item.sequence <= 0 || item.sequence > committedThrough)\n\t\t\t\tthrow new Error(\"Invalid committed source sequence\");\n\t\t\tconst existing = db\n\t\t\t\t.prepare(\"SELECT revision,sequence FROM source_event WHERE session=? AND id=?\")\n\t\t\t\t.get(sessionId, item.id);\n\t\t\tif (existing) {\n\t\t\t\tif (existing.revision !== item.revision || existing.sequence !== item.sequence)\n\t\t\t\t\tthrow new Error(\"Conflicting immutable source identity\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (item.sequence !== expected) throw new Error(\"Missing source sequence before index publication\");\n\t\t\texpected++;\n\t\t\t// Metadata-only apply cannot mint canonical producer qualification.\n\t\t\tinsertEvent(sessionId, { ...item, qualification: undefined });\n\t\t}\n\t\tif (expected - 1 !== committedThrough) throw new Error(\"Index cannot advertise unindexed source coverage\");\n\t\tdb.prepare(\"INSERT INTO coverage VALUES (?,?) ON CONFLICT(session) DO UPDATE SET sequence=excluded.sequence\").run(\n\t\t\tsessionId,\n\t\t\tcommittedThrough,\n\t\t);\n\t});\n}\ntype BranchNode = Pick<Row, \"id\" | \"parent_id\"> & { depth: number | null };\nconst branchNode = db.prepare(\n\t\"SELECT e.id,e.parent_id,a.depth FROM source_event e LEFT JOIN source_ancestry a ON a.session=e.session AND a.id=e.id WHERE e.session=? AND e.id=? AND e.sequence<=?\",\n);\nfunction validateBranchScope(\n\tsessionId: string,\n\tthrough: number,\n\tscope: { leafId: string | null },\n): BranchNode | undefined {\n\tif (\n\t\t!(scope.leafId === null || (typeof scope.leafId === \"string\" && scope.leafId.length <= 512)) ||\n\t\t!Number.isSafeInteger(through) ||\n\t\tthrough < 0\n\t)\n\t\tthrow new Error(\"Invalid history branch scope\");\n\tconst leaf =\n\t\tscope.leafId === null ? undefined : (branchNode.get(sessionId, scope.leafId, through) as BranchNode | undefined);\n\tif (scope.leafId !== null && !leaf) throw new Error(\"History branch leaf is outside the indexed prefix\");\n\treturn leaf;\n}\nfunction resolvedAncestor(sessionId: string, leaf: BranchNode, target: BranchNode): boolean {\n\tlet difference = leaf.depth! - target.depth!;\n\tif (difference < 0) return false;\n\tlet ancestorId = leaf.id;\n\tfor (let level = 0; difference > 0 && level < MAX_JUMP_LEVELS; level++) {\n\t\tif (difference % 2 === 1) {\n\t\t\tconst jump = ancestorJump.get(sessionId, ancestorId, level);\n\t\t\tif (!jump) throw new Error(\"History branch ancestry metadata is incomplete\");\n\t\t\tancestorId = String(jump.ancestor_id);\n\t\t}\n\t\tdifference = Math.floor(difference / 2);\n\t}\n\treturn ancestorId === target.id;\n}\nfunction pointEvent(\n\tsessionId: string,\n\teventId: string,\n\tscope?: { leafId: string | null; through: number },\n): Row | undefined {\n\tif (!scope)\n\t\treturn db.prepare(\"SELECT * FROM source_event WHERE session=? AND id=?\").get(sessionId, eventId) as\n\t\t\t| Row\n\t\t\t| undefined;\n\tconst leaf = validateBranchScope(sessionId, scope.through, scope);\n\tconst row = db\n\t\t.prepare(\"SELECT * FROM source_event WHERE session=? AND id=? AND sequence<=?\")\n\t\t.get(sessionId, eventId, scope.through) as Row | undefined;\n\tif (!row || !leaf) return undefined;\n\tconst targets = row.kind === \"request\" && row.parent_id !== null ? [row.id, row.parent_id] : [row.id];\n\tif (targets.includes(leaf.id)) return row;\n\tif (leaf.depth !== null) {\n\t\tlet unknown = false;\n\t\tfor (const id of targets) {\n\t\t\tconst target = branchNode.get(sessionId, id, scope.through) as BranchNode | undefined;\n\t\t\tif (target?.depth == null) unknown = true;\n\t\t\telse if (resolvedAncestor(sessionId, leaf, target)) return row;\n\t\t}\n\t\tif (!unknown) return undefined;\n\t}\n\t// Arbitrary SDK/legacy links stay intact; unknown ancestry is never reported as absence.\n\tconst visited = new Set<string>();\n\tlet current = leaf;\n\tlet lookups = 0;\n\tfor (;;) {\n\t\tif (targets.includes(current.id)) return row;\n\t\tvisited.add(current.id);\n\t\tif (current.parent_id === null) return undefined;\n\t\tif (visited.has(current.parent_id)) throw new Error(\"History branch ancestry contains a cycle\");\n\t\tif (lookups === MAX_PARENT_LOOKUPS) throw new Error(\"History branch ancestry parent lookup budget exceeded\");\n\t\tlookups++;\n\t\tconst parent = branchNode.get(sessionId, current.parent_id, scope.through) as BranchNode | undefined;\n\t\tif (!parent) throw new Error(\"History branch ancestry has a missing parent in the indexed prefix\");\n\t\tcurrent = parent;\n\t}\n}\ntype QueryCandidate = Pick<Row, \"id\" | \"parent_id\" | \"kind\" | \"sequence\">;\nconst MAX_QUERY_CANDIDATES = 256;\nconst queryCandidate = db.prepare(\"SELECT id,parent_id,kind,sequence FROM source_event WHERE session=? AND sequence=?\");\nfunction sourceCandidate(sessionId: string, sequence: number): QueryCandidate {\n\tconst row = queryCandidate.get(sessionId, sequence) as QueryCandidate | undefined;\n\tif (!row) throw new Error(\"History query source metadata is unavailable\");\n\treturn row;\n}\nfunction branchFilter(sessionId: string, through: number, scope?: { leafId: string | null }) {\n\tif (!scope) return { empty: false, matches: (_row: QueryCandidate) => true };\n\tconst leaf = validateBranchScope(sessionId, through, scope);\n\tif (!leaf) return { empty: true, matches: (_row: QueryCandidate) => false };\n\tif (leaf.depth !== null)\n\t\treturn {\n\t\t\tempty: false,\n\t\t\tmatches: (row: QueryCandidate) => pointEvent(sessionId, row.id, { ...scope, through }) !== undefined,\n\t\t};\n\t// A short arbitrary SDK/apply branch can be proved, but an unfinished walk is never empty ancestry.\n\tconst ancestors = new Set<string>([leaf.id]);\n\tlet current = leaf;\n\tlet lookups = 0;\n\twhile (current.parent_id !== null) {\n\t\tif (ancestors.has(current.parent_id)) throw new Error(\"History branch ancestry contains a cycle\");\n\t\tif (lookups++ === MAX_PARENT_LOOKUPS) throw new Error(\"History branch ancestry parent lookup budget exceeded\");\n\t\tconst parent = branchNode.get(sessionId, current.parent_id, through) as BranchNode | undefined;\n\t\tif (!parent) throw new Error(\"History branch ancestry has a missing parent in the indexed prefix\");\n\t\tancestors.add(parent.id);\n\t\tcurrent = parent;\n\t}\n\treturn {\n\t\tempty: false,\n\t\tmatches: (row: QueryCandidate) =>\n\t\t\tancestors.has(row.id) || (row.kind === \"request\" && row.parent_id !== null && ancestors.has(row.parent_id)),\n\t};\n}\nfunction selectCandidates<T>(\n\trows: T[],\n\tmatches: (row: T) => boolean,\n\tlimit: number,\n\tlabel: string,\n\tbudget = { remaining: MAX_QUERY_CANDIDATES },\n): T[] {\n\tconst selected: T[] = [];\n\tfor (const row of rows) {\n\t\tif (budget.remaining === 0) throw new Error(`${label} candidate budget exceeded`);\n\t\tbudget.remaining--;\n\t\tif (matches(row)) selected.push(row);\n\t\tif (selected.length === limit + 1) break;\n\t}\n\treturn selected;\n}\nfunction query(request: Extract<HistoryIndexRequest, { action: \"page\" | \"search\" }>) {\n\tif (!Number.isSafeInteger(request.limit) || request.limit < 1 || request.limit > 128)\n\t\tthrow new Error(\"Index page limit must be between1 and128\");\n\tif (\n\t\t!Number.isSafeInteger(request.through) ||\n\t\trequest.through < 0 ||\n\t\t(request.action === \"page\" && (!Number.isSafeInteger(request.after) || request.after < 0))\n\t)\n\t\tthrow new Error(\"Invalid history query source range\");\n\tconst indexedThrough = Number(\n\t\tdb.prepare(\"SELECT sequence FROM coverage WHERE session=?\").get(request.sessionId)?.sequence ?? 0,\n\t);\n\tconst branch = branchFilter(request.sessionId, request.through, request.scope);\n\tlet rows: QueryCandidate[];\n\tlet scanNext: number | null = null;\n\tif (request.action === \"page\") {\n\t\tconst candidates = branch.empty\n\t\t\t? []\n\t\t\t: (db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"SELECT id,parent_id,kind,sequence FROM source_event INDEXED BY sqlite_autoindex_source_event_2 WHERE session=? AND sequence>? AND sequence<=? ORDER BY sequence LIMIT ?\",\n\t\t\t\t\t)\n\t\t\t\t\t.all(\n\t\t\t\t\t\trequest.sessionId,\n\t\t\t\t\t\trequest.after,\n\t\t\t\t\t\trequest.through,\n\t\t\t\t\t\trequest.scan ? request.limit + 1 : MAX_QUERY_CANDIDATES + 1,\n\t\t\t\t\t) as QueryCandidate[]);\n\t\tif (request.scan) {\n\t\t\tconst examined = candidates.slice(0, request.limit);\n\t\t\trows = examined.filter(branch.matches);\n\t\t\tif (candidates.length > examined.length) scanNext = examined[examined.length - 1].sequence;\n\t\t} else {\n\t\t\trows = selectCandidates(candidates, branch.matches, request.limit, \"History page selection\");\n\t\t}\n\t} else {\n\t\tif (Buffer.byteLength(request.query) > 8192) throw new Error(\"Index query limit exceeded\");\n\t\tconst queryTerms = terms(request.query);\n\t\tif (queryTerms.length > 32) throw new Error(\"Index query term limit exceeded\");\n\t\tconst queryTermCount = db.prepare(\"SELECT count FROM term_count WHERE session=? AND term=?\");\n\t\tconst counted = queryTerms.map((term) => ({\n\t\t\tterm,\n\t\t\tcount: Number(queryTermCount.get(request.sessionId, term)?.count ?? 0),\n\t\t}));\n\t\tcounted.sort((left, right) => left.count - right.count);\n\t\tconst [first, ...rest] = counted.map(({ term }) => term);\n\t\tconst postings =\n\t\t\tfirst && !branch.empty\n\t\t\t\t? db\n\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\"SELECT sequence FROM source_term INDEXED BY sqlite_autoindex_source_term_1 WHERE session=? AND term=? AND sequence<=? ORDER BY sequence DESC LIMIT ?\",\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.all(request.sessionId, first, request.through, MAX_QUERY_CANDIDATES + 1)\n\t\t\t\t: [];\n\t\tconst requiredTerm = db.prepare(\"SELECT 1 FROM source_term WHERE session=? AND term=? AND sequence=?\");\n\t\tconst selected = selectCandidates(\n\t\t\tpostings,\n\t\t\t(posting) => {\n\t\t\t\tconst sequence = Number(posting.sequence);\n\t\t\t\treturn (\n\t\t\t\t\trest.every((term) => !!requiredTerm.get(request.sessionId, term, sequence)) &&\n\t\t\t\t\tbranch.matches(sourceCandidate(request.sessionId, sequence))\n\t\t\t\t);\n\t\t\t},\n\t\t\trequest.limit,\n\t\t\t\"History search selection\",\n\t\t);\n\t\trows = selected.map((posting) => sourceCandidate(request.sessionId, Number(posting.sequence)));\n\t}\n\tlet incompleteText = false;\n\tif (request.action === \"search\" && !branch.empty) {\n\t\tconst candidates = db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT id,parent_id,kind,sequence FROM source_event INDEXED BY source_incomplete WHERE session=? AND text_complete=0 AND sequence<=? ORDER BY sequence LIMIT ?\",\n\t\t\t)\n\t\t\t.all(request.sessionId, request.through, MAX_QUERY_CANDIDATES + 1) as QueryCandidate[];\n\t\tincompleteText = selectCandidates(candidates, branch.matches, 0, \"History search coverage\").length > 0;\n\t}\n\tconst events: IndexedSourceEvent[] = [];\n\tlet bytes = 0;\n\tconst content = db.prepare(\"SELECT * FROM source_event WHERE session=? AND sequence=?\");\n\tfor (const row of rows.slice(0, request.limit)) {\n\t\tconst indexed = event(content.get(request.sessionId, row.sequence) as Row);\n\t\tbytes += Buffer.byteLength(JSON.stringify(indexed));\n\t\tif (bytes > 1024 * 1024) break;\n\t\tevents.push(indexed);\n\t}\n\tconst truncated = events.length < rows.length || scanNext !== null;\n\treturn {\n\t\tevents,\n\t\tindexedThrough,\n\t\tcoverage: indexedThrough < request.through || incompleteText ? \"partial\" : \"complete\",\n\t\ttruncated,\n\t\tnextAfter:\n\t\t\trequest.action !== \"page\"\n\t\t\t\t? null\n\t\t\t\t: events.length < rows.length\n\t\t\t\t\t? (events[events.length - 1]?.sequence ?? request.after)\n\t\t\t\t\t: scanNext,\n\t};\n}\nfunction taskEvidence(request: Extract<HistoryIndexRequest, { action: \"task_evidence\" }>): TaskEvidencePage {\n\tconst { sessionId, scope, options } = request;\n\tconst limit = options.limit ?? 64;\n\tconst after = options.after ?? { sequence: 0, ordinal: -1 };\n\tif (\n\t\t!Number.isSafeInteger(limit) ||\n\t\tlimit < 1 ||\n\t\tlimit > 128 ||\n\t\t!Number.isSafeInteger(after.sequence) ||\n\t\tafter.sequence < 0 ||\n\t\t!Number.isSafeInteger(after.ordinal) ||\n\t\tafter.ordinal < -1 ||\n\t\t(options.itemId !== undefined && typeof options.itemId !== \"string\") ||\n\t\t(options.taskKey !== undefined && typeof options.taskKey !== \"string\")\n\t)\n\t\tthrow new Error(\"Invalid bounded task-evidence selection\");\n\tconst cursor = db.prepare(\"SELECT frontier FROM source_cursor WHERE session=?\").get(sessionId);\n\tconst page: TaskEvidencePage = {\n\t\tentries: [],\n\t\tindexedThrough: cursor ? Number(JSON.parse(String(cursor.frontier)).indexedThrough) : 0,\n\t\tcoverage: \"partial\",\n\t\tstructuredOnly: true,\n\t\tselective: true,\n\t\ttruncated: false,\n\t\tnextAfter: null,\n\t};\n\tif (!cursor) return page;\n\tconst frontier = JSON.parse(String(cursor.frontier)) as SessionJournalState;\n\tpage.sourceIdentity = { journalPath: frontier.journalPath, dev: frontier.dev, ino: frontier.ino };\n\tconst branch = branchFilter(sessionId, scope.through, scope);\n\tconst coverageBudget = { remaining: MAX_QUERY_CANDIDATES };\n\tconst lossKeys = options.taskKey === undefined ? [undefined] : [null, options.taskKey];\n\tlet importedLoss = false;\n\tif (!branch.empty)\n\t\tfor (const key of lossKeys) {\n\t\t\tconst keyed = key !== undefined;\n\t\t\tconst loss = db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT sequence FROM task_import_loss ${keyed ? \"INDEXED BY task_loss_key\" : \"INDEXED BY sqlite_autoindex_task_import_loss_1\"} WHERE session=? AND sequence<=?${keyed ? \" AND task_key IS ?\" : \"\"} ORDER BY sequence LIMIT ?`,\n\t\t\t\t)\n\t\t\t\t.all(sessionId, scope.through, ...(key === undefined ? [] : [key]), coverageBudget.remaining + 1);\n\t\t\tif (\n\t\t\t\tselectCandidates(\n\t\t\t\t\tloss,\n\t\t\t\t\t(row) => branch.matches(sourceCandidate(sessionId, Number(row.sequence))),\n\t\t\t\t\t0,\n\t\t\t\t\t\"Task evidence coverage\",\n\t\t\t\t\tcoverageBudget,\n\t\t\t\t).length\n\t\t\t) {\n\t\t\t\timportedLoss = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\tpage.coverage = page.indexedThrough >= scope.through && !importedLoss ? \"complete\" : \"partial\";\n\tconst task = options.taskKey === undefined ? \"\" : \" AND task_key=?\";\n\tconst item = options.itemId === undefined ? \"\" : \" AND item_id=?\";\n\tconst indexName =\n\t\toptions.taskKey !== undefined\n\t\t\t? options.itemId !== undefined\n\t\t\t\t? \"task_item\"\n\t\t\t\t: \"task_sequence\"\n\t\t\t: options.itemId !== undefined\n\t\t\t\t? \"task_item_sequence\"\n\t\t\t\t: \"sqlite_autoindex_task_evidence_1\";\n\t// Each filter shape has an ordered index seek; SQL LIMIT is before branch filtering.\n\tconst candidates = branch.empty\n\t\t? []\n\t\t: db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT sequence,ordinal FROM task_evidence INDEXED BY ${indexName} WHERE session=?${task}${item} AND (sequence,ordinal)>(?,?) AND sequence<=? ORDER BY sequence,ordinal LIMIT ?`,\n\t\t\t\t)\n\t\t\t\t.all(\n\t\t\t\t\tsessionId,\n\t\t\t\t\t...(options.taskKey === undefined ? [] : [options.taskKey]),\n\t\t\t\t\t...(options.itemId === undefined ? [] : [options.itemId]),\n\t\t\t\t\tafter.sequence,\n\t\t\t\t\tafter.ordinal,\n\t\t\t\t\tscope.through,\n\t\t\t\t\tMAX_QUERY_CANDIDATES + 1,\n\t\t\t\t);\n\tconst rows = selectCandidates(\n\t\tcandidates,\n\t\t(row) => branch.matches(sourceCandidate(sessionId, Number(row.sequence))),\n\t\tlimit,\n\t\t\"Task evidence selection\",\n\t);\n\tconst content = db.prepare(\n\t\t\"SELECT source_ref,projection FROM task_evidence WHERE session=? AND sequence=? AND ordinal=?\",\n\t);\n\tconst itemIdentity = db.prepare(\n\t\t\"SELECT CASE WHEN length(CAST(item_id AS BLOB))<=? THEN item_id END AS item_id,item_id IS NOT NULL AS has_item FROM task_evidence WHERE session=? AND sequence=? AND ordinal=?\",\n\t);\n\tconst fits = (entry: IndexedTaskEvidence, entries = page.entries) =>\n\t\tBuffer.byteLength(\n\t\t\tJSON.stringify({\n\t\t\t\t...page,\n\t\t\t\tentries: [...entries, entry],\n\t\t\t\tnextAfter: { sequence: entry.sequence, ordinal: entry.ordinal },\n\t\t\t}),\n\t\t) <= TASK_PAGE_BYTES;\n\tfor (const row of rows.slice(0, limit)) {\n\t\tconst position = { sequence: Number(row.sequence), ordinal: Number(row.ordinal) };\n\t\tconst stored = content.get(sessionId, position.sequence, position.ordinal)!;\n\t\tconst sourceReference = (): Extract<IndexedTaskEvidence, { truncated: true }> => {\n\t\t\tconst identity = itemIdentity.get(TASK_PAGE_BYTES, sessionId, position.sequence, position.ordinal)!;\n\t\t\tconst reference: Extract<IndexedTaskEvidence, { truncated: true }> = {\n\t\t\t\t...position,\n\t\t\t\tsource: JSON.parse(String(stored.source_ref)),\n\t\t\t\ttruncated: true,\n\t\t\t\t...(identity.item_id !== null\n\t\t\t\t\t? { itemId: String(identity.item_id) }\n\t\t\t\t\t: identity.has_item\n\t\t\t\t\t\t? { itemIdOmitted: true as const }\n\t\t\t\t\t\t: {}),\n\t\t\t};\n\t\t\tif (!fits(reference, []) && reference.itemId !== undefined) {\n\t\t\t\tdelete reference.itemId;\n\t\t\t\treference.itemIdOmitted = true;\n\t\t\t}\n\t\t\treturn reference;\n\t\t};\n\t\tlet entry: IndexedTaskEvidence =\n\t\t\tstored.projection === null\n\t\t\t\t? sourceReference()\n\t\t\t\t: {\n\t\t\t\t\t\t...position,\n\t\t\t\t\t\tprojection: JSON.parse(String(stored.projection)),\n\t\t\t\t\t\ttruncated: false,\n\t\t\t\t\t};\n\t\tif (!fits(entry)) {\n\t\t\tif (page.entries.length) break;\n\t\t\tentry = sourceReference();\n\t\t}\n\t\tpage.entries.push(entry);\n\t}\n\tconst more = page.entries.length < rows.length;\n\tpage.truncated = more || page.entries.some((entry) => entry.truncated);\n\tif (more && page.entries.length) {\n\t\tconst last = page.entries[page.entries.length - 1];\n\t\tpage.nextAfter = { sequence: last.sequence, ordinal: last.ordinal };\n\t}\n\treturn page;\n}\n\ntype ContextNode = BranchNode &\n\tContextState &\n\tPick<Row, \"sequence\" | \"kind\" | \"locator\" | \"revision\" | \"authority\" | \"qualification\" | \"retention\">;\nconst manifestNode =\n\tdb.prepare(`SELECT e.id,e.parent_id,e.sequence,e.kind,e.locator,e.revision,e.authority,e.qualification,e.retention,a.depth,c.visible_head,c.previous_visible,c.visible_count,c.latest_compaction,c.first_kept_id\n FROM source_event e JOIN context_node c ON c.session=e.session AND c.id=e.id\n LEFT JOIN source_ancestry a ON a.session=e.session AND a.id=e.id\n WHERE e.session=? AND e.id=? AND e.sequence<=?`);\nconst visibleJump = db.prepare(`SELECT j.ancestor_id,c.visible_count FROM source_jump j\n JOIN context_node c ON c.session=j.session AND c.id=j.ancestor_id\n WHERE j.session=? AND j.id=? AND j.level=?`);\nfunction contextRef(node: ContextNode): ContextRef {\n\treturn {\n\t\tentryId: node.id,\n\t\tsequence: node.sequence,\n\t\tauthority: node.authority,\n\t\t...(node.qualification === null ? {} : { qualification: node.qualification }),\n\t\t...(node.retention === null ? {} : { retention: node.retention }),\n\t\tkind: node.kind as ContextRef[\"kind\"],\n\t\tlocator: JSON.parse(node.locator) as ContextRef[\"locator\"],\n\t\trevision: node.revision,\n\t};\n}\nfunction parentPath(request: Extract<HistoryIndexRequest, { action: \"parent_path\" }>): ParentPathPage {\n\tconst { sessionId, scope, options } = request;\n\tconst limit = options.limit ?? 64;\n\tif (!Number.isSafeInteger(limit) || limit < 1 || limit > 128)\n\t\tthrow new Error(\"Parent path limit must be between1 and128\");\n\tconst saved = db.prepare(\"SELECT * FROM source_cursor WHERE session=?\").get(sessionId);\n\tif (!saved) throw new Error(\"Parent path index is unavailable; synchronize the source first\");\n\tconst snapshot = JSON.parse(String(saved.frontier)) as SessionJournalState & { indexedThrough: number };\n\tif (snapshot.format !== \"framed\" || snapshot.indexedThrough < scope.through)\n\t\tthrow new Error(\"Parent path index has not reached the requested source prefix\");\n\tconst leaf = validateBranchScope(sessionId, scope.through, scope);\n\tif (leaf?.depth === null) throw new Error(\"Parent path lineage is unresolved\");\n\tconst revision =\n\t\tscope.through === 0\n\t\t\t? saved.header_checksum\n\t\t\t: db.prepare(\"SELECT revision FROM source_event WHERE session=? AND sequence=?\").get(sessionId, scope.through)\n\t\t\t\t\t?.revision;\n\tif (typeof revision !== \"string\") throw new Error(\"Parent path source prefix is unavailable\");\n\tconst anchor: Omit<ParentPathCursor, \"nextDepth\"> = {\n\t\tversion: 1,\n\t\tsessionId,\n\t\tjournalPath: snapshot.journalPath,\n\t\tdev: snapshot.dev,\n\t\tino: snapshot.ino,\n\t\tleafId: scope.leafId,\n\t\tthrough: scope.through,\n\t\tthroughRevision: revision,\n\t};\n\tconst cursor = options.cursor;\n\tif (\n\t\tcursor &&\n\t\t(cursor.version !== 1 ||\n\t\t\tcursor.sessionId !== sessionId ||\n\t\t\tcursor.journalPath !== snapshot.journalPath ||\n\t\t\tcursor.dev !== snapshot.dev ||\n\t\t\tcursor.ino !== snapshot.ino ||\n\t\t\tcursor.leafId !== scope.leafId ||\n\t\t\tcursor.through !== scope.through ||\n\t\t\tcursor.throughRevision !== revision)\n\t)\n\t\tthrow new Error(\"Parent path cursor mismatch\");\n\tconst count = leaf ? leaf.depth! + 1 : 0;\n\tconst start = cursor ? cursor.nextDepth : 0;\n\tif (!Number.isSafeInteger(start) || start < 0 || start > count)\n\t\tthrow new Error(\"Invalid parent path cursor position\");\n\tconst page: ParentPathPage = { events: [], nextCursor: null, totalEntries: count };\n\tif (start === count) return page;\n\tconst end = Math.min(start + limit - 1, count - 1);\n\tlet id = leaf!.id;\n\tlet difference = leaf!.depth! - end;\n\tfor (let level = 0; difference > 0 && level < MAX_JUMP_LEVELS; level++) {\n\t\tif (difference % 2 === 1) {\n\t\t\tconst jump = ancestorJump.get(sessionId, id, level);\n\t\t\tif (!jump) throw new Error(\"Parent path ancestry metadata is incomplete\");\n\t\t\tid = String(jump.ancestor_id);\n\t\t}\n\t\tdifference = Math.floor(difference / 2);\n\t}\n\t// Reverse only this bounded page of IDs, then load metadata in chronological order.\n\tconst ids: string[] = [];\n\tfor (let depth = end; depth >= start; depth--) {\n\t\tconst node = branchNode.get(sessionId, id, scope.through) as BranchNode | undefined;\n\t\tif (!node || node.depth !== depth) throw new Error(\"Parent path ancestry metadata is incomplete\");\n\t\tids.push(node.id);\n\t\tif (depth > start) {\n\t\t\tif (node.parent_id === null) throw new Error(\"Parent path parent reference is missing\");\n\t\t\tid = node.parent_id;\n\t\t}\n\t}\n\tids.reverse();\n\tconst content = db.prepare(\"SELECT * FROM source_event WHERE session=? AND id=? AND sequence<=?\");\n\tlet bytes = Buffer.byteLength(\n\t\tJSON.stringify({ ...page, nextCursor: { ...anchor, nextDepth: Number.MAX_SAFE_INTEGER } }),\n\t);\n\tfor (const entryId of ids) {\n\t\tconst row = content.get(sessionId, entryId, scope.through) as Row | undefined;\n\t\tif (!row) throw new Error(\"Parent path source metadata is unavailable; rebuild the derived index\");\n\t\tconst item = event(row);\n\t\tconst addition = Buffer.byteLength(JSON.stringify(item)) + (page.events.length ? 1 : 0);\n\t\tif (bytes + addition > 1024 * 1024 - 1024) break;\n\t\tpage.events.push(item);\n\t\tbytes += addition;\n\t}\n\tif (page.events.length === 0) throw new Error(\"Parent path metadata exceeds the page byte limit\");\n\tconst next = start + page.events.length;\n\tpage.nextCursor = next < count ? { ...anchor, nextDepth: next } : null;\n\treturn page;\n}\nfunction ipythonSentMessages(\n\trequest: Extract<HistoryIndexRequest, { action: \"ipython_sent_messages\" }>,\n): IpythonSentMessagesPage {\n\tconst { sessionId, scope, toolCallId, options } = request;\n\tconst limit = options.limit ?? 64;\n\tif (!Number.isSafeInteger(limit) || limit < 1 || limit > 128)\n\t\tthrow new Error(\"IPython sent-message limit must be between1 and128\");\n\tif (\n\t\ttypeof toolCallId !== \"string\" ||\n\t\ttoolCallId.length > MAX_CONTEXT_UPDATE_KEY ||\n\t\t(options.messageId !== undefined &&\n\t\t\t(typeof options.messageId !== \"string\" || options.messageId.length > MAX_CONTEXT_UPDATE_KEY))\n\t)\n\t\tthrow new Error(\"IPython sent-message key limit exceeded\");\n\tconst saved = db.prepare(\"SELECT * FROM source_cursor WHERE session=?\").get(sessionId);\n\tif (!saved) throw new Error(\"IPython sent-message index is unavailable; synchronize the source first\");\n\tconst snapshot = JSON.parse(String(saved.frontier)) as SessionJournalState & { indexedThrough: number };\n\tif (snapshot.format !== \"framed\" || snapshot.indexedThrough < scope.through)\n\t\tthrow new Error(\"IPython sent-message index has not reached the requested source prefix\");\n\tconst leaf = validateBranchScope(sessionId, scope.through, scope);\n\tif (leaf?.depth === null) throw new Error(\"IPython sent-message branch lineage is unresolved\");\n\tconst revision =\n\t\tscope.through === 0\n\t\t\t? saved.header_checksum\n\t\t\t: db.prepare(\"SELECT revision FROM source_event WHERE session=? AND sequence=?\").get(sessionId, scope.through)\n\t\t\t\t\t?.revision;\n\tif (typeof revision !== \"string\") throw new Error(\"IPython sent-message source prefix is unavailable\");\n\tconst messageId = options.messageId ?? null;\n\tconst anchor: Omit<IpythonSentMessagesCursor, \"after\"> = {\n\t\tversion: 1,\n\t\tsessionId,\n\t\tjournalPath: snapshot.journalPath,\n\t\tdev: snapshot.dev,\n\t\tino: snapshot.ino,\n\t\tleafId: scope.leafId,\n\t\tthrough: scope.through,\n\t\tthroughRevision: revision,\n\t\ttoolCallId,\n\t\tmessageId,\n\t};\n\tconst cursor = options.cursor;\n\tif (\n\t\tcursor &&\n\t\t(cursor.version !== 1 ||\n\t\t\tcursor.sessionId !== sessionId ||\n\t\t\tcursor.journalPath !== snapshot.journalPath ||\n\t\t\tcursor.dev !== snapshot.dev ||\n\t\t\tcursor.ino !== snapshot.ino ||\n\t\t\tcursor.leafId !== scope.leafId ||\n\t\t\tcursor.through !== scope.through ||\n\t\t\tcursor.throughRevision !== revision ||\n\t\t\tcursor.toolCallId !== toolCallId ||\n\t\t\tcursor.messageId !== messageId)\n\t)\n\t\tthrow new Error(\"IPython sent-message cursor mismatch\");\n\tlet after = cursor ? cursor.after : 0;\n\tif (!Number.isSafeInteger(after) || after < 0 || after > scope.through)\n\t\tthrow new Error(\"Invalid IPython sent-message cursor position\");\n\tconst page: IpythonSentMessagesPage = { refs: [], nextCursor: null };\n\tif (!leaf) return page;\n\tconst kind = messageId === null ? \"ipython-sent-message\" : \"ipython-sent-message-id\";\n\tconst key = messageId === null ? toolCallId : JSON.stringify([toolCallId, messageId]);\n\tconst candidates = db\n\t\t.prepare(`SELECT event_id AS id,sequence FROM context_update\n WHERE session=? AND update_kind=? AND target_key=? AND sequence>? AND sequence<=?\n ORDER BY sequence LIMIT ?`)\n\t\t.all(sessionId, kind, key, after, scope.through, MAX_CONTEXT_UPDATE_CANDIDATES + 1) as {\n\t\tid: string;\n\t\tsequence: number;\n\t}[];\n\tlet bytes = Buffer.byteLength(\n\t\tJSON.stringify({ ...page, nextCursor: { ...anchor, after: Number.MAX_SAFE_INTEGER } }),\n\t);\n\tconst content = db.prepare(\n\t\t\"SELECT id,sequence,kind,locator,revision FROM source_event WHERE session=? AND id=? AND sequence<=?\",\n\t);\n\tfor (const candidate of candidates.slice(0, MAX_CONTEXT_UPDATE_CANDIDATES)) {\n\t\tif (page.refs.length >= limit) break;\n\t\tconst node = branchNode.get(sessionId, candidate.id, scope.through) as BranchNode | undefined;\n\t\tif (!node) throw new Error(\"IPython sent-message source metadata is unavailable\");\n\t\tif (node.depth !== null && resolvedAncestor(sessionId, leaf, node)) {\n\t\t\tconst row = content.get(sessionId, candidate.id, scope.through) as SourceRefRow | undefined;\n\t\t\tif (!row) throw new Error(\"IPython sent-message source metadata is unavailable\");\n\t\t\tconst ref = contextUpdateRef(row);\n\t\t\tconst addition = Buffer.byteLength(JSON.stringify(ref)) + (page.refs.length ? 1 : 0);\n\t\t\tif (bytes + addition > TASK_PAGE_BYTES) {\n\t\t\t\tif (page.refs.length === 0) throw new Error(\"IPython sent-message ref exceeds the page byte limit\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tpage.refs.push(ref);\n\t\t\tbytes += addition;\n\t\t}\n\t\tafter = candidate.sequence;\n\t}\n\tif (candidates.length > 0 && after < candidates[candidates.length - 1].sequence)\n\t\tpage.nextCursor = { ...anchor, after };\n\treturn page;\n}\nfunction currentSourceBootstrap(\n\trequest: Extract<HistoryIndexRequest, { action: \"current_source_bootstrap\" }>,\n): SourceBootstrapState {\n\tconst { sessionId, snapshot } = request;\n\tconst saved = db.prepare(\"SELECT * FROM source_cursor WHERE session=?\").get(sessionId);\n\tif (!saved) throw new Error(\"Current source bootstrap is unavailable; synchronize the source first\");\n\tconst current = JSON.parse(String(saved.frontier)) as SessionJournalState & { indexedThrough: number };\n\tif (\n\t\tcurrent.format !== \"framed\" ||\n\t\tsnapshot.format !== \"framed\" ||\n\t\tcurrent.journalPath !== snapshot.journalPath ||\n\t\tcurrent.dev !== snapshot.dev ||\n\t\tcurrent.ino !== snapshot.ino ||\n\t\tcurrent.byteLength !== snapshot.byteLength ||\n\t\tcurrent.nextSequence !== snapshot.nextSequence ||\n\t\tcurrent.checksum !== snapshot.checksum ||\n\t\tcurrent.indexedThrough !== snapshot.nextSequence - 1\n\t)\n\t\tthrow new Error(\"Current source bootstrap snapshot mismatch\");\n\tconst reference = (id: unknown): IndexedSourceEvent | null => {\n\t\tif (id === null) return null;\n\t\tconst row = db\n\t\t\t.prepare(\"SELECT * FROM source_event WHERE session=? AND id=? AND sequence<=?\")\n\t\t\t.get(sessionId, String(id), current.indexedThrough) as Row | undefined;\n\t\tif (!row) throw new Error(\"Current source bootstrap metadata is unavailable; rebuild the derived index\");\n\t\treturn event(row);\n\t};\n\treturn {\n\t\tleaf: reference(saved.source_leaf),\n\t\tsessionInfo: reference(saved.source_session_info),\n\t\tsessionState: reference(saved.source_session_state),\n\t\tcompactionCount: Number(saved.source_compaction_count),\n\t\tcontentPrefix: Number(saved.source_content_prefix),\n\t\thasUserContent: saved.source_has_user_content === 1,\n\t};\n}\nfunction sourceRelation(\n\trequest: Extract<HistoryIndexRequest, { action: \"source_label\" | \"source_assistant_usage\" }>,\n): IndexedSourceEvent | undefined {\n\tconst { sessionId, targetId, through } = request;\n\tif (typeof targetId !== \"string\" || targetId.length > 512) throw new Error(\"Source relation target limit exceeded\");\n\tif (!Number.isSafeInteger(through) || through < 0) throw new Error(\"Invalid history source prefix\");\n\tconst saved = db.prepare(\"SELECT frontier FROM source_cursor WHERE session=?\").get(sessionId);\n\tif (!saved) throw new Error(\"Canonical source index is unavailable; synchronize the source first\");\n\tconst snapshot = JSON.parse(String(saved.frontier)) as SessionJournalState & { indexedThrough: number };\n\tif (snapshot.format !== \"framed\" || snapshot.indexedThrough < through)\n\t\tthrow new Error(\"Canonical source index has not reached the requested source prefix\");\n\tconst kind = request.action === \"source_label\" ? \"label\" : \"assistant-usage\";\n\tconst row = db\n\t\t.prepare(`SELECT e.* FROM context_update u JOIN source_event e\n ON e.session=u.session AND e.id=u.event_id\n WHERE u.session=? AND u.update_kind=? AND u.target_key=? AND u.sequence<=?\n ORDER BY u.sequence DESC LIMIT 1`)\n\t\t.get(sessionId, kind, targetId, through) as Row | undefined;\n\treturn row ? event(row) : undefined;\n}\nfunction branchBootstrap(request: Extract<HistoryIndexRequest, { action: \"branch_bootstrap\" }>): BranchBootstrapState {\n\tconst { sessionId, scope } = request;\n\tconst saved = db.prepare(\"SELECT frontier FROM source_cursor WHERE session=?\").get(sessionId);\n\tif (!saved) throw new Error(\"Branch bootstrap index is unavailable; synchronize the source first\");\n\tconst snapshot = JSON.parse(String(saved.frontier)) as SessionJournalState & { indexedThrough: number };\n\tif (snapshot.format !== \"framed\" || snapshot.indexedThrough < scope.through)\n\t\tthrow new Error(\"Branch bootstrap index has not reached the requested source prefix\");\n\tconst leaf = validateBranchScope(sessionId, scope.through, scope);\n\tif (leaf?.depth === null) throw new Error(\"Branch bootstrap branch lineage is unresolved\");\n\tif (\n\t\tscope.through > 0 &&\n\t\t!db.prepare(\"SELECT 1 FROM source_event WHERE session=? AND sequence=?\").get(sessionId, scope.through)\n\t)\n\t\tthrow new Error(\"Branch bootstrap source prefix is unavailable\");\n\tconst state = leaf\n\t\t? (contextParent.get(sessionId, leaf.id) as (ContextState & BootstrapColumns) | undefined)\n\t\t: undefined;\n\tif (leaf && !state) throw new Error(\"Branch bootstrap metadata is unavailable; rebuild the derived index\");\n\tconst reference = (id: string | null | undefined): IndexedSourceEvent | null => {\n\t\tif (id == null) return null;\n\t\tconst row = db\n\t\t\t.prepare(\"SELECT * FROM source_event WHERE session=? AND id=? AND sequence<=?\")\n\t\t\t.get(sessionId, id, scope.through) as Row | undefined;\n\t\tif (!row) throw new Error(\"Branch bootstrap source metadata is unavailable; rebuild the derived index\");\n\t\treturn event(row);\n\t};\n\treturn {\n\t\tmodel: reference(state?.latest_model),\n\t\tthinkingLevel: reference(state?.latest_thinking),\n\t\tserviceTier: reference(state?.latest_service_tier),\n\t\tgoalState: reference(state?.latest_goal),\n\t\trlmMaxDepth: reference(state?.latest_rlm_max_depth),\n\t\tlatestCompaction: reference(state?.latest_compaction),\n\t\tcontextUsageAssistant: reference(state?.context_usage_assistant),\n\t\tgitState: reference(state?.latest_git_state),\n\t\tagentStatus: reference(state?.latest_agent_status),\n\t\thasBranchMessage: state?.has_branch_message === 1,\n\t\thasContextMessages: !!state && (state.has_session_message === 1 || state.latest_compaction !== null),\n\t\tgoalSeedable: !state || state.goal_seedable === 1,\n\t};\n}\nfunction contextManifest(request: Extract<HistoryIndexRequest, { action: \"context_manifest\" }>): ContextManifestPage {\n\tconst { sessionId, scope, options } = request;\n\tconst limit = options.limit ?? 64;\n\tif (!Number.isSafeInteger(limit) || limit < 1 || limit > 128)\n\t\tthrow new Error(\"Context manifest limit must be between1 and128\");\n\tconst saved = db.prepare(\"SELECT * FROM source_cursor WHERE session=?\").get(sessionId);\n\tif (!saved) throw new Error(\"Context manifest index is unavailable; synchronize the source first\");\n\tconst snapshot = JSON.parse(String(saved.frontier)) as SessionJournalState & { indexedThrough: number };\n\tif (snapshot.format !== \"framed\" || snapshot.indexedThrough < scope.through)\n\t\tthrow new Error(\"Context manifest index has not reached the requested source prefix\");\n\tvalidateBranchScope(sessionId, scope.through, scope);\n\tconst revision =\n\t\tscope.through === 0\n\t\t\t? saved.header_checksum\n\t\t\t: db.prepare(\"SELECT revision FROM source_event WHERE session=? AND sequence=?\").get(sessionId, scope.through)\n\t\t\t\t\t?.revision;\n\tif (typeof revision !== \"string\") throw new Error(\"Context manifest source prefix is unavailable\");\n\tconst anchor: Omit<ContextManifestCursor, \"nextOrdinal\"> = {\n\t\tversion: 1,\n\t\tsessionId,\n\t\tjournalPath: snapshot.journalPath,\n\t\tdev: snapshot.dev,\n\t\tino: snapshot.ino,\n\t\tleafId: scope.leafId,\n\t\tthrough: scope.through,\n\t\tthroughRevision: revision,\n\t};\n\tconst cursor = options.cursor;\n\tif (\n\t\tcursor &&\n\t\t(cursor.version !== 1 ||\n\t\t\tcursor.sessionId !== sessionId ||\n\t\t\tcursor.journalPath !== snapshot.journalPath ||\n\t\t\tcursor.dev !== snapshot.dev ||\n\t\t\tcursor.ino !== snapshot.ino ||\n\t\t\tcursor.leafId !== scope.leafId ||\n\t\t\tcursor.through !== scope.through ||\n\t\t\tcursor.throughRevision !== revision)\n\t)\n\t\tthrow new Error(\"Context manifest cursor mismatch\");\n\tif (cursor && (!Number.isSafeInteger(cursor.nextOrdinal) || cursor.nextOrdinal < 1))\n\t\tthrow new Error(\"Invalid context manifest cursor ordinal\");\n\tconst result: Extract<ContextManifestPage, { selection: \"known\" }> = {\n\t\tselection: \"known\",\n\t\tsummaryRef: null,\n\t\tactiveBase: 0,\n\t\tretainedMessageCount: 0,\n\t\tactiveMessageCount: 0,\n\t\trefs: [],\n\t\torder: \"source\",\n\t\tnextCursor: null,\n\t};\n\tconst node = (id: string): ContextNode => {\n\t\tconst value = manifestNode.get(sessionId, id, scope.through) as ContextNode | undefined;\n\t\tif (!value) throw new Error(\"Context manifest metadata is unavailable; rebuild the derived index\");\n\t\treturn value;\n\t};\n\tconst qualified = (selection: \"unresolved-lineage\" | \"invalid-first-kept\"): ContextManifestPage => ({\n\t\tselection,\n\t\tsummaryRef: result.summaryRef,\n\t\trefs: [],\n\t\torder: \"source\",\n\t\tnextCursor: null,\n\t});\n\tconst leaf = scope.leafId === null ? undefined : node(scope.leafId);\n\tif (leaf && (leaf.depth === null || leaf.visible_count === null)) return qualified(\"unresolved-lineage\");\n\tconst total = leaf?.visible_count ?? 0;\n\tif (leaf?.latest_compaction) {\n\t\tconst compaction = node(leaf.latest_compaction);\n\t\tif (compaction.kind !== \"compaction\" || compaction.depth === null || compaction.visible_count === null)\n\t\t\tthrow new Error(\"Context manifest compaction metadata is incomplete\");\n\t\tresult.summaryRef = contextRef(compaction);\n\t\tif (!compaction.first_kept_id) return qualified(\"invalid-first-kept\");\n\t\tconst first = manifestNode.get(sessionId, compaction.first_kept_id, scope.through) as ContextNode | undefined;\n\t\t// Exact parent-chain membership, never the broader evidence/request-parent scope rule.\n\t\tif (\n\t\t\t!first ||\n\t\t\tfirst.depth === null ||\n\t\t\tfirst.visible_count === null ||\n\t\t\tfirst.depth >= compaction.depth ||\n\t\t\t!resolvedAncestor(sessionId, compaction, first)\n\t\t)\n\t\t\treturn qualified(\"invalid-first-kept\");\n\t\tresult.activeBase = first.visible_count - (first.visible_head === first.id ? 1 : 0);\n\t\tresult.retainedMessageCount = compaction.visible_count - result.activeBase;\n\t}\n\tresult.activeMessageCount = total - result.activeBase;\n\tconst start = cursor?.nextOrdinal ?? result.activeBase + 1;\n\tif (start < result.activeBase + 1 || start > total + 1)\n\t\tthrow new Error(\"Context manifest cursor ordinal is outside active selection\");\n\tif (start === total + 1) return result;\n\tconst end = Math.min(start + limit - 1, total);\n\tlet seekId = leaf!.id;\n\t// Locate page END using physical ancestry jumps and monotonic visible counts, then reverse only this bounded page.\n\tfor (let level = MAX_JUMP_LEVELS - 1; level >= 0; level--) {\n\t\tconst jump = visibleJump.get(sessionId, seekId, level);\n\t\tif (jump && jump.visible_count !== null && Number(jump.visible_count) >= end) seekId = String(jump.ancestor_id);\n\t}\n\tconst seek = node(seekId);\n\tif (seek.visible_head === null) throw new Error(\"Context manifest visible metadata is incomplete\");\n\tlet current = seek.visible_head === seek.id ? seek : node(seek.visible_head);\n\tconst refs: (ContextRef & { ordinal: number })[] = [];\n\tfor (let ordinal = end; ordinal >= start; ordinal--) {\n\t\tif (current.visible_count !== ordinal || current.visible_head !== current.id)\n\t\t\tthrow new Error(\"Context manifest visible ordinal metadata is incomplete\");\n\t\trefs.push({ ...contextRef(current), ordinal });\n\t\tif (ordinal > start) {\n\t\t\tif (current.previous_visible === null) throw new Error(\"Context manifest previous visible ref is missing\");\n\t\t\tcurrent = node(current.previous_visible);\n\t\t}\n\t}\n\trefs.reverse();\n\t// Include the largest continuation envelope in the byte count; never advance over an unreturned ref.\n\tconst pageBytes = 1024 * 1024 - 1024;\n\tlet bytes = Buffer.byteLength(\n\t\tJSON.stringify({ ...result, nextCursor: { ...anchor, nextOrdinal: Number.MAX_SAFE_INTEGER } }),\n\t);\n\tfor (const ref of refs) {\n\t\tconst addition = Buffer.byteLength(JSON.stringify(ref)) + (result.refs.length ? 1 : 0);\n\t\tif (bytes + addition > pageBytes) break;\n\t\tresult.refs.push(ref);\n\t\tbytes += addition;\n\t}\n\tif (result.refs.length === 0) throw new Error(\"Context manifest metadata exceeds the page byte limit\");\n\tconst next = result.refs[result.refs.length - 1].ordinal + 1;\n\tresult.nextCursor = next <= total ? { ...anchor, nextOrdinal: next } : null;\n\treturn result;\n}\n\ntype SourceRefRow = Pick<Row, \"id\" | \"sequence\" | \"kind\" | \"locator\" | \"revision\">;\ntype ContextUpdateScope = { leafId: string | null; through: number };\nconst latestUsageUpdate = db.prepare(`SELECT e.id,e.sequence,e.kind,e.locator,e.revision FROM context_update u\n JOIN source_event e ON e.session=u.session AND e.id=u.event_id\n WHERE u.session=? AND u.update_kind='assistant-usage' AND u.target_key=? AND u.sequence<=?\n ORDER BY u.sequence DESC LIMIT 1`);\nconst ipythonUpdates = db.prepare(`SELECT e.id,e.sequence,e.kind,e.locator,e.revision FROM context_update u\n JOIN source_event e ON e.session=u.session AND e.id=u.event_id\n WHERE u.session=? AND u.update_kind='ipython-sent-message' AND u.target_key=? AND u.sequence<=?\n ORDER BY u.sequence LIMIT ?`);\nfunction contextUpdateSource(sessionId: string, scope: ContextUpdateScope) {\n\tconst saved = db.prepare(\"SELECT * FROM source_cursor WHERE session=?\").get(sessionId);\n\tif (!saved) throw new Error(\"Context update index is unavailable; synchronize the source first\");\n\tconst snapshot = JSON.parse(String(saved.frontier)) as SessionJournalState & { indexedThrough: number };\n\tif (snapshot.format !== \"framed\" || snapshot.indexedThrough < scope.through)\n\t\tthrow new Error(\"Context update index has not reached the requested source prefix\");\n\tconst leaf = validateBranchScope(sessionId, scope.through, scope);\n\tif (leaf?.depth === null) throw new Error(\"Context update branch lineage is unresolved\");\n\tif (\n\t\tscope.through > 0 &&\n\t\t!db.prepare(\"SELECT 1 FROM source_event WHERE session=? AND sequence=?\").get(sessionId, scope.through)\n\t)\n\t\tthrow new Error(\"Context update source prefix is unavailable\");\n\treturn snapshot;\n}\nfunction contextUpdateKey(sessionId: string, scope: ContextUpdateScope, target: ContextUpdateTarget): string {\n\tif (target.kind !== \"assistant-usage\" && target.kind !== \"ipython-sent-message\")\n\t\tthrow new Error(\"Invalid context update target\");\n\tconst key = target.kind === \"assistant-usage\" ? target.targetId : target.toolCallId;\n\tif (typeof key !== \"string\" || key.length > (target.kind === \"assistant-usage\" ? 512 : MAX_CONTEXT_UPDATE_KEY))\n\t\tthrow new Error(\"Context update target key limit exceeded\");\n\tif (target.kind === \"assistant-usage\") {\n\t\tconst assistant = db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT 1 FROM context_update WHERE session=? AND update_kind='assistant-target' AND target_key=? AND sequence<=?\",\n\t\t\t)\n\t\t\t.get(sessionId, key, scope.through);\n\t\tif (!assistant || !pointEvent(sessionId, key, scope))\n\t\t\tthrow new Error(\"Context update target is not an assistant message on the captured branch\");\n\t}\n\treturn key;\n}\nfunction contextUpdateRef(row: SourceRefRow): ContextUpdateRef {\n\treturn {\n\t\tentryId: row.id,\n\t\tsequence: row.sequence,\n\t\tkind: row.kind as ContextUpdateRef[\"kind\"],\n\t\tlocator: JSON.parse(row.locator) as ContextUpdateRef[\"locator\"],\n\t\trevision: row.revision,\n\t};\n}\nfunction contextUpdates(request: Extract<HistoryIndexRequest, { action: \"context_updates\" }>): ContextUpdates {\n\tconst { sessionId, scope, target } = request;\n\tcontextUpdateSource(sessionId, scope);\n\tconst key = contextUpdateKey(sessionId, scope, target);\n\tlet rows: SourceRefRow[];\n\tif (target.kind === \"assistant-usage\") {\n\t\tconst latest = latestUsageUpdate.get(sessionId, key, scope.through) as SourceRefRow | undefined;\n\t\trows = latest ? [latest] : [];\n\t} else {\n\t\trows =\n\t\t\tscope.leafId === null\n\t\t\t\t? []\n\t\t\t\t: (ipythonUpdates.all(sessionId, key, scope.through, MAX_CONTEXT_UPDATE_CANDIDATES + 1) as SourceRefRow[]);\n\t\tif (rows.length > MAX_CONTEXT_UPDATE_CANDIDATES) throw new Error(\"Context update candidate budget exceeded\");\n\t\trows = rows.filter((row) => pointEvent(sessionId, row.id, scope) !== undefined);\n\t}\n\tconst result: ContextUpdates = { refs: rows.map(contextUpdateRef), order: \"source\" };\n\ttry {\n\t\tstringifyBoundedJson(result, TASK_PAGE_BYTES);\n\t} catch (error) {\n\t\tif (!(error instanceof Error) || error.message !== \"JSON byte limit exceeded\") throw error;\n\t\tthrow new Error(\"Context update refs exceed the byte budget\");\n\t}\n\treturn result;\n}\nfunction readContextUpdatePayload(request: Extract<HistoryIndexRequest, { action: \"read_context_update_payload\" }>) {\n\tconst { sessionId, eventId, scope, target, options } = request;\n\tconst snapshot = contextUpdateSource(sessionId, scope);\n\tconst key = contextUpdateKey(sessionId, scope, target);\n\tlet row: SourceRefRow | undefined;\n\tif (target.kind === \"assistant-usage\") {\n\t\trow = latestUsageUpdate.get(sessionId, key, scope.through) as SourceRefRow | undefined;\n\t\tif (row?.id !== eventId) return undefined;\n\t} else {\n\t\tconst related = db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT 1 FROM context_update WHERE session=? AND update_kind='ipython-sent-message' AND event_id=? AND target_key=? AND sequence<=?\",\n\t\t\t)\n\t\t\t.get(sessionId, eventId, key, scope.through);\n\t\tif (!related) return undefined;\n\t\trow = pointEvent(sessionId, eventId, scope);\n\t}\n\treturn row ? readPayloadRow(sessionId, row, snapshot, options) : undefined;\n}\n\nfunction readPayload(request: Extract<HistoryIndexRequest, { action: \"read_payload\" }>) {\n\tconst saved = db.prepare(\"SELECT frontier FROM source_cursor WHERE session=?\").get(request.sessionId);\n\tif (!saved) throw new Error(\"Canonical payload index is unavailable; synchronize the source first\");\n\tconst snapshot = JSON.parse(String(saved.frontier)) as SessionJournalState & { indexedThrough: number };\n\tif (snapshot.format !== \"framed\" || snapshot.indexedThrough < request.scope.through)\n\t\tthrow new Error(\"Canonical payload index has not reached the requested source prefix\");\n\tconst row = pointEvent(request.sessionId, request.eventId, request.scope);\n\tif (!row) return undefined;\n\treturn readPayloadRow(request.sessionId, row, snapshot, request.options);\n}\nfunction selectSourceEvent(request: Extract<HistoryIndexRequest, { action: \"get_source\" | \"read_source_payload\" }>) {\n\tconst { sessionId, eventId, through } = request;\n\tif (!Number.isSafeInteger(through) || through < 0) throw new Error(\"Invalid history source prefix\");\n\tconst saved = db.prepare(\"SELECT frontier FROM source_cursor WHERE session=?\").get(sessionId);\n\tif (!saved) throw new Error(\"Canonical source index is unavailable; synchronize the source first\");\n\tconst snapshot = JSON.parse(String(saved.frontier)) as SessionJournalState & { indexedThrough: number };\n\tif (snapshot.format !== \"framed\" || snapshot.indexedThrough < through)\n\t\tthrow new Error(\"Canonical source index has not reached the requested source prefix\");\n\tconst row = db\n\t\t.prepare(\"SELECT * FROM source_event WHERE session=? AND id=? AND sequence<=?\")\n\t\t.get(sessionId, eventId, through) as Row | undefined;\n\treturn { row, snapshot };\n}\nfunction readPayloadRow(\n\tsessionId: string,\n\trow: SourceRefRow,\n\tsnapshot: SessionJournalState,\n\toptions: HistoryPayloadReadOptions,\n) {\n\tconst savedParts = db\n\t\t.prepare(\"SELECT parts FROM source_payload WHERE session=? AND sequence=?\")\n\t\t.get(sessionId, row.sequence);\n\tif (!savedParts) throw new Error(\"Canonical payload parts are unavailable; rebuild the derived index\");\n\tconst parts = JSON.parse(String(savedParts.parts)) as CanonicalPayloadParts;\n\tconst locator = JSON.parse(row.locator) as IndexedSourceEvent[\"locator\"];\n\tif (\n\t\tlocator.path !== snapshot.journalPath ||\n\t\tparts.source.dev !== snapshot.dev ||\n\t\tparts.source.ino !== snapshot.ino ||\n\t\tparts.frameOffset !== locator.offset ||\n\t\tparts.frameChecksum !== row.revision ||\n\t\tparts.payloadOffset < locator.offset ||\n\t\tparts.payloadOffset + parts.byteLength > locator.offset + locator.length\n\t)\n\t\tthrow new Error(\"Canonical payload metadata does not match the verified source frame\");\n\tconst identity = (current: { dev: number; ino: number; size: number }) => {\n\t\tif (current.dev !== snapshot.dev || current.ino !== snapshot.ino || current.size < snapshot.byteLength)\n\t\t\tthrow new Error(\"Canonical payload source identity or acknowledged length changed\");\n\t};\n\treturn withJournalDescriptorSync(openSync(snapshot.journalPath, \"r\"), (fd) => {\n\t\tidentity(fstatSync(fd));\n\t\tconst fragment = readCanonicalPayloadFragment(fd, parts, options.cursor, options.maxBytes);\n\t\tidentity(statSync(snapshot.journalPath));\n\t\treturn fragment;\n\t});\n}\n\nlet catalogTransaction = false;\nlet catalogReadScope: { sessionId: string; through: number } | undefined;\nasync function sessionCatalog(\n\trequest: Extract<HistoryIndexRequest, { action: \"catalog\" }>,\n): Promise<SessionCatalogIndexResult> {\n\tif (!readOnly) throw new Error(\"Catalog discovery requires a read-only index connection\");\n\tcatalogReadScope = undefined;\n\tif (!catalogTransaction) {\n\t\tdb.exec(\"BEGIN\");\n\t\tcatalogTransaction = true;\n\t}\n\tconst saved = db.prepare(\"SELECT * FROM source_cursor WHERE session=?\").get(request.sessionId);\n\tif (!saved || saved.catalog_summary === null)\n\t\treturn { selection: \"unavailable\", reason: \"No owner-maintained catalog projection covers this source\" };\n\tconst frontier = JSON.parse(String(saved.frontier)) as SourceIndexCursor[\"frontier\"];\n\tconst covered = db.prepare(\"SELECT sequence FROM coverage WHERE session=?\").get(request.sessionId);\n\tif (!covered || covered.sequence !== frontier.indexedThrough)\n\t\treturn { selection: \"stale\", reason: \"Catalog index coverage is incomplete\" };\n\tconst bySequence = (sequence: number) =>\n\t\tdb.prepare(\"SELECT * FROM source_event WHERE session=? AND sequence=?\").get(request.sessionId, sequence) as\n\t\t\t| Row\n\t\t\t| undefined;\n\tconst tail = frontier.indexedThrough > 0 ? bySequence(frontier.indexedThrough) : undefined;\n\tconst previous = frontier.indexedThrough > 1 ? bySequence(frontier.indexedThrough - 1) : undefined;\n\tif (frontier.indexedThrough > 1 && !previous) throw new Error(\"Catalog predecessor metadata is unavailable\");\n\tconst indexed: SourceIndexCursor = {\n\t\tfrontier,\n\t\theaderByteLength: Number(saved.header_bytes),\n\t\theaderChecksum: String(saved.header_checksum),\n\t};\n\tif (\n\t\t!(await validateIndexedCatalogSource(\n\t\t\trequest.sessionId,\n\t\t\trequest.source,\n\t\t\tindexed,\n\t\t\ttail ? event(tail) : null,\n\t\t\tprevious?.revision ?? indexed.headerChecksum,\n\t\t))\n\t)\n\t\treturn { selection: \"stale\", reason: \"Catalog does not cover the current canonical source\" };\n\tconst projection = decodeSessionCatalog(JSON.parse(String(saved.catalog_summary)));\n\tif (projection.unsupported) return { selection: \"unsupported\", reason: projection.unsupported };\n\tconst reference = (id: string | null) => {\n\t\tif (id === null) return null;\n\t\tconst row = db\n\t\t\t.prepare(\"SELECT * FROM source_event WHERE session=? AND id=? AND sequence<=?\")\n\t\t\t.get(request.sessionId, id, frontier.indexedThrough) as Row | undefined;\n\t\tif (!row) throw new Error(\"Catalog source reference is unavailable\");\n\t\treturn event(row);\n\t};\n\tcatalogReadScope = { sessionId: request.sessionId, through: frontier.indexedThrough };\n\treturn {\n\t\tselection: \"covered\",\n\t\tfrontier,\n\t\tprojection,\n\t\trefs: {\n\t\t\tfirstMessage:\n\t\t\t\tprojection.firstMessage && \"id\" in projection.firstMessage ? reference(projection.firstMessage.id) : null,\n\t\t\tname: reference(projection.nameId),\n\t\t\tagentStatus: reference(projection.agentStatusId),\n\t\t},\n\t};\n}\n\nasync function dispatch(request: HistoryIndexRequest): Promise<unknown> {\n\tif (readOnly && ![\"catalog\", \"get_source\", \"read_source_payload\", \"close\"].includes(request.action))\n\t\tthrow new Error(\"Read-only catalog index does not admit this operation\");\n\tif (\n\t\treadOnly &&\n\t\t(request.action === \"get_source\" || request.action === \"read_source_payload\") &&\n\t\t(!catalogReadScope ||\n\t\t\trequest.sessionId !== catalogReadScope.sessionId ||\n\t\t\trequest.through !== catalogReadScope.through)\n\t)\n\t\tthrow new Error(\"Catalog payload read is outside its covered snapshot\");\n\tswitch (request.action) {\n\t\tcase \"catalog\":\n\t\t\treturn sessionCatalog(request);\n\t\tcase \"sync_source\":\n\t\t\treturn syncSource(request.sessionId, request.snapshot);\n\t\tcase \"ipython_sent_messages\":\n\t\t\treturn ipythonSentMessages(request);\n\t\tcase \"current_source_bootstrap\":\n\t\t\treturn currentSourceBootstrap(request);\n\t\tcase \"source_label\":\n\t\tcase \"source_assistant_usage\":\n\t\t\treturn sourceRelation(request);\n\t\tcase \"task_evidence\":\n\t\t\treturn taskEvidence(request);\n\t\tcase \"read_payload\":\n\t\t\treturn readPayload(request);\n\t\tcase \"parent_path\":\n\t\t\treturn parentPath(request);\n\t\tcase \"branch_bootstrap\":\n\t\t\treturn branchBootstrap(request);\n\t\tcase \"context_manifest\":\n\t\t\treturn contextManifest(request);\n\t\tcase \"context_updates\":\n\t\t\treturn contextUpdates(request);\n\t\tcase \"read_context_update_payload\":\n\t\t\treturn readContextUpdatePayload(request);\n\t\tcase \"apply\":\n\t\t\tapply(request.sessionId, request.events, request.committedThrough);\n\t\t\treturn;\n\t\tcase \"get\": {\n\t\t\tconst row = pointEvent(request.sessionId, request.eventId, request.scope);\n\t\t\treturn row ? event(row) : undefined;\n\t\t}\n\t\tcase \"get_source\": {\n\t\t\tconst { row } = selectSourceEvent(request);\n\t\t\treturn row ? event(row) : undefined;\n\t\t}\n\t\tcase \"read_source_payload\": {\n\t\t\tconst { row, snapshot } = selectSourceEvent(request);\n\t\t\treturn row ? readPayloadRow(request.sessionId, row, snapshot, request.options) : undefined;\n\t\t}\n\t\tcase \"page\":\n\t\tcase \"search\":\n\t\t\treturn query(request);\n\t\tcase \"clear\":\n\t\t\ttransaction(() => clearSession(request.sessionId));\n\t\t\treturn;\n\t\tcase \"close\":\n\t\t\tdb.close();\n\t\t\treturn;\n\t}\n}\nlet queue: Promise<void> = Promise.resolve();\nlet accepting = true;\nlet pendingBytes = 0;\nlet pendingOperations = 0;\nprocess.on(\"message\", (input: HistoryIndexRequest) => {\n\tlet bytes: number;\n\ttry {\n\t\tbytes = Buffer.byteLength(stringifyBoundedJson(input, 2 * 1024 * 1024));\n\t} catch (error) {\n\t\tprocess.send?.({ id: input.id, error: String(error) });\n\t\treturn;\n\t}\n\tif (!accepting || pendingOperations >= 32 || pendingBytes + bytes > 4 * 1024 * 1024) {\n\t\tprocess.send?.({ id: input.id, error: \"History-index queue is closing or full\" });\n\t\treturn;\n\t}\n\tif (input.action === \"close\") accepting = false;\n\tpendingOperations++;\n\tpendingBytes += bytes;\n\tconst operation = queue.then(() => dispatch(input));\n\tqueue = operation.then(\n\t\t() => undefined,\n\t\t() => undefined,\n\t);\n\tvoid operation\n\t\t.then(\n\t\t\t(result) => {\n\t\t\t\tif (process.connected)\n\t\t\t\t\tprocess.send?.({ id: input.id, result }, () => {\n\t\t\t\t\t\tif (input.action === \"close\") process.disconnect();\n\t\t\t\t\t});\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tif (process.connected)\n\t\t\t\t\tprocess.send?.({ id: input.id, error: error instanceof Error ? error.message : String(error) });\n\t\t\t},\n\t\t)\n\t\t.finally(() => {\n\t\t\tpendingOperations--;\n\t\t\tpendingBytes -= bytes;\n\t\t});\n});\nprocess.on(\"disconnect\", () => {\n\taccepting = false;\n\tvoid queue.finally(() => {\n\t\ttry {\n\t\t\tdb.close();\n\t\t} catch {}\n\t});\n});\nprocess.send?.({ ready: true });\n"]}
@@ -223,6 +223,10 @@ function terms(text) {
223
223
  .match(/[\p{L}\p{M}\p{N}_]+/gu) ?? []),
224
224
  ];
225
225
  }
226
+ const insertSourceEvent = db.prepare("INSERT INTO source_event VALUES (?,?,?,?,?,?,?,?,?,?,?,?)");
227
+ const insertSourcePayload = db.prepare("INSERT INTO source_payload VALUES (?,?,?)");
228
+ const insertTaskImportLoss = db.prepare("INSERT INTO task_import_loss VALUES (?,?,?)");
229
+ const insertTaskEvidence = db.prepare("INSERT INTO task_evidence VALUES (?,?,?,?,?,?,?)");
226
230
  const insertTerm = db.prepare("INSERT INTO source_term VALUES (?,?,?)");
227
231
  const countTerm = db.prepare("INSERT INTO term_count VALUES (?,?,1) ON CONFLICT(session,term) DO UPDATE SET count=count+1");
228
232
  function event(row) {
@@ -265,7 +269,7 @@ function insertEvent(sessionId, item) {
265
269
  item.qualification !== "native-context-epoch" &&
266
270
  item.qualification !== "native-tool-execution")
267
271
  throw new Error("Unsupported indexed source qualification");
268
- db.prepare("INSERT INTO source_event VALUES (?,?,?,?,?,?,?,?,?,?,?,?)").run(sessionId, item.id, item.sequence, item.parentId, item.kind, item.authority, JSON.stringify(item.locator), item.revision, item.text, item.textComplete ? 1 : 0, item.retention ?? null, item.qualification ?? null);
272
+ insertSourceEvent.run(sessionId, item.id, item.sequence, item.parentId, item.kind, item.authority, JSON.stringify(item.locator), item.revision, item.text, item.textComplete ? 1 : 0, item.retention ?? null, item.qualification ?? null);
269
273
  for (const term of terms(item.text)) {
270
274
  insertTerm.run(sessionId, term, item.sequence);
271
275
  countTerm.run(sessionId, term);
@@ -508,6 +512,8 @@ async function syncSource(sessionId, snapshot) {
508
512
  source_content_prefix: 0,
509
513
  source_has_user_content: 0,
510
514
  };
515
+ // The session owner coalesces queued ACK snapshots; this whole ready suffix shares one transaction.
516
+ // Coverage and the source cursor become visible only with that transaction's COMMIT.
511
517
  let usageChanged = !previous;
512
518
  const catalog = previous
513
519
  ? decodeSessionCatalog(JSON.parse(String(row?.catalog_summary)))
@@ -543,11 +549,11 @@ async function syncSource(sessionId, snapshot) {
543
549
  const depth = insertAncestry(sessionId, item);
544
550
  insertContext(sessionId, item, entry, depth);
545
551
  insertContextUpdates(sessionId, item, entry);
546
- db.prepare("INSERT INTO source_payload VALUES (?,?,?)").run(sessionId, sequence, JSON.stringify(parts));
552
+ insertSourcePayload.run(sessionId, sequence, JSON.stringify(parts));
547
553
  const source = { sessionId, sequence, entry, locator, revision, retention, qualification };
548
554
  const imported = getTaskStateImportCoverage(source);
549
555
  if (imported)
550
- db.prepare("INSERT INTO task_import_loss VALUES (?,?,?)").run(sessionId, sequence, imported.taskKey ?? null);
556
+ insertTaskImportLoss.run(sessionId, sequence, imported.taskKey ?? null);
551
557
  let ordinal = 0;
552
558
  for (const projection of projectTaskStateSource(source)) {
553
559
  let payload;
@@ -560,7 +566,7 @@ async function syncSource(sessionId, snapshot) {
560
566
  // The original canonical field is recoverable; never clip its item or text.
561
567
  payload = null;
562
568
  }
563
- db.prepare("INSERT INTO task_evidence VALUES (?,?,?,?,?,?,?)").run(sessionId, sequence, ordinal++, projection.taskKey ?? null, projection.itemId ?? null, JSON.stringify(projection.source), payload);
569
+ insertTaskEvidence.run(sessionId, sequence, ordinal++, projection.taskKey ?? null, projection.itemId ?? null, JSON.stringify(projection.source), payload);
564
570
  }
565
571
  });
566
572
  if (usageChanged && !catalog.unsupported) {
@@ -759,13 +765,22 @@ function query(request) {
759
765
  const indexedThrough = Number(db.prepare("SELECT sequence FROM coverage WHERE session=?").get(request.sessionId)?.sequence ?? 0);
760
766
  const branch = branchFilter(request.sessionId, request.through, request.scope);
761
767
  let rows;
768
+ let scanNext = null;
762
769
  if (request.action === "page") {
763
770
  const candidates = branch.empty
764
771
  ? []
765
772
  : db
766
773
  .prepare("SELECT id,parent_id,kind,sequence FROM source_event INDEXED BY sqlite_autoindex_source_event_2 WHERE session=? AND sequence>? AND sequence<=? ORDER BY sequence LIMIT ?")
767
- .all(request.sessionId, request.after, request.through, MAX_QUERY_CANDIDATES + 1);
768
- rows = selectCandidates(candidates, branch.matches, request.limit, "History page selection");
774
+ .all(request.sessionId, request.after, request.through, request.scan ? request.limit + 1 : MAX_QUERY_CANDIDATES + 1);
775
+ if (request.scan) {
776
+ const examined = candidates.slice(0, request.limit);
777
+ rows = examined.filter(branch.matches);
778
+ if (candidates.length > examined.length)
779
+ scanNext = examined[examined.length - 1].sequence;
780
+ }
781
+ else {
782
+ rows = selectCandidates(candidates, branch.matches, request.limit, "History page selection");
783
+ }
769
784
  }
770
785
  else {
771
786
  if (Buffer.byteLength(request.query) > 8192)
@@ -810,13 +825,17 @@ function query(request) {
810
825
  break;
811
826
  events.push(indexed);
812
827
  }
813
- const truncated = events.length < rows.length;
828
+ const truncated = events.length < rows.length || scanNext !== null;
814
829
  return {
815
830
  events,
816
831
  indexedThrough,
817
832
  coverage: indexedThrough < request.through || incompleteText ? "partial" : "complete",
818
833
  truncated,
819
- nextAfter: request.action === "page" && truncated ? (events[events.length - 1]?.sequence ?? request.after) : null,
834
+ nextAfter: request.action !== "page"
835
+ ? null
836
+ : events.length < rows.length
837
+ ? (events[events.length - 1]?.sequence ?? request.after)
838
+ : scanNext,
820
839
  };
821
840
  }
822
841
  function taskEvidence(request) {
@@ -845,6 +864,8 @@ function taskEvidence(request) {
845
864
  };
846
865
  if (!cursor)
847
866
  return page;
867
+ const frontier = JSON.parse(String(cursor.frontier));
868
+ page.sourceIdentity = { journalPath: frontier.journalPath, dev: frontier.dev, ino: frontier.ino };
848
869
  const branch = branchFilter(sessionId, scope.through, scope);
849
870
  const coverageBudget = { remaining: MAX_QUERY_CANDIDATES };
850
871
  const lossKeys = options.taskKey === undefined ? [undefined] : [null, options.taskKey];