@agent-watch-ai/edge 0.2.5 → 0.3.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 (346) hide show
  1. package/CHANGELOG.md +512 -0
  2. package/README.md +217 -96
  3. package/SECURITY.md +69 -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 +50 -4
  9. package/dist/cli/constants/cli.constants.js +54 -5
  10. package/dist/cli/context.d.ts +33 -2
  11. package/dist/cli/context.js +84 -14
  12. package/dist/cli/doctor.js +309 -32
  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 +439 -98
  26. package/dist/cli/status.js +82 -13
  27. package/dist/cli/toggle.d.ts +9 -0
  28. package/dist/cli/toggle.js +113 -0
  29. package/dist/cli/types/cli.types.d.ts +37 -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 +100 -13
  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 +113 -6
  41. package/dist/config/constants/config.constants.js +126 -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 +721 -84
  51. package/dist/config/schemas/config.schema.js +388 -15
  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 +111 -0
  71. package/dist/credentials/constants/credentials.constants.js +112 -0
  72. package/dist/credentials/credential-status.d.ts +14 -0
  73. package/dist/credentials/credential-status.js +34 -0
  74. package/dist/credentials/credentials.d.ts +72 -0
  75. package/dist/credentials/credentials.js +253 -0
  76. package/dist/credentials/device-api.d.ts +64 -0
  77. package/dist/credentials/device-api.js +150 -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 +62 -0
  81. package/dist/credentials/identity.js +90 -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 +18 -0
  93. package/dist/credentials/sign-in.js +86 -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 +195 -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 +62 -16
  104. package/dist/enforcement/enforcement.d.ts +23 -2
  105. package/dist/enforcement/enforcement.js +103 -15
  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 +64 -0
  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 +7 -0
  160. package/dist/pipeline/constants/pipeline.constants.js +7 -0
  161. package/dist/pipeline/hook-pipeline.js +360 -32
  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 +73 -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 +24 -2
  197. package/dist/providers/codex/codex.otel.js +147 -30
  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 +5 -0
  202. package/dist/providers/codex/constants/codex.otel.constants.js +5 -0
  203. package/dist/providers/constants/provider.constants.d.ts +0 -3
  204. package/dist/providers/constants/provider.constants.js +0 -3
  205. package/dist/providers/cursor/constants/cursor.constants.d.ts +7 -0
  206. package/dist/providers/cursor/constants/cursor.constants.js +7 -0
  207. package/dist/providers/cursor/cursor.adapter.d.ts +33 -1
  208. package/dist/providers/cursor/cursor.adapter.js +52 -3
  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 +3 -1
  215. package/dist/providers/gemini/constants/gemini.otel.constants.js +3 -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 +19 -20
  221. package/dist/providers/gemini/gemini.otel.js +121 -17
  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/constants/hook-refusal.constants.d.ts +7 -0
  232. package/dist/providers/shared/constants/hook-refusal.constants.js +7 -0
  233. package/dist/providers/shared/constants/shell-directories.constants.d.ts +30 -0
  234. package/dist/providers/shared/constants/shell-directories.constants.js +39 -0
  235. package/dist/providers/shared/constants/tooling.constants.d.ts +18 -2
  236. package/dist/providers/shared/constants/tooling.constants.js +19 -3
  237. package/dist/providers/shared/event-builder.d.ts +12 -14
  238. package/dist/providers/shared/event-builder.js +20 -14
  239. package/dist/providers/shared/exporter-allowlist.d.ts +20 -0
  240. package/dist/providers/shared/exporter-allowlist.js +49 -0
  241. package/dist/providers/shared/hook-config.d.ts +2 -21
  242. package/dist/providers/shared/hook-config.js +5 -4
  243. package/dist/providers/shared/hook-refusal.d.ts +12 -0
  244. package/dist/providers/shared/hook-refusal.js +17 -1
  245. package/dist/providers/shared/install-record.d.ts +12 -2
  246. package/dist/providers/shared/install-record.js +5 -2
  247. package/dist/providers/shared/shell-directories.d.ts +24 -0
  248. package/dist/providers/shared/shell-directories.js +90 -0
  249. package/dist/providers/shared/tooling.d.ts +12 -1
  250. package/dist/providers/shared/tooling.js +18 -0
  251. package/dist/providers/shared/types/adapter.types.d.ts +1 -2
  252. package/dist/providers/types/provider.types.d.ts +57 -1
  253. package/dist/snapshot/constants/snapshot.constants.d.ts +32 -0
  254. package/dist/snapshot/constants/snapshot.constants.js +33 -0
  255. package/dist/snapshot/snapshot-event.js +52 -11
  256. package/dist/snapshot/snapshot-pipeline.js +1 -1
  257. package/dist/snapshot/types/snapshot.types.d.ts +2 -0
  258. package/dist/storage/atomic-file.d.ts +7 -0
  259. package/dist/storage/atomic-file.js +1 -1
  260. package/dist/storage/constants/storage.constants.d.ts +17 -0
  261. package/dist/storage/constants/storage.constants.js +17 -0
  262. package/dist/storage/disabled.d.ts +13 -0
  263. package/dist/storage/disabled.js +24 -0
  264. package/dist/storage/index.d.ts +2 -0
  265. package/dist/storage/index.js +2 -0
  266. package/dist/storage/paths.js +3 -2
  267. package/dist/storage/schemas/storage.schema.d.ts +72 -0
  268. package/dist/storage/schemas/storage.schema.js +6 -0
  269. package/dist/storage/sweep-marker.d.ts +19 -0
  270. package/dist/storage/sweep-marker.js +55 -0
  271. package/dist/storage/types/storage.types.d.ts +2 -0
  272. package/dist/storage/uninstalled.d.ts +58 -0
  273. package/dist/storage/uninstalled.js +107 -0
  274. package/dist/transport/auth-block.d.ts +66 -0
  275. package/dist/transport/auth-block.js +129 -0
  276. package/dist/transport/constants/transport.constants.d.ts +82 -3
  277. package/dist/transport/constants/transport.constants.js +83 -4
  278. package/dist/transport/cooldown.js +8 -1
  279. package/dist/transport/delivery.d.ts +14 -6
  280. package/dist/transport/delivery.js +80 -55
  281. package/dist/transport/http-transport.d.ts +1 -0
  282. package/dist/transport/http-transport.js +52 -10
  283. package/dist/transport/index.d.ts +6 -3
  284. package/dist/transport/index.js +3 -0
  285. package/dist/transport/queue-partition.d.ts +91 -0
  286. package/dist/transport/queue-partition.js +143 -0
  287. package/dist/transport/queue.d.ts +99 -20
  288. package/dist/transport/queue.js +210 -69
  289. package/dist/transport/response-body.d.ts +25 -0
  290. package/dist/transport/response-body.js +64 -0
  291. package/dist/transport/send.d.ts +11 -0
  292. package/dist/transport/send.js +17 -0
  293. package/dist/transport/types/delivery-flow.types.d.ts +19 -0
  294. package/dist/transport/types/delivery-flow.types.js +1 -0
  295. package/dist/transport/types/transport.types.d.ts +45 -0
  296. package/dist/turns/claude-transcript.d.ts +19 -1
  297. package/dist/turns/claude-transcript.js +46 -1
  298. package/dist/turns/codex-originator.d.ts +11 -0
  299. package/dist/turns/codex-originator.js +31 -0
  300. package/dist/turns/codex-transcript.d.ts +30 -0
  301. package/dist/turns/codex-transcript.js +88 -0
  302. package/dist/turns/constants/turns.constants.d.ts +141 -5
  303. package/dist/turns/constants/turns.constants.js +155 -5
  304. package/dist/turns/file-identity.d.ts +27 -0
  305. package/dist/turns/file-identity.js +48 -0
  306. package/dist/turns/gemini-transcript.d.ts +30 -0
  307. package/dist/turns/gemini-transcript.js +96 -0
  308. package/dist/turns/index.d.ts +3 -3
  309. package/dist/turns/index.js +1 -1
  310. package/dist/turns/inherited-checkout.d.ts +54 -0
  311. package/dist/turns/inherited-checkout.js +155 -0
  312. package/dist/turns/native-session-titles.d.ts +26 -0
  313. package/dist/turns/native-session-titles.js +102 -0
  314. package/dist/turns/transcript.d.ts +3 -2
  315. package/dist/turns/transcript.js +5 -1
  316. package/dist/turns/turn-state.d.ts +224 -3
  317. package/dist/turns/turn-state.js +456 -21
  318. package/dist/turns/turn-summary.d.ts +1 -14
  319. package/dist/turns/turn-summary.js +87 -51
  320. package/dist/turns/turn-tracker.d.ts +21 -2
  321. package/dist/turns/turn-tracker.js +379 -56
  322. package/dist/turns/types/transcript.types.d.ts +5 -0
  323. package/dist/turns/types/turn-state.types.d.ts +116 -5
  324. package/dist/turns/types/turn-summary.types.d.ts +64 -14
  325. package/dist/turns/types/turn-tracker.types.d.ts +27 -1
  326. package/dist/turns/work-checkout.d.ts +65 -0
  327. package/dist/turns/work-checkout.js +666 -0
  328. package/dist/untraced/constants/untraced.constants.d.ts +31 -0
  329. package/dist/untraced/constants/untraced.constants.js +63 -0
  330. package/dist/untraced/untraced.d.ts +35 -0
  331. package/dist/untraced/untraced.js +105 -0
  332. package/dist/update/constants/update.constants.d.ts +18 -0
  333. package/dist/update/constants/update.constants.js +20 -0
  334. package/dist/update/update-check.d.ts +52 -0
  335. package/dist/update/update-check.js +113 -0
  336. package/docs/AUDIT_PROMPT.md +129 -0
  337. package/docs/DATA_HANDLING.md +648 -0
  338. package/docs/ENTERPRISE_DEPLOYMENT.md +179 -0
  339. package/docs/PERFORMANCE.md +81 -0
  340. package/package.json +14 -4
  341. package/dist/enrollment/enrollment-provider.d.ts +0 -5
  342. package/dist/enrollment/manual-enrollment.d.ts +0 -32
  343. package/dist/enrollment/manual-enrollment.js +0 -72
  344. package/example/README.md +0 -43
  345. package/example/server.mjs +0 -240
  346. /package/dist/{enrollment/enrollment-provider.js → config/types/destination.types.js} +0 -0
