@cortexkit/opencode-magic-context 0.49.56 → 0.49.57

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 (52) hide show
  1. package/dist/{context-bejy30t5.js → context-a617pcqe.js} +35 -11
  2. package/dist/features/magic-context/mural/render-mural.d.ts +17 -0
  3. package/dist/features/magic-context/mural/render-mural.d.ts.map +1 -1
  4. package/dist/features/magic-context/mural/render-trigger.d.ts +2 -1
  5. package/dist/features/magic-context/mural/render-trigger.d.ts.map +1 -1
  6. package/dist/features/magic-context/mural/resolve-mural.d.ts +8 -2
  7. package/dist/features/magic-context/mural/resolve-mural.d.ts.map +1 -1
  8. package/dist/features/magic-context/storage-historian-runs.d.ts +7 -0
  9. package/dist/features/magic-context/storage-historian-runs.d.ts.map +1 -1
  10. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  11. package/dist/hooks/magic-context/compartment-runner-types.d.ts +9 -0
  12. package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
  13. package/dist/hooks/magic-context/compartment-runner.d.ts +7 -1
  14. package/dist/hooks/magic-context/compartment-runner.d.ts.map +1 -1
  15. package/dist/hooks/magic-context/historian-failure-report.d.ts +112 -0
  16. package/dist/hooks/magic-context/historian-failure-report.d.ts.map +1 -0
  17. package/dist/hooks/magic-context/hook-handlers.d.ts.map +1 -1
  18. package/dist/hooks/magic-context/transform-compartment-phase.d.ts +11 -1
  19. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  20. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  21. package/dist/{index-pxfb7pp8.js → index-0r2jk2na.js} +2 -2
  22. package/dist/{index-12p4j9wa.js → index-1wsb0e8h.js} +1 -1
  23. package/dist/{index-3jeq08jv.js → index-3600gm9z.js} +268 -21
  24. package/dist/{index-wgbp5zch.js → index-bev3zks1.js} +16 -1
  25. package/dist/{index-3wmp1nb7.js → index-pdnan1e3.js} +3 -3
  26. package/dist/{index-ffab4edg.js → index-wpcjxzrm.js} +43 -19
  27. package/dist/{index-5483ntzh.js → index-x8e50d8f.js} +2 -2
  28. package/dist/{index-qfc1kjh4.js → index-zyanqxtc.js} +2 -2
  29. package/dist/index.js +11 -11
  30. package/dist/raw-ordinal-warmup-worker.js +2 -2
  31. package/dist/{recomp-orchestrator-2tsjqbrm.js → recomp-orchestrator-xwsjrqcs.js} +3 -3
  32. package/dist/{render-fgxbcmnh.js → render-22ebrmep.js} +1 -1
  33. package/dist/{search-archive-0mz3p1g1.js → search-archive-bqqf5p7f.js} +2 -2
  34. package/dist/{transform-postprocess-phase-64xtx439.js → transform-postprocess-phase-nejydt3q.js} +3 -3
  35. package/dist/v2/{context-5hhm89jw.js → context-4gxr2xd4.js} +65 -21
  36. package/dist/v2/hooks/context.d.ts.map +1 -1
  37. package/dist/v2/hooks/usage-persist.d.ts +7 -1
  38. package/dist/v2/hooks/usage-persist.d.ts.map +1 -1
  39. package/dist/v2/raw-ordinal-warmup-worker.js +2 -2
  40. package/dist/v2/{recomp-orchestrator-dzdxrgdt.js → recomp-orchestrator-1de5c0zr.js} +2 -2
  41. package/dist/v2/{render-jfa3hj8z.js → render-g44ksejs.js} +1 -1
  42. package/dist/v2/{search-archive-p4s9q7a3.js → search-archive-5ycchnyp.js} +2 -2
  43. package/dist/v2/{server-z6sxv6n3.js → server-dqwx9pdh.js} +268 -21
  44. package/dist/v2/{server-kyfj1090.js → server-r7nj8ga0.js} +1 -1
  45. package/dist/v2/{server-8e5m2gre.js → server-t5c8awdm.js} +2 -2
  46. package/dist/v2/{server-q02z0jq7.js → server-v57wr0r9.js} +16 -1
  47. package/dist/v2/server.js +2 -2
  48. package/dist/v2/{v2-archive-reader-jpdh0ktt.js → v2-archive-reader-tgydjgfy.js} +1 -1
  49. package/dist/v2/{wrapup-orchestrator-5dfj2mcs.js → wrapup-orchestrator-3871zj7c.js} +2 -2
  50. package/dist/{v2-archive-reader-557b5dn3.js → v2-archive-reader-2czwvyc9.js} +1 -1
  51. package/dist/{wrapup-orchestrator-21hgybdk.js → wrapup-orchestrator-m1yzmgq4.js} +4 -4
  52. package/package.json +1 -1
