solve-engine 2.3.0 → 2.4.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 (83) hide show
  1. package/dist/{Configuration-Culg8H_o.d.cts → Configuration-BGQn-cJ8.d.cts} +21 -0
  2. package/dist/{Configuration-Culg8H_o.d.ts → Configuration-BGQn-cJ8.d.ts} +21 -0
  3. package/dist/FormattingSettings-bRKjU7wI.d.cts +47 -0
  4. package/dist/FormattingSettings-bRKjU7wI.d.ts +47 -0
  5. package/dist/{PackageCompatibility-DbpyKYOe.d.ts → PackageCompatibility-UsSZIfHs.d.ts} +1 -1
  6. package/dist/{PackageCompatibility-CN-2CVhu.d.cts → PackageCompatibility-cEClSSkz.d.cts} +1 -1
  7. package/dist/{PackageRegistry-jqdAsm6U.d.ts → PackageRegistry-B3yJHSxX.d.ts} +1 -1
  8. package/dist/{PackageRegistry-DXsvmpQN.d.cts → PackageRegistry-BsLmAVZJ.d.cts} +1 -1
  9. package/dist/{chunk-PXWOATTF.js → chunk-5R7S5KJJ.js} +3 -3
  10. package/dist/{chunk-PXWOATTF.js.map → chunk-5R7S5KJJ.js.map} +1 -1
  11. package/dist/chunk-6ZNNPXXE.cjs +3 -0
  12. package/dist/chunk-6ZNNPXXE.cjs.map +1 -0
  13. package/dist/chunk-AR7L5OJ2.js +2 -0
  14. package/dist/chunk-AR7L5OJ2.js.map +1 -0
  15. package/dist/chunk-B5NBFGNP.js +3 -0
  16. package/dist/chunk-B5NBFGNP.js.map +1 -0
  17. package/dist/{chunk-PBGPQM3X.cjs → chunk-E2ZSMJEL.cjs} +3 -3
  18. package/dist/{chunk-PBGPQM3X.cjs.map → chunk-E2ZSMJEL.cjs.map} +1 -1
  19. package/dist/chunk-GALZNKW7.js +3 -0
  20. package/dist/chunk-GALZNKW7.js.map +1 -0
  21. package/dist/chunk-MMT2LS5I.cjs +2 -0
  22. package/dist/chunk-MMT2LS5I.cjs.map +1 -0
  23. package/dist/chunk-NAMMTJBE.cjs +3 -0
  24. package/dist/chunk-NAMMTJBE.cjs.map +1 -0
  25. package/dist/chunk-NXIMGB4S.cjs +2 -0
  26. package/dist/chunk-NXIMGB4S.cjs.map +1 -0
  27. package/dist/{chunk-NNYMXK6H.js → chunk-UA3BGOYT.js} +4 -4
  28. package/dist/chunk-UA3BGOYT.js.map +1 -0
  29. package/dist/chunk-UGQM6ZXU.js +2 -0
  30. package/dist/chunk-UGQM6ZXU.js.map +1 -0
  31. package/dist/{chunk-L7ZQQ773.cjs → chunk-WYAY6WPQ.cjs} +4 -4
  32. package/dist/chunk-WYAY6WPQ.cjs.map +1 -0
  33. package/dist/constants.cjs +1 -1
  34. package/dist/constants.d.cts +1 -1
  35. package/dist/constants.d.ts +1 -1
  36. package/dist/constants.js +1 -1
  37. package/dist/engine.cjs +1 -1
  38. package/dist/engine.d.cts +3 -3
  39. package/dist/engine.d.ts +3 -3
  40. package/dist/engine.js +1 -1
  41. package/dist/format.cjs +1 -1
  42. package/dist/format.d.cts +2 -2
  43. package/dist/format.d.ts +2 -2
  44. package/dist/format.js +1 -1
  45. package/dist/index.cjs +1 -1
  46. package/dist/index.d.cts +4 -4
  47. package/dist/index.d.ts +4 -4
  48. package/dist/index.js +1 -1
  49. package/dist/language.d.cts +3 -3
  50. package/dist/language.d.ts +3 -3
  51. package/dist/packages.cjs +1 -1
  52. package/dist/packages.d.cts +2 -2
  53. package/dist/packages.d.ts +2 -2
  54. package/dist/packages.js +1 -1
  55. package/dist/testing.cjs +2 -2
  56. package/dist/testing.d.cts +3 -3
  57. package/dist/testing.d.ts +3 -3
  58. package/dist/testing.js +1 -1
  59. package/dist/worker.cjs +2 -2
  60. package/dist/worker.d.cts +3 -3
  61. package/dist/worker.d.ts +3 -3
  62. package/dist/worker.js +1 -1
  63. package/package.json +1 -1
  64. package/dist/FormattingSettings-CJHyxcYu.d.cts +0 -27
  65. package/dist/FormattingSettings-CJHyxcYu.d.ts +0 -27
  66. package/dist/chunk-7BXPCWKM.cjs +0 -2
  67. package/dist/chunk-7BXPCWKM.cjs.map +0 -1
  68. package/dist/chunk-AIIPKVKO.js +0 -3
  69. package/dist/chunk-AIIPKVKO.js.map +0 -1
  70. package/dist/chunk-BAVZMGTZ.cjs +0 -2
  71. package/dist/chunk-BAVZMGTZ.cjs.map +0 -1
  72. package/dist/chunk-ESXQDRP7.js +0 -2
  73. package/dist/chunk-ESXQDRP7.js.map +0 -1
  74. package/dist/chunk-HLBYHXQD.cjs +0 -3
  75. package/dist/chunk-HLBYHXQD.cjs.map +0 -1
  76. package/dist/chunk-J4LZD4ZY.js +0 -3
  77. package/dist/chunk-J4LZD4ZY.js.map +0 -1
  78. package/dist/chunk-JFREB45J.cjs +0 -3
  79. package/dist/chunk-JFREB45J.cjs.map +0 -1
  80. package/dist/chunk-L7ZQQ773.cjs.map +0 -1
  81. package/dist/chunk-NNYMXK6H.js.map +0 -1
  82. package/dist/chunk-TN5E6JU6.js +0 -2
  83. package/dist/chunk-TN5E6JU6.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/engine/SegmentTree.ts","../src/engine/DocumentModel.ts","../src/engine/CompilationWorkerManager.ts","../src/engine/PageManager.ts","../src/engine/ThreeTierEvaluator.ts","../src/engine/evaluateDocument.ts"],"names":["SegmentTree","index","lineId","left","right","split","merge","createNode","midRight","mid","removed","startIndex","deleteCount","newIds","clampedStart","clampedCount","collectInOrder","newTree","buildTreap","lineIds","endIndex","clampedEnd","result","node","leftSize","targetStart","targetEnd","offset","nodeIndex","updateSize","collect","start","end","priority","pseudoRandom","seed","x","DocumentModel","maxLines","DEFAULT_CONFIG","text","countLines","ErrorFactory","rawLines","i","djb2Hash","id","changes","inserted","sorted","a","b","change","startIdx","removedIds","atLine","texts","startLine","endLine","lineNumber","newText","state","newHash","position","idx","pos","compiledAgainstHash","results","bytecodes","expressions","reads","writes","isVariableDef","inlineSolveCount","s","CompilationWorkerManager","engine_worker_default","event","data","pending","raw","err","items","worker","resolve","reject","doc","byLineId","batch","r","w","stored","opcodes","numbers","program","PAGE_SIZE","HOT_PAGE_RADIUS","WARM_PAGE_RADIUS","PRELOAD_PAGE_COUNT","COLD_EVICT_BUFFER","PageManager","_PageManager","pageNum","docLineCount","newViewport","viewport","viewportStartPage","viewportEndPage","lastPage","hotStart","hotEnd","warmStart","warmEnd","p","coldLeftEnd","coldLeftStart","coldRightStart","coldRightEnd","direction","pages","startPage","endPage","firstPreloadPage","range","expression","inlineSpans","sharedLexer","span","EvalTier","ThreeTierEvaluator","engine","checkpointer","sharedGlobalVariableStore","name","globalDagKey","signal","enableValueArena","lines","resultMap","tierCounts","docEnd","evalEnd","inViewport","lineResult","disableValueArena","startPos","_err","allWrites","lineNum","downstreamLineIds","writeVar","affected","names","baseResult","isEmptyLine","allResults","allBytecodes","allReads","hasVariableDef","lastValue","firstError","anyFailed","anyPending","value","entry","evaluated","e","errorMessage","v","errorValue","compileErr","EngineError","errReads","errWrites","bytecode","lastResult","targets","trimmed","errorMessageOf","evaluateDocument","input","_options","previousDocumentModel","evaluator","lineCount","errors","n","startPosition","endPosition","hasInlineSolves","inlineSolves","findInlineSolvesInLine","message"],"mappings":"iUA6CO,IAAMA,EAAN,KAAkB,CAAlB,cACN,IAAA,CAAQ,IAAA,CAAoB,MAK5B,IAAI,MAAA,EAAiB,CACpB,OAAO,KAAK,IAAA,CAAO,IAAA,CAAK,KAAK,IAAA,CAAO,CACrC,CAGA,IAAI,OAAA,EAAmB,CACtB,OAAO,KAAK,IAAA,GAAS,IACtB,CAOA,KAAA,CAAMC,CAAAA,CAAmC,CACxC,GAAI,EAAAA,CAAAA,CAAQ,CAAA,EAAKA,IAAU,IAAA,CAAK,IAAA,EAAM,MAAQ,CAAA,CAAA,CAAA,CAC9C,OAAO,KAAK,MAAA,CAAO,IAAA,CAAK,IAAA,CAAMA,CAAK,EAAE,MACtC,CAMA,SAASA,CAAAA,CAAeC,CAAAA,CAAsB,CAC7C,GAAM,CAACC,CAAAA,CAAMC,CA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CAAAA,CAAO,IAAA,CAAK,CAAA,KAAA,EAAQC,CAAC,CAAA,EAAA,EAAKR,EAAAA,CAAe5J,CAAM,CAAC,CAAA,CAAE,CAAA,CAAA,CAAA,CAIpDmH,CAAAA,CAAM,KAAK,CACV,UAAA,CAAYiD,CAAAA,CACZ,IAAA,CAAAlJ,CAAAA,CACA,aAAA,CAAAmJ,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,OAAA,CAAS/H,CAAAA,CAAM,OAAA,CACf,eAAA,CAAAgI,CAAAA,CACA,aAAAC,CAAAA,CACA,UAAA,CAAAlE,CAAAA,CAIA,KAAA,CAAO,IAAA,CACP,MAAA,CAAAtG,CACD,CAAC,EACF,CAEA,OAAO,CAAE,KAAA,CAAAmH,CAAAA,CAAO,UAAA,CAAY+C,CAAAA,CAAW,MAAA,CAAAC,CAAO,CAC/C,CAAA,OAAE,CAIDF,CAAAA,CAAU,eAAA,EAAgB,CAC1BrD,CAAAA,CAAO,gBAAA,CAAiBoD,CAAqB,EAC9C,CACD","file":"chunk-PXWOATTF.js","sourcesContent":["/**\n * SegmentTree, an order-statistic Treap (randomized BST).\n *\n * Replaces the flat `lineOrder: number[]` array in DocumentModel with a\n * balanced tree that supports O(log N) insert, delete, and get-at-index\n * operations. Each node stores a `lineId` and its subtree size, enabling\n * order-statistic queries (find the k-th element by position).\n *\n * Key operations:\n * getAt(index), O(log N) expected\n * insertAt(index), O(log N) expected\n * deleteAt(index), O(log N) expected\n * spliceAt(index, deleteCount, newIds), O(log N + deleteCount + insertCount)\n * indexOf(lineId), O(N) without reverse map; cached lazily in DocumentModel\n *\n * Implementation: Treap (Tree + Heap) with implicit keys.\n * Nodes are ordered by position (in-order traversal), not by lineId value.\n * The `size` field enables O(log N) order statistics.\n * Random priorities maintain balance with high probability (O(log N) depth).\n *\n * Memory: ~40 bytes per node (lineId + size + priority + left + right).\n * For 100K lines: ~4MB for tree structure (acceptable).\n */\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\ninterface Node {\n\tlineId: number;\n\t/** Total number of nodes in this subtree (including self). */\n\tsize: number;\n\t/** Random priority for heap property (maintains balance). */\n\tpriority: number;\n\tleft: Node | null;\n\tright: Node | null;\n}\n\n// ── SegmentTree ────────────────────────────────────────────────────────────\n\n/**\n * Maps document offsets to line numbers in logarithmic time.\n *\n * A document is edited constantly, and every edit shifts the offsets of every\n * line after it. Recomputing them linearly on each keystroke is what this\n * avoids.\n */\nexport class SegmentTree {\n\tprivate root: Node | null = null;\n\n\t// ── Public API ───────────────────────────────────────────────────────\n\n\t/** Total number of elements in the tree. */\n\tget length(): number {\n\t\treturn this.root ? this.root.size : 0;\n\t}\n\n\t/** Whether the tree is empty. */\n\tget isEmpty(): boolean {\n\t\treturn this.root === null;\n\t}\n\n\t/**\n\t * Get the lineId at the given 0-based index.\n\t * Returns undefined if index is out of bounds.\n\t * O(log N) expected.\n\t */\n\tgetAt(index: number): number | undefined {\n\t\tif (index < 0 || index >= (this.root?.size ?? 0)) return undefined;\n\t\treturn this.nodeAt(this.root, index).lineId;\n\t}\n\n\t/**\n\t * Insert a single lineId at the given 0-based index.\n\t * O(log N) expected.\n\t */\n\tinsertAt(index: number, lineId: number): void {\n\t\tconst [left, right] = split(this.root, index);\n\t\tthis.root = merge(merge(left, createNode(lineId)), right);\n\t}\n\n\t/**\n\t * Delete a single element at the given 0-based index.\n\t * Returns the removed lineId, or undefined if out of bounds.\n\t * O(log N) expected.\n\t */\n\tdeleteAt(index: number): number | undefined {\n\t\tif (index < 0 || index >= (this.root?.size ?? 0)) return undefined;\n\n\t\tconst [left, midRight] = split(this.root, index);\n\t\tconst [mid, right] = split(midRight, 1);\n\n\t\tconst removed = mid ? mid.lineId : undefined;\n\t\tthis.root = merge(left, right);\n\t\treturn removed;\n\t}\n\n\t/**\n\t * Bulk splice: delete `deleteCount` elements at `startIndex` (0-based),\n\t * then insert `newIds` in their place.\n\t *\n\t * Returns the removed lineId array.\n\t * O(log N + deleteCount + insertCount) expected.\n\t */\n\tspliceAt(\n\t\tstartIndex: number,\n\t\tdeleteCount: number,\n\t\tnewIds: number[]\n\t): number[] {\n\t\tconst clampedStart = Math.max(0, startIndex);\n\t\tconst clampedCount = Math.min(\n\t\t\tMath.max(0, deleteCount),\n\t\t\t(this.root?.size ?? 0) - clampedStart\n\t\t);\n\n\t\t// Split into three parts: [0, start) [start, start+count) [start+count, end)\n\t\tconst [left, midRight] = split(this.root, clampedStart);\n\t\tconst [mid, right] = split(midRight, clampedCount);\n\n\t\t// Collect removed IDs\n\t\tconst removed = collectInOrder(mid);\n\n\t\t// Build a treap from the new IDs and merge\n\t\tconst newTree = buildTreap(newIds, 0, newIds.length);\n\t\tthis.root = merge(merge(left, newTree), right);\n\n\t\treturn removed;\n\t}\n\n\t/**\n\t * Replace the entire tree with a new set of lineIds.\n\t * O(N), builds a balanced treap from a flat array.\n\t */\n\treplaceAll(lineIds: number[]): void {\n\t\tthis.root = buildTreap(lineIds, 0, lineIds.length);\n\t}\n\n\t/**\n\t * Get a contiguous range of lineIds by index.\n\t * O(rangeSize + log N), single in-order walk instead of N × O(log N).\n\t *\n\t * This is the hot path for viewport rendering in DocumentModel.getVisibleLines().\n\t */\n\tgetRange(startIndex: number, endIndex: number): number[] {\n\t\tconst clampedStart = Math.max(0, startIndex);\n\t\tconst clampedEnd = Math.min((this.root?.size ?? 0) - 1, endIndex);\n\t\tif (clampedStart > clampedEnd) return [];\n\n\t\tconst result: number[] = [];\n\t\tthis.collectRange(this.root, clampedStart, clampedEnd, 0, result);\n\t\treturn result;\n\t}\n\n\t/**\n\t * Clear the tree.\n\t */\n\tclear(): void {\n\t\tthis.root = null;\n\t}\n\n\t// ── Iteration ─────────────────────────────────────────────────────────\n\n\t/**\n\t * In-order iterator yielding all lineIds.\n\t */\n\t*[Symbol.iterator](): IterableIterator<number> {\n\t\tyield* this.inOrder(this.root);\n\t}\n\n\tprivate *inOrder(node: Node | null): IterableIterator<number> {\n\t\tif (!node) return;\n\t\tyield* this.inOrder(node.left);\n\t\tyield node.lineId;\n\t\tyield* this.inOrder(node.right);\n\t}\n\n\t// ── Private helpers ───────────────────────────────────────────────────\n\n\tprivate nodeAt(node: Node | null, index: number): Node {\n\t\t// This is only called with valid indices, so node is non-null\n\t\tconst leftSize = node!.left ? node!.left.size : 0;\n\n\t\tif (index < leftSize) {\n\t\t\treturn this.nodeAt(node!.left, index);\n\t\t} else if (index === leftSize) {\n\t\t\treturn node!;\n\t\t} else {\n\t\t\treturn this.nodeAt(node!.right, index - leftSize - 1);\n\t\t}\n\t}\n\n\t/**\n\t * Collect all node values in the range [targetStart, targetEnd] into result.\n\t * `offset` is the 0-based start of the current subtree within the full tree.\n\t * O(rangeSize + log N), skips entire subtrees outside the target range.\n\t */\n\tprivate collectRange(\n\t\tnode: Node | null,\n\t\ttargetStart: number,\n\t\ttargetEnd: number,\n\t\toffset: number,\n\t\tresult: number[]\n\t): void {\n\t\tif (!node) return;\n\n\t\tconst leftSize = node.left ? node.left.size : 0;\n\t\tconst nodeIndex = offset + leftSize;\n\n\t\t// Traverse left subtree if it overlaps the target range\n\t\tif (nodeIndex > targetStart && node.left) {\n\t\t\tthis.collectRange(node.left, targetStart, targetEnd, offset, result);\n\t\t}\n\n\t\t// Include this node if within range\n\t\tif (nodeIndex >= targetStart && nodeIndex <= targetEnd) {\n\t\t\tresult.push(node.lineId);\n\t\t}\n\n\t\t// Traverse right subtree if it overlaps the target range\n\t\tif (nodeIndex < targetEnd && node.right) {\n\t\t\tthis.collectRange(node.right, targetStart, targetEnd, nodeIndex + 1, result);\n\t\t}\n\t}\n}\n\n// ── Free functions ──────────────────────────────────────────────────────────\n\n/** Create a new treap node. */\nfunction createNode(lineId: number): Node {\n\treturn {\n\t\tlineId,\n\t\tsize: 1,\n\t\tpriority: Math.random(),\n\t\tleft: null,\n\t\tright: null,\n\t};\n}\n\n/** Update a node's size from its children. */\nfunction updateSize(node: Node): void {\n\tnode.size = 1 + (node.left ? node.left.size : 0) + (node.right ? node.right.size : 0);\n}\n\n/**\n * Merge two treaps. All keys in `left` must be ≤ all keys in `right`.\n * O(log N) expected.\n */\nfunction merge(left: Node | null, right: Node | null): Node | null {\n\tif (!left) return right;\n\tif (!right) return left;\n\n\tif (left.priority > right.priority) {\n\t\tleft.right = merge(left.right, right);\n\t\tupdateSize(left);\n\t\treturn left;\n\t} else {\n\t\tright.left = merge(left, right.left);\n\t\tupdateSize(right);\n\t\treturn right;\n\t}\n}\n\n/**\n * Split a treap at `index` (0-based).\n * Returns [left, right] where `left` contains the first `index` elements\n * and `right` contains the rest.\n * O(log N) expected.\n */\nfunction split(\n\tnode: Node | null,\n\tindex: number\n): [Node | null, Node | null] {\n\tif (!node) return [null, null];\n\n\tconst leftSize = node.left ? node.left.size : 0;\n\n\tif (index <= leftSize) {\n\t\tconst [left, right] = split(node.left, index);\n\t\tnode.left = right;\n\t\tupdateSize(node);\n\t\treturn [left, node];\n\t} else {\n\t\tconst [left, right] = split(node.right, index - leftSize - 1);\n\t\tnode.right = left;\n\t\tupdateSize(node);\n\t\treturn [node, right];\n\t}\n}\n\n/**\n * Collect all lineIds from a treap in-order.\n * O(N).\n */\nfunction collectInOrder(node: Node | null): number[] {\n\tconst result: number[] = [];\n\tcollect(node, result);\n\treturn result;\n}\n\nfunction collect(node: Node | null, result: number[]): void {\n\tif (!node) return;\n\tcollect(node.left, result);\n\tresult.push(node.lineId);\n\tcollect(node.right, result);\n}\n\n/**\n * Build a balanced treap from a flat array of lineIds.\n * Uses divide-and-conquer with pre-sorted priorities to produce\n * a heap-ordered tree in O(N) time.\n * O(N).\n */\nfunction buildTreap(lineIds: number[], start: number, end: number): Node | null {\n\tif (start >= end) return null;\n\n\tconst mid = Math.floor((start + end) / 2);\n\n\t// Generate a deterministic-but-random priority based on position\n\t// This ensures the same array always produces the same tree shape\n\tconst priority = pseudoRandom(mid);\n\n\tconst node: Node = {\n\t\tlineId: lineIds[mid],\n\t\tsize: end - start,\n\t\tpriority,\n\t\tleft: buildTreap(lineIds, start, mid),\n\t\tright: buildTreap(lineIds, mid + 1, end),\n\t};\n\n\treturn node;\n}\n\n/**\n * Simple pseudo-random number generator for deterministic treap building.\n * Uses a multiplicative hash of the input.\n */\nfunction pseudoRandom(seed: number): number {\n\tlet x = seed;\n\tx = ((x >> 16) ^ x) * 0x45d9f3b;\n\tx = ((x >> 16) ^ x) * 0x45d9f3b;\n\tx = (x >> 16) ^ x;\n\treturn x / 0xffffffff; // normalize to [0, 1)\n}\n","import { Value } from \"@solve-js/vm/Value\";\nimport { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { djb2Hash } from \"@solve-js/utilities/Hash\";\nimport { SegmentTree } from \"@solve-js/engine/SegmentTree\";\nimport { DEFAULT_CONFIG } from \"@solve-js/constants/Configuration\";\nimport { countLines } from \"@solve-js/utilities/Strings\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n// ── LineState ──────────────────────────────────────────────────────────────\n\n/**\n * Persistent per-line state tracked by the DocumentModel.\n *\n * Each line receives an immutable `lineId` that survives structural edits\n * (insertions, deletions, line shifts). This allows caches, the dependency\n * graph, and VM checkpoints to reference lines by ID instead of by volatile\n * line numbers.\n *\n * ── Multi-expression support ─────────────────────────────────────────\n * A single document line may contain multiple inline solves (`s\\`...\\``).\n * To support this without breaking the 1:1 line-to-DAG-node contract:\n * - `expressions[]` holds all extracted expression strings (1 entry for\n * full-line expressions, N entries for N inline solves).\n * - `bytecodes[]` holds compiled bytecode in corresponding order.\n * - `results[]` holds evaluation **result groups** in corresponding order.\n * Each element is a `Value[]`, a group of Values produced by that expression.\n * For variable definitions, the group always has exactly 1 element.\n * For multi-output expressions (e.g., currency conversion), the group\n * may have multiple Values (one per target unit).\n * - `reads[]` and `writes[]` are aggregated across ALL expressions on\n * the line, the DAG treats the line as a single dependency node.\n * - `inlineSolveCount` is 0 for full-line expressions, >0 for inline solves.\n */\nexport interface LineState {\n\t/** Immutable unique identifier, survives all structural edits. */\n\treadonly lineId: number;\n\n\t/** djb2 hash of the line text, used for O(1) change detection. */\n\ttextHash: number;\n\n\t/** The full line text (may include markdown). */\n\ttext: string;\n\n\t/**\n\t * Extracted expression texts.\n\t * - Full-line expressions: one entry (the trimmed text).\n\t * - Inline solve lines: one entry per `s\\`...\\`` span, in left-to-right order.\n\t * - Markdown-only lines: empty array.\n\t */\n\texpressions: string[];\n\n\t/**\n\t * Compiled bytecode for each expression, in corresponding order.\n\t * Parallel to {@link expressions}.\n\t */\n\tbytecodes: BytecodeProgram[];\n\n\t/** Variables this line reads (for dependency tracking). Aggregated across all expressions. */\n\treads: string[];\n\n\t/** Variables this line writes (empty if not a variable definition). Aggregated across all expressions. */\n\twrites: string[];\n\n\t/**\n\t * Evaluation result groups for each expression, in corresponding order.\n\t * Each `Value[]` is a group of Values produced by one expression.\n\t * Variable definitions always produce exactly 1 Value per group.\n\t * Multi-output expressions (e.g. currency conversion) may produce N Values.\n\t */\n\tresults: Value[][];\n\n\t/**\n\t * Convenience accessor for the first expression's first result.\n\t * Equals `results[0]?.[0] ?? null`. For single-expression lines,\n\t * this is the primary result. For multi-expression (inline solve) lines,\n\t * prefer accessing `results[i][j]` directly.\n\t */\n\tresult: Value | null;\n\n\t/** True if this line needs re-evaluation. */\n\tdirty: boolean;\n\n\t/** True if any expression on this line defines a variable (never evict bytecode). */\n\tisVariableDef: boolean;\n\n\t/** True if this line contains only markdown (no evaluable expression). */\n\tisEmpty: boolean;\n\n\t/**\n\t * Number of inline solve expressions on this line.\n\t * 0 = full-line expression (or markdown-only).\n\t * >0 = N inline solves embedded in markdown text.\n\t */\n\tinlineSolveCount: number;\n}\n\n// ── ViewportRange ──────────────────────────────────────────────────────────\n\n/** The visible line range, used to decide which lines are evaluated eagerly. */\nexport interface ViewportRange {\n\tstartLine: number; // 1-based, inclusive\n\tendLine: number; // 1-based, inclusive\n}\n\n// ── LineChange ─────────────────────────────────────────────────────────────\n\n/** Describes a structural change to the document's line list. */\nexport interface LineChange {\n\t/** 1-based line number where the change starts. */\n\tstartLine: number;\n\t/** Number of lines deleted (0 for pure insertion). */\n\tdeleteCount: number;\n\t/** New line texts inserted in place of deleted lines. */\n\tinsertLines: string[];\n}\n\n// ── ApplyChangesResult ─────────────────────────────────────────────────────\n\n/** Result of applying changes to the document model. */\nexport interface ApplyChangesResult {\n\t/** Line IDs of newly inserted lines. */\n\tinserted: number[];\n\t/** Line IDs that were removed. */\n\tremoved: number[];\n}\n\n// ── DocumentModel ──────────────────────────────────────────────────────────\n\n/**\n * Persistent document model with O(log N) line lookups and structural edits.\n *\n * Design:\n * - Each line has an immutable `lineId` (monotonically increasing counter).\n * - `LineState` objects are stored in a `Map<lineId, LineState>` for O(1) access.\n * - Line ordering is maintained in a `SegmentTree` (order-statistic Treap) that\n * supports O(log N) insert, delete, and get-at-index operations.\n * - A lazy position cache (`Map<lineId, number>`) provides O(1) position lookups\n * after the first `getLinePosition()` call and is invalidated on structural edits.\n *\n * Key invariant: line IDs never change, only their positions in the order tree.\n * This means cached bytecode, dependency graph entries, and VM checkpoints\n * keyed by lineId remain valid across all structural edits.\n */\nexport class DocumentModel {\n\t/** Persistent line ID → LineState. */\n\tprivate lines: Map<number, LineState> = new Map();\n\n\t/** Order-statistic treap representing the current document line order. */\n\tprivate orderTree: SegmentTree = new SegmentTree();\n\n\t/** Monotonically increasing counter for new line IDs. */\n\tprivate nextLineId: number = 1;\n\n\t/**\n\t * Lazy position cache: lineId → 1-based position.\n\t * Built on first `getLinePosition()` call, invalidated on structural edits.\n\t */\n\tprivate _positionCache: Map<number, number> | null = null;\n\n\t/**\n\t * Line IDs currently marked dirty, maintained alongside every\n\t * `state.dirty` mutation (in this class and in every other module that\n\t * holds a direct `LineState` reference: ThreeTierEvaluator, PageManager).\n\t * Lets {@link hasAnyDirtyLineBefore} answer \"is anything before position\n\t * X dirty\" in O(d log N), d = current dirty count, typically tiny once\n\t * a document has settled after its initial evaluation, instead of\n\t * O(N log N), which used to mean every scroll event re-walked the WHOLE\n\t * document via `getLineAt()` regardless of how little of it was actually\n\t * dirty. Benchmarked: ~10.6ms per setViewport() call scrolled near the\n\t * bottom of a 20k-line document before this fix.\n\t */\n\tprivate dirtyLineIds: Set<number> = new Set();\n\n\t/**\n\t * Most lines this model will hold. See `constants/Configuration.ts`'s\n\t * `performance.maxDocumentLines`, which is where the default comes from and\n\t * which a host raises through its engine config; a host that builds a\n\t * DocumentModel directly passes it here instead.\n\t */\n\tprivate readonly maxLines: number;\n\n\t/**\n\t * @param maxLines - Ceiling on the line count, defaulting to the engine's\n\t * configured one. Every line costs a LineState with six arrays in it\n\t * whatever the line says, so the cost of a document is its line count and\n\t * nothing else bounds it: two hundred thousand lines of `1 + 1` exhausted\n\t * the heap here, before a single expression had been looked at.\n\t */\n\tconstructor(maxLines: number = DEFAULT_CONFIG.performance.maxDocumentLines) {\n\t\tthis.maxLines = maxLines;\n\t}\n\n\t// ── Initialization ──────────────────────────────────────────────────\n\n\t/**\n\t * Initialize or replace the entire document from a text blob.\n\t * Clears all existing state and assigns new persistent line IDs.\n\t *\n\t * @throws `DOCUMENT_TOO_LARGE` for a document past {@link maxLines}, before\n\t * any of it is stored. Recoverable: nothing has been replaced yet, so the\n\t * model still holds whatever it held.\n\t */\n\tsetDocument(text: string): void {\n\t\t// Counted before anything is cleared, so a refused document leaves the\n\t\t// previous one intact rather than half-replaced.\n\t\tconst lineCount = countLines(text, this.maxLines);\n\t\tif (lineCount > this.maxLines) {\n\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\"DOCUMENT_TOO_LARGE\",\n\t\t\t\t`This document has more than ${this.maxLines.toLocaleString(\"en-US\")} lines, which is the most the engine will hold at once`,\n\t\t\t\t{ maxLines: this.maxLines },\n\t\t\t);\n\t\t}\n\t\tthis.lines.clear();\n\t\tthis.orderTree.clear();\n\t\tthis._positionCache = null;\n\t\tthis.dirtyLineIds.clear();\n\t\tthis.nextLineId = 1;\n\n\t\tconst rawLines = text.split(\"\\n\");\n\t\tconst lineIds = new Array<number>(rawLines.length);\n\n\t\tfor (let i = 0; i < rawLines.length; i++) {\n\t\t\tconst lineId = this.nextLineId++;\n\t\t\tlineIds[i] = lineId;\n\t\t\tthis.lines.set(lineId, {\n\t\t\t\tlineId,\n\t\t\t\ttextHash: djb2Hash(rawLines[i]),\n\t\t\t\ttext: rawLines[i],\n\t\t\t\texpressions: [],\n\t\t\t\tbytecodes: [],\n\t\t\t\treads: [],\n\t\t\t\twrites: [],\n\t\t\t\tresults: [],\n\t\t\t\tresult: null,\n\t\t\t\tdirty: true,\n\t\t\t\tisVariableDef: false,\n\t\t\t\tisEmpty: rawLines[i].trim().length === 0,\n\t\t\t\tinlineSolveCount: 0,\n\t\t\t});\n\t\t}\n\n\t\t// O(N) balanced treap build from flat array\n\t\tthis.orderTree.replaceAll(lineIds);\n\n\t\t// Every line starts dirty (see the object literal above), seed the\n\t\t// tracking set to match. This is the one place the set is legitimately\n\t\t// O(N): a fresh document needs full evaluation anyway.\n\t\tfor (const id of lineIds) this.dirtyLineIds.add(id);\n\t}\n\n\t// ── Structural edits ────────────────────────────────────────────────\n\n\t/**\n\t * Apply one or more line-level changes to the document.\n\t *\n\t * **Precondition:** Changes must be **non-overlapping** in their line ranges.\n\t * If two changes target the same or adjacent lines, the reverse-order\n\t * processing may produce incorrect results because the first-applied\n\t * change shifts the line numbers that the second change references.\n\t *\n\t * Changes are applied in **reverse order** (highest startLine first) so\n\t * that earlier changes in the document don't shift the indices of later\n\t * changes during processing.\n\t *\n\t * Returns both the newly inserted line IDs and the removed line IDs.\n\t * Callers should use `removed` to clean up the dependency graph and\n\t * other data structures keyed by lineId.\n\t */\n\tapplyChanges(changes: LineChange[]): ApplyChangesResult {\n\t\tconst inserted: number[] = [];\n\t\tconst removed: number[] = [];\n\n\t\t// Sort descending by startLine so earlier changes don't shift later indices\n\t\tconst sorted = [...changes].sort((a, b) => b.startLine - a.startLine);\n\n\t\tfor (const change of sorted) {\n\t\t\tconst startIdx = change.startLine - 1; // convert to 0-based\n\n\t\t\t// Create new LineState entries for inserted lines\n\t\t\tconst newIds: number[] = [];\n\t\t\tfor (const text of change.insertLines) {\n\t\t\t\tconst lineId = this.nextLineId++;\n\t\t\t\tnewIds.push(lineId);\n\t\t\t\tinserted.push(lineId);\n\t\t\t\tthis.lines.set(lineId, {\n\t\t\t\t\tlineId,\n\t\t\t\t\ttextHash: djb2Hash(text),\n\t\t\t\t\ttext,\n\t\t\t\t\texpressions: [],\n\t\t\t\t\tbytecodes: [],\n\t\t\t\t\treads: [],\n\t\t\t\t\twrites: [],\n\t\t\t\t\tresults: [],\n\t\t\t\t\tresult: null,\n\t\t\t\t\tdirty: true,\n\t\t\t\t\tisVariableDef: false,\n\t\t\t\t\tisEmpty: text.trim().length === 0,\n\t\t\t\t\tinlineSolveCount: 0,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// New lines start dirty (see the object literal above), track them.\n\t\t\tfor (const id of newIds) this.dirtyLineIds.add(id);\n\n\t\t\t// O(log N) splice: delete old IDs, insert new IDs\n\t\t\tconst removedIds = this.orderTree.spliceAt(\n\t\t\t\tstartIdx,\n\t\t\t\tchange.deleteCount,\n\t\t\t\tnewIds\n\t\t\t);\n\t\t\tfor (const id of removedIds) {\n\t\t\t\tremoved.push(id);\n\t\t\t\tthis.lines.delete(id);\n\t\t\t\tthis.dirtyLineIds.delete(id);\n\t\t\t}\n\t\t}\n\n\t\t// Invalidate position cache, positions shifted for all lines\n\t\tthis._positionCache = null;\n\n\t\treturn { inserted, removed };\n\t}\n\n\t/**\n\t * Insert new lines at the given 1-based position.\n\t * Convenience wrapper around applyChanges.\n\t */\n\tinsertLines(atLine: number, texts: string[]): number[] {\n\t\tconst change: LineChange = {\n\t\t\tstartLine: atLine,\n\t\t\tdeleteCount: 0,\n\t\t\tinsertLines: texts,\n\t\t};\n\t\tconst result = this.applyChanges([change]);\n\t\treturn result.inserted;\n\t}\n\n\t/**\n\t * Delete lines in the given 1-based range [startLine, endLine] inclusive.\n\t * Convenience wrapper around applyChanges.\n\t */\n\tdeleteLines(startLine: number, endLine: number): number[] {\n\t\tconst change: LineChange = {\n\t\t\tstartLine,\n\t\t\tdeleteCount: endLine - startLine + 1,\n\t\t\tinsertLines: [],\n\t\t};\n\t\tconst result = this.applyChanges([change]);\n\t\treturn result.removed;\n\t}\n\n\t/**\n\t * Update the text of a single line in place.\n\t * If the text hash differs, marks the line dirty and clears its\n\t * bytecode/result so it gets re-evaluated.\n\t *\n\t * Returns true if the text actually changed (hash mismatch).\n\t */\n\teditLine(lineNumber: number, newText: string): boolean {\n\t\tconst state = this.getLineAt(lineNumber);\n\t\tif (!state) return false;\n\n\t\tconst newHash = djb2Hash(newText);\n\t\tif (newHash === state.textHash) return false;\n\n\t\tstate.text = newText;\n\t\tstate.textHash = newHash;\n\t\tstate.expressions = [];\n\t\tstate.bytecodes = [];\n\t\tstate.results = [];\n\t\tstate.result = null;\n\t\tstate.inlineSolveCount = 0;\n\t\tstate.dirty = true;\n\t\tthis.dirtyLineIds.add(state.lineId);\n\t\tstate.isEmpty = newText.trim().length === 0;\n\t\treturn true;\n\t}\n\n\t// ── Queries ─────────────────────────────────────────────────────────\n\n\t/**\n\t * Get the LineState at the given 1-based line position. O(1).\n\t */\n\tgetLineAt(position: number): LineState | undefined {\n\t\tconst idx = position - 1;\n\t\tconst lineId = this.orderTree.getAt(idx);\n\t\tif (lineId === undefined) return undefined;\n\t\treturn this.lines.get(lineId);\n\t}\n\n\t/**\n\t * Get the 1-based position of a line by its persistent ID.\n\t * Returns -1 if the line ID is not in the document.\n\t *\n\t * Uses a lazy position cache: O(N) on first call after structural edit,\n\t * O(1) on subsequent calls. The cache is invalidated by any structural edit.\n\t */\n\tgetLinePosition(lineId: number): number {\n\t\tif (this._positionCache) {\n\t\t\treturn this._positionCache.get(lineId) ?? -1;\n\t\t}\n\n\t\t// Build position cache on first call after invalidation\n\t\tthis._positionCache = new Map();\n\t\tlet pos = 1;\n\t\tfor (const id of this.orderTree) {\n\t\t\tthis._positionCache.set(id, pos++);\n\t\t}\n\n\t\treturn this._positionCache.get(lineId) ?? -1;\n\t}\n\n\t/**\n\t * Get all LineState entries within the given viewport range (1-based, inclusive).\n\t * Uses SegmentTree.getRange() for O(viewport + log N) collection instead of\n\t * O(viewport × log N) per-line lookups.\n\t */\n\tgetVisibleLines(startLine: number, endLine: number): LineState[] {\n\t\tconst lineIds = this.orderTree.getRange(startLine - 1, endLine - 1);\n\t\tconst result: LineState[] = [];\n\t\tfor (const lineId of lineIds) {\n\t\t\tconst state = this.lines.get(lineId);\n\t\t\tif (state) result.push(state);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get all LineState entries in order. Useful for batch processing.\n\t */\n\tgetAllLines(): LineState[] {\n\t\treturn this.getVisibleLines(1, this.lineCount);\n\t}\n\n\t/**\n\t * Get a LineState by its persistent line ID. O(1).\n\t */\n\tgetLineById(lineId: number): LineState | undefined {\n\t\treturn this.lines.get(lineId);\n\t}\n\n\t/**\n\t * Get all lines that are marked dirty.\n\t */\n\tgetDirtyLines(): LineState[] {\n\t\tconst result: LineState[] = [];\n\t\tfor (const state of this.lines.values()) {\n\t\t\tif (state.dirty) result.push(state);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Whether any line before `position` (1-based, exclusive) is dirty.\n\t *\n\t * Used by ThreeTierEvaluator.setViewport() to decide whether cached\n\t * checkpoint state might be stale and a full evaluate() (from line 1) is\n\t * needed instead of the cheap viewport-only path.\n\t *\n\t * O(d log N) where d = current dirty line count via {@link dirtyLineIds},\n\t * not O(N log N), a document that's mostly clean (the steady state after\n\t * initial load) answers this in the cost of resolving a handful of\n\t * lineIds to positions, not walking every line up to `position`.\n\t */\n\thasAnyDirtyLineBefore(position: number): boolean {\n\t\tfor (const lineId of this.dirtyLineIds) {\n\t\t\tconst pos = this.getLinePosition(lineId);\n\t\t\tif (pos >= 1 && pos < position) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Whether any **variable-definition** line before `position` (1-based,\n\t * exclusive) is dirty.\n\t *\n\t * Narrower than {@link hasAnyDirtyLineBefore}: `VMCheckpointer.snapshot()`\n\t * only ever records state for lines with `writes.length > 0` (see\n\t * VMCheckpoints.ts), so a dirty plain-expression line before the viewport\n\t * cannot have invalidated any checkpoint, there's no checkpoint entry\n\t * for it to invalidate. Only a dirty variable-def line can mean the VM\n\t * state a checkpoint would restore is stale.\n\t *\n\t * This distinction matters because `PageManager.evictPageBytecode()`\n\t * marks evicted non-variable-def lines dirty (so they get Tier 1 if\n\t * scrolled back into view), and Tier 3's compile-only path never clears\n\t * `dirty` for non-variable-def lines by design. Using the broader\n\t * `hasAnyDirtyLineBefore` here meant scrolling far into a large,\n\t * variable-def-free document would trip `setViewport()`'s fallback to\n\t * `evaluate()` on every single call, evaluate() reprocesses the evicted\n\t * lines via Tier 3, which recompiles their bytecode without clearing\n\t * dirty, so the very next `maintainAfterEval()` re-evicts and re-dirties\n\t * the same lines, forever re-triggering the fallback on an otherwise\n\t * unchanged viewport.\n\t */\n\thasAnyDirtyVariableDefLineBefore(position: number): boolean {\n\t\tfor (const lineId of this.dirtyLineIds) {\n\t\t\tconst state = this.lines.get(lineId);\n\t\t\tif (!state || !state.isVariableDef) continue;\n\t\t\tconst pos = this.getLinePosition(lineId);\n\t\t\tif (pos >= 1 && pos < position) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/** Number of lines currently marked dirty. For diagnostics/tests. */\n\tget dirtyCount(): number {\n\t\treturn this.dirtyLineIds.size;\n\t}\n\n\t// ── Thread-safety validation ────────────────────────────────────────\n\n\t/**\n\t * Verify that bytecode compiled by a worker is still valid for this line.\n\t *\n\t * When Phase 5.2h sends compilation to a worker, the worker posts back\n\t * `{lineId, bytecode, reads, writes, compiledAgainstHash}`. Between dispatch\n\t * and response, the user may have edited the line. This method lets the\n\t * main thread check whether the bytecode is still applicable.\n\t *\n\t * @returns true if the line still exists and its text hash matches.\n\t */\n\tisBytecodeValid(lineId: number, compiledAgainstHash: number): boolean {\n\t\tconst state = this.lines.get(lineId);\n\t\treturn state !== undefined && state.textHash === compiledAgainstHash;\n\t}\n\n\t// ── State mutations ─────────────────────────────────────────────────\n\n\t/**\n\t * Mark a line as clean (re-evaluated successfully).\n\t */\n\tmarkClean(lineId: number): void {\n\t\tconst state = this.lines.get(lineId);\n\t\tif (state) {\n\t\t\tstate.dirty = false;\n\t\t\tthis.dirtyLineIds.delete(lineId);\n\t\t}\n\t}\n\n\t/**\n\t * Mark a line as dirty (needs re-evaluation) by its 1-based position.\n\t * Convenience for callers that have line numbers instead of line IDs.\n\t */\n\tmarkDirtyByLineNumber(lineNumber: number): void {\n\t\tconst state = this.getLineAt(lineNumber);\n\t\tif (state) {\n\t\t\tstate.dirty = true;\n\t\t\tthis.dirtyLineIds.add(state.lineId);\n\t\t}\n\t}\n\n\t/**\n\t * Mark a line as dirty (needs re-evaluation).\n\t */\n\tmarkDirty(lineId: number): void {\n\t\tconst state = this.lines.get(lineId);\n\t\tif (state) {\n\t\t\tstate.dirty = true;\n\t\t\tthis.dirtyLineIds.add(lineId);\n\t\t}\n\t}\n\n\t/**\n\t * Mark all lines as dirty (e.g., after plugin register/unregister).\n\t */\n\tinvalidateAll(): void {\n\t\tfor (const state of this.lines.values()) {\n\t\t\tstate.dirty = true;\n\t\t}\n\t\tthis.dirtyLineIds = new Set(this.lines.keys());\n\t}\n\n\t/**\n\t * Update a line's evaluation state after successful execution (Tier 1 / Tier 2).\n\t *\n\t * Sets results, bytecodes, reads, writes, and marks the line clean.\n\t * Supports multi-expression lines (inline solves) via parallel arrays.\n\t *\n\t * @param lineId - Persistent line identifier.\n\t * @param results - Evaluation result groups for each expression (in order). Each element is a Value[].\n\t * @param bytecodes - Compiled bytecode for each expression (in order).\n\t * @param expressions - Extracted expression strings (in order).\n\t * @param reads - Aggregated read variables across all expressions.\n\t * @param writes - Aggregated write variables across all expressions.\n\t * @param isVariableDef - True if any expression defines a variable.\n\t * @param inlineSolveCount - Number of inline solves (0 for full-line).\n\t */\n\tupdateLineResult(\n\t\tlineId: number,\n\t\tresults: Value[][],\n\t\tbytecodes: BytecodeProgram[],\n\t\texpressions: string[],\n\t\treads: string[],\n\t\twrites: string[],\n\t\tisVariableDef: boolean,\n\t\tinlineSolveCount: number = 0,\n\t): void {\n\t\tconst state = this.lines.get(lineId);\n\t\tif (!state) return;\n\t\tstate.results = results;\n\t\tstate.result = results[0]?.[0] ?? null;\n\t\tstate.bytecodes = bytecodes;\n\t\tstate.expressions = expressions;\n\t\tstate.reads = reads;\n\t\tstate.writes = writes;\n\t\tstate.isVariableDef = isVariableDef;\n\t\tstate.inlineSolveCount = inlineSolveCount;\n\t\tstate.dirty = false;\n\t\tthis.dirtyLineIds.delete(lineId);\n\t}\n\n\t/**\n\t * Update a line's compile-only state (Tier 3: background compilation).\n\t *\n\t * Stores expressions, bytecodes, reads, and writes. Does NOT set results\n\t * and does NOT mark the line clean, it still needs execution (Tier 1 or\n\t * Tier 2) to produce results. This distinction allows the three-tier\n\t * evaluation strategy: compile invisible lines in the background without\n\t * executing them, then execute from cached bytecode when scrolled into view.\n\t *\n\t * @param lineId - Persistent line identifier.\n\t * @param expressions - Extracted expression strings (in order).\n\t * @param bytecodes - Compiled bytecode for each expression (in order).\n\t * @param reads - Aggregated read variables across all expressions.\n\t * @param writes - Aggregated write variables across all expressions.\n\t * @param isVariableDef - True if any expression defines a variable.\n\t * @param inlineSolveCount - Number of inline solves (0 for full-line).\n\t */\n\tupdateLineCompiled(\n\t\tlineId: number,\n\t\texpressions: string[],\n\t\tbytecodes: BytecodeProgram[],\n\t\treads: string[],\n\t\twrites: string[],\n\t\tisVariableDef: boolean,\n\t\tinlineSolveCount: number = 0,\n\t): void {\n\t\tconst state = this.lines.get(lineId);\n\t\tif (!state) return;\n\t\tstate.expressions = expressions;\n\t\tstate.bytecodes = bytecodes;\n\t\tstate.reads = reads;\n\t\tstate.writes = writes;\n\t\tstate.isVariableDef = isVariableDef;\n\t\tstate.inlineSolveCount = inlineSolveCount;\n\t\t// NOTE: dirty remains unchanged, line still needs execution\n\t}\n\n\t// ── Properties ──────────────────────────────────────────────────────\n\n\tget lineCount(): number {\n\t\treturn this.orderTree.length;\n\t}\n\n\tget isEmpty(): boolean {\n\t\treturn this.orderTree.isEmpty;\n\t}\n\n\t/**\n\t * Iterator over LineState in document order.\n\t */\n\t*[Symbol.iterator](): IterableIterator<LineState> {\n\t\tfor (const lineId of this.orderTree) {\n\t\t\tconst state = this.lines.get(lineId);\n\t\t\tif (state) yield state;\n\t\t}\n\t}\n\n\t// ── Lifecycle ───────────────────────────────────────────────────────\n\n\tclear(): void {\n\t\tthis.lines.clear();\n\t\tthis.orderTree.clear();\n\t\tthis._positionCache = null;\n\t\tthis.nextLineId = 1;\n\t}\n\n\t/**\n\t * Serialize the document model to a plain object for debugging.\n\t */\n\ttoJSON(): object {\n\t\treturn {\n\t\t\tlineCount: this.lineCount,\n\t\t\tlines: this.getAllLines().map((s) => ({\n\t\t\t\tlineId: s.lineId,\n\t\t\t\ttext: s.text.substring(0, 80), // truncate for readability\n\t\t\t\ttextHash: s.textHash,\n\t\t\t\tdirty: s.dirty,\n\t\t\t\tisVariableDef: s.isVariableDef,\n\t\t\t\tisEmpty: s.isEmpty,\n\t\t\t\thasBytecode: s.bytecodes.length > 0,\n\t\t\t\thasResult: s.results.length > 0,\n\t\t\t\tinlineSolveCount: s.inlineSolveCount,\n\t\t\t\treads: s.reads,\n\t\t\t\twrites: s.writes,\n\t\t\t})),\n\t\t};\n\t}\n}\n","/**\n * CompilationWorkerManager, main-thread bridge to the compilation worker.\n *\n * Manages the worker lifecycle and provides a batch compilation API.\n * Receives transferred ArrayBuffers from the worker and reconstructs\n * BytecodeProgram objects with zero-copy TypedArray views.\n *\n * Usage:\n * const manager = new CompilationWorkerManager();\n * const bytecodeByLineId = await manager.compileBatch(items, docModel);\n *\n * Thread safety:\n * Each result includes `compiledAgainstHash`. Before storing bytecode\n * in the DocumentModel, we validate via `docModel.isBytecodeValid()`.\n * If the line was edited between dispatch and response, the bytecode\n * is discarded, the next evaluate() will recompile it synchronously.\n */\n\nimport { DocumentModel } from \"@solve-js/engine/DocumentModel\";\nimport type { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport createCompilationWorker from \"@solve-js/workers/engine.worker\";\n\n// ── Types ─────────────────────────────────────────────────────────────────\n\n/** One line sent to a worker for compilation. */\nexport interface CompileRequestItem {\n\tlineId: number;\n\texpression: string;\n\ttextHash: number;\n}\n\n/** Compiled bytecode returned from a worker, or the error that stopped it. */\nexport interface CompileResponseItem {\n\tlineId: number;\n\t/** Hash of the expression text when the compile was dispatched (for safety validation). */\n\tcompiledAgainstHash: number;\n\tprogram: BytecodeProgram;\n\treads: string[];\n\twrites: string[];\n\tisVariableDef: boolean;\n\terror: string | null;\n}\n\n// Raw result from worker (before BytecodeProgram reconstruction)\ninterface WorkerCompileResult {\n\tlineId: number;\n\tcompiledAgainstHash: number;\n\topcodesBuffer: ArrayBuffer;\n\tnumbersBuffer: ArrayBuffer;\n\topcodesLength: number;\n\tnumbersLength: number;\n\tstrings: string[];\n\treads: string[];\n\twrites: string[];\n\tisVariableDef: boolean;\n\terror: string | null;\n}\n\n// ── CompilationWorkerManager ──────────────────────────────────────────────\n\n/**\n * Compiles lines on a background worker.\n *\n * A response is discarded when the line changed between dispatch and return,\n * because bytecode compiled against stale text would produce a result for an\n * expression the user has already edited. The next evaluation recompiles it\n * synchronously.\n */\nexport class CompilationWorkerManager {\n\tprivate worker: Worker | null = null;\n\tprivate nextId = 1;\n\tprivate pending = new Map<\n\t\tnumber,\n\t\t{\n\t\t\tresolve: (results: CompileResponseItem[]) => void;\n\t\t\treject: (error: Error) => void;\n\t\t}\n\t>();\n\n\tconstructor() {}\n\n\t/**\n\t * Ensure the worker is started (lazy initialization).\n\t * Uses esbuild-plugin-inline-worker to inline the worker as a blob URL.\n\t */\n\tprivate ensureWorker(): Worker {\n\t\tif (this.worker) return this.worker;\n\n\t\tthis.worker = createCompilationWorker();\n\n\t\tthis.worker.onmessage = (event: MessageEvent) => {\n\t\t\tconst data = event.data;\n\t\t\tif (!data || data.type !== \"COMPILE_RESULT\") return;\n\n\t\t\tconst pending = this.pending.get(data.id);\n\t\t\tif (!pending) return;\n\n\t\t\tthis.pending.delete(data.id);\n\n\t\t\tconst results: CompileResponseItem[] = [];\n\t\t\tfor (const raw of data.results as WorkerCompileResult[]) {\n\t\t\t\tresults.push(this.reconstructResult(raw));\n\t\t\t}\n\t\t\tpending.resolve(results);\n\t\t};\n\n\t\tthis.worker.onerror = (err) => {\n\t\t\t// Reject all pending requests on worker error\n\t\t\tfor (const [id, pending] of this.pending) {\n\t\t\t\tpending.reject(\n\t\t\t\t\tnew Error(`Compilation worker error: ${err.message}`)\n\t\t\t\t);\n\t\t\t\tthis.pending.delete(id);\n\t\t\t}\n\t\t};\n\n\t\treturn this.worker;\n\t}\n\n\t/**\n\t * Batch-compile expressions in the worker.\n\t *\n\t * Sends a batch of { lineId, expression, textHash } to the worker,\n\t * which compiles each and transfers bytecode ArrayBuffers back.\n\t * Bytecode is reconstructed into BytecodeProgram objects.\n\t *\n\t * Results are returned in the same order as the input items.\n\t *\n\t * @param items Expressions to compile.\n\t * @returns Compiled bytecode for each item (or error).\n\t */\n\tasync compileBatch(items: CompileRequestItem[]): Promise<CompileResponseItem[]> {\n\t\tif (items.length === 0) return [];\n\n\t\tconst worker = this.ensureWorker();\n\t\tconst id = this.nextId++;\n\n\t\treturn new Promise<CompileResponseItem[]>((resolve, reject) => {\n\t\t\tthis.pending.set(id, { resolve, reject });\n\n\t\t\tworker.postMessage({\n\t\t\t\ttype: \"COMPILE_BATCH\",\n\t\t\t\tid,\n\t\t\t\titems,\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Store worker-compiled bytecode into the DocumentModel, with safety\n\t * validation. Only stores bytecode for lines whose text has not changed\n\t * since the compilation request was dispatched.\n\t *\n\t * Results for the same lineId are batched, all bytecodes from\n\t * successful compilations are passed to updateLineCompiled in a single\n\t * call. This supports multi-expression lines (inline solves).\n\t *\n\t * @param results Compiled results from the worker.\n\t * @param doc The target document model.\n\t * @returns Number of results successfully stored (passed safety check).\n\t */\n\tstoreResults(\n\t\tresults: CompileResponseItem[],\n\t\tdoc: DocumentModel\n\t): number {\n\t\t// Batch results by lineId (multiple inline solves share the same lineId)\n\t\tconst byLineId = new Map<\n\t\t\tnumber,\n\t\t\t{\n\t\t\t\tbytecodes: BytecodeProgram[];\n\t\t\t\treads: Set<string>;\n\t\t\t\twrites: Set<string>;\n\t\t\t\tisVariableDef: boolean;\n\t\t\t\texpressions: string[];\n\t\t\t\ttextHash: number;\n\t\t\t}\n\t\t>();\n\t\tlet validCount = 0;\n\n\t\tfor (const result of results) {\n\t\t\tif (result.error) continue;\n\n\t\t\t// Safety check: has the line been edited since dispatch?\n\t\t\tconst state = doc.getLineById(result.lineId);\n\t\t\tif (!state) continue;\n\n\t\t\t// Validate that the line text hasn't changed since dispatch.\n\t\t\tif (state.textHash !== result.compiledAgainstHash) continue;\n\n\t\t\t// Batch by lineId\n\t\t\tlet batch = byLineId.get(result.lineId);\n\t\t\tif (!batch) {\n\t\t\t\tbatch = {\n\t\t\t\t\tbytecodes: [],\n\t\t\t\t\treads: new Set(),\n\t\t\t\t\twrites: new Set(),\n\t\t\t\t\tisVariableDef: false,\n\t\t\t\t\texpressions: state.expressions.length > 0 ? [...state.expressions] : [],\n\t\t\t\t\ttextHash: result.compiledAgainstHash,\n\t\t\t\t};\n\t\t\t\tbyLineId.set(result.lineId, batch);\n\t\t\t}\n\n\t\t\tbatch.bytecodes.push(result.program);\n\t\t\tfor (const r of result.reads) batch.reads.add(r);\n\t\t\tfor (const w of result.writes) batch.writes.add(w);\n\t\t\tif (result.isVariableDef) batch.isVariableDef = true;\n\t\t\tvalidCount++;\n\t\t}\n\n\t\t// Store batched results\n\t\tlet stored = 0;\n\t\tfor (const [lineId, batch] of byLineId) {\n\t\t\tif (batch.bytecodes.length === 0) continue;\n\t\t\t// Preserve inlineSolveCount from the LineState so the evaluator\n\t\t\t// knows this line has multiple expressions (avoids re-extraction).\n\t\t\tconst state = doc.getLineById(lineId);\n\t\t\tconst inlineSolveCount = state?.inlineSolveCount ?? 0;\n\t\t\tdoc.updateLineCompiled(\n\t\t\t\tlineId,\n\t\t\t\tbatch.expressions,\n\t\t\t\tbatch.bytecodes,\n\t\t\t\t[...batch.reads],\n\t\t\t\t[...batch.writes],\n\t\t\t\tbatch.isVariableDef,\n\t\t\t\tinlineSolveCount,\n\t\t\t);\n\t\t\tstored += batch.bytecodes.length;\n\t\t}\n\n\t\treturn stored;\n\t}\n\n\t/**\n\t * Terminate the worker and clean up.\n\t */\n\tterminate(): void {\n\t\tif (this.worker) {\n\t\t\tthis.worker.terminate();\n\t\t\tthis.worker = null;\n\t\t\tthis.pending.clear();\n\t\t}\n\t}\n\n\t/**\n\t * Whether the worker is currently active.\n\t */\n\tget isActive(): boolean {\n\t\treturn this.worker !== null;\n\t}\n\n\t// ── Private helpers ────────────────────────────────────────────────\n\n\t/**\n\t * Reconstruct a BytecodeProgram from transferred ArrayBuffers.\n\t *\n\t * The transferred ArrayBuffers are zero-copy, we create TypedArray\n\t * views directly over them. No data is copied or serialized.\n\t */\n\tprivate reconstructResult(raw: WorkerCompileResult): CompileResponseItem {\n\t\tif (raw.error) {\n\t\t\treturn {\n\t\t\t\tlineId: raw.lineId,\n\t\t\t\tcompiledAgainstHash: raw.compiledAgainstHash,\n\t\t\t\tprogram: { opcodes: new Uint8Array(0), numbers: new Float64Array(0), strings: [], hasAsync: false },\n\t\t\t\treads: [],\n\t\t\t\twrites: [],\n\t\t\t\tisVariableDef: false,\n\t\t\t\terror: raw.error,\n\t\t\t};\n\t\t}\n\n\t\t// Reconstruct TypedArrays from transferred ArrayBuffers.\n\t\t// These are views over the same memory, zero-copy from worker.\n\t\tconst opcodes =\n\t\t\traw.opcodesLength > 0\n\t\t\t\t? new Uint8Array(raw.opcodesBuffer, 0, raw.opcodesLength)\n\t\t\t\t: new Uint8Array(0);\n\t\tconst numbers =\n\t\t\traw.numbersLength > 0\n\t\t\t\t? new Float64Array(raw.numbersBuffer, 0, raw.numbersLength)\n\t\t\t\t: new Float64Array(0);\n\n\t\tconst program: BytecodeProgram = {\n\t\t\topcodes,\n\t\t\tnumbers,\n\t\t\tstrings: raw.strings,\n\t\t\thasAsync: false,\n\t\t};\n\n\t\treturn {\n\t\t\tlineId: raw.lineId,\n\t\t\tcompiledAgainstHash: raw.compiledAgainstHash,\n\t\t\tprogram,\n\t\t\treads: raw.reads,\n\t\t\twrites: raw.writes,\n\t\t\tisVariableDef: raw.isVariableDef,\n\t\t\terror: null,\n\t\t};\n\t}\n}\n","/**\n * PageManager, page-based LRU eviction + directional preloading.\n *\n * Groups document lines into fixed-size pages (128 lines each) and manages\n * three temperature tiers:\n * • Hot (viewport ± 3 pages): Keep bytecode + results\n * • Warm (viewport ± 6 pages): Keep bytecode, evict results\n * • Cold (beyond ± 6 pages): Evict bytecode + results (except variable defs)\n *\n * Variable definition bytecode is **never evicted** because it forms the\n * backbone of the dependency graph and VM checkpoints.\n *\n * Preloading: When the user scrolls in a consistent direction, the next\n * 1–2 pages are pre-compiled via the background worker so bytecode is\n * cache-hot by the time those lines scroll into view.\n *\n * Usage:\n * const pm = new PageManager();\n * // After evaluation:\n * pm.maintainAfterEval(viewport, doc);\n * // After scroll (viewport-only change):\n * pm.maintainAfterEval(viewport, doc);\n * const targets = pm.getPreloadTargets(viewport, doc);\n * // dispatch targets to compilation worker\n */\n\nimport { DocumentModel } from \"@solve-js/engine/DocumentModel\";\n// Deliberately the shared lexer, not an engine's own.\n//\n// `classifyLine` and `findInlineSolves` are character-level scans for headings,\n// comment markers, code fences and backtick spans. Neither consults the\n// keyword, unit or operator tables, so every lexer returns the same answer and\n// there is nothing per-engine to respect. Pinned by\n// __tests__/lexer/LineClassificationIsVocabularyIndependent.spec.ts, which\n// compares a bare lexer against one carrying extra vocabulary.\n//\n// This matters because these are free functions with no engine to ask. Making\n// them engine-aware would mean changing their signatures and every caller for\n// no behavioural difference.\nimport { sharedLexer } from \"@solve-js/lexer/Lexer\";\n\n// ── Constants ────────────────────────────────────────────────────────────\n\n/** Number of lines per page. Tunable, 128 balances granularity with overhead. */\nexport const PAGE_SIZE = 128;\n\n/** Number of pages on each side of the viewport considered \"hot.\" */\nconst HOT_PAGE_RADIUS = 3;\n\n/** Number of pages on each side of the viewport considered \"warm\" (includes hot). */\nconst WARM_PAGE_RADIUS = 6;\n\n/** Number of pages to preload ahead of the scroll direction. */\nconst PRELOAD_PAGE_COUNT = 2;\n\n/**\n * Pages just beyond the warm range that are \"newly cold\", they were warm\n * on the previous scroll and now need bytecode eviction. Once evicted, they\n * stay cold and don't need re-eviction on subsequent frames (the inner\n * `evictPageBytecode` checks for non-null bytecode and short-circuits).\n *\n * This buffer lets us skip iterating the vast majority of cold pages on\n * every scroll, reducing `maintainAfterEval` from O(total pages) to\n * O(hot + warm + buffer) ≈ O(1) for any document size.\n */\nconst COLD_EVICT_BUFFER = HOT_PAGE_RADIUS;\n\n// ── PageManager ──────────────────────────────────────────────────────────\n\n/**\n * Splits a long document into pages so only what is near the viewport is held\n * in full.\n *\n * A document is edited constantly and most of it is off screen. Paging keeps\n * the cost of a keystroke proportional to what is visible rather than to the\n * length of the document.\n */\nexport class PageManager {\n\t/** Previous viewport for scroll direction detection. null = no previous viewport. */\n\tprivate lastViewportStart: number | null = null;\n\n\t/** Saved scroll direction from the most recent maintainAfterEval call. */\n\tprivate savedDirection: \"down\" | \"up\" | null = null;\n\n\t/** Per-page access counter for LRU tracking. */\n\tprivate pageAccess: Map<number, number> = new Map();\n\n\t/** Monotonically increasing access sequence number. */\n\tprivate accessSeq = 0;\n\n\t// ── Static helpers ─────────────────────────────────────────────────\n\n\t/** Get the page number for a 1-based line number (0-based page index). */\n\tstatic pageForLine(lineNumber: number): number {\n\t\treturn Math.floor((lineNumber - 1) / PAGE_SIZE);\n\t}\n\n\t/** Get the 1-based inclusive line range for a page. */\n\tstatic pageRange(\n\t\tpageNum: number,\n\t\tdocLineCount: number\n\t): { startLine: number; endLine: number } {\n\t\treturn {\n\t\t\tstartLine: pageNum * PAGE_SIZE + 1,\n\t\t\tendLine: Math.min((pageNum + 1) * PAGE_SIZE, docLineCount),\n\t\t};\n\t}\n\n\t// ── Public API ─────────────────────────────────────────────────────\n\n\t/**\n\t * Detect scroll direction from viewport movement.\n\t * Returns null on first call (no previous viewport) or no movement.\n\t */\n\tdetectDirection(newViewport: { startLine: number }): \"down\" | \"up\" | null {\n\t\tif (this.lastViewportStart === null) return null;\n\t\tif (newViewport.startLine > this.lastViewportStart) return \"down\";\n\t\tif (newViewport.startLine < this.lastViewportStart) return \"up\";\n\t\treturn null;\n\t}\n\n\t/**\n\t * Maintain page tiers after evaluation.\n\t *\n\t * 1. Records the new viewport position\n\t * 2. Touches hot pages (viewport ± HOT_PAGE_RADIUS) for LRU\n\t * 3. Evicts cold/warm pages based on distance from viewport\n\t *\n\t * Call this after every `evaluate()`, `setViewport()`, or `evaluateAll()`.\n\t */\n\tmaintainAfterEval(\n\t\tviewport: { startLine: number; endLine: number },\n\t\tdoc: DocumentModel\n\t): void {\n\t\t// ── Capture direction BEFORE updating lastViewportStart ───\n\t\tthis.savedDirection = this.detectDirection(viewport);\n\t\tthis.lastViewportStart = viewport.startLine;\n\n\t\tconst docLineCount = doc.lineCount;\n\t\tconst viewportStartPage = PageManager.pageForLine(viewport.startLine);\n\t\tconst viewportEndPage = PageManager.pageForLine(viewport.endLine);\n\t\tconst lastPage = PageManager.pageForLine(docLineCount);\n\n\t\t// Compute hot/warm page ranges in O(1) using range math:\n\t\t// A page is within RADIUS of the viewport span iff it falls in\n\t\t// [viewportStartPage - RADIUS, viewportEndPage + RADIUS].\n\t\tconst hotStart = Math.max(0, viewportStartPage - HOT_PAGE_RADIUS);\n\t\tconst hotEnd = Math.min(lastPage, viewportEndPage + HOT_PAGE_RADIUS);\n\t\tconst warmStart = Math.max(0, viewportStartPage - WARM_PAGE_RADIUS);\n\t\tconst warmEnd = Math.min(lastPage, viewportEndPage + WARM_PAGE_RADIUS);\n\n\t\t// Touch hot pages to keep them fresh in LRU\n\t\tfor (let p = hotStart; p <= hotEnd; p++) {\n\t\t\tthis.touchPage(p);\n\t\t}\n\n\t\t// Evict warm-but-not-hot pages: keep bytecode, evict results only\n\t\tfor (let p = warmStart; p <= warmEnd; p++) {\n\t\t\tif (p >= hotStart && p <= hotEnd) continue;\n\t\t\tthis.evictPageResults(p, doc, docLineCount);\n\t\t}\n\n\t\t// Evict \"newly cold\" pages: a buffer zone just outside the warm\n\t\t// range. Pages beyond this buffer were already evicted on prior\n\t\t// scrolls and don't need re-eviction.\n\t\t// ── Left side (just above page 0, just below warm range) ──\n\t\tconst coldLeftEnd = warmStart - 1;\n\t\tconst coldLeftStart = Math.max(0, coldLeftEnd - COLD_EVICT_BUFFER + 1);\n\t\tfor (let p = coldLeftStart; p <= coldLeftEnd; p++) {\n\t\t\tthis.evictPageBytecode(p, doc, docLineCount);\n\t\t}\n\t\t// ── Right side (just above warm range, just below lastPage) ──\n\t\tconst coldRightStart = warmEnd + 1;\n\t\tconst coldRightEnd = Math.min(lastPage, coldRightStart + COLD_EVICT_BUFFER - 1);\n\t\tfor (let p = coldRightStart; p <= coldRightEnd; p++) {\n\t\t\tthis.evictPageBytecode(p, doc, docLineCount);\n\t\t}\n\t}\n\n\t/**\n\t * Get lines ahead of the viewport that should be pre-compiled.\n\t *\n\t * Looks PRELOAD_PAGE_COUNT pages ahead of the current scroll direction.\n\t * Only returns lines that are dirty, don't already have bytecode,\n\t * and are not empty/markdown-only.\n\t *\n\t * @param viewport The current viewport.\n\t * @param doc The document model.\n\t * @returns Items ready to send to the compilation worker.\n\t */\n\tgetPreloadTargets(\n\t\tviewport: { startLine: number; endLine: number },\n\t\tdoc: DocumentModel\n\t): Array<{ lineId: number; expression: string; textHash: number }> {\n\t\t// Use the direction saved by the last maintainAfterEval call.\n\t\t// We cannot re-detect because maintainAfterEval already updated\n\t\t// lastViewportStart to the current viewport position.\n\t\tconst direction = this.savedDirection;\n\t\tif (!direction) return [];\n\n\t\tconst items: Array<{ lineId: number; expression: string; textHash: number }> = [];\n\t\t// Use viewport end page for downward preload start, start page for upward.\n\t\t// This ensures we preload *beyond* the full viewport span, not just its start.\n\t\tconst viewportEndPage = PageManager.pageForLine(viewport.endLine);\n\t\tconst viewportStartPage = PageManager.pageForLine(viewport.startLine);\n\t\tconst lastPage = PageManager.pageForLine(doc.lineCount);\n\n\t\tconst pages: number[] = [];\n\t\tif (direction === \"down\") {\n\t\t\t// Preload pages immediately after the viewport's hot radius beyond its end\n\t\t\tconst startPage = viewportEndPage + HOT_PAGE_RADIUS + 1;\n\t\t\tconst endPage = Math.min(startPage + PRELOAD_PAGE_COUNT - 1, lastPage);\n\t\t\tfor (let p = startPage; p <= endPage && p <= lastPage; p++) {\n\t\t\t\tpages.push(p);\n\t\t\t}\n\t\t} else {\n\t\t\t// Preload pages immediately before the viewport's hot radius before its start\n\t\t\tconst firstPreloadPage = viewportStartPage - HOT_PAGE_RADIUS - 1;\n\t\t\tfor (let p = firstPreloadPage; p > firstPreloadPage - PRELOAD_PAGE_COUNT && p >= 0; p--) {\n\t\t\t\tpages.push(p);\n\t\t\t}\n\t\t}\n\n\t\tfor (const pageNum of pages) {\n\t\t\tconst range = PageManager.pageRange(pageNum, doc.lineCount);\n\t\t\tfor (let pos = range.startLine; pos <= range.endLine; pos++) {\n\t\t\t\tconst state = doc.getLineAt(pos);\n\t\t\t\tif (!state) continue;\n\t\t\t\tif (!state.dirty) continue;\n\t\t\t\tif (state.bytecodes.length > 0 && !state.isVariableDef) continue;\n\t\t\t\tif (state.isEmpty) continue;\n\n\t\t\t\t// Extract expressions using the shared lexer to handle inline\n\t\t\t\t// solves (s`...`). For full-line expressions, this returns [text].\n\t\t\t\t// For inline solve lines, this returns each extracted expression.\n\t\t\t\tif (state.expressions.length > 0) {\n\t\t\t\t\t// Use pre-extracted expressions (from prior evaluation)\n\t\t\t\t\tfor (const expression of state.expressions) {\n\t\t\t\t\t\tif (!expression.trim()) continue;\n\t\t\t\t\t\titems.push({\n\t\t\t\t\t\t\tlineId: state.lineId,\n\t\t\t\t\t\t\texpression,\n\t\t\t\t\t\t\ttextHash: state.textHash,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Expressions not yet extracted, use lexer to find inline solves\n\t\t\t\t\tconst inlineSpans = sharedLexer.findInlineSolves(state.text);\n\t\t\t\t\tif (inlineSpans.length > 0) {\n\t\t\t\t\t\tfor (const span of inlineSpans) {\n\t\t\t\t\t\t\tif (!span.expression.trim()) continue;\n\t\t\t\t\t\t\titems.push({\n\t\t\t\t\t\t\t\tlineId: state.lineId,\n\t\t\t\t\t\t\t\texpression: span.expression,\n\t\t\t\t\t\t\t\ttextHash: state.textHash,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Full-line expression\n\t\t\t\t\t\tconst expression = state.text.trim();\n\t\t\t\t\t\tif (expression) {\n\t\t\t\t\t\t\titems.push({\n\t\t\t\t\t\t\t\tlineId: state.lineId,\n\t\t\t\t\t\t\t\texpression,\n\t\t\t\t\t\t\t\ttextHash: state.textHash,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn items;\n\t}\n\n\t/**\n\t * Reset internal state (e.g., after document switch).\n\t */\n\tclear(): void {\n\t\tthis.pageAccess.clear();\n\t\tthis.accessSeq = 0;\n\t\tthis.lastViewportStart = null;\n\t\tthis.savedDirection = null;\n\t}\n\n\t// ── Private helpers ─────────────────────────────────────────────────\n\n\t/** Record a page access with a monotonic sequence number. */\n\tprivate touchPage(pageNum: number): void {\n\t\tthis.pageAccess.set(pageNum, ++this.accessSeq);\n\t}\n\n\t/**\n\t * Evict results from all non-variable-def lines in a page.\n\t * Bytecode is preserved so Tier 2 execution works on scroll-back.\n\t */\n\tprivate evictPageResults(\n\t\tpageNum: number,\n\t\tdoc: DocumentModel,\n\t\tdocLineCount: number\n\t): void {\n\t\tconst range = PageManager.pageRange(pageNum, docLineCount);\n\t\tfor (let pos = range.startLine; pos <= range.endLine; pos++) {\n\t\t\tconst state = doc.getLineAt(pos);\n\t\t\tif (state && !state.isVariableDef && state.results.length > 0) {\n\t\t\t\tstate.results = [];\n\t\t\t\tstate.result = null;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Evict bytecode + results from all non-variable-def lines in a page.\n\t * Variable definition bytecode is **never** evicted, it forms the\n\t * backbone of the DAG and VM checkpoints.\n\t *\n\t * Evicted lines are marked dirty so they get Tier 1 re-evaluation\n\t * when scrolled back into view.\n\t */\n\tprivate evictPageBytecode(\n\t\tpageNum: number,\n\t\tdoc: DocumentModel,\n\t\tdocLineCount: number\n\t): void {\n\t\tconst range = PageManager.pageRange(pageNum, docLineCount);\n\t\tfor (let pos = range.startLine; pos <= range.endLine; pos++) {\n\t\t\tconst state = doc.getLineAt(pos);\n\t\t\tif (!state || state.isVariableDef) continue;\n\n\t\t\tif (state.bytecodes.length > 0 || state.results.length > 0) {\n\t\t\t\tstate.bytecodes = [];\n\t\t\t\tstate.results = [];\n\t\t\t\tstate.result = null;\n\t\t\t\tdoc.markDirty(state.lineId);\n\t\t\t}\n\t\t}\n\t}\n}\n","import { ExpressionEngine } from \"@solve-js/engine/ExpressionEngine\";\nimport {\n\tDocumentModel,\n\tLineChange,\n\tLineState,\n\tViewportRange,\n} from \"@solve-js/engine/DocumentModel\";\nimport { Value, ValueType, enableValueArena, disableValueArena, errorValue } from \"@solve-js/vm/Value\";\nimport { DependencyGraph } from \"@solve-js/vm/DependencyGraph\";\nimport { VMCheckpointer } from \"@solve-js/vm/VMCheckpoints\";\nimport { isEmptyLine } from \"@solve-js/engine/ExpressionEngineSafety\";\n// Deliberately the shared lexer, not an engine's own.\n//\n// `classifyLine` and `findInlineSolves` are character-level scans for headings,\n// comment markers, code fences and backtick spans. Neither consults the\n// keyword, unit or operator tables, so every lexer returns the same answer and\n// there is nothing per-engine to respect. Pinned by\n// __tests__/lexer/LineClassificationIsVocabularyIndependent.spec.ts, which\n// compares a bare lexer against one carrying extra vocabulary.\n//\n// This matters because these are free functions with no engine to ask. Making\n// them engine-aware would mean changing their signatures and every caller for\n// no behavioural difference.\nimport { sharedLexer } from \"@solve-js/lexer/Lexer\";\nimport { CompilationWorkerManager, type CompileRequestItem } from \"@solve-js/engine/CompilationWorkerManager\";\nimport { PageManager } from \"@solve-js/engine/PageManager\";\nimport type { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { EngineError } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { sharedGlobalVariableStore, globalDagKey } from \"@solve-js/vm/GlobalVariableStore\";\n\n// ── EvalTier (diagnostic enum) ──────────────────────────────────────────\n\n/**\n * How much work a line's evaluation required.\n *\n * The tiers exist because most lines in a document have not changed. A line\n * that is clean and cached costs far less than one being compiled fresh, and\n * knowing which happened is how a slow document gets diagnosed.\n */\nexport enum EvalTier {\n\t/** Full pipeline: Lex → Parse → Compile → Execute (visible + dirty). */\n\tTier1 = 1,\n\t/** Execute-only from cached bytecode (visible + cached). */\n\tTier2 = 2,\n\t/** Compile-only for dependency tracking (invisible). Executes only variable assignments. */\n\tTier3 = 3,\n\t/** Skipped, already clean or non-evaluable. */\n\tSkipped = 0,\n}\n\n// ── EvalLineResult ──────────────────────────────────────────────────────\n\n/** Outcome for one line, including which tier handled it. */\nexport interface EvalLineResult {\n\t/** The line's persistent ID from DocumentModel. */\n\tlineId: number;\n\t/** 1-based line position. */\n\tlineNumber: number;\n\t/** Which tier was used. */\n\ttier: EvalTier;\n\t/** The first evaluation result, or null on error / non-evaluable. */\n\tresult: Value | null;\n\t/** All result groups (one per expression/inline-solve), or undefined if skipped. */\n\tresults?: Value[][];\n\t/** Error message, or null. */\n\terror: string | null;\n}\n\n// ── EvalResult ──────────────────────────────────────────────────────────\n\n/** Outcome for a whole evaluation pass, with per-tier counts. */\nexport interface EvalResult {\n\t/** Per-line evaluation results. */\n\tlines: EvalLineResult[];\n\t/** Map of line numbers → flattened results for quick lookup. */\n\tresultMap: Map<number, Value[]>;\n\t/** Number of lines processed at each tier. */\n\ttierCounts: { tier1: number; tier2: number; tier3: number; skipped: number };\n}\n\n// ── ThreeTierEvaluator ──────────────────────────────────────────────────\n\n/**\n * Orchestrates three-tier evaluation over a persistent DocumentModel.\n *\n * ── Tier assignment ─────────────────────────────────────────────────\n * | Tier | Condition | Action |\n * |───────|────────────────────────────────────|───────────────────────────────|\n * | **1** | Visible + Dirty (new/changed) | Full pipeline: lex→parse→compile→execute |\n * | **2** | Visible + Cached (scroll into view)| Execute from cached bytecode |\n * | **3** | Invisible + Dirty | Compile-only; execute only variable defs |\n * | Skip | Clean, empty, or non-evaluable | No action |\n *\n * ── Evaluation order ─────────────────────────────────────────────────\n * Lines are always processed in ascending document order (line 1 → end)\n * so that variable assignments flow correctly through the shared VM.\n * Tier 2 relies on this: by the time a clean cached line is reached,\n * the VM already contains all variables from preceding Tier-1 lines.\n *\n * ── Thread safety ────────────────────────────────────────────────────\n * Tier 1 (visible+dirty) compilation runs synchronously on the main thread\n * for immediate rendering. Tier 3 (invisible+dirty) compilation can be\n * dispatched to a Web Worker via `dispatchBackgroundCompiles()`. Worker-\n * compiled bytecode is stored in the DocumentModel and validated via\n * `isBytecodeValid()` to ensure the line text hasn't changed between\n * dispatch and response.\n */\nexport class ThreeTierEvaluator {\n\tprivate doc: DocumentModel;\n\tprivate engine: ExpressionEngine;\n\tprivate dag: DependencyGraph;\n\tprivate checkpointer: VMCheckpointer | null;\n\tprivate compilationWorker: CompilationWorkerManager | null = null;\n\tprivate pageManager: PageManager;\n\n\t/**\n\t * Unsubscribe from sharedGlobalVariableStore, set in the constructor\n\t * called from terminateWorker(). See the subscription itself below for\n\t * why this only marks lines dirty and never re-evaluates synchronously.\n\t */\n\tprivate globalUnsubscribe: (() => void) | null = null;\n\n\t/**\n\t * @param doc The persistent document model.\n\t * @param engine The expression engine (shared VM is accessed via engine.getVM()).\n\t * @param checkpointer Optional VM state checkpointer. If provided, the evaluator\n\t * will create checkpoints after variable-definition lines and support fast VM\n\t * restoration via `restoreTo()`. If omitted, checkpointing is disabled.\n\t */\n\tconstructor(\n\t\tdoc: DocumentModel,\n\t\tengine: ExpressionEngine,\n\t\tcheckpointer?: VMCheckpointer\n\t) {\n\t\tthis.doc = doc;\n\t\tthis.engine = engine;\n\t\tthis.dag = engine.getDag();\n\t\tthis.checkpointer = checkpointer ?? null;\n\t\tthis.pageManager = new PageManager();\n\n\t\t// Lets the engine answer \"what's line N's cached result\" for\n\t\t// cross-line features (prev/line<N>/aggregation) without owning\n\t\t// document lifecycle itself. See ExpressionEngine.makeLineContext().\n\t\tthis.engine.setDocumentModel(this.doc);\n\n\t\t// ── Cross-document global-variable propagation ──────────────────\n\t\t// GlobalVariableAsyncResolver (via preflight) handles a line's FIRST\n\t\t// resolution when a global it reads wasn't known yet. This handles\n\t\t// the ONGOING case: a line that already has a real (non-pending)\n\t\t// value for `global :x` needs to go dirty again when some OTHER\n\t\t// document writes a NEW value to x, so this document's next\n\t\t// evaluate() picks up the change, \"dealing with the DAG across\n\t\t// pages\", not just first-resolution.\n\t\tthis.globalUnsubscribe = sharedGlobalVariableStore.subscribe((name) => {\n\t\t\t// Mark-dirty ONLY, never synchronously re-evaluate here.\n\t\t\t// enableValueArena/disableValueArena (Value.ts) is a single\n\t\t\t// non-reentrant module-level flag; evaluate()/setViewport() both\n\t\t\t// wrap their body in it, so a re-entrant evaluate() call from\n\t\t\t// inside this callback (itself possibly firing from INSIDE\n\t\t\t// another evaluate() call, via a STORE_GLOBAL_VAR opcode in some\n\t\t\t// other document being evaluated concurrently) would disable the\n\t\t\t// arena out from under the still-running outer call. This\n\t\t\t// mirrors applyTransaction()'s existing contract exactly: mark\n\t\t\t// dirty, let the caller's own evaluate() cadence pick it up.\n\t\t\tfor (const lineNumber of this.dag.getAffectedLines(globalDagKey(name))) {\n\t\t\t\tthis.doc.markDirtyByLineNumber(lineNumber);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Evaluate all lines needed to render the given viewport.\n\t *\n\t * Processes lines from 1 to `viewport.endLine` in document order.\n\t * Dirty lines in the viewport get Tier-1 full pipeline; clean cached\n\t * lines get Tier-2 bytecode execution. Lines after the viewport\n\t * get Tier-3 compile-only (with variable-def execution).\n\t *\n\t * @returns Results for all processed lines, including tier metadata.\n\t */\n\tevaluate(viewport: ViewportRange, signal?: AbortSignal): EvalResult {\n\t\t// ── One AbortController Per Keystroke ────────────────────────\n\t\t// Link the UI layer's keystroke signal to the engine so that\n\t\t// all per-evaluation AbortControllers created during this call\n\t\t// are canceled when the user types a new keystroke.\n\t\tthis.engine.setKeystrokeSignal(signal ?? null);\n\n\t\t// ── Phase 5.3: Enable arena for zero-allocation Value reuse ──\n\t\tenableValueArena();\n\t\ttry {\n\t\t\t// Re-seed running-total accumulators before the from-line-1 pass. A\n\t\t\t// `total += 5` line reads its own running value, so re-running it in\n\t\t\t// place would read the previous evaluation's total and double-count.\n\t\t\t// Reset each accumulator variable and mark every line that touches\n\t\t\t// it dirty, so the loop below recomputes the total from its seed,\n\t\t\t// top to bottom. (No-op when the document has no accumulators.)\n\t\t\tthis.reseedAccumulators();\n\n\t\t\tconst lines: EvalLineResult[] = [];\n\t\t\tconst resultMap = new Map<number, Value[]>();\n\t\t\tconst tierCounts = { tier1: 0, tier2: 0, tier3: 0, skipped: 0 };\n\n\t\t\t// Process from line 1 to the end of the viewport for correct VM state.\n\t\t\t// We go to viewport.endLine because Tier 3 for invisible lines can be\n\t\t\t// done separately via backgroundCompile().\n\t\t\tconst docEnd = this.doc.lineCount;\n\t\t\tconst evalEnd = Math.min(viewport.endLine, docEnd);\n\n\t\t\tfor (let pos = 1; pos <= evalEnd; pos++) {\n\t\t\t\tconst state = this.doc.getLineAt(pos);\n\t\t\t\tif (!state) {\n\t\t\t\t\ttierCounts.skipped++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst inViewport = pos >= viewport.startLine && pos <= viewport.endLine;\n\n\t\t\t\tconst lineResult = this.evaluateSingleLine(state, pos, inViewport);\n\t\t\t\tlines.push(lineResult);\n\n\t\t\t\tif (lineResult.tier === EvalTier.Tier1) tierCounts.tier1++;\n\t\t\t\telse if (lineResult.tier === EvalTier.Tier2) tierCounts.tier2++;\n\t\t\t\telse if (lineResult.tier === EvalTier.Tier3) tierCounts.tier3++;\n\t\t\t\telse tierCounts.skipped++;\n\n\t\t\t\tif (lineResult.results && inViewport) {\n\t\t\t\t\tresultMap.set(pos, lineResult.results.flat());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ── Phase 5.2g: Page-based LRU eviction ──────────────────────\n\t\t\t// Evict bytecode/results from cold/warm pages to bound memory.\n\t\t\tthis.pageManager.maintainAfterEval(viewport, this.doc);\n\n\t\t\treturn { lines, resultMap, tierCounts };\n\t\t} finally {\n\t\t\t// Clear keystroke signal to prevent stale signal references\n\t\t\t// from being used by subsequent evaluations from other code paths.\n\t\t\tthis.engine.setKeystrokeSignal(null);\n\n\t\t\t// Phase 5.3: Always disable arena, even on exception.\n\t\t\t// Prevents arena Values from leaking into subsequent evaluations or tests.\n\t\t\tdisableValueArena();\n\t\t}\n\t}\n\n\t/**\n\t * Background-compile invisible dirty lines beyond the viewport (Tier 3 only).\n\t *\n\t * Compiles expressions to discover reads/writes for the dependency graph\n\t * without executing display-only expressions. Variable definitions are\n\t * executed to maintain VM state for future Tier-2 executions.\n\t *\n\t * This is intended to be called after evaluate() so visible lines are\n\t * rendered first, then background work fills in the dependency graph.\n\t *\n\t * **Phase 5.2h:** This synchronous method is retained for environments\n\t * without Worker support. Prefer `dispatchBackgroundCompiles()` which\n\t * offloads compilation to a Web Worker with Transferable bytecode.\n\t */\n\tbackgroundCompile(viewport: ViewportRange): EvalLineResult[] {\n\t\tconst results: EvalLineResult[] = [];\n\t\tconst docEnd = this.doc.lineCount;\n\t\tconst startPos = viewport.endLine + 1;\n\n\t\tfor (let pos = startPos; pos <= docEnd; pos++) {\n\t\t\tconst state = this.doc.getLineAt(pos);\n\t\t\tif (!state) continue;\n\n\t\t\t// Skip clean lines, already compiled + executed\n\t\t\tif (!state.dirty) continue;\n\n\t\t\t// Skip already-compiled Tier 3 lines, they have bytecode\n\t\t\t// but were compiled without execution (non-variable-def).\n\t\t\t// Recompiling is wasteful since the text hasn't changed\n\t\t\t// (text change clears bytecodes via editLine).\n\t\t\tif (state.bytecodes.length > 0 && !state.isVariableDef) continue;\n\n\t\t\tconst lineResult = this.evaluateSingleLine(state, pos, false);\n\t\t\tresults.push(lineResult);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Dispatch background compilation to a Web Worker (Phase 5.2h).\n\t *\n\t * Collects invisible dirty lines beyond the viewport that need compilation,\n\t * sends them to the compilation worker, and asynchronously stores the\n\t * transferred bytecode in the DocumentModel when the worker responds.\n\t *\n\t * This is the non-blocking alternative to `backgroundCompile()`. The worker\n\t * compiles expressions with Transferable ArrayBuffers (zero-copy postMessage),\n\t * so bytecode appears on the main thread without serialization overhead.\n\t *\n\t * Lines that already have cached bytecode (from a previous worker pass or\n\t * synchronous compile) are skipped, only truly uncompiled dirty lines are\n\t * sent to the worker.\n\t *\n\t * **Usage:** Call after `evaluate()` so visible lines render first, then\n\t * this fills the bytecode cache for future Tier-2 scrolls.\n\t *\n\t * @param viewport The current visible range. Lines beyond viewport.endLine\n\t * that are dirty and don't have bytecode are dispatched.\n\t */\n\tdispatchBackgroundCompiles(viewport: ViewportRange): void {\n\t\t// Collect invisible dirty lines that need compilation\n\t\tconst items = this.collectInvisibleCompileTargets(viewport);\n\t\tif (items.length === 0) return;\n\n\t\t// Lazy-init the worker (only if there are items to compile)\n\t\tif (!this.compilationWorker) {\n\t\t\tthis.compilationWorker = new CompilationWorkerManager();\n\t\t}\n\n\t\t// Fire-and-forget: send to worker, store results when they arrive\n\t\tthis.compilationWorker.compileBatch(items).then((results) => {\n\t\t\tthis.compilationWorker!.storeResults(results, this.doc);\n\t\t}).catch((_err) => {\n\t\t\t// Worker failure is non-fatal, next evaluate() will compile\n\t\t\t// these expressions synchronously.\n\t\t});\n\t}\n\n\t/**\n\t * Terminate the compilation worker if active, and unsubscribe from\n\t * sharedGlobalVariableStore. Call this when the evaluator is no longer\n\t * needed to clean up resources, every call site that retires a\n\t * ThreeTierEvaluator (document switch, pane destroy()) already calls\n\t * this unconditionally, so folding the global-store unsubscribe in here\n\t * needs no new call sites anywhere.\n\t */\n\tterminateWorker(): void {\n\t\tif (this.compilationWorker) {\n\t\t\tthis.compilationWorker.terminate();\n\t\t\tthis.compilationWorker = null;\n\t\t}\n\t\tif (this.globalUnsubscribe) {\n\t\t\tthis.globalUnsubscribe();\n\t\t\tthis.globalUnsubscribe = null;\n\t\t}\n\t}\n\n\t/**\n\t * Get the DocumentModel (read-only access for decoration building).\n\t */\n\tgetDoc(): DocumentModel {\n\t\treturn this.doc;\n\t}\n\n\t/**\n\t * Evaluate all dirty lines in the document, regardless of viewport.\n\t * Used for full re-evaluation after plugin register/unregister.\n\t */\n\tevaluateAll(signal?: AbortSignal): EvalResult {\n\t\tconst viewport = { startLine: 1, endLine: this.doc.lineCount };\n\t\tconst result = this.evaluate(viewport, signal);\n\t\t// evaluate() already calls maintainAfterEval internally\n\t\treturn result;\n\t}\n\n\t/**\n\t * Zero-allocation viewport evaluation, the Phase 5.2e \"holy grail.\"\n\t *\n\t * **Key insight:** When the user scrolls (viewport-only change, no edits),\n\t * we don't need to re-evaluate from line 1. Instead:\n\t *\n\t * 1. Restore the VM to just before the viewport via the nearest checkpoint.\n\t * 2. Evaluate ONLY the visible lines (Tier 2 for clean cached, Tier 1 for dirty).\n\t * 3. Lines before the viewport are completely skipped, their state lives in\n\t * the VM checkpointer's prototypal chain.\n\t *\n\t * **Correctness guard:** If any variable-definition line before the viewport\n\t * is dirty (e.g., the user edited a variable def that hasn't been\n\t * re-evaluated yet), we clear stale checkpoints and fall back to `evaluate()`\n\t * which processes from line 1 and rebuilds fresh checkpoints. This\n\t * guarantees that stale checkpoints are never used as restoration targets.\n\t * Only variable-def lines matter here, `VMCheckpointer.snapshot()` only\n\t * records state for lines that write a variable, so a dirty plain-expression\n\t * line before the viewport has no checkpoint to invalidate (see\n\t * `DocumentModel.hasAnyDirtyVariableDefLineBefore()`).\n\t *\n\t * **Performance:** O(visible lines) instead of O(document length). Target:\n\t * < 1ms for a typical ~30-line viewport, independent of document size.\n\t *\n\t * @param viewport The visible line range.\n\t * @returns Results for visible lines only. Lines before the viewport are\n\t * not included in `lines[]` or `resultMap`.\n\t */\n\tsetViewport(viewport: ViewportRange, signal?: AbortSignal): EvalResult {\n\t\t// ── One AbortController Per Keystroke ────────────────────────\n\t\t// Link the UI layer's keystroke signal to the engine.\n\t\tthis.engine.setKeystrokeSignal(signal ?? null);\n\n\t\t// ── Correctness guard: dirty lines before viewport invalidate checkpoints ──\n\t\tif (viewport.startLine > 1 && this.hasDirtyLinesBefore(viewport.startLine)) {\n\t\t\t// Clear stale checkpoints, evaluate() will rebuild them from line 1.\n\t\t\t// evaluate() handles its own arena enable/disable and signal cleanup.\n\t\t\tthis.checkpointer?.clear();\n\t\t\treturn this.evaluate(viewport, signal);\n\t\t}\n\n\t\t// ── Phase 5.2g: Page-based LRU eviction (MUST run before preload) ──\n\t\t// maintainAfterEval captures the scroll direction and updates lastViewportStart\n\t\t// BEFORE preloadNextPages reads the direction for preloading.\n\t\tthis.pageManager.maintainAfterEval(viewport, this.doc);\n\n\t\t// ── Phase 5.2g: Detect scroll direction & preload ───────────\n\t\tthis.preloadNextPages(viewport);\n\n\t\t// ── Restore VM state from nearest checkpoint before the viewport ──\n\t\t// This sets all variables that were defined at or before startLine-1.\n\t\tthis.restoreTo(viewport.startLine - 1);\n\n\t\t// ── Phase 5.3: Enable arena for zero-allocation Tier 2 execution ──\n\t\tenableValueArena();\n\t\ttry {\n\t\t\t// ── Evaluate only visible lines ──\n\t\t\tconst result = this.collectEvalResults(viewport.startLine, viewport.endLine);\n\t\t\treturn result;\n\t\t} finally {\n\t\t\t// Clear keystroke signal to prevent stale signal references.\n\t\t\tthis.engine.setKeystrokeSignal(null);\n\n\t\t\t// Phase 5.3: Always disable arena, even on exception.\n\t\t\t// Prevents cross-test contamination from arena leaks.\n\t\t\tdisableValueArena();\n\t\t}\n\t}\n\n\t/**\n\t * Apply incremental line-level changes to the document model.\n\t *\n\t * **Phase 5.2f:** Replaces the O(N) `setDocument()` + full re-evaluation\n\t * with O(changed) incremental updates. Key benefits:\n\t *\n\t * 1. Unchanged lines retain their persistent lineIds → bytecode survives\n\t * 2. Only changed + DAG-downstream lines are marked dirty → Tier 1 re-evaluation\n\t * 3. Clean lines in viewport use Tier 2 (cached bytecode execution)\n\t * 4. Clean lines outside viewport are skipped entirely\n\t *\n\t * The DAG is fully cleared after propagation: shifted lines would have\n\t * stale entries keyed by old line numbers, so the DAG is rebuilt from\n\t * scratch during the subsequent `evaluate()` call.\n\t *\n\t * **Caller should follow up with `evaluate(viewport)`** to re-evaluate\n\t * dirty lines from line 1 and rebuild the DAG + checkpoints.\n\t *\n\t * @param changes Line-level changes to apply. Must be non-overlapping.\n\t * @returns Metadata about the applied changes.\n\t */\n\tapplyTransaction(changes: LineChange[]): {\n\t\tinserted: number[];\n\t\tremoved: number[];\n\t} {\n\t\t// ── Phase 1: Collect DAG writes + downstream lineIds ───────────\n\t\t// Must happen BEFORE applyChanges() because line numbers are still\n\t\t// valid at this point. We collect writes from deleted lines and\n\t\t// resolve downstream consumers to lineIds (not line numbers) so\n\t\t// they survive the position shifts that applyChanges() causes.\n\t\tconst allWrites = new Set<string>();\n\n\t\tfor (const change of changes) {\n\t\t\tfor (let i = 0; i < change.deleteCount; i++) {\n\t\t\t\tconst lineNum = change.startLine + i;\n\t\t\t\tconst writes = this.dag.getWrites(lineNum);\n\t\t\t\tfor (const w of writes) {\n\t\t\t\t\tallWrites.add(w);\n\t\t\t\t}\n\t\t\t\t// Clean up DAG references for this line\n\t\t\t\tthis.dag.removeLine(lineNum);\n\t\t\t\t// And its cached bytecode. The dependency graph was already\n\t\t\t\t// pruned here; the LineCache was not, so a deleted line kept its\n\t\t\t\t// entry until the whole cache was dropped on a document switch.\n\t\t\t\t// Editing a long document over a session accumulated entries for\n\t\t\t\t// line numbers that no longer existed.\n\t\t\t\tthis.engine.getLineCache().removeAllForLine(lineNum);\n\t\t\t}\n\t\t}\n\n\t\t// Resolve downstream consumers to persistent lineIds BEFORE the\n\t\t// structural change shifts line numbers. After applyChanges(),\n\t\t// we mark these lineIds dirty, their positions don't matter.\n\t\tconst downstreamLineIds = new Set<number>();\n\t\tfor (const writeVar of allWrites) {\n\t\t\tconst affected = this.dag.getAffectedLines(writeVar);\n\t\t\tfor (const lineNum of affected) {\n\t\t\t\tconst state = this.doc.getLineAt(lineNum);\n\t\t\t\tif (state) {\n\t\t\t\t\tdownstreamLineIds.add(state.lineId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// ── Phase 2: Apply structural changes to DocumentModel ─────────\n\t\tconst result = this.doc.applyChanges(changes);\n\n\t\t// ── Phase 3: Clear checkpointer (line numbers shifted) ─────────\n\t\tthis.checkpointer?.clear();\n\n\t\t// ── Phase 4: Mark DAG-downstream lines dirty by lineId ─────────\n\t\t// Using lineId instead of line number is position-agnostic:\n\t\t// lines that shifted due to insertions/deletions above them are\n\t\t// still correctly targeted. Lines that were deleted (lineId no\n\t\t// longer in the doc) are silently ignored by markDirty().\n\t\tfor (const lineId of downstreamLineIds) {\n\t\t\tthis.doc.markDirty(lineId);\n\t\t}\n\n\t\t// ── Phase 5: Clear DAG to avoid phantom entries ────────────────\n\t\t// Entries keyed by old line numbers are stale after structural\n\t\t// changes. Rather than updating shifted entries, we clear the DAG\n\t\t// and let the subsequent evaluate() call rebuild it from scratch.\n\t\tthis.dag.clear();\n\n\t\treturn {\n\t\t\tinserted: result.inserted,\n\t\t\tremoved: result.removed,\n\t\t};\n\t}\n\n\t// ── Private helpers ─────────────────────────────────────────────────\n\n\t/**\n\t * Reset running-total accumulators and mark the lines that touch them\n\t * dirty, so the from-line-1 pass in {@link evaluate} recomputes each total\n\t * from its seed instead of reading its own previous evaluation's value.\n\t *\n\t * A `total += 5` line compiles to no bytecode (it rides the symbolic\n\t * channel), so a clean one would be skipped by the tier dispatch rather\n\t * than re-run. It must re-run to re-apply its delta over the freshly-reset\n\t * base, so every line that WRITES an accumulator name is forced dirty (the\n\t * DAG drops a self-writing line from its own variable's consumers, so\n\t * getAffectedLines can't surface them). Pure readers of the total keep\n\t * their real bytecode and re-run via Tier 2 once the total is correct, so\n\t * they need no special handling. Cheap: a no-op unless the document\n\t * actually uses `+=`/`-=`, and accumulators are rare.\n\t */\n\tprivate reseedAccumulators(): void {\n\t\tconst names = this.engine.resetAccumulators();\n\t\tif (names.size === 0) return;\n\t\tconst docEnd = this.doc.lineCount;\n\t\tfor (let pos = 1; pos <= docEnd; pos++) {\n\t\t\tconst writes = this.dag.getWrites(pos);\n\t\t\tif (writes.size === 0) continue;\n\t\t\tfor (const w of writes) {\n\t\t\t\tif (names.has(w)) {\n\t\t\t\t\tthis.doc.markDirtyByLineNumber(pos);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Collect evaluation results for a contiguous range of lines.\n\t *\n\t * Used by both `evaluate()` (startLine=1) and `setViewport()` (any start).\n\t * All lines in the range are treated as in-viewport (visible), callers that\n\t * need the invisible/dirty → Tier 3 handling should use `evaluate()` instead.\n\t *\n\t * @param startLine First line to evaluate (1-based, inclusive).\n\t * @param endLine Last line to evaluate (1-based, inclusive). Clamped to docEnd.\n\t */\n\tprivate collectEvalResults(startLine: number, endLine: number): EvalResult {\n\t\tconst lines: EvalLineResult[] = [];\n\t\tconst resultMap = new Map<number, Value[]>();\n\t\tconst tierCounts = { tier1: 0, tier2: 0, tier3: 0, skipped: 0 };\n\n\t\tconst docEnd = this.doc.lineCount;\n\t\tconst evalEnd = Math.min(endLine, docEnd);\n\n\t\tfor (let pos = startLine; pos <= evalEnd; pos++) {\n\t\t\tconst state = this.doc.getLineAt(pos);\n\t\t\tif (!state) continue;\n\n\t\t\t// All processed lines are in-viewport for setViewport, or conditionally\n\t\t\t// in-viewport for evaluate (handled by caller). We pass `true` here\n\t\t\t// because evaluateSingleLine's `inViewport` param controls Tier 1 vs\n\t\t\t// Tier 3 dispatch; callers must manage this distinction externally.\n\t\t\t//\n\t\t\t// evaluate() handles this by passing `inViewport` per-line; it loops\n\t\t\t// directly rather than using this helper for that reason.\n\t\t\tconst lineResult = this.evaluateSingleLine(state, pos, true);\n\t\t\tlines.push(lineResult);\n\n\t\t\tif (lineResult.tier === EvalTier.Tier1) tierCounts.tier1++;\n\t\t\telse if (lineResult.tier === EvalTier.Tier2) tierCounts.tier2++;\n\t\t\telse if (lineResult.tier === EvalTier.Tier3) tierCounts.tier3++;\n\t\t\telse tierCounts.skipped++;\n\n\t\t\tif (lineResult.results) {\n\t\t\t\tresultMap.set(pos, lineResult.results.flat());\n\t\t\t}\n\t\t}\n\n\t\treturn { lines, resultMap, tierCounts };\n\t}\n\n\t/**\n\t * Check whether any **variable-definition** line before `position`\n\t * (1-based, exclusive) is dirty.\n\t *\n\t * Used by `setViewport()` to decide whether to fall back to `evaluate()`:\n\t * if a variable-def before the viewport is dirty, the checkpoint state\n\t * `restoreTo()` would use may be stale and we need to reprocess from\n\t * line 1 to rebuild checkpoints correctly.\n\t *\n\t * Deliberately narrower than `DocumentModel.hasAnyDirtyLineBefore()`:\n\t * checkpoints only snapshot variable-def lines (see VMCheckpointer), so a\n\t * dirty plain-expression line before the viewport can't have invalidated\n\t * one, there's nothing checkpointed for it to invalidate. Using the\n\t * broader check here previously caused a real perf bug: `PageManager`'s\n\t * cold-page eviction marks evicted non-variable-def lines dirty, so\n\t * scrolling far into a large, variable-def-free document would trip this\n\t * guard, fall back to `evaluate()`, which recompiles those lines via\n\t * Tier 3 (never clearing their dirty flag by design), causing the very\n\t * next `maintainAfterEval()` to re-evict and re-dirty them, a\n\t * self-sustaining loop that pinned every subsequent `setViewport()` call\n\t * to the cost of a full re-evaluation instead of O(visible lines).\n\t *\n\t * Delegates to DocumentModel.hasAnyDirtyVariableDefLineBefore(), which\n\t * tracks dirty lineIds incrementally instead of scanning every line up to\n\t * `position` on every call. This used to be a real per-scroll cost\n\t * (benchmarked at ~10ms scrolled near the bottom of a 20k-line document)\n\t * since it fired on every viewport change, not just edits.\n\t */\n\tprivate hasDirtyLinesBefore(position: number): boolean {\n\t\treturn this.doc.hasAnyDirtyVariableDefLineBefore(position);\n\t}\n\n\t/**\n\t * Evaluate a single line using the appropriate tier.\n\t *\n\t * Tier assignment logic:\n\t * - Empty/markdown-only lines → skipped\n\t * - Dirty + in-viewport → Tier 1 (full pipeline)\n\t * - Dirty + not in viewport → Tier 3 (compile-only, execute variable defs)\n\t * - Clean + has bytecode + in viewport → Tier 2 (execute from cache)\n\t * - Clean + no bytecode → skipped (non-evaluable)\n\t */\n\tprivate evaluateSingleLine(\n\t\tstate: LineState,\n\t\tlineNumber: number,\n\t\tinViewport: boolean\n\t): EvalLineResult {\n\t\tconst baseResult: Omit<EvalLineResult, \"tier\" | \"result\" | \"error\"> = {\n\t\t\tlineId: state.lineId,\n\t\t\tlineNumber,\n\t\t};\n\n\t\t// Skip empty/markdown-only lines\n\t\tif (state.isEmpty || isEmptyLine(state.text)) {\n\t\t\tstate.isEmpty = true;\n\t\t\tthis.doc.markClean(state.lineId);\n\t\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t\t}\n\n\t\t// Extract all evaluable expressions (may be multiple inline solves)\n\t\tconst { expressions, inlineSolveCount } = this.extractExpressions(state);\n\t\tif (expressions.length === 0) {\n\t\t\tstate.isEmpty = true;\n\t\t\tthis.doc.markClean(state.lineId);\n\t\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t\t}\n\n\t\t// Determine the expression to evaluate (only needed for dirty lines)\n\t\tif (state.dirty) {\n\t\t\tif (inViewport) {\n\t\t\t\t// ── Tier 1: Visible + Dirty → Full Pipeline ──────────\n\t\t\t\treturn this.evaluateTier1(state, lineNumber, expressions, inlineSolveCount, baseResult);\n\t\t\t} else {\n\t\t\t\t// ── Tier 3: Invisible + Dirty → Compile-only ─────────\n\t\t\t\t// Skip recompilation if already compiled by a previous Tier 3 pass.\n\t\t\t\t// Non-variable-def lines keep dirty=true after Tier 3 (so they get\n\t\t\t\t// Tier 1 when scrolled into view), but recompiling identical text\n\t\t\t\t// produces the same bytecode and DAG entries. Text changes clear\n\t\t\t\t// bytecodes via DocumentModel.editLine(), so a length check is safe.\n\t\t\t\tif (state.bytecodes.length > 0 && state.bytecodes.length === expressions.length && !state.isVariableDef) {\n\t\t\t\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t\t\t\t}\n\t\t\t\treturn this.evaluateTier3(state, lineNumber, expressions, inlineSolveCount, baseResult);\n\t\t\t}\n\t\t}\n\n\t\t// Line is clean\n\t\tif (inViewport && state.bytecodes.length > 0) {\n\t\t\t// ── Tier 2: Visible + Cached → Execute from bytecode ────\n\t\t\treturn this.evaluateTier2(state, lineNumber, baseResult);\n\t\t}\n\n\t\t// Clean, not in viewport, or no bytecode → skip\n\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t}\n\n\t/**\n\t * Tier 1: Full pipeline, lex, parse, compile, execute.\n\t * Uses the engine's existing evaluateLine() which handles all pipeline\n\t * stages including DAG updates and LineCache population.\n\t *\n\t * Supports multiple expressions per line (inline solves). Evaluates each\n\t * expression left-to-right through the engine so variable definitions in\n\t * earlier solves update the VM state before later solves are evaluated.\n\t * Reads/writes are aggregated across all expressions for the DAG.\n\t */\n\tprivate evaluateTier1(\n\t\tstate: LineState,\n\t\tlineNumber: number,\n\t\texpressions: string[],\n\t\tinlineSolveCount: number,\n\t\tbaseResult: Omit<EvalLineResult, \"tier\" | \"result\" | \"error\">\n\t): EvalLineResult {\n\t\tconst allResults: Value[][] = [];\n\t\tconst allBytecodes: BytecodeProgram[] = [];\n\t\tconst allReads = new Set<string>();\n\t\tconst allWrites = new Set<string>();\n\t\tlet hasVariableDef = false;\n\t\tlet lastValue: Value | null = null;\n\t\tlet firstError: string | null = null;\n\t\tlet anyFailed = false;\n\t\t/** Set when any expression returned a value still waiting on a resolver. */\n\t\tlet anyPending = false;\n\n\t\t// Evaluate each expression independently, a failure in one expression\n\t\t// (e.g., parse error in s`bad syntax`) must not prevent other expressions\n\t\t// on the same line from being evaluated and having their results stored.\n\t\t// Without per-expression error handling, same-line cross-reference inline\n\t\t// solves (s`:a = 5` s`:b = a + 3` s`a + b`) would lose ALL results when\n\t\t// the third expression throws because 'b' references cross a VM state\n\t\t// boundary or the engine encounters a transient error.\n\t\tfor (const expression of expressions) {\n\t\t\tif (!expression.trim()) continue;\n\n\t\t\tlet value: Value[] | null = null;\n\t\t\tlet entry: { bytecode: BytecodeProgram; readVariables: string[]; writeVariable: string | null } | undefined;\n\n\t\t\ttry {\n\t\t\t\t// evaluateLine returns the single evaluated Value; this evaluator\n\t\t\t\t// keeps its results grouped as Value[] per expression (allResults\n\t\t\t\t// is Value[][]), so wrap the one value into its group here.\n\t\t\t\tconst evaluated = this.engine.evaluateLine(lineNumber, expression);\n\t\t\t\tvalue = [evaluated];\n\t\t\t\tlastValue = evaluated;\n\t\t\t\t// Sync the DocumentModel from the LineCache.\n\t\t\t\t// Use get(lineNumber, expression) instead of getEntryForLine(lineNumber)\n\t\t\t\t// because multiple expressions on the same line share the same lineNumber\n\t\t\t\t// and getEntryForLine always returns the FIRST entry (Map insertion order).\n\t\t\t\tentry = this.engine.getLineCache().get(lineNumber, expression) as typeof entry;\n\t\t\t} catch (e) {\n\t\t\t\tconst errorMessage = e instanceof Error ? e.message : String(e);\n\t\t\t\tif (!firstError) firstError = errorMessage;\n\t\t\t\tanyFailed = true;\n\t\t\t\tvalue = null;\n\t\t\t}\n\n\t\t\t// An unresolved async value does not throw, so `anyFailed` alone would\n\t\t\t// let this line be marked clean while its data has not arrived. Once\n\t\t\t// clean, nothing re-runs the resolver preflight and the value stays\n\t\t\t// pending for good. Treat it as not-yet-complete instead.\n\t\t\tif (value && value.some((v) => v.type === ValueType.Pending)) {\n\t\t\t\tanyPending = true;\n\t\t\t}\n\n\t\t\tif (value) {\n\t\t\t\tallResults.push(value);\n\t\t\t} else {\n\t\t\t\t// Expression failed, push an ErrorValue sentinel so results[] stays\n\t\t\t\t// aligned with expressions[] and bytecodes[] indices. Downstream code\n\t\t\t\t// checking result.type === Error will find it, vs a raw null that NPEs.\n\t\t\t\tallResults.push([errorValue(\"eval_failed\", firstError ?? \"unknown error\")]);\n\t\t\t}\n\n\t\t\tif (entry) {\n\t\t\t\tallBytecodes.push(entry.bytecode);\n\t\t\t\tfor (const r of entry.readVariables) allReads.add(r);\n\t\t\t\tif (entry.writeVariable) {\n\t\t\t\t\tallWrites.add(entry.writeVariable);\n\t\t\t\t\thasVariableDef = true;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Fallback: LineCache missed, compile expression ourselves\n\t\t\t\ttry {\n\t\t\t\t\tconst { program, reads, writes } = this.engine.compileExpression(expression);\n\t\t\t\t\tallBytecodes.push(program);\n\t\t\t\t\tfor (const r of reads) allReads.add(r);\n\t\t\t\t\tfor (const w of writes) allWrites.add(w);\n\t\t\t\t\tif (writes.length > 0) hasVariableDef = true;\n\t\t\t\t} catch (compileErr) {\n\t\t\t\t\t// Push empty bytecode, expression will recompile on next pass.\n\t\t\t\t\t// The expression still failed to compile, but reads/writes were\n\t\t\t\t\t// already extracted from its tokens before the parse attempt\n\t\t\t\t\t// compileExpression() surfaces them via the thrown error's\n\t\t\t\t\t// context. Register them anyway so the DAG knows this line\n\t\t\t\t\t// depends on those variables and re-evaluates it once they\n\t\t\t\t\t// become defined, instead of losing the dependency entirely.\n\t\t\t\t\tallBytecodes.push({ opcodes: new Uint8Array(0), numbers: new Float64Array(0), strings: [], hasAsync: false });\n\t\t\t\t\tif (compileErr instanceof EngineError && compileErr.context) {\n\t\t\t\t\t\tconst errReads = compileErr.context.reads;\n\t\t\t\t\t\tconst errWrites = compileErr.context.writes;\n\t\t\t\t\t\tif (Array.isArray(errReads)) for (const r of errReads) allReads.add(r);\n\t\t\t\t\t\tif (Array.isArray(errWrites)) for (const w of errWrites) allWrites.add(w);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst reads = [...allReads];\n\t\tconst writes = [...allWrites];\n\n\t\t// Always store results, even partial ones. If any expression failed\n\t\t// the line stays dirty so the failed expression(s) get retried on the\n\t\t// next evaluation pass. But successfully-evaluated expressions' results\n\t\t// are preserved so the DAG, UI decorations, and downstream consumers\n\t\t// can use them immediately.\n\t\tif (anyFailed || anyPending) {\n\t\t\t// Store partial results via updateLineCompiled (doesn't clear dirty).\n\t\t\t// The successful expressions' bytecodes are cached so Tier 2 works\n\t\t\t// for them on the next scroll pass.\n\t\t\tthis.doc.updateLineCompiled(\n\t\t\t\tstate.lineId,\n\t\t\t\texpressions,\n\t\t\t\tallBytecodes,\n\t\t\t\treads,\n\t\t\t\twrites,\n\t\t\t\thasVariableDef,\n\t\t\t\tinlineSolveCount,\n\t\t\t);\n\t\t\t// Also set results for the successful expressions\n\t\t\tstate.results = allResults;\n\t\t\tstate.result = allResults[0]?.[0] ?? null;\n\t\t\tstate.inlineSolveCount = inlineSolveCount;\n\t\t\tstate.expressions = expressions;\n\t\t} else {\n\t\t\t// All expressions succeeded, store full results and mark clean\n\t\t\tthis.doc.updateLineResult(\n\t\t\t\tstate.lineId,\n\t\t\t\tallResults,\n\t\t\t\tallBytecodes,\n\t\t\t\texpressions,\n\t\t\t\treads,\n\t\t\t\twrites,\n\t\t\t\thasVariableDef,\n\t\t\t\tinlineSolveCount,\n\t\t\t);\n\t\t}\n\n\t\t// Register reads/writes in DAG (aggregated across all expressions).\n\t\t// Always register, even lines with no reads/writes (pure expressions\n\t\t// like \"2+2\") need DAG entries so downstream queries for line presence work.\n\t\tthis.dag.registerLine(lineNumber, reads, writes);\n\n\t\t// ── Checkpoint after variable definition ──\n\t\t// A pending value is not a value worth checkpointing: restoring it would\n\t\t// reinstate the unresolved placeholder rather than the eventual result.\n\t\tif (this.checkpointer && writes.length > 0 && !anyFailed && !anyPending) {\n\t\t\tthis.checkpointer.snapshot(lineNumber, state.lineId, writes);\n\t\t}\n\n\t\treturn {\n\t\t\t...baseResult,\n\t\t\ttier: EvalTier.Tier1,\n\t\t\tresult: lastValue,\n\t\t\tresults: allResults,\n\t\t\terror: firstError,\n\t\t};\n\t}\n\n\t/**\n\t * Tier 2: Execute from cached bytecode only.\n\t * Skips lexing, parsing, and compiling, runs the pre-compiled bytecode\n\t * against the engine's shared VM. Supports multiple bytecodes per line\n\t * (inline solves), each is executed left-to-right so variable definitions\n\t * in earlier bytecodes update the VM before later ones run.\n\t * Assumes the VM already has correct variable state from preceding\n\t * Tier-1 evaluations.\n\t */\n\tprivate evaluateTier2(\n\t\tstate: LineState,\n\t\tlineNumber: number,\n\t\tbaseResult: Omit<EvalLineResult, \"tier\" | \"result\" | \"error\">\n\t): EvalLineResult {\n\t\tif (state.bytecodes.length === 0) {\n\t\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t\t}\n\n\t\tconst results: Value[][] = [];\n\t\tlet lastValue: Value | null = null;\n\t\tlet firstError: string | null = null;\n\t\tlet anyFailed = false;\n\n\t\t// Execute each bytecode independently, a failure in one should not\n\t\t// prevent other bytecodes on the same line from executing. Same-line\n\t\t// inline solves with variable definitions (s`:a = 5` s`a + 3`) rely\n\t\t// on earlier bytecodes updating the VM before later ones execute.\n\t\tfor (const bytecode of state.bytecodes) {\n\t\t\tif (bytecode.opcodes.length === 0) continue;\n\t\t\ttry {\n\t\t\t\tconst value = this.engine.executeCached(bytecode, lineNumber);\n\t\t\t\tlastValue = value;\n\t\t\t\tresults.push([value]);\n\t\t\t} catch (e) {\n\t\t\t\tconst errorMessage = e instanceof Error ? e.message : String(e);\n\t\t\t\tif (!firstError) firstError = errorMessage;\n\t\t\t\tanyFailed = true;\n\t\t\t\t// Push error sentinel to maintain results[i] ↔ bytecodes[i] alignment\n\t\t\t\tresults.push([errorValue(\"exec_failed\", errorMessage)]);\n\t\t\t}\n\t\t}\n\n\t\t// Update DAG: re-register reads/writes from the cached metadata.\n\t\t// Always register, even empty reads/writes so DAG line-presence queries work.\n\t\tthis.dag.registerLine(lineNumber, state.reads, state.writes);\n\n\t\tstate.results = results;\n\t\tstate.result = results[0]?.[0] ?? null;\n\t\tif (anyFailed) {\n\t\t\t// Mark dirty so failed bytecodes are re-compiled (Tier 1) next pass\n\t\t\tthis.doc.markDirty(state.lineId);\n\t\t}\n\n\t\treturn { ...baseResult, tier: EvalTier.Tier2, result: lastValue, results, error: firstError };\n\t}\n\n\t/**\n\t * Tier 3: Compile-only for invisible lines.\n\t * Lex → Parse → Compile to discover reads/writes for the dependency graph.\n\t * Executes the bytecode ONLY if the line defines a variable (isVariableDef\n\t * or writes.length > 0), because variable assignments affect VM state\n\t * that other lines depend on. Pure expression lines are compiled but NOT\n\t * executed, saving CPU for large documents.\n\t *\n\t * Supports multiple expressions per line (inline solves). Each is compiled\n\t * separately; variable-def expressions are also executed.\n\t */\n\tprivate evaluateTier3(\n\t\tstate: LineState,\n\t\tlineNumber: number,\n\t\texpressions: string[],\n\t\tinlineSolveCount: number,\n\t\tbaseResult: Omit<EvalLineResult, \"tier\" | \"result\" | \"error\">\n\t): EvalLineResult {\n\t\tconst allBytecodes: BytecodeProgram[] = [];\n\t\tconst allReads = new Set<string>();\n\t\tconst allWrites = new Set<string>();\n\t\tlet hasVariableDef = false;\n\t\tlet lastResult: Value | null = null;\n\t\tlet firstError: string | null = null;\n\t\tlet anyFailed = false;\n\t\t/** Set when a result is still waiting on a resolver. */\n\t\tlet anyPending = false;\n\n\t\t// Compile each expression independently, a parse error in one\n\t\t// should not prevent other expressions from being compiled and\n\t\t// having their reads/writes registered in the DAG.\n\t\tfor (const expression of expressions) {\n\t\t\tif (!expression.trim()) continue;\n\n\t\t\ttry {\n\t\t\t\tconst { program, reads, writes } = this.engine.compileExpression(expression);\n\t\t\t\tallBytecodes.push(program);\n\t\t\t\tfor (const r of reads) allReads.add(r);\n\t\t\t\tfor (const w of writes) allWrites.add(w);\n\t\t\t\tif (writes.length > 0) hasVariableDef = true;\n\n\t\t\t\tif (writes.length > 0 && program.opcodes.length > 0) {\n\t\t\t\t\t// Variable definitions MUST execute to maintain VM state\n\t\t\t\t\tlastResult = this.engine.executeCached(program, lineNumber);\n\t\t\t\t\t// Same reasoning as Tier 1: a pending result does not throw,\n\t\t\t\t\t// and marking the line clean would strand it unresolved.\n\t\t\t\t\tif (lastResult && lastResult.type === ValueType.Pending) {\n\t\t\t\t\t\tanyPending = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tconst errorMessage = e instanceof Error ? e.message : String(e);\n\t\t\t\tif (!firstError) firstError = errorMessage;\n\t\t\t\tanyFailed = true;\n\t\t\t\t// Push empty bytecode placeholder for alignment\n\t\t\t\tallBytecodes.push({ opcodes: new Uint8Array(0), numbers: new Float64Array(0), strings: [], hasAsync: false });\n\t\t\t}\n\t\t}\n\n\t\tconst reads = [...allReads];\n\t\tconst writes = [...allWrites];\n\n\t\t// Store compile-only state in DocumentModel, even partial results\n\t\t// preserve successful expressions' bytecodes and DAG data.\n\t\tthis.doc.updateLineCompiled(\n\t\t\tstate.lineId,\n\t\t\texpressions,\n\t\t\tallBytecodes,\n\t\t\treads,\n\t\t\twrites,\n\t\t\thasVariableDef,\n\t\t\tinlineSolveCount,\n\t\t);\n\n\t\t// Register reads/writes in DAG regardless, partial data is valid.\n\t\t// Always register, even empty reads/writes for DAG line-presence queries.\n\t\tthis.dag.registerLine(lineNumber, reads, writes);\n\n\t\tif (hasVariableDef && lastResult && !anyFailed && !anyPending) {\n\t\t\tstate.results = [[lastResult]];\n\t\t\tstate.result = lastResult;\n\t\t\tthis.doc.markClean(state.lineId);\n\n\t\t\t// ── Checkpoint after variable definition ────────────\n\t\t\tif (this.checkpointer) {\n\t\t\t\tthis.checkpointer.snapshot(lineNumber, state.lineId, writes);\n\t\t\t}\n\t\t}\n\n\t\treturn { ...baseResult, tier: EvalTier.Tier3, result: lastResult, results: hasVariableDef && lastResult && !anyFailed && !anyPending ? [[lastResult]] : undefined, error: firstError };\n\t}\n\n\t// ── Public checkpoint API (used by Phase 5.2e setViewport) ──────\n\n\t/**\n\t * Restore the VM to the state at or just after the given line number.\n\t *\n\t * Finds the nearest checkpoint at or before `lineNumber` and replays\n\t * all variable definitions from the checkpoint chain into the VM.\n\t * After calling this, the VM is ready to evaluate lines starting at\n\t * `lineNumber + 1` without re-evaluating all preceding lines.\n\t *\n\t * **Usage:** Phase 5.2e's `setViewport()` calls `restoreTo(viewport.startLine - 1)`\n\t * before evaluating only the newly visible lines. This is the key to\n\t * O(visible lines) scrolling.\n\t *\n\t * @param lineNumber The line number to restore to. Variables defined\n\t * at lines ≤ this number will be available in the VM.\n\t */\n\trestoreTo(lineNumber: number): void {\n\t\tif (this.checkpointer) {\n\t\t\tthis.checkpointer.restoreTo(lineNumber);\n\t\t}\n\t}\n\n\t/**\n\t * Get the VM checkpointer, or null if checkpointing is disabled.\n\t */\n\tgetCheckpointer(): VMCheckpointer | null {\n\t\treturn this.checkpointer;\n\t}\n\n\t/**\n\t * Get the PageManager (Phase 5.2g).\n\t * Exposed for testing.\n\t */\n\tgetPageManager(): PageManager {\n\t\treturn this.pageManager;\n\t}\n\n\t// ── Phase 5.2g: Directional preloading ──────────────────────────\n\n\t/**\n\t * Preload the next 1–2 pages in the current scroll direction.\n\t *\n\t * Called during `setViewport()` (scroll-only path). Collects dirty\n\t * uncompiled lines in pages just beyond the viewport and dispatches\n\t * them to the background compilation worker so bytecode is ready\n\t * before the user scrolls those lines into view.\n\t */\n\tprivate preloadNextPages(viewport: ViewportRange): void {\n\t\tconst targets = this.pageManager.getPreloadTargets(viewport, this.doc);\n\t\tif (targets.length === 0) return;\n\n\t\t// Lazy-init worker if needed\n\t\tif (!this.compilationWorker) {\n\t\t\tthis.compilationWorker = new CompilationWorkerManager();\n\t\t}\n\n\t\t// Fire-and-forget: worker compiles, stores bytecode on response\n\t\tthis.compilationWorker.compileBatch(targets).then((results) => {\n\t\t\tthis.compilationWorker!.storeResults(results, this.doc);\n\t\t}).catch((_err) => {\n\t\t\t// Non-fatal, next evaluate() will compile synchronously\n\t\t});\n\t}\n\n\t/**\n\t * Collect invisible dirty lines that need background compilation.\n\t *\n\t * Iterates lines beyond `viewport.endLine`, filtering for:\n\t * - Dirty lines (need re-compilation)\n\t * - Non-empty, non-markdown lines\n\t * - No existing bytecode (skip already-compiled Tier 3 lines)\n\t *\n\t * Returns CompileRequestItem[] suitable for CompilationWorkerManager.\n\t */\n\tprivate collectInvisibleCompileTargets(viewport: ViewportRange): CompileRequestItem[] {\n\t\tconst items: CompileRequestItem[] = [];\n\t\tconst docEnd = this.doc.lineCount;\n\t\tconst startPos = viewport.endLine + 1;\n\n\t\tfor (let pos = startPos; pos <= docEnd; pos++) {\n\t\t\tconst state = this.doc.getLineAt(pos);\n\t\t\tif (!state) continue;\n\n\t\t\t// Skip clean lines\n\t\t\tif (!state.dirty) continue;\n\n\t\t\t// Skip already-compiled lines\n\t\t\tif (state.bytecodes.length > 0 && !state.isVariableDef) continue;\n\n\t\t\t// Skip empty/markdown-only lines\n\t\t\tif (state.isEmpty || isEmptyLine(state.text)) continue;\n\n\t\t\tconst { expressions } = this.extractExpressions(state);\n\t\t\tif (expressions.length === 0) continue;\n\n\t\t\t// Create one CompileRequestItem per expression (inline solves\n\t\t\t// on the same line share the same lineId + textHash). The worker\n\t\t\t// compiles each independently; storeResults batches by lineId.\n\t\t\tfor (const expression of expressions) {\n\t\t\t\tif (!expression.trim()) continue;\n\t\t\t\titems.push({\n\t\t\t\t\tlineId: state.lineId,\n\t\t\t\t\texpression,\n\t\t\t\t\ttextHash: state.textHash,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn items;\n\t}\n\n\t/**\n\t * Extract all evaluable expressions from a LineState.\n\t *\n\t * For full-line expressions: returns `{ expressions: [trimmedText], inlineSolveCount: 0 }`.\n\t * For inline solve lines: returns `{ expressions: [...allSolves], inlineSolveCount: N }`.\n\t * For pre-extracted (cached) expressions: returns the cached array.\n\t *\n\t * Inline solves are extracted left-to-right via the sharedLexer, so variable\n\t * definitions in earlier solves (e.g., `s\\`x = 5\\` more text s\\`x + 1\\``)\n\t * correctly update the VM state before later solves are evaluated.\n\t */\n\tprivate extractExpressions(state: LineState): { expressions: string[]; inlineSolveCount: number } {\n\t\t// Use pre-extracted expressions if available (from cache / previous evaluation)\n\t\tif (state.expressions.length > 0) {\n\t\t\treturn { expressions: state.expressions, inlineSolveCount: state.inlineSolveCount };\n\t\t}\n\n\t\tconst trimmed = state.text.trim();\n\t\tif (trimmed.length === 0) return { expressions: [], inlineSolveCount: 0 };\n\n\t\t// Check for inline solve syntax: s`expression`\n\t\tconst inlineSpans = sharedLexer.findInlineSolves(state.text);\n\t\tif (inlineSpans.length > 0) {\n\t\t\treturn {\n\t\t\t\texpressions: inlineSpans.map(s => s.expression),\n\t\t\t\tinlineSolveCount: inlineSpans.length,\n\t\t\t};\n\t\t}\n\n\t\t// Full-line expression\n\t\treturn { expressions: [trimmed], inlineSolveCount: 0 };\n\t}\n}\n","/**\n * Whole-document evaluation through the incremental engine.\n *\n * The engine has two ways to read a document, and they are not interchangeable.\n * {@link ExpressionEngine.parseDocument} is the light batch pass: it scans the\n * text, reads earlier lines' results, and skips markdown, which is everything\n * line references, category tags and table columns need. What it has no way to\n * do is re-run an earlier line with a variable bound to a trial value, which is\n * exactly what goal seek (`solve line N for x = target`) is, so goal seek comes\n * back as a `GOAL_SEEK_NO_DOCUMENT` error through `parseDocument`.\n *\n * The re-run primitive lives on the incremental `DocumentModel` +\n * `ThreeTierEvaluator` path (a live editor drives it on every keystroke). This\n * helper stands that path up for a single pass and hands back the familiar\n * {@link ParsingResult}, so a caller reads the answers exactly as it would from\n * `parseDocument`, goal seek included. A documentation notepad that wants goal\n * seek to resolve, and the tests that prove those examples, both go through\n * here.\n *\n * Two boundaries, each deliberate:\n *\n * - It builds a fresh model and evaluator per call and disposes the evaluator\n * before returning, which suits occasional evaluation, not the keystroke loop\n * a real editor runs against one long-lived `ThreeTierEvaluator`.\n * - Unlike `parseDocument`, it does not classify a markdown table's own rows as\n * skippable: they reach the evaluator as expressions and error. A document\n * that mixes a raw table with goal seek is the one case that wants both paths,\n * the table read through `parseDocument` and the goal seek through here.\n */\nimport type { ExpressionEngine } from \"@solve-js/engine/ExpressionEngine\";\nimport { DocumentModel } from \"@solve-js/engine/DocumentModel\";\nimport { ThreeTierEvaluator } from \"@solve-js/engine/ThreeTierEvaluator\";\nimport { findInlineSolvesInLine } from \"@solve-js/engine/ExpressionEngineSafety\";\nimport { Value, ValueType } from \"@solve-js/vm/Value\";\nimport type {\n\tParsedLine,\n\tParsingResult,\n\tUnifiedParsingOptions,\n\tInlineSolvePosition,\n} from \"@solve-js/types/ParsingResult\";\n\n/** Read the human-readable message off an error Value (`unit` holds it, `value` holds the code). */\nfunction errorMessageOf(value: Value): string {\n\treturn typeof value.unit === \"string\" ? value.unit : String(value.value);\n}\n\n/**\n * Evaluate a whole document with full cross-line context, including the line\n * re-runs goal seek needs, and return per-line results in the same shape\n * {@link ExpressionEngine.parseDocument} produces.\n *\n * @param engine - The engine to borrow for the pass. Its current document model\n * (if any) is restored before returning.\n * @param input - The document text, newline-separated.\n * @param _options - Accepted so a call reads the same as `parseDocument`'s, but\n * not consulted: the incremental pass reads the document as markdown regardless.\n */\nexport function evaluateDocument(\n\tengine: ExpressionEngine,\n\tinput: string,\n\t_options: UnifiedParsingOptions = { inputType: \"markdown\" },\n): ParsingResult {\n\tconst previousDocumentModel = engine.getDocumentModel();\n\n\tconst doc = new DocumentModel();\n\tdoc.setDocument(input);\n\t// The constructor wires the model onto the engine (engine.setDocumentModel),\n\t// which is what makeLineContext reads to expose the re-run primitive.\n\tconst evaluator = new ThreeTierEvaluator(doc, engine);\n\n\ttry {\n\t\tconst lineCount = doc.lineCount;\n\t\tevaluator.evaluate({ startLine: 1, endLine: lineCount });\n\n\t\tconst lines: ParsedLine[] = [];\n\t\tconst errors: string[] = [];\n\t\t// Document character offsets are not carried on the line model, so they\n\t\t// are accumulated here to keep startPosition/endPosition faithful to\n\t\t// parseDocument's, one newline between lines.\n\t\tlet offset = 0;\n\n\t\tfor (let n = 1; n <= lineCount; n++) {\n\t\t\tconst state = doc.getLineAt(n)!;\n\t\t\tconst text = state.text;\n\t\t\tconst startPosition = offset;\n\t\t\tconst endPosition = offset + text.length;\n\t\t\toffset = endPosition + 1; // + the newline that separated this line from the next\n\n\t\t\tconst hasInlineSolves = state.inlineSolveCount > 0;\n\t\t\tlet inlineSolves: InlineSolvePosition[] = [];\n\t\t\tlet expression: string | null = null;\n\t\t\tlet result: Value | null = null;\n\n\t\t\tif (state.isEmpty) {\n\t\t\t\t// Prose, a heading, or a blank line: nothing to report.\n\t\t\t} else if (hasInlineSolves) {\n\t\t\t\t// Zip the located spans against the line's per-expression results,\n\t\t\t\t// which the model holds in the same left-to-right order.\n\t\t\t\tinlineSolves = findInlineSolvesInLine(text, n).map((span, i) => {\n\t\t\t\t\tconst value = state.results[i]?.[0] ?? null;\n\t\t\t\t\tif (value && value.type === ValueType.Error) {\n\t\t\t\t\t\tconst message = errorMessageOf(value);\n\t\t\t\t\t\terrors.push(`Line ${n}: ${message}`);\n\t\t\t\t\t\treturn { ...span, result: null, error: message };\n\t\t\t\t\t}\n\t\t\t\t\treturn { ...span, result: value, error: null };\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\texpression = state.expressions[0] ?? null;\n\t\t\t\t// A returned error (goal seek with no document, a faulted\n\t\t\t\t// conversion) stays in `result` as an error-typed Value, exactly\n\t\t\t\t// as parseDocument leaves it, so both document passes report a\n\t\t\t\t// line the same way and a caller can compare them value for\n\t\t\t\t// value. It is also gathered into `errors` for a flat list.\n\t\t\t\tresult = state.result ?? null;\n\t\t\t\tif (result && result.type === ValueType.Error) {\n\t\t\t\t\terrors.push(`Line ${n}: ${errorMessageOf(result)}`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlines.push({\n\t\t\t\tlineNumber: n,\n\t\t\t\ttext,\n\t\t\t\tstartPosition,\n\t\t\t\tendPosition,\n\t\t\t\tisEmpty: state.isEmpty,\n\t\t\t\thasInlineSolves,\n\t\t\t\tinlineSolves,\n\t\t\t\texpression,\n\t\t\t\t// Always null: the incremental pass stores a line's failure as an\n\t\t\t\t// error-typed Value in `result` (above), never as a thrown error\n\t\t\t\t// the way parseDocument sets this field. Kept for shape parity.\n\t\t\t\terror: null,\n\t\t\t\tresult,\n\t\t\t});\n\t\t}\n\n\t\treturn { lines, totalLines: lineCount, errors };\n\t} finally {\n\t\t// Drop this pass's evaluator (unsubscribes it from the shared global\n\t\t// store) and put back whatever document the host had wired, so borrowing\n\t\t// the engine for one pass leaves nothing behind.\n\t\tevaluator.terminateWorker();\n\t\tengine.setDocumentModel(previousDocumentModel);\n\t}\n}\n"]}