@@ -1,24 +1,41 @@
1
1
  import path from 'node:path';
2
+ import { performance } from 'node:perf_hooks';
2
3
  import { asRecord } from '../core/object.js';
4
+ import { applyProductCapture } from '../privacy/product-capture.js';
3
5
  import { debugLog } from '../core/logger.js';
4
6
  import { next, runFlow, step, stop } from '../core/pipe.js';
5
7
  import { loadEffectiveConfig } from '../config/repo-config.js';
8
+ import { CREDENTIAL_BUDGET_SHARE } from '../credentials/constants/credentials.constants.js';
9
+ import { cachedBearer, resolveBearer } from '../credentials/credentials.js';
10
+ import { hasCredential, identityOf } from '../credentials/identity.js';
11
+ import { credentialScope, inheritedRootConfig, selectRoot, servesMultipleIdentities } from '../config/root-config.js';
6
12
  import { DECISION_BLOCK } from '../enforcement/constants/enforcement.constants.js';
7
- import { resolveEnforcement } from '../enforcement/enforcement.js';
13
+ import { enforcementWouldAsk, resolveEnforcement } from '../enforcement/enforcement.js';
14
+ import { sessionBillingFact } from '../billing/session-billing.js';
8
15
  import { enrichEvents } from '../events/enrich.js';
16
+ import { readGateCheckout } from '../git/gate-checkout.js';
17
+ import { checkoutRootOf } from '../git/checkout-root.js';
18
+ import { normalizeRemote } from '../git/remote-sanitize.js';
9
19
  import { developerIdentity, runGit } from '../git/git-context.js';
20
+ import { shellDirectories } from '../providers/shared/shell-directories.js';
10
21
  import { runSnapshotPipeline } from '../snapshot/snapshot-pipeline.js';
