@cortexkit/pi-magic-context 0.49.12 → 0.49.13

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.
@@ -18,11 +18,11 @@ var [
18
18
  { Database, registerSqliteDiagnosticSink },
19
19
  { log }
20
20
  ] = await Promise.all([
21
- import("./embedding-backfill-14tqcfrn.js"),
21
+ import("./embedding-backfill-7kj16fh9.js"),
22
22
  import("./embedding-cache-7rp4gqzr.js"),
23
23
  import("./storage-memory-axnsk5t1.js"),
24
- import("./project-embedding-registry-ymvne11v.js"),
25
- import("./search-85e21wb8.js"),
24
+ import("./project-embedding-registry-52zwmtbn.js"),
25
+ import("./search-hffb8xht.js"),
26
26
  import("./embedding-activity-ew6dshfd.js"),
27
27
  import("./harness-9872e0ym.js"),
28
28
  import("./sqlite-adjpy399.js"),
@@ -0,0 +1,87 @@
1
+ import {
2
+ setHarness2
3
+ } from "./index-0h2mkab2.js";
4
+ import {
5
+ Database2
6
+ } from "./index-asrxgdt4.js";
7
+ import {
8
+ configureContextDatabasePragmas2
9
+ } from "./index-fapenpch.js";
10
+ import"./index-g4jf772p.js";
11
+ import"./index-7bqrfyny.js";
12
+ import"./index-6dz2ed1v.js";
13
+ import"./index-djxc8w8c.js";
14
+ import {
15
+ replaceCompartmentChunkEmbeddings,
16
+ recordChunkEmbedBackoff,
17
+ loadUnembeddedSessionChunkCandidates,
18
+ countUnembeddedSessionCompartments
19
+ } from "./index-7qc73yk5.js";
20
+ import {
21
+ recordSessionProjectIdentity,
22
+ acquireGitSweepLease,
23
+ renewGitSweepLease,
24
+ releaseGitSweepLease
25
+ } from "./index-1mrvw9en.js";
26
+ import"./index-6ex901g3.js";
27
+ import"./index-apgwdby5.js";
28
+ import {
29
+ LATEST_SUPPORTED_VERSION,
30
+ enforceSchemaFence
31
+ } from "./index-t27xk4r7.js";
32
+ import"./index-3cnarwf8.js";
33
+ import"./index-jrap43gc.js";
34
+ import"./index-135e8hvg.js";
35
+ import"./index-8976mezv.js";
36
+ import"./index-d4dt19md.js";
37
+
38
+ // ../plugin/src/features/magic-context/chunk-embedding-write-worker.ts
39
+ import { parentPort, workerData } from "node:worker_threads";
40
+ var port = parentPort;
41
+ if (!port)
42
+ throw new Error("chunk embedding writer requires a parent port");
43
+ setHarness2(workerData.harness);
44
+ var db = new Database2(workerData.path);
45
+ if (!enforceSchemaFence(db, workerData.path, LATEST_SUPPORTED_VERSION)) {
46
+ db.close();
47
+ throw new Error("chunk embedding writer rejected an unsupported store schema");
48
+ }
49
+ var timeout = Math.max(0, Math.floor(workerData.timeout));
50
+ db.exec(`PRAGMA busy_timeout=${timeout}; PRAGMA foreign_keys=ON`);
51
+ configureContextDatabasePragmas2(db);
52
+ port.on("message", (input) => {
53
+ try {
54
+ let value;
55
+ switch (input.kind) {
56
+ case "replace":
57
+ replaceCompartmentChunkEmbeddings(db, input.rows, input.sourceKey);
58
+ break;
59
+ case "project":
60
+ recordSessionProjectIdentity(db, input.session, input.project);
61
+ break;
62
+ case "count":
63
+ value = countUnembeddedSessionCompartments(db, input.project, input.session, input.model, input.tokens);
64
+ break;
65
+ case "candidates":
66
+ value = loadUnembeddedSessionChunkCandidates(db, input.project, input.session, input.model, input.limit, input.excluded, input.tokens, true);
67
+ break;
68
+ case "backoff":
69
+ recordChunkEmbedBackoff(db, input.candidate, input.project, input.model);
70
+ break;
71
+ case "acquire":
72
+ value = acquireGitSweepLease(db, input.project, input.holder, {
73
+ ignoreCooldown: true
74
+ });
75
+ break;
76
+ case "renew":
77
+ value = renewGitSweepLease(db, input.project, input.holder);
78
+ break;
79
+ case "release":
80
+ releaseGitSweepLease(db, input.project, input.holder);
81
+ break;
82
+ }
83
+ port.postMessage({ value });
84
+ } catch (error) {
85
+ port.postMessage({ error: error instanceof Error ? error.message : String(error) });
86
+ }
87
+ });
@@ -1,11 +1,12 @@
1
1
  import {
2
2
  ensureMemoryEmbeddings2
3
- } from "./index-xpsht877.js";
4
- import"./index-f6e8jsrh.js";
3
+ } from "./index-7wagp5jp.js";
4
+ import"./index-nwbhe6qv.js";
5
5
  import"./index-9p40dgkm.js";
6
- import"./index-af9nb5db.js";
7
6
  import"./index-yhzhdp3m.js";
8
- import"./index-j24916mq.js";
7
+ import"./index-1mrvw9en.js";
8
+ import"./index-7qc73yk5.js";
9
+ import"./index-9jvktm7k.js";
9
10
  import"./index-6dz2ed1v.js";
10
11
  import"./index-1k729e4f.js";
11
12
  import"./index-6ex901g3.js";
@@ -12,7 +12,7 @@ import {
12
12
  resolveLocalEmbeddingWorkerRuntime,
13
13
  getLocalEmbeddingNativeMemoryStats,
14
14
  LocalEmbeddingProvider
15
- } from "./index-j24916mq.js";
15
+ } from "./index-9jvktm7k.js";
16
16
  import {
17
17
  setStoragePrivatePermissionEnforcement
18
18
  } from "./index-81nthk8j.js";
