@cortexkit/pi-magic-context 0.47.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/auto-search-worker.js +27 -22
  2. package/dist/embedding-activity-ew6dshfd.js +10 -0
  3. package/dist/embedding-backfill-b71dvfs8.js +20 -0
  4. package/dist/embedding-cache-7rp4gqzr.js +16 -0
  5. package/dist/embedding-worker.js +11 -8
  6. package/dist/harness-9872e0ym.js +10 -0
  7. package/dist/historian-calibration-extension.js +30 -4
  8. package/dist/index-041ex0cj.js +519 -0
  9. package/dist/index-0h2mkab2.js +17 -0
  10. package/dist/{index-2p1e8706.js → index-0vrkp1jq.js} +3 -3
  11. package/dist/index-135e8hvg.js +43 -0
  12. package/dist/{index-vgcemg0n.js → index-1evzceyw.js} +151 -2452
  13. package/dist/index-21v1kfs7.js +2309 -0
  14. package/dist/{index-n3g5mwa8.js → index-290tzwp1.js} +3 -3
  15. package/dist/{index-0qejsd7f.js → index-3cgbv47m.js} +289 -45
  16. package/dist/{index-xpbh1ypk.js → index-3mgf68pn.js} +38 -741
  17. package/dist/index-3rea6zd9.js +2396 -0
  18. package/dist/index-674f6qs2.js +16 -0
  19. package/dist/index-8976mezv.js +209 -0
  20. package/dist/index-904reqtg.js +152 -0
  21. package/dist/index-9p40dgkm.js +22 -0
  22. package/dist/index-9x1f96r8.js +11 -0
  23. package/dist/index-bejpsj10.js +1060 -0
  24. package/dist/{index-spk5vrhy.js → index-bgmv2kaf.js} +1 -16
  25. package/dist/{index-k3ezsjng.js → index-ehybv5nr.js} +14657 -13951
  26. package/dist/index-fapenpch.js +13 -0
  27. package/dist/index-hwqb3s7f.js +3804 -0
  28. package/dist/index-kjd1fj55.js +3106 -0
  29. package/dist/{index-td885aah.js → index-mcgehvgw.js} +181 -230
  30. package/dist/index-r024r8da.js +171 -0
  31. package/dist/{index-266qrgss.js → index-r56xgha8.js} +301 -27
  32. package/dist/{index-kztsbkqq.js → index-t7xfqtg6.js} +171 -168
  33. package/dist/index-vakawmbc.js +1262 -0
  34. package/dist/{index-7n8gb6j3.js → index-x3dcnxh0.js} +34 -33
  35. package/dist/index-xjqheg7a.js +931 -0
  36. package/dist/index-yarjn32j.js +3026 -0
  37. package/dist/index-yhzhdp3m.js +143 -0
  38. package/dist/index-yzcjxnt2.js +787 -0
  39. package/dist/{index-w76x3af7.js → index-zh1jw8qp.js} +107 -4
  40. package/dist/index.js +4926 -2437
  41. package/dist/logger-j6tecd1h.js +19 -0
  42. package/dist/message-index-bounded-qz5dz2se.js +120 -0
  43. package/dist/{message-time-backfill-d3db2etr.js → message-time-backfill-05ppypkz.js} +7 -6
  44. package/dist/migration-worker.js +20 -14
  45. package/dist/project-embedding-registry-ky7wrkr1.js +85 -0
  46. package/dist/raw-ordinal-warmup-worker.js +60 -0
  47. package/dist/{read-session-chunk-atxsyfqv.js → read-session-chunk-24sd89tf.js} +14 -6
  48. package/dist/read-session-raw-npx3920c.js +57 -0
  49. package/dist/{safe-notification-target-6cn3z99t.js → safe-notification-target-vn9kpmv4.js} +3 -2
  50. package/dist/search-jbh28nwy.js +40 -0
  51. package/dist/sqlite-3yye76ht.js +44 -0
  52. package/dist/sqlite-context-pragmas-gcgch6qz.js +6 -0
  53. package/dist/storage-memory-1z20y55x.js +71 -0
  54. package/dist/storage-tags-kjnsqbdb.js +127 -0
  55. package/dist/subagent-entry.js +35 -17
  56. package/dist/transformers-node-wasm.js +18415 -18415
  57. package/package.json +3 -3
  58. package/dist/index-7s8vw2y0.js +0 -5207
  59. package/dist/index-qaa5j277.js +0 -8544
  60. /package/dist/{index-en1k8h8m.js → index-5prbx026.js} +0 -0