11
22
  import { SnapshotStateStore } from '../snapshot/snapshot-state.js';
12
23
  import { SNAPSHOT_BUDGET_MS } from '../snapshot/constants/snapshot.constants.js';
24
+ import { BackendAuthBlock } from '../transport/auth-block.js';
13
25
  import { BackendCooldown } from '../transport/cooldown.js';
14
26
  import { DeliveryStats } from '../transport/delivery-stats.js';
15
27
  import { deliverEvents } from '../transport/delivery.js';
16
28
  import { HttpTransport } from '../transport/http-transport.js';
17
29
  import { EventQueue } from '../transport/queue.js';
18
- import { COOLDOWN_FILE_NAME, DELIVERY_STATS_FILE_NAME } from '../transport/constants/transport.constants.js';
30
+ import { identityPaths, settleLegacyQueue } from '../transport/queue-partition.js';
19
31
  import { eventsUrl } from '../config/config.js';
20
- import { trackTurn } from '../turns/turn-tracker.js';
21
- import { PAYLOAD_CWD_KEY, PROMPT_SUBMITTED_TYPE, STAGE_DELIVER, STAGE_ENFORCE, STAGE_ENRICH, STAGE_PARSE_EVENTS, STAGE_RESOLVE_CONTEXT, STAGE_SNAPSHOT, STAGE_TRACK_TURN, STOP_DRY_RUN, STOP_NO_EVENTS, STOP_NO_SNAPSHOT } from './constants/pipeline.constants.js';
32
+ import { untracedNotice as untracedNoticeText } from '../untraced/constants/untraced.constants.js';
33
+ import { isRunCommand, manifestVerdict, rootHash } from '../untraced/untraced.js';
34
+ import { installedPackage, startUpdateCheck, updateNotice } from '../update/update-check.js';
35
+ import { TurnStateStore } from '../turns/turn-state.js';
36
+ import { MAX_TURN_CHECKOUTS, SHELL_REREAD_TYPES, TOOL_START_TYPES } from '../turns/constants/turns.constants.js';
37
+ import { resolveSurface, trackTurnOutcome } from '../turns/turn-tracker.js';
38
+ import { PAYLOAD_CWD_KEY, PROMPT_SUBMITTED_TYPE, STAGE_DELIVER, STAGE_ENFORCE, STAGE_ENRICH, MAX_WORKSPACE_ROOTS, STAGE_NOMINATE, STAGE_PARSE_EVENTS, STAGE_RESOLVE_CONTEXT, STAGE_SNAPSHOT, STAGE_TRACK_TURN, STAGE_UNTRACED, STAGE_UPDATE, QUIET_SESSION_SOURCES, STOP_DRY_RUN, STOP_NO_EVENTS, STOP_NO_SNAPSHOT } from './constants/pipeline.constants.js';
22
39
  /**
23
40
  * The hook flow, as the list of stages it is.
24
41
  *
@@ -33,6 +50,9 @@ import { PAYLOAD_CWD_KEY, PROMPT_SUBMITTED_TYPE, STAGE_DELIVER, STAGE_ENFORCE, S
33
50
  const HOOK_STAGES = [
34
51
  step(STAGE_RESOLVE_CONTEXT, resolveContext),
35
52
  step(STAGE_PARSE_EVENTS, parseEvents),
53
+ step(STAGE_NOMINATE, nominate),
54
+ step(STAGE_UNTRACED, untracedNotice),
55
+ step(STAGE_UPDATE, updateNoticeStage),
36
56
  step(STAGE_ENFORCE, enforce),
37
57
  step(STAGE_ENRICH, enrich),
38
58
  step(STAGE_TRACK_TURN, trackTurnStage),
@@ -53,7 +73,7 @@ export function runHookPipeline(input) {
53
73
  const initial = {
54
74
  ...input,
55
75
  cwd: resolvePayloadCwd(input),
56
- config: input.globalConfig,
76
+ config: input.globalConfig.config,
57
77
  events: [],
58
78
  outbound: []
59
79
  };
@@ -73,8 +93,8 @@ export function runHookPipeline(input) {
73
93
  * @returns The state with its effective config resolved.
74
94
  */
75
95
  async function resolveContext(state) {
76
- const effective = await loadEffectiveConfig(state.paths, state.cwd);
77
- return next({ ...state, config: effective.config });
96
+ const effective = await loadEffectiveConfig(state.paths, state.cwd, state.globalConfig);
97
+ return next({ ...state, config: effective.config, credentialScope: credentialScope(selectRoot(state.globalConfig.config.roots, state.cwd)) });
78
98
  }
79
99
  /**
80
100
  * Turn the payload into canonical events.
@@ -88,6 +108,126 @@ async function parseEvents(state) {
88
108
  return stop(state, STOP_NO_EVENTS);
89
109
  return next({ ...state, events });
90
110
  }
111
+ /**
112
+ * Name the checkouts a shell call is about to work in.
113
+ *
114
+ * The only place the edge reads a shell command. It is read in memory for
115
+ * directory names, each name becomes the real root of the checkout it lies in,
116
+ * and only those roots go on: the command and every directory in it go out of
117
+ * scope here, and nothing — not the state, an event, a record or a log line —
118
+ * holds either. A failure logs a fixed sentence, never its error, which could
119
+ * quote a path.
120
+ *
121
+ * A working directory the agent names for the call (Codex `workdir`, Cursor's
122
+ * shell `cwd`) is nominated as it stands, and the command's relative paths are
123
+ * read against it. The folders an agent has open (Cursor's workspace roots) are
124
+ * candidates too, but weak ones: they say where the agent sits, not what the
125
+ * call named.
126
+ *
127
+ * Only on a tool-start hook, or a tool call's completion, failed or not (a shell
128
+ * command may have created the worktree it named; `shellCall` answers only for
129
+ * a shell), and only while git capture is on: which checkout a
130
+ * turn worked in is git metadata, and a developer who turned that off said no.
131
+ * Open folders are read on a tool start only.
132
+ *
133
+ * @param state - Current flow state.
134
+ * @returns The state, with the named checkouts' roots.
135
+ */
136
+ async function nominate(state) {
137
+ const start = state.events.some((event) => TOOL_START_TYPES.has(event.event.type));
138
+ if (!state.config.capture.git || (!start && !state.events.some((event) => SHELL_REREAD_TYPES.has(event.event.type))))
139
+ return next(state);
140
+ try {
141
+ const call = state.provider.shellCall?.(state.payload);
142
+ // Untrusted: only an absolute directory is taken, never one resolved against a guess.
143
+ const workdir = typeof call?.workdir === 'string' && path.isAbsolute(call.workdir) ? call.workdir : undefined;
144
+ const named = [
145
+ ...(workdir ? [workdir] : []),
146
+ ...(typeof call?.command === 'string' && call.command ? shellDirectories(call.command, workdir ?? state.cwd, state.env.home) : [])
147
+ ];
148
+ // ponytail: the first few open checkouts only, so weak candidates never fill a
149
+ // turn's checkout slots before a call names one; a wider window loses the rest.
150
+ // The folders looked at are bounded too, since the list is untrusted.
151
+ const open = [...new Set((start ? (state.provider.workspaceRoots?.(state.payload) ?? []) : []).filter((root) => typeof root === 'string' && path.isAbsolute(root)))].slice(0, MAX_TURN_CHECKOUTS);
152
+ const [nominations, openRoots] = await Promise.all([checkoutRoots(named), checkoutRoots(open)]);
153
+ return next({ ...state, nominations, workspaceRoots: openRoots.slice(0, MAX_WORKSPACE_ROOTS) });
154
+ }
155
+ catch {
156
+ debugLog('shell nomination failed; this call names no checkout');
157
+ return next(state);
158
+ }
159
+ }
160
+ /**
161
+ * Tell the developer, as a session starts or resumes, that npm has a newer release.
162
+ *
163
+ * Not on Claude Code's `clear` or `compact` starts: those happen mid-session,
164
+ * and the line would come back after every compaction.
165
+ *
166
+ * Reads a local cache only; a stale one starts a detached registry check whose
167
+ * answer shows on the next session. Every failure means no notice.
168
+ *
169
+ * @param state - Current flow state.
170
+ * @returns The state, carrying the notice when one is due.
171
+ */
172
+ async function updateNoticeStage(state) {
173
+ if (state.dryRun || state.notice !== undefined || !state.config.updateNotices || !state.provider.getNoticeResponse)
174
+ return next(state);
175
+ if (!state.events.some((event) => event.event.type === 'session.started'))
176
+ return next(state);
177
+ if (QUIET_SESSION_SOURCES.has(String(asRecord(state.payload)?.['source'])))
178
+ return next(state);
179
+ const notice = await updateNotice(state.paths.dataDir, state.env.now(), installedPackage().version, () => startUpdateCheck(state.env));
180
+ return next(notice === undefined ? state : { ...state, notice });
181
+ }
182
+ /**
183
+ * Tell the developer, once per repository per session, that a run called an
184
+ * LLM with no tracing (AWT-310).
185
+ *
186
+ * Decided on this machine from the dependency manifests alone: it adds no
187
+ * event, field or request, and every failure — an unreadable manifest, a store
188
+ * that cannot be written — means no notice, never a failed hook. The command is
189
+ * read in memory for the one question "is this a run?" and goes no further.
190
+ *
191
+ * @param state - Current flow state.
192
+ * @returns The state, carrying the notice when this run earns one.
193
+ */
194
+ async function untracedNotice(state) {
195
+ if (state.dryRun || !state.config.untracedNotices || !state.provider.getNoticeResponse)
196
+ return next(state);
197
+ const sessionId = state.events.find((event) => event.event.type === 'shell.completed')?.session.id;
198
+ if (!sessionId)
199
+ return next(state);
200
+ try {
201
+ const call = state.provider.shellCall?.(state.payload);
202
+ if (typeof call?.command !== 'string' || !isRunCommand(call.command))
203
+ return next(state);
204
+ const workdir = typeof call.workdir === 'string' && path.isAbsolute(call.workdir) ? call.workdir : state.cwd;
205
+ // The checkouts the command names, then the one the agent sits in: the run may be in either.
206
+ const here = await checkoutRootOf(workdir);
207
+ const roots = [...new Set([...(state.nominations ?? []), ...(here ? [here] : [])])];
208
+ for (const root of roots) {
209
+ const verdict = await manifestVerdict(root, state.paths.dataDir);
210
+ if (verdict.providers.length === 0 || verdict.traced)
211
+ continue;
212
+ if (await new TurnStateStore(state.paths.turnsDir).takeNotice(sessionId, rootHash(root)))
213
+ return next({ ...state, notice: untracedNoticeText(verdict.providers) });
214
+ }
215
+ }
216
+ catch {
217
+ debugLog('untraced: check failed; no notice');
218
+ }
219
+ return next(state);
220
+ }
221
+ /**
222
+ * The distinct checkout roots a list of paths lies in, `stat`s only.
223
+ *
224
+ * @param paths - Absolute paths.
225
+ * @returns Canonical roots, in first-seen order.
226
+ */
227
+ async function checkoutRoots(paths) {
228
+ const roots = await Promise.all(paths.map(checkoutRootOf));
229
+ return [...new Set(roots.filter((root) => root !== undefined))];
230
+ }
91
231
  /**
92
232
  * Ask the platform whether this turn may start.
93
233
  *
@@ -104,30 +244,142 @@ async function parseEvents(state) {
104
244
  * @returns The state, carrying the refusal when there is one.
105
245
  */
