@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
@@ -0,0 +1,666 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { REPO_CONFIG_NAME } from '../config/constants/config.constants.js';
4
+ import { loadEffectiveConfig } from '../config/repo-config.js';
5
+ import { asRecord } from '../core/object.js';
6
+ import { canonicalRoot, selectRoot } from '../config/root-config.js';
7
+ import { REPOSITORY_PATH_METADATA_KEY } from '../events/constants/enrich.constants.js';
8
+ import { sha256Hex } from '../events/event-id.js';
9
+ import { featureCandidatesFromBranch } from '../feature/ticket-candidates.js';
10
+ import { checkoutRootOf } from '../git/checkout-root.js';
11
+ import { ASSUMED_DEFAULT_BRANCHES, GIT_FIELD_SEPARATOR, GIT_REMOTE_ARGS, GIT_TIMEOUT_MS, MAX_WORK_CHANGED_FILES, gitRemoteBranchesAtArgs, gitVerifyRefArgs } from '../git/constants/git.constants.js';
12
+ import { asFingerprint, commitFiles, dirtyDelta, fingerprint } from '../git/fingerprint.js';
13
+ import { repositoryIdentity, runGit } from '../git/git-context.js';
14
+ import { isBeneath } from '../git/repository-root.js';
15
+ import { CHECKOUT_KEY_HASH_LENGTH, CHECKOUT_RECORD_PREFIX, MAX_TURN_CHECKOUTS, TOOL_COMPLETION_TYPES, TOOL_START_TYPES, OWN_COMMIT_SINCE_SLACK_MS, TURN_STATE_TTL_MS, gitOwnCommitCountArgs } from './constants/turns.constants.js';
16
+ import { resolveInherited } from './inherited-checkout.js';
17
+ /**
18
+ * Write down the checkouts this tool hook names, for its turn's close.
19
+ *
20
+ * On a tool-start hook: the checkout of the hook's cwd, of a file tool's path,
21
+ * and of every directory the shell command named (`options.nominations`, roots
22
+ * only). On a completion hook: the file's checkout and the shell command's
23
+ * checkouts, when the turn has not named them yet — a command can create the
24
+ * worktree it then works in. The first time a turn names a checkout, its baseline fingerprint is
25
+ * taken — the one git process a tool hook may add — and later sightings are
26
+ * votes, one small file each.
27
+ *
28
+ * Only checkouts this session may report are written: the same admission the
29
+ * close applies, asked early so no git process runs in another tenant's
30
+ * checkout.
31
+ *
32
+ * @param store - Per-session state store.
33
+ * @param sessionId - Provider session id.
34
+ * @param event - The tool event, already enriched.
35
+ * @param options - Tracking options.
36
+ */
37
+ export async function recordCheckouts(store, sessionId, event, options) {
38
+ const type = event.event.type;
39
+ const start = TOOL_START_TYPES.has(type);
40
+ if (!options.config.capture.git || (!start && !TOOL_COMPLETION_TYPES.has(type)))
41
+ return;
42
+ const { candidates, named } = await hookCandidates(event, options, start);
43
+ if (candidates.length === 0)
44
+ return;
45
+ const admits = admission(options, (await store.readStart(sessionId)) ?? options.cwd);
46
+ const prefix = `${CHECKOUT_RECORD_PREFIX}${shortHash(event.session.turnId ?? '')}-`;
47
+ const seen = new Set();
48
+ const names = new Set(await store.names(sessionId));
49
+ const callKey = shortHash(event.id);
50
+ for (const name of names) {
51
+ if (name.startsWith(prefix))
52
+ seen.add(name.slice(prefix.length, prefix.length + CHECKOUT_KEY_HASH_LENGTH));
53
+ }
54
+ const writes = [];
55
+ for (const { root, via } of candidates) {
56
+ const key = shortHash(root);
57
+ const first = !seen.has(key);
58
+ // A completion hook adds a vote only for a root a shell call created: a
59
+ // worktree the command itself added did not exist when its start hook ran.
60
+ const votes = (start || first) && (via === 'shell' || (start && via === 'cwd' && !named));
61
+ // A re-fired hook has the same event id: its record is already there, and
62
+ // rewriting it would drop the first sighting's seq and baseline.
63
+ const duplicate = names.has(`${prefix}${key}-${callKey}.json`);
64
+ if (duplicate || (!first && !votes) || (first && seen.size >= MAX_TURN_CHECKOUTS) || !admits(root))
65
+ continue;
66
+ writes.push({ root, via, key, seq: first ? seen.size : undefined });
67
+ if (first)
68
+ seen.add(key);
69
+ }
70
+ await Promise.all(writes.map(async ({ root, via, key, seq }) => {
71
+ const record = {
72
+ kind: 'checkout',
73
+ at: event.timestamp,
74
+ turnId: event.session.turnId,
75
+ root,
76
+ via,
77
+ named,
78
+ seq,
79
+ baseline: seq === undefined ? undefined : await fingerprint(root)
80
+ };
81
+ await store.append(sessionId, `${prefix}${key}-${callKey}`, record);
82
+ }));
83
+ }
84
+ /**
85
+ * Which checkout a closing turn worked in, and what it changed there.
86
+ *
87
+ * Every admitted checkout the turn named is fingerprinted again, all at once,
88
+ * and compared with its baseline. The turn reports, in this order: the one it
89
+ * changed most (`changed`); else the session's last changed checkout
90
+ * (`carried`); else the one it named most (`referenced`); else the Stop folder's
91
+ * own repository, as before this existed (`cwd`). Ties go to the checkout named
92
+ * first. Every failure makes a candidate lose, never the summary.
93
+ *
94
+ * @param store - Per-session state store.
95
+ * @param sessionId - Provider session id.
96
+ * @param records - This turn's records.
97
+ * @param stopEvent - The closing event, enriched for the Stop folder.
98
+ * @param options - Tracking options.
99
+ * @returns The checkout to report and the tools with its paths only.
100
+ */
101
+ export async function resolveWorkCheckout(store, sessionId, records, stopEvent, options) {
102
+ const tools = records.filter((record) => record.kind === 'tool');
103
+ // Earlier hooks may have placed paths in checkouts this close will not judge;
104
+ // without git capture none of them is reported, only bare basenames.
105
+ if (!options.config.capture.git)
106
+ return { tools: keepingPathsIn(tools, undefined), git: stopEvent.git };
107
+ const admits = admission(options, (await store.readStart(sessionId)) ?? options.cwd);
108
+ const candidates = candidatesOf(records, admits);
109
+ const [memo, shared] = await Promise.all([store.readWorkCheckout(sessionId), sharedCheckouts(store, sessionId)]);
110
+ // A branch another active session changed there is withheld from a turn that
111
+ // changed nothing, unless this session changed that branch itself.
112
+ const withheld = (root, branch) => branch !== undefined
113
+ && changedByOthers(shared.get(root), branch)
114
+ && !(memo !== undefined && canonicalRoot(memo.root) === root && memo.branch === branch);
115
+ const carried = memo && admits(memo.root) ? canonicalRoot(memo.root) : undefined;
116
+ const carriedCandidate = carried === undefined || candidates.some((candidate) => candidate.root === carried) ? [] : [emptyCandidate(carried, candidates.length)];
117
+ const batch = [...candidates, ...carriedCandidate];
118
+ const probes = new Map(await Promise.all(batch.map(async (candidate) => [candidate.root, await probe(candidate)])));
119
+ const changed = new Map(candidates.map((candidate) => [candidate.root, changedFiles(candidate, probes.get(candidate.root), shared.get(candidate.root))]));
120
+ const reportable = candidates.filter((candidate) => probes.get(candidate.root)?.closing);
121
+ // Ranked on the whole list, capped only when reported. A HEAD that moved with
122
+ // no file to show for it (a switch, a pull, a reset) is no change (SPEC §3a):
123
+ // in a shared checkout it is as likely another session's.
124
+ // A commit with no file of its own to show (an empty one, or on a branch the
125
+ // turn created) still counts, below one changed file — unless another active
126
+ // session is changing that checkout, whose commit it may as well be. A commit
127
+ // whose files were all another session's is not this turn's either.
128
+ // ponytail: in a checkout another session is changing, a turn's own file-less
129
+ // commit is no change: nothing tells it from the other's. Upgrade path: the
130
+ // committer identity per session.
131
+ const committedHere = (candidate) => {
132
+ const probed = probes.get(candidate.root);
133
+ return probed.committed && probed.commits.length === 0 && !changedByOthers(shared.get(candidate.root), probed.branch ?? '');
134
+ };
135
+ const byChange = best(reportable, (candidate) => changed.get(candidate.root).length || (committedHere(candidate) ? 0.5 : 0));
136
+ if (byChange)
137
+ return reportCheckout({ root: byChange.root, evidence: 'changed', probed: probes.get(byChange.root), changed: changed.get(byChange.root), withhold: false }, tools, options);
138
+ // Carried only while the folder is still the repository that was
139
+ // remembered: a directory re-cloned from another remote is not that work.
140
+ const carriedProbe = carried === undefined ? undefined : probes.get(carried);
141
+ const stillSame = carriedProbe?.closing !== undefined && repositoryIdentity(carried, carriedProbe.remote).repository === memo?.repository;
142
+ if (stillSame)
143
+ return reportCheckout({ root: carried, evidence: 'carried', probed: carriedProbe, changed: [], withhold: withheld(carried, carriedProbe.branch) }, tools, options);
144
+ const byVotes = best(reportable, (candidate) => candidate.votes + candidate.read.size);
145
+ const votedProbe = byVotes === undefined ? undefined : probes.get(byVotes.root);
146
+ if (byVotes)
147
+ return reportCheckout({ root: byVotes.root, evidence: 'referenced', probed: votedProbe, changed: [], withhold: withheld(byVotes.root, votedProbe.branch) }, tools, options);
148
+ const stopRoot = await checkoutRootOf(options.cwd);
149
+ const inherited = stopRoot === undefined ? await inheritedCheckout(store, sessionId, options, tools) : undefined;
150
+ if (inherited)
151
+ return inherited;
152
+ // The Stop folder's own repository is held to the same admission as every
153
+ // candidate: a lasting cd can end the turn in another tenant's checkout, or
154
+ // outside the start folder.
155
+ // A folder whose checkout cannot be found is not admitted either: git may
156
+ // still have named a repository there, past what the walk reaches.
157
+ if (stopRoot === undefined || !admits(stopRoot))
158
+ return { tools: keepingPathsIn(tools, undefined) };
159
+ // Enrichment read the folder's branch; a detached review gets its pull
160
+ // request's (SPEC §3b), withheld by the same rule as any other.
161
+ const reviewed = stopEvent.git?.repository && !stopEvent.git.branch ? await reviewedBranch(stopRoot, stopEvent.git.commit) : undefined;
162
+ if (withheld(stopRoot, stopEvent.git?.branch ?? reviewed)) {
163
+ return {
164
+ git: { ...stopEvent.git, branch: undefined, commit: undefined },
165
+ tools: keepingPathsIn(tools, stopRoot),
166
+ evidence: stopEvent.git?.repository ? 'cwd' : undefined,
167
+ root: stopEvent.git?.repository ? stopRoot : undefined
168
+ };
169
+ }
170
+ if (reviewed) {
171
+ return {
172
+ git: { ...stopEvent.git, branch: reviewed },
173
+ featureCandidates: [...(stopEvent.feature?.candidates ?? []), ...featureCandidatesFromBranch(reviewed)],
174
+ tools: keepingPathsIn(tools, stopRoot),
175
+ evidence: 'cwd',
176
+ root: stopRoot
177
+ };
178
+ }
179
+ return {
180
+ git: stopEvent.git,
181
+ featureCandidates: stopEvent.feature?.candidates,
182
+ tools: keepingPathsIn(tools, stopRoot),
183
+ evidence: stopEvent.git?.repository ? 'cwd' : undefined,
184
+ root: stopEvent.git?.repository ? stopRoot : undefined
185
+ };
186
+ }
187
+ /**
188
+ * What a session started outside any checkout inherited from the process that
189
+ * started it, reported as `inherited` — the last resort, behind everything the
190
+ * turn's own work names.
191
+ *
192
+ * Admitted by tenant alone: the start folder is no checkout, so there is no
193
+ * folder to be beneath. Branch, commit and ticket keys are read from the
194
+ * inherited root now, never carried over from the parent's memo. Known ceiling:
195
+ * no repository snapshot is taken for it (the pipeline takes one at the
196
+ * reported root, and core may drop an inherited repository that folder evidence
197
+ * contradicts, SPEC §3), so an inherited turn never mints a work unit.
198
+ *
199
+ * @param store - Per-session state store.
200
+ * @param sessionId - Provider session id.
201
+ * @param options - Tracking options.
202
+ * @param tools - The turn's tool records.
203
+ * @returns The report, or undefined when nothing was inherited or it cannot be read.
204
+ */
205
+ async function inheritedCheckout(store, sessionId, options, tools) {
206
+ const found = await resolveInherited(store, sessionId, admission(options, (await store.readStart(sessionId)) ?? options.cwd, true));
207
+ if (!found)
208
+ return undefined;
209
+ const probed = await probe(emptyCandidate(found.root, 0));
210
+ if (!probed.closing)
211
+ return undefined;
212
+ // Never withheld: a parent's checkout is what the child inherits on purpose.
213
+ const reported = await reportCheckout({ root: found.root, evidence: 'inherited', probed, changed: [], withhold: false }, tools, options);
214
+ return reported.git ? { ...reported, parentSessionId: found.parentSessionId } : undefined;
215
+ }
216
+ /**
217
+ * The checkouts one tool hook names, the named ones first, and whether the call
218
+ * named one at all.
219
+ *
220
+ * A call that names a checkout — a shell command's directory or a file tool's
221
+ * file — votes through the name, so its cwd does not also vote: where an agent
222
+ * sits is weaker evidence than where it says it is looking. The cwd's duplicate
223
+ * of a named root is dropped.
224
+ *
225
+ * @param event - The tool event.
226
+ * @param options - Tracking options.
227
+ * @param start - Whether this is a tool-start hook.
228
+ * @returns Distinct canonical roots with how each was named.
229
+ */
230
+ async function hookCandidates(event, options, start) {
231
+ const repositoryPath = event.metadata?.[REPOSITORY_PATH_METADATA_KEY];
232
+ const fileRoot = typeof repositoryPath === 'string' && repositoryPath ? canonicalRoot(path.join(options.cwd, repositoryPath)) : undefined;
233
+ const cwdRoot = start ? await checkoutRootOf(options.cwd) : undefined;
234
+ const nominations = options.nominations ?? [];
235
+ const all = [
236
+ ...nominations.map((root) => ({ root, via: 'shell' })),
237
+ { root: fileRoot, via: 'file' },
238
+ { root: cwdRoot, via: 'cwd' },
239
+ // The folders the agent has open say where it sits, as its cwd does.
240
+ ...(start ? (options.workspaceRoots ?? []) : []).map((root) => ({ root, via: 'cwd' }))
241
+ ];
242
+ const distinct = new Map();
243
+ for (const { root, via } of all) {
244
+ if (root !== undefined && path.isAbsolute(root) && !distinct.has(root))
245
+ distinct.set(root, via);
246
+ }
247
+ return { candidates: [...distinct].map(([root, via]) => ({ root, via })), named: start && (nominations.length > 0 || fileRoot !== undefined) };
248
+ }
249
+ /**
250
+ * Whether this session may report a checkout.
251
+ *
252
+ * A checkout another project root claims is refused outright: the start folder
253
+ * alone decides which tenant a session sends as. With roots configured and the
254
+ * start folder in one, any checkout of that tenant is admitted — worktrees sit
255
+ * beside the start folder, not beneath it. With roots configured and the start
256
+ * folder in none, any checkout in none is admitted likewise. Otherwise only checkouts beneath the
257
+ * start folder are, and the one it lies in. Asked of real paths, because a symlink can lead anywhere.
258
+ *
259
+ * @param options - Tracking options; the machine's roots.
260
+ * @param startFolder - The folder the session started in.
261
+ * @param inherited - Admitting a checkout the session inherited from the process that started it: the start folder is no checkout, so only the tenant is asked. With roots configured and the start folder in none, the checkout's own root is that tenant (SPEC §3).
262
+ * @returns The admission test, memoised per root.
263
+ */
264
+ function admission(options, startFolder, inherited = false) {
265
+ const roots = options.globalConfig.config.roots;
266
+ const tenant = selectRoot(roots, startFolder)?.path;
267
+ // The identity this hook sends as is its own folder's. A session whose start
268
+ // and current folder sit in two tenants reports no checkout, rather than one
269
+ // tenant's under the other's token.
270
+ const sameIdentity = selectRoot(roots, options.cwd)?.path === tenant;
271
+ const boundary = canonicalRoot(startFolder);
272
+ // Roots configured, none holding the start folder, and an inherited checkout:
273
+ // the hook's own folder is also in no root (sameIdentity), so the checkout's
274
+ // root is the only tenant there is.
275
+ const inheritsTenant = inherited && tenant === undefined && Object.keys(roots ?? {}).some((key) => path.isAbsolute(key));
276
+ // Roots configured, none holding the start folder: it is the machine's default
277
+ // identity, and a checkout in no root sends as that same identity, so a
278
+ // sibling of the start folder (AWT-318) leaks nothing. With no roots at all
279
+ // there is no tenant to tell siblings apart, so the start folder bounds it.
280
+ const defaultIdentity = tenant === undefined && Object.keys(roots ?? {}).some((key) => path.isAbsolute(key));
281
+ const verdicts = new Map();
282
+ return (root) => {
283
+ const known = verdicts.get(root);
284
+ if (known !== undefined)
285
+ return known;
286
+ const real = path.isAbsolute(root) ? canonicalRoot(root) : undefined;
287
+ const rooted = real === undefined ? undefined : selectRoot(roots, real)?.path;
288
+ // A start folder in no root has no tenant of its own, so an inherited checkout
289
+ // brings one: the root that claims it. A checkout no root claims is refused,
290
+ // never sent as the machine's default.
291
+ const sameTenant = inheritsTenant ? rooted !== undefined : rooted === tenant;
292
+ // Beneath the start folder, or the checkout the start folder itself lies in.
293
+ const verdict = real !== undefined && sameIdentity && sameTenant && (tenant !== undefined || inherited || defaultIdentity || isBeneath(boundary, real) || isBeneath(real, boundary));
294
+ verdicts.set(root, verdict);
295
+ return verdict;
296
+ };
297
+ }
298
+ /**
299
+ * The turn's admitted candidates out of its records, type-checked.
300
+ *
301
+ * Turn state is a file on disk between hooks, so every field is checked before
302
+ * it is used. At most {@link MAX_TURN_CHECKOUTS}, the first named winning.
303
+ *
304
+ * @param records - This turn's records, oldest first.
305
+ * @param admits - The admission test.
306
+ * @returns The candidates.
307
+ */
308
+ function candidatesOf(records, admits) {
309
+ const byRoot = new Map();
310
+ const canonical = new Map();
311
+ const at = (raw) => {
312
+ if (typeof raw !== 'string' || !admits(raw))
313
+ return undefined;
314
+ const root = canonical.get(raw) ?? canonicalRoot(raw);
315
+ canonical.set(raw, root);
316
+ const candidate = byRoot.get(root) ?? emptyCandidate(root, byRoot.size);
317
+ byRoot.set(root, candidate);
318
+ return candidate;
319
+ };
320
+ for (const record of records) {
321
+ if (record.kind === 'checkout') {
322
+ const candidate = at(record.root);
323
+ if (!candidate)
324
+ continue;
325
+ if (typeof record.seq === 'number' && record.seq < candidate.first) {
326
+ candidate.first = record.seq;
327
+ candidate.baseline = asFingerprint(record.baseline) ?? candidate.baseline;
328
+ candidate.since = record.at;
329
+ }
330
+ if (record.via === 'shell' || (record.via === 'cwd' && record.named === false))
331
+ candidate.votes += 1;
332
+ continue;
333
+ }
334
+ // Only a completed read or edit is evidence: a failed call names a file it
335
+ // may never have touched, and carries no access marker.
336
+ if (record.kind !== 'tool' || typeof record.filePath !== 'string' || (record.access !== 'read' && record.access !== 'edit'))
337
+ continue;
338
+ const candidate = at(record.repositoryRoot);
339
+ candidate?.[record.access === 'read' ? 'read' : 'edited'].add(record.filePath);
340
+ }
341
+ return [...byRoot.values()].sort(byFirstSight).slice(0, MAX_TURN_CHECKOUTS);
342
+ }
343
+ /**
344
+ * A checkout at the Stop: fingerprint and remote together, then the commit diff
345
+ * when HEAD moved. A checkout whose directory is gone keeps its baseline's
346
+ * branch and oid, and its commits are read from the shared git dir.
347
+ *
348
+ * @param candidate - The checkout.
349
+ * @returns What the Stop learned; no closing fingerprint when git could not say.
350
+ */
351
+ async function probe(candidate) {
352
+ const [closing, remote] = await Promise.all([fingerprint(candidate.root), runGit(GIT_REMOTE_ARGS, candidate.root, GIT_TIMEOUT_MS)]);
353
+ const from = candidate.baseline?.oid;
354
+ if (closing) {
355
+ // Only a baseline git called unborn lists its first commit's files; a
356
+ // baseline that merely lacks an oid proves nothing, and walking the whole
357
+ // history for it would call the whole tree changed.
358
+ // ponytail: a commit the turn pushed before the Stop is reachable from a
359
+ // remote-tracking ref and reports no files, same as a pulled one. Upgrade
360
+ // path: also keep commits authored by user.email.
361
+ const unborn = candidate.baseline?.unborn === true;
362
+ const moved = (unborn || from !== undefined) && closing.oid !== undefined && from !== closing.oid;
363
+ // A switch to another branch is no commit of the turn's own.
364
+ const own = moved && candidate.baseline?.branch === closing.branch;
365
+ const [commits, branch] = await Promise.all([
366
+ own ? commitFiles(candidate.root, from, closing.oid) : [],
367
+ closing.branch ?? reviewedBranch(candidate.root, closing.oid)
368
+ ]);
369
+ // After a switch, only commits made since the turn first named the checkout
370
+ // are its own: a branch it created and committed to, not another's tip.
371
+ const since = own ? undefined : sinceFirstSight(candidate.since);
372
+ const asked = commits.length === 0 && moved && (own || since !== undefined);
373
+ return { closing, branch, remote, commits, committed: commits.length > 0 || (asked && (await ownCommits(candidate.root, { from, to: closing.oid, since }))), vanished: false };
374
+ }
375
+ const common = candidate.baseline?.commonDir;
376
+ const branch = candidate.baseline?.branch;
377
+ const unborn = candidate.baseline?.unborn === true;
378
+ if (!common || (!from && !unborn) || !branch || (await exists(candidate.root)))
379
+ return { commits: [], committed: false, vanished: false };
380
+ const [head, commonRemote] = await Promise.all([
381
+ runGit(['--git-dir', common, ...gitVerifyRefArgs(`refs/heads/${branch}`)], common, GIT_TIMEOUT_MS),
382
+ runGit(['--git-dir', common, ...GIT_REMOTE_ARGS], common, GIT_TIMEOUT_MS)
383
+ ]);
384
+ // Moved when the branch no longer points where the turn started — an empty
385
+ // commit moves it too, with no file to show for it. An unborn baseline's
386
+ // first commit is listed from the whole history.
387
+ const moved = head !== undefined && head !== from;
388
+ const commits = moved ? await commitFiles(common, from, `refs/heads/${branch}`, common) : [];
389
+ const committed = commits.length > 0 || (moved && (await ownCommits(common, { from, to: `refs/heads/${branch}` }, common)));
390
+ return { closing: { oid: from ?? head, branch, commonDir: common, dirty: {} }, branch, remote: commonRemote, commits, committed, vanished: true };
391
+ }
392
+ /**
393
+ * The files a turn changed in one checkout: its dirty entries new or re-stamped
394
+ * since the baseline, the files of any commit it made, and what its file tools
395
+ * edited there. A file another active session changed there is that session's,
396
+ * unless this turn's own edit tool named it too (SPEC §3a).
397
+ *
398
+ * @param candidate - The checkout.
399
+ * @param probed - What the Stop learned about it.
400
+ * @param others - What other active sessions changed in it.
401
+ * @returns Repository-relative paths, uncapped: the count ranks candidates.
402
+ */
403
+ function changedFiles(candidate, probed, others) {
404
+ if (!probed.closing)
405
+ return [];
406
+ const files = new Set();
407
+ const seen = [...(candidate.baseline && !probed.vanished ? dirtyDelta(candidate.baseline, probed.closing) : []), ...probed.commits];
408
+ const reported = others?.reported.get(probed.branch ?? '');
409
+ for (const file of seen) {
410
+ if (!others?.files.has(file) && !reported?.has(file))
411
+ files.add(file);
412
+ }
413
+ for (const file of candidate.edited)
414
+ files.add(file);
415
+ return [...files];
416
+ }
417
+ /**
418
+ * What every other active session on the machine changed, per canonical
419
+ * checkout root: the files its edit tools named or its turns reported, the
420
+ * branch it changed there, and the branch its open turn first saw there. Machine-local state only; no git process.
421
+ *
422
+ * @param store - Per-session state store.
423
+ * @param sessionId - The closing session, left out.
424
+ * @returns The changes by root; empty when nothing can be read, which is the behaviour before SPEC §3a.
425
+ */
426
+ async function sharedCheckouts(store, sessionId) {
427
+ const activity = await store.othersActivity(sessionId, TURN_STATE_TTL_MS).catch(() => []);
428
+ const byRoot = new Map();
429
+ const at = (raw) => {
430
+ const root = canonicalRoot(raw);
431
+ const entry = byRoot.get(root) ?? { files: new Set(), reported: new Map(), branches: new Set(), editing: false, baselines: new Set() };
432
+ byRoot.set(root, entry);
433
+ return entry;
434
+ };
435
+ for (const { memo, edits, baselines } of activity) {
436
+ for (const { root, branch } of baselines) {
437
+ if (path.isAbsolute(root))
438
+ at(root).baselines.add(branch);
439
+ }
440
+ if (memo) {
441
+ const entry = at(memo.root);
442
+ const branch = memo.branch ?? '';
443
+ const files = entry.reported.get(branch) ?? new Set();
444
+ if (memo.branch)
445
+ entry.branches.add(memo.branch);
446
+ for (const file of memo.files ?? [])
447
+ files.add(file);
448
+ entry.reported.set(branch, files);
449
+ }
450
+ for (const { root, filePath, current } of edits) {
451
+ if (!path.isAbsolute(root))
452
+ continue;
453
+ const entry = at(root);
454
+ entry.files.add(filePath);
455
+ entry.editing ||= current;
456
+ }
457
+ }
458
+ return byRoot;
459
+ }
460
+ /**
461
+ * The winning checkout as the summary reports it, under that checkout's own
462
+ * `.agentwatch.json`: a file committed there is what a session started inside
463
+ * it would honour.
464
+ *
465
+ * @param winner - The checkout, how it was chosen, its closing state, the files
466
+ * the turn changed there, and whether its branch is withheld because another
467
+ * active session changed it (SPEC §3a).
468
+ * @param tools - The turn's tool records.
469
+ * @param options - Tracking options.
470
+ * @returns The report.
471
+ */
472
+ async function reportCheckout(winner, tools, options) {
473
+ const { root, evidence, probed, changed } = winner;
474
+ // A worktree removed before the Stop has no file left to read; its main
475
+ // checkout, beside the shared git dir, carries the same committed one.
476
+ const configRoot = probed.vanished && probed.closing?.commonDir ? path.dirname(probed.closing.commonDir) : root;
477
+ const loaded = (await loadEffectiveConfig(options.paths, configRoot, options.globalConfig)).config.capture;
478
+ // The main checkout's file may be looser than the one the removed branch
479
+ // committed: the branch's own may only narrow what is reported, never widen it.
480
+ const capture = probed.vanished ? narrowedByBranch(loaded, await branchCapture(probed.closing)) : loaded;
481
+ // Its own paths and nothing else: another checkout's are a wrong vote in the
482
+ // placement corpus. The calls still count.
483
+ // capture.files: false withholds every path, bare basenames and paths outside
484
+ // any checkout included.
485
+ const own = capture.files ? keepingPathsIn(tools, root) : tools.map((record) => ({ ...record, filePath: undefined, externalPath: undefined }));
486
+ if (!capture.git)
487
+ return { tools: own, capture };
488
+ // A withheld branch takes its commit and ticket keys with it: the session
489
+ // then falls to its other evidence, or is unattributed with a reason.
490
+ const branch = winner.withhold ? undefined : probed.branch;
491
+ const candidates = featureCandidatesFromBranch(branch);
492
+ return {
493
+ // Field by field, and no root: nothing absolute is sent.
494
+ git: {
495
+ ...repositoryIdentity(root, probed.remote),
496
+ branch,
497
+ commit: winner.withhold ? undefined : probed.closing?.oid,
498
+ changedFiles: capture.files && changed.length > 0 ? changed.slice(0, MAX_WORK_CHANGED_FILES) : undefined
499
+ },
500
+ featureCandidates: candidates.length > 0 ? candidates : undefined,
501
+ tools: own,
502
+ evidence,
503
+ root,
504
+ capture,
505
+ changed
506
+ };
507
+ }
508
+ /**
509
+ * The tools with every path dropped that is not in `root`. A path in no
510
+ * checkout is a bare basename and stays, as it always has.
511
+ *
512
+ * @param tools - The turn's tool records.
513
+ * @param root - The reported checkout's root, or undefined to keep only basenames.
514
+ * @returns A new list; the records are not mutated.
515
+ */
516
+ function keepingPathsIn(tools, root) {
517
+ return tools.map((record) => {
518
+ if (record.repositoryRoot === undefined)
519
+ return record;
520
+ const own = root !== undefined && typeof record.repositoryRoot === 'string' && path.isAbsolute(record.repositoryRoot) && canonicalRoot(record.repositoryRoot) === root;
521
+ return own ? record : { ...record, filePath: undefined };
522
+ });
523
+ }
524
+ /**
525
+ * The candidate with the highest positive score, the first named winning a tie.
526
+ *
527
+ * @param candidates - Candidates in first-sight order.
528
+ * @param score - What to count.
529
+ * @returns The winner, or undefined when nothing scored.
530
+ */
531
+ function best(candidates, score) {
532
+ let winner;
533
+ let top = 0;
534
+ // Sorted by first sight and compared strictly, so the earliest tied one stays.
535
+ for (const candidate of candidates) {
536
+ const value = score(candidate);
537
+ if (value <= top)
538
+ continue;
539
+ winner = candidate;
540
+ top = value;
541
+ }
542
+ return winner;
543
+ }
544
+ /**
545
+ * The capture flags a vanished worktree's branch committed in its own
546
+ * `.agentwatch.json`, read from the shared git dir.
547
+ *
548
+ * @param closing - The vanished checkout's stand-in fingerprint.
549
+ * @returns The flags it sets, or undefined when it has no such file.
550
+ */
551
+ async function branchCapture(closing) {
552
+ if (!closing?.commonDir || !closing.branch)
553
+ return undefined;
554
+ const text = await runGit(['--git-dir', closing.commonDir, 'show', `refs/heads/${closing.branch}:${REPO_CONFIG_NAME}`], closing.commonDir, GIT_TIMEOUT_MS);
555
+ try {
556
+ return asRecord(asRecord(text === undefined ? undefined : JSON.parse(text))?.['capture']);
557
+ }
558
+ catch {
559
+ return undefined;
560
+ }
561
+ }
562
+ /**
563
+ * A capture policy narrowed by another file's explicit `false`s.
564
+ *
565
+ * @param capture - The policy loaded from disk.
566
+ * @param branch - The branch file's capture flags, if any.
567
+ * @returns The policy, with git and files off wherever either says so.
568
+ */
569
+ function narrowedByBranch(capture, branch) {
570
+ return { ...capture, git: capture.git && branch?.git !== false, files: capture.files && branch?.files !== false };
571
+ }
572
+ function byFirstSight(a, b) {
573
+ return a.first - b.first || a.order - b.order;
574
+ }
575
+ function emptyCandidate(root, order) {
576
+ return { root, first: Number.POSITIVE_INFINITY, order, edited: new Set(), read: new Set(), votes: 0 };
577
+ }
578
+ /**
579
+ * Whether HEAD's move includes a commit no remote reaches. Asked only when the
580
+ * move listed no file, so a turn that commits files pays nothing.
581
+ *
582
+ * @param cwd - The checkout, or the shared git dir of a vanished one.
583
+ * @param range - The move to look in.
584
+ * @param range.from - The oid the turn started on.
585
+ * @param range.to - The oid or ref it ended on.
586
+ * @param range.since - After a switch, the time since which a commit is the turn's.
587
+ * @param gitDir - The shared git dir, for a vanished worktree.
588
+ * @returns True when there is at least one; false when git could not say.
589
+ */
590
+ async function ownCommits(cwd, range, gitDir) {
591
+ const args = gitOwnCommitCountArgs(range.from, range.to, range.since);
592
+ const count = await runGit(gitDir ? ['--git-dir', gitDir, ...args] : args, cwd, GIT_TIMEOUT_MS);
593
+ return Number(count) > 0;
594
+ }
595
+ /**
596
+ * The pull request branch a review in a detached checkout is looking at (SPEC
597
+ * §3b): the one remote-tracking branch whose tip is HEAD, when it is not the
598
+ * default branch. None, several or the default (with or without others) is no
599
+ * branch; picking one would be a guess.
600
+ *
601
+ * Asked at the Stop, once per detached checkout the turn named, beside its
602
+ * other probes: one git process, never in the prompt hook. A branch that moved on since the checkout no longer points here,
603
+ * and the turn reports no branch, as before.
604
+ *
605
+ * ponytail: the default branch is what a `<remote>/HEAD` at this commit names,
606
+ * else `main` or `master`. A trunk called anything else, in a clone that never
607
+ * fetched `<remote>/HEAD`, reads as a pull request branch when HEAD is its tip.
608
+ * Upgrade path: ask `symbolic-ref refs/remotes/origin/HEAD` too.
609
+ *
610
+ * @param root - Checkout root.
611
+ * @param oid - The checked-out commit; undefined asks nothing.
612
+ * @returns The branch, without its remote's prefix, or undefined.
613
+ */
614
+ async function reviewedBranch(root, oid) {
615
+ if (oid === undefined)
616
+ return undefined;
617
+ const output = await runGit(gitRemoteBranchesAtArgs(oid), root, GIT_TIMEOUT_MS);
618
+ if (!output)
619
+ return undefined;
620
+ const defaults = new Set(ASSUMED_DEFAULT_BRANCHES);
621
+ const names = new Set();
622
+ for (const line of output.split('\n')) {
623
+ const [name, target] = line.split(GIT_FIELD_SEPARATOR);
624
+ if (target) {
625
+ defaults.add(target);
626
+ continue;
627
+ }
628
+ if (name)
629
+ names.add(name);
630
+ }
631
+ // The default branch at HEAD is a commit of the trunk, whatever else points there.
632
+ const [only, ...more] = names;
633
+ return only !== undefined && more.length === 0 && !defaults.has(only) ? only : undefined;
634
+ }
635
+ /**
636
+ * Whether other active sessions changed the branch a checkout has now: a turn
637
+ * of theirs changed it, an open turn's edit tool is changing it, or an open
638
+ * turn first saw the checkout on another branch, so it was switched during that
639
+ * turn, before the turn could report anything (a switch made through the shell).
640
+ *
641
+ * @param others - What other active sessions changed in the checkout.
642
+ * @param branch - The branch checked out now.
643
+ * @returns True when the branch is theirs to report, not this turn's.
644
+ */
645
+ function changedByOthers(others, branch) {
646
+ if (!others)
647
+ return false;
648
+ return others.branches.has(branch) || others.editing || [...others.baselines].some((first) => first !== branch);
649
+ }
650
+ /**
651
+ * The time from which a commit counts as the turn's, a little before it first
652
+ * named the checkout.
653
+ *
654
+ * @param at - When the turn first named it, as the record holds it.
655
+ * @returns An ISO time, or undefined when the record holds none usable.
656
+ */
657
+ function sinceFirstSight(at) {
658
+ const time = at === undefined ? Number.NaN : Date.parse(at);
659
+ return Number.isNaN(time) ? undefined : new Date(time - OWN_COMMIT_SINCE_SLACK_MS).toISOString();
660
+ }
661
+ async function exists(target) {
662
+ return fs.stat(target).then(() => true, () => false);
663
+ }
664
+ function shortHash(value) {
665
+ return sha256Hex(value).slice(0, CHECKOUT_KEY_HASH_LENGTH);
666
+ }