@agent-watch-ai/edge 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (309) hide show
  1. package/CHANGELOG.md +288 -9
  2. package/README.md +307 -5
  3. package/dist/billing/billing-mode.d.ts +37 -5
  4. package/dist/billing/billing-mode.js +28 -19
  5. package/dist/billing/constants/billing.constants.d.ts +0 -2
  6. package/dist/billing/constants/billing.constants.js +0 -2
  7. package/dist/billing/index.d.ts +2 -1
  8. package/dist/billing/index.js +1 -1
  9. package/dist/billing/session-billing.d.ts +7 -3
  10. package/dist/billing/session-billing.js +34 -13
  11. package/dist/billing/types/billing.types.d.ts +7 -0
  12. package/dist/capture/capture-env.d.ts +147 -0
  13. package/dist/capture/capture-env.js +301 -0
  14. package/dist/capture/captured-step.d.ts +88 -0
  15. package/dist/capture/captured-step.js +503 -0
  16. package/dist/capture/constants/capture.constants.d.ts +85 -0
  17. package/dist/capture/constants/capture.constants.js +87 -0
  18. package/dist/capture/launched-runs.d.ts +43 -0
  19. package/dist/capture/launched-runs.js +157 -0
  20. package/dist/capture/node.cjs +697 -0
  21. package/dist/capture/node.d.cts +32 -0
  22. package/dist/capture/python/sitecustomize.py +832 -0
  23. package/dist/capture/schemas/capture.schema.d.ts +35 -0
  24. package/dist/capture/schemas/capture.schema.js +31 -0
  25. package/dist/capture/types/capture.types.d.ts +20 -0
  26. package/dist/capture/venv-loader.d.ts +68 -0
  27. package/dist/capture/venv-loader.js +189 -0
  28. package/dist/cli/constants/cli.constants.d.ts +23 -6
  29. package/dist/cli/constants/cli.constants.js +24 -7
  30. package/dist/cli/context.d.ts +19 -22
  31. package/dist/cli/context.js +23 -54
  32. package/dist/cli/doctor-run-capture.d.ts +21 -0
  33. package/dist/cli/doctor-run-capture.js +33 -0
  34. package/dist/cli/doctor.js +21 -68
  35. package/dist/cli/hook-check.d.ts +7 -2
  36. package/dist/cli/hook-check.js +30 -15
  37. package/dist/cli/hook.d.ts +14 -0
  38. package/dist/cli/hook.js +82 -1
  39. package/dist/cli/index.d.ts +1 -1
  40. package/dist/cli/index.js +1 -1
  41. package/dist/cli/misc.js +10 -2
  42. package/dist/cli/npm-global.d.ts +24 -0
  43. package/dist/cli/npm-global.js +77 -0
  44. package/dist/cli/npx-install.js +22 -6
  45. package/dist/cli/replay.d.ts +33 -0
  46. package/dist/cli/replay.js +228 -0
  47. package/dist/cli/setup.d.ts +10 -2
  48. package/dist/cli/setup.js +200 -31
  49. package/dist/cli/status.js +45 -5
  50. package/dist/cli/toggle.js +10 -0
  51. package/dist/cli/types/cli.types.d.ts +15 -1
  52. package/dist/cli/uninstall.js +42 -23
  53. package/dist/cli/update.js +3 -2
  54. package/dist/cli.js +104 -17
  55. package/dist/config/config-store.d.ts +15 -4
  56. package/dist/config/config-store.js +31 -7
  57. package/dist/config/config.d.ts +0 -2
  58. package/dist/config/config.js +0 -1
  59. package/dist/config/constants/config.constants.d.ts +8 -1
  60. package/dist/config/constants/config.constants.js +10 -1
  61. package/dist/config/events-transport.d.ts +15 -0
  62. package/dist/config/events-transport.js +29 -0
  63. package/dist/config/index.d.ts +2 -1
  64. package/dist/config/index.js +1 -0
  65. package/dist/config/root-config.d.ts +12 -0
  66. package/dist/config/root-config.js +24 -0
  67. package/dist/config/schemas/config.schema.d.ts +15 -2
  68. package/dist/config/schemas/config.schema.js +52 -8
  69. package/dist/config/types/config.types.d.ts +7 -0
  70. package/dist/core/index.d.ts +1 -1
  71. package/dist/core/index.js +1 -1
  72. package/dist/core/version.d.ts +9 -0
  73. package/dist/core/version.js +14 -0
  74. package/dist/core/which.d.ts +11 -0
  75. package/dist/core/which.js +18 -0
  76. package/dist/credentials/cloud-claim.d.ts +34 -0
  77. package/dist/credentials/cloud-claim.js +61 -0
  78. package/dist/credentials/constants/credentials.constants.d.ts +16 -1
  79. package/dist/credentials/constants/credentials.constants.js +17 -2
  80. package/dist/credentials/credential-status.js +1 -1
  81. package/dist/credentials/credentials.d.ts +3 -3
  82. package/dist/credentials/credentials.js +26 -12
  83. package/dist/credentials/device-api.d.ts +15 -1
  84. package/dist/credentials/device-api.js +12 -1
  85. package/dist/credentials/identity.d.ts +2 -2
  86. package/dist/credentials/identity.js +2 -2
  87. package/dist/credentials/install-key.d.ts +31 -0
  88. package/dist/credentials/install-key.js +58 -0
  89. package/dist/credentials/migration.d.ts +9 -7
  90. package/dist/credentials/migration.js +58 -18
  91. package/dist/credentials/secret-store.d.ts +12 -0
  92. package/dist/credentials/secret-store.js +18 -1
  93. package/dist/credentials/sign-in.d.ts +27 -0
  94. package/dist/credentials/sign-in.js +31 -1
  95. package/dist/credentials/token-refresher.d.ts +5 -1
  96. package/dist/credentials/token-refresher.js +10 -2
  97. package/dist/enforcement/enforcement.js +1 -1
  98. package/dist/events/constants/events.constants.d.ts +5 -2
  99. package/dist/events/constants/events.constants.js +4 -1
  100. package/dist/events/enrich.d.ts +14 -0
  101. package/dist/events/enrich.js +1 -1
  102. package/dist/events/index.d.ts +1 -0
  103. package/dist/events/product-event.d.ts +6 -3
  104. package/dist/events/types/events.types.d.ts +6 -0
  105. package/dist/events/types/replay-progress.types.d.ts +26 -0
  106. package/dist/events/types/replay-progress.types.js +1 -0
  107. package/dist/events/types/repo-tree.types.d.ts +2 -1
  108. package/dist/feature/ticket-candidates.d.ts +1 -1
  109. package/dist/git/checkout-root.d.ts +15 -0
  110. package/dist/git/checkout-root.js +18 -0
  111. package/dist/git/code-state.d.ts +2 -16
  112. package/dist/git/code-state.js +11 -12
  113. package/dist/git/constants/git.constants.d.ts +33 -11
  114. package/dist/git/constants/git.constants.js +45 -12
  115. package/dist/git/fingerprint.d.ts +3 -6
  116. package/dist/git/fingerprint.js +5 -8
  117. package/dist/git/git-context.js +5 -1
  118. package/dist/git/index.d.ts +1 -2
  119. package/dist/git/index.js +1 -1
  120. package/dist/git/repo-snapshot.d.ts +13 -4
  121. package/dist/git/repo-snapshot.js +53 -9
  122. package/dist/git/types/snapshot.types.d.ts +6 -0
  123. package/dist/pipeline/constants/pipeline.constants.d.ts +3 -0
  124. package/dist/pipeline/constants/pipeline.constants.js +3 -0
  125. package/dist/pipeline/hook-pipeline.js +82 -57
  126. package/dist/privacy/product-capture.js +2 -0
  127. package/dist/providers/antigravity/antigravity.capture.d.ts +2 -0
  128. package/dist/providers/antigravity/antigravity.capture.js +5 -0
  129. package/dist/providers/antigravity/antigravity.detect.js +8 -22
  130. package/dist/providers/antigravity/antigravity.provider.js +10 -3
  131. package/dist/providers/antigravity/constants/antigravity.constants.d.ts +1 -0
  132. package/dist/providers/antigravity/constants/antigravity.constants.js +1 -0
  133. package/dist/providers/claude/claude.adapter.js +9 -6
  134. package/dist/providers/claude/claude.detect.js +2 -17
  135. package/dist/providers/claude/claude.otel.d.ts +21 -3
  136. package/dist/providers/claude/claude.otel.js +216 -61
  137. package/dist/providers/claude/claude.provider.js +21 -1
  138. package/dist/providers/claude/claude.version.d.ts +9 -0
  139. package/dist/providers/claude/claude.version.js +28 -0
  140. package/dist/providers/claude/constants/claude.constants.d.ts +27 -0
  141. package/dist/providers/claude/constants/claude.constants.js +27 -0
  142. package/dist/providers/claude/constants/claude.otel.constants.d.ts +27 -0
  143. package/dist/providers/claude/constants/claude.otel.constants.js +45 -5
  144. package/dist/providers/claude/types/claude.types.d.ts +13 -0
  145. package/dist/providers/codex/codex.capture.d.ts +76 -0
  146. package/dist/providers/codex/codex.capture.js +454 -0
  147. package/dist/providers/codex/codex.detect.js +2 -4
  148. package/dist/providers/codex/codex.otel.d.ts +38 -2
  149. package/dist/providers/codex/codex.otel.js +50 -6
  150. package/dist/providers/codex/codex.provider.js +8 -0
  151. package/dist/providers/codex/codex.surface.d.ts +9 -0
  152. package/dist/{turns/codex-originator.js → providers/codex/codex.surface.js} +17 -3
  153. package/dist/providers/codex/codex.titles.d.ts +14 -0
  154. package/dist/providers/codex/codex.titles.js +35 -0
  155. package/dist/providers/codex/constants/codex.constants.d.ts +4 -0
  156. package/dist/providers/codex/constants/codex.constants.js +4 -0
  157. package/dist/providers/cursor/constants/cursor.constants.d.ts +17 -4
  158. package/dist/providers/cursor/constants/cursor.constants.js +25 -5
  159. package/dist/providers/cursor/cursor-mcp-memo.d.ts +34 -0
  160. package/dist/providers/cursor/cursor-mcp-memo.js +94 -0
  161. package/dist/providers/cursor/cursor.adapter.js +20 -82
  162. package/dist/providers/cursor/cursor.capture.d.ts +1 -0
  163. package/dist/providers/cursor/cursor.capture.js +4 -0
  164. package/dist/providers/cursor/cursor.detect.d.ts +5 -1
  165. package/dist/providers/cursor/cursor.detect.js +11 -26
  166. package/dist/providers/cursor/cursor.hooks.js +2 -2
  167. package/dist/providers/cursor/cursor.provider.js +16 -7
  168. package/dist/providers/cursor/cursor.titles.d.ts +14 -0
  169. package/dist/providers/cursor/cursor.titles.js +20 -0
  170. package/dist/providers/cursor/schemas/cursor.schema.d.ts +3 -3
  171. package/dist/providers/cursor/schemas/cursor.schema.js +5 -3
  172. package/dist/providers/gemini/constants/gemini.constants.d.ts +16 -0
  173. package/dist/providers/gemini/constants/gemini.constants.js +17 -0
  174. package/dist/providers/gemini/gemini.capture.d.ts +81 -0
  175. package/dist/providers/gemini/gemini.capture.js +210 -0
  176. package/dist/providers/gemini/gemini.detect.js +57 -24
  177. package/dist/providers/gemini/gemini.otel.d.ts +38 -2
  178. package/dist/providers/gemini/gemini.otel.js +56 -125
  179. package/dist/providers/gemini/gemini.provider.js +5 -0
  180. package/dist/providers/index.d.ts +1 -0
  181. package/dist/providers/index.js +1 -0
  182. package/dist/providers/provider.d.ts +8 -0
  183. package/dist/providers/provider.js +9 -0
  184. package/dist/providers/registry.d.ts +14 -0
  185. package/dist/providers/registry.js +14 -0
  186. package/dist/providers/shared/constants/hook-config.constants.d.ts +2 -0
  187. package/dist/providers/shared/constants/hook-config.constants.js +2 -0
  188. package/dist/providers/shared/constants/terminal-capture.constants.d.ts +6 -0
  189. package/dist/providers/shared/constants/terminal-capture.constants.js +6 -0
  190. package/dist/providers/shared/editor-paths.d.ts +8 -0
  191. package/dist/providers/shared/editor-paths.js +18 -0
  192. package/dist/providers/shared/hook-config.d.ts +5 -0
  193. package/dist/providers/shared/hook-config.js +39 -1
  194. package/dist/providers/shared/hooks-marker.d.ts +14 -0
  195. package/dist/providers/shared/hooks-marker.js +23 -0
  196. package/dist/providers/shared/install-record.d.ts +29 -0
  197. package/dist/providers/shared/install-record.js +52 -0
  198. package/dist/providers/shared/session-title-store.d.ts +23 -0
  199. package/dist/providers/shared/session-title-store.js +50 -0
  200. package/dist/providers/shared/terminal-capture.d.ts +41 -0
  201. package/dist/providers/shared/terminal-capture.js +109 -0
  202. package/dist/providers/shared/tooling.d.ts +21 -0
  203. package/dist/providers/shared/tooling.js +36 -1
  204. package/dist/providers/types/provider.types.d.ts +57 -4
  205. package/dist/replay/checkout-resolver.d.ts +56 -0
  206. package/dist/replay/checkout-resolver.js +173 -0
  207. package/dist/replay/codex-turns.d.ts +24 -0
  208. package/dist/replay/codex-turns.js +221 -0
  209. package/dist/replay/constants/replay.constants.d.ts +99 -0
  210. package/dist/replay/constants/replay.constants.js +102 -0
  211. package/dist/replay/describe.d.ts +10 -0
  212. package/dist/replay/describe.js +31 -0
  213. package/dist/replay/gemini-turns.d.ts +36 -0
  214. package/dist/replay/gemini-turns.js +192 -0
  215. package/dist/replay/machine.d.ts +34 -0
  216. package/dist/replay/machine.js +68 -0
  217. package/dist/replay/progress-event.d.ts +21 -0
  218. package/dist/replay/progress-event.js +45 -0
  219. package/dist/replay/replay-runner.d.ts +60 -0
  220. package/dist/replay/replay-runner.js +581 -0
  221. package/dist/replay/replay-scan.d.ts +84 -0
  222. package/dist/replay/replay-scan.js +182 -0
  223. package/dist/replay/replay-state.d.ts +108 -0
  224. package/dist/replay/replay-state.js +199 -0
  225. package/dist/replay/resume.d.ts +18 -0
  226. package/dist/replay/resume.js +34 -0
  227. package/dist/replay/start.d.ts +23 -0
  228. package/dist/replay/start.js +39 -0
  229. package/dist/replay/throttle.d.ts +36 -0
  230. package/dist/replay/throttle.js +44 -0
  231. package/dist/replay/transcript-turns.d.ts +35 -0
  232. package/dist/replay/transcript-turns.js +241 -0
  233. package/dist/replay/turn-event.d.ts +40 -0
  234. package/dist/replay/turn-event.js +127 -0
  235. package/dist/replay/types/replay.types.d.ts +198 -0
  236. package/dist/replay/types/replay.types.js +1 -0
  237. package/dist/replay/window.d.ts +28 -0
  238. package/dist/replay/window.js +41 -0
  239. package/dist/replay/worktree-map.d.ts +42 -0
  240. package/dist/replay/worktree-map.js +134 -0
  241. package/dist/snapshot/branch-selection.d.ts +40 -23
  242. package/dist/snapshot/branch-selection.js +71 -41
  243. package/dist/snapshot/constants/snapshot-stages.constants.d.ts +3 -1
  244. package/dist/snapshot/constants/snapshot-stages.constants.js +3 -1
  245. package/dist/snapshot/constants/snapshot.constants.d.ts +34 -7
  246. package/dist/snapshot/constants/snapshot.constants.js +34 -7
  247. package/dist/snapshot/index.d.ts +2 -2
  248. package/dist/snapshot/index.js +1 -1
  249. package/dist/snapshot/snapshot-pipeline.js +100 -26
  250. package/dist/snapshot/snapshot-state.js +6 -2
  251. package/dist/snapshot/tree-pipeline.d.ts +1 -1
  252. package/dist/snapshot/tree-pipeline.js +34 -15
  253. package/dist/snapshot/types/snapshot.types.d.ts +22 -3
  254. package/dist/storage/schemas/storage.schema.d.ts +2 -0
  255. package/dist/storage/schemas/storage.schema.js +6 -0
  256. package/dist/transport/delivery-stats.d.ts +13 -1
  257. package/dist/transport/delivery-stats.js +18 -2
  258. package/dist/transport/delivery.d.ts +4 -3
  259. package/dist/transport/delivery.js +21 -7
  260. package/dist/transport/identity-delivery.d.ts +20 -0
  261. package/dist/transport/identity-delivery.js +41 -0
  262. package/dist/transport/index.d.ts +2 -0
  263. package/dist/transport/index.js +1 -0
  264. package/dist/transport/types/delivery-flow.types.d.ts +7 -0
  265. package/dist/turns/claude-transcript.js +4 -12
  266. package/dist/turns/codex-transcript.d.ts +9 -0
  267. package/dist/turns/codex-transcript.js +27 -19
  268. package/dist/turns/constants/turns.constants.d.ts +29 -12
  269. package/dist/turns/constants/turns.constants.js +31 -19
  270. package/dist/turns/gemini-transcript.d.ts +19 -1
  271. package/dist/turns/gemini-transcript.js +29 -18
  272. package/dist/turns/index.d.ts +3 -4
  273. package/dist/turns/index.js +2 -3
  274. package/dist/turns/run-state.d.ts +71 -0
  275. package/dist/turns/run-state.js +114 -0
  276. package/dist/turns/tool-events.d.ts +11 -1
  277. package/dist/turns/tool-events.js +32 -9
  278. package/dist/turns/transcript.d.ts +15 -14
  279. package/dist/turns/transcript.js +23 -4
  280. package/dist/turns/turn-state.d.ts +82 -7
  281. package/dist/turns/turn-state.js +157 -10
  282. package/dist/turns/turn-summary.js +7 -2
  283. package/dist/turns/turn-tracker.d.ts +9 -16
  284. package/dist/turns/turn-tracker.js +163 -87
  285. package/dist/turns/types/transcript.types.d.ts +11 -1
  286. package/dist/turns/types/turn-provider.types.d.ts +33 -0
  287. package/dist/turns/types/turn-provider.types.js +1 -0
  288. package/dist/turns/types/turn-state.types.d.ts +9 -0
  289. package/dist/turns/types/turn-summary.types.d.ts +17 -1
  290. package/dist/turns/types/turn-tracker.types.d.ts +3 -1
  291. package/dist/turns/work-checkout.js +1 -2
  292. package/docs/AUDIT_PROMPT.md +10 -0
  293. package/docs/DATA_HANDLING.md +201 -13
  294. package/docs/ENTERPRISE_DEPLOYMENT.md +3 -3
  295. package/docs/PERFORMANCE.md +10 -0
  296. package/package.json +3 -2
  297. package/dist/events/canonical-event.d.ts +0 -10
  298. package/dist/events/canonical-event.js +0 -9
  299. package/dist/git/repository-root.d.ts +0 -39
  300. package/dist/git/repository-root.js +0 -131
  301. package/dist/git/types/repository-root.types.d.ts +0 -11
  302. package/dist/transport/transport.d.ts +0 -6
  303. package/dist/turns/codex-originator.d.ts +0 -11
  304. package/dist/turns/cursor-transcript.d.ts +0 -21
  305. package/dist/turns/cursor-transcript.js +0 -66
  306. package/dist/turns/native-session-titles.d.ts +0 -26
  307. package/dist/turns/native-session-titles.js +0 -102
  308. /package/dist/{git/types/repository-root.types.js → billing/types/billing.types.js} +0 -0
  309. /package/dist/{transport/transport.js → capture/types/capture.types.js} +0 -0