@@ -2,7 +2,7 @@ import {
2
2
  subagentTemperature,
3
3
  promptFingerprint,
4
4
  readHostSystemPrompt
5
- } from "./index-xmdkde4v.js";
5
+ } from "./index-y29y2j2w.js";
6
6
  import"./index-6x556c2q.js";
7
7
  import"./index-0h2mkab2.js";
8
8
  import"./index-7bqrfyny.js";
@@ -0,0 +1,225 @@
1
+ import {
2
+ getHarness2
3
+ } from "./index-0h2mkab2.js";
4
+ import {
5
+ isUserHomeDirectory
6
+ } from "./index-6ex901g3.js";
7
+ import {
8
+ logSlowWriteTransaction
9
+ } from "./index-d4dt19md.js";
10
+
11
+ // ../plugin/src/features/magic-context/session-project-storage.ts
12
+ var SESSION_CHUNK_REPAIR_BATCH_SIZE = 100;
13
+ var upsertSessionProjectStatements = new WeakMap;
14
+ var repairSessionChunkProjectStatements = new WeakMap;
15
+ var misScopedProjectChunkStatements = new WeakMap;
16
+ var MIS_SCOPED_PROJECT_CHUNK_IDS_SQL = `
17
+ SELECT e.id FROM compartment_chunk_embeddings e
18
+ JOIN session_projects sp ON sp.session_id = e.session_id AND sp.harness = e.harness
19
+ WHERE e.project_path = ? AND sp.project_path <> e.project_path
20
+ UNION ALL
21
+ SELECT e.id FROM session_projects sp
22
+ JOIN compartment_chunk_embeddings e ON e.session_id = sp.session_id
23
+ WHERE sp.project_path = ? AND e.harness = sp.harness AND e.project_path <> sp.project_path`;
24
+ function getUpsertSessionProjectStatement(db) {
25
+ let stmt = upsertSessionProjectStatements.get(db);
26
+ if (!stmt) {
27
+ stmt = db.prepare(`INSERT INTO session_projects (session_id, harness, project_path, updated_at)
28
+ VALUES (?, ?, ?, ?)
29
+ ON CONFLICT(session_id, harness) DO UPDATE SET
30
+ project_path = excluded.project_path,
31
+ updated_at = excluded.updated_at
32
+ WHERE session_projects.project_path <> excluded.project_path`);
33
+ upsertSessionProjectStatements.set(db, stmt);
34
+ }
35
+ return stmt;
36
+ }
37
+ function getRepairSessionChunkProjectStatement(db) {
38
+ let stmt = repairSessionChunkProjectStatements.get(db);
39
+ if (!stmt) {
40
+ stmt = db.prepare(`UPDATE compartment_chunk_embeddings
41
+ SET project_path = ?
42
+ WHERE id IN (
43
+ SELECT id
44
+ FROM compartment_chunk_embeddings
45
+ WHERE session_id = ?
46
+ AND harness = ?
47
+ AND project_path <> ?
48
+ LIMIT ?
49
+ )`);
50
+ repairSessionChunkProjectStatements.set(db, stmt);
51
+ }
52
+ return stmt;
53
+ }
54
+ function findMisScopedCompartmentChunkEmbeddingIdsForProject(db, projectPath) {
55
+ return db.prepare(`SELECT id FROM (${MIS_SCOPED_PROJECT_CHUNK_IDS_SQL}) LIMIT 25`).all(projectPath, projectPath).map(({ id }) => id);
56
+ }
57
+ function recordSessionProjectIdentity(db, sessionId, projectPath) {
58
+ if (!sessionId || !projectPath)
59
+ return;
60
+ if (!projectPath.startsWith("git:") && !projectPath.startsWith("dir:") && isUserHomeDirectory(projectPath))
61
+ return;
62
+ const harness = getHarness2();
63
+ const now = Date.now();
64
+ let previousProjectPath;
65
+ db.transaction(() => {
66
+ const existing = db.prepare("SELECT project_path FROM session_projects WHERE session_id = ? AND harness = ?").get(sessionId, harness);
67
+ previousProjectPath = existing?.project_path;
68
+ getUpsertSessionProjectStatement(db).run(sessionId, harness, projectPath, now);
69
+ getRepairSessionChunkProjectStatement(db).run(projectPath, sessionId, harness, projectPath, SESSION_CHUNK_REPAIR_BATCH_SIZE);
70
+ }).immediate();
71
+ return previousProjectPath === projectPath ? undefined : { previousProjectPath, projectPath };
72
+ }
73
+ function repairMisScopedCompartmentChunkEmbeddingsForProject(db, projectPath, ids = findMisScopedCompartmentChunkEmbeddingIdsForProject(db, projectPath)) {
74
+ if (!projectPath || ids.length === 0)
75
+ return 0;
76
+ return db.prepare(`UPDATE compartment_chunk_embeddings
77
+ SET project_path = (SELECT sp.project_path FROM session_projects sp
78
+ WHERE sp.session_id = compartment_chunk_embeddings.session_id
79
+ AND sp.harness = compartment_chunk_embeddings.harness)
80
+ WHERE id IN (${ids.map(() => "?").join(",")}) AND EXISTS (
81
+ SELECT 1 FROM session_projects sp
82
+ WHERE sp.session_id = compartment_chunk_embeddings.session_id
83
+ AND sp.harness = compartment_chunk_embeddings.harness
84
+ AND sp.project_path <> compartment_chunk_embeddings.project_path
85
+ AND (sp.project_path = ? OR compartment_chunk_embeddings.project_path = ?)
86
+ )`).run(...ids, projectPath, projectPath).changes;
87
+ }
88
+
89
+ // ../plugin/src/features/magic-context/git-commits/sweep-coordinator.ts
90
+ var GIT_SWEEP_COOLDOWN_MS = 10 * 60 * 1000;
91
+ var GIT_SWEEP_LEASE_TTL_MS = 5 * 60 * 1000;
92
+ var GIT_SWEEP_NON_INDEXABLE_REPROBE_MS = 24 * 60 * 60 * 1000;
93
+ var GIT_SWEEP_LEASE_RENEWAL_MS = 60 * 1000;
94
+ function runImmediate(db, body) {
95
+ db.exec("BEGIN IMMEDIATE");
96
+ const transactionStartedAt = performance.now();
97
+ let committed = false;
98
+ try {
99
+ const result = body();
100
+ db.exec("COMMIT");
101
+ committed = true;
102
+ logSlowWriteTransaction("git_sweep_lease", transactionStartedAt);
103
+ return result;
104
+ } finally {
105
+ if (!committed) {
106
+ try {
107
+ db.exec("ROLLBACK");
108
+ } catch {}
109
+ }
110
+ }
111
+ }
112
+ function rowToState(row) {
113
+ return {
114
+ projectPath: row.project_path,
115
+ leaseHolder: row.lease_holder,
116
+ leaseExpiresAt: row.lease_expires_at,
117
+ lastSweptAt: row.last_swept_at
118
+ };
119
+ }
120
+ function getGitSweepCoordinatorState(db, projectPath) {
121
+ const row = db.prepare(`SELECT project_path, lease_holder, lease_expires_at, last_swept_at
122
+ FROM git_sweep_coordinator
123
+ WHERE project_path = ?`).get(projectPath);
124
+ return row ? rowToState(row) : null;
125
+ }
126
+ function acquireGitSweepLease(db, projectPath, holderId, options = {}) {
127
+ const cooldownMs = options.cooldownMs ?? GIT_SWEEP_COOLDOWN_MS;
128
+ const leaseTtlMs = options.leaseTtlMs ?? GIT_SWEEP_LEASE_TTL_MS;
129
+ return runImmediate(db, () => {
130
+ const now = Date.now();
131
+ const row = getGitSweepCoordinatorState(db, projectPath);
132
+ if (row?.leaseHolder && row.leaseExpiresAt !== null && row.leaseExpiresAt > now) {
133
+ return {
134
+ acquired: false,
135
+ projectPath,
136
+ reason: "lease_active",
137
+ leaseHolder: row.leaseHolder,
138
+ leaseExpiresAt: row.leaseExpiresAt,
139
+ lastSweptAt: row.lastSweptAt,
140
+ nextAllowedAt: null
141
+ };
142
+ }
143
+ if (!options.ignoreCooldown && row?.lastSweptAt !== null && row?.lastSweptAt !== undefined) {
144
+ const nextAllowedAt = row.lastSweptAt + cooldownMs;
145
+ if (nextAllowedAt > now) {
146
+ return {
147
+ acquired: false,
148
+ projectPath,
149
+ reason: "cooldown_active",
150
+ leaseHolder: row.leaseHolder,
151
+ leaseExpiresAt: row.leaseExpiresAt,
152
+ lastSweptAt: row.lastSweptAt,
153
+ nextAllowedAt
154
+ };
155
+ }
156
+ }
157
+ const leaseExpiresAt = now + leaseTtlMs;
158
+ db.prepare(`INSERT INTO git_sweep_coordinator (
159
+ project_path,
160
+ lease_holder,
161
+ lease_expires_at,
162
+ last_swept_at
163
+ ) VALUES (?, ?, ?, NULL)
164
+ ON CONFLICT(project_path) DO UPDATE SET
165
+ lease_holder = excluded.lease_holder,
166
+ lease_expires_at = excluded.lease_expires_at`).run(projectPath, holderId, leaseExpiresAt);
167
+ return {
168
+ acquired: true,
169
+ projectPath,
170
+ holderId,
171
+ acquiredAt: now,
172
+ leaseExpiresAt
173
+ };
174
+ });
175
+ }
176
+ function renewGitSweepLease(db, projectPath, holderId, leaseTtlMs = GIT_SWEEP_LEASE_TTL_MS) {
177
+ return runImmediate(db, () => {
178
+ const now = Date.now();
179
+ const leaseExpiresAt = now + leaseTtlMs;
180
+ const result = db.prepare(`UPDATE git_sweep_coordinator
181
+ SET lease_expires_at = ?
182
+ WHERE project_path = ?
183
+ AND lease_holder = ?
184
+ AND lease_expires_at > ?`).run(leaseExpiresAt, projectPath, holderId, now);
185
+ return result.changes === 1;
186
+ });
187
+ }
188
+ function markGitSweepSuccessAndRelease(db, projectPath, holderId) {
189
+ return runImmediate(db, () => {
190
+ const now = Date.now();
191
+ const result = db.prepare(`UPDATE git_sweep_coordinator
192
+ SET lease_holder = NULL,
193
+ lease_expires_at = NULL,
194
+ last_swept_at = ?
195
+ WHERE project_path = ?
196
+ AND lease_holder = ?
197
+ AND lease_expires_at > ?`).run(now, projectPath, holderId, now);
198
+ return result.changes === 1;
199
+ });
200
+ }
201
+ function parkGitSweepNonIndexable(db, projectPath, holderId, reprobeMs = GIT_SWEEP_NON_INDEXABLE_REPROBE_MS) {
202
+ return runImmediate(db, () => {
203
+ const now = Date.now();
204
+ const sweptAt = now + reprobeMs - GIT_SWEEP_COOLDOWN_MS;
205
+ const result = db.prepare(`UPDATE git_sweep_coordinator
206
+ SET lease_holder = NULL,
207
+ lease_expires_at = NULL,
208
+ last_swept_at = ?
209
+ WHERE project_path = ?
210
+ AND lease_holder = ?
211
+ AND lease_expires_at > ?`).run(sweptAt, projectPath, holderId, now);
212
+ return result.changes === 1;
213
+ });
214
+ }
215
+ function releaseGitSweepLease(db, projectPath, holderId) {
216
+ runImmediate(db, () => {
217
+ db.prepare(`UPDATE git_sweep_coordinator
218
+ SET lease_holder = NULL,
219
+ lease_expires_at = NULL
220
+ WHERE project_path = ?
221
+ AND lease_holder = ?`).run(projectPath, holderId);
222
+ });
223
+ }
224
+
225
+ export { findMisScopedCompartmentChunkEmbeddingIdsForProject, recordSessionProjectIdentity, repairMisScopedCompartmentChunkEmbeddingsForProject, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease };
@@ -858,13 +858,17 @@ function loadUnembeddedShadowChunkCandidates(db, projectPath, primaryModelId, sh
858
858
  const rows = getShadowBackfillCandidateStatement(db).all(projectPath, projectPath, primaryModelId);
859
859
  return selectHashIncompleteChunkCandidates(db, projectPath, shadowModelId, mapBackfillCandidateRows(rows), Math.max(1, limit), shadowMaxInputTokens);
860
860
  }