106
246
  async function enforce(state) {
107
- if (state.dryRun || !state.provider.getBlockResponse || !isTurnGate(state))
247
+ if (state.dryRun || !state.provider.getBlockResponse)
248
+ return next(state);
249
+ const prompt = turnGateEvent(state);
250
+ if (!prompt)
251
+ return next(state);
252
+ // Nothing below is paid for on a machine that would not ask. Working out which
253
+ // checkout this is costs a walk of the working copy and, once per checkout, a
254
+ // git process — small, and still the wrong thing to spend on a developer whose
255
+ // organization set no cap.
256
+ if (!enforcementWouldAsk(state.config))
108
257
  return next(state);
258
+ // Together, not in turn. Each can cost its own git timeout, and taken in order
259
+ // a slow machine pays both before the agent's first token. Resolving the
260
+ // identity first would save a checkout lookup only on a machine that has no
261
+ // identity at all — a rare and stable condition — at the price of doubling the
262
+ // worst case for everyone else. The session's model joins them for the same
263
+ // reason: it is one small file, and it is still a file.
264
+ const [developerId, checkout, model] = await Promise.all([
265
+ developerIdentity(state.config.developerEmail, state.cwd, { home: state.env.home }),
266
+ gateCheckout(state, prompt),
267
+ statedModel(state, prompt)
268
+ ]);
269
+ // Cached only: a refresh or an exchange may cost a network round trip, and
270
+ // this sits between enter and the agent's first token. Delivery refreshes.
271
+ const bearer = await cachedBearer(credentialContext(state, state.config.enforcement.timeoutMs), state.config);
109
272
  const decision = await resolveEnforcement({
110
273
  config: state.config,
111
274
  paths: state.paths,
112
- developerId: await developerIdentity(state.config.developerEmail, state.cwd, { home: state.env.home }),
275
+ developerId,
276
+ checkout,
277
+ model,
278
+ ...(bearer ? { bearer } : {}),
113
279
  now: state.env.now
114
280
  });
115
281
  if (decision.decision !== DECISION_BLOCK)
116
- return next(state);
282
+ return next({ ...state, failOpenReason: decision.failOpenReason });
117
283
  return next({ ...state, blockMessage: decision.message });
118
284
  }
119
285
  /**
120
- * Whether this payload is the moment before the turn's first LLM call.
286
+ * The event that makes this payload the moment before the turn's first LLM
287
+ * call, if it is one.
121
288
  *
122
289
  * @param state - Current flow state.
123
- * @returns True when the provider reported a submitted prompt.
290
+ * @returns The submitted prompt, or undefined when this hook is not a gate.
124
291
  */
