@agent-watch-ai/edge 0.2.5 → 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 (348) hide show
  1. package/CHANGELOG.md +558 -0
  2. package/README.md +222 -97
  3. package/SECURITY.md +72 -0
  4. package/dist/billing/session-billing.d.ts +19 -0
  5. package/dist/billing/session-billing.js +52 -0
  6. package/dist/cli/args.d.ts +10 -0
  7. package/dist/cli/args.js +20 -0
  8. package/dist/cli/constants/cli.constants.d.ts +52 -4
  9. package/dist/cli/constants/cli.constants.js +56 -5
  10. package/dist/cli/context.d.ts +33 -2
  11. package/dist/cli/context.js +84 -14
  12. package/dist/cli/doctor.js +321 -33
  13. package/dist/cli/hook-check.d.ts +23 -0
  14. package/dist/cli/hook-check.js +114 -0
  15. package/dist/cli/hook.js +118 -7
  16. package/dist/cli/index.d.ts +3 -1
  17. package/dist/cli/index.js +3 -1
  18. package/dist/cli/misc.d.ts +11 -0
  19. package/dist/cli/misc.js +80 -4
  20. package/dist/cli/npx-install.d.ts +37 -0
  21. package/dist/cli/npx-install.js +79 -0
  22. package/dist/cli/open-browser.d.ts +39 -0
  23. package/dist/cli/open-browser.js +62 -0
  24. package/dist/cli/setup.d.ts +17 -8
  25. package/dist/cli/setup.js +553 -103
  26. package/dist/cli/status.js +82 -13
  27. package/dist/cli/toggle.d.ts +9 -0
  28. package/dist/cli/toggle.js +117 -0
  29. package/dist/cli/types/cli.types.d.ts +43 -3
  30. package/dist/cli/ui.d.ts +7 -0
  31. package/dist/cli/ui.js +10 -1
  32. package/dist/cli/uninstall.js +39 -2
  33. package/dist/cli/update.d.ts +17 -0
  34. package/dist/cli/update.js +76 -0
  35. package/dist/cli.js +110 -12
  36. package/dist/config/config-store.d.ts +57 -0
  37. package/dist/config/config-store.js +250 -12
  38. package/dist/config/config.d.ts +53 -6
  39. package/dist/config/config.js +66 -6
  40. package/dist/config/constants/config.constants.d.ts +116 -6
  41. package/dist/config/constants/config.constants.js +131 -8
  42. package/dist/config/destination.d.ts +24 -0
  43. package/dist/config/destination.js +33 -0
  44. package/dist/config/index.d.ts +7 -4
  45. package/dist/config/index.js +5 -3
  46. package/dist/config/repo-config.d.ts +11 -7
  47. package/dist/config/repo-config.js +64 -15
  48. package/dist/config/root-config.d.ts +72 -0
  49. package/dist/config/root-config.js +170 -0
  50. package/dist/config/schemas/config.schema.d.ts +831 -84
  51. package/dist/config/schemas/config.schema.js +398 -16
  52. package/dist/config/types/config.types.d.ts +15 -1
  53. package/dist/config/types/destination.types.d.ts +8 -0
  54. package/dist/core/async.d.ts +36 -0
  55. package/dist/core/async.js +68 -0
  56. package/dist/core/index.d.ts +1 -1
  57. package/dist/core/index.js +1 -1
  58. package/dist/core/object.d.ts +5 -0
  59. package/dist/core/object.js +9 -4
  60. package/dist/core/pipe.d.ts +0 -13
  61. package/dist/core/pipe.js +1 -9
  62. package/dist/core/types/core.types.d.ts +9 -0
  63. package/dist/core/types/core.types.js +0 -3
  64. package/dist/core/which.d.ts +14 -0
  65. package/dist/core/which.js +43 -3
  66. package/dist/credentials/budget.d.ts +9 -0
  67. package/dist/credentials/budget.js +16 -0
  68. package/dist/credentials/command-runner.d.ts +16 -0
  69. package/dist/credentials/command-runner.js +37 -0
  70. package/dist/credentials/constants/credentials.constants.d.ts +119 -0
  71. package/dist/credentials/constants/credentials.constants.js +120 -0
  72. package/dist/credentials/credential-status.d.ts +14 -0
  73. package/dist/credentials/credential-status.js +38 -0
  74. package/dist/credentials/credentials.d.ts +86 -0
  75. package/dist/credentials/credentials.js +278 -0
  76. package/dist/credentials/device-api.d.ts +73 -0
  77. package/dist/credentials/device-api.js +161 -0
  78. package/dist/credentials/device-state.d.ts +31 -0
  79. package/dist/credentials/device-state.js +51 -0
  80. package/dist/credentials/identity.d.ts +73 -0
  81. package/dist/credentials/identity.js +101 -0
  82. package/dist/credentials/index.d.ts +7 -0
  83. package/dist/credentials/index.js +5 -0
  84. package/dist/credentials/migration.d.ts +46 -0
  85. package/dist/credentials/migration.js +164 -0
  86. package/dist/credentials/schemas/device-api.schema.d.ts +77 -0
  87. package/dist/credentials/schemas/device-api.schema.js +33 -0
  88. package/dist/credentials/schemas/device-state.schema.d.ts +51 -0
  89. package/dist/credentials/schemas/device-state.schema.js +20 -0
  90. package/dist/credentials/secret-store.d.ts +54 -0
  91. package/dist/credentials/secret-store.js +217 -0
  92. package/dist/credentials/sign-in.d.ts +31 -0
  93. package/dist/credentials/sign-in.js +105 -0
  94. package/dist/credentials/token-refresher.d.ts +39 -0
  95. package/dist/credentials/token-refresher.js +185 -0
  96. package/dist/credentials/types/credentials.types.d.ts +206 -0
  97. package/dist/credentials/types/credentials.types.js +1 -0
  98. package/dist/enforcement/constants/enforcement.constants.d.ts +47 -1
  99. package/dist/enforcement/constants/enforcement.constants.js +56 -0
  100. package/dist/enforcement/decision-cache.d.ts +20 -1
  101. package/dist/enforcement/decision-cache.js +65 -2
  102. package/dist/enforcement/decision-client.d.ts +9 -8
  103. package/dist/enforcement/decision-client.js +64 -17
  104. package/dist/enforcement/enforcement.d.ts +23 -2
  105. package/dist/enforcement/enforcement.js +107 -17
  106. package/dist/enforcement/index.d.ts +4 -3
  107. package/dist/enforcement/index.js +3 -2
  108. package/dist/enforcement/types/enforcement.types.d.ts +66 -2
  109. package/dist/enrollment/constants/enrollment.constants.d.ts +2 -6
  110. package/dist/enrollment/constants/enrollment.constants.js +2 -6
  111. package/dist/enrollment/enrollment.d.ts +16 -0
  112. package/dist/enrollment/enrollment.js +54 -0
  113. package/dist/enrollment/index.d.ts +3 -7
  114. package/dist/enrollment/index.js +1 -1
  115. package/dist/enrollment/types/enrollment.types.d.ts +9 -13
  116. package/dist/events/constants/enrich.constants.d.ts +15 -0
  117. package/dist/events/constants/enrich.constants.js +15 -0
  118. package/dist/events/constants/events.constants.d.ts +6 -2
  119. package/dist/events/constants/events.constants.js +5 -1
  120. package/dist/events/enrich.js +92 -10
  121. package/dist/events/event-id.d.ts +0 -8
  122. package/dist/events/event-id.js +0 -10
  123. package/dist/events/index.d.ts +2 -2
  124. package/dist/events/index.js +1 -1
  125. package/dist/events/product-event.d.ts +9 -6
  126. package/dist/events/types/repo-snapshot.types.d.ts +7 -0
  127. package/dist/events/types/session-billing.types.d.ts +16 -0
  128. package/dist/events/types/session-billing.types.js +1 -0
  129. package/dist/feature/constants/feature.constants.d.ts +7 -0
  130. package/dist/feature/constants/feature.constants.js +7 -0
  131. package/dist/feature/index.d.ts +1 -1
  132. package/dist/feature/index.js +1 -1
  133. package/dist/feature/ticket-candidates.d.ts +14 -0
  134. package/dist/feature/ticket-candidates.js +26 -8
  135. package/dist/git/blob-hash.d.ts +21 -0
  136. package/dist/git/blob-hash.js +69 -0
  137. package/dist/git/checkout-root.d.ts +27 -0
  138. package/dist/git/checkout-root.js +75 -0
  139. package/dist/git/constants/git.constants.d.ts +160 -0
  140. package/dist/git/constants/git.constants.js +181 -0
  141. package/dist/git/fingerprint.d.ts +74 -0
  142. package/dist/git/fingerprint.js +219 -0
  143. package/dist/git/gate-checkout.d.ts +44 -0
  144. package/dist/git/gate-checkout.js +201 -0
  145. package/dist/git/git-context.d.ts +45 -0
  146. package/dist/git/git-context.js +61 -3
  147. package/dist/git/index.d.ts +4 -2
  148. package/dist/git/index.js +2 -1
  149. package/dist/git/manifest-repository.d.ts +13 -0
  150. package/dist/git/manifest-repository.js +92 -0
  151. package/dist/git/repo-snapshot.d.ts +29 -3
  152. package/dist/git/repo-snapshot.js +110 -7
  153. package/dist/git/repository-root.d.ts +39 -0
  154. package/dist/git/repository-root.js +131 -0
  155. package/dist/git/types/git.types.d.ts +55 -0
  156. package/dist/git/types/repository-root.types.d.ts +11 -0
  157. package/dist/git/types/repository-root.types.js +1 -0
  158. package/dist/git/types/snapshot.types.d.ts +9 -0
  159. package/dist/pipeline/constants/pipeline.constants.d.ts +10 -0
  160. package/dist/pipeline/constants/pipeline.constants.js +10 -0
  161. package/dist/pipeline/hook-pipeline.js +410 -33
  162. package/dist/pipeline/types/pipeline.types.d.ts +39 -4
  163. package/dist/privacy/constants/privacy.constants.js +15 -1
  164. package/dist/privacy/index.d.ts +1 -0
  165. package/dist/privacy/index.js +1 -0
  166. package/dist/privacy/product-capture.d.ts +12 -0
  167. package/dist/privacy/product-capture.js +75 -0
  168. package/dist/privacy/sanitizer.d.ts +21 -3
  169. package/dist/privacy/sanitizer.js +52 -8
  170. package/dist/process/ancestors.d.ts +39 -0
  171. package/dist/process/ancestors.js +121 -0
  172. package/dist/process/constants/process.constants.d.ts +34 -0
  173. package/dist/process/constants/process.constants.js +34 -0
  174. package/dist/process/index.d.ts +7 -0
  175. package/dist/process/index.js +2 -0
  176. package/dist/process/types/process.types.d.ts +23 -0
  177. package/dist/process/types/process.types.js +1 -0
  178. package/dist/providers/antigravity/antigravity.adapter.d.ts +12 -1
  179. package/dist/providers/antigravity/antigravity.adapter.js +21 -3
  180. package/dist/providers/antigravity/antigravity.detect.d.ts +0 -9
  181. package/dist/providers/antigravity/antigravity.detect.js +1 -1
  182. package/dist/providers/antigravity/antigravity.provider.js +3 -2
  183. package/dist/providers/antigravity/constants/antigravity.constants.d.ts +2 -0
  184. package/dist/providers/antigravity/constants/antigravity.constants.js +2 -0
  185. package/dist/providers/claude/claude.adapter.d.ts +11 -1
  186. package/dist/providers/claude/claude.adapter.js +26 -5
  187. package/dist/providers/claude/claude.otel.d.ts +32 -18
  188. package/dist/providers/claude/claude.otel.js +81 -6
  189. package/dist/providers/claude/claude.provider.js +5 -2
  190. package/dist/providers/claude/constants/claude.constants.d.ts +2 -0
  191. package/dist/providers/claude/constants/claude.constants.js +2 -0
  192. package/dist/providers/claude/constants/claude.otel.constants.d.ts +4 -0
  193. package/dist/providers/claude/constants/claude.otel.constants.js +8 -0
  194. package/dist/providers/codex/codex.adapter.d.ts +15 -1
  195. package/dist/providers/codex/codex.adapter.js +29 -5
  196. package/dist/providers/codex/codex.otel.d.ts +36 -3
  197. package/dist/providers/codex/codex.otel.js +199 -32
  198. package/dist/providers/codex/codex.provider.js +5 -2
  199. package/dist/providers/codex/constants/codex.constants.d.ts +2 -0
  200. package/dist/providers/codex/constants/codex.constants.js +16 -0
  201. package/dist/providers/codex/constants/codex.otel.constants.d.ts +10 -0
  202. package/dist/providers/codex/constants/codex.otel.constants.js +10 -0
  203. package/dist/providers/constants/provider.constants.d.ts +8 -3
  204. package/dist/providers/constants/provider.constants.js +8 -3
  205. package/dist/providers/cursor/constants/cursor.constants.d.ts +9 -0
  206. package/dist/providers/cursor/constants/cursor.constants.js +9 -0
  207. package/dist/providers/cursor/cursor.adapter.d.ts +33 -1
  208. package/dist/providers/cursor/cursor.adapter.js +129 -4
  209. package/dist/providers/cursor/cursor.detect.d.ts +0 -7
  210. package/dist/providers/cursor/cursor.detect.js +1 -1
  211. package/dist/providers/cursor/cursor.provider.js +5 -2
  212. package/dist/providers/gemini/constants/gemini.constants.d.ts +9 -0
  213. package/dist/providers/gemini/constants/gemini.constants.js +9 -0
  214. package/dist/providers/gemini/constants/gemini.otel.constants.d.ts +9 -1
  215. package/dist/providers/gemini/constants/gemini.otel.constants.js +9 -0
  216. package/dist/providers/gemini/gemini.adapter.d.ts +14 -1
  217. package/dist/providers/gemini/gemini.adapter.js +25 -5
  218. package/dist/providers/gemini/gemini.detect.d.ts +0 -7
  219. package/dist/providers/gemini/gemini.detect.js +1 -1
  220. package/dist/providers/gemini/gemini.otel.d.ts +30 -21
  221. package/dist/providers/gemini/gemini.otel.js +166 -22
  222. package/dist/providers/gemini/gemini.provider.js +2 -1
  223. package/dist/providers/index.d.ts +1 -1
  224. package/dist/providers/index.js +1 -1
  225. package/dist/providers/loaders.d.ts +10 -0
  226. package/dist/providers/loaders.js +40 -0
  227. package/dist/providers/provider.d.ts +11 -0
  228. package/dist/providers/provider.js +1 -1
  229. package/dist/providers/registry.d.ts +11 -8
  230. package/dist/providers/registry.js +11 -15
  231. package/dist/providers/shared/bearer-rewrite.d.ts +19 -0
  232. package/dist/providers/shared/bearer-rewrite.js +46 -0
  233. package/dist/providers/shared/constants/hook-refusal.constants.d.ts +7 -0
  234. package/dist/providers/shared/constants/hook-refusal.constants.js +7 -0
  235. package/dist/providers/shared/constants/shell-directories.constants.d.ts +30 -0
  236. package/dist/providers/shared/constants/shell-directories.constants.js +39 -0
  237. package/dist/providers/shared/constants/tooling.constants.d.ts +24 -2
  238. package/dist/providers/shared/constants/tooling.constants.js +25 -3
  239. package/dist/providers/shared/event-builder.d.ts +12 -14
  240. package/dist/providers/shared/event-builder.js +20 -14
  241. package/dist/providers/shared/exporter-allowlist.d.ts +20 -0
  242. package/dist/providers/shared/exporter-allowlist.js +49 -0
  243. package/dist/providers/shared/hook-config.d.ts +2 -21
  244. package/dist/providers/shared/hook-config.js +5 -4
  245. package/dist/providers/shared/hook-refusal.d.ts +12 -0
  246. package/dist/providers/shared/hook-refusal.js +17 -1
  247. package/dist/providers/shared/install-record.d.ts +12 -2
  248. package/dist/providers/shared/install-record.js +5 -2
  249. package/dist/providers/shared/shell-directories.d.ts +24 -0
  250. package/dist/providers/shared/shell-directories.js +90 -0
  251. package/dist/providers/shared/tooling.d.ts +40 -1
  252. package/dist/providers/shared/tooling.js +70 -1
  253. package/dist/providers/shared/types/adapter.types.d.ts +1 -2
  254. package/dist/providers/types/provider.types.d.ts +81 -1
  255. package/dist/snapshot/constants/snapshot.constants.d.ts +32 -0
  256. package/dist/snapshot/constants/snapshot.constants.js +33 -0
  257. package/dist/snapshot/snapshot-event.js +52 -11
  258. package/dist/snapshot/snapshot-pipeline.js +1 -1
  259. package/dist/snapshot/types/snapshot.types.d.ts +2 -0
  260. package/dist/storage/atomic-file.d.ts +21 -0
  261. package/dist/storage/atomic-file.js +20 -1
  262. package/dist/storage/constants/storage.constants.d.ts +19 -0
  263. package/dist/storage/constants/storage.constants.js +19 -0
  264. package/dist/storage/disabled.d.ts +13 -0
  265. package/dist/storage/disabled.js +24 -0
  266. package/dist/storage/index.d.ts +2 -0
  267. package/dist/storage/index.js +2 -0
  268. package/dist/storage/paths.js +3 -2
  269. package/dist/storage/schemas/storage.schema.d.ts +72 -0
  270. package/dist/storage/schemas/storage.schema.js +6 -0
  271. package/dist/storage/sweep-marker.d.ts +19 -0
  272. package/dist/storage/sweep-marker.js +55 -0
  273. package/dist/storage/types/storage.types.d.ts +2 -0
  274. package/dist/storage/uninstalled.d.ts +58 -0
  275. package/dist/storage/uninstalled.js +107 -0
  276. package/dist/transport/auth-block.d.ts +66 -0
  277. package/dist/transport/auth-block.js +129 -0
  278. package/dist/transport/constants/transport.constants.d.ts +82 -3
  279. package/dist/transport/constants/transport.constants.js +83 -4
  280. package/dist/transport/cooldown.js +8 -1
  281. package/dist/transport/delivery.d.ts +14 -6
  282. package/dist/transport/delivery.js +80 -55
  283. package/dist/transport/http-transport.d.ts +1 -0
  284. package/dist/transport/http-transport.js +52 -10
  285. package/dist/transport/index.d.ts +6 -3
  286. package/dist/transport/index.js +3 -0
  287. package/dist/transport/queue-partition.d.ts +91 -0
  288. package/dist/transport/queue-partition.js +143 -0
  289. package/dist/transport/queue.d.ts +99 -20
  290. package/dist/transport/queue.js +210 -69
  291. package/dist/transport/response-body.d.ts +25 -0
  292. package/dist/transport/response-body.js +64 -0
  293. package/dist/transport/send.d.ts +11 -0
  294. package/dist/transport/send.js +17 -0
  295. package/dist/transport/types/delivery-flow.types.d.ts +19 -0
  296. package/dist/transport/types/delivery-flow.types.js +1 -0
  297. package/dist/transport/types/transport.types.d.ts +45 -0
  298. package/dist/turns/claude-transcript.d.ts +19 -1
  299. package/dist/turns/claude-transcript.js +46 -1
  300. package/dist/turns/codex-originator.d.ts +11 -0
  301. package/dist/turns/codex-originator.js +31 -0
  302. package/dist/turns/codex-transcript.d.ts +30 -0
  303. package/dist/turns/codex-transcript.js +88 -0
  304. package/dist/turns/constants/turns.constants.d.ts +141 -5
  305. package/dist/turns/constants/turns.constants.js +155 -5
  306. package/dist/turns/file-identity.d.ts +27 -0
  307. package/dist/turns/file-identity.js +48 -0
  308. package/dist/turns/gemini-transcript.d.ts +30 -0
  309. package/dist/turns/gemini-transcript.js +96 -0
  310. package/dist/turns/index.d.ts +3 -3
  311. package/dist/turns/index.js +1 -1
  312. package/dist/turns/inherited-checkout.d.ts +54 -0
  313. package/dist/turns/inherited-checkout.js +155 -0
  314. package/dist/turns/native-session-titles.d.ts +26 -0
  315. package/dist/turns/native-session-titles.js +102 -0
  316. package/dist/turns/transcript.d.ts +3 -2
  317. package/dist/turns/transcript.js +5 -1
  318. package/dist/turns/turn-state.d.ts +224 -3
  319. package/dist/turns/turn-state.js +456 -21
  320. package/dist/turns/turn-summary.d.ts +1 -14
  321. package/dist/turns/turn-summary.js +87 -51
  322. package/dist/turns/turn-tracker.d.ts +21 -2
  323. package/dist/turns/turn-tracker.js +379 -56
  324. package/dist/turns/types/transcript.types.d.ts +5 -0
  325. package/dist/turns/types/turn-state.types.d.ts +116 -5
  326. package/dist/turns/types/turn-summary.types.d.ts +64 -14
  327. package/dist/turns/types/turn-tracker.types.d.ts +27 -1
  328. package/dist/turns/work-checkout.d.ts +67 -0
  329. package/dist/turns/work-checkout.js +700 -0
  330. package/dist/untraced/constants/untraced.constants.d.ts +31 -0
  331. package/dist/untraced/constants/untraced.constants.js +63 -0
  332. package/dist/untraced/untraced.d.ts +35 -0
  333. package/dist/untraced/untraced.js +105 -0
  334. package/dist/update/constants/update.constants.d.ts +18 -0
  335. package/dist/update/constants/update.constants.js +20 -0
  336. package/dist/update/update-check.d.ts +52 -0
  337. package/dist/update/update-check.js +113 -0
  338. package/docs/AUDIT_PROMPT.md +129 -0
  339. package/docs/DATA_HANDLING.md +655 -0
  340. package/docs/ENTERPRISE_DEPLOYMENT.md +194 -0
  341. package/docs/PERFORMANCE.md +81 -0
  342. package/package.json +14 -4
  343. package/dist/enrollment/enrollment-provider.d.ts +0 -5
  344. package/dist/enrollment/manual-enrollment.d.ts +0 -32
  345. package/dist/enrollment/manual-enrollment.js +0 -72
  346. package/example/README.md +0 -43
  347. package/example/server.mjs +0 -240
  348. /package/dist/{enrollment/enrollment-provider.js → config/types/destination.types.js} +0 -0