1
+ {"version":3,"sources":["../src/engine/SegmentTree.ts","../src/engine/DocumentModel.ts","../src/engine/CompilationWorkerManager.ts","../src/engine/PageManager.ts","../src/engine/ThreeTierEvaluator.ts","../src/engine/evaluateDocument.ts"],"names":["SegmentTree","index","lineId","left","right","split","merge","createNode","midRight","mid","removed","startIndex","deleteCount","newIds","clampedStart","clampedCount","collectInOrder","newTree","buildTreap","lineIds","endIndex","clampedEnd","result","node","leftSize","targetStart","targetEnd","offset","nodeIndex","updateSize","collect","start","end","priority","pseudoRandom","seed","x","DocumentModel","maxLines","DEFAULT_CONFIG","text","countLines","ErrorFactory","rawLines","i","djb2Hash","id","changes","inserted","sorted","a","b","change","startIdx","removedIds","atLine","texts","startLine","endLine","lineNumber","newText","state","newHash","position","idx","pos","compiledAgainstHash","results","bytecodes","expressions","reads","writes","isVariableDef","inlineSolveCount","s","CompilationWorkerManager","engine_worker_default","event","data","pending","raw","err","items","worker","resolve","reject","doc","byLineId","batch","r","w","stored","opcodes","numbers","program","PAGE_SIZE","HOT_PAGE_RADIUS","WARM_PAGE_RADIUS","PRELOAD_PAGE_COUNT","COLD_EVICT_BUFFER","PageManager","_PageManager","pageNum","docLineCount","newViewport","viewport","viewportStartPage","viewportEndPage","lastPage","hotStart","hotEnd","warmStart","warmEnd","p","coldLeftEnd","coldLeftStart","coldRightStart","coldRightEnd","direction","pages","startPage","endPage","firstPreloadPage","range","expression","inlineSpans","sharedLexer","span","EvalTier","ThreeTierEvaluator","engine","checkpointer","sharedGlobalVariableStore","name","globalDagKey","signal","enableValueArena","lines","resultMap","tierCounts","docEnd","evalEnd","inViewport","lineResult","disableValueArena","startPos","_err","allWrites","lineNum","downstreamLineIds","writeVar","affected","names","baseResult","isEmptyLine","allResults","allBytecodes","allReads","hasVariableDef","lastValue","firstError","anyFailed","anyPending","value","entry","evaluated","e","errorMessage","v","errorValue","compileErr","EngineError","errReads","errWrites","bytecode","lastResult","targets","trimmed","errorMessageOf","evaluateDocument","input","_options","previousDocumentModel","evaluator","lineCount","errors","n","startPosition","endPosition","hasInlineSolves","inlineSolves","findInlineSolvesInLine","message"],"mappings":"iUA6CO,IAAMA,EAAN,KAAkB,CAAlB,cACN,IAAA,CAAQ,IAAA,CAAoB,MAK5B,IAAI,MAAA,EAAiB,CACpB,OAAO,KAAK,IAAA,CAAO,IAAA,CAAK,KAAK,IAAA,CAAO,CACrC,CAGA,IAAI,OAAA,EAAmB,CACtB,OAAO,KAAK,IAAA,GAAS,IACtB,CAOA,KAAA,CAAMC,CAAAA,CAAmC,CACxC,GAAI,EAAAA,CAAAA,CAAQ,CAAA,EAAKA,IAAU,IAAA,CAAK,IAAA,EAAM,MAAQ,CAAA,CAAA,CAAA,CAC9C,OAAO,K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,CAAC,CAAA,EAAK,IAAA,CAMrCvC,CAAAA,CAASuC,CAAAA,CAAM,MAAA,EAAU,IAAA,CACrBvC,GAAUA,CAAAA,CAAO,IAAA,GAAS,EAAA,EAC7BmK,CAAAA,CAAO,IAAA,CAAK,CAAA,KAAA,EAAQC,CAAC,CAAA,EAAA,EAAKR,EAAAA,CAAe5J,CAAM,CAAC,CAAA,CAAE,CAAA,CAAA,CAAA,CAIpDmH,CAAAA,CAAM,KAAK,CACV,UAAA,CAAYiD,CAAAA,CACZ,IAAA,CAAAlJ,CAAAA,CACA,aAAA,CAAAmJ,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,OAAA,CAAS/H,CAAAA,CAAM,OAAA,CACf,eAAA,CAAAgI,CAAAA,CACA,aAAAC,CAAAA,CACA,UAAA,CAAAlE,CAAAA,CAIA,KAAA,CAAO,IAAA,CACP,MAAA,CAAAtG,CACD,CAAC,EACF,CAEA,OAAO,CAAE,KAAA,CAAAmH,CAAAA,CAAO,UAAA,CAAY+C,CAAAA,CAAW,MAAA,CAAAC,CAAO,CAC/C,CAAA,OAAE,CAIDF,CAAAA,CAAU,eAAA,EAAgB,CAC1BrD,CAAAA,CAAO,gBAAA,CAAiBoD,CAAqB,EAC9C,CACD","file":"chunk-5R7S5KJJ.js","sourcesContent":["/**\n * SegmentTree, an order-statistic Treap (randomized BST).\n *\n * Replaces the flat `lineOrder: number[]` array in DocumentModel with a\n * balanced tree that supports O(log N) insert, delete, and get-at-index\n * operations. Each node stores a `lineId` and its subtree size, enabling\n * order-statistic queries (find the k-th element by position).\n *\n * Key operations:\n * getAt(index), O(log N) expected\n * insertAt(index), O(log N) expected\n * deleteAt(index), O(log N) expected\n * spliceAt(index, deleteCount, newIds), O(log N + deleteCount + insertCount)\n * indexOf(lineId), O(N) without reverse map; cached lazily in DocumentModel\n *\n * Implementation: Treap (Tree + Heap) with implicit keys.\n * Nodes are ordered by position (in-order traversal), not by lineId value.\n * The `size` field enables O(log N) order statistics.\n * Random priorities maintain balance with high probability (O(log N) depth).\n *\n * Memory: ~40 bytes per node (lineId + size + priority + left + right).\n * For 100K lines: ~4MB for tree structure (acceptable).\n */\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\ninterface Node {\n\tlineId: number;\n\t/** Total number of nodes in this subtree (including self). */\n\tsize: number;\n\t/** Random priority for heap property (maintains balance). */\n\tpriority: number;\n\tleft: Node | null;\n\tright: Node | null;\n}\n\n// ── SegmentTree ────────────────────────────────────────────────────────────\n\n/**\n * Maps document offsets to line numbers in logarithmic time.\n *\n * A document is edited constantly, and every edit shifts the offsets of every\n * line after it. Recomputing them linearly on each keystroke is what this\n * avoids.\n */\nexport class SegmentTree {\n\tprivate root: Node | null = null;\n\n\t// ── Public API ───────────────────────────────────────────────────────\n\n\t/** Total number of elements in the tree. */\n\tget length(): number {\n\t\treturn this.root ? this.root.size : 0;\n\t}\n\n\t/** Whether the tree is empty. */\n\tget isEmpty(): boolean {\n\t\treturn this.root === null;\n\t}\n\n\t/**\n\t * Get the lineId at the given 0-based index.\n\t * Returns undefined if index is out of bounds.\n\t * O(log N) expected.\n\t */\n\tgetAt(index: number): number | undefined {\n\t\tif (index < 0 || index >= (this.root?.size ?? 0)) return undefined;\n\t\treturn this.nodeAt(this.root, index).lineId;\n\t}\n\n\t/**\n\t * Insert a single lineId at the given 0-based index.\n\t * O(log N) expected.\n\t */\n\tinsertAt(index: number, lineId: number): void {\n\t\tconst [left, right] = split(this.root, index);\n\t\tthis.root = merge(merge(left, createNode(lineId)), right);\n\t}\n\n\t/**\n\t * Delete a single element at the given 0-based index.\n\t * Returns the removed lineId, or undefined if out of bounds.\n\t * O(log N) expected.\n\t */\n\tdeleteAt(index: number): number | undefined {\n\t\tif (index < 0 || index >= (this.root?.size ?? 0)) return undefined;\n\n\t\tconst [left, midRight] = split(this.root, index);\n\t\tconst [mid, right] = split(midRight, 1);\n\n\t\tconst removed = mid ? mid.lineId : undefined;\n\t\tthis.root = merge(left, right);\n\t\treturn removed;\n\t}\n\n\t/**\n\t * Bulk splice: delete `deleteCount` elements at `startIndex` (0-based),\n\t * then insert `newIds` in their place.\n\t *\n\t * Returns the removed lineId array.\n\t * O(log N + deleteCount + insertCount) expected.\n\t */\n\tspliceAt(\n\t\tstartIndex: number,\n\t\tdeleteCount: number,\n\t\tnewIds: number[]\n\t): number[] {\n\t\tconst clampedStart = Math.max(0, startIndex);\n\t\tconst clampedCount = Math.min(\n\t\t\tMath.max(0, deleteCount),\n\t\t\t(this.root?.size ?? 0) - clampedStart\n\t\t);\n\n\t\t// Split into three parts: [0, start) [start, start+count) [start+count, end)\n\t\tconst [left, midRight] = split(this.root, clampedStart);\n\t\tconst [mid, right] = split(midRight, clampedCount);\n\n\t\t// Collect removed IDs\n\t\tconst removed = collectInOrder(mid);\n\n\t\t// Build a treap from the new IDs and merge\n\t\tconst newTree = buildTreap(newIds, 0, newIds.length);\n\t\tthis.root = merge(merge(left, newTree), right);\n\n\t\treturn removed;\n\t}\n\n\t/**\n\t * Replace the entire tree with a new set of lineIds.\n\t * O(N), builds a balanced treap from a flat array.\n\t */\n\treplaceAll(lineIds: number[]): void {\n\t\tthis.root = buildTreap(lineIds, 0, lineIds.length);\n\t}\n\n\t/**\n\t * Get a contiguous range of lineIds by index.\n\t * O(rangeSize + log N), single in-order walk instead of N × O(log N).\n\t *\n\t * This is the hot path for viewport rendering in DocumentModel.getVisibleLines().\n\t */\n\tgetRange(startIndex: number, endIndex: number): number[] {\n\t\tconst clampedStart = Math.max(0, startIndex);\n\t\tconst clampedEnd = Math.min((this.root?.size ?? 0) - 1, endIndex);\n\t\tif (clampedStart > clampedEnd) return [];\n\n\t\tconst result: number[] = [];\n\t\tthis.collectRange(this.root, clampedStart, clampedEnd, 0, result);\n\t\treturn result;\n\t}\n\n\t/**\n\t * Clear the tree.\n\t */\n\tclear(): void {\n\t\tthis.root = null;\n\t}\n\n\t// ── Iteration ─────────────────────────────────────────────────────────\n\n\t/**\n\t * In-order iterator yielding all lineIds.\n\t */\n\t*[Symbol.iterator](): IterableIterator<number> {\n\t\tyield* this.inOrder(this.root);\n\t}\n\n\tprivate *inOrder(node: Node | null): IterableIterator<number> {\n\t\tif (!node) return;\n\t\tyield* this.inOrder(node.left);\n\t\tyield node.lineId;\n\t\tyield* this.inOrder(node.right);\n\t}\n\n\t// ── Private helpers ───────────────────────────────────────────────────\n\n\tprivate nodeAt(node: Node | null, index: number): Node {\n\t\t// This is only called with valid indices, so node is non-null\n\t\tconst leftSize = node!.left ? node!.left.size : 0;\n\n\t\tif (index < leftSize) {\n\t\t\treturn this.nodeAt(node!.left, index);\n\t\t} else if (index === leftSize) {\n\t\t\treturn node!;\n\t\t} else {\n\t\t\treturn this.nodeAt(node!.right, index - leftSize - 1);\n\t\t}\n\t}\n\n\t/**\n\t * Collect all node values in the range [targetStart, targetEnd] into result.\n\t * `offset` is the 0-based start of the current subtree within the full tree.\n\t * O(rangeSize + log N), skips entire subtrees outside the target range.\n\t */\n\tprivate collectRange(\n\t\tnode: Node | null,\n\t\ttargetStart: number,\n\t\ttargetEnd: number,\n\t\toffset: number,\n\t\tresult: number[]\n\t): void {\n\t\tif (!node) return;\n\n\t\tconst leftSize = node.left ? node.left.size : 0;\n\t\tconst nodeIndex = offset + leftSize;\n\n\t\t// Traverse left subtree if it overlaps the target range\n\t\tif (nodeIndex > targetStart && node.left) {\n\t\t\tthis.collectRange(node.left, targetStart, targetEnd, offset, result);\n\t\t}\n\n\t\t// Include this node if within range\n\t\tif (nodeIndex >= targetStart && nodeIndex <= targetEnd) {\n\t\t\tresult.push(node.lineId);\n\t\t}\n\n\t\t// Traverse right subtree if it overlaps the target range\n\t\tif (nodeIndex < targetEnd && node.right) {\n\t\t\tthis.collectRange(node.right, targetStart, targetEnd, nodeIndex + 1, result);\n\t\t}\n\t}\n}\n\n// ── Free functions ──────────────────────────────────────────────────────────\n\n/** Create a new treap node. */\nfunction createNode(lineId: number): Node {\n\treturn {\n\t\tlineId,\n\t\tsize: 1,\n\t\tpriority: Math.random(),\n\t\tleft: null,\n\t\tright: null,\n\t};\n}\n\n/** Update a node's size from its children. */\nfunction updateSize(node: Node): void {\n\tnode.size = 1 + (node.left ? node.left.size : 0) + (node.right ? node.right.size : 0);\n}\n\n/**\n * Merge two treaps. All keys in `left` must be ≤ all keys in `right`.\n * O(log N) expected.\n */\nfunction merge(left: Node | null, right: Node | null): Node | null {\n\tif (!left) return right;\n\tif (!right) return left;\n\n\tif (left.priority > right.priority) {\n\t\tleft.right = merge(left.right, right);\n\t\tupdateSize(left);\n\t\treturn left;\n\t} else {\n\t\tright.left = merge(left, right.left);\n\t\tupdateSize(right);\n\t\treturn right;\n\t}\n}\n\n/**\n * Split a treap at `index` (0-based).\n * Returns [left, right] where `left` contains the first `index` elements\n * and `right` contains the rest.\n * O(log N) expected.\n */\nfunction split(\n\tnode: Node | null,\n\tindex: number\n): [Node | null, Node | null] {\n\tif (!node) return [null, null];\n\n\tconst leftSize = node.left ? node.left.size : 0;\n\n\tif (index <= leftSize) {\n\t\tconst [left, right] = split(node.left, index);\n\t\tnode.left = right;\n\t\tupdateSize(node);\n\t\treturn [left, node];\n\t} else {\n\t\tconst [left, right] = split(node.right, index - leftSize - 1);\n\t\tnode.right = left;\n\t\tupdateSize(node);\n\t\treturn [node, right];\n\t}\n}\n\n/**\n * Collect all lineIds from a treap in-order.\n * O(N).\n */\nfunction collectInOrder(node: Node | null): number[] {\n\tconst result: number[] = [];\n\tcollect(node, result);\n\treturn result;\n}\n\nfunction collect(node: Node | null, result: number[]): void {\n\tif (!node) return;\n\tcollect(node.left, result);\n\tresult.push(node.lineId);\n\tcollect(node.right, result);\n}\n\n/**\n * Build a balanced treap from a flat array of lineIds.\n * Uses divide-and-conquer with pre-sorted priorities to produce\n * a heap-ordered tree in O(N) time.\n * O(N).\n */\nfunction buildTreap(lineIds: number[], start: number, end: number): Node | null {\n\tif (start >= end) return null;\n\n\tconst mid = Math.floor((start + end) / 2);\n\n\t// Generate a deterministic-but-random priority based on position\n\t// This ensures the same array always produces the same tree shape\n\tconst priority = pseudoRandom(mid);\n\n\tconst node: Node = {\n\t\tlineId: lineIds[mid],\n\t\tsize: end - start,\n\t\tpriority,\n\t\tleft: buildTreap(lineIds, start, mid),\n\t\tright: buildTreap(lineIds, mid + 1, end),\n\t};\n\n\treturn node;\n}\n\n/**\n * Simple pseudo-random number generator for deterministic treap building.\n * Uses a multiplicative hash of the input.\n */\nfunction pseudoRandom(seed: number): number {\n\tlet x = seed;\n\tx = ((x >> 16) ^ x) * 0x45d9f3b;\n\tx = ((x >> 16) ^ x) * 0x45d9f3b;\n\tx = (x >> 16) ^ x;\n\treturn x / 0xffffffff; // normalize to [0, 1)\n}\n","import { Value } from \"@solve-js/vm/Value\";\nimport { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { djb2Hash } from \"@solve-js/utilities/Hash\";\nimport { SegmentTree } from \"@solve-js/engine/SegmentTree\";\nimport { DEFAULT_CONFIG } from \"@solve-js/constants/Configuration\";\nimport { countLines } from \"@solve-js/utilities/Strings\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n// ── LineState ──────────────────────────────────────────────────────────────\n\n/**\n * Persistent per-line state tracked by the DocumentModel.\n *\n * Each line receives an immutable `lineId` that survives structural edits\n * (insertions, deletions, line shifts). This allows caches, the dependency\n * graph, and VM checkpoints to reference lines by ID instead of by volatile\n * line numbers.\n *\n * ── Multi-expression support ─────────────────────────────────────────\n * A single document line may contain multiple inline solves (`s\\`...\\``).\n * To support this without breaking the 1:1 line-to-DAG-node contract:\n * - `expressions[]` holds all extracted expression strings (1 entry for\n * full-line expressions, N entries for N inline solves).\n * - `bytecodes[]` holds compiled bytecode in corresponding order.\n * - `results[]` holds evaluation **result groups** in corresponding order.\n * Each element is a `Value[]`, a group of Values produced by that expression.\n * For variable definitions, the group always has exactly 1 element.\n * For multi-output expressions (e.g., currency conversion), the group\n * may have multiple Values (one per target unit).\n * - `reads[]` and `writes[]` are aggregated across ALL expressions on\n * the line, the DAG treats the line as a single dependency node.\n * - `inlineSolveCount` is 0 for full-line expressions, >0 for inline solves.\n */\nexport interface LineState {\n\t/** Immutable unique identifier, survives all structural edits. */\n\treadonly lineId: number;\n\n\t/** djb2 hash of the line text, used for O(1) change detection. */\n\ttextHash: number;\n\n\t/** The full line text (may include markdown). */\n\ttext: string;\n\n\t/**\n\t * Extracted expression texts.\n\t * - Full-line expressions: one entry (the trimmed text).\n\t * - Inline solve lines: one entry per `s\\`...\\`` span, in left-to-right order.\n\t * - Markdown-only lines: empty array.\n\t */\n\texpressions: string[];\n\n\t/**\n\t * Compiled bytecode for each expression, in corresponding order.\n\t * Parallel to {@link expressions}.\n\t */\n\tbytecodes: BytecodeProgram[];\n\n\t/** Variables this line reads (for dependency tracking). Aggregated across all expressions. */\n\treads: string[];\n\n\t/** Variables this line writes (empty if not a variable definition). Aggregated across all expressions. */\n\twrites: string[];\n\n\t/**\n\t * Evaluation result groups for each expression, in corresponding order.\n\t * Each `Value[]` is a group of Values produced by one expression.\n\t * Variable definitions always produce exactly 1 Value per group.\n\t * Multi-output expressions (e.g. currency conversion) may produce N Values.\n\t */\n\tresults: Value[][];\n\n\t/**\n\t * Convenience accessor for the first expression's first result.\n\t * Equals `results[0]?.[0] ?? null`. For single-expression lines,\n\t * this is the primary result. For multi-expression (inline solve) lines,\n\t * prefer accessing `results[i][j]` directly.\n\t */\n\tresult: Value | null;\n\n\t/** True if this line needs re-evaluation. */\n\tdirty: boolean;\n\n\t/** True if any expression on this line defines a variable (never evict bytecode). */\n\tisVariableDef: boolean;\n\n\t/** True if this line contains only markdown (no evaluable expression). */\n\tisEmpty: boolean;\n\n\t/**\n\t * Number of inline solve expressions on this line.\n\t * 0 = full-line expression (or markdown-only).\n\t * >0 = N inline solves embedded in markdown text.\n\t */\n\tinlineSolveCount: number;\n}\n\n// ── ViewportRange ──────────────────────────────────────────────────────────\n\n/** The visible line range, used to decide which lines are evaluated eagerly. */\nexport interface ViewportRange {\n\tstartLine: number; // 1-based, inclusive\n\tendLine: number; // 1-based, inclusive\n}\n\n// ── LineChange ─────────────────────────────────────────────────────────────\n\n/** Describes a structural change to the document's line list. */\nexport interface LineChange {\n\t/** 1-based line number where the change starts. */\n\tstartLine: number;\n\t/** Number of lines deleted (0 for pure insertion). */\n\tdeleteCount: number;\n\t/** New line texts inserted in place of deleted lines. */\n\tinsertLines: string[];\n}\n\n// ── ApplyChangesResult ─────────────────────────────────────────────────────\n\n/** Result of applying changes to the document model. */\nexport interface ApplyChangesResult {\n\t/** Line IDs of newly inserted lines. */\n\tinserted: number[];\n\t/** Line IDs that were removed. */\n\tremoved: number[];\n}\n\n// ── DocumentModel ──────────────────────────────────────────────────────────\n\n/**\n * Persistent document model with O(log N) line lookups and structural edits.\n *\n * Design:\n * - Each line has an immutable `lineId` (monotonically increasing counter).\n * - `LineState` objects are stored in a `Map<lineId, LineState>` for O(1) access.\n * - Line ordering is maintained in a `SegmentTree` (order-statistic Treap) that\n * supports O(log N) insert, delete, and get-at-index operations.\n * - A lazy position cache (`Map<lineId, number>`) provides O(1) position lookups\n * after the first `getLinePosition()` call and is invalidated on structural edits.\n *\n * Key invariant: line IDs never change, only their positions in the order tree.\n * This means cached bytecode, dependency graph entries, and VM checkpoints\n * keyed by lineId remain valid across all structural edits.\n */\nexport class DocumentModel {\n\t/** Persistent line ID → LineState. */\n\tprivate lines: Map<number, LineState> = new Map();\n\n\t/** Order-statistic treap representing the current document line order. */\n\tprivate orderTree: SegmentTree = new SegmentTree();\n\n\t/** Monotonically increasing counter for new line IDs. */\n\tprivate nextLineId: number = 1;\n\n\t/**\n\t * Lazy position cache: lineId → 1-based position.\n\t * Built on first `getLinePosition()` call, invalidated on structural edits.\n\t */\n\tprivate _positionCache: Map<number, number> | null = null;\n\n\t/**\n\t * Line IDs currently marked dirty, maintained alongside every\n\t * `state.dirty` mutation (in this class and in every other module that\n\t * holds a direct `LineState` reference: ThreeTierEvaluator, PageManager).\n\t * Lets {@link hasAnyDirtyLineBefore} answer \"is anything before position\n\t * X dirty\" in O(d log N), d = current dirty count, typically tiny once\n\t * a document has settled after its initial evaluation, instead of\n\t * O(N log N), which used to mean every scroll event re-walked the WHOLE\n\t * document via `getLineAt()` regardless of how little of it was actually\n\t * dirty. Benchmarked: ~10.6ms per setViewport() call scrolled near the\n\t * bottom of a 20k-line document before this fix.\n\t */\n\tprivate dirtyLineIds: Set<number> = new Set();\n\n\t/**\n\t * Most lines this model will hold. See `constants/Configuration.ts`'s\n\t * `performance.maxDocumentLines`, which is where the default comes from and\n\t * which a host raises through its engine config; a host that builds a\n\t * DocumentModel directly passes it here instead.\n\t */\n\tprivate readonly maxLines: number;\n\n\t/**\n\t * @param maxLines - Ceiling on the line count, defaulting to the engine's\n\t * configured one. Every line costs a LineState with six arrays in it\n\t * whatever the line says, so the cost of a document is its line count and\n\t * nothing else bounds it: two hundred thousand lines of `1 + 1` exhausted\n\t * the heap here, before a single expression had been looked at.\n\t */\n\tconstructor(maxLines: number = DEFAULT_CONFIG.performance.maxDocumentLines) {\n\t\tthis.maxLines = maxLines;\n\t}\n\n\t// ── Initialization ──────────────────────────────────────────────────\n\n\t/**\n\t * Initialize or replace the entire document from a text blob.\n\t * Clears all existing state and assigns new persistent line IDs.\n\t *\n\t * @throws `DOCUMENT_TOO_LARGE` for a document past {@link maxLines}, before\n\t * any of it is stored. Recoverable: nothing has been replaced yet, so the\n\t * model still holds whatever it held.\n\t */\n\tsetDocument(text: string): void {\n\t\t// Counted before anything is cleared, so a refused document leaves the\n\t\t// previous one intact rather than half-replaced.\n\t\tconst lineCount = countLines(text, this.maxLines);\n\t\tif (lineCount > this.maxLines) {\n\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\"DOCUMENT_TOO_LARGE\",\n\t\t\t\t`This document has more than ${this.maxLines.toLocaleString(\"en-US\")} lines, which is the most the engine will hold at once`,\n\t\t\t\t{ maxLines: this.maxLines },\n\t\t\t);\n\t\t}\n\t\tthis.lines.clear();\n\t\tthis.orderTree.clear();\n\t\tthis._positionCache = null;\n\t\tthis.dirtyLineIds.clear();\n\t\tthis.nextLineId = 1;\n\n\t\tconst rawLines = text.split(\"\\n\");\n\t\tconst lineIds = new Array<number>(rawLines.length);\n\n\t\tfor (let i = 0; i < rawLines.length; i++) {\n\t\t\tconst lineId = this.nextLineId++;\n\t\t\tlineIds[i] = lineId;\n\t\t\tthis.lines.set(lineId, {\n\t\t\t\tlineId,\n\t\t\t\ttextHash: djb2Hash(rawLines[i]),\n\t\t\t\ttext: rawLines[i],\n\t\t\t\texpressions: [],\n\t\t\t\tbytecodes: [],\n\t\t\t\treads: [],\n\t\t\t\twrites: [],\n\t\t\t\tresults: [],\n\t\t\t\tresult: null,\n\t\t\t\tdirty: true,\n\t\t\t\tisVariableDef: false,\n\t\t\t\tisEmpty: rawLines[i].trim().length === 0,\n\t\t\t\tinlineSolveCount: 0,\n\t\t\t});\n\t\t}\n\n\t\t// O(N) balanced treap build from flat array\n\t\tthis.orderTree.replaceAll(lineIds);\n\n\t\t// Every line starts dirty (see the object literal above), seed the\n\t\t// tracking set to match. This is the one place the set is legitimately\n\t\t// O(N): a fresh document needs full evaluation anyway.\n\t\tfor (const id of lineIds) this.dirtyLineIds.add(id);\n\t}\n\n\t// ── Structural edits ────────────────────────────────────────────────\n\n\t/**\n\t * Apply one or more line-level changes to the document.\n\t *\n\t * **Precondition:** Changes must be **non-overlapping** in their line ranges.\n\t * If two changes target the same or adjacent lines, the reverse-order\n\t * processing may produce incorrect results because the first-applied\n\t * change shifts the line numbers that the second change references.\n\t *\n\t * Changes are applied in **reverse order** (highest startLine first) so\n\t * that earlier changes in the document don't shift the indices of later\n\t * changes during processing.\n\t *\n\t * Returns both the newly inserted line IDs and the removed line IDs.\n\t * Callers should use `removed` to clean up the dependency graph and\n\t * other data structures keyed by lineId.\n\t */\n\tapplyChanges(changes: LineChange[]): ApplyChangesResult {\n\t\tconst inserted: number[] = [];\n\t\tconst removed: number[] = [];\n\n\t\t// Sort descending by startLine so earlier changes don't shift later indices\n\t\tconst sorted = [...changes].sort((a, b) => b.startLine - a.startLine);\n\n\t\tfor (const change of sorted) {\n\t\t\tconst startIdx = change.startLine - 1; // convert to 0-based\n\n\t\t\t// Create new LineState entries for inserted lines\n\t\t\tconst newIds: number[] = [];\n\t\t\tfor (const text of change.insertLines) {\n\t\t\t\tconst lineId = this.nextLineId++;\n\t\t\t\tnewIds.push(lineId);\n\t\t\t\tinserted.push(lineId);\n\t\t\t\tthis.lines.set(lineId, {\n\t\t\t\t\tlineId,\n\t\t\t\t\ttextHash: djb2Hash(text),\n\t\t\t\t\ttext,\n\t\t\t\t\texpressions: [],\n\t\t\t\t\tbytecodes: [],\n\t\t\t\t\treads: [],\n\t\t\t\t\twrites: [],\n\t\t\t\t\tresults: [],\n\t\t\t\t\tresult: null,\n\t\t\t\t\tdirty: true,\n\t\t\t\t\tisVariableDef: false,\n\t\t\t\t\tisEmpty: text.trim().length === 0,\n\t\t\t\t\tinlineSolveCount: 0,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// New lines start dirty (see the object literal above), track them.\n\t\t\tfor (const id of newIds) this.dirtyLineIds.add(id);\n\n\t\t\t// O(log N) splice: delete old IDs, insert new IDs\n\t\t\tconst removedIds = this.orderTree.spliceAt(\n\t\t\t\tstartIdx,\n\t\t\t\tchange.deleteCount,\n\t\t\t\tnewIds\n\t\t\t);\n\t\t\tfor (const id of removedIds) {\n\t\t\t\tremoved.push(id);\n\t\t\t\tthis.lines.delete(id);\n\t\t\t\tthis.dirtyLineIds.delete(id);\n\t\t\t}\n\t\t}\n\n\t\t// Invalidate position cache, positions shifted for all lines\n\t\tthis._positionCache = null;\n\n\t\treturn { inserted, removed };\n\t}\n\n\t/**\n\t * Insert new lines at the given 1-based position.\n\t * Convenience wrapper around applyChanges.\n\t */\n\tinsertLines(atLine: number, texts: string[]): number[] {\n\t\tconst change: LineChange = {\n\t\t\tstartLine: atLine,\n\t\t\tdeleteCount: 0,\n\t\t\tinsertLines: texts,\n\t\t};\n\t\tconst result = this.applyChanges([change]);\n\t\treturn result.inserted;\n\t}\n\n\t/**\n\t * Delete lines in the given 1-based range [startLine, endLine] inclusive.\n\t * Convenience wrapper around applyChanges.\n\t */\n\tdeleteLines(startLine: number, endLine: number): number[] {\n\t\tconst change: LineChange = {\n\t\t\tstartLine,\n\t\t\tdeleteCount: endLine - startLine + 1,\n\t\t\tinsertLines: [],\n\t\t};\n\t\tconst result = this.applyChanges([change]);\n\t\treturn result.removed;\n\t}\n\n\t/**\n\t * Update the text of a single line in place.\n\t * If the text hash differs, marks the line dirty and clears its\n\t * bytecode/result so it gets re-evaluated.\n\t *\n\t * Returns true if the text actually changed (hash mismatch).\n\t */\n\teditLine(lineNumber: number, newText: string): boolean {\n\t\tconst state = this.getLineAt(lineNumber);\n\t\tif (!state) return false;\n\n\t\tconst newHash = djb2Hash(newText);\n\t\tif (newHash === state.textHash) return false;\n\n\t\tstate.text = newText;\n\t\tstate.textHash = newHash;\n\t\tstate.expressions = [];\n\t\tstate.bytecodes = [];\n\t\tstate.results = [];\n\t\tstate.result = null;\n\t\tstate.inlineSolveCount = 0;\n\t\tstate.dirty = true;\n\t\tthis.dirtyLineIds.add(state.lineId);\n\t\tstate.isEmpty = newText.trim().length === 0;\n\t\treturn true;\n\t}\n\n\t// ── Queries ─────────────────────────────────────────────────────────\n\n\t/**\n\t * Get the LineState at the given 1-based line position. O(1).\n\t */\n\tgetLineAt(position: number): LineState | undefined {\n\t\tconst idx = position - 1;\n\t\tconst lineId = this.orderTree.getAt(idx);\n\t\tif (lineId === undefined) return undefined;\n\t\treturn this.lines.get(lineId);\n\t}\n\n\t/**\n\t * Get the 1-based position of a line by its persistent ID.\n\t * Returns -1 if the line ID is not in the document.\n\t *\n\t * Uses a lazy position cache: O(N) on first call after structural edit,\n\t * O(1) on subsequent calls. The cache is invalidated by any structural edit.\n\t */\n\tgetLinePosition(lineId: number): number {\n\t\tif (this._positionCache) {\n\t\t\treturn this._positionCache.get(lineId) ?? -1;\n\t\t}\n\n\t\t// Build position cache on first call after invalidation\n\t\tthis._positionCache = new Map();\n\t\tlet pos = 1;\n\t\tfor (const id of this.orderTree) {\n\t\t\tthis._positionCache.set(id, pos++);\n\t\t}\n\n\t\treturn this._positionCache.get(lineId) ?? -1;\n\t}\n\n\t/**\n\t * Get all LineState entries within the given viewport range (1-based, inclusive).\n\t * Uses SegmentTree.getRange() for O(viewport + log N) collection instead of\n\t * O(viewport × log N) per-line lookups.\n\t */\n\tgetVisibleLines(startLine: number, endLine: number): LineState[] {\n\t\tconst lineIds = this.orderTree.getRange(startLine - 1, endLine - 1);\n\t\tconst result: LineState[] = [];\n\t\tfor (const lineId of lineIds) {\n\t\t\tconst state = this.lines.get(lineId);\n\t\t\tif (state) result.push(state);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get all LineState entries in order. Useful for batch processing.\n\t */\n\tgetAllLines(): LineState[] {\n\t\treturn this.getVisibleLines(1, this.lineCount);\n\t}\n\n\t/**\n\t * Get a LineState by its persistent line ID. O(1).\n\t */\n\tgetLineById(lineId: number): LineState | undefined {\n\t\treturn this.lines.get(lineId);\n\t}\n\n\t/**\n\t * Get all lines that are marked dirty.\n\t */\n\tgetDirtyLines(): LineState[] {\n\t\tconst result: LineState[] = [];\n\t\tfor (const state of this.lines.values()) {\n\t\t\tif (state.dirty) result.push(state);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Whether any line before `position` (1-based, exclusive) is dirty.\n\t *\n\t * Used by ThreeTierEvaluator.setViewport() to decide whether cached\n\t * checkpoint state might be stale and a full evaluate() (from line 1) is\n\t * needed instead of the cheap viewport-only path.\n\t *\n\t * O(d log N) where d = current dirty line count via {@link dirtyLineIds},\n\t * not O(N log N), a document that's mostly clean (the steady state after\n\t * initial load) answers this in the cost of resolving a handful of\n\t * lineIds to positions, not walking every line up to `position`.\n\t */\n\thasAnyDirtyLineBefore(position: number): boolean {\n\t\tfor (const lineId of this.dirtyLineIds) {\n\t\t\tconst pos = this.getLinePosition(lineId);\n\t\t\tif (pos >= 1 && pos < position) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Whether any **variable-definition** line before `position` (1-based,\n\t * exclusive) is dirty.\n\t *\n\t * Narrower than {@link hasAnyDirtyLineBefore}: `VMCheckpointer.snapshot()`\n\t * only ever records state for lines with `writes.length > 0` (see\n\t * VMCheckpoints.ts), so a dirty plain-expression line before the viewport\n\t * cannot have invalidated any checkpoint, there's no checkpoint entry\n\t * for it to invalidate. Only a dirty variable-def line can mean the VM\n\t * state a checkpoint would restore is stale.\n\t *\n\t * This distinction matters because `PageManager.evictPageBytecode()`\n\t * marks evicted non-variable-def lines dirty (so they get Tier 1 if\n\t * scrolled back into view), and Tier 3's compile-only path never clears\n\t * `dirty` for non-variable-def lines by design. Using the broader\n\t * `hasAnyDirtyLineBefore` here meant scrolling far into a large,\n\t * variable-def-free document would trip `setViewport()`'s fallback to\n\t * `evaluate()` on every single call, evaluate() reprocesses the evicted\n\t * lines via Tier 3, which recompiles their bytecode without clearing\n\t * dirty, so the very next `maintainAfterEval()` re-evicts and re-dirties\n\t * the same lines, forever re-triggering the fallback on an otherwise\n\t * unchanged viewport.\n\t */\n\thasAnyDirtyVariableDefLineBefore(position: number): boolean {\n\t\tfor (const lineId of this.dirtyLineIds) {\n\t\t\tconst state = this.lines.get(lineId);\n\t\t\tif (!state || !state.isVariableDef) continue;\n\t\t\tconst pos = this.getLinePosition(lineId);\n\t\t\tif (pos >= 1 && pos < position) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/** Number of lines currently marked dirty. For diagnostics/tests. */\n\tget dirtyCount(): number {\n\t\treturn this.dirtyLineIds.size;\n\t}\n\n\t// ── Thread-safety validation ────────────────────────────────────────\n\n\t/**\n\t * Verify that bytecode compiled by a worker is still valid for this line.\n\t *\n\t * When Phase 5.2h sends compilation to a worker, the worker posts back\n\t * `{lineId, bytecode, reads, writes, compiledAgainstHash}`. Between dispatch\n\t * and response, the user may have edited the line. This method lets the\n\t * main thread check whether the bytecode is still applicable.\n\t *\n\t * @returns true if the line still exists and its text hash matches.\n\t */\n\tisBytecodeValid(lineId: number, compiledAgainstHash: number): boolean {\n\t\tconst state = this.lines.get(lineId);\n\t\treturn state !== undefined && state.textHash === compiledAgainstHash;\n\t}\n\n\t// ── State mutations ─────────────────────────────────────────────────\n\n\t/**\n\t * Mark a line as clean (re-evaluated successfully).\n\t */\n\tmarkClean(lineId: number): void {\n\t\tconst state = this.lines.get(lineId);\n\t\tif (state) {\n\t\t\tstate.dirty = false;\n\t\t\tthis.dirtyLineIds.delete(lineId);\n\t\t}\n\t}\n\n\t/**\n\t * Mark a line as dirty (needs re-evaluation) by its 1-based position.\n\t * Convenience for callers that have line numbers instead of line IDs.\n\t */\n\tmarkDirtyByLineNumber(lineNumber: number): void {\n\t\tconst state = this.getLineAt(lineNumber);\n\t\tif (state) {\n\t\t\tstate.dirty = true;\n\t\t\tthis.dirtyLineIds.add(state.lineId);\n\t\t}\n\t}\n\n\t/**\n\t * Mark a line as dirty (needs re-evaluation).\n\t */\n\tmarkDirty(lineId: number): void {\n\t\tconst state = this.lines.get(lineId);\n\t\tif (state) {\n\t\t\tstate.dirty = true;\n\t\t\tthis.dirtyLineIds.add(lineId);\n\t\t}\n\t}\n\n\t/**\n\t * Mark all lines as dirty (e.g., after plugin register/unregister).\n\t */\n\tinvalidateAll(): void {\n\t\tfor (const state of this.lines.values()) {\n\t\t\tstate.dirty = true;\n\t\t}\n\t\tthis.dirtyLineIds = new Set(this.lines.keys());\n\t}\n\n\t/**\n\t * Update a line's evaluation state after successful execution (Tier 1 / Tier 2).\n\t *\n\t * Sets results, bytecodes, reads, writes, and marks the line clean.\n\t * Supports multi-expression lines (inline solves) via parallel arrays.\n\t *\n\t * @param lineId - Persistent line identifier.\n\t * @param results - Evaluation result groups for each expression (in order). Each element is a Value[].\n\t * @param bytecodes - Compiled bytecode for each expression (in order).\n\t * @param expressions - Extracted expression strings (in order).\n\t * @param reads - Aggregated read variables across all expressions.\n\t * @param writes - Aggregated write variables across all expressions.\n\t * @param isVariableDef - True if any expression defines a variable.\n\t * @param inlineSolveCount - Number of inline solves (0 for full-line).\n\t */\n\tupdateLineResult(\n\t\tlineId: number,\n\t\tresults: Value[][],\n\t\tbytecodes: BytecodeProgram[],\n\t\texpressions: string[],\n\t\treads: string[],\n\t\twrites: string[],\n\t\tisVariableDef: boolean,\n\t\tinlineSolveCount: number = 0,\n\t): void {\n\t\tconst state = this.lines.get(lineId);\n\t\tif (!state) return;\n\t\tstate.results = results;\n\t\tstate.result = results[0]?.[0] ?? null;\n\t\tstate.bytecodes = bytecodes;\n\t\tstate.expressions = expressions;\n\t\tstate.reads = reads;\n\t\tstate.writes = writes;\n\t\tstate.isVariableDef = isVariableDef;\n\t\tstate.inlineSolveCount = inlineSolveCount;\n\t\tstate.dirty = false;\n\t\tthis.dirtyLineIds.delete(lineId);\n\t}\n\n\t/**\n\t * Update a line's compile-only state (Tier 3: background compilation).\n\t *\n\t * Stores expressions, bytecodes, reads, and writes. Does NOT set results\n\t * and does NOT mark the line clean, it still needs execution (Tier 1 or\n\t * Tier 2) to produce results. This distinction allows the three-tier\n\t * evaluation strategy: compile invisible lines in the background without\n\t * executing them, then execute from cached bytecode when scrolled into view.\n\t *\n\t * @param lineId - Persistent line identifier.\n\t * @param expressions - Extracted expression strings (in order).\n\t * @param bytecodes - Compiled bytecode for each expression (in order).\n\t * @param reads - Aggregated read variables across all expressions.\n\t * @param writes - Aggregated write variables across all expressions.\n\t * @param isVariableDef - True if any expression defines a variable.\n\t * @param inlineSolveCount - Number of inline solves (0 for full-line).\n\t */\n\tupdateLineCompiled(\n\t\tlineId: number,\n\t\texpressions: string[],\n\t\tbytecodes: BytecodeProgram[],\n\t\treads: string[],\n\t\twrites: string[],\n\t\tisVariableDef: boolean,\n\t\tinlineSolveCount: number = 0,\n\t): void {\n\t\tconst state = this.lines.get(lineId);\n\t\tif (!state) return;\n\t\tstate.expressions = expressions;\n\t\tstate.bytecodes = bytecodes;\n\t\tstate.reads = reads;\n\t\tstate.writes = writes;\n\t\tstate.isVariableDef = isVariableDef;\n\t\tstate.inlineSolveCount = inlineSolveCount;\n\t\t// NOTE: dirty remains unchanged, line still needs execution\n\t}\n\n\t// ── Properties ──────────────────────────────────────────────────────\n\n\tget lineCount(): number {\n\t\treturn this.orderTree.length;\n\t}\n\n\tget isEmpty(): boolean {\n\t\treturn this.orderTree.isEmpty;\n\t}\n\n\t/**\n\t * Iterator over LineState in document order.\n\t */\n\t*[Symbol.iterator](): IterableIterator<LineState> {\n\t\tfor (const lineId of this.orderTree) {\n\t\t\tconst state = this.lines.get(lineId);\n\t\t\tif (state) yield state;\n\t\t}\n\t}\n\n\t// ── Lifecycle ───────────────────────────────────────────────────────\n\n\tclear(): void {\n\t\tthis.lines.clear();\n\t\tthis.orderTree.clear();\n\t\tthis._positionCache = null;\n\t\tthis.nextLineId = 1;\n\t}\n\n\t/**\n\t * Serialize the document model to a plain object for debugging.\n\t */\n\ttoJSON(): object {\n\t\treturn {\n\t\t\tlineCount: this.lineCount,\n\t\t\tlines: this.getAllLines().map((s) => ({\n\t\t\t\tlineId: s.lineId,\n\t\t\t\ttext: s.text.substring(0, 80), // truncate for readability\n\t\t\t\ttextHash: s.textHash,\n\t\t\t\tdirty: s.dirty,\n\t\t\t\tisVariableDef: s.isVariableDef,\n\t\t\t\tisEmpty: s.isEmpty,\n\t\t\t\thasBytecode: s.bytecodes.length > 0,\n\t\t\t\thasResult: s.results.length > 0,\n\t\t\t\tinlineSolveCount: s.inlineSolveCount,\n\t\t\t\treads: s.reads,\n\t\t\t\twrites: s.writes,\n\t\t\t})),\n\t\t};\n\t}\n}\n","/**\n * CompilationWorkerManager, main-thread bridge to the compilation worker.\n *\n * Manages the worker lifecycle and provides a batch compilation API.\n * Receives transferred ArrayBuffers from the worker and reconstructs\n * BytecodeProgram objects with zero-copy TypedArray views.\n *\n * Usage:\n * const manager = new CompilationWorkerManager();\n * const bytecodeByLineId = await manager.compileBatch(items, docModel);\n *\n * Thread safety:\n * Each result includes `compiledAgainstHash`. Before storing bytecode\n * in the DocumentModel, we validate via `docModel.isBytecodeValid()`.\n * If the line was edited between dispatch and response, the bytecode\n * is discarded, the next evaluate() will recompile it synchronously.\n */\n\nimport { DocumentModel } from \"@solve-js/engine/DocumentModel\";\nimport type { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport createCompilationWorker from \"@solve-js/workers/engine.worker\";\n\n// ── Types ─────────────────────────────────────────────────────────────────\n\n/** One line sent to a worker for compilation. */\nexport interface CompileRequestItem {\n\tlineId: number;\n\texpression: string;\n\ttextHash: number;\n}\n\n/** Compiled bytecode returned from a worker, or the error that stopped it. */\nexport interface CompileResponseItem {\n\tlineId: number;\n\t/** Hash of the expression text when the compile was dispatched (for safety validation). */\n\tcompiledAgainstHash: number;\n\tprogram: BytecodeProgram;\n\treads: string[];\n\twrites: string[];\n\tisVariableDef: boolean;\n\terror: string | null;\n}\n\n// Raw result from worker (before BytecodeProgram reconstruction)\ninterface WorkerCompileResult {\n\tlineId: number;\n\tcompiledAgainstHash: number;\n\topcodesBuffer: ArrayBuffer;\n\tnumbersBuffer: ArrayBuffer;\n\topcodesLength: number;\n\tnumbersLength: number;\n\tstrings: string[];\n\treads: string[];\n\twrites: string[];\n\tisVariableDef: boolean;\n\terror: string | null;\n}\n\n// ── CompilationWorkerManager ──────────────────────────────────────────────\n\n/**\n * Compiles lines on a background worker.\n *\n * A response is discarded when the line changed between dispatch and return,\n * because bytecode compiled against stale text would produce a result for an\n * expression the user has already edited. The next evaluation recompiles it\n * synchronously.\n */\nexport class CompilationWorkerManager {\n\tprivate worker: Worker | null = null;\n\tprivate nextId = 1;\n\tprivate pending = new Map<\n\t\tnumber,\n\t\t{\n\t\t\tresolve: (results: CompileResponseItem[]) => void;\n\t\t\treject: (error: Error) => void;\n\t\t}\n\t>();\n\n\tconstructor() {}\n\n\t/**\n\t * Ensure the worker is started (lazy initialization).\n\t * Uses esbuild-plugin-inline-worker to inline the worker as a blob URL.\n\t */\n\tprivate ensureWorker(): Worker {\n\t\tif (this.worker) return this.worker;\n\n\t\tthis.worker = createCompilationWorker();\n\n\t\tthis.worker.onmessage = (event: MessageEvent) => {\n\t\t\tconst data = event.data;\n\t\t\tif (!data || data.type !== \"COMPILE_RESULT\") return;\n\n\t\t\tconst pending = this.pending.get(data.id);\n\t\t\tif (!pending) return;\n\n\t\t\tthis.pending.delete(data.id);\n\n\t\t\tconst results: CompileResponseItem[] = [];\n\t\t\tfor (const raw of data.results as WorkerCompileResult[]) {\n\t\t\t\tresults.push(this.reconstructResult(raw));\n\t\t\t}\n\t\t\tpending.resolve(results);\n\t\t};\n\n\t\tthis.worker.onerror = (err) => {\n\t\t\t// Reject all pending requests on worker error\n\t\t\tfor (const [id, pending] of this.pending) {\n\t\t\t\tpending.reject(\n\t\t\t\t\tnew Error(`Compilation worker error: ${err.message}`)\n\t\t\t\t);\n\t\t\t\tthis.pending.delete(id);\n\t\t\t}\n\t\t};\n\n\t\treturn this.worker;\n\t}\n\n\t/**\n\t * Batch-compile expressions in the worker.\n\t *\n\t * Sends a batch of { lineId, expression, textHash } to the worker,\n\t * which compiles each and transfers bytecode ArrayBuffers back.\n\t * Bytecode is reconstructed into BytecodeProgram objects.\n\t *\n\t * Results are returned in the same order as the input items.\n\t *\n\t * @param items Expressions to compile.\n\t * @returns Compiled bytecode for each item (or error).\n\t */\n\tasync compileBatch(items: CompileRequestItem[]): Promise<CompileResponseItem[]> {\n\t\tif (items.length === 0) return [];\n\n\t\tconst worker = this.ensureWorker();\n\t\tconst id = this.nextId++;\n\n\t\treturn new Promise<CompileResponseItem[]>((resolve, reject) => {\n\t\t\tthis.pending.set(id, { resolve, reject });\n\n\t\t\tworker.postMessage({\n\t\t\t\ttype: \"COMPILE_BATCH\",\n\t\t\t\tid,\n\t\t\t\titems,\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Store worker-compiled bytecode into the DocumentModel, with safety\n\t * validation. Only stores bytecode for lines whose text has not changed\n\t * since the compilation request was dispatched.\n\t *\n\t * Results for the same lineId are batched, all bytecodes from\n\t * successful compilations are passed to updateLineCompiled in a single\n\t * call. This supports multi-expression lines (inline solves).\n\t *\n\t * @param results Compiled results from the worker.\n\t * @param doc The target document model.\n\t * @returns Number of results successfully stored (passed safety check).\n\t */\n\tstoreResults(\n\t\tresults: CompileResponseItem[],\n\t\tdoc: DocumentModel\n\t): number {\n\t\t// Batch results by lineId (multiple inline solves share the same lineId)\n\t\tconst byLineId = new Map<\n\t\t\tnumber,\n\t\t\t{\n\t\t\t\tbytecodes: BytecodeProgram[];\n\t\t\t\treads: Set<string>;\n\t\t\t\twrites: Set<string>;\n\t\t\t\tisVariableDef: boolean;\n\t\t\t\texpressions: string[];\n\t\t\t\ttextHash: number;\n\t\t\t}\n\t\t>();\n\t\tlet validCount = 0;\n\n\t\tfor (const result of results) {\n\t\t\tif (result.error) continue;\n\n\t\t\t// Safety check: has the line been edited since dispatch?\n\t\t\tconst state = doc.getLineById(result.lineId);\n\t\t\tif (!state) continue;\n\n\t\t\t// Validate that the line text hasn't changed since dispatch.\n\t\t\tif (state.textHash !== result.compiledAgainstHash) continue;\n\n\t\t\t// Batch by lineId\n\t\t\tlet batch = byLineId.get(result.lineId);\n\t\t\tif (!batch) {\n\t\t\t\tbatch = {\n\t\t\t\t\tbytecodes: [],\n\t\t\t\t\treads: new Set(),\n\t\t\t\t\twrites: new Set(),\n\t\t\t\t\tisVariableDef: false,\n\t\t\t\t\texpressions: state.expressions.length > 0 ? [...state.expressions] : [],\n\t\t\t\t\ttextHash: result.compiledAgainstHash,\n\t\t\t\t};\n\t\t\t\tbyLineId.set(result.lineId, batch);\n\t\t\t}\n\n\t\t\tbatch.bytecodes.push(result.program);\n\t\t\tfor (const r of result.reads) batch.reads.add(r);\n\t\t\tfor (const w of result.writes) batch.writes.add(w);\n\t\t\tif (result.isVariableDef) batch.isVariableDef = true;\n\t\t\tvalidCount++;\n\t\t}\n\n\t\t// Store batched results\n\t\tlet stored = 0;\n\t\tfor (const [lineId, batch] of byLineId) {\n\t\t\tif (batch.bytecodes.length === 0) continue;\n\t\t\t// Preserve inlineSolveCount from the LineState so the evaluator\n\t\t\t// knows this line has multiple expressions (avoids re-extraction).\n\t\t\tconst state = doc.getLineById(lineId);\n\t\t\tconst inlineSolveCount = state?.inlineSolveCount ?? 0;\n\t\t\tdoc.updateLineCompiled(\n\t\t\t\tlineId,\n\t\t\t\tbatch.expressions,\n\t\t\t\tbatch.bytecodes,\n\t\t\t\t[...batch.reads],\n\t\t\t\t[...batch.writes],\n\t\t\t\tbatch.isVariableDef,\n\t\t\t\tinlineSolveCount,\n\t\t\t);\n\t\t\tstored += batch.bytecodes.length;\n\t\t}\n\n\t\treturn stored;\n\t}\n\n\t/**\n\t * Terminate the worker and clean up.\n\t */\n\tterminate(): void {\n\t\tif (this.worker) {\n\t\t\tthis.worker.terminate();\n\t\t\tthis.worker = null;\n\t\t\tthis.pending.clear();\n\t\t}\n\t}\n\n\t/**\n\t * Whether the worker is currently active.\n\t */\n\tget isActive(): boolean {\n\t\treturn this.worker !== null;\n\t}\n\n\t// ── Private helpers ────────────────────────────────────────────────\n\n\t/**\n\t * Reconstruct a BytecodeProgram from transferred ArrayBuffers.\n\t *\n\t * The transferred ArrayBuffers are zero-copy, we create TypedArray\n\t * views directly over them. No data is copied or serialized.\n\t */\n\tprivate reconstructResult(raw: WorkerCompileResult): CompileResponseItem {\n\t\tif (raw.error) {\n\t\t\treturn {\n\t\t\t\tlineId: raw.lineId,\n\t\t\t\tcompiledAgainstHash: raw.compiledAgainstHash,\n\t\t\t\tprogram: { opcodes: new Uint8Array(0), numbers: new Float64Array(0), strings: [], hasAsync: false },\n\t\t\t\treads: [],\n\t\t\t\twrites: [],\n\t\t\t\tisVariableDef: false,\n\t\t\t\terror: raw.error,\n\t\t\t};\n\t\t}\n\n\t\t// Reconstruct TypedArrays from transferred ArrayBuffers.\n\t\t// These are views over the same memory, zero-copy from worker.\n\t\tconst opcodes =\n\t\t\traw.opcodesLength > 0\n\t\t\t\t? new Uint8Array(raw.opcodesBuffer, 0, raw.opcodesLength)\n\t\t\t\t: new Uint8Array(0);\n\t\tconst numbers =\n\t\t\traw.numbersLength > 0\n\t\t\t\t? new Float64Array(raw.numbersBuffer, 0, raw.numbersLength)\n\t\t\t\t: new Float64Array(0);\n\n\t\tconst program: BytecodeProgram = {\n\t\t\topcodes,\n\t\t\tnumbers,\n\t\t\tstrings: raw.strings,\n\t\t\thasAsync: false,\n\t\t};\n\n\t\treturn {\n\t\t\tlineId: raw.lineId,\n\t\t\tcompiledAgainstHash: raw.compiledAgainstHash,\n\t\t\tprogram,\n\t\t\treads: raw.reads,\n\t\t\twrites: raw.writes,\n\t\t\tisVariableDef: raw.isVariableDef,\n\t\t\terror: null,\n\t\t};\n\t}\n}\n","/**\n * PageManager, page-based LRU eviction + directional preloading.\n *\n * Groups document lines into fixed-size pages (128 lines each) and manages\n * three temperature tiers:\n * • Hot (viewport ± 3 pages): Keep bytecode + results\n * • Warm (viewport ± 6 pages): Keep bytecode, evict results\n * • Cold (beyond ± 6 pages): Evict bytecode + results (except variable defs)\n *\n * Variable definition bytecode is **never evicted** because it forms the\n * backbone of the dependency graph and VM checkpoints.\n *\n * Preloading: When the user scrolls in a consistent direction, the next\n * 1–2 pages are pre-compiled via the background worker so bytecode is\n * cache-hot by the time those lines scroll into view.\n *\n * Usage:\n * const pm = new PageManager();\n * // After evaluation:\n * pm.maintainAfterEval(viewport, doc);\n * // After scroll (viewport-only change):\n * pm.maintainAfterEval(viewport, doc);\n * const targets = pm.getPreloadTargets(viewport, doc);\n * // dispatch targets to compilation worker\n */\n\nimport { DocumentModel } from \"@solve-js/engine/DocumentModel\";\n// Deliberately the shared lexer, not an engine's own.\n//\n// `classifyLine` and `findInlineSolves` are character-level scans for headings,\n// comment markers, code fences and backtick spans. Neither consults the\n// keyword, unit or operator tables, so every lexer returns the same answer and\n// there is nothing per-engine to respect. Pinned by\n// __tests__/lexer/LineClassificationIsVocabularyIndependent.spec.ts, which\n// compares a bare lexer against one carrying extra vocabulary.\n//\n// This matters because these are free functions with no engine to ask. Making\n// them engine-aware would mean changing their signatures and every caller for\n// no behavioural difference.\nimport { sharedLexer } from \"@solve-js/lexer/Lexer\";\n\n// ── Constants ────────────────────────────────────────────────────────────\n\n/** Number of lines per page. Tunable, 128 balances granularity with overhead. */\nexport const PAGE_SIZE = 128;\n\n/** Number of pages on each side of the viewport considered \"hot.\" */\nconst HOT_PAGE_RADIUS = 3;\n\n/** Number of pages on each side of the viewport considered \"warm\" (includes hot). */\nconst WARM_PAGE_RADIUS = 6;\n\n/** Number of pages to preload ahead of the scroll direction. */\nconst PRELOAD_PAGE_COUNT = 2;\n\n/**\n * Pages just beyond the warm range that are \"newly cold\", they were warm\n * on the previous scroll and now need bytecode eviction. Once evicted, they\n * stay cold and don't need re-eviction on subsequent frames (the inner\n * `evictPageBytecode` checks for non-null bytecode and short-circuits).\n *\n * This buffer lets us skip iterating the vast majority of cold pages on\n * every scroll, reducing `maintainAfterEval` from O(total pages) to\n * O(hot + warm + buffer) ≈ O(1) for any document size.\n */\nconst COLD_EVICT_BUFFER = HOT_PAGE_RADIUS;\n\n// ── PageManager ──────────────────────────────────────────────────────────\n\n/**\n * Splits a long document into pages so only what is near the viewport is held\n * in full.\n *\n * A document is edited constantly and most of it is off screen. Paging keeps\n * the cost of a keystroke proportional to what is visible rather than to the\n * length of the document.\n */\nexport class PageManager {\n\t/** Previous viewport for scroll direction detection. null = no previous viewport. */\n\tprivate lastViewportStart: number | null = null;\n\n\t/** Saved scroll direction from the most recent maintainAfterEval call. */\n\tprivate savedDirection: \"down\" | \"up\" | null = null;\n\n\t/** Per-page access counter for LRU tracking. */\n\tprivate pageAccess: Map<number, number> = new Map();\n\n\t/** Monotonically increasing access sequence number. */\n\tprivate accessSeq = 0;\n\n\t// ── Static helpers ─────────────────────────────────────────────────\n\n\t/** Get the page number for a 1-based line number (0-based page index). */\n\tstatic pageForLine(lineNumber: number): number {\n\t\treturn Math.floor((lineNumber - 1) / PAGE_SIZE);\n\t}\n\n\t/** Get the 1-based inclusive line range for a page. */\n\tstatic pageRange(\n\t\tpageNum: number,\n\t\tdocLineCount: number\n\t): { startLine: number; endLine: number } {\n\t\treturn {\n\t\t\tstartLine: pageNum * PAGE_SIZE + 1,\n\t\t\tendLine: Math.min((pageNum + 1) * PAGE_SIZE, docLineCount),\n\t\t};\n\t}\n\n\t// ── Public API ─────────────────────────────────────────────────────\n\n\t/**\n\t * Detect scroll direction from viewport movement.\n\t * Returns null on first call (no previous viewport) or no movement.\n\t */\n\tdetectDirection(newViewport: { startLine: number }): \"down\" | \"up\" | null {\n\t\tif (this.lastViewportStart === null) return null;\n\t\tif (newViewport.startLine > this.lastViewportStart) return \"down\";\n\t\tif (newViewport.startLine < this.lastViewportStart) return \"up\";\n\t\treturn null;\n\t}\n\n\t/**\n\t * Maintain page tiers after evaluation.\n\t *\n\t * 1. Records the new viewport position\n\t * 2. Touches hot pages (viewport ± HOT_PAGE_RADIUS) for LRU\n\t * 3. Evicts cold/warm pages based on distance from viewport\n\t *\n\t * Call this after every `evaluate()`, `setViewport()`, or `evaluateAll()`.\n\t */\n\tmaintainAfterEval(\n\t\tviewport: { startLine: number; endLine: number },\n\t\tdoc: DocumentModel\n\t): void {\n\t\t// ── Capture direction BEFORE updating lastViewportStart ───\n\t\tthis.savedDirection = this.detectDirection(viewport);\n\t\tthis.lastViewportStart = viewport.startLine;\n\n\t\tconst docLineCount = doc.lineCount;\n\t\tconst viewportStartPage = PageManager.pageForLine(viewport.startLine);\n\t\tconst viewportEndPage = PageManager.pageForLine(viewport.endLine);\n\t\tconst lastPage = PageManager.pageForLine(docLineCount);\n\n\t\t// Compute hot/warm page ranges in O(1) using range math:\n\t\t// A page is within RADIUS of the viewport span iff it falls in\n\t\t// [viewportStartPage - RADIUS, viewportEndPage + RADIUS].\n\t\tconst hotStart = Math.max(0, viewportStartPage - HOT_PAGE_RADIUS);\n\t\tconst hotEnd = Math.min(lastPage, viewportEndPage + HOT_PAGE_RADIUS);\n\t\tconst warmStart = Math.max(0, viewportStartPage - WARM_PAGE_RADIUS);\n\t\tconst warmEnd = Math.min(lastPage, viewportEndPage + WARM_PAGE_RADIUS);\n\n\t\t// Touch hot pages to keep them fresh in LRU\n\t\tfor (let p = hotStart; p <= hotEnd; p++) {\n\t\t\tthis.touchPage(p);\n\t\t}\n\n\t\t// Evict warm-but-not-hot pages: keep bytecode, evict results only\n\t\tfor (let p = warmStart; p <= warmEnd; p++) {\n\t\t\tif (p >= hotStart && p <= hotEnd) continue;\n\t\t\tthis.evictPageResults(p, doc, docLineCount);\n\t\t}\n\n\t\t// Evict \"newly cold\" pages: a buffer zone just outside the warm\n\t\t// range. Pages beyond this buffer were already evicted on prior\n\t\t// scrolls and don't need re-eviction.\n\t\t// ── Left side (just above page 0, just below warm range) ──\n\t\tconst coldLeftEnd = warmStart - 1;\n\t\tconst coldLeftStart = Math.max(0, coldLeftEnd - COLD_EVICT_BUFFER + 1);\n\t\tfor (let p = coldLeftStart; p <= coldLeftEnd; p++) {\n\t\t\tthis.evictPageBytecode(p, doc, docLineCount);\n\t\t}\n\t\t// ── Right side (just above warm range, just below lastPage) ──\n\t\tconst coldRightStart = warmEnd + 1;\n\t\tconst coldRightEnd = Math.min(lastPage, coldRightStart + COLD_EVICT_BUFFER - 1);\n\t\tfor (let p = coldRightStart; p <= coldRightEnd; p++) {\n\t\t\tthis.evictPageBytecode(p, doc, docLineCount);\n\t\t}\n\t}\n\n\t/**\n\t * Get lines ahead of the viewport that should be pre-compiled.\n\t *\n\t * Looks PRELOAD_PAGE_COUNT pages ahead of the current scroll direction.\n\t * Only returns lines that are dirty, don't already have bytecode,\n\t * and are not empty/markdown-only.\n\t *\n\t * @param viewport The current viewport.\n\t * @param doc The document model.\n\t * @returns Items ready to send to the compilation worker.\n\t */\n\tgetPreloadTargets(\n\t\tviewport: { startLine: number; endLine: number },\n\t\tdoc: DocumentModel\n\t): Array<{ lineId: number; expression: string; textHash: number }> {\n\t\t// Use the direction saved by the last maintainAfterEval call.\n\t\t// We cannot re-detect because maintainAfterEval already updated\n\t\t// lastViewportStart to the current viewport position.\n\t\tconst direction = this.savedDirection;\n\t\tif (!direction) return [];\n\n\t\tconst items: Array<{ lineId: number; expression: string; textHash: number }> = [];\n\t\t// Use viewport end page for downward preload start, start page for upward.\n\t\t// This ensures we preload *beyond* the full viewport span, not just its start.\n\t\tconst viewportEndPage = PageManager.pageForLine(viewport.endLine);\n\t\tconst viewportStartPage = PageManager.pageForLine(viewport.startLine);\n\t\tconst lastPage = PageManager.pageForLine(doc.lineCount);\n\n\t\tconst pages: number[] = [];\n\t\tif (direction === \"down\") {\n\t\t\t// Preload pages immediately after the viewport's hot radius beyond its end\n\t\t\tconst startPage = viewportEndPage + HOT_PAGE_RADIUS + 1;\n\t\t\tconst endPage = Math.min(startPage + PRELOAD_PAGE_COUNT - 1, lastPage);\n\t\t\tfor (let p = startPage; p <= endPage && p <= lastPage; p++) {\n\t\t\t\tpages.push(p);\n\t\t\t}\n\t\t} else {\n\t\t\t// Preload pages immediately before the viewport's hot radius before its start\n\t\t\tconst firstPreloadPage = viewportStartPage - HOT_PAGE_RADIUS - 1;\n\t\t\tfor (let p = firstPreloadPage; p > firstPreloadPage - PRELOAD_PAGE_COUNT && p >= 0; p--) {\n\t\t\t\tpages.push(p);\n\t\t\t}\n\t\t}\n\n\t\tfor (const pageNum of pages) {\n\t\t\tconst range = PageManager.pageRange(pageNum, doc.lineCount);\n\t\t\tfor (let pos = range.startLine; pos <= range.endLine; pos++) {\n\t\t\t\tconst state = doc.getLineAt(pos);\n\t\t\t\tif (!state) continue;\n\t\t\t\tif (!state.dirty) continue;\n\t\t\t\tif (state.bytecodes.length > 0 && !state.isVariableDef) continue;\n\t\t\t\tif (state.isEmpty) continue;\n\n\t\t\t\t// Extract expressions using the shared lexer to handle inline\n\t\t\t\t// solves (s`...`). For full-line expressions, this returns [text].\n\t\t\t\t// For inline solve lines, this returns each extracted expression.\n\t\t\t\tif (state.expressions.length > 0) {\n\t\t\t\t\t// Use pre-extracted expressions (from prior evaluation)\n\t\t\t\t\tfor (const expression of state.expressions) {\n\t\t\t\t\t\tif (!expression.trim()) continue;\n\t\t\t\t\t\titems.push({\n\t\t\t\t\t\t\tlineId: state.lineId,\n\t\t\t\t\t\t\texpression,\n\t\t\t\t\t\t\ttextHash: state.textHash,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Expressions not yet extracted, use lexer to find inline solves\n\t\t\t\t\tconst inlineSpans = sharedLexer.findInlineSolves(state.text);\n\t\t\t\t\tif (inlineSpans.length > 0) {\n\t\t\t\t\t\tfor (const span of inlineSpans) {\n\t\t\t\t\t\t\tif (!span.expression.trim()) continue;\n\t\t\t\t\t\t\titems.push({\n\t\t\t\t\t\t\t\tlineId: state.lineId,\n\t\t\t\t\t\t\t\texpression: span.expression,\n\t\t\t\t\t\t\t\ttextHash: state.textHash,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Full-line expression\n\t\t\t\t\t\tconst expression = state.text.trim();\n\t\t\t\t\t\tif (expression) {\n\t\t\t\t\t\t\titems.push({\n\t\t\t\t\t\t\t\tlineId: state.lineId,\n\t\t\t\t\t\t\t\texpression,\n\t\t\t\t\t\t\t\ttextHash: state.textHash,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn items;\n\t}\n\n\t/**\n\t * Reset internal state (e.g., after document switch).\n\t */\n\tclear(): void {\n\t\tthis.pageAccess.clear();\n\t\tthis.accessSeq = 0;\n\t\tthis.lastViewportStart = null;\n\t\tthis.savedDirection = null;\n\t}\n\n\t// ── Private helpers ─────────────────────────────────────────────────\n\n\t/** Record a page access with a monotonic sequence number. */\n\tprivate touchPage(pageNum: number): void {\n\t\tthis.pageAccess.set(pageNum, ++this.accessSeq);\n\t}\n\n\t/**\n\t * Evict results from all non-variable-def lines in a page.\n\t * Bytecode is preserved so Tier 2 execution works on scroll-back.\n\t */\n\tprivate evictPageResults(\n\t\tpageNum: number,\n\t\tdoc: DocumentModel,\n\t\tdocLineCount: number\n\t): void {\n\t\tconst range = PageManager.pageRange(pageNum, docLineCount);\n\t\tfor (let pos = range.startLine; pos <= range.endLine; pos++) {\n\t\t\tconst state = doc.getLineAt(pos);\n\t\t\tif (state && !state.isVariableDef && state.results.length > 0) {\n\t\t\t\tstate.results = [];\n\t\t\t\tstate.result = null;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Evict bytecode + results from all non-variable-def lines in a page.\n\t * Variable definition bytecode is **never** evicted, it forms the\n\t * backbone of the DAG and VM checkpoints.\n\t *\n\t * Evicted lines are marked dirty so they get Tier 1 re-evaluation\n\t * when scrolled back into view.\n\t */\n\tprivate evictPageBytecode(\n\t\tpageNum: number,\n\t\tdoc: DocumentModel,\n\t\tdocLineCount: number\n\t): void {\n\t\tconst range = PageManager.pageRange(pageNum, docLineCount);\n\t\tfor (let pos = range.startLine; pos <= range.endLine; pos++) {\n\t\t\tconst state = doc.getLineAt(pos);\n\t\t\tif (!state || state.isVariableDef) continue;\n\n\t\t\tif (state.bytecodes.length > 0 || state.results.length > 0) {\n\t\t\t\tstate.bytecodes = [];\n\t\t\t\tstate.results = [];\n\t\t\t\tstate.result = null;\n\t\t\t\tdoc.markDirty(state.lineId);\n\t\t\t}\n\t\t}\n\t}\n}\n","import { ExpressionEngine } from \"@solve-js/engine/ExpressionEngine\";\nimport {\n\tDocumentModel,\n\tLineChange,\n\tLineState,\n\tViewportRange,\n} from \"@solve-js/engine/DocumentModel\";\nimport { Value, ValueType, enableValueArena, disableValueArena, errorValue } from \"@solve-js/vm/Value\";\nimport { DependencyGraph } from \"@solve-js/vm/DependencyGraph\";\nimport { VMCheckpointer } from \"@solve-js/vm/VMCheckpoints\";\nimport { isEmptyLine } from \"@solve-js/engine/ExpressionEngineSafety\";\n// Deliberately the shared lexer, not an engine's own.\n//\n// `classifyLine` and `findInlineSolves` are character-level scans for headings,\n// comment markers, code fences and backtick spans. Neither consults the\n// keyword, unit or operator tables, so every lexer returns the same answer and\n// there is nothing per-engine to respect. Pinned by\n// __tests__/lexer/LineClassificationIsVocabularyIndependent.spec.ts, which\n// compares a bare lexer against one carrying extra vocabulary.\n//\n// This matters because these are free functions with no engine to ask. Making\n// them engine-aware would mean changing their signatures and every caller for\n// no behavioural difference.\nimport { sharedLexer } from \"@solve-js/lexer/Lexer\";\nimport { CompilationWorkerManager, type CompileRequestItem } from \"@solve-js/engine/CompilationWorkerManager\";\nimport { PageManager } from \"@solve-js/engine/PageManager\";\nimport type { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { EngineError } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { sharedGlobalVariableStore, globalDagKey } from \"@solve-js/vm/GlobalVariableStore\";\n\n// ── EvalTier (diagnostic enum) ──────────────────────────────────────────\n\n/**\n * How much work a line's evaluation required.\n *\n * The tiers exist because most lines in a document have not changed. A line\n * that is clean and cached costs far less than one being compiled fresh, and\n * knowing which happened is how a slow document gets diagnosed.\n */\nexport enum EvalTier {\n\t/** Full pipeline: Lex → Parse → Compile → Execute (visible + dirty). */\n\tTier1 = 1,\n\t/** Execute-only from cached bytecode (visible + cached). */\n\tTier2 = 2,\n\t/** Compile-only for dependency tracking (invisible). Executes only variable assignments. */\n\tTier3 = 3,\n\t/** Skipped, already clean or non-evaluable. */\n\tSkipped = 0,\n}\n\n// ── EvalLineResult ──────────────────────────────────────────────────────\n\n/** Outcome for one line, including which tier handled it. */\nexport interface EvalLineResult {\n\t/** The line's persistent ID from DocumentModel. */\n\tlineId: number;\n\t/** 1-based line position. */\n\tlineNumber: number;\n\t/** Which tier was used. */\n\ttier: EvalTier;\n\t/** The first evaluation result, or null on error / non-evaluable. */\n\tresult: Value | null;\n\t/** All result groups (one per expression/inline-solve), or undefined if skipped. */\n\tresults?: Value[][];\n\t/** Error message, or null. */\n\terror: string | null;\n}\n\n// ── EvalResult ──────────────────────────────────────────────────────────\n\n/** Outcome for a whole evaluation pass, with per-tier counts. */\nexport interface EvalResult {\n\t/** Per-line evaluation results. */\n\tlines: EvalLineResult[];\n\t/** Map of line numbers → flattened results for quick lookup. */\n\tresultMap: Map<number, Value[]>;\n\t/** Number of lines processed at each tier. */\n\ttierCounts: { tier1: number; tier2: number; tier3: number; skipped: number };\n}\n\n// ── ThreeTierEvaluator ──────────────────────────────────────────────────\n\n/**\n * Orchestrates three-tier evaluation over a persistent DocumentModel.\n *\n * ── Tier assignment ─────────────────────────────────────────────────\n * | Tier | Condition | Action |\n * |───────|────────────────────────────────────|───────────────────────────────|\n * | **1** | Visible + Dirty (new/changed) | Full pipeline: lex→parse→compile→execute |\n * | **2** | Visible + Cached (scroll into view)| Execute from cached bytecode |\n * | **3** | Invisible + Dirty | Compile-only; execute only variable defs |\n * | Skip | Clean, empty, or non-evaluable | No action |\n *\n * ── Evaluation order ─────────────────────────────────────────────────\n * Lines are always processed in ascending document order (line 1 → end)\n * so that variable assignments flow correctly through the shared VM.\n * Tier 2 relies on this: by the time a clean cached line is reached,\n * the VM already contains all variables from preceding Tier-1 lines.\n *\n * ── Thread safety ────────────────────────────────────────────────────\n * Tier 1 (visible+dirty) compilation runs synchronously on the main thread\n * for immediate rendering. Tier 3 (invisible+dirty) compilation can be\n * dispatched to a Web Worker via `dispatchBackgroundCompiles()`. Worker-\n * compiled bytecode is stored in the DocumentModel and validated via\n * `isBytecodeValid()` to ensure the line text hasn't changed between\n * dispatch and response.\n */\nexport class ThreeTierEvaluator {\n\tprivate doc: DocumentModel;\n\tprivate engine: ExpressionEngine;\n\tprivate dag: DependencyGraph;\n\tprivate checkpointer: VMCheckpointer | null;\n\tprivate compilationWorker: CompilationWorkerManager | null = null;\n\tprivate pageManager: PageManager;\n\n\t/**\n\t * Unsubscribe from sharedGlobalVariableStore, set in the constructor\n\t * called from terminateWorker(). See the subscription itself below for\n\t * why this only marks lines dirty and never re-evaluates synchronously.\n\t */\n\tprivate globalUnsubscribe: (() => void) | null = null;\n\n\t/**\n\t * @param doc The persistent document model.\n\t * @param engine The expression engine (shared VM is accessed via engine.getVM()).\n\t * @param checkpointer Optional VM state checkpointer. If provided, the evaluator\n\t * will create checkpoints after variable-definition lines and support fast VM\n\t * restoration via `restoreTo()`. If omitted, checkpointing is disabled.\n\t */\n\tconstructor(\n\t\tdoc: DocumentModel,\n\t\tengine: ExpressionEngine,\n\t\tcheckpointer?: VMCheckpointer\n\t) {\n\t\tthis.doc = doc;\n\t\tthis.engine = engine;\n\t\tthis.dag = engine.getDag();\n\t\tthis.checkpointer = checkpointer ?? null;\n\t\tthis.pageManager = new PageManager();\n\n\t\t// Lets the engine answer \"what's line N's cached result\" for\n\t\t// cross-line features (prev/line<N>/aggregation) without owning\n\t\t// document lifecycle itself. See ExpressionEngine.makeLineContext().\n\t\tthis.engine.setDocumentModel(this.doc);\n\n\t\t// ── Cross-document global-variable propagation ──────────────────\n\t\t// GlobalVariableAsyncResolver (via preflight) handles a line's FIRST\n\t\t// resolution when a global it reads wasn't known yet. This handles\n\t\t// the ONGOING case: a line that already has a real (non-pending)\n\t\t// value for `global :x` needs to go dirty again when some OTHER\n\t\t// document writes a NEW value to x, so this document's next\n\t\t// evaluate() picks up the change, \"dealing with the DAG across\n\t\t// pages\", not just first-resolution.\n\t\tthis.globalUnsubscribe = sharedGlobalVariableStore.subscribe((name) => {\n\t\t\t// Mark-dirty ONLY, never synchronously re-evaluate here.\n\t\t\t// enableValueArena/disableValueArena (Value.ts) is a single\n\t\t\t// non-reentrant module-level flag; evaluate()/setViewport() both\n\t\t\t// wrap their body in it, so a re-entrant evaluate() call from\n\t\t\t// inside this callback (itself possibly firing from INSIDE\n\t\t\t// another evaluate() call, via a STORE_GLOBAL_VAR opcode in some\n\t\t\t// other document being evaluated concurrently) would disable the\n\t\t\t// arena out from under the still-running outer call. This\n\t\t\t// mirrors applyTransaction()'s existing contract exactly: mark\n\t\t\t// dirty, let the caller's own evaluate() cadence pick it up.\n\t\t\tfor (const lineNumber of this.dag.getAffectedLines(globalDagKey(name))) {\n\t\t\t\tthis.doc.markDirtyByLineNumber(lineNumber);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Evaluate all lines needed to render the given viewport.\n\t *\n\t * Processes lines from 1 to `viewport.endLine` in document order.\n\t * Dirty lines in the viewport get Tier-1 full pipeline; clean cached\n\t * lines get Tier-2 bytecode execution. Lines after the viewport\n\t * get Tier-3 compile-only (with variable-def execution).\n\t *\n\t * @returns Results for all processed lines, including tier metadata.\n\t */\n\tevaluate(viewport: ViewportRange, signal?: AbortSignal): EvalResult {\n\t\t// ── One AbortController Per Keystroke ────────────────────────\n\t\t// Link the UI layer's keystroke signal to the engine so that\n\t\t// all per-evaluation AbortControllers created during this call\n\t\t// are canceled when the user types a new keystroke.\n\t\tthis.engine.setKeystrokeSignal(signal ?? null);\n\n\t\t// ── Phase 5.3: Enable arena for zero-allocation Value reuse ──\n\t\tenableValueArena();\n\t\ttry {\n\t\t\t// Re-seed running-total accumulators before the from-line-1 pass. A\n\t\t\t// `total += 5` line reads its own running value, so re-running it in\n\t\t\t// place would read the previous evaluation's total and double-count.\n\t\t\t// Reset each accumulator variable and mark every line that touches\n\t\t\t// it dirty, so the loop below recomputes the total from its seed,\n\t\t\t// top to bottom. (No-op when the document has no accumulators.)\n\t\t\tthis.reseedAccumulators();\n\n\t\t\tconst lines: EvalLineResult[] = [];\n\t\t\tconst resultMap = new Map<number, Value[]>();\n\t\t\tconst tierCounts = { tier1: 0, tier2: 0, tier3: 0, skipped: 0 };\n\n\t\t\t// Process from line 1 to the end of the viewport for correct VM state.\n\t\t\t// We go to viewport.endLine because Tier 3 for invisible lines can be\n\t\t\t// done separately via backgroundCompile().\n\t\t\tconst docEnd = this.doc.lineCount;\n\t\t\tconst evalEnd = Math.min(viewport.endLine, docEnd);\n\n\t\t\tfor (let pos = 1; pos <= evalEnd; pos++) {\n\t\t\t\tconst state = this.doc.getLineAt(pos);\n\t\t\t\tif (!state) {\n\t\t\t\t\ttierCounts.skipped++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst inViewport = pos >= viewport.startLine && pos <= viewport.endLine;\n\n\t\t\t\tconst lineResult = this.evaluateSingleLine(state, pos, inViewport);\n\t\t\t\tlines.push(lineResult);\n\n\t\t\t\tif (lineResult.tier === EvalTier.Tier1) tierCounts.tier1++;\n\t\t\t\telse if (lineResult.tier === EvalTier.Tier2) tierCounts.tier2++;\n\t\t\t\telse if (lineResult.tier === EvalTier.Tier3) tierCounts.tier3++;\n\t\t\t\telse tierCounts.skipped++;\n\n\t\t\t\tif (lineResult.results && inViewport) {\n\t\t\t\t\tresultMap.set(pos, lineResult.results.flat());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ── Phase 5.2g: Page-based LRU eviction ──────────────────────\n\t\t\t// Evict bytecode/results from cold/warm pages to bound memory.\n\t\t\tthis.pageManager.maintainAfterEval(viewport, this.doc);\n\n\t\t\treturn { lines, resultMap, tierCounts };\n\t\t} finally {\n\t\t\t// Clear keystroke signal to prevent stale signal references\n\t\t\t// from being used by subsequent evaluations from other code paths.\n\t\t\tthis.engine.setKeystrokeSignal(null);\n\n\t\t\t// Phase 5.3: Always disable arena, even on exception.\n\t\t\t// Prevents arena Values from leaking into subsequent evaluations or tests.\n\t\t\tdisableValueArena();\n\t\t}\n\t}\n\n\t/**\n\t * Background-compile invisible dirty lines beyond the viewport (Tier 3 only).\n\t *\n\t * Compiles expressions to discover reads/writes for the dependency graph\n\t * without executing display-only expressions. Variable definitions are\n\t * executed to maintain VM state for future Tier-2 executions.\n\t *\n\t * This is intended to be called after evaluate() so visible lines are\n\t * rendered first, then background work fills in the dependency graph.\n\t *\n\t * **Phase 5.2h:** This synchronous method is retained for environments\n\t * without Worker support. Prefer `dispatchBackgroundCompiles()` which\n\t * offloads compilation to a Web Worker with Transferable bytecode.\n\t */\n\tbackgroundCompile(viewport: ViewportRange): EvalLineResult[] {\n\t\tconst results: EvalLineResult[] = [];\n\t\tconst docEnd = this.doc.lineCount;\n\t\tconst startPos = viewport.endLine + 1;\n\n\t\tfor (let pos = startPos; pos <= docEnd; pos++) {\n\t\t\tconst state = this.doc.getLineAt(pos);\n\t\t\tif (!state) continue;\n\n\t\t\t// Skip clean lines, already compiled + executed\n\t\t\tif (!state.dirty) continue;\n\n\t\t\t// Skip already-compiled Tier 3 lines, they have bytecode\n\t\t\t// but were compiled without execution (non-variable-def).\n\t\t\t// Recompiling is wasteful since the text hasn't changed\n\t\t\t// (text change clears bytecodes via editLine).\n\t\t\tif (state.bytecodes.length > 0 && !state.isVariableDef) continue;\n\n\t\t\tconst lineResult = this.evaluateSingleLine(state, pos, false);\n\t\t\tresults.push(lineResult);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Dispatch background compilation to a Web Worker (Phase 5.2h).\n\t *\n\t * Collects invisible dirty lines beyond the viewport that need compilation,\n\t * sends them to the compilation worker, and asynchronously stores the\n\t * transferred bytecode in the DocumentModel when the worker responds.\n\t *\n\t * This is the non-blocking alternative to `backgroundCompile()`. The worker\n\t * compiles expressions with Transferable ArrayBuffers (zero-copy postMessage),\n\t * so bytecode appears on the main thread without serialization overhead.\n\t *\n\t * Lines that already have cached bytecode (from a previous worker pass or\n\t * synchronous compile) are skipped, only truly uncompiled dirty lines are\n\t * sent to the worker.\n\t *\n\t * **Usage:** Call after `evaluate()` so visible lines render first, then\n\t * this fills the bytecode cache for future Tier-2 scrolls.\n\t *\n\t * @param viewport The current visible range. Lines beyond viewport.endLine\n\t * that are dirty and don't have bytecode are dispatched.\n\t */\n\tdispatchBackgroundCompiles(viewport: ViewportRange): void {\n\t\t// Collect invisible dirty lines that need compilation\n\t\tconst items = this.collectInvisibleCompileTargets(viewport);\n\t\tif (items.length === 0) return;\n\n\t\t// Lazy-init the worker (only if there are items to compile)\n\t\tif (!this.compilationWorker) {\n\t\t\tthis.compilationWorker = new CompilationWorkerManager();\n\t\t}\n\n\t\t// Fire-and-forget: send to worker, store results when they arrive\n\t\tthis.compilationWorker.compileBatch(items).then((results) => {\n\t\t\tthis.compilationWorker!.storeResults(results, this.doc);\n\t\t}).catch((_err) => {\n\t\t\t// Worker failure is non-fatal, next evaluate() will compile\n\t\t\t// these expressions synchronously.\n\t\t});\n\t}\n\n\t/**\n\t * Terminate the compilation worker if active, and unsubscribe from\n\t * sharedGlobalVariableStore. Call this when the evaluator is no longer\n\t * needed to clean up resources, every call site that retires a\n\t * ThreeTierEvaluator (document switch, pane destroy()) already calls\n\t * this unconditionally, so folding the global-store unsubscribe in here\n\t * needs no new call sites anywhere.\n\t */\n\tterminateWorker(): void {\n\t\tif (this.compilationWorker) {\n\t\t\tthis.compilationWorker.terminate();\n\t\t\tthis.compilationWorker = null;\n\t\t}\n\t\tif (this.globalUnsubscribe) {\n\t\t\tthis.globalUnsubscribe();\n\t\t\tthis.globalUnsubscribe = null;\n\t\t}\n\t}\n\n\t/**\n\t * Get the DocumentModel (read-only access for decoration building).\n\t */\n\tgetDoc(): DocumentModel {\n\t\treturn this.doc;\n\t}\n\n\t/**\n\t * Evaluate all dirty lines in the document, regardless of viewport.\n\t * Used for full re-evaluation after plugin register/unregister.\n\t */\n\tevaluateAll(signal?: AbortSignal): EvalResult {\n\t\tconst viewport = { startLine: 1, endLine: this.doc.lineCount };\n\t\tconst result = this.evaluate(viewport, signal);\n\t\t// evaluate() already calls maintainAfterEval internally\n\t\treturn result;\n\t}\n\n\t/**\n\t * Zero-allocation viewport evaluation, the Phase 5.2e \"holy grail.\"\n\t *\n\t * **Key insight:** When the user scrolls (viewport-only change, no edits),\n\t * we don't need to re-evaluate from line 1. Instead:\n\t *\n\t * 1. Restore the VM to just before the viewport via the nearest checkpoint.\n\t * 2. Evaluate ONLY the visible lines (Tier 2 for clean cached, Tier 1 for dirty).\n\t * 3. Lines before the viewport are completely skipped, their state lives in\n\t * the VM checkpointer's prototypal chain.\n\t *\n\t * **Correctness guard:** If any variable-definition line before the viewport\n\t * is dirty (e.g., the user edited a variable def that hasn't been\n\t * re-evaluated yet), we clear stale checkpoints and fall back to `evaluate()`\n\t * which processes from line 1 and rebuilds fresh checkpoints. This\n\t * guarantees that stale checkpoints are never used as restoration targets.\n\t * Only variable-def lines matter here, `VMCheckpointer.snapshot()` only\n\t * records state for lines that write a variable, so a dirty plain-expression\n\t * line before the viewport has no checkpoint to invalidate (see\n\t * `DocumentModel.hasAnyDirtyVariableDefLineBefore()`).\n\t *\n\t * **Performance:** O(visible lines) instead of O(document length). Target:\n\t * < 1ms for a typical ~30-line viewport, independent of document size.\n\t *\n\t * @param viewport The visible line range.\n\t * @returns Results for visible lines only. Lines before the viewport are\n\t * not included in `lines[]` or `resultMap`.\n\t */\n\tsetViewport(viewport: ViewportRange, signal?: AbortSignal): EvalResult {\n\t\t// ── One AbortController Per Keystroke ────────────────────────\n\t\t// Link the UI layer's keystroke signal to the engine.\n\t\tthis.engine.setKeystrokeSignal(signal ?? null);\n\n\t\t// ── Correctness guard: dirty lines before viewport invalidate checkpoints ──\n\t\tif (viewport.startLine > 1 && this.hasDirtyLinesBefore(viewport.startLine)) {\n\t\t\t// Clear stale checkpoints, evaluate() will rebuild them from line 1.\n\t\t\t// evaluate() handles its own arena enable/disable and signal cleanup.\n\t\t\tthis.checkpointer?.clear();\n\t\t\treturn this.evaluate(viewport, signal);\n\t\t}\n\n\t\t// ── Phase 5.2g: Page-based LRU eviction (MUST run before preload) ──\n\t\t// maintainAfterEval captures the scroll direction and updates lastViewportStart\n\t\t// BEFORE preloadNextPages reads the direction for preloading.\n\t\tthis.pageManager.maintainAfterEval(viewport, this.doc);\n\n\t\t// ── Phase 5.2g: Detect scroll direction & preload ───────────\n\t\tthis.preloadNextPages(viewport);\n\n\t\t// ── Restore VM state from nearest checkpoint before the viewport ──\n\t\t// This sets all variables that were defined at or before startLine-1.\n\t\tthis.restoreTo(viewport.startLine - 1);\n\n\t\t// ── Phase 5.3: Enable arena for zero-allocation Tier 2 execution ──\n\t\tenableValueArena();\n\t\ttry {\n\t\t\t// ── Evaluate only visible lines ──\n\t\t\tconst result = this.collectEvalResults(viewport.startLine, viewport.endLine);\n\t\t\treturn result;\n\t\t} finally {\n\t\t\t// Clear keystroke signal to prevent stale signal references.\n\t\t\tthis.engine.setKeystrokeSignal(null);\n\n\t\t\t// Phase 5.3: Always disable arena, even on exception.\n\t\t\t// Prevents cross-test contamination from arena leaks.\n\t\t\tdisableValueArena();\n\t\t}\n\t}\n\n\t/**\n\t * Apply incremental line-level changes to the document model.\n\t *\n\t * **Phase 5.2f:** Replaces the O(N) `setDocument()` + full re-evaluation\n\t * with O(changed) incremental updates. Key benefits:\n\t *\n\t * 1. Unchanged lines retain their persistent lineIds → bytecode survives\n\t * 2. Only changed + DAG-downstream lines are marked dirty → Tier 1 re-evaluation\n\t * 3. Clean lines in viewport use Tier 2 (cached bytecode execution)\n\t * 4. Clean lines outside viewport are skipped entirely\n\t *\n\t * The DAG is fully cleared after propagation: shifted lines would have\n\t * stale entries keyed by old line numbers, so the DAG is rebuilt from\n\t * scratch during the subsequent `evaluate()` call.\n\t *\n\t * **Caller should follow up with `evaluate(viewport)`** to re-evaluate\n\t * dirty lines from line 1 and rebuild the DAG + checkpoints.\n\t *\n\t * @param changes Line-level changes to apply. Must be non-overlapping.\n\t * @returns Metadata about the applied changes.\n\t */\n\tapplyTransaction(changes: LineChange[]): {\n\t\tinserted: number[];\n\t\tremoved: number[];\n\t} {\n\t\t// ── Phase 1: Collect DAG writes + downstream lineIds ───────────\n\t\t// Must happen BEFORE applyChanges() because line numbers are still\n\t\t// valid at this point. We collect writes from deleted lines and\n\t\t// resolve downstream consumers to lineIds (not line numbers) so\n\t\t// they survive the position shifts that applyChanges() causes.\n\t\tconst allWrites = new Set<string>();\n\n\t\tfor (const change of changes) {\n\t\t\tfor (let i = 0; i < change.deleteCount; i++) {\n\t\t\t\tconst lineNum = change.startLine + i;\n\t\t\t\tconst writes = this.dag.getWrites(lineNum);\n\t\t\t\tfor (const w of writes) {\n\t\t\t\t\tallWrites.add(w);\n\t\t\t\t}\n\t\t\t\t// Clean up DAG references for this line\n\t\t\t\tthis.dag.removeLine(lineNum);\n\t\t\t\t// And its cached bytecode. The dependency graph was already\n\t\t\t\t// pruned here; the LineCache was not, so a deleted line kept its\n\t\t\t\t// entry until the whole cache was dropped on a document switch.\n\t\t\t\t// Editing a long document over a session accumulated entries for\n\t\t\t\t// line numbers that no longer existed.\n\t\t\t\tthis.engine.getLineCache().removeAllForLine(lineNum);\n\t\t\t}\n\t\t}\n\n\t\t// Resolve downstream consumers to persistent lineIds BEFORE the\n\t\t// structural change shifts line numbers. After applyChanges(),\n\t\t// we mark these lineIds dirty, their positions don't matter.\n\t\tconst downstreamLineIds = new Set<number>();\n\t\tfor (const writeVar of allWrites) {\n\t\t\tconst affected = this.dag.getAffectedLines(writeVar);\n\t\t\tfor (const lineNum of affected) {\n\t\t\t\tconst state = this.doc.getLineAt(lineNum);\n\t\t\t\tif (state) {\n\t\t\t\t\tdownstreamLineIds.add(state.lineId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// ── Phase 2: Apply structural changes to DocumentModel ─────────\n\t\tconst result = this.doc.applyChanges(changes);\n\n\t\t// ── Phase 3: Clear checkpointer (line numbers shifted) ─────────\n\t\tthis.checkpointer?.clear();\n\n\t\t// ── Phase 4: Mark DAG-downstream lines dirty by lineId ─────────\n\t\t// Using lineId instead of line number is position-agnostic:\n\t\t// lines that shifted due to insertions/deletions above them are\n\t\t// still correctly targeted. Lines that were deleted (lineId no\n\t\t// longer in the doc) are silently ignored by markDirty().\n\t\tfor (const lineId of downstreamLineIds) {\n\t\t\tthis.doc.markDirty(lineId);\n\t\t}\n\n\t\t// ── Phase 5: Clear DAG to avoid phantom entries ────────────────\n\t\t// Entries keyed by old line numbers are stale after structural\n\t\t// changes. Rather than updating shifted entries, we clear the DAG\n\t\t// and let the subsequent evaluate() call rebuild it from scratch.\n\t\tthis.dag.clear();\n\n\t\treturn {\n\t\t\tinserted: result.inserted,\n\t\t\tremoved: result.removed,\n\t\t};\n\t}\n\n\t// ── Private helpers ─────────────────────────────────────────────────\n\n\t/**\n\t * Reset running-total accumulators and mark the lines that touch them\n\t * dirty, so the from-line-1 pass in {@link evaluate} recomputes each total\n\t * from its seed instead of reading its own previous evaluation's value.\n\t *\n\t * A `total += 5` line compiles to no bytecode (it rides the symbolic\n\t * channel), so a clean one would be skipped by the tier dispatch rather\n\t * than re-run. It must re-run to re-apply its delta over the freshly-reset\n\t * base, so every line that WRITES an accumulator name is forced dirty (the\n\t * DAG drops a self-writing line from its own variable's consumers, so\n\t * getAffectedLines can't surface them). Pure readers of the total keep\n\t * their real bytecode and re-run via Tier 2 once the total is correct, so\n\t * they need no special handling. Cheap: a no-op unless the document\n\t * actually uses `+=`/`-=`, and accumulators are rare.\n\t */\n\tprivate reseedAccumulators(): void {\n\t\tconst names = this.engine.resetAccumulators();\n\t\tif (names.size === 0) return;\n\t\tconst docEnd = this.doc.lineCount;\n\t\tfor (let pos = 1; pos <= docEnd; pos++) {\n\t\t\tconst writes = this.dag.getWrites(pos);\n\t\t\tif (writes.size === 0) continue;\n\t\t\tfor (const w of writes) {\n\t\t\t\tif (names.has(w)) {\n\t\t\t\t\tthis.doc.markDirtyByLineNumber(pos);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Collect evaluation results for a contiguous range of lines.\n\t *\n\t * Used by both `evaluate()` (startLine=1) and `setViewport()` (any start).\n\t * All lines in the range are treated as in-viewport (visible), callers that\n\t * need the invisible/dirty → Tier 3 handling should use `evaluate()` instead.\n\t *\n\t * @param startLine First line to evaluate (1-based, inclusive).\n\t * @param endLine Last line to evaluate (1-based, inclusive). Clamped to docEnd.\n\t */\n\tprivate collectEvalResults(startLine: number, endLine: number): EvalResult {\n\t\tconst lines: EvalLineResult[] = [];\n\t\tconst resultMap = new Map<number, Value[]>();\n\t\tconst tierCounts = { tier1: 0, tier2: 0, tier3: 0, skipped: 0 };\n\n\t\tconst docEnd = this.doc.lineCount;\n\t\tconst evalEnd = Math.min(endLine, docEnd);\n\n\t\tfor (let pos = startLine; pos <= evalEnd; pos++) {\n\t\t\tconst state = this.doc.getLineAt(pos);\n\t\t\tif (!state) continue;\n\n\t\t\t// All processed lines are in-viewport for setViewport, or conditionally\n\t\t\t// in-viewport for evaluate (handled by caller). We pass `true` here\n\t\t\t// because evaluateSingleLine's `inViewport` param controls Tier 1 vs\n\t\t\t// Tier 3 dispatch; callers must manage this distinction externally.\n\t\t\t//\n\t\t\t// evaluate() handles this by passing `inViewport` per-line; it loops\n\t\t\t// directly rather than using this helper for that reason.\n\t\t\tconst lineResult = this.evaluateSingleLine(state, pos, true);\n\t\t\tlines.push(lineResult);\n\n\t\t\tif (lineResult.tier === EvalTier.Tier1) tierCounts.tier1++;\n\t\t\telse if (lineResult.tier === EvalTier.Tier2) tierCounts.tier2++;\n\t\t\telse if (lineResult.tier === EvalTier.Tier3) tierCounts.tier3++;\n\t\t\telse tierCounts.skipped++;\n\n\t\t\tif (lineResult.results) {\n\t\t\t\tresultMap.set(pos, lineResult.results.flat());\n\t\t\t}\n\t\t}\n\n\t\treturn { lines, resultMap, tierCounts };\n\t}\n\n\t/**\n\t * Check whether any **variable-definition** line before `position`\n\t * (1-based, exclusive) is dirty.\n\t *\n\t * Used by `setViewport()` to decide whether to fall back to `evaluate()`:\n\t * if a variable-def before the viewport is dirty, the checkpoint state\n\t * `restoreTo()` would use may be stale and we need to reprocess from\n\t * line 1 to rebuild checkpoints correctly.\n\t *\n\t * Deliberately narrower than `DocumentModel.hasAnyDirtyLineBefore()`:\n\t * checkpoints only snapshot variable-def lines (see VMCheckpointer), so a\n\t * dirty plain-expression line before the viewport can't have invalidated\n\t * one, there's nothing checkpointed for it to invalidate. Using the\n\t * broader check here previously caused a real perf bug: `PageManager`'s\n\t * cold-page eviction marks evicted non-variable-def lines dirty, so\n\t * scrolling far into a large, variable-def-free document would trip this\n\t * guard, fall back to `evaluate()`, which recompiles those lines via\n\t * Tier 3 (never clearing their dirty flag by design), causing the very\n\t * next `maintainAfterEval()` to re-evict and re-dirty them, a\n\t * self-sustaining loop that pinned every subsequent `setViewport()` call\n\t * to the cost of a full re-evaluation instead of O(visible lines).\n\t *\n\t * Delegates to DocumentModel.hasAnyDirtyVariableDefLineBefore(), which\n\t * tracks dirty lineIds incrementally instead of scanning every line up to\n\t * `position` on every call. This used to be a real per-scroll cost\n\t * (benchmarked at ~10ms scrolled near the bottom of a 20k-line document)\n\t * since it fired on every viewport change, not just edits.\n\t */\n\tprivate hasDirtyLinesBefore(position: number): boolean {\n\t\treturn this.doc.hasAnyDirtyVariableDefLineBefore(position);\n\t}\n\n\t/**\n\t * Evaluate a single line using the appropriate tier.\n\t *\n\t * Tier assignment logic:\n\t * - Empty/markdown-only lines → skipped\n\t * - Dirty + in-viewport → Tier 1 (full pipeline)\n\t * - Dirty + not in viewport → Tier 3 (compile-only, execute variable defs)\n\t * - Clean + has bytecode + in viewport → Tier 2 (execute from cache)\n\t * - Clean + no bytecode → skipped (non-evaluable)\n\t */\n\tprivate evaluateSingleLine(\n\t\tstate: LineState,\n\t\tlineNumber: number,\n\t\tinViewport: boolean\n\t): EvalLineResult {\n\t\tconst baseResult: Omit<EvalLineResult, \"tier\" | \"result\" | \"error\"> = {\n\t\t\tlineId: state.lineId,\n\t\t\tlineNumber,\n\t\t};\n\n\t\t// Skip empty/markdown-only lines\n\t\tif (state.isEmpty || isEmptyLine(state.text)) {\n\t\t\tstate.isEmpty = true;\n\t\t\tthis.doc.markClean(state.lineId);\n\t\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t\t}\n\n\t\t// Extract all evaluable expressions (may be multiple inline solves)\n\t\tconst { expressions, inlineSolveCount } = this.extractExpressions(state);\n\t\tif (expressions.length === 0) {\n\t\t\tstate.isEmpty = true;\n\t\t\tthis.doc.markClean(state.lineId);\n\t\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t\t}\n\n\t\t// Determine the expression to evaluate (only needed for dirty lines)\n\t\tif (state.dirty) {\n\t\t\tif (inViewport) {\n\t\t\t\t// ── Tier 1: Visible + Dirty → Full Pipeline ──────────\n\t\t\t\treturn this.evaluateTier1(state, lineNumber, expressions, inlineSolveCount, baseResult);\n\t\t\t} else {\n\t\t\t\t// ── Tier 3: Invisible + Dirty → Compile-only ─────────\n\t\t\t\t// Skip recompilation if already compiled by a previous Tier 3 pass.\n\t\t\t\t// Non-variable-def lines keep dirty=true after Tier 3 (so they get\n\t\t\t\t// Tier 1 when scrolled into view), but recompiling identical text\n\t\t\t\t// produces the same bytecode and DAG entries. Text changes clear\n\t\t\t\t// bytecodes via DocumentModel.editLine(), so a length check is safe.\n\t\t\t\tif (state.bytecodes.length > 0 && state.bytecodes.length === expressions.length && !state.isVariableDef) {\n\t\t\t\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t\t\t\t}\n\t\t\t\treturn this.evaluateTier3(state, lineNumber, expressions, inlineSolveCount, baseResult);\n\t\t\t}\n\t\t}\n\n\t\t// Line is clean\n\t\tif (inViewport && state.bytecodes.length > 0) {\n\t\t\t// ── Tier 2: Visible + Cached → Execute from bytecode ────\n\t\t\treturn this.evaluateTier2(state, lineNumber, baseResult);\n\t\t}\n\n\t\t// Clean, not in viewport, or no bytecode → skip\n\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t}\n\n\t/**\n\t * Tier 1: Full pipeline, lex, parse, compile, execute.\n\t * Uses the engine's existing evaluateLine() which handles all pipeline\n\t * stages including DAG updates and LineCache population.\n\t *\n\t * Supports multiple expressions per line (inline solves). Evaluates each\n\t * expression left-to-right through the engine so variable definitions in\n\t * earlier solves update the VM state before later solves are evaluated.\n\t * Reads/writes are aggregated across all expressions for the DAG.\n\t */\n\tprivate evaluateTier1(\n\t\tstate: LineState,\n\t\tlineNumber: number,\n\t\texpressions: string[],\n\t\tinlineSolveCount: number,\n\t\tbaseResult: Omit<EvalLineResult, \"tier\" | \"result\" | \"error\">\n\t): EvalLineResult {\n\t\tconst allResults: Value[][] = [];\n\t\tconst allBytecodes: BytecodeProgram[] = [];\n\t\tconst allReads = new Set<string>();\n\t\tconst allWrites = new Set<string>();\n\t\tlet hasVariableDef = false;\n\t\tlet lastValue: Value | null = null;\n\t\tlet firstError: string | null = null;\n\t\tlet anyFailed = false;\n\t\t/** Set when any expression returned a value still waiting on a resolver. */\n\t\tlet anyPending = false;\n\n\t\t// Evaluate each expression independently, a failure in one expression\n\t\t// (e.g., parse error in s`bad syntax`) must not prevent other expressions\n\t\t// on the same line from being evaluated and having their results stored.\n\t\t// Without per-expression error handling, same-line cross-reference inline\n\t\t// solves (s`:a = 5` s`:b = a + 3` s`a + b`) would lose ALL results when\n\t\t// the third expression throws because 'b' references cross a VM state\n\t\t// boundary or the engine encounters a transient error.\n\t\tfor (const expression of expressions) {\n\t\t\tif (!expression.trim()) continue;\n\n\t\t\tlet value: Value[] | null = null;\n\t\t\tlet entry: { bytecode: BytecodeProgram; readVariables: string[]; writeVariable: string | null } | undefined;\n\n\t\t\ttry {\n\t\t\t\t// evaluateLine returns the single evaluated Value; this evaluator\n\t\t\t\t// keeps its results grouped as Value[] per expression (allResults\n\t\t\t\t// is Value[][]), so wrap the one value into its group here.\n\t\t\t\tconst evaluated = this.engine.evaluateLine(lineNumber, expression);\n\t\t\t\tvalue = [evaluated];\n\t\t\t\tlastValue = evaluated;\n\t\t\t\t// Sync the DocumentModel from the LineCache.\n\t\t\t\t// Use get(lineNumber, expression) instead of getEntryForLine(lineNumber)\n\t\t\t\t// because multiple expressions on the same line share the same lineNumber\n\t\t\t\t// and getEntryForLine always returns the FIRST entry (Map insertion order).\n\t\t\t\tentry = this.engine.getLineCache().get(lineNumber, expression) as typeof entry;\n\t\t\t} catch (e) {\n\t\t\t\tconst errorMessage = e instanceof Error ? e.message : String(e);\n\t\t\t\tif (!firstError) firstError = errorMessage;\n\t\t\t\tanyFailed = true;\n\t\t\t\tvalue = null;\n\t\t\t}\n\n\t\t\t// An unresolved async value does not throw, so `anyFailed` alone would\n\t\t\t// let this line be marked clean while its data has not arrived. Once\n\t\t\t// clean, nothing re-runs the resolver preflight and the value stays\n\t\t\t// pending for good. Treat it as not-yet-complete instead.\n\t\t\tif (value && value.some((v) => v.type === ValueType.Pending)) {\n\t\t\t\tanyPending = true;\n\t\t\t}\n\n\t\t\tif (value) {\n\t\t\t\tallResults.push(value);\n\t\t\t} else {\n\t\t\t\t// Expression failed, push an ErrorValue sentinel so results[] stays\n\t\t\t\t// aligned with expressions[] and bytecodes[] indices. Downstream code\n\t\t\t\t// checking result.type === Error will find it, vs a raw null that NPEs.\n\t\t\t\tallResults.push([errorValue(\"eval_failed\", firstError ?? \"unknown error\")]);\n\t\t\t}\n\n\t\t\tif (entry) {\n\t\t\t\tallBytecodes.push(entry.bytecode);\n\t\t\t\tfor (const r of entry.readVariables) allReads.add(r);\n\t\t\t\tif (entry.writeVariable) {\n\t\t\t\t\tallWrites.add(entry.writeVariable);\n\t\t\t\t\thasVariableDef = true;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Fallback: LineCache missed, compile expression ourselves\n\t\t\t\ttry {\n\t\t\t\t\tconst { program, reads, writes } = this.engine.compileExpression(expression);\n\t\t\t\t\tallBytecodes.push(program);\n\t\t\t\t\tfor (const r of reads) allReads.add(r);\n\t\t\t\t\tfor (const w of writes) allWrites.add(w);\n\t\t\t\t\tif (writes.length > 0) hasVariableDef = true;\n\t\t\t\t} catch (compileErr) {\n\t\t\t\t\t// Push empty bytecode, expression will recompile on next pass.\n\t\t\t\t\t// The expression still failed to compile, but reads/writes were\n\t\t\t\t\t// already extracted from its tokens before the parse attempt\n\t\t\t\t\t// compileExpression() surfaces them via the thrown error's\n\t\t\t\t\t// context. Register them anyway so the DAG knows this line\n\t\t\t\t\t// depends on those variables and re-evaluates it once they\n\t\t\t\t\t// become defined, instead of losing the dependency entirely.\n\t\t\t\t\tallBytecodes.push({ opcodes: new Uint8Array(0), numbers: new Float64Array(0), strings: [], hasAsync: false });\n\t\t\t\t\tif (compileErr instanceof EngineError && compileErr.context) {\n\t\t\t\t\t\tconst errReads = compileErr.context.reads;\n\t\t\t\t\t\tconst errWrites = compileErr.context.writes;\n\t\t\t\t\t\tif (Array.isArray(errReads)) for (const r of errReads) allReads.add(r);\n\t\t\t\t\t\tif (Array.isArray(errWrites)) for (const w of errWrites) allWrites.add(w);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst reads = [...allReads];\n\t\tconst writes = [...allWrites];\n\n\t\t// Always store results, even partial ones. If any expression failed\n\t\t// the line stays dirty so the failed expression(s) get retried on the\n\t\t// next evaluation pass. But successfully-evaluated expressions' results\n\t\t// are preserved so the DAG, UI decorations, and downstream consumers\n\t\t// can use them immediately.\n\t\tif (anyFailed || anyPending) {\n\t\t\t// Store partial results via updateLineCompiled (doesn't clear dirty).\n\t\t\t// The successful expressions' bytecodes are cached so Tier 2 works\n\t\t\t// for them on the next scroll pass.\n\t\t\tthis.doc.updateLineCompiled(\n\t\t\t\tstate.lineId,\n\t\t\t\texpressions,\n\t\t\t\tallBytecodes,\n\t\t\t\treads,\n\t\t\t\twrites,\n\t\t\t\thasVariableDef,\n\t\t\t\tinlineSolveCount,\n\t\t\t);\n\t\t\t// Also set results for the successful expressions\n\t\t\tstate.results = allResults;\n\t\t\tstate.result = allResults[0]?.[0] ?? null;\n\t\t\tstate.inlineSolveCount = inlineSolveCount;\n\t\t\tstate.expressions = expressions;\n\t\t} else {\n\t\t\t// All expressions succeeded, store full results and mark clean\n\t\t\tthis.doc.updateLineResult(\n\t\t\t\tstate.lineId,\n\t\t\t\tallResults,\n\t\t\t\tallBytecodes,\n\t\t\t\texpressions,\n\t\t\t\treads,\n\t\t\t\twrites,\n\t\t\t\thasVariableDef,\n\t\t\t\tinlineSolveCount,\n\t\t\t);\n\t\t}\n\n\t\t// Register reads/writes in DAG (aggregated across all expressions).\n\t\t// Always register, even lines with no reads/writes (pure expressions\n\t\t// like \"2+2\") need DAG entries so downstream queries for line presence work.\n\t\tthis.dag.registerLine(lineNumber, reads, writes);\n\n\t\t// ── Checkpoint after variable definition ──\n\t\t// A pending value is not a value worth checkpointing: restoring it would\n\t\t// reinstate the unresolved placeholder rather than the eventual result.\n\t\tif (this.checkpointer && writes.length > 0 && !anyFailed && !anyPending) {\n\t\t\tthis.checkpointer.snapshot(lineNumber, state.lineId, writes);\n\t\t}\n\n\t\treturn {\n\t\t\t...baseResult,\n\t\t\ttier: EvalTier.Tier1,\n\t\t\tresult: lastValue,\n\t\t\tresults: allResults,\n\t\t\terror: firstError,\n\t\t};\n\t}\n\n\t/**\n\t * Tier 2: Execute from cached bytecode only.\n\t * Skips lexing, parsing, and compiling, runs the pre-compiled bytecode\n\t * against the engine's shared VM. Supports multiple bytecodes per line\n\t * (inline solves), each is executed left-to-right so variable definitions\n\t * in earlier bytecodes update the VM before later ones run.\n\t * Assumes the VM already has correct variable state from preceding\n\t * Tier-1 evaluations.\n\t */\n\tprivate evaluateTier2(\n\t\tstate: LineState,\n\t\tlineNumber: number,\n\t\tbaseResult: Omit<EvalLineResult, \"tier\" | \"result\" | \"error\">\n\t): EvalLineResult {\n\t\tif (state.bytecodes.length === 0) {\n\t\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t\t}\n\n\t\tconst results: Value[][] = [];\n\t\tlet lastValue: Value | null = null;\n\t\tlet firstError: string | null = null;\n\t\tlet anyFailed = false;\n\n\t\t// Execute each bytecode independently, a failure in one should not\n\t\t// prevent other bytecodes on the same line from executing. Same-line\n\t\t// inline solves with variable definitions (s`:a = 5` s`a + 3`) rely\n\t\t// on earlier bytecodes updating the VM before later ones execute.\n\t\tfor (const bytecode of state.bytecodes) {\n\t\t\tif (bytecode.opcodes.length === 0) continue;\n\t\t\ttry {\n\t\t\t\tconst value = this.engine.executeCached(bytecode, lineNumber);\n\t\t\t\tlastValue = value;\n\t\t\t\tresults.push([value]);\n\t\t\t} catch (e) {\n\t\t\t\tconst errorMessage = e instanceof Error ? e.message : String(e);\n\t\t\t\tif (!firstError) firstError = errorMessage;\n\t\t\t\tanyFailed = true;\n\t\t\t\t// Push error sentinel to maintain results[i] ↔ bytecodes[i] alignment\n\t\t\t\tresults.push([errorValue(\"exec_failed\", errorMessage)]);\n\t\t\t}\n\t\t}\n\n\t\t// Update DAG: re-register reads/writes from the cached metadata.\n\t\t// Always register, even empty reads/writes so DAG line-presence queries work.\n\t\tthis.dag.registerLine(lineNumber, state.reads, state.writes);\n\n\t\tstate.results = results;\n\t\tstate.result = results[0]?.[0] ?? null;\n\t\tif (anyFailed) {\n\t\t\t// Mark dirty so failed bytecodes are re-compiled (Tier 1) next pass\n\t\t\tthis.doc.markDirty(state.lineId);\n\t\t}\n\n\t\treturn { ...baseResult, tier: EvalTier.Tier2, result: lastValue, results, error: firstError };\n\t}\n\n\t/**\n\t * Tier 3: Compile-only for invisible lines.\n\t * Lex → Parse → Compile to discover reads/writes for the dependency graph.\n\t * Executes the bytecode ONLY if the line defines a variable (isVariableDef\n\t * or writes.length > 0), because variable assignments affect VM state\n\t * that other lines depend on. Pure expression lines are compiled but NOT\n\t * executed, saving CPU for large documents.\n\t *\n\t * Supports multiple expressions per line (inline solves). Each is compiled\n\t * separately; variable-def expressions are also executed.\n\t */\n\tprivate evaluateTier3(\n\t\tstate: LineState,\n\t\tlineNumber: number,\n\t\texpressions: string[],\n\t\tinlineSolveCount: number,\n\t\tbaseResult: Omit<EvalLineResult, \"tier\" | \"result\" | \"error\">\n\t): EvalLineResult {\n\t\tconst allBytecodes: BytecodeProgram[] = [];\n\t\tconst allReads = new Set<string>();\n\t\tconst allWrites = new Set<string>();\n\t\tlet hasVariableDef = false;\n\t\tlet lastResult: Value | null = null;\n\t\tlet firstError: string | null = null;\n\t\tlet anyFailed = false;\n\t\t/** Set when a result is still waiting on a resolver. */\n\t\tlet anyPending = false;\n\n\t\t// Compile each expression independently, a parse error in one\n\t\t// should not prevent other expressions from being compiled and\n\t\t// having their reads/writes registered in the DAG.\n\t\tfor (const expression of expressions) {\n\t\t\tif (!expression.trim()) continue;\n\n\t\t\ttry {\n\t\t\t\tconst { program, reads, writes } = this.engine.compileExpression(expression);\n\t\t\t\tallBytecodes.push(program);\n\t\t\t\tfor (const r of reads) allReads.add(r);\n\t\t\t\tfor (const w of writes) allWrites.add(w);\n\t\t\t\tif (writes.length > 0) hasVariableDef = true;\n\n\t\t\t\tif (writes.length > 0 && program.opcodes.length > 0) {\n\t\t\t\t\t// Variable definitions MUST execute to maintain VM state\n\t\t\t\t\tlastResult = this.engine.executeCached(program, lineNumber);\n\t\t\t\t\t// Same reasoning as Tier 1: a pending result does not throw,\n\t\t\t\t\t// and marking the line clean would strand it unresolved.\n\t\t\t\t\tif (lastResult && lastResult.type === ValueType.Pending) {\n\t\t\t\t\t\tanyPending = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tconst errorMessage = e instanceof Error ? e.message : String(e);\n\t\t\t\tif (!firstError) firstError = errorMessage;\n\t\t\t\tanyFailed = true;\n\t\t\t\t// Push empty bytecode placeholder for alignment\n\t\t\t\tallBytecodes.push({ opcodes: new Uint8Array(0), numbers: new Float64Array(0), strings: [], hasAsync: false });\n\t\t\t}\n\t\t}\n\n\t\tconst reads = [...allReads];\n\t\tconst writes = [...allWrites];\n\n\t\t// Store compile-only state in DocumentModel, even partial results\n\t\t// preserve successful expressions' bytecodes and DAG data.\n\t\tthis.doc.updateLineCompiled(\n\t\t\tstate.lineId,\n\t\t\texpressions,\n\t\t\tallBytecodes,\n\t\t\treads,\n\t\t\twrites,\n\t\t\thasVariableDef,\n\t\t\tinlineSolveCount,\n\t\t);\n\n\t\t// Register reads/writes in DAG regardless, partial data is valid.\n\t\t// Always register, even empty reads/writes for DAG line-presence queries.\n\t\tthis.dag.registerLine(lineNumber, reads, writes);\n\n\t\tif (hasVariableDef && lastResult && !anyFailed && !anyPending) {\n\t\t\tstate.results = [[lastResult]];\n\t\t\tstate.result = lastResult;\n\t\t\tthis.doc.markClean(state.lineId);\n\n\t\t\t// ── Checkpoint after variable definition ────────────\n\t\t\tif (this.checkpointer) {\n\t\t\t\tthis.checkpointer.snapshot(lineNumber, state.lineId, writes);\n\t\t\t}\n\t\t}\n\n\t\treturn { ...baseResult, tier: EvalTier.Tier3, result: lastResult, results: hasVariableDef && lastResult && !anyFailed && !anyPending ? [[lastResult]] : undefined, error: firstError };\n\t}\n\n\t// ── Public checkpoint API (used by Phase 5.2e setViewport) ──────\n\n\t/**\n\t * Restore the VM to the state at or just after the given line number.\n\t *\n\t * Finds the nearest checkpoint at or before `lineNumber` and replays\n\t * all variable definitions from the checkpoint chain into the VM.\n\t * After calling this, the VM is ready to evaluate lines starting at\n\t * `lineNumber + 1` without re-evaluating all preceding lines.\n\t *\n\t * **Usage:** Phase 5.2e's `setViewport()` calls `restoreTo(viewport.startLine - 1)`\n\t * before evaluating only the newly visible lines. This is the key to\n\t * O(visible lines) scrolling.\n\t *\n\t * @param lineNumber The line number to restore to. Variables defined\n\t * at lines ≤ this number will be available in the VM.\n\t */\n\trestoreTo(lineNumber: number): void {\n\t\tif (this.checkpointer) {\n\t\t\tthis.checkpointer.restoreTo(lineNumber);\n\t\t}\n\t}\n\n\t/**\n\t * Get the VM checkpointer, or null if checkpointing is disabled.\n\t */\n\tgetCheckpointer(): VMCheckpointer | null {\n\t\treturn this.checkpointer;\n\t}\n\n\t/**\n\t * Get the PageManager (Phase 5.2g).\n\t * Exposed for testing.\n\t */\n\tgetPageManager(): PageManager {\n\t\treturn this.pageManager;\n\t}\n\n\t// ── Phase 5.2g: Directional preloading ──────────────────────────\n\n\t/**\n\t * Preload the next 1–2 pages in the current scroll direction.\n\t *\n\t * Called during `setViewport()` (scroll-only path). Collects dirty\n\t * uncompiled lines in pages just beyond the viewport and dispatches\n\t * them to the background compilation worker so bytecode is ready\n\t * before the user scrolls those lines into view.\n\t */\n\tprivate preloadNextPages(viewport: ViewportRange): void {\n\t\tconst targets = this.pageManager.getPreloadTargets(viewport, this.doc);\n\t\tif (targets.length === 0) return;\n\n\t\t// Lazy-init worker if needed\n\t\tif (!this.compilationWorker) {\n\t\t\tthis.compilationWorker = new CompilationWorkerManager();\n\t\t}\n\n\t\t// Fire-and-forget: worker compiles, stores bytecode on response\n\t\tthis.compilationWorker.compileBatch(targets).then((results) => {\n\t\t\tthis.compilationWorker!.storeResults(results, this.doc);\n\t\t}).catch((_err) => {\n\t\t\t// Non-fatal, next evaluate() will compile synchronously\n\t\t});\n\t}\n\n\t/**\n\t * Collect invisible dirty lines that need background compilation.\n\t *\n\t * Iterates lines beyond `viewport.endLine`, filtering for:\n\t * - Dirty lines (need re-compilation)\n\t * - Non-empty, non-markdown lines\n\t * - No existing bytecode (skip already-compiled Tier 3 lines)\n\t *\n\t * Returns CompileRequestItem[] suitable for CompilationWorkerManager.\n\t */\n\tprivate collectInvisibleCompileTargets(viewport: ViewportRange): CompileRequestItem[] {\n\t\tconst items: CompileRequestItem[] = [];\n\t\tconst docEnd = this.doc.lineCount;\n\t\tconst startPos = viewport.endLine + 1;\n\n\t\tfor (let pos = startPos; pos <= docEnd; pos++) {\n\t\t\tconst state = this.doc.getLineAt(pos);\n\t\t\tif (!state) continue;\n\n\t\t\t// Skip clean lines\n\t\t\tif (!state.dirty) continue;\n\n\t\t\t// Skip already-compiled lines\n\t\t\tif (state.bytecodes.length > 0 && !state.isVariableDef) continue;\n\n\t\t\t// Skip empty/markdown-only lines\n\t\t\tif (state.isEmpty || isEmptyLine(state.text)) continue;\n\n\t\t\tconst { expressions } = this.extractExpressions(state);\n\t\t\tif (expressions.length === 0) continue;\n\n\t\t\t// Create one CompileRequestItem per expression (inline solves\n\t\t\t// on the same line share the same lineId + textHash). The worker\n\t\t\t// compiles each independently; storeResults batches by lineId.\n\t\t\tfor (const expression of expressions) {\n\t\t\t\tif (!expression.trim()) continue;\n\t\t\t\titems.push({\n\t\t\t\t\tlineId: state.lineId,\n\t\t\t\t\texpression,\n\t\t\t\t\ttextHash: state.textHash,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn items;\n\t}\n\n\t/**\n\t * Extract all evaluable expressions from a LineState.\n\t *\n\t * For full-line expressions: returns `{ expressions: [trimmedText], inlineSolveCount: 0 }`.\n\t * For inline solve lines: returns `{ expressions: [...allSolves], inlineSolveCount: N }`.\n\t * For pre-extracted (cached) expressions: returns the cached array.\n\t *\n\t * Inline solves are extracted left-to-right via the sharedLexer, so variable\n\t * definitions in earlier solves (e.g., `s\\`x = 5\\` more text s\\`x + 1\\``)\n\t * correctly update the VM state before later solves are evaluated.\n\t */\n\tprivate extractExpressions(state: LineState): { expressions: string[]; inlineSolveCount: number } {\n\t\t// Use pre-extracted expressions if available (from cache / previous evaluation)\n\t\tif (state.expressions.length > 0) {\n\t\t\treturn { expressions: state.expressions, inlineSolveCount: state.inlineSolveCount };\n\t\t}\n\n\t\tconst trimmed = state.text.trim();\n\t\tif (trimmed.length === 0) return { expressions: [], inlineSolveCount: 0 };\n\n\t\t// Check for inline solve syntax: s`expression`\n\t\tconst inlineSpans = sharedLexer.findInlineSolves(state.text);\n\t\tif (inlineSpans.length > 0) {\n\t\t\treturn {\n\t\t\t\texpressions: inlineSpans.map(s => s.expression),\n\t\t\t\tinlineSolveCount: inlineSpans.length,\n\t\t\t};\n\t\t}\n\n\t\t// Full-line expression\n\t\treturn { expressions: [trimmed], inlineSolveCount: 0 };\n\t}\n}\n","/**\n * Whole-document evaluation through the incremental engine.\n *\n * The engine has two ways to read a document, and they are not interchangeable.\n * {@link ExpressionEngine.parseDocument} is the light batch pass: it scans the\n * text, reads earlier lines' results, and skips markdown, which is everything\n * line references, category tags and table columns need. What it has no way to\n * do is re-run an earlier line with a variable bound to a trial value, which is\n * exactly what goal seek (`solve line N for x = target`) is, so goal seek comes\n * back as a `GOAL_SEEK_NO_DOCUMENT` error through `parseDocument`.\n *\n * The re-run primitive lives on the incremental `DocumentModel` +\n * `ThreeTierEvaluator` path (a live editor drives it on every keystroke). This\n * helper stands that path up for a single pass and hands back the familiar\n * {@link ParsingResult}, so a caller reads the answers exactly as it would from\n * `parseDocument`, goal seek included. A documentation notepad that wants goal\n * seek to resolve, and the tests that prove those examples, both go through\n * here.\n *\n * Two boundaries, each deliberate:\n *\n * - It builds a fresh model and evaluator per call and disposes the evaluator\n * before returning, which suits occasional evaluation, not the keystroke loop\n * a real editor runs against one long-lived `ThreeTierEvaluator`.\n * - Unlike `parseDocument`, it does not classify a markdown table's own rows as\n * skippable: they reach the evaluator as expressions and error. A document\n * that mixes a raw table with goal seek is the one case that wants both paths,\n * the table read through `parseDocument` and the goal seek through here.\n */\nimport type { ExpressionEngine } from \"@solve-js/engine/ExpressionEngine\";\nimport { DocumentModel } from \"@solve-js/engine/DocumentModel\";\nimport { ThreeTierEvaluator } from \"@solve-js/engine/ThreeTierEvaluator\";\nimport { findInlineSolvesInLine } from \"@solve-js/engine/ExpressionEngineSafety\";\nimport { Value, ValueType } from \"@solve-js/vm/Value\";\nimport type {\n\tParsedLine,\n\tParsingResult,\n\tUnifiedParsingOptions,\n\tInlineSolvePosition,\n} from \"@solve-js/types/ParsingResult\";\n\n/** Read the human-readable message off an error Value (`unit` holds it, `value` holds the code). */\nfunction errorMessageOf(value: Value): string {\n\treturn typeof value.unit === \"string\" ? value.unit : String(value.value);\n}\n\n/**\n * Evaluate a whole document with full cross-line context, including the line\n * re-runs goal seek needs, and return per-line results in the same shape\n * {@link ExpressionEngine.parseDocument} produces.\n *\n * @param engine - The engine to borrow for the pass. Its current document model\n * (if any) is restored before returning.\n * @param input - The document text, newline-separated.\n * @param _options - Accepted so a call reads the same as `parseDocument`'s, but\n * not consulted: the incremental pass reads the document as markdown regardless.\n */\nexport function evaluateDocument(\n\tengine: ExpressionEngine,\n\tinput: string,\n\t_options: UnifiedParsingOptions = { inputType: \"markdown\" },\n): ParsingResult {\n\tconst previousDocumentModel = engine.getDocumentModel();\n\n\tconst doc = new DocumentModel();\n\tdoc.setDocument(input);\n\t// The constructor wires the model onto the engine (engine.setDocumentModel),\n\t// which is what makeLineContext reads to expose the re-run primitive.\n\tconst evaluator = new ThreeTierEvaluator(doc, engine);\n\n\ttry {\n\t\tconst lineCount = doc.lineCount;\n\t\tevaluator.evaluate({ startLine: 1, endLine: lineCount });\n\n\t\tconst lines: ParsedLine[] = [];\n\t\tconst errors: string[] = [];\n\t\t// Document character offsets are not carried on the line model, so they\n\t\t// are accumulated here to keep startPosition/endPosition faithful to\n\t\t// parseDocument's, one newline between lines.\n\t\tlet offset = 0;\n\n\t\tfor (let n = 1; n <= lineCount; n++) {\n\t\t\tconst state = doc.getLineAt(n)!;\n\t\t\tconst text = state.text;\n\t\t\tconst startPosition = offset;\n\t\t\tconst endPosition = offset + text.length;\n\t\t\toffset = endPosition + 1; // + the newline that separated this line from the next\n\n\t\t\tconst hasInlineSolves = state.inlineSolveCount > 0;\n\t\t\tlet inlineSolves: InlineSolvePosition[] = [];\n\t\t\tlet expression: string | null = null;\n\t\t\tlet result: Value | null = null;\n\n\t\t\tif (state.isEmpty) {\n\t\t\t\t// Prose, a heading, or a blank line: nothing to report.\n\t\t\t} else if (hasInlineSolves) {\n\t\t\t\t// Zip the located spans against the line's per-expression results,\n\t\t\t\t// which the model holds in the same left-to-right order.\n\t\t\t\tinlineSolves = findInlineSolvesInLine(text, n).map((span, i) => {\n\t\t\t\t\tconst value = state.results[i]?.[0] ?? null;\n\t\t\t\t\tif (value && value.type === ValueType.Error) {\n\t\t\t\t\t\tconst message = errorMessageOf(value);\n\t\t\t\t\t\terrors.push(`Line ${n}: ${message}`);\n\t\t\t\t\t\treturn { ...span, result: null, error: message };\n\t\t\t\t\t}\n\t\t\t\t\treturn { ...span, result: value, error: null };\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\texpression = state.expressions[0] ?? null;\n\t\t\t\t// A returned error (goal seek with no document, a faulted\n\t\t\t\t// conversion) stays in `result` as an error-typed Value, exactly\n\t\t\t\t// as parseDocument leaves it, so both document passes report a\n\t\t\t\t// line the same way and a caller can compare them value for\n\t\t\t\t// value. It is also gathered into `errors` for a flat list.\n\t\t\t\tresult = state.result ?? null;\n\t\t\t\tif (result && result.type === ValueType.Error) {\n\t\t\t\t\terrors.push(`Line ${n}: ${errorMessageOf(result)}`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlines.push({\n\t\t\t\tlineNumber: n,\n\t\t\t\ttext,\n\t\t\t\tstartPosition,\n\t\t\t\tendPosition,\n\t\t\t\tisEmpty: state.isEmpty,\n\t\t\t\thasInlineSolves,\n\t\t\t\tinlineSolves,\n\t\t\t\texpression,\n\t\t\t\t// Always null: the incremental pass stores a line's failure as an\n\t\t\t\t// error-typed Value in `result` (above), never as a thrown error\n\t\t\t\t// the way parseDocument sets this field. Kept for shape parity.\n\t\t\t\terror: null,\n\t\t\t\tresult,\n\t\t\t});\n\t\t}\n\n\t\treturn { lines, totalLines: lineCount, errors };\n\t} finally {\n\t\t// Drop this pass's evaluator (unsubscribes it from the shared global\n\t\t// store) and put back whatever document the host had wired, so borrowing\n\t\t// the engine for one pass leaves nothing behind.\n\t\tevaluator.terminateWorker();\n\t\tengine.setDocumentModel(previousDocumentModel);\n\t}\n}\n"]}