@retaw106/mmc-oc 2.3.0 → 2.5.0

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 (216) hide show
  1. package/dist/cli.js +12 -1
  2. package/dist/config/schema/magic-context.d.ts +33 -0
  3. package/dist/config/schema/magic-context.d.ts.map +1 -1
  4. package/dist/config-init.js +12 -1
  5. package/dist/{context-wt7g4f8k.js → context-xx09sh1g.js} +1985 -603
  6. package/dist/features/magic-context/memory-maintainer/launcher.d.ts +13 -4
  7. package/dist/features/magic-context/memory-maintainer/launcher.d.ts.map +1 -1
  8. package/dist/features/magic-context/memory-maintainer/manual-commands.d.ts.map +1 -1
  9. package/dist/features/magic-context/memory-maintainer/model-chain.d.ts +47 -0
  10. package/dist/features/magic-context/memory-maintainer/model-chain.d.ts.map +1 -0
  11. package/dist/features/magic-context/memory-maintainer/oc2-adapter.d.ts +17 -4
  12. package/dist/features/magic-context/memory-maintainer/oc2-adapter.d.ts.map +1 -1
  13. package/dist/features/magic-context/memory-maintainer/pipeline.d.ts +6 -0
  14. package/dist/features/magic-context/memory-maintainer/pipeline.d.ts.map +1 -1
  15. package/dist/features/magic-context/message-index-async.d.ts +6 -2
  16. package/dist/features/magic-context/message-index-async.d.ts.map +1 -1
  17. package/dist/features/magic-context/message-index.d.ts +5 -8
  18. package/dist/features/magic-context/message-index.d.ts.map +1 -1
  19. package/dist/features/magic-context/search.d.ts +5 -1
  20. package/dist/features/magic-context/search.d.ts.map +1 -1
  21. package/dist/features/magic-context/storage-db.d.ts +2 -0
  22. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  23. package/dist/features/magic-context/storage-host-instruction-retention.d.ts +4 -0
  24. package/dist/features/magic-context/storage-host-instruction-retention.d.ts.map +1 -0
  25. package/dist/features/magic-context/storage-meta-session.d.ts.map +1 -1
  26. package/dist/features/magic-context/storage-meta-shared.d.ts +2 -2
  27. package/dist/features/magic-context/storage-meta-shared.d.ts.map +1 -1
  28. package/dist/features/magic-context/storage-session-tables.d.ts +9 -1
  29. package/dist/features/magic-context/storage-session-tables.d.ts.map +1 -1
  30. package/dist/features/magic-context/storage-tags.d.ts +4 -0
  31. package/dist/features/magic-context/storage-tags.d.ts.map +1 -1
  32. package/dist/features/magic-context/transform-decision-log.d.ts +57 -2
  33. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  34. package/dist/hooks/magic-context/__fixtures__/tail-hygiene-refresh.d.ts +34 -0
  35. package/dist/hooks/magic-context/__fixtures__/tail-hygiene-refresh.d.ts.map +1 -0
  36. package/dist/hooks/magic-context/apply-operations.d.ts +3 -1
  37. package/dist/hooks/magic-context/apply-operations.d.ts.map +1 -1
  38. package/dist/hooks/magic-context/auto-search-hint.d.ts +3 -0
  39. package/dist/hooks/magic-context/auto-search-hint.d.ts.map +1 -1
  40. package/dist/hooks/magic-context/auto-search-runner.d.ts.map +1 -1
  41. package/dist/hooks/magic-context/channel2-delivery.d.ts.map +1 -1
  42. package/dist/hooks/magic-context/compartment-runner-historian.d.ts +2 -2
  43. package/dist/hooks/magic-context/compartment-runner-types.d.ts +2 -2
  44. package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
  45. package/dist/hooks/magic-context/compartment-runner-validation.d.ts.map +1 -1
  46. package/dist/hooks/magic-context/compartment-runner.d.ts +4 -0
  47. package/dist/hooks/magic-context/compartment-runner.d.ts.map +1 -1
  48. package/dist/hooks/magic-context/compartment-trigger-error.d.ts +11 -0
  49. package/dist/hooks/magic-context/compartment-trigger-error.d.ts.map +1 -0
  50. package/dist/hooks/magic-context/compartment-trigger.d.ts +1 -1
  51. package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
  52. package/dist/hooks/magic-context/ctx-reduce-nudge.d.ts +1 -0
  53. package/dist/hooks/magic-context/ctx-reduce-nudge.d.ts.map +1 -1
  54. package/dist/hooks/magic-context/degraded-pass-refusal.d.ts +2 -0
  55. package/dist/hooks/magic-context/degraded-pass-refusal.d.ts.map +1 -1
  56. package/dist/hooks/magic-context/diagnostic-log-state.d.ts +4 -0
  57. package/dist/hooks/magic-context/diagnostic-log-state.d.ts.map +1 -0
  58. package/dist/hooks/magic-context/edit-marker.d.ts +2 -0
  59. package/dist/hooks/magic-context/edit-marker.d.ts.map +1 -1
  60. package/dist/hooks/magic-context/emergency-drop.d.ts.map +1 -1
  61. package/dist/hooks/magic-context/file-token-coverage.d.ts +11 -0
  62. package/dist/hooks/magic-context/file-token-coverage.d.ts.map +1 -0
  63. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts +2 -0
  64. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts.map +1 -1
  65. package/dist/hooks/magic-context/hook-handlers.d.ts.map +1 -1
  66. package/dist/hooks/magic-context/host-served-rows.d.ts +10 -0
  67. package/dist/hooks/magic-context/host-served-rows.d.ts.map +1 -1
  68. package/dist/hooks/magic-context/inject-compartments.d.ts +1 -1
  69. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  70. package/dist/hooks/magic-context/lkg-recovery-fence.d.ts.map +1 -1
  71. package/dist/hooks/magic-context/lkg-replay.d.ts.map +1 -1
  72. package/dist/hooks/magic-context/lkg-slot.d.ts +1 -1
  73. package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
  74. package/dist/hooks/magic-context/nudge-evaluation-log.d.ts +3 -0
  75. package/dist/hooks/magic-context/nudge-evaluation-log.d.ts.map +1 -0
  76. package/dist/hooks/magic-context/pass-outcome.d.ts +2 -0
  77. package/dist/hooks/magic-context/pass-outcome.d.ts.map +1 -1
  78. package/dist/hooks/magic-context/pending-drop-eligibility.d.ts +14 -0
  79. package/dist/hooks/magic-context/pending-drop-eligibility.d.ts.map +1 -0
  80. package/dist/hooks/magic-context/pending-materialization.d.ts +2 -0
  81. package/dist/hooks/magic-context/pending-materialization.d.ts.map +1 -1
  82. package/dist/hooks/magic-context/protected-tail-boundary.d.ts +2 -0
  83. package/dist/hooks/magic-context/protected-tail-boundary.d.ts.map +1 -1
  84. package/dist/hooks/magic-context/provider-visible-parts.d.ts +10 -4
  85. package/dist/hooks/magic-context/provider-visible-parts.d.ts.map +1 -1
  86. package/dist/hooks/magic-context/read-session-chunk.d.ts.map +1 -1
  87. package/dist/hooks/magic-context/recomp-orchestrator.d.ts +3 -3
  88. package/dist/hooks/magic-context/recomp-orchestrator.d.ts.map +1 -1
  89. package/dist/hooks/magic-context/render-options.d.ts +19 -0
  90. package/dist/hooks/magic-context/render-options.d.ts.map +1 -0
  91. package/dist/hooks/magic-context/supersession-reclaim.d.ts +5 -3
  92. package/dist/hooks/magic-context/supersession-reclaim.d.ts.map +1 -1
  93. package/dist/hooks/magic-context/system-date-refresh.d.ts +3 -2
  94. package/dist/hooks/magic-context/system-date-refresh.d.ts.map +1 -1
  95. package/dist/hooks/magic-context/system-prompt-hash.d.ts.map +1 -1
  96. package/dist/hooks/magic-context/system-prompt-sticky-date.d.ts +4 -0
  97. package/dist/hooks/magic-context/system-prompt-sticky-date.d.ts.map +1 -0
  98. package/dist/hooks/magic-context/tag-content-primitives.d.ts +1 -1
  99. package/dist/hooks/magic-context/tag-content-primitives.d.ts.map +1 -1
  100. package/dist/hooks/magic-context/tag-messages.d.ts +15 -2
  101. package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
  102. package/dist/hooks/magic-context/tail-hygiene-output-count.d.ts +18 -0
  103. package/dist/hooks/magic-context/tail-hygiene-output-count.d.ts.map +1 -0
  104. package/dist/hooks/magic-context/tail-hygiene-walk.d.ts +8 -4
  105. package/dist/hooks/magic-context/tail-hygiene-walk.d.ts.map +1 -1
  106. package/dist/hooks/magic-context/text-complete.d.ts +1 -1
  107. package/dist/hooks/magic-context/text-complete.d.ts.map +1 -1
  108. package/dist/hooks/magic-context/todo-view.d.ts +2 -2
  109. package/dist/hooks/magic-context/tool-drop-target.d.ts +3 -2
  110. package/dist/hooks/magic-context/tool-drop-target.d.ts.map +1 -1
  111. package/dist/hooks/magic-context/tool-reclaim.d.ts +5 -2
  112. package/dist/hooks/magic-context/tool-reclaim.d.ts.map +1 -1
  113. package/dist/hooks/magic-context/transform-compartment-phase.d.ts +1 -0
  114. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  115. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +8 -0
  116. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  117. package/dist/hooks/magic-context/transform-stage-logger.d.ts +3 -0
  118. package/dist/hooks/magic-context/transform-stage-logger.d.ts.map +1 -1
  119. package/dist/hooks/magic-context/transform.d.ts +4 -9
  120. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  121. package/dist/hooks/magic-context/unresolved-history-boundary.d.ts +5 -1
  122. package/dist/hooks/magic-context/unresolved-history-boundary.d.ts.map +1 -1
  123. package/dist/{index-kw21z5pe.js → index-0d40b4q8.js} +17119 -16569
  124. package/dist/{index-z2w1eq3y.js → index-1vxffj5j.js} +558 -211
  125. package/dist/{index-z2g20msd.js → index-azbmnekv.js} +4 -4
  126. package/dist/{index-18yrysyj.js → index-bpjjcdy9.js} +1 -1
  127. package/dist/{index-a5mw0xp3.js → index-k25thxq7.js} +1 -1
  128. package/dist/{index-3gj1ak4c.js → index-mjf0p7yq.js} +1 -1
  129. package/dist/{index-czba8tw3.js → index-pte3cfs9.js} +226 -14
  130. package/dist/index.js +2 -2
  131. package/dist/{message-time-backfill-sykevdax.js → message-time-backfill-g9py24yt.js} +1 -1
  132. package/dist/model-resolution-cvyrrcjw.js +8 -0
  133. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  134. package/dist/plugin/subagent-tool-policy.d.ts +4 -0
  135. package/dist/plugin/subagent-tool-policy.d.ts.map +1 -1
  136. package/dist/{read-session-chunk-863d6c06.js → read-session-chunk-eb3fy45y.js} +3 -3
  137. package/dist/{recomp-orchestrator-wrjy3qym.js → recomp-orchestrator-mmpy5cb7.js} +6 -6
  138. package/dist/{send-session-notification-cz6ev088.js → send-session-notification-zpqs213d.js} +3 -3
  139. package/dist/shared/model-suggestion-retry.d.ts +23 -0
  140. package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
  141. package/dist/shared/prompt-surface-runtime.d.ts +5 -0
  142. package/dist/shared/prompt-surface-runtime.d.ts.map +1 -1
  143. package/dist/shared/reclaim-distance.d.ts +33 -0
  144. package/dist/shared/reclaim-distance.d.ts.map +1 -0
  145. package/dist/shared/rpc-discovery-cleanup.d.ts +3 -0
  146. package/dist/shared/rpc-discovery-cleanup.d.ts.map +1 -0
  147. package/dist/shared/rpc-server.d.ts +2 -0
  148. package/dist/shared/rpc-server.d.ts.map +1 -1
  149. package/dist/shared/search-text.d.ts +8 -0
  150. package/dist/shared/search-text.d.ts.map +1 -0
  151. package/dist/shared/sqlite.d.ts +8 -1
  152. package/dist/shared/sqlite.d.ts.map +1 -1
  153. package/dist/shared/stable-json.d.ts +7 -0
  154. package/dist/shared/stable-json.d.ts.map +1 -1
  155. package/dist/shared/storage-file-mutex.d.ts.map +1 -1
  156. package/dist/shared/system-directive.d.ts +2 -0
  157. package/dist/shared/system-directive.d.ts.map +1 -1
  158. package/dist/shared/tail-hygiene-json.d.ts +22 -0
  159. package/dist/shared/tail-hygiene-json.d.ts.map +1 -0
  160. package/dist/shared/user-facing-codes.d.ts +2 -2
  161. package/dist/v2/fold/native-replay.d.ts +11 -2
  162. package/dist/v2/fold/native-replay.d.ts.map +1 -1
  163. package/dist/v2/fold/policy.d.ts.map +1 -1
  164. package/dist/v2/fold/restore.d.ts.map +1 -1
  165. package/dist/v2/hidden-completion.d.ts +20 -1
  166. package/dist/v2/hidden-completion.d.ts.map +1 -1
  167. package/dist/v2/hooks/context.d.ts +1 -1
  168. package/dist/v2/hooks/context.d.ts.map +1 -1
  169. package/dist/v2/hooks/generate.d.ts +36 -1
  170. package/dist/v2/hooks/generate.d.ts.map +1 -1
  171. package/dist/v2/hooks/hidden-child.d.ts +22 -1
  172. package/dist/v2/hooks/hidden-child.d.ts.map +1 -1
  173. package/dist/v2/hooks/lkg-system.d.ts +35 -4
  174. package/dist/v2/hooks/lkg-system.d.ts.map +1 -1
  175. package/dist/v2/hooks/payload.d.ts +10 -1
  176. package/dist/v2/hooks/payload.d.ts.map +1 -1
  177. package/dist/v2/hooks/store.d.ts +2 -0
  178. package/dist/v2/hooks/store.d.ts.map +1 -1
  179. package/dist/v2/hooks/types.d.ts +12 -0
  180. package/dist/v2/hooks/types.d.ts.map +1 -1
  181. package/dist/v2/server.js +16272 -13742
  182. package/dist/v2/store-reader.d.ts +38 -1
  183. package/dist/v2/store-reader.d.ts.map +1 -1
  184. package/dist/web/main.js +262 -17
  185. package/dist/{wrapup-orchestrator-bmybc5p5.js → wrapup-orchestrator-jq589pgr.js} +6 -6
  186. package/package.json +1 -1
  187. package/src/config/latch-permanence-guard.test.ts +8 -0
  188. package/src/config/project-security.test.ts +17 -0
  189. package/src/config/schema/magic-context.test.ts +50 -0
  190. package/src/config/schema/magic-context.ts +34 -1
  191. package/src/shared/model-suggestion-retry.test.ts +52 -0
  192. package/src/shared/model-suggestion-retry.ts +13 -4
  193. package/src/shared/prompt-surface-runtime.ts +12 -0
  194. package/src/shared/reclaim-distance.test.ts +111 -0
  195. package/src/shared/reclaim-distance.ts +91 -0
  196. package/src/shared/root-async-context.probe.mjs +36 -0
  197. package/src/shared/root-async-context.test.ts +49 -0
  198. package/src/shared/rpc-discovery-cleanup.test.ts +125 -0
  199. package/src/shared/rpc-discovery-cleanup.ts +57 -0
  200. package/src/shared/rpc-server.ts +36 -13
  201. package/src/shared/search-text.test.ts +30 -0
  202. package/src/shared/search-text.ts +62 -0
  203. package/src/shared/sqlite-busy-budget-review.test.ts +291 -0
  204. package/src/shared/sqlite-foreground-wait.test.ts +237 -1
  205. package/src/shared/sqlite-turn-deadline.test.ts +286 -0
  206. package/src/shared/sqlite.ts +292 -23
  207. package/src/shared/stable-json.ts +56 -14
  208. package/src/shared/storage-file-mutex.test.ts +51 -2
  209. package/src/shared/storage-file-mutex.ts +11 -1
  210. package/src/shared/system-directive.test.ts +37 -0
  211. package/src/shared/system-directive.ts +19 -1
  212. package/src/shared/tag-transcript.ts +16 -4
  213. package/src/shared/tail-hygiene-json.test.ts +117 -0
  214. package/src/shared/tail-hygiene-json.ts +217 -0
  215. package/src/shared/user-facing-codes.ts +2 -2
  216. package/dist/model-resolution-wazv26n0.js +0 -6
