@cortexkit/pi-magic-context 0.43.0 → 0.43.2

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.
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  log,
10
10
  sessionLog,
11
11
  flushLogger
12
- } from "./index-83wwtw1q.js";
12
+ } from "./index-bfd52y8p.js";
13
13
  import {
14
14
  COMPACTION_ENABLED_PATH,
15
15
  isDreamerRunnable,
@@ -402,7 +402,7 @@ import {
402
402
  registerTodoStateLifecycle,
403
403
  syncCtxMemoryToolEnabled,
404
404
  registerMagicContextTools
405
- } from "./index-5tw61yhp.js";
405
+ } from "./index-bkrh6jhp.js";
406
406
  import {
407
407
  CTX_REDUCE_KEEP,
408
408
  newestCtxReduceTagNumbers,
@@ -512,13 +512,14 @@ import {
512
512
  getRawSessionTagKeysThrough2,
513
513
  getLegacyProtectedTailStartOrdinal2,
514
514
  readSessionChunk2
515
- } from "./index-vcjgpb6f.js";
515
+ } from "./index-mea04n1j.js";
516
516
  import {
517
517
  pushNotification2
518
518
  } from "./index-b3eqj1g6.js";
519
+ import"./index-5v60m046.js";
519
520
  import {
520
521
  logSlowWriteTransaction
521
- } from "./index-y33j7m6y.js";
522
+ } from "./index-17102c1m.js";
522
523
  import {
523
524
  __toESM
524
525
  } from "./index-22jkk6wg.js";
