@cortexkit/opencode-magic-context 0.49.45 → 0.49.46

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 (104) hide show
  1. package/dist/auto-search-worker.js +1 -1
  2. package/dist/chunk-embedding-write-worker.js +1 -1
  3. package/dist/{context-y85dvs6j.js → context-cb51adcz.js} +362 -103
  4. package/dist/{derive-budgets-htj16n4x.js → derive-budgets-nkw09vq7.js} +1 -1
  5. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  6. package/dist/hooks/magic-context/inject-compartments.d.ts +21 -0
  7. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  8. package/dist/hooks/magic-context/priced-pass-sizing.d.ts +132 -0
  9. package/dist/hooks/magic-context/priced-pass-sizing.d.ts.map +1 -0
  10. package/dist/hooks/magic-context/reasoning-budget.d.ts.map +1 -1
  11. package/dist/hooks/magic-context/recovery-fit.d.ts +51 -0
  12. package/dist/hooks/magic-context/recovery-fit.d.ts.map +1 -0
  13. package/dist/hooks/magic-context/routine-cleanup-decision.d.ts +109 -0
  14. package/dist/hooks/magic-context/routine-cleanup-decision.d.ts.map +1 -0
  15. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  16. package/dist/hooks/magic-context/transform-compartment-phase.d.ts +24 -0
  17. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  18. package/dist/hooks/magic-context/transform-context-state.d.ts +2 -1
  19. package/dist/hooks/magic-context/transform-context-state.d.ts.map +1 -1
  20. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +15 -2
  21. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  22. package/dist/hooks/magic-context/transform.d.ts +10 -2
  23. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  24. package/dist/{index-tvd2j34s.js → index-44pp3vrj.js} +1 -1
  25. package/dist/{index-xejh7cqv.js → index-55ngkbqa.js} +28 -9
  26. package/dist/{index-980brvjr.js → index-5jk4h64j.js} +3 -3
  27. package/dist/{index-dnqqqc5f.js → index-8cfnaagj.js} +10 -2
  28. package/dist/{index-7na94cjf.js → index-a4t7pdmm.js} +3 -3
  29. package/dist/{index-z8dacvkt.js → index-b0xt5qz9.js} +1 -1
  30. package/dist/{index-bzq05g00.js → index-etn2hmb5.js} +1 -1
  31. package/dist/{index-rk5hyc41.js → index-gaxktvxm.js} +2 -2
  32. package/dist/{index-dcdvyaeh.js → index-kevd267m.js} +3 -3
  33. package/dist/{index-gf1vx3bn.js → index-kw7azjmy.js} +2 -2
  34. package/dist/{index-jwa5t1s4.js → index-n9q8c1dr.js} +2 -2
  35. package/dist/{index-qdx8dq60.js → index-pwfmcg4e.js} +4 -4
  36. package/dist/{index-fs3zfby1.js → index-snztv1f0.js} +608 -96
  37. package/dist/{index-0a79y98x.js → index-tajstyw4.js} +161 -81
  38. package/dist/{index-gxqr0sbd.js → index-x53gnmce.js} +10 -10
  39. package/dist/{index-wwg1je98.js → index-xgnh498s.js} +3 -2
  40. package/dist/index.js +19 -19
  41. package/dist/{message-index-bounded-d8xt6q5c.js → message-index-bounded-3qpg8dq5.js} +3 -3
  42. package/dist/migration-worker.js +1 -1
  43. package/dist/raw-ordinal-warmup-worker.js +4 -4
  44. package/dist/{read-session-chunk-k3fqshw8.js → read-session-chunk-7h9f32sz.js} +2 -2
  45. package/dist/{recomp-orchestrator-y75thsc3.js → recomp-orchestrator-qnactdw7.js} +8 -8
  46. package/dist/{render-3psbedzk.js → render-da999saz.js} +6 -6
  47. package/dist/{search-hd16c8gq.js → search-0a3hh5x6.js} +5 -5
  48. package/dist/{search-archive-rvr7j5gx.js → search-archive-0z9cxv8e.js} +4 -4
  49. package/dist/shared/window-geometry.d.ts +5 -0
  50. package/dist/shared/window-geometry.d.ts.map +1 -1
  51. package/dist/{storage-tags-ye9aqrqy.js → storage-tags-q8erkn48.js} +3 -1
  52. package/dist/tools/parameter-descriptions.d.ts +6 -6
  53. package/dist/tools/parameter-descriptions.d.ts.map +1 -1
  54. package/dist/{transform-postprocess-phase-1rzxmkhb.js → transform-postprocess-phase-k9d1r13f.js} +9 -9
  55. package/dist/v2/auto-search-worker.js +1 -1
  56. package/dist/v2/chunk-embedding-write-worker.js +1 -1
  57. package/dist/v2/{context-0e946t63.js → context-jtqj5e1r.js} +1077 -245
  58. package/dist/v2/{derive-budgets-sa0v7bz0.js → derive-budgets-b5cgrtp8.js} +2 -2
  59. package/dist/v2/fold/code-mode-catalog.d.ts +11 -3
  60. package/dist/v2/fold/code-mode-catalog.d.ts.map +1 -1
  61. package/dist/v2/fold/instruction-supersession.d.ts +13 -2
  62. package/dist/v2/fold/instruction-supersession.d.ts.map +1 -1
  63. package/dist/v2/fold/native-replay.d.ts +5 -0
  64. package/dist/v2/fold/native-replay.d.ts.map +1 -1
  65. package/dist/v2/fold/owner.d.ts +14 -0
  66. package/dist/v2/fold/owner.d.ts.map +1 -1
  67. package/dist/v2/fold/summary.d.ts +35 -0
  68. package/dist/v2/fold/summary.d.ts.map +1 -1
  69. package/dist/v2/hooks/context.d.ts +2 -1
  70. package/dist/v2/hooks/context.d.ts.map +1 -1
  71. package/dist/v2/hooks/lkg-system.d.ts +3 -0
  72. package/dist/v2/hooks/lkg-system.d.ts.map +1 -1
  73. package/dist/v2/{message-index-bounded-wt64v2rn.js → message-index-bounded-60tdhht5.js} +3 -3
  74. package/dist/v2/migration-worker.js +1 -1
  75. package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
  76. package/dist/v2/{read-session-chunk-4b31z6bz.js → read-session-chunk-9tmsxwb2.js} +2 -2
  77. package/dist/v2/{recomp-orchestrator-6qrm2nea.js → recomp-orchestrator-7y8smqqp.js} +9 -9
  78. package/dist/v2/{render-f8mw16pp.js → render-j0y57skn.js} +6 -6
  79. package/dist/v2/{search-archive-7d0xdp54.js → search-archive-1e2tr8eq.js} +4 -4
  80. package/dist/v2/{search-ecjd7e50.js → search-qhd2m8kn.js} +4 -4
  81. package/dist/v2/{server-ftyc8awt.js → server-3rp821fw.js} +1 -1
  82. package/dist/v2/{server-39kzpp8q.js → server-4m71jpaj.js} +2 -2
  83. package/dist/v2/{server-vnpnmrsv.js → server-5dtrzs6j.js} +3 -2
  84. package/dist/v2/{server-0ymsgh0j.js → server-5vy0xt3p.js} +1 -1
  85. package/dist/v2/{server-sd8hvzte.js → server-af1rmkyn.js} +1 -1
  86. package/dist/v2/{server-zqzh2ybj.js → server-ahy062xr.js} +30 -11
  87. package/dist/v2/{server-wbxbk3za.js → server-ht0dyq9r.js} +2 -2
  88. package/dist/v2/{server-2qyfev3b.js → server-rjn4msjj.js} +2 -2
  89. package/dist/v2/{server-an1ff8d8.js → server-rshcp4gy.js} +3 -3
  90. package/dist/v2/{server-hq7fdqfm.js → server-sscb1r3e.js} +2 -2
  91. package/dist/v2/{server-gwqfwtzq.js → server-t4hk02v1.js} +10 -10
  92. package/dist/v2/{server-vjhk8v41.js → server-wa4qhryh.js} +1 -1
  93. package/dist/v2/{server-qxzbmtqt.js → server-zt1m5rwj.js} +10 -2
  94. package/dist/v2/server.js +4 -4
  95. package/dist/v2/{storage-tags-8nttt1sk.js → storage-tags-ztar1k0g.js} +3 -1
  96. package/dist/v2/{v2-archive-reader-53kp5mme.js → v2-archive-reader-tme5988n.js} +1 -1
  97. package/dist/v2/{wrapup-orchestrator-bng0dfxy.js → wrapup-orchestrator-k7m16xze.js} +9 -9
  98. package/dist/{v2-archive-reader-0fcxs5e9.js → v2-archive-reader-dq5ebwe6.js} +1 -1
  99. package/dist/{wrapup-orchestrator-r5cqgyrg.js → wrapup-orchestrator-4pqwet8p.js} +9 -9
  100. package/package.json +1 -1
  101. package/src/agents/smart-notes-dreamer-gate.golden.json +169 -169
  102. package/src/shared/prompt-surface-a1-golden.md +4 -4
  103. package/src/shared/window-geometry.test.ts +85 -0
  104. package/src/shared/window-geometry.ts +29 -2
