@cortexkit/opencode-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.
Files changed (36) hide show
  1. package/dist/{context-v1apxpct.js → context-3mfsdp1v.js} +4 -4
  2. package/dist/hooks/magic-context/compartment-prompt.d.ts +8 -1
  3. package/dist/hooks/magic-context/compartment-prompt.d.ts.map +1 -1
  4. package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
  5. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  6. package/dist/hooks/magic-context/compartment-runner-types.d.ts +5 -0
  7. package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
  8. package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
  9. package/dist/hooks/magic-context/historian-prompt-fit.d.ts +10 -3
  10. package/dist/hooks/magic-context/historian-prompt-fit.d.ts.map +1 -1
  11. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  12. package/dist/hooks/magic-context/inject-compartments.d.ts +11 -0
  13. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  14. package/dist/hooks/magic-context/reference-retrieval.d.ts +3 -2
  15. package/dist/hooks/magic-context/reference-retrieval.d.ts.map +1 -1
  16. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  17. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  18. package/dist/hooks/magic-context/wrapup-orchestrator.d.ts +1 -0
  19. package/dist/hooks/magic-context/wrapup-orchestrator.d.ts.map +1 -1
  20. package/dist/{index-hs9xxmmy.js → index-8596jbnw.js} +3 -2
  21. package/dist/{index-5fbeycst.js → index-san8daqa.js} +1 -1
  22. package/dist/{index-aq4yfcq6.js → index-stqmv1mt.js} +55 -27
  23. package/dist/{index-m568xww6.js → index-wz0t5e5s.js} +1 -1
  24. package/dist/{index-zdd01nhc.js → index-x2hwwzk1.js} +60 -6
  25. package/dist/index.js +9 -8
  26. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  27. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  28. package/dist/{recomp-orchestrator-6vxnrh2w.js → recomp-orchestrator-nyj8ca0y.js} +2 -2
  29. package/dist/{transform-postprocess-phase-jjc9jcer.js → transform-postprocess-phase-8yjcca9t.js} +2 -2
  30. package/dist/v2/{context-nfkhb5sv.js → context-34sr5ner.js} +53 -25
  31. package/dist/v2/{recomp-orchestrator-krccyz0a.js → recomp-orchestrator-r4gqhhaw.js} +1 -1
  32. package/dist/v2/{server-xse5jngy.js → server-9rwm2z2h.js} +60 -6
  33. package/dist/v2/server.js +2 -2
  34. package/dist/v2/{wrapup-orchestrator-v2rgtczc.js → wrapup-orchestrator-p0ysz3s9.js} +2 -1
  35. package/dist/{wrapup-orchestrator-qbtg1dhm.js → wrapup-orchestrator-dxda1svq.js} +3 -3
  36. package/package.json +1 -1
@@ -220,7 +220,7 @@ import {
220
220
  startCompartmentAgent,
221
221
  setRecompStarting2,
222
222
  setRecompTerminal2
223
- } from "./server-xse5jngy.js";
223
+ } from "./server-9rwm2z2h.js";
224
224
  import {
225
225
  resolveHistorianModel2
226
226
  } from "./server-5kym00ag.js";
