@cortexkit/opencode-magic-context 0.38.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/README.md +37 -4
  2. package/dist/{announcement-6c1g4es4.js → announcement-5eg4t64s.js} +6 -6
  3. package/dist/config/index.d.ts.map +1 -1
  4. package/dist/config/project-security.d.ts +11 -6
  5. package/dist/config/project-security.d.ts.map +1 -1
  6. package/dist/config/raw-loader.d.ts +42 -0
  7. package/dist/config/raw-loader.d.ts.map +1 -0
  8. package/dist/config/schema/magic-context.d.ts +586 -551
  9. package/dist/config/schema/magic-context.d.ts.map +1 -1
  10. package/dist/{conflict-warning-hook-an4fxhwf.js → conflict-warning-hook-f406ggbw.js} +5 -5
  11. package/dist/{derive-budgets-da4yg3tz.js → derive-budgets-xk8cy5e6.js} +5 -5
  12. package/dist/{emscripten-module-ap8t3st0.js → emscripten-module-49k43zfy.js} +1 -1
  13. package/dist/{emscripten-module-682pfzaa.js → emscripten-module-ex4v0x4z.js} +1 -1
  14. package/dist/{emscripten-module-r5h7aghp.js → emscripten-module-jfs3d1dq.js} +1 -1
  15. package/dist/{emscripten-module-bkktz927.js → emscripten-module-ss4g4spn.js} +1 -1
  16. package/dist/features/magic-context/dreamer/classify.d.ts +3 -2
  17. package/dist/features/magic-context/dreamer/classify.d.ts.map +1 -1
  18. package/dist/features/magic-context/dreamer/evaluate-smart-notes.d.ts +9 -2
  19. package/dist/features/magic-context/dreamer/evaluate-smart-notes.d.ts.map +1 -1
  20. package/dist/features/magic-context/dreamer/map-memories-prompt.d.ts +4 -2
  21. package/dist/features/magic-context/dreamer/map-memories-prompt.d.ts.map +1 -1
  22. package/dist/features/magic-context/dreamer/map-memories.d.ts +21 -5
  23. package/dist/features/magic-context/dreamer/map-memories.d.ts.map +1 -1
  24. package/dist/features/magic-context/dreamer/refresh-primers.d.ts +3 -2
  25. package/dist/features/magic-context/dreamer/refresh-primers.d.ts.map +1 -1
  26. package/dist/features/magic-context/dreamer/retrospective-orphan-sweep.d.ts +17 -6
  27. package/dist/features/magic-context/dreamer/retrospective-orphan-sweep.d.ts.map +1 -1
  28. package/dist/features/magic-context/dreamer/task-config.d.ts +2 -1
  29. package/dist/features/magic-context/dreamer/task-config.d.ts.map +1 -1
  30. package/dist/features/magic-context/dreamer/task-executor.d.ts +0 -1
  31. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  32. package/dist/features/magic-context/dreamer/task-scheduler.d.ts +3 -2
  33. package/dist/features/magic-context/dreamer/task-scheduler.d.ts.map +1 -1
  34. package/dist/features/magic-context/dreamer/verify-prompt.d.ts +5 -2
  35. package/dist/features/magic-context/dreamer/verify-prompt.d.ts.map +1 -1
  36. package/dist/features/magic-context/dreamer/verify.d.ts +6 -3
  37. package/dist/features/magic-context/dreamer/verify.d.ts.map +1 -1
  38. package/dist/features/magic-context/memory/storage-memory.d.ts.map +1 -1
  39. package/dist/features/magic-context/memory/types.d.ts +16 -0
  40. package/dist/features/magic-context/memory/types.d.ts.map +1 -1
  41. package/dist/features/magic-context/message-index.d.ts +3 -2
  42. package/dist/features/magic-context/message-index.d.ts.map +1 -1
  43. package/dist/features/magic-context/migrations.d.ts.map +1 -1
  44. package/dist/features/magic-context/mural/compress-cues.d.ts +3 -2
  45. package/dist/features/magic-context/mural/compress-cues.d.ts.map +1 -1
  46. package/dist/features/magic-context/smart-notes/compiler.d.ts +3 -2
  47. package/dist/features/magic-context/smart-notes/compiler.d.ts.map +1 -1
  48. package/dist/features/magic-context/smart-notes/condition-compiler.d.ts +2 -0
  49. package/dist/features/magic-context/smart-notes/condition-compiler.d.ts.map +1 -1
  50. package/dist/features/magic-context/smart-notes/sandbox-runner.d.ts.map +1 -1
  51. package/dist/features/magic-context/storage-db.d.ts +1 -1
  52. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  53. package/dist/features/magic-context/storage-embedding-measurements.d.ts +1 -1
  54. package/dist/features/magic-context/storage-embedding-measurements.d.ts.map +1 -1
  55. package/dist/features/magic-context/storage-meta-persisted.d.ts +7 -2
  56. package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
  57. package/dist/features/magic-context/storage-meta-session.d.ts.map +1 -1
  58. package/dist/features/magic-context/storage-meta-shared.d.ts +1 -0
  59. package/dist/features/magic-context/storage-meta-shared.d.ts.map +1 -1
  60. package/dist/features/magic-context/storage-meta.d.ts +1 -1
  61. package/dist/features/magic-context/storage-meta.d.ts.map +1 -1
  62. package/dist/features/magic-context/storage-session-tables.d.ts +18 -0
  63. package/dist/features/magic-context/storage-session-tables.d.ts.map +1 -0
  64. package/dist/features/magic-context/storage-tags.d.ts.map +1 -1
  65. package/dist/features/magic-context/storage.d.ts +1 -1
  66. package/dist/features/magic-context/storage.d.ts.map +1 -1
  67. package/dist/features/magic-context/tool-definition-tokens.d.ts +10 -0
  68. package/dist/features/magic-context/tool-definition-tokens.d.ts.map +1 -1
  69. package/dist/features/magic-context/transform-decision-log.d.ts +33 -0
  70. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  71. package/dist/features/magic-context/user-memory/review-user-memories.d.ts +3 -2
  72. package/dist/features/magic-context/user-memory/review-user-memories.d.ts.map +1 -1
  73. package/dist/{ffi-d8pnn3mn.js → ffi-bbm9vkfa.js} +1 -1
  74. package/dist/{ffi-04jzypzk.js → ffi-kb5r0x1j.js} +1 -1
  75. package/dist/{ffi-t8b862vx.js → ffi-qnrt0y78.js} +1 -1
  76. package/dist/{ffi-9wvt2wwz.js → ffi-yx2hpf4p.js} +1 -1
  77. package/dist/hooks/magic-context/channel2-delivery.d.ts +3 -1
  78. package/dist/hooks/magic-context/channel2-delivery.d.ts.map +1 -1
  79. package/dist/hooks/magic-context/command-handler.d.ts +4 -0
  80. package/dist/hooks/magic-context/command-handler.d.ts.map +1 -1
  81. package/dist/hooks/magic-context/compartment-runner-historian.d.ts +4 -1
  82. package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
  83. package/dist/hooks/magic-context/compartment-runner-partial-recomp.d.ts.map +1 -1
  84. package/dist/hooks/magic-context/compartment-runner-recomp.d.ts.map +1 -1
  85. package/dist/hooks/magic-context/compartment-runner-types.d.ts +4 -1
  86. package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
  87. package/dist/hooks/magic-context/ctx-reduce-nudge.d.ts +14 -2
  88. package/dist/hooks/magic-context/ctx-reduce-nudge.d.ts.map +1 -1
  89. package/dist/hooks/magic-context/emergency-fail-closed.d.ts +7 -0
  90. package/dist/hooks/magic-context/emergency-fail-closed.d.ts.map +1 -1
  91. package/dist/hooks/magic-context/empty-task-output.d.ts +16 -0
  92. package/dist/hooks/magic-context/empty-task-output.d.ts.map +1 -0
  93. package/dist/hooks/magic-context/hook-handlers.d.ts.map +1 -1
  94. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  95. package/dist/hooks/magic-context/inject-compartments.d.ts +18 -1
  96. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  97. package/dist/hooks/magic-context/lkg-persist.d.ts +14 -0
  98. package/dist/hooks/magic-context/lkg-persist.d.ts.map +1 -0
  99. package/dist/hooks/magic-context/lkg-slot.d.ts +13 -0
  100. package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
  101. package/dist/hooks/magic-context/module-state-sync.d.ts +1 -0
  102. package/dist/hooks/magic-context/module-state-sync.d.ts.map +1 -1
  103. package/dist/hooks/magic-context/module-transport.d.ts +12 -0
  104. package/dist/hooks/magic-context/module-transport.d.ts.map +1 -1
  105. package/dist/hooks/magic-context/raw-fallback-context-limit.d.ts.map +1 -1
  106. package/dist/hooks/magic-context/recomp-orchestrator.d.ts +4 -1
  107. package/dist/hooks/magic-context/recomp-orchestrator.d.ts.map +1 -1
  108. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  109. package/dist/hooks/magic-context/tail-hygiene-walk.d.ts +12 -0
  110. package/dist/hooks/magic-context/tail-hygiene-walk.d.ts.map +1 -1
  111. package/dist/hooks/magic-context/transform-compartment-phase.d.ts +3 -1
  112. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  113. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +8 -0
  114. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  115. package/dist/hooks/magic-context/transform.d.ts +9 -1
  116. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  117. package/dist/hooks/magic-context/wrapup-orchestrator.d.ts.map +1 -1
  118. package/dist/{index-cae89eas.js → index-1h9t9xb5.js} +2 -2
  119. package/dist/{index-wckvcay0.js → index-1yh8g550.js} +8 -6
  120. package/dist/{index-cgyfn1s2.js → index-2wchnyk6.js} +4 -2
  121. package/dist/{index-2y0ybv5x.js → index-3dkzzh0t.js} +15 -17
  122. package/dist/{index-4cz5nfxf.js → index-btj2qhmc.js} +5 -5
  123. package/dist/index-ehpzdy0v.js +126 -0
  124. package/dist/{index-mmvhrqqb.js → index-k2ts0wk1.js} +6435 -4339
  125. package/dist/{index-9zhhvr4w.js → index-mg1yx1ph.js} +1 -1
  126. package/dist/{index-ayd60xnw.js → index-rgdqj8nj.js} +3 -3
  127. package/dist/{index-ygcng9t8.js → index-rpgg35ms.js} +50 -50
  128. package/dist/index-rw0qrkvq.js +560 -0
  129. package/dist/index.d.ts.map +1 -1
  130. package/dist/index.js +27158 -24736
  131. package/dist/model-resolution-r9jbcz86.js +15 -0
  132. package/dist/{module-ES6BEMUI-atfbtnbp.js → module-ES6BEMUI-1yjdz59c.js} +4 -4
  133. package/dist/{module-asyncify-2EFITU5U-7xckhw8w.js → module-asyncify-2EFITU5U-fdkx4fhy.js} +1 -1
  134. package/dist/plugin/dream-timer.d.ts +8 -0
  135. package/dist/plugin/dream-timer.d.ts.map +1 -1
  136. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  137. package/dist/plugin/messages-transform.d.ts +14 -6
  138. package/dist/plugin/messages-transform.d.ts.map +1 -1
  139. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  140. package/dist/{prompt-context-jpe2dstn.js → prompt-context-29qkb28f.js} +1 -1
  141. package/dist/{recomp-orchestrator-jsde4ygw.js → recomp-orchestrator-2pncxee7.js} +15 -16
  142. package/dist/{rpc-notifications-4d22ybn5.js → rpc-notifications-1ffm755w.js} +6 -6
  143. package/dist/{safe-notification-target-b693f9x3.js → safe-notification-target-tepzc2xa.js} +3 -3
  144. package/dist/{send-session-notification-dxske5zm.js → send-session-notification-6v5b72b4.js} +7 -7
  145. package/dist/shared/harness-provider-map.d.ts +6 -0
  146. package/dist/shared/harness-provider-map.d.ts.map +1 -1
  147. package/dist/shared/jsonc-edit.d.ts +6 -1
  148. package/dist/shared/jsonc-edit.d.ts.map +1 -1
  149. package/dist/shared/model-resolution.d.ts +53 -0
  150. package/dist/shared/model-resolution.d.ts.map +1 -0
  151. package/dist/shared/model-suggestion-retry.d.ts +4 -1
  152. package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
  153. package/dist/shared/resolve-fallbacks.d.ts +5 -1
  154. package/dist/shared/resolve-fallbacks.d.ts.map +1 -1
  155. package/dist/shared/status-detail-text.d.ts +4 -0
  156. package/dist/shared/status-detail-text.d.ts.map +1 -0
  157. package/dist/shared/subagent-runner.d.ts +2 -1
  158. package/dist/shared/subagent-runner.d.ts.map +1 -1
  159. package/dist/{storage-meta-session-mk4gsnke.js → storage-meta-session-yvtbaw7c.js} +8 -8
  160. package/dist/{task-config-gbp7r23g.js → task-config-a1qmj9bx.js} +8 -8
  161. package/package.json +4 -2
  162. package/src/config/index.test.ts +73 -17
  163. package/src/config/index.ts +38 -23
  164. package/src/config/project-security.hostile-matrix.test.ts +471 -0
  165. package/src/config/project-security.test.ts +26 -5
  166. package/src/config/project-security.ts +141 -22
  167. package/src/config/raw-loader.test.ts +424 -0
  168. package/src/config/raw-loader.ts +490 -0
  169. package/src/config/schema/magic-context.test.ts +145 -2
  170. package/src/config/schema/magic-context.ts +256 -52
  171. package/src/shared/harness-provider-map.test.ts +36 -0
  172. package/src/shared/harness-provider-map.ts +8 -0
  173. package/src/shared/jsonc-edit.ts +74 -1
  174. package/src/shared/model-resolution.test.ts +170 -0
  175. package/src/shared/model-resolution.ts +227 -0
  176. package/src/shared/model-suggestion-retry.test.ts +27 -0
  177. package/src/shared/model-suggestion-retry.ts +19 -10
  178. package/src/shared/resolve-fallbacks.test.ts +13 -1
  179. package/src/shared/resolve-fallbacks.ts +19 -4
  180. package/src/shared/status-detail-text.test.ts +80 -0
  181. package/src/shared/status-detail-text.ts +56 -0
  182. package/src/shared/subagent-runner.ts +3 -1
  183. package/src/tui/index.tsx +1 -1
  184. package/src/tui/tui-compiled-runtime-imports.test.ts +3 -0
  185. package/src/tui-compiled/index.tsx +1 -1
  186. package/dist/index-crke4z5j.js +0 -3022
  187. package/dist/index-td9depx5.js +0 -46
  188. package/dist/resolve-fallbacks-5n5tvge1.js +0 -11
