foottrace 0.0.0-stage → 1.0.1

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 (196) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +73 -2
  3. package/dist/esm/index.d.ts +27 -0
  4. package/dist/esm/index.js +12 -0
  5. package/dist/esm/lib/capture/freeze.d.ts +91 -0
  6. package/dist/esm/lib/capture/freeze.js +313 -0
  7. package/dist/esm/lib/capture/ownData.d.ts +18 -0
  8. package/dist/esm/lib/capture/ownData.js +35 -0
  9. package/dist/esm/lib/capture/valueKinds.d.ts +57 -0
  10. package/dist/esm/lib/capture/valueKinds.js +141 -0
  11. package/dist/esm/lib/ids/runtimeStageId.d.ts +173 -0
  12. package/dist/esm/lib/ids/runtimeStageId.js +193 -0
  13. package/dist/esm/lib/memory/EventLog.d.ts +105 -0
  14. package/dist/esm/lib/memory/EventLog.js +147 -0
  15. package/dist/esm/lib/memory/RecordFrame.d.ts +232 -0
  16. package/dist/esm/lib/memory/RecordFrame.js +295 -0
  17. package/dist/esm/lib/memory/SharedMemory.d.ts +46 -0
  18. package/dist/esm/lib/memory/SharedMemory.js +87 -0
  19. package/dist/esm/lib/memory/TransactionBuffer.d.ts +521 -0
  20. package/dist/esm/lib/memory/TransactionBuffer.js +946 -0
  21. package/dist/esm/lib/memory/admission.d.ts +81 -0
  22. package/dist/esm/lib/memory/admission.js +152 -0
  23. package/dist/esm/lib/memory/backtrack.d.ts +292 -0
  24. package/dist/esm/lib/memory/backtrack.js +466 -0
  25. package/dist/esm/lib/memory/commitLogUtils.d.ts +217 -0
  26. package/dist/esm/lib/memory/commitLogUtils.js +383 -0
  27. package/dist/esm/lib/memory/deltaEncoding.d.ts +66 -0
  28. package/dist/esm/lib/memory/deltaEncoding.js +121 -0
  29. package/dist/esm/lib/memory/equality.d.ts +93 -0
  30. package/dist/esm/lib/memory/equality.js +261 -0
  31. package/dist/esm/lib/memory/eventPosition.d.ts +18 -0
  32. package/dist/esm/lib/memory/eventPosition.js +1 -0
  33. package/dist/esm/lib/memory/honesty.d.ts +93 -0
  34. package/dist/esm/lib/memory/honesty.js +91 -0
  35. package/dist/esm/lib/memory/keyPaths.d.ts +125 -0
  36. package/dist/esm/lib/memory/keyPaths.js +226 -0
  37. package/dist/esm/lib/memory/logModel.d.ts +76 -0
  38. package/dist/esm/lib/memory/logModel.js +363 -0
  39. package/dist/esm/lib/memory/merge.d.ts +26 -0
  40. package/dist/esm/lib/memory/merge.js +51 -0
  41. package/dist/esm/lib/memory/pathOps.d.ts +118 -0
  42. package/dist/esm/lib/memory/pathOps.js +292 -0
  43. package/dist/esm/lib/memory/paths.d.ts +56 -0
  44. package/dist/esm/lib/memory/paths.js +60 -0
  45. package/dist/esm/lib/memory/placeholders.d.ts +39 -0
  46. package/dist/esm/lib/memory/placeholders.js +39 -0
  47. package/dist/esm/lib/memory/recordCommit.d.ts +45 -0
  48. package/dist/esm/lib/memory/recordCommit.js +60 -0
  49. package/dist/esm/lib/memory/scrub.d.ts +52 -0
  50. package/dist/esm/lib/memory/scrub.js +72 -0
  51. package/dist/esm/lib/memory/types.d.ts +209 -0
  52. package/dist/esm/lib/memory/types.js +9 -0
  53. package/dist/esm/lib/memory/utils.d.ts +73 -0
  54. package/dist/esm/lib/memory/utils.js +150 -0
  55. package/dist/esm/lib/memory/verbs.d.ts +333 -0
  56. package/dist/esm/lib/memory/verbs.js +426 -0
  57. package/dist/esm/lib/recorder/CommitRangeIndex.d.ts +147 -0
  58. package/dist/esm/lib/recorder/CommitRangeIndex.js +206 -0
  59. package/dist/esm/lib/slice/elementProvenance.d.ts +81 -0
  60. package/dist/esm/lib/slice/elementProvenance.js +189 -0
  61. package/dist/esm/lib/slice/forwardSliceForKey.d.ts +88 -0
  62. package/dist/esm/lib/slice/forwardSliceForKey.js +242 -0
  63. package/dist/esm/lib/slice/index.d.ts +26 -0
  64. package/dist/esm/lib/slice/index.js +25 -0
  65. package/dist/esm/lib/slice/keyIndex.d.ts +137 -0
  66. package/dist/esm/lib/slice/keyIndex.js +292 -0
  67. package/dist/esm/lib/slice/keyTimeline.d.ts +49 -0
  68. package/dist/esm/lib/slice/keyTimeline.js +112 -0
  69. package/dist/esm/lib/slice/keysReadSources.d.ts +51 -0
  70. package/dist/esm/lib/slice/keysReadSources.js +94 -0
  71. package/dist/esm/lib/slice/serialize.d.ts +78 -0
  72. package/dist/esm/lib/slice/serialize.js +277 -0
  73. package/dist/esm/lib/slice/sliceForKey.d.ts +40 -0
  74. package/dist/esm/lib/slice/sliceForKey.js +80 -0
  75. package/dist/esm/lib/slice/types.d.ts +567 -0
  76. package/dist/esm/lib/slice/types.js +24 -0
  77. package/dist/esm/lib/time-travel/axis.d.ts +119 -0
  78. package/dist/esm/lib/time-travel/axis.js +178 -0
  79. package/dist/esm/lib/time-travel/bundles.d.ts +77 -0
  80. package/dist/esm/lib/time-travel/bundles.js +135 -0
  81. package/dist/esm/lib/time-travel/chain.d.ts +93 -0
  82. package/dist/esm/lib/time-travel/chain.js +187 -0
  83. package/dist/esm/lib/time-travel/commitStops.d.ts +55 -0
  84. package/dist/esm/lib/time-travel/commitStops.js +201 -0
  85. package/dist/esm/lib/time-travel/index.d.ts +22 -0
  86. package/dist/esm/lib/time-travel/index.js +20 -0
  87. package/dist/esm/lib/time-travel/stateAt.d.ts +102 -0
  88. package/dist/esm/lib/time-travel/stateAt.js +152 -0
  89. package/dist/esm/lib/time-travel/tagStops.d.ts +72 -0
  90. package/dist/esm/lib/time-travel/tagStops.js +101 -0
  91. package/dist/esm/lib/time-travel/timeTravel.d.ts +70 -0
  92. package/dist/esm/lib/time-travel/timeTravel.js +359 -0
  93. package/dist/esm/lib/time-travel/types.d.ts +470 -0
  94. package/dist/esm/lib/time-travel/types.js +22 -0
  95. package/dist/esm/package.json +1 -0
  96. package/dist/esm/paths.d.ts +4 -0
  97. package/dist/esm/paths.js +4 -0
  98. package/dist/esm/write.d.ts +49 -0
  99. package/dist/esm/write.js +47 -0
  100. package/dist/index.js +67 -0
  101. package/dist/lib/capture/freeze.js +319 -0
  102. package/dist/lib/capture/ownData.js +40 -0
  103. package/dist/lib/capture/valueKinds.js +145 -0
  104. package/dist/lib/ids/runtimeStageId.js +209 -0
  105. package/dist/lib/memory/EventLog.js +151 -0
  106. package/dist/lib/memory/RecordFrame.js +299 -0
  107. package/dist/lib/memory/SharedMemory.js +91 -0
  108. package/dist/lib/memory/TransactionBuffer.js +950 -0
  109. package/dist/lib/memory/admission.js +158 -0
  110. package/dist/lib/memory/backtrack.js +473 -0
  111. package/dist/lib/memory/commitLogUtils.js +398 -0
  112. package/dist/lib/memory/deltaEncoding.js +127 -0
  113. package/dist/lib/memory/equality.js +265 -0
  114. package/dist/lib/memory/eventPosition.js +2 -0
  115. package/dist/lib/memory/honesty.js +94 -0
  116. package/dist/lib/memory/keyPaths.js +242 -0
  117. package/dist/lib/memory/logModel.js +371 -0
  118. package/dist/lib/memory/merge.js +55 -0
  119. package/dist/lib/memory/pathOps.js +308 -0
  120. package/dist/lib/memory/paths.js +66 -0
  121. package/dist/lib/memory/placeholders.js +42 -0
  122. package/dist/lib/memory/recordCommit.js +64 -0
  123. package/dist/lib/memory/scrub.js +77 -0
  124. package/dist/lib/memory/types.js +10 -0
  125. package/dist/lib/memory/utils.js +169 -0
  126. package/dist/lib/memory/verbs.js +443 -0
  127. package/dist/lib/recorder/CommitRangeIndex.js +210 -0
  128. package/dist/lib/slice/elementProvenance.js +194 -0
  129. package/dist/lib/slice/forwardSliceForKey.js +246 -0
  130. package/dist/lib/slice/index.js +42 -0
  131. package/dist/lib/slice/keyIndex.js +312 -0
  132. package/dist/lib/slice/keyTimeline.js +116 -0
  133. package/dist/lib/slice/keysReadSources.js +100 -0
  134. package/dist/lib/slice/serialize.js +285 -0
  135. package/dist/lib/slice/sliceForKey.js +84 -0
  136. package/dist/lib/slice/types.js +25 -0
  137. package/dist/lib/time-travel/axis.js +183 -0
  138. package/dist/lib/time-travel/bundles.js +143 -0
  139. package/dist/lib/time-travel/chain.js +192 -0
  140. package/dist/lib/time-travel/commitStops.js +205 -0
  141. package/dist/lib/time-travel/index.js +31 -0
  142. package/dist/lib/time-travel/stateAt.js +159 -0
  143. package/dist/lib/time-travel/tagStops.js +105 -0
  144. package/dist/lib/time-travel/timeTravel.js +363 -0
  145. package/dist/lib/time-travel/types.js +23 -0
  146. package/dist/paths.js +14 -0
  147. package/dist/types/index.d.ts +27 -0
  148. package/dist/types/lib/capture/freeze.d.ts +91 -0
  149. package/dist/types/lib/capture/ownData.d.ts +18 -0
  150. package/dist/types/lib/capture/valueKinds.d.ts +57 -0
  151. package/dist/types/lib/ids/runtimeStageId.d.ts +173 -0
  152. package/dist/types/lib/memory/EventLog.d.ts +105 -0
  153. package/dist/types/lib/memory/RecordFrame.d.ts +232 -0
  154. package/dist/types/lib/memory/SharedMemory.d.ts +46 -0
  155. package/dist/types/lib/memory/TransactionBuffer.d.ts +521 -0
  156. package/dist/types/lib/memory/admission.d.ts +81 -0
  157. package/dist/types/lib/memory/backtrack.d.ts +292 -0
  158. package/dist/types/lib/memory/commitLogUtils.d.ts +217 -0
  159. package/dist/types/lib/memory/deltaEncoding.d.ts +66 -0
  160. package/dist/types/lib/memory/equality.d.ts +93 -0
  161. package/dist/types/lib/memory/eventPosition.d.ts +18 -0
  162. package/dist/types/lib/memory/honesty.d.ts +93 -0
  163. package/dist/types/lib/memory/keyPaths.d.ts +125 -0
  164. package/dist/types/lib/memory/logModel.d.ts +76 -0
  165. package/dist/types/lib/memory/merge.d.ts +26 -0
  166. package/dist/types/lib/memory/pathOps.d.ts +118 -0
  167. package/dist/types/lib/memory/paths.d.ts +56 -0
  168. package/dist/types/lib/memory/placeholders.d.ts +39 -0
  169. package/dist/types/lib/memory/recordCommit.d.ts +45 -0
  170. package/dist/types/lib/memory/scrub.d.ts +52 -0
  171. package/dist/types/lib/memory/types.d.ts +209 -0
  172. package/dist/types/lib/memory/utils.d.ts +73 -0
  173. package/dist/types/lib/memory/verbs.d.ts +333 -0
  174. package/dist/types/lib/recorder/CommitRangeIndex.d.ts +147 -0
  175. package/dist/types/lib/slice/elementProvenance.d.ts +81 -0
  176. package/dist/types/lib/slice/forwardSliceForKey.d.ts +88 -0
  177. package/dist/types/lib/slice/index.d.ts +26 -0
  178. package/dist/types/lib/slice/keyIndex.d.ts +137 -0
  179. package/dist/types/lib/slice/keyTimeline.d.ts +49 -0
  180. package/dist/types/lib/slice/keysReadSources.d.ts +51 -0
  181. package/dist/types/lib/slice/serialize.d.ts +78 -0
  182. package/dist/types/lib/slice/sliceForKey.d.ts +40 -0
  183. package/dist/types/lib/slice/types.d.ts +567 -0
  184. package/dist/types/lib/time-travel/axis.d.ts +119 -0
  185. package/dist/types/lib/time-travel/bundles.d.ts +77 -0
  186. package/dist/types/lib/time-travel/chain.d.ts +93 -0
  187. package/dist/types/lib/time-travel/commitStops.d.ts +55 -0
  188. package/dist/types/lib/time-travel/index.d.ts +22 -0
  189. package/dist/types/lib/time-travel/stateAt.d.ts +102 -0
  190. package/dist/types/lib/time-travel/tagStops.d.ts +72 -0
  191. package/dist/types/lib/time-travel/timeTravel.d.ts +70 -0
  192. package/dist/types/lib/time-travel/types.d.ts +470 -0
  193. package/dist/types/paths.d.ts +4 -0
  194. package/dist/types/write.d.ts +49 -0
  195. package/dist/write.js +56 -0
  196. package/package.json +48 -4