861
- async function loadUnembeddedCompartmentChunkCandidatesPolite(db, projectPath, modelId, limit, maxInputTokens = DEFAULT_COMPARTMENT_CHUNK_MAX_INPUT_TOKENS, leaseHeldRenumber = false) {
861
+ async function loadUnembeddedCompartmentChunkCandidatesPolite(db, projectPath, modelId, limit, maxInputTokens = DEFAULT_COMPARTMENT_CHUNK_MAX_INPUT_TOKENS, leaseHeldRenumber = false, isEligible) {
862
862
  const rows = getBackfillCandidateStatement(db).all(projectPath);
863
863
  const candidates = mapBackfillCandidateRows(rows);
864
864
  const missing = [];
865
865
  const stale = [];
866
866
  let sliceStarted = performance.now();
867
867
  for (const candidate of candidates) {
868
+ if (isEligible && !isEligible(candidate)) {
869
+ sliceStarted = await yieldCoverageSlice(sliceStarted);
870
+ continue;
871
+ }
868
872
  const classification = classifyChunkCoverageDefect(db, projectPath, modelId, candidate, maxInputTokens);
869
873
  if (classification.defect === "missing")
870
874
  missing.push(candidate);
@@ -1019,7 +1023,7 @@ function memoizedCoverageWindows(candidate, canonicalText, sourceKey, modelId, m
1019
1023
  return windows;
1020
1024
  }
1021
1025
  async function yieldCoverageSlice(started) {
1022
- if (performance.now() - started < 35)
1026
+ if (performance.now() - started < 8)
1023
1027
  return started;
1024
1028
  await new Promise((resolve) => setTimeout(resolve, 0));
1025
1029
  return performance.now();
@@ -1093,6 +1097,47 @@ function selectHashIncompleteChunkCandidates(db, projectPath, modelId, candidate
1093
1097
  return [...missing, ...stale].slice(0, limit);
1094
1098
  }
1095
1099
  var sessionBackfillCandidateStatements = new WeakMap;
1100
+ function loadUnembeddedSessionChunkCandidates(db, projectPath, sessionId, modelId, limit, excludeIds, maxInputTokens = DEFAULT_COMPARTMENT_CHUNK_MAX_INPUT_TOKENS, leaseHeldRenumber = false) {
1101
+ const exclusions = excludeIds && excludeIds.length > 0 ? excludeIds : [];
1102
+ const exclusionSql = exclusions.length > 0 ? `AND c.id NOT IN (${exclusions.map(() => "?").join(", ")})` : "";
1103
+ const stmt = exclusions.length > 0 ? db.prepare(`SELECT c.id AS id,
1104
+ c.session_id AS sessionId,
1105
+ c.start_message AS startMessage,
1106
+ c.end_message AS endMessage,
1107
+ c.title AS title
1108
+ FROM compartments c
1109
+ JOIN session_projects sp
1110
+ ON sp.session_id = c.session_id
1111
+ AND sp.harness = c.harness
1112
+ AND sp.project_path = ?
1113
+ WHERE c.session_id = ?
1114
+ AND c.start_message IS NOT NULL
1115
+ AND c.end_message IS NOT NULL
1116
+ ${exclusionSql}
1117
+ ORDER BY c.start_message ASC, c.id ASC`) : (() => {
1118
+ let cached = sessionBackfillCandidateStatements.get(db);
1119
+ if (!cached) {
1120
+ cached = db.prepare(`SELECT c.id AS id,
1121
+ c.session_id AS sessionId,
1122
+ c.start_message AS startMessage,
1123
+ c.end_message AS endMessage,
1124
+ c.title AS title
1125
+ FROM compartments c
1126
+ JOIN session_projects sp
1127
+ ON sp.session_id = c.session_id
1128
+ AND sp.harness = c.harness
1129
+ AND sp.project_path = ?
1130
+ WHERE c.session_id = ?
1131
+ AND c.start_message IS NOT NULL
1132
+ AND c.end_message IS NOT NULL
1133
+ ORDER BY c.start_message ASC, c.id ASC`);
1134
+ sessionBackfillCandidateStatements.set(db, cached);
1135
+ }
1136
+ return cached;
1137
+ })();
1138
+ const rows = stmt.all(projectPath, sessionId, ...exclusions);
1139
+ return selectHashIncompleteChunkCandidates(db, projectPath, modelId, mapBackfillCandidateRows(rows), Math.max(1, limit), maxInputTokens, leaseHeldRenumber);
1140
+ }
1096
1141
  async function loadUnembeddedSessionChunkCandidatesPolite(db, projectPath, sessionId, modelId, limit, excludeIds = [], maxInputTokens = DEFAULT_COMPARTMENT_CHUNK_MAX_INPUT_TOKENS, leaseHeldRenumber = false) {
1097
1142
  const excluded = new Set(excludeIds);
1098
1143
  const missing = [];
@@ -1109,10 +1154,22 @@ async function loadUnembeddedSessionChunkCandidatesPolite(db, projectPath, sessi
1109
1154
  else if (leaseHeldRenumber) {
1110
1155
  applyLeaseHeldCoverageRepair(db, candidate, projectPath, modelId, classification);
1111
1156
  }
1157
+ if (missing.length >= Math.max(1, limit))
1158
+ return missing;
1112
1159
  started = await yieldCoverageSlice(started);
1113
1160
  }
1114
1161
  return [...missing, ...stale].slice(0, Math.max(1, limit));
1115
1162
  }
1163
+ function countUnembeddedSessionCompartments(db, projectPath, sessionId, modelId, maxInputTokens = DEFAULT_COMPARTMENT_CHUNK_MAX_INPUT_TOKENS) {
1164
+ const rows = getSessionBackfillRows(db, projectPath, sessionId);
1165
+ let count = 0;
1166
+ for (const candidate of rows) {
1167
+ const { defect } = classifyChunkCoverageDefect(db, projectPath, modelId, candidate, maxInputTokens);
1168
+ if (defect === "missing" || defect === "stale")
1169
+ count++;
1170
+ }
1171
+ return count;
1172
+ }
1116
1173
  function countSessionCompartmentEmbedCoverage(db, projectPath, sessionId, modelId, maxInputTokens = DEFAULT_COMPARTMENT_CHUNK_MAX_INPUT_TOKENS) {
1117
1174
  const candidates = getSessionBackfillRows(db, projectPath, sessionId);
1118
1175
  let embedded = 0;
@@ -1165,4 +1222,4 @@ async function countUnembeddedSessionCompartmentsPolite(db, projectPath, session
1165
1222
  return count;
1166
1223
  }
1167
1224
 
1168
- export { DEFAULT_COMPARTMENT_CHUNK_MAX_INPUT_TOKENS, CHUNK_WINDOW_SAFETY_RATIO, normalizeCompartmentChunkMaxInputTokens, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, loadCompartmentChunkEmbeddingsForSearch, loadUnembeddedShadowChunkCandidates, loadUnembeddedCompartmentChunkCandidatesPolite, deleteChunkEmbedBackoffForSession, recordChunkEmbedBackoff, chunkWindowSourceKey, loadUnembeddedSessionChunkCandidatesPolite, countSessionCompartmentEmbedCoverage, countSessionCompartmentEmbedCoveragePolite, countUnembeddedSessionCompartmentsPolite };
1225
+ export { DEFAULT_COMPARTMENT_CHUNK_MAX_INPUT_TOKENS, CHUNK_WINDOW_SAFETY_RATIO, normalizeCompartmentChunkMaxInputTokens, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, loadCompartmentChunkEmbeddingsForSearch, loadUnembeddedShadowChunkCandidates, loadUnembeddedCompartmentChunkCandidatesPolite, deleteChunkEmbedBackoffForSession, recordChunkEmbedBackoff, chunkWindowSourceKey, loadUnembeddedSessionChunkCandidates, loadUnembeddedSessionChunkCandidatesPolite, countUnembeddedSessionCompartments, countSessionCompartmentEmbedCoverage, countSessionCompartmentEmbedCoveragePolite, countUnembeddedSessionCompartmentsPolite };
@@ -10,12 +10,12 @@ import {
10
10
  } from "./index-6dz2ed1v.js";
11
11
  import {
12
12
  LocalEmbeddingProvider
13
- } from "./index-j24916mq.js";
13
+ } from "./index-9jvktm7k.js";
14
14
  import {
15
15
  OpenAICompatibleEmbeddingProvider,
16
16
  getProjectEmbeddingSnapshot2,
17
17
  embedBatchForProject2
18
- } from "./index-f6e8jsrh.js";
18
+ } from "./index-nwbhe6qv.js";
19
19
  import {
20
20
  isEmbeddingHostBusy2
21
21
  } from "./index-9p40dgkm.js";
@@ -103,7 +103,7 @@ import {
103
103
  clearLkgRecoveryFence,
104
104
  deleteSessionScopedRows,
105
105
  getLastIndexedOrdinal2
106
- } from "./index-6hex51s9.js";
106
+ } from "./index-vv1j5cak.js";
107
107
  import {
108
108
  SubcClient,
109
109
  connectionFileExists,
@@ -114,9 +114,22 @@ import {
114
114
  import {
115
115
  sameProjectDirectory
116
116
  } from "./index-djxc8w8c.js";
117
+ import {
118
+ invalidateAutoEmbedSession,
119
+ drainBackgroundBatches,
120
+ markProjectLoadUntrusted2,
121
+ drainProjectEmbeddingIdentityMaintenance2,
122
+ registerProjectEmbedding2,
123
+ registerProjectShadowEmbedding2,
124
+ registerProjectInObservationMode2,
125
+ unregisterProjectShadowEmbedding2,
126
+ unregisterProjectEmbedding2,
127
+ getProjectEmbeddingSnapshot2,
128
+ embedTextForProject2
129
+ } from "./index-nwbhe6qv.js";
117
130
  import {
118
131
  getErrorMessage
119
- } from "./index-z5ftst3e.js";
132
+ } from "./index-t27xk4r7.js";
120
133
  import {
121
134
  V2_MEMORY_CATEGORIES,
122
135
  CATEGORY_PRIORITY,
@@ -137,18 +150,6 @@ import {
137
150
  normalizeStoredProjectPath,
138
151
  storedPathBelongsToIdentity
139
152
  } from "./index-6ex901g3.js";
140
- import {
141
- drainBackgroundBatches,
142
- markProjectLoadUntrusted2,
143
- drainProjectEmbeddingIdentityMaintenance2,
144
- registerProjectEmbedding2,
145
- registerProjectShadowEmbedding2,
146
- registerProjectInObservationMode2,
147
- unregisterProjectShadowEmbedding2,
148
- unregisterProjectEmbedding2,
149
- getProjectEmbeddingSnapshot2,
150
- embedTextForProject2
151
- } from "./index-f6e8jsrh.js";
152
153
  import {
153
154
  getNoteByIdInScope,
154
155
  getNotes,
@@ -165,7 +166,7 @@ import {
165
166
  resolveMemoriesByIdsForSearch2,
166
167
  unifiedSearch2,
167
168
  formatSearchResults2
168
- } from "./index-gykw2zhn.js";
169
+ } from "./index-wp9q91kn.js";
169
170
  import {
170
171
  computeCueContentHash,
171
172
  getMuralCueState,
@@ -4499,11 +4500,12 @@ class V2StoreReader {
4499
4500
  const head = Math.floor((maxChars - truncationMarker.length) / 2);
4500
4501
  const tail = maxChars - truncationMarker.length - head;
4501
4502
  return this.prepare(`WITH users AS (
4502
- SELECT seq, time_created, data FROM session_message
4503
- WHERE session_id = ? AND type = 'user' AND time_created ${before ? "<=" : ">"} ?
4503
+ SELECT session_id, seq, time_created, data FROM session_message
4504
+ WHERE session_id = ? AND type = 'user' AND time_created ${before ? "<=" : ">"}
4505
+ ?
4504
4506
  ORDER BY time_created ${direction}, seq ${direction} LIMIT ?
4505
4507
  ), texts AS (
4506
- SELECT seq, time_created, CASE
4508
+ SELECT session_id, seq, time_created, CASE
4507
4509
  WHEN json_extract(data, '$.synthetic') = 1 OR json_extract(data, '$.ignored') = 1 THEN ''
4508
4510
  WHEN json_type(data, '$.text') = 'text' THEN json_extract(data, '$.text')
4509
4511
  ELSE COALESCE((SELECT group_concat(json_extract(value, '$.text'), char(10))
@@ -4513,7 +4515,19 @@ class V2StoreReader {
4513
4515
  AND COALESCE(json_extract(value, '$.ignored'), 0) <> 1), '') END AS text
4514
4516
  FROM users WHERE json_valid(data)
4515
4517
  ) SELECT seq, time_created, CASE WHEN length(text) > ?
4516
- THEN substr(text, 1, ?) || ? || substr(text, -?) ELSE text END AS text
4518
+ THEN substr(text, 1, ?) || ? || substr(text, -?) ELSE text END AS text,
4519
+ EXISTS (
4520
+ SELECT 1 FROM session_message assistant_reply
4521
+ WHERE assistant_reply.session_id = texts.session_id
4522
+ AND assistant_reply.type = 'assistant'
4523
+ AND assistant_reply.seq < texts.seq
4524
+ AND EXISTS (
4525
+ SELECT 1 FROM session_message prior_user
4526
+ WHERE prior_user.session_id = texts.session_id
4527
+ AND prior_user.type = 'user'
4528
+ AND prior_user.seq < assistant_reply.seq
4529
+ )
4530
+ ) AS follows_assistant_reply
4517
4531
  FROM texts ORDER BY time_created ${direction}, seq ${direction}`).all(sessionID, boundaryMs, limit, maxChars, head, truncationMarker, tail);
4518
4532
  }
4519
4533
  storedRowsAfter(sessionID, after) {
@@ -4948,31 +4962,6 @@ function clearSession(db, sessionId, rustModuleCleanupAcknowledged = false, perm
4948
4962
  clearUnpublishedAutoSearchNoHints(sessionId);
4949
4963
  logSlowWriteTransaction("clear-session", transactionStartedAt);
4950
4964
  }
4951
- // ../plugin/src/hooks/magic-context/embed-session-state.ts
4952
- var embedPauseBySession = new Set;
4953
- var embedRunStateBySession = new Map;
4954
- var autoEmbedAttemptedBySession = new Set;
4955
- var autoEmbedIdentityBySession = new Map;
4956
- function invalidateAutoEmbedSession(sessionId) {
4957
- autoEmbedAttemptedBySession.delete(sessionId);
4958
- autoEmbedIdentityBySession.delete(sessionId);
4959
- }
4960
- function getEmbedDrainUiStatus(sessionId, progress) {
4961
- if (embedPauseBySession.has(sessionId)) {
4962
- return { status: "paused" };
4963
- }
4964
- const activeRun = embedRunStateBySession.get(sessionId);
4965
- if (activeRun && !activeRun.signal.aborted || progress?.kind === "embed" && progress.phase === "recomp") {
4966
- return { status: "running" };
4967
- }
4968
- if (progress?.kind === "embed" && (progress.phase === "failed" || progress.phase === "skipped") && progress.message) {
4969
- if (/provider/i.test(progress.message)) {
4970
- return { status: "stopped", detail: progress.message };
4971
- }
4972
- }
4973
- return { status: "idle" };
4974
- }
4975
-
4976
4965
  // ../plugin/src/features/magic-context/compartment-lease.ts
4977
4966
  var COMPARTMENT_LEASE_TTL_MS = 5 * 60 * 1000;
4978
4967
  var COMPARTMENT_LEASE_RENEWAL_MS = 60 * 1000;
@@ -15565,4 +15554,4 @@ function registerMagicContextTools(pi, opts) {
15565
15554
  }
15566
15555
  }
15567
15556
 
15568
- export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, parseJsoncRecovering, detectConfigFile, MIN_PLAUSIBLE_CONTEXT_LIMIT, catalogOutputReserve, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, formatWindowSource, isSaneLimit, resolveOutputReserve, getSdkWindowGeometry, getSdkContextLimit, getSdkOutputLimit, getSdkInputLimit, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, readSessionMeta, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, embedPauseBySession, embedRunStateBySession, autoEmbedAttemptedBySession, autoEmbedIdentityBySession, invalidateAutoEmbedSession, getEmbedDrainUiStatus, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, HAS_COMPARTMENT_CONTENT_SQL, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getUncoveredCompartmentEndThrough, isPartialCompartmentEnd, readProjectDocsCanonical, providerResponseFailed, isSuccessfulProviderCompletion, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, recordSystemRefreshOwnership, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, acknowledgeSystemPromptDelivery, deferDeliveredSystemRefresh, clearSystemPromptDelivery, saveLkgSlotToDb, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, replayLkg, registerLkgPersistence, LKG_SNAPSHOT_ARRAY, LKG_SNAPSHOT_OBJECT, LKG_SNAPSHOT_KEY, LKG_SNAPSHOT_STRING, LKG_SNAPSHOT_NUMBER, LKG_SNAPSHOT_BOOLEAN, LKG_SNAPSHOT_NULL, LKG_SNAPSHOT_UNDEFINED, contentSnapshotValue, signatureForFields, lkgContentFields, lkgContentDigestFromFields, isLegacyLkgDigest, legacyLkgDigestFromFields, lkgFieldsMatchDigest, exactReusablePrefix, incrementalLkgContentDigests, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, dropSlot, TOOL_SWEEP_SCOPED_MARKER, encodePiContentDecision, decodePiContentDecision, getPiContentDecisions, freezePiContentDecision, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, externalHistorianFailureReason, subprocessExitHistorianFailureReason, countHistorianRuns, recordHistorianRun, summarizeImportance, tallyFactsByCategory, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, noteTouchedAt, noteNudgePickIndex, formatNoteNudge, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, resolvePiRealStableId, isPiContentFallbackId, isPiIndexFallbackId, piContentFallbackIds, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findRestartModelSeedFromBranch, iterateEntriesToRawMessageRange, iterateAsyncEntriesToRawMessageRange, convertEntriesToRawMessages, convertPiAssistantEntryById, convertEntriesToRawMessagePage, countPiRawMessages, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getTaskScheduleState, getFailingDreamTasks, getSkippedDreamTasks, getMostRecentTaskRunAt, pruneNonCanonicalTaskRows, deleteTaskScheduleRowsForProject, seedTaskScheduleState, writeTaskScheduleState, isRetrospectiveWindowProcessed, recordRetrospectiveWindowProcessed, curateCategoryForMemoryCategory, peekCurateCategoryScope, beginCurateCategoryRun, curateTaskStateAfterSuccess, MEMORY_MURAL_BLOCK, buildMagicContextSection, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, MEMORY_RENDER_FORMAT_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, withCachedM0MemoryIds, readCachedM0MemoryIds, renderBudgetIdentityChanged, renderedBudgetSnapshot, renderedBudgetShrinkReason, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, TEMPORAL_MARKER_REPLAY_PATTERN, temporalMarkerPrefix, renderUserProfileContent, clearInjectionCache, getVisibleMemoryIds, orderHistorianMemories, renderHistorianMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, resetPrefixTrimFallbackState, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, loadPiConfig, loadPiConfigDetailed, unregisterPiProjectEmbeddings, ensureProjectRegisteredFromPiDirectory, resolvePiHarnessDetection, resolvePiHarnessKind, resolvePiOrdinalAlignment, piRawOrdinalOffsetSource, resolvePiOrdinalAlignmentForContext, isPiOrdinalAlignmentUnanchored, clearPiOrdinalAlignmentSession, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
15557
+ export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, parseJsoncRecovering, detectConfigFile, MIN_PLAUSIBLE_CONTEXT_LIMIT, catalogOutputReserve, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, formatWindowSource, isSaneLimit, resolveOutputReserve, getSdkWindowGeometry, getSdkContextLimit, getSdkOutputLimit, getSdkInputLimit, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, readSessionMeta, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, HAS_COMPARTMENT_CONTENT_SQL, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getUncoveredCompartmentEndThrough, isPartialCompartmentEnd, readProjectDocsCanonical, providerResponseFailed, isSuccessfulProviderCompletion, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, recordSystemRefreshOwnership, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, acknowledgeSystemPromptDelivery, deferDeliveredSystemRefresh, clearSystemPromptDelivery, saveLkgSlotToDb, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, replayLkg, registerLkgPersistence, LKG_SNAPSHOT_ARRAY, LKG_SNAPSHOT_OBJECT, LKG_SNAPSHOT_KEY, LKG_SNAPSHOT_STRING, LKG_SNAPSHOT_NUMBER, LKG_SNAPSHOT_BOOLEAN, LKG_SNAPSHOT_NULL, LKG_SNAPSHOT_UNDEFINED, contentSnapshotValue, signatureForFields, lkgContentFields, lkgContentDigestFromFields, isLegacyLkgDigest, legacyLkgDigestFromFields, lkgFieldsMatchDigest, exactReusablePrefix, incrementalLkgContentDigests, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, dropSlot, TOOL_SWEEP_SCOPED_MARKER, encodePiContentDecision, decodePiContentDecision, getPiContentDecisions, freezePiContentDecision, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, externalHistorianFailureReason, subprocessExitHistorianFailureReason, countHistorianRuns, recordHistorianRun, summarizeImportance, tallyFactsByCategory, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, noteTouchedAt, noteNudgePickIndex, formatNoteNudge, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, resolvePiRealStableId, isPiContentFallbackId, isPiIndexFallbackId, piContentFallbackIds, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findRestartModelSeedFromBranch, iterateEntriesToRawMessageRange, iterateAsyncEntriesToRawMessageRange, convertEntriesToRawMessages, convertPiAssistantEntryById, convertEntriesToRawMessagePage, countPiRawMessages, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getTaskScheduleState, getFailingDreamTasks, getSkippedDreamTasks, getMostRecentTaskRunAt, pruneNonCanonicalTaskRows, deleteTaskScheduleRowsForProject, seedTaskScheduleState, writeTaskScheduleState, isRetrospectiveWindowProcessed, recordRetrospectiveWindowProcessed, curateCategoryForMemoryCategory, peekCurateCategoryScope, beginCurateCategoryRun, curateTaskStateAfterSuccess, MEMORY_MURAL_BLOCK, buildMagicContextSection, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, MEMORY_RENDER_FORMAT_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, withCachedM0MemoryIds, readCachedM0MemoryIds, renderBudgetIdentityChanged, renderedBudgetSnapshot, renderedBudgetShrinkReason, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, TEMPORAL_MARKER_REPLAY_PATTERN, temporalMarkerPrefix, renderUserProfileContent, clearInjectionCache, getVisibleMemoryIds, orderHistorianMemories, renderHistorianMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, resetPrefixTrimFallbackState, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, loadPiConfig, loadPiConfigDetailed, unregisterPiProjectEmbeddings, ensureProjectRegisteredFromPiDirectory, resolvePiHarnessDetection, resolvePiHarnessKind, resolvePiOrdinalAlignment, piRawOrdinalOffsetSource, resolvePiOrdinalAlignmentForContext, isPiOrdinalAlignmentUnanchored, clearPiOrdinalAlignmentSession, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };