@cortexkit/pi-magic-context 0.49.64 → 0.49.65

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.
@@ -102,6 +102,7 @@ import {
102
102
  insertMemory2,
103
103
  getMemoryByHash2,
104
104
  getMemoriesByProject2,
105
+ getMemoriesByProjects2,
105
106
  getMemoryById2,
106
107
  getMemoriesByIds2,
107
108
  updateMemorySeenCount2,
@@ -156,7 +157,8 @@ import {
156
157
  resolveWorkspaceIdentitySet,
157
158
  expandWorkspaceIdentitySetWithAliases,
158
159
  resolveStoredPathWorkspaceIdentity,
159
- storedPathBelongsToWorkspace
160
+ storedPathBelongsToWorkspace,
161
+ sourceNameForMemory
160
162
  } from "./index-gavj3e6h.js";
161
163
  import {
162
164
  getNoteByIdInScope,
@@ -6303,6 +6305,51 @@ ${sections.join(`
6303
6305
  }
6304
6306
  var DEFAULT_MEMORY_BUDGET_TOKENS = 8000;
6305
6307
  var DEFAULT_USER_PROFILE_BUDGET_TOKENS = 4000;
6308
+ function resolveWorkspaceRenderContext(args) {
6309
+ if (!args.projectPath) {
6310
+ return {
6311
+ identities: [],
6312
+ expandedIdentities: [],
6313
+ ownIdentities: [],
6314
+ shareCategories: null,
6315
+ namesByIdentity: new Map,
6316
+ canonicalIdentityByStoredPath: new Map,
6317
+ isWorkspaced: false
6318
+ };
6319
+ }
6320
+ const identitySet = args.workspaceIdentitySet ?? resolveWorkspaceIdentitySet(args.db, args.projectPath);
6321
+ const isWorkspaced = identitySet.identities.length > 1;
6322
+ const expanded = expandWorkspaceIdentitySetWithAliases(args.db, identitySet.identities);
6323
+ const expandedIdentities = isWorkspaced ? expanded.expandedIdentities : identitySet.identities;
6324
+ const canonicalIdentityByStoredPath = isWorkspaced ? expanded.canonicalIdentityByStoredPath : new Map(identitySet.identities.map((identity) => [identity, identity]));
6325
+ let ownIdentities = expandedIdentities.filter((identity) => canonicalIdentityByStoredPath.get(identity) === args.projectPath);
6326
+ if (ownIdentities.length === 0 && expandedIdentities.includes(args.projectPath)) {
6327
+ ownIdentities = [args.projectPath];
6328
+ }
6329
+ return {
6330
+ identities: identitySet.identities,
6331
+ expandedIdentities,
6332
+ ownIdentities,
6333
+ shareCategories: isWorkspaced ? resolveWorkspaceShareCategories(args.db, args.projectPath) : null,
6334
+ namesByIdentity: identitySet.namesByIdentity,
6335
+ canonicalIdentityByStoredPath,
6336
+ isWorkspaced
6337
+ };
6338
+ }
6339
+ function sourceNamesForMemories(args) {
6340
+ if (!args.projectPath || !args.workspace.isWorkspaced)
6341
+ return;
6342
+ const names = new Map;
6343
+ for (const memory of args.memories) {
6344
+ const source = sourceNameForMemory(memory.projectPath, args.projectPath, args.workspace.identities, args.workspace.namesByIdentity, args.workspace.canonicalIdentityByStoredPath);
6345
+ if (source)
6346
+ names.set(memory.id, source);
6347
+ }
6348
+ return names.size > 0 ? names : undefined;
6349
+ }
6350
+ function readM0ProjectMemories(db, projectPath, workspace, at = Date.now()) {
6351
+ return workspace.isWorkspaced ? getMemoriesByProjects2(db, workspace.expandedIdentities, ["active", "permanent"], at, workspace.ownIdentities, workspace.shareCategories) : getMemoriesByProject2(db, projectPath, ["active", "permanent"], at);
6352
+ }
6306
6353
  function memoryCanonicalIdentity(memory, workspace) {
6307
6354
  return resolveStoredPathWorkspaceIdentity(memory.projectPath, workspace.identities, workspace.canonicalIdentityByStoredPath);
6308
6355
  }
@@ -10906,4 +10953,4 @@ function registerMagicContextTools(pi, opts) {
10906
10953
  }
10907
10954
  }
10908
10955
 
10909
- 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, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, resetPrefixTrimFallbackState, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, loadPiConfig, loadPiConfigDetailed, unregisterPiProjectEmbeddings, ensureProjectRegisteredFromPiDirectory, neutralizeOmpMentions, restoreOmpMentions, resolvePiHarnessDetection, resolvePiHarnessKind, readSubagentStartupError, reportSubagentStartupError, resolvePiOrdinalAlignment, piRawOrdinalOffsetSource, resolvePiOrdinalAlignmentForContext, isPiOrdinalAlignmentUnanchored, clearPiOrdinalAlignmentSession, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
10956
+ 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, resolvePiOrdinalAlignment, piRawOrdinalOffsetSource, resolvePiOrdinalAlignmentForContext, isPiOrdinalAlignmentUnanchored, clearPiOrdinalAlignmentSession, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
package/dist/index.js CHANGED
@@ -124,6 +124,9 @@ import {
124
124
  renderHistorianMemoryBlock,
125
125
  DEFAULT_MEMORY_BUDGET_TOKENS,
126
126
  DEFAULT_USER_PROFILE_BUDGET_TOKENS,
127
+ resolveWorkspaceRenderContext,
128
+ sourceNamesForMemories,
129
+ readM0ProjectMemories,
127
130
  trimMemoriesToBudgetV2,
128
131
  trimWorkspaceMemoriesToBudgetV2,
129
132
  trimUserMemoriesToBudget,
@@ -154,7 +157,7 @@ import {
154
157
  registerTodoStateLifecycle,
155
158
  syncCtxMemoryToolEnabled,
156
159
  registerMagicContextTools
157
- } from "./index-691zz6f4.js";
160
+ } from "./index-1tkrgcdt.js";
158
161
  import"./index-4knyh1kt.js";
159
162
  import {
160
163
  canonicalModelIdentity,
@@ -3602,7 +3605,7 @@ function startHostStallProfilerSwitch() {
3602
3605
  // package.json
3603
3606
  var package_default = {
3604
3607
  name: "@cortexkit/pi-magic-context",
3605
- version: "0.49.64",
3608
+ version: "0.49.65",
3606
3609
  type: "module",
3607
3610
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3608
3611
  main: "dist/index.js",
@@ -7368,11 +7371,11 @@ var USER_OBSERVATIONS_DISABLED_TOGGLE = `<user_observation_extraction>disabled</
7368
7371
  User-memory review is not running (the dreamer is disabled): do NOT emit a <user_observations> block.`;
7369
7372
  function buildCompartmentAgentPrompt(inputs) {
7370
7373
  const parts = [];
7374
+ parts.push(...readEnabledProjectMemories(inputs.memoryEnabled, () => inputs.projectMemory ? [inputs.projectMemory] : []));
7371
7375
  if (inputs.seedExamples)
7372
7376
  parts.push(inputs.seedExamples);
7373
7377
  if (inputs.sessionReferences)
7374
7378
  parts.push(inputs.sessionReferences);
7375
- parts.push(...readEnabledProjectMemories(inputs.memoryEnabled, () => inputs.projectMemory ? [inputs.projectMemory] : []));
7376
7379
  if (inputs.extractionFree) {
7377
7380
  parts.push(`<extraction>disabled</extraction>
7378
7381
  Structural recomp mode: emit compartments and <meta> only. Do NOT emit <facts>, <events>, <user_observations>, or <primer_candidates>.`);
@@ -7392,6 +7395,34 @@ Memory is disabled for this project: do NOT emit a <facts> block. Produce compar
7392
7395
 
7393
7396
  `);
7394
7397
  }
7398
+ function logHistorianPromptSizes(sessionId, system, prompt) {
7399
+ const sourceStart = prompt.indexOf(`<new_messages>
7400
+
7401
+ `);
7402
+ const sourceEnd = prompt.lastIndexOf(`
7403
+
7404
+ </new_messages>
7405
+
7406
+ ${HISTORIAN_TRANSCRIPT_GUARD}`);
7407
+ const hasSource = sourceStart !== -1 && sourceEnd > sourceStart;
7408
+ const blockBytes = (tag) => {
7409
+ if (!hasSource)
7410
+ return 0;
7411
+ const start = prompt.indexOf(`<${tag}>`);
7412
+ const close = `</${tag}>`;
7413
+ const end = prompt.indexOf(close, start + 1);
7414
+ return start >= 0 && end > start && end < sourceStart ? Buffer.byteLength(prompt.slice(start, end + close.length)) : 0;
7415
+ };
7416
+ const memoryBytes = blockBytes("project-memory");
7417
+ const seedBytes = blockBytes("compartment_examples_from_other_projects");
7418
+ const referenceBytes = blockBytes("session_references");
7419
+ const newMessageBytes = hasSource ? Buffer.byteLength(prompt.slice(sourceStart, sourceEnd + `
7420
+
7421
+ </new_messages>`.length)) : 0;
7422
+ const systemBytes = Buffer.byteLength(system);
7423
+ const userBytes = Buffer.byteLength(prompt);
7424
+ sessionLog2(sessionId, `historian request sizes: systemBytes=${systemBytes} userBytes=${userBytes} memoryBytes=${memoryBytes} seedBytes=${seedBytes} referenceBytes=${referenceBytes} newMessageBytes=${newMessageBytes}`);
7425
+ }
7395
7426
 
7396
7427
  // ../plugin/src/hooks/magic-context/compartment-runner-mapping.ts
7397
7428
  function tierFieldsOf(c) {
@@ -9464,9 +9495,9 @@ function fnv1a(input) {
9464
9495
  }
9465
9496
  return h >>> 0;
9466
9497
  }
9467
- function selectSeeds(sessionId, chunkStart, count = SEED_FLOOR) {
9498
+ function selectSeeds(sessionId, _chunkStart, count = SEED_FLOOR) {
9468
9499
  const bands = seedsByBand();
9469
- const seed = fnv1a(`${sessionId}:${chunkStart}`);
9500
+ const seed = fnv1a(sessionId);
9470
9501
  const picks = [];
9471
9502
  const bandOrder = [];
9472
9503
  for (let i = 0;i < SEED_BANDS.length; i++) {
@@ -9613,7 +9644,22 @@ function fitHistorianPrompt(args) {
9613
9644
  const requested = Math.max(0, Math.floor(args.requestedChunkTokens));
9614
9645
  const seeds = selectSeeds(args.sessionId, args.chunkStart);
9615
9646
  const references = selectSessionReferences(args.sessionCompartments, seeds, args.sessionId, args.chunkStart);
9616
- const memories = orderHistorianMemories(readEnabledProjectMemories(args.memoryEnabled, () => typeof args.memories === "function" ? args.memories() : args.memories));
9647
+ const memories = readEnabledProjectMemories(args.memoryEnabled, () => {
9648
+ const project = args.memoryProject;
9649
+ const projectPath = project?.projectPath;
9650
+ const workspace = project && resolveWorkspaceRenderContext(project);
9651
+ const rows = project ? projectPath && workspace ? readM0ProjectMemories(project.db, projectPath, workspace) : [] : (typeof args.memories === "function" ? args.memories() : args.memories) ?? [];
9652
+ const budget = args.memoryInjectionBudgetTokens ?? DEFAULT_MEMORY_BUDGET_TOKENS;
9653
+ const { selected } = workspace?.isWorkspaced ? trimWorkspaceMemoriesToBudgetV2(args.sessionId, rows, budget, workspace, {
9654
+ sourceNameByMemoryId: sourceNamesForMemories({
9655
+ memories: rows,
9656
+ projectPath,
9657
+ workspace
9658
+ })
9659
+ }) : trimMemoriesToBudgetV2(args.sessionId, rows, budget);
9660
+ const selectedIds = new Set(selected.map((memory) => memory.id));
9661
+ return orderHistorianMemories(rows.filter((memory) => selectedIds.has(memory.id)));
9662
+ });
9617
9663
  const render = (refs, memoryCount, seedCount) => ({
9618
9664
  seedExamples: renderSeedExamplesBlock(seeds.slice(0, seedCount)),
9619
9665
  sessionReferences: renderSessionReferencesBlock(references, refs),
@@ -10175,6 +10221,7 @@ async function runHistorianPrompt(args) {
10175
10221
  });
10176
10222
  if (failure)
10177
10223
  throw new Error(failure);
10224
+ logHistorianPromptSizes(parentSessionId, system, prompt);
10178
10225
  return executor.attempt(opened, request);
10179
10226
  }, { childSessionId: opened.childSessionId }),
10180
10227
  timeoutMs: timeoutMs ?? DEFAULT_HISTORIAN_TIMEOUT_MS,
@@ -26704,7 +26751,6 @@ function shouldWaitForNewHistorianHistory(snapshot, options = {}) {
26704
26751
  var PROACTIVE_TRIGGER_OFFSET_PERCENTAGE = 2;
26705
26752
  var POST_DROP_TARGET_RATIO = 0.75;
26706
26753
  var MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE = 6000;
26707
- var MIN_PROACTIVE_TAIL_MESSAGE_COUNT = 12;
26708
26754
  var DEFAULT_MIN_COMMIT_CLUSTERS_FOR_TRIGGER = 3;
26709
26755
  var TAIL_SIZE_TRIGGER_MULTIPLIER = 3;
26710
26756
  var BLOCK_UNTIL_DONE_PERCENTAGE = 95;
@@ -26796,7 +26842,6 @@ var TAIL_INFO_DEFAULTS = {
26796
26842
  nextStartOrdinal: 1,
26797
26843
  hasNewRawHistory: false,
26798
26844
  hasProtectedEligibleHead: false,
26799
- isMeaningful: false,
26800
26845
  tokenEstimate: 0,
26801
26846
  chunkHasMore: false,
26802
26847
  trueRawEligibleTokens: 0,
@@ -26810,6 +26855,17 @@ function resolveBoundaryContextLimit(usage, fallbackContextLimit) {
26810
26855
  }
26811
26856
  return 128000;
26812
26857
  }
26858
+ function scanFormattedHead(db, sessionId, triggerBudget, offset, eligibleEnd) {
26859
+ const seed = sessionDecisionCalibration(db, sessionId);
26860
+ const sourceRatio = Math.max(seed.proseRatio, seed.toolsRatio);
26861
+ const scanBudget = Math.floor(Math.max(MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE, triggerBudget * TAIL_SIZE_TRIGGER_MULTIPLIER) / sourceRatio);
26862
+ const chunk = readSessionChunk2(sessionId, scanBudget, offset, eligibleEnd);
26863
+ return {
26864
+ tokenEstimate: Math.ceil(chunk.tokenEstimate * sourceRatio),
26865
+ chunkHasMore: chunk.hasMore,
26866
+ commitClusterCount: chunk.commitClusterCount
26867
+ };
26868
+ }
26813
26869
  function getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThresholdPercentage, contextLimit, inMemoryTail, taggerFloor = 0, liftLivePromptFloor = false) {
26814
26870
  return withRawSessionMessageCache2(() => {
26815
26871
  try {
@@ -26852,20 +26908,15 @@ function getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThr
26852
26908
  boundarySnapshot: boundary
26853
26909
  };
26854
26910
  }
26855
- const seed = sessionDecisionCalibration(db, sessionId);
26856
- const sourceRatio = Math.max(seed.proseRatio, seed.toolsRatio);
26857
- const scanBudget = Math.floor(Math.max(MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE, triggerBudget * TAIL_SIZE_TRIGGER_MULTIPLIER) / sourceRatio);
26858
- const chunk = readSessionChunk2(sessionId, scanBudget, rawEligibility.offset, boundary.eligibleEndOrdinal);
26859
- const isMeaningful = chunk.hasMore || boundary.trueRawEligibleTokens >= MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE || Math.ceil(chunk.tokenEstimate * sourceRatio) >= MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE || chunk.messageCount >= MIN_PROACTIVE_TAIL_MESSAGE_COUNT;
26911
+ const formatted = scanFormattedHead(db, sessionId, triggerBudget, rawEligibility.offset, boundary.eligibleEndOrdinal);
26912
+ const proactiveAdmission = formatted.chunkHasMore ? "has_more" : boundary.trueRawEligibleTokens >= MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE ? "true_raw" : formatted.tokenEstimate >= MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE ? "formatted" : undefined;
26860
26913
  return {
26861
26914
  nextStartOrdinal: rawEligibility.offset,
26862
26915
  hasNewRawHistory: true,
26863
26916
  hasProtectedEligibleHead,
26864
- isMeaningful,
26865
- tokenEstimate: Math.ceil(chunk.tokenEstimate * sourceRatio),
26866
- chunkHasMore: chunk.hasMore,
26917
+ proactiveAdmission,
26918
+ ...formatted,
26867
26919
  trueRawEligibleTokens: boundary.trueRawEligibleTokens,
26868
- commitClusterCount: chunk.commitClusterCount,
26869
26920
  boundarySnapshot: boundary
26870
26921
  };
26871
26922
  } catch (error) {
@@ -26981,8 +27032,12 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
26981
27032
  sessionLog2(sessionId, `historian redundancy skip: summarizer not needed this pass — force band is ${forceMaterializationPercentage}%; queued/automatic drops are projected to reclaim to ${projectedPostDropPercentage.toFixed(1)}% (target ${relativePostDropTarget.toFixed(1)}%) on this pass (${rideLabel})`);
26982
27033
  return { shouldFire: false };
26983
27034
  }
26984
- sessionLog2(sessionId, `compartment trigger: force-firing at ${usage.percentage.toFixed(1)}% (projected post-drop ${formatProjectedPostDropPercentage(projectedPostDropPercentage)})`);
27035
+ const admittedBy = recovery ? "overflow_recovery" : usage.percentage >= BLOCK_UNTIL_DONE_PERCENTAGE ? "emergency_95" : "force_band";
27036
+ const logForceFire = (trueRawTokens, formattedTokens) => {
27037
+ sessionLog2(sessionId, `compartment trigger: force-firing at ${usage.percentage.toFixed(1)}% (projected post-drop ${formatProjectedPostDropPercentage(projectedPostDropPercentage)}) admittedBy=${admittedBy} trueRawTokens=${trueRawTokens} formattedTokens=${formattedTokens}`);
27038
+ };
26985
27039
  if (tailInfo.boundarySnapshot && hasRunnableCompartmentWindow(tailInfo.boundarySnapshot)) {
27040
+ logForceFire(tailInfo.trueRawEligibleTokens, tailInfo.tokenEstimate);
26986
27041
  return {
26987
27042
  shouldFire: true,
26988
27043
  reason: "force_band",
@@ -26998,7 +27053,7 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
26998
27053
  absoluteMessageCount: resolvedInMemoryTail.absoluteMessageCount
26999
27054
  });
27000
27055
  }
27001
- return resolveOpenCodeProtectedTailBoundary({
27056
+ const boundary = resolveOpenCodeProtectedTailBoundary({
27002
27057
  db,
27003
27058
  sessionId,
27004
27059
  mode: "trigger",
@@ -27009,8 +27064,18 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
27009
27064
  emergencyTailScale: scale,
27010
27065
  recovery
27011
27066
  });
27067
+ if (!hasRunnableCompartmentWindow(boundary))
27068
+ return null;
27069
+ let formattedTokens;
27070
+ try {
27071
+ formattedTokens = scanFormattedHead(db, sessionId, triggerBudget, boundary.offset, boundary.eligibleEndOrdinal).tokenEstimate;
27072
+ } catch {
27073
+ formattedTokens = "unavailable";
27074
+ }
27075
+ logForceFire(boundary.trueRawEligibleTokens, formattedTokens);
27076
+ return boundary;
27012
27077
  });
27013
- if (hasRunnableCompartmentWindow(scaledBoundary)) {
27078
+ if (scaledBoundary) {
27014
27079
  return { shouldFire: true, reason: "force_band", boundarySnapshot: scaledBoundary };
27015
27080
  }
27016
27081
  sessionLog2(sessionId, "compartment trigger: force_band skipped — no protected head meets summary admission after emergency tail scale");
@@ -27019,7 +27084,7 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
27019
27084
  const clusterEnabled = commitClusterTrigger?.enabled ?? true;
27020
27085
  const minClusters = commitClusterTrigger?.min_clusters ?? DEFAULT_MIN_COMMIT_CLUSTERS_FOR_TRIGGER;
27021
27086
  if (clusterEnabled && tailInfo.commitClusterCount >= minClusters && tailInfo.tokenEstimate >= triggerBudget) {
27022
- sessionLog2(sessionId, `compartment trigger: commit-cluster fire — ${tailInfo.commitClusterCount} clusters (min=${minClusters}), ~${tailInfo.tokenEstimate} tokens in eligible prefix`);
27087
+ sessionLog2(sessionId, `compartment trigger: commit-cluster fire — ${tailInfo.commitClusterCount} clusters (min=${minClusters}) admittedBy=commit_clusters trueRawTokens=${tailInfo.trueRawEligibleTokens} formattedTokens=${tailInfo.tokenEstimate}`);
27023
27088
  return {
27024
27089
  shouldFire: true,
27025
27090
  reason: "commit_clusters",
@@ -27027,7 +27092,8 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
27027
27092
  };
27028
27093
  }
27029
27094
  if (tailInfo.tokenEstimate >= triggerBudget * TAIL_SIZE_TRIGGER_MULTIPLIER || tailInfo.chunkHasMore && tailInfo.tokenEstimate > 0) {
27030
- sessionLog2(sessionId, `compartment trigger: tail-size fire — ~${tailInfo.tokenEstimate} TC-chunked tokens (hasMore=${tailInfo.chunkHasMore}, true-raw ~${tailInfo.trueRawEligibleTokens}) exceeds ${triggerBudget * TAIL_SIZE_TRIGGER_MULTIPLIER} budget threshold`);
27095
+ const admittedBy = tailInfo.chunkHasMore ? "has_more" : "formatted";
27096
+ sessionLog2(sessionId, `compartment trigger: tail-size fire — budget threshold ${triggerBudget * TAIL_SIZE_TRIGGER_MULTIPLIER} admittedBy=${admittedBy} trueRawTokens=${tailInfo.trueRawEligibleTokens} formattedTokens=${tailInfo.tokenEstimate}`);
27031
27097
  return {
27032
27098
  shouldFire: true,
27033
27099
  reason: "tail_size",
@@ -27043,13 +27109,13 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
27043
27109
  sessionLog2(sessionId, `historian redundancy skip: summarizer not needed this pass — usage is ${usage.percentage.toFixed(1)}%; queued/automatic drops are projected to reclaim to ${projectedPostDropPercentage.toFixed(1)}% (target ${relativePostDropTarget.toFixed(1)}%) on this pass (${rideLabel})`);
27044
27110
  return { shouldFire: false };
27045
27111
  }
27046
- if (!tailInfo.hasProtectedEligibleHead || !tailInfo.isMeaningful) {
27112
+ if (!tailInfo.hasProtectedEligibleHead || !tailInfo.proactiveAdmission) {
27047
27113
  let floorOnly = false;
27048
27114
  const boundary = tailInfo.boundarySnapshot;
27049
27115
  const floor = boundary?.diagnostics?.livePromptFloor;
27050
27116
  if (!consumedFloorMark && floor?.ordinal && floor.from > floor.to) {
27051
27117
  const withoutFloor = getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThresholdPercentage, contextLimit, resolvedInMemoryTail, taggerFloor, true);
27052
- floorOnly = withoutFloor.hasProtectedEligibleHead && withoutFloor.isMeaningful;
27118
+ floorOnly = withoutFloor.hasProtectedEligibleHead && withoutFloor.proactiveAdmission !== undefined;
27053
27119
  if (floorOnly && primaryExecute && usage.percentage >= executeThresholdPercentage && writeExecuteReclaimState(db, sessionId, {
27054
27120
  floorOrdinal: floor.ordinal,
27055
27121
  floorPromptId: floor.messageId ?? null
@@ -27061,7 +27127,7 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
27061
27127
  sessionLog2(sessionId, `compartment trigger: not firing at ${usage.percentage.toFixed(1)}% — ${refusal}; offset=${tailInfo.nextStartOrdinal} protectedStart=${boundary?.protectedTailStart ?? "none"} eligibleEnd=${boundary?.eligibleEndOrdinal ?? "none"} rawTokens=${tailInfo.trueRawEligibleTokens} chunkTokens=${tailInfo.tokenEstimate}`);
27062
27128
  return { shouldFire: false };
27063
27129
  }
27064
- sessionLog2(sessionId, `compartment trigger: proactive fire at ${usage.percentage.toFixed(1)}% (floor=${proactiveTriggerPercentage}% projected post-drop=${formatProjectedPostDropPercentage(projectedPostDropPercentage)} target=${relativePostDropTarget.toFixed(1)}%)`);
27130
+ sessionLog2(sessionId, `compartment trigger: proactive fire at ${usage.percentage.toFixed(1)}% (floor=${proactiveTriggerPercentage}% projected post-drop=${formatProjectedPostDropPercentage(projectedPostDropPercentage)} target=${relativePostDropTarget.toFixed(1)}%) admittedBy=${tailInfo.proactiveAdmission} trueRawTokens=${tailInfo.trueRawEligibleTokens} formattedTokens=${tailInfo.tokenEstimate}`);
27065
27131
  return {
27066
27132
  shouldFire: true,
27067
27133
  reason: "projected_headroom",
@@ -31054,6 +31120,7 @@ async function runHistorianSubagentWithTransientRetriesGuarded(args) {
31054
31120
  if (failure)
31055
31121
  throw new Error(failure);
31056
31122
  args.onDispatch?.();
31123
+ logHistorianPromptSizes(args.sessionId, args.options.systemPrompt, args.options.userMessage);
31057
31124
  result = await args.runner.run({
31058
31125
  ...args.options,
31059
31126
  cacheTail: retryIndex > 0 ? "write" : args.options.cacheTail ?? "skip",
@@ -31358,7 +31425,8 @@ async function runPiHistorian(deps) {
31358
31425
  chunkStart: Math.max(1, offset),
31359
31426
  lastOrdinal: eligibleEndOrdinal - 1,
31360
31427
  sessionCompartments: priorCompartments,
31361
- memories: () => projectPath ? getMemoriesByProject2(db, projectPath, ["active", "permanent"]) : [],
31428
+ memoryProject: { db, projectPath: projectPath ?? undefined },
31429
+ memoryInjectionBudgetTokens: deps.memoryInjectionBudgetTokens,
31362
31430
  memoryEnabled: memoryEnabled !== false,
31363
31431
  userObservationsRequested
31364
31432
  });
@@ -31470,6 +31538,9 @@ async function runPiHistorian(deps) {
31470
31538
  if (chunkText !== chunk.text) {
31471
31539
  sessionLog2(sessionId, `historian pre-flight: truncated formatted input for ${chunk.startIndex}-${chunk.endIndex} to fit ${chunkTokens} tokens`);
31472
31540
  }
31541
+ if (deps.recoveryTriggerReason) {
31542
+ sessionLog2(sessionId, `historian recovery fire: admittedBy=${deps.recoveryTriggerReason} trueRawTokens=${boundarySnapshot.trueRawEligibleTokens} formattedChunkTokens=${chunk.tokenEstimate}`);
31543
+ }
31473
31544
  const prompt = buildCompartmentAgentPrompt({
31474
31545
  seedExamples: promptFit.seedExamples,
31475
31546
  sessionReferences: promptFit.sessionReferences,
@@ -51841,6 +51912,8 @@ function spawnPiHistorianRun(args) {
51841
51912
  expandTools: historian.expandTools,
51842
51913
  thinkingLevel: historian.thinkingLevel,
51843
51914
  memoryEnabled: historian.memoryEnabled,
51915
+ memoryInjectionBudgetTokens: historian.memoryInjectionBudgetTokens,
51916
+ recoveryTriggerReason: args.recoveryTriggerReason,
51844
51917
  allowHomeProject: historian.allowHomeProject,
51845
51918
  autoPromote: historian.autoPromote,
51846
51919
  userMemoriesEnabled: historian.userMemoriesEnabled,
@@ -52098,6 +52171,7 @@ function maybeFireHistorian(args) {
52098
52171
  provider,
52099
52172
  unregister,
52100
52173
  boundarySnapshot: snapshot,
52174
+ recoveryTriggerReason: "history_retirement",
52101
52175
  refreshBoundarySnapshot: resolveRunnablePiBoundarySnapshot,
52102
52176
  currentContextLimit: boundaryContextLimit,
52103
52177
  fallbackModelId: modelKey
@@ -52128,6 +52202,7 @@ Historian previously failed ${failureCount} time(s), so Magic Context is retryin
52128
52202
  provider,
52129
52203
  unregister,
52130
52204
  boundarySnapshot: prepareRecoveryBoundary,
52205
+ recoveryTriggerReason: "startup_recovery",
52131
52206
  refreshBoundarySnapshot: resolveRunnablePiBoundarySnapshot,
52132
52207
  currentContextLimit: boundaryContextLimit,
52133
52208
  fallbackModelId: modelKey
@@ -57056,6 +57131,7 @@ Chunk ${chunkIndex}: wrapping messages ${plan.snapshot.offset}-${plan.snapshot.e
57056
57131
  maxOutputTokens: deps.historianMaxOutputTokens,
57057
57132
  thinkingLevel: deps.historianThinkingLevel,
57058
57133
  memoryEnabled: deps.memoryEnabled,
57134
+ memoryInjectionBudgetTokens: deps.memoryInjectionBudgetTokens,
57059
57135
  autoPromote: deps.autoPromote,
57060
57136
  userMemoriesEnabled: deps.userMemoriesEnabled,
57061
57137
  userObservationsRequested: deps.userObservationsRequested,
@@ -58231,6 +58307,7 @@ function resolveHistorianFromConfig(config, harness = PI_HARNESS_KIND, modelRegi
58231
58307
  keepReasoningTokens: config.keep_reasoning_tokens,
58232
58308
  historyBudgetPercentage: config.history_budget_percentage,
58233
58309
  memoryEnabled: config.memory.enabled,
58310
+ memoryInjectionBudgetTokens: config.memory.injection_budget_tokens,
58234
58311
  autoPromote: config.memory.auto_promote,
58235
58312
  userMemoriesEnabled: userObservationCollectionEnabled(config.dreamer),
58236
58313
  userObservationsRequested: userObservationsRequested(config.dreamer),
@@ -58891,6 +58968,7 @@ async function startPiMagicContextRuntime(pi, database, dbPath) {
58891
58968
  ...buildPiHistorianCommandOptions(bootProjectDeps.historianConfig, bootProjectDeps.config),
58892
58969
  language: bootProjectDeps.config.language,
58893
58970
  memoryEnabled: bootProjectDeps.config.memory.enabled,
58971
+ memoryInjectionBudgetTokens: bootProjectDeps.config.memory.injection_budget_tokens,
58894
58972
  autoPromote: bootProjectDeps.config.memory.auto_promote,
58895
58973
  compactionOff,
58896
58974
  userMemoriesEnabled: userObservationCollectionEnabled(bootProjectDeps.config.dreamer),
@@ -58907,6 +58985,7 @@ async function startPiMagicContextRuntime(pi, database, dbPath) {
58907
58985
  ...buildPiHistorianCommandOptions(historian, current.config),
58908
58986
  language: current.config.language,
58909
58987
  memoryEnabled: current.config.memory.enabled,
58988
+ memoryInjectionBudgetTokens: current.config.memory.injection_budget_tokens,
58910
58989
  autoPromote: fresh.memory.auto_promote,
58911
58990
  compactionOff,
58912
58991
  userMemoriesEnabled: userObservationCollectionEnabled(current.config.dreamer),
@@ -34,7 +34,7 @@ import {
34
34
  resolvePiHarnessKind,
35
35
  reportSubagentStartupError,
36
36
  registerMagicContextTools
37
- } from "./index-691zz6f4.js";
37
+ } from "./index-1tkrgcdt.js";
38
38
  import"./index-vcegxfwg.js";
39
39
  import"./index-5rcjs14a.js";
40
40
  import"./index-cxczethe.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.49.64",
3
+ "version": "0.49.65",
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",