@@ -0,0 +1,466 @@
1
+ /**
2
+ * backtrack.ts — Backward causal chain analysis on the commit log.
3
+ *
4
+ * Implements **backward program slicing** (Weiser 1984, thin-slice variant):
5
+ * given a starting execution step, walk backwards through read→write
6
+ * dependencies to build the causal DAG that produced the data at that step.
7
+ *
8
+ * ## Algorithm
9
+ *
10
+ * BFS on the implicit dependency graph where edges run from reader → writer.
11
+ *
12
+ * 1. Locate startId in commitLog → root node
13
+ * 2. Get keysRead for root via `getKeysRead` callback
14
+ * 3. For each key read, find who last wrote it before this step → parent commit
15
+ * ("wrote" is the writer rule of `keyPaths.ts`, 9.33.0: a row on the key, inside it, or
16
+ * around it that changed it — so a stage that read `cfg` links to the subflow seed or
17
+ * merge-back that wrote `cfg␟b`)
18
+ * 4. Create parent CausalNode, link to root.parents
19
+ * 5. Enqueue parent. Repeat until queue empty or limits hit.
20
+ *
21
+ * Output is a **DAG** (not a linked list): a stage reading `creditScore` AND `dti`
22
+ * from different writers has two parents.
23
+ *
24
+ * ## Staged Optimization
25
+ *
26
+ * Two writer-lookup strategies, chosen automatically by commit log size:
27
+ *
28
+ * | Strategy | When | Complexity per lookup |
29
+ * |----------|------|----------------------|
30
+ * | Linear scan | N ≤ 256 | O(N) — simple backward scan |
31
+ * | Reverse index | N > 256 | O(K log N) — prebuilt key→[indices], binary search |
32
+ *
33
+ * The threshold (256) is chosen so the O(N) build cost of the reverse index
34
+ * is amortized over the BFS traversal. Below 256, linear scan wins because
35
+ * there's no index build overhead. The consumer never sees this — `causalChain()`
36
+ * picks the right strategy internally (like a query optimizer choosing between
37
+ * sequential scan vs index scan based on table size).
38
+ *
39
+ * ## Complexity
40
+ *
41
+ * - **Small logs (N ≤ 256):** O(V × K × N) total. V=visited, K=avg keys/node.
42
+ * - **Large logs (N > 256):** O(N × U) index build + O(V × K × log N) lookups.
43
+ * U = unique keys. Amortized over all BFS hops.
44
+ *
45
+ * ## References
46
+ *
47
+ * - Weiser, M. (1984). "Program Slicing." IEEE TSE.
48
+ * - Sridharan, M. et al. (2007). "Thin Slicing." PLDI.
49
+ *
50
+ * @example
51
+ * ```typescript
52
+ * import { causalChain, flattenCausalDAG, formatCausalChain } from 'foottrace';
53
+ *
54
+ * const dag = causalChain(commitLog, 'decide#2', (id) => recorder.getKeysRead(id));
55
+ * const flat = flattenCausalDAG(dag); // BFS-ordered flat list
56
+ * console.log(formatCausalChain(dag)); // human-readable
57
+ * ```
58
+ */
59
+ import { buildCommitIndex, findLastWriter } from './commitLogUtils.js';
60
+ import { queryWork, relation, writesOnlyInside } from './keyPaths.js';
61
+ import { logModel } from './logModel.js';
62
+ // ── Staged optimization: writer lookup strategies ──────────────────────
63
+ /**
64
+ * Threshold for switching from linear scan to reverse index.
65
+ * Below this, O(N) scan is faster (no index build cost).
66
+ * Above this, O(log N) binary search wins.
67
+ */
68
+ const REVERSE_INDEX_THRESHOLD = 256;
69
+ /** Strategy 1: Linear scan — O(N) per lookup, zero setup cost. */
70
+ function linearScanLookup(commitLog) {
71
+ return (key, beforeIdx) => findLastWriter(commitLog, key, beforeIdx);
72
+ }
73
+ /**
74
+ * Strategy 2: Reverse index — one O(rows) build, O(depth + log N) per lookup.
75
+ * The log's read model (`logModel.ts`: a path trie, each top-level key folded at
76
+ * most once) answers the writer rule — rows on, inside or around the key — by
77
+ * binary search for the last write on or inside it, then a verdict only for the
78
+ * around-candidates after it. The same answer `findLastWriter` gives, so the
79
+ * strategy switch below never changes a slice.
80
+ */
81
+ function reverseIndexLookup(commitLog) {
82
+ const model = logModel(commitLog);
83
+ return (key, beforeIdx) => {
84
+ const at = model.lastWriterBefore(key, beforeIdx);
85
+ return at >= 0 ? commitLog[at] : undefined;
86
+ };
87
+ }
88
+ /**
89
+ * The trace entries of `commit` that make it a writer of `linkKey` — the entries whose read
90
+ * prefix (`TraceEntry.readKeys`) a per-write edge expands through. The FIRST entry on the exact
91
+ * path when there is one (the #P1 behaviour, unchanged); otherwise every entry inside or around
92
+ * the key (9.33.0: the commit wrote the key through a nested row — a subflow seed, an
93
+ * outputMapper merge-back — and all of those rows wrote it).
94
+ */
95
+ function linkingEntries(commit, linkKey) {
96
+ const exact = commit.trace.find((t) => t.path === linkKey);
97
+ if (exact !== undefined)
98
+ return [exact];
99
+ return commit.trace.filter((t) => relation(t.path, linkKey) !== undefined);
100
+ }
101
+ /**
102
+ * Staged optimization: pick the right writer-lookup strategy based on data size.
103
+ *
104
+ * Like a database query optimizer choosing between sequential scan and index scan:
105
+ *
106
+ * - **Small log (≤ 256):** Linear scan wins. Zero setup cost, good cache locality.
107
+ * The overhead of building a reverse index isn't worth it for short logs.
108
+ *
109
+ * - **Large log (> 256):** Reverse index wins. O(N×U) upfront build cost is amortized
110
+ * across all BFS hops. Each lookup becomes O(log N) via binary search instead of O(N).
111
+ * For an agent loop with 500 iterations and 5 keys per hop, this is 500×5×log(500)≈22K ops
112
+ * vs 500×5×500=1.25M ops with linear scan.
113
+ *
114
+ * The caller never sees this — `causalChain()` picks automatically.
115
+ */
116
+ function createWriterLookup(commitLog) {
117
+ if (commitLog.length <= REVERSE_INDEX_THRESHOLD) {
118
+ return linearScanLookup(commitLog);
119
+ }
120
+ return reverseIndexLookup(commitLog);
121
+ }
122
+ // ── Core algorithm ─────────────────────────────────────────────────────
123
+ /**
124
+ * RFC-003 D2: the `incompleteSources` node fragment for a commit — `{}`
125
+ * when the stage consumed no untracked read paths, keeping the field
126
+ * ABSENT (not empty-array-valued) for fully-tracked stages.
127
+ */
128
+ function incompleteSourcesFragment(commit) {
129
+ if (!commit.untrackedSources || commit.untrackedSources.length === 0)
130
+ return {};
131
+ return { incompleteSources: commit.untrackedSources };
132
+ }
133
+ /**
134
+ * Build the causal DAG rooted at `startId` by walking backwards
135
+ * through read→write dependencies in the commit log.
136
+ *
137
+ * Automatically selects the optimal writer lookup strategy:
138
+ * - Linear scan for small logs (≤ 256 commits)
139
+ * - Reverse index with binary search for large logs (> 256 commits)
140
+ *
141
+ * Produces a DAG (not a tree): if two children both read from the same
142
+ * parent, the parent node is shared (deduped by runtimeStageId).
143
+ *
144
+ * @param commitLog Ordered commit bundles from executor.getSnapshot().commitLog
145
+ * @param startId runtimeStageId to start backtracking from
146
+ * @param getKeysRead Callback returning keys read by a given execution step
147
+ * @param options Depth and node limits
148
+ * @returns Root CausalNode with .parents forming the DAG, or undefined if startId not found
149
+ */
150
+ export function causalChain(commitLog, startId, getKeysRead, options) {
151
+ return buildCausalChain(commitLog, startId, getKeysRead, options);
152
+ }
153
+ /**
154
+ * Internal slice composition: keep the actual bundle selected by the writer
155
+ * query (including a nonempty continuation). This is not a public entry point.
156
+ * The read position still belongs to the execution's first commit.
157
+ */
158
+ export function causalChainFromCommit(commitLog, writer, getKeysRead, options) {
159
+ return buildCausalChain(commitLog, writer.runtimeStageId, getKeysRead, options, writer);
160
+ }
161
+ function buildCausalChain(commitLog, startId, getKeysRead, options, selectedWriter) {
162
+ const maxDepth = options?.maxDepth ?? 20;
163
+ const maxNodes = options?.maxNodes ?? 100;
164
+ const controlDeps = options?.controlDeps;
165
+ const weigh = options?.weigh;
166
+ const perWrite = options?.edgeAttribution === 'per-write';
167
+ // RFC-003 D4 — truncation visibility. Set only when a limit actually
168
+ // cuts the slice; surfaced on the root as `truncated` so a consumer can
169
+ // never mistake a truncated slice for a complete one.
170
+ let truncatedByDepth = false;
171
+ let truncatedByNodes = false;
172
+ // A continuation may write more data, but it is not another execution of
173
+ // the stage's reads. Use the shared FIRST-commit rule for every read cutoff;
174
+ // keep writer bundles separately for their write metadata and read prefixes.
175
+ const idxMap = buildCommitIndex(commitLog);
176
+ queryWork.units += commitLog.length;
177
+ const startIdx = idxMap.get(startId);
178
+ if (startIdx === undefined)
179
+ return undefined;
180
+ const startCommit = selectedWriter ?? commitLog[startIdx];
181
+ // Pick writer lookup strategy based on log size
182
+ const findWriter = createWriterLookup(commitLog);
183
+ // Node dedup map: runtimeStageId → CausalNode (ensures DAG, not tree)
184
+ const nodeMap = new Map();
185
+ const root = {
186
+ runtimeStageId: startId,
187
+ stageId: startCommit.stageId,
188
+ stageName: startCommit.stage,
189
+ keysWritten: startCommit.trace.map((t) => t.path),
190
+ linkedBy: '',
191
+ depth: 0,
192
+ parents: [],
193
+ parentEdges: [],
194
+ ...incompleteSourcesFragment(startCommit),
195
+ };
196
+ nodeMap.set(startId, root);
197
+ // ── #P1 per-write attribution machinery (inert under 'stage') ──────────
198
+ // expandedReads: per node, the reads already queued for expansion — late
199
+ // links via additional keys re-enqueue only the DELTA, so the slice grows
200
+ // monotonically toward the stage-level ceiling and terminates (each key
201
+ // expands at most once per node). fullyExpanded: nodes that fell back to
202
+ // stage level (no readKeys on a linking entry) — nothing left to add.
203
+ const expandedReads = new Map();
204
+ const fullyExpanded = new Set();
205
+ /**
206
+ * Resolve a node's expansion read-set for the given linking WRITTEN keys.
207
+ * Per-write mode with provenance present → union of the linking writes'
208
+ * temporal-prefix `readKeys`. Any linking entry WITHOUT `readKeys` (or no
209
+ * linkKeys at all) → honest stage-level fallback, flagged via the second
210
+ * tuple member so the caller marks the node fully expanded.
211
+ */
212
+ function readsForLinks(commit, linkKeys) {
213
+ if (!perWrite || !linkKeys || linkKeys.length === 0) {
214
+ return [getKeysRead(commit.runtimeStageId), true];
215
+ }
216
+ const union = new Set();
217
+ for (const linkKey of linkKeys) {
218
+ const entries = linkingEntries(commit, linkKey);
219
+ if (entries.length === 0 || entries.some((e) => e.readKeys === undefined)) {
220
+ // Mixed/dial-off log — degrade THIS node to stage level, honestly.
221
+ return [getKeysRead(commit.runtimeStageId), true];
222
+ }
223
+ for (const entry of entries)
224
+ for (const rk of entry.readKeys)
225
+ union.add(rk);
226
+ }
227
+ return [[...union], false];
228
+ }
229
+ // BFS/worklist queue: [node, commitIdx, depth, keysToExpand]
230
+ const [rootReads, rootIsFull] = perWrite
231
+ ? readsForLinks(startCommit, options?.rootLinkKeys)
232
+ : [getKeysRead(startId), true];
233
+ expandedReads.set(startId, new Set(rootReads));
234
+ if (rootIsFull)
235
+ fullyExpanded.add(startId);
236
+ const queue = [[root, startIdx, 0, rootReads]];
237
+ let visited = 1;
238
+ /**
239
+ * Link `node → parent` (creating + enqueueing the parent when new).
240
+ * Shared by data-edge expansion (read→write) and control-edge expansion
241
+ * (D3). One CausalEdge per distinct (parent, kind, key) link; `parents`
242
+ * keeps its historical one-entry-per-parent dedup.
243
+ */
244
+ function linkParent(node, parentCommit, kind, key, depth) {
245
+ const parentId = parentCommit.runtimeStageId;
246
+ // the dedup scans below, and the parent's trace when it is new — counted for the scaling test
247
+ queryWork.units += 1 + node.parents.length + node.parentEdges.length;
248
+ // #P1: the parent's expansion reads, resolved LAZILY (only for new nodes
249
+ // or per-write re-expansion — duplicate links under 'stage' pay nothing).
250
+ // Data links expand through the reads that fed the parent's write of
251
+ // `key`; control links expand the decider at stage level (a decision
252
+ // depends on everything it read).
253
+ const resolveLinkReads = () => kind === 'data'
254
+ ? readsForLinks(parentCommit, key !== undefined ? [key] : undefined)
255
+ : [getKeysRead(parentId), true];
256
+ let parentNode = nodeMap.get(parentId);
257
+ if (!parentNode) {
258
+ // New node — create and enqueue (respecting the node budget)
259
+ if (visited >= maxNodes) {
260
+ truncatedByNodes = true; // D4: a discovered parent was dropped
261
+ return;
262
+ }
263
+ const parentIdx = idxMap.get(parentId);
264
+ if (parentIdx === undefined)
265
+ return;
266
+ queryWork.units += parentCommit.trace.length;
267
+ parentNode = {
268
+ runtimeStageId: parentId,
269
+ stageId: parentCommit.stageId,
270
+ stageName: parentCommit.stage,
271
+ keysWritten: parentCommit.trace.map((t) => t.path),
272
+ // linkedBy stays a DATA-key concept (back-compat) — control-linked
273
+ // nodes carry their label on the edge instead.
274
+ linkedBy: kind === 'data' ? key ?? '' : '',
275
+ depth: depth + 1,
276
+ parents: [],
277
+ parentEdges: [],
278
+ ...incompleteSourcesFragment(parentCommit),
279
+ };
280
+ nodeMap.set(parentId, parentNode);
281
+ visited++;
282
+ const [linkReads, linkIsFull] = resolveLinkReads();
283
+ expandedReads.set(parentId, new Set(linkReads));
284
+ if (linkIsFull)
285
+ fullyExpanded.add(parentId);
286
+ queue.push([parentNode, parentIdx, depth + 1, linkReads]);
287
+ }
288
+ else if (perWrite && !fullyExpanded.has(parentId)) {
289
+ // #P1 worklist: an EXISTING node linked via another key may owe more
290
+ // expansion — enqueue only the reads not yet expanded (monotone; the
291
+ // node budget is untouched, no node is created). Re-expansion keeps
292
+ // the node's ORIGINAL depth so its parents get a consistent depth+1.
293
+ const [linkReads, linkIsFull] = resolveLinkReads();
294
+ const expanded = expandedReads.get(parentId);
295
+ const delta = linkReads.filter((k) => !expanded.has(k));
296
+ if (linkIsFull)
297
+ fullyExpanded.add(parentId);
298
+ if (delta.length > 0) {
299
+ for (const k of delta)
300
+ expanded.add(k);
301
+ const parentIdx = idxMap.get(parentId);
302
+ if (parentIdx !== undefined)
303
+ queue.push([parentNode, parentIdx, parentNode.depth, delta]);
304
+ }
305
+ }
306
+ // DAG merge: one parents[] entry per distinct parent (historical shape)
307
+ if (!node.parents.some((p) => p.runtimeStageId === parentId)) {
308
+ node.parents.push(parentNode);
309
+ }
310
+ // One edge per distinct (parent, kind, key) link. The weigher (D4)
311
+ // stamps the weight at creation; `undefined` → 1.0 — the engine never
312
+ // computes weights itself.
313
+ if (!node.parentEdges.some((e) => e.parent.runtimeStageId === parentId && e.kind === kind && e.key === key)) {
314
+ // Error isolation (review finding): a consumer weigher that throws
315
+ // must degrade to the default weight, never crash the slice — the
316
+ // same contract every other consumer callback in the library gets.
317
+ let weight = 1.0;
318
+ if (weigh) {
319
+ try {
320
+ weight = weigh(node, parentNode, key, kind) ?? 1.0;
321
+ }
322
+ catch {
323
+ /* weigher threw — keep 1.0, the slice stays usable */
324
+ }
325
+ }
326
+ const nested = kind === 'data' && key !== undefined && writesOnlyInside(parentCommit, key);
327
+ node.parentEdges.push({
328
+ parent: parentNode,
329
+ kind,
330
+ key,
331
+ weight,
332
+ ...(nested && { basis: 'nested-rows' }),
333
+ });
334
+ }
335
+ }
336
+ while (queue.length > 0) {
337
+ const [node, commitIdx, depth, keysToExpand] = queue.shift();
338
+ queryWork.units += 1 + keysToExpand.length;
339
+ if (depth >= maxDepth) {
340
+ // D4: only a node that still HAD something to expand counts as a cut
341
+ // (a leaf at the horizon truncates nothing).
342
+ if (keysToExpand.length > 0 || controlDeps?.(node.runtimeStageId) !== undefined) {
343
+ truncatedByDepth = true;
344
+ }
345
+ continue;
346
+ }
347
+ // Data edges: for each key in this expansion's read-set, find who wrote
348
+ // it. Under 'stage' this is the node's full read-set (historical
349
+ // behavior); under 'per-write' it is the linking writes' temporal prefix
350
+ // (or a worklist delta on re-expansion).
351
+ const keysRead = keysToExpand;
352
+ for (const key of keysRead) {
353
+ const writer = findWriter(key, commitIdx);
354
+ if (!writer) {
355
+ // F4b: say why there is no edge — no commit before this node wrote the key.
356
+ node.preRunReads ??= { code: 'pre-run-origin', keys: [] };
357
+ if (!node.preRunReads.keys.includes(key))
358
+ node.preRunReads.keys.push(key);
359
+ continue;
360
+ }
361
+ linkParent(node, writer, 'data', key, depth);
362
+ }
363
+ // Control edge (RFC-003 D3): link the governing decider, labeled by the
364
+ // decide() rule label when present. The decider node then expands
365
+ // normally through its own data reads (and its own control parent).
366
+ if (controlDeps) {
367
+ const dep = controlDeps(node.runtimeStageId);
368
+ if (dep) {
369
+ const deciderIdx = idxMap.get(dep.deciderId);
370
+ if (deciderIdx !== undefined) {
371
+ linkParent(node, commitLog[deciderIdx], 'control', dep.label, depth);
372
+ }
373
+ }
374
+ }
375
+ }
376
+ // RFC-003 D4 — truncation visibility on the root (absent when complete). It is DATA, and only
377
+ // data: a reader reads `root.truncated` (and `formatCausalChain` prints it); the record writes no
378
+ // console line (the dev-mode warning went in C6 — the record imports nothing outside itself).
379
+ if (truncatedByDepth || truncatedByNodes) {
380
+ root.truncated = { byDepth: truncatedByDepth, byNodes: truncatedByNodes };
381
+ }
382
+ return root;
383
+ }
384
+ // ── Utilities ──────────────────────────────────────────────────────────
385
+ /**
386
+ * Flatten the causal DAG into a BFS-ordered list of nodes.
387
+ * Each node appears exactly once (first occurrence by BFS order).
388
+ * Useful for linear display or iteration.
389
+ */
390
+ export function flattenCausalDAG(root) {
391
+ const result = [];
392
+ const visited = new Set();
393
+ const queue = [root];
394
+ while (queue.length > 0) {
395
+ const node = queue.shift();
396
+ if (visited.has(node.runtimeStageId))
397
+ continue;
398
+ visited.add(node.runtimeStageId);
399
+ result.push(node);
400
+ for (const parent of node.parents) {
401
+ if (!visited.has(parent.runtimeStageId)) {
402
+ queue.push(parent);
403
+ }
404
+ }
405
+ }
406
+ return result;
407
+ }
408
+ /**
409
+ * Format a causal DAG as human-readable indented text.
410
+ * Shows the dependency chain with depth indentation and linked-by keys.
411
+ *
412
+ * RFC-003 D2: nodes that consumed untracked read paths render an extra
413
+ * `⚠ also consumed … — slice may be incomplete here` line, so a consumer
414
+ * (human or LLM) debugging from the slice is TOLD when it is incomplete.
415
+ *
416
+ * RFC-003 D3: control edges render as `← [control: <rule label>]`
417
+ * (label omitted when the decision carried none). Data rendering is
418
+ * byte-identical to the pre-D3 output — `← via <key>` from the node's
419
+ * discovery-time `linkedBy`.
420
+ *
421
+ * RFC-003 D4: edge weights from the `weigh` hook render as a suffix —
422
+ * `← via systemPrompt (0.18)` — only when ≠ 1.0, so unweighted output is
423
+ * unchanged. A truncated slice (root.truncated) appends a final
424
+ * `⚠ slice truncated …` line.
425
+ */
426
+ export function formatCausalChain(root) {
427
+ const lines = [];
428
+ const visited = new Set();
429
+ const weightSuffix = (edge) => edge !== undefined && edge.weight !== 1 ? ` (${edge.weight})` : '';
430
+ function walk(node, indent, edgesFromChild) {
431
+ if (visited.has(node.runtimeStageId)) {
432
+ lines.push(`${' '.repeat(indent)}↳ ${node.runtimeStageId} (see above)`);
433
+ return;
434
+ }
435
+ visited.add(node.runtimeStageId);
436
+ const linkParts = [];
437
+ if (node.linkedBy) {
438
+ const dataEdge = edgesFromChild?.find((e) => e.kind === 'data');
439
+ linkParts.push(`via ${node.linkedBy}${weightSuffix(dataEdge)}`);
440
+ }
441
+ const controlEdge = edgesFromChild?.find((e) => e.kind === 'control');
442
+ if (controlEdge) {
443
+ linkParts.push(`[control${controlEdge.key ? `: ${controlEdge.key}` : ''}]${weightSuffix(controlEdge)}`);
444
+ }
445
+ const link = linkParts.length > 0 ? ` ← ${linkParts.join(' ← ')}` : '';
446
+ const writes = node.keysWritten.length > 0 ? ` [wrote: ${node.keysWritten.join(', ')}]` : '';
447
+ lines.push(`${' '.repeat(indent)}${node.stageName} (${node.runtimeStageId})${link}${writes}`);
448
+ if (node.incompleteSources && node.incompleteSources.length > 0) {
449
+ lines.push(`${' '.repeat(indent + 1)}⚠ also consumed ${node.incompleteSources.join('/')} — slice may be incomplete here`);
450
+ }
451
+ for (const parent of node.parents) {
452
+ walk(parent, indent + 1, node.parentEdges.filter((e) => e.parent === parent));
453
+ }
454
+ }
455
+ walk(root, 0);
456
+ if (root.truncated) {
457
+ const causes = [root.truncated.byDepth && 'maxDepth reached', root.truncated.byNodes && 'maxNodes reached']
458
+ .filter(Boolean)
459
+ .join(', ');
460
+ lines.push(`⚠ slice truncated (${causes}) — older causes exist beyond this horizon`);
461
+ }
462
+ return lines.join('\n');
463
+ }
464
+ // ── Exported for testing (internal) ────────────────────────────────────
465
+ /** @internal Exposed for testing the strategy selection. */
466
+ export const _REVERSE_INDEX_THRESHOLD = REVERSE_INDEX_THRESHOLD;