@@ -19,7 +19,7 @@ serveWorkerJobs(async (input, port) => {
19
19
  await main();
20
20
  async function main() {
21
21
  if (input.v2ArchiveReader) {
22
- const { serveV2ArchiveReads } = await import("./v2-archive-reader-jpdh0ktt.js");
22
+ const { serveV2ArchiveReads } = await import("./v2-archive-reader-tgydjgfy.js");
23
23
  await serveV2ArchiveReads(port, openConnections);
24
24
  return;
25
25
  }
@@ -51,7 +51,7 @@ serveWorkerJobs(async (input, port) => {
51
51
  await runMessageFtsRowidMapBackfill(db);
52
52
  reply = { kind: "fts-rowid-backfill" };
53
53
  } else if (input.searchArchive) {
54
- const { renderSearchArchive } = await import("./search-archive-p4s9q7a3.js");
54
+ const { renderSearchArchive } = await import("./search-archive-5ycchnyp.js");
55
55
  const { readRawSessionMessageIdOrdinalsForRangeFromDb } = await import("./read-session-raw-3e482h3c.js");
56
56
  const archive = input.searchArchive;
57
57
  let raw;
@@ -7,14 +7,14 @@ import {
7
7
  setRecompTerminal2,
8
8
  buildRecompDeps2,
9
9
  runManagedRecomp2
10
- } from "./server-z6sxv6n3.js";
10
+ } from "./server-dqwx9pdh.js";
11
11
  import"./server-c8z2grq0.js";
12
12
  import"./server-v817sf79.js";
13
13
  import"./server-ycvqg2s3.js";
14
14
  import"./server-jjvbk92s.js";
15
15
  import"./server-rpmkz5ta.js";
16
16
  import"./server-4dhv7mqz.js";
17
- import"./server-q02z0jq7.js";
17
+ import"./server-v57wr0r9.js";
18
18
  import"./server-4x0xq8a1.js";
19
19
  import"./server-jwydbwcx.js";
20
20
  import"./server-2amn2s73.js";
@@ -3,7 +3,7 @@ import {
3
3
  renderVerboseRangeForTool2,
4
4
  renderItemByTag2
5
5
  } from "./server-avfc9ezb.js";
6
- import"./server-q02z0jq7.js";
6
+ import"./server-v57wr0r9.js";
7
7
  import"./server-4x0xq8a1.js";
8
8
  import"./server-jwydbwcx.js";
9
9
  import"./server-2amn2s73.js";
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  renderSearchArchive2,
3
3
  renderSearchArchiveOffThread2
4
- } from "./server-kyfj1090.js";
5
- import"./server-8e5m2gre.js";
4
+ } from "./server-r7nj8ga0.js";
5
+ import"./server-t5c8awdm.js";
6
6
  import"./server-52x68mj4.js";
7
7
  import"./server-gge95a03.js";
8
8
  import"./server-beydmd68.js";
@@ -64,6 +64,7 @@ import {
64
64
  persistCachedM0,
65
65
  clearCachedM0M1,
66
66
  describeProtectedTailDrainBudgetSkip,
67
+ loadPersistedUsage,
67
68
  loadProtectedTailMeta,
68
69
  markProtectedTailPolicyV3Seeded,
69
70
  recordProtectedTailPublicationFloor,
@@ -194,6 +195,7 @@ import {
194
195
  requestPendingMaterialization,
195
196
  dropSlot,
196
197
  externalHistorianFailureReason,
198
+ getRecentFailedHistorianRunTimes,
197
199
  recordHistorianRun,
198
200
  summarizeImportance,
199
201
  tallyFactsByCategory,
@@ -206,7 +208,7 @@ import {
206
208
  getProjectState,
207
209
  recordSubagentInvocation,
208
210
  getLatestHistorianInvocationId
209
- } from "./server-q02z0jq7.js";
211
+ } from "./server-v57wr0r9.js";
210
212
  import {
211
213
  invalidateAutoEmbedSession
212
214
  } from "./server-2amn2s73.js";
@@ -6826,6 +6828,60 @@ function codepoints(value) {
6826
6828
  function escapeText(value) {
6827
6829
  return value.replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").trim();
6828
6830
  }
6831
+ var PUNCTUATION_FALLBACKS = {
6832
+ "‘": "'",
6833
+ "’": "'",
6834
+ "‚": "'",
6835
+ "‛": "'",
6836
+ "“": '"',
6837
+ "”": '"',
6838
+ "„": '"',
6839
+ "‟": '"',
6840
+ "–": "-",
6841
+ "—": "-",
6842
+ "…": "...",
6843
+ " ": " ",
6844
+ " ": " ",
6845
+ " ": " "
6846
+ };
6847
+ var REMOVABLE_COMBINING_MARK = /(?![\u0334-\u0338])\p{M}/gu;
6848
+ function hasGlyph(character) {
6849
+ return MURAL_FONT_GLYPHS[character] !== undefined;
6850
+ }
6851
+ function drawableMuralCue(cue) {
6852
+ const text = escapeText(cue);
6853
+ let normalized = "";
6854
+ let changed = false;
6855
+ for (const character of text) {
6856
+ if (hasGlyph(character)) {
6857
+ normalized += character;
6858
+ continue;
6859
+ }
6860
+ changed = true;
6861
+ const replacement = PUNCTUATION_FALLBACKS[character] ?? character.normalize("NFKD").replace(REMOVABLE_COMBINING_MARK, "");
6862
+ for (const part of replacement) {
6863
+ if (!hasGlyph(part))
6864
+ return null;
6865
+ }
6866
+ normalized += replacement;
6867
+ }
6868
+ if (!changed)
6869
+ return cue;
6870
+ const result = escapeText(normalized);
6871
+ return result.length > 0 ? result : null;
6872
+ }
6873
+ function partitionDrawableEntries(entries) {
6874
+ const drawable = [];
6875
+ const undrawableIds = [];
6876
+ for (const entry of entries) {
6877
+ const cue = drawableMuralCue(entry.cue);
6878
+ if (cue === null)
6879
+ undrawableIds.push(entry.id);
6880
+ else
6881
+ drawable.push(cue === entry.cue ? entry : { ...entry, cue });
6882
+ }
6883
+ return { drawable, undrawableIds };
6884
+ }
6829
6885
  function banner(category, roomWidth) {
6830
6886
  const label = ` <${category}> `;
6831
6887
  if (codepoints(label) > roomWidth) {
@@ -7131,11 +7187,12 @@ function snapDimensionToVisionTile(contentPixels, maximum) {
7131
7187
  return Math.min(maximum, Math.max(MURAL_VISION_TILE, Math.ceil(contentPixels / MURAL_VISION_TILE) * MURAL_VISION_TILE));
7132
7188
  }
7133
7189
  function planMuralRender(entries) {
7134
- const roomWidth = chooseRoomWidth(entries);
7135
- const plan = planLines(entries, roomWidth);
7190
+ const { drawable, undrawableIds } = partitionDrawableEntries(entries);
7191
+ const roomWidth = chooseRoomWidth(drawable);
7192
+ const plan = planLines(drawable, roomWidth);
7136
7193
  const candidates = Array.from({ length: MURAL_COLUMNS }, (_, index) => {
7137
7194
  const requestedColumnCount = index + 1;
7138
- const layout = renderLayout(entries, plan, roomWidth, requestedColumnCount);
7195
+ const layout = renderLayout(drawable, plan, roomWidth, requestedColumnCount);
7139
7196
  const contentWidth = layout.columnCount === 0 ? 0 : layout.columnCount * roomWidth * MURAL_CELL_WIDTH + MURAL_COLUMN_GAP * (layout.columnCount - 1) * MURAL_CELL_WIDTH;
7140
7197
  const contentHeight = layout.rowCount * MURAL_LINE_PITCH;
7141
7198
  const width = snapDimensionToVisionTile(contentWidth, MURAL_WIDTH);
@@ -7164,7 +7221,13 @@ function planMuralRender(entries) {
7164
7221
  }
7165
7222
  return candidate.requestedColumnCount < best.requestedColumnCount ? candidate : best;
7166
7223
  }, firstCandidate);
7167
- return { roomWidth, layout: selected.layout, width: selected.width, height: selected.height };
7224
+ return {
7225
+ roomWidth,
7226
+ layout: selected.layout,
7227
+ width: selected.width,
7228
+ height: selected.height,
7229
+ undrawableIds
7230
+ };
7168
7231
  }
7169
7232
  function rasterMural(plan) {
7170
7233
  const { roomWidth, layout, width, height } = plan;
@@ -7200,6 +7263,7 @@ function renderPlannedMural(plan) {
7200
7263
  layoutItems: layout.layoutItems,
7201
7264
  renderedIds: layout.renderedIds,
7202
7265
  droppedIds: layout.droppedIds,
7266
+ undrawableIds: plan.undrawableIds,
7203
7267
  categoryLineUsage: layout.usage,
7204
7268
  filledLineCount: layout.filledLineCount,
7205
7269
  width,
@@ -7231,13 +7295,17 @@ function poolContentHash(pool, memory) {
7231
7295
  function getMuralCoverage(db, projectIdentity, pool) {
7232
7296
  const { memories, cueState } = pool ?? readMuralPool(db, projectIdentity);
7233
7297
  let cuedMemoryCount = 0;
7298
+ let undrawableCueCount = 0;
7234
7299
  for (const memory of memories) {
7235
7300
  const state = cueState.get(memory.id);
7236
7301
  if (state && typeof state.cue === "string" && state.cue.trim() !== "" && state.hash !== null && state.hash === poolContentHash(pool, memory)) {
7237
- cuedMemoryCount += 1;
7302
+ if (drawableMuralCue(state.cue) === null)
7303
+ undrawableCueCount += 1;
7304
+ else
7305
+ cuedMemoryCount += 1;
7238
7306
  }
7239
7307
  }
7240
- return { activeMemoryCount: memories.length, cuedMemoryCount };
7308
+ return { activeMemoryCount: memories.length, cuedMemoryCount, undrawableCueCount };
7241
7309
  }
7242
7310
  function resolveMural(db, projectIdentity, budgetTokens = DEFAULT_MURAL_MEMORY_BUDGET, pool) {
7243
7311
  const memories = pool?.memories ?? getMemoriesByProject2(db, projectIdentity, ["active", "permanent"]);
@@ -7355,7 +7423,8 @@ function ensureMuralRendered(db, projectIdentity, budgetTokens = DEFAULT_MURAL_M
7355
7423
  const pool = readMuralPool(db, projectIdentity);
7356
7424
  const coverage = getMuralCoverage(db, projectIdentity, pool);
7357
7425
  if (coverage.activeMemoryCount === 0 || !muralCoverageGate(coverage.cuedMemoryCount, coverage.activeMemoryCount)) {
7358
- const skipReason = coverage.activeMemoryCount === 0 ? "no active memories" : `only ${coverage.cuedMemoryCount}/${coverage.activeMemoryCount} active memories have current cues (requires ${MIN_MURAL_CUED_MEMORIES} cues or ${MIN_MURAL_COVERAGE * 100}% coverage)`;
7426
+ const undrawable = coverage.undrawableCueCount > 0 ? ` the mural font can draw (${coverage.undrawableCueCount} more use characters it has no glyph for)` : "";
7427
+ const skipReason = coverage.activeMemoryCount === 0 ? "no active memories" : `only ${coverage.cuedMemoryCount}/${coverage.activeMemoryCount} active memories have current cues${undrawable} (requires ${MIN_MURAL_CUED_MEMORIES} cues or ${MIN_MURAL_COVERAGE * 100}% coverage)`;
7359
7428
  log2(`[mural] skipped for ${projectIdentity}: ${skipReason}`);
7360
7429
  return { hasMural: false, rerendered: false, skipReason };
7361
7430
  }
@@ -7370,6 +7439,11 @@ function ensureMuralRendered(db, projectIdentity, budgetTokens = DEFAULT_MURAL_M
7370
7439
  return { ...cached.result };
7371
7440
  }
7372
7441
  const plan = planMuralRender(entries);
7442
+ if (plan.layout.renderedIds.length === 0) {
7443
+ const skipReason = `none of the ${entries.length} overflow cues can be drawn (${plan.undrawableIds.length} use characters the mural font has no glyph for)`;
7444
+ log2(`[mural] skipped for ${projectIdentity}: ${skipReason}`);
7445
+ return { hasMural: false, rerendered: false, skipReason };
7446
+ }
7373
7447
  const textHash = createHash7("sha256").update(plan.layout.text).digest("hex");
7374
7448
  if (existing && existing.contentHash === textHash && existing.width === plan.width && existing.height === plan.height) {
7375
7449
  return rememberRender(db, projectIdentity, key, existing.image, {
@@ -7382,6 +7456,8 @@ function ensureMuralRendered(db, projectIdentity, budgetTokens = DEFAULT_MURAL_M
7382
7456
  });
7383
7457
  }
7384
7458
  const rendered = renderPlannedMural(plan);
7459
+ if (rendered.undrawableIds.length > 0)
7460
+ log2(`[mural] rendered for ${projectIdentity}: ${rendered.renderedIds.length} cues drawn, ${rendered.droppedIds.length} left out for space, ${rendered.undrawableIds.length} left out because the mural font has no glyph for their characters`);
7385
7461
  if (mode === "persist")
7386
7462
  upsertMural(db, {
7387
7463
  projectPath: projectIdentity,
@@ -13085,6 +13161,140 @@ function sanitizeDumpName(value) {
13085
13161
  return value.replace(/[^a-zA-Z0-9._-]/g, "-");
13086
13162
  }
13087
13163
 
13164
+ // src/hooks/magic-context/historian-failure-report.ts
13165
+ var REPEATED_HISTORIAN_FAILURE_WARNING_STEP = 3;
13166
+ var REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS = 30 * 60 * 1000;
13167
+ var ACTIONS = "What to do: run /ctx-status for detail; change the historian model or its fallback models in magic-context.jsonc (user or project config); or run /ctx-recomp to rebuild the history.";
13168
+ var REFUSAL_ERROR_MAX_CHARS = 500;
13169
+ var WARNING_ERROR_MAX_CHARS = 200;
13170
+ function readHistorianFailureStreak(db, sessionId, options = {}) {
13171
+ const state = getHistorianFailureState(db, sessionId);
13172
+ const count = state.failureCount;
13173
+ let since = null;
13174
+ if (count > 0) {
13175
+ const recorded = count - Math.max(0, options.unrecordedFailures ?? 0);
13176
+ if (recorded <= 0) {
13177
+ since = state.lastFailureAt;
13178
+ } else {
13179
+ const times = getRecentFailedHistorianRunTimes(db, sessionId, recorded);
13180
+ since = times.length === recorded ? times[recorded - 1] ?? null : null;
13181
+ }
13182
+ }
13183
+ return { count, lastError: state.lastError, lastFailureAt: state.lastFailureAt, since };
13184
+ }
13185
+ function formatHistorianClockTime(at, now = Date.now()) {
13186
+ const date = new Date(at);
13187
+ const pad = (value) => String(value).padStart(2, "0");
13188
+ const clock = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
13189
+ const today = new Date(now);
13190
+ const sameDay = date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate();
13191
+ return sameDay ? clock : `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${clock}`;
13192
+ }
13193
+ function formatHistorianSeconds(ms) {
13194
+ const seconds = Math.max(0, ms) / 1000;
13195
+ return String(Number(seconds.toFixed(seconds >= 10 ? 0 : 3)));
13196
+ }
13197
+ function singleLine(text) {
13198
+ return text.replace(/\s+/g, " ").trim();
13199
+ }
13200
+ function quoteError(error, maxChars) {
13201
+ const text = sanitizeDiagnosticText(singleLine(error));
13202
+ return text.length > maxChars ? `${text.slice(0, maxChars - 1).trimEnd()}…` : text;
13203
+ }
13204
+ function endSentence(text) {
13205
+ return /[.!?]$/.test(text) ? text : `${text}.`;
13206
+ }
13207
+ function usageClause(usagePercentage) {
13208
+ return typeof usagePercentage === "number" && Number.isFinite(usagePercentage) ? `context is at ${Math.round(usagePercentage)}% of the window` : "context is nearly full";
13209
+ }
13210
+ function capitalize(text) {
13211
+ return text.charAt(0).toUpperCase() + text.slice(1);
13212
+ }
13213
+ function chunkLabel(chunk) {
13214
+ return chunk ? `messages ${chunk.start}-${chunk.end}` : "";
13215
+ }
13216
+ function streakSentence(failures, now) {
13217
+ if (failures.count <= 0)
13218
+ return null;
13219
+ const since = failures.since !== null ? `, since ${formatHistorianClockTime(failures.since, now)}` : "";
13220
+ return `Summary runs failed in a row: ${failures.count}${since}.`;
13221
+ }
13222
+ function failureBelongsToRun(failures, run) {
13223
+ return failures.count > 0 && failures.lastFailureAt !== null && run?.startedAt !== undefined && failures.lastFailureAt >= run.startedAt;
13224
+ }
13225
+ function describeHistorianJoinRefusal(input) {
13226
+ const now = input.now ?? Date.now();
13227
+ const { run, failures } = input;
13228
+ const sentences = [
13229
+ `This turn was not sent: ${usageClause(input.usagePercentage)}, and Magic Context waited ${formatHistorianSeconds(input.waitedMs)} s for a history summary that did not finish in time.`
13230
+ ];
13231
+ const subject = run?.chunk ? `The summary of ${chunkLabel(run.chunk)}` : "The summary run";
13232
+ const ownFailure = failureBelongsToRun(failures, run);
13233
+ const lastError = failures.lastError ? quoteError(failures.lastError, REFUSAL_ERROR_MAX_CHARS) : "";
13234
+ if (ownFailure) {
13235
+ sentences.push(endSentence(`${subject} failed: ${lastError || "no reason recorded"}`));
13236
+ } else if (run && run.endedAt === undefined) {
13237
+ sentences.push(run.startedAt !== undefined ? `${subject} is still running after ${formatHistorianSeconds(now - run.startedAt)} s.` : `${subject} is still running.`);
13238
+ } else if (run) {
13239
+ sentences.push(`${subject} finished after the wait ended.`);
13240
+ }
13241
+ if (!ownFailure && failures.count > 0 && lastError && failures.lastFailureAt !== null) {
13242
+ sentences.push(endSentence(`The previous run failed at ${formatHistorianClockTime(failures.lastFailureAt, now)}: ${lastError}`));
13243
+ }
13244
+ const streak = streakSentence(failures, now);
13245
+ if (streak)
13246
+ sentences.push(streak);
13247
+ sentences.push(ACTIONS);
13248
+ return sentences.join(" ");
13249
+ }
13250
+ function describeRepeatedHistorianFailures(input) {
13251
+ const now = input.now ?? Date.now();
13252
+ const { failures } = input;
13253
+ const facts = [
13254
+ streakSentence(failures, now) ?? "Summary runs are failing.",
13255
+ ...input.chunk ? [`Last chunk: ${chunkLabel(input.chunk)}.`] : [],
13256
+ ...failures.lastError ? [
13257
+ endSentence(`Last error: ${quoteError(failures.lastError, WARNING_ERROR_MAX_CHARS)}`)
13258
+ ] : [],
13259
+ `${capitalize(usageClause(input.usagePercentage))}; at 95% a turn can be refused if no summary finishes in time.`
13260
+ ];
13261
+ return [
13262
+ "## Magic Context — History summaries keep failing",
13263
+ "",
13264
+ facts.join(" "),
13265
+ "",
13266
+ ACTIONS
13267
+ ].join(`
13268
+ `);
13269
+ }
13270
+ var repeatedFailureWarnings = new Map;
13271
+ function shouldWarnRepeatedHistorianFailures(sessionId, failureCount, now = Date.now()) {
13272
+ const step = REPEATED_HISTORIAN_FAILURE_WARNING_STEP;
13273
+ if (failureCount < step || failureCount % step !== 0)
13274
+ return false;
13275
+ const last = repeatedFailureWarnings.get(sessionId);
13276
+ if (last && failureCount > last.count && now - last.at < REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS) {
13277
+ return false;
13278
+ }
13279
+ repeatedFailureWarnings.set(sessionId, { count: failureCount, at: now });
13280
+ return true;
13281
+ }
13282
+ function takeRepeatedHistorianFailureWarning(input) {
13283
+ const now = input.now ?? Date.now();
13284
+ if (!shouldWarnRepeatedHistorianFailures(input.sessionId, input.failureCount, now)) {
13285
+ return null;
13286
+ }
13287
+ const failures = readHistorianFailureStreak(input.db, input.sessionId, {
13288
+ unrecordedFailures: input.unrecordedFailures
13289
+ });
13290
+ return describeRepeatedHistorianFailures({
13291
+ chunk: input.chunk,
13292
+ failures: { ...failures, count: input.failureCount },
13293
+ usagePercentage: loadPersistedUsage(input.db, input.sessionId)?.usage.percentage,
13294
+ now
13295
+ });
13296
+ }
13297
+
13088
13298
  // src/hooks/magic-context/historian-history-wait.ts
13089
13299
  var historyWaits = new Map;
13090
13300
  function newestMessageId(snapshot) {
@@ -14510,6 +14720,28 @@ async function runCompartmentAgent(deps) {
14510
14720
  }
14511
14721
  await sendStatusNotification2(client, sessionId, message, getNotificationParams?.() ?? {});
14512
14722
  };
14723
+ const notifyCountedFailure = async (failureCount, notice) => {
14724
+ let warning = null;
14725
+ try {
14726
+ warning = takeRepeatedHistorianFailureWarning({
14727
+ db,
14728
+ sessionId,
14729
+ failureCount,
14730
+ chunk: telemetry.chunkStartOrdinal != null && telemetry.chunkEndOrdinal != null ? { start: telemetry.chunkStartOrdinal, end: telemetry.chunkEndOrdinal } : undefined,
14731
+ unrecordedFailures: 1
14732
+ });
14733
+ } catch (error) {
14734
+ sessionLog2(sessionId, "historian repeated-failure warning failed:", error);
14735
+ }
14736
+ if (!warning) {
14737
+ await notifyHistorianIssue(notice);
14738
+ return;
14739
+ }
14740
+ issueNotified = true;
14741
+ lastHistorianAlertBySession.set(sessionId, Date.now());
14742
+ sessionLog2(sessionId, `historian repeated-failure warning sent: count=${failureCount}`);
14743
+ await sendStatusNotification2(client, sessionId, warning, getNotificationParams?.() ?? {});
14744
+ };
14513
14745
  const truncateHistorianInputIfNeeded = (text, budget) => {
14514
14746
  if (estimateTokens(text) <= budget)
14515
14747
  return text;
@@ -14590,9 +14822,9 @@ async function runCompartmentAgent(deps) {
14590
14822
  telemetry.failureReason = `existing-validation: ${existingValidationError}`;
14591
14823
  retainDrainReservationForRetryThrottle = true;
14592
14824
  if (unresolvedInvolved) {
14593
- await notifyHistorianIssue(buildStoredCompartmentsInvalidNotice());
14825
+ await notifyCountedFailure(failCount, buildStoredCompartmentsInvalidNotice());
14594
14826
  } else {
14595
- await notifyHistorianIssue(buildHistorianFailureNotice(failCount, existingValidationError));
14827
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, existingValidationError));
14596
14828
  }
14597
14829
  return;
14598
14830
  }
@@ -14723,9 +14955,9 @@ async function runCompartmentAgent(deps) {
14723
14955
  return;
14724
14956
  }
14725
14957
  sessionLog2(sessionId, `historian failure: source=prompt-fit reason="${promptFit.reason}"`);
14726
- incrementHistorianFailure(db, sessionId, promptFit.reason);
14958
+ const failCount = incrementHistorianFailure(db, sessionId, promptFit.reason);
14727
14959
  retainDrainReservationForRetryThrottle = true;
14728
- await notifyHistorianIssue(buildHistorianWindowTooSmallNotice());
14960
+ await notifyCountedFailure(failCount, buildHistorianWindowTooSmallNotice());
14729
14961
  return;
14730
14962
  }
14731
14963
  const chunkTokens = promptFit.chunkTokens;
@@ -14765,6 +14997,7 @@ async function runCompartmentAgent(deps) {
14765
14997
  const forceKeepLastCompartmentForChunk = deps.forceKeepLastCompartment === true && !chunk.hasMore;
14766
14998
  telemetry.chunkStartOrdinal = chunk.startIndex;
14767
14999
  telemetry.chunkEndOrdinal = chunk.endIndex;
15000
+ deps.onChunkSelected?.({ start: chunk.startIndex, end: chunk.endIndex });
14768
15001
  if (!chunk.text || chunk.messageCount === 0) {
14769
15002
  if (persistFilteredNoise(db, sessionId, chunk, eligibleEndOrdinal)) {
14770
15003
  telemetry.status = "noop";
@@ -14825,7 +15058,7 @@ async function runCompartmentAgent(deps) {
14825
15058
  telemetry.failureReason = `chunk-coverage: ${chunkCoverageError}`;
14826
15059
  sessionLog2(sessionId, `historian failure: source=chunk-coverage reason="${chunkCoverageError}" chunkRange=${chunk.startIndex}-${chunk.endIndex}`);
14827
15060
  const failCount = incrementHistorianFailure(db, sessionId, chunkCoverageError);
14828
- await notifyHistorianIssue(buildHistorianFailureNotice(failCount, chunkCoverageError));
15061
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, chunkCoverageError));
14829
15062
  rollbackDrainReservation();
14830
15063
  return;
14831
15064
  }
@@ -14876,7 +15109,7 @@ ${chunkText}`,
14876
15109
  sessionLog2(sessionId, `historian failure: source=validation reason="${validatedPass.error}" chunkRange=${chunk.startIndex}-${chunk.endIndex} fallbackModel=${deps.fallbackModelId ?? "<none>"} twoPass=${deps.historianTwoPass ? "true" : "false"}`);
14877
15110
  const failCount = incrementHistorianFailure(db, sessionId, validatedPass.error);
14878
15111
  telemetry.failureReason = validatedPass.failureReason ?? validatedPass.error;
14879
- await notifyHistorianIssue(buildHistorianFailureNotice(failCount, validatedPass.error));
15112
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, validatedPass.error));
14880
15113
  return;
14881
15114
  }
14882
15115
  retainDrainReservationForRetryThrottle = false;
@@ -14905,7 +15138,7 @@ ${chunkText}`,
14905
15138
  sessionLog2(sessionId, "historian output discarded: reason=no_forward_progress");
14906
15139
  const failCount = incrementHistorianFailure(db, sessionId, `no forward progress beyond raw message ${offset - 1}`);
14907
15140
  try {
14908
- await notifyHistorianIssue(buildHistorianFailureNotice(failCount, `historian made no forward progress beyond raw message ${offset - 1}`));
15141
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, `historian made no forward progress beyond raw message ${offset - 1}`));
14909
15142
  } finally {
14910
15143
  recordHistorianNoProgress(boundarySnapshot, inEmergency);
14911
15144
  }
@@ -14956,7 +15189,7 @@ ${chunkText}`,
14956
15189
  sessionLog2(sessionId, `historian publish refused: sequence=${danglingBoundary.sequence} side=${danglingBoundary.side} missing_id=${danglingBoundary.messageId}; raw snapshot changed during the historian run`);
14957
15190
  sessionLog2(sessionId, "historian output discarded: reason=dangling_boundary");
14958
15191
  const failCount = incrementHistorianFailure(db, sessionId, reason);
14959
- await notifyHistorianIssue(buildHistorianFailureNotice(failCount, reason));
15192
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, reason));
14960
15193
  rollbackDrainReservation();
14961
15194
  return;
14962
15195
  }
@@ -15164,7 +15397,7 @@ ${chunkText}`,
15164
15397
  sessionLog2(sessionId, `historian failure: source=exception ${desc.brief}${desc.stackHead ? ` stackHead="${desc.stackHead}"` : ""}`);
15165
15398
  if (!issueNotified) {
15166
15399
  const failCount = incrementHistorianFailure(db, sessionId, desc.brief);
15167
- await notifyHistorianIssue(buildHistorianFailureNotice(failCount, desc.brief));
15400
+ await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, desc.brief));
15168
15401
  }
15169
15402
  } finally {
15170
15403
  if (!completedSuccessfully) {
@@ -15988,10 +16221,12 @@ function registerActiveCompartmentRun(sessionId, promise, kind = "other") {
15988
16221
  const activeRun = {
15989
16222
  promise: Promise.resolve(),
15990
16223
  published: false,
15991
- kind
16224
+ kind,
16225
+ startedAt: Date.now()
15992
16226
  };
15993
16227
  const wrapped = promise.finally(() => {
15994
16228
  activeRun.settled = true;
16229
+ activeRun.endedAt = Date.now();
15995
16230
  if (activeRuns.get(sessionId)?.promise === wrapped) {
15996
16231
  activeRuns.delete(sessionId);
15997
16232
  }
@@ -16048,9 +16283,19 @@ function startBackgroundCompartmentAgent(deps, runAgent, prepareBoundary) {
16048
16283
  return;
16049
16284
  }
16050
16285
  const renewal = startLeaseRenewal(deps, holderId);
16286
+ const activeRun = {
16287
+ promise: Promise.resolve(),
16288
+ published: false,
16289
+ kind: "incremental",
16290
+ startedAt: Date.now()
16291
+ };
16051
16292
  const runnerDeps = withPublishedCallback({
16052
16293
  ...deps,
16053
- compartmentLeaseHolderId: holderId
16294
+ compartmentLeaseHolderId: holderId,
16295
+ onChunkSelected: (chunk) => {
16296
+ activeRun.chunk = chunk;
16297
+ deps.onChunkSelected?.(chunk);
16298
+ }
16054
16299
  });
16055
16300
  const promise = new Promise((resolve) => setTimeout(resolve, 0)).then(() => withRawSessionMessageCache2(() => {
16056
16301
  const snapshot = deps.boundarySnapshot;
@@ -16080,6 +16325,7 @@ function startBackgroundCompartmentAgent(deps, runAgent, prepareBoundary) {
16080
16325
  updateSessionMeta(deps.db, deps.sessionId, { compartmentInProgress: false });
16081
16326
  } catch {}
16082
16327
  }).finally(() => {
16328
+ activeRun.endedAt = Date.now();
16083
16329
  try {
16084
16330
  clearInterval(renewal);
16085
16331
  releaseCompartmentLeaseBestEffort(deps.db, deps.sessionId, holderId, sessionLog2);
@@ -16090,7 +16336,8 @@ function startBackgroundCompartmentAgent(deps, runAgent, prepareBoundary) {
16090
16336
  sessionLog2(deps.sessionId, "compartment agent: finalizer failed:", err);
16091
16337
  }
16092
16338
  });
16093
- activeRuns.set(deps.sessionId, { promise, published: false, kind: "incremental" });
16339
+ activeRun.promise = promise;
16340
+ activeRuns.set(deps.sessionId, activeRun);
16094
16341
  }
16095
16342
  async function executeContextRecompWithResult(deps, options = {}) {
16096
16343
  const { sessionId } = deps;
@@ -16279,4 +16526,4 @@ ${failure}`;
16279
16526
  }
16280
16527
  }
16281
16528
 
16282
- export { historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, v2ToolDefinitionsHash, v2RequestToolsFingerprint, classifyRequestToolsChange, readCoordinateGeneration, rebaseSessionCoordinatesAsync, HiddenCompletionRefusal, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, startCompactionMarkerCandidatePreparation, removeMcOwnedCompactionMarkers, getCompartmentEvents, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, DreamerProviderOutputFailureError, providerOutputFailureFromInvalidManifest, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, parseProviderModel, modelBodyField, toModelEntry, hiddenModelCooldowns, ModelProducedNoOutputError, noteModelActivityMonitored, noteModelOutputReceived, isPromptTimeoutError, getPromptFailureDetail, raceWithSignal, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, annotateSubagentInvocationError, failedInvocationStatus, emptyTokenTotals, sumTokensFromChildMessages, recordChildInvocation, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, teardownChildSession, runTokenLog, formatRunTokenLog, createChildSessionWithFence, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, extractM0Block, formatDate, TEMPORAL_MARKER_REPLAY_PATTERN, collectTemporalCandidates, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, MaterializeContentionError, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, stripMemoryMuralBlock, servedHeadTexts, materializeM0, hydrateCachedM0Mural, resetPrefixTrimFallbackState, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, headMessagesForSizing, rawTailAfterNewestCompartment, hasCompleteCachedM0M1, injectM0M1, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, shouldWaitForNewHistorianHistory, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, omitIncompleteFileTokenTotals, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, runCompartmentAgent, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, isRecompFailure2, isRecompSkip2, extractRecompReason2, setRecompStarting2, setRecompNote2, setRecompTerminal2, buildRecompDeps2, runManagedRecomp2 };
16529
+ export { historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, v2ToolDefinitionsHash, v2RequestToolsFingerprint, classifyRequestToolsChange, readCoordinateGeneration, rebaseSessionCoordinatesAsync, HiddenCompletionRefusal, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, startCompactionMarkerCandidatePreparation, removeMcOwnedCompactionMarkers, getCompartmentEvents, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, DreamerProviderOutputFailureError, providerOutputFailureFromInvalidManifest, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, parseProviderModel, modelBodyField, toModelEntry, hiddenModelCooldowns, ModelProducedNoOutputError, noteModelActivityMonitored, noteModelOutputReceived, isPromptTimeoutError, getPromptFailureDetail, raceWithSignal, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, annotateSubagentInvocationError, failedInvocationStatus, emptyTokenTotals, sumTokensFromChildMessages, recordChildInvocation, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, teardownChildSession, runTokenLog, formatRunTokenLog, createChildSessionWithFence, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, extractM0Block, formatDate, TEMPORAL_MARKER_REPLAY_PATTERN, collectTemporalCandidates, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, MaterializeContentionError, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, stripMemoryMuralBlock, servedHeadTexts, materializeM0, hydrateCachedM0Mural, resetPrefixTrimFallbackState, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, headMessagesForSizing, rawTailAfterNewestCompartment, hasCompleteCachedM0M1, injectM0M1, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, readHistorianFailureStreak, describeHistorianJoinRefusal, shouldWaitForNewHistorianHistory, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, omitIncompleteFileTokenTotals, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, runCompartmentAgent, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, isRecompFailure2, isRecompSkip2, extractRecompReason2, setRecompStarting2, setRecompNote2, setRecompTerminal2, buildRecompDeps2, runManagedRecomp2 };
@@ -22,7 +22,7 @@ import {
22
22
  } from "./server-gge95a03.js";
23
23
  import {
24
24
  readV2ArchiveOffThread2
25
- } from "./server-8e5m2gre.js";
25
+ } from "./server-t5c8awdm.js";
26
26
 
27
27
  // src/tools/ctx-expand/search-archive.ts
28
28
  var archiveReadsOnThisThread = 0;
@@ -140,8 +140,8 @@ async function serveV2ArchiveReads2(port, openConnections) {
140
140
  import("./store-reader-yaxtdy6f.js"),
141
141
  import("./store-skkhh3rd.js"),
142
142
  import("./read-session-chunk-nqkn0yb4.js"),
143
- import("./render-jfa3hj8z.js"),
144
- import("./search-archive-p4s9q7a3.js"),
143
+ import("./render-g44ksejs.js"),
144
+ import("./search-archive-5ycchnyp.js"),
145
145
  import("./expand-attachments-h33jbgyz.js")
146
146
  ]);
147
147
  const pool = new V2StoreReaderPool;
@@ -4817,6 +4817,21 @@ function externalHistorianFailureReason(error, prefix = "provider_error") {
4817
4817
  }
4818
4818
 
4819
4819
  // src/features/magic-context/storage-historian-runs.ts
4820
+ function getRecentFailedHistorianRunTimes(db, sessionId, limit) {
4821
+ if (!Number.isInteger(limit) || limit <= 0)
4822
+ return [];
4823
+ try {
4824
+ return db.prepare(`SELECT created_at FROM historian_runs
4825
+ WHERE session_id = ? AND run_kind = 'incremental' AND status = 'failed'
4826
+ AND id > (
4827
+ SELECT COALESCE(MAX(id), 0) FROM historian_runs
4828
+ WHERE session_id = ? AND run_kind = 'incremental' AND status = 'success'
4829
+ )
4830
+ ORDER BY id DESC LIMIT ?`).all(sessionId, sessionId, limit).map((row) => row.created_at);
4831
+ } catch {
4832
+ return [];
4833
+ }
4834
+ }
4820
4835
  function recordHistorianRun(db, input) {
4821
4836
  try {
4822
4837
  const failureReason = input.failureReason == null ? input.status === "failed" ? "provider_error" : null : capHistorianFailureReason(input.failureReason, input.status === "failed" ? "provider_error" : "");
@@ -5121,4 +5136,4 @@ var ERROR_CLASSES = new Set([
5121
5136
  "permission_denied",
5122
5137
  "unknown"
5123
5138
  ]);
5124
- export { COMPARTMENT_LEASE_RENEWAL_MS, getCompartmentLeaseBlocker, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, buildCompartmentBlock, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getUncoveredCompartmentEndsThrough, isPartialCompartmentEnd, readProjectDocsCanonical, readServerFallbackUsage, providerResponseFailed, isSuccessfulProviderCompletion, LkgRecoveryFenceError, lkgServedArrayDigest, hasCleanLkgRecoveryFence, dirtyLkgRecoveryRevision, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, prepareLkgCaptureFence, certifyCommittedLkgCapture, markLkgRecoveryDirty, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, advanceSessionActivity, backfillSessionActivity, readSessionMeta, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, markSessionCleanupPending, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, clearSession, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, clearPendingMaterializationOrigin, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, isHeldHeadForRequest, deferDeliveredSystemRefresh, retirePendingSystemPromptDelivery, lkgProviderInputTotal, beginV2LkgRequest, claimLkgRequestIdentity, currentLkgRequestIdentity, noteCapturedLkgRequest, noteLkgProviderResponse, measuredLkgPrefix, clearLkgMeasuredRequest, saveLkgSlotToDb, clearPersistedLkgSlotStrict, loadPersistedLkgSlot, drainStaleLkgSlots, resolveLkgModelKeys, createLkgEntryProjector, captureLkgSlot, validateAnthropicReasoningRuns, validateLkgSeam, replayLkg, coldStartRawServedIndex, coldStartUncapturedReplay, noteUncertifiedNormalLkg, hasProcessLocalLkgProof, lkgDirtyRevision, rememberLkgDirtyRevision, readPersistedLkgUntaggedInputIds, persistLkgUntaggedInputIds, noteLkgRecoveryPrefix, readLkgRecoveryPrefix, noteLkgHealthyPrefix, lkgRecoveryReplayUnproven, lkgRecoveryEntryUnproven, beginServedRequest, noteServedPassPermission, noteServedModel, noteServedReplay, noteServedHostInput, noteServedRefusal, countServedRefusal, dropServedRecord, forgetServedRecord, commitServedRequest, lkgInputIdentity, beginLkgPass, visitMessageContentFields, contentSnapshotValue, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgContentDigest, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, forgetInMemorySlot, dropSlot, noteEntry, getLkgSlotHeapStats, TOOL_SWEEP_SCOPED_MARKER, useScopedToolSweep, createPreAdoptionToolSweepResolver, copySessionStateForClone, externalHistorianFailureReason, recordHistorianRun, summarizeImportance, tallyFactsByCategory, MEMORY_VISIBILITY_MUTATION_CATEGORY, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId };
5139
+ export { COMPARTMENT_LEASE_RENEWAL_MS, getCompartmentLeaseBlocker, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, buildCompartmentBlock, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getUncoveredCompartmentEndsThrough, isPartialCompartmentEnd, readProjectDocsCanonical, readServerFallbackUsage, providerResponseFailed, isSuccessfulProviderCompletion, LkgRecoveryFenceError, lkgServedArrayDigest, hasCleanLkgRecoveryFence, dirtyLkgRecoveryRevision, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, prepareLkgCaptureFence, certifyCommittedLkgCapture, markLkgRecoveryDirty, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, advanceSessionActivity, backfillSessionActivity, readSessionMeta, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, markSessionCleanupPending, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, clearSession, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, clearPendingMaterializationOrigin, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, isHeldHeadForRequest, deferDeliveredSystemRefresh, retirePendingSystemPromptDelivery, lkgProviderInputTotal, beginV2LkgRequest, claimLkgRequestIdentity, currentLkgRequestIdentity, noteCapturedLkgRequest, noteLkgProviderResponse, measuredLkgPrefix, clearLkgMeasuredRequest, saveLkgSlotToDb, clearPersistedLkgSlotStrict, loadPersistedLkgSlot, drainStaleLkgSlots, resolveLkgModelKeys, createLkgEntryProjector, captureLkgSlot, validateAnthropicReasoningRuns, validateLkgSeam, replayLkg, coldStartRawServedIndex, coldStartUncapturedReplay, noteUncertifiedNormalLkg, hasProcessLocalLkgProof, lkgDirtyRevision, rememberLkgDirtyRevision, readPersistedLkgUntaggedInputIds, persistLkgUntaggedInputIds, noteLkgRecoveryPrefix, readLkgRecoveryPrefix, noteLkgHealthyPrefix, lkgRecoveryReplayUnproven, lkgRecoveryEntryUnproven, beginServedRequest, noteServedPassPermission, noteServedModel, noteServedReplay, noteServedHostInput, noteServedRefusal, countServedRefusal, dropServedRecord, forgetServedRecord, commitServedRequest, lkgInputIdentity, beginLkgPass, visitMessageContentFields, contentSnapshotValue, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgContentDigest, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, forgetInMemorySlot, dropSlot, noteEntry, getLkgSlotHeapStats, TOOL_SWEEP_SCOPED_MARKER, useScopedToolSweep, createPreAdoptionToolSweepResolver, copySessionStateForClone, externalHistorianFailureReason, getRecentFailedHistorianRunTimes, recordHistorianRun, summarizeImportance, tallyFactsByCategory, MEMORY_VISIBILITY_MUTATION_CATEGORY, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId };
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.56",
7878
+ version: "0.49.57",
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-5hhm89jw.js");
8199
+ const { registerContext } = await import("./context-4gxr2xd4.js");
8200
8200
  setHarness2("opencode2");
8201
8201
  bindStaleBuildNotice({}, import.meta.url, "opencode2");
8202
8202
  const duties = await registerContext(context);
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  readV2ArchiveOffThread2,
3
3
  serveV2ArchiveReads2
4
- } from "./server-8e5m2gre.js";
4
+ } from "./server-t5c8awdm.js";
5
5
  import"./server-v0p37hm2.js";
6
6
  import"./server-gzy5w8ya.js";
7
7
  import"./server-1d042x6w.js";
@@ -11,7 +11,7 @@ import {
11
11
  releaseCompartmentLeaseBestEffort,
12
12
  getCompartments,
13
13
  getLastCompartmentEndMessage
14
- } from "./server-q02z0jq7.js";
14
+ } from "./server-v57wr0r9.js";
15
15
  import"./server-2amn2s73.js";
16
16
  import"./server-3jc6qmdz.js";
17
17
  import"./server-mxsy9h1d.js";
@@ -63,7 +63,7 @@ import {
63
63
  registerActiveCompartmentRun,
64
64
  setRecompStarting2,
65
65
  setRecompTerminal2
66
- } from "./server-z6sxv6n3.js";
66
+ } from "./server-dqwx9pdh.js";
67
67
  import"./server-qt1qqasc.js";
68
68
  import"./server-rpmkz5ta.js";
69
69
  import"./server-qp5sj6n5.js";