@cortexkit/pi-magic-context 0.49.78 → 0.49.80

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 (27) hide show
  1. package/dist/auto-search-worker.js +2 -2
  2. package/dist/chunk-embedding-write-worker.js +1 -1
  3. package/dist/{embedding-backfill-h1wjzh1n.js → embedding-backfill-arvg2p6f.js} +1 -1
  4. package/dist/{index-mm9y1m77.js → index-0t9xfj3x.js} +1 -1
  5. package/dist/{index-9a92hc6c.js → index-0th11rhf.js} +1 -1
  6. package/dist/{index-6bjc4pam.js → index-5009ew3c.js} +33 -13
  7. package/dist/{index-gczr1m66.js → index-5tkveh4p.js} +4 -6
  8. package/dist/{index-xxjx713t.js → index-6crdakkm.js} +3 -3
  9. package/dist/{index-cyzsn2hb.js → index-fvfq9gva.js} +1 -1
  10. package/dist/{index-077gbj21.js → index-hnvq96j6.js} +3 -3
  11. package/dist/{index-apff8dej.js → index-hpbdnbtf.js} +1 -1
  12. package/dist/{index-6gwasf0v.js → index-nh4srq1p.js} +5 -3
  13. package/dist/{index-wmkkxwvf.js → index-pdrberjp.js} +1 -1
  14. package/dist/{index-px5g7twk.js → index-pz85rpzf.js} +16 -11
  15. package/dist/index.js +157 -77
  16. package/dist/{message-index-bounded-cv87994v.js → message-index-bounded-sra4jpac.js} +3 -3
  17. package/dist/migration-worker.js +1 -1
  18. package/dist/raw-ordinal-warmup-worker.js +4 -4
  19. package/dist/{read-session-chunk-ygwyfvtr.js → read-session-chunk-wek7gb7j.js} +2 -2
  20. package/dist/{render-gbeyky54.js → render-fhrce5g6.js} +5 -5
  21. package/dist/{search-archive-hrp4sa2w.js → search-archive-661vc3fb.js} +4 -4
  22. package/dist/{search-zazd3b88.js → search-vw6ps2me.js} +5 -5
  23. package/dist/{storage-tags-zzttnzn6.js → storage-tags-mj9tptw2.js} +1 -1
  24. package/dist/subagent-entry.js +10 -10
  25. package/dist/tag-snapshot-worker-pi.js +3 -3
  26. package/dist/{v2-archive-reader-w897mvf5.js → v2-archive-reader-zndhp4c4.js} +1 -1
  27. package/package.json +1 -1
@@ -27,11 +27,11 @@ serveWorkerJobs(async (initial, port) => {
27
27
  { Database, registerSqliteDiagnosticSink },
28
28
  { log }
29
29
  ] = await Promise.all([
30
- import("./embedding-backfill-h1wjzh1n.js"),
30
+ import("./embedding-backfill-arvg2p6f.js"),
31
31
  import("./embedding-cache-7rp4gqzr.js"),
32
32
  import("./storage-memory-0ndn65fm.js"),
33
33
  import("./project-embedding-registry-zgzq9ehw.js"),
34
- import("./search-zazd3b88.js"),
34
+ import("./search-vw6ps2me.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-9a92hc6c.js";
38
+ } from "./index-0th11rhf.js";
39
39
  import"./index-3bb24eb6.js";
40
40
  import"./index-gavj3e6h.js";
41
41
  import"./index-jhmz9tgv.js";
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  ensureMemoryEmbeddings2
3
- } from "./index-gczr1m66.js";
3
+ } from "./index-5tkveh4p.js";
4
4
  import"./index-0bmsfzqf.js";
5
5
  import"./index-9p40dgkm.js";
6
6
  import"./index-hgd00nas.js";
@@ -9,7 +9,7 @@ import {
9
9
  } from "./index-pefn1gt5.js";
10
10
  import {
11
11
  cleanUserText2
12
- } from "./index-apff8dej.js";
12
+ } from "./index-hpbdnbtf.js";
13
13
  import {
14
14
  recordMessageFtsRowid2,
15
15
  recordIndexedMessageTime2,
@@ -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-ygwyfvtr.js"));
1790
+ const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-wek7gb7j.js"));
1791
1791
  const { startMessageTimeBackfill } = await importPluginModule(() => import("./message-time-backfill-8zwv9byv.js"));
1792
1792
  if (signal.aborted)
1793
1793
  return;
@@ -56,7 +56,7 @@ import {
56
56
  import {
57
57
  piHarnessKindFromExecutable,
58
58
  getErrorMessage
59
- } from "./index-9a92hc6c.js";
59
+ } from "./index-0th11rhf.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-xxjx713t.js";
73
+ } from "./index-6crdakkm.js";
74
74
  import {
75
75
  getLastIndexedOrdinal
76
- } from "./index-mm9y1m77.js";
76
+ } from "./index-0t9xfj3x.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-6gwasf0v.js";
92
+ } from "./index-nh4srq1p.js";
93
93
  import {
94
94
  stableStringify,
95
95
  BoundedSessionMap
@@ -142,7 +142,7 @@ import {
142
142
  resolveMemoriesByIdsForSearch2,
143
143
  unifiedSearch2,
144
144
  formatSearchResults2
145
- } from "./index-px5g7twk.js";
145
+ } from "./index-pz85rpzf.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-apff8dej.js";
154
+ } from "./index-hpbdnbtf.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-cyzsn2hb.js";
187
+ } from "./index-fvfq9gva.js";
188
188
  import {
189
189
  computeNormalizedHash
190
190
  } from "./index-9x1f96r8.js";
@@ -704,6 +704,8 @@ var OUTPUT_RESERVE_CAP_RATIO2 = 0.25;
704
704
  var outputReserveConfig;
705
705
  var reserveClampLogSeen = new Set;
706
706
  var apiCache = null;
707
+ var v2DraftModelLimits = new Map;
708
+ var v2DraftModelLimitLogged = new Set;
707
709
  var persistSeedLoaded = false;
708
710
  function persistFilePath() {
709
711
  return join(getMagicContextStorageDir(), `model-context-limits-${getHarness2()}.json`);
@@ -802,9 +804,12 @@ function resolveLimit(limit, providerID, modelID, reserveConfig = outputReserveC
802
804
  }
803
805
  return Math.floor(context - reserve);
804
806
  }
805
- function getSdkWindowGeometry(providerID, modelID, detectedContextLimit, options) {
807
+ function windowMetadata(providerID, modelID) {
806
808
  loadPersistedApiCacheOnce();
807
- const metadata = lookupMetadataWithTagFallback(apiCache, providerID, modelID);
809
+ return (getHarness2() === "opencode2" ? v2DraftModelLimits.get(`${providerID}/${modelID}`) : undefined) ?? lookupMetadataWithTagFallback(apiCache, providerID, modelID);
810
+ }
811
+ function getSdkWindowGeometry(providerID, modelID, detectedContextLimit, options) {
812
+ const metadata = windowMetadata(providerID, modelID);
808
813
  if (!metadata)
809
814
  return;
810
815
  const rawContext = metadata.contextLimit ?? metadata.limit;
@@ -833,8 +838,7 @@ function getSdkContextLimit(providerID, modelID, detectedContextLimit, options)
833
838
  detectedLimitProvenance: options?.detectedLimitProvenance
834
839
  })?.usableSoft;
835
840
  }
836
- loadPersistedApiCacheOnce();
837
- const metadata = lookupMetadataWithTagFallback(apiCache, providerID, modelID);
841
+ const metadata = windowMetadata(providerID, modelID);
838
842
  if (!metadata)
839
843
  return;
