@iowarp/clio-coder 0.3.2 → 0.3.4

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 (259) hide show
  1. package/CHANGELOG.md +269 -458
  2. package/CONTRIBUTING.md +1 -1
  3. package/README.md +3 -3
  4. package/dist/{acp-BIYHVZIM.js → acp-S5R4RR5B.js} +7 -6
  5. package/dist/{agents-YT6SSRIT.js → agents-P6DMMVZY.js} +24 -21
  6. package/dist/assets/codewiki.json +1 -1
  7. package/dist/{auth-5TWEIYDN.js → auth-2XCZLPKS.js} +12 -8
  8. package/dist/{chunk-GGXXDWE4.js → chunk-22NAGB7X.js} +2 -2
  9. package/dist/{chunk-WMSVI4G2.js → chunk-2LZI5CAG.js} +133 -13
  10. package/dist/{chunk-OAO4GE4M.js → chunk-2TZWSW76.js} +2 -2
  11. package/dist/{chunk-OOJYHWRB.js → chunk-34475P3I.js} +2 -2
  12. package/dist/{chunk-WVO7V2QY.js → chunk-35MKKU5R.js} +4 -4
  13. package/dist/{chunk-LBNRH5WM.js → chunk-3HZ5RWN2.js} +5 -5
  14. package/dist/{chunk-AGYYIBLL.js → chunk-3JLKSKD7.js} +2 -2
  15. package/dist/{chunk-MBS4V7ZP.js → chunk-4JUF2NNX.js} +7 -7
  16. package/dist/{chunk-ZDOOVTXZ.js → chunk-4OC57DA6.js} +27 -4
  17. package/dist/chunk-5M54SPOL.js +926 -0
  18. package/dist/{chunk-STBPMHSX.js → chunk-7RXG6QRZ.js} +51 -11
  19. package/dist/{chunk-77VKQEHF.js → chunk-A2GZF7DC.js} +5 -5
  20. package/dist/{chunk-A3CYT5EX.js → chunk-AD2SYQYC.js} +55 -2
  21. package/dist/chunk-AOCYTWAV.js +449 -0
  22. package/dist/chunk-BEY543CS.js +258 -0
  23. package/dist/{chunk-6N5PTWMY.js → chunk-BP4OYD6A.js} +32 -13
  24. package/dist/chunk-BPGS2WCQ.js +612 -0
  25. package/dist/{chunk-J5HN4RYU.js → chunk-BRXQQJFP.js} +8 -8
  26. package/dist/chunk-CFGTUFWB.js +67 -0
  27. package/dist/{chunk-CBCAPZAA.js → chunk-E25LMLRW.js} +2 -2
  28. package/dist/{chunk-G2DE3C7R.js → chunk-EDRHSCIE.js} +4 -4
  29. package/dist/{chunk-4KLWL3UC.js → chunk-EFADSJET.js} +2 -2
  30. package/dist/{chunk-M6SHUN7Q.js → chunk-FO5ZOVUY.js} +2 -2
  31. package/dist/chunk-FYYLNIL5.js +313 -0
  32. package/dist/{chunk-EPVUXGXG.js → chunk-HV5X7OR2.js} +14 -12
  33. package/dist/{chunk-TZTZS7QK.js → chunk-HXG4IURW.js} +5 -3
  34. package/dist/{chunk-IGLFWIYI.js → chunk-K6WL7QZT.js} +3 -3
  35. package/dist/chunk-K7VKOLQQ.js +15 -0
  36. package/dist/{chunk-BMEMKKIT.js → chunk-KOHPCX4K.js} +2 -2
  37. package/dist/{chunk-V4RXGQ5Q.js → chunk-KRPY7NTG.js} +10 -7
  38. package/dist/chunk-LL4KHSZI.js +22 -0
  39. package/dist/{chunk-KJ5LWLOE.js → chunk-MEQ45TQ4.js} +15 -9
  40. package/dist/{chunk-5UUP6MWO.js → chunk-MV3K5QF2.js} +5 -436
  41. package/dist/{chunk-AO4RKG4M.js → chunk-N4CZJQRK.js} +5 -5
  42. package/dist/{chunk-ARBGF5F7.js → chunk-NILBFAPG.js} +14 -8
  43. package/dist/chunk-OZNBF4L3.js +23 -0
  44. package/dist/{verify-G6V4D2G7.js → chunk-PCZJO5TI.js} +127 -42
  45. package/dist/chunk-QQK64KLB.js +1360 -0
  46. package/dist/{chunk-6EJV5X2W.js → chunk-QQL5RT5M.js} +979 -1619
  47. package/dist/{chunk-LZSJBIVT.js → chunk-QWU7ZBO7.js} +70 -720
  48. package/dist/{chunk-2EHAIA3X.js → chunk-RD5U66HV.js} +3 -3
  49. package/dist/{chunk-OKGUZO2U.js → chunk-SPULKLCF.js} +4 -3
  50. package/dist/{chunk-OQ33BKR3.js → chunk-TTNYS3EA.js} +3 -60
  51. package/dist/chunk-TW3WDMVS.js +677 -0
  52. package/dist/chunk-TZSKNMZG.js +434 -0
  53. package/dist/{chunk-7MNJORFF.js → chunk-UL3WSD3F.js} +6 -1
  54. package/dist/{chunk-7EYHLWU7.js → chunk-UZHIZC5S.js} +7 -7
  55. package/dist/{chunk-QTYWRVRA.js → chunk-VAWWTKDP.js} +8 -8
  56. package/dist/{chunk-X75S7HFS.js → chunk-VEZEGCGW.js} +214 -20
  57. package/dist/{chunk-OHHN2SO4.js → chunk-VMNQ6OZA.js} +98 -202
  58. package/dist/chunk-VSNATDE6.js +122 -0
  59. package/dist/chunk-W6GROXXM.js +69 -0
  60. package/dist/chunk-WPQLXFOZ.js +375 -0
  61. package/dist/{chunk-ORBHGJC5.js → chunk-WR67VIZY.js} +3 -3
  62. package/dist/{chunk-3ZXDFGR5.js → chunk-X6COSD2O.js} +5 -5
  63. package/dist/chunk-ZGVHUX3M.js +66 -0
  64. package/dist/{chunk-MAW544W2.js → chunk-ZWMF7253.js} +4 -4
  65. package/dist/{chunk-MQSRRFWA.js → chunk-ZYKPLLNQ.js} +563 -546
  66. package/dist/cli/index.js +27 -23
  67. package/dist/{clio-4LY5K2AC.js → clio-J5JIOIDS.js} +7 -6
  68. package/dist/{code-nav-7AX6FYE6.js → code-nav-AXCXSBHX.js} +5 -3
  69. package/dist/{config-GTLUW2PR.js → config-OEBMIN2U.js} +37 -27
  70. package/dist/{configure-R6A64DHX.js → configure-PUQOSIXQ.js} +16 -13
  71. package/dist/{context-5VKGUVJJ.js → context-EKDCKUUZ.js} +82 -7
  72. package/dist/{context-RW5HC47S.js → context-MGSE4Z2T.js} +33 -23
  73. package/dist/{context-JFZEJ7W5.js → context-URSXPBCK.js} +17 -9
  74. package/dist/{context-clear-6ZHBAZZT.js → context-clear-KDAJRNUK.js} +33 -23
  75. package/dist/context-working-set-SBKMPPI2.js +1552 -0
  76. package/dist/{dispatch-runner-VKBRCWQC.js → dispatch-runner-MSWN72NK.js} +43 -29
  77. package/dist/{doctor-KI767GSN.js → doctor-7BSE27PJ.js} +10 -10
  78. package/dist/{eval-XSSNATB4.js → eval-IZGDOO4H.js} +9 -8
  79. package/dist/{evidence-UA6AWDQQ.js → evidence-SR7WXB5B.js} +51 -23
  80. package/dist/{evolve-QNTFGV6Z.js → evolve-K7VE2CBX.js} +30 -20
  81. package/dist/{fleet-Q7UOMUSG.js → fleet-7XMJNQNF.js} +48 -38
  82. package/dist/{fleet-preflight-DDN536IT.js → fleet-preflight-AQNAH644.js} +3 -3
  83. package/dist/{init-WBB65ZHQ.js → init-JGNPAYXT.js} +41 -31
  84. package/dist/{memory-MD3O64RI.js → memory-4ALKDJ4Q.js} +32 -22
  85. package/dist/{models-BZU34YWD.js → models-ZMMLFJNN.js} +22 -19
  86. package/dist/{monitor-MEQA5C3I.js → monitor-2F3T5KHP.js} +55 -43
  87. package/dist/{orchestrator-CGFKEP27.js → orchestrator-ORHT43JB.js} +2507 -1896
  88. package/dist/{reset-L2FQEE3E.js → reset-NXGTYNUO.js} +4 -3
  89. package/dist/{run-IV4Q6RLN.js → run-RF4WJGMT.js} +51 -41
  90. package/dist/{share-S5BZQC5I.js → share-UT3W6E4M.js} +5 -4
  91. package/dist/{skills-LQEKRDTN.js → skills-PSACKC5Q.js} +2 -2
  92. package/dist/{skills-eval-3DC4HEWS.js → skills-eval-WJSI55RZ.js} +34 -24
  93. package/dist/{targets-C4SSGQOB.js → targets-PIIRAOYS.js} +23 -20
  94. package/dist/{terminal-lease-IT5JW2NR.js → terminal-lease-ULWXWNVY.js} +5 -4
  95. package/dist/{upgrade-7TT7SQ3G.js → upgrade-346TZ6AV.js} +18 -17
  96. package/dist/{usage-GV4PKT3M.js → usage-6KKXR32N.js} +34 -24
  97. package/dist/verifiers-4UUM6TEE.js +1214 -0
  98. package/dist/verify-X5HDROLA.js +25 -0
  99. package/dist/{wiki-generate-DQF6Z66B.js → wiki-generate-7STOCIFZ.js} +42 -31
  100. package/dist/worker/entry.js +33 -24
  101. package/docs/README.md +8 -7
  102. package/docs/acp.md +1 -1
  103. package/docs/alcf-provider.md +1 -1
  104. package/docs/architecture.md +2 -2
  105. package/docs/artifact-versions.md +1 -1
  106. package/docs/built-in-agents.md +1 -1
  107. package/docs/capacity-and-scheduling.md +1 -1
  108. package/docs/commands-and-modes.md +53 -21
  109. package/docs/config-knobs-audit.md +1 -2
  110. package/docs/configuration-and-targets.md +15 -1
  111. package/docs/context-engine.md +64 -12
  112. package/docs/context-working-set.md +194 -0
  113. package/docs/development-pipeline.md +1 -1
  114. package/docs/documentation-coverage.md +5 -5
  115. package/docs/documentation-guide.md +6 -5
  116. package/docs/environment-variables.md +2 -1
  117. package/docs/eval-runner.md +1 -1
  118. package/docs/evals-internal.md +14 -1
  119. package/docs/evidence-and-memory.md +74 -2
  120. package/docs/evolution.md +1 -1
  121. package/docs/exit-codes-and-output.md +1 -1
  122. package/docs/extensions-and-sharing.md +2 -2
  123. package/docs/fleet-dispatch.md +22 -7
  124. package/docs/glossary.md +21 -1
  125. package/docs/installation-and-lifecycle.md +6 -6
  126. package/docs/middleware-and-components.md +1 -1
  127. package/docs/model-catalog.md +7 -9
  128. package/docs/observability.md +4 -4
  129. package/docs/performance-methodology.md +2 -2
  130. package/docs/proactive-memory.md +1 -1
  131. package/docs/prompt-envelope-and-tools.md +4 -4
  132. package/docs/provider-adapter-cookbook.md +1 -1
  133. package/docs/release-cut-checklist.md +35 -35
  134. package/docs/safety-model.md +23 -4
  135. package/docs/scientific-validation.md +21 -3
  136. package/docs/session-lifecycle.md +3 -3
  137. package/docs/skills-marketplace.md +1 -1
  138. package/docs/tool-usage.md +79 -12
  139. package/docs/trace-store.md +1 -1
  140. package/docs/troubleshooting.md +1 -1
  141. package/docs/tui-design.md +2 -2
  142. package/docs/worker-dispatch-mechanics.md +11 -1
  143. package/package.json +8 -11
  144. package/skills/meta/clio-test/SKILL.md +20 -17
  145. package/skills/meta/clio-test/evals.md +3 -3
  146. package/skills/meta/clio-test/references/harness.md +35 -6
  147. package/skills/meta/clio-test/references/test-map.md +20 -10
  148. package/skills/registry.yaml +2 -2
  149. package/skills/skill-marketplace.json +1 -1
  150. package/src/cli/context-working-set.ts +513 -0
  151. package/src/cli/context.ts +8 -0
  152. package/src/cli/evidence.ts +20 -2
  153. package/src/cli/index.ts +4 -0
  154. package/src/cli/verifiers.ts +325 -0
  155. package/src/core/bash-exec.ts +39 -14
  156. package/src/core/bus-events.ts +19 -4
  157. package/src/core/config.ts +54 -0
  158. package/src/core/defaults.ts +50 -3
  159. package/src/core/git-commit-attribution.ts +46 -21
  160. package/src/core/verification-scripts.ts +6 -0
  161. package/src/domains/agents/builtins/verifier.md +3 -0
  162. package/src/domains/config/classify.ts +1 -0
  163. package/src/domains/config/keybindings.ts +3 -3
  164. package/src/domains/context/working-set/contract.ts +161 -0
  165. package/src/domains/context/working-set/defaults.ts +28 -0
  166. package/src/domains/context/working-set/engine.ts +203 -0
  167. package/src/domains/context/working-set/fold.ts +62 -0
  168. package/src/domains/context/working-set/horizon.ts +38 -0
  169. package/src/domains/context/working-set/marker.ts +103 -0
  170. package/src/domains/context/working-set/path-index.ts +436 -0
  171. package/src/domains/context/working-set/payload.ts +152 -0
  172. package/src/domains/context/working-set/policies/age-horizon.ts +55 -0
  173. package/src/domains/context/working-set/policies/index.ts +21 -0
  174. package/src/domains/context/working-set/policies/structural.ts +160 -0
  175. package/src/domains/context/working-set/project.ts +132 -0
  176. package/src/domains/context/working-set/protect.ts +109 -0
  177. package/src/domains/context/working-set/recall.ts +177 -0
  178. package/src/domains/context/working-set/replay/controls.ts +112 -0
  179. package/src/domains/context/working-set/replay/load-clio.ts +199 -0
  180. package/src/domains/context/working-set/replay/metrics.ts +185 -0
  181. package/src/domains/context/working-set/replay/reference-graph.ts +79 -0
  182. package/src/domains/context/working-set/replay/report.ts +139 -0
  183. package/src/domains/context/working-set/replay/runner.ts +325 -0
  184. package/src/domains/context/working-set/replay/synthetic.ts +422 -0
  185. package/src/domains/context/working-set/replay/trace.ts +21 -0
  186. package/src/domains/context/working-set/visible.ts +54 -0
  187. package/src/domains/evidence/build.ts +112 -45
  188. package/src/domains/evidence/eval.ts +24 -7
  189. package/src/domains/evidence/index.ts +53 -0
  190. package/src/domains/evidence/ordering.ts +12 -0
  191. package/src/domains/evidence/run-trust.ts +221 -0
  192. package/src/domains/evidence/store.ts +46 -6
  193. package/src/domains/evidence/trust-status.ts +854 -0
  194. package/src/domains/evidence/types.ts +26 -0
  195. package/src/domains/middleware/memory-intervention.ts +3 -0
  196. package/src/domains/middleware/stalled-turn.ts +165 -4
  197. package/src/domains/safety/autonomy.ts +1 -1
  198. package/src/domains/safety/default-path-policy.ts +8 -0
  199. package/src/domains/safety/finish-contract.ts +4 -3
  200. package/src/domains/safety/policy-engine.ts +48 -6
  201. package/src/domains/session/compaction/compact.ts +23 -1
  202. package/src/domains/session/compaction/cut-point.ts +2 -0
  203. package/src/domains/session/compaction/tokens.ts +16 -1
  204. package/src/domains/session/context-ledger.ts +2 -0
  205. package/src/domains/session/entries.ts +107 -1
  206. package/src/domains/session/manager.ts +9 -2
  207. package/src/domains/session/migrations/index.ts +22 -3
  208. package/src/engine/acp/server.ts +3 -0
  209. package/src/engine/agent.ts +18 -1
  210. package/src/engine/session.ts +9 -3
  211. package/src/entry/orchestrator.ts +16 -4
  212. package/src/interactive/chat-loop-messages.ts +18 -6
  213. package/src/interactive/chat-panel.ts +571 -244
  214. package/src/interactive/chat-renderer.ts +79 -39
  215. package/src/interactive/context-meter.ts +10 -0
  216. package/src/interactive/context-overlay.ts +81 -6
  217. package/src/interactive/context-recall-command.ts +110 -0
  218. package/src/interactive/editor-submit.ts +26 -1
  219. package/src/interactive/footer/widgets.ts +22 -20
  220. package/src/interactive/footer-panel.ts +6 -1
  221. package/src/interactive/interactive-application.ts +2 -0
  222. package/src/interactive/interactive-event-projection.ts +12 -0
  223. package/src/interactive/interactive-slash-runtime.ts +49 -8
  224. package/src/interactive/model-session-replay.ts +21 -0
  225. package/src/interactive/overlay-general-openers.ts +6 -0
  226. package/src/interactive/overlay-session-lifecycle.ts +8 -4
  227. package/src/interactive/overlays/ask-user.ts +146 -24
  228. package/src/interactive/renderers/tool-execution.ts +167 -56
  229. package/src/interactive/session-transcript.ts +2 -2
  230. package/src/interactive/slash-commands.ts +29 -2
  231. package/src/interactive/status/index.ts +12 -1
  232. package/src/interactive/status/reasoning.ts +87 -0
  233. package/src/interactive/status/summary.ts +13 -2
  234. package/src/interactive/transcript-detail.ts +120 -0
  235. package/src/interactive/turn-context.ts +238 -88
  236. package/src/interactive/turn-middleware.ts +6 -6
  237. package/src/tools/agent-tools.ts +11 -4
  238. package/src/tools/bash.ts +144 -82
  239. package/src/tools/builtin-tool-catalog.ts +18 -6
  240. package/src/tools/context/index.ts +105 -3
  241. package/src/tools/context/surface.ts +3 -2
  242. package/src/tools/core-bootstrap.ts +21 -0
  243. package/src/tools/dispatch-runner.ts +9 -7
  244. package/src/tools/monitor.ts +28 -20
  245. package/src/tools/presentation.ts +107 -0
  246. package/src/tools/registry.ts +65 -7
  247. package/src/tools/result-disposition.ts +550 -0
  248. package/src/tools/result-shaping.ts +262 -19
  249. package/src/tools/safe-exec.ts +2 -0
  250. package/src/tools/verify/authoring.ts +1119 -0
  251. package/src/tools/verify/catalog.ts +346 -0
  252. package/src/tools/verify/index.ts +13 -3
  253. package/src/tools/verify/scripts.ts +135 -37
  254. package/src/tools/verify/surface.ts +9 -5
  255. package/src/tools/worker-evidence.ts +35 -12
  256. package/dist/chunk-MNA4JGU4.js +0 -255
  257. package/dist/chunk-SRF2PJNW.js +0 -184
  258. package/dist/chunk-T6YILFSB.js +0 -80
  259. package/dist/chunk-VAKQQHWR.js +0 -434
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Fold the working-set ledger records on the active path into a view.
3
+ *
4
+ * Pure over entries. The active path is selected here, through
5
+ * `filterEntriesToActivePath`, so every consumer (live projection, recall,
6
+ * overlay, replay-lite) shares the same #94 discipline: after a `/tree` switch
7
+ * the raw file still holds abandoned turns, and an eviction recorded on an
8
+ * abandoned branch must not project onto the live one. Forks inherit the view
9
+ * of their shared prefix for the same reason compaction summaries do.
10
+ */
11
+
12
+ import type { SessionEntry } from "../../session/entries.js";
13
+ import { filterEntriesToActivePath } from "../../session/tree/active-path.js";
14
+ import type { EvictedState, WorkingSetRef, WorkingSetView } from "./contract.js";
15
+
16
+ /** Ref keys index `WorkingSetView.evicted`. Today a key is the entry turnId. */
17
+ export function refKey(ref: WorkingSetRef): string {
18
+ return ref.entry;
19
+ }
20
+
21
+ export function parseRefKey(key: string): WorkingSetRef | null {
22
+ const trimmed = key.trim();
23
+ if (trimmed.length === 0 || /\s/.test(trimmed)) return null;
24
+ return { entry: trimmed };
25
+ }
26
+
27
+ export function foldWorkingSet(entries: ReadonlyArray<SessionEntry>, activeLeafTurnId?: string): WorkingSetView {
28
+ const active = filterEntriesToActivePath(entries, activeLeafTurnId);
29
+ const evicted = new Map<string, EvictedState>();
30
+ let evictionEvents = 0;
31
+ let itemsEvicted = 0;
32
+ let recalls = 0;
33
+ let lastPolicyId: string | null = null;
34
+ let lastEvictionTurnId: string | null = null;
35
+ for (const entry of active) {
36
+ if (entry.kind === "contextEviction") {
37
+ evictionEvents += 1;
38
+ lastPolicyId = entry.policyId;
39
+ lastEvictionTurnId = entry.turnId;
40
+ for (const item of entry.evicted) {
41
+ itemsEvicted += 1;
42
+ evicted.set(refKey(item.ref), {
43
+ reason: item.reason,
44
+ marker: item.marker,
45
+ ...(item.by === undefined ? {} : { by: item.by }),
46
+ tokensFreed: item.tokensFreed,
47
+ evictedAtTurnId: entry.turnId,
48
+ policyId: entry.policyId,
49
+ });
50
+ }
51
+ continue;
52
+ }
53
+ // A recall does not un-evict. The recalled body rides the recall tool
54
+ // result at the tail of the working set, which is where the model asked
55
+ // for it and where it costs no cold prefix; readmitting it at the
56
+ // original position would duplicate the bytes and invalidate the cache
57
+ // for everything after it. The marker stays, byte-stable, and a second
58
+ // recall of the same ref is the churn signal.
59
+ if (entry.kind === "contextRecall") recalls += 1;
60
+ }
61
+ return { evicted, evictionEvents, itemsEvicted, recalls, lastPolicyId, lastEvictionTurnId };
62
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The protection horizon: where the recent, untouchable window begins.
3
+ *
4
+ * Both policies and every protection predicate answer "is this entry inside the
5
+ * last `protectLastTurns` turns" the same way, so the arithmetic lives here
6
+ * once. It is the same cutoff `maskStaleObservations` used before this layer
7
+ * existed, which is what keeps `age-horizon` selection-identical to the
8
+ * destructive stage it replaced.
9
+ */
10
+
11
+ import type { SessionEntry } from "../../session/entries.js";
12
+
13
+ /**
14
+ * What starts a turn, in the sense the protection horizon counts. A local `!`
15
+ * bash execution and a branch summary both open a new stretch of work the same
16
+ * way an operator message does.
17
+ */
18
+ export function isTurnStart(entry: SessionEntry): boolean {
19
+ if (entry.kind === "bashExecution" || entry.kind === "branchSummary") return true;
20
+ return entry.kind === "message" && entry.role === "user";
21
+ }
22
+
23
+ /**
24
+ * Index of the first protected entry: walk back until `protectLastTurns` turn
25
+ * starts have been seen. Entries before it are candidates, entries from it on
26
+ * are the recent window nothing touches.
27
+ */
28
+ export function protectionCutoffIndex(entries: ReadonlyArray<SessionEntry>, protectLastTurns: number): number {
29
+ const horizon = Math.max(1, Math.floor(protectLastTurns));
30
+ let seen = 0;
31
+ for (let i = entries.length - 1; i >= 0; i -= 1) {
32
+ const entry = entries[i];
33
+ if (!entry || !isTurnStart(entry)) continue;
34
+ seen += 1;
35
+ if (seen >= horizon) return i;
36
+ }
37
+ return 0;
38
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * The one-line stub the projection renders in place of an evicted tool-result
3
+ * body.
4
+ *
5
+ * Byte-stable by construction: same input, same bytes, forever. No timestamp,
6
+ * no counter, no `Date.now()`. Two reasons. The marker is persisted inside the
7
+ * `contextEviction` entry and replayed by the projection on every request, so a
8
+ * marker that changed between renders would invalidate the prompt cache on a
9
+ * turn that evicted nothing new. And replay-lite reruns the same policy over
10
+ * recorded ledgers; a marker carrying wall-clock state would make two runs of
11
+ * the same trace disagree.
12
+ *
13
+ * The field order is fixed (ref, reason, by, tool, path, size, offload,
14
+ * recall, then the body tail) so a diff between two markers is readable and so
15
+ * a model reading many of them sees the same shape every time. Undefined
16
+ * fields are omitted rather than rendered empty. `recall` spells out the exact
17
+ * tool call that brings the body back, which is the only affordance the model
18
+ * has once the body is gone.
19
+ *
20
+ * The body tail is `preview` for every reason but one. A `failure_resolved`
21
+ * eviction renders `first_line` instead: failures are evidence, and the line
22
+ * that says what failed is the part worth a marker's tokens, where a preview
23
+ * of a stack trace is not.
24
+ */
25
+
26
+ import { formatSize } from "../../../engine/truncate.js";
27
+ import type { EvictionReason, WorkingSetRef } from "./contract.js";
28
+
29
+ /** Characters of the original body the marker keeps as a preview. */
30
+ const PREVIEW_LIMIT = 120;
31
+
32
+ export interface MarkerInput {
33
+ ref: WorkingSetRef;
34
+ reason: EvictionReason;
35
+ /** Ref key of the entry that superseded or resolved this one, when the reason names one. */
36
+ by?: string | undefined;
37
+ toolName: string;
38
+ /** The body leaving the working set; drives size and preview. */
39
+ text: string;
40
+ /** Set when the original result was offloaded to scratch. Replaces the preview. */
41
+ offloadPath?: string | undefined;
42
+ /** Primary file the result was about, when the payload names exactly one. */
43
+ path?: string | undefined;
44
+ }
45
+
46
+ /** Lines as `split(/\r\n|\r|\n/)` would count them, without materializing them. */
47
+ function lineCount(text: string): number {
48
+ if (text.length === 0) return 0;
49
+ let count = 1;
50
+ for (let index = 0; index < text.length; index += 1) {
51
+ const code = text.charCodeAt(index);
52
+ if (code === 10 || (code === 13 && text.charCodeAt(index + 1) !== 10)) count += 1;
53
+ }
54
+ return count;
55
+ }
56
+
57
+ /**
58
+ * First `PREVIEW_LIMIT` characters with whitespace collapsed to single spaces
59
+ * and double quotes escaped, so the preview never breaks the quoted field or
60
+ * spills onto a second line. Bounded: the body is scanned only as far as the
61
+ * preview reaches, because the marker is priced once per candidate on every
62
+ * eviction and a body-length collapse was most of that price.
63
+ */
64
+ function preview(text: string): string {
65
+ let out = "";
66
+ let pendingSpace = false;
67
+ for (const char of text) {
68
+ if (/\s/.test(char)) {
69
+ pendingSpace = out.length > 0;
70
+ continue;
71
+ }
72
+ if (pendingSpace) out += " ";
73
+ pendingSpace = false;
74
+ out += char;
75
+ if (out.length >= PREVIEW_LIMIT) break;
76
+ }
77
+ return out.slice(0, PREVIEW_LIMIT).replace(/"/g, '\\"');
78
+ }
79
+
80
+ /** The first line that says anything, bounded and escaped like a preview. */
81
+ function firstLine(text: string): string {
82
+ const line = /[^\r\n]*\S[^\r\n]*/.exec(text)?.[0] ?? "";
83
+ return line.trim().slice(0, PREVIEW_LIMIT).replace(/"/g, '\\"');
84
+ }
85
+
86
+ export function renderMarker(input: MarkerInput): string {
87
+ const ref = input.ref.entry;
88
+ const fields: string[] = [`ref=${ref}`, `reason=${input.reason}`];
89
+ if (input.by !== undefined) fields.push(`by=${input.by}`);
90
+ fields.push(`tool=${input.toolName}`);
91
+ if (input.path !== undefined) fields.push(`path=${input.path}`);
92
+ fields.push(`size=${lineCount(input.text)} lines/${formatSize(Buffer.byteLength(input.text, "utf8"))}`);
93
+ if (input.offloadPath !== undefined) fields.push(`offload=${input.offloadPath}`);
94
+ fields.push(`recall=context(scope="recall", ref="${ref}")`);
95
+ // An offloaded body is one `read` away at a stable path; a preview of it
96
+ // would spend tokens repeating what the pointer already promises.
97
+ if (input.offloadPath === undefined) {
98
+ const failed = input.reason === "failure_resolved";
99
+ const tail = failed ? firstLine(input.text) : preview(input.text);
100
+ if (tail.length > 0) fields.push(`${failed ? "first_line" : "preview"}="${tail}"`);
101
+ }
102
+ return `[evicted ${fields.join(" ")}]`;
103
+ }
@@ -0,0 +1,436 @@
1
+ /**
2
+ * What the session has observed about which files.
3
+ *
4
+ * One pass over the active-path entries produces one `PathObservation` per
5
+ * tool result (and per `fileEntry`) that names a path: which file, which line
6
+ * range, which paths a listing surfaced, whether the call failed, and where in
7
+ * the turn sequence it sits. The structural policy reads it to answer the four
8
+ * questions its rules ask ("was this file written after I read it", "did a
9
+ * later read cover this range", "did this failure get resolved", "has this
10
+ * listing been consumed"), and the replay reference graph reads the same index
11
+ * to label `file_reread`, `file_discovery`, and `file_rewrite` edges. One
12
+ * index, two consumers, so a rule and its measurement can never disagree about
13
+ * what the session did.
14
+ *
15
+ * Pure, deterministic, single pass. No filesystem access: paths are resolved
16
+ * lexically against the session cwd the caller passes (`options.cwd`), and only
17
+ * normalized when it does not. The cwd is never sniffed from the entries and
18
+ * never defaulted to `process.cwd()`: the live ledger readers strip the JSONL
19
+ * header, and a replay run and a live run must index the same ledger the same
20
+ * way.
21
+ *
22
+ * This is `extractFileOps` in `compaction/compact.ts` generalized: same
23
+ * `path | file_path | filePath` argument reading, same tool-call pairing as
24
+ * `chat-renderer.ts`, plus ranges, listings, failures, and turn positions.
25
+ */
26
+
27
+ import { basename, isAbsolute, join, normalize, resolve } from "node:path";
28
+ import type { MessageEntry, SessionEntry } from "../../session/entries.js";
29
+ import type { WorkingSetRef } from "./contract.js";
30
+ import { isTurnStart } from "./horizon.js";
31
+ import { isRecord, toolResultText } from "./payload.js";
32
+
33
+ /**
34
+ * The observing verb. Clio's `git` and `verify` are command runners with an
35
+ * exit status, so they index as `bash`; `artifact` writes a file, so it indexes
36
+ * as `write`. Tools that observe no path at all (dispatch, web_fetch, tasks,
37
+ * ask_user, context, ...) produce no observation.
38
+ */
39
+ export type PathOp = "read" | "grep" | "find" | "ls" | "code_nav" | "write" | "edit" | "bash";
40
+
41
+ /**
42
+ * Lines of a file an observation covers. `offset` counts lines skipped from the
43
+ * top (0-based), so a whole-file read is `{ offset: 0, limit: null }` and
44
+ * `read(offset: 1)` normalizes to it. `limit: null` means "to EOF".
45
+ */
46
+ export interface PathRange {
47
+ offset: number;
48
+ limit: number | null;
49
+ }
50
+
51
+ function rangeEnd(range: PathRange): number {
52
+ return range.limit === null ? Number.POSITIVE_INFINITY : range.offset + range.limit;
53
+ }
54
+
55
+ function isFullRead(range: PathRange | null): boolean {
56
+ return range !== null && range.offset === 0 && range.limit === null;
57
+ }
58
+
59
+ /**
60
+ * Whether a later read makes the earlier range redundant. A full read covers
61
+ * everything, including a tail read whose coverage is unknown. Any other read
62
+ * covers only an identical or containing range, and an unknown range covers
63
+ * nothing.
64
+ */
65
+ export function covers(later: PathRange | null, earlier: PathRange | null): boolean {
66
+ if (isFullRead(later)) return true;
67
+ if (later === null || earlier === null) return false;
68
+ return later.offset <= earlier.offset && rangeEnd(later) >= rangeEnd(earlier);
69
+ }
70
+
71
+ export interface PathObservation {
72
+ /** The evictable unit: the tool_result entry, or the fileEntry entry for write/edit evidence. */
73
+ ref: WorkingSetRef;
74
+ toolCallId: string | null;
75
+ toolName: string;
76
+ op: PathOp;
77
+ /**
78
+ * Canonical absolute path when the session cwd is known, else the path as
79
+ * the call wrote it. Empty when the call named no path (a bash command with
80
+ * no cwd argument), which keeps it out of `byPath` without dropping the
81
+ * observation the failure rules need.
82
+ */
83
+ path: string;
84
+ /**
85
+ * Line coverage for `read`, null for everything else and for a `tail` read,
86
+ * whose coverage is unknowable without the file. Supersession treats a null
87
+ * range as unknown: it covers nothing and only a full read covers it.
88
+ */
89
+ range: PathRange | null;
90
+ /** Listing ops only: concrete file paths the result surfaced, resolved like `path`. */
91
+ surfaced: ReadonlyArray<string>;
92
+ isError: boolean;
93
+ /** The safety rails refused the call: no observation happened, and it resolves nothing. */
94
+ isBlocked: boolean;
95
+ /** Turn starts (user message, bashExecution, branchSummary) strictly before this entry. */
96
+ turnIndex: number;
97
+ /** Index in the entries array this index was built from. */
98
+ entryIndex: number;
99
+ /** Tool-call arguments as deterministic JSON with sorted keys; empty when the call is unknown. */
100
+ argsKey: string;
101
+ }
102
+
103
+ export interface PathIndex {
104
+ /** Ledger order. */
105
+ observations: ReadonlyArray<PathObservation>;
106
+ byRef: ReadonlyMap<string, PathObservation>;
107
+ byPath: ReadonlyMap<string, ReadonlyArray<PathObservation>>;
108
+ /** Every entry's turn position, including entries that observe no path. */
109
+ turnIndexOf: ReadonlyMap<string, number>;
110
+ turnCount: number;
111
+ }
112
+
113
+ /** Commands whose stdout is a list of paths. Anything else surfaces nothing. */
114
+ const LISTING_COMMANDS = new Set(["ls", "find", "tree", "fd", "rg", "grep"]);
115
+ /** Commands whose stdout is `path:line:text` rather than one path per line. */
116
+ const MATCH_LINE_COMMANDS = new Set(["rg", "grep"]);
117
+
118
+ const TOOL_OPS: ReadonlyMap<string, PathOp> = new Map<string, PathOp>([
119
+ ["read", "read"],
120
+ ["grep", "grep"],
121
+ ["find", "find"],
122
+ ["ls", "ls"],
123
+ ["code_nav", "code_nav"],
124
+ ["write", "write"],
125
+ ["edit", "edit"],
126
+ ["artifact", "write"],
127
+ ["bash", "bash"],
128
+ ["git", "bash"],
129
+ ["verify", "bash"],
130
+ ]);
131
+
132
+ /** code_nav modes whose `query` is a file path rather than a symbol or page name. */
133
+ const CODE_NAV_PATH_MODES = new Set(["path", "outline", "deps", "dependents"]);
134
+
135
+ /** Ops whose result is a list of other paths. */
136
+ const LISTING_OPS = new Set<PathOp>(["grep", "find", "ls", "bash"]);
137
+
138
+ export interface PathIndexOptions {
139
+ /** Session working directory; relative arguments resolve against it. Null leaves them relative (normalized). */
140
+ cwd?: string | null;
141
+ }
142
+
143
+ /**
144
+ * Lexical canonicalization only: no realpath, no `process.cwd()`, no `~`
145
+ * expansion. With a cwd, `src/a.ts`, `./src/a.ts`, and `/cwd/src/a.ts` all key
146
+ * the same file; without one the first two still do.
147
+ */
148
+ function canonicalize(value: string, cwd: string | null): string {
149
+ const trimmed = value.trim();
150
+ if (trimmed.length === 0) return "";
151
+ if (isAbsolute(trimmed)) return normalize(trimmed);
152
+ return cwd === null ? normalize(trimmed) : resolve(cwd, trimmed);
153
+ }
154
+
155
+ function usableCwd(options: PathIndexOptions | undefined): string | null {
156
+ const cwd = options?.cwd;
157
+ if (typeof cwd !== "string" || cwd.trim().length === 0 || !isAbsolute(cwd)) return null;
158
+ return normalize(cwd);
159
+ }
160
+
161
+ function stableStringify(value: unknown): string {
162
+ if (value === null) return "null";
163
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
164
+ if (isRecord(value)) {
165
+ const keys = Object.keys(value).sort();
166
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
167
+ }
168
+ if (value === undefined) return "null";
169
+ return JSON.stringify(value) ?? "null";
170
+ }
171
+
172
+ interface ToolCallFacts {
173
+ toolName: string;
174
+ args: unknown;
175
+ argsKey: string;
176
+ }
177
+
178
+ function callFacts(toolName: string, args: unknown): ToolCallFacts {
179
+ return { toolName, args, argsKey: args === undefined ? "" : stableStringify(args) };
180
+ }
181
+
182
+ function stringField(record: Record<string, unknown> | null, ...keys: string[]): string | null {
183
+ if (record === null) return null;
184
+ for (const key of keys) {
185
+ const value = record[key];
186
+ if (typeof value === "string" && value.trim().length > 0) return value.trim();
187
+ }
188
+ return null;
189
+ }
190
+
191
+ function payloadRecord(payload: unknown): Record<string, unknown> | null {
192
+ return isRecord(payload) ? payload : null;
193
+ }
194
+
195
+ /** Record every tool call the ledger holds, in both shapes it persists them. */
196
+ function collectToolCalls(entries: ReadonlyArray<SessionEntry>): Map<string, ToolCallFacts> {
197
+ const calls = new Map<string, ToolCallFacts>();
198
+ for (const entry of entries) {
199
+ if (entry.kind !== "message") continue;
200
+ const obj = payloadRecord(entry.payload);
201
+ if (entry.role === "tool_call" && obj !== null) {
202
+ const id = stringField(obj, "toolCallId", "tool_call_id", "id") ?? entry.turnId;
203
+ const name = stringField(obj, "name", "toolName", "tool") ?? "tool";
204
+ calls.set(id, callFacts(name, obj.args ?? obj.arguments ?? obj.input));
205
+ continue;
206
+ }
207
+ if (entry.role !== "assistant" || obj === null || !Array.isArray(obj.content)) continue;
208
+ for (const block of obj.content) {
209
+ if (!isRecord(block) || block.type !== "toolCall") continue;
210
+ const id = stringField(block, "id", "toolCallId") ?? entry.turnId;
211
+ const name = stringField(block, "name", "toolName") ?? "tool";
212
+ calls.set(id, callFacts(name, block.arguments ?? block.args ?? block.input));
213
+ }
214
+ }
215
+ return calls;
216
+ }
217
+
218
+ /**
219
+ * The one path argument of every tool call, as the model wrote it, keyed by
220
+ * toolCallId. Markers read this so a `read` that left the working set still
221
+ * says which file it was; the canonical, cwd-resolved form the rules key on
222
+ * would show the model an absolute path it never typed.
223
+ */
224
+ export function callPathsByToolCallId(entries: ReadonlyArray<SessionEntry>): ReadonlyMap<string, string> {
225
+ const paths = new Map<string, string>();
226
+ for (const [id, call] of collectToolCalls(entries)) {
227
+ const named = stringField(isRecord(call.args) ? call.args : null, "path", "file_path", "filePath");
228
+ if (named !== null) paths.set(id, named);
229
+ }
230
+ return paths;
231
+ }
232
+
233
+ /**
234
+ * The path the call was about. Search tools default to the working directory,
235
+ * which is what they actually searched, so a `grep` with no `path` argument is
236
+ * an observation of the cwd rather than of nothing.
237
+ */
238
+ function observedPath(op: PathOp, args: Record<string, unknown> | null, cwd: string | null): string {
239
+ if (op === "bash") {
240
+ const explicit = stringField(args, "cwd");
241
+ return explicit === null ? "" : canonicalize(explicit, cwd);
242
+ }
243
+ if (op === "code_nav") {
244
+ const mode = stringField(args, "mode");
245
+ if (mode === null || !CODE_NAV_PATH_MODES.has(mode)) return "";
246
+ const query = stringField(args, "query");
247
+ return query === null ? "" : canonicalize(query, cwd);
248
+ }
249
+ const named = stringField(args, "path", "file_path", "filePath");
250
+ if (named !== null) return canonicalize(named, cwd);
251
+ // grep, find, and ls all default to ".".
252
+ if (op === "grep" || op === "find" || op === "ls") return cwd ?? ".";
253
+ return "";
254
+ }
255
+
256
+ function readRange(args: Record<string, unknown> | null): PathRange | null {
257
+ if (args === null) return { offset: 0, limit: null };
258
+ const tail = args.tail;
259
+ // A tail read covers an unknown suffix; claiming a range would let it
260
+ // supersede reads it may not contain.
261
+ if (typeof tail === "number" && Number.isFinite(tail) && tail > 0) return null;
262
+ const rawOffset = args.offset;
263
+ const rawLimit = args.limit;
264
+ const offset =
265
+ typeof rawOffset === "number" && Number.isFinite(rawOffset) && rawOffset > 1 ? Math.floor(rawOffset) - 1 : 0;
266
+ const limit = typeof rawLimit === "number" && Number.isFinite(rawLimit) && rawLimit > 0 ? Math.floor(rawLimit) : null;
267
+ return { offset, limit };
268
+ }
269
+
270
+ /**
271
+ * Is this line a concrete file path rather than prose, a directory, or a
272
+ * tool's own notice? Deliberately permissive about extensions (`Makefile` and
273
+ * `LICENSE` are files) and strict about whitespace, because every listing this
274
+ * parses prints one path per line. Over-counting only keeps a listing in the
275
+ * working set longer; under-counting would evict a listing whose paths the
276
+ * agent still needs.
277
+ */
278
+ function looksLikeConcreteFilePath(line: string): boolean {
279
+ const text = line.trim();
280
+ if (text.length === 0) return false;
281
+ // The observation envelope's own trailer, e.g. `[grep: 261/261+ matches ...]`.
282
+ if (text.startsWith("[")) return false;
283
+ if (text.endsWith("/")) return false;
284
+ return !/\s/.test(text);
285
+ }
286
+
287
+ /** `path:line: text` from grep content mode and from bash `rg`/`grep`. */
288
+ function pathFromMatchLine(line: string): string | null {
289
+ const match = /^([^\s:]+):\d+[:-]/.exec(line.trim());
290
+ return match?.[1] ?? null;
291
+ }
292
+
293
+ function surfacedPaths(
294
+ op: PathOp,
295
+ args: Record<string, unknown> | null,
296
+ text: string,
297
+ root: string,
298
+ cwd: string | null,
299
+ ): string[] {
300
+ const lines = text.split("\n");
301
+ const matchLines = op === "grep" || (op === "bash" && isMatchLineCommand(args));
302
+ const out: string[] = [];
303
+ const seen = new Set<string>();
304
+ for (const line of lines) {
305
+ const raw = matchLines ? (pathFromMatchLine(line) ?? candidateWholeLine(line)) : candidateWholeLine(line);
306
+ if (raw === null) continue;
307
+ const resolved = resolveSurfaced(raw, root, cwd);
308
+ if (resolved.length === 0 || seen.has(resolved)) continue;
309
+ seen.add(resolved);
310
+ out.push(resolved);
311
+ }
312
+ return out;
313
+ }
314
+
315
+ function candidateWholeLine(line: string): string | null {
316
+ return looksLikeConcreteFilePath(line) ? line.trim() : null;
317
+ }
318
+
319
+ function isMatchLineCommand(args: Record<string, unknown> | null): boolean {
320
+ const verb = commandVerb(args);
321
+ return verb !== null && MATCH_LINE_COMMANDS.has(verb);
322
+ }
323
+
324
+ function commandVerb(args: Record<string, unknown> | null): string | null {
325
+ const command = stringField(args, "command");
326
+ if (command === null) return null;
327
+ const first = command.trimStart().split(/\s+/)[0];
328
+ return first === undefined || first.length === 0 ? null : basename(first);
329
+ }
330
+
331
+ /**
332
+ * A listing prints paths relative to what it searched, so they join onto the
333
+ * observation's own path before canonicalizing, whether that root is absolute
334
+ * or still relative. A single-file search root surfaces its own basename,
335
+ * which resolves back to the root rather than to a child of it.
336
+ */
337
+ function resolveSurfaced(value: string, root: string, cwd: string | null): string {
338
+ if (isAbsolute(value)) return normalize(value);
339
+ if (root.length === 0) return canonicalize(value, cwd);
340
+ if (basename(root) === value) return canonicalize(root, cwd);
341
+ return canonicalize(join(root, value), cwd);
342
+ }
343
+
344
+ /** A listing result only surfaces paths when the call was a listing in the first place. */
345
+ function shouldParseSurfaced(op: PathOp, args: Record<string, unknown> | null, isError: boolean): boolean {
346
+ if (isError || !LISTING_OPS.has(op)) return false;
347
+ if (op !== "bash") return true;
348
+ const verb = commandVerb(args);
349
+ return verb !== null && LISTING_COMMANDS.has(verb);
350
+ }
351
+
352
+ function fileEntryOp(operation: "read" | "write" | "edit" | "create" | "delete"): PathOp {
353
+ if (operation === "read") return "read";
354
+ if (operation === "edit") return "edit";
355
+ return "write";
356
+ }
357
+
358
+ function toolResultObservation(
359
+ entry: MessageEntry,
360
+ context: { entryIndex: number; turnIndex: number; cwd: string | null; calls: ReadonlyMap<string, ToolCallFacts> },
361
+ ): PathObservation | null {
362
+ const obj = payloadRecord(entry.payload);
363
+ const toolCallId = stringField(obj, "toolCallId", "tool_call_id", "id");
364
+ const call = toolCallId === null ? undefined : context.calls.get(toolCallId);
365
+ const toolName = stringField(obj, "toolName", "name", "tool") ?? call?.toolName ?? "tool";
366
+ const op = TOOL_OPS.get(toolName);
367
+ if (op === undefined) return null;
368
+ const args = call !== undefined && isRecord(call.args) ? call.args : null;
369
+ const isError = obj?.isError === true || obj?.error === true;
370
+ const isBlocked = obj?.outcome === "blocked" || typeof obj?.blockReason === "string";
371
+ const path = observedPath(op, args, context.cwd);
372
+ const surfaced = shouldParseSurfaced(op, args, isError)
373
+ ? surfacedPaths(op, args, toolResultText(obj?.result ?? entry.payload), path, context.cwd)
374
+ : [];
375
+ return {
376
+ ref: { entry: entry.turnId },
377
+ toolCallId,
378
+ toolName,
379
+ op,
380
+ path,
381
+ range: op === "read" ? readRange(args) : null,
382
+ surfaced,
383
+ isError,
384
+ isBlocked,
385
+ turnIndex: context.turnIndex,
386
+ entryIndex: context.entryIndex,
387
+ argsKey: call?.argsKey ?? "",
388
+ };
389
+ }
390
+
391
+ export function buildPathIndex(entries: ReadonlyArray<SessionEntry>, options?: PathIndexOptions): PathIndex {
392
+ const cwd = usableCwd(options);
393
+ const calls = collectToolCalls(entries);
394
+ const observations: PathObservation[] = [];
395
+ const byRef = new Map<string, PathObservation>();
396
+ const byPath = new Map<string, PathObservation[]>();
397
+ const turnIndexOf = new Map<string, number>();
398
+ let turnIndex = 0;
399
+
400
+ for (let entryIndex = 0; entryIndex < entries.length; entryIndex += 1) {
401
+ const entry = entries[entryIndex];
402
+ if (entry === undefined) continue;
403
+ turnIndexOf.set(entry.turnId, turnIndex);
404
+ let observation: PathObservation | null = null;
405
+ if (entry.kind === "fileEntry") {
406
+ observation = {
407
+ ref: { entry: entry.turnId },
408
+ toolCallId: null,
409
+ toolName: "fileEntry",
410
+ op: fileEntryOp(entry.operation),
411
+ path: canonicalize(entry.path, cwd),
412
+ range: null,
413
+ surfaced: [],
414
+ isError: false,
415
+ isBlocked: false,
416
+ turnIndex,
417
+ entryIndex,
418
+ argsKey: "",
419
+ };
420
+ } else if (entry.kind === "message" && entry.role === "tool_result") {
421
+ observation = toolResultObservation(entry, { entryIndex, turnIndex, cwd, calls });
422
+ }
423
+ if (observation !== null) {
424
+ observations.push(observation);
425
+ byRef.set(observation.ref.entry, observation);
426
+ if (observation.path.length > 0) {
427
+ const bucket = byPath.get(observation.path);
428
+ if (bucket === undefined) byPath.set(observation.path, [observation]);
429
+ else bucket.push(observation);
430
+ }
431
+ }
432
+ if (isTurnStart(entry)) turnIndex += 1;
433
+ }
434
+
435
+ return { observations, byRef, byPath, turnIndexOf, turnCount: turnIndex };
436
+ }