@@ -6252,7 +6252,6 @@ function isHistorianDrainBudgetSpent(args) {
6252
6252
  var PROACTIVE_TRIGGER_OFFSET_PERCENTAGE = 2;
6253
6253
  var POST_DROP_TARGET_RATIO = 0.75;
6254
6254
  var MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE = 6000;
6255
- var MIN_PROACTIVE_TAIL_MESSAGE_COUNT = 12;
6256
6255
  var DEFAULT_MIN_COMMIT_CLUSTERS_FOR_TRIGGER = 3;
6257
6256
  var TAIL_SIZE_TRIGGER_MULTIPLIER = 3;
6258
6257
  var BLOCK_UNTIL_DONE_PERCENTAGE = 95;
@@ -6362,7 +6361,6 @@ var TAIL_INFO_DEFAULTS = {
6362
6361
  nextStartOrdinal: 1,
6363
6362
  hasNewRawHistory: false,
6364
6363
  hasProtectedEligibleHead: false,
6365
- isMeaningful: false,
6366
6364
  tokenEstimate: 0,
6367
6365
  chunkHasMore: false,
6368
6366
  trueRawEligibleTokens: 0,
@@ -6376,6 +6374,17 @@ function resolveBoundaryContextLimit(usage, fallbackContextLimit) {
6376
6374
  }
6377
6375
  return 128000;
6378
6376
  }
6377
+ function scanFormattedHead(db, sessionId, triggerBudget, offset, eligibleEnd) {
6378
+ const seed = sessionDecisionCalibration(db, sessionId);
6379
+ const sourceRatio = Math.max(seed.proseRatio, seed.toolsRatio);
6380
+ const scanBudget = Math.floor(Math.max(MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE, triggerBudget * TAIL_SIZE_TRIGGER_MULTIPLIER) / sourceRatio);
6381
+ const chunk = readSessionChunk2(sessionId, scanBudget, offset, eligibleEnd);
6382
+ return {
6383
+ tokenEstimate: Math.ceil(chunk.tokenEstimate * sourceRatio),
6384
+ chunkHasMore: chunk.hasMore,
6385
+ commitClusterCount: chunk.commitClusterCount
6386
+ };
6387
+ }
6379
6388
  function getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThresholdPercentage, contextLimit, inMemoryTail, taggerFloor = 0, liftLivePromptFloor = false) {
6380
6389
  return withRawSessionMessageCache2(() => {
6381
6390
  try {
@@ -6418,20 +6427,15 @@ function getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThr
6418
6427
  boundarySnapshot: boundary
6419
6428
  };
6420
6429
  }
6421
- const seed = sessionDecisionCalibration(db, sessionId);
6422
- const sourceRatio = Math.max(seed.proseRatio, seed.toolsRatio);
6423
- const scanBudget = Math.floor(Math.max(MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE, triggerBudget * TAIL_SIZE_TRIGGER_MULTIPLIER) / sourceRatio);
6424
- const chunk = readSessionChunk2(sessionId, scanBudget, rawEligibility.offset, boundary.eligibleEndOrdinal);
6425
- 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;
6430
+ const formatted = scanFormattedHead(db, sessionId, triggerBudget, rawEligibility.offset, boundary.eligibleEndOrdinal);
6431
+ const proactiveAdmission = formatted.chunkHasMore ? "has_more" : boundary.trueRawEligibleTokens >= MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE ? "true_raw" : formatted.tokenEstimate >= MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE ? "formatted" : undefined;
6426
6432
  return {
6427
6433
  nextStartOrdinal: rawEligibility.offset,
6428
6434
  hasNewRawHistory: true,
6429
6435
  hasProtectedEligibleHead,
6430
- isMeaningful,
6431
- tokenEstimate: Math.ceil(chunk.tokenEstimate * sourceRatio),
6432
- chunkHasMore: chunk.hasMore,
6436
+ proactiveAdmission,
6437
+ ...formatted,
6433
6438
  trueRawEligibleTokens: boundary.trueRawEligibleTokens,
6434
- commitClusterCount: chunk.commitClusterCount,
6435
6439
  boundarySnapshot: boundary
6436
6440
  };
6437
6441
  } catch (error) {
@@ -6547,8 +6551,12 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
6547
6551
  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})`);
6548
6552
  return { shouldFire: false };
6549
6553
  }
6550
- sessionLog2(sessionId, `compartment trigger: force-firing at ${usage.percentage.toFixed(1)}% (projected post-drop ${formatProjectedPostDropPercentage(projectedPostDropPercentage)})`);
6554
+ const admittedBy = recovery ? "overflow_recovery" : usage.percentage >= BLOCK_UNTIL_DONE_PERCENTAGE ? "emergency_95" : "force_band";
6555
+ const logForceFire = (trueRawTokens, formattedTokens) => {
6556
+ sessionLog2(sessionId, `compartment trigger: force-firing at ${usage.percentage.toFixed(1)}% (projected post-drop ${formatProjectedPostDropPercentage(projectedPostDropPercentage)}) admittedBy=${admittedBy} trueRawTokens=${trueRawTokens} formattedTokens=${formattedTokens}`);
6557
+ };
6551
6558
  if (tailInfo.boundarySnapshot && hasRunnableCompartmentWindow(tailInfo.boundarySnapshot)) {
6559
+ logForceFire(tailInfo.trueRawEligibleTokens, tailInfo.tokenEstimate);
6552
6560
  return {
6553
6561
  shouldFire: true,
6554
6562
  reason: "force_band",
@@ -6564,7 +6572,7 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
6564
6572
  absoluteMessageCount: resolvedInMemoryTail.absoluteMessageCount
6565
6573
  });
6566
6574
  }
6567
- return resolveOpenCodeProtectedTailBoundary({
6575
+ const boundary = resolveOpenCodeProtectedTailBoundary({
6568
6576
  db,
6569
6577
  sessionId,
6570
6578
  mode: "trigger",
@@ -6575,8 +6583,18 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
6575
6583
  emergencyTailScale: scale,
6576
6584
  recovery
6577
6585
  });
6586
+ if (!hasRunnableCompartmentWindow(boundary))
6587
+ return null;
6588
+ let formattedTokens;
6589
+ try {
6590
+ formattedTokens = scanFormattedHead(db, sessionId, triggerBudget, boundary.offset, boundary.eligibleEndOrdinal).tokenEstimate;
6591
+ } catch {
6592
+ formattedTokens = "unavailable";
6593
+ }
6594
+ logForceFire(boundary.trueRawEligibleTokens, formattedTokens);
6595
+ return boundary;
6578
6596
  });
6579
- if (hasRunnableCompartmentWindow(scaledBoundary)) {
6597
+ if (scaledBoundary) {
6580
6598
  return { shouldFire: true, reason: "force_band", boundarySnapshot: scaledBoundary };
6581
6599
  }
6582
6600
  sessionLog2(sessionId, "compartment trigger: force_band skipped — no protected head meets summary admission after emergency tail scale");
@@ -6585,7 +6603,7 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
6585
6603
  const clusterEnabled = commitClusterTrigger?.enabled ?? true;
6586
6604
  const minClusters = commitClusterTrigger?.min_clusters ?? DEFAULT_MIN_COMMIT_CLUSTERS_FOR_TRIGGER;
6587
6605
  if (clusterEnabled && tailInfo.commitClusterCount >= minClusters && tailInfo.tokenEstimate >= triggerBudget) {
6588
- sessionLog2(sessionId, `compartment trigger: commit-cluster fire — ${tailInfo.commitClusterCount} clusters (min=${minClusters}), ~${tailInfo.tokenEstimate} tokens in eligible prefix`);
6606
+ sessionLog2(sessionId, `compartment trigger: commit-cluster fire — ${tailInfo.commitClusterCount} clusters (min=${minClusters}) admittedBy=commit_clusters trueRawTokens=${tailInfo.trueRawEligibleTokens} formattedTokens=${tailInfo.tokenEstimate}`);
6589
6607
  return {
6590
6608
  shouldFire: true,
6591
6609
  reason: "commit_clusters",
@@ -6593,7 +6611,8 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
6593
6611
  };
6594
6612
  }
6595
6613
  if (tailInfo.tokenEstimate >= triggerBudget * TAIL_SIZE_TRIGGER_MULTIPLIER || tailInfo.chunkHasMore && tailInfo.tokenEstimate > 0) {
6596
- 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`);
6614
+ const admittedBy = tailInfo.chunkHasMore ? "has_more" : "formatted";
6615
+ sessionLog2(sessionId, `compartment trigger: tail-size fire — budget threshold ${triggerBudget * TAIL_SIZE_TRIGGER_MULTIPLIER} admittedBy=${admittedBy} trueRawTokens=${tailInfo.trueRawEligibleTokens} formattedTokens=${tailInfo.tokenEstimate}`);
6597
6616
  return {
6598
6617
  shouldFire: true,
6599
6618
  reason: "tail_size",
@@ -6609,13 +6628,13 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
6609
6628
  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})`);
6610
6629
  return { shouldFire: false };
6611
6630
  }
6612
- if (!tailInfo.hasProtectedEligibleHead || !tailInfo.isMeaningful) {
6631
+ if (!tailInfo.hasProtectedEligibleHead || !tailInfo.proactiveAdmission) {
6613
6632
  let floorOnly = false;
6614
6633
  const boundary = tailInfo.boundarySnapshot;
6615
6634
  const floor = boundary?.diagnostics?.livePromptFloor;
6616
6635
  if (!consumedFloorMark && floor?.ordinal && floor.from > floor.to) {
6617
6636
  const withoutFloor = getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThresholdPercentage, contextLimit, resolvedInMemoryTail, taggerFloor, true);
6618
- floorOnly = withoutFloor.hasProtectedEligibleHead && withoutFloor.isMeaningful;
6637
+ floorOnly = withoutFloor.hasProtectedEligibleHead && withoutFloor.proactiveAdmission !== undefined;
6619
6638
  if (floorOnly && primaryExecute && usage.percentage >= executeThresholdPercentage && writeExecuteReclaimState(db, sessionId, {
6620
6639
  floorOrdinal: floor.ordinal,
6621
6640
  floorPromptId: floor.messageId ?? null
@@ -6627,7 +6646,7 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
6627
6646
  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}`);