@@ -5,5 +5,23 @@ export function isSystemDirective(text: string): boolean {
5
5
  }
6
6
 
7
7
  export function removeSystemReminders(text: string): string {
8
- return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/gi, "").trim();
8
+ return removeNestedBlocks(text, ["system-reminder"]).trim();
9
+ }
10
+
11
+ /** Remove matching tagged regions, including nested regions and regions with no closing tag. */
12
+ export function removeNestedBlocks(text: string, names: readonly string[]): string {
13
+ const tags = new RegExp(`<(/?)(${names.join("|")})(?:\\s[^<>]*?)?\\s*(/?)>`, "gi");
14
+ const stack: string[] = [];
15
+ let end = 0;
16
+ let result = "";
17
+ for (const match of text.matchAll(tags)) {
18
+ if (stack.length === 0) result += text.slice(end, match.index);
19
+ const name = match[2].toLowerCase();
20
+ if (match[1]) {
21
+ if (stack[stack.length - 1] === name) stack.pop();
22
+ } else if (!match[3]) stack.push(name);
23
+ end = match.index + match[0].length;
24
+ }
25
+ if (stack.length === 0) result += text.slice(end);
26
+ return result;
9
27
  }
@@ -835,12 +835,17 @@ class ConversationEndGuard {
835
835
  }