840
844
  const rawContext = metadata.contextLimit ?? metadata.limit;
@@ -3839,7 +3843,7 @@ function beginCurateCategoryRun(db, projectIdentity, memories) {
3839
3843
  }));
3840
3844
  return scope;
3841
3845
  }
3842
- function curateTaskStateAfterSuccess(db, projectIdentity, category) {
3846
+ function curateTaskStateAfterCategoryTurn(db, projectIdentity, category) {
3843
3847
  const state = readState(db, projectIdentity);
3844
3848
  return JSON.stringify({
3845
3849
  ...state,
@@ -6555,6 +6559,22 @@ function isDirectiveShapedProjectRule(category, content) {
6555
6559
  // ../plugin/src/features/magic-context/dreamer/curate-memory-safety.ts
6556
6560
  var PROJECT_SCOPED_CATEGORIES = new Set(V2_MEMORY_CATEGORIES);
6557
6561
  var USER_PROFILE_REFERENCE = /\buser(?:[\s_-]+)(?:profile|preferences?)\b|\bU\d+\b/i;
6562
+ var CURATE_SAFETY_REFUSAL_REASONS = [
6563
+ "missing-active-same-category-successor",
6564
+ "user-profile-is-not-project-memory",
6565
+ "directive-shaped-project-rule",
6566
+ "content-loss"
6567
+ ];
6568
+ var refusalReasons = new Set(CURATE_SAFETY_REFUSAL_REASONS);
6569
+ function parseCurateSafetyRefusal(action, output) {
6570
+ if (action !== "archive" && action !== "update")
6571
+ return null;
6572
+ const refusal = /^Skipped (archive|update) for memory \[ID: -?\d+(?:, -?\d+)*\]: curate safety refusal \(([a-z,-]+)\); refused=[1-9]\d*\.$/.exec(output);
6573
+ if (refusal?.[1] !== action || !refusal[2])
6574
+ return null;
6575
+ const reasons = [...new Set(refusal[2].split(","))];
6576
+ return reasons.every((reason) => refusalReasons.has(reason)) ? reasons : null;
6577
+ }
6558
6578
  var refusalCountsBySession = new Map;
6559
6579
  function isSurvivingConsolidationTarget(memory, successor, projectIdentity) {
6560
6580
  return successor !== null && successor.id !== memory.id && successor.status === "active" && successor.supersededByMemoryId === null && (successor.expiresAt === null || successor.expiresAt > Date.now()) && projectIdentity(successor) === projectIdentity(memory) && successor.category === memory.category;
@@ -11042,4 +11062,4 @@ function registerMagicContextTools(pi, opts) {
11042
11062
  }
11043
11063
  }
11044
11064
 
11045
- export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, isCommitRetentionPaused, copyCommitRetentionRecovery, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, parseJsoncRecovering, detectConfigFile, OPENCODE_OUTPUT_CAP, MIN_PLAUSIBLE_CONTEXT_LIMIT, catalogOutputReserve, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, formatWindowSource, isSaneLimit, resolveOutputReserve, getSdkWindowGeometry, getSdkContextLimit, getSdkOutputLimit, getSdkInputLimit, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, noteTouchedAt, noteNudgePickIndex, formatNoteNudge, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, resolvePiRealStableId, isPiContentFallbackId, isPiIndexFallbackId, piContentFallbackIds, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findRestartModelSeedFromBranch, iterateEntriesToRawMessageRange, iterateAsyncEntriesToRawMessageRange, convertEntriesToRawMessages, convertPiAssistantEntryById, convertEntriesToRawMessagePage, countPiRawMessages, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getTaskScheduleState, getFailingDreamTasks, getSkippedDreamTasks, getMostRecentTaskRunAt, pruneNonCanonicalTaskRows, deleteTaskScheduleRowsForProject, seedTaskScheduleState, writeTaskScheduleState, isRetrospectiveWindowProcessed, recordRetrospectiveWindowProcessed, curateCategoryForMemoryCategory, peekCurateCategoryScope, beginCurateCategoryRun, curateTaskStateAfterSuccess, MEMORY_MURAL_BLOCK, buildMagicContextSection, resolveMuralWire, requestToolsFingerprint, classifyRequestToolsChange, requestToolSchemaDigest, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, MEMORY_RENDER_FORMAT_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, withCachedM0MemoryIds, readCachedM0MemoryIds, renderBudgetIdentityChanged, renderedBudgetSnapshot, renderedBudgetShrinkReason, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, TEMPORAL_MARKER_REPLAY_PATTERN, temporalMarkerPrefix, renderUserProfileContent, clearInjectionCache, getVisibleMemoryIds, orderHistorianMemories, renderHistorianMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, resolveWorkspaceRenderContext, sourceNamesForMemories, readM0ProjectMemories, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, resetPrefixTrimFallbackState, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, loadPiConfig, loadPiConfigDetailed, unregisterPiProjectEmbeddings, ensureProjectRegisteredFromPiDirectory, neutralizeOmpMentions, restoreOmpMentions, resolvePiHarnessDetection, resolvePiHarnessKind, readSubagentStartupError, reportSubagentStartupError, legacyTui, canRenderPiRows, piTerminalRows, piOverlayOptions, matchesKey, truncateToWidth, visibleWidth, inheritPiOrdinalAlignment, resolvePiOrdinalAlignment, piRawOrdinalOffsetSource, resolvePiOrdinalAlignmentForContext, isPiOrdinalAlignmentUnanchored, clearPiOrdinalAlignmentSession, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
11065
+ export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, isCommitRetentionPaused, copyCommitRetentionRecovery, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, parseJsoncRecovering, detectConfigFile, OPENCODE_OUTPUT_CAP, MIN_PLAUSIBLE_CONTEXT_LIMIT, catalogOutputReserve, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, formatWindowSource, isSaneLimit, resolveOutputReserve, getSdkWindowGeometry, getSdkContextLimit, getSdkOutputLimit, getSdkInputLimit, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, noteTouchedAt, noteNudgePickIndex, formatNoteNudge, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, resolvePiRealStableId, isPiContentFallbackId, isPiIndexFallbackId, piContentFallbackIds, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findRestartModelSeedFromBranch, iterateEntriesToRawMessageRange, iterateAsyncEntriesToRawMessageRange, convertEntriesToRawMessages, convertPiAssistantEntryById, convertEntriesToRawMessagePage, countPiRawMessages, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getTaskScheduleState, getFailingDreamTasks, getSkippedDreamTasks, getMostRecentTaskRunAt, pruneNonCanonicalTaskRows, deleteTaskScheduleRowsForProject, seedTaskScheduleState, writeTaskScheduleState, isRetrospectiveWindowProcessed, recordRetrospectiveWindowProcessed, curateCategoryForMemoryCategory, peekCurateCategoryScope, beginCurateCategoryRun, curateTaskStateAfterCategoryTurn, MEMORY_MURAL_BLOCK, buildMagicContextSection, resolveMuralWire, requestToolsFingerprint, classifyRequestToolsChange, requestToolSchemaDigest, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, MEMORY_RENDER_FORMAT_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, withCachedM0MemoryIds, readCachedM0MemoryIds, renderBudgetIdentityChanged, renderedBudgetSnapshot, renderedBudgetShrinkReason, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, TEMPORAL_MARKER_REPLAY_PATTERN, temporalMarkerPrefix, renderUserProfileContent, clearInjectionCache, getVisibleMemoryIds, orderHistorianMemories, renderHistorianMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, resolveWorkspaceRenderContext, sourceNamesForMemories, readM0ProjectMemories, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, resetPrefixTrimFallbackState, isDirectiveShapedProjectRule, parseCurateSafetyRefusal, takeCurateSafetyRefusalCount, wakePlaneStatus, loadPiConfig, loadPiConfigDetailed, unregisterPiProjectEmbeddings, ensureProjectRegisteredFromPiDirectory, neutralizeOmpMentions, restoreOmpMentions, resolvePiHarnessDetection, resolvePiHarnessKind, readSubagentStartupError, reportSubagentStartupError, legacyTui, canRenderPiRows, piTerminalRows, piOverlayOptions, matchesKey, truncateToWidth, visibleWidth, inheritPiOrdinalAlignment, resolvePiOrdinalAlignment, piRawOrdinalOffsetSource, resolvePiOrdinalAlignmentForContext, isPiOrdinalAlignmentUnanchored, clearPiOrdinalAlignmentSession, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
@@ -22,7 +22,8 @@ async function ensureMemoryEmbeddings2(args) {
22
22
  if (isEmbeddingHostBusy2())
23
23
  return args.existingEmbeddings;
24
24
  const snapshot = getProjectEmbeddingSnapshot2(args.projectIdentity);
25
- if (!snapshot?.enabled) {
25
+ const expected = args.expectedEmbedding;
26
+ if (!snapshot?.enabled || expected && (snapshot.modelId !== expected.modelId || expected.generation !== undefined && snapshot.generation !== expected.generation)) {
26
27
  return args.existingEmbeddings;
27
28
  }
28
29
  const missing = args.memories.filter((memory) => !args.existingEmbeddings.has(memory.id)).sort((a, b) => a.id - b.id);
@@ -40,7 +41,8 @@ async function ensureMemoryEmbeddings2(args) {
40
41
  text: memory.content,
41
42
  contentSha256: contentSha2562(memory.content)
42
43
  })), undefined, args.db, args.projectIdentity, { maxItemsPerCall: SEARCH_BACKFILL_REQUEST_SIZE });
43
- if (!result) {
44
+ const currentSnapshot = getProjectEmbeddingSnapshot2(args.projectIdentity);
45
+ if (!result || result.modelId !== snapshot.modelId || result.generation !== snapshot.generation || currentSnapshot?.generation !== snapshot.generation) {
44
46
  return args.existingEmbeddings;
45
47
  }
46
48
  const staged = new Map;
@@ -56,10 +58,6 @@ async function ensureMemoryEmbeddings2(args) {
56
58
  }
57
59
  }
58
60
  }).immediate();
59
- const currentSnapshot = getProjectEmbeddingSnapshot2(args.projectIdentity);
60
- if (!currentSnapshot || currentSnapshot.generation !== result.generation) {
61
- return args.existingEmbeddings;
62
- }
63
61
  if (capped && (cursor !== undefined || result.vectors.size < missingMemories.length)) {
64
62
  const nextCursor = start + missingMemories.length < missing.length ? missingMemories.at(-1)?.id : undefined;
65
63
  writeSearchBackfillCursor2(args.projectIdentity, snapshot.generation, cursor, nextCursor);
@@ -40,7 +40,7 @@ import {
40
40
  serializeProcessedImageMarkers,
41
41
  getPendingPiCompactionMarkerState,
42
42
  logPiCompactionMarkerClear
43
- } from "./index-6gwasf0v.js";
43
+ } from "./index-nh4srq1p.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-9a92hc6c.js";
64
+ } from "./index-0th11rhf.js";
65
65
  import {
66
66
  withReadOnlySessionDb,
67
67
  expandToolPart,
68
68
  visitRawSessionMessages2,
69
69
  readRawSessionMessageById2
70
- } from "./index-apff8dej.js";
70
+ } from "./index-hpbdnbtf.js";
71
71
  import {
72
72
  gaDatabasePath2,
73
73
  V2StoreReader2
@@ -6,7 +6,7 @@ import {
6
6
  } from "./index-pefn1gt5.js";
7
7
  import {
8
8
  readRawSessionMessageIdOrdinalsForRange2
9
- } from "./index-apff8dej.js";
9
+ } from "./index-hpbdnbtf.js";
10
10
 