@@ -0,0 +1,560 @@
1
+ import {
2
+ piModelRefToCanonical
3
+ } from "./index-2wchnyk6.js";
4
+ import {
5
+ withReadOnlySessionDb
6
+ } from "./index-sw8gnq34.js";
7
+ import {
8
+ log
9
+ } from "./index-8pqfcghm.js";
10
+ import {
11
+ getHarness
12
+ } from "./index-mmrhhk9a.js";
13
+
14
+ // src/features/magic-context/storage-meta-session.ts
15
+ import { Buffer as Buffer2 } from "node:buffer";
16
+
17
+ // src/features/magic-context/resolve-subagent-fallback.ts
18
+ function resolveIsSubagentFromOpenCodeDb(sessionId) {
19
+ try {
20
+ return withReadOnlySessionDb((openCodeDb) => {
21
+ const row = openCodeDb.prepare("SELECT parent_id FROM session WHERE id = ?").get(sessionId);
22
+ if (!row)
23
+ return null;
24
+ return typeof row.parent_id === "string" && row.parent_id.length > 0;
25
+ });
26
+ } catch (error) {
27
+ log(`[magic-context] resolveIsSubagentFromOpenCodeDb failed for ${sessionId}:`, error);
28
+ return null;
29
+ }
30
+ }
31
+
32
+ // src/features/magic-context/storage-meta-shared.ts
33
+ import { Buffer } from "node:buffer";
34
+ var SESSION_META_SELECT_COLUMNS = [
35
+ "session_id",
36
+ "last_response_time",
37
+ "cache_ttl",
38
+ "counter",
39
+ "last_nudge_tokens",
40
+ "last_nudge_band",
41
+ "last_transform_error",
42
+ "is_subagent",
43
+ "last_context_percentage",
44
+ "last_input_tokens",
45
+ "observed_safe_input_tokens",
46
+ "cache_alert_sent",
47
+ "times_execute_threshold_reached",
48
+ "compartment_in_progress",
49
+ "system_prompt_hash",
50
+ "system_prompt_tokens",
51
+ "conversation_tokens",
52
+ "tool_call_tokens",
53
+ "cleared_reasoning_through_tag",
54
+ "tool_reclaim_watermark",
55
+ "last_todo_state",
56
+ "cached_m0_bytes",
57
+ "cached_m0_mural_data_url",
58
+ "cached_m0_mural_hash",
59
+ "cached_m1_bytes",
60
+ "cached_m0_project_memory_epoch",
61
+ "cached_m0_workspace_fingerprint",
62
+ "cached_m0_project_user_profile_version",
63
+ "cached_m0_max_compartment_seq",
64
+ "cached_m0_max_memory_id",
65
+ "cached_m0_max_mutation_id",
66
+ "cached_m0_max_memory_mutation_id",
67
+ "cached_m0_project_docs_hash",
68
+ "cached_m0_materialized_at",
69
+ "cached_m0_session_facts_version",
70
+ "cached_m0_upgrade_state",
71
+ "cached_m0_system_hash",
72
+ "cached_m0_tool_set_hash",
73
+ "cached_m0_model_key",
74
+ "cached_m0_project_identity",
75
+ "last_observed_model_key",
76
+ "last_usage_context_limit",
77
+ "prior_boundary_ordinal",
78
+ "protected_tail_policy_version",
79
+ "protected_tail_drain_window_started_at",
80
+ "protected_tail_drain_tokens",
81
+ "recovery_no_eligible_head_count",
82
+ "force_emergency_bypass_window_start",
83
+ "force_emergency_bypass_used",
84
+ "emergency_drain_active",
85
+ "historian_drain_failure_at",
86
+ "upgrade_reminded_at",
87
+ "upgrade_reminder_last_sent_at",
88
+ "upgrade_reminder_count",
89
+ "pi_stable_id_scheme"
90
+ ];
91
+ var META_COLUMNS = {
92
+ lastResponseTime: "last_response_time",
93
+ cacheTtl: "cache_ttl",
94
+ counter: "counter",
95
+ lastNudgeTokens: "last_nudge_tokens",
96
+ lastNudgeBand: "last_nudge_band",
97
+ lastTransformError: "last_transform_error",
98
+ isSubagent: "is_subagent",
99
+ lastContextPercentage: "last_context_percentage",
100
+ lastInputTokens: "last_input_tokens",
101
+ observedSafeInputTokens: "observed_safe_input_tokens",
102
+ cacheAlertSent: "cache_alert_sent",
103
+ timesExecuteThresholdReached: "times_execute_threshold_reached",
104
+ compartmentInProgress: "compartment_in_progress",
105
+ systemPromptHash: "system_prompt_hash",
106
+ systemPromptTokens: "system_prompt_tokens",
107
+ conversationTokens: "conversation_tokens",
108
+ toolCallTokens: "tool_call_tokens",
109
+ clearedReasoningThroughTag: "cleared_reasoning_through_tag",
110
+ toolReclaimWatermark: "tool_reclaim_watermark",
111
+ lastTodoState: "last_todo_state",
112
+ cachedM0Bytes: "cached_m0_bytes",
113
+ cachedM0MuralDataUrl: "cached_m0_mural_data_url",
114
+ cachedM0MuralHash: "cached_m0_mural_hash",
115
+ cachedM1Bytes: "cached_m1_bytes",
116
+ cachedM0ProjectMemoryEpoch: "cached_m0_project_memory_epoch",
117
+ cachedM0WorkspaceFingerprint: "cached_m0_workspace_fingerprint",
118
+ cachedM0ProjectUserProfileVersion: "cached_m0_project_user_profile_version",
119
+ cachedM0MaxCompartmentSeq: "cached_m0_max_compartment_seq",
120
+ cachedM0MaxMemoryId: "cached_m0_max_memory_id",
121
+ cachedM0MaxMutationId: "cached_m0_max_mutation_id",
122
+ cachedM0MaxMemoryMutationId: "cached_m0_max_memory_mutation_id",
123
+ cachedM0ProjectDocsHash: "cached_m0_project_docs_hash",
124
+ cachedM0MaterializedAt: "cached_m0_materialized_at",
125
+ cachedM0SessionFactsVersion: "cached_m0_session_facts_version",
126
+ cachedM0UpgradeState: "cached_m0_upgrade_state",
127
+ cachedM0SystemHash: "cached_m0_system_hash",
128
+ cachedM0ToolSetHash: "cached_m0_tool_set_hash",
129
+ cachedM0ModelKey: "cached_m0_model_key",
130
+ cachedM0ProjectIdentity: "cached_m0_project_identity",
131
+ lastObservedModelKey: "last_observed_model_key",
132
+ lastUsageContextLimit: "last_usage_context_limit",
133
+ priorBoundaryOrdinal: "prior_boundary_ordinal",
134
+ protectedTailPolicyVersion: "protected_tail_policy_version",
135
+ protectedTailDrainWindowStartedAt: "protected_tail_drain_window_started_at",
136
+ protectedTailDrainTokens: "protected_tail_drain_tokens",
137
+ recoveryNoEligibleHeadCount: "recovery_no_eligible_head_count",
138
+ forceEmergencyBypassWindowStart: "force_emergency_bypass_window_start",
139
+ forceEmergencyBypassUsed: "force_emergency_bypass_used",
140
+ emergencyDrainActive: "emergency_drain_active",
141
+ historianDrainFailureAt: "historian_drain_failure_at",
142
+ upgradeRemindedAt: "upgrade_reminded_at",
143
+ upgradeReminderLastSentAt: "upgrade_reminder_last_sent_at",
144
+ upgradeReminderCount: "upgrade_reminder_count",
145
+ piStableIdScheme: "pi_stable_id_scheme"
146
+ };
147
+ var BOOLEAN_META_KEYS = new Set(["isSubagent", "compartmentInProgress", "cacheAlertSent"]);
148
+ var NULL_BIND_META_KEYS = new Set([
149
+ "cachedM0Bytes",
150
+ "cachedM0MuralDataUrl",
151
+ "cachedM0MuralHash",
152
+ "cachedM1Bytes",
153
+ "cachedM0ProjectMemoryEpoch",
154
+ "cachedM0WorkspaceFingerprint",
155
+ "cachedM0ProjectUserProfileVersion",
156
+ "cachedM0MaxCompartmentSeq",
157
+ "cachedM0MaxMemoryId",
158
+ "cachedM0MaxMutationId",
159
+ "cachedM0MaxMemoryMutationId",
160
+ "cachedM0ProjectDocsHash",
161
+ "cachedM0MaterializedAt",
162
+ "cachedM0SessionFactsVersion",
163
+ "cachedM0UpgradeState",
164
+ "cachedM0ProjectIdentity",
165
+ "lastObservedModelKey",
166
+ "upgradeRemindedAt",
167
+ "upgradeReminderLastSentAt",
168
+ "piStableIdScheme"
169
+ ]);
170
+ function isStringOrNull(value) {
171
+ return value === null || typeof value === "string";
172
+ }
173
+ function isNumberOrNull(value) {
174
+ return value === null || typeof value === "number";
175
+ }
176
+ function isBlobOrNull(value) {
177
+ return value === null || Buffer.isBuffer(value) || value instanceof Uint8Array;
178
+ }
179
+ function toBufferOrNull(value) {
180
+ if (value === null)
181
+ return null;
182
+ if (Buffer.isBuffer(value))
183
+ return value;
184
+ return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
185
+ }
186
+ function isSessionMetaRow(row) {
187
+ if (row === null || typeof row !== "object")
188
+ return false;
189
+ const r = row;
190
+ return typeof r.session_id === "string" && typeof r.last_response_time === "number" && isStringOrNull(r.cache_ttl) && typeof r.counter === "number" && typeof r.last_nudge_tokens === "number" && isStringOrNull(r.last_nudge_band) && isStringOrNull(r.last_transform_error) && typeof r.is_subagent === "number" && typeof r.last_context_percentage === "number" && typeof r.last_input_tokens === "number" && isNumberOrNull(r.observed_safe_input_tokens) && isNumberOrNull(r.cache_alert_sent) && isNumberOrNull(r.times_execute_threshold_reached) && isNumberOrNull(r.compartment_in_progress) && (r.system_prompt_hash === null || typeof r.system_prompt_hash === "string" || typeof r.system_prompt_hash === "number") && isNumberOrNull(r.system_prompt_tokens) && isNumberOrNull(r.conversation_tokens) && isNumberOrNull(r.tool_call_tokens) && isNumberOrNull(r.cleared_reasoning_through_tag) && isStringOrNull(r.last_todo_state) && isBlobOrNull(r.cached_m0_bytes) && isStringOrNull(r.cached_m0_mural_data_url) && isStringOrNull(r.cached_m0_mural_hash) && isBlobOrNull(r.cached_m1_bytes) && isNumberOrNull(r.cached_m0_project_memory_epoch) && isStringOrNull(r.cached_m0_workspace_fingerprint) && isNumberOrNull(r.cached_m0_project_user_profile_version) && isNumberOrNull(r.cached_m0_max_compartment_seq) && isNumberOrNull(r.cached_m0_max_memory_id) && isNumberOrNull(r.cached_m0_max_mutation_id) && isNumberOrNull(r.cached_m0_max_memory_mutation_id) && isStringOrNull(r.cached_m0_project_docs_hash) && isNumberOrNull(r.cached_m0_materialized_at) && isNumberOrNull(r.cached_m0_session_facts_version) && isStringOrNull(r.cached_m0_upgrade_state) && isStringOrNull(r.cached_m0_system_hash) && isStringOrNull(r.cached_m0_tool_set_hash) && isStringOrNull(r.cached_m0_model_key) && isStringOrNull(r.cached_m0_project_identity) && isStringOrNull(r.last_observed_model_key) && isNumberOrNull(r.last_usage_context_limit) && isNumberOrNull(r.prior_boundary_ordinal) && isNumberOrNull(r.protected_tail_policy_version) && isNumberOrNull(r.protected_tail_drain_window_started_at) && isNumberOrNull(r.protected_tail_drain_tokens) && isNumberOrNull(r.recovery_no_eligible_head_count) && isNumberOrNull(r.force_emergency_bypass_window_start) && isNumberOrNull(r.force_emergency_bypass_used) && isNumberOrNull(r.upgrade_reminded_at) && isNumberOrNull(r.upgrade_reminder_last_sent_at) && isNumberOrNull(r.upgrade_reminder_count) && isNumberOrNull(r.pi_stable_id_scheme) && isNumberOrNull(r.tool_reclaim_watermark);
191
+ }
192
+ function getDefaultSessionMeta(sessionId) {
193
+ return {
194
+ sessionId,
195
+ lastResponseTime: 0,
196
+ cacheTtl: "5m",
197
+ counter: 0,
198
+ lastNudgeTokens: 0,
199
+ lastNudgeBand: null,
200
+ lastTransformError: null,
201
+ isSubagent: false,
202
+ lastContextPercentage: 0,
203
+ lastInputTokens: 0,
204
+ observedSafeInputTokens: 0,
205
+ cacheAlertSent: false,
206
+ timesExecuteThresholdReached: 0,
207
+ compartmentInProgress: false,
208
+ systemPromptHash: "",
209
+ systemPromptTokens: 0,
210
+ conversationTokens: 0,
211
+ toolCallTokens: 0,
212
+ clearedReasoningThroughTag: 0,
213
+ toolReclaimWatermark: 0,
214
+ lastTodoState: "",
215
+ cachedM0Bytes: null,
216
+ cachedM0MuralDataUrl: null,
217
+ cachedM0MuralHash: null,
218
+ cachedM1Bytes: null,
219
+ cachedM0ProjectMemoryEpoch: null,
220
+ cachedM0WorkspaceFingerprint: null,
221
+ cachedM0ProjectUserProfileVersion: null,
222
+ cachedM0MaxCompartmentSeq: null,
223
+ cachedM0MaxMemoryId: null,
224
+ cachedM0MaxMutationId: null,
225
+ cachedM0MaxMemoryMutationId: null,
226
+ cachedM0ProjectDocsHash: null,
227
+ cachedM0MaterializedAt: null,
228
+ cachedM0SessionFactsVersion: null,
229
+ cachedM0UpgradeState: null,
230
+ cachedM0SystemHash: null,
231
+ cachedM0ToolSetHash: null,
232
+ cachedM0ModelKey: null,
233
+ cachedM0ProjectIdentity: null,
234
+ lastObservedModelKey: null,
235
+ lastUsageContextLimit: 0,
236
+ priorBoundaryOrdinal: 1,
237
+ protectedTailPolicyVersion: 0,
238
+ protectedTailDrainWindowStartedAt: 0,
239
+ protectedTailDrainTokens: 0,
240
+ recoveryNoEligibleHeadCount: 0,
241
+ forceEmergencyBypassWindowStart: 0,
242
+ forceEmergencyBypassUsed: 0,
243
+ upgradeRemindedAt: null,
244
+ upgradeReminderLastSentAt: null,
245
+ upgradeReminderCount: 0,
246
+ piStableIdScheme: null
247
+ };
248
+ }
249
+ function ensureSessionMetaRow(db, sessionId) {
250
+ const defaults = getDefaultSessionMeta(sessionId);
251
+ db.prepare("INSERT OR IGNORE INTO session_meta (session_id, harness, last_response_time, cache_ttl, counter, last_nudge_tokens, last_nudge_band, last_transform_error, is_subagent, last_context_percentage, last_input_tokens, observed_safe_input_tokens, cache_alert_sent, times_execute_threshold_reached, compartment_in_progress, system_prompt_hash, cleared_reasoning_through_tag) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(sessionId, getHarness(), defaults.lastResponseTime, defaults.cacheTtl, defaults.counter, defaults.lastNudgeTokens, defaults.lastNudgeBand ?? "", defaults.lastTransformError ?? "", defaults.isSubagent ? 1 : 0, defaults.lastContextPercentage, defaults.lastInputTokens, defaults.observedSafeInputTokens, defaults.cacheAlertSent ? 1 : 0, defaults.timesExecuteThresholdReached, defaults.compartmentInProgress ? 1 : 0, defaults.systemPromptHash ?? "", defaults.clearedReasoningThroughTag);
252
+ }
253
+ function toSessionMeta(row) {
254
+ const nudgeBandRaw = typeof row.last_nudge_band === "string" ? row.last_nudge_band : "";
255
+ const transformErrorRaw = typeof row.last_transform_error === "string" ? row.last_transform_error : "";
256
+ const cacheTtlRaw = typeof row.cache_ttl === "string" && row.cache_ttl.length > 0 ? row.cache_ttl : "5m";
257
+ const systemPromptHashRaw = row.system_prompt_hash == null ? "" : row.system_prompt_hash;
258
+ const lastTodoStateRaw = typeof row.last_todo_state === "string" ? row.last_todo_state : "";
259
+ const numOrZero = (value) => typeof value === "number" ? value : 0;
260
+ const numOrNull = (value) => typeof value === "number" ? value : null;
261
+ const stringOrNull = (value) => typeof value === "string" ? value : null;
262
+ return {
263
+ sessionId: row.session_id,
264
+ lastResponseTime: row.last_response_time,
265
+ cacheTtl: cacheTtlRaw,
266
+ counter: row.counter,
267
+ lastNudgeTokens: row.last_nudge_tokens,
268
+ lastNudgeBand: nudgeBandRaw.length > 0 ? nudgeBandRaw : null,
269
+ lastTransformError: transformErrorRaw.length > 0 ? transformErrorRaw : null,
270
+ isSubagent: row.is_subagent === 1,
271
+ lastContextPercentage: row.last_context_percentage,
272
+ lastInputTokens: row.last_input_tokens,
273
+ observedSafeInputTokens: numOrZero(row.observed_safe_input_tokens),
274
+ cacheAlertSent: numOrZero(row.cache_alert_sent) === 1,
275
+ timesExecuteThresholdReached: numOrZero(row.times_execute_threshold_reached),
276
+ compartmentInProgress: row.compartment_in_progress === 1,
277
+ systemPromptHash: String(systemPromptHashRaw),
278
+ systemPromptTokens: numOrZero(row.system_prompt_tokens),
279
+ conversationTokens: numOrZero(row.conversation_tokens),
280
+ toolCallTokens: numOrZero(row.tool_call_tokens),
281
+ clearedReasoningThroughTag: numOrZero(row.cleared_reasoning_through_tag),
282
+ toolReclaimWatermark: numOrZero(row.tool_reclaim_watermark),
283
+ lastTodoState: lastTodoStateRaw,
284
+ cachedM0Bytes: toBufferOrNull(row.cached_m0_bytes),
285
+ cachedM0MuralDataUrl: stringOrNull(row.cached_m0_mural_data_url),
286
+ cachedM0MuralHash: stringOrNull(row.cached_m0_mural_hash),
287
+ cachedM1Bytes: toBufferOrNull(row.cached_m1_bytes),
288
+ cachedM0ProjectMemoryEpoch: numOrNull(row.cached_m0_project_memory_epoch),
289
+ cachedM0WorkspaceFingerprint: stringOrNull(row.cached_m0_workspace_fingerprint),
290
+ cachedM0ProjectUserProfileVersion: numOrNull(row.cached_m0_project_user_profile_version),
291
+ cachedM0MaxCompartmentSeq: numOrNull(row.cached_m0_max_compartment_seq),
292
+ cachedM0MaxMemoryId: numOrNull(row.cached_m0_max_memory_id),
293
+ cachedM0MaxMutationId: numOrNull(row.cached_m0_max_mutation_id),
294
+ cachedM0MaxMemoryMutationId: numOrNull(row.cached_m0_max_memory_mutation_id),
295
+ cachedM0ProjectDocsHash: stringOrNull(row.cached_m0_project_docs_hash),
296
+ cachedM0MaterializedAt: numOrNull(row.cached_m0_materialized_at),
297
+ cachedM0SessionFactsVersion: numOrNull(row.cached_m0_session_facts_version),
298
+ cachedM0UpgradeState: stringOrNull(row.cached_m0_upgrade_state),
299
+ cachedM0SystemHash: stringOrNull(row.cached_m0_system_hash),
300
+ cachedM0ToolSetHash: stringOrNull(row.cached_m0_tool_set_hash),
301
+ cachedM0ModelKey: stringOrNull(row.cached_m0_model_key),
302
+ cachedM0ProjectIdentity: stringOrNull(row.cached_m0_project_identity),
303
+ lastObservedModelKey: stringOrNull(row.last_observed_model_key),
304
+ lastUsageContextLimit: numOrZero(row.last_usage_context_limit),
305
+ priorBoundaryOrdinal: Math.max(1, numOrZero(row.prior_boundary_ordinal) || 1),
306
+ protectedTailPolicyVersion: numOrZero(row.protected_tail_policy_version),
307
+ protectedTailDrainWindowStartedAt: numOrZero(row.protected_tail_drain_window_started_at),
308
+ protectedTailDrainTokens: numOrZero(row.protected_tail_drain_tokens),
309
+ recoveryNoEligibleHeadCount: numOrZero(row.recovery_no_eligible_head_count),
310
+ forceEmergencyBypassWindowStart: numOrZero(row.force_emergency_bypass_window_start),
311
+ forceEmergencyBypassUsed: numOrZero(row.force_emergency_bypass_used),
312
+ upgradeRemindedAt: numOrNull(row.upgrade_reminded_at),
313
+ upgradeReminderLastSentAt: numOrNull(row.upgrade_reminder_last_sent_at),
314
+ upgradeReminderCount: numOrZero(row.upgrade_reminder_count),
315
+ piStableIdScheme: numOrNull(row.pi_stable_id_scheme)
316
+ };
317
+ }
318
+ function persistCachedM0(db, sessionId, payload) {
319
+ ensureSessionMetaRow(db, sessionId);
320
+ db.prepare(`UPDATE session_meta SET
321
+ cached_m0_bytes = ?,
322
+ cached_m0_mural_data_url = ?,
323
+ cached_m0_mural_hash = ?,
324
+ cached_m0_project_memory_epoch = ?,
325
+ cached_m0_workspace_fingerprint = ?,
326
+ cached_m0_project_user_profile_version = ?,
327
+ cached_m0_max_compartment_seq = ?,
328
+ cached_m0_max_memory_id = ?,
329
+ cached_m0_max_mutation_id = ?,
330
+ cached_m0_max_memory_mutation_id = ?,
331
+ cached_m1_bytes = ?,
332
+ cached_m0_project_docs_hash = ?,
333
+ cached_m0_materialized_at = ?,
334
+ cached_m0_session_facts_version = ?,
335
+ cached_m0_upgrade_state = ?,
336
+ cached_m0_system_hash = ?,
337
+ cached_m0_tool_set_hash = ?,
338
+ cached_m0_model_key = ?,
339
+ cached_m0_project_identity = ?
340
+ WHERE session_id = ?`).run(Buffer.from(payload.m0Bytes), payload.muralDataUrl ?? null, payload.muralHash ?? null, payload.projectMemoryEpoch, payload.workspaceFingerprint ?? null, payload.projectUserProfileVersion, payload.maxCompartmentSeq, payload.maxMemoryId, payload.maxMutationId, payload.maxMemoryMutationId ?? null, payload.m1Bytes ? Buffer.from(payload.m1Bytes) : null, payload.projectDocsHash, payload.materializedAt, payload.sessionFactsVersion, payload.upgradeState, payload.systemHash ?? "", payload.toolSetHash ?? "", payload.modelKey ? piModelRefToCanonical(payload.modelKey) : "", payload.projectIdentity ?? null, sessionId);
341
+ }
342
+ function clearCachedM0M1(db, sessionId) {
343
+ ensureSessionMetaRow(db, sessionId);
344
+ const existingColumns = new Set(db.prepare("PRAGMA table_info(session_meta)").all().map((column) => column.name));
345
+ const clears = [
346
+ ["cached_m0_bytes", null],
347
+ ["cached_m0_mural_data_url", null],
348
+ ["cached_m0_mural_hash", null],
349
+ ["cached_m1_bytes", null],
350
+ ["cached_m0_project_memory_epoch", null],
351
+ ["cached_m0_workspace_fingerprint", null],
352
+ ["cached_m0_project_user_profile_version", null],
353
+ ["cached_m0_max_compartment_seq", null],
354
+ ["cached_m0_max_memory_id", null],
355
+ ["cached_m0_max_mutation_id", null],
356
+ ["cached_m0_max_memory_mutation_id", null],
357
+ ["cached_m0_project_docs_hash", null],
358
+ ["cached_m0_materialized_at", null],
359
+ ["cached_m0_session_facts_version", null],
360
+ ["cached_m0_upgrade_state", null],
361
+ ["cached_m0_system_hash", null],
362
+ ["cached_m0_tool_set_hash", null],
363
+ ["cached_m0_model_key", null],
364
+ ["cached_m0_project_identity", null],
365
+ ["cached_m0_last_baseline_end_message_id", null],
366
+ ["memory_block_cache", ""],
367
+ ["memory_block_count", 0],
368
+ ["memory_block_ids", ""]
369
+ ];
370
+ const setClauses = [];
371
+ const values = [];
372
+ for (const [column, value] of clears) {
373
+ if (!existingColumns.has(column))
374
+ continue;
375
+ setClauses.push(`${column} = ?`);
376
+ values.push(value);
377
+ }
378
+ if (setClauses.length === 0)
379
+ return;
380
+ db.prepare(`UPDATE session_meta SET ${setClauses.join(", ")} WHERE session_id = ?`).run(...values, sessionId);
381
+ }
382
+
383
+ // src/features/magic-context/storage-session-tables.ts
384
+ var SESSION_SCOPED_TABLES = [
385
+ { table: "pending_ops", harnessScoped: true },
386
+ { table: "source_contents", harnessScoped: true },
387
+ { table: "tool_owner_backfill_state" },
388
+ { table: "tags", harnessScoped: true },
389
+ { table: "session_meta", harnessScoped: true },
390
+ { table: "session_projects", harnessScoped: true },
391
+ { table: "compartment_chunk_embeddings", harnessScoped: true },
392
+ { table: "compartments", harnessScoped: true },
393
+ { table: "compression_depth", harnessScoped: true },
394
+ { table: "session_facts", harnessScoped: true },
395
+ { table: "compartment_state_lease" },
396
+ { table: "notes", harnessScoped: true, extraPredicate: "type = 'session'" },
397
+ { table: "recomp_compartments", harnessScoped: true },
398
+ { table: "recomp_facts", harnessScoped: true },
399
+ { table: "user_memory_candidates" },
400
+ { table: "primer_candidates", harnessScoped: true },
401
+ { table: "m0_mutation_log" },
402
+ { table: "compartment_events", harnessScoped: true },
403
+ { table: "subagent_invocations", harnessScoped: true },
404
+ { table: "historian_runs", harnessScoped: true },
405
+ { table: "plugin_messages" },
406
+ { table: "transform_decisions", harnessScoped: true },
407
+ { table: "synapse_batch_ledger" },
408
+ { table: "embedding_measurement_corpus" },
409
+ { table: "pending_session_cleanup", harnessScoped: true },
410
+ { table: "message_history_fts" },
411
+ { table: "message_history_source", harnessScoped: true },
412
+ { table: "message_history_index", harnessScoped: true },
413
+ { table: "lkg_slots" }
414
+ ];
415
+ function deleteSessionScopedRows(db, sessionIds, harness) {
416
+ if (sessionIds.length === 0)
417
+ return;
418
+ const placeholders = sessionIds.map(() => "?").join(", ");
419
+ for (const definition of SESSION_SCOPED_TABLES) {
420
+ const predicates = [`session_id IN (${placeholders})`];
421
+ if (definition.extraPredicate)
422
+ predicates.push(definition.extraPredicate);
423
+ const bindHarness = harness !== undefined && definition.harnessScoped === true;
424
+ if (bindHarness)
425
+ predicates.push("harness = ?");
426
+ const statement = db.prepare(`DELETE FROM ${definition.table} WHERE ${predicates.join(" AND ")}`);
427
+ if (bindHarness)
428
+ statement.run(...sessionIds, harness);
429
+ else
430
+ statement.run(...sessionIds);
431
+ }
432
+ }
433
+
434
+ // src/features/magic-context/storage-meta-session.ts
435
+ var SESSION_META_FALLBACK_SELECTS = {
436
+ cache_ttl: "'5m' AS cache_ttl",
437
+ last_nudge_band: "'' AS last_nudge_band",
438
+ last_transform_error: "'' AS last_transform_error",
439
+ system_prompt_hash: "'' AS system_prompt_hash",
440
+ last_todo_state: "'' AS last_todo_state",
441
+ tool_reclaim_watermark: "0 AS tool_reclaim_watermark",
442
+ cached_m0_bytes: "NULL AS cached_m0_bytes",
443
+ cached_m0_mural_data_url: "NULL AS cached_m0_mural_data_url",
444
+ cached_m0_mural_hash: "NULL AS cached_m0_mural_hash",
445
+ cached_m1_bytes: "NULL AS cached_m1_bytes",
446
+ cached_m0_project_memory_epoch: "NULL AS cached_m0_project_memory_epoch",
447
+ cached_m0_project_user_profile_version: "NULL AS cached_m0_project_user_profile_version",
448
+ cached_m0_max_compartment_seq: "NULL AS cached_m0_max_compartment_seq",
449
+ cached_m0_max_memory_id: "NULL AS cached_m0_max_memory_id",
450
+ cached_m0_max_mutation_id: "NULL AS cached_m0_max_mutation_id",
451
+ cached_m0_max_memory_mutation_id: "NULL AS cached_m0_max_memory_mutation_id",
452
+ cached_m0_project_docs_hash: "NULL AS cached_m0_project_docs_hash",
453
+ cached_m0_materialized_at: "NULL AS cached_m0_materialized_at",
454
+ cached_m0_session_facts_version: "NULL AS cached_m0_session_facts_version",
455
+ cached_m0_upgrade_state: "NULL AS cached_m0_upgrade_state",
456
+ cached_m0_system_hash: "NULL AS cached_m0_system_hash",
457
+ cached_m0_tool_set_hash: "NULL AS cached_m0_tool_set_hash",
458
+ cached_m0_model_key: "NULL AS cached_m0_model_key",
459
+ cached_m0_project_identity: "NULL AS cached_m0_project_identity",
460
+ last_observed_model_key: "NULL AS last_observed_model_key",
461
+ upgrade_reminded_at: "NULL AS upgrade_reminded_at",
462
+ upgrade_reminder_last_sent_at: "NULL AS upgrade_reminder_last_sent_at",
463
+ upgrade_reminder_count: "0 AS upgrade_reminder_count"
464
+ };
465
+ var sessionMetaSelectColumnsCache = new WeakMap;
466
+ function getSessionMetaSelectColumns(db) {
467
+ const cached = sessionMetaSelectColumnsCache.get(db);
468
+ if (cached !== undefined)
469
+ return cached;
470
+ const existingColumns = new Set(db.prepare("PRAGMA table_info(session_meta)").all().map((column) => column.name));
471
+ const projection = SESSION_META_SELECT_COLUMNS.map((column) => {
472
+ if (existingColumns.has(column))
473
+ return column;
474
+ return SESSION_META_FALLBACK_SELECTS[column] ?? `0 AS ${column}`;
475
+ }).join(", ");
476
+ sessionMetaSelectColumnsCache.set(db, projection);
477
+ return projection;
478
+ }
479
+ function getOrCreateSessionMeta(db, sessionId) {
480
+ const result = db.prepare(`SELECT ${getSessionMetaSelectColumns(db)} FROM session_meta WHERE session_id = ?`).get(sessionId);
481
+ if (isSessionMetaRow(result)) {
482
+ return toSessionMeta(result);
483
+ }
484
+ const defaults = getDefaultSessionMeta(sessionId);
485
+ const fallbackSubagent = getHarness() === "opencode" ? resolveIsSubagentFromOpenCodeDb(sessionId) : null;
486
+ if (fallbackSubagent === true) {
487
+ defaults.isSubagent = true;
488
+ }
489
+ ensureSessionMetaRow(db, sessionId);
490
+ if (fallbackSubagent === true) {
491
+ db.prepare("UPDATE session_meta SET is_subagent = 1 WHERE session_id = ?").run(sessionId);
492
+ }
493
+ return defaults;
494
+ }
495
+ function updateSessionMeta(db, sessionId, updates) {
496
+ const setClauses = [];
497
+ const values = [];
498
+ for (const [key, column] of Object.entries(META_COLUMNS)) {
499
+ const value = updates[key];
500
+ if (value === undefined)
501
+ continue;
502
+ if (value === null) {
503
+ setClauses.push(`${column} = ?`);
504
+ values.push(NULL_BIND_META_KEYS.has(key) ? null : "");
505
+ } else if ((key === "cachedM0Bytes" || key === "cachedM1Bytes") && value instanceof Uint8Array) {
506
+ setClauses.push(`${column} = ?`);
507
+ values.push(Buffer2.from(value.buffer, value.byteOffset, value.byteLength));
508
+ } else if (BOOLEAN_META_KEYS.has(key)) {
509
+ setClauses.push(`${column} = ?`);
510
+ values.push(value ? 1 : 0);
511
+ } else if (typeof value === "string" || typeof value === "number") {
512
+ setClauses.push(`${column} = ?`);
513
+ values.push(key === "lastObservedModelKey" && typeof value === "string" ? piModelRefToCanonical(value) : value);
514
+ }
515
+ }
516
+ if (setClauses.length === 0) {
517
+ return;
518
+ }
519
+ db.transaction(() => {
520
+ ensureSessionMetaRow(db, sessionId);
521
+ db.prepare(`UPDATE session_meta SET ${setClauses.join(", ")} WHERE session_id = ?`).run(...values, sessionId);
522
+ })();
523
+ }
524
+ function advanceToolReclaimWatermark(db, sessionId, maxTagNumber) {
525
+ if (maxTagNumber <= 0)
526
+ return;
527
+ db.transaction(() => {
528
+ ensureSessionMetaRow(db, sessionId);
529
+ db.prepare("UPDATE session_meta SET tool_reclaim_watermark = MAX(COALESCE(tool_reclaim_watermark, 0), ?) WHERE session_id = ?").run(maxTagNumber, sessionId);
530
+ })();
531
+ }
532
+ function markSessionCleanupPending(db, sessionId) {
533
+ db.prepare(`INSERT INTO pending_session_cleanup (session_id, harness, requested_at, last_attempt_at)
534
+ VALUES (?, ?, ?, NULL)
535
+ ON CONFLICT(session_id) DO UPDATE SET
536
+ harness = excluded.harness,
537
+ requested_at = MIN(pending_session_cleanup.requested_at, excluded.requested_at)`).run(sessionId, getHarness(), Date.now());
538
+ }
539
+ function retryPendingSessionCleanups(db, limit = 200) {
540
+ const rows = db.prepare("SELECT session_id FROM pending_session_cleanup ORDER BY requested_at ASC, session_id ASC LIMIT ?").all(Math.max(1, Math.floor(limit)));
541
+ const failedSessionIds = [];
542
+ let cleared = 0;
543
+ for (const row of rows) {
544
+ try {
545
+ db.prepare("UPDATE pending_session_cleanup SET last_attempt_at = ? WHERE session_id = ?").run(Date.now(), row.session_id);
546
+ clearSession(db, row.session_id);
547
+ cleared += 1;
548
+ } catch {
549
+ failedSessionIds.push(row.session_id);
550
+ }
551
+ }
552
+ return { attempted: rows.length, cleared, failedSessionIds };
553
+ }
554
+ function clearSession(db, sessionId) {
555
+ db.transaction(() => {
556
+ deleteSessionScopedRows(db, [sessionId]);
557
+ })();
558
+ }
559
+
560
+ export { ensureSessionMetaRow, persistCachedM0, clearCachedM0M1, deleteSessionScopedRows, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, markSessionCleanupPending, retryPendingSessionCleanups, clearSession };
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAiB,YAAY,EAAE,MAAM,qBAAqB,CAAC;AA0zBvE,QAAA,MAAM,MAAM,EAAE,YAGb,CAAC;AAEF,eAAe,MAAM,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAiB,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAg0BvE,QAAA,MAAM,MAAM,EAAE,YAGb,CAAC;AAEF,eAAe,MAAM,CAAC"}