836
836
  }
837
837
 
838
- wouldStrand(occurrences: readonly ToolOccurrence[]): boolean {
838
+ wouldStrand(
839
+ occurrences: readonly ToolOccurrence[],
840
+ plannedRemovals?: ReadonlySet<unknown>,
841
+ ): boolean {
839
842
  const end = this.end;
840
843
  if (!end || !occurrences.some((occ) => occ.message === end)) return false;
841
844
  const leaving = new Set(occurrences.map((occ) => partKey(occ.part)));
842
845
  const survives = (part: TranscriptPart) =>
843
- !leaving.has(partKey(part)) && !this.removed.has(partKey(part));
846
+ !leaving.has(partKey(part)) &&
847
+ !this.removed.has(partKey(part)) &&
848
+ !plannedRemovals?.has(partKey(part));
844
849
  return end.info.role === "assistant"
845
850
  ? !end.parts.some((part) => part.kind === "tool_result" && survives(part))
846
851
  : !end.parts.some((part) => partHasContent(part) && survives(part));
@@ -1379,8 +1384,11 @@ function buildAggregateTarget(
1379
1384
  }
1380
1385
  return null;
1381
1386
  },
1382
- wouldStrandConversationEnd(): boolean {
1383
- return conversationEnd?.wouldStrand(occurrences) ?? false;
1387
+ wouldStrandConversationEnd(plannedRemovals): boolean {
1388
+ return conversationEnd?.wouldStrand(occurrences, plannedRemovals) ?? false;
1389
+ },
1390
+ notePlannedRemoval(plannedRemovals): void {
1391
+ for (const occ of occurrences) plannedRemovals.add(partKey(occ.part));
1384
1392
  },
1385
1393
  editMarker(): "truncated" | "absent" {
1386
1394
  // Edit-marker: preserve the tool_use input's filePath + a region
@@ -1443,6 +1451,10 @@ function buildTextTarget(
1443
1451
  return {
1444
1452
  mutationParts: [{ message: { info: message.info, parts: [] }, part }],
1445
1453
  textPrefix,
1454
+ canSetContent(content): boolean {
1455
+ const current = part.getText();
1456
+ return typeof current === "string" && current !== content;
1457
+ },
1446
1458
  setContent(content: string): boolean {
1447
1459
  return part.setText(content);
1448
1460
  },
@@ -0,0 +1,117 @@
1
+ import { expect, test } from "bun:test";
2
+ import { jsonHashSink, stableStringify, stableStringifyHash } from "./stable-json";
3
+ import { piJsonHash, TailHygieneJsonMemo } from "./tail-hygiene-json";
4
+
5
+ function hash(text: string): string {
6
+ const sink = jsonHashSink("excluded\0");
7
+ sink.write(text);
8
+ return sink.digest();
9
+ }
10
+
11
+ function piStringify(value: unknown): string {
12
+ const seen = new Set<object>();
13
+ try {
14
+ return (
15
+ JSON.stringify(value, (_key, current) => {
16
+ if (!current || typeof current !== "object" || Array.isArray(current))
17
+ return current;
18
+ if (seen.has(current)) return "[Circular]";
19
+ seen.add(current);
20
+ return Object.fromEntries(
21
+ Object.entries(current).sort(([a], [b]) => a.localeCompare(b)),
22
+ );
23
+ }) ?? ""
24
+ );
25
+ } catch {
26
+ return "";
27
+ }
28
+ }
29
+
30
+ test("streamed excluded fingerprints equal both original serializers on randomized values", () => {
31
+ let state = 704;
32
+ const random = (n: number): number => {
33
+ state = (Math.imul(state, 1664525) + 1013904223) | 0;
34
+ return (state >>> 0) % n;
35
+ };
36
+ const leaves = [
37
+ undefined,
38
+ null,
39
+ -0,
40
+ NaN,
41
+ Infinity,
42
+ 1e-7,
43
+ 1e23,
44
+ false,
45
+ "\ud800",
46
+ "é😀\n\u2028",
47
+ '"\\',
48
+ ];
49
+ const generate = (depth: number): unknown => {
50
+ if (!depth || random(3) === 0) return leaves[random(leaves.length)];
51
+ if (random(2)) {
52
+ const array = new Array(4);
53
+ array[0] = generate(depth - 1);
54
+ array[2] = undefined;
55
+ array[3] = generate(depth - 1);
56
+ return array;
57
+ }
58
+ const value: Record<string, unknown> = {};
59
+ const keys = ["10", "2", "Z", "ä", "a", "e\u0301", "é"];
60
+ for (let i = 0; i < 4; i++) value[keys[random(keys.length)]] = generate(depth - 1);
61
+ if (random(5) === 0) value.self = value;
62
+ return value;
63
+ };
64
+ const shared = { a: undefined, z: "shared" };
65
+ const cycle: unknown[] = [];
66
+ cycle.push(cycle);
67
+ const samples: unknown[] = [
68
+ cycle,
69
+ { a: shared, b: shared },
70
+ 1n,
71
+ new Date(0),
72
+ { toJSON: () => "date" },
73
+ ];
74
+ for (let i = 0; i < 2_000; i++) samples.push(generate(4));
75
+ for (const value of samples) {
76
+ try {
77
+ const expected = stableStringify(value);
78
+ expect(stableStringifyHash(value, "excluded\0")).toBe(hash(expected));
79
+ } catch {
80
+ expect(() => stableStringifyHash(value, "excluded\0")).toThrow();
81
+ }
82
+ expect(piJsonHash(value, () => piStringify(value))).toBe(hash(piStringify(value)));
83
+ }
84
+ console.log(`excluded fingerprint differential: ${samples.length} values per serializer`);
85
+ });
86
+
87
+ test("part memo catches in-place edits, alias changes, key order and accessor values", () => {
88
+ const memo = new TailHygieneJsonMemo();
89
+ let calls = 0;
90
+ const get = (value: unknown): string => {
91
+ memo.beginPass();
92
+ return memo.get("part", value, () => {
93
+ calls++;
94
+ return stableStringify(value);
95
+ });
96
+ };
97
+ const shared = { value: "first" };
98
+ const value = { a: shared, b: shared };
99
+ expect(get(value)).toBe(get(structuredClone(value)));
100
+ expect(calls).toBe(1);
101
+ shared.value = "other";
102
+ expect(get(value)).toContain("other");
103
+ expect(calls).toBe(2);
104
+ value.b = { value: "other" };
105
+ expect(get(value)).not.toContain("Circular");
106
+ expect(calls).toBe(3);
107
+ expect(get({ b: value.b, a: value.a })).toBe(get(value));
108
+ expect(calls).toBe(5);
109
+ let changing = 0;
110
+ const accessor = {
111
+ get value() {
112
+ return ++changing;
113
+ },
114
+ };
115
+ expect(get(accessor)).not.toBe(get(accessor));
116
+ expect(calls).toBe(7);
117
+ });
@@ -0,0 +1,217 @@
1
+ import { jsonHashSink } from "./stable-json";
2
+
3
+ const MAX_MEMO_BYTES = 64 * 1024 * 1024;
4
+ const MAX_MEMO_ENTRIES = 10_000;
5
+
6
+ /**
7
+ * A bounded, process-local memo for individual parts and selected tool fields.
8
+ * Detached snapshots catch in-place host edits; reference equality alone cannot.
9
+ * Key collisions between sessions only evict entries, never imply equality.
10
+ */
11
+ export class TailHygieneJsonMemo {
12
+ private entries = new Map<string, { snapshot: unknown; result: string; bytes: number }>();
13
+ private bytes = 0;
14
+ private passText = new WeakMap<object, string>();
15
+ private passHash = new WeakMap<object, string>();
16
+
17
+ beginPass(): void {
18
+ this.passText = new WeakMap();
19
+ this.passHash = new WeakMap();
20
+ }
21
+
22
+ get(key: string, value: unknown, compute: () => string, fingerprint = false): string {
23
+ const pass = fingerprint ? this.passHash : this.passText;
24
+ const object = value !== null && typeof value === "object" ? value : undefined;
25
+ const local = object ? pass.get(object) : undefined;
26
+ if (local !== undefined) return local;
27
+ const previous = this.entries.get(key);
28
+ if (previous && sameJson(previous.snapshot, value)) {
29
+ if (object) pass.set(object, previous.result);
30
+ return previous.result;
31
+ }
32
+ const result = compute();
33
+ if (previous) {
34
+ this.bytes -= previous.bytes;
35
+ this.entries.delete(key);
36
+ }
37
+ try {
38
+ const copy = copyJson(value);
39
+ const bytes = copy.bytes + (key.length + result.length) * 2;
40
+ if (bytes <= MAX_MEMO_BYTES) {
41
+ this.entries.set(key, { snapshot: copy.value, result, bytes });
42
+ this.bytes += bytes;
43
+ if (object) pass.set(object, result);
44
+ }
45
+ } catch {
46
+ // Accessors and exotic objects retain their original serialization behavior.
47
+ }
48
+ while (this.bytes > MAX_MEMO_BYTES || this.entries.size > MAX_MEMO_ENTRIES) {
49
+ const oldest = this.entries.entries().next().value;
50
+ if (!oldest) break;
51
+ this.bytes -= oldest[1].bytes;
52
+ this.entries.delete(oldest[0]);
53
+ }
54
+ return result;
55
+ }
56
+ }
57
+
58
+ function copyJson(value: unknown): { value: unknown; bytes: number } {
59
+ const seen = new Map<object, unknown>();
60
+ let bytes = 0;
61
+ const copy = (current: unknown): unknown => {
62
+ bytes += 16;
63
+ if (typeof current === "string") bytes += current.length * 2;
64
+ if (bytes > MAX_MEMO_BYTES) throw new Error("memo capacity");
65
+ if (current === null || typeof current !== "object") {
66
+ if (["function", "symbol", "bigint"].includes(typeof current))
67
+ throw new Error("exotic");
68
+ return current;
69
+ }
70
+ if (seen.has(current)) return seen.get(current);
71
+ const prototype = Object.getPrototypeOf(current);
72
+ if (!Array.isArray(current) && prototype !== Object.prototype && prototype !== null)
73
+ throw new Error("exotic");
74
+ const result = Array.isArray(current)
75
+ ? new Array(current.length)
76
+ : Object.create(prototype);
77
+ seen.set(current, result);
78
+ for (const key of Object.keys(current)) {
79
+ const descriptor = Object.getOwnPropertyDescriptor(current, key);
80
+ if (!descriptor || !("value" in descriptor)) throw new Error("accessor");
81
+ bytes += key.length * 2 + 16;
82
+ if (key === "__proto__") {
83
+ Object.defineProperty(result, key, {
84
+ value: copy(descriptor.value),
85
+ enumerable: true,
86
+ writable: true,
87
+ configurable: true,
88
+ });
89
+ } else result[key] = copy(descriptor.value);
90
+ }
91
+ return result;
92
+ };
93
+ return { value: copy(value), bytes };
94
+ }
95
+
96
+ function sameJson(before: unknown, after: unknown): boolean {
97
+ const forward = new Map<object, object>();
98
+ const reverse = new Set<object>();
99
+ const same = (left: unknown, right: unknown): boolean => {
100
+ if (
101
+ left === null ||
102
+ right === null ||
103
+ typeof left !== "object" ||
104
+ typeof right !== "object"
105
+ )
106
+ return Object.is(left, right);
107
+ if (forward.has(left)) return forward.get(left) === right;
108
+ if (reverse.has(right) || Object.getPrototypeOf(left) !== Object.getPrototypeOf(right))
109
+ return false;
110
+ forward.set(left, right);
111
+ reverse.add(right);
112
+ if (Array.isArray(left) && (!Array.isArray(right) || left.length !== right.length))
113
+ return false;
114
+ const keys = Object.keys(left);
115
+ const otherKeys = Object.keys(right);
116
+ if (keys.length !== otherKeys.length) return false;
117
+ for (let index = 0; index < keys.length; index++) {
118
+ const key = keys[index];
119
+ // Pi sorts with localeCompare, which can tie distinct Unicode spellings.
120
+ // Preserve insertion order too, because a tied sort keeps that order.
121
+ if (key !== otherKeys[index]) return false;
122
+ const descriptor = Object.getOwnPropertyDescriptor(right, key);
123
+ if (
124
+ !descriptor ||
125
+ !("value" in descriptor) ||
126
+ !same((left as Record<string, unknown>)[key], descriptor.value)
127
+ )
128
+ return false;
129
+ }
130
+ return true;
131
+ };
132
+ return same(before, after);
133
+ }
134
+
135
+ /**
136
+ * Fingerprint excluded Pi content without retaining its whole JSON string.
137
+ * Match Pi's native JSON replacer: localeCompare key order, omitted undefined
138
+ * object fields, null array holes, and a marker for repeated non-array objects.
139
+ * Unsupported objects and array cycles use the original serializer; serialization
140
+ * errors produce the fingerprint of an empty string, as they did before.
141
+ */
142
+ export function piJsonHash(value: unknown, fallback: () => string): string {
143
+ const sink = jsonHashSink("excluded\0");
144
+ try {
145
+ const seen = new Set<object>();
146
+ const arrays = new Set<object>();
147
+ const write = (current: unknown): void => {
148
+ if (current === null || typeof current !== "object") {
149
+ if (["function", "symbol", "bigint"].includes(typeof current))
150
+ throw new Error("exotic");
151
+ sink.write(JSON.stringify(current) ?? "");
152
+ } else if (Array.isArray(current)) {
153
+ if (
154
+ Object.getPrototypeOf(current) !== Array.prototype ||
155
+ Object.hasOwn(current, "toJSON")
156
+ )
157
+ throw new Error("exotic array");
158
+ if (arrays.has(current)) throw new Error("array cycle");
159
+ arrays.add(current);
160
+ sink.write("[");
161
+ for (let index = 0; index < current.length; index++) {
162
+ if (index) sink.write(",");
163
+ const descriptor = Object.getOwnPropertyDescriptor(current, index);
164
+ if (descriptor && !("value" in descriptor)) throw new Error("accessor");
165
+ if (!descriptor && index in current) throw new Error("inherited array element");
166
+ write(descriptor?.value === undefined ? null : descriptor.value);
167
+ }
168
+ sink.write("]");
169
+ arrays.delete(current);
170
+ } else if (seen.has(current)) {
171
+ sink.write('"[Circular]"');
172
+ } else {
173
+ const prototype = Object.getPrototypeOf(current);
174
+ if (prototype !== Object.prototype && prototype !== null) throw new Error("exotic");
175
+ seen.add(current);
176
+ const entries = Object.keys(current).map((key): [string, unknown] => {
177
+ const descriptor = Object.getOwnPropertyDescriptor(current, key);
178
+ if (!descriptor || !("value" in descriptor)) throw new Error("accessor");
179
+ return [key, descriptor.value];
180
+ });
181
+ const sorted = Object.fromEntries(entries.sort(([a], [b]) => a.localeCompare(b)));
182
+ if (
183
+ entries.length <= 16 &&
184
+ entries.every(
185
+ ([key, child]) =>
186
+ key.length <= 4096 &&
187
+ (child === null ||
188
+ child === undefined ||
189
+ typeof child === "number" ||
190
+ typeof child === "boolean" ||
191
+ (typeof child === "string" && child.length <= 4096)),
192
+ )
193
+ ) {
194
+ sink.write(JSON.stringify(sorted));
195
+ return;
196
+ }
197
+ sink.write("{");
198
+ let first = true;
199
+ for (const [key, child] of Object.entries(sorted)) {
200
+ if (child === undefined) continue;
201
+ if (!first) sink.write(",");
202
+ first = false;
203
+ sink.write(JSON.stringify(key));
204
+ sink.write(":");
205
+ write(child);
206
+ }
207
+ sink.write("}");
208
+ }
209
+ };
210
+ write(value);
211
+ return sink.digest();
212
+ } catch {
213
+ const failed = jsonHashSink("excluded\0");
214
+ failed.write(fallback());
215
+ return failed.digest();
216
+ }
217
+ }
@@ -18,8 +18,8 @@ export const USER_FACING_FAILURES = {
18
18
  history_boundary_unresolved: {
19
19
  code: "MC-H04",
20
20
  sentence:
21
- "This request was not sent: the message that marks where this session's history summary ends is missing from the OpenCode store, and without it the request is larger than the model's context window.",
22
- action: "Run /mmc-recomp to rebuild the history summary.",
21
+ "This request was not sent: Magic Context could not safely place the history summary boundary in the loaded conversation, and the untrimmed request is larger than the model's context window.",
22
+ action: "Reopen this session in its current project directory, then run /mmc-recomp to rebuild the history summary. A model with a larger context window can also help.",
23
23
  },
24
24
  history_over_window_unmanaged: {
25
25
  code: "MC-H06",
@@ -1,6 +0,0 @@
1
- import {
2
- resolveHistorianModel2
3
- } from "./index-z2g20msd.js";
4
- export {
5
- resolveHistorianModel2 as resolveHistorianModel
6
- };