125
- function isTurnGate(state) {
292
+ function turnGateEvent(state) {
126
293
  for (const event of state.events) {
127
294
  if (event.event.type === PROMPT_SUBMITTED_TYPE)
128
- return true;
295
+ return event;
296
+ }
297
+ return undefined;
298
+ }
299
+ /**
300
+ * The checkout to state on the gate request.
301
+ *
302
+ * From a session's second turn on, the checkout its last turn changed, wherever
303
+ * the agent sits now: a spinoff parked in the docs repository that edits a
304
+ * feature worktree is working on that feature. The turn tracker wrote down the
305
+ * checkout's root and repository, so this costs one small file and the same
306
+ * `.git` walk as today, and the branch is still read from `HEAD` on disk, so a
307
+ * switch since that turn is seen. No git process: the repository is the one
308
+ * remembered.
309
+ *
310
+ * Only a checkout the asking tenant's root governs: the config (and so the token)
311
+ * asking here comes from the folder the agent sits in, and another tenant's
312
+ * repository must never travel on it. With no roots there is one tenant, and the
313
+ * tracker only remembered a checkout beneath the session's start folder.
314
+ *
315
+ * Anything missing, unreadable, gone or on a detached HEAD answers exactly what
316
+ * today's lookup of the agent's own folder answers.
317
+ *
318
+ * @param state - Current flow state.
319
+ * @param prompt - The prompt event being gated.
320
+ * @returns The checkout, or undefined when none is known.
321
+ */
322
+ async function gateCheckout(state, prompt) {
323
+ const base = { checkoutsDir: state.paths.checkoutsDir, now: state.env.now };
324
+ const work = await lastWorkCheckout(state, prompt.session.id);
325
+ const carried = work && await readGateCheckout({ ...base, cwd: work.root, repository: work.repository });
326
+ return carried ?? readGateCheckout({ ...base, cwd: state.cwd });
327
+ }
328
+ /**
329
+ * The session's last changed checkout, when the asking tenant may name it.
330
+ *
331
+ * @param state - Current flow state.
332
+ * @param sessionId - Provider session id, if the prompt has one.
333
+ * @returns The remembered checkout, or undefined.
334
+ */
335
+ async function lastWorkCheckout(state, sessionId) {
336
+ if (!sessionId)
337
+ return undefined;
338
+ try {
339
+ const work = await new TurnStateStore(state.paths.turnsDir).readWorkCheckout(sessionId);
340
+ const roots = state.globalConfig.config.roots;
341
+ // Only a value already in the canonical, credential-free form git capture
342
+ // produces: a checkout with no remote is remembered by its folder name, which
343
+ // names no repository (today's gate states nothing for it either), and a
344
+ // damaged or hand-edited file must never put anything else on the request.
345
+ if (!work || normalizeRemote(`https://${work.repository}`) !== work.repository)
346
+ return undefined;
347
+ return selectRoot(roots, work.root)?.path === selectRoot(roots, state.cwd)?.path ? work : undefined;
348
+ }
349
+ catch {
350
+ // A fixed sentence: the error could quote a path.
351
+ debugLog('enforcement: last work checkout unreadable; asking about the current folder');
352
+ return undefined;
353
+ }
354
+ }
355
+ /**
356
+ * The model to state on the gate request.
357
+ *
358
+ * Codex, Cursor, Gemini and Antigravity name their model on the prompt hook
359
+ * itself. Claude Code names it only when the session starts, so the tracker
360
+ * wrote it down and this reads it back — one small file, inside the same
361
+ * `Promise.all` as identity and checkout, so it adds no serial wait to the gate.
362
+ *
363
+ * Anything that goes wrong states nothing: the model narrows the question, and a
364
+ * question asked without it is still answered.
365
+ *
366
+ * @param state - Current flow state.
367
+ * @param prompt - The prompt event being gated.
368
+ * @returns The model, or undefined when none is known.
369
+ */
370
+ async function statedModel(state, prompt) {
371
+ if (prompt.ai?.model)
372
+ return prompt.ai.model;
373
+ const sessionId = prompt.session.id;
374
+ if (!sessionId)
375
+ return undefined;
376
+ try {
377
+ return await new TurnStateStore(state.paths.turnsDir).readModel(sessionId);
378
+ }
379
+ catch (error) {
380
+ debugLog('enforcement: session model unreadable; stating none:', error);
381
+ return undefined;
129
382
  }
130
- return false;
131
383
  }
132
384
  /**
133
385
  * Attach development context and scrub the events.
@@ -159,33 +411,70 @@ async function trackTurnStage(state) {
159
411
  // Assembly failing must not cost the *queue* its drain: a hook that produced
160
412
  // no summary still has a backlog to move, so this stage degrades to "no
161
413
  // summary" instead of ending the flow.
162
- const summary = await trackTurnSafely(state);
163
- const outbound = summary && state.config.emit.turnSummaries ? [summary] : [];
164
- return next({ ...state, summary, outbound });
414
+ const { summary, workRoot, capture } = await trackTurnSafely(state);
415
+ // Re-applied under the reported checkout's own policy when it has one: that
416
+ // checkout's file decides what is said about it, not the folder the Stop ran in.
417
+ const workCapture = capture ?? state.config.capture;
418
+ // A session started in no root, working in a checkout a root claims, sends as
419
+ // that root: its token, destination and queue, from this close on. The summary
420
+ // is the only thing that leaves, and it is built here, so nothing earlier in
421
+ // the session was sent under another identity.
422
+ const routed = inheritedRootConfig(state.globalConfig.config, summary?.work_evidence, workRoot);
423
+ const config = routed ? (await loadEffectiveConfig(state.paths, workRoot, state.globalConfig)).config : state.config;
424
+ const gated = summary && config.emit.turnSummaries ? applyProductCapture(summary, workCapture) : undefined;
425
+ const billing = config.emit.turnSummaries && !state.dryRun ? await billingFactSafely(state) : undefined;
426
+ const outbound = [...(billing ? [billing] : []), ...(gated ? [gated] : [])];
427
+ const scope = routed ? credentialScope(selectRoot(state.globalConfig.config.roots, workRoot)) : state.credentialScope;
428
+ return next({ ...state, config, credentialScope: scope, summary, workRoot, workCapture, outbound });
429
+ }
430
+ /**
431
+ * The session's billing fact, or nothing on any failure.
432
+ *
433
+ * Sent when the session opens rather than with the turn summary, because a turn
434
+ * that never reaches its Stop hook never produces one (AWT-476). Best effort:
435
+ * a hook never fails for it, and the offline queue carries it like any record.
436
+ *
437
+ * @param state - Current flow state.
438
+ * @returns The event, when this hook opened the session and its mode is known.
439
+ */
440
+ async function billingFactSafely(state) {
441
+ try {
442
+ const surface = await resolveSurface(state.events[0]?.agent.provider ?? state.provider.id, state.env, state.payload);
443
+ return await sessionBillingFact(new TurnStateStore(state.paths.turnsDir), state.events, state.provider.id, state.env, surface);
444
+ }
445
+ catch (error) {
446
+ debugLog('session billing fact failed:', error);
447
+ return undefined;
448
+ }
165
449
  }
166
450
  /**
167
451
  * Assemble the turn, degrading to no summary on any failure.
168
452
  *
169
453
  * @param state - Current flow state.
170
- * @returns The summary, or undefined.
454
+ * @returns The summary and the local root it reported, or neither.
171
455
  */
172
456
  async function trackTurnSafely(state) {
173
457
  try {
174
- return await trackTurn({
458
+ return await trackTurnOutcome({
175
459
  agentId: state.provider.id,
176
460
  rawPayload: state.payload,
177
461
  events: state.events,
178
462
  config: state.config,
463
+ globalConfig: state.globalConfig,
464
+ paths: state.paths,
179
465
  turnsDir: state.paths.turnsDir,
180
466
  locksDir: state.paths.locksDir,
181
467
  env: state.env,
182
468
  cwd: state.cwd,
183
- readOnly: state.dryRun
469
+ readOnly: state.dryRun,
470
+ failOpenReason: state.failOpenReason,
471
+ nominations: state.nominations,
472
+ workspaceRoots: state.workspaceRoots
184
473
  });
185
474
  }
186
475
  catch (error) {
187
476
  debugLog('turn summary failed:', error);
188
- return undefined;
477
+ return {};
189
478
  }
190
479
  }
191
480
  /**
@@ -197,8 +486,20 @@ async function trackTurnSafely(state) {
197
486
  async function deliver(state) {
198
487
  if (state.dryRun)
199
488
  return stop(state, STOP_DRY_RUN);
200
- const queue = buildQueue(state);
201
- const delivery = await deliverEvents(state.outbound, buildTransport(state), queue, state.config.delivery.drainBatchSize, new BackendCooldown(path.join(state.paths.dataDir, COOLDOWN_FILE_NAME), state.env.now), new DeliveryStats(path.join(state.paths.dataDir, DELIVERY_STATS_FILE_NAME), state.env.now, state.paths.locksDir));
489
+ // `globalConfig`, not `config`: roots are stripped from the effective config
490
+ // once applied, and the question is what the *machine* sends as.
491
+ await settleLegacyQueue(state.paths.queueDir, identityOf(state.config), servesMultipleIdentities(state.globalConfig.config));
492
+ const identity = identityPaths(state.paths, identityOf(state.config));
493
+ // One budget for the credential and the send: credential work (a keychain
494
+ // read, a refresh, an exchange) may spend its share of it and no more, and
495
+ // the send gets what is left. A hook never waits longer than it did before.
496
+ // `resolveBearer` never throws: a failure there leaves no bearer, and the
497
+ // transport defers, so the run's records queue.
498
+ const budgetMs = state.config.delivery.timeoutMs;
499
+ const started = performance.now();
500
+ const bearer = await resolveBearer({ ...credentialContext(state, budgetMs), deadline: started + budgetMs * CREDENTIAL_BUDGET_SHARE }, state.config);
501
+ const remaining = Math.max(0, budgetMs - (performance.now() - started));
502
+ const delivery = await deliverEvents(state.outbound, buildTransport(state, bearer, remaining), buildQueue(state), state.config.delivery.drainBatchSize, new BackendCooldown(identity.cooldownFile, state.env.now), new DeliveryStats(identity.statsFile, state.env.now, state.paths.locksDir), new BackendAuthBlock(identity.authBlockFile, state.env.now));
202
503
  debugLog(`delivery: sent=${delivery.delivered} queued=${delivery.queued} drained=${delivery.drained} rejected=${delivery.rejected}`);
203
504
  return next({ ...state, delivery });
204
505
  }
@@ -220,11 +521,18 @@ async function deliver(state) {
220
521
  */
221
522
  async function snapshot(state) {
222
523
  const repository = state.summary?.repository;
223
- if (!repository || !state.config.capture.git)
524
+ // Never for an inherited repository: core may drop it when folder evidence
525
+ // disagrees, and a snapshot of it would mint a work unit for the wrong one.
526
+ const capture = state.workCapture ?? state.config.capture;
527
+ if (!repository || state.summary?.work_evidence === 'inherited' || !capture.git)
224
528
  return stop(state, STOP_NO_SNAPSHOT);
225
529
  await runSnapshotPipeline({
226
530
  input: {
227
- cwd: state.cwd,
531
+ // The checkout the summary named, which need not be the folder the agent sits in.
532
+ cwd: state.workRoot ?? state.cwd,
533
+ // The repository's own policy, which may lower the global one: file names
534
+ // off means the files listing never runs, not that it is emptied later.
535
+ files: capture.files !== false,
228
536
  repository,
229
537
  provider: state.summary?.provider ?? state.provider.id,
230
538
  surface: state.summary?.surface ?? state.provider.id,
@@ -244,38 +552,58 @@ async function snapshot(state) {
244
552
  return next(state);
245
553
  }
246
554
  /**
247
- * The offline queue for this run.
555
+ * The offline queue for this run, partitioned by the identity it sends as.
556
+ * `deliver` settles a pre-partition backlog before the first build.
248
557
  *
249
558
  * @param state - Current flow state.
250
559
  * @returns A queue bound to this run's paths and delivery limits.
251
560
  */
252
561
  function buildQueue(state) {
562
+ const identity = identityPaths(state.paths, identityOf(state.config));
253
563
  return new EventQueue({
254
- queueDir: state.paths.queueDir,
564
+ queueDir: identity.queueDir,
255
565
  locksDir: state.paths.locksDir,
256
566
  maxEvents: state.config.delivery.maxQueueEvents,
257
567
  maxAttempts: state.config.delivery.maxAttempts,
258
568
  maxEventAgeDays: state.config.delivery.maxEventAgeDays,
259
- now: state.env.now
569
+ now: state.env.now,
570
+ // So the entries the bound sacrifices are counted wherever an enqueue
571
+ // happens, the snapshot pipeline's included.
572
+ stats: new DeliveryStats(identity.statsFile, state.env.now, state.paths.locksDir)
260
573
  });
261
574
  }
262
575
  /**
263
576
  * The transport for this run, when a backend is configured.
264
577
  *
265
578
  * @param state - Current flow state.
579
+ * @param bearer - What to authenticate with; see `resolveBearer`.
580
+ * @param budgetMs - What is left of the delivery budget.
266
581
  * @returns The transport, or undefined before setup has run.
267
582
  */
268
- function buildTransport(state) {
583
+ function buildTransport(state, bearer, budgetMs) {
269
584
  const url = eventsUrl(state.config);
270
585
  if (!url)
271
586
  return undefined;
272
587
  return new HttpTransport({
273
588
  eventsUrl: url,
274
- token: state.config.token,
589
+ capture: state.config.capture,
590
+ token: bearer,
591
+ credentialPending: hasCredential(state.config) && !bearer,
275
592
  installationId: state.config.installationId,
276
- timeoutMs: state.config.delivery.timeoutMs
593
+ timeoutMs: state.config.delivery.timeoutMs,
594
+ budgetMs
277
595
  });
278
596
  }
597
+ /**
598
+ * What the credential code needs from this run.
599
+ *
600
+ * @param state - Current flow state.
601
+ * @param timeoutMs - Ceiling for one keychain read or gateway call.
602
+ * @returns The context.
603
+ */
604
+ function credentialContext(state, timeoutMs) {
605
+ return { env: state.env, paths: state.paths, timeoutMs, hookPath: true, scope: state.credentialScope };
606
+ }
279
607
  /**
280
608
  * Where this payload happened.
281
609
  *
@@ -1,6 +1,8 @@
1
- import type { AgentWatchConfig } from '../../config/types/config.types.js';
1
+ import type { AgentWatchConfig, CaptureConfig, ConfigLoadResult } from '../../config/types/config.types.js';
2
2
  import type { Env } from '../../core/types/core.types.js';
3
+ import type { FailOpenReason } from '../../enforcement/types/enforcement.types.js';
3
4
  import type { AgentWatchEvent } from '../../events/types/events.types.js';
5
+ import type { ProductEvent } from '../../events/product-event.js';
4
6
  import type { AgentProvider } from '../../providers/types/provider.types.js';
5
7
  import type { AgentWatchPaths } from '../../storage/types/storage.types.js';
6
8
  import type { TurnSummaryEvent } from '../../turns/types/turn-summary.types.js';
@@ -10,8 +12,15 @@ export interface HookPipelineInput {
10
12
  readonly provider: AgentProvider;
11
13
  readonly env: Env;
12
14
  readonly paths: AgentWatchPaths;
13
- /** The machine-global configuration, before the repository overlay. */
14
- readonly globalConfig: AgentWatchConfig;
15
+ /**
16
+ * The machine-global configuration as loaded, before the repository overlay.
17
+ *
18
+ * The load *result*, not just the config: the repository overlay is refused
19
+ * outright when the global file is missing or corrupt, so the stage that
20
+ * applies it needs to know which — and carrying it here is what keeps the
21
+ * hook path down to one read of the file.
22
+ */
23
+ readonly globalConfig: ConfigLoadResult;
15
24
  /** Decoded hook payload. */
16
25
  readonly payload: unknown;
17
26
  /** Preview only: append nothing, consume nothing, send nothing. */
@@ -28,6 +37,8 @@ export interface HookPipelineState extends HookPipelineInput {
28
37
  readonly cwd: string;
29
38
  /** Global config with the repository overlay applied. */
30
39
  readonly config: AgentWatchConfig;
40
+ /** The uninstall-marker scope of `config`'s credential; absent for the machine's. */
41
+ readonly credentialScope?: string;
31
42
  /** Canonical events the provider adapter produced. */
32
43
  readonly events: readonly AgentWatchEvent[];
33
44
  /**
@@ -39,10 +50,34 @@ export interface HookPipelineState extends HookPipelineInput {
39
50
  * a refusal without a message — so its presence *is* the refusal.
40
51
  */
41
52
  readonly blockMessage?: string;
53
+ /**
54
+ * A line for the developer: after a shell run that called an LLM with no
55
+ * tracing (AWT-310, the `untraced` stage), or at session start when a newer
56
+ * release exists (the `update` stage). Never sent anywhere.
57
+ */
58
+ readonly notice?: string;
59
+ /**
60
+ * Why the turn was allowed without a decision, when it was. Set only by the
61
+ * `enforce` stage; carried onto the prompt record so the turn's summary can
62
+ * say it ran unchecked.
63
+ */
64
+ readonly failOpenReason?: FailOpenReason;
65
+ /**
66
+ * The real roots of the checkouts this payload's shell command names. Roots
67
+ * only: the command and the directories in it never leave the `nominate`
68
+ * stage.
69
+ */
70
+ readonly nominations?: readonly string[];
71
+ /** The real roots of the folders the agent has open, when it reports them (Cursor). Roots only. */
72
+ readonly workspaceRoots?: readonly string[];
73
+ /** Local root of the checkout the closed turn reported; where its snapshot is taken. Never sent. */
74
+ readonly workRoot?: string;
75
+ /** That checkout's own capture policy, re-applied to the summary and asked by the snapshot. */
76
+ readonly workCapture?: CaptureConfig;
42
77
  /** The turn summary, when this payload closed a turn. */
43
78
  readonly summary?: TurnSummaryEvent;
44
79
  /** Records this run intends to send; empty on a dry run. */
45
- readonly outbound: readonly TurnSummaryEvent[];
80
+ readonly outbound: readonly ProductEvent[];
46
81
  /** What delivery did, when it ran. */
47
82
  readonly delivery?: DeliveryOutcome;
48
83
  }
@@ -21,7 +21,21 @@ export const SENSITIVE_KEY_PATTERN = /(^|[_.-])(authorization|auth|token|secret|
21
21
  */
22
22
  export const SECRET_PATTERNS = [
23
23
  { name: 'private-key-block', pattern: /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g },
24
- { name: 'url-credentials', pattern: /(\w+:\/\/)([^/\s:@]+)(?::([^/\s@]+))?@/g, replacement: `$1${REDACTED}@` },
24
+ // The scheme is the only part that was quadratic: `\w+` re-consumed the rest of
25
+ // the string at every start index before backtracking to look for `://`, which
26
+ // cost 1.8s on a 64KiB prompt and 17s on a 200_000-character one, on the
27
+ // agent's hook path. `\w{1,32}` ends that, and no real scheme comes near 32 —
28
+ // `\w` never matched `mongodb+srv` in the first place. That bound is what makes
29
+ // scrubbing the *whole* string affordable, which `sanitizeText` needs in order
30
+ // to redact a credential straddling the length cap.
31
+ //
32
+ // The userinfo groups stay unbounded on purpose. A negated class that cannot
33
+ // cross `@` or whitespace cannot backtrack the same way — measured linear, 21ms
34
+ // on a 200_000-character run with no `@` in it — while a ceiling there leaks
35
+ // every credential longer than it: a 300-character URL password went out in the
36
+ // clear under a `{1,256}` bound, and a signed URL, a service-account secret or
37
+ // a JWT used as a password is routinely longer than that.
38
+ { name: 'url-credentials', pattern: /(\w{1,32}:\/\/)([^/\s:@]+)(?::([^/\s@]+))?@/g, replacement: `$1${REDACTED}@` },
25
39
  { name: 'aws-access-key', pattern: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g },
26
40
  { name: 'github-token', pattern: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\b/g },
27
41
  { name: 'github-fine-grained', pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}\b/g },
@@ -5,3 +5,4 @@
5
5
  export type { SecretPattern } from './types/privacy.types.js';
6
6
  export { REDACTED, SECRET_PATTERNS, SENSITIVE_KEY_PATTERN } from './constants/privacy.constants.js';
7
7
  export { sanitizeText, sanitizeValue } from './sanitizer.js';
8
+ export { applyProductCapture } from './product-capture.js';
@@ -1,2 +1,3 @@
1
1
  export { REDACTED, SECRET_PATTERNS, SENSITIVE_KEY_PATTERN } from './constants/privacy.constants.js';
2
2
  export { sanitizeText, sanitizeValue } from './sanitizer.js';
3
+ export { applyProductCapture } from './product-capture.js';
@@ -0,0 +1,12 @@
1
+ import type { CaptureConfig } from '../config/types/config.types.js';
2
+ import type { ProductEvent } from '../events/product-event.js';
3
+ /**
4
+ * Reapply current capture policy to persisted records before queueing or sending.
5
+ * Old turn state and offline events may predate a flag change — or this release —
6
+ * so the gate runs again here rather than only where the record was built.
7
+ * @param event - Product record, possibly from an older installation.
8
+ * @param capture - Effective, consent-gated capture flags. Metadata follows the
9
+ * schema defaults, so only an explicit `false` drops it.
10
+ * @returns A sanitized copy, or undefined when the whole record is no longer allowed.
11
+ */
12
+ export declare function applyProductCapture<T extends ProductEvent>(event: T, capture?: CaptureConfig): T | undefined;