@@ -1,25 +1,38 @@
1
+ import path from 'node:path';
1
2
  import { pollUntil } from '../core/async.js';
2
3
  import { debugLog } from '../core/logger.js';
3
- import { asRecord } from '../core/object.js';
4
+ import { asRecord, compact } from '../core/object.js';
4
5
  import { detectBillingMode } from '../billing/billing-mode.js';
5
6
  import { sha256Hex } from '../events/event-id.js';
6
- import { developerIdentity } from '../git/git-context.js';
7
+ import { REPOSITORY_PATH_METADATA_KEY } from '../events/constants/enrich.constants.js';
8
+ import { developerDisplayName, developerIdentity } from '../git/git-context.js';
7
9
  import { sanitizeValue } from '../privacy/sanitizer.js';
8
10
  import { acquireLock } from '../storage/lock.js';
9
- import { readTurnUsage } from './claude-transcript.js';
11
+ import { inheritedRootConfig } from '../config/root-config.js';
12
+ import { MAX_WORK_CHANGED_FILES } from '../git/constants/git.constants.js';
13
+ import { readClaudeSessionTitles, readTurnUsage } from './claude-transcript.js';
14
+ import { isCodexExecTranscript } from './codex-originator.js';
15
+ import { readCodexTurnUsage } from './codex-transcript.js';
10
16
  import { readCursorTurnUsage } from './cursor-transcript.js';