11
11
  // ../plugin/src/tools/ctx-expand/search-archive.ts
12
12
  var archiveReadsOnThisThread = 0;
@@ -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-e9ve3qzt.js"),
142
- import("./read-session-chunk-ygwyfvtr.js"),
143
- import("./render-gbeyky54.js"),
144
- import("./search-archive-hrp4sa2w.js"),
142
+ import("./read-session-chunk-wek7gb7j.js"),
143
+ import("./render-fhrce5g6.js"),
144
+ import("./search-archive-661vc3fb.js"),
145
145
  import("./expand-attachments-8sxeyj26.js")
146
146
  ]);
147
147
  const pool = new V2StoreReaderPool;
@@ -39,7 +39,7 @@ import {
39
39
  providerVisiblePart,
40
40
  getCandidateToolOwners2,
41
41
  pickNearestPriorOwner2
42
- } from "./index-6gwasf0v.js";
42
+ } from "./index-nh4srq1p.js";
43
43
  import {
44
44
  OMO_INTERNAL_INITIATOR_MARKER,
45
45
  isSystemDirective,
@@ -1379,15 +1379,17 @@ function estimateImageTokensFromHeader(header, bytes, jpegReader) {
1379
1379
  function nativeMediaImage(part) {
1380
1380
  if (part.type !== "media" || !isRecord(part.media))
1381
1381
  return;
1382
- const { mediaType, source } = part.media;
1382
+ const { mediaType: assetMediaType, source } = part.media;
1383
+ const encoded = assetMediaType === undefined;
1384
+ const mediaType = encoded && isRecord(source) ? source.mediaType : assetMediaType;
1383
1385
  if (typeof mediaType !== "string" || !mediaType.startsWith("image/"))
1384
1386
  return;
1385
1387
  let inline;
1386
1388
  if (isRecord(source)) {
1387
1389
  const { type, data } = source;
1388
- if (type === "base64" && typeof data === "string" && data.length > 0)
1390
+ if ((type === "base64" || encoded && type === "bytes") && typeof data === "string" && data.length > 0)
1389
1391
  inline = data;
1390
- if (type === "bytes" && data instanceof Uint8Array && data.byteLength > 0)
1392
+ if (!encoded && type === "bytes" && data instanceof Uint8Array && data.byteLength > 0)
1391
1393
  inline = data;
1392
1394
  }
1393
1395
  return { mediaType, inline };
@@ -7,7 +7,7 @@ import {
7
7
  import {
8
8
  getTagsBySession2,
9
9
  getTagsByNumbers2
10
- } from "./index-6gwasf0v.js";
10
+ } from "./index-nh4srq1p.js";
11
11
  import {
12
12
  inRootAsyncContext2,
13
13
  getSqliteDatabasePath2,
@@ -69,7 +69,7 @@ import {
69
69
  } from "./index-yhzhdp3m.js";
70
70
  import {
71
71
  ensureMemoryEmbeddings2
72
- } from "./index-gczr1m66.js";
72
+ } from "./index-5tkveh4p.js";
73
73
  import {
74
74
  getMemorySelectColumns2,
75
75
  isMemoryRow2,
@@ -97,7 +97,7 @@ import {
97
97
  clearIndexedMessages,
98
98
  indexSingleMessage,
99
99
  indexMessagesAfterOrdinal
100
- } from "./index-mm9y1m77.js";
100
+ } from "./index-0t9xfj3x.js";
101
101
  import {
102
102
  MESSAGE_FTS_SESSION_FILTER_SQL,
103
103
  withMessageFtsSessionFilter
@@ -595,19 +595,19 @@ function promoteSessionFactsDurable(db, sessionId, projectPath, facts) {
595
595
  }
596
596
  async function embedPromotedFacts(db, sessionId, projectPath, refs) {
597
597
  for (const ref of refs) {
598
- await embedAndStoreMemory(db, sessionId, projectPath, ref.memoryId, ref.content);
598
+ await embedAndStoreMemory(db, sessionId, projectPath, ref.memoryId);
599
599
  }
600
600
  }
601
- async function embedAndStoreMemory(db, sessionId, projectPath, memoryId, content) {
601
+ async function embedAndStoreMemory(db, sessionId, projectPath, memoryId) {
602
602
  try {
603
- const hashBeforeEmbed = getMemoryById2(db, memoryId)?.normalizedHash;
604
- if (!hashBeforeEmbed) {
603
+ const memory = getMemoryById2(db, memoryId);
604
+ if (!memory?.normalizedHash) {
605
605
  return;
606
606
  }
607
- const result = await embedTextForProject2(projectPath, content);
607
+ const result = await embedTextForProject2(projectPath, memory.content);
608
608
  if (result) {
609
609
  db.transaction(() => {
610
- saveEmbeddingIfHashMatches(db, memoryId, result.vector, result.modelId, hashBeforeEmbed);
610
+ saveEmbeddingIfHashMatches(db, memoryId, result.vector, result.modelId, memory.normalizedHash);
611
611
  }).immediate();
612
612
  }
613
613
  } catch (error) {
@@ -2687,17 +2687,19 @@ async function getSemanticScores(args) {
2687
2687
  if (!args.queryEmbedding || args.memories.length === 0 || !args.queryModelId || args.queryModelId === "off") {
2688
2688
  return semanticScores;
2689
2689
  }
2690
+ const expectedEmbedding = { modelId: args.queryModelId, generation: args.queryGeneration };
2690
2691
  if (!args.workspace?.isWorkspaced) {
2691
2692
  const cachedEmbeddings = getProjectEmbeddings2(args.db, args.projectPath, args.queryModelId);
2692
2693
  const embeddings = args.backfillMemoryEmbeddings === false ? cachedEmbeddings : await ensureMemoryEmbeddings2({
2693
2694
  db: args.db,
2694
2695
  projectIdentity: args.projectPath,
2695
2696
  memories: args.memories,
2696
- existingEmbeddings: cachedEmbeddings
2697
+ existingEmbeddings: cachedEmbeddings,
2698
+ expectedEmbedding
2697
2699
  });
2698
2700
  for (const memory of args.memories) {
2699
2701
  const memoryEmbedding = embeddings.get(memory.id);
2700
- if (!memoryEmbedding) {
2702
+ if (!memoryEmbedding || memoryEmbedding.modelId !== args.queryModelId) {
2701
2703
  continue;
2702
2704
  }
2703
2705
  semanticScores.set(memory.id, normalizeCosineScore(cosineSimilarity(args.queryEmbedding, memoryEmbedding.embedding)));
@@ -2721,7 +2723,8 @@ async function getSemanticScores(args) {
2721
2723
  db: args.db,
2722
2724
  projectIdentity: args.projectPath,
2723
2725
  memories: ownMemories,
2724
- existingEmbeddings: ownEmbeddings
2726
+ existingEmbeddings: ownEmbeddings,
2727
+ expectedEmbedding
2725
2728
  });
2726
2729
  }
2727
2730
  for (const identity of workspace.identities) {
@@ -2849,6 +2852,7 @@ async function searchMemories(args) {
2849
2852
  backfillMemoryEmbeddings: args.backfillMemoryEmbeddings,
2850
2853
  queryEmbedding: args.queryEmbedding,
2851
2854
  queryModelId: args.queryModelId,
2855
+ queryGeneration: args.queryGeneration,
2852
2856
  workspace: args.workspace
2853
2857
  });
2854
2858
  const sourceNameByMemoryId = sourceNamesForSearchMemories({
@@ -3751,6 +3755,7 @@ async function unifiedSearch2(db, sessionId, projectPath, query, options = {}) {
3751
3755
  memoryEnabled: true,
3752
3756
  queryEmbedding,
3753
3757
  queryModelId: embeddingModelId && embeddingModelId !== "off" ? embeddingModelId : null,
3758
+ queryGeneration: queryContract?.generation ?? embeddingSnapshot?.generation,
3754
3759
  workspace,
3755
3760
  visibleMemoryIds: options.visibleMemoryIds,
3756
3761
  backfillMemoryEmbeddings: options.backfillMemoryEmbeddings,
package/dist/index.js CHANGED
@@ -93,7 +93,7 @@ import {
93
93
  curateCategoryForMemoryCategory,
94
94
  peekCurateCategoryScope,
95
95
  beginCurateCategoryRun,
96
- curateTaskStateAfterSuccess,
96
+ curateTaskStateAfterCategoryTurn,
97
97
  MEMORY_MURAL_BLOCK,
98
98
  buildMagicContextSection,
99
99
  resolveMuralWire,
@@ -134,6 +134,7 @@ import {
134
134
  stripMemoryMuralBlock,
135
135
  resetPrefixTrimFallbackState,
136
136
  isDirectiveShapedProjectRule,
137
+ parseCurateSafetyRefusal,
137
138
  takeCurateSafetyRefusalCount,
138
139
  wakePlaneStatus,
139
140
  loadPiConfig,
@@ -165,7 +166,7 @@ import {
165
166
  registerTodoStateLifecycle,
166
167
  syncCtxMemoryToolEnabled,
167
168
  registerMagicContextTools
168
- } from "./index-6bjc4pam.js";
169
+ } from "./index-5009ew3c.js";
169
170
  import"./index-4knyh1kt.js";
170
171
  import {
171
172
  canonicalModelIdentity,
@@ -417,7 +418,7 @@ import {
417
418
  setSessionWorkMetrics,
418
419
  getSessionWorkMetrics,
419
420
  resolveEpochFloorForPass
420
- } from "./index-6gwasf0v.js";
421
+ } from "./index-nh4srq1p.js";
421
422
  import {
422
423
  textMentionsRecentCommit,
423
424
  hasMeaningfulUserText2,
@@ -468,7 +469,7 @@ import {
468
469
  openCurrentDatabase,
469
470
  openDatabaseAsync,
470
471
  closeDatabase
471
- } from "./index-9a92hc6c.js";
472
+ } from "./index-0th11rhf.js";
472
473
  import {
473
474
  LkgRecoveryFenceError,
474
475
  clearLkgFenceProcessState,
@@ -598,7 +599,7 @@ import {
598
599
  getSourceContents,
599
600
  recordSubagentInvocation,
600
601
  getLatestHistorianInvocationId
601
- } from "./index-xxjx713t.js";
602
+ } from "./index-6crdakkm.js";
602
603
  import {
603
604
  resolveOpenCodeDbPath,
604
605
  assertOpenCodeStoreGeneration,
@@ -664,7 +665,7 @@ import {
664
665
  getRawSessionTagKeysThrough2,
665
666
  getLegacyProtectedTailStartOrdinal2,
666
667
  readSessionChunk2
667
- } from "./index-apff8dej.js";
668
+ } from "./index-hpbdnbtf.js";
668
669
  import"./index-nvh6d3bz.js";
669
670
  import {
670
671
  formatSynapseLaneDescriptor
@@ -704,7 +705,7 @@ import {
704
705
  clearCompressionDepthRange,
705
706
  cleanSearchText,
706
707
  matchedSearchSnippet
707
- } from "./index-mm9y1m77.js";
708
+ } from "./index-0t9xfj3x.js";
708
709
  import {
709
710
  rememberV1HiddenRun
710
711
  } from "./index-6x556c2q.js";
@@ -831,8 +832,8 @@ import {
831
832
  scheduleClearAndReindex,
832
833
  clearSessionTracking,
833
834
  createAutoSearchDiagnostics
834
- } from "./index-px5g7twk.js";
835
- import"./index-gczr1m66.js";
835
+ } from "./index-pz85rpzf.js";
836
+ import"./index-5tkveh4p.js";
836
837
  import"./index-3s39a1md.js";
837
838
  import {
838
839
  DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
@@ -862,11 +863,11 @@ import {
862
863
  drainPiTagSnapshotSession,
863
864
  assertPiTagSnapshotReady,
864
865
  ensurePiTagSnapshotReady
865
- } from "./index-wmkkxwvf.js";
866
+ } from "./index-pdrberjp.js";
866
867
  import"./index-71rg8j43.js";
867
868
  import"./index-8d2z6503.js";
868
- import"./index-077gbj21.js";
869
- import"./index-cyzsn2hb.js";
869
+ import"./index-hnvq96j6.js";
870
+ import"./index-fvfq9gva.js";
870
871
  import {
871
872
  __toESM
872
873
  } from "./index-22jkk6wg.js";
@@ -3618,7 +3619,7 @@ function startHostStallProfilerSwitch() {
3618
3619
  // package.json
3619
3620
  var package_default = {
3620
3621
  name: "@cortexkit/pi-magic-context",
3621
- version: "0.49.78",
3622
+ version: "0.49.80",
3622
3623
  type: "module",
3623
3624
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3624
3625
  main: "dist/index.js",
@@ -18211,8 +18212,11 @@ function validateCurateAssistantText(text) {
18211
18212
  }
18212
18213
  return text;
18213
18214
  }
18215
+ function emptyCurateMemoryOperations() {
18216
+ return { totalCalls: 0, completedActions: [], refusals: [] };
18217
+ }
18214
18218
  function inspectCurateMemoryOperations(messages) {
18215
- const summary = { totalCalls: 0, completedActions: [] };
18219
+ const summary = emptyCurateMemoryOperations();
18216
18220
  if (!Array.isArray(messages))
18217
18221
  return summary;
18218
18222
  for (const message of messages) {
@@ -18227,28 +18231,69 @@ function inspectCurateMemoryOperations(messages) {
18227
18231
  const toolName = part.tool ?? part.name;
18228
18232
  if (toolName !== "ctx_memory")
18229
18233
  continue;
18234
+ const state = isRecord(part.state) ? part.state : null;
18235
+ const input = isRecord(state?.input) ? state.input : null;
18236
+ const action = input?.action;
18237
+ const output = state?.status === "completed" && typeof state.output === "string" ? state.output : null;
18238
+ if (output && (action === "get" || action === "list") && /^(?:Found \d+ (?:active )?memor(?:y|ies):|No active memories found\.$|id -?\d+: not found or not visible from this project)/.test(output))
18239
+ continue;
18230
18240
  summary.totalCalls += 1;
18231
- if (!isRecord(part.state) || part.state.status !== "completed")
18241
+ if (!output)
18232
18242
  continue;
18233
- const input = isRecord(part.state.input) ? part.state.input : null;
18234
- const action = input?.action;
18235
- const output = typeof part.state.output === "string" ? part.state.output : "";
18236
- if (output === "completed" && (action === "merge" || action === "archive" || action === "update") || action === "merge" && output.startsWith("Merged memories") || action === "archive" && output.startsWith("Archived memor") || action === "update" && output.startsWith("Updated memory"))
18243
+ if (action === "merge" && output.startsWith("Merged memories") || action === "archive" && output.startsWith("Archived memor") || action === "update" && output.startsWith("Updated memory")) {
18237
18244
  summary.completedActions.push(action);
18245
+ } else {
18246
+ const reasons = parseCurateSafetyRefusal(action, output);
18247
+ if (reasons)
18248
+ summary.refusals.push(reasons);
18249
+ }
18238
18250
  }
18239
18251
  }
18240
18252
  return summary;
18241
18253
  }
18254
+ function unrecognisedCurateOperations(operations) {
18255
+ return operations.totalCalls - operations.completedActions.length - operations.refusals.length;
18256
+ }
18257
+ function validateCurateOutput(messages, text, transport) {
18258
+ const operations = inspectCurateMemoryOperations(messages);
18259
+ if (text)
18260
+ validateCurateAssistantText(text);
18261
+ if (operations.completedActions.length || operations.refusals.length && !unrecognisedCurateOperations(operations))
18262
+ return operations;
18263
+ if (!text && transport === "child")
18264
+ throw new Error("Dreamer returned no assistant output.");
18265
+ if (operations.totalCalls > 0)
18266
+ throw new Error("Curate returned no completed ctx_memory tool result.");
18267
+ if (!text)
18268
+ throw new Error("Dreamer returned no assistant output.");
18269
+ return operations;
18270
+ }
18242
18271
  function formatExpiredArchiveProgress(count) {
18243
18272
  return `curate: archived ${count} expired ${count === 1 ? "memory" : "memories"}`;
18244
18273
  }
18245
- function formatCurateMemoryOperations(actions) {
18274
+ function formatCurateMemoryOperations(operations) {
18275
+ const { completedActions: actions, refusals } = operations;
18276
+ if (!actions.length && !refusals.length)
18277
+ return null;
18246
18278
  const actionCounts = new Map;
18247
18279
  for (const action of actions)
18248
18280
  actionCounts.set(action, (actionCounts.get(action) ?? 0) + 1);
18249
18281
  const actionDetail = [...actionCounts].map(([action, count]) => count === 1 ? action : `${action} ×${count}`).join(", ");
18250
- const noun = actions.length === 1 ? "operation" : "operations";
18251
- return `curate: ${actions.length} memory ${noun} applied${actionDetail ? ` (${actionDetail})` : ""}`;
18282
+ const applied = actions.length ? `${actions.length} memory ${actions.length === 1 ? "operation" : "operations"} applied (${actionDetail})` : "no changes";
18283
+ const detail = [`curate: ${applied}`];
18284
+ if (refusals.length) {
18285
+ const reasonCounts = new Map;
18286
+ for (const reasons of refusals) {
18287
+ for (const reason of reasons)
18288
+ reasonCounts.set(reason, (reasonCounts.get(reason) ?? 0) + 1);
18289
+ }
18290
+ const countedReasons = [...reasonCounts].sort(([a], [b]) => a.localeCompare(b)).map(([reason, count]) => `${reason} ×${count}`).join(", ");
18291
+ detail.push(`${refusals.length} ${refusals.length === 1 ? "operation" : "operations"} refused (${countedReasons})`);
18292
+ }
18293
+ const unrecognised = unrecognisedCurateOperations(operations);
18294
+ if (unrecognised)
18295
+ detail.push(`${unrecognised} with an unrecognised result`);
18296
+ return detail.join("; ");
18252
18297
  }
18253
18298
  function requireDreamClient(client) {
18254
18299
  if (!client)
@@ -18456,6 +18501,7 @@ function createDreamTaskExecutor(deps) {
18456
18501
  };
18457
18502
  return writtenIds.length || deletedIds.length || archivedIds.length || mergedIds.length ? changes : null;
18458
18503
  }
18504
+ let curateCategory;
18459
18505
  try {
18460
18506
  const skip = (reason) => {
18461
18507
  log2(`[dreamer] ${config.task}: skipped (${reason})`);
@@ -18767,7 +18813,10 @@ function createDreamTaskExecutor(deps) {
18767
18813
  computeMemoryDelta,
18768
18814
  reportProgress,
18769
18815
  leaseAcquisition,
18770
- moduleRoute
18816
+ moduleRoute,
18817
+ onCurateCategory: (category) => {
18818
+ curateCategory = category;
18819
+ }
18771
18820
  });
18772
18821
  } catch (error) {
18773
18822
  if (error instanceof DreamTokenBudgetExceeded) {
@@ -18785,7 +18834,11 @@ function createDreamTaskExecutor(deps) {
18785
18834
  transient,
18786
18835
  error: brief,
18787
18836
  failureDetail: formatDreamRunFailure(failure),
18788
- ...retrospectiveOverflow ? { schedulePatch: retrospectiveOverflow.schedulePatch } : {}
18837
+ ...retrospectiveOverflow ? { schedulePatch: retrospectiveOverflow.schedulePatch } : curateCategory && !transient ? {
18838
+ schedulePatch: {
18839
+ taskStateJson: curateTaskStateAfterCategoryTurn(db, projectIdentity, curateCategory)
18840
+ }
18841
+ } : {}
18789
18842
  };
18790
18843
  } finally {
18791
18844
  deps.onProgress?.(null, config.task);
@@ -19292,6 +19345,8 @@ async function runAgenticTask(config, ctx, helpers) {
19292
19345
  const scope = beginCurateCategoryRun(db, projectIdentity, loadActiveMemoryPromptMemories(db, projectIdentity));
19293
19346
  curateMemories = scope?.memories ?? [];
19294
19347
  curateCategory = scope?.category;
19348
+ if (curateCategory)
19349
+ helpers.onCurateCategory(curateCategory);
19295
19350
  log2(`[dreamer] curate pool: category=${curateCategory ?? "none"} in_scope=${curateMemories.length} expired_archived=${expiredArchived}`);
19296
19351
  if (curateMemories.length === 0) {
19297
19352
  const progress = expiredArchived > 0 ? formatExpiredArchiveProgress(expiredArchived) : "curate: no populated project-memory category";
@@ -19319,15 +19374,11 @@ async function runAgenticTask(config, ctx, helpers) {
19319
19374
  if (task === "maintain-docs" && hasCurrentDocsProposal(docsDir)) {
19320
19375
  const reason = "pending proposal matches current docs";
19321
19376
  helpers.recordRun("completed", null, { progress: reason });
19322
- return {
19323
- status: "completed",
19324
- detail: reason,
19325
- ...changes ? { schedulePatch: { taskStateJson: JSON.stringify({ head: changes.head }) } } : {}
19326
- };
19377
+ return { status: "completed", detail: reason };
19327
19378
  }
19328
19379
  const curateChunks = curateMemories ? chunkCurateMemories(curateMemories, Math.max(4000, Math.floor(resolveRetrospectiveUsableInputTokens(config, deps) * 2))) : [];
19329
19380
  const batches = task === "curate" ? curateChunks : [{ memories: [], crossChunkCandidates: [] }];
19330
- const completedActions = [];
19381
+ const curateOperations = emptyCurateMemoryOperations();
19331
19382
  let curateRefused = 0;
19332
19383
  let run = {
19333
19384
  output: [],
@@ -19376,14 +19427,7 @@ async function runAgenticTask(config, ctx, helpers) {
19376
19427
  parseDocsProposalOutput(text);
19377
19428
  if (task !== "curate")
19378
19429
  return text;
19379
- const memoryOperations = inspectCurateMemoryOperations(completion.messages);
19380
- if (text)
19381
- validateCurateAssistantText(text);
19382
- if (memoryOperations.totalCalls > 0 && memoryOperations.completedActions.length === 0)
19383
- throw new Error("Curate returned no completed ctx_memory tool result.");
19384
- if (!text && memoryOperations.completedActions.length === 0)
19385
- throw new Error("Dreamer returned no assistant output.");
19386
- return { text: text || null, memoryOperations };
19430
+ return validateCurateOutput(completion.messages, text, "hidden");
19387
19431
  }
19388
19432
  });
19389
19433
  childSessionId = hidden.childSessionId;
@@ -19442,24 +19486,15 @@ async function runAgenticTask(config, ctx, helpers) {
19442
19486
  parseDocsProposalOutput(text);
19443
19487
  return text;
19444
19488
  }
19445
- const memoryOperations = inspectCurateMemoryOperations(messages);
19446
- if (text)
19447
- validateCurateAssistantText(text);
19448
- if (memoryOperations.completedActions.length > 0) {
19449
- return { text, memoryOperations };
19450
- }
19451
- if (!text)
19452
- throw new Error("Dreamer returned no assistant output.");
19453
- if (memoryOperations.totalCalls > 0) {
19454
- throw new Error("Curate returned no completed ctx_memory tool result.");
19455
- }
19456
- return { text, memoryOperations };
19489
+ return validateCurateOutput(messages, text, "child");
19457
19490
  }
19458
19491
  });
19459
19492
  promptSettled = true;
19460
19493
  }
19461
- if (task === "curate") {
19462
- completedActions.push(...run.validated.memoryOperations.completedActions);
19494
+ if (typeof run.validated !== "string") {
19495
+ curateOperations.totalCalls += run.validated.totalCalls;
19496
+ curateOperations.completedActions.push(...run.validated.completedActions);
19497
+ curateOperations.refusals.push(...run.validated.refusals);
19463
19498
  curateRefused += takeCurateSafetyRefusalCount(childSessionId ?? "");
19464
19499
  }
19465
19500
  if (childSessionId && !deps.hiddenCompletionExecutor) {
@@ -19475,17 +19510,15 @@ async function runAgenticTask(config, ctx, helpers) {
19475
19510
  childSessionId = null;
19476
19511
  }
19477
19512
  }
19478
- if (task === "curate")
19479
- run.validated = {
19480
- text: null,
19481
- memoryOperations: { totalCalls: completedActions.length, completedActions }
19482
- };
19483
19513
  if (leaseLost)
19484
19514
  throw new Error("Dream lease lost during task");
19485
19515
  if (curateRefused > 0) {
19486
19516
  helpers.reportProgress(curateRefused, curateRefused);
19487
19517
  log2(`[dreamer] curate safety summary: refused=${curateRefused}`);
19488
19518
  }
19519
+ const unrecognised = unrecognisedCurateOperations(curateOperations);
19520
+ if (unrecognised > 0)
19521
+ log2(`[dreamer] curate result summary: unrecognised=${unrecognised}`);
19489
19522
  recordInvocation("completed", run.output);
19490
19523
  if (task === "maintain-docs" && docsHashes && changes) {
19491
19524
  try {
@@ -19505,13 +19538,12 @@ async function runAgenticTask(config, ctx, helpers) {
19505
19538
  return { status: "failed", error: reason };
19506
19539
  }
19507
19540
  }
19508
- const curateOutput = task === "curate" ? run.validated : undefined;
19509
19541
  const curateScopeProgress = task === "curate" && curateCategory && curateMemories ? `curate: ${curateCategory} (${curateMemories.length})` : null;
19510
19542
  const progress = [
19511
19543
  curateScopeProgress,
19512
19544
  expiredArchived > 0 ? formatExpiredArchiveProgress(expiredArchived) : null,
19513
- curateOutput && curateOutput.memoryOperations.completedActions.length > 0 ? formatCurateMemoryOperations(curateOutput.memoryOperations.completedActions) : null,
19514
- curateRefused > 0 ? `curate: refused ${curateRefused} unsafe mutation(s)` : null
19545
+ formatCurateMemoryOperations(curateOperations),
19546
+ curateRefused > 0 && !curateOperations.refusals.length ? `curate: refused ${curateRefused} unsafe mutation(s)` : null
19515
19547
  ].filter((value) => Boolean(value)).join("; ");
19516
19548
  const curateCount = task === "curate" && curateCategory ? loadActiveMemoryPromptMemories(db, projectIdentity).filter((memory) => curateCategoryForMemoryCategory(memory.category) === curateCategory).length : undefined;
19517
19549
  const curateBacklog = curateCount !== undefined && curateCategory ? {
@@ -19530,7 +19562,7 @@ async function runAgenticTask(config, ctx, helpers) {
19530
19562
  ...curateBacklog ? { backlog: curateBacklog } : {},
19531
19563
  ...curateCategory ? {
19532
19564
  schedulePatch: {
19533
- taskStateJson: curateTaskStateAfterSuccess(db, projectIdentity, curateCategory)
19565
+ taskStateJson: curateTaskStateAfterCategoryTurn(db, projectIdentity, curateCategory)
19534
19566
  }
19535
19567
  } : {}
19536
19568
  };
@@ -21949,15 +21981,23 @@ class PiSubagentRunner {
21949
21981
  });
21950
21982
  if (settled)
21951
21983
  return;
21952
- const settleCompletedToolOnlyDreamer = (messages, completedMemoryCalls) => {
21953
- if (!DREAMER_ACTION_AGENTS.has(options.agent) || completedMemoryCalls.length === 0) {
21984
+ const toolResults = (messages) => {
21985
+ if (options.accountingTask === "curate")
21986
+ return {
21987
+ curateMemoryToolCalls: extractCurateMemoryToolCalls(messages)
21988
+ };
21989
+ const completedToolCalls = extractCompletedToolCalls(messages).filter((call) => call.name === "ctx_memory");
21990
+ return completedToolCalls.length ? { completedToolCalls } : {};
21991
+ };
21992
+ const settleToolOnlyDreamer = (messages, results) => {
21993
+ if (!DREAMER_ACTION_AGENTS.has(options.agent) || !results.completedToolCalls?.length && !results.curateMemoryToolCalls?.length) {
21954
21994
  return false;
21955
21995
  }
21956
21996
  settle({
21957
21997
  ok: true,
21958
21998
  assistantText: "",
21959
21999
  toolCallCount: countToolCalls(messages),
21960
- completedToolCalls: completedMemoryCalls,
22000
+ ...results,
21961
22001
  durationMs: Date.now() - startTime,
21962
22002
  meta: { stderr: stderr.length > 0 ? stderr : undefined }
21963
22003
  });
@@ -21965,11 +22005,10 @@ class PiSubagentRunner {
21965
22005
  };
21966
22006
  if (sawAgentEnd) {
21967
22007
  const outputMessages = agentEndMessages ?? accumulatedMessages;
21968
- const completedCalls = extractCompletedToolCalls(outputMessages);
21969
- const completedMemoryCalls = completedCalls.filter((call) => call.name === "ctx_memory");
22008
+ const results = toolResults(outputMessages);
21970
22009
  const trimmedAssistantText = finalAssistantText?.trim() ?? null;
21971
22010
  if (trimmedAssistantText === null || trimmedAssistantText.length === 0) {
21972
- if (settleCompletedToolOnlyDreamer(outputMessages, completedMemoryCalls))
22011
+ if (settleToolOnlyDreamer(outputMessages, results))
21973
22012
  return;
21974
22013
  const emptyAssistantReason = trimmedAssistantText === null ? "pi agent_end did not include an assistant message" : "pi assistant produced empty text";
21975
22014
  settle({
@@ -21998,7 +22037,7 @@ class PiSubagentRunner {
21998
22037
  ok: true,
21999
22038
  assistantText: trimmedAssistantText,
22000
22039
  toolCallCount: countToolCalls(outputMessages),
22001
- ...completedMemoryCalls.length > 0 ? { completedToolCalls: completedMemoryCalls } : {},
22040
+ ...results,
22002
22041
  durationMs: Date.now() - startTime,
22003
22042
  meta: { stderr: stderr.length > 0 ? stderr : undefined }
22004
22043
  });
@@ -22032,8 +22071,7 @@ class PiSubagentRunner {
22032
22071
  });
22033
22072
  return;
22034
22073
  }
22035
- const completedMemoryCalls = extractCompletedToolCalls(accumulatedMessages).filter((call) => call.name === "ctx_memory");
22036
- if (settleCompletedToolOnlyDreamer(accumulatedMessages, completedMemoryCalls))
22074
+ if (settleToolOnlyDreamer(accumulatedMessages, toolResults(accumulatedMessages)))
22037
22075
  return;
22038
22076
  settle({
22039
22077
  ok: false,
@@ -22252,7 +22290,7 @@ function extractFinalAssistant(messages) {
22252
22290
  }
22253
22291
  return { text: null, stopReason: null, errorMessage: null };
22254
22292
  }
22255
- function extractCompletedToolCalls(messages) {
22293
+ function extractToolInvocations(messages) {
22256
22294
  const invocations = new Map;
22257
22295
  for (const message of messages) {
22258
22296
  if (typeof message !== "object" || message === null)
@@ -22274,6 +22312,10 @@ function extractCompletedToolCalls(messages) {
22274
22312
  invocations.set(id, { name, arguments: args });
22275
22313
  }
22276
22314
  }
22315
+ return invocations;
22316
+ }
22317
+ function extractCompletedToolCalls(messages) {
22318
+ const invocations = extractToolInvocations(messages);
22277
22319
  const completed = [];
22278
22320
  const seen = new Set;
22279
22321
  for (const message of messages) {
@@ -22293,6 +22335,36 @@ function extractCompletedToolCalls(messages) {
22293
22335
  }
22294
22336
  return completed;
22295
22337
  }
22338
+ function extractCurateMemoryToolCalls(messages) {
22339
+ const calls = new Map;
22340
+ for (const [id, call] of extractToolInvocations(messages)) {
22341
+ if (call.name === "ctx_memory")
22342
+ calls.set(id, {
22343
+ id,
22344
+ name: call.name,
22345
+ arguments: call.arguments,
22346
+ status: "pending"
22347
+ });
22348
+ }
22349
+ for (const message of messages) {
22350
+ if (typeof message !== "object" || message === null)
22351
+ continue;
22352
+ const result = message;
22353
+ if (result.role !== "toolResult" || typeof result.toolCallId !== "string" || typeof result.isError !== "boolean")
22354
+ continue;
22355
+ const call = calls.get(result.toolCallId);
22356
+ if (call?.status !== "pending" || typeof result.toolName === "string" && result.toolName !== call.name)
22357
+ continue;
22358
+ call.status = result.isError ? "error" : "completed";
22359
+ if (Array.isArray(result.content)) {
22360
+ const text = result.content.flatMap((part) => part?.type === "text" && typeof part.text === "string" ? [part.text] : []).join(`
22361
+ `);
22362
+ if (text)
22363
+ call.output = text;
22364
+ }
22365
+ }
22366
+ return [...calls.values()];
22367
+ }
22296
22368
  function countToolCalls(messages) {
22297
22369
  let count = 0;
22298
22370
  for (const msg of messages) {
@@ -23389,7 +23461,7 @@ function createPiDreamerClient(opts, onAdjunctsRefreshNeeded = opts.onAdjunctsRe
23389
23461
  dreamSession.messages = [
23390
23462
  makeMessage("user", [{ type: "text", text: userMessage }]),
23391
23463
  makeMessage("assistant", [
23392
- ...syntheticToolParts(result.toolCallCount ?? 0, result.completedToolCalls),
23464
+ ...syntheticToolParts(result.toolCallCount ?? 0, result.completedToolCalls, accountingTask === "curate" ? result.curateMemoryToolCalls ?? [] : undefined),
23393
23465
  ...result.assistantText ? [{ type: "text", text: result.assistantText }] : []
23394
23466
  ])
23395
23467
  ];
@@ -23505,9 +23577,17 @@ function extractBodyAgent(args) {
23505
23577
  const agent = body.agent;
23506
23578
  return typeof agent === "string" && agent.length > 0 ? agent : undefined;
23507
23579
  }
23508
- function syntheticToolParts(count, completedCalls = []) {
23509
- const safe = Math.max(completedCalls.length, Math.max(0, Math.floor(count)));
23510
- const completed = completedCalls.map((call, index) => ({
23580
+ function syntheticToolParts(count, completedCalls = [], curateCalls) {
23581
+ const calls = curateCalls ? curateCalls.map((call) => ({
23582
+ type: "tool",
23583
+ callID: call.id,
23584
+ tool: call.name,
23585
+ state: {
23586
+ status: call.status,
23587
+ input: call.arguments,
23588
+ ...call.output === undefined ? {} : call.status === "error" ? { error: call.output } : { output: call.output }
23589
+ }
23590
+ })) : completedCalls.map((call, index) => ({
23511
23591
  type: "tool",
23512
23592
  callID: `pi-completed-tool-${index}`,
23513
23593
  tool: call.name,
@@ -23517,12 +23597,12 @@ function syntheticToolParts(count, completedCalls = []) {
23517
23597
  output: "completed"
23518
23598
  }
23519
23599
  }));
23520
- const remaining = Array.from({ length: safe - completed.length }, () => ({
23600
+ const remaining = Array.from({ length: Math.max(0, Math.floor(count) - calls.length) }, () => ({
23521
23601
  type: "tool",
23522
23602
  tool: "investigation",
23523
23603
  state: { input: { description: "investigation step" } }
23524
23604
  }));
23525
- return [...completed, ...remaining];
23605
+ return [...calls, ...remaining];
23526
23606
  }
23527
23607
  function makeMessage(role, parts) {
23528
23608
  return {
@@ -3,7 +3,7 @@ import {
3
3
  withIndexChunk2,
4
4
  yieldIndexChunk2
5
5
  } from "./index-2qtx0q6h.js";
6
- import"./index-6gwasf0v.js";
6
+ import"./index-nh4srq1p.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-apff8dej.js";
18
+ import"./index-hpbdnbtf.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-mm9y1m77.js";
27
+ } from "./index-0t9xfj3x.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-9a92hc6c.js";
20
+ } from "./index-0th11rhf.js";
21
21
  import"./index-fapenpch.js";
22
22
  import"./index-3bb24eb6.js";
23
23
  import"./index-8sqebjzk.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-w897mvf5.js");
22
+ const { serveV2ArchiveReads } = await import("./v2-archive-reader-zndhp4c4.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-hrp4sa2w.js");
54
+ const { renderSearchArchive } = await import("./search-archive-661vc3fb.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-cv87994v.js"),
84
+ import("./message-index-bounded-sra4jpac.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-zzttnzn6.js");
98
+ const { scanTagOwnerSummary, scanTagOwnerDelta } = await import("./storage-tags-mj9tptw2.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-apff8dej.js";
42
- import"./index-6gwasf0v.js";
41
+ } from "./index-hpbdnbtf.js";
42
+ import"./index-nh4srq1p.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-xxjx713t.js";
6
+ } from "./index-6crdakkm.js";
7
7
  import"./index-k7a8x7ba.js";
8
- import"./index-mm9y1m77.js";
8
+ import"./index-0t9xfj3x.js";
9
9
  import"./index-hgd00nas.js";
10
10
  import"./index-nvh6d3bz.js";
11
11
  import"./index-cxczethe.js";
12
- import"./index-apff8dej.js";
13
- import"./index-6gwasf0v.js";
12
+ import"./index-hpbdnbtf.js";
13
+ import"./index-nh4srq1p.js";
14
14
  import"./index-6x556c2q.js";
15
15
  import"./index-5rcjs14a.js";
16
16
  import"./index-vcegxfwg.js";
17
- import"./index-9a92hc6c.js";
17
+ import"./index-0th11rhf.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-cyzsn2hb.js";
4
- import"./index-077gbj21.js";
3
+ } from "./index-fvfq9gva.js";
4
+ import"./index-hnvq96j6.js";
5
5
  import"./index-8d2z6503.js";
6
- import"./index-apff8dej.js";
7
- import"./index-6gwasf0v.js";
6
+ import"./index-hpbdnbtf.js";
7
+ import"./index-nh4srq1p.js";
8
8
  import"./index-6x556c2q.js";
9
9
  import"./index-vcegxfwg.js";
10
10
  import"./index-jhmz9tgv.js";
@@ -5,11 +5,11 @@ import {
5
5
  resolveMemoriesByIdsForSearch2,
6
6
  unifiedSearch2,
7
7
  formatSearchResults2
8
- } from "./index-px5g7twk.js";
8
+ } from "./index-pz85rpzf.js";
9
9
  import"./index-k7a8x7ba.js";
10
- import"./index-mm9y1m77.js";
10
+ import"./index-0t9xfj3x.js";
11
11
  import"./index-8d2z6503.js";
12
- import"./index-gczr1m66.js";
12
+ import"./index-5tkveh4p.js";
13
13
  import"./index-29nw7n1r.js";
14
14
  import"./index-0bmsfzqf.js";
15
15
  import"./index-9p40dgkm.js";
@@ -17,8 +17,8 @@ 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-apff8dej.js";
21
- import"./index-6gwasf0v.js";
20
+ import"./index-hpbdnbtf.js";
21
+ import"./index-nh4srq1p.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-6gwasf0v.js";
65
+ } from "./index-nh4srq1p.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-apff8dej.js";
3
+ } from "./index-hpbdnbtf.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-9a92hc6c.js";
17
+ } from "./index-0th11rhf.js";
18
18
  import"./index-fapenpch.js";
19
19
  import"./index-3bb24eb6.js";
20
20
  import"./index-8sqebjzk.js";
@@ -34,7 +34,7 @@ import {
34
34
  resolvePiHarnessKind,
35
35
  reportSubagentStartupError,
36
36
  registerMagicContextTools
37
- } from "./index-6bjc4pam.js";
37
+ } from "./index-5009ew3c.js";
38
38
  import"./index-vcegxfwg.js";
39
39
  import"./index-5rcjs14a.js";
40
40
  import"./index-cxczethe.js";
@@ -44,17 +44,17 @@ 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-px5g7twk.js";
48
- import"./index-xxjx713t.js";
49
- import"./index-mm9y1m77.js";
50
- import"./index-6gwasf0v.js";
47
+ import"./index-pz85rpzf.js";
48
+ import"./index-6crdakkm.js";
49
+ import"./index-0t9xfj3x.js";
50
+ import"./index-nh4srq1p.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-077gbj21.js";
56
- import"./index-cyzsn2hb.js";
57
- import"./index-gczr1m66.js";
55
+ import"./index-hnvq96j6.js";
56
+ import"./index-fvfq9gva.js";
57
+ import"./index-5tkveh4p.js";
58
58
  import"./index-29nw7n1r.js";
59
59
  import"./index-3s39a1md.js";
60
60
  import"./index-1ts77n1b.js";
@@ -8,7 +8,7 @@ import"./index-tm11k42a.js";
8
8
  import {
9
9
  LATEST_SUPPORTED_VERSION,
10
10
  getPersistedSchemaVersion
11
- } from "./index-9a92hc6c.js";
11
+ } from "./index-0th11rhf.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-6gwasf0v.js";
31
+ } from "./index-nh4srq1p.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-wmkkxwvf.js";
38
+ } from "./index-pdrberjp.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-077gbj21.js";
4
+ } from "./index-hnvq96j6.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.78",
3
+ "version": "0.49.80",
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",