@cortexkit/opencode-magic-context 0.49.82 → 0.49.84
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auto-search-worker.js +1 -1
- package/dist/chunk-embedding-write-worker.js +1 -1
- package/dist/{context-00f1hdz2.js → context-3sajdysh.js} +309 -98
- package/dist/{derive-budgets-2z6xxm7e.js → derive-budgets-0kcek5ex.js} +1 -1
- package/dist/features/magic-context/dreamer/map-memories-retry.d.ts +18 -0
- package/dist/features/magic-context/dreamer/map-memories-retry.d.ts.map +1 -0
- package/dist/features/magic-context/dreamer/map-memories.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/retrospective-raw-provider.d.ts +2 -0
- package/dist/features/magic-context/dreamer/retrospective-raw-provider.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-gates.d.ts +1 -1
- package/dist/features/magic-context/dreamer/task-gates.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-registry.d.ts +7 -0
- package/dist/features/magic-context/dreamer/task-registry.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-scheduler.d.ts +9 -0
- package/dist/features/magic-context/dreamer/task-scheduler.d.ts.map +1 -1
- package/dist/features/magic-context/mural/render-trigger.d.ts +3 -3
- package/dist/features/magic-context/mural/render-trigger.d.ts.map +1 -1
- package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
- package/dist/{index-zzvd4a9z.js → index-05bm2ndp.js} +1 -1
- package/dist/{index-2xhzmwf6.js → index-0wehkw71.js} +5 -5
- package/dist/{index-zvane1rq.js → index-5wjv4c41.js} +1 -1
- package/dist/{index-twmeey4h.js → index-70cv85b0.js} +2 -2
- package/dist/{index-2q0t43fy.js → index-7j2zv9nm.js} +1 -1
- package/dist/{index-wxxcfpxh.js → index-cfy5k1pa.js} +6 -6
- package/dist/{index-b2787fk6.js → index-d028gmgp.js} +25 -9
- package/dist/{index-dg5jvh9r.js → index-k0jnsjcp.js} +3 -3
- package/dist/{index-nda0zgna.js → index-kknjvmpx.js} +2 -1
- package/dist/{index-tky3j43e.js → index-kthfyf45.js} +55 -11
- package/dist/{index-hz1xdb15.js → index-qybp04ff.js} +3 -3
- package/dist/{index-e21n48yd.js → index-rdh63md0.js} +23 -0
- package/dist/{index-x8qgqnym.js → index-skwwbcnv.js} +2 -2
- package/dist/{index-2ygw6q5s.js → index-szwrpyac.js} +2 -2
- package/dist/{index-eptthgkw.js → index-tqnvn9pa.js} +5 -5
- package/dist/{index-93rezfvc.js → index-tvbkemec.js} +37 -6
- package/dist/{index-rnyaa7cj.js → index-xd0ww0ns.js} +1 -1
- package/dist/{index-jvr9ba9y.js → index-xjfan0za.js} +210 -139
- package/dist/{index-y208s7zx.js → index-xrnhxkz7.js} +6 -1
- package/dist/index.js +21 -21
- package/dist/{message-index-bounded-cfkeyf72.js → message-index-bounded-6fr624zf.js} +3 -3
- package/dist/migration-worker.js +1 -1
- package/dist/raw-ordinal-warmup-worker.js +4 -4
- package/dist/{read-session-chunk-s3qac56g.js → read-session-chunk-6wedfths.js} +2 -2
- package/dist/{recomp-orchestrator-fjdp3t1d.js → recomp-orchestrator-m2s3jpvj.js} +9 -9
- package/dist/{render-c9fjwrad.js → render-p2j7rn9a.js} +7 -7
- package/dist/{search-archive-s2jas2jb.js → search-archive-hz9xh7nh.js} +4 -4
- package/dist/{search-1jejx5cx.js → search-ksx0f1qd.js} +5 -5
- package/dist/shared/models-dev-cache.d.ts +6 -1
- package/dist/shared/models-dev-cache.d.ts.map +1 -1
- package/dist/shared/test-git-env.d.ts +3 -0
- package/dist/shared/test-git-env.d.ts.map +1 -0
- package/dist/{storage-tags-6e83pvff.js → storage-tags-y2mrb8e6.js} +1 -1
- package/dist/{store-reader-tr64nxyy.js → store-reader-tsv1w4vt.js} +1 -1
- package/dist/{store-ggrq9e14.js → store-x0swqb5c.js} +2 -2
- package/dist/{task-config-t6bpyka7.js → task-config-qt6n4bxm.js} +1 -1
- package/dist/{transform-postprocess-phase-p2egg02g.js → transform-postprocess-phase-1wb2rrr1.js} +10 -10
- package/dist/v2/auto-search-worker.js +1 -1
- package/dist/v2/chunk-embedding-write-worker.js +3 -3
- package/dist/v2/{context-gwkgh0wd.js → context-at9nje0j.js} +711 -435
- package/dist/v2/{derive-budgets-2eam671q.js → derive-budgets-xbwcap8k.js} +2 -2
- package/dist/v2/fold/restore.d.ts.map +1 -1
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/hooks/revert-message-state.d.ts +12 -0
- package/dist/v2/hooks/revert-message-state.d.ts.map +1 -0
- package/dist/v2/hooks/storage-notice.d.ts +12 -6
- package/dist/v2/hooks/storage-notice.d.ts.map +1 -1
- package/dist/v2/{message-index-bounded-0xy4dn04.js → message-index-bounded-jqy7283g.js} +4 -4
- package/dist/v2/migration-worker.js +3 -3
- package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
- package/dist/v2/{read-session-chunk-6mt2t6dy.js → read-session-chunk-n3nhfvd7.js} +3 -3
- package/dist/v2/{recomp-orchestrator-jn39mxh0.js → recomp-orchestrator-nhef90gc.js} +13 -13
- package/dist/v2/{render-q2aj9bgy.js → render-c9r2g2jv.js} +10 -10
- package/dist/v2/retrospective-raw-provider.d.ts.map +1 -1
- package/dist/v2/{search-archive-fj59gjv1.js → search-archive-80ckv9kq.js} +5 -5
- package/dist/v2/{search-9xn6ds9x.js → search-t06js5dc.js} +7 -7
- package/dist/v2/{server-2ktxmtbd.js → server-210rc0z9.js} +1 -1
- package/dist/v2/{server-2gcfmd47.js → server-2k8tkbhz.js} +2 -2
- package/dist/v2/{server-92g7d776.js → server-2kswss3d.js} +2 -1
- package/dist/v2/{server-c8mqs0v5.js → server-3cndh146.js} +10 -10
- package/dist/v2/{server-vt6nj2hn.js → server-3hhakg5a.js} +35 -19
- package/dist/v2/{server-53n8hv5q.js → server-863bwkga.js} +4 -4
- package/dist/v2/{server-5yfq912a.js → server-9nk5h6w6.js} +23 -0
- package/dist/v2/{server-xepx8t43.js → server-a2f1bhyj.js} +1 -1
- package/dist/v2/{server-r00xyx66.js → server-ap81bk3c.js} +28 -28
- package/dist/v2/{server-1efjj215.js → server-cce6m31c.js} +37 -6
- package/dist/v2/{server-2w1rdttn.js → server-dfesqfv1.js} +2 -2
- package/dist/v2/{server-569he5mh.js → server-hhw6rzsn.js} +1 -1
- package/dist/v2/{server-1cn3kryt.js → server-mr9rqn0y.js} +5 -5
- package/dist/v2/{server-g1a0nhtk.js → server-ry6rpspz.js} +4 -4
- package/dist/v2/{server-xdh4r20h.js → server-s15knz0w.js} +642 -627
- package/dist/v2/{server-0dmzr7f9.js → server-sxfbjdye.js} +2 -2
- package/dist/v2/{server-nqdzv8b7.js → server-sy98vksf.js} +55 -11
- package/dist/v2/{server-rp52f40v.js → server-w1jfaxas.js} +1 -1
- package/dist/v2/{server-bj779zmp.js → server-y4favn4d.js} +1 -1
- package/dist/v2/server.js +4 -4
- package/dist/v2/{storage-tags-z8j8wq34.js → storage-tags-xq81zgt2.js} +2 -2
- package/dist/v2/{store-qdgzd38f.js → store-h3s95ywe.js} +2 -2
- package/dist/v2/{store-reader-83tka051.js → store-reader-paamf0ac.js} +1 -1
- package/dist/v2/store-reader.d.ts +11 -0
- package/dist/v2/store-reader.d.ts.map +1 -1
- package/dist/v2/{task-config-7md27rx8.js → task-config-ex2vajr2.js} +1 -1
- package/dist/v2/{v2-archive-reader-9z8z97db.js → v2-archive-reader-1zzteaa5.js} +1 -1
- package/dist/v2/{wrapup-orchestrator-vd5zfp3v.js → wrapup-orchestrator-9y98qcqz.js} +13 -13
- package/dist/{v2-archive-reader-r0xpxsb1.js → v2-archive-reader-3yjxaj5z.js} +1 -1
- package/dist/{wrapup-orchestrator-k29zqfp9.js → wrapup-orchestrator-sa3a075a.js} +10 -10
- package/package.json +1 -1
- package/src/features/magic-context/dreamer/task-registry.ts +8 -0
- package/src/shared/models-dev-cache.ts +90 -21
- package/src/shared/reusable-worker.test.ts +31 -29
- package/src/shared/sqlite.test.ts +19 -6
- package/src/shared/test-db.test.ts +5 -3
- package/src/shared/test-git-env.test.ts +38 -0
- package/src/shared/test-git-env.ts +10 -0
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getHarness2
|
|
3
|
+
} from "./server-pavzsdc6.js";
|
|
4
|
+
import {
|
|
5
|
+
getTagIdentityWriteGeneration2,
|
|
6
|
+
getSqliteDatabasePath2,
|
|
7
|
+
prepareCachedStatement2
|
|
8
|
+
} from "./server-gzy5w8ya.js";
|
|
1
9
|
import {
|
|
2
10
|
UNKNOWN_FIT_RATIO,
|
|
3
11
|
resolveDecisionCalibration,
|
|
@@ -11,9 +19,6 @@ import {
|
|
|
11
19
|
estimateTokens,
|
|
12
20
|
createTokenCountMemo
|
|
13
21
|
} from "./server-y8xjr8rx.js";
|
|
14
|
-
import {
|
|
15
|
-
getHarness2
|
|
16
|
-
} from "./server-pavzsdc6.js";
|
|
17
22
|
import {
|
|
18
23
|
sessionLog2
|
|
19
24
|
} from "./server-j8376q08.js";
|
|
@@ -25,7 +30,7 @@ import {
|
|
|
25
30
|
getSessionToolDefinitionTokens,
|
|
26
31
|
tagOrderConstraintIndex,
|
|
27
32
|
tagIdentityRevisionKey
|
|
28
|
-
} from "./server-
|
|
33
|
+
} from "./server-a2f1bhyj.js";
|
|
29
34
|
import {
|
|
30
35
|
resolveModelConfigValue,
|
|
31
36
|
DEFAULT_PROTECTED_TOOLS,
|
|
@@ -33,11 +38,6 @@ import {
|
|
|
33
38
|
mergeProtectedTools,
|
|
34
39
|
deriveDefaultProtectedTokens
|
|
35
40
|
} from "./server-rz6g5xne.js";
|
|
36
|
-
import {
|
|
37
|
-
getTagIdentityWriteGeneration2,
|
|
38
|
-
getSqliteDatabasePath2,
|
|
39
|
-
prepareCachedStatement2
|
|
40
|
-
} from "./server-gzy5w8ya.js";
|
|
41
41
|
import {
|
|
42
42
|
canonicalModelIdentity,
|
|
43
43
|
piModelRefToCanonical
|
|
@@ -46,149 +46,522 @@ import {
|
|
|
46
46
|
logSlowWriteTransaction
|
|
47
47
|
} from "./server-5sbsnpkn.js";
|
|
48
48
|
|
|
49
|
-
// src/features/magic-context/storage-
|
|
50
|
-
import {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
49
|
+
// src/features/magic-context/storage-meta-shared.ts
|
|
50
|
+
import { Buffer as Buffer2 } from "node:buffer";
|
|
51
|
+
var CACHED_TRIM_PARTIAL_SQL = `EXISTS (
|
|
52
|
+
SELECT 1 FROM compartments
|
|
53
|
+
WHERE compartments.session_id = session_meta.session_id
|
|
54
|
+
AND compartments.end_message_id = session_meta.cached_m0_last_baseline_end_message_id
|
|
55
|
+
AND compartments.end_block_index IS NOT NULL
|
|
56
|
+
)`;
|
|
57
|
+
var SESSION_META_SELECT_COLUMNS = [
|
|
58
|
+
"session_id",
|
|
59
|
+
"last_response_time",
|
|
60
|
+
"cache_ttl",
|
|
61
|
+
"counter",
|
|
62
|
+
"last_nudge_tokens",
|
|
63
|
+
"last_nudge_band",
|
|
64
|
+
"last_transform_error",
|
|
65
|
+
"is_subagent",
|
|
66
|
+
"last_context_percentage",
|
|
67
|
+
"last_input_tokens",
|
|
68
|
+
"observed_safe_input_tokens",
|
|
69
|
+
"cache_alert_sent",
|
|
70
|
+
"times_execute_threshold_reached",
|
|
71
|
+
"compartment_in_progress",
|
|
72
|
+
"system_prompt_hash",
|
|
73
|
+
"system_prompt_tokens",
|
|
74
|
+
"conversation_tokens",
|
|
75
|
+
"tool_call_tokens",
|
|
76
|
+
"cleared_reasoning_through_tag",
|
|
77
|
+
"tool_reclaim_watermark",
|
|
78
|
+
"last_todo_state",
|
|
79
|
+
"cached_m0_bytes",
|
|
80
|
+
"cached_m0_mural_data_url",
|
|
81
|
+
"cached_m0_mural_hash",
|
|
82
|
+
"cached_m1_bytes",
|
|
83
|
+
"cached_m0_last_baseline_end_message_id",
|
|
84
|
+
"cached_m0_project_memory_epoch",
|
|
85
|
+
"cached_m0_workspace_fingerprint",
|
|
86
|
+
"cached_m0_project_user_profile_version",
|
|
87
|
+
"cached_m0_max_compartment_seq",
|
|
88
|
+
"cached_m0_max_memory_id",
|
|
89
|
+
"cached_m0_max_mutation_id",
|
|
90
|
+
"cached_m0_max_memory_mutation_id",
|
|
91
|
+
"cached_m0_project_docs_hash",
|
|
92
|
+
"cached_m0_materialized_at",
|
|
93
|
+
"cached_m0_session_facts_version",
|
|
94
|
+
"cached_m0_upgrade_state",
|
|
95
|
+
"cached_m0_system_hash",
|
|
96
|
+
"cached_m0_tool_set_hash",
|
|
97
|
+
"cached_m0_model_key",
|
|
98
|
+
"cached_m0_project_identity",
|
|
99
|
+
"last_observed_model_key",
|
|
100
|
+
"last_usage_context_limit",
|
|
101
|
+
"prior_boundary_ordinal",
|
|
102
|
+
"protected_tail_policy_version",
|
|
103
|
+
"protected_tail_drain_window_started_at",
|
|
104
|
+
"protected_tail_drain_tokens",
|
|
105
|
+
"recovery_no_eligible_head_count",
|
|
106
|
+
"force_emergency_bypass_window_start",
|
|
107
|
+
"force_emergency_bypass_used",
|
|
108
|
+
"emergency_drain_active",
|
|
109
|
+
"historian_drain_failure_at",
|
|
110
|
+
"upgrade_reminded_at",
|
|
111
|
+
"upgrade_reminder_last_sent_at",
|
|
112
|
+
"upgrade_reminder_count",
|
|
113
|
+
"pi_stable_id_scheme"
|
|
114
|
+
];
|
|
115
|
+
var META_COLUMNS = {
|
|
116
|
+
lastResponseTime: "last_response_time",
|
|
117
|
+
cacheTtl: "cache_ttl",
|
|
118
|
+
counter: "counter",
|
|
119
|
+
lastNudgeTokens: "last_nudge_tokens",
|
|
120
|
+
lastNudgeBand: "last_nudge_band",
|
|
121
|
+
lastTransformError: "last_transform_error",
|
|
122
|
+
isSubagent: "is_subagent",
|
|
123
|
+
lastContextPercentage: "last_context_percentage",
|
|
124
|
+
lastInputTokens: "last_input_tokens",
|
|
125
|
+
observedSafeInputTokens: "observed_safe_input_tokens",
|
|
126
|
+
cacheAlertSent: "cache_alert_sent",
|
|
127
|
+
timesExecuteThresholdReached: "times_execute_threshold_reached",
|
|
128
|
+
compartmentInProgress: "compartment_in_progress",
|
|
129
|
+
systemPromptHash: "system_prompt_hash",
|
|
130
|
+
systemPromptTokens: "system_prompt_tokens",
|
|
131
|
+
conversationTokens: "conversation_tokens",
|
|
132
|
+
toolCallTokens: "tool_call_tokens",
|
|
133
|
+
clearedReasoningThroughTag: "cleared_reasoning_through_tag",
|
|
134
|
+
toolReclaimWatermark: "tool_reclaim_watermark",
|
|
135
|
+
lastTodoState: "last_todo_state",
|
|
136
|
+
cachedM0Bytes: "cached_m0_bytes",
|
|
137
|
+
cachedM0MuralDataUrl: "cached_m0_mural_data_url",
|
|
138
|
+
cachedM0MuralHash: "cached_m0_mural_hash",
|
|
139
|
+
cachedM1Bytes: "cached_m1_bytes",
|
|
140
|
+
cachedM0ProjectMemoryEpoch: "cached_m0_project_memory_epoch",
|
|
141
|
+
cachedM0WorkspaceFingerprint: "cached_m0_workspace_fingerprint",
|
|
142
|
+
cachedM0ProjectUserProfileVersion: "cached_m0_project_user_profile_version",
|
|
143
|
+
cachedM0MaxCompartmentSeq: "cached_m0_max_compartment_seq",
|
|
144
|
+
cachedM0MaxMemoryId: "cached_m0_max_memory_id",
|
|
145
|
+
cachedM0MaxMutationId: "cached_m0_max_mutation_id",
|
|
146
|
+
cachedM0MaxMemoryMutationId: "cached_m0_max_memory_mutation_id",
|
|
147
|
+
cachedM0ProjectDocsHash: "cached_m0_project_docs_hash",
|
|
148
|
+
cachedM0MaterializedAt: "cached_m0_materialized_at",
|
|
149
|
+
cachedM0SessionFactsVersion: "cached_m0_session_facts_version",
|
|
150
|
+
cachedM0UpgradeState: "cached_m0_upgrade_state",
|
|
151
|
+
cachedM0SystemHash: "cached_m0_system_hash",
|
|
152
|
+
cachedM0ToolSetHash: "cached_m0_tool_set_hash",
|
|
153
|
+
cachedM0ModelKey: "cached_m0_model_key",
|
|
154
|
+
cachedM0ProjectIdentity: "cached_m0_project_identity",
|
|
155
|
+
lastObservedModelKey: "last_observed_model_key",
|
|
156
|
+
lastUsageContextLimit: "last_usage_context_limit",
|
|
157
|
+
priorBoundaryOrdinal: "prior_boundary_ordinal",
|
|
158
|
+
protectedTailPolicyVersion: "protected_tail_policy_version",
|
|
159
|
+
protectedTailDrainWindowStartedAt: "protected_tail_drain_window_started_at",
|
|
160
|
+
protectedTailDrainTokens: "protected_tail_drain_tokens",
|
|
161
|
+
recoveryNoEligibleHeadCount: "recovery_no_eligible_head_count",
|
|
162
|
+
forceEmergencyBypassWindowStart: "force_emergency_bypass_window_start",
|
|
163
|
+
forceEmergencyBypassUsed: "force_emergency_bypass_used",
|
|
164
|
+
emergencyDrainActive: "emergency_drain_active",
|
|
165
|
+
historianDrainFailureAt: "historian_drain_failure_at",
|
|
166
|
+
upgradeRemindedAt: "upgrade_reminded_at",
|
|
167
|
+
upgradeReminderLastSentAt: "upgrade_reminder_last_sent_at",
|
|
168
|
+
upgradeReminderCount: "upgrade_reminder_count",
|
|
169
|
+
piStableIdScheme: "pi_stable_id_scheme"
|
|
170
|
+
};
|
|
171
|
+
var BOOLEAN_META_KEYS = new Set(["isSubagent", "compartmentInProgress", "cacheAlertSent"]);
|
|
172
|
+
var NULL_BIND_META_KEYS = new Set([
|
|
173
|
+
"cachedM0Bytes",
|
|
174
|
+
"cachedM0MuralDataUrl",
|
|
175
|
+
"cachedM0MuralHash",
|
|
176
|
+
"cachedM1Bytes",
|
|
177
|
+
"cachedM0ProjectMemoryEpoch",
|
|
178
|
+
"cachedM0WorkspaceFingerprint",
|
|
179
|
+
"cachedM0ProjectUserProfileVersion",
|
|
180
|
+
"cachedM0MaxCompartmentSeq",
|
|
181
|
+
"cachedM0MaxMemoryId",
|
|
182
|
+
"cachedM0MaxMutationId",
|
|
183
|
+
"cachedM0MaxMemoryMutationId",
|
|
184
|
+
"cachedM0ProjectDocsHash",
|
|
185
|
+
"cachedM0MaterializedAt",
|
|
186
|
+
"cachedM0SessionFactsVersion",
|
|
187
|
+
"cachedM0UpgradeState",
|
|
188
|
+
"cachedM0ProjectIdentity",
|
|
189
|
+
"lastObservedModelKey",
|
|
190
|
+
"upgradeRemindedAt",
|
|
191
|
+
"upgradeReminderLastSentAt",
|
|
192
|
+
"piStableIdScheme"
|
|
193
|
+
]);
|
|
194
|
+
function isStringOrNull(value) {
|
|
195
|
+
return value === null || typeof value === "string";
|
|
98
196
|
}
|
|
99
|
-
function
|
|
100
|
-
return value
|
|
197
|
+
function isNumberOrNull(value) {
|
|
198
|
+
return value === null || typeof value === "number";
|
|
101
199
|
}
|
|
102
|
-
function
|
|
103
|
-
return value.
|
|
200
|
+
function isBlobOrNull(value) {
|
|
201
|
+
return value === null || Buffer2.isBuffer(value) || value instanceof Uint8Array;
|
|
104
202
|
}
|
|
105
|
-
function
|
|
106
|
-
if (
|
|
203
|
+
function toBufferOrNull(value) {
|
|
204
|
+
if (value === null)
|
|
205
|
+
return null;
|
|
206
|
+
if (Buffer2.isBuffer(value))
|
|
107
207
|
return value;
|
|
108
|
-
|
|
109
|
-
text = stripCompleteTagPairsGlobally(text);
|
|
110
|
-
text = stripMalformedTagNotationGlobally(text);
|
|
111
|
-
text = stripDanglingTagNotationGlobally(text);
|
|
112
|
-
text = stripTagSectionCharacters(text);
|
|
113
|
-
const stripped = text.trim();
|
|
114
|
-
return !acceptsEmpty && value.trim().length > 0 && stripped.length === 0 ? value : stripped;
|
|
115
|
-
}
|
|
116
|
-
function byteSize(value) {
|
|
117
|
-
return encoder.encode(value).length;
|
|
208
|
+
return Buffer2.from(value.buffer, value.byteOffset, value.byteLength);
|
|
118
209
|
}
|
|
119
|
-
function
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
stripped = stripped.replace(TAG_PREFIX_REGEX, "");
|
|
125
|
-
stripped = stripped.replace(DANGLING_TAG_PREFIX_REGEX, "");
|
|
126
|
-
if (stripped === prev)
|
|
127
|
-
break;
|
|
128
|
-
}
|
|
129
|
-
return stripped;
|
|
210
|
+
function isSessionMetaRow(row) {
|
|
211
|
+
if (row === null || typeof row !== "object")
|
|
212
|
+
return false;
|
|
213
|
+
const r = row;
|
|
214
|
+
return typeof r.session_id === "string" && isNumberOrNull(r.last_response_time) && isStringOrNull(r.cache_ttl) && typeof r.counter === "number" && typeof r.last_nudge_tokens === "number" && isStringOrNull(r.last_nudge_band) && isStringOrNull(r.last_transform_error) && isNumberOrNull(r.is_subagent) && 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);
|
|
130
215
|
}
|
|
131
|
-
function
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
216
|
+
function getDefaultSessionMeta(sessionId) {
|
|
217
|
+
return {
|
|
218
|
+
sessionId,
|
|
219
|
+
lastResponseTime: 0,
|
|
220
|
+
cacheTtl: "5m",
|
|
221
|
+
counter: 0,
|
|
222
|
+
lastNudgeTokens: 0,
|
|
223
|
+
lastNudgeBand: null,
|
|
224
|
+
lastTransformError: null,
|
|
225
|
+
isSubagent: false,
|
|
226
|
+
lastContextPercentage: 0,
|
|
227
|
+
lastInputTokens: 0,
|
|
228
|
+
observedSafeInputTokens: 0,
|
|
229
|
+
cacheAlertSent: false,
|
|
230
|
+
timesExecuteThresholdReached: 0,
|
|
231
|
+
compartmentInProgress: false,
|
|
232
|
+
systemPromptHash: "",
|
|
233
|
+
systemPromptTokens: 0,
|
|
234
|
+
conversationTokens: 0,
|
|
235
|
+
toolCallTokens: 0,
|
|
236
|
+
clearedReasoningThroughTag: 0,
|
|
237
|
+
toolReclaimWatermark: 0,
|
|
238
|
+
lastTodoState: "",
|
|
239
|
+
cachedM0Bytes: null,
|
|
240
|
+
cachedM0MuralDataUrl: null,
|
|
241
|
+
cachedM0MuralHash: null,
|
|
242
|
+
cachedM1Bytes: null,
|
|
243
|
+
cachedM0TrimBoundaryId: null,
|
|
244
|
+
cachedM0TrimBoundaryPartial: false,
|
|
245
|
+
cachedM0ProjectMemoryEpoch: null,
|
|
246
|
+
cachedM0WorkspaceFingerprint: null,
|
|
247
|
+
cachedM0ProjectUserProfileVersion: null,
|
|
248
|
+
cachedM0MaxCompartmentSeq: null,
|
|
249
|
+
cachedM0MaxMemoryId: null,
|
|
250
|
+
cachedM0MaxMutationId: null,
|
|
251
|
+
cachedM0MaxMemoryMutationId: null,
|
|
252
|
+
cachedM0ProjectDocsHash: null,
|
|
253
|
+
cachedM0MaterializedAt: null,
|
|
254
|
+
cachedM0SessionFactsVersion: null,
|
|
255
|
+
cachedM0UpgradeState: null,
|
|
256
|
+
cachedM0SystemHash: null,
|
|
257
|
+
cachedM0ToolSetHash: null,
|
|
258
|
+
cachedM0ModelKey: null,
|
|
259
|
+
cachedM0ProjectIdentity: null,
|
|
260
|
+
lastObservedModelKey: null,
|
|
261
|
+
lastUsageContextLimit: 0,
|
|
262
|
+
priorBoundaryOrdinal: 1,
|
|
263
|
+
protectedTailPolicyVersion: 0,
|
|
264
|
+
protectedTailDrainWindowStartedAt: 0,
|
|
265
|
+
protectedTailDrainTokens: 0,
|
|
266
|
+
recoveryNoEligibleHeadCount: 0,
|
|
267
|
+
forceEmergencyBypassWindowStart: 0,
|
|
268
|
+
forceEmergencyBypassUsed: 0,
|
|
269
|
+
upgradeRemindedAt: null,
|
|
270
|
+
upgradeReminderLastSentAt: null,
|
|
271
|
+
upgradeReminderCount: 0,
|
|
272
|
+
piStableIdScheme: null
|
|
273
|
+
};
|
|
136
274
|
}
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
275
|
+
var sessionMetaExistsStatements = new WeakMap;
|
|
276
|
+
function ensureSessionMetaRow(db, sessionId, initialIsSubagent = getHarness2() === "opencode2" ? null : false) {
|
|
277
|
+
let exists = sessionMetaExistsStatements.get(db);
|
|
278
|
+
if (!exists) {
|
|
279
|
+
exists = prepareCachedStatement2(db, "SELECT 1 FROM session_meta WHERE session_id = ?");
|
|
280
|
+
sessionMetaExistsStatements.set(db, exists);
|
|
281
|
+
}
|
|
282
|
+
if (exists.get(sessionId))
|
|
283
|
+
return;
|
|
284
|
+
const defaults = getDefaultSessionMeta(sessionId);
|
|
285
|
+
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, getHarness2(), defaults.lastResponseTime, defaults.cacheTtl, defaults.counter, defaults.lastNudgeTokens, defaults.lastNudgeBand ?? "", defaults.lastTransformError ?? "", initialIsSubagent === null ? null : initialIsSubagent ? 1 : 0, defaults.lastContextPercentage, defaults.lastInputTokens, defaults.observedSafeInputTokens, defaults.cacheAlertSent ? 1 : 0, defaults.timesExecuteThresholdReached, defaults.compartmentInProgress ? 1 : 0, defaults.systemPromptHash ?? "", defaults.clearedReasoningThroughTag);
|
|
140
286
|
}
|
|
141
|
-
function
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
const
|
|
145
|
-
|
|
287
|
+
function toSessionMeta(row) {
|
|
288
|
+
const nudgeBandRaw = typeof row.last_nudge_band === "string" ? row.last_nudge_band : "";
|
|
289
|
+
const transformErrorRaw = typeof row.last_transform_error === "string" ? row.last_transform_error : "";
|
|
290
|
+
const cacheTtlRaw = typeof row.cache_ttl === "string" && row.cache_ttl.length > 0 ? row.cache_ttl : "5m";
|
|
291
|
+
const systemPromptHashRaw = row.system_prompt_hash == null ? "" : row.system_prompt_hash;
|
|
292
|
+
const lastTodoStateRaw = typeof row.last_todo_state === "string" ? row.last_todo_state : "";
|
|
293
|
+
const numOrZero = (value) => typeof value === "number" ? value : 0;
|
|
294
|
+
const numOrNull = (value) => typeof value === "number" ? value : null;
|
|
295
|
+
const stringOrNull = (value) => typeof value === "string" ? value : null;
|
|
296
|
+
return {
|
|
297
|
+
sessionId: row.session_id,
|
|
298
|
+
lastResponseTime: numOrZero(row.last_response_time),
|
|
299
|
+
cacheTtl: cacheTtlRaw,
|
|
300
|
+
counter: row.counter,
|
|
301
|
+
lastNudgeTokens: row.last_nudge_tokens,
|
|
302
|
+
lastNudgeBand: nudgeBandRaw.length > 0 ? nudgeBandRaw : null,
|
|
303
|
+
lastTransformError: transformErrorRaw.length > 0 ? transformErrorRaw : null,
|
|
304
|
+
isSubagent: row.is_subagent === 1,
|
|
305
|
+
lastContextPercentage: row.last_context_percentage,
|
|
306
|
+
lastInputTokens: row.last_input_tokens,
|
|
307
|
+
observedSafeInputTokens: numOrZero(row.observed_safe_input_tokens),
|
|
308
|
+
cacheAlertSent: numOrZero(row.cache_alert_sent) === 1,
|
|
309
|
+
timesExecuteThresholdReached: numOrZero(row.times_execute_threshold_reached),
|
|
310
|
+
compartmentInProgress: row.compartment_in_progress === 1,
|
|
311
|
+
systemPromptHash: String(systemPromptHashRaw),
|
|
312
|
+
systemPromptTokens: numOrZero(row.system_prompt_tokens),
|
|
313
|
+
conversationTokens: numOrZero(row.conversation_tokens),
|
|
314
|
+
toolCallTokens: numOrZero(row.tool_call_tokens),
|
|
315
|
+
clearedReasoningThroughTag: numOrZero(row.cleared_reasoning_through_tag),
|
|
316
|
+
toolReclaimWatermark: numOrZero(row.tool_reclaim_watermark),
|
|
317
|
+
lastTodoState: lastTodoStateRaw,
|
|
318
|
+
cachedM0Bytes: toBufferOrNull(row.cached_m0_bytes),
|
|
319
|
+
cachedM0MuralDataUrl: stringOrNull(row.cached_m0_mural_data_url),
|
|
320
|
+
cachedM0MuralHash: stringOrNull(row.cached_m0_mural_hash),
|
|
321
|
+
cachedM1Bytes: toBufferOrNull(row.cached_m1_bytes),
|
|
322
|
+
cachedM0TrimBoundaryId: row.cached_m0_last_baseline_end_message_id || null,
|
|
323
|
+
cachedM0TrimBoundaryPartial: row.cached_trim_partial === 1,
|
|
324
|
+
cachedM0ProjectMemoryEpoch: numOrNull(row.cached_m0_project_memory_epoch),
|
|
325
|
+
cachedM0WorkspaceFingerprint: stringOrNull(row.cached_m0_workspace_fingerprint),
|
|
326
|
+
cachedM0ProjectUserProfileVersion: numOrNull(row.cached_m0_project_user_profile_version),
|
|
327
|
+
cachedM0MaxCompartmentSeq: numOrNull(row.cached_m0_max_compartment_seq),
|
|
328
|
+
cachedM0MaxMemoryId: numOrNull(row.cached_m0_max_memory_id),
|
|
329
|
+
cachedM0MaxMutationId: numOrNull(row.cached_m0_max_mutation_id),
|
|
330
|
+
cachedM0MaxMemoryMutationId: numOrNull(row.cached_m0_max_memory_mutation_id),
|
|
331
|
+
cachedM0ProjectDocsHash: stringOrNull(row.cached_m0_project_docs_hash),
|
|
332
|
+
cachedM0MaterializedAt: numOrNull(row.cached_m0_materialized_at),
|
|
333
|
+
cachedM0SessionFactsVersion: numOrNull(row.cached_m0_session_facts_version),
|
|
334
|
+
cachedM0UpgradeState: stringOrNull(row.cached_m0_upgrade_state),
|
|
335
|
+
cachedM0SystemHash: stringOrNull(row.cached_m0_system_hash),
|
|
336
|
+
cachedM0ToolSetHash: stringOrNull(row.cached_m0_tool_set_hash),
|
|
337
|
+
cachedM0ModelKey: stringOrNull(row.cached_m0_model_key),
|
|
338
|
+
cachedM0ProjectIdentity: stringOrNull(row.cached_m0_project_identity),
|
|
339
|
+
lastObservedModelKey: stringOrNull(row.last_observed_model_key),
|
|
340
|
+
lastUsageContextLimit: numOrZero(row.last_usage_context_limit),
|
|
341
|
+
priorBoundaryOrdinal: Math.max(1, numOrZero(row.prior_boundary_ordinal) || 1),
|
|
342
|
+
protectedTailPolicyVersion: numOrZero(row.protected_tail_policy_version),
|
|
343
|
+
protectedTailDrainWindowStartedAt: numOrZero(row.protected_tail_drain_window_started_at),
|
|
344
|
+
protectedTailDrainTokens: numOrZero(row.protected_tail_drain_tokens),
|
|
345
|
+
recoveryNoEligibleHeadCount: numOrZero(row.recovery_no_eligible_head_count),
|
|
346
|
+
forceEmergencyBypassWindowStart: numOrZero(row.force_emergency_bypass_window_start),
|
|
347
|
+
forceEmergencyBypassUsed: numOrZero(row.force_emergency_bypass_used),
|
|
348
|
+
upgradeRemindedAt: numOrNull(row.upgrade_reminded_at),
|
|
349
|
+
upgradeReminderLastSentAt: numOrNull(row.upgrade_reminder_last_sent_at),
|
|
350
|
+
upgradeReminderCount: numOrZero(row.upgrade_reminder_count),
|
|
351
|
+
piStableIdScheme: numOrNull(row.pi_stable_id_scheme)
|
|
352
|
+
};
|
|
146
353
|
}
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
354
|
+
function persistCachedM0(db, sessionId, payload) {
|
|
355
|
+
ensureSessionMetaRow(db, sessionId);
|
|
356
|
+
db.prepare(`UPDATE session_meta SET
|
|
357
|
+
cached_m0_bytes = ?,
|
|
358
|
+
cached_m0_mural_data_url = ?,
|
|
359
|
+
cached_m0_mural_hash = ?,
|
|
360
|
+
cached_m0_project_memory_epoch = ?,
|
|
361
|
+
cached_m0_workspace_fingerprint = ?,
|
|
362
|
+
cached_m0_project_user_profile_version = ?,
|
|
363
|
+
cached_m0_max_compartment_seq = ?,
|
|
364
|
+
cached_m0_max_memory_id = ?,
|
|
365
|
+
cached_m0_max_mutation_id = ?,
|
|
366
|
+
cached_m0_max_memory_mutation_id = ?,
|
|
367
|
+
cached_m1_bytes = ?,
|
|
368
|
+
cached_m0_project_docs_hash = ?,
|
|
369
|
+
cached_m0_materialized_at = ?,
|
|
370
|
+
cached_m0_session_facts_version = ?,
|
|
371
|
+
cached_m0_upgrade_state = ?,
|
|
372
|
+
cached_m0_system_hash = ?,
|
|
373
|
+
cached_m0_tool_set_hash = ?,
|
|
374
|
+
cached_m0_model_key = ?,
|
|
375
|
+
cached_m0_project_identity = ?
|
|
376
|
+
WHERE session_id = ?`).run(Buffer2.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 ? Buffer2.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);
|
|
152
377
|
}
|
|
153
|
-
function
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
378
|
+
function clearCachedM0M1(db, sessionId) {
|
|
379
|
+
ensureSessionMetaRow(db, sessionId);
|
|
380
|
+
const existingColumns = new Set(db.prepare("PRAGMA table_info(session_meta)").all().map((column) => column.name));
|
|
381
|
+
const clears = [
|
|
382
|
+
["cached_m0_bytes", null],
|
|
383
|
+
["cached_m0_mural_data_url", null],
|
|
384
|
+
["cached_m0_mural_hash", null],
|
|
385
|
+
["cached_m1_bytes", null],
|
|
386
|
+
["cached_m0_project_memory_epoch", null],
|
|
387
|
+
["cached_m0_workspace_fingerprint", null],
|
|
388
|
+
["cached_m0_project_user_profile_version", null],
|
|
389
|
+
["cached_m0_max_compartment_seq", null],
|
|
390
|
+
["cached_m0_max_memory_id", null],
|
|
391
|
+
["cached_m0_max_mutation_id", null],
|
|
392
|
+
["cached_m0_max_memory_mutation_id", null],
|
|
393
|
+
["cached_m0_project_docs_hash", null],
|
|
394
|
+
["cached_m0_materialized_at", null],
|
|
395
|
+
["cached_m0_session_facts_version", null],
|
|
396
|
+
["cached_m0_upgrade_state", null],
|
|
397
|
+
["cached_m0_system_hash", null],
|
|
398
|
+
["cached_m0_tool_set_hash", null],
|
|
399
|
+
["cached_m0_model_key", null],
|
|
400
|
+
["cached_m0_project_identity", null],
|
|
401
|
+
["cached_m0_last_baseline_end_message_id", null],
|
|
402
|
+
["memory_block_cache", ""],
|
|
403
|
+
["memory_block_count", 0],
|
|
404
|
+
["memory_block_ids", ""]
|
|
405
|
+
];
|
|
406
|
+
const setClauses = [];
|
|
407
|
+
const values = [];
|
|
408
|
+
for (const [column, value] of clears) {
|
|
409
|
+
if (!existingColumns.has(column))
|
|
410
|
+
continue;
|
|
411
|
+
setClauses.push(`${column} = ?`);
|
|
412
|
+
values.push(value);
|
|
413
|
+
}
|
|
414
|
+
if (setClauses.length === 0)
|
|
415
|
+
return;
|
|
416
|
+
db.prepare(`UPDATE session_meta SET ${setClauses.join(", ")} WHERE session_id = ?`).run(...values, sessionId);
|
|
157
417
|
}
|
|
158
|
-
function
|
|
159
|
-
|
|
160
|
-
return 0;
|
|
161
|
-
return baseline[CURRENT_OUTPUT_COUNT];
|
|
418
|
+
function clearCachedM0(db, sessionId) {
|
|
419
|
+
clearCachedM0M1(db, sessionId);
|
|
162
420
|
}
|
|
163
421
|
|
|
164
|
-
// src/
|
|
165
|
-
|
|
166
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
167
|
-
}
|
|
422
|
+
// src/features/magic-context/storage-tags.ts
|
|
423
|
+
import { isMainThread } from "node:worker_threads";
|
|
168
424
|
|
|
169
|
-
// src/
|
|
170
|
-
var
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
const positional = POSITIONAL_CONTENT_SUFFIX.exec(contentId);
|
|
176
|
-
if (positional)
|
|
177
|
-
return contentId.slice(0, positional.index);
|
|
178
|
-
const derived = CONTENT_DERIVED_TEXT_SUFFIX.exec(contentId);
|
|
179
|
-
if (derived)
|
|
180
|
-
return contentId.slice(0, derived.index);
|
|
181
|
-
return contentId;
|
|
425
|
+
// src/features/magic-context/reclaim-protection.ts
|
|
426
|
+
var CTX_REDUCE_KEEP = DEFAULT_PROTECTED_TOOLS.ctx_reduce;
|
|
427
|
+
function adoptedProtectedToolsPolicy(current, previous, rebuilding, hasBaseline) {
|
|
428
|
+
if (rebuilding || !hasBaseline)
|
|
429
|
+
return mergeProtectedTools(current);
|
|
430
|
+
return { ...previous ?? { todowrite: 0, ctx_reduce: 3 } };
|
|
182
431
|
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
432
|
+
function protectedToolTagNumbers(tags, protectedTools) {
|
|
433
|
+
const counts = mergeProtectedTools(protectedTools);
|
|
434
|
+
const protectedTags = new Set;
|
|
435
|
+
for (const tag of [...tags].sort((left, right) => right.tagNumber - left.tagNumber)) {
|
|
436
|
+
if (tag.status !== undefined && tag.status !== "active")
|
|
437
|
+
continue;
|
|
438
|
+
if (tag.type !== undefined && tag.type !== "tool")
|
|
439
|
+
continue;
|
|
440
|
+
const name = normalizeProtectedToolName(tag.toolName);
|
|
441
|
+
if (!Object.hasOwn(counts, name) || counts[name] <= 0)
|
|
442
|
+
continue;
|
|
443
|
+
protectedTags.add(tag.tagNumber);
|
|
444
|
+
counts[name] -= 1;
|
|
445
|
+
}
|
|
446
|
+
return protectedTags;
|
|
447
|
+
}
|
|
448
|
+
function protectedToolTokenCount(tags, counts, calibration) {
|
|
449
|
+
const protectedTags = protectedToolTagNumbers(tags, counts);
|
|
450
|
+
const tokens = tags.reduce((sum, tag) => sum + (protectedTags.has(tag.tagNumber) ? tag.tokenCount ?? 0 : 0), 0);
|
|
451
|
+
return calibration && hasMeasuredDecisionCalibration(calibration) ? providerMass({ tools: tokens }, calibration) : 0;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// src/hooks/magic-context/tag-content-primitives.ts
|
|
455
|
+
var encoder = new TextEncoder;
|
|
456
|
+
var TAG_PREFIX_REGEX = /^(?:§\d+§\s*)+/;
|
|
457
|
+
var MALFORMED_TAG_PREFIX_REGEX = /^(?:§\d+">§(?:\d+§)?\s*)+/;
|
|
458
|
+
var DANGLING_TAG_GLOBAL_REGEX = /\u00a7\d+(?!\d)(?!\.\d)[^\s\u00a7\w.]?/g;
|
|
459
|
+
var DANGLING_TAG_PREFIX_REGEX = /^(?:\u00a7\d+(?!\d)(?!\.\d)[^\s\u00a7\w.]?\s*)+/;
|
|
460
|
+
var COMPLETE_TAG_PAIR_GLOBAL_REGEX = /\u00a7\d+\u00a7/g;
|
|
461
|
+
var MALFORMED_TAG_GLOBAL_REGEX = /\u00a7\d+">(?:\u00a7(?:\d+\u00a7)?)?/g;
|
|
462
|
+
var STRAY_SECTION_CHAR_REGEX = /\u00a7/g;
|
|
463
|
+
function stripWellFormedLeadingTagPrefix(value) {
|
|
464
|
+
return value.replace(/^(\u00a7\d+\u00a7\s*)+/, "");
|
|
465
|
+
}
|
|
466
|
+
function stripCompleteTagPairsGlobally(value) {
|
|
467
|
+
return value.replace(COMPLETE_TAG_PAIR_GLOBAL_REGEX, "");
|
|
468
|
+
}
|
|
469
|
+
function stripMalformedTagNotationGlobally(value) {
|
|
470
|
+
return value.replace(MALFORMED_TAG_GLOBAL_REGEX, "");
|
|
471
|
+
}
|
|
472
|
+
function stripDanglingTagNotationGlobally(value) {
|
|
473
|
+
return value.replace(DANGLING_TAG_GLOBAL_REGEX, "");
|
|
474
|
+
}
|
|
475
|
+
function stripTagSectionCharacters(value) {
|
|
476
|
+
return value.replace(STRAY_SECTION_CHAR_REGEX, "");
|
|
477
|
+
}
|
|
478
|
+
function stripPersistedAssistantText(value, acceptsEmpty = true) {
|
|
479
|
+
if (!acceptsEmpty && !value.includes("§") && !value.trim())
|
|
480
|
+
return value;
|
|
481
|
+
let text = stripWellFormedLeadingTagPrefix(value);
|
|
482
|
+
text = stripCompleteTagPairsGlobally(text);
|
|
483
|
+
text = stripMalformedTagNotationGlobally(text);
|
|
484
|
+
text = stripDanglingTagNotationGlobally(text);
|
|
485
|
+
text = stripTagSectionCharacters(text);
|
|
486
|
+
const stripped = text.trim();
|
|
487
|
+
return !acceptsEmpty && value.trim().length > 0 && stripped.length === 0 ? value : stripped;
|
|
488
|
+
}
|
|
489
|
+
function byteSize(value) {
|
|
490
|
+
return encoder.encode(value).length;
|
|
491
|
+
}
|
|
492
|
+
function stripTagPrefix(value) {
|
|
493
|
+
let stripped = value;
|
|
494
|
+
for (let pass = 0;pass < 8; pass++) {
|
|
495
|
+
const prev = stripped;
|
|
496
|
+
stripped = stripped.replace(MALFORMED_TAG_PREFIX_REGEX, "");
|
|
497
|
+
stripped = stripped.replace(TAG_PREFIX_REGEX, "");
|
|
498
|
+
stripped = stripped.replace(DANGLING_TAG_PREFIX_REGEX, "");
|
|
499
|
+
if (stripped === prev)
|
|
500
|
+
break;
|
|
501
|
+
}
|
|
502
|
+
return stripped;
|
|
503
|
+
}
|
|
504
|
+
function peelLeadingMcTagNotation(value) {
|
|
505
|
+
const body = stripTagPrefix(value);
|
|
506
|
+
if (body === value)
|
|
507
|
+
return { tagPrefix: "", body };
|
|
508
|
+
return { tagPrefix: value.slice(0, value.length - body.length), body };
|
|
509
|
+
}
|
|
510
|
+
function prependTag(tagId, value) {
|
|
511
|
+
const stripped = stripTagPrefix(value);
|
|
512
|
+
return `§${tagId}§ ${stripped}`;
|
|
513
|
+
}
|
|
514
|
+
function isThinkingPart(part) {
|
|
515
|
+
if (part === null || typeof part !== "object")
|
|
516
|
+
return false;
|
|
517
|
+
const candidate = part;
|
|
518
|
+
return candidate.type === "thinking" || candidate.type === "reasoning";
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// src/hooks/magic-context/tail-hygiene-output-count.ts
|
|
522
|
+
var CURRENT_OUTPUT_COUNT = Symbol.for("magic-context.current-reclaimable-tool-output-count");
|
|
523
|
+
function countReclaimableToolOutputs(parts) {
|
|
524
|
+
return parts.filter((part) => part.kind === "toolOutput" && part.uTokens > 0).length;
|
|
525
|
+
}
|
|
526
|
+
function rememberCurrentToolOutputCount(baseline, measurement) {
|
|
527
|
+
return Object.assign(baseline, {
|
|
528
|
+
[CURRENT_OUTPUT_COUNT]: countReclaimableToolOutputs(measurement.parts)
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
function currentReclaimableToolOutputCount(baseline) {
|
|
532
|
+
if (!baseline || !Object.hasOwn(baseline, CURRENT_OUTPUT_COUNT))
|
|
533
|
+
return 0;
|
|
534
|
+
return baseline[CURRENT_OUTPUT_COUNT];
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// src/shared/record-type-guard.ts
|
|
538
|
+
function isRecord(value) {
|
|
539
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// src/shared/tag-owner-id.ts
|
|
543
|
+
var TEXT_TAG_IDENTITY_MARKER = ":mc-text-v1:";
|
|
544
|
+
var PI_FALLBACK_PREFIXES_JSON = JSON.stringify([..."pi-msg-"].reduce((prefixes, char) => prefixes.flatMap((prefix) => /[a-z]/.test(char) ? [prefix + char, prefix + char.toUpperCase()] : [prefix + char]), [""]));
|
|
545
|
+
var POSITIONAL_CONTENT_SUFFIX = /:(?:p|file)\d+$/;
|
|
546
|
+
var CONTENT_DERIVED_TEXT_SUFFIX = /:mc-text-v1:[0-9a-f]+:[0-9a-f]+:o\d+$/;
|
|
547
|
+
function contentTagOwnerMessageId(contentId) {
|
|
548
|
+
const positional = POSITIONAL_CONTENT_SUFFIX.exec(contentId);
|
|
549
|
+
if (positional)
|
|
550
|
+
return contentId.slice(0, positional.index);
|
|
551
|
+
const derived = CONTENT_DERIVED_TEXT_SUFFIX.exec(contentId);
|
|
552
|
+
if (derived)
|
|
553
|
+
return contentId.slice(0, derived.index);
|
|
554
|
+
return contentId;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
// src/shared/tail-hygiene-json.ts
|
|
558
|
+
var MAX_MEMO_BYTES = 64 * 1024 * 1024;
|
|
559
|
+
var MAX_MEMO_ENTRIES = 1e4;
|
|
560
|
+
|
|
561
|
+
class TailHygieneJsonMemo {
|
|
562
|
+
entries = new Map;
|
|
563
|
+
bytes = 0;
|
|
564
|
+
passText = new WeakMap;
|
|
192
565
|
passHash = new WeakMap;
|
|
193
566
|
beginPass() {
|
|
194
567
|
this.passText = new WeakMap;
|
|
@@ -2366,501 +2739,128 @@ function computeProtectionWindow(rows, floor, toolsRatio = 1) {
|
|
|
2366
2739
|
coordinateSpace: "row-identity",
|
|
2367
2740
|
rowIdentities: new Set
|
|
2368
2741
|
},
|
|
2369
|
-
ordinalCutoff: { coordinateSpace: "tag-number", cutoff: null },
|
|
2370
|
-
cutoff: null,
|
|
2371
|
-
protectedTagNumbers: new Set,
|
|
2372
|
-
protectedRowIdentities: new Set,
|
|
2373
|
-
status: {
|
|
2374
|
-
floor,
|
|
2375
|
-
protectedCount: 0,
|
|
2376
|
-
protectedMass: 0
|
|
2377
|
-
},
|
|
2378
|
-
isProtected: () => false
|
|
2379
|
-
};
|
|
2380
|
-
}
|
|
2381
|
-
const sortedAsc = [...toolRows].sort(compareRowsAscending);
|
|
2382
|
-
const tieGroupsDescending = [];
|
|
2383
|
-
let currentGroup = [];
|
|
2384
|
-
let currentTagNumber = null;
|
|
2385
|
-
for (let i = sortedAsc.length - 1;i >= 0; i--) {
|
|
2386
|
-
const row = sortedAsc[i];
|
|
2387
|
-
const tagNum = getRowTagNumber(row);
|
|
2388
|
-
if (currentTagNumber === null || tagNum === currentTagNumber) {
|
|
2389
|
-
currentGroup.push(row);
|
|
2390
|
-
currentTagNumber = tagNum;
|
|
2391
|
-
} else {
|
|
2392
|
-
tieGroupsDescending.push(currentGroup);
|
|
2393
|
-
currentGroup = [row];
|
|
2394
|
-
currentTagNumber = tagNum;
|
|
2395
|
-
}
|
|
2396
|
-
}
|
|
2397
|
-
if (currentGroup.length > 0) {
|
|
2398
|
-
tieGroupsDescending.push(currentGroup);
|
|
2399
|
-
}
|
|
2400
|
-
const massWindowRows = [];
|
|
2401
|
-
let cumulativeMass = 0;
|
|
2402
|
-
for (const group of tieGroupsDescending) {
|
|
2403
|
-
for (const row of group) {
|
|
2404
|
-
massWindowRows.push(row);
|
|
2405
|
-
cumulativeMass += rowWindowMass(row);
|
|
2406
|
-
}
|
|
2407
|
-
if (Math.ceil(cumulativeMass * toolsRatio) >= floor) {
|
|
2408
|
-
break;
|
|
2409
|
-
}
|
|
2410
|
-
}
|
|
2411
|
-
const mass_cutoff = massWindowRows.length > 0 ? getRowTagNumber(massWindowRows[massWindowRows.length - 1]) : null;
|
|
2412
|
-
const distinctToolTagNumbers = tieGroupsDescending.map((g) => getRowTagNumber(g[0]));
|
|
2413
|
-
const minCount = Math.min(3, distinctToolTagNumbers.length);
|
|
2414
|
-
const newest3_cutoff = minCount > 0 ? distinctToolTagNumbers[minCount - 1] : null;
|
|
2415
|
-
const cutoff = mass_cutoff !== null && newest3_cutoff !== null ? Math.min(mass_cutoff, newest3_cutoff) : mass_cutoff ?? newest3_cutoff;
|
|
2416
|
-
const memberRows = cutoff !== null ? sortedAsc.filter((row) => getRowTagNumber(row) >= cutoff) : [];
|
|
2417
|
-
const memberRowKeys = new Set(memberRows.map(rowKey));
|
|
2418
|
-
const protectedTagNumbers = new Set(memberRows.map(getRowTagNumber));
|
|
2419
|
-
const protectedRowIdentities = new Set(memberRows.map(getRowIdentity));
|
|
2420
|
-
const protectedCount = memberRows.length;
|
|
2421
|
-
const protectedMass = Math.ceil(memberRows.reduce((sum, row) => sum + rowWindowMass(row), 0) * toolsRatio);
|
|
2422
|
-
const isProtected = (row) => {
|
|
2423
|
-
return getRowKind(row) === "tool" && cutoff !== null && getRowTagNumber(row) >= cutoff;
|
|
2424
|
-
};
|
|
2425
|
-
return {
|
|
2426
|
-
memberRows,
|
|
2427
|
-
memberRowKeys,
|
|
2428
|
-
tagNumberSet: {
|
|
2429
|
-
coordinateSpace: "tag-number",
|
|
2430
|
-
tagNumbers: protectedTagNumbers
|
|
2431
|
-
},
|
|
2432
|
-
rowIdentitySet: {
|
|
2433
|
-
coordinateSpace: "row-identity",
|
|
2434
|
-
rowIdentities: protectedRowIdentities
|
|
2435
|
-
},
|
|
2436
|
-
ordinalCutoff: {
|
|
2437
|
-
coordinateSpace: "tag-number",
|
|
2438
|
-
cutoff
|
|
2439
|
-
},
|
|
2440
|
-
cutoff,
|
|
2441
|
-
protectedTagNumbers,
|
|
2442
|
-
protectedRowIdentities,
|
|
2443
|
-
status: {
|
|
2444
|
-
floor,
|
|
2445
|
-
protectedCount,
|
|
2446
|
-
protectedMass
|
|
2447
|
-
},
|
|
2448
|
-
isProtected
|
|
2449
|
-
};
|
|
2450
|
-
}
|
|
2451
|
-
function readEpochFloorSnapshot(db, sessionId) {
|
|
2452
|
-
try {
|
|
2453
|
-
const row = db.prepare("SELECT protected_tokens_effective FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
2454
|
-
if (row && typeof row.protected_tokens_effective === "number" && Number.isFinite(row.protected_tokens_effective)) {
|
|
2455
|
-
return row.protected_tokens_effective;
|
|
2456
|
-
}
|
|
2457
|
-
} catch {}
|
|
2458
|
-
return null;
|
|
2459
|
-
}
|
|
2460
|
-
function getProtectionWindowForSession(db, sessionId, floor) {
|
|
2461
|
-
const effectiveFloor = typeof floor === "number" && Number.isFinite(floor) ? floor : readEpochFloorSnapshot(db, sessionId) ?? 0;
|
|
2462
|
-
const toolsRatio = sessionDecisionCalibration(db, sessionId).toolsRatio;
|
|
2463
|
-
const pageSize = 256;
|
|
2464
|
-
const projection = `SELECT ${TAG_SELECT_COLUMNS2} FROM tags
|
|
2465
|
-
WHERE session_id = ? AND +type = 'tool'`;
|
|
2466
|
-
const order = `ORDER BY tag_number DESC, id DESC LIMIT ${pageSize}`;
|
|
2467
|
-
let page = db.prepare(`${projection} ${order}`).all(sessionId);
|
|
2468
|
-
const rows = [];
|
|
2469
|
-
let mass = 0;
|
|
2470
|
-
let distinctTags = 0;
|
|
2471
|
-
let currentTag = null;
|
|
2472
|
-
while (page.length > 0) {
|
|
2473
|
-
for (const row of page) {
|
|
2474
|
-
const tagNumber = getRowTagNumber(row);
|
|
2475
|
-
if (tagNumber !== currentTag) {
|
|
2476
|
-
if (distinctTags >= 3 && Math.ceil(mass * toolsRatio) >= effectiveFloor) {
|
|
2477
|
-
return computeProtectionWindow(rows, effectiveFloor, toolsRatio);
|
|
2478
|
-
}
|
|
2479
|
-
distinctTags++;
|
|
2480
|
-
currentTag = tagNumber;
|
|
2481
|
-
}
|
|
2482
|
-
rows.push(row);
|
|
2483
|
-
mass += rowWindowMass(row);
|
|
2484
|
-
}
|
|
2485
|
-
if (page.length < pageSize)
|
|
2486
|
-
break;
|
|
2487
|
-
const last = page[page.length - 1];
|
|
2488
|
-
page = db.prepare(`${projection} AND (tag_number, id) < (?, ?) ${order}`).all(sessionId, getRowTagNumber(last), getRowIdentity(last));
|
|
2489
|
-
}
|
|
2490
|
-
return computeProtectionWindow(rows, effectiveFloor, toolsRatio);
|
|
2491
|
-
}
|
|
2492
|
-
|
|
2493
|
-
// src/features/magic-context/storage-meta-shared.ts
|
|
2494
|
-
import { Buffer as Buffer2 } from "node:buffer";
|
|
2495
|
-
var CACHED_TRIM_PARTIAL_SQL = `EXISTS (
|
|
2496
|
-
SELECT 1 FROM compartments
|
|
2497
|
-
WHERE compartments.session_id = session_meta.session_id
|
|
2498
|
-
AND compartments.end_message_id = session_meta.cached_m0_last_baseline_end_message_id
|
|
2499
|
-
AND compartments.end_block_index IS NOT NULL
|
|
2500
|
-
)`;
|
|
2501
|
-
var SESSION_META_SELECT_COLUMNS = [
|
|
2502
|
-
"session_id",
|
|
2503
|
-
"last_response_time",
|
|
2504
|
-
"cache_ttl",
|
|
2505
|
-
"counter",
|
|
2506
|
-
"last_nudge_tokens",
|
|
2507
|
-
"last_nudge_band",
|
|
2508
|
-
"last_transform_error",
|
|
2509
|
-
"is_subagent",
|
|
2510
|
-
"last_context_percentage",
|
|
2511
|
-
"last_input_tokens",
|
|
2512
|
-
"observed_safe_input_tokens",
|
|
2513
|
-
"cache_alert_sent",
|
|
2514
|
-
"times_execute_threshold_reached",
|
|
2515
|
-
"compartment_in_progress",
|
|
2516
|
-
"system_prompt_hash",
|
|
2517
|
-
"system_prompt_tokens",
|
|
2518
|
-
"conversation_tokens",
|
|
2519
|
-
"tool_call_tokens",
|
|
2520
|
-
"cleared_reasoning_through_tag",
|
|
2521
|
-
"tool_reclaim_watermark",
|
|
2522
|
-
"last_todo_state",
|
|
2523
|
-
"cached_m0_bytes",
|
|
2524
|
-
"cached_m0_mural_data_url",
|
|
2525
|
-
"cached_m0_mural_hash",
|
|
2526
|
-
"cached_m1_bytes",
|
|
2527
|
-
"cached_m0_last_baseline_end_message_id",
|
|
2528
|
-
"cached_m0_project_memory_epoch",
|
|
2529
|
-
"cached_m0_workspace_fingerprint",
|
|
2530
|
-
"cached_m0_project_user_profile_version",
|
|
2531
|
-
"cached_m0_max_compartment_seq",
|
|
2532
|
-
"cached_m0_max_memory_id",
|
|
2533
|
-
"cached_m0_max_mutation_id",
|
|
2534
|
-
"cached_m0_max_memory_mutation_id",
|
|
2535
|
-
"cached_m0_project_docs_hash",
|
|
2536
|
-
"cached_m0_materialized_at",
|
|
2537
|
-
"cached_m0_session_facts_version",
|
|
2538
|
-
"cached_m0_upgrade_state",
|
|
2539
|
-
"cached_m0_system_hash",
|
|
2540
|
-
"cached_m0_tool_set_hash",
|
|
2541
|
-
"cached_m0_model_key",
|
|
2542
|
-
"cached_m0_project_identity",
|
|
2543
|
-
"last_observed_model_key",
|
|
2544
|
-
"last_usage_context_limit",
|
|
2545
|
-
"prior_boundary_ordinal",
|
|
2546
|
-
"protected_tail_policy_version",
|
|
2547
|
-
"protected_tail_drain_window_started_at",
|
|
2548
|
-
"protected_tail_drain_tokens",
|
|
2549
|
-
"recovery_no_eligible_head_count",
|
|
2550
|
-
"force_emergency_bypass_window_start",
|
|
2551
|
-
"force_emergency_bypass_used",
|
|
2552
|
-
"emergency_drain_active",
|
|
2553
|
-
"historian_drain_failure_at",
|
|
2554
|
-
"upgrade_reminded_at",
|
|
2555
|
-
"upgrade_reminder_last_sent_at",
|
|
2556
|
-
"upgrade_reminder_count",
|
|
2557
|
-
"pi_stable_id_scheme"
|
|
2558
|
-
];
|
|
2559
|
-
var META_COLUMNS = {
|
|
2560
|
-
lastResponseTime: "last_response_time",
|
|
2561
|
-
cacheTtl: "cache_ttl",
|
|
2562
|
-
counter: "counter",
|
|
2563
|
-
lastNudgeTokens: "last_nudge_tokens",
|
|
2564
|
-
lastNudgeBand: "last_nudge_band",
|
|
2565
|
-
lastTransformError: "last_transform_error",
|
|
2566
|
-
isSubagent: "is_subagent",
|
|
2567
|
-
lastContextPercentage: "last_context_percentage",
|
|
2568
|
-
lastInputTokens: "last_input_tokens",
|
|
2569
|
-
observedSafeInputTokens: "observed_safe_input_tokens",
|
|
2570
|
-
cacheAlertSent: "cache_alert_sent",
|
|
2571
|
-
timesExecuteThresholdReached: "times_execute_threshold_reached",
|
|
2572
|
-
compartmentInProgress: "compartment_in_progress",
|
|
2573
|
-
systemPromptHash: "system_prompt_hash",
|
|
2574
|
-
systemPromptTokens: "system_prompt_tokens",
|
|
2575
|
-
conversationTokens: "conversation_tokens",
|
|
2576
|
-
toolCallTokens: "tool_call_tokens",
|
|
2577
|
-
clearedReasoningThroughTag: "cleared_reasoning_through_tag",
|
|
2578
|
-
toolReclaimWatermark: "tool_reclaim_watermark",
|
|
2579
|
-
lastTodoState: "last_todo_state",
|
|
2580
|
-
cachedM0Bytes: "cached_m0_bytes",
|
|
2581
|
-
cachedM0MuralDataUrl: "cached_m0_mural_data_url",
|
|
2582
|
-
cachedM0MuralHash: "cached_m0_mural_hash",
|
|
2583
|
-
cachedM1Bytes: "cached_m1_bytes",
|
|
2584
|
-
cachedM0ProjectMemoryEpoch: "cached_m0_project_memory_epoch",
|
|
2585
|
-
cachedM0WorkspaceFingerprint: "cached_m0_workspace_fingerprint",
|
|
2586
|
-
cachedM0ProjectUserProfileVersion: "cached_m0_project_user_profile_version",
|
|
2587
|
-
cachedM0MaxCompartmentSeq: "cached_m0_max_compartment_seq",
|
|
2588
|
-
cachedM0MaxMemoryId: "cached_m0_max_memory_id",
|
|
2589
|
-
cachedM0MaxMutationId: "cached_m0_max_mutation_id",
|
|
2590
|
-
cachedM0MaxMemoryMutationId: "cached_m0_max_memory_mutation_id",
|
|
2591
|
-
cachedM0ProjectDocsHash: "cached_m0_project_docs_hash",
|
|
2592
|
-
cachedM0MaterializedAt: "cached_m0_materialized_at",
|
|
2593
|
-
cachedM0SessionFactsVersion: "cached_m0_session_facts_version",
|
|
2594
|
-
cachedM0UpgradeState: "cached_m0_upgrade_state",
|
|
2595
|
-
cachedM0SystemHash: "cached_m0_system_hash",
|
|
2596
|
-
cachedM0ToolSetHash: "cached_m0_tool_set_hash",
|
|
2597
|
-
cachedM0ModelKey: "cached_m0_model_key",
|
|
2598
|
-
cachedM0ProjectIdentity: "cached_m0_project_identity",
|
|
2599
|
-
lastObservedModelKey: "last_observed_model_key",
|
|
2600
|
-
lastUsageContextLimit: "last_usage_context_limit",
|
|
2601
|
-
priorBoundaryOrdinal: "prior_boundary_ordinal",
|
|
2602
|
-
protectedTailPolicyVersion: "protected_tail_policy_version",
|
|
2603
|
-
protectedTailDrainWindowStartedAt: "protected_tail_drain_window_started_at",
|
|
2604
|
-
protectedTailDrainTokens: "protected_tail_drain_tokens",
|
|
2605
|
-
recoveryNoEligibleHeadCount: "recovery_no_eligible_head_count",
|
|
2606
|
-
forceEmergencyBypassWindowStart: "force_emergency_bypass_window_start",
|
|
2607
|
-
forceEmergencyBypassUsed: "force_emergency_bypass_used",
|
|
2608
|
-
emergencyDrainActive: "emergency_drain_active",
|
|
2609
|
-
historianDrainFailureAt: "historian_drain_failure_at",
|
|
2610
|
-
upgradeRemindedAt: "upgrade_reminded_at",
|
|
2611
|
-
upgradeReminderLastSentAt: "upgrade_reminder_last_sent_at",
|
|
2612
|
-
upgradeReminderCount: "upgrade_reminder_count",
|
|
2613
|
-
piStableIdScheme: "pi_stable_id_scheme"
|
|
2614
|
-
};
|
|
2615
|
-
var BOOLEAN_META_KEYS = new Set(["isSubagent", "compartmentInProgress", "cacheAlertSent"]);
|
|
2616
|
-
var NULL_BIND_META_KEYS = new Set([
|
|
2617
|
-
"cachedM0Bytes",
|
|
2618
|
-
"cachedM0MuralDataUrl",
|
|
2619
|
-
"cachedM0MuralHash",
|
|
2620
|
-
"cachedM1Bytes",
|
|
2621
|
-
"cachedM0ProjectMemoryEpoch",
|
|
2622
|
-
"cachedM0WorkspaceFingerprint",
|
|
2623
|
-
"cachedM0ProjectUserProfileVersion",
|
|
2624
|
-
"cachedM0MaxCompartmentSeq",
|
|
2625
|
-
"cachedM0MaxMemoryId",
|
|
2626
|
-
"cachedM0MaxMutationId",
|
|
2627
|
-
"cachedM0MaxMemoryMutationId",
|
|
2628
|
-
"cachedM0ProjectDocsHash",
|
|
2629
|
-
"cachedM0MaterializedAt",
|
|
2630
|
-
"cachedM0SessionFactsVersion",
|
|
2631
|
-
"cachedM0UpgradeState",
|
|
2632
|
-
"cachedM0ProjectIdentity",
|
|
2633
|
-
"lastObservedModelKey",
|
|
2634
|
-
"upgradeRemindedAt",
|
|
2635
|
-
"upgradeReminderLastSentAt",
|
|
2636
|
-
"piStableIdScheme"
|
|
2637
|
-
]);
|
|
2638
|
-
function isStringOrNull(value) {
|
|
2639
|
-
return value === null || typeof value === "string";
|
|
2640
|
-
}
|
|
2641
|
-
function isNumberOrNull(value) {
|
|
2642
|
-
return value === null || typeof value === "number";
|
|
2643
|
-
}
|
|
2644
|
-
function isBlobOrNull(value) {
|
|
2645
|
-
return value === null || Buffer2.isBuffer(value) || value instanceof Uint8Array;
|
|
2646
|
-
}
|
|
2647
|
-
function toBufferOrNull(value) {
|
|
2648
|
-
if (value === null)
|
|
2649
|
-
return null;
|
|
2650
|
-
if (Buffer2.isBuffer(value))
|
|
2651
|
-
return value;
|
|
2652
|
-
return Buffer2.from(value.buffer, value.byteOffset, value.byteLength);
|
|
2653
|
-
}
|
|
2654
|
-
function isSessionMetaRow(row) {
|
|
2655
|
-
if (row === null || typeof row !== "object")
|
|
2656
|
-
return false;
|
|
2657
|
-
const r = row;
|
|
2658
|
-
return typeof r.session_id === "string" && isNumberOrNull(r.last_response_time) && isStringOrNull(r.cache_ttl) && typeof r.counter === "number" && typeof r.last_nudge_tokens === "number" && isStringOrNull(r.last_nudge_band) && isStringOrNull(r.last_transform_error) && isNumberOrNull(r.is_subagent) && 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);
|
|
2659
|
-
}
|
|
2660
|
-
function getDefaultSessionMeta(sessionId) {
|
|
2661
|
-
return {
|
|
2662
|
-
sessionId,
|
|
2663
|
-
lastResponseTime: 0,
|
|
2664
|
-
cacheTtl: "5m",
|
|
2665
|
-
counter: 0,
|
|
2666
|
-
lastNudgeTokens: 0,
|
|
2667
|
-
lastNudgeBand: null,
|
|
2668
|
-
lastTransformError: null,
|
|
2669
|
-
isSubagent: false,
|
|
2670
|
-
lastContextPercentage: 0,
|
|
2671
|
-
lastInputTokens: 0,
|
|
2672
|
-
observedSafeInputTokens: 0,
|
|
2673
|
-
cacheAlertSent: false,
|
|
2674
|
-
timesExecuteThresholdReached: 0,
|
|
2675
|
-
compartmentInProgress: false,
|
|
2676
|
-
systemPromptHash: "",
|
|
2677
|
-
systemPromptTokens: 0,
|
|
2678
|
-
conversationTokens: 0,
|
|
2679
|
-
toolCallTokens: 0,
|
|
2680
|
-
clearedReasoningThroughTag: 0,
|
|
2681
|
-
toolReclaimWatermark: 0,
|
|
2682
|
-
lastTodoState: "",
|
|
2683
|
-
cachedM0Bytes: null,
|
|
2684
|
-
cachedM0MuralDataUrl: null,
|
|
2685
|
-
cachedM0MuralHash: null,
|
|
2686
|
-
cachedM1Bytes: null,
|
|
2687
|
-
cachedM0TrimBoundaryId: null,
|
|
2688
|
-
cachedM0TrimBoundaryPartial: false,
|
|
2689
|
-
cachedM0ProjectMemoryEpoch: null,
|
|
2690
|
-
cachedM0WorkspaceFingerprint: null,
|
|
2691
|
-
cachedM0ProjectUserProfileVersion: null,
|
|
2692
|
-
cachedM0MaxCompartmentSeq: null,
|
|
2693
|
-
cachedM0MaxMemoryId: null,
|
|
2694
|
-
cachedM0MaxMutationId: null,
|
|
2695
|
-
cachedM0MaxMemoryMutationId: null,
|
|
2696
|
-
cachedM0ProjectDocsHash: null,
|
|
2697
|
-
cachedM0MaterializedAt: null,
|
|
2698
|
-
cachedM0SessionFactsVersion: null,
|
|
2699
|
-
cachedM0UpgradeState: null,
|
|
2700
|
-
cachedM0SystemHash: null,
|
|
2701
|
-
cachedM0ToolSetHash: null,
|
|
2702
|
-
cachedM0ModelKey: null,
|
|
2703
|
-
cachedM0ProjectIdentity: null,
|
|
2704
|
-
lastObservedModelKey: null,
|
|
2705
|
-
lastUsageContextLimit: 0,
|
|
2706
|
-
priorBoundaryOrdinal: 1,
|
|
2707
|
-
protectedTailPolicyVersion: 0,
|
|
2708
|
-
protectedTailDrainWindowStartedAt: 0,
|
|
2709
|
-
protectedTailDrainTokens: 0,
|
|
2710
|
-
recoveryNoEligibleHeadCount: 0,
|
|
2711
|
-
forceEmergencyBypassWindowStart: 0,
|
|
2712
|
-
forceEmergencyBypassUsed: 0,
|
|
2713
|
-
upgradeRemindedAt: null,
|
|
2714
|
-
upgradeReminderLastSentAt: null,
|
|
2715
|
-
upgradeReminderCount: 0,
|
|
2716
|
-
piStableIdScheme: null
|
|
2717
|
-
};
|
|
2718
|
-
}
|
|
2719
|
-
var sessionMetaExistsStatements = new WeakMap;
|
|
2720
|
-
function ensureSessionMetaRow(db, sessionId, initialIsSubagent = getHarness2() === "opencode2" ? null : false) {
|
|
2721
|
-
let exists = sessionMetaExistsStatements.get(db);
|
|
2722
|
-
if (!exists) {
|
|
2723
|
-
exists = prepareCachedStatement2(db, "SELECT 1 FROM session_meta WHERE session_id = ?");
|
|
2724
|
-
sessionMetaExistsStatements.set(db, exists);
|
|
2742
|
+
ordinalCutoff: { coordinateSpace: "tag-number", cutoff: null },
|
|
2743
|
+
cutoff: null,
|
|
2744
|
+
protectedTagNumbers: new Set,
|
|
2745
|
+
protectedRowIdentities: new Set,
|
|
2746
|
+
status: {
|
|
2747
|
+
floor,
|
|
2748
|
+
protectedCount: 0,
|
|
2749
|
+
protectedMass: 0
|
|
2750
|
+
},
|
|
2751
|
+
isProtected: () => false
|
|
2752
|
+
};
|
|
2725
2753
|
}
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2754
|
+
const sortedAsc = [...toolRows].sort(compareRowsAscending);
|
|
2755
|
+
const tieGroupsDescending = [];
|
|
2756
|
+
let currentGroup = [];
|
|
2757
|
+
let currentTagNumber = null;
|
|
2758
|
+
for (let i = sortedAsc.length - 1;i >= 0; i--) {
|
|
2759
|
+
const row = sortedAsc[i];
|
|
2760
|
+
const tagNum = getRowTagNumber(row);
|
|
2761
|
+
if (currentTagNumber === null || tagNum === currentTagNumber) {
|
|
2762
|
+
currentGroup.push(row);
|
|
2763
|
+
currentTagNumber = tagNum;
|
|
2764
|
+
} else {
|
|
2765
|
+
tieGroupsDescending.push(currentGroup);
|
|
2766
|
+
currentGroup = [row];
|
|
2767
|
+
currentTagNumber = tagNum;
|
|
2768
|
+
}
|
|
2769
|
+
}
|
|
2770
|
+
if (currentGroup.length > 0) {
|
|
2771
|
+
tieGroupsDescending.push(currentGroup);
|
|
2772
|
+
}
|
|
2773
|
+
const massWindowRows = [];
|
|
2774
|
+
let cumulativeMass = 0;
|
|
2775
|
+
for (const group of tieGroupsDescending) {
|
|
2776
|
+
for (const row of group) {
|
|
2777
|
+
massWindowRows.push(row);
|
|
2778
|
+
cumulativeMass += rowWindowMass(row);
|
|
2779
|
+
}
|
|
2780
|
+
if (Math.ceil(cumulativeMass * toolsRatio) >= floor) {
|
|
2781
|
+
break;
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
const mass_cutoff = massWindowRows.length > 0 ? getRowTagNumber(massWindowRows[massWindowRows.length - 1]) : null;
|
|
2785
|
+
const distinctToolTagNumbers = tieGroupsDescending.map((g) => getRowTagNumber(g[0]));
|
|
2786
|
+
const minCount = Math.min(3, distinctToolTagNumbers.length);
|
|
2787
|
+
const newest3_cutoff = minCount > 0 ? distinctToolTagNumbers[minCount - 1] : null;
|
|
2788
|
+
const cutoff = mass_cutoff !== null && newest3_cutoff !== null ? Math.min(mass_cutoff, newest3_cutoff) : mass_cutoff ?? newest3_cutoff;
|
|
2789
|
+
const memberRows = cutoff !== null ? sortedAsc.filter((row) => getRowTagNumber(row) >= cutoff) : [];
|
|
2790
|
+
const memberRowKeys = new Set(memberRows.map(rowKey));
|
|
2791
|
+
const protectedTagNumbers = new Set(memberRows.map(getRowTagNumber));
|
|
2792
|
+
const protectedRowIdentities = new Set(memberRows.map(getRowIdentity));
|
|
2793
|
+
const protectedCount = memberRows.length;
|
|
2794
|
+
const protectedMass = Math.ceil(memberRows.reduce((sum, row) => sum + rowWindowMass(row), 0) * toolsRatio);
|
|
2795
|
+
const isProtected = (row) => {
|
|
2796
|
+
return getRowKind(row) === "tool" && cutoff !== null && getRowTagNumber(row) >= cutoff;
|
|
2797
|
+
};
|
|
2740
2798
|
return {
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
cachedM0MuralHash: stringOrNull(row.cached_m0_mural_hash),
|
|
2765
|
-
cachedM1Bytes: toBufferOrNull(row.cached_m1_bytes),
|
|
2766
|
-
cachedM0TrimBoundaryId: row.cached_m0_last_baseline_end_message_id || null,
|
|
2767
|
-
cachedM0TrimBoundaryPartial: row.cached_trim_partial === 1,
|
|
2768
|
-
cachedM0ProjectMemoryEpoch: numOrNull(row.cached_m0_project_memory_epoch),
|
|
2769
|
-
cachedM0WorkspaceFingerprint: stringOrNull(row.cached_m0_workspace_fingerprint),
|
|
2770
|
-
cachedM0ProjectUserProfileVersion: numOrNull(row.cached_m0_project_user_profile_version),
|
|
2771
|
-
cachedM0MaxCompartmentSeq: numOrNull(row.cached_m0_max_compartment_seq),
|
|
2772
|
-
cachedM0MaxMemoryId: numOrNull(row.cached_m0_max_memory_id),
|
|
2773
|
-
cachedM0MaxMutationId: numOrNull(row.cached_m0_max_mutation_id),
|
|
2774
|
-
cachedM0MaxMemoryMutationId: numOrNull(row.cached_m0_max_memory_mutation_id),
|
|
2775
|
-
cachedM0ProjectDocsHash: stringOrNull(row.cached_m0_project_docs_hash),
|
|
2776
|
-
cachedM0MaterializedAt: numOrNull(row.cached_m0_materialized_at),
|
|
2777
|
-
cachedM0SessionFactsVersion: numOrNull(row.cached_m0_session_facts_version),
|
|
2778
|
-
cachedM0UpgradeState: stringOrNull(row.cached_m0_upgrade_state),
|
|
2779
|
-
cachedM0SystemHash: stringOrNull(row.cached_m0_system_hash),
|
|
2780
|
-
cachedM0ToolSetHash: stringOrNull(row.cached_m0_tool_set_hash),
|
|
2781
|
-
cachedM0ModelKey: stringOrNull(row.cached_m0_model_key),
|
|
2782
|
-
cachedM0ProjectIdentity: stringOrNull(row.cached_m0_project_identity),
|
|
2783
|
-
lastObservedModelKey: stringOrNull(row.last_observed_model_key),
|
|
2784
|
-
lastUsageContextLimit: numOrZero(row.last_usage_context_limit),
|
|
2785
|
-
priorBoundaryOrdinal: Math.max(1, numOrZero(row.prior_boundary_ordinal) || 1),
|
|
2786
|
-
protectedTailPolicyVersion: numOrZero(row.protected_tail_policy_version),
|
|
2787
|
-
protectedTailDrainWindowStartedAt: numOrZero(row.protected_tail_drain_window_started_at),
|
|
2788
|
-
protectedTailDrainTokens: numOrZero(row.protected_tail_drain_tokens),
|
|
2789
|
-
recoveryNoEligibleHeadCount: numOrZero(row.recovery_no_eligible_head_count),
|
|
2790
|
-
forceEmergencyBypassWindowStart: numOrZero(row.force_emergency_bypass_window_start),
|
|
2791
|
-
forceEmergencyBypassUsed: numOrZero(row.force_emergency_bypass_used),
|
|
2792
|
-
upgradeRemindedAt: numOrNull(row.upgrade_reminded_at),
|
|
2793
|
-
upgradeReminderLastSentAt: numOrNull(row.upgrade_reminder_last_sent_at),
|
|
2794
|
-
upgradeReminderCount: numOrZero(row.upgrade_reminder_count),
|
|
2795
|
-
piStableIdScheme: numOrNull(row.pi_stable_id_scheme)
|
|
2799
|
+
memberRows,
|
|
2800
|
+
memberRowKeys,
|
|
2801
|
+
tagNumberSet: {
|
|
2802
|
+
coordinateSpace: "tag-number",
|
|
2803
|
+
tagNumbers: protectedTagNumbers
|
|
2804
|
+
},
|
|
2805
|
+
rowIdentitySet: {
|
|
2806
|
+
coordinateSpace: "row-identity",
|
|
2807
|
+
rowIdentities: protectedRowIdentities
|
|
2808
|
+
},
|
|
2809
|
+
ordinalCutoff: {
|
|
2810
|
+
coordinateSpace: "tag-number",
|
|
2811
|
+
cutoff
|
|
2812
|
+
},
|
|
2813
|
+
cutoff,
|
|
2814
|
+
protectedTagNumbers,
|
|
2815
|
+
protectedRowIdentities,
|
|
2816
|
+
status: {
|
|
2817
|
+
floor,
|
|
2818
|
+
protectedCount,
|
|
2819
|
+
protectedMass
|
|
2820
|
+
},
|
|
2821
|
+
isProtected
|
|
2796
2822
|
};
|
|
2797
2823
|
}
|
|
2798
|
-
function
|
|
2799
|
-
|
|
2800
|
-
|
|
2801
|
-
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
|
|
2805
|
-
|
|
2806
|
-
cached_m0_project_user_profile_version = ?,
|
|
2807
|
-
cached_m0_max_compartment_seq = ?,
|
|
2808
|
-
cached_m0_max_memory_id = ?,
|
|
2809
|
-
cached_m0_max_mutation_id = ?,
|
|
2810
|
-
cached_m0_max_memory_mutation_id = ?,
|
|
2811
|
-
cached_m1_bytes = ?,
|
|
2812
|
-
cached_m0_project_docs_hash = ?,
|
|
2813
|
-
cached_m0_materialized_at = ?,
|
|
2814
|
-
cached_m0_session_facts_version = ?,
|
|
2815
|
-
cached_m0_upgrade_state = ?,
|
|
2816
|
-
cached_m0_system_hash = ?,
|
|
2817
|
-
cached_m0_tool_set_hash = ?,
|
|
2818
|
-
cached_m0_model_key = ?,
|
|
2819
|
-
cached_m0_project_identity = ?
|
|
2820
|
-
WHERE session_id = ?`).run(Buffer2.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 ? Buffer2.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);
|
|
2824
|
+
function readEpochFloorSnapshot(db, sessionId) {
|
|
2825
|
+
try {
|
|
2826
|
+
const row = db.prepare("SELECT protected_tokens_effective FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
2827
|
+
if (row && typeof row.protected_tokens_effective === "number" && Number.isFinite(row.protected_tokens_effective)) {
|
|
2828
|
+
return row.protected_tokens_effective;
|
|
2829
|
+
}
|
|
2830
|
+
} catch {}
|
|
2831
|
+
return null;
|
|
2821
2832
|
}
|
|
2822
|
-
function
|
|
2823
|
-
|
|
2824
|
-
const
|
|
2825
|
-
const
|
|
2826
|
-
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
|
|
2830
|
-
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
|
|
2834
|
-
|
|
2835
|
-
|
|
2836
|
-
|
|
2837
|
-
|
|
2838
|
-
|
|
2839
|
-
|
|
2840
|
-
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
|
|
2844
|
-
|
|
2845
|
-
|
|
2846
|
-
|
|
2847
|
-
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
|
|
2851
|
-
const values = [];
|
|
2852
|
-
for (const [column, value] of clears) {
|
|
2853
|
-
if (!existingColumns.has(column))
|
|
2854
|
-
continue;
|
|
2855
|
-
setClauses.push(`${column} = ?`);
|
|
2856
|
-
values.push(value);
|
|
2833
|
+
function getProtectionWindowForSession(db, sessionId, floor) {
|
|
2834
|
+
const effectiveFloor = typeof floor === "number" && Number.isFinite(floor) ? floor : readEpochFloorSnapshot(db, sessionId) ?? 0;
|
|
2835
|
+
const toolsRatio = sessionDecisionCalibration(db, sessionId).toolsRatio;
|
|
2836
|
+
const pageSize = 256;
|
|
2837
|
+
const projection = `SELECT ${TAG_SELECT_COLUMNS2} FROM tags
|
|
2838
|
+
WHERE session_id = ? AND +type = 'tool'`;
|
|
2839
|
+
const order = `ORDER BY tag_number DESC, id DESC LIMIT ${pageSize}`;
|
|
2840
|
+
let page = db.prepare(`${projection} ${order}`).all(sessionId);
|
|
2841
|
+
const rows = [];
|
|
2842
|
+
let mass = 0;
|
|
2843
|
+
let distinctTags = 0;
|
|
2844
|
+
let currentTag = null;
|
|
2845
|
+
while (page.length > 0) {
|
|
2846
|
+
for (const row of page) {
|
|
2847
|
+
const tagNumber = getRowTagNumber(row);
|
|
2848
|
+
if (tagNumber !== currentTag) {
|
|
2849
|
+
if (distinctTags >= 3 && Math.ceil(mass * toolsRatio) >= effectiveFloor) {
|
|
2850
|
+
return computeProtectionWindow(rows, effectiveFloor, toolsRatio);
|
|
2851
|
+
}
|
|
2852
|
+
distinctTags++;
|
|
2853
|
+
currentTag = tagNumber;
|
|
2854
|
+
}
|
|
2855
|
+
rows.push(row);
|
|
2856
|
+
mass += rowWindowMass(row);
|
|
2857
|
+
}
|
|
2858
|
+
if (page.length < pageSize)
|
|
2859
|
+
break;
|
|
2860
|
+
const last = page[page.length - 1];
|
|
2861
|
+
page = db.prepare(`${projection} AND (tag_number, id) < (?, ?) ${order}`).all(sessionId, getRowTagNumber(last), getRowIdentity(last));
|
|
2857
2862
|
}
|
|
2858
|
-
|
|
2859
|
-
return;
|
|
2860
|
-
db.prepare(`UPDATE session_meta SET ${setClauses.join(", ")} WHERE session_id = ?`).run(...values, sessionId);
|
|
2861
|
-
}
|
|
2862
|
-
function clearCachedM0(db, sessionId) {
|
|
2863
|
-
clearCachedM0M1(db, sessionId);
|
|
2863
|
+
return computeProtectionWindow(rows, effectiveFloor, toolsRatio);
|
|
2864
2864
|
}
|
|
2865
2865
|
|
|
2866
2866
|
// src/features/magic-context/storage-replay-document.ts
|
|
@@ -3316,6 +3316,12 @@ function isPersistedUsageRow(row) {
|
|
|
3316
3316
|
const r = row;
|
|
3317
3317
|
return typeof r.last_context_percentage === "number" && typeof r.last_input_tokens === "number" && typeof r.last_response_time === "number" && (typeof r.last_observed_model_key === "string" || r.last_observed_model_key === null) && (typeof r.last_usage_context_limit === "number" || r.last_usage_context_limit === null) && typeof r.observed_safe_input_tokens === "number";
|
|
3318
3318
|
}
|
|
3319
|
+
function isPersistedReasoningWatermarkRow(row) {
|
|
3320
|
+
if (row === null || typeof row !== "object")
|
|
3321
|
+
return false;
|
|
3322
|
+
const r = row;
|
|
3323
|
+
return typeof r.cleared_reasoning_through_tag === "number";
|
|
3324
|
+
}
|
|
3319
3325
|
function isPersistedNoteNudgeRow(row) {
|
|
3320
3326
|
if (row === null || typeof row !== "object")
|
|
3321
3327
|
return false;
|
|
@@ -3831,6 +3837,10 @@ function rollbackProtectedTailDrainReservation(db, reservation) {
|
|
|
3831
3837
|
WHERE session_id = ? AND protected_tail_drain_window_started_at = ?`).run(reservation.tokens, reservation.sessionId, reservation.windowStartedAt);
|
|
3832
3838
|
}).immediate();
|
|
3833
3839
|
}
|
|
3840
|
+
function getPersistedReasoningWatermark(db, sessionId) {
|
|
3841
|
+
const result = db.prepare("SELECT cleared_reasoning_through_tag FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
3842
|
+
return isPersistedReasoningWatermarkRow(result) ? result.cleared_reasoning_through_tag : 0;
|
|
3843
|
+
}
|
|
3834
3844
|
function setPersistedReasoningWatermark(db, sessionId, tagNumber) {
|
|
3835
3845
|
ensureSessionMetaRow(db, sessionId);
|
|
3836
3846
|
db.prepare("UPDATE session_meta SET cleared_reasoning_through_tag = ? WHERE session_id = ?").run(tagNumber, sessionId);
|
|
@@ -4124,6 +4134,11 @@ function pruneNoteNudgeAnchors(db, sessionId, visibleMessageIds) {
|
|
|
4124
4134
|
});
|
|
4125
4135
|
return pruned;
|
|
4126
4136
|
}
|
|
4137
|
+
function pruneAutoSearchHintDecisions(db, sessionId, retiredMessageIds) {
|
|
4138
|
+
if (retiredMessageIds.size === 0)
|
|
4139
|
+
return 0;
|
|
4140
|
+
return updateAutoSearchHintRetirement(db, sessionId, retiredMessageIds).pruned;
|
|
4141
|
+
}
|
|
4127
4142
|
var pendingAutoSearchRetirements = new WeakMap;
|
|
4128
4143
|
var AUTO_SEARCH_DECISION_SOFT_LIMIT = 2000;
|
|
4129
4144
|
function queueAutoSearchHintDecisionRetirement(db, sessionId, messageIds) {
|
|
@@ -8888,4 +8903,4 @@ function deleteToolTagsByOwner(db, sessionId, ownerMsgId) {
|
|
|
8888
8903
|
return getDeleteToolTagsByOwnerStatement(db).all(sessionId, ownerMsgId).length;
|
|
8889
8904
|
}
|
|
8890
8905
|
|
|
8891
|
-
export { protectedToolTagNumbers, protectedToolTokenCount, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isThinkingPart, currentReclaimableToolOutputCount, isRecord, contentTagOwnerMessageId, estimateImageTokensFromDataUrl, estimateToolAttachmentImageTokens, providerVisiblePart, providerVisibleMessage, CLEARED_TODO_STATE_JSON, normalizeTodoStateJson, buildSyntheticTodoPart, computeSyntheticCallId, isSyntheticTodoPart, countRealUserMessages, tailHygieneStructuralSignature, sameTailHygieneStructuralSignature, formatTailHygienePrefixMismatch, refreshTailHygieneBaseline, effectiveTailHygiene, assertTailHygieneContentUnchangedIfEnabled, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, isDroppedToolOutput, toolOutputTokens, decideChannel1, evaluateChannel2, formatChannel1Evaluation, formatChannel2Evaluation, buildChannel2Reminder, buildChannel1Reminder, createFinalWireIncompleteLogger, MERGED_REASONING_PARTS_PREFIX, decodeMergedReasoningParts, readFrozenMergedReasoningParts, MAX_EXECUTE_THRESHOLD, escalationBands, HYGIENE_PROVIDER_UNITS_VERSION, sessionDecisionCalibration, transitionSessionHygieneUnits, readEpochFloorSnapshot, getProtectionWindowForSession,
|
|
8906
|
+
export { CACHED_TRIM_PARTIAL_SQL, SESSION_META_SELECT_COLUMNS, META_COLUMNS, BOOLEAN_META_KEYS, NULL_BIND_META_KEYS, isSessionMetaRow, getDefaultSessionMeta, ensureSessionMetaRow, toSessionMeta, persistCachedM0, clearCachedM0M1, clearCachedM0, protectedToolTagNumbers, protectedToolTokenCount, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isThinkingPart, currentReclaimableToolOutputCount, isRecord, contentTagOwnerMessageId, estimateImageTokensFromDataUrl, estimateToolAttachmentImageTokens, providerVisiblePart, providerVisibleMessage, CLEARED_TODO_STATE_JSON, normalizeTodoStateJson, buildSyntheticTodoPart, computeSyntheticCallId, isSyntheticTodoPart, countRealUserMessages, tailHygieneStructuralSignature, sameTailHygieneStructuralSignature, formatTailHygienePrefixMismatch, refreshTailHygieneBaseline, effectiveTailHygiene, assertTailHygieneContentUnchangedIfEnabled, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, isDroppedToolOutput, toolOutputTokens, decideChannel1, evaluateChannel2, formatChannel1Evaluation, formatChannel2Evaluation, buildChannel2Reminder, buildChannel1Reminder, createFinalWireIncompleteLogger, MERGED_REASONING_PARTS_PREFIX, decodeMergedReasoningParts, readFrozenMergedReasoningParts, MAX_EXECUTE_THRESHOLD, escalationBands, HYGIENE_PROVIDER_UNITS_VERSION, sessionDecisionCalibration, transitionSessionHygieneUnits, readEpochFloorSnapshot, getProtectionWindowForSession, withReplayEnvelopeSnapshot, invalidateReplayEnvelopeSnapshot, isRustMarkerAdmissionFenced, setRustMarkerAdmissionFence, ReplayDocumentError, readReplayEnvelope, readReplayDocument, updateReplayDocument, writeReplayDocument, isEmergencyRecoveryArmed, isProviderOverflowReconfirmed, isProviderOverflowFailClosedProven, getEmergencyRecoveryArmedAt, describeProtectedTailDrainBudgetSkip, loadPersistedUsage, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, resetProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, getProtectedTailDrainBudgetSkip, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, getPersistedReasoningWatermark, setPersistedReasoningWatermark, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, queueAutoSearchHintDecisionRetirement, flushAutoSearchHintDecisionRetirement, getPersistedTodoPermissionDenied, setPersistedTodoPermissionDenied, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, setNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, loadTransformPassStateSnapshot, recordOverflowDetected, recordDetectedContextLimit, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, getCompactionMarkerPublicationState, compareAndSetCompactionMarkerPublicationState, setPersistedCompactionMarkerState, getDeferredClearedCompactionMarkerState, retireDeferredClearedCompactionMarkerState, parseStrippedPlaceholderState, serializeStrippedPlaceholderState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, THINKING_BINDING_STRIP_ORDER_END_MARKER, thinkingBindingRecoveryFrozenId, COMPACTION_OFF_THINKING_FROZEN_PREFIX, compactionOffThinkingFrozenId, compactionOffFrozenThinkingIds, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, noteBindingRecoveryAwaitingClear, bindingRecoveryAwaitingClear, retryBindingRecoveryClear, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getTrailingBlankDecisions, addTrailingBlankDecisions, demoteTrailingBlankKeepDecisions, getStaleReduceStrippedIds, addStaleReduceStrippedIds, getProcessedImageStrippedIds, parseProcessedImageMarkers, serializeProcessedImageMarkers, getProcessedImageMarkers, addProcessedImageStrippedIds, getPendingCompactionMarkerState, getCompactionMarkerHealth, loadPostprocessReplaySnapshot, setPendingCompactionMarkerState, replacePendingCompactionMarkerStateIf, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, logPiCompactionMarkerClear, getObservedEpochFloor, resolveEpochFloorForPass, getReasoningRemovalState, addRemovedReasoningIds, markDropLeavesReasoning, detectThinkingBindingMismatch, detectLatestTurnThinkingMismatch, isPrefixBoundThinkingModel, detectOverflow, modelAcceptsEmptyContent, isAnthropicFamilyRoute, neutralizeDroppedReasoningPart, restoreNeutralizedReasoningPart, isNeutralizedReasoningPart, variantChangeBustsProviderCache, makeSentinel, makeWholeMessageSentinel, isSentinel, replaySentinelByMessageIds, isInActiveAnthropicTurn, activeAnthropicTurnStart, hasAnthropicReasoning, markServedShapeRepair, prepareServedShapeRepair, stripSystemInjectedMessages, stripDroppedPlaceholderMessages, replayClearedReasoning, replayStrippedInlineThinking, clearOldReasoning, stripClearedReasoning, captureInlineThinkingRepairs, stripInlineThinking, findReasoningBearingAssistantIds, findLatestAssistantReasoningMutationExemptMessage, snapshotTrailingBlankSourceDecisions, findTrailingBlankDecisionCandidates, applyFrozenTrailingBlankDecisions, stripReasoningFromAssistantIds, findMergedReasoningStripDecisions, stripReasoningFromMergedAssistants, getEmptyImageParts, stripProcessedImages, projectOpencodeReasoningBudgetCutoff, DEFAULT_KEEP_REASONING_TOKENS, resolveKeepReasoningTokens, reasoningStepCost, reasoningBudgetCutoff, reasoningTextAndOpaque, opencodeReasoningBudgetCutoff, describeFinalWireTail, estimatePartImageTokens, openCode2ThinkingPayload, estimateMessageTokens, wireContentBytes, createFinalWireUsageTracker, estimateFinalWireInputTokens, estimateAppendedWireTokens, estimateEmergencyDropReclaimTokens, planEmergencyDrop, measureEmergencyTag, snapshotEmergencyServedMass, tagsSinceReading, emergencyServedMassRemovedSince, queuePendingOp, queuePendingDropForUnchangedTag, getPendingOps, hasPendingDropOps, getPendingOpsCount, clearPendingOps, removePendingOp, updateTagByteSize2, getRecentTagOwnerMessageIds2, getActiveTagTokenAggregate2, AGE_RECLAIM_MIN_TOKENS2, getOldestActiveUnprotectedToolTags2, getActiveToolTagsForAgeReclaim2, getTriggerTagTokenUpperBound2, getActiveTagTokenTotalsByMessage2, updateTagTokenCount2, getPersistedToolTagAccounting2, getAllStatusTagTokenTotalsFlat2, getReasoningTokenEstimatesByMessage2, tryGetReasoningTokenEstimatesByMessage2, getMaxTagNumberByOwnerMessage2, TagOwnerSummaryNotReady2, scanTagOwnerSummary2, cachedTagOwnerRatios2, tagOwnerWarmupState2, scanTagOwnerDelta2, installTagOwnerDelta2, installTagOwnerSummary2, isTagOwnerSummaryReady2, tagTokenCountIsNull2, backfillTagTokenCounts2, insertTag2, updateTagStatus2, markTagDropped2, markWhitespaceAssistantTagInert2, getInertWhitespaceAssistantTags2, getInertWhitespaceAssistantTagsByNumbers2, updateTagDropMode2, updateCavemanDepth2, updateTagMessageId2, hasPiFallbackMessageTags2, findAdoptableFallbackTags2, adoptFallbackTagMessageId2, foldShrunkPartTags2, hasPiFallbackToolOwnerTags2, findPiFallbackToolOwnerTags2, adoptPiFallbackToolOwnerTag2, adoptPiFallbackMessageTag2, markTagsCompactedByMessageIds2, deleteTagsByMessageId2, getMaxTagNumberBySession2, getTagNumberByMessageId2, getAssignableTagNumberByMessageId2, getMinMessageTagNumberForRawId2, deriveTagLoadFloor2, TAG_SELECT_COLUMNS2, getTagsBySession2, getActiveTagsBySession2, getTailHygieneTags2, getDroppedTagsBySession2, getTagsForPendingOperations2, getTagsByNumbers2, getNewestToolTagNumbers2, getDroppedTagsByNumbers2, getMaxDroppedTagNumber2, getTagById2, getTopNBySize2, getToolTagNumberByOwner2, getNullOwnerToolTag2, adoptNullOwnerToolTag2, getCandidateToolOwners2, pickNearestPriorOwner2 };
|