cocheck 0.0.0-stage → 0.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 (305) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +104 -2
  3. package/THIRD_PARTY_NOTICES.md +279 -0
  4. package/bin/cocheck.mjs +8 -0
  5. package/dist/agent-transcripts.js +541 -0
  6. package/dist/attribution/basis.js +31 -0
  7. package/dist/attribution/evidence.js +311 -0
  8. package/dist/attribution/hooks/cocheck-preload.cjs +254 -0
  9. package/dist/attribution/hooks/sitecustomize.py +245 -0
  10. package/dist/attribution/names.js +163 -0
  11. package/dist/attribution/reconstruct.js +128 -0
  12. package/dist/attribution/tag.js +246 -0
  13. package/dist/attribution/write-scope-win.js +615 -0
  14. package/dist/attribution/write-scope.js +1668 -0
  15. package/dist/build-info.json +1 -0
  16. package/dist/cli-main.js +8 -0
  17. package/dist/cli.js +193 -0
  18. package/dist/codex-config.js +107 -0
  19. package/dist/connector/after-gap.js +56 -0
  20. package/dist/connector/after-snapshot.js +244 -0
  21. package/dist/connector/before-snapshot.js +168 -0
  22. package/dist/connector/builtins.js +93 -0
  23. package/dist/connector/changes-v1.js +276 -0
  24. package/dist/connector/claimed-state.js +40 -0
  25. package/dist/connector/claimed.js +86 -0
  26. package/dist/connector/conformance.js +458 -0
  27. package/dist/connector/diff-object.js +81 -0
  28. package/dist/connector/diff-samples.js +64 -0
  29. package/dist/connector/diff.js +273 -0
  30. package/dist/connector/doc-level.js +20 -0
  31. package/dist/connector/enabled-types.js +87 -0
  32. package/dist/connector/export-view.js +13 -0
  33. package/dist/connector/file-capture.js +265 -0
  34. package/dist/connector/frozen.js +213 -0
  35. package/dist/connector/installed-manifests.js +72 -0
  36. package/dist/connector/installed-match.js +161 -0
  37. package/dist/connector/local-process.js +119 -0
  38. package/dist/connector/nothing-changed-rule.js +23 -0
  39. package/dist/connector/old-rows.js +66 -0
  40. package/dist/connector/png-pixels.js +4 -0
  41. package/dist/connector/registry.js +78 -0
  42. package/dist/connector/requires.js +30 -0
  43. package/dist/connector/row-doc.js +54 -0
  44. package/dist/connector/run-argv.js +25 -0
  45. package/dist/connector/runner.js +325 -0
  46. package/dist/connector/schema.js +242 -0
  47. package/dist/connector/subject.js +8 -0
  48. package/dist/connector/subjects.js +113 -0
  49. package/dist/connector/validate.js +200 -0
  50. package/dist/connector-auth.js +101 -0
  51. package/dist/connector-create.js +55 -0
  52. package/dist/connector-doctor.js +167 -0
  53. package/dist/connector-test-cli.js +627 -0
  54. package/dist/connector-types-cli.js +43 -0
  55. package/dist/connectors/microsoft-excel/cocheck-connector.json +13 -0
  56. package/dist/connectors/microsoft-excel/connector.mjs +11 -0
  57. package/dist/connectors/microsoft-powerpoint/cocheck-connector.json +13 -0
  58. package/dist/connectors/microsoft-powerpoint/connector.mjs +11 -0
  59. package/dist/connectors/microsoft-word/cocheck-connector.json +13 -0
  60. package/dist/connectors/microsoft-word/connector.mjs +11 -0
  61. package/dist/copies.js +151 -0
  62. package/dist/copilot-helpers.js +246 -0
  63. package/dist/coverage.js +277 -0
  64. package/dist/credit-guard.js +330 -0
  65. package/dist/display.js +78 -0
  66. package/dist/file-lock.js +145 -0
  67. package/dist/fingerprint.js +25 -0
  68. package/dist/formats/files/align.js +84 -0
  69. package/dist/formats/files/csv.js +78 -0
  70. package/dist/formats/files/layer.js +274 -0
  71. package/dist/formats/files/scan.js +86 -0
  72. package/dist/formats/files/textlike.js +21 -0
  73. package/dist/formats/layer.js +48 -0
  74. package/dist/helpers/pdfpages +0 -0
  75. package/dist/home-page.js +173 -0
  76. package/dist/home-perms.js +59 -0
  77. package/dist/hook-adapter.js +3415 -0
  78. package/dist/hook-cli.js +505 -0
  79. package/dist/hook-journal.js +147 -0
  80. package/dist/hook.js +25 -0
  81. package/dist/hosts/claude.js +250 -0
  82. package/dist/hosts/codex-bin-macos.js +2 -0
  83. package/dist/hosts/codex-bin.js +35 -0
  84. package/dist/hosts/codex-trust-probe.js +52 -0
  85. package/dist/hosts/codex-trust.js +46 -0
  86. package/dist/hosts/codex.js +355 -0
  87. package/dist/hosts/copilot.js +236 -0
  88. package/dist/hosts/index.js +52 -0
  89. package/dist/hosts/session-titles.js +327 -0
  90. package/dist/hosts/shared.js +31 -0
  91. package/dist/hosts/types.js +26 -0
  92. package/dist/html.js +4 -0
  93. package/dist/install.js +676 -0
  94. package/dist/items.js +105 -0
  95. package/dist/ledger.js +2097 -0
  96. package/dist/narration.js +202 -0
  97. package/dist/normalize.js +82 -0
  98. package/dist/office/connector/apps.js +34 -0
  99. package/dist/office/connector/docx/layer.js +247 -0
  100. package/dist/office/connector/docx/reader.js +284 -0
  101. package/dist/office/connector/excel/align.js +284 -0
  102. package/dist/office/connector/excel/answer.js +352 -0
  103. package/dist/office/connector/excel/diff.js +1310 -0
  104. package/dist/office/connector/excel/errors.js +44 -0
  105. package/dist/office/connector/excel/look.js +121 -0
  106. package/dist/office/connector/excel/print-boxes.js +432 -0
  107. package/dist/office/connector/excel/print-grid-previous.js +206 -0
  108. package/dist/office/connector/excel/print-setup.js +168 -0
  109. package/dist/office/connector/excel/workbook.js +374 -0
  110. package/dist/office/connector/export-driver.js +9 -0
  111. package/dist/office/connector/helpers/cocheck-screen +0 -0
  112. package/dist/office/connector/issues.js +31 -0
  113. package/dist/office/connector/mac-guard.js +16 -0
  114. package/dist/office/connector/main.js +23 -0
  115. package/dist/office/connector/nothing-changed.js +18 -0
  116. package/dist/office/connector/office-job.js +416 -0
  117. package/dist/office/connector/office-macos.js +473 -0
  118. package/dist/office/connector/office-win-export.js +107 -0
  119. package/dist/office/connector/office-win-lifecycle.js +194 -0
  120. package/dist/office/connector/office-win.js +209 -0
  121. package/dist/office/connector/office-win.ps1 +451 -0
  122. package/dist/office/connector/open-watch.js +46 -0
  123. package/dist/office/connector/pictures.js +156 -0
  124. package/dist/office/connector/pptx/diff.js +589 -0
  125. package/dist/office/connector/pptx/frames.js +105 -0
  126. package/dist/office/connector/pptx/layer.js +148 -0
  127. package/dist/office/connector/pptx/links.js +59 -0
  128. package/dist/office/connector/pptx/reader.js +744 -0
  129. package/dist/office/connector/pptx/spans.js +70 -0
  130. package/dist/office/connector/pptx/tags.js +86 -0
  131. package/dist/office/connector/pptx/xml.js +96 -0
  132. package/dist/office/connector/pptx/zip.js +223 -0
  133. package/dist/office/connector/pptx-boxes.js +238 -0
  134. package/dist/office/connector/print-copy-cap.js +19 -0
  135. package/dist/office/connector/print-copy.js +13 -0
  136. package/dist/office/connector/program.js +291 -0
  137. package/dist/office/connector/reach.js +27 -0
  138. package/dist/office/connector/refusal.js +16 -0
  139. package/dist/office/connector/screen-macos.js +193 -0
  140. package/dist/office/connector/screen-windows.js +34 -0
  141. package/dist/office/connector/shared/chart-diff.js +376 -0
  142. package/dist/office/connector/shared/docprops-noise.js +13 -0
  143. package/dist/office/connector/shared/lock.js +107 -0
  144. package/dist/office/connector/shared/ooxml-names.js +347 -0
  145. package/dist/office/connector/shared/owner.js +57 -0
  146. package/dist/office/connector/shared/package-media.js +703 -0
  147. package/dist/office/connector/shared/preflight.js +226 -0
  148. package/dist/office/connector/shared/structure-check.js +623 -0
  149. package/dist/office/connector/word-boxes.js +364 -0
  150. package/dist/office/connector/word-print-copy.js +234 -0
  151. package/dist/office/connector/xlsx/diff.js +1038 -0
  152. package/dist/office/connector/xlsx/formula.js +410 -0
  153. package/dist/office/connector/xlsx/layer.js +621 -0
  154. package/dist/office/connector/xlsx/memo.js +39 -0
  155. package/dist/office/connector/xlsx/numbers.js +31 -0
  156. package/dist/office/connector/xlsx/numfmt.js +913 -0
  157. package/dist/office/connector/xlsx/parts.js +66 -0
  158. package/dist/office/connector/xlsx/reader.js +394 -0
  159. package/dist/office/connector/xlsx/types.js +20 -0
  160. package/dist/office/connector/xlsx/written.js +446 -0
  161. package/dist/open-pick.js +99 -0
  162. package/dist/patch-secrets.js +194 -0
  163. package/dist/paths.js +65 -0
  164. package/dist/platform/darwin.js +179 -0
  165. package/dist/platform/index.js +61 -0
  166. package/dist/platform/spawn.js +115 -0
  167. package/dist/platform/stub.js +21 -0
  168. package/dist/platform/task-folder.js +41 -0
  169. package/dist/platform/types.js +20 -0
  170. package/dist/platform/win32-docrender.js +7 -0
  171. package/dist/platform/win32.js +265 -0
  172. package/dist/preferences.js +49 -0
  173. package/dist/reason.js +103 -0
  174. package/dist/region-delivery.js +148 -0
  175. package/dist/registry.js +68 -0
  176. package/dist/reveal.js +45 -0
  177. package/dist/review-process.js +154 -0
  178. package/dist/review-refresh-process.js +17 -0
  179. package/dist/review-refresh.js +120 -0
  180. package/dist/review-server.js +2079 -0
  181. package/dist/review-view-server.js +106 -0
  182. package/dist/review.js +8 -0
  183. package/dist/seal.js +315 -0
  184. package/dist/secret-files.js +34 -0
  185. package/dist/secret-hashes.js +27 -0
  186. package/dist/secret-rules.generated.js +3519 -0
  187. package/dist/secret-scan.js +127 -0
  188. package/dist/session-context.js +18 -0
  189. package/dist/signoff.js +419 -0
  190. package/dist/skill.js +110 -0
  191. package/dist/states.js +192 -0
  192. package/dist/tasks.js +1001 -0
  193. package/dist/timeline/attribution.js +207 -0
  194. package/dist/timeline/broken.js +55 -0
  195. package/dist/timeline/describe.js +413 -0
  196. package/dist/timeline/generic.js +195 -0
  197. package/dist/timeline/load.js +464 -0
  198. package/dist/timeline/loading.js +49 -0
  199. package/dist/timeline/notes.js +208 -0
  200. package/dist/timeline/page.js +178 -0
  201. package/dist/timeline/picture.js +303 -0
  202. package/dist/timeline/rail/assets/cocheck-icon.svg +1 -0
  203. package/dist/timeline/rail/assets/files-view.js +198 -0
  204. package/dist/timeline/rail/assets/loaders/icon-intro.json +1 -0
  205. package/dist/timeline/rail/assets/loaders/loader-orbit.json +1 -0
  206. package/dist/timeline/rail/assets/loaders/loader-spin.json +1 -0
  207. package/dist/timeline/rail/assets/review.css +992 -0
  208. package/dist/timeline/rail/assets/review.js +3365 -0
  209. package/dist/timeline/rail/assets/view-table.js +683 -0
  210. package/dist/timeline/rail/failure-line.js +26 -0
  211. package/dist/timeline/rail/files-model.js +45 -0
  212. package/dist/timeline/rail/live.js +49 -0
  213. package/dist/timeline/rail/made-pictures.js +48 -0
  214. package/dist/timeline/rail/mcp-card.js +307 -0
  215. package/dist/timeline/rail/model.js +1317 -0
  216. package/dist/timeline/rail/page.js +167 -0
  217. package/dist/timeline/rail/passes.js +106 -0
  218. package/dist/timeline/rail/regions.js +26 -0
  219. package/dist/timeline/rail/send-back.js +154 -0
  220. package/dist/timeline/rail/stop-status.js +164 -0
  221. package/dist/timeline/read-signal.js +743 -0
  222. package/dist/timeline/render/claimed.js +13 -0
  223. package/dist/timeline/render/fallback.js +36 -0
  224. package/dist/timeline/render/pdf-helper.js +71 -0
  225. package/dist/timeline/render/pdf.js +410 -0
  226. package/dist/timeline/render/pixel-pages.js +168 -0
  227. package/dist/timeline/render/png-crop.js +281 -0
  228. package/dist/timeline/render/registry.js +7 -0
  229. package/dist/timeline/render/text.js +366 -0
  230. package/dist/timeline/render/types.js +1 -0
  231. package/dist/timeline/render/view-v1.js +148 -0
  232. package/dist/timeline/render/whole.js +6 -0
  233. package/dist/timeline/rollout-failures.js +40 -0
  234. package/dist/timeline/runs.js +836 -0
  235. package/dist/timeline/stored-image.js +34 -0
  236. package/dist/timeline/subject-display.js +44 -0
  237. package/dist/timeline/timeline.js +1114 -0
  238. package/dist/timeline/write-signal.js +403 -0
  239. package/dist/tool-label.js +201 -0
  240. package/dist/tracking.js +87 -0
  241. package/dist/vendor/pdfjs/LICENSE +177 -0
  242. package/dist/vendor/pdfjs/pdf.min.mjs +27 -0
  243. package/dist/vendor/pdfjs/pdf.worker.min.mjs +27 -0
  244. package/package.json +66 -4
  245. package/public-kit/GUIDE.md +189 -0
  246. package/public-kit/README.md +10 -0
  247. package/public-kit/conformance/README.md +13 -0
  248. package/public-kit/conformance/cases/C1.json +12 -0
  249. package/public-kit/conformance/cases/C10.json +15 -0
  250. package/public-kit/conformance/cases/C11.json +16 -0
  251. package/public-kit/conformance/cases/C12.json +18 -0
  252. package/public-kit/conformance/cases/C13.json +23 -0
  253. package/public-kit/conformance/cases/C14.json +16 -0
  254. package/public-kit/conformance/cases/C16.json +15 -0
  255. package/public-kit/conformance/cases/C17.json +25 -0
  256. package/public-kit/conformance/cases/C2.json +13 -0
  257. package/public-kit/conformance/cases/C3.json +44 -0
  258. package/public-kit/conformance/cases/C4.json +13 -0
  259. package/public-kit/conformance/cases/C5.json +16 -0
  260. package/public-kit/conformance/cases/C6.json +58 -0
  261. package/public-kit/conformance/generate-large.mjs +15 -0
  262. package/public-kit/examples/toy-export/cocheck-connector.json +10 -0
  263. package/public-kit/examples/toy-export/connector.mjs +28 -0
  264. package/public-kit/examples/toy-helpers/cocheck-connector.json +10 -0
  265. package/public-kit/examples/toy-helpers/connector.mjs +69 -0
  266. package/public-kit/examples/toy-level-1/cocheck-connector.json +10 -0
  267. package/public-kit/examples/toy-level-1/connector.mjs +61 -0
  268. package/public-kit/examples/toy-level-3/cocheck-connector.json +10 -0
  269. package/public-kit/examples/toy-level-3/connector.mjs +82 -0
  270. package/public-kit/examples/toy-tracker/cocheck-connector.json +14 -0
  271. package/public-kit/examples/toy-tracker/connector.mjs +46 -0
  272. package/public-kit/examples/toy-tracker/samples/history.json +10 -0
  273. package/public-kit/examples/toy-tracker/samples/samples.json +7 -0
  274. package/public-kit/examples/toy-vendor/cocheck-connector.json +15 -0
  275. package/public-kit/examples/toy-vendor/connector.mjs +62 -0
  276. package/public-kit/helpers/pdf-text-layout.d.mts +35 -0
  277. package/public-kit/helpers/pdf-text-layout.mjs +602 -0
  278. package/public-kit/helpers/pdf-text.d.mts +56 -0
  279. package/public-kit/helpers/pdf-text.mjs +375 -0
  280. package/public-kit/helpers/pdf.d.mts +61 -0
  281. package/public-kit/helpers/pdf.mjs +251 -0
  282. package/public-kit/helpers/png.d.mts +15 -0
  283. package/public-kit/helpers/png.mjs +88 -0
  284. package/public-kit/helpers/spec.d.mts +4 -0
  285. package/public-kit/helpers/spec.mjs +2 -0
  286. package/public-kit/scaffold/README.md +23 -0
  287. package/public-kit/scaffold/template/README.md +13 -0
  288. package/public-kit/scaffold/template/cocheck-connector.json +10 -0
  289. package/public-kit/scaffold/template/connector.mjs +50 -0
  290. package/public-kit/spec/README.md +408 -0
  291. package/public-kit/spec/v1.md +598 -0
  292. package/public-kit/toy-product/README.md +7 -0
  293. package/public-kit/toy-product/notes-store.mjs +30 -0
  294. package/public-kit/toy-product/states/create.after.json +16 -0
  295. package/public-kit/toy-product/states/create.before.json +12 -0
  296. package/public-kit/toy-product/states/delete.after.json +8 -0
  297. package/public-kit/toy-product/states/delete.before.json +12 -0
  298. package/public-kit/toy-product/states/edit.after.json +12 -0
  299. package/public-kit/toy-product/states/edit.before.json +12 -0
  300. package/public-kit/toy-product/states/malformed.after.json +1 -0
  301. package/public-kit/toy-product/states/malformed.before.json +12 -0
  302. package/public-kit/toy-product/states/no-change.after.json +12 -0
  303. package/public-kit/toy-product/states/no-change.before.json +12 -0
  304. package/scripts/hook-launch.mjs +58 -0
  305. package/scripts/hook-launch.sh +52 -0