@@ -37,7 +37,7 @@ import {
37
37
  rebaseSessionCoordinatesAsync,
38
38
  resolveOpenCodeProtectedTailBoundary,
39
39
  getActiveCompartmentRun
40
- } from "./index-xejh7cqv.js";
40
+ } from "./index-55ngkbqa.js";
41
41
  import"./index-sd3egckz.js";
42
42
  import {
43
43
  getHarness2
@@ -60,7 +60,7 @@ import {
60
60
  deriveHistorianChunkTokens2,
61
61
  resolveKnownHistorianContextLimit2,
62
62
  resolveHistorianContextLimit2
63
- } from "./index-dnqqqc5f.js";
63
+ } from "./index-8cfnaagj.js";
64
64
  import"./index-4dpvnp8k.js";
65
65
  import {
66
66
  CANONICAL_DREAM_TASKS,
@@ -131,7 +131,7 @@ import {
131
131
  applyJsonSchemaParameterDescriptions,
132
132
  MagicContextRpcServer,
133
133
  subagentTemperature
134
- } from "./index-fs3zfby1.js";
134
+ } from "./index-snztv1f0.js";
135
135
  import {
136
136
  resolveHistorianModel2
137
137
  } from "./index-5kym00ag.js";
@@ -165,7 +165,7 @@ import {
165
165
  isDroppedToolOutput,
166
166
  evaluateChannel2,
167
167
  buildChannel2Reminder
168
- } from "./index-gxqr0sbd.js";
168
+ } from "./index-x53gnmce.js";
169
169
  import {
170
170
  hasMeaningfulUserText2,
171
171
  preloadTokenizer,
@@ -210,17 +210,17 @@ import {
210
210
  cleanUserText2,
211
211
  readRawSessionMessageIdOrdinalsForRange2,
212
212
  readRawSessionMessageOrdinalById2
213
- } from "./index-wwg1je98.js";
213
+ } from "./index-xgnh498s.js";
214
214
  import {
215
215
  BoundedSessionMap,
216
216
  recordToolDefinitionSet,
217
217
  getCurrentToolSetHash
218
218
  } from "./index-smtbdmc3.js";
219
- import"./index-bzq05g00.js";
219
+ import"./index-etn2hmb5.js";
220
220
  import"./index-h9m41624.js";
221
221
  import {
222
222
  scheduleClearAndReindex
223
- } from "./index-tvd2j34s.js";
223
+ } from "./index-44pp3vrj.js";
224
224
  import {
225
225
  invalidateAutoEmbedSession,
226
226
  clearEmbedSessionState
@@ -257,7 +257,7 @@ import {
257
257
  getSlot,
258
258
  dropSlot,
259
259
  copySessionStateForClone
260
- } from "./index-jwa5t1s4.js";
260
+ } from "./index-n9q8c1dr.js";
261
261
  import {
262
262
  startBootDeadline,
263
263
  BOOT_SQLITE_BUSY_TIMEOUT_MS,
@@ -265,7 +265,7 @@ import {
265
265
  openDatabaseAsync,
266
266
  isDatabasePersisted,
267
267
  getDatabasePersistenceError
268
- } from "./index-z8dacvkt.js";
268
+ } from "./index-b0xt5qz9.js";
269
269
  import"./index-fr0wbhdn.js";
270
270
  import"./index-nj360hcs.js";
271
271
  import {
@@ -284,7 +284,7 @@ import {
284
284
  EmergencyFailClosedError,
285
285
  DegradedPassRefusalError,
286
286
  isSyntheticHeadMessage2
287
- } from "./index-0a79y98x.js";
287
+ } from "./index-tajstyw4.js";
288
288
  import"./index-gn6gfz4y.js";
289
289
  import"./index-qt1qqasc.js";
