@cortexkit/pi-magic-context 0.49.71 → 0.49.73

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 (30) hide show
  1. package/dist/auto-search-worker.js +3 -3
  2. package/dist/chunk-embedding-write-worker.js +1 -1
  3. package/dist/{embedding-backfill-3g3cm51d.js → embedding-backfill-p0qszhx7.js} +2 -2
  4. package/dist/{index-73fw4cd4.js → index-6gwasf0v.js} +17 -3
  5. package/dist/{index-bcwy4wm1.js → index-6t4m64m1.js} +8 -8
  6. package/dist/{index-sg6tdkqh.js → index-9a92hc6c.js} +1 -1
  7. package/dist/{index-2kb65n0s.js → index-apff8dej.js} +1 -1
  8. package/dist/{index-2bavnrw8.js → index-cevw58nn.js} +99 -8
  9. package/dist/{index-4dqwxb7k.js → index-cyzsn2hb.js} +1 -1
  10. package/dist/{index-d7yx4ymd.js → index-mm9y1m77.js} +1 -1
  11. package/dist/{index-zgj2mxrn.js → index-mtpsqxev.js} +3 -3
  12. package/dist/{index-tcrd11cb.js → index-tygcydj7.js} +26 -4
  13. package/dist/index-w2snpk0j.js +65 -0
  14. package/dist/{index-51xr6g7s.js → index-wmkkxwvf.js} +1 -1
  15. package/dist/{index-e9wkbh8y.js → index-yk0ve8hn.js} +4 -3
  16. package/dist/index.js +75 -44
  17. package/dist/{message-index-bounded-fqeqp76p.js → message-index-bounded-cv87994v.js} +3 -3
  18. package/dist/migration-worker.js +1 -1
  19. package/dist/{project-embedding-registry-63wsm3a8.js → project-embedding-registry-2natnvdf.js} +1 -1
  20. package/dist/raw-ordinal-warmup-worker.js +4 -4
  21. package/dist/{read-session-chunk-tjj2wzxs.js → read-session-chunk-ygwyfvtr.js} +2 -2
  22. package/dist/{render-793jtz3r.js → render-cm4572er.js} +5 -5
  23. package/dist/{search-archive-gmyvkadj.js → search-archive-8kcsmnzt.js} +4 -4
  24. package/dist/{search-7tpgsnbs.js → search-hm8dc1e8.js} +6 -6
  25. package/dist/{storage-tags-wq8p5wrh.js → storage-tags-zzttnzn6.js} +1 -1
  26. package/dist/subagent-entry.js +11 -11
  27. package/dist/tag-snapshot-worker-pi.js +3 -3
  28. package/dist/{v2-archive-reader-99stcer0.js → v2-archive-reader-ycw2nxf1.js} +1 -1
  29. package/package.json +1 -1
  30. package/dist/index-qdy49kwk.js +0 -155
@@ -27,11 +27,11 @@ serveWorkerJobs(async (initial, port) => {
27
27
  { Database, registerSqliteDiagnosticSink },
28
28
  { log }
29
29
  ] = await Promise.all([
30
- import("./embedding-backfill-3g3cm51d.js"),
30
+ import("./embedding-backfill-p0qszhx7.js"),
31
31
  import("./embedding-cache-7rp4gqzr.js"),
32
32
  import("./storage-memory-0ndn65fm.js"),
33
- import("./project-embedding-registry-63wsm3a8.js"),
34
- import("./search-7tpgsnbs.js"),
33
+ import("./project-embedding-registry-2natnvdf.js"),
34
+ import("./search-hm8dc1e8.js"),
35
35
  import("./compartment-chunk-embedding-avkyp2df.js"),
36
36
  import("./embedding-activity-ew6dshfd.js"),
37
37
  import("./harness-9872e0ym.js"),
@@ -35,7 +35,7 @@ import"./index-453s1hj6.js";
35
35
  import {
36
36
  LATEST_SUPPORTED_VERSION,
37
37
  enforceSchemaFence
38
- } from "./index-sg6tdkqh.js";
38
+ } from "./index-9a92hc6c.js";
39
39
  import"./index-3bb24eb6.js";
40
40
  import"./index-gavj3e6h.js";
41
41
  import"./index-jhmz9tgv.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  ensureMemoryEmbeddings2
3
- } from "./index-qdy49kwk.js";
4
- import"./index-e9wkbh8y.js";
3
+ } from "./index-w2snpk0j.js";
4
+ import"./index-yk0ve8hn.js";
5
5
  import"./index-9p40dgkm.js";
6
6
  import"./index-hgd00nas.js";
7
7
  import"./index-yhzhdp3m.js";
