@cortexkit/pi-magic-context 0.49.27 → 0.49.29

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.
@@ -24,11 +24,11 @@ var [
24
24
  { Database, registerSqliteDiagnosticSink },
25
25
  { log }
26
26
  ] = await Promise.all([
27
- import("./embedding-backfill-25fp3b8w.js"),
27
+ import("./embedding-backfill-v83xh6e8.js"),
28
28
  import("./embedding-cache-7rp4gqzr.js"),
29
29
  import("./storage-memory-0ndn65fm.js"),
30
- import("./project-embedding-registry-hc4ahjdt.js"),
31
- import("./search-vkkfg27q.js"),
30
+ import("./project-embedding-registry-wwbhm9rf.js"),
31
+ import("./search-pq1nqjp4.js"),
32
32
  import("./compartment-chunk-embedding-pkk5beqp.js"),
33
33
  import("./embedding-activity-ew6dshfd.js"),
34
34
  import("./harness-9872e0ym.js"),
@@ -33,7 +33,7 @@ import"./index-48twbev2.js";
33
33
  import {
34
34
  LATEST_SUPPORTED_VERSION,
35
35
  enforceSchemaFence
36
- } from "./index-5d506f7y.js";
36
+ } from "./index-9pfffeqj.js";
37
37
  import"./index-0s14xaca.js";
38
38
  import"./index-g026ztby.js";
39
39
  import"./index-135e8hvg.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  ensureMemoryEmbeddings2
3
- } from "./index-wjbqw6r1.js";
4
- import"./index-xa90f88m.js";
3
+ } from "./index-4nny4r40.js";
4
+ import"./index-0jykn0dw.js";
5
5
  import"./index-9p40dgkm.js";
6
6
  import"./index-yhzhdp3m.js";
7
7
  import"./index-4zemngt7.js";
@@ -61,13 +61,12 @@ import {
61
61
  logPiCompactionMarkerClear,
62
62
  withReadOnlySessionDb,
63
63
  expandToolPart,
64
- isCoveredInstructionRow,
65
64
  hasRawMessageProvider2,
66
65
  setRawMessageProvider2,
67
66
  visitRawSessionMessages2,
68
67
  readRawSessionMessageById2,
69
68
  readSessionChunk2
70
- } from "./index-kagezf2h.js";
69
+ } from "./index-yvb1cz6b.js";
71
70
  import {
72
71
  isRecord,
73
72
  providerVisibleMessage,
@@ -107,7 +106,7 @@ import {
107
106
  isPidAlive,
108
107
  readProcessStartTime,
109
108
  getErrorMessage
110
- } from "./index-5d506f7y.js";
109
+ } from "./index-9pfffeqj.js";
111
110
  import {
112
111
  BoundedSessionMap,
113
112
  resolveOpenCodeDbPath,
@@ -141,10 +140,10 @@ import {
141
140
  unregisterProjectEmbedding2,
142
141
  getProjectEmbeddingSnapshot2,
143
142
  embedTextForProject2
144
- } from "./index-xa90f88m.js";
143
+ } from "./index-0jykn0dw.js";
145
144
  import {
146
145
  getLastIndexedOrdinal
147
- } from "./index-v0ht940m.js";
146
+ } from "./index-vppykq05.js";
148
147
  import {
149
148
  V2_MEMORY_CATEGORIES,
150
149
  CATEGORY_PRIORITY,
@@ -181,7 +180,7 @@ import {
181
180
  resolveMemoriesByIdsForSearch2,
182
181
  unifiedSearch2,
183
182
  formatSearchResults2
184
- } from "./index-sdsnb5b6.js";
183
+ } from "./index-wcma874r.js";
185
184
  import {
186
185
  computeCueContentHash,
187
186
  getMuralCueState,
@@ -212,7 +211,7 @@ import {
212
211
  } from "./index-6wdwv3a6.js";
213
212
  import {
214
213
  renderSearchArchive2
215
- } from "./index-vea2d9ka.js";
214
+ } from "./index-fp40yrsy.js";
216
215
  import {
217
216
  computeNormalizedHash
218
217
  } from "./index-9x1f96r8.js";
@@ -273,6 +272,30 @@ function migrateLegacyAgentEnabledInMemory(rawConfig, warnings) {
273
272
  return patched;
274
273
  }
275
274
 
275
+ // ../plugin/src/config/commit-retention-recovery.ts
276
+ var pausedRetention = new WeakSet;
277
+ var RETENTION_FIELD = "memory.git_commit_indexing.max_commits";
278
+ function applyCommitRetentionRecovery(config, recoveredFieldPaths, warnings) {
279
+ if (!recoveredFieldPaths.some((path) => RETENTION_FIELD === path || RETENTION_FIELD.startsWith(`${path}.`)))
280
+ return;
281
+ pausedRetention.add(config.memory.git_commit_indexing);
282
+ const message = `${RETENTION_FIELD}: retention eviction is paused until the invalid value is fixed.`;
283
+ const index = warnings.findIndex((warning) => warning.includes(RETENTION_FIELD));
284
+ if (index >= 0)
285
+ warnings[index] = `${warnings[index]} ${message}`;
286
+ else
287
+ warnings.push(message);
288
+ }
289
+ function isCommitRetentionPaused(settings) {
290
+ return pausedRetention.has(settings);
291
+ }
292
+ function copyCommitRetentionRecovery(from, to) {
293
+ if (pausedRetention.has(from))
294
+ pausedRetention.add(to);
295
+ else
296
+ pausedRetention.delete(to);
297
+ }
298
+
276
299
  // ../plugin/src/shared/config-diagnostics.ts
277
300
  var CONFIG_WARNING_CLASS = {
278
301
  FILE_PARSE: "file-parse",
@@ -2269,7 +2292,11 @@ function restoreTrustedValuesOverInvalidProjectValues(args) {
2269
2292
  if (!changed)
2270
2293
  break;
2271
2294
  }
2272
- return { warnings, restoredTopLevelKeys: [...restoredTopLevelKeys] };
2295
+ return {
2296
+ warnings,
2297
+ restoredTopLevelKeys: [...restoredTopLevelKeys],
2298
+ restoredFieldPaths: [...restored]
2299
+ };
2273
2300
  }
2274
2301
 
2275
2302
  // ../plugin/src/config/prune-config-leaf.ts
@@ -5529,6 +5556,12 @@ function noteLkgCapturedPrefix(sessionId) {
5529
5556
  }
5530
5557
 
5531
5558
  // ../plugin/src/hooks/magic-context/lkg-slot.ts
5559
+ var POSITIONAL_SYSTEM_KEY = "\x00mc-system:";
5560
+ function lkgInputIdentity(id, role, index) {
5561
+ if (typeof id === "string" && id.length > 0)
5562
+ return id.startsWith(POSITIONAL_SYSTEM_KEY) ? null : id;
5563
+ return role === "system" ? `${POSITIONAL_SYSTEM_KEY}${index}` : null;
5564
+ }
5532
5565
  var LKG_SINGLE_SLOT_BYTES = 72 * 1024 * 1024;
5533
5566
  var LKG_TOTAL_BYTES = 160 * 1024 * 1024;
5534
5567
  var LKG_METADATA_BYTES = 256;
@@ -5957,11 +5990,8 @@ function noteEntry(sessionId, input) {
5957
5990
  const slot = getSlot(sessionId);
5958
5991
  if (!slot)
5959
5992
  return null;
5960
- const messages = input.some((message) => isCoveredInstructionRow(message.info)) ? input.filter((message) => !isCoveredInstructionRow(message.info)) : input;
5961
- const entryInputIds = messages.map((message) => {
5962
- const id = message.info?.id;
5963
- return typeof id === "string" ? id : "";
5964
- });
5993
+ const messages = input;
5994
+ const entryInputIds = messages.map((message, index) => lkgInputIdentity(message.info?.id, message.info?.role, index) ?? "");
5965
5995
  const anchorIndex = entryInputIds.indexOf(slot.lastInputMessageId);
5966
5996
  if (anchorIndex < 0)
5967
5997
  return null;
@@ -10441,28 +10471,28 @@ var EMBEDDING_AFFECTING_KEYS = new Set([
10441
10471
  "embedding.query_instruction",
10442
10472
  "embedding.document_prefix",
10443
10473
  "embedding.fallback_provider",
10444
- "subc",
10474
+ "embedding.local_runtime",
10475
+ "embedding.local_dtype",
10445
10476
  "subc.connection_file",
10446
- "shadow_embedding"
10477
+ "shadow_embedding.enabled",
10478
+ "memory.enabled",
10479
+ "memory.git_commit_indexing.enabled",
10480
+ "allow_home_project"
10447
10481
  ]);
10448
10482
  var LITERAL_CONFIG_TOKEN_RE = /\{(?:env|file):[^}]+\}/;