@@ -0,0 +1,60 @@
1
+ import type { ReplayPorts, ReplayRecord, ReplayWindow } from './types/replay.types.js';
2
+ /** What a run of `agentwatch replay` ended as. */
3
+ export type ReplayOutcome = 'done' | 'paused' | 'stopped' | 'skipped' | 'failed';
4
+ /** What a dry run counted, in place of sending. */
5
+ export interface ReplayDryCounts {
6
+ readonly files: number;
7
+ /** The cheap pre-count the progress bar's total is made from. */
8
+ readonly estimate: number;
9
+ /** The turns the run built. */
10
+ readonly turns: number;
11
+ readonly repositories: number;
12
+ /** Files and built turns per agent. */
13
+ readonly agents: Readonly<Record<string, {
14
+ readonly files: number;
15
+ readonly turns: number;
16
+ }>>;
17
+ }
18
+ /** The end of a run, and a sentence for the person who started it. */
19
+ export interface ReplayResult {
20
+ readonly outcome: ReplayOutcome;
21
+ readonly message: string;
22
+ readonly record?: ReplayRecord;
23
+ readonly dry?: ReplayDryCounts;
24
+ }
25
+ /** What a run was asked to do. */
26
+ export interface ReplayRequest {
27
+ readonly days: number;
28
+ /** Operator-only historical window. Automatic replay never supplies one. */
29
+ readonly window?: ReplayWindow;
30
+ readonly resume: boolean;
31
+ /** Build every record and count it; send nothing, write nothing. */
32
+ readonly dryRun: boolean;
33
+ /** Setup's start: never repeat an earlier replay attempt for this identity. */
34
+ readonly skipIfExisting: boolean;
35
+ }
36
+ /**
37
+ * Replay a developer's earlier Claude Code, Codex and Gemini CLI sessions to the backend, slowly.
38
+ *
39
+ * In order: decide whether to begin, continue or leave an earlier replay;
40
+ * count the window's transcripts; send their turns newest first in small
41
+ * batches, each preceded by a look at the machine; send one snapshot per
42
+ * repository; end with a final progress record. A crash or a `--stop` leaves a
43
+ * checkpoint per finished file, and every turn is idempotent downstream, so a
44
+ * rerun costs bandwidth, never correctness.
45
+ *
46
+ * @param ports - The machine, the identity and the transport, handed in.
47
+ * @param request - What was asked.
48
+ * @returns How it ended.
49
+ */
50
+ export declare function runReplay(ports: ReplayPorts, request: ReplayRequest): Promise<ReplayResult>;
51
+ /**
52
+ * `agentwatch replay --stop`: end the replay, wherever it is running.
53
+ *
54
+ * A running replay notices the written state at its next write and reports
55
+ * its own end; one that is not running is ended and reported here.
56
+ *
57
+ * @param ports - The machine.
58
+ * @returns What happened.
59
+ */
60
+ export declare function stopReplay(ports: ReplayPorts): Promise<ReplayResult>;
@@ -0,0 +1,581 @@
1
+ import crypto from 'node:crypto';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { isDisabled } from '../storage/disabled.js';
5
+ import { debugLog } from '../core/logger.js';
6
+ import { repositoryIdentity, runGit } from '../git/git-context.js';
7
+ import { CANONICAL_PROVIDER_NAMES } from '../otlp/constants/otlp.constants.js';
8
+ import { runSnapshotPipeline } from '../snapshot/snapshot-pipeline.js';
9
+ import { SnapshotStateStore } from '../snapshot/snapshot-state.js';
10
+ import { runTreePipeline } from '../snapshot/tree-pipeline.js';
11
+ import { SNAPSHOT_BRANCH_COUNT } from '../snapshot/constants/snapshot.constants.js';
12
+ import { acquireLock } from '../storage/lock.js';
13
+ import { ANY_DESTINATION, AUTH_REJECTED_STATUSES } from '../transport/constants/transport.constants.js';
14
+ import { sendEvents } from '../transport/send.js';
15
+ import { PREPASS_PERSIST_EVERY, REPLAY_BATCH_INTERVAL_MS, REPLAY_BATCH_TURNS, REPLAY_FILE_PAUSE_MS, REPLAY_GIVE_UP_FAILURES, REPLAY_HEARTBEAT_MS, REPLAY_LIVE_TURN_GRACE_MS, REPLAY_NICE, REPLAY_PROGRESS_EVERY_BATCHES, REPLAY_RUN_BUDGET_MS, REPLAY_SNAPSHOT_BUDGET_MS } from './constants/replay.constants.js';
16
+ import { checkoutOfTurn, isEdit, markFilesOutsideCheckouts } from './checkout-resolver.js';
17
+ import { buildReplayProgress } from './progress-event.js';
18
+ import { countsByAgent, listSources, sourceOf } from './replay-scan.js';
19
+ import { decideStart, isRunning, readReplayRecord, setPending, writeReplayRecord } from './replay-state.js';
20
+ import { isWorthWaiting, nextBackoff, throttleVerdict } from './throttle.js';
21
+ import { buildReplayTurnEvent } from './turn-event.js';
22
+ import { firstOpenInstant, replayWindow } from './window.js';
23
+ /** The scan writes its state this often, not per file: the state holds a map of every transcript. */
24
+ const SCAN_PERSIST_EVERY = 20;
25
+ /**
26
+ * Replay a developer's earlier Claude Code, Codex and Gemini CLI sessions to the backend, slowly.
27
+ *
28
+ * In order: decide whether to begin, continue or leave an earlier replay;
29
+ * count the window's transcripts; send their turns newest first in small
30
+ * batches, each preceded by a look at the machine; send one snapshot per
31
+ * repository; end with a final progress record. A crash or a `--stop` leaves a
32
+ * checkpoint per finished file, and every turn is idempotent downstream, so a
33
+ * rerun costs bandwidth, never correctness.
34
+ *
35
+ * @param ports - The machine, the identity and the transport, handed in.
36
+ * @param request - What was asked.
37
+ * @returns How it ended.
38
+ */
39
+ export async function runReplay(ports, request) {
40
+ const claimed = request.dryRun ? { record: freshRecord(ports, request.days, request.window), fresh: true } : await claim(ports, request);
41
+ if ('result' in claimed)
42
+ return claimed.result;
43
+ lowerPriority();
44
+ return execute(ports, request, claimed.record, claimed.fresh);
45
+ }
46
+ /**
47
+ * Take the replay, under a short lock, so two starters (setup and a hook) cannot both run it.
48
+ *
49
+ * @param ports - The machine.
50
+ * @param request - What was asked.
51
+ * @returns The record to run and whether it is a new replay, or why not.
52
+ */
53
+ async function claim(ports, request) {
54
+ // In the identity's own state directory, not `locks/`: the throttle reads that directory's mtime as "a hook is working".
55
+ const release = await acquireLock(path.dirname(ports.stateFile), 'replay-start', ports.env.now);
56
+ if (!release)
57
+ return { result: { outcome: 'skipped', message: 'another replay is starting' } };
58
+ try {
59
+ const existing = await readReplayRecord(ports.stateFile);
60
+ const decision = decideStart(existing, { identity: ports.identity, resume: request.resume, skipIfExisting: request.skipIfExisting, nowMs: ports.env.now().getTime() }, ports.alive);
61
+ if (decision.action === 'skip')
62
+ return { result: { outcome: 'skipped', message: decision.message } };
63
+ const fresh = decision.action === 'fresh';
64
+ const record = fresh ? freshRecord(ports, request.days, request.window) : continuedRecord(decision.record, ports, request.window);
65
+ await writeReplayRecord(ports.stateFile, record);
66
+ await setPending(ports.stateFile, true);
67
+ return { record, fresh };
68
+ }
69
+ finally {
70
+ await release();
71
+ }
72
+ }
73
+ function freshRecord(ports, days, explicit) {
74
+ const now = ports.env.now();
75
+ const window = explicit ?? replayWindow(now, days);
76
+ const at = now.toISOString();
77
+ return {
78
+ operator: explicit !== undefined,
79
+ replayId: crypto.randomUUID(),
80
+ identity: ports.identity,
81
+ state: 'scanning',
82
+ windowStart: window.start.toISOString(),
83
+ windowEnd: window.end.toISOString(),
84
+ startedAt: at,
85
+ updatedAt: at,
86
+ pid: process.pid,
87
+ heartbeatAt: at,
88
+ turnsTotal: 0,
89
+ turnsSent: 0,
90
+ sessionsTotal: 0,
91
+ sessionsSent: 0,
92
+ batches: 0,
93
+ refused: 0,
94
+ snapshotted: [],
95
+ files: {},
96
+ agents: ports.sources.map((source) => source.agent)
97
+ };
98
+ }
99
+ /**
100
+ * An unfinished replay, taken over by this process.
101
+ *
102
+ * The window's start may only move later: the month can have turned since, and
103
+ * the open charge period with it.
104
+ *
105
+ * @param record - What the dead or stopped run left.
106
+ * @param ports - The machine.
107
+ * @returns The record, owned by this process.
108
+ */
109
+ function continuedRecord(record, ports, explicit) {
110
+ const now = ports.env.now();
111
+ // A hook resumes with no operator environment, so the record has to remember the window it was given.
112
+ const pinned = explicit ?? (record.operator === true ? { start: new Date(record.windowStart), end: new Date(record.windowEnd) } : undefined);
113
+ const start = pinned?.start.getTime() ?? Math.max(Date.parse(record.windowStart), firstOpenInstant(now).getTime());
114
+ const at = now.toISOString();
115
+ return { ...record, operator: pinned !== undefined, state: 'running', pause: undefined, windowStart: new Date(start).toISOString(), windowEnd: pinned?.end.toISOString() ?? at, updatedAt: at, pid: process.pid, heartbeatAt: at };
116
+ }
117
+ /** `nice` 19, so the operating system hands every other process the CPU first. Fails open: some systems refuse. */
118
+ function lowerPriority() {
119
+ try {
120
+ os.setPriority(0, REPLAY_NICE);
121
+ }
122
+ catch (error) {
123
+ debugLog('replay: could not lower its priority:', error);
124
+ }
125
+ }
126
+ /**
127
+ * Send a progress record for the replay's state.
128
+ *
129
+ * Never throws: a progress record is a courtesy. A terminal one that cannot be
130
+ * sent is kept in the offline queue, because the last word is the one the
131
+ * platform is waiting for.
132
+ *
133
+ * @param ports - The machine.
134
+ * @param record - The replay's state.
135
+ * @param terminal - Whether this is the last record of the run.
136
+ */
137
+ async function reportProgress(ports, record, terminal) {
138
+ try {
139
+ const event = buildReplayProgress(record, { developerId: ports.developerId, installationId: ports.installationId });
140
+ const transport = await ports.transport();
141
+ const result = transport ? await sendEvents(transport, [event]) : undefined;
142
+ if (!result?.ok && terminal)
143
+ await ports.queue.enqueue([event], transport?.destination ?? ANY_DESTINATION);
144
+ }
145
+ catch (error) {
146
+ debugLog('replay: progress record not sent:', error);
147
+ }
148
+ }
149
+ /**
150
+ * `agentwatch replay --stop`: end the replay, wherever it is running.
151
+ *
152
+ * A running replay notices the written state at its next write and reports
153
+ * its own end; one that is not running is ended and reported here.
154
+ *
155
+ * @param ports - The machine.
156
+ * @returns What happened.
157
+ */
158
+ export async function stopReplay(ports) {
159
+ const record = await readReplayRecord(ports.stateFile);
160
+ if (!record || record.identity !== ports.identity || record.state === 'done' || record.state === 'stopped')
161
+ return { outcome: 'skipped', message: 'no replay to stop' };
162
+ const running = isRunning(record, ports.env.now().getTime(), ports.alive);
163
+ const stopped = { ...record, state: 'stopped', pause: undefined, pid: running ? record.pid : undefined, updatedAt: ports.env.now().toISOString() };
164
+ await writeReplayRecord(ports.stateFile, stopped);
165
+ if (!running) {
166
+ await setPending(ports.stateFile, false);
167
+ await reportProgress(ports, stopped, true);
168
+ }
169
+ return { outcome: 'stopped', message: running ? 'replay stopping' : 'replay stopped', record: stopped };
170
+ }
171
+ /**
172
+ * Why a gate that did not say go ends the run.
173
+ *
174
+ * @param gated - What the gate said.
175
+ * @returns The exit.
176
+ */
177
+ function exitOfGate(gated) {
178
+ if (gated === 'stop')
179
+ return 'stop';
180
+ return gated === 'budget' ? 'budget' : 'give-up';
181
+ }
182
+ /**
183
+ * The run itself. One closure holds the record, because everything it does is
184
+ * "change the record, write it, say so": `persist`, `report`, `nap`, `gate`.
185
+ */
186
+ async function execute(ports, request, start, fresh) {
187
+ const dry = request.dryRun;
188
+ const clock = () => ports.env.now().getTime();
189
+ const startedMs = clock();
190
+ const sinceMs = Date.parse(start.windowStart);
191
+ const capture = ports.config.capture;
192
+ let record = start;
193
+ let waitedMs = 0;
194
+ let stopRequested = false;
195
+ const persist = async (patch) => {
196
+ const at = ports.env.now().toISOString();
197
+ record = { ...record, ...patch, updatedAt: at, heartbeatAt: at };
198
+ if (dry)
199
+ return;
200
+ // A `--stop` written while this runs must not be written over.
201
+ const disk = await readReplayRecord(ports.stateFile);
202
+ if (disk?.replayId === record.replayId && disk.state === 'stopped' && record.state !== 'stopped') {
203
+ stopRequested = true;
204
+ return;
205
+ }
206
+ await writeReplayRecord(ports.stateFile, record);
207
+ };
208
+ const report = async (terminal) => {
209
+ if (!dry)
210
+ await reportProgress(ports, record, terminal);
211
+ };
212
+ /** Wait, in pieces short enough that the heartbeat never goes stale. `idle` waits do not count against the run's budget. */
213
+ const nap = async (ms, idle) => {
214
+ if (dry)
215
+ return;
216
+ for (let left = ms; left > 0; left -= REPLAY_HEARTBEAT_MS) {
217
+ const piece = Math.min(left, REPLAY_HEARTBEAT_MS);
218
+ await ports.sleep(piece);
219
+ waitedMs += idle ? piece : 0;
220
+ await persist({});
221
+ if (stopRequested)
222
+ return;
223
+ }
224
+ };
225
+ /** The machine's say-so before a batch: go, or wait it out and ask again. */
226
+ const gate = async () => {
227
+ if (dry)
228
+ return 'go';
229
+ for (;;) {
230
+ // `agentwatch off` ends it too: a disabled install sends nothing, replay included.
231
+ if (stopRequested || (await isDisabled(ports.paths)))
232
+ return 'stop';
233
+ if (clock() - startedMs - waitedMs >= REPLAY_RUN_BUDGET_MS)
234
+ return 'budget';
235
+ const transport = await ports.transport();
236
+ if (!transport)
237
+ return 'backend';
238
+ if (transport.destination && (await ports.authBlock.holds(transport.destination)))
239
+ return 'backend';
240
+ const verdict = (await ports.cooldown.active()) ? { go: false, pause: 'backend', waitMs: REPLAY_HEARTBEAT_MS } : throttleVerdict(await ports.machine(), record.operator === true);
241
+ if (verdict.go) {
242
+ if (record.state === 'paused') {
243
+ await persist({ state: 'running', pause: undefined });
244
+ await report(false);
245
+ }
246
+ return 'go';
247
+ }
248
+ if (record.state !== 'paused' || record.pause !== verdict.pause) {
249
+ await persist({ state: 'paused', pause: verdict.pause });
250
+ await report(false);
251
+ }
252
+ await nap(verdict.waitMs, true);
253
+ }
254
+ };
255
+ const giveUp = async (pause) => {
256
+ await persist({ state: 'paused', pause });
257
+ return 'give-up';
258
+ };
259
+ /** What a failed send means: an auth refusal ends the run, a hard refusal drops the batch, anything else is waited out. */
260
+ const refused = async (result, transport, count) => {
261
+ if (result.status !== undefined && AUTH_REJECTED_STATUSES.has(result.status)) {
262
+ if (transport.destination)
263
+ await ports.authBlock.raise(transport.destination, result.status, result.refusal);
264
+ return giveUp('backend');
265
+ }
266
+ if (isWorthWaiting(result.status, result.retryable))
267
+ return undefined;
268
+ // The backend said no and will say it again: do not wedge the whole replay on twenty turns.
269
+ await persist({ refused: record.refused + count });
270
+ ports.log(`the backend refused ${count} replayed turn(s) with HTTP ${result.status ?? '?'}; skipping them`);
271
+ return 'ok';
272
+ };
273
+ /** One batch to the backend, retried with backoff while the backend or the network is down. */
274
+ const send = async (events) => {
275
+ if (dry || events.length === 0)
276
+ return 'ok';
277
+ let backoff;
278
+ for (let failures = 1;; failures += 1) {
279
+ const gated = await gate();
280
+ if (gated === 'stop' || gated === 'budget')
281
+ return gated;
282
+ if (gated === 'backend')
283
+ return giveUp('backend');
284
+ const transport = (await ports.transport());
285
+ const result = await sendEvents(transport, events);
286
+ if (result.ok)
287
+ return 'ok';
288
+ const exit = await refused(result, transport, events.length);
289
+ if (exit)
290
+ return exit;
291
+ if (failures >= REPLAY_GIVE_UP_FAILURES)
292
+ return giveUp('backend');
293
+ backoff = nextBackoff(backoff);
294
+ debugLog(`replay: send failed (${result.status ?? 'network'}); waiting ${backoff} ms`);
295
+ if (record.pause !== 'backend') {
296
+ await persist({ state: 'paused', pause: 'backend' });
297
+ await report(false);
298
+ }
299
+ await nap(backoff, true);
300
+ }
301
+ };
302
+ const finish = async (exit, counts) => {
303
+ if (exit === 'stop') {
304
+ await persist({ state: 'stopped', pause: undefined, pid: undefined });
305
+ await setPending(ports.stateFile, false);
306
+ await report(true);
307
+ return { outcome: 'stopped', message: 'replay stopped', record };
308
+ }
309
+ if (exit === 'ok') {
310
+ await persist({ state: 'done', pause: undefined, pid: undefined, turnsTotal: record.turnsSent, sessionsTotal: record.sessionsSent });
311
+ if (!dry)
312
+ await setPending(ports.stateFile, false);
313
+ await report(true);
314
+ return { outcome: 'done', message: `replayed ${record.turnsSent} turns from ${record.sessionsSent} sessions`, record, dry: counts };
315
+ }
316
+ await persist({ state: 'paused', pause: exit === 'budget' ? 'budget' : (record.pause ?? 'backend'), pid: undefined });
317
+ await report(false);
318
+ return { outcome: 'paused', message: 'replay paused; it continues on the next agent session or with `agentwatch replay --resume`', record };
319
+ };
320
+ // 1. Count what there is.
321
+ if (fresh || Object.keys(record.files).length === 0) {
322
+ await report(false);
323
+ const found = await listSources(ports.sources, sinceMs);
324
+ const files = {};
325
+ let total = 0;
326
+ for (const [index, transcript] of found.entries()) {
327
+ const entry = { mtimeMs: transcript.mtimeMs, size: transcript.size, turns: 0, done: false, agent: transcript.agent };
328
+ const turns = (await sourceOf(ports.sources, entry)?.estimate(transcript.file, sinceMs)) ?? 0;
329
+ files[transcript.file] = { ...entry, turns };
330
+ total += turns;
331
+ if (index % SCAN_PERSIST_EVERY === 0)
332
+ await persist({ files: { ...files }, turnsTotal: total, sessionsTotal: found.length });
333
+ await nap(REPLAY_FILE_PAUSE_MS, false);
334
+ }
335
+ await persist({ files, turnsTotal: total, sessionsTotal: found.length });
336
+ }
337
+ await persist({ state: 'running', pause: undefined });
338
+ await report(false);
339
+ // 2. Send the turns, newest transcript first.
340
+ const pending = Object.entries(record.files)
341
+ .filter(([, entry]) => !entry.done)
342
+ .sort(([, a], [, b]) => b.mtimeMs - a.mtimeMs)
343
+ .map(([file]) => file);
344
+ const cutoffMs = Math.min(clock() - REPLAY_LIVE_TURN_GRACE_MS, Date.parse(record.windowEnd));
345
+ const seen = new Set();
346
+ // Seen repositories outlive a pause: a resumed leg reads only the files still pending, and the snapshot of a
347
+ // repository it never reads again must still force the branches an earlier leg saw.
348
+ const repositories = new Map(Object.entries(record.repositories ?? {}).map(([root, seen]) => [root, { ...seen, branches: new Set(seen.branches) }]));
349
+ const context = { developerId: ports.developerId, developerName: ports.developerName, installationId: ports.installationId, capture, billingMode: ports.billingMode };
350
+ let buffer = [];
351
+ let finished = [];
352
+ const sessionOfFile = new Map();
353
+ let built = 0;
354
+ const builtBy = new Map();
355
+ /** Send the buffer; every file read through to its end by now has all its turns in what has been sent. */
356
+ const flush = async () => {
357
+ const exit = await send(buffer);
358
+ if (exit !== 'ok')
359
+ return exit;
360
+ const files = { ...record.files };
361
+ for (const file of finished)
362
+ files[file] = { ...files[file], done: true, session: sessionOfFile.get(file) ?? files[file]?.session };
363
+ built += buffer.length;
364
+ await persist({
365
+ files,
366
+ turnsSent: record.turnsSent + (dry ? 0 : buffer.length),
367
+ // Distinct sessions: a resumed Codex session leaves one rollout file per resume. A file with no turn counts as its own.
368
+ sessionsSent: new Set(Object.entries(files).filter(([, entry]) => entry.done).map(([name, entry]) => entry.session ?? name)).size,
369
+ batches: record.batches + 1,
370
+ repositories: Object.fromEntries([...repositories].map(([root, seen]) => [root, { ...seen, branches: [...seen.branches] }]))
371
+ });
372
+ if (!dry && buffer.length > 0) {
373
+ if (record.batches % REPLAY_PROGRESS_EVERY_BATCHES === 0)
374
+ await report(false);
375
+ await nap(REPLAY_BATCH_INTERVAL_MS, false);
376
+ }
377
+ buffer = [];
378
+ finished = [];
379
+ return stopRequested ? 'stop' : 'ok';
380
+ };
381
+ // What each folder's transcripts say about it, read before sending: a folder that is gone (a
382
+ // review's temp tree) is known only by the Codex rollout that ran in it, and a Claude session
383
+ // in the same folder borrows that. Every file of the run is read, finished ones too, so the answer
384
+ // does not depend on where a resumed run paused. `knownRepos` maps a repository to a checkout of it
385
+ // the run has seen, only to find the capture file that narrows it. Scope is never decided from it:
386
+ // a folder that is gone belongs to a root by its path alone, as for the live hook.
387
+ const folders = new Map();
388
+ const knownRepos = new Map();
389
+ const carriedBySession = new Map();
390
+ const newestFirst = Object.entries(record.files).sort(([, x], [, y]) => y.mtimeMs - x.mtimeMs);
391
+ // Before anything is resolved: the resolver remembers its answers.
392
+ // A worktree another root's checkout made is that root's: learned here, its repository would be read and snapshotted.
393
+ // Over a long history this pass outlasts the stale-heartbeat limit, and a second replay would start beside it.
394
+ const beat = setInterval(() => void persist({}).catch(() => undefined), REPLAY_HEARTBEAT_MS);
395
+ try {
396
+ for (const source of ports.sources)
397
+ ports.learnWorktrees?.(((await source.worktreeAdds?.(() => stopRequested).catch(() => [])) ?? []).filter((entry) => ports.inScope(entry.main)));
398
+ }
399
+ finally {
400
+ clearInterval(beat);
401
+ }
402
+ await persist({});
403
+ if (stopRequested)
404
+ return finish('stop');
405
+ // `capture.git: false` skips the child-checkout scan: its git reads would serve only snapshots that never go.
406
+ for (const checkout of (capture.git === false ? [] : await ports.localCheckouts?.().catch(() => [])) ?? []) {
407
+ if (ports.inScope(checkout.root) && !knownRepos.has(checkout.repository))
408
+ knownRepos.set(checkout.repository, checkout.root);
409
+ }
410
+ for (const [index, [file, entry]] of newestFirst.entries()) {
411
+ // A long pass must still look alive, and still hear a `--stop`.
412
+ if (index % PREPASS_PERSIST_EVERY === 0)
413
+ await persist({});
414
+ if (stopRequested)
415
+ return finish('stop');
416
+ const id = await sourceOf(ports.sources, entry)
417
+ ?.identity?.(file)
418
+ .catch(() => undefined);
419
+ if (!id)
420
+ continue;
421
+ // The newest rollout that names a remote, whole: fields of two sessions are never mixed.
422
+ if (!folders.get(id.cwd)?.remote)
423
+ folders.set(id.cwd, id);
424
+ // Only this identity's folders: another root's are neither read nor told about.
425
+ const known = ports.inScope(id.cwd) ? await ports.checkout(id.cwd) : undefined;
426
+ if (known && !knownRepos.has(known.repository))
427
+ knownRepos.set(known.repository, known.root);
428
+ }
429
+ const withFolderIdentity = (turn) => {
430
+ const own = turn.cwd && !turn.remote ? folders.get(turn.cwd) : undefined;
431
+ return own ? { ...turn, remote: own.remote, commit: turn.branch ? undefined : own.commit, branch: turn.branch ?? own.branch } : turn;
432
+ };
433
+ /** The checkout of the repository a gone folder's transcript names, whose capture file narrows it. */
434
+ const rootOfRemote = (turn) => {
435
+ const remote = withFolderIdentity(turn).remote;
436
+ const repository = remote ? repositoryIdentity('', remote).remote : undefined;
437
+ return repository ? knownRepos.get(repository) : undefined;
438
+ };
439
+ for (const file of pending) {
440
+ const source = sourceOf(ports.sources, record.files[file]);
441
+ const billingMode = source?.billingMode ?? ports.billingMode;
442
+ try {
443
+ // A file of an agent this run has no source for (none should be) is read as empty and marked done.
444
+ for await (const turn of source?.read(file, capture.promptText === true) ?? []) {
445
+ const startedAt = Date.parse(turn.startedAt);
446
+ const endedAt = Date.parse(turn.endedAt);
447
+ if (startedAt < sinceMs || endedAt > cutoffMs || seen.has(turn.turnId))
448
+ continue;
449
+ if (turn.cwd && !ports.inScope(turn.cwd))
450
+ continue;
451
+ seen.add(turn.turnId);
452
+ // What a live hook in that folder would capture: a repository's own file may narrow it.
453
+ // A repository found some other way (a tool's file, a gone folder's remote) answers to its own checkout's file.
454
+ let turnCapture = turn.cwd ? await ports.captureFor(turn.cwd) : capture;
455
+ let checkout = turnCapture.git !== false ? await checkoutOfTurn(turn, ports.checkout, (found) => ports.inScope(found.root), carriedBySession.get(turn.sessionId)) : undefined;
456
+ if (checkout?.evidence === 'changed')
457
+ carriedBySession.set(turn.sessionId, checkout);
458
+ // ponytail: also learned as turns resolve, for Claude- and Gemini-only checkouts the pre-pass cannot see;
459
+ // a gone folder read before its repository is first seen answers to the global capture. Ceiling: a
460
+ // pre-pass over every transcript's folder; upgrade path: an `identity` on those sources.
461
+ if (checkout && !knownRepos.has(checkout.repository))
462
+ knownRepos.set(checkout.repository, checkout.gitRoot ?? checkout.root);
463
+ // Another folder's own capture file narrows the turn's, never widens it.
464
+ const otherRoot = checkout ? (checkout.gitRoot ?? (checkout.evidence && checkout.root)) : rootOfRemote(turn);
465
+ if (otherRoot)
466
+ turnCapture = narrower(turnCapture, await ports.captureFor(otherRoot));
467
+ if (turnCapture.git === false)
468
+ checkout = undefined;
469
+ sessionOfFile.set(file, turn.sessionId);
470
+ // A turn whose edits all lie in no checkout reports none (`checkoutOfTurn`), so it borrows no folder identity either.
471
+ const replayTurn = checkout || turn.tools.some(isEdit) ? turn : withFolderIdentity(turn);
472
+ const remoteRoot = checkout || turnCapture.git === false ? undefined : rootOfRemote(replayTurn);
473
+ const snapshotRoot = checkout?.gitRoot ?? checkout?.root ?? remoteRoot;
474
+ const repository = checkout?.repository ?? (replayTurn.remote ? repositoryIdentity('', replayTurn.remote).remote : undefined);
475
+ if (snapshotRoot && repository) {
476
+ const seenRepository = repositories.get(snapshotRoot) ?? {
477
+ repository,
478
+ sessionId: turn.sessionId,
479
+ surface: turn.surface ?? 'cli',
480
+ provider: turn.provider,
481
+ branches: new Set()
482
+ };
483
+ const sentBranch = checkout?.branch ?? (checkout?.evidence ? undefined : replayTurn.branch);
484
+ if (sentBranch)
485
+ seenRepository.branches.add(sentBranch);
486
+ repositories.set(snapshotRoot, seenRepository);
487
+ }
488
+ const placed = { ...replayTurn, tools: turnCapture.git !== false ? await markFilesOutsideCheckouts(replayTurn.tools, ports.checkout, ports.inScope) : replayTurn.tools };
489
+ buffer.push(buildReplayTurnEvent(placed, checkout, { ...context, capture: turnCapture, billingMode, home: ports.env.home }));
490
+ builtBy.set(turn.provider, (builtBy.get(turn.provider) ?? 0) + 1);
491
+ if (buffer.length < REPLAY_BATCH_TURNS)
492
+ continue;
493
+ const exit = await flush();
494
+ if (exit !== 'ok')
495
+ return finish(exit);
496
+ }
497
+ }
498
+ catch (error) {
499
+ // A transcript that cannot be read is skipped, not the replay.
500
+ debugLog('replay: skipped an unreadable transcript:', error);
501
+ }
502
+ finished.push(file);
503
+ if (!dry)
504
+ await ports.sleep(REPLAY_FILE_PAUSE_MS);
505
+ }
506
+ const last = await flush();
507
+ if (last !== 'ok')
508
+ return finish(last);
509
+ // 3. One snapshot per repository the turns ran in, at the end: they are what makes the branches known.
510
+ if (!dry && capture.git !== false) {
511
+ for (const [root, seenRepository] of repositories) {
512
+ if (record.snapshotted.includes(root))
513
+ continue;
514
+ const gated = await gate();
515
+ if (gated !== 'go')
516
+ return finish(exitOfGate(gated));
517
+ await snapshotOf(ports, root, seenRepository);
518
+ await persist({ snapshotted: [...record.snapshotted, root] });
519
+ await nap(REPLAY_FILE_PAUSE_MS, false);
520
+ }
521
+ }
522
+ return finish('ok', { files: pending.length, estimate: record.turnsTotal, turns: built, repositories: repositories.size, agents: countsByAgent(pending, record.files, builtBy) });
523
+ }
524
+ /**
525
+ * The snapshot, and tree, of one repository, then a drain so they leave now.
526
+ *
527
+ * Both are the hook path's own flows, with a longer deadline: no hook is
528
+ * waiting on this one. The queue holds them if the send fails.
529
+ *
530
+ * @param ports - The machine.
531
+ * @param root - The checkout root.
532
+ * @param seen - Which repository and session it was.
533
+ */
534
+ async function snapshotOf(ports, root, seen) {
535
+ try {
536
+ // The label a live turn of that agent carries: `claude-code` for Claude Code, as before.
537
+ const label = CANONICAL_PROVIDER_NAMES[seen.provider] ?? seen.provider;
538
+ const input = {
539
+ cwd: root,
540
+ files: (await ports.captureFor(root)).files !== false,
541
+ identity: ports.identity,
542
+ repository: seen.repository,
543
+ provider: label,
544
+ surface: seen.surface,
545
+ agentName: label,
546
+ developerId: ports.developerId,
547
+ installationId: ports.installationId,
548
+ sessionId: seen.sessionId,
549
+ capturedAt: ports.env.now().toISOString(),
550
+ // Real time, as the hook's: this bounds git subprocesses, which the wall clock times.
551
+ deadline: Date.now() + REPLAY_SNAPSHOT_BUDGET_MS,
552
+ run: runGit,
553
+ requiredBranches: [...seen.branches]
554
+ };
555
+ const store = new SnapshotStateStore(ports.paths.snapshotsDir);
556
+ const required = input.requiredBranches.length > 0 ? input.requiredBranches : [undefined];
557
+ for (let index = 0; index < required.length; index += SNAPSHOT_BRANCH_COUNT) {
558
+ const branches = required[0] === undefined ? [] : required.slice(index, index + SNAPSHOT_BRANCH_COUNT);
559
+ // Each group, and the tree, gets the whole budget: one deadline for all would leave the later groups none.
560
+ await runSnapshotPipeline({ input: { ...input, requiredBranches: branches, deadline: Date.now() + REPLAY_SNAPSHOT_BUDGET_MS }, store, queue: ports.queue });
561
+ }
562
+ if (input.files)
563
+ await runTreePipeline({ input: { ...input, deadline: Date.now() + REPLAY_SNAPSHOT_BUDGET_MS }, store, queue: ports.queue });
564
+ const transport = await ports.transport();
565
+ if (transport)
566
+ await ports.queue.drain(transport, ports.config.delivery.drainBatchSize, undefined, ports.authBlock);
567
+ }
568
+ catch (error) {
569
+ debugLog('replay: snapshot failed:', error);
570
+ }
571
+ }
572
+ /**
573
+ * Two capture configs at once: a flag is on only where both have it on.
574
+ *
575
+ * @param own - The turn's own folder's.
576
+ * @param other - The repository's whose checkout the turn's work was found in.
577
+ * @returns The narrower of the two.
578
+ */
579
+ function narrower(own, other) {
580
+ return Object.fromEntries(Object.entries(own).map(([key, on]) => [key, on && other[key]]));
581
+ }