@@ -2770,16 +2770,30 @@ function isAnthropicFamilyRoute(providerID, modelID) {
2770
2770
  var REMOVED_REASONING_MARK = Symbol.for("magic-context.removed-reasoning");
2771
2771
  var NEUTRALIZED_ORIGINALS = new WeakMap;
2772
2772
  var VARIANT_CACHE_PRESERVING_MODELS = {
2773
- "anthropic/claude-fable-5-1": "2026-09-02",
2774
- "openai/gpt-6-astra": "2026-09-05",
2775
- "anthropic/claude-opus-5-5": "2026-09-23"
2773
+ "anthropic/claude-fable-5-1": ["2026-09-02"],
2774
+ "openai/gpt-6-astra": ["2026-09-05"],
2775
+ "anthropic/claude-opus-5-5": ["2026-09-23", true],
2776
+ "anthropic/claude-sonnet-5-5": ["2026-11-23", true],
2777
+ "anthropic/claude-haiku-5-5": ["2026-11-23", true],
2778
+ "anthropic/claude-fable-5-2": ["2026-11-23", true],
2779
+ "anthropic/claude-mythos-5-1": ["2026-11-23", true],
2780
+ "anthropic/claude-mythos-5-2": ["2026-11-23", true]
2776
2781
  };
2782
+ var CLAUDE_VARIANT_ALIAS = /^(?:(?:[a-z0-9-]+\.)?anthropic\.)?(?:claude-)?([a-z]+)[-_.]?([0-9]+)[-_.]([0-9]+)(?:[-@][0-9]{8})?(?:-v[0-9]+:[0-9]+)?$/i;
2777
2783
  function canonicalVariantModelIdentity(providerID, modelID) {
2778
2784
  const normalizedProviderID = providerID.toLowerCase();
2779
2785
  const isAnthropicFamily = normalizedProviderID === "anthropic" || normalizedProviderID === "google-vertex-anthropic" || normalizedProviderID.includes("bedrock");
2780
2786
  if (isAnthropicFamily && isFable51ThinkingBindingModel("anthropic", modelID)) {
2781
2787
  return "anthropic/claude-fable-5-1";
2782
2788
  }
2789
+ if (isAnthropicFamily) {
2790
+ const alias = CLAUDE_VARIANT_ALIAS.exec(modelID.split("/").at(-1) ?? "");
2791
+ if (alias) {
2792
+ const identity = `anthropic/claude-${alias[1].toLowerCase()}-${alias[2]}-${alias[3]}`;
2793
+ if (VARIANT_CACHE_PRESERVING_MODELS[identity]?.[1])
2794
+ return identity;
2795
+ }
2796
+ }
2783
2797
  return canonicalModelIdentity(`${providerID}/${modelID}`).toLowerCase();
2784
2798
  }
2785
2799
  function variantChangeBustsProviderCache(providerID, modelID) {
@@ -56,7 +56,7 @@ import {
56
56
  import {
57
57
  piHarnessKindFromExecutable,
58
58
  getErrorMessage
59
- } from "./index-sg6tdkqh.js";
59
+ } from "./index-9a92hc6c.js";
60
60
  import {
61
61
  getOrCreateSessionMeta,
62
62
  updateSessionMeta,
@@ -70,10 +70,10 @@ import {
70
70
  renderMessageByOrdinal2,
71
71
  renderVerboseRange2,
72
72
  renderItemByTag2
73
- } from "./index-tcrd11cb.js";
73
+ } from "./index-tygcydj7.js";
74
74
  import {
75
75
  getLastIndexedOrdinal
76
- } from "./index-d7yx4ymd.js";
76
+ } from "./index-mm9y1m77.js";
77
77
  import {
78
78
  TODO_STATUSES,
79
79
  TODO_PRIORITIES,
@@ -89,7 +89,7 @@ import {
89
89
  getCompactionMarkerPublicationState,
90
90
  compareAndSetCompactionMarkerPublicationState,
91
91
  getDeferredClearedCompactionMarkerState
92
- } from "./index-73fw4cd4.js";
92
+ } from "./index-6gwasf0v.js";
93
93
  import {
94
94
  stableStringify,
95
95
  BoundedSessionMap
@@ -129,7 +129,7 @@ import {
129
129
  unregisterProjectEmbedding2,
130
130
  getProjectEmbeddingSnapshot2,
131
131
  embedTextForProject2
132
- } from "./index-e9wkbh8y.js";
132
+ } from "./index-yk0ve8hn.js";
133
133
  import {
134
134
  directoryHasGitMetadata,
135
135
  resolveProjectIdentityForSession,
@@ -142,7 +142,7 @@ import {
142
142
  resolveMemoriesByIdsForSearch2,
143
143
  unifiedSearch2,
144
144
  formatSearchResults2
145
- } from "./index-2bavnrw8.js";
145
+ } from "./index-cevw58nn.js";
146
146
  import {
147
147
  resolveOpenCodeDbPath,
148
148
  assertOpenCodeStoreGeneration
@@ -151,7 +151,7 @@ import {
151
151
  hasRawMessageProvider2,
152
152
  setRawMessageProvider2,
153
153
  readSessionChunk2
154
- } from "./index-2kb65n0s.js";
154
+ } from "./index-apff8dej.js";
155
155
  import {
156
156
  resolveWorkspaceShareCategories,
157
157
  resolveWorkspaceIdentitySet,
@@ -184,7 +184,7 @@ import {
184
184
  } from "./index-3s39a1md.js";
185
185
  import {
186
186
  renderSearchArchive2
187
- } from "./index-4dqwxb7k.js";
187
+ } from "./index-cyzsn2hb.js";
188
188
  import {
189
189
  computeNormalizedHash
190
190
  } from "./index-9x1f96r8.js";
@@ -1787,7 +1787,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
1787
1787
  state.running = startMessageFtsRowidMapBackfill2(db, signal).then(async () => {
1788
1788
  if (signal.aborted || !readsOpenCodeStore)
1789
1789
  return;
1790
- const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-tjj2wzxs.js"));
1790
+ const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-ygwyfvtr.js"));
1791
1791
  const { startMessageTimeBackfill } = await importPluginModule(() => import("./message-time-backfill-8zwv9byv.js"));
1792
1792
  if (signal.aborted)
1793
1793
  return;
@@ -39,7 +39,7 @@ import {
39
39
  providerVisiblePart,
40
40
  getCandidateToolOwners2,
41
41
  pickNearestPriorOwner2
42
- } from "./index-73fw4cd4.js";
42
+ } from "./index-6gwasf0v.js";
43
43
  import {
44
44
  OMO_INTERNAL_INITIATOR_MARKER,
45
45
  isSystemDirective,
@@ -5,6 +5,9 @@ import {
5
5
  PROMOTABLE_CATEGORIES,
6
6
  CATEGORY_DEFAULT_TTL
7
7
  } from "./index-135e8hvg.js";
8
+ import {
9
+ DEFAULT_LOCAL_EMBEDDING_MODEL
10
+ } from "./index-vcegxfwg.js";
8
11
  import {
9
12
  getHarness2
10
13
  } from "./index-0h2mkab2.js";
@@ -14,7 +17,9 @@ import {
14
17
  sessionLog2
15
18
  } from "./index-tm11k42a.js";
16
19
  import {
17
- SubcClient
20
+ SubcClient,
21
+ isSynapseEmbeddingTruncated,
22
+ SynapseEmbeddingProvider
18
23
  } from "./index-5rcjs14a.js";
19
24
  import {
20
25
  inRootAsyncContext2,
@@ -32,6 +37,10 @@ import {
32
37
  warmCompartmentChunkSearchPool2
33
38
  } from "./index-cxczethe.js";
34
39
  import {
40
+ LocalEmbeddingProvider
41
+ } from "./index-txcs0vnj.js";
42
+ import {
43
+ OpenAICompatibleEmbeddingProvider,
35
44
  saveCommitEmbedding,
36
45
  loadProjectCommitEmbeddings,
37
46
  loadUnembeddedCommits,
@@ -47,7 +56,7 @@ import {
47
56
  getProjectEmbeddingSnapshot2,
48
57
  embedTextForProject2,
49
58
  embedItemsForProject2
50
- } from "./index-e9wkbh8y.js";
59
+ } from "./index-yk0ve8hn.js";
51
60
  import {
52
61
  recordEmbeddingMeasurement
53
62
  } from "./index-hgd00nas.js";
@@ -59,11 +68,8 @@ import {
59
68
  getProjectEmbeddings2
60
69
  } from "./index-yhzhdp3m.js";
61
70
  import {
62
- cosineSimilarity,
63
- isEmbeddingEnabled,
64
- embedText,
65
71
  ensureMemoryEmbeddings2
66
- } from "./index-qdy49kwk.js";
72
+ } from "./index-w2snpk0j.js";
67
73
  import {
68
74
  getMemorySelectColumns2,
69
75
  isMemoryRow2,
@@ -91,7 +97,7 @@ import {
91
97
  clearIndexedMessages,
92
98
  indexSingleMessage,
93
99
  indexMessagesAfterOrdinal
94
- } from "./index-d7yx4ymd.js";
100
+ } from "./index-mm9y1m77.js";
95
101
  import {
96
102
  MESSAGE_FTS_SESSION_FILTER_SQL,
97
103
  withMessageFtsSessionFilter
@@ -463,6 +469,91 @@ function projectNeedsSingleStoreMigration(db, projectPath) {
463
469
  const table = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'authority_managed'").get();
464
470
  return Boolean(table && db.prepare("SELECT 1 FROM authority_managed WHERE project_path = ?").get(projectPath));
465
471
  }
472
+ // ../plugin/src/features/magic-context/memory/cosine-similarity.ts
473
+ function cosineSimilarity(a, b) {
474
+ if (a.length !== b.length) {
475
+ return 0;
476
+ }
477
+ let dotProduct = 0;
478
+ let normA = 0;
479
+ let normB = 0;
480
+ for (let index = 0;index < a.length; index++) {
481
+ dotProduct += a[index] * b[index];
482
+ normA += a[index] * a[index];
483
+ normB += b[index] * b[index];
484
+ }
485
+ const denominator = Math.sqrt(normA) * Math.sqrt(normB);
486
+ return denominator === 0 ? 0 : dotProduct / denominator;
487
+ }
488
+
489
+ // ../plugin/src/features/magic-context/memory/embedding.ts
490
+ var DEFAULT_EMBEDDING_CONFIG = {
491
+ provider: "local",
492
+ model: DEFAULT_LOCAL_EMBEDDING_MODEL,
493
+ local_runtime: "auto"
494
+ };
495
+ var embeddingConfig = DEFAULT_EMBEDDING_CONFIG;
496
+ var provider = null;
497
+ function createProvider(config) {
498
+ if (config.provider === "off") {
499
+ return null;
500
+ }
501
+ if (config.provider === "openai-compatible") {
502
+ return new OpenAICompatibleEmbeddingProvider({
503
+ endpoint: config.endpoint,
504
+ model: config.model,
505
+ apiKey: config.api_key,
506
+ inputType: config.input_type,
507
+ queryInputType: config.query_input_type,
508
+ queryInstruction: config.query_instruction,
509
+ documentPrefix: config.document_prefix,
510
+ truncate: config.truncate,
511
+ dimensions: config.dimensions,
512
+ maxInputTokens: config.max_input_tokens
513
+ });
514
+ }
515
+ if (config.provider === "local") {
516
+ return new LocalEmbeddingProvider(config.model, config.max_input_tokens, config.local_dtype, config.local_runtime);
517
+ }
518
+ if (config.provider === "synapse") {
519
+ const synapse = config;
520
+ return new SynapseEmbeddingProvider({
521
+ connectionFile: synapse.synapse_connection_file ?? "",
522
+ projectRoot: "",
523
+ session: "embedding",
524
+ model: synapse.model,
525
+ fingerprint: synapse.synapse_fingerprint,
526
+ tableEpoch: synapse.synapse_table_epoch,
527
+ dims: synapse.synapse_dims,
528
+ recommendedBatch: synapse.synapse_recommended_batch,
529
+ recommendedTokenBudget: synapse.synapse_recommended_token_budget,
530
+ descriptor: synapse.synapse_descriptor,
531
+ provenance: synapse.synapse_provenance
532
+ });
533
+ }
534
+ throw new Error("Unknown embedding provider");
535
+ }
536
+ function getOrCreateProvider() {
537
+ if (provider) {
538
+ return provider;
539
+ }
540
+ provider = createProvider(embeddingConfig);
541
+ return provider;
542
+ }
543
+ function isEmbeddingEnabled() {
544
+ return embeddingConfig.provider !== "off";
545
+ }
546
+ async function embedText(text, signal) {
547
+ const currentProvider = getOrCreateProvider();
548
+ if (!currentProvider) {
549
+ return null;
550
+ }
551
+ if (!await currentProvider.initialize()) {
552
+ return null;
553
+ }
554
+ const vector = await currentProvider.embed(text, signal);
555
+ return vector && !isSynapseEmbeddingTruncated(vector) ? vector : null;
556
+ }
466
557
  // ../plugin/src/features/magic-context/memory/promotion.ts
467
558
  function isPromotableCategory(category) {
468
559
  return PROMOTABLE_CATEGORIES.some((promotableCategory) => promotableCategory === category);
@@ -3891,4 +3982,4 @@ ${bodyParts.join(`
3891
3982
  `)}`;
3892
3983
  }
3893
3984
 
3894
- export { USER_FACING_FAILURES, renderUserFacingFailure, userFacingFailureCode, renderCapabilityRefusal, renderDreamFailure, dreamFailureCode, renderEmbeddingFailure, renderSingleStoreMigrationRequiredRefusal, SingleStoreMigrationRequiredError, projectNeedsSingleStoreMigration, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, indexCommitsForProject, embedUnembeddedCommits, getMessageIndexEpoch, isMessageIndexSearchable, scheduleReconciliation, scheduleIncrementalIndex, scheduleClearAndReindex, clearSessionTracking, createAutoSearchDiagnostics, createUnifiedSearchDiagnostics2, searchMessageHistory2, parseIdShapedQuery2, resolveMemoriesByIdsForSearch2, unifiedSearch2, formatSearchResults2 };
3985
+ export { USER_FACING_FAILURES, renderUserFacingFailure, userFacingFailureCode, renderCapabilityRefusal, renderDreamFailure, dreamFailureCode, renderEmbeddingFailure, renderSingleStoreMigrationRequiredRefusal, SingleStoreMigrationRequiredError, projectNeedsSingleStoreMigration, cosineSimilarity, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, indexCommitsForProject, embedUnembeddedCommits, getMessageIndexEpoch, isMessageIndexSearchable, scheduleReconciliation, scheduleIncrementalIndex, scheduleClearAndReindex, clearSessionTracking, createAutoSearchDiagnostics, createUnifiedSearchDiagnostics2, searchMessageHistory2, parseIdShapedQuery2, resolveMemoriesByIdsForSearch2, unifiedSearch2, formatSearchResults2 };
@@ -6,7 +6,7 @@ import {
6
6
  } from "./index-pefn1gt5.js";
7
7
  import {
8
8
  readRawSessionMessageIdOrdinalsForRange2
9
- } from "./index-2kb65n0s.js";
9
+ } from "./index-apff8dej.js";
10
10
 
11
11
  // ../plugin/src/tools/ctx-expand/search-archive.ts
12
12
  var archiveReadsOnThisThread = 0;
@@ -9,7 +9,7 @@ import {
9
9
  } from "./index-pefn1gt5.js";
10
10
  import {
11
11
  cleanUserText2
12
- } from "./index-2kb65n0s.js";
12
+ } from "./index-apff8dej.js";
13
13
  import {
14
14
  recordMessageFtsRowid2,
15
15
  recordIndexedMessageTime2,
@@ -139,9 +139,9 @@ async function serveV2ArchiveReads2(port, openConnections) {
139
139
  import("./sqlite-v89bj0yy.js"),
140
140
  import("./store-reader-mmfw2h48.js"),
141
141
  import("./store-grcwn6hs.js"),
142
- import("./read-session-chunk-tjj2wzxs.js"),
143
- import("./render-793jtz3r.js"),
144
- import("./search-archive-gmyvkadj.js"),
142
+ import("./read-session-chunk-ygwyfvtr.js"),
143
+ import("./render-cm4572er.js"),
144
+ import("./search-archive-8kcsmnzt.js"),
145
145
  import("./expand-attachments-8sxeyj26.js")
146
146
  ]);
147
147
  const pool = new V2StoreReaderPool;
@@ -40,7 +40,7 @@ import {
40
40
  serializeProcessedImageMarkers,
41
41
  getPendingPiCompactionMarkerState,
42
42
  logPiCompactionMarkerClear
43
- } from "./index-73fw4cd4.js";
43
+ } from "./index-6gwasf0v.js";
44
44
  import {
45
45
  estimateTokens
46
46
  } from "./index-pefn1gt5.js";
@@ -61,13 +61,13 @@ import {
61
61
  import {
62
62
  isPidAlive,
63
63
  readProcessStartTime
64
- } from "./index-sg6tdkqh.js";
64
+ } from "./index-9a92hc6c.js";
65
65
  import {
66
66
  withReadOnlySessionDb,
67
67
  expandToolPart,
68
68
  visitRawSessionMessages2,
69
69
  readRawSessionMessageById2
70
- } from "./index-2kb65n0s.js";
70
+ } from "./index-apff8dej.js";
71
71
  import {
72
72
  gaDatabasePath2,
73
73
  V2StoreReader2
@@ -1505,11 +1505,33 @@ function pendingMaterializationOrigin(sessions, sessionId) {
1505
1505
  function hasPendingMaterializationOrigin(sessions, sessionId, origin) {
1506
1506
  return sessions.has(sessionId) && causes.get(sessions)?.get(sessionId)?.has(origin) === true;
1507
1507
  }
1508
+ function hasExplicitRefreshRequest(sessions, sessionId) {
1509
+ return hasPendingMaterializationOrigin(sessions, sessionId, "user_flush") || hasPendingMaterializationOrigin(sessions, sessionId, "user_wrapup");
1510
+ }
1508
1511
  function clearPendingMaterialization(sessions, sessionId) {
1509
1512
  sessions.delete(sessionId);
1510
1513
  origins.get(sessions)?.delete(sessionId);
1511
1514
  causes.get(sessions)?.delete(sessionId);
1512
1515
  }
1516
+ function clearReclaimedMaterialization(sessions, sessionId) {
1517
+ const wrapupPending = hasPendingMaterializationOrigin(sessions, sessionId, "user_wrapup");
1518
+ clearPendingMaterialization(sessions, sessionId);
1519
+ if (wrapupPending)
1520
+ requestPendingMaterialization(sessions, sessionId, "user_wrapup");
1521
+ }
1522
+ function clearPendingMaterializationOrigin(sessions, sessionId, origin) {
1523
+ const pendingCauses = causes.get(sessions)?.get(sessionId);
1524
+ if (!sessions.has(sessionId) || !pendingCauses?.has(origin))
1525
+ return;
1526
+ pendingCauses.delete(origin);
1527
+ const [next] = pendingCauses;
1528
+ if (next === undefined) {
1529
+ clearPendingMaterialization(sessions, sessionId);
1530
+ return;
1531
+ }
1532
+ if (origins.get(sessions)?.get(sessionId) === origin)
1533
+ origins.get(sessions)?.set(sessionId, next);
1534
+ }
1513
1535
  function hasOnlySystemHashMaterialization(sessions, sessionId) {
1514
1536
  const pendingCauses = causes.get(sessions)?.get(sessionId);
1515
1537
  return sessions.has(sessionId) && pendingCauses?.size === 1 && pendingCauses.has("system_hash");
@@ -4703,4 +4725,4 @@ function renderItemByTag2(db, sessionId, number, textIndexDomain = "part", attac
4703
4725
  return selected ? renderPartFull(selected) ?? "" : `Tag ${number}'s original text part is no longer in stored history.`;
4704
4726
  }
4705
4727
 
4706
- export { LkgRecoveryFenceError, clearLkgFenceProcessState, lkgFenceRequiresRebuild, lkgRecoveryFenceUnclean, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, markLkgRecoveryDirty, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, PI_IDENTITY_FOLD_GUARD_LIMIT, readPiIdentityFoldGuards, writePiIdentityFoldGuards, readSessionActivity, observeSessionActivity, backfillSessionActivity, 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, getUncoveredCompartmentEndsThrough, readProjectDocsCanonical, providerResponseFailed, isSuccessfulProviderCompletion, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, recordSystemRefreshOwnership, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, acknowledgeSystemPromptDelivery, deferDeliveredSystemRefresh, clearSystemPromptDelivery, saveLkgSlotToDb, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, replayLkg, beginServedRequest, noteServedPassPermission, noteServedReplay, countServedRefusal, dropServedRecord, commitServedRequest, 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, withNativeReplayWriteBarrier, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, externalHistorianFailureReason, subprocessExitHistorianFailureReason, countHistorianRuns, getRecentFailedHistorianRunTimes, recordHistorianRun, summarizeImportance, tallyFactsByCategory, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, renderMessageByOrdinal2, renderVerboseRange2, renderVerboseRangeForTool2, renderItemByTag2 };
4728
+ export { LkgRecoveryFenceError, clearLkgFenceProcessState, lkgFenceRequiresRebuild, lkgRecoveryFenceUnclean, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, markLkgRecoveryDirty, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, PI_IDENTITY_FOLD_GUARD_LIMIT, readPiIdentityFoldGuards, writePiIdentityFoldGuards, readSessionActivity, observeSessionActivity, backfillSessionActivity, 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, getUncoveredCompartmentEndsThrough, readProjectDocsCanonical, providerResponseFailed, isSuccessfulProviderCompletion, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, hasExplicitRefreshRequest, clearPendingMaterialization, clearReclaimedMaterialization, clearPendingMaterializationOrigin, recordSystemRefreshOwnership, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, acknowledgeSystemPromptDelivery, deferDeliveredSystemRefresh, clearSystemPromptDelivery, saveLkgSlotToDb, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, replayLkg, beginServedRequest, noteServedPassPermission, noteServedReplay, countServedRefusal, dropServedRecord, commitServedRequest, 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, withNativeReplayWriteBarrier, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, externalHistorianFailureReason, subprocessExitHistorianFailureReason, countHistorianRuns, getRecentFailedHistorianRunTimes, recordHistorianRun, summarizeImportance, tallyFactsByCategory, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, renderMessageByOrdinal2, renderVerboseRange2, renderVerboseRangeForTool2, renderItemByTag2 };
@@ -0,0 +1,65 @@
1
+ import {
2
+ isEmbeddingHostBusy2
3
+ } from "./index-9p40dgkm.js";
4
+ import {
5
+ log2
6
+ } from "./index-tm11k42a.js";
7
+ import {
8
+ contentSha2562,
9
+ getProjectEmbeddingSnapshot2,
10
+ embedItemsWindowBounded2
11
+ } from "./index-yk0ve8hn.js";
12
+ import {
13
+ saveEmbeddingIfHashMatches
14
+ } from "./index-yhzhdp3m.js";
15
+
16
+ // ../plugin/src/features/magic-context/memory/embedding-backfill.ts
17
+ var SEARCH_BACKFILL_LIMIT = 50;
18
+ var SEARCH_BACKFILL_REQUEST_SIZE = 10;
19
+ async function ensureMemoryEmbeddings2(args) {
20
+ if (isEmbeddingHostBusy2())
21
+ return args.existingEmbeddings;
22
+ const snapshot = getProjectEmbeddingSnapshot2(args.projectIdentity);
23
+ if (!snapshot?.enabled) {
24
+ return args.existingEmbeddings;
25
+ }
26
+ const missingMemories = args.memories.filter((memory) => !args.existingEmbeddings.has(memory.id)).sort((a, b) => a.id - b.id).slice(0, SEARCH_BACKFILL_LIMIT);
27
+ if (missingMemories.length === 0) {
28
+ return args.existingEmbeddings;
29
+ }
30
+ try {
31
+ const result = await embedItemsWindowBounded2(args.projectIdentity, missingMemories.map((memory) => ({
32
+ id: `memory:${memory.id}`,
33
+ text: memory.content,
34
+ contentSha256: contentSha2562(memory.content)
35
+ })), undefined, args.db, args.projectIdentity, { maxItemsPerCall: SEARCH_BACKFILL_REQUEST_SIZE });
36
+ if (!result) {
37
+ return args.existingEmbeddings;
38
+ }
39
+ const staged = new Map;
40
+ args.db.transaction(() => {
41
+ for (const memory of missingMemories) {
42
+ const embedding = result.vectors.get(`memory:${memory.id}`);
43
+ if (!embedding) {
44
+ continue;
45
+ }
46
+ const saved = saveEmbeddingIfHashMatches(args.db, memory.id, embedding, result.modelId, memory.normalizedHash);
47
+ if (saved) {
48
+ staged.set(memory.id, { embedding, modelId: result.modelId });
49
+ }
50
+ }
51
+ }).immediate();
52
+ const currentSnapshot = getProjectEmbeddingSnapshot2(args.projectIdentity);
53
+ if (!currentSnapshot || currentSnapshot.generation !== result.generation) {
54
+ return args.existingEmbeddings;
55
+ }
56
+ for (const [id, embedding] of staged) {
57
+ args.existingEmbeddings.set(id, embedding);
58
+ }
59
+ } catch (error) {
60
+ log2("[magic-context] failed to backfill memory embeddings:", error);
61
+ }
62
+ return args.existingEmbeddings;
63
+ }
64
+
65
+ export { ensureMemoryEmbeddings2 };
@@ -7,7 +7,7 @@ import {
7
7
  import {
8
8
  getTagsBySession2,
9
9
  getTagsByNumbers2
10
- } from "./index-73fw4cd4.js";
10
+ } from "./index-6gwasf0v.js";
11
11
  import {
12
12
  inRootAsyncContext2,
13
13
  getSqliteDatabasePath2,
@@ -2558,14 +2558,15 @@ async function embedItemsForProject2(projectIdentity, items, signal, db, session
2558
2558
  return { vectors, modelId, generation };
2559
2559
  }
2560
2560
  async function embedItemsWindowBounded2(projectIdentity, items, signal, db, sessionId = projectIdentity, options = {}) {
2561
- if (items.length <= MAX_WINDOWS_PER_EMBED_CALL) {
2561
+ const maxItemsPerCall = options.maxItemsPerCall ?? MAX_WINDOWS_PER_EMBED_CALL;
2562
+ if (items.length <= maxItemsPerCall) {
2562
2563
  return embedItemsForProject2(projectIdentity, items, signal, db, sessionId);
2563
2564
  }
2564
2565
  const vectors = new Map;
2565
2566
  let modelId = null;
2566
2567
  let generation = null;
2567
- for (let start = 0;start < items.length; start += MAX_WINDOWS_PER_EMBED_CALL) {
2568
- const slice = items.slice(start, start + MAX_WINDOWS_PER_EMBED_CALL);
2568
+ for (let start = 0;start < items.length; start += maxItemsPerCall) {
2569
+ const slice = items.slice(start, start + maxItemsPerCall);
2569
2570
  const result = await embedItemsForProject2(projectIdentity, slice, signal, db, sessionId);
2570
2571
  if (!result)
2571
2572
  return null;
package/dist/index.js CHANGED
@@ -158,7 +158,7 @@ import {
158
158
  registerTodoStateLifecycle,
159
159
  syncCtxMemoryToolEnabled,
160
160
  registerMagicContextTools
161
- } from "./index-bcwy4wm1.js";
161
+ } from "./index-6t4m64m1.js";
162
162
  import"./index-4knyh1kt.js";
163
163
  import {
164
164
  canonicalModelIdentity,
@@ -410,7 +410,7 @@ import {
410
410
  setSessionWorkMetrics,
411
411
  getSessionWorkMetrics,
412
412
  resolveEpochFloorForPass
413
- } from "./index-73fw4cd4.js";
413
+ } from "./index-6gwasf0v.js";
414
414
  import {
415
415
  textMentionsRecentCommit,
416
416
  hasMeaningfulUserText2,
@@ -461,7 +461,7 @@ import {
461
461
  openCurrentDatabase,
462
462
  openDatabaseAsync,
463
463
  closeDatabase
464
- } from "./index-sg6tdkqh.js";
464
+ } from "./index-9a92hc6c.js";
465
465
  import {
466
466
  LkgRecoveryFenceError,
467
467
  clearLkgFenceProcessState,
@@ -516,7 +516,10 @@ import {
516
516
  requestPendingMaterialization,
517
517
  pendingMaterializationOrigin,
518
518
  hasPendingMaterializationOrigin,
519
+ hasExplicitRefreshRequest,
519
520
  clearPendingMaterialization,
521
+ clearReclaimedMaterialization,
522
+ clearPendingMaterializationOrigin,
520
523
  recordSystemRefreshOwnership,
521
524
  recordSystemPromptForRequest,
522
525
  recordHeldHeadForRequest,
@@ -587,7 +590,7 @@ import {
587
590
  getSourceContents,
588
591
  recordSubagentInvocation,
589
592
  getLatestHistorianInvocationId
590
- } from "./index-tcrd11cb.js";
593
+ } from "./index-tygcydj7.js";
591
594
  import {
592
595
  resolveOpenCodeDbPath,
593
596
  assertOpenCodeStoreGeneration,
@@ -653,7 +656,7 @@ import {
653
656
  getRawSessionTagKeysThrough2,
654
657
  getLegacyProtectedTailStartOrdinal2,
655
658
  readSessionChunk2
656
- } from "./index-2kb65n0s.js";
659
+ } from "./index-apff8dej.js";
657
660
  import"./index-nvh6d3bz.js";
658
661
  import {
659
662
  formatSynapseLaneDescriptor
@@ -693,7 +696,7 @@ import {
693
696
  clearCompressionDepthRange,
694
697
  cleanSearchText,
695
698
  matchedSearchSnippet
696
- } from "./index-d7yx4ymd.js";
699
+ } from "./index-mm9y1m77.js";
697
700
  import {
698
701
  rememberV1HiddenRun
699
702
  } from "./index-6x556c2q.js";
@@ -785,10 +788,7 @@ import {
785
788
  embedSessionCompartmentChunks2,
786
789
  getEmbeddingCoverageStatus2,
787
790
  getAutoEmbeddingSessionCoverage2
788
- } from "./index-e9wkbh8y.js";
789
- import {
790
- cosineSimilarity
791
- } from "./index-qdy49kwk.js";
791
+ } from "./index-yk0ve8hn.js";
792
792
  import {
793
793
  USER_FACING_FAILURES,
794
794
  renderUserFacingFailure,
@@ -800,6 +800,7 @@ import {
800
800
  renderSingleStoreMigrationRequiredRefusal,
801
801
  SingleStoreMigrationRequiredError,
802
802
  projectNeedsSingleStoreMigration,
803
+ cosineSimilarity,
803
804
  promoteSessionFactsDurable,
804
805
  embedPromotedFacts,
805
806
  recordMemoryMapping,
@@ -822,7 +823,8 @@ import {
822
823
  scheduleClearAndReindex,
823
824
  clearSessionTracking,
824
825
  createAutoSearchDiagnostics
825
- } from "./index-2bavnrw8.js";
826
+ } from "./index-cevw58nn.js";
827
+ import"./index-w2snpk0j.js";
826
828
  import"./index-3s39a1md.js";
827
829
  import {
828
830
  DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
@@ -852,11 +854,11 @@ import {
852
854
  drainPiTagSnapshotSession,
853
855
  assertPiTagSnapshotReady,
854
856
  ensurePiTagSnapshotReady
855
- } from "./index-51xr6g7s.js";
857
+ } from "./index-wmkkxwvf.js";
856
858
  import"./index-71rg8j43.js";
857
859
  import"./index-8d2z6503.js";
858
- import"./index-zgj2mxrn.js";
859
- import"./index-4dqwxb7k.js";
860
+ import"./index-mtpsqxev.js";
861
+ import"./index-cyzsn2hb.js";
860
862
  import {
861
863
  __toESM
862
864
  } from "./index-22jkk6wg.js";
@@ -3608,7 +3610,7 @@ function startHostStallProfilerSwitch() {
3608
3610
  // package.json
3609
3611
  var package_default = {
3610
3612
  name: "@cortexkit/pi-magic-context",
3611
- version: "0.49.71",
3613
+ version: "0.49.73",
3612
3614
  type: "module",
3613
3615
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3614
3616
  main: "dist/index.js",
@@ -24249,6 +24251,15 @@ import * as crypto3 from "node:crypto";
24249
24251
 
24250
24252
  // ../plugin/src/hooks/magic-context/event-resolvers.ts
24251
24253
  var DEFAULT_CONTEXT_LIMIT = 200000;
24254
+ var WRAPUP_WINDOW_UNAVAILABLE = "Cannot run /ctx-wrapup: the model's context window is unknown. Select a model with a configured context window or send a message with that model, then retry.";
24255
+ function readPersistedWrapupWindow(db, sessionId, modelKey) {
24256
+ const { lastUsageContextLimit, lastObservedModelKey } = getOrCreateSessionMeta(db, sessionId);
24257
+ if (!isSaneLimit(lastUsageContextLimit) || !lastObservedModelKey)
24258
+ return;
24259
+ if (modelKey && piModelRefToCanonical(modelKey) !== piModelRefToCanonical(lastObservedModelKey))
24260
+ return;
24261
+ return { contextLimit: lastUsageContextLimit, modelKey: lastObservedModelKey };
24262
+ }
24252
24263
  var clampWarnSeen = new Set;
24253
24264
  function isFinitePositive(v) {
24254
24265
  return typeof v === "number" && Number.isFinite(v) && v > 0;
@@ -24800,6 +24811,7 @@ var canonicalReasons = new Set([
24800
24811
  "ttl_idle",
24801
24812
  "explicit_flush",
24802
24813
  "user_flush",
24814
+ "user_wrapup",
24803
24815
  "fit_retry",
24804
24816
  "pending_materialization",
24805
24817
  "variant_change",
@@ -36569,7 +36581,7 @@ function injectM0M1Pi(state, db, piMessages, entryIds, recomputeM1ThisPass = fal
36569
36581
  const m1HasContent = m1 !== PI_M1_PLACEHOLDER;
36570
36582
  const { m0Tokens, m1Tokens } = cachedInjectionTokenCounts(state.sessionId, m0, m1);
36571
36583
  const m1OverAbsoluteCap = m1HasContent && m1Tokens > m1AbsoluteBudget;
36572
- if (!materialized && !contentionExhausted && m1Recomputed && recomputeM1ThisPass && (memoryUpdateCount > 40 || m1OverAbsoluteCap || m1HasContent && m0Tokens >= M0_DRIFT_RATIO_FLOOR_TOKENS && m1Tokens > m0Tokens * M1_DRIFT_RATIO)) {
36584
+ if (!materialized && !contentionExhausted && m1Recomputed && recomputeM1ThisPass && !state.skipPressureRefold && (memoryUpdateCount > 40 || m1OverAbsoluteCap || m1HasContent && m0Tokens >= M0_DRIFT_RATIO_FLOOR_TOKENS && m1Tokens > m0Tokens * M1_DRIFT_RATIO)) {
36573
36585
  decision = { value: true, reason: "drift" };
36574
36586
  try {
36575
36587
  const result = materializeM0PiWithRetry(state, db, 3, snapshot);
@@ -48762,11 +48774,6 @@ function clearSystemPromptRefresh(sessionId) {
48762
48774
  function hasPendingMaterialization(sessionId) {
48763
48775
  return pendingMaterializationSessions.has(sessionId);
48764
48776
  }
48765
- function consumePendingMaterialization(sessionId) {
48766
- const wasSet = pendingMaterializationSessions.has(sessionId);
48767
- clearPendingMaterialization(pendingMaterializationSessions, sessionId);
48768
- return wasSet;
48769
- }
48770
48777
  function resolveSessionId2(ctx) {
48771
48778
  const sm = ctx.sessionManager;
48772
48779
  if (sm === undefined)
@@ -50908,7 +50915,7 @@ function registerPiContextHandler(pi, baseOptions) {
50908
50915
  inputTokens: usageInputTokens
50909
50916
  },
50910
50917
  isCacheBusting,
50911
- userFlushOrigin: hasPendingMaterializationOrigin(pendingMaterializationSessions, sessionId, "user_flush"),
50918
+ userFlushOrigin: hasExplicitRefreshRequest(pendingMaterializationSessions, sessionId),
50912
50919
  reasoningClearing: {
50913
50920
  keepReasoningTokens: resolveKeepReasoningTokens(options.heuristics?.keepReasoningTokens, resolvePiContextModelKey(ctx)),
50914
50921
  nativeReasoningMayClear: canClearNativeReasoning(ctx.model),
@@ -52324,7 +52331,7 @@ Historian previously failed ${failureCount} time(s), so Magic Context is retryin
52324
52331
  const trigger = checkCompartmentTrigger(db, sessionId, sessionMeta, usage, 0, triggerInputs.executeThresholdPercentage, triggerInputs.triggerBudget, triggerInputs.keepReasoningTokens, triggerInputs.commitClusterTrigger, args.activeTags, boundaryContextLimit, () => readPiHistorianTail(db, sessionId, provider), args.taggerFloor, { canClearReasoning: true }, {
52325
52332
  hardFold: false,
52326
52333
  force: usage.percentage >= historianForceMaterializationPercentage && (usage.percentage >= 95 || getEmergencyInputSample(db, sessionId) === 0),
52327
- explicitFlush: hasPendingMaterializationOrigin(pendingMaterializationSessions, sessionId, "user_flush"),
52334
+ explicitFlush: hasExplicitRefreshRequest(pendingMaterializationSessions, sessionId),
52328
52335
  publishedHistory: args.publishedHistoryRide,
52329
52336
  permission: {
52330
52337
  signedThinkingHold: args.signedThinkingHeld === true,
@@ -52772,6 +52779,9 @@ async function runPipeline(args) {
52772
52779
  let publishedM1RefreshedThisPass = false;
52773
52780
  let prefixPreflightContended = false;
52774
52781
  const softRefreshOpportunity = args.schedulerDecision === "execute";
52782
+ const wrapupPending = hasPendingMaterializationOrigin(pendingMaterializationSessions, args.sessionId, "user_wrapup");
52783
+ if (piM0State)
52784
+ piM0State.skipPressureRefold = wrapupPending;
52775
52785
  const cachedPrefixBeforePreflight = piM0State && (foldDueDecision.value || softRefreshOpportunity) && !emergencyDropEligible ? prepareCachedM0M1PiReplay(piM0State, args.db, injectionPassSnapshot?.cachedRow) : undefined;
52776
52786
  let preFoldInjectionResult = null;
52777
52787
  const persistedM0BeforeFold = injectionPassSnapshot?.sessionMeta ?? args.sessionMeta;
@@ -52941,7 +52951,7 @@ async function runPipeline(args) {
52941
52951
  subagentExecute: args.sessionMeta.isSubagent && args.schedulerDecision === "execute",
52942
52952
  hardFold: foldBustsServedPrefixThisPass || systemPrefixChangedThisPass || requestToolListChanged || firstRenderBust || isCacheBustingPass,
52943
52953
  force: (args.forceMaterialization === true || emergencyDropEligible) && (args.contextUsage.percentage >= 95 || getEmergencyInputSample(args.db, args.sessionId) === 0),
52944
- explicitFlush: !protectedSignedPrefix && (args.userFlushOrigin === true || hasPendingMaterializationOrigin(pendingMaterializationSessions, args.sessionId, "user_flush")),
52954
+ explicitFlush: !protectedSignedPrefix && (args.userFlushOrigin === true || hasExplicitRefreshRequest(pendingMaterializationSessions, args.sessionId)),
52945
52955
  publishedHistory: !prefixPreflightContended && publishedM1RefreshedThisPass
52946
52956
  };
52947
52957
  const ridePermissionGate = {
@@ -53387,7 +53397,7 @@ async function runPipeline(args) {
53387
53397
  if (hasPendingMaterializeSignal) {
53388
53398
  if (args.heuristics === undefined) {
53389
53399
  if (!pendingOps.some((op) => newTargets.get(op.tagId)?.thinkingDropProtected))
53390
- consumePendingMaterialization(args.sessionId);
53400
+ clearReclaimedMaterialization(pendingMaterializationSessions, args.sessionId);
53391
53401
  }
53392
53402
  }
53393
53403
  } catch (err) {
@@ -53559,7 +53569,7 @@ async function runPipeline(args) {
53559
53569
  executedWorkThisPass = true;
53560
53570
  if (hasPendingMaterializeSignal) {
53561
53571
  if (!pendingOps.some((op) => newTargets.get(op.tagId)?.thinkingDropProtected))
53562
- consumePendingMaterialization(args.sessionId);
53572
+ clearReclaimedMaterialization(pendingMaterializationSessions, args.sessionId);
53563
53573
  }
53564
53574
  if (currentTurnId !== null) {
53565
53575
  lastHeuristicsTurnIdBySession.set(args.sessionId, currentTurnId);
@@ -53885,6 +53895,10 @@ async function runPipeline(args) {
53885
53895
  }
53886
53896
  }
53887
53897
  if (!heldHeadReleasedForSystemChange) {
53898
+ if (wrapupPending && isCacheBustingPass && !protectedSignedPrefix && wireInjectionResult.injected && !wireInjectionResult.contentionExhausted) {
53899
+ clearPendingMaterializationOrigin(pendingMaterializationSessions, args.sessionId, "user_wrapup");
53900
+ historyWasConsumedThisPass = true;
53901
+ }
53888
53902
  if (args.isCacheBusting && prefixMutationAllowed) {
53889
53903
  historyRefreshSessions.delete(args.sessionId);
53890
53904
  historyWasConsumedThisPass = true;
@@ -57059,8 +57073,12 @@ The stored history boundaries no longer match this session branch (${ordinalAlig
57059
57073
  const unregister = setRawMessageProvider2(sessionId, provider);
57060
57074
  let holderId = "";
57061
57075
  try {
57062
- const contextLimit = resolvePiContextLimit(ctx, deps.db, sessionId);
57063
- const modelKey = ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined;
57076
+ const window = resolvePiWrapupWindow(ctx, deps.db, sessionId);
57077
+ if (!window)
57078
+ return `## Magic Wrapup — Skipped
57079
+
57080
+ ${WRAPUP_WINDOW_UNAVAILABLE}`;
57081
+ const { contextLimit, modelKey } = window;
57064
57082
  const executeThresholdPercentage = resolveExecuteThreshold(deps.executeThresholdPercentage ?? 65, modelKey, 65, {
57065
57083
  tokensConfig: deps.executeThresholdTokens,
57066
57084
  contextLimit,
@@ -57290,9 +57308,14 @@ Wrapped up ${messagesWrapped} messages into ${compartmentsCreated} compartments;
57290
57308
  try {
57291
57309
  clearEmergencyRecovery(deps.db, sessionId);
57292
57310
  } catch {}
57293
- return `## Magic Wrapup
57311
+ let message = `## Magic Wrapup
57294
57312
 
57295
- Wrapped up ${messagesWrapped} messages into ${compartmentsCreated} compartments. The compacted history is queued and materializes on your next message.`;
57313
+ Wrapped up ${messagesWrapped} messages into ${compartmentsCreated} compartments.`;
57314
+ if (compartmentsCreated > 0) {
57315
+ signalPiPendingMaterialization(sessionId, "user_wrapup");
57316
+ message += " The compacted history applies on your next message, or on the next rebuild if the host restarts first.";
57317
+ }
57318
+ return message;
57296
57319
  } finally {
57297
57320
  clearInterval(renewal);
57298
57321
  deps.shutdownSignal?.removeEventListener("abort", stopRenewal);
@@ -57302,20 +57325,28 @@ Wrapped up ${messagesWrapped} messages into ${compartmentsCreated} compartments.
57302
57325
  unregister();
57303
57326
  }
57304
57327
  }
57305
- function resolvePiContextLimit(ctx, db, sessionId) {
57306
- const usage = ctx.getContextUsage?.();
57307
- let detectedContextLimit;
57308
- try {
57309
- const detected = getOverflowState(db, sessionId).detectedContextLimit;
57310
- if (detected > 0)
57311
- detectedContextLimit = detected;
57312
- } catch {}
57313
- return resolvePiUsableContextLimit({
57314
- rawContextWindow: usage?.contextWindow ?? ctx.model?.contextWindow,
57315
- rawContextWindowSource: "catalog",
57316
- model: ctx.model,
57317
- detectedContextLimit
57318
- }) ?? 128000;
57328
+ function resolvePiWrapupWindow(ctx, db, sessionId) {
57329
+ const model = ctx.model;
57330
+ if (!model)
57331
+ return readPersistedWrapupWindow(db, sessionId);
57332
+ const modelKey = `${model.provider}/${model.id}`;
57333
+ const overflow = getOverflowState(db, sessionId, modelKey);
57334
+ const window = {
57335
+ model,
57336
+ detectedContextLimit: overflow.detectedContextLimit
57337
+ };
57338
+ const provenInputTokens = resolvePiProvenInputFloor({
57339
+ db,
57340
+ sessionId,
57341
+ modelKey,
57342
+ readBranch: () => ctx.sessionManager.getBranch(),
57343
+ providerInputLimit: piPressureEvidenceLimit(resolvePiWindowGeometry(window))
57344
+ });
57345
+ const contextLimit = resolvePiUsableContextLimit({
57346
+ ...window,
57347
+ provenInputTokens: provenInputTokens || undefined
57348
+ });
57349
+ return contextLimit === undefined ? readPersistedWrapupWindow(db, sessionId, modelKey) : { contextLimit, modelKey };
57319
57350
  }
57320
57351
  async function acquireCompartmentLeaseEventually(db, sessionId, renewWrapupMarker, maxWaitMs, signal) {
57321
57352
  const waitStartedAt = Date.now();
@@ -3,7 +3,7 @@ import {
3
3
  withIndexChunk2,
4
4
  yieldIndexChunk2
5
5
  } from "./index-2qtx0q6h.js";
6
- import"./index-73fw4cd4.js";
6
+ import"./index-6gwasf0v.js";
7
7
  import"./index-pefn1gt5.js";
8
8
  import"./index-0h2mkab2.js";
9
9
  import"./index-tm11k42a.js";
@@ -15,7 +15,7 @@ import"./index-wfqysrwq.js";
15
15
  import"./index-x2n261wp.js";
16
16
  import"./index-xjhq27z9.js";
17
17
  import"./index-n0zjvs3h.js";
18
- import"./index-2kb65n0s.js";
18
+ import"./index-apff8dej.js";
19
19
  import"./index-6x556c2q.js";
20
20
  import {
21
21
  MESSAGE_INDEX_MAX_FTS_BYTES,
@@ -24,7 +24,7 @@ import {
24
24
  markMessageIndexDirty,
25
25
  getIndexableContent,
26
26
  indexSingleMessage
27
- } from "./index-d7yx4ymd.js";
27
+ } from "./index-mm9y1m77.js";
28
28
  import"./index-ghp32f9m.js";
29
29
  import"./index-1ts77n1b.js";
30
30
 
@@ -17,7 +17,7 @@ import"./index-453s1hj6.js";
17
17
  import {
18
18
  setSqlitePragmaConfig,
19
19
  initializeDatabase
20
- } from "./index-sg6tdkqh.js";
20
+ } from "./index-9a92hc6c.js";
21
21
  import"./index-fapenpch.js";
22
22
  import"./index-3bb24eb6.js";
23
23
  import"./index-8sqebjzk.js";
@@ -34,7 +34,7 @@ import {
34
34
  sweepAllRegisteredProjects2,
35
35
  _setTestProviderFactoryForProject2,
36
36
  _resetProjectEmbeddingRegistryForTests2
37
- } from "./index-e9wkbh8y.js";
37
+ } from "./index-yk0ve8hn.js";
38
38
  import"./index-9p40dgkm.js";
39
39
  import"./index-hgd00nas.js";
40
40
  import"./index-yhzhdp3m.js";
@@ -19,7 +19,7 @@ serveWorkerJobs(async (input, port) => {
19
19
  await main();
20
20
  async function main() {
21
21
  if (input.v2ArchiveReader) {
22
- const { serveV2ArchiveReads } = await import("./v2-archive-reader-99stcer0.js");
22
+ const { serveV2ArchiveReads } = await import("./v2-archive-reader-ycw2nxf1.js");
23
23
  await serveV2ArchiveReads(port, openConnections);
24
24
  return;
25
25
  }
@@ -51,7 +51,7 @@ serveWorkerJobs(async (input, port) => {
51
51
  await runMessageFtsRowidMapBackfill(db);
52
52
  reply = { kind: "fts-rowid-backfill" };
53
53
  } else if (input.searchArchive) {
54
- const { renderSearchArchive } = await import("./search-archive-gmyvkadj.js");
54
+ const { renderSearchArchive } = await import("./search-archive-8kcsmnzt.js");
55
55
  const { readRawSessionMessageIdOrdinalsForRangeFromDb } = await import("./read-session-raw-0tytrjye.js");
56
56
  const archive = input.searchArchive;
57
57
  let raw;
@@ -81,7 +81,7 @@ serveWorkerJobs(async (input, port) => {
81
81
  const { setHarness } = await import("./harness-9872e0ym.js");
82
82
  setHarness(input.harness ?? "opencode");
83
83
  const [{ indexMessageInShortChunks }, { configureContextDatabasePragmas }] = await Promise.all([
84
- import("./message-index-bounded-fqeqp76p.js"),
84
+ import("./message-index-bounded-cv87994v.js"),
85
85
  import("./sqlite-context-pragmas-gcgch6qz.js")
86
86
  ]);
87
87
  configureContextDatabasePragmas(db);
@@ -95,7 +95,7 @@ serveWorkerJobs(async (input, port) => {
95
95
  measurements: result.measurements
96
96
  };
97
97
  } else if (input.tagRatio !== undefined) {
98
- const { scanTagOwnerSummary, scanTagOwnerDelta } = await import("./storage-tags-wq8p5wrh.js");
98
+ const { scanTagOwnerSummary, scanTagOwnerDelta } = await import("./storage-tags-zzttnzn6.js");
99
99
  const delta = input.tagState ? scanTagOwnerDelta(db, input.sessionId, input.tagState) : null;
100
100
  if (delta)
101
101
  reply = { kind: "tag-delta", delta };
@@ -38,8 +38,8 @@ import {
38
38
  readSessionChunk2,
39
39
  getRawSessionMessageIdsThrough2,
40
40
  readRawSessionSeedTail2
41
- } from "./index-2kb65n0s.js";
42
- import"./index-73fw4cd4.js";
41
+ } from "./index-apff8dej.js";
42
+ import"./index-6gwasf0v.js";
43
43
  import"./index-6x556c2q.js";
44
44
  import"./index-vcegxfwg.js";
45
45
  import"./index-jhmz9tgv.js";
@@ -3,18 +3,18 @@ import {
3
3
  renderVerboseRange2,
4
4
  renderVerboseRangeForTool2,
5
5
  renderItemByTag2
6
- } from "./index-tcrd11cb.js";
6
+ } from "./index-tygcydj7.js";
7
7
  import"./index-k7a8x7ba.js";
8
- import"./index-d7yx4ymd.js";
8
+ import"./index-mm9y1m77.js";
9
9
  import"./index-hgd00nas.js";
10
10
  import"./index-nvh6d3bz.js";
11
11
  import"./index-cxczethe.js";
12
- import"./index-2kb65n0s.js";
13
- import"./index-73fw4cd4.js";
12
+ import"./index-apff8dej.js";
13
+ import"./index-6gwasf0v.js";
14
14
  import"./index-6x556c2q.js";
15
15
  import"./index-5rcjs14a.js";
16
16
  import"./index-vcegxfwg.js";
17
- import"./index-sg6tdkqh.js";
17
+ import"./index-9a92hc6c.js";
18
18
  import"./index-fapenpch.js";
19
19
  import"./index-gavj3e6h.js";
20
20
  import"./index-135e8hvg.js";
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  renderSearchArchive2
3
- } from "./index-4dqwxb7k.js";
4
- import"./index-zgj2mxrn.js";
3
+ } from "./index-cyzsn2hb.js";
4
+ import"./index-mtpsqxev.js";
5
5
  import"./index-8d2z6503.js";
6
- import"./index-2kb65n0s.js";
7
- import"./index-73fw4cd4.js";
6
+ import"./index-apff8dej.js";
7
+ import"./index-6gwasf0v.js";
8
8
  import"./index-6x556c2q.js";
9
9
  import"./index-vcegxfwg.js";
10
10
  import"./index-jhmz9tgv.js";
@@ -5,20 +5,20 @@ import {
5
5
  resolveMemoriesByIdsForSearch2,
6
6
  unifiedSearch2,
7
7
  formatSearchResults2
8
- } from "./index-2bavnrw8.js";
8
+ } from "./index-cevw58nn.js";
9
9
  import"./index-k7a8x7ba.js";
10
- import"./index-d7yx4ymd.js";
10
+ import"./index-mm9y1m77.js";
11
11
  import"./index-8d2z6503.js";
12
- import"./index-qdy49kwk.js";
12
+ import"./index-w2snpk0j.js";
13
13
  import"./index-29nw7n1r.js";
14
- import"./index-e9wkbh8y.js";
14
+ import"./index-yk0ve8hn.js";
15
15
  import"./index-9p40dgkm.js";
16
16
  import"./index-hgd00nas.js";
17
17
  import"./index-yhzhdp3m.js";
18
18
  import"./index-79xfn84y.js";
19
19
  import"./index-cxczethe.js";
20
- import"./index-2kb65n0s.js";
21
- import"./index-73fw4cd4.js";
20
+ import"./index-apff8dej.js";
21
+ import"./index-6gwasf0v.js";
22
22
  import"./index-6x556c2q.js";
23
23
  import"./index-txcs0vnj.js";
24
24
  import"./index-5rcjs14a.js";
@@ -62,7 +62,7 @@ import {
62
62
  adoptNullOwnerToolTag2,
63
63
  getCandidateToolOwners2,
64
64
  pickNearestPriorOwner2
65
- } from "./index-73fw4cd4.js";
65
+ } from "./index-6gwasf0v.js";
66
66
  import"./index-vcegxfwg.js";
67
67
  import"./index-jhmz9tgv.js";
68
68
  import"./index-1ts77n1b.js";
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  TOKEN_BUDGET_TOOL_REFUSAL
3
- } from "./index-2kb65n0s.js";
3
+ } from "./index-apff8dej.js";
4
4
  import {
5
5
  setHarness2
6
6
  } from "./index-0h2mkab2.js";
@@ -14,7 +14,7 @@ import {
14
14
  import"./index-2qtx0q6h.js";
15
15
  import {
16
16
  openDatabase
17
- } from "./index-sg6tdkqh.js";
17
+ } from "./index-9a92hc6c.js";
18
18
  import"./index-fapenpch.js";
19
19
  import"./index-3bb24eb6.js";
20
20
  import"./index-8sqebjzk.js";
@@ -34,28 +34,28 @@ import {
34
34
  resolvePiHarnessKind,
35
35
  reportSubagentStartupError,
36
36
  registerMagicContextTools
37
- } from "./index-bcwy4wm1.js";
37
+ } from "./index-6t4m64m1.js";
38
38
  import"./index-vcegxfwg.js";
39
39
  import"./index-5rcjs14a.js";
40
40
  import"./index-cxczethe.js";
41
41
  import"./index-txcs0vnj.js";
42
- import"./index-e9wkbh8y.js";
42
+ import"./index-yk0ve8hn.js";
43
43
  import"./index-hgd00nas.js";
44
44
  import"./index-9p40dgkm.js";
45
45
  import"./index-79xfn84y.js";
46
46
  import"./index-yhzhdp3m.js";
47
- import"./index-qdy49kwk.js";
48
- import"./index-tcrd11cb.js";
49
- import"./index-d7yx4ymd.js";
50
- import"./index-73fw4cd4.js";
47
+ import"./index-cevw58nn.js";
48
+ import"./index-tygcydj7.js";
49
+ import"./index-mm9y1m77.js";
50
+ import"./index-6gwasf0v.js";
51
51
  import"./index-6x556c2q.js";
52
52
  import"./index-nvh6d3bz.js";
53
53
  import"./index-k7a8x7ba.js";
54
54
  import"./index-8d2z6503.js";
55
- import"./index-zgj2mxrn.js";
56
- import"./index-4dqwxb7k.js";
55
+ import"./index-mtpsqxev.js";
56
+ import"./index-cyzsn2hb.js";
57
+ import"./index-w2snpk0j.js";
57
58
  import"./index-29nw7n1r.js";
58
- import"./index-2bavnrw8.js";
59
59
  import"./index-3s39a1md.js";
60
60
  import"./index-1ts77n1b.js";
61
61
  import {
@@ -8,7 +8,7 @@ import"./index-tm11k42a.js";
8
8
  import {
9
9
  LATEST_SUPPORTED_VERSION,
10
10
  getPersistedSchemaVersion
11
- } from "./index-sg6tdkqh.js";
11
+ } from "./index-9a92hc6c.js";
12
12
  import"./index-fapenpch.js";
13
13
  import"./index-3bb24eb6.js";
14
14
  import"./index-8sqebjzk.js";
@@ -28,14 +28,14 @@ import"./index-pefn1gt5.js";
28
28
  import {
29
29
  normalizeTagSnapshotRow2,
30
30
  TAG_SELECT_COLUMNS2
31
- } from "./index-73fw4cd4.js";
31
+ } from "./index-6gwasf0v.js";
32
32
  import"./index-vcegxfwg.js";
33
33
  import {
34
34
  encodePiHydrationOperation,
35
35
  projectPiPassTag,
36
36
  PI_FALLBACK_ROW_COLUMNS,
37
37
  PI_FALLBACK_ROW_PREDICATE
38
- } from "./index-51xr6g7s.js";
38
+ } from "./index-wmkkxwvf.js";
39
39
  import"./index-1ts77n1b.js";
40
40
  import {
41
41
  serveWorkerJobs
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  readV2ArchiveOffThread2,
3
3
  serveV2ArchiveReads2
4
- } from "./index-zgj2mxrn.js";
4
+ } from "./index-mtpsqxev.js";
5
5
  import"./index-8sqebjzk.js";
6
6
  import"./index-2qtx0q6h.js";
7
7
  import"./index-x2n261wp.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.49.71",
3
+ "version": "0.49.73",
4
4
  "type": "module",
5
5
  "description": "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
6
6
  "main": "dist/index.js",
@@ -1,155 +0,0 @@
1
- import {
2
- DEFAULT_LOCAL_EMBEDDING_MODEL
3
- } from "./index-vcegxfwg.js";
4
- import {
5
- log2
6
- } from "./index-tm11k42a.js";
7
- import {
8
- isSynapseEmbeddingTruncated,
9
- SynapseEmbeddingProvider
10
- } from "./index-5rcjs14a.js";
11
- import {
12
- LocalEmbeddingProvider
13
- } from "./index-txcs0vnj.js";
14
- import {
15
- OpenAICompatibleEmbeddingProvider,
16
- getProjectEmbeddingSnapshot2,
17
- embedBatchForProject2
18
- } from "./index-e9wkbh8y.js";
19
- import {
20
- isEmbeddingHostBusy2
21
- } from "./index-9p40dgkm.js";
22
- import {
23
- saveEmbeddingIfHashMatches
24
- } from "./index-yhzhdp3m.js";
25
-
26
- // ../plugin/src/features/magic-context/memory/cosine-similarity.ts
27
- function cosineSimilarity(a, b) {
28
- if (a.length !== b.length) {
29
- return 0;
30
- }
31
- let dotProduct = 0;
32
- let normA = 0;
33
- let normB = 0;
34
- for (let index = 0;index < a.length; index++) {
35
- dotProduct += a[index] * b[index];
36
- normA += a[index] * a[index];
37
- normB += b[index] * b[index];
38
- }
39
- const denominator = Math.sqrt(normA) * Math.sqrt(normB);
40
- return denominator === 0 ? 0 : dotProduct / denominator;
41
- }
42
-
43
- // ../plugin/src/features/magic-context/memory/embedding.ts
44
- var DEFAULT_EMBEDDING_CONFIG = {
45
- provider: "local",
46
- model: DEFAULT_LOCAL_EMBEDDING_MODEL,
47
- local_runtime: "auto"
48
- };
49
- var embeddingConfig = DEFAULT_EMBEDDING_CONFIG;
50
- var provider = null;
51
- function createProvider(config) {
52
- if (config.provider === "off") {
53
- return null;
54
- }
55
- if (config.provider === "openai-compatible") {
56
- return new OpenAICompatibleEmbeddingProvider({
57
- endpoint: config.endpoint,
58
- model: config.model,
59
- apiKey: config.api_key,
60
- inputType: config.input_type,
61
- queryInputType: config.query_input_type,
62
- queryInstruction: config.query_instruction,
63
- documentPrefix: config.document_prefix,
64
- truncate: config.truncate,
65
- dimensions: config.dimensions,
66
- maxInputTokens: config.max_input_tokens
67
- });
68
- }
69
- if (config.provider === "local") {
70
- return new LocalEmbeddingProvider(config.model, config.max_input_tokens, config.local_dtype, config.local_runtime);
71
- }
72
- if (config.provider === "synapse") {
73
- const synapse = config;
74
- return new SynapseEmbeddingProvider({
75
- connectionFile: synapse.synapse_connection_file ?? "",
76
- projectRoot: "",
77
- session: "embedding",
78
- model: synapse.model,
79
- fingerprint: synapse.synapse_fingerprint,
80
- tableEpoch: synapse.synapse_table_epoch,
81
- dims: synapse.synapse_dims,
82
- recommendedBatch: synapse.synapse_recommended_batch,
83
- recommendedTokenBudget: synapse.synapse_recommended_token_budget,
84
- descriptor: synapse.synapse_descriptor,
85
- provenance: synapse.synapse_provenance
86
- });
87
- }
88
- throw new Error("Unknown embedding provider");
89
- }
90
- function getOrCreateProvider() {
91
- if (provider) {
92
- return provider;
93
- }
94
- provider = createProvider(embeddingConfig);
95
- return provider;
96
- }
97
- function isEmbeddingEnabled() {
98
- return embeddingConfig.provider !== "off";
99
- }
100
- async function embedText(text, signal) {
101
- const currentProvider = getOrCreateProvider();
102
- if (!currentProvider) {
103
- return null;
104
- }
105
- if (!await currentProvider.initialize()) {
106
- return null;
107
- }
108
- const vector = await currentProvider.embed(text, signal);
109
- return vector && !isSynapseEmbeddingTruncated(vector) ? vector : null;
110
- }
111
-
112
- // ../plugin/src/features/magic-context/memory/embedding-backfill.ts
113
- async function ensureMemoryEmbeddings2(args) {
114
- if (isEmbeddingHostBusy2())
115
- return args.existingEmbeddings;
116
- const snapshot = getProjectEmbeddingSnapshot2(args.projectIdentity);
117
- if (!snapshot?.enabled) {
118
- return args.existingEmbeddings;
119
- }
120
- const missingMemories = args.memories.filter((memory) => !args.existingEmbeddings.has(memory.id));
121
- if (missingMemories.length === 0) {
122
- return args.existingEmbeddings;
123
- }
124
- try {
125
- const result = await embedBatchForProject2(args.projectIdentity, missingMemories.map((memory) => memory.content));
126
- if (!result) {
127
- return args.existingEmbeddings;
128
- }
129
- const staged = new Map;
130
- args.db.transaction(() => {
131
- for (const [index, memory] of missingMemories.entries()) {
132
- const embedding = result.vectors[index];
133
- if (!embedding) {
134
- continue;
135
- }
136
- const saved = saveEmbeddingIfHashMatches(args.db, memory.id, embedding, result.modelId, memory.normalizedHash);
137
- if (saved) {
138
- staged.set(memory.id, { embedding, modelId: result.modelId });
139
- }
140
- }
141
- }).immediate();
142
- const currentSnapshot = getProjectEmbeddingSnapshot2(args.projectIdentity);
143
- if (!currentSnapshot || currentSnapshot.generation !== result.generation) {
144
- return args.existingEmbeddings;
145
- }
146
- for (const [id, embedding] of staged) {
147
- args.existingEmbeddings.set(id, embedding);
148
- }
149
- } catch (error) {
150
- log2("[magic-context] failed to backfill memory embeddings:", error);
151
- }
152
- return args.existingEmbeddings;
153
- }
154
-
155
- export { cosineSimilarity, isEmbeddingEnabled, embedText, ensureMemoryEmbeddings2 };