10449
- function embeddingConfigHasLiteralTokens(embedding) {
10450
- if (!embedding)
10451
- return false;
10452
- for (const value of Object.values(embedding)) {
10483
+ function affectsEmbeddingRegistration(path) {
10484
+ return [...EMBEDDING_AFFECTING_KEYS].some((field) => field === path || field.startsWith(`${path}.`));
10485
+ }
10486
+ function untrustedConfigFieldPaths(detailed) {
10487
+ const paths = (detailed.recoveredFieldPaths ?? detailed.recoveredTopLevelKeys).filter(affectsEmbeddingRegistration);
10488
+ paths.push(...detailed.substitutionFailures.map((failure) => failure.keyPath).filter(affectsEmbeddingRegistration));
10489
+ for (const [key, value] of Object.entries(detailed.config.embedding)) {
10453
10490
  if (typeof value === "string" && LITERAL_CONFIG_TOKEN_RE.test(value)) {
10454
- return true;
10491
+ paths.push(`embedding.${key}`);
10455
10492
  }
10456
10493
  }
10457
- return false;
10494
+ return [...new Set(paths)].sort();
10458
10495
  }
10459
- var EMBEDDING_AFFECTING_TOP_LEVEL_KEYS = new Set([
10460
- "embedding",
10461
- "memory",
10462
- "experimental",
10463
- "subc",
10464
- "shadow_embedding"
10465
- ]);
10466
10496
  var EMBEDDING_WARNING_TERMS = [
10467
10497
  "api_key",
10468
10498
  "endpoint",
@@ -10487,21 +10517,12 @@ function isConfigLoadUntrusted(detailed) {
10487
10517
  return true;
10488
10518
  }
10489
10519
  for (const failure of detailed.substitutionFailures) {
10490
- if (EMBEDDING_AFFECTING_KEYS.has(failure.keyPath)) {
10491
- return true;
10492
- }
10493
10520
  if (failure.keyPath === "<unknown>" && warningLooksEmbeddingRelated(failure.message)) {
10494
10521
  return true;
10495
10522
  }
10496
10523
  }
10497
- for (const recoveredKey of detailed.recoveredTopLevelKeys) {
10498
- if (EMBEDDING_AFFECTING_TOP_LEVEL_KEYS.has(recoveredKey)) {
10499
- return true;
10500
- }
10501
- }
10502
- if (embeddingConfigHasLiteralTokens(detailed.config.embedding)) {
10524
+ if (untrustedConfigFieldPaths(detailed).length > 0)
10503
10525
  return true;
10504
- }
10505
10526
  return false;
10506
10527
  }
10507
10528
  function describeFailure(detailed) {
@@ -10514,8 +10535,9 @@ function describeFailure(detailed) {
10514
10535
  if (detailed.substitutionFailures.length > 0) {
10515
10536
  parts.push(`substitution=${detailed.substitutionFailures.map((failure) => `${failure.source}:${failure.keyPath}`).join(",")}`);
10516
10537
  }
10517
- if (detailed.recoveredTopLevelKeys.length > 0) {
10518
- parts.push(`recovered=${detailed.recoveredTopLevelKeys.join(",")}`);
10538
+ const recovered = detailed.recoveredFieldPaths ?? detailed.recoveredTopLevelKeys;
10539
+ if (recovered.length > 0) {
10540
+ parts.push(`recovered=${recovered.join(",")}`);
10519
10541
  }
10520
10542
  return parts.length > 0 ? parts.join("; ") : detailed.loadOutcome;
10521
10543
  }
@@ -10523,7 +10545,8 @@ function logConfigFailureOnce(projectIdentity, detailed) {
10523
10545
  const signature = sha256Prefix(JSON.stringify({
10524
10546
  outcomes: detailed.sources,
10525
10547
  substitutions: detailed.substitutionFailures.map((failure) => `${failure.source}:${failure.keyPath}:${failure.message}`).sort(),
10526
- recoveredTopLevelKeys: [...detailed.recoveredTopLevelKeys].sort()
10548
+ recoveredTopLevelKeys: [...detailed.recoveredTopLevelKeys].sort(),
10549
+ recoveredFieldPaths: detailed.recoveredFieldPaths?.slice().sort()
10527
10550
  }));
10528
10551
  const existing = loggedFailureSignatures.get(projectIdentity) ?? new Set;
10529
10552
  if (existing.has(signature))
@@ -10539,9 +10562,14 @@ function handleUntrustedLoad(db, projectIdentity, directory, detailed) {
10539
10562
  logConfigFailureOnce(projectIdentity, detailed);
10540
10563
  return true;
10541
10564
  }
10542
- registerProjectInObservationMode2(db, projectIdentity, directory, detailed.config.embedding, describeFailure(detailed));
10565
+ registerProjectInObservationMode2(db, projectIdentity, directory, detailed.config.embedding, describeFailure(detailed), untrustedConfigMemoryMessage(detailed));
10543
10566
  return true;
10544
10567
  }
10568
+ function untrustedConfigMemoryMessage(detailed) {
10569
+ const fields = untrustedConfigFieldPaths(detailed);
10570
+ const cause = fields.length > 0 ? `has invalid embedding or project identity settings: ${fields.join(", ")}` : Object.values(detailed.sources).includes("legacy-config-unmigrated") ? "is awaiting config migration" : Object.values(detailed.sources).some((source) => source === "project-file-parse-error" || source === "project-file-io-error") ? "could not be read or parsed" : "has invalid embedding settings";
10571
+ return `Cross-session memory is off for this project because magic-context.jsonc ${cause}.`;
10572
+ }
10545
10573
 
10546
10574
  // ../plugin/src/plugin/embedding-routing.ts
10547
10575
  var SYNAPSE_PROBE_TTL_MS = 60000;
@@ -10823,7 +10851,7 @@ function mergeRawConfigs(base, override) {
10823
10851
  }
10824
10852
  return merged;
10825
10853
  }
10826
- function parsePiConfig(rawConfig, recoveredTopLevelKeys = []) {
10854
+ function parsePiConfig(rawConfig, recoveredTopLevelKeys = [], recoveredFieldPaths = []) {
10827
10855
  const preMigrationWarnings = [];
10828
10856
  if (Object.hasOwn(rawConfig, "clear_reasoning_age")) {
10829
10857
  preMigrationWarnings.push("clear_reasoning_age is deprecated and ignored. Magic Context now keeps reasoning up to a token budget, keep_reasoning_tokens (default 10,000). Remove the key, or set keep_reasoning_tokens to a token count.");
@@ -10888,10 +10916,12 @@ function parsePiConfig(rawConfig, recoveredTopLevelKeys = []) {
10888
10916
  }
10889
10917
  if (prunedLeaves.length === issuePaths.length) {
10890
10918
  patched[key] = prunedBlock;
10919
+ recoveredFieldPaths.push(...prunedLeaves.map((leaf) => `${key}.${leaf}`));
10891
10920
  warnings.push(`"${key}": invalid nested field(s) ${prunedLeaves.map((leaf) => `"${key}.${leaf}"`).join(", ")}, using defaults for those.`);
10892
10921
  continue;
10893
10922
  }
10894
10923
  }
10924
+ recoveredFieldPaths.push(key);
10895
10925
  if (isAgentConfig) {
10896
10926
  delete patched[key];
10897
10927
  warnings.push(`"${key}": invalid agent configuration, ignoring. Check your magic-context.jsonc.`);
@@ -10911,6 +10941,7 @@ function parsePiConfig(rawConfig, recoveredTopLevelKeys = []) {
10911
10941
  return { config: retryParsed.data, warnings };
10912
10942
  }
10913
10943
  warnings.push("Config recovery failed, using all defaults.");
10944
+ recoveredFieldPaths.push("embedding", "memory", "subc", "shadow_embedding", "allow_home_project");
10914
10945
  return { config: defaults, warnings };
10915
10946
  }
10916
10947
  function collectPiSchemaIssuePaths(rawConfig) {
@@ -11041,6 +11072,7 @@ function loadPiConfigDetailed(opts = {}, applyRuntimeGlobals = true) {
11041
11072
  let rawConfig = trustedProfiledRaw;
11042
11073
  const trustedBaseConfig = parsePiConfig(trustedProfiledRaw).config;
11043
11074
  let projectRestoredTopLevelKeys = [];
11075
+ let projectRestoredFieldPaths = [];
11044
11076
  if (projectLayer) {
11045
11077
  rawConfig = mergeRawConfigs(rawConfig, profileResolution.projectBase);
11046
11078
  for (const warning of dropInheritedEmbeddingKeyOnRedirect(projectRaw, rawConfig, profileResolution.userBase)) {
@@ -11063,11 +11095,14 @@ function loadPiConfigDetailed(opts = {}, applyRuntimeGlobals = true) {
11063
11095
  warnings.push(`[project config] ${warning}`);
11064
11096
  }
11065
11097
  projectRestoredTopLevelKeys = restoredOverProject.restoredTopLevelKeys;
11098
+ projectRestoredFieldPaths = restoredOverProject.restoredFieldPaths;
11066
11099
  }
11067
11100
  const hasDeprecatedProtectedTags = Object.hasOwn(userRaw, "protected_tags") || Object.hasOwn(projectRaw, "protected_tags") || Object.hasOwn(rawConfig, "protected_tags");
11068
11101
  const recoveredTopLevelKeys = [];
11102
+ const recoveredFieldPaths = [];
11069
11103
  const cacheTtlConfigured = Object.hasOwn(rawConfig, "cache_ttl");
11070
- const parsed = parsePiConfig(rawConfig, recoveredTopLevelKeys);
11104
+ const parsed = parsePiConfig(rawConfig, recoveredTopLevelKeys, recoveredFieldPaths);
11105
+ recoveredFieldPaths.push(...projectRestoredFieldPaths);
11071
11106
  Object.defineProperty(parsed.config, "cacheTtlConfigured", {
11072
11107
  value: cacheTtlConfigured
11073
11108
  });
@@ -11084,6 +11119,7 @@ function loadPiConfigDetailed(opts = {}, applyRuntimeGlobals = true) {
11084
11119
  if (applyRuntimeGlobals) {
11085
11120
  setOutputReserveConfig(parsed.config.output_reserve);
11086
11121
  }
11122
+ applyCommitRetentionRecovery(parsed.config, recoveredFieldPaths, parsed.warnings);
11087
11123
  warnings.push(...parsed.warnings.map((warning) => `[merged config] ${warning}`));
11088
11124
  const substitutionFailures = loadedFiles.flatMap(bindSubstitutionFailures);
11089
11125
  const userLoaded = loadedFiles.find((loaded) => loaded.scope === "user");
@@ -11113,6 +11149,7 @@ function loadPiConfigDetailed(opts = {}, applyRuntimeGlobals = true) {
11113
11149
  sources,
11114
11150
  substitutionFailures,
11115
11151
  recoveredTopLevelKeys,
11152
+ recoveredFieldPaths,
11116
11153
  configParseFailures,
11117
11154
  warningDetails,
11118
11155
  cacheTtlConfigured,
@@ -12748,7 +12785,7 @@ function createCtxMemoryTool(deps) {
12748
12785
  const memoryOwnedByTool = (memory) => workspaceIdentitySet.identities.length > 1 ? targetIdentityForStoredPath(memory.projectPath) === projectIdentity : storedPathBelongsToIdentity(memory.projectPath, projectIdentity);
12749
12786
  const snapshot = getProjectEmbeddingSnapshot2(projectIdentity);
12750
12787
  if (snapshot ? !snapshot.features.memoryEnabled : deps.memoryEnabled === false) {
12751
- return err2("Cross-session memory is disabled for this project.");
12788
+ return err2(snapshot?.memoryDisabledReason ?? "Cross-session memory is disabled for this project.");
12752
12789
  }
12753
12790
  const sessionId = ctx.sessionManager.getSessionId();
12754
12791
  let curateSuccessor = null;
@@ -14853,4 +14890,4 @@ function registerMagicContextTools(pi, opts) {
14853
14890
  }
14854
14891
  }
14855
14892
 
14856
- export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, 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, LkgRecoveryFenceError, clearLkgFenceProcessState, lkgFenceRequiresRebuild, lkgRecoveryFenceUnclean, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, markLkgRecoveryDirty, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, 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, isPartialCompartmentEnd, readProjectDocsCanonical, providerResponseFailed, isSuccessfulProviderCompletion, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, recordSystemRefreshOwnership, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, acknowledgeSystemPromptDelivery, deferDeliveredSystemRefresh, clearSystemPromptDelivery, saveLkgSlotToDb, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, replayLkg, registerLkgPersistence, LKG_SNAPSHOT_ARRAY, LKG_SNAPSHOT_OBJECT, LKG_SNAPSHOT_KEY, LKG_SNAPSHOT_STRING, LKG_SNAPSHOT_NUMBER, LKG_SNAPSHOT_BOOLEAN, LKG_SNAPSHOT_NULL, LKG_SNAPSHOT_UNDEFINED, contentSnapshotValue, signatureForFields, lkgContentFields, lkgContentDigestFromFields, isLegacyLkgDigest, legacyLkgDigestFromFields, lkgFieldsMatchDigest, exactReusablePrefix, incrementalLkgContentDigests, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, dropSlot, TOOL_SWEEP_SCOPED_MARKER, encodePiContentDecision, decodePiContentDecision, getPiContentDecisions, freezePiContentDecision, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, externalHistorianFailureReason, subprocessExitHistorianFailureReason, countHistorianRuns, recordHistorianRun, summarizeImportance, tallyFactsByCategory, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, noteTouchedAt, noteNudgePickIndex, formatNoteNudge, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, resolvePiRealStableId, isPiContentFallbackId, isPiIndexFallbackId, piContentFallbackIds, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findRestartModelSeedFromBranch, iterateEntriesToRawMessageRange, iterateAsyncEntriesToRawMessageRange, convertEntriesToRawMessages, convertPiAssistantEntryById, convertEntriesToRawMessagePage, countPiRawMessages, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getTaskScheduleState, getFailingDreamTasks, getSkippedDreamTasks, getMostRecentTaskRunAt, pruneNonCanonicalTaskRows, deleteTaskScheduleRowsForProject, seedTaskScheduleState, writeTaskScheduleState, isRetrospectiveWindowProcessed, recordRetrospectiveWindowProcessed, curateCategoryForMemoryCategory, peekCurateCategoryScope, beginCurateCategoryRun, curateTaskStateAfterSuccess, MEMORY_MURAL_BLOCK, buildMagicContextSection, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, MEMORY_RENDER_FORMAT_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, withCachedM0MemoryIds, readCachedM0MemoryIds, renderBudgetIdentityChanged, renderedBudgetSnapshot, renderedBudgetShrinkReason, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, TEMPORAL_MARKER_REPLAY_PATTERN, temporalMarkerPrefix, renderUserProfileContent, clearInjectionCache, getVisibleMemoryIds, orderHistorianMemories, renderHistorianMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, resetPrefixTrimFallbackState, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, loadPiConfig, loadPiConfigDetailed, unregisterPiProjectEmbeddings, ensureProjectRegisteredFromPiDirectory, neutralizeOmpMentions, restoreOmpMentions, resolvePiHarnessDetection, resolvePiHarnessKind, resolvePiOrdinalAlignment, piRawOrdinalOffsetSource, resolvePiOrdinalAlignmentForContext, isPiOrdinalAlignmentUnanchored, clearPiOrdinalAlignmentSession, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
14893
+ 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, LkgRecoveryFenceError, clearLkgFenceProcessState, lkgFenceRequiresRebuild, lkgRecoveryFenceUnclean, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, markLkgRecoveryDirty, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, 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, isPartialCompartmentEnd, readProjectDocsCanonical, providerResponseFailed, isSuccessfulProviderCompletion, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, recordSystemRefreshOwnership, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, acknowledgeSystemPromptDelivery, deferDeliveredSystemRefresh, clearSystemPromptDelivery, saveLkgSlotToDb, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, replayLkg, registerLkgPersistence, LKG_SNAPSHOT_ARRAY, LKG_SNAPSHOT_OBJECT, LKG_SNAPSHOT_KEY, LKG_SNAPSHOT_STRING, LKG_SNAPSHOT_NUMBER, LKG_SNAPSHOT_BOOLEAN, LKG_SNAPSHOT_NULL, LKG_SNAPSHOT_UNDEFINED, contentSnapshotValue, signatureForFields, lkgContentFields, lkgContentDigestFromFields, isLegacyLkgDigest, legacyLkgDigestFromFields, lkgFieldsMatchDigest, exactReusablePrefix, incrementalLkgContentDigests, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, dropSlot, TOOL_SWEEP_SCOPED_MARKER, encodePiContentDecision, decodePiContentDecision, getPiContentDecisions, freezePiContentDecision, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, externalHistorianFailureReason, subprocessExitHistorianFailureReason, countHistorianRuns, recordHistorianRun, summarizeImportance, tallyFactsByCategory, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, noteTouchedAt, noteNudgePickIndex, formatNoteNudge, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, resolvePiRealStableId, isPiContentFallbackId, isPiIndexFallbackId, piContentFallbackIds, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findRestartModelSeedFromBranch, iterateEntriesToRawMessageRange, iterateAsyncEntriesToRawMessageRange, convertEntriesToRawMessages, convertPiAssistantEntryById, convertEntriesToRawMessagePage, countPiRawMessages, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getTaskScheduleState, getFailingDreamTasks, getSkippedDreamTasks, getMostRecentTaskRunAt, pruneNonCanonicalTaskRows, deleteTaskScheduleRowsForProject, seedTaskScheduleState, writeTaskScheduleState, isRetrospectiveWindowProcessed, recordRetrospectiveWindowProcessed, curateCategoryForMemoryCategory, peekCurateCategoryScope, beginCurateCategoryRun, curateTaskStateAfterSuccess, MEMORY_MURAL_BLOCK, buildMagicContextSection, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, MEMORY_RENDER_FORMAT_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, withCachedM0MemoryIds, readCachedM0MemoryIds, renderBudgetIdentityChanged, renderedBudgetSnapshot, renderedBudgetShrinkReason, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, TEMPORAL_MARKER_REPLAY_PATTERN, temporalMarkerPrefix, renderUserProfileContent, clearInjectionCache, getVisibleMemoryIds, orderHistorianMemories, renderHistorianMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, resetPrefixTrimFallbackState, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, loadPiConfig, loadPiConfigDetailed, unregisterPiProjectEmbeddings, ensureProjectRegisteredFromPiDirectory, neutralizeOmpMentions, restoreOmpMentions, resolvePiHarnessDetection, resolvePiHarnessKind, resolvePiOrdinalAlignment, piRawOrdinalOffsetSource, resolvePiOrdinalAlignmentForContext, isPiOrdinalAlignmentUnanchored, clearPiOrdinalAlignmentSession, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
@@ -1371,6 +1371,7 @@ function snapshotFor(registration) {
1371
1371
  runtimeFingerprint: registration.runtimeFingerprint,
1372
1372
  generation: registration.generation,
1373
1373
  features: { ...registration.features },
1374
+ ...registration.memoryDisabledReason ? { memoryDisabledReason: registration.memoryDisabledReason } : {},
1374
1375
  enabled,
1375
1376
  historyEnabled,
1376
1377
  gitCommitEnabled,
@@ -2340,7 +2341,7 @@ async function runShadowWorker() {
2340
2341
  await new Promise((resolve) => setTimeout(resolve, 0));
2341
2342
  }
2342
2343
  }
2343
- function registerProjectInObservationMode2(db, projectIdentity, sourceDirectory, failedConfig, failureSummary) {
2344
+ function registerProjectInObservationMode2(db, projectIdentity, sourceDirectory, failedConfig, failureSummary, memoryDisabledReason) {
2344
2345
  const prior = projectRegistrations.get(projectIdentity);
2345
2346
  const runtimeFingerprint = `observation:${sha256Prefix(failureSummary)}`;
2346
2347
  const generation = prior?.runtimeFingerprint === runtimeFingerprint && prior.observationMode ? prior.generation : ++globalRegistrationGeneration;
@@ -2355,7 +2356,8 @@ function registerProjectInObservationMode2(db, projectIdentity, sourceDirectory,
2355
2356
  features: { memoryEnabled: false, gitCommitEnabled: false },
2356
2357
  modelId: "off",
2357
2358
  chunkModelId: "off",
2358
- observationMode: true
2359
+ observationMode: true,
2360
+ memoryDisabledReason
2359
2361
  };
2360
2362
  projectRegistrations.set(projectIdentity, registration);
2361
2363
  disposeProvider(prior?.provider ?? null);
@@ -15,7 +15,7 @@ import {
15
15
  OpenAICompatibleEmbeddingProvider,
16
16
  getProjectEmbeddingSnapshot2,
17
17
  embedBatchForProject2
18
- } from "./index-xa90f88m.js";
18
+ } from "./index-0jykn0dw.js";
19
19
  import {
20
20
  isEmbeddingHostBusy2
21
21
  } from "./index-9p40dgkm.js";
@@ -2003,7 +2003,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
2003
2003
  state.running = startMessageFtsRowidMapBackfill2(db, signal).then(async () => {
2004
2004
  if (signal.aborted || !readsOpenCodeStore)
2005
2005
  return;
2006
- const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-1rfprgc1.js"));
2006
+ const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-cfq56m0y.js"));
2007
2007
  const { startMessageTimeBackfill } = await importPluginModule(() => import("./message-time-backfill-e3r8ddh1.js"));
2008
2008
  if (signal.aborted)
2009
2009
  return;
@@ -15,7 +15,7 @@ import {
15
15
  } from "./index-2qtx0q6h.js";
16
16
  import {
17
17
  createFailClosedBlockingError
18
- } from "./index-5d506f7y.js";
18
+ } from "./index-9pfffeqj.js";
19
19
  import {
20
20
  createWorkerShutdown
21
21
  } from "./index-54wmg4rj.js";
@@ -6,7 +6,7 @@ import {
6
6
  } from "./index-my0dn413.js";
7
7
  import {
8
8
  readRawSessionMessageIdOrdinalsForRange2
9
- } from "./index-kagezf2h.js";
9
+ } from "./index-yvb1cz6b.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-my0dn413.js";
10
10
  import {
11
11
  cleanUserText2
12
- } from "./index-kagezf2h.js";
12
+ } from "./index-yvb1cz6b.js";
13
13
  import {
14
14
  recordMessageFtsRowid2,
15
15
  recordIndexedMessageTime2,
@@ -52,7 +52,7 @@ import {
52
52
  getProjectEmbeddingSnapshot2,
53
53
  embedTextForProject2,
54
54
  embedItemsForProject2
55
- } from "./index-xa90f88m.js";
55
+ } from "./index-0jykn0dw.js";
56
56
  import {
57
57
  saveEmbeddingIfHashMatches,
58
58
  getProjectEmbeddings2
@@ -62,7 +62,7 @@ import {
62
62
  isEmbeddingEnabled,
63
63
  embedText,
64
64
  ensureMemoryEmbeddings2
65
- } from "./index-wjbqw6r1.js";
65
+ } from "./index-4nny4r40.js";
66
66
  import {
67
67
  getMemorySelectColumns2,
68
68
  isMemoryRow2,
@@ -82,7 +82,7 @@ import {
82
82
  keywordRelevance,
83
83
  matchedSearchSnippet,
84
84
  getIndexedMessageCorpusSize
85
- } from "./index-v0ht940m.js";
85
+ } from "./index-vppykq05.js";
86
86
  import {
87
87
  MESSAGE_FTS_SESSION_FILTER_SQL,
88
88
  withMessageFtsSessionFilter
@@ -1529,7 +1529,9 @@ async function indexCommitsForProject(db, projectPath, directory, options) {
1529
1529
  return result;
1530
1530
  }
1531
1531
  if (commits.length === 0) {
1532
- result.evicted = enforceProjectCap(db, projectPath, options.maxCommits);
1532
+ if (!options.skipRetention) {
1533
+ result.evicted = enforceProjectCap(db, projectPath, options.maxCommits);
1534
+ }
1533
1535
  log2(`[git-commits] no new commits for ${projectPath} (sinceMs=${sinceMs} latestIndexed=${latestIndexed?.slice(0, 7) ?? "none"} evicted=${result.evicted})`);
1534
1536
  return result;
1535
1537
  }
@@ -1537,7 +1539,9 @@ async function indexCommitsForProject(db, projectPath, directory, options) {
1537
1539
  const upsert = upsertCommits(db, projectPath, commits);
1538
1540
  result.inserted = upsert.inserted;
1539
1541
  result.updated = upsert.updated;
1540
- result.evicted = enforceProjectCap(db, projectPath, options.maxCommits);
1542
+ if (!options.skipRetention) {
1543
+ result.evicted = enforceProjectCap(db, projectPath, options.maxCommits);
1544
+ }
1541
1545
  const snapshot = getProjectEmbeddingSnapshot2(projectPath);
1542
1546
  if (options.skipEmbed || !snapshot?.gitCommitEnabled) {
1543
1547
  log2(`[git-commits] indexed ${projectPath}: scanned=${result.scanned} inserted=${result.inserted} updated=${result.updated} evicted=${result.evicted} embedded=0 (embedding skipped: skipEmbed=${options.skipEmbed === true} gitCommitEnabled=${snapshot?.gitCommitEnabled === true})`);
@@ -2784,8 +2784,8 @@ function resolveEpochFloorForPass(db, sessionId, inputs) {
2784
2784
  }
2785
2785
 
2786
2786
  // ../plugin/src/hooks/magic-context/read-session-db.ts
2787
- function openCodeDbExists() {
2788
- return harnessOwnsOpenCodeStore2() && openCodeDbPathExists(resolveOpenCodeDbPath());
2787
+ function openCodeDbExists(generation = "v1") {
2788
+ return harnessOwnsOpenCodeStore2() && openCodeDbPathExists(resolveOpenCodeDbPath(generation));
2789
2789
  }
2790
2790
  var cachedReadOnlyDbs = {
2791
2791
  v1: null,
@@ -2808,7 +2808,7 @@ function getReadOnlySessionDb(generation = "v1") {
2808
2808
  if (!harnessOwnsOpenCodeStore2()) {
2809
2809
  throw new Error("OpenCode session database is not readable from a Pi-compatible process; its history lives in Pi sessions");
2810
2810
  }
2811
- const resolution = resolveOpenCodeDbPath();
2811
+ const resolution = resolveOpenCodeDbPath(generation);
2812
2812
  const dbPath = resolution.path;
2813
2813
  if (!openCodeDbPathExists(resolution)) {
2814
2814
  throw new Error(`OpenCode session database is unavailable at ${dbPath} (source=${resolution.source})`);
@@ -2829,8 +2829,8 @@ function getReadOnlySessionDb(generation = "v1") {
2829
2829
  clearOpenCodeDbReadFailure();
2830
2830
  return db;
2831
2831
  }
2832
- function withReadOnlySessionDb(fn) {
2833
- return fn(getReadOnlySessionDb());
2832
+ function withReadOnlySessionDb(fn, generation = "v1") {
2833
+ return fn(getReadOnlySessionDb(generation));
2834
2834
  }
2835
2835
  function getRawSessionMessageCountFromDb(db, sessionId) {
2836
2836
  const row = db.prepare(`SELECT COUNT(*) as count FROM message WHERE session_id = ?
@@ -3027,10 +3027,6 @@ function retreatPastHostUnservedRows(messages, exclusiveEnd, floor) {
3027
3027
  end -= 1;
3028
3028
  return end;
3029
3029
  }
3030
- var COVERED_INSTRUCTION_ROW = "coveredInstructionRow";
3031
- function isCoveredInstructionRow(value) {
3032
- return typeof value === "object" && value !== null && value[COVERED_INSTRUCTION_ROW] === true;
3033
- }
3034
3030
 
3035
3031
  // ../plugin/src/hooks/magic-context/read-session-true-raw-tokens.ts
3036
3032
  function completedToolArcCrossesBoundary(invOrdinal, resOrdinal, boundary) {
@@ -5043,6 +5039,10 @@ function readSessionChunk2(sessionId, tokenBudget, offset = 1, eligibleEndOrdina
5043
5039
  const meta = { ordinal: msg.ordinal, messageId: msg.id };
5044
5040
  if (isHostUnservedRow(msg))
5045
5041
  markHostUnservedRow(meta);
5042
+ if (msg.role === "system") {
5043
+ recordFilteredNoise(meta);
5044
+ continue;
5045
+ }
5046
5046
  if (msg.role === "user" && !hasMeaningfulChunkUserText(msg.parts)) {
5047
5047
  const tcSummaries = msg.parts.flatMap((part) => {
5048
5048
  if (expandedResults.has(part))
@@ -5214,4 +5214,4 @@ function readRawSessionSeedTail2(sessionId, boundaryId, onQuery) {
5214
5214
  });
5215
5215
  }
5216
5216
 
5217
- export { detectThinkingBindingMismatch, detectLatestTurnThinkingMismatch, isPrefixBoundThinkingModel, detectOverflow, MAX_EXECUTE_THRESHOLD, escalationBands, MERGED_REASONING_PARTS_PREFIX, decodeMergedReasoningParts, HYGIENE_PROVIDER_UNITS_VERSION, sessionDecisionCalibration, transitionSessionHygieneUnits, computeProtectionWindow, readEpochFloorSnapshot, getProtectionWindowForSession, SESSION_META_SELECT_COLUMNS, META_COLUMNS, BOOLEAN_META_KEYS, NULL_BIND_META_KEYS, isSessionMetaRow, getDefaultSessionMeta, ensureSessionMetaRow, toSessionMeta, persistCachedM0, clearCachedM0M1, isRustMarkerAdmissionFenced, ReplayDocumentError, readReplayEnvelope, readReplayDocument, updateReplayDocument, writeReplayDocument, isProviderOverflowFailClosedProven, getEmergencyRecoveryArmedAt, describeProtectedTailDrainBudgetSkip, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, EMERGENCY_DRAIN_FAILURE_BACKOFF_MS, getProtectedTailDrainBudgetSkip, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, queueAutoSearchHintDecisionRetirement, flushAutoSearchHintDecisionRetirement, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, setNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, setPersistedCompactionMarkerState, parseStrippedPlaceholderState, serializeStrippedPlaceholderState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, THINKING_BINDING_STRIP_ORDER_END_MARKER, thinkingBindingRecoveryFrozenId, COMPACTION_OFF_THINKING_FROZEN_PREFIX, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getProcessedImageStrippedIds, parseProcessedImageMarkers, serializeProcessedImageMarkers, addProcessedImageStrippedIds, getPendingCompactionMarkerState, getCompactionMarkerHealth, loadPostprocessReplaySnapshot, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, logPiCompactionMarkerClear, getSessionsWithPendingPiMarker, setSessionWorkMetrics, getSessionWorkMetrics, resolveEpochFloorForPass, withReadOnlySessionDb, expandToolPart, askAnswerLines, retreatPastHostUnservedRows, isCoveredInstructionRow, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripSystemInjection, isFilePart, hasUserAnswerMetadata, DreamTokenBudgetExceeded, TOKEN_BUDGET_FINALIZE_MESSAGE, TOKEN_BUDGET_TOOL_REFUSAL, registerBudgetFinalizeChild, releaseBudgetFinalizeChild, createDreamTokenBudget, droppedInputMarker, createDroppedInputGuard, isEditTool, applyEditMarkerToInput, modelAcceptsEmptyContent, isAnthropicFamilyRoute, variantChangeBustsProviderCache, isInActiveAnthropicTurn, activeAnthropicTurnStart, hasAnthropicReasoning, findLatestAssistantReasoningMutationExemptMessage, DEFAULT_KEEP_REASONING_TOKENS, resolveKeepReasoningTokens, reasoningStepCost, reasoningBudgetCutoff, reasoningTextAndOpaque, opaqueThinkingCost, estimatePartImageTokens, SKELETON_REAL_INPUT_MAX_BYTES, toolInputStringBytes, resolveHostServedBoundaryId2, hasRawMessageProvider2, setRawMessageProvider2, setBoundedRawMessageProvider2, withRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, RAW_MESSAGE_VISIT_PAGE_SIZE2, visitRawSessionMessages2, visitRawSessionMessagesAsync2, readRawSessionMessageRange2, prepareRawSessionOrdinals2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageOrdinalPage2, getRawSessionStoredMessageCount2, readRawSessionMessageIdOrdinalsForRange2, readRawSessionMessageIdOrdinals2, readRawSessionMessagePartsById2, readRawSessionBoundaryEndpoints2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, resolveHistorianChunkStart2, compareRawSessionMessageOrder2, readRawSessionMessageById2, getRawSessionMessageCount2, RAW_SESSION_TAG_KEY_PAGE_SIZE2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, getProtectedTailStartOrdinal2, readSessionChunk2, getRawSessionMessageIdsThrough2, readRawSessionSeedTail2 };
5217
+ export { detectThinkingBindingMismatch, detectLatestTurnThinkingMismatch, isPrefixBoundThinkingModel, detectOverflow, MAX_EXECUTE_THRESHOLD, escalationBands, MERGED_REASONING_PARTS_PREFIX, decodeMergedReasoningParts, HYGIENE_PROVIDER_UNITS_VERSION, sessionDecisionCalibration, transitionSessionHygieneUnits, computeProtectionWindow, readEpochFloorSnapshot, getProtectionWindowForSession, SESSION_META_SELECT_COLUMNS, META_COLUMNS, BOOLEAN_META_KEYS, NULL_BIND_META_KEYS, isSessionMetaRow, getDefaultSessionMeta, ensureSessionMetaRow, toSessionMeta, persistCachedM0, clearCachedM0M1, isRustMarkerAdmissionFenced, ReplayDocumentError, readReplayEnvelope, readReplayDocument, updateReplayDocument, writeReplayDocument, isProviderOverflowFailClosedProven, getEmergencyRecoveryArmedAt, describeProtectedTailDrainBudgetSkip, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, EMERGENCY_DRAIN_FAILURE_BACKOFF_MS, getProtectedTailDrainBudgetSkip, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, queueAutoSearchHintDecisionRetirement, flushAutoSearchHintDecisionRetirement, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, setNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, setPersistedCompactionMarkerState, parseStrippedPlaceholderState, serializeStrippedPlaceholderState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, THINKING_BINDING_STRIP_ORDER_END_MARKER, thinkingBindingRecoveryFrozenId, COMPACTION_OFF_THINKING_FROZEN_PREFIX, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getProcessedImageStrippedIds, parseProcessedImageMarkers, serializeProcessedImageMarkers, addProcessedImageStrippedIds, getPendingCompactionMarkerState, getCompactionMarkerHealth, loadPostprocessReplaySnapshot, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, logPiCompactionMarkerClear, getSessionsWithPendingPiMarker, setSessionWorkMetrics, getSessionWorkMetrics, resolveEpochFloorForPass, withReadOnlySessionDb, expandToolPart, askAnswerLines, retreatPastHostUnservedRows, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripSystemInjection, isFilePart, hasUserAnswerMetadata, DreamTokenBudgetExceeded, TOKEN_BUDGET_FINALIZE_MESSAGE, TOKEN_BUDGET_TOOL_REFUSAL, registerBudgetFinalizeChild, releaseBudgetFinalizeChild, createDreamTokenBudget, droppedInputMarker, createDroppedInputGuard, isEditTool, applyEditMarkerToInput, modelAcceptsEmptyContent, isAnthropicFamilyRoute, variantChangeBustsProviderCache, isInActiveAnthropicTurn, activeAnthropicTurnStart, hasAnthropicReasoning, findLatestAssistantReasoningMutationExemptMessage, DEFAULT_KEEP_REASONING_TOKENS, resolveKeepReasoningTokens, reasoningStepCost, reasoningBudgetCutoff, reasoningTextAndOpaque, opaqueThinkingCost, estimatePartImageTokens, SKELETON_REAL_INPUT_MAX_BYTES, toolInputStringBytes, resolveHostServedBoundaryId2, hasRawMessageProvider2, setRawMessageProvider2, setBoundedRawMessageProvider2, withRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, RAW_MESSAGE_VISIT_PAGE_SIZE2, visitRawSessionMessages2, visitRawSessionMessagesAsync2, readRawSessionMessageRange2, prepareRawSessionOrdinals2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageOrdinalPage2, getRawSessionStoredMessageCount2, readRawSessionMessageIdOrdinalsForRange2, readRawSessionMessageIdOrdinals2, readRawSessionMessagePartsById2, readRawSessionBoundaryEndpoints2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, resolveHistorianChunkStart2, compareRawSessionMessageOrder2, readRawSessionMessageById2, getRawSessionMessageCount2, RAW_SESSION_TAG_KEY_PAGE_SIZE2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, getProtectedTailStartOrdinal2, readSessionChunk2, getRawSessionMessageIdsThrough2, readRawSessionSeedTail2 };
package/dist/index.js CHANGED
@@ -22,6 +22,8 @@ import {
22
22
  COMPACTION_ENABLED_PATH,
23
23
  isDreamerRunnable,
24
24
  isCompactionEnabled,
25
+ isCommitRetentionPaused,
26
+ copyCommitRetentionRecovery,
25
27
  formatConfigParseStatusLine,
26
28
  formatConfigParseNotice,
27
29
  claimConfigParseFailuresOnce,
@@ -260,7 +262,7 @@ import {
260
262
  registerTodoStateLifecycle,
261
263
  syncCtxMemoryToolEnabled,
262
264
  registerMagicContextTools
263
- } from "./index-bkcwcghx.js";
265
+ } from "./index-00p6t4nd.js";
264
266
  import"./index-4knyh1kt.js";
265
267
  import {
266
268
  canonicalModelIdentity,
@@ -302,7 +304,7 @@ import {
302
304
  openCurrentDatabase,
303
305
  openDatabaseAsync,
304
306
  closeDatabase
305
- } from "./index-5d506f7y.js";
307
+ } from "./index-9pfffeqj.js";
306
308
  import {
307
309
  sameProjectDirectory,
308
310
  pruneMissingProjectIdentities,
@@ -478,7 +480,7 @@ import {
478
480
  getRawSessionTagKeysThrough2,
479
481
  getLegacyProtectedTailStartOrdinal2,
480
482
  readSessionChunk2
481
- } from "./index-kagezf2h.js";
483
+ } from "./index-yvb1cz6b.js";
482
484
  import {
483
485
  UNKNOWN_FIT_RATIO,
484
486
  hasMeasuredDecisionCalibration,
@@ -665,7 +667,7 @@ import {
665
667
  embedSessionCompartmentChunks2,
666
668
  getEmbeddingCoverageStatus2,
667
669
  getAutoEmbeddingSessionCoverage2
668
- } from "./index-xa90f88m.js";
670
+ } from "./index-0jykn0dw.js";
669
671
  import {
670
672
  clearCompressionDepth,
671
673
  clearCompressionDepthRange,
@@ -678,7 +680,7 @@ import {
678
680
  isMessageIndexReconciledThrough,
679
681
  indexSingleMessage,
680
682
  indexMessagesAfterOrdinal
681
- } from "./index-v0ht940m.js";
683
+ } from "./index-vppykq05.js";
682
684
  import {
683
685
  rememberV1HiddenRun
684
686
  } from "./index-6x556c2q.js";
@@ -743,7 +745,7 @@ import {
743
745
  normalizeVerificationFiles,
744
746
  indexCommitsForProject,
745
747
  embedUnembeddedCommits
746
- } from "./index-sdsnb5b6.js";
748
+ } from "./index-wcma874r.js";
747
749
  import {
748
750
  setEmbeddingSessionBusy2,
749
751
  isEmbeddingHostBusy2
@@ -779,7 +781,7 @@ import {
779
781
  } from "./index-wqpjhx1p.js";
780
782
  import {
781
783
  cosineSimilarity
782
- } from "./index-wjbqw6r1.js";
784
+ } from "./index-4nny4r40.js";
783
785
  import"./index-6wdwv3a6.js";
784
786
  import {
785
787
  DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
@@ -807,10 +809,10 @@ import {
807
809
  drainPiTagSnapshotSession,
808
810
  assertPiTagSnapshotReady,
809
811
  ensurePiTagSnapshotReady
810
- } from "./index-xw070axm.js";
812
+ } from "./index-f1pcnedq.js";
811
813
  import"./index-jn44h81p.js";
812
814
  import"./index-1cvyaw9a.js";
813
- import"./index-vea2d9ka.js";
815
+ import"./index-fp40yrsy.js";
814
816
  import {
815
817
  __toESM
816
818
  } from "./index-22jkk6wg.js";
@@ -1169,7 +1171,13 @@ function sampleLiveConfig(boot, fresh) {
1169
1171
  if (leaf !== undefined)
1170
1172
  target[leaf] = value;
1171
1173
  }
1172
- return result;
1174
+ const sampled = result;
1175
+ const freshCommitIndexing = fresh.memory?.git_commit_indexing;
1176
+ const sampledCommitIndexing = sampled.memory?.git_commit_indexing;
1177
+ if (freshCommitIndexing && sampledCommitIndexing) {
1178
+ copyCommitRetentionRecovery(freshCommitIndexing, sampledCommitIndexing);
1179
+ }
1180
+ return sampled;
1173
1181
  }
1174
1182
  function removeLeaf(root, parts) {
1175
1183
  const parents = parts.slice(0, -1);
@@ -3549,7 +3557,7 @@ function startHostStallProfilerSwitch() {
3549
3557
  // package.json
3550
3558
  var package_default = {
3551
3559
  name: "@cortexkit/pi-magic-context",
3552
- version: "0.49.27",
3560
+ version: "0.49.29",
3553
3561
  type: "module",
3554
3562
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3555
3563
  main: "dist/index.js",
@@ -10937,7 +10945,7 @@ async function runHiddenSingleShotPrompt(args) {
10937
10945
  let timer;
10938
10946
  try {
10939
10947
  const completion = await Promise.race([
10940
- args.executor.collect(handle, 200),
10948
+ args.executor.collectPartial?.(handle, 200) ?? args.executor.collect(handle, 200),
10941
10949
  new Promise((resolve) => {
10942
10950
  timer = setTimeout(() => resolve(null), 5000);
10943
10951
  })
@@ -13580,6 +13588,7 @@ Remember: output only the JSON object described by the system prompt.`;
13580
13588
  let childSessionId = null;
13581
13589
  let promptSettled = false;
13582
13590
  let invocationRecorded = false;
13591
+ let completionUsage;
13583
13592
  const recordInvocation = (params) => {
13584
13593
  if (!args.db || !args.parentSessionId || invocationRecorded)
13585
13594
  return;
@@ -13593,6 +13602,7 @@ Remember: output only the JSON object described by the system prompt.`;
13593
13602
  startedAt,
13594
13603
  status: params.status,
13595
13604
  messages: params.messages,
13605
+ tokens: args.hiddenCompletionExecutor?.capabilities.harness === "opencode2" ? completionUsage : undefined,
13596
13606
  attemptedModel: args.model,
13597
13607
  configuredModels: args.fallbackModels,
13598
13608
  error: params.error
@@ -13617,11 +13627,15 @@ Remember: output only the JSON object described by the system prompt.`;
13617
13627
  timeoutMs: remainingMs,
13618
13628
  signal: args.signal,
13619
13629
  metadata: { task: "evaluate-smart-notes" },
13630
+ onFailureOutput: (completion) => {
13631
+ completionUsage = completion.usage;
13632
+ },
13620
13633
  parse: parseCompilerOutput
13621
13634
  });
13622
13635
  promptSettled = true;
13623
13636
  response = carried.validated;
13624
13637
  outputMessages = carried.completion.messages;
13638
+ completionUsage = carried.completion.usage;
13625
13639
  } else {
13626
13640
  const client = args.client;
13627
13641
  if (!client) {
@@ -14342,6 +14356,7 @@ async function confirmReadOnly(args, noteId, content, surfaceCondition, leaseSig
14342
14356
  startedAt,
14343
14357
  status: params.status,
14344
14358
  messages: params.messages,
14359
+ tokens: args.hiddenCompletionExecutor?.capabilities.harness === "opencode2" ? params.tokens : undefined,
14345
14360
  attemptedModel: args.model,
14346
14361
  configuredModels: args.fallbackModels,
14347
14362
  error: params.error
@@ -14369,7 +14384,11 @@ async function confirmReadOnly(args, noteId, content, surfaceCondition, leaseSig
14369
14384
  parse: parseConfirmationVerdict
14370
14385
  });
14371
14386
  promptSettled = true;
14372
- recordInvocation({ status: "completed", messages: run.completion.messages });
14387
+ recordInvocation({
14388
+ status: "completed",
14389
+ messages: run.completion.messages,
14390
+ tokens: run.completion.usage
14391
+ });
14373
14392
  return run.validated;
14374
14393
  } finally {
14375
14394
  promptSignal.cleanup();
@@ -14927,8 +14946,8 @@ async function mapMemories(args) {
14927
14946
  result.failureStage = outcome.failure.stage;
14928
14947
  }
14929
14948
  const committed = outcome.mapped + outcome.independent;
14949
+ const committedIds = new Set(outcome.committedIds);
14930
14950
  runLeaseGuardedWrite(args.db, args.holderId, args.leaseKey, () => {
14931
- const committedIds = new Set(outcome.committedIds);
14932
14951
  for (const memory of batch.inputs) {
14933
14952
  if (committedIds.has(memory.id)) {
14934
14953
  delete retries[memory.id];
@@ -14963,7 +14982,22 @@ async function mapMemories(args) {
14963
14982
  log2(`[dreamer] map-memories: targeted retry still omitted ${outcome.requeue.length} id(s); leaving them unmapped for the next run`);
14964
14983
  }
14965
14984
  }
14966
- if (outcome.failure?.class === "timeout" && committed === 0) {
14985
+ if (outcome.failure?.class === "timeout" && batch.inputs.length > 1) {
14986
+ const unmapped = batch.inputs.filter((memory) => !committedIds.has(memory.id));
14987
+ const splitSize = Math.floor(batch.inputs.length / 2);
14988
+ const splits = [];
14989
+ for (let offset = 0;offset < unmapped.length; offset += splitSize) {
14990
+ splits.push({
14991
+ inputs: unmapped.slice(offset, offset + splitSize),
14992
+ isOmissionRetry: batch.isOmissionRetry
14993
+ });
14994
+ }
14995
+ if (splits.length > 0) {
14996
+ batches.splice(i + 1, 0, ...splits);
14997
+ log2(`[dreamer] map-memories: splitting batch [${batch.inputs.map((memory) => memory.id).join(",")}] into ${splits.map((split) => split.inputs.length).join("+")} after timeout; retrying ${unmapped.length} uncommitted mapping(s)`);
14998
+ }
14999
+ }
15000
+ if (outcome.failure?.class === "timeout" && batch.inputs.length === 1 && committed === 0) {
14967
15001
  consecutiveTimeouts += 1;
14968
15002
  timeoutStreakElapsedMs.push(outcome.failure.elapsedMs);
14969
15003
  if (consecutiveTimeouts >= CONSECUTIVE_TIMEOUT_LIMIT2) {
@@ -14971,7 +15005,7 @@ async function mapMemories(args) {
14971
15005
  log2(`[dreamer] map-memories starvation: circuit breaker tripped after ${consecutiveTimeouts} consecutive batch timeouts with no committed mappings (investigation made no durable progress); per-batch elapsed [${timeoutStreakElapsedMs.join("ms, ")}ms] vs ${sliceMs}ms slice; stopping with ${result.remaining} mapping(s) remaining`);
14972
15006
  break;
14973
15007
  }
14974
- } else {
15008
+ } else if (committed > 0 || outcome.failure?.class !== "timeout") {
14975
15009
  consecutiveTimeouts = 0;
14976
15010
  timeoutStreakElapsedMs = [];
14977
15011
  }
@@ -15022,7 +15056,8 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
15022
15056
  });
15023
15057
  recordInvocation2(args, startedAt, {
15024
15058
  status: "completed",
15025
- messages: run.completion.messages ?? []
15059
+ messages: run.completion.messages ?? [],
15060
+ tokens: run.completion.usage
15026
15061
  });
15027
15062
  stage = "apply";
15028
15063
  const outcome = await applyParsedBatchMappings(args, batch, run.validated, budgetFinalized, true);
@@ -15097,7 +15132,8 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
15097
15132
  recordInvocation2(args, startedAt, {
15098
15133
  status: failedInvocationStatus(error),
15099
15134
  error,
15100
- messages
15135
+ messages,
15136
+ tokens: failedCompletion?.usage
15101
15137
  });
15102
15138
  if (error instanceof DreamerModuleFailureError)
15103
15139
  throw error;
@@ -15264,6 +15300,7 @@ function recordInvocation2(args, startedAt, params) {
15264
15300
  startedAt,
15265
15301
  status: params.status,
15266
15302
  messages: params.messages,
15303
+ tokens: args.hiddenCompletionExecutor?.capabilities.harness === "opencode2" ? params.tokens : undefined,
15267
15304
  attemptedModel: args.model,
15268
15305
  configuredModels: args.fallbackModels,
15269
15306
  error: params.error
@@ -16515,7 +16552,8 @@ async function git2(root, args) {
16515
16552
  cwd: root,
16516
16553
  timeout: 1e4,
16517
16554
  maxBuffer: MAX_DIFF_BYTES,
16518
- encoding: "utf8"
16555
+ encoding: "utf8",
16556
+ windowsHide: true
16519
16557
  });
16520
16558
  return stdout;
16521
16559
  }
@@ -17157,7 +17195,8 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
17157
17195
  });
17158
17196
  recordInvocation4(args, startedAt, {
17159
17197
  status: "completed",
17160
- messages: run.completion.messages ?? []
17198
+ messages: run.completion.messages ?? [],
17199
+ tokens: run.completion.usage
17161
17200
  });
17162
17201
  reportUsage(run.completion.messages ?? [], run.childSessionId, run.completion.usage.input + (run.completion.usage.cacheRead ?? 0) + (run.completion.usage.cacheWrite ?? 0));
17163
17202
  return await applyParsedVerifyManifest(args, batch, run.validated, evidence?.head ?? headAtPrompt, budgetFinalized);
@@ -17231,7 +17270,8 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
17231
17270
  recordInvocation4(args, startedAt, {
17232
17271
  status: failedInvocationStatus(error),
17233
17272
  error,
17234
- messages
17273
+ messages,
17274
+ tokens: failedCompletion?.usage
17235
17275
  });
17236
17276
  if (error instanceof DreamerModuleFailureError || signal.aborted)
17237
17277
  throw error;
@@ -17490,6 +17530,7 @@ function recordInvocation4(args, startedAt, params) {
17490
17530
  startedAt,
17491
17531
  status: params.status,
17492
17532
  messages: params.messages,
17533
+ tokens: args.hiddenCompletionExecutor?.capabilities.harness === "opencode2" ? params.tokens : undefined,
17493
17534
  attemptedModel: args.model,
17494
17535
  configuredModels: args.fallbackModels,
17495
17536
  error: params.error
@@ -17559,6 +17600,15 @@ function classifyFailure(error) {
17559
17600
  const transient = explicitTransient || name === "AbortError" || /abort|lease|timeout|timed out|econn|socket|network|rate.?limit|429|503|overloaded|sqlite_busy|database is locked/.test(combined);
17560
17601
  return { transient, brief };
17561
17602
  }
17603
+ function sumCompletionUsages(usages) {
17604
+ return usages.reduce((total, usage) => ({
17605
+ input: total.input + usage.input,
17606
+ output: total.output + usage.output,
17607
+ cacheRead: total.cacheRead + usage.cacheRead,
17608
+ cacheWrite: total.cacheWrite + usage.cacheWrite,
17609
+ ...total.reasoning !== undefined || usage.reasoning !== undefined ? { reasoning: (total.reasoning ?? 0) + (usage.reasoning ?? 0) } : {}
17610
+ }), emptyTokenTotals());
17611
+ }
17562
17612
  function newIds(beforeIds, afterIds) {
17563
17613
  const before = new Set(beforeIds);
17564
17614
  const out = [];
@@ -18366,6 +18416,7 @@ async function runRetrospectiveTask(config, ctx, helpers) {
18366
18416
  }, ctx.leaseAcquisition);
18367
18417
  let childSessionId = null;
18368
18418
  let hiddenHandle = null;
18419
+ const hiddenUsages = [];
18369
18420
  let promptSettled = false;
18370
18421
  let invocationRecorded = false;
18371
18422
  const recordInvocation = (status, messages, error) => {
@@ -18381,6 +18432,7 @@ async function runRetrospectiveTask(config, ctx, helpers) {
18381
18432
  startedAt: helpers.invocationStartedAt,
18382
18433
  status,
18383
18434
  messages,
18435
+ tokens: deps.hiddenCompletionExecutor?.capabilities.harness === "opencode2" && hiddenUsages.length ? sumCompletionUsages(hiddenUsages) : undefined,
18384
18436
  attemptedModel: config.model,
18385
18437
  configuredModels: config.fallbackModels,
18386
18438
  error
@@ -18466,6 +18518,8 @@ async function runRetrospectiveTask(config, ctx, helpers) {
18466
18518
  }
18467
18519
  });
18468
18520
  promptSettled = true;
18521
+ if (hiddenHandle)
18522
+ hiddenUsages.push(run.output.usage);
18469
18523
  const output = hiddenHandle ? run.output.messages ?? [] : run.output;
18470
18524
  return { ...run, output };
18471
18525
  };
@@ -18636,6 +18690,7 @@ async function runAgenticTask(config, ctx, helpers) {
18636
18690
  let childSessionId = null;
18637
18691
  let promptSettled = false;
18638
18692
  let expiredArchived = 0;
18693
+ const hiddenUsages = [];
18639
18694
  let invocationRecorded = false;
18640
18695
  const recordInvocation = (status, messages, error) => {
18641
18696
  if (!parent || !childSessionId || invocationRecorded)
@@ -18650,6 +18705,7 @@ async function runAgenticTask(config, ctx, helpers) {
18650
18705
  startedAt: invocationStartedAt,
18651
18706
  status,
18652
18707
  messages,
18708
+ tokens: deps.hiddenCompletionExecutor?.capabilities.harness === "opencode2" && hiddenUsages.length ? sumCompletionUsages(hiddenUsages) : undefined,
18653
18709
  attemptedModel: config.model,
18654
18710
  configuredModels: config.fallbackModels,
18655
18711
  error
@@ -18767,6 +18823,7 @@ async function runAgenticTask(config, ctx, helpers) {
18767
18823
  }
18768
18824
  });
18769
18825
  childSessionId = hidden.childSessionId;
18826
+ hiddenUsages.push(hidden.completion.usage);
18770
18827
  run = { output: hidden.completion.messages ?? [], validated: hidden.validated };
18771
18828
  promptSettled = true;
18772
18829
  } else {
@@ -19902,7 +19959,8 @@ async function sweepGitCommits(args) {
19902
19959
  try {
19903
19960
  const result = await indexCommitsForProject(db, projectIdentity, directory, {
19904
19961
  sinceDays: gitCommitIndexing.since_days,
19905
- maxCommits: gitCommitIndexing.max_commits
19962
+ maxCommits: gitCommitIndexing.max_commits,
19963
+ skipRetention: isCommitRetentionPaused(gitCommitIndexing)
19906
19964
  });
19907
19965
  if (result.nonIndexable) {
19908
19966
  if (!parkGitSweepNonIndexable(db, projectIdentity, holderId)) {
@@ -22630,6 +22688,8 @@ async function awaitInFlightDreamers(registrationOwner) {
22630
22688
  return;
22631
22689
  await Promise.allSettled(runs);
22632
22690
  }
22691
+ var RUNNER_TIMEOUT_HEADROOM_MINUTES = 5;
22692
+ var UNKNOWN_TASK_TIMEOUT_MINUTES = 30;
22633
22693
  function createPiDreamerClient(opts, onAdjunctsRefreshNeeded = opts.onAdjunctsRefreshNeeded, isRegistrationOwnerActive = () => true, getMaxOutputTokens = () => opts.config.maxTokens, getDreamerConfig = () => opts.config) {
22634
22694
  const runner = piSubagentRunnerFactory();
22635
22695
  const budgetStates = new Map;
@@ -22683,7 +22743,7 @@ function createPiDreamerClient(opts, onAdjunctsRefreshNeeded = opts.onAdjunctsRe
22683
22743
  userMessage,
22684
22744
  model: perTaskModel,
22685
22745
  fallbackModels: undefined,
22686
- timeoutMs: 30 * 60 * 1000,
22746
+ timeoutMs: ((taskConfig?.timeoutMinutes ?? UNKNOWN_TASK_TIMEOUT_MINUTES) + RUNNER_TIMEOUT_HEADROOM_MINUTES) * 60 * 1000,
22687
22747
  cwd: dreamSession.directory,
22688
22748
  signal: args.signal ? AbortSignal.any([args.signal, controller.signal]) : controller.signal,
22689
22749
  thinkingLevel: extractBodyVariant(args),
@@ -22792,7 +22852,11 @@ function accountingTaskFromTitle(title) {
22792
22852
  const task = title.slice("magic-context-dream-".length);
22793
22853
  if (!title.startsWith("magic-context-dream-") || task.length === 0)
22794
22854
  return null;
22795
- return task === "classify" ? "classify-memories" : task;
22855
+ if (task === "classify")
22856
+ return "classify-memories";
22857
+ if (task === "user-memories")
22858
+ return "review-user-memories";
22859
+ return task;
22796
22860
  }
22797
22861
  function readSessionTitle(args) {
22798
22862
  const body = args.body;
@@ -13,7 +13,7 @@ import"./index-399p688g.js";
13
13
  import"./index-54wmg4rj.js";
14
14
  import"./index-6981g1xv.js";
15
15
  import"./index-23t8ryqw.js";
16
- import"./index-kagezf2h.js";
16
+ import"./index-yvb1cz6b.js";
17
17
  import"./index-6x556c2q.js";
18
18
  import {
19
19
  MESSAGE_INDEX_MAX_FTS_BYTES,
@@ -22,7 +22,7 @@ import {
22
22
  markMessageIndexDirty,
23
23
  getIndexableContent,
24
24
  indexSingleMessage
25
- } from "./index-v0ht940m.js";
25
+ } from "./index-vppykq05.js";
26
26
  import"./index-bvpar0bg.js";
27
27
  import"./index-hqw0rt9k.js";
28
28
 
@@ -18,7 +18,7 @@ import"./index-48twbev2.js";
18
18
  import {
19
19
  setSqlitePragmaConfig,
20
20
  initializeDatabase
21
- } from "./index-5d506f7y.js";
21
+ } from "./index-9pfffeqj.js";
22
22
  import"./index-fapenpch.js";
23
23
  import"./index-399p688g.js";
24
24
  import"./index-54wmg4rj.js";
@@ -33,7 +33,7 @@ import {
33
33
  sweepAllRegisteredProjects2,
34
34
  _setTestProviderFactoryForProject2,
35
35
  _resetProjectEmbeddingRegistryForTests2
36
- } from "./index-xa90f88m.js";
36
+ } from "./index-0jykn0dw.js";
37
37
  import"./index-9p40dgkm.js";
38
38
  import"./index-yhzhdp3m.js";
39
39
  import"./index-4zemngt7.js";
@@ -51,7 +51,7 @@ async function main() {
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-mpjeecwj.js");
54
+ const { renderSearchArchive } = await import("./search-archive-yky3g10b.js");
55
55
  const { readRawSessionMessageIdOrdinalsForRangeFromDb } = await import("./read-session-raw-g9b1zdn5.js");
56
56
  const archive = input.searchArchive;
57
57
  let raw;
@@ -81,7 +81,7 @@ async function main() {
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-avbaa7wa.js"),
84
+ import("./message-index-bounded-w10cy1s9.js"),
85
85
  import("./sqlite-context-pragmas-gcgch6qz.js")
86
86
  ]);
87
87
  configureContextDatabasePragmas(db);
@@ -36,7 +36,7 @@ import {
36
36
  readSessionChunk2,
37
37
  getRawSessionMessageIdsThrough2,
38
38
  readRawSessionSeedTail2
39
- } from "./index-kagezf2h.js";
39
+ } from "./index-yvb1cz6b.js";
40
40
  import"./index-0x1c054v.js";
41
41
  import"./index-6x556c2q.js";
42
42
  import"./index-ccanzg8p.js";
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  renderSearchArchive2
3
- } from "./index-vea2d9ka.js";
3
+ } from "./index-fp40yrsy.js";
4
4
  import"./index-1cvyaw9a.js";
5
- import"./index-kagezf2h.js";
5
+ import"./index-yvb1cz6b.js";
6
6
  import"./index-0x1c054v.js";
7
7
  import"./index-6x556c2q.js";
8
8
  import"./index-ccanzg8p.js";
@@ -5,17 +5,17 @@ import {
5
5
  resolveMemoriesByIdsForSearch2,
6
6
  unifiedSearch2,
7
7
  formatSearchResults2
8
- } from "./index-sdsnb5b6.js";
8
+ } from "./index-wcma874r.js";
9
9
  import"./index-1cvyaw9a.js";
10
- import"./index-v0ht940m.js";
11
- import"./index-wjbqw6r1.js";
12
- import"./index-xa90f88m.js";
10
+ import"./index-vppykq05.js";
11
+ import"./index-4nny4r40.js";
12
+ import"./index-0jykn0dw.js";
13
13
  import"./index-9p40dgkm.js";
14
14
  import"./index-29nw7n1r.js";
15
15
  import"./index-yhzhdp3m.js";
16
16
  import"./index-4zemngt7.js";
17
17
  import"./index-kmk3xpf9.js";
18
- import"./index-kagezf2h.js";
18
+ import"./index-yvb1cz6b.js";
19
19
  import"./index-0x1c054v.js";
20
20
  import"./index-6x556c2q.js";
21
21
  import"./index-wqpjhx1p.js";
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  TOKEN_BUDGET_TOOL_REFUSAL
3
- } from "./index-kagezf2h.js";
3
+ } from "./index-yvb1cz6b.js";
4
4
  import {
5
5
  setHarness2
6
6
  } from "./index-0h2mkab2.js";
@@ -13,7 +13,7 @@ import {
13
13
  import"./index-2qtx0q6h.js";
14
14
  import {
15
15
  openDatabase
16
- } from "./index-5d506f7y.js";
16
+ } from "./index-9pfffeqj.js";
17
17
  import"./index-fapenpch.js";
18
18
  import"./index-399p688g.js";
19
19
  import"./index-54wmg4rj.js";
@@ -30,22 +30,22 @@ import {
30
30
  ensureProjectRegisteredFromPiDirectory,
31
31
  resolvePiHarnessKind,
32
32
  registerMagicContextTools
33
- } from "./index-bkcwcghx.js";
33
+ } from "./index-00p6t4nd.js";
34
34
  import"./index-ccanzg8p.js";
35
35
  import"./index-gwxaz0z5.js";
36
36
  import"./index-kmk3xpf9.js";
37
37
  import"./index-wqpjhx1p.js";
38
- import"./index-xa90f88m.js";
38
+ import"./index-0jykn0dw.js";
39
39
  import"./index-9p40dgkm.js";
40
40
  import"./index-4zemngt7.js";
41
41
  import"./index-yhzhdp3m.js";
42
- import"./index-wjbqw6r1.js";
43
- import"./index-v0ht940m.js";
42
+ import"./index-4nny4r40.js";
43
+ import"./index-vppykq05.js";
44
44
  import"./index-0x1c054v.js";
45
45
  import"./index-6x556c2q.js";
46
- import"./index-sdsnb5b6.js";
46
+ import"./index-wcma874r.js";
47
47
  import"./index-1cvyaw9a.js";
48
- import"./index-vea2d9ka.js";
48
+ import"./index-fp40yrsy.js";
49
49
  import"./index-29nw7n1r.js";
50
50
  import"./index-6wdwv3a6.js";
51
51
  import"./index-hqw0rt9k.js";
@@ -7,7 +7,7 @@ import"./index-fgs78jyd.js";
7
7
  import {
8
8
  LATEST_SUPPORTED_VERSION,
9
9
  getPersistedSchemaVersion
10
- } from "./index-5d506f7y.js";
10
+ } from "./index-9pfffeqj.js";
11
11
  import"./index-fapenpch.js";
12
12
  import"./index-399p688g.js";
13
13
  import {
@@ -30,7 +30,7 @@ import {
30
30
  encodePiHydrationOperation,
31
31
  PI_FALLBACK_ROW_COLUMNS,
32
32
  PI_FALLBACK_ROW_PREDICATE
33
- } from "./index-xw070axm.js";
33
+ } from "./index-f1pcnedq.js";
34
34
  import"./index-hqw0rt9k.js";
35
35
 
36
36
  // src/tag-snapshot-worker-pi.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.49.27",
3
+ "version": "0.49.29",
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",