@@ -1,558 +1,33 @@
1
1
  import {
2
- getMagicContextStorageDir,
3
- log
4
- } from "./index-7n8gb6j3.js";
2
+ V2_MEMORY_CATEGORIES
3
+ } from "./index-135e8hvg.js";
4
+ import {
5
+ log2
6
+ } from "./index-x3dcnxh0.js";
5
7
  import {
6
8
  ensureColumn,
7
9
  healAllNullColumns,
8
- installV95PerfSchema,
10
+ installV95PerfSchema
11
+ } from "./index-mcgehvgw.js";
12
+ import {
9
13
  resolveOpenCodeDbPath,
10
14
  openCodeDbPathExists,
11
15
  getOpenCodeDbProbeDescriptions
12
- } from "./index-td885aah.js";
16
+ } from "./index-8976mezv.js";
13
17
  import {
14
- Database,
15
- withSqliteBackgroundWriter,
16
- withoutSqliteTransformPass
17
- } from "./index-0qejsd7f.js";
18
+ Database2
19
+ } from "./index-3cgbv47m.js";
18
20
  import {
19
- writeStorageFileAtomicSync
20
- } from "./index-vf38qhee.js";
21
+ normalizeStoredProjectPath,
22
+ storedPathBelongsToIdentity
23
+ } from "./index-041ex0cj.js";
21
24
  import {
22
25
  logSlowWriteTransaction
23
- } from "./index-2p1e8706.js";
24
-
25
- // ../plugin/src/features/magic-context/memory/project-identity.ts
26
- import { execFileSync } from "node:child_process";
27
- import { createHash as createHash2 } from "node:crypto";
28
- import { existsSync, realpathSync, statSync } from "node:fs";
29
- import { homedir } from "node:os";
30
- import path3 from "node:path";
31
-
32
- // ../plugin/src/features/magic-context/memory/project-identity-cache.ts
33
- import { createHash } from "node:crypto";
34
- import { readFileSync } from "node:fs";
35
- import path2 from "node:path";
36
-
37
- // ../plugin/src/shared/project-directory-key.ts
38
- import path from "node:path";
39
- function projectDirectoryKey(directory) {
40
- const slashed = directory.replaceAll("\\", "/").replace(/^\/\/\?\/UNC\//i, "//").replace(/^\/\/\?\//, "");
41
- if (/^[a-z]:\//i.test(slashed) || slashed.startsWith("//")) {
42
- return path.win32.normalize(slashed).replaceAll("\\", "/").replace(/\/$/, "").toLowerCase();
43
- }
44
- return path.resolve(directory);
45
- }
46
-
47
- // ../plugin/src/features/magic-context/memory/project-identity-cache.ts
48
- function cachePath(directory, storageDir = getMagicContextStorageDir()) {
49
- const hash = createHash("sha256").update(projectDirectoryKey(directory)).digest("hex");
50
- return path2.join(storageDir, "project-identities", `${hash}.json`);
51
- }
52
- function rememberGitIdentity(directory, identity) {
53
- try {
54
- const destination = cachePath(directory);
55
- writeStorageFileAtomicSync(destination, JSON.stringify({ directory: projectDirectoryKey(directory), identity }));
56
- } catch {}
57
- }
58
- function readRememberedGitIdentity(directory, storageDir) {
59
- try {
60
- const record = JSON.parse(readFileSync(cachePath(directory, storageDir), "utf8"));
61
- if (record.directory === projectDirectoryKey(directory) && /^git:[0-9a-f]{7,64}$/.test(record.identity))
62
- return record.identity;
63
- } catch {}
64
- return;
65
- }
66
-
67
- // ../plugin/src/features/magic-context/memory/project-identity.ts
68
- var GIT_TIMEOUT_MS = 5000;
69
- var TRANSIENT_FAILURE_COOLDOWN_MS = 5 * 60 * 1000;
70
- var identityCache = new Map;
71
- var linkedGitWorktreeCache = new Map;
72
- var lastKnownGitIdentityCache = new Map;
73
- var directoryFallbackCache = new Map;
74
- var transientFailureCooldown = new Map;
75
- var dubiousOwnershipFallbackDirectories = new Set;
76
- var dubiousOwnershipLoggedDirectories = new Set;
77
- var dubiousOwnershipWarnedDirectories = new Set;
78
- var transientGitIdentityReuseLoggedDirectories = new Set;
79
- var sessionIdentityCache = new Map;
80
- var homeProjectPermission = false;
81
- var pausedIdentityReasons = new Map;
82
- var pausedIdentityLogged = new Set;
83
- function setHomeProjectPermission(allowed) {
84
- homeProjectPermission = allowed;
85
- }
86
- var execFileSyncForIdentity = execFileSync;
87
- var userHomeDirectoryForIdentity = () => homedir();
88
- var nowMs = () => Date.now();
89
- var filesystemProbeObserverForTests;
90
-
91
- class ProjectIdentityError extends Error {
92
- errorClass;
93
- rawDirectory;
94
- constructor(errorClass, rawDirectory, message, cause) {
95
- super(message);
96
- this.name = "ProjectIdentityError";
97
- this.errorClass = errorClass;
98
- this.rawDirectory = rawDirectory;
99
- if (cause) {
100
- this.cause = cause;
101
- }
102
- }
103
- }
104
- function asError(error) {
105
- return error instanceof Error ? error : undefined;
106
- }
107
- function getErrorCode(error) {
108
- if (error === null || typeof error !== "object" || !("code" in error)) {
109
- return;
110
- }
111
- const code = error.code;
112
- return typeof code === "string" ? code : undefined;
113
- }
114
- function getErrorSignal(error) {
115
- if (error === null || typeof error !== "object" || !("signal" in error)) {
116
- return;
117
- }
118
- const signal = error.signal;
119
- return typeof signal === "string" ? signal : undefined;
120
- }
121
- function getErrorKilled(error) {
122
- if (error === null || typeof error !== "object" || !("killed" in error)) {
123
- return false;
124
- }
125
- return error.killed === true;
126
- }
127
- function getErrorStderr(error) {
128
- if (error === null || typeof error !== "object" || !("stderr" in error)) {
129
- return "";
130
- }
131
- const stderr = error.stderr;
132
- if (typeof stderr === "string") {
133
- return stderr;
134
- }
135
- if (Buffer.isBuffer(stderr)) {
136
- return stderr.toString("utf8");
137
- }
138
- return "";
139
- }
140
- function directoryFallback(directory) {
141
- const canonical = path3.resolve(directory);
142
- const hash = createHash2("md5").update(canonical, "utf8").digest("hex").slice(0, 12);
143
- return `dir:${hash}`;
144
- }
145
- function rememberedIdentityOrDirectoryFallback(canonical) {
146
- return readRememberedGitIdentity(canonical) ?? directoryFallback(canonical);
147
- }
148
- function assertDirectoryUsable(canonicalDirectory, rawDirectory) {
149
- try {
150
- const stat = statSync(canonicalDirectory);
151
- if (!stat.isDirectory()) {
152
- throw new ProjectIdentityError("unknown", rawDirectory, `Project path is not a directory: ${canonicalDirectory}`);
153
- }
154
- } catch (error) {
155
- if (error instanceof ProjectIdentityError) {
156
- throw error;
157
- }
158
- const code = getErrorCode(error);
159
- if (code === "EACCES" || code === "EPERM") {
160
- throw new ProjectIdentityError("permission_denied", rawDirectory, `Permission denied while accessing project directory: ${canonicalDirectory}`, asError(error));
161
- }
162
- throw new ProjectIdentityError("unknown", rawDirectory, `Unable to access project directory: ${canonicalDirectory}`, asError(error));
163
- }
164
- }
165
- function isGitTimeoutError(error) {
166
- const code = getErrorCode(error);
167
- const signal = getErrorSignal(error);
168
- return code === "ETIMEDOUT" || signal === "SIGTERM" || signal === "SIGKILL" || getErrorKilled(error);
169
- }
170
- function hasUnbornHead(directory) {
171
- const options = {
172
- cwd: directory,
173
- encoding: "utf8",
174
- env: { ...process.env, LC_ALL: "C", LANG: "C" },
175
- stdio: ["ignore", "pipe", "pipe"],
176
- timeout: GIT_TIMEOUT_MS,
177
- windowsHide: true
178
- };
179
- try {
180
- execFileSyncForIdentity("git", ["rev-parse", "--git-dir"], options);
181
- try {
182
- execFileSyncForIdentity("git", ["rev-parse", "--verify", "--quiet", "HEAD"], options);
183
- return false;
184
- } catch (error) {
185
- return !isGitTimeoutError(error) && typeof error === "object" && error !== null && "status" in error && error.status === 1 && getErrorStderr(error) === "";
186
- }
187
- } catch {
188
- return false;
189
- }
190
- }
191
- function classifyGitError(error, rawDirectory) {
192
- if (isGitTimeoutError(error)) {
193
- return new ProjectIdentityError("git_timeout", rawDirectory, `git rev-list timed out after ${GIT_TIMEOUT_MS}ms`, asError(error));
194
- }
195
- const code = getErrorCode(error);
196
- if (code === "ENOENT") {
197
- return new ProjectIdentityError("git_missing", rawDirectory, "git binary is not available in PATH", asError(error));
198
- }
199
- if (code === "EACCES" || code === "EPERM") {
200
- return new ProjectIdentityError("permission_denied", rawDirectory, "Permission denied while spawning git", asError(error));
201
- }
202
- const stderr = getErrorStderr(error).toLowerCase();
203
- if (stderr.includes("detected dubious ownership")) {
204
- return new ProjectIdentityError("dubious_ownership", rawDirectory, "git refused to read the repository because it detected dubious ownership", asError(error));
205
- }
206
- if (stderr.includes("not a git repository") || stderr.includes("does not have any commits yet") || stderr.includes("ambiguous argument 'head'") || stderr.includes("unknown revision or path")) {
207
- return new ProjectIdentityError("not_git_repo", rawDirectory, "Directory has no git root commit; caller may use directory fallback", asError(error));
208
- }
209
- return new ProjectIdentityError("unknown", rawDirectory, "git rev-list failed while resolving project identity", asError(error));
210
- }
211
- function resolveProjectIdentityStrict(directory, allowHomeProject = homeProjectPermission) {
212
- assertProjectAllowed(directory, allowHomeProject);
213
- const canonical = path3.resolve(directory);
214
- const cached = identityCache.get(canonical);
215
- if (cached !== undefined) {
216
- return cached;
217
- }
218
- assertDirectoryUsable(canonical, directory);
219
- if (!hasGitDir(canonical)) {
220
- throw new ProjectIdentityError("not_git_repo", directory, "Directory has no git metadata; caller may use directory fallback");
221
- }
222
- let output;
223
- try {
224
- output = execFileSyncForIdentity("git", ["rev-list", "--max-parents=0", "HEAD"], {
225
- cwd: canonical,
226
- encoding: "utf8",
227
- env: { ...process.env, LC_ALL: "C", LANG: "C" },
228
- stdio: ["ignore", "pipe", "pipe"],
229
- timeout: GIT_TIMEOUT_MS,
230
- windowsHide: true
231
- });
232
- } catch (error) {
233
- const classified = classifyGitError(error, directory);
234
- if (classified.errorClass === "not_git_repo" && hasUnbornHead(canonical)) {
235
- throw new ProjectIdentityError("no_commits", directory, "Git repository has no commits yet");
236
- }
237
- throw classified;
238
- }
239
- const rootCommit = output.split(`
240
- `).map((line) => line.trim().slice(0, 64)).filter((line) => /^[0-9a-f]{7,64}$/.test(line)).sort()[0];
241
- if (!rootCommit) {
242
- throw new ProjectIdentityError("unknown", directory, "git rev-list returned no valid root commit hash");
243
- }
244
- const identity = `git:${rootCommit}`;
245
- identityCache.set(canonical, identity);
246
- lastKnownGitIdentityCache.set(canonical, identity);
247
- rememberGitIdentity(canonical, identity);
248
- const root = gitRootDirectory(canonical);
249
- if (root && root !== canonical)
250
- rememberGitIdentity(root, identity);
251
- transientFailureCooldown.delete(canonical);
252
- dubiousOwnershipFallbackDirectories.delete(canonical);
253
- transientGitIdentityReuseLoggedDirectories.delete(canonical);
254
- return identity;
255
- }
256
- function shouldUseDirectoryFallback(error) {
257
- return error.errorClass !== "home_project_disabled";
258
- }
259
- function getActiveCooldown(canonical) {
260
- const until = transientFailureCooldown.get(canonical);
261
- if (until === undefined)
262
- return;
263
- if (nowMs() < until)
264
- return until;
265
- transientFailureCooldown.delete(canonical);
266
- return;
267
- }
268
- function lastKnownGitIdentity(canonical) {
269
- return lastKnownGitIdentityCache.get(canonical) ?? identityCache.get(canonical) ?? readRememberedGitIdentity(canonical);
270
- }
271
- function nearestLastKnownGitIdentity(canonical) {
272
- const visited = new Set;
273
- const walk = (start) => {
274
- let current = start;
275
- while (!visited.has(current)) {
276
- visited.add(current);
277
- const cached = lastKnownGitIdentity(current);
278
- if (cached !== undefined)
279
- return { identity: cached, source: current };
280
- if (existsSync(path3.join(current, ".git")))
281
- break;
282
- const parent = path3.dirname(current);
283
- if (parent === current)
284
- break;
285
- current = parent;
286
- }
287
- return;
288
- };
289
- const exactOrAncestor = walk(canonical);
290
- if (exactOrAncestor)
291
- return exactOrAncestor;
292
- try {
293
- const realCanonical = realpathSync.native(canonical);
294
- if (realCanonical !== canonical)
295
- return walk(realCanonical);
296
- } catch {}
297
- return;
298
- }
299
- function reuseLastKnownGitIdentity(canonical) {
300
- const cached = nearestLastKnownGitIdentity(canonical);
301
- if (cached === undefined)
302
- return;
303
- if (!transientGitIdentityReuseLoggedDirectories.has(canonical)) {
304
- transientGitIdentityReuseLoggedDirectories.add(canonical);
305
- const sourceNote = cached.source === canonical ? "" : ` from ancestor ${cached.source}`;
306
- log(`[magic-context] git identity resolution is temporarily unavailable for ${canonical}; reusing the last successful project identity${sourceNote} to avoid splitting project-scoped memory`);
307
- }
308
- return cached.identity;
309
- }
310
- function formatDubiousOwnershipWarning(canonical) {
311
- return `Magic Context: git refused to read ${canonical} (dubious ownership — the repo is owned by a different user). Memory features are paused unless a previous git identity is available. Fix: git config --global --add safe.directory ${canonical}`;
312
- }
313
- function recordDubiousOwnershipFallback(canonical) {
314
- dubiousOwnershipFallbackDirectories.add(canonical);
315
- if (dubiousOwnershipLoggedDirectories.has(canonical))
316
- return;
317
- dubiousOwnershipLoggedDirectories.add(canonical);
318
- log(`[magic-context] ${formatDubiousOwnershipWarning(canonical)}`);
319
- }
320
- function canonicalUserHomeDirectory() {
321
- const homeDirectory = userHomeDirectoryForIdentity();
322
- try {
323
- return realpathSync.native(homeDirectory);
324
- } catch {
325
- return homeDirectory;
326
- }
327
- }
328
- function isUserHomeDirectory(directory) {
329
- if (projectDirectoryKey(directory) === projectDirectoryKey(userHomeDirectoryForIdentity()))
330
- return true;
331
- try {
332
- return projectDirectoryKey(realpathSync.native(path3.resolve(directory))) === projectDirectoryKey(canonicalUserHomeDirectory());
333
- } catch {
334
- return false;
335
- }
336
- }
337
- function assertProjectAllowed(directory, allowHomeProject) {
338
- const canonical = path3.resolve(directory);
339
- if (!allowHomeProject && (isUserHomeDirectory(directory) || isUserHomeDirectory(gitRootDirectory(canonical) ?? canonical))) {
340
- throw new ProjectIdentityError("home_project_disabled", directory, "Home project memory is disabled; set allow_home_project to opt in");
341
- }
342
- }
343
- function resolveProjectIdentity(directory, allowHomeProject = homeProjectPermission) {
344
- assertProjectAllowed(directory, allowHomeProject);
345
- const canonical = path3.resolve(directory);
346
- const cachedFallback = directoryFallbackCache.get(canonical);
347
- if (cachedFallback !== undefined) {
348
- if (!hasGitDir(canonical)) {
349
- return cachedFallback;
350
- }
351
- directoryFallbackCache.delete(canonical);
352
- }
353
- if (getActiveCooldown(canonical) !== undefined) {
354
- if (hasGitDir(canonical)) {
355
- const cachedGitIdentity = reuseLastKnownGitIdentity(canonical);
356
- if (cachedGitIdentity !== undefined) {
357
- return cachedGitIdentity;
358
- }
359
- throw new ProjectIdentityError("git_identity_unavailable", directory, "Git identity unavailable; memory features paused until the retry cooldown expires");
360
- }
361
- return rememberedIdentityOrDirectoryFallback(canonical);
362
- }
363
- try {
364
- return resolveProjectIdentityStrict(directory, allowHomeProject);
365
- } catch (error) {
366
- if (error instanceof ProjectIdentityError && shouldUseDirectoryFallback(error)) {
367
- if (error.errorClass === "no_commits")
368
- return directoryFallback(canonical);
369
- if (!hasGitDir(canonical)) {
370
- if (error.errorClass === "permission_denied")
371
- throw error;
372
- const resolved = rememberedIdentityOrDirectoryFallback(canonical);
373
- directoryFallbackCache.set(canonical, resolved);
374
- transientFailureCooldown.delete(canonical);
375
- return resolved;
376
- }
377
- transientFailureCooldown.set(canonical, nowMs() + TRANSIENT_FAILURE_COOLDOWN_MS);
378
- const cachedGitIdentity = reuseLastKnownGitIdentity(canonical);
379
- if (error.errorClass === "dubious_ownership")
380
- recordDubiousOwnershipFallback(canonical);
381
- if (cachedGitIdentity !== undefined) {
382
- return cachedGitIdentity;
383
- }
384
- throw error;
385
- }
386
- throw error;
387
- }
388
- }
389
- function resolveProjectIdentityOrFallback(directory, allowHomeProject = homeProjectPermission) {
390
- try {
391
- return resolveProjectIdentity(directory, allowHomeProject);
392
- } catch (error) {
393
- const canonical = path3.resolve(directory);
394
- if (hasGitDir(canonical) || error instanceof ProjectIdentityError && error.errorClass === "home_project_disabled")
395
- throw error;
396
- const fallback = rememberedIdentityOrDirectoryFallback(canonical);
397
- const message = error instanceof Error ? error.message : String(error);
398
- log(`[magic-context] project identity resolution failed for ${canonical}; using directory fallback ${fallback}: ${message}`);
399
- return fallback;
400
- }
401
- }
402
- function hasGitDir(canonical) {
403
- if (hasGitDirInAncestorChain(canonical)) {
404
- return true;
405
- }
406
- try {
407
- const realCanonical = realpathSync.native(canonical);
408
- return realCanonical !== canonical && hasGitDirInAncestorChain(realCanonical);
409
- } catch {
410
- return false;
411
- }
412
- }
413
- function gitRootInAncestorChain(startDirectory) {
414
- let current = startDirectory;
415
- while (true) {
416
- if (existsSync(path3.join(current, ".git"))) {
417
- try {
418
- return realpathSync.native(current);
419
- } catch {
420
- return path3.resolve(current);
421
- }
422
- }
423
- const parent = path3.dirname(current);
424
- if (parent === current) {
425
- return null;
426
- }
427
- current = parent;
428
- }
429
- }
430
- function hasGitDirInAncestorChain(startDirectory) {
431
- return gitRootInAncestorChain(startDirectory) !== null;
432
- }
433
- function gitRootDirectory(canonical) {
434
- const direct = gitRootInAncestorChain(canonical);
435
- if (direct)
436
- return direct;
437
- try {
438
- const realCanonical = realpathSync.native(canonical);
439
- return realCanonical === canonical ? null : gitRootInAncestorChain(realCanonical);
440
- } catch {
441
- return null;
442
- }
443
- }
444
- function directoryHasGitMetadata(directory) {
445
- return gitRootDirectory(path3.resolve(directory)) !== null;
446
- }
447
- function isUsableProjectIdentity(identity) {
448
- return typeof identity === "string" && identity.trim().length > 0;
449
- }
450
- function resolveProjectIdentityForSession(directory, allowHomeProject = homeProjectPermission) {
451
- const resolvedDirectory = path3.resolve(directory);
452
- const cacheKey = `${allowHomeProject ? "1" : "0"}\x00${resolvedDirectory}`;
453
- const cached = sessionIdentityCache.get(cacheKey);
454
- if (cached && (cached.revalidateAt === null || nowMs() < cached.revalidateAt) && !(cached.identity?.startsWith("dir:") && hasGitDir(resolvedDirectory))) {
455
- return cached.identity;
456
- }
457
- sessionIdentityCache.delete(cacheKey);
458
- filesystemProbeObserverForTests?.();
459
- const canonicalDirectory = (() => {
460
- try {
461
- filesystemProbeObserverForTests?.();
462
- return realpathSync.native(resolvedDirectory);
463
- } catch {
464
- return resolvedDirectory;
465
- }
466
- })();
467
- filesystemProbeObserverForTests?.();
468
- const homeRoot = gitRootDirectory(canonicalDirectory);
469
- const inheritsHomeRepository = homeRoot !== null && isUserHomeDirectory(homeRoot);
470
- let identity;
471
- if (!allowHomeProject && (isUserHomeDirectory(directory) || inheritsHomeRepository)) {
472
- identity = undefined;
473
- } else {
474
- try {
475
- identity = resolveProjectIdentityOrFallback(isUserHomeDirectory(directory) ? canonicalUserHomeDirectory() : directory, allowHomeProject);
476
- } catch (error) {
477
- if (!(error instanceof ProjectIdentityError))
478
- throw error;
479
- const reason = error.errorClass === "git_identity_unavailable" ? pausedIdentityReasons.get(resolvedDirectory) ?? error.errorClass : error.errorClass;
480
- pausedIdentityReasons.set(resolvedDirectory, reason);
481
- const logKey = `${resolvedDirectory}\x00${reason}`;
482
- if (!pausedIdentityLogged.has(logKey)) {
483
- pausedIdentityLogged.add(logKey);
484
- log(`[magic-context] memory features paused for ${resolvedDirectory}: ${reason}`);
485
- }
486
- identity = undefined;
487
- }
488
- }
489
- if (identity !== undefined)
490
- pausedIdentityReasons.delete(resolvedDirectory);
491
- sessionIdentityCache.set(cacheKey, {
492
- identity,
493
- revalidateAt: identity?.startsWith("git:") === true ? null : nowMs() + TRANSIENT_FAILURE_COOLDOWN_MS
494
- });
495
- return identity;
496
- }
497
- function normalizeStoredProjectPath(rawOrStored) {
498
- if (rawOrStored.startsWith("git:") || rawOrStored.startsWith("dir:")) {
499
- return rawOrStored;
500
- }
501
- try {
502
- return resolveProjectIdentity(rawOrStored);
503
- } catch {
504
- return rawOrStored;
505
- }
506
- }
507
- function storedPathBelongsToIdentity(storedProjectPath, projectIdentity) {
508
- return storedProjectPath === projectIdentity || normalizeStoredProjectPath(storedProjectPath) === projectIdentity;
509
- }
26
+ } from "./index-0vrkp1jq.js";
510
27
 