11
- import { CLAUDE_ENTRYPOINT_VAR, DEFAULT_SURFACE, FILE_PATH_KEY, IDE_SURFACE, IDE_SURFACE_PROVIDERS, LOCK_KEY_HASH_LENGTH, PROMPT_EVIDENCE_KEY, PROMPT_TEXT_KEY, RESPONSE_EVIDENCE_KEY, RESPONSE_TEXT_KEY, TOOL_COMPLETION_TYPES, TRANSCRIPT_PATH_KEY, TURN_STATE_TTL_MS, USAGE_LOCK_POLL_MS, USAGE_LOCK_WAIT_MS, USAGE_RETRY } from './constants/turns.constants.js';
17
+ import { readGeminiTurnUsage } from './gemini-transcript.js';
18
+ import { readCodexSessionTitles, readCursorSessionTitles } from './native-session-titles.js';
19
+ import { CLAUDE_ENTRYPOINT_VAR, PARENT_SESSION_VAR, RE_PARENT_SESSION_ID, DEFAULT_SURFACE, EXTERNAL_PATH_KEY, FILE_PATH_KEY, IDE_SURFACE, IDE_SURFACE_PROVIDERS, LOCK_KEY_HASH_LENGTH, MAX_PROMPT_TEXT_LENGTH, MAX_TOOL_INPUT_LENGTH, PROMPT_EVIDENCE_KEY, PROMPT_JIRA_IDS_KEY, PROMPT_TEXT_KEY, RESPONSE_EVIDENCE_KEY, TOOL_COMPLETION_TYPES, EXEC_SURFACE, TRANSCRIPT_PATH_KEY, TURN_STATE_TTL_MS, USAGE_LOCK_POLL_MS, USAGE_LOCK_WAIT_MS, USAGE_RETRY } from './constants/turns.constants.js';
20
+ import { resolveFileIdentity } from './file-identity.js';
12
21
  import { TurnStateStore } from './turn-state.js';