6628
6647
  return { shouldFire: false };
6629
6648
  }
6630
- sessionLog2(sessionId, `compartment trigger: proactive fire at ${usage.percentage.toFixed(1)}% (floor=${proactiveTriggerPercentage}% projected post-drop=${formatProjectedPostDropPercentage(projectedPostDropPercentage)} target=${relativePostDropTarget.toFixed(1)}%)`);
6649
+ 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}`);
6631
6650
  return {
6632
6651
  shouldFire: true,
6633
6652
  reason: "projected_headroom",
@@ -20380,7 +20399,7 @@ async function runCompartmentPhaseImpl(args) {
20380
20399
  const budgetMs = resolveHistorianInlineJoinBudget(args.historianTimeoutMs);
20381
20400
  return { timeoutMs: budgetMs, budgetMs };
20382
20401
  }
20383
- function historianRunDeps(boundarySnapshot) {
20402
+ function historianRunDeps(boundarySnapshot, recoveryTriggerReason) {
20384
20403
  return {
20385
20404
  client: args.client,
20386
20405
  hiddenCompletionExecutor: args.hiddenCompletionExecutor,
@@ -20389,6 +20408,7 @@ async function runCompartmentPhaseImpl(args) {
20389
20408
  sessionId: args.sessionId,
20390
20409
  historianChunkTokens: args.historianChunkTokens,
20391
20410
  boundarySnapshot,
20411
+ recoveryTriggerReason,
20392
20412
  currentContextLimit: args.boundaryContextLimit,
20393
20413
  historyBudgetTokens: args.historyBudgetTokens,
20394
20414
  historianTimeoutMs: args.historianTimeoutMs,
@@ -20405,6 +20425,8 @@ async function runCompartmentPhaseImpl(args) {
20405
20425
  historianTwoPass: args.historianTwoPass,
20406
20426
  historianExpandTools: args.historianExpandTools,
20407
20427
  memoryEnabled: args.memoryEnabled,
20428
+ memoryInjectionBudgetTokens: args.injectionBudgetTokens,
20429
+ memoryProjectPath: args.projectPath ?? null,
20408
20430
  autoPromote: args.autoPromote,
20409
20431
  onCompartmentStatePublished: args.onCompartmentStatePublished,
20410
20432
  preserveInjectionCacheUntilConsumed: true
@@ -20467,7 +20489,7 @@ async function runCompartmentPhaseImpl(args) {
20467
20489
  sessionLog2(args.sessionId, `transform: recovery chain stops: the historian's drain budget is spent; the request is still about ${fit.tokens} tokens, over the 95% line ${fit.lineTokens}`);