@@ -842,7 +843,7 @@ var DREAM_TASK_CAPABILITIES = {
842
843
  "maintain-docs": {
843
844
  requiresTools: true,
844
845
  transport: "tool-loop",
845
- toolLoopPurpose: "needs file read and write tools to update project documentation"
846
+ toolLoopPurpose: "needs read-only file tools to investigate documentation corrections"
846
847
  },
847
848
  "evaluate-smart-notes": { requiresTools: false, transport: "single-shot" },
848
849
  "review-user-memories": { requiresTools: false, transport: "single-shot" },
@@ -1823,6 +1824,8 @@ function setCtxReduceRegisteredGlobally(registered) {
1823
1824
  var availabilityBySession = new BoundedSessionMap(1000);
1824
1825
  var permissionDeniedBySession = new BoundedSessionMap(2000);
1825
1826
  var ctxReducePermissionDenyLogged = new BoundedSessionMap(1000);
1827
+ var ctxReduceSpawnPermissionDenied = new BoundedSessionMap(1000);
1828
+ var ctxReduceSpawnPermissionReads = new Map;
1826
1829
 
1827
1830
  // ../plugin/src/hooks/magic-context/derive-budgets.ts
1828
1831
  var TRIGGER_BUDGET_PERCENTAGE = 0.05;
@@ -2779,6 +2782,11 @@ var USER_FACING_FAILURES = {
2779
2782
  sentence: "Some finished background sessions could not be removed from this host.",
2780
2783
  action: "They are removed automatically the next time Magic Context runs inside a registered OpenCode service."
2781
2784
  },
2785
+ historian_saved_history_misaligned: {
2786
+ code: "MC-H03",
2787
+ sentence: "History compression is paused because this session's saved summaries no longer line up with its messages.",
2788
+ action: "Run /ctx-recomp to rebuild them."
2789
+ },
2782
2790
  recomp_unavailable: {
2783
2791
  code: "MC-R01",
2784
2792
  sentence: "History compression could not be rebuilt.",
@@ -2949,6 +2957,11 @@ var USER_FACING_FAILURES = {
2949
2957
  sentence: "History compression is paused while the engine syncs.",
2950
2958
  action: "Retry in a moment."
2951
2959
  },
2960
+ history_compression_needs_message: {
2961
+ code: "MC-C12",
2962
+ sentence: "History compression has not seen this session since Magic Context reconnected.",
2963
+ action: "Send a message in this session first, then run /ctx-wrapup again."
2964
+ },
2952
2965
  context_service_unavailable: {
2953
2966
  code: "MC-C10",
2954
2967
  sentence: "Magic Context is temporarily unavailable.",
@@ -3191,6 +3204,73 @@ class HiddenCompletionRefusal extends Error {
3191
3204
  this.name = "HiddenCompletionRefusal";
3192
3205
  }
3193
3206
  }
3207
+ // ../plugin/src/shared/assistant-message-extractor.ts
3208
+ function asSessionMessage(value) {
3209
+ if (!isRecord(value))
3210
+ return null;
3211
+ const info = value.info;
3212
+ const parts = value.parts;
3213
+ return {
3214
+ info: isRecord(info) ? {
3215
+ role: typeof info.role === "string" ? info.role : undefined,
3216
+ time: isRecord(info.time) ? {
3217
+ created: typeof info.time.created === "number" ? info.time.created : undefined
3218
+ } : undefined,
3219
+ error: info.error,
3220
+ finish: typeof info.finish === "string" ? info.finish : typeof info.finish_reason === "string" ? info.finish_reason : typeof info.finishReason === "string" ? info.finishReason : undefined
3221
+ } : undefined,
3222
+ parts
3223
+ };
3224
+ }
3225
+ function getCreatedTime(message) {
3226
+ return message.info?.time?.created ?? 0;
3227
+ }
3228
+ function getTextParts(message) {
3229
+ if (!Array.isArray(message.parts))
3230
+ return [];
3231
+ return message.parts.filter((part) => isRecord(part)).map((part) => ({
3232
+ type: typeof part.type === "string" ? part.type : undefined,
3233
+ text: typeof part.text === "string" ? part.text : undefined
3234
+ })).filter((part) => part.type === "text" && Boolean(part.text));
3235
+ }
3236
+ function getLatestAssistantMessage(messages) {
3237
+ if (!Array.isArray(messages) || messages.length === 0)
3238
+ return null;
3239
+ return messages.map(asSessionMessage).filter((message) => message !== null).filter((message) => message.info?.role === "assistant").sort((a, b) => getCreatedTime(b) - getCreatedTime(a))[0] ?? null;
3240
+ }
3241
+ function extractLatestAssistantText(messages) {
3242
+ const latest = getLatestAssistantMessage(messages);
3243
+ if (!latest)
3244
+ return null;
3245
+ return getTextParts(latest).map((part) => part.text).join(`
3246
+ `) || null;
3247
+ }
3248
+ function extractLatestAssistantFailure(messages) {
3249
+ const latest = getLatestAssistantMessage(messages);
3250
+ if (!latest || latest.info?.error === undefined || latest.info.error === null)
3251
+ return null;
3252
+ return {
3253
+ error: latest.info.error,
3254
+ finish: latest.info.finish ?? null
3255
+ };
3256
+ }
3257
+ function hasLengthCappedOutput(value) {
3258
+ if (Array.isArray(value))
3259
+ return value.some((item) => hasLengthCappedOutput(item));
3260
+ if (!isRecord(value))
3261
+ return false;
3262
+ if (value.length_capped === true || value.lengthCapped === true)
3263
+ return true;
3264
+ const finishReason = value.finish_reason ?? value.finishReason ?? value.finish ?? (value.type === "step-finish" ? value.reason : undefined) ?? value.stopReason;
3265
+ if (typeof finishReason === "string") {
3266
+ const normalized = finishReason.toLowerCase();
3267
+ if (normalized === "length" || normalized === "max_tokens" || normalized === "max_output_tokens") {
3268
+ return true;
3269
+ }
3270
+ }
3271
+ return Object.values(value).some((item) => hasLengthCappedOutput(item));
3272
+ }
3273
+
3194
3274
  // ../plugin/src/shared/resolve-fallbacks.ts
3195
3275
  function parseProviderModel(spec) {
3196
3276
  const slash = spec.indexOf("/");
@@ -3484,6 +3564,17 @@ async function attemptAndValidate(client, args, timeoutMs, signal, callContext,
3484
3564
  };
3485
3565
  }
3486
3566
  try {
3567
+ if (!extractLatestAssistantText(output)) {
3568
+ const assistantFailure = extractLatestAssistantFailure(output);
3569
+ if (assistantFailure) {
3570
+ const error = new Error(`Host recorded assistant error: ${String(assistantFailure.error)}`);
3571
+ Object.assign(error, {
3572
+ name: "DreamerProviderOutputFailureError",
3573
+ transient: true
3574
+ });
3575
+ throw error;
3576
+ }
3577
+ }
3487
3578
  const validated = await options.validateOutput(output, attempt);
3488
3579
  return { output, validated, attempt };
3489
3580
  } catch (error) {
@@ -3611,73 +3702,6 @@ function summarizeChildStderr(stderr) {
3611
3702
  return excerptLines.join(`
3612
3703
  `).slice(0, MAX_CHILD_STDERR_SUMMARY_LENGTH);
3613
3704
  }
3614
- // ../plugin/src/shared/assistant-message-extractor.ts
3615
- function asSessionMessage(value) {
3616
- if (!isRecord(value))
3617
- return null;
3618
- const info = value.info;
3619
- const parts = value.parts;
3620
- return {
3621
- info: isRecord(info) ? {
3622
- role: typeof info.role === "string" ? info.role : undefined,
3623
- time: isRecord(info.time) ? {
3624
- created: typeof info.time.created === "number" ? info.time.created : undefined
3625
- } : undefined,
3626
- error: info.error,
3627
- finish: typeof info.finish === "string" ? info.finish : typeof info.finish_reason === "string" ? info.finish_reason : typeof info.finishReason === "string" ? info.finishReason : undefined
3628
- } : undefined,
3629
- parts
3630
- };
3631
- }
3632
- function getCreatedTime(message) {
3633
- return message.info?.time?.created ?? 0;
3634
- }
3635
- function getTextParts(message) {
3636
- if (!Array.isArray(message.parts))
3637
- return [];
3638
- return message.parts.filter((part) => isRecord(part)).map((part) => ({
3639
- type: typeof part.type === "string" ? part.type : undefined,
3640
- text: typeof part.text === "string" ? part.text : undefined
3641
- })).filter((part) => part.type === "text" && Boolean(part.text));
3642
- }
3643
- function getLatestAssistantMessage(messages) {
3644
- if (!Array.isArray(messages) || messages.length === 0)
3645
- return null;
3646
- return messages.map(asSessionMessage).filter((message) => message !== null).filter((message) => message.info?.role === "assistant").sort((a, b) => getCreatedTime(b) - getCreatedTime(a))[0] ?? null;
3647
- }
3648
- function extractLatestAssistantText(messages) {
3649
- const latest = getLatestAssistantMessage(messages);
3650
- if (!latest)
3651
- return null;
3652
- return getTextParts(latest).map((part) => part.text).join(`
3653
- `) || null;
3654
- }
3655
- function extractLatestAssistantFailure(messages) {
3656
- const latest = getLatestAssistantMessage(messages);
3657
- if (!latest || latest.info?.error === undefined || latest.info.error === null)
3658
- return null;
3659
- return {
3660
- error: latest.info.error,
3661
- finish: latest.info.finish ?? null
3662
- };
3663
- }
3664
- function hasLengthCappedOutput(value) {
3665
- if (Array.isArray(value))
3666
- return value.some((item) => hasLengthCappedOutput(item));
3667
- if (!isRecord(value))
3668
- return false;
3669
- if (value.length_capped === true || value.lengthCapped === true)
3670
- return true;
3671
- const finishReason = value.finish_reason ?? value.finishReason ?? value.finish ?? (value.type === "step-finish" ? value.reason : undefined) ?? value.stopReason;
3672
- if (typeof finishReason === "string") {
3673
- const normalized = finishReason.toLowerCase();
3674
- if (normalized === "length" || normalized === "max_tokens" || normalized === "max_output_tokens") {
3675
- return true;
3676
- }
3677
- }
3678
- return Object.values(value).some((item) => hasLengthCappedOutput(item));
3679
- }
3680
-
3681
3705
  // ../plugin/src/shared/child-session-teardown.ts
3682
3706
  async function teardownChildSession(args) {
3683
3707
  const { client, sessionId, sessionDirectory, promptSettled, context, log } = args;
@@ -6526,13 +6550,13 @@ async function runHiddenSingleShotPrompt(args) {
6526
6550
  throw new Error(`${args.callContext} returned length-capped output`);
6527
6551
  }
6528
6552
  const text = completion.text;
6529
- if (!text)
6553
+ if (!text && !args.allowEmpty)
6530
6554
  throw new Error(`${args.callContext} returned no output`);
6531
- return args.parse(text);
6555
+ return args.parse(text ?? "", completion);
6532
6556
  }
6533
6557
  });
6534
6558
  promptSettled = true;
6535
- return { validated: run.validated, completion: run.output };
6559
+ return { validated: run.validated, completion: run.output, childSessionId: handle.id };
6536
6560
  } finally {
6537
6561
  await args.executor.close(handle, {
6538
6562
  promptSettled,
@@ -7248,8 +7272,11 @@ async function classifyOneChunk(args, chunk, anchors, sliceMs, signal) {
7248
7272
  anchors
7249
7273
  });
7250
7274
  if (moduleRoute) {
7251
- const run = await runClassifyThroughModule(args, chunk, anchors, signal);
7252
- recordInvocation(args, startedAt, { status: "completed" });
7275
+ const { accounting, ...run } = await runClassifyThroughModule(args, chunk, anchors, signal);
7276
+ recordInvocation(args, startedAt, {
7277
+ status: "completed",
7278
+ moduleAccounting: accounting
7279
+ });
7253
7280
  return run;
7254
7281
  }
7255
7282
  const executor = resolveHiddenCompletionExecutor(args.hiddenCompletionExecutor, args.client, args.db, args.sessionDirectory, "classify-memories");
@@ -7351,7 +7378,7 @@ async function runClassifyThroughModule(args, chunk, anchors, signal) {
7351
7378
  task: "classify",
7352
7379
  command_id: `classify:${args.moduleCommandId ?? Date.now()}:${createHash5("sha256").update(chunk.map((candidate) => candidate.id).join(",")).digest("hex").slice(0, 24)}`,
7353
7380
  authority_generation: args.moduleAuthorityGeneration,
7354
- ...resolvedModelChain.length > 0 ? { model_chain: resolvedModelChain } : {},
7381
+ model_chain: resolvedModelChain,
7355
7382
  payload: {
7356
7383
  prompt_body: prompt,
7357
7384
  items: chunk.map((candidate) => ({
@@ -7372,6 +7399,7 @@ async function runClassifyThroughModule(args, chunk, anchors, signal) {
7372
7399
  if (result.truncated === true) {
7373
7400
  throw new Error("classify returned length-capped output");
7374
7401
  }
7402
+ const accounting = moduleClassifyAccounting(result);
7375
7403
  const parsed = validateClassifyManifest(manifestText, new Set(chunk.map((candidate) => candidate.id)));
7376
7404
  const rows = parsed.map((entry) => {
7377
7405
  const candidate = chunk.find((item) => item.id === entry.id);
@@ -7444,7 +7472,39 @@ async function runClassifyThroughModule(args, chunk, anchors, signal) {
7444
7472
  throw new Error(`module accepted unknown memory ${moduleId}`);
7445
7473
  return candidate.contextMemory.id;
7446
7474
  });
7447
- return { classified: acceptedContextIds.length, changed: acceptedContextIds.length };
7475
+ return {
7476
+ classified: acceptedContextIds.length,
7477
+ changed: acceptedContextIds.length,
7478
+ accounting
7479
+ };
7480
+ }
7481
+ function nonNegativeCount(value) {
7482
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
7483
+ }
7484
+ function moduleClassifyAccounting(result) {
7485
+ const accounting = {};
7486
+ const usage = result.usage;
7487
+ if (usage && typeof usage === "object") {
7488
+ const record = usage;
7489
+ accounting.tokens = {
7490
+ input: nonNegativeCount(record.input),
7491
+ output: nonNegativeCount(record.output),
7492
+ cacheRead: nonNegativeCount(record.cache_read),
7493
+ cacheWrite: nonNegativeCount(record.cache_write)
7494
+ };
7495
+ }
7496
+ const diagnostics = result.diagnostics;
7497
+ const model = diagnostics && typeof diagnostics === "object" ? diagnostics.model : undefined;
7498
+ if (typeof model === "string") {
7499
+ const parsed = parseProviderModel(model);
7500
+ if (parsed) {
7501
+ accounting.providerId = parsed.providerID;
7502
+ accounting.modelId = parsed.modelID;
7503
+ } else if (model.trim()) {
7504
+ accounting.modelId = model.trim();
7505
+ }
7506
+ }
7507
+ return accounting;
7448
7508
  }
7449
7509
  function applyClassifications(args, chunk, manifestText) {
7450
7510
  const byId = new Map(chunk.map((m) => [m.id, m]));
@@ -7489,6 +7549,11 @@ function recordInvocation(args, startedAt, params) {
7489
7549
  providerId: params.completion.providerId,
7490
7550
  modelId: params.completion.modelId
7491
7551
  } : {},
7552
+ ...params.moduleAccounting ? {
7553
+ tokens: params.moduleAccounting.tokens,
7554
+ providerId: params.moduleAccounting.providerId,
7555
+ modelId: params.moduleAccounting.modelId
7556
+ } : {},
7492
7557
  error: params.error
7493
7558
  });
7494
7559
  }
@@ -9721,8 +9786,36 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
9721
9786
  let promptSettled = false;
9722
9787
  const startedAt = Date.now();
9723
9788
  try {
9789
+ const prompt = buildMapMemoriesPrompt(args.projectIdentity, batch);
9790
+ if (args.hiddenCompletionExecutor) {
9791
+ const run = await runHiddenSingleShotPrompt({
9792
+ executor: args.hiddenCompletionExecutor,
9793
+ parentSessionId: args.parentSessionId,
9794
+ sessionDirectory: args.sessionDirectory,
9795
+ agent: DREAMER_MEMORY_MAPPER_AGENT,
9796
+ system: MAP_MEMORIES_SYSTEM_PROMPT,
9797
+ prompt,
9798
+ title: "magic-context-dream-map-memories",
9799
+ callContext: "dreamer:map-memories",
9800
+ model: args.model,
9801
+ fallbackModels: args.fallbackModels,
9802
+ timeoutMs: sliceMs,
9803
+ signal,
9804
+ parse: (text) => validateMapMemoriesManifest(text, new Set(batch.map((memory) => memory.id)))
9805
+ });
9806
+ recordInvocation2(args, startedAt, {
9807
+ status: "completed",
9808
+ messages: run.completion.messages ?? []
9809
+ });
9810
+ const outcome = await applyParsedBatchMappings(args, batch, run.validated);
9811
+ const returnedIds = new Set(run.validated.map((entry) => entry.id));
9812
+ return { ...outcome, requeue: batch.filter((memory) => !returnedIds.has(memory.id)) };
9813
+ }
9814
+ const client = args.client;
9815
+ if (!client)
9816
+ throw new Error("map-memories requires a client or hidden completion executor");
9724
9817
  const createResponse = await createChildSessionWithFence({
9725
- client: args.client,
9818
+ client,
9726
9819
  db: args.db,
9727
9820
  parentSessionId: args.parentSessionId,
9728
9821
  title: "magic-context-dream-map-memories",
@@ -9734,8 +9827,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
9734
9827
  agentSessionId = typeof created?.id === "string" ? created.id : null;
9735
9828
  if (!agentSessionId)
9736
9829
  throw new Error("Could not create map-memories session.");
9737
- const prompt = buildMapMemoriesPrompt(args.projectIdentity, batch);
9738
- const run = await promptSyncWithValidatedOutputRetry(args.client, {
9830
+ const run = await promptSyncWithValidatedOutputRetry(client, {
9739
9831
  path: { id: agentSessionId },
9740
9832
  query: { directory: args.sessionDirectory },
9741
9833
  body: {
@@ -9750,7 +9842,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
9750
9842
  fallbackModels: args.fallbackModels,
9751
9843
  callContext: "dreamer:map-memories",
9752
9844
  fetchOutput: async () => {
9753
- const messagesResponse = await args.client.session.messages({
9845
+ const messagesResponse = await client.session.messages({
9754
9846
  path: { id: agentSessionId },
9755
9847
  query: { directory: args.sessionDirectory, limit: 100 }
9756
9848
  });
@@ -9793,15 +9885,16 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
9793
9885
  }
9794
9886
  };
9795
9887
  } finally {
9796
- await teardownChildSession({
9797
- client: args.client,
9798
- sessionId: agentSessionId,
9799
- sessionDirectory: args.sessionDirectory,
9800
- promptSettled,
9801
- privacySensitive: true,
9802
- context: "[dreamer] map-memories",
9803
- log
9804
- });
9888
+ if (agentSessionId && args.client)
9889
+ await teardownChildSession({
9890
+ client: args.client,
9891
+ sessionId: agentSessionId,
9892
+ sessionDirectory: args.sessionDirectory,
9893
+ promptSettled,
9894
+ privacySensitive: true,
9895
+ context: "[dreamer] map-memories",
9896
+ log
9897
+ });
9805
9898
  }
9806
9899
  }
9807
9900
  async function applyParsedBatchMappings(args, batch, parsed) {
@@ -10394,8 +10487,41 @@ async function refreshOnePrimer(args, primer, sliceMs, signal) {
10394
10487
  let promptSettled = false;
10395
10488
  const startedAt = Date.now();
10396
10489
  try {
10490
+ const prompt = buildInvestigationPrompt(primer, seed.kind, seed.orientation, seed.prePost);
10491
+ if (args.hiddenCompletionExecutor) {
10492
+ const run = await runHiddenSingleShotPrompt({
10493
+ executor: args.hiddenCompletionExecutor,
10494
+ parentSessionId: args.parentSessionId,
10495
+ sessionDirectory: args.sessionDirectory,
10496
+ agent: DREAMER_PRIMER_INVESTIGATOR_AGENT,
10497
+ system: PRIMER_INVESTIGATOR_SYSTEM_PROMPT,
10498
+ prompt,
10499
+ title: "magic-context-dream-refresh-primers",
10500
+ callContext: "dreamer:refresh-primers",
10501
+ model: args.model,
10502
+ fallbackModels: args.fallbackModels,
10503
+ language: args.language,
10504
+ timeoutMs: sliceMs,
10505
+ signal,
10506
+ parse: (text) => parseAnswer([{ info: { role: "assistant" }, parts: [{ type: "text", text }] }], primer.answer)
10507
+ });
10508
+ recordInvocation3(args, startedAt, {
10509
+ status: "completed",
10510
+ messages: run.completion.messages ?? []
10511
+ });
10512
+ const answer = run.validated.trim();
10513
+ if (!answer || investigationToolCallCount(run.completion.messages ?? []) === 0)
10514
+ return false;
10515
+ runLeaseGuardedWrite(args.db, args.holderId, args.leaseKey, () => {
10516
+ updatePrimerAnswer(args.db, primer.id, answer);
10517
+ });
10518
+ return true;
10519
+ }
10520
+ const client = args.client;
10521
+ if (!client)
10522
+ throw new Error("refresh-primers requires a client or hidden completion executor");
10397
10523
  const createResponse = await createChildSessionWithFence({
10398
- client: args.client,
10524
+ client,
10399
10525
  db: args.db,
10400
10526
  parentSessionId: args.parentSessionId,
10401
10527
  title: "magic-context-dream-refresh-primers",
@@ -10407,8 +10533,7 @@ async function refreshOnePrimer(args, primer, sliceMs, signal) {
10407
10533
  agentSessionId = typeof created?.id === "string" ? created.id : null;
10408
10534
  if (!agentSessionId)
10409
10535
  throw new Error("Could not create primer refresh session.");
10410
- const prompt = buildInvestigationPrompt(primer, seed.kind, seed.orientation, seed.prePost);
10411
- const run = await promptSyncWithValidatedOutputRetry(args.client, {
10536
+ const run = await promptSyncWithValidatedOutputRetry(client, {
10412
10537
  path: { id: agentSessionId },
10413
10538
  query: { directory: args.sessionDirectory },
10414
10539
  body: {
@@ -10423,7 +10548,7 @@ async function refreshOnePrimer(args, primer, sliceMs, signal) {
10423
10548
  fallbackModels: args.fallbackModels,
10424
10549
  callContext: "dreamer:refresh-primers",
10425
10550
  fetchOutput: async () => {
10426
- const messagesResponse = await args.client.session.messages({
10551
+ const messagesResponse = await client.session.messages({
10427
10552
  path: { id: agentSessionId },
10428
10553
  query: { directory: args.sessionDirectory, limit: 100 }
10429
10554
  });
@@ -10452,15 +10577,16 @@ async function refreshOnePrimer(args, primer, sliceMs, signal) {
10452
10577
  recordInvocation3(args, startedAt, { status: failedInvocationStatus(error), error });
10453
10578
  throw error;
10454
10579
  } finally {
10455
- await teardownChildSession({
10456
- client: args.client,
10457
- sessionId: agentSessionId,
10458
- sessionDirectory: args.sessionDirectory,
10459
- promptSettled,
10460
- privacySensitive: true,
10461
- context: "[dreamer] refresh-primers",
10462
- log
10463
- });
10580
+ if (agentSessionId && args.client)
10581
+ await teardownChildSession({
10582
+ client: args.client,
10583
+ sessionId: agentSessionId,
10584
+ sessionDirectory: args.sessionDirectory,
10585
+ promptSettled,
10586
+ privacySensitive: true,
10587
+ context: "[dreamer] refresh-primers",
10588
+ log
10589
+ });
10464
10590
  }
10465
10591
  }
10466
10592
  function originSessionIdForPrimer(args, primer) {
@@ -11362,8 +11488,40 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
11362
11488
  let promptSettled = false;
11363
11489
  const startedAt = Date.now();
11364
11490
  try {
11491
+ const prompt = buildVerifyPrompt(args.projectIdentity, batch);
11492
+ if (args.hiddenCompletionExecutor) {
11493
+ const run = await runHiddenSingleShotPrompt({
11494
+ executor: args.hiddenCompletionExecutor,
11495
+ parentSessionId: args.parentSessionId,
11496
+ sessionDirectory: args.sessionDirectory,
11497
+ agent: DREAMER_MEMORY_MAPPER_AGENT,
11498
+ system: VERIFY_SYSTEM_PROMPT,
11499
+ prompt,
11500
+ title: "magic-context-dream-verify",
11501
+ callContext: "dreamer:verify",
11502
+ model: args.model,
11503
+ fallbackModels: args.fallbackModels,
11504
+ language: args.language,
11505
+ timeoutMs: sliceMs,
11506
+ signal,
11507
+ parse: (text) => {
11508
+ const providerFailure = providerOutputFailureFromInvalidManifest([], text);
11509
+ if (providerFailure)
11510
+ throw providerFailure;
11511
+ return validateVerifyManifest(text, new Set(batch.map((memory) => memory.id)));
11512
+ }
11513
+ });
11514
+ recordInvocation4(args, startedAt, {
11515
+ status: "completed",
11516
+ messages: run.completion.messages ?? []
11517
+ });
11518
+ return applyParsedVerifyManifest(args, batch, run.validated);
11519
+ }
11520
+ const client = args.client;
11521
+ if (!client)
11522
+ throw new Error("verify requires a client or hidden completion executor");
11365
11523
  const createResponse = await createChildSessionWithFence({
11366
- client: args.client,
11524
+ client,
11367
11525
  db: args.db,
11368
11526
  parentSessionId: args.parentSessionId,
11369
11527
  title: "magic-context-dream-verify",
@@ -11375,8 +11533,7 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
11375
11533
  agentSessionId = typeof created?.id === "string" ? created.id : null;
11376
11534
  if (!agentSessionId)
11377
11535
  throw new Error("Could not create verify session.");
11378
- const prompt = buildVerifyPrompt(args.projectIdentity, batch);
11379
- const run = await promptSyncWithValidatedOutputRetry(args.client, {
11536
+ const run = await promptSyncWithValidatedOutputRetry(client, {
11380
11537
  path: { id: agentSessionId },
11381
11538
  query: { directory: args.sessionDirectory },
11382
11539
  body: {
@@ -11391,7 +11548,7 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
11391
11548
  fallbackModels: args.fallbackModels,
11392
11549
  callContext: "dreamer:verify",
11393
11550
  fetchOutput: async () => {
11394
- const messagesResponse = await args.client.session.messages({
11551
+ const messagesResponse = await client.session.messages({
11395
11552
  path: { id: agentSessionId },
11396
11553
  query: { directory: args.sessionDirectory, limit: 100 }
11397
11554
  });
@@ -11432,15 +11589,16 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
11432
11589
  providerFailure
11433
11590
  };
11434
11591
  } finally {
11435
- await teardownChildSession({
11436
- client: args.client,
11437
- sessionId: agentSessionId,
11438
- sessionDirectory: args.sessionDirectory,
11439
- promptSettled,
11440
- privacySensitive: true,
11441
- context: "[dreamer] verify",
11442
- log
11443
- });
11592
+ if (agentSessionId && args.client)
11593
+ await teardownChildSession({
11594
+ client: args.client,
11595
+ sessionId: agentSessionId,
11596
+ sessionDirectory: args.sessionDirectory,
11597
+ promptSettled,
11598
+ privacySensitive: true,
11599
+ context: "[dreamer] verify",
11600
+ log
11601
+ });
11444
11602
  }
11445
11603
  }
11446
11604
  async function applyParsedVerifyManifest(args, batch, parsed) {
@@ -11608,6 +11766,8 @@ async function applyParsedVerifyManifest(args, batch, parsed) {
11608
11766
  async function normalizeFiles(args, rawFiles) {
11609
11767
  if (rawFiles.length === 0)
11610
11768
  return [];
11769
+ if (args.normalizeFiles)
11770
+ return args.normalizeFiles(rawFiles);
11611
11771
  const normalized = await normalizeVerificationFiles({
11612
11772
  cwd: args.sessionDirectory,
11613
11773
  files: rawFiles
@@ -11941,7 +12101,8 @@ function createDreamTaskExecutor(deps) {
11941
12101
  if (config.task === "map-memories") {
11942
12102
  const result = await mapMemories({
11943
12103
  db,
11944
- client: requireDreamClient(deps.client),
12104
+ client: deps.client,
12105
+ hiddenCompletionExecutor: deps.hiddenCompletionExecutor,
11945
12106
  projectIdentity,
11946
12107
  parentSessionId: parent,
11947
12108
  sessionDirectory: deps.sessionDirectory,
@@ -11978,7 +12139,8 @@ function createDreamTaskExecutor(deps) {
11978
12139
  const memoryBefore = getMemoryCountsByStatus(db, projectIdentity);
11979
12140
  const result = await runVerify({
11980
12141
  db,
11981
- client: requireDreamClient(deps.client),
12142
+ client: deps.client,
12143
+ hiddenCompletionExecutor: deps.hiddenCompletionExecutor,
11982
12144
  projectIdentity,
11983
12145
  parentSessionId: parent,
11984
12146
  sessionDirectory: deps.sessionDirectory,
@@ -12079,7 +12241,8 @@ function createDreamTaskExecutor(deps) {
12079
12241
  if (config.task === "refresh-primers") {
12080
12242
  const result = await refreshPrimers({
12081
12243
  db,
12082
- client: requireDreamClient(deps.client),
12244
+ client: deps.client,
12245
+ hiddenCompletionExecutor: deps.hiddenCompletionExecutor,
12083
12246
  projectIdentity,
12084
12247
  parentSessionId: parent,
12085
12248
  sessionDirectory: deps.sessionDirectory,
@@ -12347,24 +12510,45 @@ async function runRetrospectiveTask(config, ctx, helpers) {
12347
12510
  abortController.abort();
12348
12511
  }, ctx.leaseAcquisition);
12349
12512
  let childSessionId = null;
12513
+ let hiddenHandle = null;
12350
12514
  let promptSettled = false;
12351
12515
  try {
12352
- const createResponse = await createChildSessionWithFence({
12353
- client: requireDreamClient(deps.client),
12354
- db,
12355
- parentSessionId: parent ?? undefined,
12356
- title: "magic-context-dream-retrospective",
12357
- directory: deps.sessionDirectory
12358
- });
12359
- const created = normalizeSDKResponse(createResponse, null, { preferResponseOnMissingData: true });
12360
- childSessionId = typeof created?.id === "string" ? created.id : null;
12361
- if (!childSessionId)
12362
- throw new Error("Retrospective could not create its child session.");
12516
+ if (deps.hiddenCompletionExecutor) {
12517
+ hiddenHandle = await deps.hiddenCompletionExecutor.open({
12518
+ parentSessionId: parent ?? undefined,
12519
+ agent: DREAMER_RETROSPECTIVE_AGENT,
12520
+ kind: "dreamer-task",
12521
+ system: FRICTION_GATE_SYSTEM_PROMPT,
12522
+ model: config.model,
12523
+ configuredModels: [
12524
+ ...config.model ? [config.model] : [],
12525
+ ...config.fallbackModels ?? []
12526
+ ],
12527
+ timeoutMs: Math.max(1, deadline - Date.now()),
12528
+ title: "magic-context-dream-retrospective",
12529
+ directory: deps.sessionDirectory
12530
+ });
12531
+ childSessionId = hiddenHandle.id;
12532
+ } else {
12533
+ const createResponse = await createChildSessionWithFence({
12534
+ client: requireDreamClient(deps.client),
12535
+ db,
12536
+ parentSessionId: parent ?? undefined,
12537
+ title: "magic-context-dream-retrospective",
12538
+ directory: deps.sessionDirectory
12539
+ });
12540
+ const created = normalizeSDKResponse(createResponse, null, { preferResponseOnMissingData: true });
12541
+ childSessionId = typeof created?.id === "string" ? created.id : null;
12542
+ if (!childSessionId)
12543
+ throw new Error("Retrospective could not create its child session.");
12544
+ }
12363
12545
  const sessionId = childSessionId;
12546
+ if (!sessionId)
12547
+ throw new Error("Retrospective could not create its child session.");
12364
12548
  const runChildTurn = async (system, userText) => {
12365
12549
  const remainingMs = Math.max(0, deadline - Date.now());
12366
12550
  promptSettled = false;
12367
- const run = await promptSyncWithValidatedOutputRetry(requireDreamClient(deps.client), {
12551
+ const run = await promptSyncWithValidatedOutputRetry(deps.hiddenCompletionExecutor ? undefined : requireDreamClient(deps.client), {
12368
12552
  path: { id: sessionId },
12369
12553
  query: { directory: deps.sessionDirectory },
12370
12554
  body: {
@@ -12378,7 +12562,13 @@ async function runRetrospectiveTask(config, ctx, helpers) {
12378
12562
  signal: abortController.signal,
12379
12563
  fallbackModels: config.fallbackModels,
12380
12564
  callContext: "dreamer:retrospective",
12565
+ ...hiddenHandle && deps.hiddenCompletionExecutor ? {
12566
+ transport: Object.assign((request) => deps.hiddenCompletionExecutor?.attempt(hiddenHandle, request) ?? Promise.reject(new Error("Hidden transport unavailable")), { childSessionId: hiddenHandle.childSessionId })
12567
+ } : {},
12381
12568
  fetchOutput: async () => {
12569
+ if (hiddenHandle && deps.hiddenCompletionExecutor) {
12570
+ return deps.hiddenCompletionExecutor.collect(hiddenHandle, 50);
12571
+ }
12382
12572
  const messagesResponse = await requireDreamClient(deps.client).session.messages({
12383
12573
  path: { id: sessionId },
12384
12574
  query: { directory: deps.sessionDirectory, limit: 50 }
@@ -12388,14 +12578,15 @@ async function runRetrospectiveTask(config, ctx, helpers) {
12388
12578
  });
12389
12579
  },
12390
12580
  validateOutput: (outputMessages) => {
12391
- const text = extractLatestAssistantText(outputMessages);
12581
+ const text = hiddenHandle ? outputMessages.text : extractLatestAssistantText(outputMessages);
12392
12582
  if (!text)
12393
12583
  throw new Error("Retrospective child returned no output.");
12394
12584
  return text;
12395
12585
  }
12396
12586
  });
12397
12587
  promptSettled = true;
12398
- return run;
12588
+ const output = hiddenHandle ? run.output.messages ?? [] : run.output;
12589
+ return { ...run, output };
12399
12590
  };
12400
12591
  const finish = (run, watermark) => {
12401
12592
  if (parent && run) {
@@ -12525,15 +12716,23 @@ async function runRetrospectiveTask(config, ctx, helpers) {
12525
12716
  });
12526
12717
  } finally {
12527
12718
  heartbeat.stop();
12528
- await teardownChildSession({
12529
- client: requireDreamClient(deps.client),
12530
- sessionId: childSessionId,
12531
- sessionDirectory: deps.sessionDirectory,
12532
- promptSettled,
12533
- privacySensitive: true,
12534
- context: "[dreamer] retrospective",
12535
- log
12536
- });
12719
+ if (hiddenHandle && deps.hiddenCompletionExecutor) {
12720
+ await deps.hiddenCompletionExecutor.close(hiddenHandle, {
12721
+ promptSettled,
12722
+ privacySensitive: true,
12723
+ context: "[dreamer] retrospective",
12724
+ log
12725
+ });
12726
+ } else
12727
+ await teardownChildSession({
12728
+ client: requireDreamClient(deps.client),
12729
+ sessionId: childSessionId,
12730
+ sessionDirectory: deps.sessionDirectory,
12731
+ promptSettled,
12732
+ privacySensitive: true,
12733
+ context: "[dreamer] retrospective",
12734
+ log
12735
+ });
12537
12736
  }
12538
12737
  }
12539
12738
  async function runAgenticTask(config, ctx, helpers) {
@@ -12607,72 +12806,107 @@ async function runAgenticTask(config, ctx, helpers) {
12607
12806
  docsCurrentTokens: maintainDocsSnapshot ? Math.ceil([...maintainDocsSnapshot.values()].join("").length / 3.5) : 0,
12608
12807
  curate: curateMemories && curateCategory ? { category: curateCategory, memories: curateMemories } : undefined
12609
12808
  });
12610
- const createResponse = await createChildSessionWithFence({
12611
- client: requireDreamClient(deps.client),
12612
- db,
12613
- parentSessionId: parent ?? undefined,
12614
- title: `magic-context-dream-${task}`,
12615
- directory: docsDir
12616
- });
12617
- const created = normalizeSDKResponse(createResponse, null, {
12618
- preferResponseOnMissingData: true
12619
- });
12620
- childSessionId = typeof created?.id === "string" ? created.id : null;
12621
- if (!childSessionId)
12622
- throw new Error("Dreamer could not create its child session.");
12623
- const sessionId = childSessionId;
12624
- const remainingMs = Math.max(0, deadline - Date.now());
12625
- const run = await promptSyncWithValidatedOutputRetry(requireDreamClient(deps.client), {
12626
- path: { id: sessionId },
12627
- query: { directory: docsDir },
12628
- body: {
12809
+ let run;
12810
+ if (deps.hiddenCompletionExecutor) {
12811
+ const hidden = await runHiddenSingleShotPrompt({
12812
+ executor: deps.hiddenCompletionExecutor,
12813
+ parentSessionId: parent ?? undefined,
12814
+ sessionDirectory: docsDir,
12629
12815
  agent: task === "maintain-docs" ? DREAMER_DOCS_AGENT : DREAMER_AGENT,
12630
- system: task === "maintain-docs" ? MAINTAIN_DOCS_SYSTEM_PROMPT : withContentLanguageDirective(CURATE_SYSTEM_PROMPT, config.language ?? deps.language),
12631
- ...modelBodyField(config.model),
12632
- parts: [{ type: "text", text: taskPrompt, synthetic: true }]
12633
- }
12634
- }, {
12635
- timeoutMs: Math.min(remainingMs, config.timeoutMinutes * 60 * 1000),
12636
- signal: abortController.signal,
12637
- fallbackModels: config.fallbackModels,
12638
- callContext: `dreamer:${task}`,
12639
- fetchOutput: async () => {
12640
- const messagesResponse = await requireDreamClient(deps.client).session.messages({
12641
- path: { id: sessionId },
12642
- query: {
12643
- directory: docsDir,
12644
- ...task === "curate" ? {} : { limit: 50 }
12816
+ system: task === "maintain-docs" ? MAINTAIN_DOCS_SYSTEM_PROMPT : CURATE_SYSTEM_PROMPT,
12817
+ prompt: taskPrompt,
12818
+ title: `magic-context-dream-${task}`,
12819
+ callContext: `dreamer:${task}`,
12820
+ allowEmpty: task === "curate",
12821
+ model: config.model,
12822
+ fallbackModels: config.fallbackModels,
12823
+ language: task === "curate" ? config.language ?? deps.language : undefined,
12824
+ timeoutMs: Math.min(Math.max(0, deadline - Date.now()), config.timeoutMinutes * 60 * 1000),
12825
+ signal: abortController.signal,
12826
+ parse: (text, completion) => {
12827
+ if (task !== "curate")
12828
+ return text;
12829
+ const memoryOperations = inspectCurateMemoryOperations(completion.messages);
12830
+ if (text)
12831
+ validateCurateAssistantText(text);
12832
+ if (memoryOperations.totalCalls > 0 && memoryOperations.completedActions.length === 0)
12833
+ throw new Error("Curate returned no completed ctx_memory tool result.");
12834
+ if (!text && memoryOperations.completedActions.length === 0)
12835
+ throw new Error("Dreamer returned no assistant output.");
12836
+ return { text: text || null, memoryOperations };
12837
+ }
12838
+ });
12839
+ childSessionId = hidden.childSessionId;
12840
+ run = { output: hidden.completion.messages ?? [], validated: hidden.validated };
12841
+ promptSettled = true;
12842
+ } else {
12843
+ const createResponse = await createChildSessionWithFence({
12844
+ client: requireDreamClient(deps.client),
12845
+ db,
12846
+ parentSessionId: parent ?? undefined,
12847
+ title: `magic-context-dream-${task}`,
12848
+ directory: docsDir
12849
+ });
12850
+ const created = normalizeSDKResponse(createResponse, null, {
12851
+ preferResponseOnMissingData: true
12852
+ });
12853
+ childSessionId = typeof created?.id === "string" ? created.id : null;
12854
+ if (!childSessionId)
12855
+ throw new Error("Dreamer could not create its child session.");
12856
+ const sessionId = childSessionId;
12857
+ const remainingMs = Math.max(0, deadline - Date.now());
12858
+ run = await promptSyncWithValidatedOutputRetry(requireDreamClient(deps.client), {
12859
+ path: { id: sessionId },
12860
+ query: { directory: docsDir },
12861
+ body: {
12862
+ agent: task === "maintain-docs" ? DREAMER_DOCS_AGENT : DREAMER_AGENT,
12863
+ system: task === "maintain-docs" ? MAINTAIN_DOCS_SYSTEM_PROMPT : withContentLanguageDirective(CURATE_SYSTEM_PROMPT, config.language ?? deps.language),
12864
+ ...modelBodyField(config.model),
12865
+ parts: [{ type: "text", text: taskPrompt, synthetic: true }]
12866
+ }
12867
+ }, {
12868
+ timeoutMs: Math.min(remainingMs, config.timeoutMinutes * 60 * 1000),
12869
+ signal: abortController.signal,
12870
+ fallbackModels: config.fallbackModels,
12871
+ callContext: `dreamer:${task}`,
12872
+ fetchOutput: async () => {
12873
+ const messagesResponse = await requireDreamClient(deps.client).session.messages({
12874
+ path: { id: sessionId },
12875
+ query: {
12876
+ directory: docsDir,
12877
+ ...task === "curate" ? {} : { limit: 50 }
12878
+ }
12879
+ });
12880
+ return normalizeSDKResponse(messagesResponse, [], {
12881
+ preferResponseOnMissingData: true
12882
+ });
12883
+ },
12884
+ validateOutput: (messages) => {
12885
+ const text = extractLatestAssistantText(messages);
12886
+ if (task !== "curate") {
12887
+ if (!text)
12888
+ throw new Error("Dreamer returned no assistant output.");
12889
+ return text;
12890
+ }
12891
+ const memoryOperations = inspectCurateMemoryOperations(messages);
12892
+ if (text)
12893
+ validateCurateAssistantText(text);
12894
+ if (memoryOperations.completedActions.length > 0) {
12895
+ return { text, memoryOperations };
12645
12896
  }
12646
- });
12647
- return normalizeSDKResponse(messagesResponse, [], {
12648
- preferResponseOnMissingData: true
12649
- });
12650
- },
12651
- validateOutput: (messages) => {
12652
- const text = extractLatestAssistantText(messages);
12653
- if (task !== "curate") {
12654
12897
  if (!text)
12655
12898
  throw new Error("Dreamer returned no assistant output.");
12656
- return text;
12657
- }
12658
- const memoryOperations = inspectCurateMemoryOperations(messages);
12659
- if (text)
12660
- validateCurateAssistantText(text);
12661
- if (memoryOperations.completedActions.length > 0) {
12899
+ if (memoryOperations.totalCalls > 0) {
12900
+ throw new Error("Curate returned no completed ctx_memory tool result.");
12901
+ }
12662
12902
  return { text, memoryOperations };
12663
12903
  }
12664
- if (!text)
12665
- throw new Error("Dreamer returned no assistant output.");
12666
- if (memoryOperations.totalCalls > 0) {
12667
- throw new Error("Curate returned no completed ctx_memory tool result.");
12668
- }
12669
- return { text, memoryOperations };
12670
- }
12671
- });
12672
- promptSettled = true;
12904
+ });
12905
+ promptSettled = true;
12906
+ }
12673
12907
  if (leaseLost)
12674
12908
  throw new Error("Dream lease lost during task");
12675
- const curateRefused = task === "curate" ? takeCurateSafetyRefusalCount(sessionId) : 0;
12909
+ const curateRefused = task === "curate" ? takeCurateSafetyRefusalCount(childSessionId ?? "") : 0;
12676
12910
  if (curateRefused > 0) {
12677
12911
  helpers.reportProgress(curateRefused, curateRefused);
12678
12912
  log(`[dreamer] curate safety summary: refused=${curateRefused}`);
@@ -12742,15 +12976,16 @@ async function runAgenticTask(config, ctx, helpers) {
12742
12976
  heartbeat.stop();
12743
12977
  if (childSessionId)
12744
12978
  takeCurateSafetyRefusalCount(childSessionId);
12745
- await teardownChildSession({
12746
- client: requireDreamClient(deps.client),
12747
- sessionId: childSessionId,
12748
- sessionDirectory: docsDir,
12749
- promptSettled,
12750
- privacySensitive: true,
12751
- context: `[dreamer] ${task}`,
12752
- log
12753
- });
12979
+ if (!deps.hiddenCompletionExecutor)
12980
+ await teardownChildSession({
12981
+ client: requireDreamClient(deps.client),
12982
+ sessionId: childSessionId,
12983
+ sessionDirectory: docsDir,
12984
+ promptSettled,
12985
+ privacySensitive: true,
12986
+ context: `[dreamer] ${task}`,
12987
+ log
12988
+ });
12754
12989
  }
12755
12990
  }
12756
12991
 
@@ -18328,7 +18563,7 @@ function getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThr
18328
18563
  function formatProjectedPostDropPercentage(value) {
18329
18564
  return value === null ? "none" : `${value.toFixed(1)}%`;
18330
18565
  }
18331
- function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPercentage, executeThresholdPercentage, triggerBudget, clearReasoningAge, commitClusterTrigger, preloadedActiveTags, contextLimit, inMemoryTail, taggerFloorOverride, reasoningProjection) {
18566
+ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPercentage, executeThresholdPercentage, triggerBudget, clearReasoningAge, commitClusterTrigger, preloadedActiveTags, contextLimit, inMemoryTail, taggerFloorOverride, reasoningProjection, reclaimRide) {
18332
18567
  if (sessionMeta.compartmentInProgress) {
18333
18568
  sessionLog(sessionId, `compartment trigger: skipped — historian already in progress (usage=${usage.percentage.toFixed(1)}%)`);
18334
18569
  return { shouldFire: false };
@@ -18386,10 +18621,12 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
18386
18621
  const canClearReasoning = reasoningProjection?.canClearReasoning ?? modelAcceptsEmptyContent(reasoningProjection?.providerID);
18387
18622
  const projectedPostDropPercentage = estimateProjectedPostDropPercentage(db, sessionId, usage, preloadedActiveTags ?? getActiveTagsBySession(db, sessionId), clearReasoningAge, sessionMeta.clearedReasoningThroughTag, canClearReasoning);
18388
18623
  const relativePostDropTarget = executeThresholdPercentage * POST_DROP_TARGET_RATIO;
18624
+ const rideLabel = reclaimRide ? reclaimRideLabel(reclaimRide) : "ride=none";
18625
+ const dropsCanLand = reclaimRide !== undefined && hasReclaimRide(reclaimRide);
18389
18626
  const forceMaterializationPercentage = escalationBands(executeThresholdPercentage).forceMaterializationPercentage;
18390
18627
  if (usage.percentage >= forceMaterializationPercentage) {
18391
- if (projectedPostDropPercentage !== null && projectedPostDropPercentage <= relativePostDropTarget) {
18392
- sessionLog(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 the next eligible execute pass`);
18628
+ if (dropsCanLand && projectedPostDropPercentage !== null && projectedPostDropPercentage <= relativePostDropTarget) {
18629
+ sessionLog(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})`);
18393
18630
  return { shouldFire: false };
18394
18631
  }
18395
18632
  sessionLog(sessionId, `compartment trigger: force-firing at ${usage.percentage.toFixed(1)}% (projected post-drop ${formatProjectedPostDropPercentage(projectedPostDropPercentage)})`);
@@ -18449,8 +18686,8 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
18449
18686
  sessionLog(sessionId, `compartment trigger: not firing at ${usage.percentage.toFixed(1)}% — below proactive floor (${proactiveTriggerPercentage}%)`);
18450
18687
  return { shouldFire: false };
18451
18688
  }
18452
- if (projectedPostDropPercentage !== null && projectedPostDropPercentage <= relativePostDropTarget) {
18453
- sessionLog(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 the next eligible execute pass`);
18689
+ if (dropsCanLand && projectedPostDropPercentage !== null && projectedPostDropPercentage <= relativePostDropTarget) {
18690
+ sessionLog(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})`);
18454
18691
  return { shouldFire: false };
18455
18692
  }
18456
18693
  if (!tailInfo.hasProtectedEligibleHead || !tailInfo.isMeaningful) {
@@ -29862,7 +30099,8 @@ function registerPiContextHandler(pi, baseOptions) {
29862
30099
  sessionMeta,
29863
30100
  piUsage,
29864
30101
  minimumPercentage: usagePercentage,
29865
- historianStateSnapshot: historianStateForPass
30102
+ historianStateSnapshot: historianStateForPass,
30103
+ publishedHistoryRide: isCacheBusting
29866
30104
  });
29867
30105
  }
29868
30106
  logTransformTiming(sessionId, "historianScheduling", tHistorianScheduling);
@@ -30502,7 +30740,12 @@ Historian previously failed ${failureCount} time(s), so Magic Context is retryin
30502
30740
  const trigger = checkCompartmentTrigger(db, sessionId, sessionMeta, usage, 0, triggerInputs.executeThresholdPercentage, triggerInputs.triggerBudget, triggerInputs.clearReasoningAge, triggerInputs.commitClusterTrigger, args.activeTags, boundaryContextLimit, () => {
30503
30741
  const messages = provider.readMessages();
30504
30742
  return { messages, absoluteMessageCount: messages.length };
30505
- }, args.taggerFloor, { canClearReasoning: true });
30743
+ }, args.taggerFloor, { canClearReasoning: true }, {
30744
+ hardFold: false,
30745
+ force: usage.percentage >= historianForceMaterializationPercentage && (usage.percentage >= 95 || getEmergencyInputSample(db, sessionId) === 0),
30746
+ explicitFlush: hasPendingMaterialization(sessionId),
30747
+ publishedHistory: args.publishedHistoryRide
30748
+ });
30506
30749
  if (!trigger.shouldFire) {
30507
30750
  sessionLog(sessionId, `historian trigger eval: shouldFire=false (no trigger condition met)`);
30508
30751
  try {
@@ -31747,6 +31990,9 @@ ${result}`;
31747
31990
  });
31748
31991
  }
31749
31992
 
31993
+ // ../plugin/src/features/magic-context/store-generation-rebase.ts
31994
+ var repairCheckedSessions = new WeakMap;
31995
+
31750
31996
  // ../plugin/src/hooks/magic-context/historian-state-file.ts
31751
31997
  import { mkdirSync as mkdirSync5, unlinkSync as unlinkSync2, writeFileSync as writeFileSync7 } from "node:fs";
31752
31998
  function cleanupHistorianStateFile(path) {
@@ -31810,6 +32056,7 @@ async function sendStatusNotification(_client, sessionId, text, params) {
31810
32056
  var inconsistentProducerWindows = new Set;
31811
32057
  var HISTORIAN_ALERT_COOLDOWN_MS2 = 60 * 1000;
31812
32058
  var lastHistorianAlertBySession2 = new Map;
32059
+ var STORED_COMPARTMENT_FAILURE_BACKOFF_MS = 30 * 60 * 1000;
31813
32060
 
31814
32061
  // ../plugin/src/hooks/magic-context/compartment-runner-recomp.ts
31815
32062
  function insertRecompCompartmentRows(db, sessionId, compartments, now) {
@@ -33873,7 +34120,7 @@ function buildStatusView(source, options) {
33873
34120
  // package.json
33874
34121
  var package_default = {
33875
34122
  name: "@cortexkit/pi-magic-context",
33876
- version: "0.43.0",
34123
+ version: "0.43.2",
33877
34124
  type: "module",
33878
34125
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
33879
34126
  main: "dist/index.js",