290
290
  import {
@@ -305,8 +305,8 @@ import {
305
305
  } from "./index-x8a7jmkh.js";
306
306
  import"./index-fw42ms3m.js";
307
307
  import"./index-25ka1jza.js";
308
- import"./index-980brvjr.js";
309
- import"./index-dcdvyaeh.js";
308
+ import"./index-5jk4h64j.js";
309
+ import"./index-kevd267m.js";
310
310
  import"./index-gp3kcpc4.js";
311
311
  import {
312
312
  detectConflicts
@@ -329,10 +329,10 @@ import {
329
329
  createV2RawMessageProvider2
330
330
  } from "./index-29gd1zcx.js";
331
331
  import"./index-fmsr7v69.js";
332
- import"./index-gf1vx3bn.js";
332
+ import"./index-kw7azjmy.js";
333
333
  import"./index-kaqs6h31.js";
334
- import"./index-7na94cjf.js";
335
- import"./index-rk5hyc41.js";
334
+ import"./index-a4t7pdmm.js";
335
+ import"./index-gaxktvxm.js";
336
336
  import {
337
337
  isDreamerRunnable,
338
338
  isSmartNoteSurfaceAvailable,
@@ -863,59 +863,194 @@ var changed = "The Code Mode tool catalog has changed.";
863
863
  var replacement = `${changed} This catalog supersedes the previous Code Mode tool catalog.`;
864
864
  var codeMode = "core/codemode";
865
865
  var mcp = "core/mcp-guidance";
866
+ var date = "core/date";
867
+ var noCodeModeTools = "No Code Mode tools are currently available. Later Code Mode catalog updates may add or remove tools. Do not call `execute` unless there is at least one available Code Mode tool.";
868
+ var codeModeRemoved = "Code Mode tools are no longer available. Do not use any previously listed Code Mode tools.";
869
+ var catalogHeadings = ["## Available tools", "## Code Mode tools (call only inside `execute`)"];
866
870
  var mcpReplacement = "The available MCP server instructions have changed. This list supersedes the previous one.";
867
- var mcpDeltas = [
868
- "New MCP server instructions are available in addition to those previously listed:",
869
- "The following MCP server instructions have changed. Each entry replaces the previously listed server with the same name:",
870
- "Instructions for the following MCP servers are no longer available:"
871
- ];
872
- function sourceState(text, source) {
873
- const starts = (prefix) => text.startsWith(prefix) || text.includes(`
874
-
875
- ${prefix}`);
876
- if (source === codeMode) {
877
- if (text.startsWith(`${replacement}
871
+ var mcpRemoved = "MCP server instructions are no longer available.";
872
+ var mcpAdded = "New MCP server instructions are available in addition to those previously listed:";
873
+ var mcpChanged = "The following MCP server instructions have changed. Each entry replaces the previously listed server with the same name:";
874
+ var mcpGone = "Instructions for the following MCP servers are no longer available: ";
875
+ var dateLine = /^Today's date(?: is now)?: (?:Sun|Mon|Tue|Wed|Thu|Fri|Sat) (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{2} \d{4}$/;
876
+ var mentions = (part) => part.full ? [] : [...part.entries ?? [], ...part.removed ?? []];
877
+ function codeModePart(text) {
878
+ if (text === noCodeModeTools || text === codeModeRemoved || text.startsWith(`# Code Mode
879
+ `))
880
+ return { full: true };
881
+ if (text.startsWith(`${replacement}
878
882
 
879
883
  `)) {
880
- const rendered = text.slice(replacement.length + 2);
881
- if (rendered.startsWith(`# Code Mode
882
- `) || rendered.startsWith("No Code Mode tools are currently available."))
883
- return "full";
884
+ const rendered = text.slice(replacement.length + 2);
885
+ return rendered === noCodeModeTools || rendered.startsWith(`# Code Mode
886
+ `) ? { full: true } : undefined;
887
+ }
888
+ return text.startsWith(`${changed}
889
+
890
+ `) ? { full: false } : undefined;
891
+ }
892
+ function startsWithFullCatalog(text) {
893
+ const begins = (whole) => text === whole || text.startsWith(`${whole}
894
+
895
+ `);
896
+ return text.startsWith(`# Code Mode
897
+ `) || text.startsWith(`${replacement}
898
+
899
+ # Code Mode
900
+ `) || begins(noCodeModeTools) || begins(`${replacement}
901
+
902
+ ${noCodeModeTools}`) || begins(codeModeRemoved);
903
+ }
904
+ function wholeCatalog(text) {
905
+ if (text === codeModeRemoved)
906
+ return true;
907
+ const rendered = text.startsWith(`${replacement}
908
+
909
+ `) ? text.slice(replacement.length + 2) : text;
910
+ if (rendered === noCodeModeTools)
911
+ return true;
912
+ if (!rendered.startsWith(`# Code Mode
913
+ `))
914
+ return false;
915
+ const ends = catalogHeadings.map((heading) => {
916
+ const at = rendered.indexOf(`
917
+
918
+ ${heading}
919
+
920
+ `);
921
+ return at < 0 ? undefined : at + heading.length + 4;
922
+ }).filter((end) => end !== undefined);
923
+ return ends.length > 0 && !rendered.slice(Math.min(...ends)).includes(`
924
+
925
+ `);
926
+ }
927
+ function serverEntries(lines, start) {
928
+ const names = [];
929
+ let index = start;
930
+ for (;; ) {
931
+ const open = /^ {2}<server name="(.*)">$/.exec(lines[index] ?? "");
932
+ if (!open)
933
+ return { names, next: index };
934
+ let end = index + 1;
935
+ while (lines[end]?.startsWith(" "))
936
+ end++;
937
+ if (end === index + 1 || lines[end] !== " </server>")
884
938
  return;
885
- }
886
- if (text.startsWith(changed))
887
- return "delta";
888
- if (text.startsWith(`# Code Mode
889
- `) || text.startsWith("No Code Mode tools are currently available."))
890
- return "full";
891
- }
892
- if (source === mcp) {
893
- if (mcpDeltas.some(starts))
894
- return "delta";
895
- if ((starts(`${mcpReplacement}
896
- <mcp_instructions>
897
- `) || starts(`<mcp_instructions>
898
- `)) && text.includes("</mcp_instructions>"))
899
- return "full";
939
+ names.push(open[1]);
940
+ index = end + 1;
900
941
  }
901
- return;
942
+ }
943
+ function mcpPart(text) {
944
+ if (text === mcpRemoved)
945
+ return { full: true };
946
+ const lines = text.split(`
947
+ `);
948
+ const listStart = lines[0] === mcpReplacement ? 1 : 0;
949
+ if (lines[listStart] === "<mcp_instructions>") {
950
+ const entries = serverEntries(lines, listStart + 1);
951
+ return entries && entries.next === lines.length - 1 && lines[entries.next] === "</mcp_instructions>" ? { full: true, entries: entries.names } : undefined;
952
+ }
953
+ if (listStart > 0)
954
+ return;
955
+ const entries = [];
956
+ let removed;
957
+ let index = 0;
958
+ for (const header of [mcpAdded, mcpChanged]) {
959
+ if (lines[index] !== header)
960
+ continue;
961
+ const section = serverEntries(lines, index + 1);
962
+ if (!section || section.names.length === 0)
963
+ return;
964
+ entries.push(...section.names);
965
+ index = section.next;
966
+ }
967
+ const gone = lines[index];
968
+ if (gone?.startsWith(mcpGone) && gone.endsWith(".") && gone.length > mcpGone.length + 1) {
969
+ removed = gone.slice(mcpGone.length, -1).split(", ");
970
+ index++;
971
+ }
972
+ return index === lines.length && (entries.length > 0 || removed) ? { full: false, entries, ...removed ? { removed } : {} } : undefined;
973
+ }
974
+ var datePart = (text) => dateLine.test(text) ? { full: true } : undefined;
975
+ var parsers = {
976
+ [codeMode]: codeModePart,
977
+ [mcp]: mcpPart,
978
+ [date]: datePart
979
+ };
980
+ function splitRow(text, sources) {
981
+ const parts = sources.map(() => {
982
+ return;
983
+ });
984
+ let rest = text;
985
+ let index = sources.length - 1;
986
+ for (;index > 0; index--) {
987
+ const source = sources[index];
988
+ const cut = rest.lastIndexOf(`
989
+
990
+ `);
991
+ const part = source === codeMode || cut < 0 ? undefined : parsers[source]?.(rest.slice(cut + 2));
992
+ if (!part)
993
+ break;
994
+ parts[index] = part;
995
+ rest = rest.slice(0, cut);
996
+ }
997
+ if (index === 0)
998
+ parts[0] = parsers[sources[0]]?.(rest);
999
+ else if (sources[0] === codeMode && startsWithFullCatalog(text))
1000
+ parts[0] = { full: true };
1001
+ return parts;
1002
+ }
1003
+ function rowParts(data) {
1004
+ const text = data.text ?? "";
1005
+ const metadata = data.metadata;
1006
+ if (typeof metadata === "object" && metadata !== null && "instructionSources" in metadata) {
1007
+ const keys = metadata.instructionSources;
1008
+ const sources = Array.isArray(keys) && keys.length > 0 && keys.every((key) => typeof key === "string") && new Set(keys).size === keys.length ? keys : [];
1009
+ return { sources, parts: splitRow(text, sources) };
1010
+ }
1011
+ const cut = text.lastIndexOf(`
1012
+
1013
+ `);
1014
+ const guidance = cut < 0 ? undefined : mcpPart(text.slice(cut + 2));
1015
+ if (guidance && wholeCatalog(text.slice(0, cut)))
1016
+ return { sources: [codeMode, mcp], parts: [{ full: true }, guidance] };
1017
+ if (wholeCatalog(text))
1018
+ return { sources: [codeMode], parts: [{ full: true }] };
1019
+ const alone = mcpPart(text);
1020
+ return alone ? { sources: [mcp], parts: [alone] } : { sources: [], parts: [] };
1021
+ }
1022
+ function joinedRuns(names) {
1023
+ const runs = [];
1024
+ for (let start = 0;start < names.length; start++)
1025
+ for (let end = start + 2;end <= names.length; end++)
1026
+ runs.push(names.slice(start, end).join(", "));
1027
+ return runs;
902
1028
  }
903
1029
  function supersededInstructionIDs(rows) {
904
- const covered = new Set;
1030
+ const parsed = rows.map((row) => rowParts(row.data));
1031
+ const named = new Set(parsed.flatMap(({ parts }) => parts.flatMap((part) => part?.entries ?? [])));
1032
+ for (const { parts } of parsed)
1033
+ parts.forEach((part, i) => {
1034
+ if (part?.removed && !(part.removed.every((name) => named.has(name)) && !joinedRuns(part.removed).some((name) => named.has(name))))
1035
+ parts[i] = undefined;
1036
+ });
1037
+ const restated = new Set;
1038
+ const mentioned = new Set;
905
1039
  const retired = new Set;
906
1040
  for (let index = rows.length - 1;index >= 0; index--) {
907
- const row = rows[index];
908
- const metadata = row.data.metadata;
909
- const keyed = typeof metadata === "object" && metadata !== null && "instructionSources" in metadata;
910
- const keys = keyed ? metadata.instructionSources : undefined;
911
- const text = row.data.text ?? "";
912
- const sources = keyed ? Array.isArray(keys) && keys.length > 0 && keys.every((key) => typeof key === "string") ? keys : [] : [codeMode, mcp].filter((source) => sourceState(text, source) !== undefined);
913
- const states = sources.map((source) => sourceState(text, source));
914
- if (sources.length > 0 && sources.every((source, i) => states[i] !== undefined && covered.has(source)))
915
- retired.add(row.id);
916
- sources.forEach((source, i) => {
917
- if (states[i] === "full")
918
- covered.add(source);
1041
+ const { sources, parts } = parsed[index];
1042
+ if (sources.length > 0 && parts.every((part, i) => {
1043
+ if (part === undefined)
1044
+ return false;
1045
+ const servers = mentions(part);
1046
+ return restated.has(sources[i]) || servers.length > 0 && servers.every((server) => mentioned.has(server));
1047
+ }))
1048
+ retired.add(rows[index].id);
1049
+ parts.forEach((part, i) => {
1050
+ if (part?.full)
1051
+ restated.add(sources[i]);
1052
+ for (const server of part ? mentions(part) : [])
1053
+ mentioned.add(server);
919
1054
  });
920
1055
  }
921
1056
  return retired;
@@ -923,6 +1058,7 @@ function supersededInstructionIDs(rows) {
923
1058
 
924
1059
  // src/v2/fold/instruction-supersession.ts
925
1060
  var namespace = "instructionSupersession";
1061
+ var coveredNamespace = "coveredInstructionSupersession";
926
1062
  function decode(value) {
927
1063
  if (value === undefined)
928
1064
  return new Set;
@@ -930,32 +1066,44 @@ function decode(value) {
930
1066
  throw new Error("Invalid instruction supersession replay state");
931
1067
  return new Set(value);
932
1068
  }
1069
+ var coveredOn = (value) => typeof value === "object" && value !== null && value.on === true;
933
1070
  function retiredLiveInstructionIDs(db, sessionID) {
934
1071
  return decode(readReplayEnvelope(db, sessionID)[namespace]);
935
1072
  }
936
- function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new Set) {
937
- const rows = messages.flatMap((message) => {
1073
+ function coveredInstructionSupersessionOn(db, sessionID) {
1074
+ return coveredOn(readReplayEnvelope(db, sessionID)[coveredNamespace]);
1075
+ }
1076
+ var coveredSupersessionEnabled = true;
1077
+ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new Set, covered = []) {
1078
+ const instructionRows = (list) => list.flatMap((message) => {
938
1079
  const row = hostInstructionRow(message.info);
939
1080
  return row ? [{ message, row }] : [];
940
1081
  });
1082
+ const coveredRows = coveredSupersessionEnabled ? instructionRows(covered) : [];
1083
+ const rows = [...coveredRows, ...instructionRows(messages)];
1084
+ const coveredMessages = new Set(coveredRows.map(({ message }) => message));
941
1085
  const retired = rows.length ? retiredLiveInstructionIDs(db, sessionID) : new Set;
1086
+ const coveredFollowed = rows.length > 0 && (coveredRows.length > 0 || permitted) && coveredInstructionSupersessionOn(db, sessionID);
1087
+ const switchCovered = permitted && rows.length > 0 && !coveredFollowed && coveredSupersessionEnabled;
942
1088
  const selected = permitted ? supersededInstructionIDs(rows.map(({ row }) => row)) : new Set;
943
1089
  const newlyRetired = new Set([...selected].filter((id) => !retired.has(id)));
944
1090
  const omitted = new Set([...retired, ...newlyRetired]);
1091
+ const omits = (message, id) => omitted.has(id) && (!coveredMessages.has(message) || coveredFollowed || switchCovered);
945
1092
  const edits = [];
946
1093
  for (const { message, row } of rows) {
947
- if (!omitted.has(row.id))
1094
+ if (!omits(message, row.id))
948
1095
  continue;
949
- if (newlyRetired.has(row.id) && message.parts.length > 0)
1096
+ const firstApplication = newlyRetired.has(row.id) || coveredMessages.has(message) && switchCovered;
1097
+ if (firstApplication && message.parts.length > 0)
950
1098
  edits.push(message);
951
1099
  message.parts = [];
952
1100
  }
953
1101
  return {
954
1102
  edits,
955
1103
  commit() {
956
- if (newlyRetired.size > 0 && !updateReplayDocument(db, sessionID, (doc) => {
1104
+ if ((newlyRetired.size > 0 || switchCovered) && !updateReplayDocument(db, sessionID, (doc) => {
957
1105
  const current = decode(doc[namespace]);
958
- if ([...newlyRetired].every((id) => current.has(id)))
1106
+ if ([...newlyRetired].every((id) => current.has(id)) && (!switchCovered || coveredOn(doc[coveredNamespace])))
959
1107
  return false;
960
1108
  for (const id of folded)
961
1109
  current.delete(id);
@@ -963,11 +1111,13 @@ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new
963
1111
  current.add(id);
964
1112
  doc.version = 2;
965
1113
  doc[namespace] = [...current];
1114
+ if (switchCovered)
1115
+ doc[coveredNamespace] = { on: true };
966
1116
  return true;
967
1117
  }))
968
1118
  throw new Error("Cannot persist instruction supersession");
969
1119
  for (const { message, row } of rows) {
970
- if (omitted.has(row.id))
1120
+ if (omits(message, row.id))
971
1121
  markRetiredInstructionRow(message.info);
972
1122
  }
973
1123
  }
@@ -1006,6 +1156,35 @@ import { randomUUID } from "node:crypto";
1006
1156
 
1007
1157
  // src/v2/fold/owner.ts
1008
1158
  import { createHash } from "node:crypto";
1159
+
1160
+ // src/v2/fold/summary.ts
1161
+ var RAW_HISTORY_ACCOUNT = "Magic Context retains the conversation as raw messages; no summarized history is available yet.";
1162
+ var CHECKPOINT_NOTE = "Magic Context added a compaction marker here to keep this OpenCode session fast. Your history is unchanged: Magic Context still keeps it and sends it to the model.";
1163
+ var CHECKPOINT_NOTES = Object.freeze([CHECKPOINT_NOTE]);
1164
+ function isCheckpointNote(value) {
1165
+ return typeof value === "string" && CHECKPOINT_NOTES.includes(value);
1166
+ }
1167
+ function hasFoldSummary(summary) {
1168
+ return typeof summary === "string" && summary.replace(/<[^>]*>/g, "").trim().length > 0;
1169
+ }
1170
+ function isHistoryHead(value) {
1171
+ return value !== RAW_HISTORY_ACCOUNT && !isCheckpointNote(value) && hasFoldSummary(value);
1172
+ }
1173
+ function withRecordedHead(checkpoint, submitted, head) {
1174
+ if (!isCheckpointNote(submitted) || head === undefined || head === submitted)
1175
+ return checkpoint;
1176
+ const copy = structuredClone(checkpoint);
1177
+ for (const part of copy.content)
1178
+ if (part.type === "text" && typeof part.text === "string")
1179
+ part.text = part.text.replace(`<summary>
1180
+ ${submitted}
1181
+ </summary>`, () => `<summary>
1182
+ ${head}
1183
+ </summary>`);
1184
+ return copy;
1185
+ }
1186
+
1187
+ // src/v2/fold/owner.ts
1009
1188
  var foldDigest = (value) => createHash("sha256").update(value).digest("hex");
1010
1189
 
1011
1190
  class FoldOwner {
@@ -1035,14 +1214,23 @@ class FoldOwner {
1035
1214
  return this.serial(args.sessionID, async () => {
1036
1215
  const previous = await this.read(args.sessionID);
1037
1216
  const same = previous && (args.runningCut !== undefined ? previous.cutSeq === args.runningCut : previous.cutSeq === undefined && previous.watermark === args.watermark);
1038
- if (same)
1217
+ if (same) {
1218
+ const id = args.checkpointID;
1219
+ if (id !== undefined && !previous.answered?.includes(id)) {
1220
+ previous.answered = [...previous.answered ?? [], id].slice(-8);
1221
+ await this.storage.set(this.key(args.sessionID), previous);
1222
+ }
1039
1223
  return previous;
1040
- const submitted = args.materialize();
1224
+ }
1225
+ const head = args.materialize();
1226
+ const submitted = args.checkpointText ?? head;
1041
1227
  const next = {
1042
1228
  watermark: args.watermark,
1043
1229
  cutSeq: args.runningCut,
1044
1230
  submitted,
1045
- submittedSha: foldDigest(submitted)
1231
+ submittedSha: foldDigest(submitted),
1232
+ ...submitted === head ? {} : { head },
1233
+ ...args.checkpointID === undefined ? {} : { answered: [args.checkpointID] }
1046
1234
  };
1047
1235
  await this.storage.set(this.key(args.sessionID), next);
1048
1236
  return next;
@@ -1051,8 +1239,12 @@ class FoldOwner {
1051
1239
  async observe(args) {
1052
1240
  return this.serial(args.sessionID, async () => {
1053
1241
  let state = await this.read(args.sessionID);
1054
- if (state?.rendered && state.rendered.id !== args.rendered.id)
1242
+ let carriedHead;
1243
+ if (state && (state.rendered ? state.rendered.id !== args.rendered.id : state.answered !== undefined && !state.answered.includes(args.rendered.id ?? ""))) {
1244
+ if (isCheckpointNote(args.summary) && state.answered?.includes(args.rendered.id ?? ""))
1245
+ carriedHead = state.head;
1055
1246
  state = undefined;
1247
+ }
1056
1248
  let changed = !state;
1057
1249
  const observedSha = foldDigest(JSON.stringify(args.rendered));
1058
1250
  const rendered = structuredClone(args.rendered);
@@ -1065,6 +1257,7 @@ class FoldOwner {
1065
1257
  watermark: args.cutSeq,
1066
1258
  submitted: args.summary,
1067
1259
  submittedSha: foldDigest(args.summary),
1260
+ ...carriedHead === undefined ? {} : { head: carriedHead },
1068
1261
  reason: "boot_recovery"
1069
1262
  };
1070
1263
  }
@@ -2893,6 +3086,7 @@ ${cached}
2893
3086
  }
2894
3087
  async supplyHeld(args) {
2895
3088
  const { draft, reader, summary } = args;
3089
+ const stored = args.checkpointText ?? summary;
2896
3090
  if (this.options.protocol === 3) {
2897
3091
  if (this.unprovenControls.has(draft.sessionID))
2898
3092
  return false;
@@ -2923,7 +3117,7 @@ ${cached}
2923
3117
  source: this.storage.sourceID,
2924
3118
  sessionID: draft.sessionID,
2925
3119
  admissionID: running.id,
2926
- summary
3120
+ summary: stored
2927
3121
  }));
2928
3122
  const value = {
2929
3123
  version: 3,
@@ -2932,7 +3126,7 @@ ${cached}
2932
3126
  sourceDigest: foldDigest(reader.hostIdentity()),
2933
3127
  sessionID: draft.sessionID,
2934
3128
  admissionID: running.id,
2935
- summaryDigest: foldDigest(summary),
3129
+ summaryDigest: foldDigest(stored),
2936
3130
  historyDigest: historyDigest(reader, draft.sessionID, running.seq - 1, replay.floor.after)
2937
3131
  }
2938
3132
  };
@@ -2984,7 +3178,7 @@ ${cached}
2984
3178
  source: this.storage.sourceID,
2985
3179
  sessionID: draft.sessionID,
2986
3180
  admissionID: running.id,
2987
- summary
3181
+ summary: stored
2988
3182
  }));
2989
3183
  return true;
2990
3184
  }
@@ -3020,7 +3214,7 @@ ${cached}
3020
3214
  source: this.storage.sourceID,
3021
3215
  sessionID: draft.sessionID,
3022
3216
  admissionID: id,
3023
- summary
3217
+ summary: stored
3024
3218
  };
3025
3219
  await this.storage.supply(draft.sessionID, id, JSON.stringify(snapshot));
3026
3220
  if (this.admissions) {
@@ -3028,7 +3222,7 @@ ${cached}
3028
3222
  sourceDigest: foldDigest(reader.hostIdentity()),
3029
3223
  sessionID: draft.sessionID,
3030
3224
  admissionID: id,
3031
- summaryDigest: foldDigest(summary),
3225
+ summaryDigest: foldDigest(stored),
3032
3226
  historyDigest: historyDigest(reader, draft.sessionID, (running?.seq ?? through) - 1)
3033
3227
  };
3034
3228
  const payload = JSON.stringify(provenance);
@@ -3119,7 +3313,7 @@ ${cached}
3119
3313
  await this.storage.saveTail(sessionID, JSON.stringify({
3120
3314
  model,
3121
3315
  sourceSeq: through,
3122
- baseline: tail?.baseline ?? cut.data.summary
3316
+ baseline: tail?.baseline ?? (isCheckpointNote(cut.data.summary) ? readSessionMeta(this.storage.db, sessionID).cachedM0Bytes?.toString("utf8") : cut.data.summary)
3123
3317
  }), []);
3124
3318
  this.loaded.set(sessionID, through);
3125
3319
  this.dirty.delete(sessionID);
@@ -3286,12 +3480,6 @@ class HostFoldPolicy {
3286
3480
  }
3287
3481
  }
3288
3482
 
3289
- // src/v2/fold/summary.ts
3290
- var RAW_HISTORY_ACCOUNT = "Magic Context retains the conversation as raw messages; no summarized history is available yet.";
3291
- function hasFoldSummary(summary) {
3292
- return typeof summary === "string" && summary.replace(/<[^>]*>/g, "").trim().length > 0;
3293
- }
3294
-
3295
3483
  // src/v2/fork-inheritance.ts
3296
3484
  var RAW_TYPES = new Set(RAW_MESSAGE_TYPES2);
3297
3485
  function forkBoundarySeq(origin, sequenceForId) {
@@ -5992,14 +6180,14 @@ function applyCheckpointHead(draft, head) {
5992
6180
  const first = draft.messages.find((message) => message.id === HEAD_IDS[0]);
5993
6181
  const baseline = first?.content.find((part) => part.type === "text")?.text;
5994
6182
  if (typeof baseline !== "string") {
5995
- draft.messages.unshift(checkpoint);
6183
+ draft.messages.unshift(withRecordedHead(checkpoint, submitted, head.head));
5996
6184
  return true;
5997
6185
  }
5998
6186
  for (const part of checkpoint.content)
5999
6187
  if (part.type === "text" && typeof part.text === "string") {
6000
6188
  part.text = part.text.replace(`<summary>
6001
6189
  ${submitted}
6002
- </summary>`, `<summary>
6190
+ </summary>`, () => `<summary>
6003
6191
  ${baseline}
6004
6192
  </summary>`);
6005
6193
  }
@@ -6009,24 +6197,46 @@ ${baseline}
6009
6197
  draft.messages.splice(0, draft.messages.length, checkpoint, ...draft.messages.filter((message) => message !== first));
6010
6198
  return true;
6011
6199
  }
6200
+ function servableCarrier(stored, head) {
6201
+ return !isCheckpointNote(stored) || head !== undefined;
6202
+ }
6012
6203
  function bindKeptInstructionCoordinates(messages, incoming, reader, sessionID) {
6013
6204
  const rows = reader.instructionRowsThrough(sessionID, reader.latestSequence(sessionID));
6014
6205
  let previous;
6015
6206
  let pending = [];
6207
+ const matches = (message, row) => message?.role === "system" && message.content.length === 1 && message.content[0]?.type === "text" && message.content[0].text === row?.data.text;
6016
6208
  const bind = (next) => {
6017
6209
  if (!pending.length)
6018
6210
  return;
6019
6211
  const candidates = rows.filter((row) => (previous === undefined || row.seq > previous) && (next === undefined || row.seq < next));
6020
6212
  const selected = previous === undefined ? candidates.slice(-pending.length) : next === undefined ? candidates.slice(0, pending.length) : candidates;
6021
- if (selected.length === pending.length && selected.every((row, index) => {
6022
- const message = pending[index];
6023
- return message?.role === "system" && message.content.length === 1 && message.content[0]?.type === "text" && message.content[0].text === row.data.text;
6024
- })) {
6213
+ if (selected.length === pending.length && selected.every((row, index) => matches(pending[index], row))) {
6025
6214
  selected.forEach((row, index) => {
6026
6215
  const message = pending[index];
6027
6216
  if (message)
6028
6217
  bindNativeRowID(message, row.id, row.seq);
6029
6218
  });
6219
+ } else {
6220
+ const earliest = [];
6221
+ let at = 0;
6222
+ for (const message of pending) {
6223
+ while (at < candidates.length && !matches(message, candidates[at]))
6224
+ at++;
6225
+ earliest.push(at++);
6226
+ }
6227
+ const latest = [];
6228
+ at = candidates.length - 1;
6229
+ for (let index = pending.length - 1;index >= 0; index--) {
6230
+ while (at >= 0 && !matches(pending[index], candidates[at]))
6231
+ at--;
6232
+ latest[index] = at--;
6233
+ }
6234
+ if (earliest.every((position) => position < candidates.length))
6235
+ pending.forEach((message, index) => {
6236
+ const row = candidates[earliest[index]];
6237
+ if (row && earliest[index] === latest[index])
6238
+ bindNativeRowID(message, row.id, row.seq);
6239
+ });
6030
6240
  }
6031
6241
  pending = [];
6032
6242
  };
@@ -6131,6 +6341,30 @@ function estimateCheckpointRequest(draft) {
6131
6341
  sessionId: draft.sessionID
6132
6342
  });
6133
6343
  }
6344
+ function estimateCheckpointFraming(draft, checkpoint, submitted) {
6345
+ const framing = structuredClone(checkpoint);
6346
+ for (const part of framing.content)
6347
+ if (part.type === "text" && typeof part.text === "string")
6348
+ part.text = part.text.replace(`<summary>
6349
+ ${submitted}
6350
+ </summary>`, `<summary>
6351
+
6352
+ </summary>`);
6353
+ try {
6354
+ const estimate = estimateFinalWireInputTokens({
6355
+ messages: adaptPayload({ ...draft, messages: [framing] }).messages,
6356
+ toolDefinitionTokens: 0,
6357
+ systemPromptTokens: 0,
6358
+ providerID: draft.model.providerID,
6359
+ modelID: draft.model.id,
6360
+ agentName: draft.agent,
6361
+ sessionId: draft.sessionID
6362
+ });
6363
+ return estimate.pressureTokens ?? estimate.tokens;
6364
+ } catch {
6365
+ return;
6366
+ }
6367
+ }
6134
6368
  var HIDDEN_SESSION_ERROR_GRACE_MS = 50;
6135
6369
  var STORE_POOL_DISPOSE_WAIT_MS = 1000;
6136
6370
  function isBlockingV2TransformError(error) {
@@ -6808,8 +7042,8 @@ async function registerContext(context) {
6808
7042
  servedModuleM0Text(sessionID),
6809
7043
  await nativeFoldReplay.baseline(sessionID),
6810
7044
  meta.cachedM0Bytes?.toString("utf8")
6811
- ].find((value) => value !== RAW_HISTORY_ACCOUNT && hasFoldSummary(value));
6812
- return !meta.isSubagent && summary !== RAW_HISTORY_ACCOUNT && hasFoldSummary(summary) && nativeFoldReplay.canFold(sessionID, reader);
7045
+ ].find(isHistoryHead);
7046
+ return !meta.isSubagent && isHistoryHead(summary) && nativeFoldReplay.canFold(sessionID, reader);
6813
7047
  },
6814
7048
  threshold: Number(process.env.MC_OC2_HOST_FOLD_ROWS ?? 1000),
6815
7049
  log: sessionLog2
@@ -7027,12 +7261,13 @@ async function registerContext(context) {
7027
7261
  const state = getOrCreateSessionMeta(storage.require(), draft.sessionID);
7028
7262
  const staged = manual && moduleBaseline == null ? stageManualBaseline(storage.require(), draft.sessionID, () => materialize(draft)) : undefined;
7029
7263
  const publishedHistory = Boolean(storage.require().prepare("SELECT 1 FROM compartments WHERE session_id = ? LIMIT 1").get(draft.sessionID));
7264
+ const owned = await folds.read(draft.sessionID);
7030
7265
  const candidate = [
7031
7266
  moduleBaseline,
7032
7267
  await nativeFoldReplay.baseline(draft.sessionID),
7033
7268
  state.cachedM0Bytes?.toString("utf8"),
7034
- (await folds.read(draft.sessionID))?.submitted
7035
- ].find((value) => value !== RAW_HISTORY_ACCOUNT && (publishedHistory && value?.includes("<session-history>") || hasFoldSummary(value)));
7269
+ owned?.head ?? owned?.submitted
7270
+ ].find((value) => value !== RAW_HISTORY_ACCOUNT && !isCheckpointNote(value) && (publishedHistory && value?.includes("<session-history>") || hasFoldSummary(value)));
7036
7271
  const manualHistory = manual && hasFoldSummary(staged?.summary ?? moduleBaseline);
7037
7272
  const summary = manualHistory ? staged?.summary ?? candidate ?? RAW_HISTORY_ACCOUNT : candidate ?? RAW_HISTORY_ACCOUNT;
7038
7273
  const manualReplay = manualHistory && summary ? await nativeFoldReplay.prepareManualFold(draft.sessionID, reader, staged ? staged.boundaryID : storage.require().prepare("SELECT cached_m0_last_baseline_end_message_id AS id FROM session_meta WHERE session_id = ?").get(draft.sessionID).id, summary) : undefined;
@@ -7041,6 +7276,7 @@ async function registerContext(context) {
7041
7276
  reader,
7042
7277
  previousCut: reader.latestCompaction(draft.sessionID),
7043
7278
  summary,
7279
+ checkpointText: CHECKPOINT_NOTE,
7044
7280
  manual: manualReplay ? { replay: manualReplay, commit: () => staged?.commit() } : undefined
7045
7281
  })) {
7046
7282
  if (manualHistory) {
@@ -7050,7 +7286,10 @@ async function registerContext(context) {
7050
7286
  historyRefreshSessions.add(draft.sessionID);
7051
7287
  requestPendingMaterialization(pendingMaterializationSessions, draft.sessionID, "host_compaction");
7052
7288
  }
7053
- draft.result = { summary, metadata: { keepID: undefined } };
7289
+ draft.result = {
7290
+ summary: CHECKPOINT_NOTE,
7291
+ metadata: { keepID: undefined }
7292
+ };
7054
7293
  return;
7055
7294
  }
7056
7295
  if (manual)
@@ -7069,7 +7308,9 @@ async function registerContext(context) {
7069
7308
  materialize: () => {
7070
7309
  const summary = moduleBaseline ?? materialize(draft);
7071
7310
  return hasFoldSummary(summary) ? summary : RAW_HISTORY_ACCOUNT;
7072
- }
7311
+ },
7312
+ checkpointText: CHECKPOINT_NOTE,
7313
+ checkpointID: running?.id
7073
7314
  });
7074
7315
  sessionLog2(draft.sessionID, `v2 compaction hook: fired answered=true source=${source}`);
7075
7316
  draft.result = { summary: fold.submitted, metadata: { keepID: undefined } };
@@ -7157,7 +7398,7 @@ async function registerContext(context) {
7157
7398
  onPassPermission: (sessionID, permission) => {
7158
7399
  checkpointPassPermissions.set(sessionID, permission);
7159
7400
  },
7160
- reclaimHostRows: (sessionID, messages, permitted) => reclaimInstructionRows(database, sessionID, messages, permitted, foldedInstructionIDs.get(sessionID)),
7401
+ reclaimHostRows: (sessionID, messages, permitted, covered) => reclaimInstructionRows(database, sessionID, messages, permitted, foldedInstructionIDs.get(sessionID), covered),
7161
7402
  compactionOff,
7162
7403
  storeGeneration: "v2",
7163
7404
  normalizeRestoredAssistantText: (text, providerID) => stripCopiedTagNotation(text, providerID === "anthropic"),
@@ -7510,6 +7751,7 @@ async function registerContext(context) {
7510
7751
  const reader = openStoreReader();
7511
7752
  let checkpoint;
7512
7753
  let submitted;
7754
+ let recordedHead;
7513
7755
  let upgradeCheckpointSequence;
7514
7756
  try {
7515
7757
  const candidates = syntheticCandidates(context, draft.sessionID, reader.syntheticMessageIDs(draft.sessionID));
@@ -7549,9 +7791,13 @@ async function registerContext(context) {
7549
7791
  requestPendingMaterialization(pendingMaterializationSessions, draft.sessionID, "host_compaction");
7550
7792
  }
7551
7793
  });
7552
- checkpoint = structuredClone(identity.rendered ?? carrier.rendered);
7553
- submitted = identity.renderedSummary ?? carrier.submitted;
7554
- upgradeCheckpointSequence = carrier.row.seq;
7794
+ const stored = identity.renderedSummary ?? carrier.submitted;
7795
+ if (servableCarrier(stored, identity.head)) {
7796
+ checkpoint = structuredClone(identity.rendered ?? carrier.rendered);
7797
+ submitted = stored;
7798
+ recordedHead = identity.head;
7799
+ upgradeCheckpointSequence = carrier.row.seq;
7800
+ }
7555
7801
  }
7556
7802
  }
7557
7803
  let nativeRestored = localCut ? nativeFoldReplay?.legacyUpgradeInput(draft.sessionID, draft.model) : undefined;
@@ -7588,8 +7834,13 @@ async function registerContext(context) {
7588
7834
  requestPendingMaterialization(pendingMaterializationSessions, draft.sessionID, "host_compaction");
7589
7835
  }
7590
7836
  });
7591
- checkpoint = structuredClone(identity.rendered ?? incoming);
7592
- submitted = identity.rendered ? identity.renderedSummary ?? identity.submitted : cut.data.summary ?? "";
7837
+ const stored = identity.rendered ? identity.renderedSummary ?? identity.submitted : cut.data.summary ?? "";
7838
+ if (servableCarrier(stored, identity.head)) {
7839
+ checkpoint = structuredClone(identity.rendered ?? incoming);
7840
+ submitted = stored;
7841
+ recordedHead = identity.head;
7842
+ } else
7843
+ sessionLog2(draft.sessionID, "v2 host fold: note checkpoint without a recorded head; serving restored history");
7593
7844
  }
7594
7845
  draft.messages.splice(0, draft.messages.length, ...await restoreAfterCheckpoint({
7595
7846
  db,
@@ -7629,11 +7880,15 @@ async function registerContext(context) {
7629
7880
  if (stripCheckpointRecentContext(projected, submitted)) {
7630
7881
  const estimate = estimateCheckpointRequest({
7631
7882
  ...draft,
7632
- messages: [checkpoint, ...draft.messages]
7883
+ messages: [
7884
+ withRecordedHead(checkpoint, submitted, recordedHead),
7885
+ ...draft.messages
7886
+ ]
7633
7887
  });
7634
7888
  checkpointInputEstimates.set(draft.sessionID, {
7635
7889
  tokens: estimate.tokens,
7636
- pressureTokens: estimate.pressureTokens ?? estimate.tokens
7890
+ pressureTokens: estimate.pressureTokens ?? estimate.tokens,
7891
+ hostAddedTokens: estimateCheckpointFraming(draft, projected, submitted)
7637
7892
  });
7638
7893
  }
7639
7894
  }
@@ -7679,7 +7934,11 @@ async function registerContext(context) {
7679
7934
  if (db) {
7680
7935
  await deliverPendingChannel2(context, db, draft.sessionID, channel1.get(draft.sessionID));
7681
7936
  }
7682
- const head = replayHead !== undefined ? replayHead : checkpoint && submitted !== undefined ? { checkpoint, submitted } : null;
7937
+ const head = replayHead !== undefined ? replayHead : checkpoint && submitted !== undefined ? {
7938
+ checkpoint,
7939
+ submitted,
7940
+ ...recordedHead === undefined ? {} : { head: recordedHead }
7941
+ } : null;
7683
7942
  const servedHead = head && structuredClone(head);
7684
7943
  const headApplied = head ? applyCheckpointHead(draft, head) : false;
7685
7944
  if (nativeMessages && (!checkpoint || upgradeCheckpointSequence !== undefined)) {