20468
20490
  return "stopped";
20469
20491
  }
20470
- startCompartmentAgent(historianRunDeps(boundary));
20492
+ startCompartmentAgent(historianRunDeps(boundary, "recovery_chain"));
20471
20493
  const nextRun = getActiveCompartmentRun(args.sessionId);
20472
20494
  if (!nextRun || nextRun === lastRun) {
20473
20495
  sessionLog2(args.sessionId, "transform: recovery chain stops: the next historian run did not start");
@@ -20542,6 +20564,8 @@ async function runCompartmentPhaseImpl(args) {
20542
20564
  historianTwoPass: args.historianTwoPass,
20543
20565
  historianExpandTools: args.historianExpandTools,
20544
20566
  memoryEnabled: args.memoryEnabled,
20567
+ memoryInjectionBudgetTokens: args.injectionBudgetTokens,
20568
+ memoryProjectPath: args.projectPath ?? null,
20545
20569
  autoPromote: args.autoPromote,
20546
20570
  onCompartmentStatePublished: args.onCompartmentStatePublished,
20547
20571
  preserveInjectionCacheUntilConsumed: true
@@ -20560,7 +20584,7 @@ async function runCompartmentPhaseImpl(args) {
20560
20584
  let activeRun = getActiveCompartmentRun(args.sessionId);
20561
20585
  if (!activeRun && hasEligibleHistoryForCompartment() && (args.client || args.hiddenCompletionExecutor)) {
20562
20586
  sessionLog2(args.sessionId, `transform: 95% reached (${args.contextUsage.percentage.toFixed(1)}%), force-starting compartment agent and blocking`);
20563
- startCompartmentAgent(historianRunDeps(getBoundarySnapshotForCompartment() ?? undefined));
20587
+ startCompartmentAgent(historianRunDeps(getBoundarySnapshotForCompartment() ?? undefined, "emergency_95"));
20564
20588
  activeRun = getActiveCompartmentRun(args.sessionId);
20565
20589
  } else if (!activeRun && hasEligibleHistoryForCompartment()) {
20566
20590
  sessionLog2(args.sessionId, "transform: cannot force-start compartment agent without client");
@@ -21428,6 +21452,7 @@ function createTransform(deps) {
21428
21452
  sessionId,
21429
21453
  historianChunkTokens: historianRun?.chunkTokens ?? deps.getHistorianChunkTokens?.() ?? 20000,
21430
21454
  boundarySnapshot: boundarySnapshot ?? undefined,
21455
+ recoveryTriggerReason: emergencyRecoveryArmed ? "overflow_recovery" : urgent ? "emergency_95" : "startup_recovery",
21431
21456
  currentContextLimit: boundaryContextLimit,
21432
21457
  historyBudgetTokens,
21433
21458
  historianTimeoutMs: historianRun?.timeoutMs ?? deps.historianTimeoutMs,
@@ -21442,6 +21467,8 @@ function createTransform(deps) {
21442
21467
  historianTwoPass: historianRun?.twoPass ?? deps.historianTwoPass,
21443
21468
  historianExpandTools: historianRun?.expandTools ?? deps.historianExpandTools,
21444
21469
  memoryEnabled: deps.memoryConfig?.enabled,
21470
+ memoryInjectionBudgetTokens: deps.memoryConfig?.injectionBudgetTokens,
21471
+ memoryProjectPath: projectIdentity ?? null,
21445
21472
  autoPromote: historianRun?.autoPromote ?? deps.memoryConfig?.autoPromote,
21446
21473
  ensureProjectRegistered: deps.ensureProjectRegistered,
21447
21474
  preserveInjectionCacheUntilConsumed: true,
@@ -26079,7 +26106,7 @@ function registerRpcHandlers(rpcServer, args) {
26079
26106
  const db = readDatabase();
26080
26107
  if (!db)
26081
26108
  return { ok: false, error: "db unavailable" };
26082
- const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-krccyz0a.js"));
26109
+ const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-r4gqhhaw.js"));
26083
26110
  const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-8g4r97bp.js"));
26084
26111
  log2(`[rpc] recomp requested for session ${sessionId}`);
26085
26112
  if (!args.client && !args.hiddenCompletionExecutor) {
@@ -26164,11 +26191,12 @@ function registerRpcHandlers(rpcServer, args) {
26164
26191
  const db = readDatabase();
26165
26192
  if (!db)
26166
26193
  return { ok: false, error: "db unavailable" };
26167
- const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-v2rgtczc.js"));
26194
+ const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-p0ysz3s9.js"));
26168
26195
  const model = liveSessionState.liveModelBySession.get(sessionId);
26169
26196
  const contextLimit = model ? resolveContextLimit(model.providerID, model.modelID, { db, sessionID: sessionId }) : 128000;
26170
26197
  const ctx = {
26171
26198
  ...await buildManagedCtx(db),
26199
+ memoryInjectionBudgetTokens: config.memory?.injection_budget_tokens,
26172
26200
  contextLimit,
26173
26201
  executeThresholdPercentage: resolveExecuteThresholdDetail(config.execute_threshold_percentage ?? 65, model ? `${model.providerID}/${model.modelID}` : undefined, 65, {
26174
26202
  tokensConfig: config.execute_threshold_tokens,
@@ -7,7 +7,7 @@ import {
7
7
  setRecompTerminal2,
8
8
  buildRecompDeps2,
9
9
  runManagedRecomp2
10
- } from "./server-xse5jngy.js";
10
+ } from "./server-9rwm2z2h.js";
11
11
  import"./server-at0v0z4t.js";
12
12
  import"./server-d07yxksx.js";
13
13
  import"./server-d9aayyxk.js";
@@ -6016,11 +6016,11 @@ var USER_OBSERVATIONS_DISABLED_TOGGLE = `<user_observation_extraction>disabled</
6016
6016
  User-memory review is not running (the dreamer is disabled): do NOT emit a <user_observations> block.`;
6017
6017
  function buildCompartmentAgentPrompt(inputs) {
6018
6018
  const parts = [];
6019
+ parts.push(...readEnabledProjectMemories(inputs.memoryEnabled, () => inputs.projectMemory ? [inputs.projectMemory] : []));
6019
6020
  if (inputs.seedExamples)
6020
6021
  parts.push(inputs.seedExamples);
6021
6022
  if (inputs.sessionReferences)
6022
6023
  parts.push(inputs.sessionReferences);
6023
- parts.push(...readEnabledProjectMemories(inputs.memoryEnabled, () => inputs.projectMemory ? [inputs.projectMemory] : []));
6024
6024
  if (inputs.extractionFree) {
6025
6025
  parts.push(`<extraction>disabled</extraction>
6026
6026
  Structural recomp mode: emit compartments and <meta> only. Do NOT emit <facts>, <events>, <user_observations>, or <primer_candidates>.`);
@@ -6040,6 +6040,34 @@ Memory is disabled for this project: do NOT emit a <facts> block. Produce compar
6040
6040
 
6041
6041
  `);
6042
6042
  }
6043
+ function logHistorianPromptSizes(sessionId, system, prompt) {
6044
+ const sourceStart = prompt.indexOf(`<new_messages>
6045
+
6046
+ `);
6047
+ const sourceEnd = prompt.lastIndexOf(`
6048
+
6049
+ </new_messages>
6050
+
6051
+ ${HISTORIAN_TRANSCRIPT_GUARD}`);
6052
+ const hasSource = sourceStart !== -1 && sourceEnd > sourceStart;
6053
+ const blockBytes = (tag) => {
6054
+ if (!hasSource)
6055
+ return 0;
6056
+ const start = prompt.indexOf(`<${tag}>`);
6057
+ const close = `</${tag}>`;
6058
+ const end = prompt.indexOf(close, start + 1);
6059
+ return start >= 0 && end > start && end < sourceStart ? Buffer.byteLength(prompt.slice(start, end + close.length)) : 0;
6060
+ };
6061
+ const memoryBytes = blockBytes("project-memory");
6062
+ const seedBytes = blockBytes("compartment_examples_from_other_projects");
6063
+ const referenceBytes = blockBytes("session_references");
6064
+ const newMessageBytes = hasSource ? Buffer.byteLength(prompt.slice(sourceStart, sourceEnd + `
6065
+
6066
+ </new_messages>`.length)) : 0;
6067
+ const systemBytes = Buffer.byteLength(system);
6068
+ const userBytes = Buffer.byteLength(prompt);
6069
+ sessionLog2(sessionId, `historian request sizes: systemBytes=${systemBytes} userBytes=${userBytes} memoryBytes=${memoryBytes} seedBytes=${seedBytes} referenceBytes=${referenceBytes} newMessageBytes=${newMessageBytes}`);
6070
+ }
6043
6071
 
6044
6072
  // src/hooks/magic-context/compartment-runner-drop-queue.ts
6045
6073
  function prepareCompartmentDrops(db, sessionId, upToMessageIndex, observedKeys, fromMessageIndex = 1) {
@@ -8522,6 +8550,9 @@ function sourceNamesForMemories(args) {
8522
8550
  }
8523
8551
  return names.size > 0 ? names : undefined;
8524
8552
  }
8553
+ function readM0ProjectMemories(db, projectPath, workspace, at = Date.now()) {
8554
+ return workspace.isWorkspaced ? getMemoriesByProjects2(db, workspace.expandedIdentities, ["active", "permanent"], at, workspace.ownIdentities, workspace.shareCategories) : getMemoriesByProject2(db, projectPath, ["active", "permanent"], at);
8555
+ }
8525
8556
  function memoryCanonicalIdentity(memory, workspace) {
8526
8557
  return resolveStoredPathWorkspaceIdentity(memory.projectPath, workspace.identities, workspace.canonicalIdentityByStoredPath);
8527
8558
  }
@@ -9298,7 +9329,7 @@ function materializeM0(options) {
9298
9329
  snapshotMarkers.projectDocsHash = docs.canonicalHash;
9299
9330
  compartments = options.compactionOff ? [] : readM0Compartments(options.db, options.sessionId);
9300
9331
  facts = [];
9301
- memories = projectPath ? workspace.isWorkspaced ? getMemoriesByProjects2(options.db, workspace.expandedIdentities, ["active", "permanent"], foldMaterializedAt, workspace.ownIdentities, workspace.shareCategories) : getMemoriesByProject2(options.db, projectPath, ["active", "permanent"], foldMaterializedAt) : [];
9332
+ memories = projectPath ? readM0ProjectMemories(options.db, projectPath, workspace, foldMaterializedAt) : [];
9302
9333
  userMemories = options.memoryEnabled === false ? [] : safeGetActiveUserMemories(options.db);
9303
9334
  options.db.exec("COMMIT");
9304
9335
  } catch (error) {
@@ -12253,9 +12284,9 @@ function fnv1a(input) {
12253
12284
  }
12254
12285
  return h >>> 0;
12255
12286
  }
12256
- function selectSeeds(sessionId, chunkStart, count = SEED_FLOOR) {
12287
+ function selectSeeds(sessionId, _chunkStart, count = SEED_FLOOR) {
12257
12288
  const bands = seedsByBand();
12258
- const seed = fnv1a(`${sessionId}:${chunkStart}`);
12289
+ const seed = fnv1a(sessionId);
12259
12290
  const picks = [];
12260
12291
  const bandOrder = [];
12261
12292
  for (let i = 0;i < SEED_BANDS.length; i++) {
@@ -12402,7 +12433,22 @@ function fitHistorianPrompt(args) {
12402
12433
  const requested = Math.max(0, Math.floor(args.requestedChunkTokens));
12403
12434
  const seeds = selectSeeds(args.sessionId, args.chunkStart);
12404
12435
  const references = selectSessionReferences(args.sessionCompartments, seeds, args.sessionId, args.chunkStart);
12405
- const memories = orderHistorianMemories(readEnabledProjectMemories(args.memoryEnabled, () => typeof args.memories === "function" ? args.memories() : args.memories));
12436
+ const memories = readEnabledProjectMemories(args.memoryEnabled, () => {
12437
+ const project = args.memoryProject;
12438
+ const projectPath = project?.projectPath;
12439
+ const workspace = project && resolveWorkspaceRenderContext(project);
12440
+ const rows = project ? projectPath && workspace ? readM0ProjectMemories(project.db, projectPath, workspace) : [] : (typeof args.memories === "function" ? args.memories() : args.memories) ?? [];
12441
+ const budget = args.memoryInjectionBudgetTokens ?? DEFAULT_MEMORY_BUDGET_TOKENS;
12442
+ const { selected } = workspace?.isWorkspaced ? trimWorkspaceMemoriesToBudgetV2(args.sessionId, rows, budget, workspace, {
12443
+ sourceNameByMemoryId: sourceNamesForMemories({
12444
+ memories: rows,
12445
+ projectPath,
12446
+ workspace
12447
+ })
12448
+ }) : trimMemoriesToBudgetV2(args.sessionId, rows, budget);
12449
+ const selectedIds = new Set(selected.map((memory) => memory.id));
12450
+ return orderHistorianMemories(rows.filter((memory) => selectedIds.has(memory.id)));
12451
+ });
12406
12452
  const render = (refs, memoryCount, seedCount) => ({
12407
12453
  seedExamples: renderSeedExamplesBlock(seeds.slice(0, seedCount)),
12408
12454
  sessionReferences: renderSessionReferencesBlock(references, refs),
@@ -12964,6 +13010,7 @@ async function runHistorianPrompt(args) {
12964
13010
  });
12965
13011
  if (failure)
12966
13012
  throw new Error(failure);
13013
+ logHistorianPromptSizes(parentSessionId, system, prompt);
12967
13014
  return executor.attempt(opened, request);
12968
13015
  }, { childSessionId: opened.childSessionId }),
12969
13016
  timeoutMs: timeoutMs ?? DEFAULT_HISTORIAN_TIMEOUT_MS,
@@ -14983,7 +15030,11 @@ async function runCompartmentAgent(deps) {
14983
15030
  chunkStart: Math.max(1, offset),
14984
15031
  lastOrdinal: eligibleEndOrdinal - 1,
14985
15032
  sessionCompartments: priorCompartments,
14986
- memories: () => getMemoriesByProject2(db, projectPath, ["active", "permanent"]),
15033
+ memoryProject: {
15034
+ db,
15035
+ projectPath: deps.memoryProjectPath === undefined ? projectPath : deps.memoryProjectPath ?? undefined
15036
+ },
15037
+ memoryInjectionBudgetTokens: deps.memoryInjectionBudgetTokens,
14987
15038
  memoryEnabled: deps.memoryEnabled !== false,
14988
15039
  userObservationsRequested: deps.userObservationsRequested
14989
15040
  });
@@ -15104,6 +15155,9 @@ async function runCompartmentAgent(deps) {
15104
15155
  }
15105
15156
  historianRunStarted = true;
15106
15157
  deps.onHistorianRunStarted?.();
15158
+ if (deps.recoveryTriggerReason) {
15159
+ sessionLog2(sessionId, `historian recovery fire: admittedBy=${deps.recoveryTriggerReason} trueRawTokens=${boundarySnapshot.trueRawEligibleTokens} formattedChunkTokens=${chunk.tokenEstimate}`);
15160
+ }
15107
15161
  const prompt = buildCompartmentAgentPrompt({
15108
15162
  seedExamples: promptFit.seedExamples,
15109
15163
  sessionReferences: promptFit.sessionReferences,
package/dist/v2/server.js CHANGED
@@ -7875,7 +7875,7 @@ var require_src2 = __commonJS(function(exports, module) {
7875
7875
  // package.json
7876
7876
  var package_default = {
7877
7877
  name: "@cortexkit/opencode-magic-context",
7878
- version: "0.49.64",
7878
+ version: "0.49.65",
7879
7879
  type: "module",
7880
7880
  description: "OpenCode plugin for Magic Context — cross-session memory and context management",
7881
7881
  main: "dist/index.js",
@@ -8196,7 +8196,7 @@ async function setup(context) {
8196
8196
  if (claimStorageBackupWarningCheck() && isMagicContextStorageOutsideEngram(storageDir)) {
8197
8197
  log2(`[magic-context] Magic Context storage is at ${storageDir}, outside the folder Engram backs up (~/.local/share/cortexkit/magic-context). It is not included in CortexKit backups.`);
8198
8198
  }
8199
- const { registerContext } = await import("./context-nfkhb5sv.js");
8199
+ const { registerContext } = await import("./context-34sr5ner.js");
8200
8200
  setHarness2("opencode2");
8201
8201
  bindStaleBuildNotice({}, import.meta.url, "opencode2");
8202
8202
  const duties = await registerContext(context);
@@ -63,7 +63,7 @@ import {
63
63
  registerActiveCompartmentRun,
64
64
  setRecompStarting2,
65
65
  setRecompTerminal2
66
- } from "./server-xse5jngy.js";
66
+ } from "./server-9rwm2z2h.js";
67
67
  import"./server-qt1qqasc.js";
68
68
  import"./server-z5255w05.js";
69
69
  import"./server-jtq03rkb.js";
@@ -231,6 +231,7 @@ async function runOneWrapupIteration(args) {
231
231
  historianTwoPass: ctx.historianTwoPass,
232
232
  historianExpandTools: ctx.historianExpandTools,
233
233
  memoryEnabled: ctx.memoryEnabled,
234
+ memoryInjectionBudgetTokens: ctx.memoryInjectionBudgetTokens,
234
235
  autoPromote: ctx.autoPromote,
235
236
  experimentalUserMemories: ctx.userMemoriesEnabled,
236
237
  userObservationsRequested: ctx.userObservationsRequested,
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  runManagedWrapup2
3
- } from "./index-hs9xxmmy.js";
4
- import"./index-m568xww6.js";
5
- import"./index-zdd01nhc.js";
3
+ } from "./index-8596jbnw.js";
4
+ import"./index-wz0t5e5s.js";
5
+ import"./index-x2hwwzk1.js";
6
6
  import"./index-832w615x.js";
7
7
  import"./index-sd3egckz.js";
8
8
  import"./index-n6aye6ny.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-magic-context",
3
- "version": "0.49.64",
3
+ "version": "0.49.65",
4
4
  "type": "module",
5
5
  "description": "OpenCode plugin for Magic Context — cross-session memory and context management",
6
6
  "main": "dist/index.js",