@@ -0,0 +1,836 @@
1
+ // Requests, runs and CoCheck's reading, from the ledger record alone. Pure: ops and file_states rows in, plain data out.
2
+ // Nothing here knows a file format, a tool name or a particular run. Rules (spec of record):
3
+ // - The call is the atom. A call's target = the files named in its input plus the files whose state changed while it was
4
+ // open (a background call stays open until Stop by construction, so for it only the changes credited to it count; a change
5
+ // credited to another session's call is never this session's).
6
+ // - A request belongs to one session. A session's turn is everything up to its own Stop; the prompt ops logged inside that
7
+ // turn give its request text(s). Held prompts re-logged at another session's round close are the same request.
8
+ // - A run is a maximal stretch of consecutive calls in one session and one request. It ends at the first of: an observed
9
+ // change to a file in its target; a call with a non-empty target that shares nothing with the run's target so far; a new
10
+ // request; the end of the request. Calls with an empty target never start a run: they join the open run, or the next one.
11
+ // - Guideposts ("CoCheck's reading") come from these rules only. They never quote the agent and never set credit.
12
+ //
13
+ // Request order and lanes (the tests pin each):
14
+ // - A request's order is read under CoCheck's own names too: the prompt op's `requests: [{seq, at, firstStep}]`.
15
+ // - A call carries `startSeq` and `toolLabel`, when the record has them.
16
+ // - With a submit `seq` on every request text and a `startSeq` on every call, a call belongs to the last request submitted
17
+ // before it started, and calls and requests sort by those counters. Without them the time and step rules apply.
18
+ // - A subagent's calls (`agent_id` on the call op) belong to the request its first call belongs to, wherever they start, so a
19
+ // request submitted while an agent is still running never takes the agent's calls. A call with no agent id is never moved.
20
+ // - A run never mixes lanes: the main line and each subagent are cut into runs apart, and a request's runs are listed in
21
+ // the order their first calls started.
22
+ // - That holds across turns: the Stop that cut the ledger's turn does not decide it. An agent's calls that run on after a
23
+ // Stop stay with the request that launched it, not the prompt that wakes the session later.
24
+ import { pathKit } from "../paths.js";
25
+ import { reportsFailureEvents, toolNameOf } from "../hosts/index.js";
26
+ import { isLauncherTool } from "../credit-guard.js";
27
+ const EVIDENCE_KINDS = new Set(["result", "interrupted", "turn", "blocked", "denied"]);
28
+ /** An op's `ended` ({at, kind}) when well formed, else null. */
29
+ function endedOf(v) {
30
+ const e = v;
31
+ return e !== null && typeof e === "object" && typeof e.at === "number" && Number.isFinite(e.at) && typeof e.kind === "string" && EVIDENCE_KINDS.has(e.kind) ? { at: e.at, kind: e.kind } : null;
32
+ }
33
+ const MODE = /^\s*(ANSWER|PLAN|EXECUTE|SURVEY|DEEP-DIVE|REMEMBER|IDEATE|CRITIQUE|DEBATE|TUTOR)\b[.:]?\s*/; // a mode label (and one "." or ":" right after it), not words
34
+ /** Text with at least one letter or digit; "." and "..." are not words. */
35
+ export const WORDY = /[\p{L}\p{N}]/u;
36
+ export const words = (t) => String(t ?? "").replace(MODE, "").trim();
37
+ export const baseName = (p) => pathKit().baseName(String(p ?? ""));
38
+ const json = (v, d) => {
39
+ if (v == null || v === "")
40
+ return d;
41
+ if (typeof v !== "string")
42
+ return v;
43
+ try {
44
+ return JSON.parse(v);
45
+ }
46
+ catch {
47
+ return d;
48
+ }
49
+ };
50
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
51
+ const pl = (n, w, ws = w + "s") => `${n} ${n === 1 ? w : ws}`;
52
+ const listOf = (xs, max = 3) => {
53
+ const a = [...xs];
54
+ if (a.length > max)
55
+ return `${a.slice(0, max).join(", ")} and ${a.length - max} more`;
56
+ return a.length <= 1 ? a.join("") : `${a.slice(0, -1).join(", ")} and ${a.at(-1)}`;
57
+ };
58
+ // A host whose profile says it sends a failure event for a failed call (`capabilities.failureEvent`): a call it closes with none succeeded.
59
+ // Any host whose record holds a failed call also counts.
60
+ const NOTE = / \[(joint attribution|cells found)[^\]]*\]$/;
61
+ /** The rule version a run carries, so two days' timelines can be compared knowing whether the cut moved. */
62
+ export const RUN_RULE = "runs/1";
63
+ // The request's submit order, if the record carries it. CoCheck's own record is a list of `{seq, at, firstStep}` on the
64
+ // prompt op.
65
+ function readOrder(a, n) {
66
+ const none = () => Array.from({ length: n }, () => null);
67
+ const listed = Array.isArray(a.requests) ? a.requests : null;
68
+ if (listed && listed.length === n) {
69
+ const field = (k) => listed.map((q) => num(q?.[k]));
70
+ const seq = field("seq").map((s) => (s != null && s > 0 ? s : null));
71
+ return { seq, at: field("at"), step: field("firstStep") };
72
+ }
73
+ return { seq: none(), at: none(), step: none() };
74
+ }
75
+ /** A stored agent id or type: a non-empty string, else null (the call is on the main line). */
76
+ function plainId(v) {
77
+ return typeof v === "string" && v.trim() !== "" ? v : null;
78
+ }
79
+ /** Reads the stored label shape; anything else (a string, a stray object) is no label. */
80
+ function readToolLabel(raw) {
81
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
82
+ return null;
83
+ const r = raw;
84
+ const fields = {};
85
+ if (r.fields !== null && typeof r.fields === "object" && !Array.isArray(r.fields)) {
86
+ for (const [k, v] of Object.entries(r.fields)) {
87
+ if (typeof v === "string" && v.trim())
88
+ fields[k] = v.trim();
89
+ else if (Array.isArray(v)) {
90
+ const list = v.filter((x) => typeof x === "string" && x.trim() !== "").map((x) => x.trim());
91
+ if (list.length)
92
+ fields[k] = list;
93
+ }
94
+ }
95
+ }
96
+ const inputFields = Array.isArray(r.inputFields) ? r.inputFields.filter((x) => typeof x === "string") : undefined;
97
+ // Only the fact that a brief was withheld is kept (never a value), so the page can say so.
98
+ const droppedRaw = r.dropped !== null && typeof r.dropped === "object" && !Array.isArray(r.dropped) ? r.dropped : undefined;
99
+ // A withheld message, content or summary is said so too (the reason only, never a value).
100
+ const droppedKept = {};
101
+ for (const k of ["prompt", "message", "content", "summary"])
102
+ if (typeof droppedRaw?.[k] === "string")
103
+ droppedKept[k] = droppedRaw[k].slice(0, 200);
104
+ const dropped = Object.keys(droppedKept).length > 0 ? droppedKept : undefined;
105
+ // The way back for a withheld field (family, hash, locator), kept as stored: strings only, never a value.
106
+ const withheldRaw = r.withheld !== null && typeof r.withheld === "object" && !Array.isArray(r.withheld) ? r.withheld : undefined;
107
+ const withheld = {};
108
+ for (const [k, v] of Object.entries(withheldRaw ?? {})) {
109
+ const w = v;
110
+ if (w === null || typeof w !== "object" || typeof w.family !== "string" || typeof w.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(w.sha256))
111
+ continue;
112
+ const loc = w.locator;
113
+ withheld[k] = { family: w.family.slice(0, 40), sha256: w.sha256, ...(loc !== null && typeof loc === "object" && typeof loc.file === "string" && typeof loc.id === "string" ? { locator: { file: loc.file, id: loc.id } } : {}) };
114
+ }
115
+ if (Object.keys(fields).length === 0 && !inputFields?.length && !dropped)
116
+ return null;
117
+ return { fields, ...(inputFields?.length ? { inputFields } : {}), ...(dropped ? { dropped } : {}), ...(Object.keys(withheld).length > 0 ? { withheld } : {}) };
118
+ }
119
+ // ---- wakes ----
120
+ const WAKE_START = "<task-notification>";
121
+ const WAKE_END = "</task-notification>";
122
+ const PLAIN_ID = /^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}$/;
123
+ /** One block's head (its own top level, before any `<result>` or `<usage>`): the tool-use id, the status word and the summary. Null when it has no plain tool-use id. */
124
+ function parseHead(head) {
125
+ const id = /<tool-use-id>([^<]*)<\/tool-use-id>/.exec(head)?.[1]?.trim();
126
+ if (id === undefined || !PLAIN_ID.test(id))
127
+ return null;
128
+ const task = /<task-id>([^<]*)<\/task-id>/.exec(head)?.[1]?.trim();
129
+ const status = /<status>\s*([A-Za-z_-]{1,20})\s*<\/status>/.exec(head)?.[1] ?? null;
130
+ const summary = /<summary>([\s\S]*?)<\/summary>/.exec(head)?.[1]?.trim() ?? null;
131
+ return { toolUseId: id, taskId: task !== undefined && PLAIN_ID.test(task) ? task : null, status, summary: summary === "" ? null : summary };
132
+ }
133
+ /**
134
+ * Parses a wake prompt as a sequence of top-level blocks (docs/timeline.md, "Background agent wakes"). Null when the prompt does not start
135
+ * with a block. A block opens at the start of the prompt or right after the previous block's closing tag (whitespace between). Its head is
136
+ * everything up to the first `<result>`, `<usage>` or closing tag; fields are read from the head only. After a `<result>`/`<usage>` the rest
137
+ * is an opaque span: opening tags in it count up; a closing tag preceded by `</result>` or `</usage>` counts down, or, at depth 0, ends the
138
+ * block. A closing tag preceded by anything else is content. If the span never balances, the block runs to the end of the prompt. Text after the last block is `rest`.
139
+ */
140
+ export function parseBlocks(text) {
141
+ if (!text.startsWith(WAKE_START))
142
+ return null;
143
+ const blocks = [];
144
+ let pos = 0;
145
+ for (;;) {
146
+ const bodyStart = pos + WAKE_START.length;
147
+ const ends = [text.indexOf("<result>", bodyStart), text.indexOf("<usage>", bodyStart), text.indexOf(WAKE_END, bodyStart)].filter((i) => i >= 0);
148
+ const headEnd = ends.length ? Math.min(...ends) : text.length;
149
+ blocks.push(parseHead(text.slice(bodyStart, headEnd)));
150
+ let end = text.length;
151
+ if (text.startsWith(WAKE_END, headEnd))
152
+ end = headEnd + WAKE_END.length;
153
+ else if (headEnd < text.length) {
154
+ let depth = 0;
155
+ for (const m of text.slice(headEnd).matchAll(/<task-notification>|<\/task-notification>/g)) {
156
+ if (m[0] === WAKE_START)
157
+ depth++;
158
+ else if (/<\/(result|usage)>\s*$/.test(text.slice(0, headEnd + m.index))) {
159
+ if (depth === 0) {
160
+ end = headEnd + m.index + WAKE_END.length;
161
+ break;
162
+ }
163
+ depth--;
164
+ }
165
+ }
166
+ }
167
+ const tail = text.slice(end).trimStart();
168
+ if (tail.startsWith(WAKE_START)) {
169
+ pos = text.length - tail.length;
170
+ continue;
171
+ }
172
+ return { blocks, rest: tail.trim() };
173
+ }
174
+ }
175
+ /**
176
+ * Marks the prompt texts that are wakes. A text is parsed into its top-level blocks (`parseBlocks`); it must start with a block. Each block
177
+ * needs a launcher call in its own session (a call of the Agent, Task or SendMessage tool, or one an agent's calls name as their launcher) to be a wake of
178
+ * its own; a block that fails that is dropped, and its text is shown nowhere. A text with no valid block stays a request, whole. When a wake
179
+ * prompt has text after its last block, that text becomes a request of its own (same stamp) and the block text is never shown.
180
+ */
181
+ function markWakes(events, calls) {
182
+ const named = new Set();
183
+ for (const c of calls.values())
184
+ if (c.agentId !== null && c.launchId !== null)
185
+ named.add(c.session + "\u0000" + c.launchId);
186
+ for (const e of events) {
187
+ if (e.type !== "prompt")
188
+ continue;
189
+ const out = [];
190
+ for (const t of e.texts) {
191
+ out.push(t);
192
+ const parsed = parseBlocks(t.text);
193
+ if (parsed === null)
194
+ continue;
195
+ const wakes = [];
196
+ for (const w of parsed.blocks) {
197
+ if (w === null)
198
+ continue;
199
+ const launcher = calls.get(w.toolUseId);
200
+ if (launcher === undefined || launcher.session !== e.session)
201
+ continue;
202
+ if (!(isLauncherTool(launcher.tool) || launcher.tool === "SendMessage" || named.has(launcher.session + "\u0000" + launcher.id)))
203
+ continue;
204
+ const agent = [...calls.values()].filter((c) => c.session === e.session && c.agentId !== null && c.launchId === w.toolUseId).sort((x, y) => (x.startSeq ?? Infinity) - (y.startSeq ?? Infinity) || x.firstOp - y.firstOp)[0];
205
+ // A SendMessage that resumed an agent is no Agent call, so no agent carries its id; the notification's task id names the agent.
206
+ const woken = agent?.agentId ?? (launcher.tool === "SendMessage" ? w.taskId : null);
207
+ wakes.push({ session: e.session, seq: t.seq, at: t.at, toolUseId: w.toolUseId, launcher, agentId: woken, status: w.status, summary: w.summary });
208
+ }
209
+ if (wakes.length === 0)
210
+ continue;
211
+ t.wakes = wakes;
212
+ if (parsed.rest !== "")
213
+ out.push({ text: parsed.rest, seq: t.seq, at: t.at, step: t.step });
214
+ }
215
+ e.texts = out;
216
+ }
217
+ }
218
+ // ---- the record, normalised ----
219
+ /** An Agent or Task call whose input says `run_in_background: true` is a background launch (the meta-file case is read in agent-transcripts.ts). */
220
+ function launchedInBackground(tool, input) {
221
+ return (tool === "Agent" || tool === "Task") && typeof input === "object" && input !== null && input.run_in_background === true;
222
+ }
223
+ export function readRecord(ops, fileStates) {
224
+ const calls = new Map();
225
+ const events = []; // in op order
226
+ const firstSteps = new Map();
227
+ for (const o of [...ops].sort((x, y) => x.id - y.id)) {
228
+ const a = o.args ?? json(o.args_json, {});
229
+ const session = typeof a.session_id === "string" ? a.session_id : null;
230
+ if (a.hookEvent === "RequestFirstStep") {
231
+ // A request written at its round's first call is told its first step by this op, once the step exists.
232
+ for (const q of Array.isArray(a.requests) ? a.requests : []) {
233
+ const seq = num(q?.seq);
234
+ const step = num(q?.firstStep);
235
+ if (seq != null && seq > 0 && step != null)
236
+ firstSteps.set(seq, step);
237
+ }
238
+ continue;
239
+ }
240
+ if (a.hookEvent === "UserPromptSubmit") {
241
+ const texts = (a.prompts ?? []).map(String);
242
+ const order = readOrder(a, texts.length);
243
+ events.push({
244
+ type: "prompt",
245
+ opId: o.id,
246
+ session,
247
+ texts: texts.map((t, i) => ({ text: t, seq: order.seq[i] ?? null, at: order.at[i] ?? null, step: order.step[i] ?? null })),
248
+ earlier: num(a.earlier) ?? 0,
249
+ });
250
+ continue;
251
+ }
252
+ if (a.hookEvent === "SubagentStop") {
253
+ const agentId = plainId(a.agent_id);
254
+ if (agentId === null)
255
+ continue;
256
+ const f = (a.finish ?? {});
257
+ events.push({ type: "finish", opId: o.id, session, seq: num(a.seq), at: num(a.at), agentId, agentType: plainId(a.agent_type), text: typeof f.text === "string" && f.text.trim() !== "" ? f.text : null, host: typeof a.host === "string" ? a.host : null });
258
+ continue;
259
+ }
260
+ if (a.hookEvent === "TrackingStopped") {
261
+ events.push({ type: "trackstop", opId: o.id, session, at: num(a.at) });
262
+ continue;
263
+ }
264
+ if (a.hookEvent === "Stop") {
265
+ events.push({ type: "stop", opId: o.id, session, at: num(a.at), closing: a.closing ?? null, host: typeof a.host === "string" ? a.host : null });
266
+ continue;
267
+ }
268
+ if (typeof a.lateNarrationFor === "string") {
269
+ // Words that reached the host's file after the call closed. They fill a call that has none; words the call has are never replaced.
270
+ const late = calls.get(a.lateNarrationFor);
271
+ const n = a.narration;
272
+ if (late !== undefined && late.narration?.source !== "agent" && n?.source === "agent")
273
+ late.narration = n;
274
+ continue;
275
+ }
276
+ if (!a.tool_use_id)
277
+ continue;
278
+ const id = String(a.tool_use_id);
279
+ let c = calls.get(id);
280
+ if (!c) {
281
+ const description = String(a.description ?? "").trim();
282
+ let command = String(o.intent ?? "").replace(NOTE, "").replace(NOTE, "");
283
+ if (description && command.endsWith(" - " + description))
284
+ command = command.slice(0, -(description.length + 3));
285
+ const label = readToolLabel(a.toolLabel);
286
+ // A record stored before its host's tool names were separated at ingest is read by the tool's own name too.
287
+ const reported = typeof a.tool_name === "string" ? a.tool_name : (o.tool ?? null);
288
+ const tool = reported === null ? null : toolNameOf(typeof a.host === "string" ? a.host : null, reported);
289
+ c = {
290
+ id,
291
+ session,
292
+ host: typeof a.host === "string" ? a.host : null,
293
+ tool,
294
+ description,
295
+ command,
296
+ openedAt: num(a.openedAt),
297
+ closedAt: num(a.closedAt),
298
+ closedBy: typeof a.closedBy === "string" ? a.closedBy : null,
299
+ error: a.closedBy === "failure" && typeof a.error === "string" && a.error !== "" ? a.error : null,
300
+ errorInferred: a.closedBy === "failure" && a.errorInferred === true,
301
+ background: a.background === true || launchedInBackground(tool, a.tool_input ?? a.toolInput ?? a.input),
302
+ ...(a.waits === true ? { waits: true } : {}),
303
+ ended: endedOf(a.ended),
304
+ narration: a.narration ?? null,
305
+ input: a.tool_input ?? a.toolInput ?? a.input ?? null,
306
+ toolLabel: label,
307
+ startSeq: num(a.startSeq),
308
+ agentId: plainId(a.agent_id),
309
+ agentType: plainId(a.agent_type),
310
+ launchId: plainId(a.launch_tool_use_id),
311
+ named: new Set(a.namedFiles ?? []),
312
+ stepIds: new Set(),
313
+ opIds: [],
314
+ firstOp: o.id,
315
+ };
316
+ calls.set(id, c);
317
+ events.push({ type: "call", opId: o.id, session, call: c });
318
+ }
319
+ if (c.ended === null)
320
+ c.ended = endedOf(a.ended);
321
+ if (a.closedBy === "failure") {
322
+ c.closedBy = "failure";
323
+ if (typeof a.error === "string" && a.error !== "")
324
+ c.error = a.error;
325
+ if (a.errorInferred === true)
326
+ c.errorInferred = true;
327
+ }
328
+ else if (a.closedBy === "post" && c.closedBy === "expiry") {
329
+ // The Post came after expiry closed the call; the host's word replaces the expiry outcome.
330
+ c.closedBy = "post";
331
+ c.closedAt = num(a.closedAt) ?? c.closedAt;
332
+ }
333
+ for (const f of a.namedFiles ?? [])
334
+ c.named.add(f);
335
+ for (const s of a.steps ?? [])
336
+ c.stepIds.add(s);
337
+ if (Array.isArray(a.sameBytesRewrites)) {
338
+ const more = a.sameBytesRewrites.filter((x) => typeof x === "string");
339
+ if (more.length > 0)
340
+ c.rewrote = [...new Set([...(c.rewrote ?? []), ...more])];
341
+ }
342
+ c.opIds.push(o.id);
343
+ }
344
+ // A parallel call's words are its sibling's: `sameAs` names the first call of the same host message, so the sibling must be in the
345
+ // same session and the same lane (main line or agent) and must hold words of its own. Anything else keeps the call without words.
346
+ for (const c of calls.values()) {
347
+ const n = c.narration;
348
+ if (n?.source !== "agent" || n.sameAs === undefined || n.text !== undefined)
349
+ continue;
350
+ const from = calls.get(n.sameAs);
351
+ const t = from?.narration;
352
+ if (from === undefined || from === c || from.session !== c.session || from.agentId !== c.agentId || t?.source !== "agent" || t.text === undefined)
353
+ continue;
354
+ c.narration = { source: "agent", ...(t.label === undefined ? {} : { label: t.label }), text: t.text, sameAs: n.sameAs };
355
+ }
356
+ // Each agent's first call in a session heads its lane. An agent id with no agent type still has a lane; a call with no agent id never does.
357
+ const heads = new Map();
358
+ for (const c of [...calls.values()].sort((x, y) => (x.startSeq ?? Infinity) - (y.startSeq ?? Infinity) || x.firstOp - y.firstOp)) {
359
+ if (c.agentId === null)
360
+ continue;
361
+ const key = `${c.session}\u0000${c.agentId}`;
362
+ const head = heads.get(key);
363
+ if (head === undefined)
364
+ heads.set(key, c);
365
+ else
366
+ c.laneHead = head;
367
+ }
368
+ // A lane's launcher is the call named by the first launch id any of its calls carries. The lane's calls are placed by it
369
+ // (through the launcher's own anchor when the launcher is itself an agent's call); with none in the record, by the lane head.
370
+ const launchers = new Map();
371
+ for (const c of [...calls.values()].sort((x, y) => (x.startSeq ?? Infinity) - (y.startSeq ?? Infinity) || x.firstOp - y.firstOp)) {
372
+ if (c.agentId === null || c.launchId === null)
373
+ continue;
374
+ const key = `${c.session}\u0000${c.agentId}`;
375
+ const found = calls.get(c.launchId);
376
+ if (!launchers.has(key) && found && found.session === c.session && found.agentId !== c.agentId)
377
+ launchers.set(key, found);
378
+ }
379
+ markWakes(events, calls);
380
+ for (const c of calls.values())
381
+ if (c.agentId !== null) {
382
+ const l = launchers.get(`${c.session}\u0000${c.agentId}`);
383
+ if (l !== undefined)
384
+ c.launcherCall = l;
385
+ }
386
+ // An agent resumed by a SendMessage does its later work for the request that sent it. The recipient is the SendMessage's own `to`
387
+ // when the record holds its input, else the task id of the notification that SendMessage launched.
388
+ const resumes = new Map();
389
+ const noteResume = (session, agentId, send) => {
390
+ if (agentId === null)
391
+ return;
392
+ const key = `${session}\u0000${agentId}`;
393
+ const list = resumes.get(key) ?? [];
394
+ if (!list.includes(send))
395
+ resumes.set(key, [...list, send]);
396
+ };
397
+ for (const c of calls.values()) {
398
+ const to = c.tool === "SendMessage" && typeof c.input === "object" && c.input !== null ? plainId(c.input.to) : null;
399
+ noteResume(c.session, to, c);
400
+ }
401
+ for (const e of events)
402
+ if (e.type === "prompt")
403
+ for (const t of e.texts)
404
+ for (const w of t.wakes ?? [])
405
+ if (w.launcher.tool === "SendMessage")
406
+ noteResume(w.session, w.agentId, w.launcher);
407
+ const startedBefore = (a, b) => {
408
+ if (a.startSeq != null && b.startSeq != null)
409
+ return a.startSeq < b.startSeq;
410
+ if (a.openedAt != null && b.openedAt != null && a.openedAt !== b.openedAt)
411
+ return a.openedAt < b.openedAt;
412
+ return a.firstOp < b.firstOp;
413
+ };
414
+ const anchorOf = (c, depth = 0) => {
415
+ if (c.agentId === null || depth > 8)
416
+ return c;
417
+ const via = launchers.get(`${c.session}\u0000${c.agentId}`) ?? c.laneHead;
418
+ return via === undefined || via === c ? c : anchorOf(via, depth + 1);
419
+ };
420
+ for (const c of calls.values())
421
+ if (c.agentId !== null) {
422
+ const a = anchorOf(c);
423
+ if (a !== c)
424
+ c.placeBy = a;
425
+ const sent = (resumes.get(`${c.session}\u0000${c.agentId}`) ?? []).filter((s) => s !== c && startedBefore(s, c)).sort((x, y) => (startedBefore(x, y) ? 1 : -1))[0];
426
+ if (sent !== undefined) {
427
+ c.resumedBy = sent;
428
+ c.placeBy = anchorOf(sent);
429
+ }
430
+ }
431
+ const firstStep = Math.min(...fileStates.map((s) => s.step_id ?? s.id), Infinity);
432
+ const states = [...fileStates]
433
+ .sort((a, b) => a.id - b.id)
434
+ .map((s) => {
435
+ const credited = json(s.credited_json, []);
436
+ const open = json(s.calls_open_json, []);
437
+ // The baseline (every file copied at the task's first event) is not a change; any other state is one (a new file included).
438
+ const baseline = !s.prev_sha256 && !credited.length && (s.step_id ?? s.id) === firstStep;
439
+ return { ...s, credited, open, change: !baseline };
440
+ });
441
+ if (firstSteps.size > 0) {
442
+ for (const e of events) {
443
+ if (e.type !== "prompt")
444
+ continue;
445
+ for (const t of e.texts)
446
+ if (t.step == null && t.seq != null && firstSteps.has(t.seq))
447
+ t.step = firstSteps.get(t.seq);
448
+ }
449
+ }
450
+ return { calls, events, states };
451
+ }
452
+ // ---- requests ----
453
+ const timeOf = (c) => c.openedAt ?? c.closedAt;
454
+ function orderCalls(list) {
455
+ if (list.length > 0 && list.every((c) => c.startSeq != null))
456
+ return [...list].sort((a, b) => a.startSeq - b.startSeq || a.firstOp - b.firstOp);
457
+ const timed = list.every((c) => timeOf(c) != null);
458
+ return [...list].sort((a, b) => (timed ? timeOf(a) - timeOf(b) : 0) || a.firstOp - b.firstOp);
459
+ }
460
+ // Prompt ops inside one turn re-log the session's held prompts: the same texts, possibly with newer ones after them.
461
+ function mergeTexts(acc, texts) {
462
+ if (texts.every((t) => t.seq != null)) {
463
+ for (const t of texts)
464
+ if (!acc.some((x) => x.seq === t.seq))
465
+ acc.push(t);
466
+ return;
467
+ }
468
+ let k = Math.min(acc.length, texts.length);
469
+ for (; k > 0; k--)
470
+ if (acc.slice(-k).every((x, i) => x.text === texts[i].text))
471
+ break;
472
+ acc.push(...texts.slice(k));
473
+ }
474
+ // A session's requests when every request text carries its submit `seq` and every call its `startSeq`. A call belongs to the
475
+ // last request the session submitted before the call started, whichever Stop cut the ledger's turn around it: an agent's calls that
476
+ // run on after a Stop are written into the next turn's ops, and a prompt that wakes the session is stamped after they started, so the
477
+ // turn's ops alone would hand them to the wake. A call that started before the session's first request has none and sits in a
478
+ // request with no text. A turn's closing claim stays with the request its last prompt made (else its last call's). Null when the
479
+ // record lacks a stamp, which leaves the per-turn placement below.
480
+ function requestsBySeq(session, segs) {
481
+ const texts = [];
482
+ // A wake is not a request; it is kept apart, once per submit stamp (held prompts are re-logged).
483
+ const wakes = [];
484
+ for (const seg of segs) {
485
+ for (const p of seg.prompts) {
486
+ for (const t of p.texts) {
487
+ if (t.wakes) {
488
+ for (const w of t.wakes)
489
+ if (!wakes.some((x) => x.seq === w.seq && x.toolUseId === w.toolUseId))
490
+ wakes.push(w);
491
+ }
492
+ else if (t.text.trim() && !texts.some((x) => x.t.seq === t.seq))
493
+ texts.push({ t, opId: p.opId });
494
+ }
495
+ }
496
+ }
497
+ const calls = segs.flatMap((seg) => seg.calls);
498
+ if (texts.length === 0 || texts.some((x) => x.t.seq == null) || wakes.some((w) => w.seq == null) || calls.some((c) => c.startSeq == null))
499
+ return null;
500
+ texts.sort((a, b) => a.t.seq - b.t.seq);
501
+ wakes.sort((a, b) => a.seq - b.seq);
502
+ const mk = (t, opId) => ({ session, texts: t ? [t.text] : [], captured: t !== null, placement: "recorded", calls: [], closing: null, replies: [], finishes: [], wakes: [], firstOp: opId, anchor: t?.at ?? null, anchorSeq: t?.seq ?? null });
503
+ const orphan = mk(null, null);
504
+ const reqs = texts.map((x) => mk(x.t, x.opId));
505
+ const ownerOf = new Map();
506
+ for (const c of orderCalls(calls)) {
507
+ const at = (c.placeBy ?? c).startSeq;
508
+ let i = -1;
509
+ while (i + 1 < texts.length && texts[i + 1].t.seq < at)
510
+ i++;
511
+ let r = i < 0 ? orphan : reqs[i];
512
+ // Work after a wake (and before the next request) belongs to the request that owns the woken agent.
513
+ let j = -1;
514
+ while (j + 1 < wakes.length && wakes[j + 1].seq < at)
515
+ j++;
516
+ // Not for a helper's launch or work: those belong to the latest real request before the launching call, never to a notification.
517
+ const helperWork = c.agentId !== null || isLauncherTool(c.tool) || c.tool === "SendMessage";
518
+ if (!helperWork && j >= 0 && wakes[j].seq > (i < 0 ? Number.NEGATIVE_INFINITY : texts[i].t.seq))
519
+ r = ownerOf.get(wakes[j].launcher) ?? r;
520
+ r.calls.push(c);
521
+ r.firstOp = Math.min(r.firstOp ?? c.firstOp, c.firstOp);
522
+ ownerOf.set(c, r);
523
+ }
524
+ for (const w of wakes) {
525
+ // The request that owns the launcher call owns the wake; failing that, the one in force when the wake came.
526
+ let i = -1;
527
+ while (i + 1 < texts.length && texts[i + 1].t.seq < w.seq)
528
+ i++;
529
+ (ownerOf.get(w.launcher) ?? (i < 0 ? orphan : reqs[i])).wakes.push(w);
530
+ }
531
+ for (const seg of segs) {
532
+ const last = seg.prompts.flatMap((p) => p.texts).filter((t) => t.text.trim() && !t.wakes).at(-1);
533
+ const owner = last ? reqs[texts.findIndex((x) => x.t.seq === last.seq)] : ownerOf.get(seg.calls.at(-1));
534
+ if (owner && seg.stop)
535
+ keepReply(owner, seg.stop);
536
+ }
537
+ return orphan.calls.length > 0 || orphan.wakes.length > 0 ? [orphan, ...reqs] : reqs;
538
+ }
539
+ /** A turn's reply joins its request's replies (none is overwritten); `closing` stays the latest one. */
540
+ function keepReply(r, stop) {
541
+ r.closing = stop.closing;
542
+ if (stop.closing !== null)
543
+ r.replies.push({ closing: stop.closing, at: stop.at, host: stop.host });
544
+ }
545
+ function requestsOf(rec) {
546
+ const sessions = [...new Set(rec.events.map((e) => e.session))];
547
+ const out = [];
548
+ for (const session of sessions) {
549
+ const segs = [];
550
+ let cur = { calls: [], prompts: [], stop: null, firstOp: null };
551
+ for (const e of rec.events.filter((x) => x.session === session)) {
552
+ cur.firstOp ??= e.opId;
553
+ if (e.type === "call")
554
+ cur.calls.push(e.call);
555
+ else if (e.type === "prompt")
556
+ cur.prompts.push(e);
557
+ else if (e.type === "stop") {
558
+ cur.stop = e;
559
+ segs.push(cur);
560
+ cur = { calls: [], prompts: [], stop: null, firstOp: null };
561
+ }
562
+ }
563
+ if (cur.calls.length || cur.prompts.length)
564
+ segs.push(cur);
565
+ const placed = requestsBySeq(session, segs);
566
+ if (placed) {
567
+ out.push(...placed);
568
+ continue;
569
+ }
570
+ const mine = () => out.filter((r) => r.session === session);
571
+ const ownerOfWake = (w) => mine().find((r) => r.calls.includes(w.launcher)) ?? mine().at(-1);
572
+ for (const seg of segs) {
573
+ const texts = [];
574
+ const turnWakes = [];
575
+ for (const p of seg.prompts) {
576
+ mergeTexts(texts, p.texts.filter((t) => t.text.trim() && !t.wakes));
577
+ for (const t of p.texts)
578
+ for (const w of t.wakes ?? [])
579
+ if (!turnWakes.some((x) => x.seq === w.seq && x.toolUseId === w.toolUseId))
580
+ turnWakes.push(w);
581
+ }
582
+ const calls = orderCalls(seg.calls);
583
+ // A turn a wake opened has no request of its own: its calls and its closing belong to the request that owns the woken agent.
584
+ const woken = texts.length === 0 && turnWakes.length > 0 ? ownerOfWake(turnWakes[0]) : undefined;
585
+ if (woken) {
586
+ woken.calls = orderCalls([...woken.calls, ...calls]);
587
+ woken.wakes.push(...turnWakes);
588
+ if (seg.stop)
589
+ keepReply(woken, seg.stop);
590
+ continue;
591
+ }
592
+ if (!calls.length && !texts.length)
593
+ continue; // a chat-only Stop: no round, nothing to show
594
+ const mk = (ts, cs, placement) => ({ session, texts: ts.map((t) => t.text), captured: ts.length > 0, placement, calls: cs, closing: null, replies: [], finishes: [], wakes: [], firstOp: seg.firstOp, anchor: ts[0]?.at ?? null, anchorSeq: ts[0]?.seq ?? null });
595
+ const many = texts.length > 1;
596
+ const bySeq = many && texts.every((t) => t.seq != null) && calls.every((c) => c.startSeq != null);
597
+ const byAt = many && texts.every((t) => t.at != null);
598
+ const byStep = many && texts.every((t) => t.step != null);
599
+ let reqs;
600
+ if (bySeq || byAt || byStep) {
601
+ // Recorded order: each call goes to the last request submitted before it opened (or before its first step).
602
+ const key = (call) => {
603
+ const c = call.placeBy ?? call; // An agent's calls go where its launcher (else its first call) went
604
+ return bySeq ? c.startSeq : byAt ? c.openedAt : c.stepIds.size ? Math.min(...c.stepIds) : null;
605
+ };
606
+ const submitted = (t) => (bySeq ? t.seq : byAt ? t.at : t.step);
607
+ const groups = texts.map(() => []);
608
+ const groupOf = new Map();
609
+ const laneGroup = new Map();
610
+ let i = 0;
611
+ for (const c of calls) {
612
+ // An agent's call goes to the group of its launcher (else of its lane's first placed call), whatever the pointer
613
+ // has reached; the pointer moves for the other calls only.
614
+ const lane = c.agentId === null ? null : `${c.session}\u0000${c.agentId}`;
615
+ const fixed = c.placeBy !== undefined && groupOf.has(c.placeBy) ? groupOf.get(c.placeBy) : lane !== null ? laneGroup.get(lane) : undefined;
616
+ let g = fixed;
617
+ if (g === undefined) {
618
+ const k = key(c);
619
+ if (k != null)
620
+ while (i + 1 < texts.length && submitted(texts[i + 1]) <= k)
621
+ i++;
622
+ g = i;
623
+ }
624
+ if (lane !== null && !laneGroup.has(lane))
625
+ laneGroup.set(lane, g);
626
+ groupOf.set(c, g);
627
+ groups[g].push(c);
628
+ }
629
+ reqs = texts.map((t, j) => mk([t], groups[j], "recorded"));
630
+ }
631
+ else {
632
+ const anchored = texts.length === 1 && (texts[0].seq != null || texts[0].at != null || texts[0].step != null);
633
+ reqs = [mk(texts, calls, anchored ? "recorded" : "inferred")];
634
+ }
635
+ if (seg.stop)
636
+ keepReply(reqs.at(-1), seg.stop);
637
+ out.push(...reqs);
638
+ for (const w of turnWakes)
639
+ ownerOfWake(w)?.wakes.push(w);
640
+ }
641
+ }
642
+ // A helper's finish belongs to the request that owns the helper's calls; with none on record, to the latest request submitted
643
+ // before it (by seq, else by time), else the session's last.
644
+ for (const e of rec.events) {
645
+ if (e.type !== "finish")
646
+ continue;
647
+ const mine = out.filter((r) => r.session === e.session);
648
+ const own = mine.find((r) => r.calls.some((c) => c.agentId === e.agentId));
649
+ const before = (key, at) => (at === null ? undefined : mine.filter((r) => key(r) !== null && key(r) <= at).at(-1));
650
+ const owner = own ?? before((r) => r.anchorSeq, e.seq) ?? before((r) => r.anchor, e.at) ?? mine.at(-1);
651
+ owner?.finishes.push({ session: e.session, seq: e.seq, at: e.at, agentId: e.agentId, agentType: e.agentType, text: e.text, host: e.host });
652
+ }
653
+ // A tracking stop goes to the latest request of its session submitted (or started) before it, else the session's last.
654
+ for (const e of rec.events) {
655
+ if (e.type !== "trackstop")
656
+ continue;
657
+ const mine = out.filter((r) => r.session === e.session);
658
+ const started = (r) => r.anchor ?? r.calls[0]?.openedAt ?? null;
659
+ const owner = (e.at === null ? undefined : mine.filter((r) => started(r) !== null && started(r) <= e.at).at(-1)) ?? mine.at(-1);
660
+ if (owner)
661
+ (owner.trackingStops ??= []).push({ at: e.at });
662
+ }
663
+ const seqKey = (r) => r.anchorSeq ?? r.calls[0]?.startSeq ?? null;
664
+ const first = (r) => (r.calls[0] ? timeOf(r.calls[0]) : r.anchor);
665
+ if (out.length > 0 && out.every((r) => seqKey(r) != null))
666
+ out.sort((a, b) => seqKey(a) - seqKey(b) || a.firstOp - b.firstOp);
667
+ else {
668
+ const timed = out.every((r) => first(r) != null);
669
+ out.sort((a, b) => (timed ? first(a) - first(b) : 0) || a.firstOp - b.firstOp);
670
+ }
671
+ out.forEach((r, i) => {
672
+ r.index = i;
673
+ r.id = "r" + String(i + 1).padStart(3, "0");
674
+ });
675
+ return out;
676
+ }
677
+ // ---- runs ----
678
+ export function buildRuns(ops, fileStates) {
679
+ const rec = readRecord(ops, fileStates);
680
+ const requests = requestsOf(rec);
681
+ const changes = rec.states.filter((s) => s.change);
682
+ // What each call observed: the changes credited to it, plus (unless it runs in the background) those found while it was open.
683
+ const observed = new Map();
684
+ // A change credited to another session's call is that session's: runs never mix sessions, so it is not observed here.
685
+ const sessionOf = (id) => rec.calls.get(id)?.session;
686
+ const mine = (s, c) => !s.credited.length || s.credited.some((id) => sessionOf(id) === c.session);
687
+ for (const c of rec.calls.values())
688
+ observed.set(c.id, changes.filter((s) => s.credited.includes(c.id) || (!c.background && s.open.includes(c.id) && mine(s, c))));
689
+ const targetOf = (c) => new Set([...c.named, ...observed.get(c.id).map((s) => s.file_path)]);
690
+ const failsReported = (session) => [...rec.calls.values()].some((c) => c.session === session && ((c.closedBy === "failure" && !c.errorInferred) || reportsFailureEvents(c.host)));
691
+ const runs = [];
692
+ for (const r of requests) {
693
+ r.runs = [];
694
+ r.calls.forEach((c, k) => {
695
+ c.index = k + 1;
696
+ c.target = targetOf(c);
697
+ });
698
+ // One lane per agent id plus the main line; a run never mixes lanes. With no agent id in the record this is one pass.
699
+ const lanes = new Map();
700
+ for (const c of r.calls)
701
+ lanes.set(c.agentId, [...(lanes.get(c.agentId) ?? []), c]);
702
+ const made = [];
703
+ for (const laneCalls of lanes.values()) {
704
+ let run = null;
705
+ let pending = [];
706
+ const close = () => {
707
+ if (run)
708
+ made.push(run);
709
+ run = null;
710
+ };
711
+ const open = (first) => {
712
+ run = { request: r, session: r.session, calls: [...pending, first], target: new Set(), endsInChange: false };
713
+ pending = [];
714
+ };
715
+ for (const c of laneCalls) {
716
+ if (!c.target.size) {
717
+ if (run)
718
+ run.calls.push(c);
719
+ else
720
+ pending.push(c);
721
+ continue;
722
+ }
723
+ if (run && ![...c.target].some((f) => run.target.has(f)))
724
+ close();
725
+ if (run)
726
+ run.calls.push(c);
727
+ else
728
+ open(c);
729
+ const cur = run;
730
+ for (const f of c.target)
731
+ cur.target.add(f);
732
+ if (observed.get(c.id).some((s) => cur.target.has(s.file_path))) {
733
+ cur.endsInChange = true;
734
+ close();
735
+ }
736
+ }
737
+ close();
738
+ if (pending.length) {
739
+ run = { request: r, session: r.session, calls: pending, target: new Set(), endsInChange: false };
740
+ pending = [];
741
+ close();
742
+ }
743
+ }
744
+ made.sort((x, y) => x.calls[0].index - y.calls[0].index);
745
+ for (const run of made) {
746
+ r.runs.push(run);
747
+ runs.push(run);
748
+ }
749
+ }
750
+ // Changes per run, and the phase, which looks at the session's earlier and later runs.
751
+ for (const run of runs) {
752
+ run.changes = [];
753
+ for (const c of run.calls)
754
+ for (const s of observed.get(c.id))
755
+ if (!run.changes.some((x) => x.state === s))
756
+ run.changes.push({ state: s, call: c });
757
+ run.changed = new Set(run.changes.map((x) => x.state.file_path));
758
+ }
759
+ runs.forEach((run, i) => {
760
+ const same = runs.filter((x) => x.session === run.session);
761
+ const at = same.indexOf(run);
762
+ const before = same.slice(0, at);
763
+ const after = same.slice(at + 1);
764
+ const hits = (xs) => xs.some((x) => [...run.target].some((f) => x.changed.has(f)));
765
+ const onTarget = (c) => (c.target.size ? c.target : run.target);
766
+ const retried = run.calls.some((c, j) => c.closedBy === "failure" && run.calls.slice(j + 1).some((d) => d.target.size && [...onTarget(c)].some((f) => d.target.has(f))));
767
+ run.phase = run.endsInChange || run.changed.size ? "changing" : retried ? "failed and retrying" : hits(after) ? "trying" : hits(before) ? "checking" : "looking";
768
+ run.index = run.request.runs.indexOf(run);
769
+ run.id = "u" + String(i + 1).padStart(3, "0");
770
+ run.failuresReported = failsReported(run.session);
771
+ });
772
+ const sessions = [...new Set(requests.map((r) => r.session))];
773
+ for (const r of requests)
774
+ r.reading = readingOfRequest(r, requests, sessions);
775
+ for (const run of runs)
776
+ run.reading = readingOfRun(run, requests);
777
+ return { requests, runs, calls: rec.calls, states: rec.states, observed, sessions };
778
+ }
779
+ // ---- CoCheck's reading, in words ----
780
+ const sessionTag = (s) => (s == null ? "unknown session" : `session …${String(s).slice(-6)}`);
781
+ function readingOfRequest(r, requests, sessions) {
782
+ return {
783
+ position: `request ${r.index + 1} of ${requests.length}`,
784
+ session: sessions.length > 1 ? sessionTag(r.session) : null,
785
+ placement: r.placement === "recorded" ? "placed by its recorded submit order" : "placed before its first run (inferred: the record carries no submit order)",
786
+ texts: r.texts.length > 1 && r.placement === "inferred" ? `${r.texts.length} requests sent in one turn; the record does not say which calls answer which, so they are shown together` : null,
787
+ };
788
+ }
789
+ function readingOfRun(run, requests) {
790
+ const r = run.request;
791
+ const N = r.calls.length;
792
+ const k0 = run.calls[0].index;
793
+ const k1 = run.calls.at(-1).index;
794
+ const position = `request ${r.index + 1} of ${requests.length}, run ${run.index + 1} of ${r.runs.length}, ${k0 === k1 ? `call ${k0}` : `calls ${k0}–${k1}`} of ${N}`;
795
+ const onTarget = run.calls.filter((c) => c.target.size);
796
+ const lookups = run.calls.length - onTarget.length;
797
+ const named = [...new Set(run.calls.flatMap((c) => [...c.named]))].map(baseName);
798
+ const tail = lookups ? ` and ${pl(lookups, "lookup")}` : "";
799
+ let caption = named.length
800
+ ? `worked on ${listOf([...new Set(named)])} across ${pl(onTarget.length, "call")}${tail}`
801
+ : `the agent didn't name what it was working on (${onTarget.length ? pl(onTarget.length, "call") + tail : pl(lookups, "lookup")})`;
802
+ const firsts = new Map(); // file -> first call index that observed its change
803
+ for (const x of run.changes) {
804
+ const f = x.state.file_path;
805
+ if (!firsts.has(f) || x.call.index < firsts.get(f))
806
+ firsts.set(f, x.call.index);
807
+ }
808
+ const byCall = new Map();
809
+ for (const [f, k] of firsts) {
810
+ if (!byCall.has(k))
811
+ byCall.set(k, []);
812
+ byCall.get(k).push(baseName(f));
813
+ }
814
+ for (const [k, fs] of [...byCall].sort((a, b) => a[0] - b[0]))
815
+ caption += `; ${listOf(fs)} first changed at call ${k}`;
816
+ if (!firsts.size)
817
+ caption += "; no file changed";
818
+ const failed = onTarget.filter((c) => c.closedBy === "failure").length;
819
+ const attempts = !onTarget.length
820
+ ? "no call on a target"
821
+ : run.failuresReported
822
+ ? `${pl(onTarget.length, "call")} on the target, ${failed} failed`
823
+ : `${pl(onTarget.length, "call")} on the target; this host doesn't report failures`;
824
+ return { position, phase: run.phase, caption: caption[0].toUpperCase() + caption.slice(1), attempts, lookups, failed: run.failuresReported ? failed : null };
825
+ }
826
+ // The agent's own words recorded within a run, in call order, and each call's fallback label.
827
+ export function wordsOfRun(run) {
828
+ const out = [];
829
+ for (const c of run.calls) {
830
+ const t = c.narration?.source === "agent" ? words(c.narration.text) : "";
831
+ if (t && WORDY.test(t) && out.at(-1)?.text !== t)
832
+ out.push({ call: c.index, text: t });
833
+ }
834
+ return out;
835
+ }
836
+ export const labelOf = (c) => c.description || c.command || c.tool || "call";