13
- import { alignContentEvidence, buildTurnSummary } from './turn-summary.js';
22
+ import { buildTurnSummary } from './turn-summary.js';
23
+ import { rememberInheritance, retryInheritance } from './inherited-checkout.js';
24
+ import { recordCheckouts, resolveWorkCheckout } from './work-checkout.js';
14
25
  /**
15
26
  * Providers whose transcript can be read for token usage.
16
27
  *
17
- * Claude windows by message timestamps; Cursor rows carry none, so its reader
28
+ * Claude, Codex and Gemini window by row timestamps; Cursor rows carry none, so its reader
18
29
  * relies solely on the exactly-once message-id ledger (today Cursor rows also
19
30
  * carry no usage — the reader returns undefined and the summary stays pending).
20
31
  */
21
32
  const TRANSCRIPT_READERS = {
22
33
  claude: (transcriptPath, startedAt, untilIso, excludeMessageIds) => readTurnUsage(transcriptPath, startedAt, USAGE_RETRY, untilIso, excludeMessageIds),
34
+ codex: (transcriptPath, startedAt, untilIso, excludeMessageIds) => readCodexTurnUsage(transcriptPath, startedAt, USAGE_RETRY, untilIso, excludeMessageIds),
35
+ gemini: (transcriptPath, startedAt, untilIso, excludeMessageIds) => readGeminiTurnUsage(transcriptPath, startedAt, USAGE_RETRY, untilIso, excludeMessageIds),
23
36
  cursor: (transcriptPath, _startedAt, _untilIso, excludeMessageIds) => readCursorTurnUsage(transcriptPath, USAGE_RETRY, excludeMessageIds)
24
37
  };
25
38
  /**
@@ -33,25 +46,36 @@ const TRANSCRIPT_READERS = {
33
46
  * @returns The turn summary when this payload closed a turn.
34
47
  */