511
28
  // ../plugin/src/features/magic-context/migrations.ts
512
29
  import { isMainThread } from "node:worker_threads";
513
30
 
514
- // ../plugin/src/features/magic-context/memory/constants.ts
515
- var V2_MEMORY_CATEGORIES = [
516
- "PROJECT_RULES",
517
- "ARCHITECTURE",
518
- "CONSTRAINTS",
519
- "CONFIG_VALUES",
520
- "NAMING"
521
- ];
522
- var PROMOTABLE_CATEGORIES = [
523
- ...V2_MEMORY_CATEGORIES,
524
- "ARCHITECTURE_DECISIONS",
525
- "CONFIG_DEFAULTS",
526
- "USER_PREFERENCES",
527
- "USER_DIRECTIVES",
528
- "ENVIRONMENT",
529
- "WORKFLOW_RULES",
530
- "KNOWN_ISSUES"
531
- ];
532
- var CATEGORY_PRIORITY = [
533
- ...V2_MEMORY_CATEGORIES,
534
- "USER_DIRECTIVES",
535
- "USER_PREFERENCES",
536
- "CONFIG_DEFAULTS",
537
- "ARCHITECTURE_DECISIONS",
538
- "ENVIRONMENT",
539
- "WORKFLOW_RULES",
540
- "KNOWN_ISSUES"
541
- ];
542
- var MEMORY_CATEGORY_ORDER_UNKNOWN = 99;
543
- var MEMORY_CATEGORY_ORDER_PRIORITY = CATEGORY_PRIORITY.reduce((acc, category, index) => {
544
- acc[category] = index;
545
- return acc;
546
- }, {});
547
- var MEMORY_CATEGORY_ORDER_SQL = `CASE category ${CATEGORY_PRIORITY.map((category, index) => `WHEN '${category}' THEN ${index}`).join(" ")} ELSE ${MEMORY_CATEGORY_ORDER_UNKNOWN} END`;
548
- function getMemoryCategoryOrder(category) {
549
- return MEMORY_CATEGORY_ORDER_PRIORITY[category] ?? MEMORY_CATEGORY_ORDER_UNKNOWN;
550
- }
551
- var CATEGORY_DEFAULT_TTL = {
552
- WORKFLOW_RULES: 90 * 24 * 60 * 60 * 1000,
553
- KNOWN_ISSUES: 30 * 24 * 60 * 60 * 1000
554
- };
555
-
556
31
  // ../plugin/src/shared/xml-unescape.ts
557
32
  var XML_ENTITY_REGEX = /&(amp|apos|quot|lt|gt);/g;
558
33
  var XML_ENTITIES = {
@@ -762,7 +237,7 @@ function parseCompartmentOutput(text) {
762
237
  continue;
763
238
  droppedFactBlocks++;
764
239
  droppedFacts += items.length;
765
- log(`[historian] Dropped <facts> category ${category} (${items.length} facts)`);
240
+ log2(`[historian] Dropped <facts> category ${category} (${items.length} facts)`);
766
241
  continue;
767
242
  }
768
243
  for (const content of items)
@@ -846,7 +321,7 @@ function parseEvents(text) {
846
321
  }
847
322
 
848
323
  // ../plugin/src/features/magic-context/lkg-prefix-chunks.ts
849
- import { createHash as createHash3 } from "node:crypto";
324
+ import { createHash } from "node:crypto";
850
325
  var LKG_PREFIX_CHUNK_CHARS = 64 * 1024;
851
326
  function splitLkgPrefix(jsonPrefix) {
852
327
  const chunks = [];
@@ -864,10 +339,10 @@ function splitLkgPrefix(jsonPrefix) {
864
339
  return chunks;
865
340
  }
866
341
  function hashLkgChunk(body) {
867
- return createHash3("sha256").update(body).digest("hex");
342
+ return createHash("sha256").update(body).digest("hex");
868
343
  }
869
344
  function hashLkgChunkList(chunkHashes) {
870
- return createHash3("sha256").update(chunkHashes.join(`
345
+ return createHash("sha256").update(chunkHashes.join(`
871
346
  `)).digest("hex");
872
347
  }
873
348
  function layoutLkgPrefix(jsonPrefix) {
@@ -1111,7 +586,7 @@ function collectCandidateSessions(db, shapes) {
1111
586
  return [...sessions].sort();
1112
587
  }
1113
588
  function openEvidenceStore(path) {
1114
- const store = new Database(path, { readonly: true, fileMustExist: true });
589
+ const store = new Database2(path, { readonly: true, fileMustExist: true });
1115
590
  try {
1116
591
  const hasV1Messages = tableExists2(store, "message");
1117
592
  const hasV1Session = tableExists2(store, "session");
@@ -1222,13 +697,13 @@ function repairOpenCode2HarnessLabels(db, options) {
1222
697
  reason = "store_schema_unknown";
1223
698
  } catch (error) {
1224
699
  reason = "store_unreadable";
1225
- log(`[migration] OpenCode session database at ${resolution.path} could not be read: ${error instanceof Error ? error.message : String(error)}`);
700
+ log2(`[migration] OpenCode session database at ${resolution.path} could not be read: ${error instanceof Error ? error.message : String(error)}`);
1226
701
  }
1227
702
  }
1228
703
  if (!evidence || reason !== null) {
1229
704
  evidence?.close();
1230
705
  writeUnresolvedState(db, reason ?? "store_not_found", resolution, candidateSessionIds);
1231
- log(`[migration] OpenCode harness labels left unverified for ${candidateSessionIds.length} session(s): ` + `no readable OpenCode session database (${reason ?? "store_not_found"}) at ${resolution.path}. ` + "Nothing was relabelled; `magic-context doctor` reports the affected sessions.");
706
+ log2(`[migration] OpenCode harness labels left unverified for ${candidateSessionIds.length} session(s): ` + `no readable OpenCode session database (${reason ?? "store_not_found"}) at ${resolution.path}. ` + "Nothing was relabelled; `magic-context doctor` reports the affected sessions.");
1232
707
  return {
1233
708
  status: "unresolved",
1234
709
  reason: reason ?? "store_not_found",
@@ -1262,7 +737,7 @@ function repairOpenCode2HarnessLabels(db, options) {
1262
737
  clearUnresolvedState(db);
1263
738
  if (relabelledSessions.length > 0) {
1264
739
  const toOpenCode2 = relabelledSessions.filter((entry) => entry.harness === "opencode2").length;
1265
- log(`[migration] OpenCode harness labels repaired from ${resolution.path}: ` + `${toOpenCode2} session(s) restored to opencode2, ` + `${relabelledSessions.length - toOpenCode2} session(s) set to opencode.`);
740
+ log2(`[migration] OpenCode harness labels repaired from ${resolution.path}: ` + `${toOpenCode2} session(s) restored to opencode2, ` + `${relabelledSessions.length - toOpenCode2} session(s) set to opencode.`);
1266
741
  }
1267
742
  return {
1268
743
  status: "resolved",
@@ -1354,7 +829,7 @@ function installCompartmentHistoryVersions(db) {
1354
829
  }
1355
830
 
1356
831
  // ../plugin/src/features/magic-context/workspaces.ts
1357
- import { createHash as createHash4 } from "node:crypto";
832
+ import { createHash as createHash2 } from "node:crypto";
1358
833
  var VALID_SHARE_CATEGORIES = new Set(V2_MEMORY_CATEGORIES);
1359
834
  var DEFAULT_WORKSPACE_SHARE_CATEGORIES = ["CONSTRAINTS"];
1360
835
  function tableExists3(db, tableName) {
@@ -1375,7 +850,7 @@ function defaultWorkspaceShareCategories() {
1375
850
  return [...DEFAULT_WORKSPACE_SHARE_CATEGORIES];
1376
851
  }
1377
852
  function warnInvalidShareCategories(reason, raw) {
1378
- log("[magic-context] WARN: invalid workspace share_categories; sharing no foreign memory categories", {
853
+ log2("[magic-context] WARN: invalid workspace share_categories; sharing no foreign memory categories", {
1379
854
  reason,
1380
855
  raw
1381
856
  });
@@ -1422,7 +897,7 @@ function selectWorkspaceShareCategories(db, identities) {
1422
897
  if (!hasMembership)
1423
898
  return null;
1424
899
  if (!tableExists3(db, "workspaces")) {
1425
- log("[magic-context] WARN: workspace member has no workspaces table; sharing no foreign memory categories");
900
+ log2("[magic-context] WARN: workspace member has no workspaces table; sharing no foreign memory categories");
1426
901
  return [];
1427
902
  }
1428
903
  if (!columnExists2(db, "workspaces", "share_categories")) {
@@ -1435,7 +910,7 @@ function selectWorkspaceShareCategories(db, identities) {
1435
910
  ORDER BY workspace.id ASC
1436
911
  LIMIT 1`).get(...candidates);
1437
912
  if (!row) {
1438
- log("[magic-context] WARN: workspace member has no workspace share_categories row; sharing no foreign memory categories");
913
+ log2("[magic-context] WARN: workspace member has no workspace share_categories row; sharing no foreign memory categories");
1439
914
  return [];
1440
915
  }
1441
916
  return normalizeShareCategories(row.shareCategories);
@@ -1540,7 +1015,7 @@ function computeWorkspaceEpochFingerprint(db, identities) {
1540
1015
  const canonical = uniqueSorted(identities.filter((identity) => identity.length > 0));
1541
1016
  const epochs = getEpochMap(db, canonical);
1542
1017
  const shareCategories = selectWorkspaceShareCategories(db, canonical);
1543
- const hash = createHash4("sha256");
1018
+ const hash = createHash2("sha256");
1544
1019
  hash.update("share_categories", "utf8");
1545
1020
  hash.update("\x00");
1546
1021
  hash.update(shareCategories === null ? "NO_WORKSPACE" : JSON.stringify(shareCategories), "utf8");
@@ -2023,10 +1498,10 @@ var MIGRATIONS = [
2023
1498
  const hasTable = (name) => Boolean(db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name = ?").get(name));
2024
1499
  const memoryEmbeddings = hasTable("memory_embeddings") ? db.prepare(`DELETE FROM memory_embeddings
2025
1500
  WHERE memory_id NOT IN (SELECT id FROM memories)`).run().changes : 0;
2026
- log(`[migrations] v12 cleaned ${memoryEmbeddings} orphan memory_embeddings row(s)`);
1501
+ log2(`[migrations] v12 cleaned ${memoryEmbeddings} orphan memory_embeddings row(s)`);
2027
1502
  const gitCommitEmbeddings = hasTable("git_commit_embeddings") ? db.prepare(`DELETE FROM git_commit_embeddings
2028
1503
  WHERE sha NOT IN (SELECT sha FROM git_commits)`).run().changes : 0;
2029
- log(`[migrations] v12 cleaned ${gitCommitEmbeddings} orphan git_commit_embeddings row(s)`);
1504
+ log2(`[migrations] v12 cleaned ${gitCommitEmbeddings} orphan git_commit_embeddings row(s)`);
2030
1505
  }
2031
1506
  },
2032
1507
  {
@@ -4043,7 +3518,7 @@ function runMigrations(db) {
4043
3518
  return false;
4044
3519
  if (!loggedPlan) {
4045
3520
  const pendingCount = MIGRATIONS.filter((candidate) => candidate.version > currentVersion && !isMigrationApplied(db, candidate.version)).length;
4046
- log(`[migrations] current upstream migration lane: ${currentVersion}, applying ${pendingCount} migration(s)`);
3521
+ log2(`[migrations] current upstream migration lane: ${currentVersion}, applying ${pendingCount} migration(s)`);
4047
3522
  loggedPlan = true;
4048
3523
  }
4049
3524
  if (isMainThread)
@@ -4058,13 +3533,13 @@ function runMigrations(db) {
4058
3533
  break;
4059
3534
  if (migration.version <= 61)
4060
3535
  touchedLegacyAuthorityBatch = true;
4061
- log(`[migrations] applied v${migration.version}: ${migration.description}`);
3536
+ log2(`[migrations] applied v${migration.version}: ${migration.description}`);
4062
3537
  } catch (error) {
4063
3538
  if (!migration && isSqliteLockError(error)) {
4064
3539
  throw new MigrationLockBusyError(`failed to acquire migration write lock: ${error instanceof Error ? error.message : String(error)}`);
4065
3540
  }
4066
3541
  if (migration && isSiblingMigrationConflict(db, error, migration.version)) {
4067
- log(`[migrations] v${migration.version} already applied by sibling instance — resuming with re-read version`);
3542
+ log2(`[migrations] v${migration.version} already applied by sibling instance — resuming with re-read version`);
4068
3543
  const reReadVersion = getCurrentVersion(db);
4069
3544
  if (reReadVersion > currentVersion)
4070
3545
  continue;
@@ -4072,7 +3547,7 @@ function runMigrations(db) {
4072
3547
  }
4073
3548
  const version = migration?.version ?? currentVersion + 1;
4074
3549
  const description = migration?.description ?? "acquire migration write lock";
4075
- log(`[migrations] FAILED v${version}: ${description} — ${error instanceof Error ? error.message : String(error)}`);
3550
+ log2(`[migrations] FAILED v${version}: ${description} — ${error instanceof Error ? error.message : String(error)}`);
4076
3551
  throw new Error(`Migration v${version} failed: ${error instanceof Error ? error.message : String(error)}. Database may need manual repair.`);
4077
3552
  }
4078
3553
  }
@@ -4089,7 +3564,7 @@ function runMigrations(db) {
4089
3564
  }
4090
3565
  }
4091
3566
  if (loggedPlan) {
4092
- log(`[migrations] upstream migration lane now: ${MIGRATIONS[MIGRATIONS.length - 1].version}`);
3567
+ log2(`[migrations] upstream migration lane now: ${MIGRATIONS[MIGRATIONS.length - 1].version}`);
4093
3568
  }
4094
3569
  }
4095
3570
  async function runMigrationsWithRetry(db, options = {}) {
@@ -4097,7 +3572,7 @@ async function runMigrationsWithRetry(db, options = {}) {
4097
3572
  const sleep = options.sleep ?? ((delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs)));
4098
3573
  const totalAttempts = retryDelaysMs.length + 1;
4099
3574
  for (let attempt = 1;attempt <= totalAttempts; attempt += 1) {
4100
- log(`[migrations] migration lock check attempt ${attempt}/${totalAttempts}`);
3575
+ log2(`[migrations] migration lock check attempt ${attempt}/${totalAttempts}`);
4101
3576
  try {
4102
3577
  runMigrations(db);
4103
3578
  return;
@@ -4107,188 +3582,10 @@ async function runMigrationsWithRetry(db, options = {}) {
4107
3582
  const delayMs = retryDelaysMs[attempt - 1];
4108
3583
  if (delayMs === undefined)
4109
3584
  throw error;
4110
- log(`[migrations] migration write lock is busy; retrying attempt ${attempt + 1}/${totalAttempts} in ${delayMs}ms`);
3585
+ log2(`[migrations] migration write lock is busy; retrying attempt ${attempt + 1}/${totalAttempts} in ${delayMs}ms`);
4111
3586
  await sleep(delayMs);
4112
3587
  }
4113
3588
  }
4114
3589
  }
4115
3590
 
4116
- // ../plugin/src/plugin/boot-quiet.ts
4117
- var BOOT_QUIET_MS = 120000;
4118
- var bootQuietUntilMs = 0;
4119
- function beginBootQuietPeriod(now = Date.now()) {
4120
- if (bootQuietUntilMs === 0)
4121
- bootQuietUntilMs = now + BOOT_QUIET_MS;
4122
- }
4123
- function bootQuietRemainingMs(now = Date.now()) {
4124
- return Math.max(0, bootQuietUntilMs - now);
4125
- }
4126
- function scheduleAfterBootQuiet(task, additionalDelayMs = 0) {
4127
- const timer = setTimeout(task, bootQuietRemainingMs() + Math.max(0, additionalDelayMs));
4128
- timer.unref?.();
4129
- return timer;
4130
- }
4131
-
4132
- // ../plugin/src/features/magic-context/message-fts-rowid-map.ts
4133
- import { createHash as createHash5 } from "node:crypto";
4134
- var MESSAGE_FTS_ROWID_MAP_BACKFILL_BATCH_SIZE = 100;
4135
- var BACKFILL_STATE_ID = 1;
4136
- var EMPTY_INDEX_CONTENT_HASH = createHash5("sha256").update("").digest("hex");
4137
- var upsertMapStatements = new WeakMap;
4138
- var rangeReadyStatements = new WeakMap;
4139
- var updateTimeStatements = new WeakMap;
4140
- var activeBackfills = new WeakMap;
4141
- function getUpsertMapStatement(db) {
4142
- let statement = upsertMapStatements.get(db);
4143
- if (!statement) {
4144
- statement = db.prepare(`INSERT INTO message_fts_rowid_map
4145
- (session_id, message_ordinal, fts_rowid, message_time_ms)
4146
- VALUES (?, ?, ?, ?)
4147
- ON CONFLICT(session_id, message_ordinal) DO UPDATE SET
4148
- fts_rowid = excluded.fts_rowid,
4149
- message_time_ms = COALESCE(
4150
- excluded.message_time_ms,
4151
- message_fts_rowid_map.message_time_ms
4152
- )`);
4153
- upsertMapStatements.set(db, statement);
4154
- }
4155
- return statement;
4156
- }
4157
- function getBackfillState(db) {
4158
- const row = db.prepare(`SELECT watermark_rowid AS watermarkRowid, completed
4159
- FROM message_fts_rowid_map_backfill_state
4160
- WHERE id = ?`).get(BACKFILL_STATE_ID);
4161
- return {
4162
- processed: 0,
4163
- watermarkRowid: typeof row?.watermarkRowid === "number" && Number.isSafeInteger(row.watermarkRowid) ? row.watermarkRowid : 0,
4164
- completed: row?.completed === 1
4165
- };
4166
- }
4167
- function recordMessageFtsRowid(db, sessionId, messageOrdinal, ftsRowid, messageTimeMs = null) {
4168
- const numericRowid = Number(ftsRowid);
4169
- if (!Number.isSafeInteger(numericRowid) || numericRowid <= 0) {
4170
- throw new Error(`invalid message FTS rowid: ${String(ftsRowid)}`);
4171
- }
4172
- const normalizedTime = typeof messageTimeMs === "number" && Number.isSafeInteger(messageTimeMs) && messageTimeMs >= 0 ? messageTimeMs : null;
4173
- getUpsertMapStatement(db).run(sessionId, messageOrdinal, numericRowid, normalizedTime);
4174
- }
4175
- function recordIndexedMessageTime(db, sessionId, messageOrdinal, messageTimeMs) {
4176
- if (typeof messageTimeMs !== "number" || !Number.isSafeInteger(messageTimeMs) || messageTimeMs < 0) {
4177
- return;
4178
- }
4179
- let statement = updateTimeStatements.get(db);
4180
- if (!statement) {
4181
- statement = db.prepare(`UPDATE message_fts_rowid_map
4182
- SET message_time_ms = ?
4183
- WHERE session_id = ? AND message_ordinal = ?
4184
- AND message_time_ms IS NULL`);
4185
- updateTimeStatements.set(db, statement);
4186
- }
4187
- statement.run(messageTimeMs, sessionId, messageOrdinal);
4188
- }
4189
- function backfillMessageFtsRowidMapBatch(db, batchSize = MESSAGE_FTS_ROWID_MAP_BACKFILL_BATCH_SIZE) {
4190
- const boundedBatchSize = Number.isFinite(batchSize) ? Math.min(MESSAGE_FTS_ROWID_MAP_BACKFILL_BATCH_SIZE, Math.max(1, Math.floor(batchSize))) : MESSAGE_FTS_ROWID_MAP_BACKFILL_BATCH_SIZE;
4191
- let progress = {
4192
- processed: 0,
4193
- watermarkRowid: 0,
4194
- completed: false
4195
- };
4196
- let transactionStartedAt = 0;
4197
- db.transaction(() => {
4198
- transactionStartedAt = performance.now();
4199
- db.prepare(`INSERT OR IGNORE INTO message_fts_rowid_map_backfill_state
4200
- (id, watermark_rowid, completed) VALUES (?, 0, 0)`).run(BACKFILL_STATE_ID);
4201
- const state = getBackfillState(db);
4202
- if (state.completed) {
4203
- progress = state;
4204
- return;
4205
- }
4206
- const rows = db.prepare(`SELECT rowid AS ftsRowid,
4207
- session_id AS sessionId, message_ordinal AS messageOrdinal
4208
- FROM message_history_fts WHERE rowid > ? ORDER BY rowid ASC LIMIT ?`).all(state.watermarkRowid, boundedBatchSize);
4209
- let watermarkRowid = state.watermarkRowid;
4210
- for (const row of rows) {
4211
- const ftsRowid = Number(row.ftsRowid);
4212
- const messageOrdinal = Number(row.messageOrdinal);
4213
- if (Number.isSafeInteger(ftsRowid) && ftsRowid > watermarkRowid) {
4214
- watermarkRowid = ftsRowid;
4215
- }
4216
- if (typeof row.sessionId === "string" && Number.isSafeInteger(messageOrdinal) && messageOrdinal >= 0 && Number.isSafeInteger(ftsRowid) && ftsRowid > 0) {
4217
- recordMessageFtsRowid(db, row.sessionId, messageOrdinal, ftsRowid);
4218
- }
4219
- }
4220
- const completed = rows.length < boundedBatchSize;
4221
- db.prepare(`UPDATE message_fts_rowid_map_backfill_state
4222
- SET watermark_rowid = ?, completed = ?, updated_at = ?
4223
- WHERE id = ?`).run(watermarkRowid, completed ? 1 : 0, Date.now(), BACKFILL_STATE_ID);
4224
- progress = {
4225
- processed: rows.length,
4226
- watermarkRowid,
4227
- completed
4228
- };
4229
- }).immediate();
4230
- logSlowWriteTransaction("message_fts_rowid_backfill", transactionStartedAt);
4231
- return progress;
4232
- }
4233
- async function runMessageFtsRowidMapBackfill(db) {
4234
- await new Promise((resolve) => setTimeout(resolve, 0));
4235
- for (;; ) {
4236
- const progress = backfillMessageFtsRowidMapBatch(db);
4237
- if (progress.completed)
4238
- return;
4239
- await new Promise((resolve) => setTimeout(resolve, 0));
4240
- }
4241
- }
4242
- function startMessageFtsRowidMapBackfill(db) {
4243
- const active = activeBackfills.get(db);
4244
- if (active)
4245
- return active;
4246
- const run = withoutSqliteTransformPass(() => withSqliteBackgroundWriter(() => runMessageFtsRowidMapBackfill(db))).finally(() => {
4247
- activeBackfills.delete(db);
4248
- });
4249
- activeBackfills.set(db, run);
4250
- return run;
4251
- }
4252
- function messageFtsOrdinalRangeIsMapped(db, sessionId, startOrdinal, endOrdinal) {
4253
- if (endOrdinal < startOrdinal)
4254
- return true;
4255
- if (getBackfillState(db).completed)
4256
- return true;
4257
- let statement = rangeReadyStatements.get(db);
4258
- if (!statement) {
4259
- statement = db.prepare(`SELECT COUNT(DISTINCT source.message_ordinal) AS sourceOrdinalCount,
4260
- COUNT(DISTINCT CASE
4261
- WHEN source.role IN ('user', 'assistant')
4262
- AND source.normalized_content_hash != ?
4263
- THEN source.message_ordinal
4264
- END) AS expectedMapCount,
4265
- COUNT(DISTINCT CASE
4266
- WHEN source.role IN ('user', 'assistant')
4267
- AND source.normalized_content_hash != ?
4268
- AND map.fts_rowid IS NOT NULL
4269
- THEN source.message_ordinal
4270
- END) AS mappedCount
4271
- FROM message_history_source AS source
4272
- LEFT JOIN message_fts_rowid_map AS map
4273
- ON map.session_id = source.session_id
4274
- AND map.message_ordinal = source.message_ordinal
4275
- WHERE source.session_id = ?
4276
- AND source.message_ordinal BETWEEN ? AND ?`);
4277
- rangeReadyStatements.set(db, statement);
4278
- }
4279
- const row = statement.get(EMPTY_INDEX_CONTENT_HASH, EMPTY_INDEX_CONTENT_HASH, sessionId, startOrdinal, endOrdinal);
4280
- const ordinalCount = endOrdinal - startOrdinal + 1;
4281
- return row?.sourceOrdinalCount === ordinalCount && row.expectedMapCount === row.mappedCount;
4282
- }
4283
- function deleteUnmappedMessageFtsRows(db, sessionIds) {
4284
- if (sessionIds.length === 0)
4285
- return;
4286
- const state = getBackfillState(db);
4287
- if (state.completed)
4288
- return;
4289
- const placeholders = sessionIds.map(() => "?").join(", ");
4290
- db.prepare(`DELETE FROM message_history_fts
4291
- WHERE rowid > ? AND session_id IN (${placeholders})`).run(state.watermarkRowid, ...sessionIds);
4292
- }
4293
-
4294
- export { setHomeProjectPermission, ProjectIdentityError, resolveProjectIdentityStrict, isUserHomeDirectory, resolveProjectIdentity, directoryHasGitMetadata, isUsableProjectIdentity, resolveProjectIdentityForSession, normalizeStoredProjectPath, storedPathBelongsToIdentity, recordMessageFtsRowid, recordIndexedMessageTime, startMessageFtsRowidMapBackfill, messageFtsOrdinalRangeIsMapped, deleteUnmappedMessageFtsRows, V2_MEMORY_CATEGORIES, PROMOTABLE_CATEGORIES, CATEGORY_PRIORITY, getMemoryCategoryOrder, CATEGORY_DEFAULT_TTL, unescapeXml, parseCompartmentOutput, layoutLkgPrefix, assembleLkgPrefix, LKG_SLOT_CHUNKS_DDL, SESSION_REPLAY_DECISIONS_DDL, LKG_SLOTS_DDL, installCompartmentHistoryVersions, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, resolveStoredPathWorkspaceIdentity, storedPathBelongsToWorkspace, sourceNameForMemory, computeWorkspaceEpochFingerprint, FORK_MIGRATION_VERSION_FLOOR, managedAuthorityNoteRow, hasPendingMigrations, getMainThreadMigrationBodyCount, runMigrations, runMigrationsWithRetry, beginBootQuietPeriod, bootQuietRemainingMs, scheduleAfterBootQuiet };
3591
+ export { unescapeXml, parseCompartmentOutput, layoutLkgPrefix, assembleLkgPrefix, LKG_SLOT_CHUNKS_DDL, SESSION_REPLAY_DECISIONS_DDL, LKG_SLOTS_DDL, installCompartmentHistoryVersions, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, resolveStoredPathWorkspaceIdentity, storedPathBelongsToWorkspace, sourceNameForMemory, computeWorkspaceEpochFingerprint, FORK_MIGRATION_VERSION_FLOOR, managedAuthorityNoteRow, hasPendingMigrations, getMainThreadMigrationBodyCount, runMigrations, runMigrationsWithRetry };