35
48
  export async function trackTurn(options) {
49
+ return (await trackTurnOutcome(options)).summary;
50
+ }
51
+ /**
52
+ * {@link trackTurn}, with the local root of the checkout the summary reported
53
+ * beside it: the pipeline takes the repository snapshot there. The root never
54
+ * goes on the summary.
55
+ *
56
+ * @param options - The payload's events, config, paths and clock.
57
+ * @returns The summary when this payload closed a turn, and its checkout's root.
58
+ */
59
+ export async function trackTurnOutcome(options) {
36
60
  const store = new TurnStateStore(options.turnsDir);
37
- let summary;
61
+ let outcome = {};
38
62
  for (const event of options.events) {
39
63
  const sessionId = event.session.id;
40
64
  if (!sessionId)
41
65
  continue;
42
66
  try {
43
- summary = (await processEvent(store, sessionId, event, options)) ?? summary;
67
+ outcome = (await processEvent(store, sessionId, event, options)) ?? outcome;
44
68
  }
45
69
  catch (error) {
46
70
  debugLog('turn tracking failed:', error);
47
71
  // Closing failed (corrupt turn state, unreadable transcript, IO error):
48
72
  // the turn must still reach the backend rather than silently vanish.
49
- if (event.event.type === 'generation.completed' && !summary) {
50
- summary = fallbackSummary(sessionId, event, options);
73
+ if (event.event.type === 'generation.completed' && !outcome.summary) {
74
+ outcome = { summary: await fallbackSummary(store, sessionId, event, options) };
51
75
  }
52
76
  }
53
77
  }
54
- return summary;
78
+ return outcome;
55
79
  }
56
80
  /**
57
81
  * Apply one canonical event to the accumulator.
@@ -71,13 +95,36 @@ async function processEvent(store, sessionId, event, options) {
71
95
  return undefined;
72
96
  return closeTurnLocked(store, sessionId, event, options, true);
73
97
  }
74
- const record = recordFor(event);
98
+ // On the session's own hook and no other. Claude names its model only there,
99
+ // which is the whole reason the memo exists; the agents that name it on every
100
+ // hook also name it on that one, so once per session is all it ever takes.
101
+ //
102
+ // Narrow on purpose, twice over. It keeps a per-hook write off the agent's
103
+ // critical path for something no later hook can read — those agents carry the
104
+ // model on the prompt payload the gate already holds. And it keeps the write
105
+ // out of the two invocations that must not be pre-empted: a failure on
106
+ // `generation.completed` would degrade the turn to a fallback summary, and one
107
+ // on `session.ended` would leave a session's raw prompt text undeleted.
108
+ if (type === 'session.started')
109
+ await rememberModelSafely(store, sessionId, event);
110
+ // The first hook walks; a later one walks again only when the deadline cut
111
+ // the last walk, so a busy first hook does not cost the whole session. Not
112
+ // at the session's end, which clears the answer straight after.
113
+ const first = await rememberStartSafely(store, sessionId, options.cwd);
114
+ if (first)
115
+ await rememberInheritance(store, sessionId, options);
116
+ if (!first && type !== 'session.ended')
117
+ await retryInheritance(store, sessionId, options);
118
+ if (type === 'prompt.submitted')
119
+ await rememberPromptTicketsSafely(store, sessionId, event, options.config.capture.git);
120
+ await recordCheckoutsSafely(store, sessionId, event, options);
121
+ const record = recordFor(event, options.cwd, options.failOpenReason);
75
122
  if (record)
76
123
  await store.append(sessionId, recordKeyFor(event), record);
77
124
  if (type === 'generation.completed') {
78
- const summary = await closeTurn(store, sessionId, event, options);
125
+ const outcome = await closeTurn(store, sessionId, event, options);
79
126
  await store.sweep(TURN_STATE_TTL_MS);
80
- return summary;
127
+ return outcome;
81
128
  }
82
129
  if (type === 'session.ended') {
83
130
  await store.clear(sessionId);
@@ -85,18 +132,109 @@ async function processEvent(store, sessionId, event, options) {
85
132
  }
86
133
  return undefined;
87
134
  }
135
+ /**
136
+ * Remember the session's model, or carry on without it.
137
+ *
138
+ * A memo that cannot be written is a gate that states no model, which is the
139
+ * answer it gives for every other reason too. It is never a reason to fail the
140
+ * hook the agent is waiting on.
141
+ *
142
+ * @param store - Per-session state store.
143
+ * @param sessionId - Provider session id.
144
+ * @param event - The session's own event, which may or may not name a model.
145
+ */
146
+ async function rememberModelSafely(store, sessionId, event) {
147
+ const model = event.ai?.model;
148
+ try {
149
+ // A start that names no model actively forgets, rather than leaving whatever
150
+ // a previous session under the same id left behind: a SessionEnd cleanup can
151
+ // fail, `--resume` reuses the id, and Claude does not name a model on every
152
+ // start. Inheriting one would make the gate state a model this session is
153
+ // not on.
154
+ await (model ? store.rememberModel(sessionId, model) : store.forgetModel(sessionId));
155
+ }
156
+ catch (error) {
157
+ debugLog('could not record the session model:', error);
158
+ }
159
+ }
160
+ /**
161
+ * Remember the folder the session started in, or carry on without it.
162
+ *
163
+ * Every hook tries and only the first writes: the file is created exclusively.
164
+ * Without it the close asks the Stop folder instead, which is what it asked
165
+ * before this existed.
166
+ *
167
+ * @param store - Per-session state store.
168
+ * @param sessionId - Provider session id.
169
+ * @param cwd - This hook's cwd.
170
+ * @returns Whether this was the session's first hook.
171
+ */
172
+ async function rememberStartSafely(store, sessionId, cwd) {
173
+ try {
174
+ return await store.rememberStart(sessionId, cwd);
175
+ }
176
+ catch (error) {
177
+ debugLog('could not record the session start folder:', error);
178
+ return false;
179
+ }
180
+ }
181
+ /**
182
+ * Remember the opening prompt's ticket keys, or carry on without them.
183
+ *
184
+ * Every prompt tries and only the session's first writes. Without the memo the
185
+ * summaries carry no prompt keys, which is what they carried before it existed.
186
+ * A fixed sentence on failure: the keys came from a prompt.
187
+ *
188
+ * @param store - Per-session state store.
189
+ * @param sessionId - Provider session id.
190
+ * @param event - The prompt event.
191
+ * @param git - Whether this prompt's capture policy allows git context.
192
+ */
193
+ async function rememberPromptTicketsSafely(store, sessionId, event, git) {
194
+ const named = event.metadata?.[PROMPT_JIRA_IDS_KEY];
195
+ // With git capture off the session is still claimed, so a later prompt cannot
196
+ // become its opening one, but nothing it named is kept on disk.
197
+ const keys = git && Array.isArray(named) ? named.filter((key) => typeof key === 'string') : [];
198
+ try {
199
+ await store.rememberPromptTickets(sessionId, keys);
200
+ }
201
+ catch {
202
+ debugLog('could not record the opening prompt\'s ticket keys');
203
+ }
204
+ }
205
+ /**
206
+ * Write down the checkouts this hook names, or carry on without them.
207
+ *
208
+ * A fixed sentence on failure and never the error: the nominated roots came
209
+ * from a shell command, and a log line is not where they may go.
210
+ *
211
+ * @param store - Per-session state store.
212
+ * @param sessionId - Provider session id.
213
+ * @param event - The event.
214
+ * @param options - Tracking options.
215
+ */
216
+ async function recordCheckoutsSafely(store, sessionId, event, options) {
217
+ try {
218
+ await recordCheckouts(store, sessionId, event, options);
219
+ }
220
+ catch {
221
+ debugLog('could not record the checkouts a tool call named');
222
+ }
223
+ }
88
224
  /**
89
225
  * The turn record one event should be persisted as, if any.
90
226
  *
91
227
  * @param event - Canonical event.
228
+ * @param cwd - This hook's own working directory.
229
+ * @param failOpenReason - Why this payload's prompt ran unchecked, if it did.
92
230
  * @returns The record, or undefined when the event carries no turn state.
93
231
  */
94
- function recordFor(event) {
232
+ function recordFor(event, cwd, failOpenReason) {
95
233
  const type = event.event.type;
96
234
  if (type === 'prompt.submitted')
97
- return promptRecord(event);
235
+ return promptRecord(event, failOpenReason);
98
236
  if (TOOL_COMPLETION_TYPES.has(type))
99
- return toolRecord(event);
237
+ return toolRecord(event, cwd);
100
238
  // Cursor delivers the response text in its own hook (afterAgentResponse)
101
239
  // instead of on Stop; keep it as turn state until the turn closes.
102
240
  if (type === 'agent.other' && responseFrom(event) !== undefined)
@@ -137,7 +275,7 @@ function recordKeyFor(event) {
137
275
  * @param sessionId - Provider session id.
138
276
  * @param stopEvent - The closing event.
139
277
  * @param options - Tracking options.
140
- * @returns The summary, or undefined when another closer holds the lock.
278
+ * @returns The outcome, or undefined when another closer holds the lock.
141
279
  */
142
280
  async function closeTurn(store, sessionId, stopEvent, options) {
143
281
  const lockKey = sha256Hex(`${sessionId}::${stopEvent.session.turnId ?? ''}`).slice(0, LOCK_KEY_HASH_LENGTH);
@@ -163,7 +301,7 @@ async function closeTurn(store, sessionId, stopEvent, options) {
163
301
  * @param stopEvent - The closing event.
164
302
  * @param options - Tracking options.
165
303
  * @param readOnly - Preview only: consume and claim nothing.
166
- * @returns The summary, or undefined when there is nothing to summarize.
304
+ * @returns The summary and its checkout's root, or undefined when there is nothing to summarize.
167
305
  */
168
306
  async function closeTurnLocked(store, sessionId, stopEvent, options, readOnly = false) {
169
307
  const stopTurnId = stopEvent.session.turnId;
@@ -182,21 +320,50 @@ async function closeTurnLocked(store, sessionId, stopEvent, options, readOnly =
182
320
  // watched the transcript still belongs to this turn.
183
321
  const mine = filterTurn(await store.collectEntries(sessionId), stopTurnId);
184
322
  const records = mine.map((entry) => entry.record);
323
+ // Which checkout this turn worked in is answerable only here, where every
324
+ // checkout it named and every tool call it made are in hand — and this is the
325
+ // one hook that may pay for a batch of git processes.
326
+ // Alongside the session's opening prompt keys, not this turn's: later prompts never move them.
327
+ const [work, promptJiraIds] = await Promise.all([resolveWorkCheckout(store, sessionId, records, stopEvent, options), store.readPromptTickets(sessionId)]);
185
328
  // Usage is mirrored onto a *copy* of the Stop event: the summary's model
186
329
  // should come from the transcript when the transcript knows better, and
187
330
  // rewriting an event another stage may still be reading is not an option.
188
331
  const resolvedStop = withResolvedUsage(stopEvent, usage, billingMode);
332
+ // Together, not in turn: each shells out to git and each can cost its own
333
+ // GIT_TIMEOUT_MS, so taken in order a slow machine pays both inside the
334
+ // lock on every close. The pre-turn path resolves the same pair this way.
335
+ // An inherited checkout in a root sends as that root, so the developer is the
336
+ // one that root names; every other turn keeps its hook folder's config.
337
+ const identity = inheritedRootConfig(options.globalConfig.config, work.evidence, work.root) ?? options.config;
338
+ const [developerId, developerName] = await Promise.all([
339
+ // From this hook's cwd, never the winning repository's: the prompt gate
340
+ // enforced this turn as the developer it resolved there, before any
341
+ // repository was known, and one turn is one developer.
342
+ developerIdentity(identity.developerEmail, options.cwd, { home: options.env.home }),
343
+ developerDisplayName(identity.developerName, options.cwd, { home: options.env.home })
344
+ ]);
345
+ const fileIdentity = await resolveFileIdentity(store, sessionId, work.tools, stopEvent, options).catch((error) => {
346
+ debugLog('could not identify the turn\'s files:', error);
347
+ return {};
348
+ });
349
+ const sessionTitles = await resolveSessionTitles(store, sessionId, options, readOnly);
189
350
  const summary = buildTurnSummary({
351
+ ...fileIdentity,
352
+ sessionTitles,
190
353
  provider: stopEvent.agent.provider,
191
- surface: resolveSurface(stopEvent.agent.provider, options.env),
354
+ surface: await resolveSurface(stopEvent.agent.provider, options.env, options.rawPayload),
192
355
  sessionId,
193
356
  turnId: stopTurnId,
194
- developerId: await developerIdentity(options.config.developerEmail, options.cwd, { home: options.env.home }),
195
- installationId: options.config.installationId,
196
- git: stopEvent.git,
197
- featureCandidates: stopEvent.feature?.candidates,
357
+ developerId,
358
+ developerName,
359
+ installationId: identity.installationId,
360
+ git: work.git,
361
+ featureCandidates: work.featureCandidates,
362
+ promptJiraIds,
363
+ workEvidence: work.evidence,
364
+ parentSessionId: declaredParent(options.env, sessionId) ?? work.parentSessionId,
198
365
  prompts: recordsOfKind(records, 'prompt'),
199
- tools: recordsOfKind(records, 'tool'),
366
+ tools: work.tools,
200
367
  response: resolveResponse(stopEvent, records),
201
368
  usage,
202
369
  model: resolvedStop.ai?.model,
@@ -206,7 +373,34 @@ async function closeTurnLocked(store, sessionId, stopEvent, options, readOnly =
206
373
  // Consume exactly what went into the summary; other prompts' records stay.
207
374
  if (!readOnly)
208
375
  await store.remove(mine.map((entry) => entry.file));
209
- return alignContentEvidence(sanitizeValue(summary));
376
+ // The next turn that changes nothing carries this one; the prompt gate asks it too.
377
+ if (!readOnly && work.evidence === 'changed' && work.root && work.git?.repository) {
378
+ // After the records are consumed, so a failure here must not cost the summary.
379
+ await rememberChange(store, sessionId, { root: work.root, repository: work.git.repository, at: stopEvent.timestamp, branch: work.git.branch }, work.capture?.files === false ? [] : (work.changed ?? [])).catch((error) => {
380
+ debugLog('could not record the work checkout:', error);
381
+ });
382
+ }
383
+ return { summary: sanitizeValue(summary), workRoot: work.root, capture: work.capture };
384
+ }
385
+ /**
386
+ * Remember the checkout this turn changed, with its branch and the files the
387
+ * session has changed there on it, for another session sharing the checkout to
388
+ * read (SPEC §3a). Files accumulate while the root and branch stay the same.
389
+ *
390
+ * @param store - The turn state store.
391
+ * @param sessionId - Provider session id.
392
+ * @param memo - The checkout, its repository, branch and when.
393
+ * @param changed - The files this turn changed there.
394
+ */
395
+ async function rememberChange(store, sessionId, memo, changed) {
396
+ const previous = await store.readWorkCheckout(sessionId);
397
+ const same = previous?.root === memo.root && previous.branch === memo.branch;
398
+ // With capture.files off no path is kept, here either: the turn's files then
399
+ // shield nothing for a session sharing the checkout.
400
+ // ponytail: the newest MAX_WORK_CHANGED_FILES files of the branch; older ones
401
+ // stop shielding the session's work from a concurrent session's turn.
402
+ const files = [...new Set([...changed, ...(same ? (previous.files ?? []) : [])])].slice(0, MAX_WORK_CHANGED_FILES);
403
+ await store.rememberWorkCheckout(sessionId, { ...memo, files });
210
404
  }
211
405
  /**
212
406
  * Degraded close: a summary built from the Stop event alone.
@@ -215,29 +409,50 @@ async function closeTurnLocked(store, sessionId, stopEvent, options, readOnly =
215
409
  * finalizes usage from the llm.call ledger — via the turn id when present, else
216
410
  * the session-wide ownership join. A thin record beats a missing turn.
217
411
  *
412
+ * @param store - The turn state store.
218
413
  * @param sessionId - Provider session id.
219
414
  * @param stopEvent - The closing event.
220
415
  * @param options - Tracking options.
221
416
  * @returns The degraded summary, or undefined when even that failed.
222
417
  */
223
- function fallbackSummary(sessionId, stopEvent, options) {
418
+ async function fallbackSummary(store, sessionId, stopEvent, options) {
224
419
  try {
420
+ // The same resolvers the healthy close uses, and resolved together for the
421
+ // same reason: on a machine that names its developer through git alone,
422
+ // reading the config verbatim here would ship a turn attributed to nobody.
423
+ const [developerId, developerName] = await Promise.all([
424
+ developerIdentity(options.config.developerEmail, options.cwd, { home: options.env.home }),
425
+ developerDisplayName(options.config.developerName, options.cwd, { home: options.env.home })
426
+ ]);
427
+ // Caught on its own, as on the healthy close: a throw here must not cost the thin record.
428
+ const fileIdentity = await resolveFileIdentity(store, sessionId, [], stopEvent, options).catch((error) => {
429
+ debugLog('could not identify the turn\'s files:', error);
430
+ return {};
431
+ });
225
432
  const summary = buildTurnSummary({
433
+ ...fileIdentity,
226
434
  provider: stopEvent.agent.provider,
227
- surface: resolveSurface(stopEvent.agent.provider, options.env),
435
+ surface: await resolveSurface(stopEvent.agent.provider, options.env, options.rawPayload),
228
436
  sessionId,
229
437
  turnId: stopEvent.session.turnId,
230
- developerId: options.config.developerEmail,
438
+ developerId,
439
+ developerName,
231
440
  installationId: options.config.installationId,
232
441
  git: stopEvent.git,
233
442
  featureCandidates: stopEvent.feature?.candidates,
443
+ // A memo, not turn state: still readable when the records were not.
444
+ promptJiraIds: await store.readPromptTickets(sessionId),
445
+ // The environment, unlike the turn state, is still readable here.
446
+ parentSessionId: declaredParent(options.env, sessionId),
447
+ // No prompt records, so no fail-open reason either: a degraded summary
448
+ // reports what it can read, and the state it could not read is the point.
234
449
  prompts: [],
235
450
  tools: [],
236
451
  response: responseFrom(stopEvent),
237
452
  model: stopEvent.ai?.model,
238
453
  endedAt: stopEvent.timestamp
239
454
  });
240
- return alignContentEvidence(sanitizeValue(summary));
455
+ return sanitizeValue(summary);
241
456
  }
242
457
  catch (error) {
243
458
  debugLog('fallback turn summary failed:', error);
@@ -340,6 +555,62 @@ async function readTranscriptUsage(options, window, excludeMessageIds) {
340
555
  return undefined;
341
556
  return reader(transcriptPath, window.startedAt, window.untilIso, excludeMessageIds);
342
557
  }
558
+ /**
559
+ * The session's name and generated title, when the config lets them leave the machine.
560
+ *
561
+ * Read only under `capture.sessionTitle`, so with it off the transcript is not
562
+ * even looked at for one. Claude Code alone names its sessions in its
563
+ * transcript. Codex and Cursor keep them in local read-model databases. The
564
+ * other agents send none, and nothing is derived from the prompt. Claude's
565
+ * last title of each kind is remembered, each on its own, for a turn whose
566
+ * tail no longer reaches one. A failure costs the titles, never the summary.
567
+ *
568
+ * ponytail: a second tail read after the usage one, rather than threading the
569
+ * title through the usage settle loop; the tail is in the page cache by then.
570
+ * Merge the two passes if Stop latency ever shows it.
571
+ *
572
+ * @param store - Per-session state store.
573
+ * @param sessionId - Provider session id.
574
+ * @param options - Tracking options carrying the config and raw payload.
575
+ * @param readOnly - Preview only: remember nothing.
576
+ * @returns The raw titles; empty when there are none to send.
577
+ */
578
+ async function resolveSessionTitles(store, sessionId, options, readOnly) {
579
+ if (options.config.capture.sessionTitle !== true)
580
+ return {};
581
+ if (options.agentId === 'codex')
582
+ return safeNativeTitles(() => readCodexSessionTitles(options.env, sessionId));
583
+ if (options.agentId === 'cursor')
584
+ return safeNativeTitles(() => readCursorSessionTitles(options.env, sessionId));
585
+ const transcriptPath = asRecord(options.rawPayload)?.[TRANSCRIPT_PATH_KEY];
586
+ if (options.agentId !== 'claude' || typeof transcriptPath !== 'string')
587
+ return {};
588
+ try {
589
+ const [seen, remembered] = await Promise.all([readClaudeSessionTitles(transcriptPath), store.readSessionTitles(sessionId)]);
590
+ const titles = compact({ custom: seen.custom ?? remembered.custom, generated: seen.generated ?? remembered.generated });
591
+ // Its own catch: a memo that fails to write must not cost this turn's title.
592
+ if (!readOnly && (titles.custom !== remembered.custom || titles.generated !== remembered.generated)) {
593
+ await store.rememberSessionTitles(sessionId, titles).catch((error) => {
594
+ debugLog('could not remember the session title:', error);
595
+ });
596
+ }
597
+ return titles;
598
+ }
599
+ catch (error) {
600
+ debugLog('could not read the session title:', error);
601
+ return {};
602
+ }
603
+ }
604
+ /** A provider-owned read model may disappear or change without costing a turn. */
605
+ async function safeNativeTitles(read) {
606
+ try {
607
+ return await read();
608
+ }
609
+ catch (error) {
610
+ debugLog('could not read the session title:', error);
611
+ return {};
612
+ }
613
+ }
343
614
  /**
344
615
  * The records of one kind, narrowed.
345
616
  *
@@ -368,16 +639,10 @@ function filterTurn(entries, stopTurnId) {
368
639
  *
369
640
  * @param stopEvent - The closing event.
370
641
  * @param records - The turn's records.
371
- * @returns The response, or undefined when none was captured.
642
+ * @returns The response's evidence, or undefined when none was recorded.
372
643
  */
373
644
  function resolveResponse(stopEvent, records) {
374
- const fromStop = responseFrom(stopEvent);
375
- if (fromStop)
376
- return fromStop;
377
- const last = recordsOfKind(records, 'response').at(-1);
378
- if (!last)
379
- return undefined;
380
- return { text: last.text, evidence: last.evidence };
645
+ return responseFrom(stopEvent) ?? recordsOfKind(records, 'response').at(-1)?.evidence;
381
646
  }
382
647
  /**
383
648
  * A copy of the closing event carrying the usage we resolved for it.
@@ -412,33 +677,74 @@ function withResolvedUsage(stopEvent, usage, billingMode) {
412
677
  * A prompt record from a prompt event.
413
678
  *
414
679
  * @param event - The prompt event.
680
+ * @param failOpenReason - Why it ran without an enforcement decision, if it did.
415
681
  * @returns The record.
416
682
  */
417
- function promptRecord(event) {
418
- const metadata = event.metadata ?? {};
683
+ function promptRecord(event, failOpenReason) {
684
+ const text = event.metadata?.[PROMPT_TEXT_KEY];
419
685
  return {
420
686
  kind: 'prompt',
421
687
  at: event.timestamp,
422
688
  turnId: event.session.turnId,
423
- text: typeof metadata[PROMPT_TEXT_KEY] === 'string' ? metadata[PROMPT_TEXT_KEY] : undefined,
424
- evidence: asEvidence(metadata[PROMPT_EVIDENCE_KEY])
689
+ evidence: asEvidence(event.metadata?.[PROMPT_EVIDENCE_KEY]),
690
+ // Enrichment already scrubbed the whole string; the bound comes after it.
691
+ text: typeof text === 'string' && text ? text.slice(0, MAX_PROMPT_TEXT_LENGTH) : undefined,
692
+ failOpenReason
425
693
  };
426
694
  }
427
695
  /**
428
696
  * A tool record from a tool-completion event.
429
697
  *
430
698
  * @param event - The tool event.
699
+ * @param cwd - This hook's own working directory, which the event's repository path is relative to.
431
700
  * @returns The record.
432
701
  */
433
- function toolRecord(event) {
702
+ function toolRecord(event, cwd) {
434
703
  const filePath = event.metadata?.[FILE_PATH_KEY];
704
+ const externalPath = event.metadata?.[EXTERNAL_PATH_KEY];
705
+ const repositoryPath = event.metadata?.[REPOSITORY_PATH_METADATA_KEY];
435
706
  return {
436
707
  kind: 'tool',
437
708
  at: event.timestamp,
438
709
  turnId: event.session.turnId,
439
710
  tool: event.tool?.name,
440
711
  filePath: typeof filePath === 'string' ? filePath : undefined,
441
- access: accessFor(event.event.type)
712
+ // Anchored here, to the cwd it was resolved against: a lasting `cd` moves
713
+ // the cwd the next hook reports, so the Stop hook's is not this one's.
714
+ repositoryRoot: typeof repositoryPath === 'string' && repositoryPath ? path.join(cwd, repositoryPath) : undefined,
715
+ access: accessFor(event.event.type),
716
+ externalPath: typeof externalPath === 'string' && externalPath ? externalPath : undefined,
717
+ input: toolInputOf(event)
718
+ };
719
+ }
720
+ /**
721
+ * The shell command or connector call a tool event carries, bounded.
722
+ *
723
+ * Reads only what the adapter already put on the event, and the adapter puts
724
+ * it there only under `capture.toolInput`; enrichment has scrubbed it, with its
725
+ * sensitive keys, before it is turned into text here.
726
+ *
727
+ * @param event - The tool event.
728
+ * @returns The input, or undefined when the call is neither or carried none.
729
+ */
730
+ function toolInputOf(event) {
731
+ const tool = event.tool?.name;
732
+ const command = event.metadata?.['command'];
733
+ const provider = asRecord(event.metadata?.['provider']);
734
+ const server = provider?.['mcpServer'];
735
+ const args = event.metadata?.['toolInput'];
736
+ if (!tool)
737
+ return undefined;
738
+ if (typeof command === 'string' && command)
739
+ return { tool: tool.slice(0, MAX_TOOL_INPUT_LENGTH), command: command.slice(0, MAX_TOOL_INPUT_LENGTH) };
740
+ if (typeof server !== 'string' || args === undefined)
741
+ return undefined;
742
+ const name = provider?.['mcpTool'];
743
+ return {
744
+ tool: tool.slice(0, MAX_TOOL_INPUT_LENGTH),
745
+ server: server.slice(0, MAX_TOOL_INPUT_LENGTH),
746
+ name: typeof name === 'string' ? name.slice(0, MAX_TOOL_INPUT_LENGTH) : undefined,
747
+ arguments: JSON.stringify(args).slice(0, MAX_TOOL_INPUT_LENGTH)
442
748
  };
443
749
  }
444
750
  /**
@@ -464,28 +770,21 @@ function accessFor(type) {
464
770
  * @returns The record.
465
771
  */
466
772
  function responseRecord(event) {
467
- const response = responseFrom(event);
468
773
  return {
469
774
  kind: 'response',
470
775
  at: event.timestamp,
471
776
  turnId: event.session.turnId,
472
- text: response?.text,
473
- evidence: response?.evidence
777
+ evidence: responseFrom(event)
474
778
  };
475
779
  }
476
780
  /**
477
- * Response text and evidence carried on an event's metadata.
781
+ * Response evidence carried on an event's metadata.
478
782
  *
479
783
  * @param event - Any canonical event.
480
- * @returns The response, or undefined when the event carries none.
784
+ * @returns The evidence, or undefined when the event carries none.
481
785
  */
482
786
  function responseFrom(event) {
483
- const metadata = event.metadata ?? {};
484
- const text = typeof metadata[RESPONSE_TEXT_KEY] === 'string' ? metadata[RESPONSE_TEXT_KEY] : undefined;
485
- const evidence = asEvidence(metadata[RESPONSE_EVIDENCE_KEY]);
486
- if (text === undefined && evidence === undefined)
487
- return undefined;
488
- return { text, evidence };
787
+ return asEvidence(event.metadata?.[RESPONSE_EVIDENCE_KEY]);
489
788
  }
490
789
  /**
491
790
  * Content evidence out of an untrusted metadata value.
@@ -499,19 +798,43 @@ function asEvidence(value) {
499
798
  return undefined;
500
799
  return { length: record['length'], sha256: record['sha256'] };
501
800
  }
801
+ /**
802
+ * The parent session the launcher declared in the environment, ahead of any
803
+ * parent the process walk found: it is stated, not inferred.
804
+ *
805
+ * ponytail: the variable is inherited by everything the child starts, so an
806
+ * agent the child launches without a launcher of its own names the
807
+ * grandparent. Launchers overwrite it, which covers spinoffs and reviews.
808
+ *
809
+ * @param env - The hook's environment.
810
+ * @param sessionId - This session's id; a session is never its own parent.
811
+ * @returns The parent session id, or undefined when none or malformed.
812
+ */
813
+ function declaredParent(env, sessionId) {
814
+ const parent = env.vars[PARENT_SESSION_VAR]?.trim();
815
+ if (!parent || parent === sessionId || !RE_PARENT_SESSION_ID.test(parent))
816
+ return undefined;
817
+ return parent;
818
+ }
502
819
  /**
503
820
  * Which surface the turn happened on.
504
821
  *
505
822
  * @param provider - Internal provider id.
506
823
  * @param env - Environment; Claude Code reports its own entrypoint there.
824
+ * @param rawPayload - Hook payload; Codex only names its originator in the transcript it points at.
507
825
  * @returns The surface label.
508
826
  */
509
- function resolveSurface(provider, env) {
827
+ export async function resolveSurface(provider, env, rawPayload) {
510
828
  if (provider === 'claude') {
511
829
  const entrypoint = env.vars[CLAUDE_ENTRYPOINT_VAR];
512
830
  if (entrypoint)
513
831
  return entrypoint;
514
832
  }
833
+ if (provider === 'codex') {
834
+ const transcriptPath = asRecord(rawPayload)?.[TRANSCRIPT_PATH_KEY];
835
+ if (typeof transcriptPath === 'string' && (await isCodexExecTranscript(transcriptPath)))
836
+ return EXEC_SURFACE;
837
+ }
515
838
  // Cursor and Antigravity hooks fire from an editor agent. Cursor's
516
839
  // is_background_agent is only available on sessionStart, not on Stop, so v1
517
840
  // reports a single surface for them.
@@ -1,3 +1,8 @@
1
+ /** A session's titles as Claude Code records them: one the user set, and the one it generated. */
2
+ export interface SessionTitles {
3
+ readonly custom?: string;
4
+ readonly generated?: string;
5
+ }
1
6
  /** Token usage read out of an agent's own transcript. */
2
7
  export interface TurnUsage {
3
8
  readonly model?: string;