@agent-watch-ai/edge 0.2.5 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (348) hide show
  1. package/CHANGELOG.md +558 -0
  2. package/README.md +222 -97
  3. package/SECURITY.md +72 -0
  4. package/dist/billing/session-billing.d.ts +19 -0
  5. package/dist/billing/session-billing.js +52 -0
  6. package/dist/cli/args.d.ts +10 -0
  7. package/dist/cli/args.js +20 -0
  8. package/dist/cli/constants/cli.constants.d.ts +52 -4
  9. package/dist/cli/constants/cli.constants.js +56 -5
  10. package/dist/cli/context.d.ts +33 -2
  11. package/dist/cli/context.js +84 -14
  12. package/dist/cli/doctor.js +321 -33
  13. package/dist/cli/hook-check.d.ts +23 -0
  14. package/dist/cli/hook-check.js +114 -0
  15. package/dist/cli/hook.js +118 -7
  16. package/dist/cli/index.d.ts +3 -1
  17. package/dist/cli/index.js +3 -1
  18. package/dist/cli/misc.d.ts +11 -0
  19. package/dist/cli/misc.js +80 -4
  20. package/dist/cli/npx-install.d.ts +37 -0
  21. package/dist/cli/npx-install.js +79 -0
  22. package/dist/cli/open-browser.d.ts +39 -0
  23. package/dist/cli/open-browser.js +62 -0
  24. package/dist/cli/setup.d.ts +17 -8
  25. package/dist/cli/setup.js +553 -103
  26. package/dist/cli/status.js +82 -13
  27. package/dist/cli/toggle.d.ts +9 -0
  28. package/dist/cli/toggle.js +117 -0
  29. package/dist/cli/types/cli.types.d.ts +43 -3
  30. package/dist/cli/ui.d.ts +7 -0
  31. package/dist/cli/ui.js +10 -1
  32. package/dist/cli/uninstall.js +39 -2
  33. package/dist/cli/update.d.ts +17 -0
  34. package/dist/cli/update.js +76 -0
  35. package/dist/cli.js +110 -12
  36. package/dist/config/config-store.d.ts +57 -0
  37. package/dist/config/config-store.js +250 -12
  38. package/dist/config/config.d.ts +53 -6
  39. package/dist/config/config.js +66 -6
  40. package/dist/config/constants/config.constants.d.ts +116 -6
  41. package/dist/config/constants/config.constants.js +131 -8
  42. package/dist/config/destination.d.ts +24 -0
  43. package/dist/config/destination.js +33 -0
  44. package/dist/config/index.d.ts +7 -4
  45. package/dist/config/index.js +5 -3
  46. package/dist/config/repo-config.d.ts +11 -7
  47. package/dist/config/repo-config.js +64 -15
  48. package/dist/config/root-config.d.ts +72 -0
  49. package/dist/config/root-config.js +170 -0
  50. package/dist/config/schemas/config.schema.d.ts +831 -84
  51. package/dist/config/schemas/config.schema.js +398 -16
  52. package/dist/config/types/config.types.d.ts +15 -1
  53. package/dist/config/types/destination.types.d.ts +8 -0
  54. package/dist/core/async.d.ts +36 -0
  55. package/dist/core/async.js +68 -0
  56. package/dist/core/index.d.ts +1 -1
  57. package/dist/core/index.js +1 -1
  58. package/dist/core/object.d.ts +5 -0
  59. package/dist/core/object.js +9 -4
  60. package/dist/core/pipe.d.ts +0 -13
  61. package/dist/core/pipe.js +1 -9
  62. package/dist/core/types/core.types.d.ts +9 -0
  63. package/dist/core/types/core.types.js +0 -3
  64. package/dist/core/which.d.ts +14 -0
  65. package/dist/core/which.js +43 -3
  66. package/dist/credentials/budget.d.ts +9 -0
  67. package/dist/credentials/budget.js +16 -0
  68. package/dist/credentials/command-runner.d.ts +16 -0
  69. package/dist/credentials/command-runner.js +37 -0
  70. package/dist/credentials/constants/credentials.constants.d.ts +119 -0
  71. package/dist/credentials/constants/credentials.constants.js +120 -0
  72. package/dist/credentials/credential-status.d.ts +14 -0
  73. package/dist/credentials/credential-status.js +38 -0
  74. package/dist/credentials/credentials.d.ts +86 -0
  75. package/dist/credentials/credentials.js +278 -0
  76. package/dist/credentials/device-api.d.ts +73 -0
  77. package/dist/credentials/device-api.js +161 -0
  78. package/dist/credentials/device-state.d.ts +31 -0
  79. package/dist/credentials/device-state.js +51 -0
  80. package/dist/credentials/identity.d.ts +73 -0
  81. package/dist/credentials/identity.js +101 -0
  82. package/dist/credentials/index.d.ts +7 -0
  83. package/dist/credentials/index.js +5 -0
  84. package/dist/credentials/migration.d.ts +46 -0
  85. package/dist/credentials/migration.js +164 -0
  86. package/dist/credentials/schemas/device-api.schema.d.ts +77 -0
  87. package/dist/credentials/schemas/device-api.schema.js +33 -0
  88. package/dist/credentials/schemas/device-state.schema.d.ts +51 -0
  89. package/dist/credentials/schemas/device-state.schema.js +20 -0
  90. package/dist/credentials/secret-store.d.ts +54 -0
  91. package/dist/credentials/secret-store.js +217 -0
  92. package/dist/credentials/sign-in.d.ts +31 -0
  93. package/dist/credentials/sign-in.js +105 -0
  94. package/dist/credentials/token-refresher.d.ts +39 -0
  95. package/dist/credentials/token-refresher.js +185 -0
  96. package/dist/credentials/types/credentials.types.d.ts +206 -0
  97. package/dist/credentials/types/credentials.types.js +1 -0
  98. package/dist/enforcement/constants/enforcement.constants.d.ts +47 -1
  99. package/dist/enforcement/constants/enforcement.constants.js +56 -0
  100. package/dist/enforcement/decision-cache.d.ts +20 -1
  101. package/dist/enforcement/decision-cache.js +65 -2
  102. package/dist/enforcement/decision-client.d.ts +9 -8
  103. package/dist/enforcement/decision-client.js +64 -17
  104. package/dist/enforcement/enforcement.d.ts +23 -2
  105. package/dist/enforcement/enforcement.js +107 -17
  106. package/dist/enforcement/index.d.ts +4 -3
  107. package/dist/enforcement/index.js +3 -2
  108. package/dist/enforcement/types/enforcement.types.d.ts +66 -2
  109. package/dist/enrollment/constants/enrollment.constants.d.ts +2 -6
  110. package/dist/enrollment/constants/enrollment.constants.js +2 -6
  111. package/dist/enrollment/enrollment.d.ts +16 -0
  112. package/dist/enrollment/enrollment.js +54 -0
  113. package/dist/enrollment/index.d.ts +3 -7
  114. package/dist/enrollment/index.js +1 -1
  115. package/dist/enrollment/types/enrollment.types.d.ts +9 -13
  116. package/dist/events/constants/enrich.constants.d.ts +15 -0
  117. package/dist/events/constants/enrich.constants.js +15 -0
  118. package/dist/events/constants/events.constants.d.ts +6 -2
  119. package/dist/events/constants/events.constants.js +5 -1
  120. package/dist/events/enrich.js +92 -10
  121. package/dist/events/event-id.d.ts +0 -8
  122. package/dist/events/event-id.js +0 -10
  123. package/dist/events/index.d.ts +2 -2
  124. package/dist/events/index.js +1 -1
  125. package/dist/events/product-event.d.ts +9 -6
  126. package/dist/events/types/repo-snapshot.types.d.ts +7 -0
  127. package/dist/events/types/session-billing.types.d.ts +16 -0
  128. package/dist/events/types/session-billing.types.js +1 -0
  129. package/dist/feature/constants/feature.constants.d.ts +7 -0
  130. package/dist/feature/constants/feature.constants.js +7 -0
  131. package/dist/feature/index.d.ts +1 -1
  132. package/dist/feature/index.js +1 -1
  133. package/dist/feature/ticket-candidates.d.ts +14 -0
  134. package/dist/feature/ticket-candidates.js +26 -8
  135. package/dist/git/blob-hash.d.ts +21 -0
  136. package/dist/git/blob-hash.js +69 -0
  137. package/dist/git/checkout-root.d.ts +27 -0
  138. package/dist/git/checkout-root.js +75 -0
  139. package/dist/git/constants/git.constants.d.ts +160 -0
  140. package/dist/git/constants/git.constants.js +181 -0
  141. package/dist/git/fingerprint.d.ts +74 -0
  142. package/dist/git/fingerprint.js +219 -0
  143. package/dist/git/gate-checkout.d.ts +44 -0
  144. package/dist/git/gate-checkout.js +201 -0
  145. package/dist/git/git-context.d.ts +45 -0
  146. package/dist/git/git-context.js +61 -3
  147. package/dist/git/index.d.ts +4 -2
  148. package/dist/git/index.js +2 -1
  149. package/dist/git/manifest-repository.d.ts +13 -0
  150. package/dist/git/manifest-repository.js +92 -0
  151. package/dist/git/repo-snapshot.d.ts +29 -3
  152. package/dist/git/repo-snapshot.js +110 -7
  153. package/dist/git/repository-root.d.ts +39 -0
  154. package/dist/git/repository-root.js +131 -0
  155. package/dist/git/types/git.types.d.ts +55 -0
  156. package/dist/git/types/repository-root.types.d.ts +11 -0
  157. package/dist/git/types/repository-root.types.js +1 -0
  158. package/dist/git/types/snapshot.types.d.ts +9 -0
  159. package/dist/pipeline/constants/pipeline.constants.d.ts +10 -0
  160. package/dist/pipeline/constants/pipeline.constants.js +10 -0
  161. package/dist/pipeline/hook-pipeline.js +410 -33
  162. package/dist/pipeline/types/pipeline.types.d.ts +39 -4
  163. package/dist/privacy/constants/privacy.constants.js +15 -1
  164. package/dist/privacy/index.d.ts +1 -0
  165. package/dist/privacy/index.js +1 -0
  166. package/dist/privacy/product-capture.d.ts +12 -0
  167. package/dist/privacy/product-capture.js +75 -0
  168. package/dist/privacy/sanitizer.d.ts +21 -3
  169. package/dist/privacy/sanitizer.js +52 -8
  170. package/dist/process/ancestors.d.ts +39 -0
  171. package/dist/process/ancestors.js +121 -0
  172. package/dist/process/constants/process.constants.d.ts +34 -0
  173. package/dist/process/constants/process.constants.js +34 -0
  174. package/dist/process/index.d.ts +7 -0
  175. package/dist/process/index.js +2 -0
  176. package/dist/process/types/process.types.d.ts +23 -0
  177. package/dist/process/types/process.types.js +1 -0
  178. package/dist/providers/antigravity/antigravity.adapter.d.ts +12 -1
  179. package/dist/providers/antigravity/antigravity.adapter.js +21 -3
  180. package/dist/providers/antigravity/antigravity.detect.d.ts +0 -9
  181. package/dist/providers/antigravity/antigravity.detect.js +1 -1
  182. package/dist/providers/antigravity/antigravity.provider.js +3 -2
  183. package/dist/providers/antigravity/constants/antigravity.constants.d.ts +2 -0
  184. package/dist/providers/antigravity/constants/antigravity.constants.js +2 -0
  185. package/dist/providers/claude/claude.adapter.d.ts +11 -1
  186. package/dist/providers/claude/claude.adapter.js +26 -5
  187. package/dist/providers/claude/claude.otel.d.ts +32 -18
  188. package/dist/providers/claude/claude.otel.js +81 -6
  189. package/dist/providers/claude/claude.provider.js +5 -2
  190. package/dist/providers/claude/constants/claude.constants.d.ts +2 -0
  191. package/dist/providers/claude/constants/claude.constants.js +2 -0
  192. package/dist/providers/claude/constants/claude.otel.constants.d.ts +4 -0
  193. package/dist/providers/claude/constants/claude.otel.constants.js +8 -0
  194. package/dist/providers/codex/codex.adapter.d.ts +15 -1
  195. package/dist/providers/codex/codex.adapter.js +29 -5
  196. package/dist/providers/codex/codex.otel.d.ts +36 -3
  197. package/dist/providers/codex/codex.otel.js +199 -32
  198. package/dist/providers/codex/codex.provider.js +5 -2
  199. package/dist/providers/codex/constants/codex.constants.d.ts +2 -0
  200. package/dist/providers/codex/constants/codex.constants.js +16 -0
  201. package/dist/providers/codex/constants/codex.otel.constants.d.ts +10 -0
  202. package/dist/providers/codex/constants/codex.otel.constants.js +10 -0
  203. package/dist/providers/constants/provider.constants.d.ts +8 -3
  204. package/dist/providers/constants/provider.constants.js +8 -3
  205. package/dist/providers/cursor/constants/cursor.constants.d.ts +9 -0
  206. package/dist/providers/cursor/constants/cursor.constants.js +9 -0
  207. package/dist/providers/cursor/cursor.adapter.d.ts +33 -1
  208. package/dist/providers/cursor/cursor.adapter.js +129 -4
  209. package/dist/providers/cursor/cursor.detect.d.ts +0 -7
  210. package/dist/providers/cursor/cursor.detect.js +1 -1
  211. package/dist/providers/cursor/cursor.provider.js +5 -2
  212. package/dist/providers/gemini/constants/gemini.constants.d.ts +9 -0
  213. package/dist/providers/gemini/constants/gemini.constants.js +9 -0
  214. package/dist/providers/gemini/constants/gemini.otel.constants.d.ts +9 -1
  215. package/dist/providers/gemini/constants/gemini.otel.constants.js +9 -0
  216. package/dist/providers/gemini/gemini.adapter.d.ts +14 -1
  217. package/dist/providers/gemini/gemini.adapter.js +25 -5
  218. package/dist/providers/gemini/gemini.detect.d.ts +0 -7
  219. package/dist/providers/gemini/gemini.detect.js +1 -1
  220. package/dist/providers/gemini/gemini.otel.d.ts +30 -21
  221. package/dist/providers/gemini/gemini.otel.js +166 -22
  222. package/dist/providers/gemini/gemini.provider.js +2 -1
  223. package/dist/providers/index.d.ts +1 -1
  224. package/dist/providers/index.js +1 -1
  225. package/dist/providers/loaders.d.ts +10 -0
  226. package/dist/providers/loaders.js +40 -0
  227. package/dist/providers/provider.d.ts +11 -0
  228. package/dist/providers/provider.js +1 -1
  229. package/dist/providers/registry.d.ts +11 -8
  230. package/dist/providers/registry.js +11 -15
  231. package/dist/providers/shared/bearer-rewrite.d.ts +19 -0
  232. package/dist/providers/shared/bearer-rewrite.js +46 -0
  233. package/dist/providers/shared/constants/hook-refusal.constants.d.ts +7 -0
  234. package/dist/providers/shared/constants/hook-refusal.constants.js +7 -0
  235. package/dist/providers/shared/constants/shell-directories.constants.d.ts +30 -0
  236. package/dist/providers/shared/constants/shell-directories.constants.js +39 -0
  237. package/dist/providers/shared/constants/tooling.constants.d.ts +24 -2
  238. package/dist/providers/shared/constants/tooling.constants.js +25 -3
  239. package/dist/providers/shared/event-builder.d.ts +12 -14
  240. package/dist/providers/shared/event-builder.js +20 -14
  241. package/dist/providers/shared/exporter-allowlist.d.ts +20 -0
  242. package/dist/providers/shared/exporter-allowlist.js +49 -0
  243. package/dist/providers/shared/hook-config.d.ts +2 -21
  244. package/dist/providers/shared/hook-config.js +5 -4
  245. package/dist/providers/shared/hook-refusal.d.ts +12 -0
  246. package/dist/providers/shared/hook-refusal.js +17 -1
  247. package/dist/providers/shared/install-record.d.ts +12 -2
  248. package/dist/providers/shared/install-record.js +5 -2
  249. package/dist/providers/shared/shell-directories.d.ts +24 -0
  250. package/dist/providers/shared/shell-directories.js +90 -0
  251. package/dist/providers/shared/tooling.d.ts +40 -1
  252. package/dist/providers/shared/tooling.js +70 -1
  253. package/dist/providers/shared/types/adapter.types.d.ts +1 -2
  254. package/dist/providers/types/provider.types.d.ts +81 -1
  255. package/dist/snapshot/constants/snapshot.constants.d.ts +32 -0
  256. package/dist/snapshot/constants/snapshot.constants.js +33 -0
  257. package/dist/snapshot/snapshot-event.js +52 -11
  258. package/dist/snapshot/snapshot-pipeline.js +1 -1
  259. package/dist/snapshot/types/snapshot.types.d.ts +2 -0
  260. package/dist/storage/atomic-file.d.ts +21 -0
  261. package/dist/storage/atomic-file.js +20 -1
  262. package/dist/storage/constants/storage.constants.d.ts +19 -0
  263. package/dist/storage/constants/storage.constants.js +19 -0
  264. package/dist/storage/disabled.d.ts +13 -0
  265. package/dist/storage/disabled.js +24 -0
  266. package/dist/storage/index.d.ts +2 -0
  267. package/dist/storage/index.js +2 -0
  268. package/dist/storage/paths.js +3 -2
  269. package/dist/storage/schemas/storage.schema.d.ts +72 -0
  270. package/dist/storage/schemas/storage.schema.js +6 -0
  271. package/dist/storage/sweep-marker.d.ts +19 -0
  272. package/dist/storage/sweep-marker.js +55 -0
  273. package/dist/storage/types/storage.types.d.ts +2 -0
  274. package/dist/storage/uninstalled.d.ts +58 -0
  275. package/dist/storage/uninstalled.js +107 -0
  276. package/dist/transport/auth-block.d.ts +66 -0
  277. package/dist/transport/auth-block.js +129 -0
  278. package/dist/transport/constants/transport.constants.d.ts +82 -3
  279. package/dist/transport/constants/transport.constants.js +83 -4
  280. package/dist/transport/cooldown.js +8 -1
  281. package/dist/transport/delivery.d.ts +14 -6
  282. package/dist/transport/delivery.js +80 -55
  283. package/dist/transport/http-transport.d.ts +1 -0
  284. package/dist/transport/http-transport.js +52 -10
  285. package/dist/transport/index.d.ts +6 -3
  286. package/dist/transport/index.js +3 -0
  287. package/dist/transport/queue-partition.d.ts +91 -0
  288. package/dist/transport/queue-partition.js +143 -0
  289. package/dist/transport/queue.d.ts +99 -20
  290. package/dist/transport/queue.js +210 -69
  291. package/dist/transport/response-body.d.ts +25 -0
  292. package/dist/transport/response-body.js +64 -0
  293. package/dist/transport/send.d.ts +11 -0
  294. package/dist/transport/send.js +17 -0
  295. package/dist/transport/types/delivery-flow.types.d.ts +19 -0
  296. package/dist/transport/types/delivery-flow.types.js +1 -0
  297. package/dist/transport/types/transport.types.d.ts +45 -0
  298. package/dist/turns/claude-transcript.d.ts +19 -1
  299. package/dist/turns/claude-transcript.js +46 -1
  300. package/dist/turns/codex-originator.d.ts +11 -0
  301. package/dist/turns/codex-originator.js +31 -0
  302. package/dist/turns/codex-transcript.d.ts +30 -0
  303. package/dist/turns/codex-transcript.js +88 -0
  304. package/dist/turns/constants/turns.constants.d.ts +141 -5
  305. package/dist/turns/constants/turns.constants.js +155 -5
  306. package/dist/turns/file-identity.d.ts +27 -0
  307. package/dist/turns/file-identity.js +48 -0
  308. package/dist/turns/gemini-transcript.d.ts +30 -0
  309. package/dist/turns/gemini-transcript.js +96 -0
  310. package/dist/turns/index.d.ts +3 -3
  311. package/dist/turns/index.js +1 -1
  312. package/dist/turns/inherited-checkout.d.ts +54 -0
  313. package/dist/turns/inherited-checkout.js +155 -0
  314. package/dist/turns/native-session-titles.d.ts +26 -0
  315. package/dist/turns/native-session-titles.js +102 -0
  316. package/dist/turns/transcript.d.ts +3 -2
  317. package/dist/turns/transcript.js +5 -1
  318. package/dist/turns/turn-state.d.ts +224 -3
  319. package/dist/turns/turn-state.js +456 -21
  320. package/dist/turns/turn-summary.d.ts +1 -14
  321. package/dist/turns/turn-summary.js +87 -51
  322. package/dist/turns/turn-tracker.d.ts +21 -2
  323. package/dist/turns/turn-tracker.js +379 -56
  324. package/dist/turns/types/transcript.types.d.ts +5 -0
  325. package/dist/turns/types/turn-state.types.d.ts +116 -5
  326. package/dist/turns/types/turn-summary.types.d.ts +64 -14
  327. package/dist/turns/types/turn-tracker.types.d.ts +27 -1
  328. package/dist/turns/work-checkout.d.ts +67 -0
  329. package/dist/turns/work-checkout.js +700 -0
  330. package/dist/untraced/constants/untraced.constants.d.ts +31 -0
  331. package/dist/untraced/constants/untraced.constants.js +63 -0
  332. package/dist/untraced/untraced.d.ts +35 -0
  333. package/dist/untraced/untraced.js +105 -0
  334. package/dist/update/constants/update.constants.d.ts +18 -0
  335. package/dist/update/constants/update.constants.js +20 -0
  336. package/dist/update/update-check.d.ts +52 -0
  337. package/dist/update/update-check.js +113 -0
  338. package/docs/AUDIT_PROMPT.md +129 -0
  339. package/docs/DATA_HANDLING.md +655 -0
  340. package/docs/ENTERPRISE_DEPLOYMENT.md +194 -0
  341. package/docs/PERFORMANCE.md +81 -0
  342. package/package.json +14 -4
  343. package/dist/enrollment/enrollment-provider.d.ts +0 -5
  344. package/dist/enrollment/manual-enrollment.d.ts +0 -32
  345. package/dist/enrollment/manual-enrollment.js +0 -72
  346. package/example/README.md +0 -43
  347. package/example/server.mjs +0 -240
  348. /package/dist/{enrollment/enrollment-provider.js → config/types/destination.types.js} +0 -0
@@ -3,16 +3,29 @@ import fs from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import process from 'node:process';
5
5
  import { fileURLToPath } from 'node:url';
6
- import { eventsUrl, otlpBaseUrl } from '../config/config.js';
6
+ import { describeCredential } from '../credentials/credential-status.js';
7
+ import { awaitingSignIn, hasCredential } from '../credentials/identity.js';
8
+ import { selectRoot } from '../config/root-config.js';
9
+ import { enabledSignalNames, enforcementUrl, eventsUrl, otlpBaseUrl } from '../config/config.js';
7
10
  import { loadEffectiveConfig } from '../config/repo-config.js';
8
- import { CONTENT_CAPTURE_FLAGS } from '../config/constants/config.constants.js';
11
+ import { storedRetiredCapture } from '../config/config-store.js';
12
+ import { CONTENT_CAPTURE_KEYS } from '../config/constants/config.constants.js';
9
13
  import { meetsMinVersion, parseVersion } from '../core/version.js';
10
14
  import { findExecutable } from '../core/which.js';
11
- import { developerIdentity } from '../git/git-context.js';
15
+ import { developerDisplayName, developerIdentity } from '../git/git-context.js';
12
16
  import { providers } from '../providers/registry.js';
13
- import { buildCliContext, buildHookCommand, buildQueue } from './context.js';
14
- import { BACKEND_PROBE_TIMEOUT_MS, CLAUDE_MIN_VERSION_FOR_PROMPT_ID, CLAUDE_VERSION_TIMEOUT_MS, DEVELOPER_IDENTITY_CHECK, DEVELOPER_IDENTITY_REMEDIES, GIT_VERSION_TIMEOUT_MS, MIN_NODE_MAJOR, NO_DEVELOPER_IDENTITY, STALE_QUEUE_AGE_MS } from './constants/cli.constants.js';
15
- import { bold, dim, levelSymbol, println } from './ui.js';
17
+ import { removeRefusedExporters } from '../providers/shared/exporter-allowlist.js';
18
+ import { saveInstallState } from '../storage/install-state.js';
19
+ import { SECRET_FILE_MODE } from '../storage/constants/storage.constants.js';
20
+ import { unattributedCount, unattributedQueue } from '../transport/queue-partition.js';
21
+ import { AUTH_REJECTED_STATUSES, CONTENT_TYPE_HEADER, JSON_CONTENT_TYPE } from '../transport/constants/transport.constants.js';
22
+ import { discardResponseBody } from '../transport/response-body.js';
23
+ import { edgeHeaders } from '../transport/headers.js';
24
+ import { DEVICE_SOURCE_BATCH_CODE } from '../credentials/constants/credentials.constants.js';
25
+ import { buildAuthBlock, buildCliContext, buildHookCommand, buildQueue, resolveContextBearer } from './context.js';
26
+ import { installedHookChecks } from './hook-check.js';
27
+ import { BACKEND_CONNECTIVITY_CHECK, BACKEND_PROBE_TIMEOUT_MS, EMPTY_BATCH_REFUSED_STATUS, CLAUDE_MIN_VERSION_FOR_PROMPT_ID, CLAUDE_VERSION_TIMEOUT_MS, DEVELOPER_IDENTITY_CHECK, DEVELOPER_IDENTITY_REMEDIES, DEVELOPER_NAME_REMEDIES, GIT_VERSION_TIMEOUT_MS, MIN_NODE_MAJOR, NO_DEVELOPER_IDENTITY, NO_DEVELOPER_NAME, STALE_QUEUE_AGE_MS } from './constants/cli.constants.js';
28
+ import { bold, customEndpointOverride, dim, levelSymbol, println } from './ui.js';
16
29
  /**
17
30
  * `agentwatch doctor` — every reason telemetry might not be arriving, in one
18
31
  * pass.
@@ -26,11 +39,28 @@ import { bold, dim, levelSymbol, println } from './ui.js';
26
39
  * @returns 1 when any check failed, else 0.
27
40
  */
28
41
  export async function runDoctor(env, options = {}) {
29
- const context = await buildCliContext(env);
42
+ const loaded = await buildCliContext(env);
43
+ // Before the per-agent checks, so they inspect what is left. Even while
44
+ // disabled: the off switch stops hooks, not an exporter carrying a bearer.
45
+ // Not on a missing or invalid config, whose fallback trusts no custom origin.
46
+ const swept = loaded.configState === 'ok'
47
+ ? await removeRefusedExporters({ env, paths: loaded.paths, config: loaded.config, hookCommand: '', installState: loaded.installState }, providers)
48
+ : { installState: loaded.installState, refused: [] };
49
+ if (swept.installState !== loaded.installState)
50
+ await saveInstallState(loaded.paths, swept.installState);
51
+ const context = { ...loaded, installState: swept.installState };
52
+ const gated = await withheldNativeSignals(env, context.config);
30
53
  const checks = [
54
+ { name: 'AgentWatch operation', level: context.disabled ? 'warn' : 'ok', detail: context.disabled ? 'DISABLED; restart running agents to stop native exporters' : 'enabled' },
55
+ { name: 'content capture consent', level: 'ok', detail: context.config.contentCaptureConsent ? 'granted globally (prompt text and tool content, per capture flag; responses are never collected)' : 'absent — prompt text and tool content disabled; responses are never collected' },
56
+ retiredCaptureCheck(await storedRetiredCapture(context.paths)),
57
+ nativePrivacyCheck(gated),
31
58
  nodeVersionCheck(),
32
59
  configurationCheck(context),
33
- ...endpointChecks(context),
60
+ ...(await endpointChecks(context)),
61
+ ...endpointAllowlistChecks(context.config),
62
+ ...swept.refused.map((refused) => ({ name: `${refused.agent} native exporter allowlist`, level: refused.removed ? 'warn' : 'fail', detail: refused.message })),
63
+ enforcementCheck(context),
34
64
  await developerIdentityCheck(env, context, options),
35
65
  ...(await connectivityChecks(context)),
36
66
  await gitCheck(),
@@ -53,6 +83,67 @@ export async function runDoctor(env, options = {}) {
53
83
  println();
54
84
  return exitCode(checks);
55
85
  }
86
+ /**
87
+ * Detected providers holding back signals, and which signals each one loses.
88
+ *
89
+ * Asks every configurator its own rule rather than keying on `otel.logs` and
90
+ * one global predicate: Codex drops logs *and* traces together on the two tool
91
+ * flags, Gemini never gets traces (they can carry prompts) even when its logs
92
+ * are allowed, and a provider with per-field switches — Claude — answers
93
+ * nothing. Keying on `otel.logs` alone reported "compatible" for both of the
94
+ * cases above while the exporters were in fact being withheld.
95
+ *
96
+ * @param env - User environment, for detection.
97
+ * @param config - Effective global configuration.
98
+ * @returns One `Name (signals)` entry per affected provider that is installed.
99
+ */
100
+ async function withheldNativeSignals(env, config) {
101
+ const gated = await Promise.all(providers.map(async (provider) => {
102
+ const withheld = provider.nativeTelemetry?.withheldSignals?.(config) ?? [];
103
+ if (withheld.length === 0 || !(await provider.detect(env)).detected)
104
+ return undefined;
105
+ return `${provider.displayName} (${withheld.join(', ')})`;
106
+ }));
107
+ return gated.filter((entry) => entry !== undefined);
108
+ }
109
+ /**
110
+ * Explain why a detected provider's native signals cannot run in metadata-only mode.
111
+ *
112
+ * Named providers only: warning about Codex and Gemini on a Claude-only machine
113
+ * is a permanent warning nobody can act on, which is how a report stops being read.
114
+ *
115
+ * @param gated - Affected providers and the signals they lose.
116
+ * @returns A visible limitation or the explicit consent state.
117
+ */
118
+ function nativePrivacyCheck(gated) {
119
+ return {
120
+ name: 'native telemetry privacy',
121
+ level: gated.length > 0 ? 'warn' : 'ok',
122
+ detail: gated.length > 0
123
+ ? `native signals withheld because provider telemetry can contain prompts or tool arguments/results: ${gated.join('; ')}; tool-content consent enables Codex and Gemini logs, nothing enables signals that carry prompts`
124
+ : 'requested native signals are compatible with current global content consent'
125
+ };
126
+ }
127
+ /**
128
+ * Name retired prompt/response flags still written in the global config.
129
+ *
130
+ * They collect nothing whatever their value — the schema strips them, and
131
+ * prompt text is `promptText` now — but a file that still says `prompts: true`
132
+ * reads as opted in to anyone auditing the machine. The next `agentwatch setup`
133
+ * removes them.
134
+ *
135
+ * @param retired - Retired keys present on disk.
136
+ * @returns The check.
137
+ */
138
+ function retiredCaptureCheck(retired) {
139
+ return {
140
+ name: 'retired capture flags',
141
+ level: retired.length > 0 ? 'warn' : 'ok',
142
+ detail: retired.length > 0
143
+ ? `capture ${retired.join(', ')} still in the config but ignored — prompt text is capture.promptText, response text is never collected; run \`agentwatch setup\` to remove them`
144
+ : 'none'
145
+ };
146
+ }
56
147
  /**
57
148
  * Whether the runtime is new enough.
58
149
  *
@@ -73,24 +164,110 @@ function nodeVersionCheck() {
73
164
  * @returns The check.
74
165
  */
75
166
  function configurationCheck(context) {
167
+ // The state first, because `loadConfig` attaches warnings to an *invalid*
168
+ // result too: a file with both a refused URL and a genuinely fatal error —
169
+ // a `schemaVersion` from a downgrade, a `maxAttempts` a templating tool sent
170
+ // as a string — would otherwise report only the URL, and never the fact that
171
+ // the runtime is on `fallbackConfig()` with no token, no installation id and
172
+ // the backlog orphaned. The developer fixes the URL, re-runs, and reads the
173
+ // same line. `status.ts` orders these the same way.
174
+ if (context.configState === 'invalid') {
175
+ return { name: 'configuration', level: 'fail', detail: [context.configError, ...context.configWarnings].join('; ') };
176
+ }
177
+ // Then a refused field: the file parsed, so every other check reads healthy
178
+ // while one destination receives nothing.
179
+ if (context.configWarnings.length > 0)
180
+ return { name: 'configuration', level: 'fail', detail: `${context.paths.configFile}: ${context.configWarnings.join('; ')}` };
76
181
  if (context.configState === 'ok')
77
182
  return { name: 'configuration', level: 'ok', detail: context.paths.configFile };
78
- if (context.configState === 'missing')
79
- return { name: 'configuration', level: 'warn', detail: 'not found — run `agentwatch setup`' };
80
- return { name: 'configuration', level: 'fail', detail: context.configError };
183
+ return { name: 'configuration', level: 'warn', detail: 'not found — run `agentwatch setup`' };
81
184
  }
82
185
  /**
83
186
  * Whether a backend and a token are configured. Never reveals the token.
84
187
  *
188
+ * The *rooted* identity, and it says so when a root produced it: a diagnostic
189
+ * that names the machine-global endpoint while the hooks in this directory send
190
+ * somewhere else on another token is a diagnostic of an install nobody is
191
+ * running.
192
+ *
85
193
  * @param context - Resolved CLI context.
86
194
  * @returns The checks.
87
195
  */
88
- function endpointChecks(context) {
196
+ async function endpointChecks(context) {
197
+ const config = context.identityConfig;
198
+ const via = context.identityRoot === undefined ? '' : ` (root ${context.identityRoot})`;
199
+ const credential = await describeCredential(context.paths, config, context.credentialScope);
89
200
  return [
90
- { name: 'backend endpoint', level: context.config.endpoint ? 'ok' : 'warn', detail: context.config.endpoint ?? 'not configured' },
91
- { name: 'auth token', level: 'ok', detail: context.config.token ? 'present (hidden)' : 'none configured' }
201
+ { name: 'backend endpoint', level: config.endpoint ? 'ok' : 'warn', detail: endpointDetail(config.endpoint, via) },
202
+ { name: 'credential', level: credential.level, detail: `${credential.detail}${via}` }
92
203
  ];
93
204
  }
205
+ /**
206
+ * The origins this machine trusts outside the Agent Watch hosts, when it has any.
207
+ *
208
+ * `warn`, not `fail`: the override is a deliberate, supported setup for a
209
+ * self-hosted backend, and a fleet script must not treat it as broken. Never
210
+ * silent while it exists (SPEC R9). A URL the allowlist refused is the
211
+ * configuration check's failure, with its remedy.
212
+ *
213
+ * @param config - The machine config.
214
+ * @returns The check, or none.
215
+ */
216
+ function endpointAllowlistChecks(config) {
217
+ if (config.customEndpoints.length === 0)
218
+ return [];
219
+ return [{ name: 'endpoint allowlist', level: 'warn', detail: customEndpointOverride(config.customEndpoints) }];
220
+ }
221
+ // A refused root must never expose its bearer to machine enforcement, but the
222
+ // resulting lack of budget checks must be an explicit failure in diagnostics.
223
+ function enforcementCheck(context) {
224
+ const name = 'budget enforcement';
225
+ const config = context.identityConfig;
226
+ const via = context.identityRoot === undefined ? '' : ` under root ${context.identityRoot}`;
227
+ if (context.disabled || !config.enforcement.enabled)
228
+ return { name, level: 'warn', detail: 'disabled; budget caps are not enforced' };
229
+ if (!hasCredential(config))
230
+ return { name, level: 'warn', detail: 'no credential configured; budget caps are not enforced' };
231
+ const url = enforcementUrl(config);
232
+ if (!url)
233
+ return { name, level: 'fail', detail: `budget caps are not enforced${via}: no usable decision URL; fix the endpoint reported by the configuration check` };
234
+ const root = context.identityRoot === undefined ? undefined : selectRoot(context.config.roots, context.identityRoot)?.override;
235
+ const host = new URL(url).host;
236
+ // Compare destinations, not which fields happened to be present. An own
237
+ // base states policy intent; otherwise explicit telemetry routes identify
238
+ // the root's hosts, falling back to the shared machine base for token-only roots.
239
+ const routes = root?.endpoint ? [root.endpoint] : [root?.eventsUrl, root?.otlpUrl].filter((value) => Boolean(value));
240
+ const expected = routes.length > 0 ? routes : [context.config.endpoint];
241
+ // `none match`, not `any differs`: a root with a split ingest - events to the backend, OTLP
242
+ // to its own collector - declares two hosts, and the decision host can only be one of them.
243
+ // Asking whether any route differs calls that layout foreign while the decision host is the
244
+ // root's own events host, and then advises setting `endpoint`, which would collapse the split.
245
+ // The credential is somewhere it was never pointed at only when nothing the root declared matches.
246
+ const foreignPolicy = !expected.some((value) => value && new URL(value).host === host);
247
+ if (root && foreignPolicy) {
248
+ return { name, level: 'warn', detail: `budget decisions at ${host} use this root's credential${via}; set this root's endpoint if budget checks belong elsewhere` };
249
+ }
250
+ return { name, level: 'ok', detail: `decision route at ${host}${via}; request failures allow turns` };
251
+ }
252
+ /**
253
+ * How the endpoint reads in the report when there is no URL to print.
254
+ *
255
+ * Three states, not two: `undefined` is "nothing was ever configured", `null`
256
+ * is "a URL was written here and the edge refuses to talk to it". Printing the
257
+ * latter through the same branch as a real URL interpolated the literal string
258
+ * `null` into a report an install script parses.
259
+ *
260
+ * @param endpoint - The rooted identity's endpoint, as parsed.
261
+ * @param via - Suffix naming the root, empty for the machine identity.
262
+ * @returns The detail line.
263
+ */
264
+ function endpointDetail(endpoint, via) {
265
+ if (endpoint === undefined)
266
+ return 'not configured';
267
+ if (endpoint === null)
268
+ return `refused — see the configuration check${via}`;
269
+ return `${endpoint}${via}`;
270
+ }
94
271
  /**
95
272
  * Whether anything on this machine can name the developer.
96
273
  *
@@ -105,10 +282,24 @@ function endpointChecks(context) {
105
282
  * @returns The check.
106
283
  */
107
284
  async function developerIdentityCheck(env, context, options) {
108
- const identity = await developerIdentity(context.config.developerEmail, env.cwd, { home: env.home, run: options.gitRun });
285
+ // Together, not in turn: each can cost its own git timeout, and doctor has no
286
+ // reason to pay both in sequence.
287
+ const [identity, name] = await Promise.all([
288
+ developerIdentity(context.identityConfig.developerEmail, env.cwd, { home: env.home, run: options.gitRun }),
289
+ developerDisplayName(context.identityConfig.developerName, env.cwd, { home: env.home, run: options.gitRun })
290
+ ]);
291
+ // A code names its developer on the platform: a CI runner needs no email of its own.
292
+ if (!identity && context.identityConfig.device?.source === DEVICE_SOURCE_BATCH_CODE)
293
+ return { name: DEVELOPER_IDENTITY_CHECK, level: 'ok', detail: 'the identity the enrollment code names' };
294
+ // Not yet a fault on an install waiting for its sign-in, which names the developer.
109
295
  if (!identity)
110
- return { name: DEVELOPER_IDENTITY_CHECK, level: 'fail', detail: `${NO_DEVELOPER_IDENTITY}; ${DEVELOPER_IDENTITY_REMEDIES}` };
111
- return { name: DEVELOPER_IDENTITY_CHECK, level: 'ok', detail: identity };
296
+ return { name: DEVELOPER_IDENTITY_CHECK, level: awaitingSignIn(context.identityConfig) ? 'warn' : 'fail', detail: `${NO_DEVELOPER_IDENTITY}; ${DEVELOPER_IDENTITY_REMEDIES}` };
297
+ // The name is reported beside the identity, never instead of it: the address
298
+ // is what a turn is keyed on, and a reader has to be able to see the value
299
+ // policy will match.
300
+ if (!name)
301
+ return { name: DEVELOPER_IDENTITY_CHECK, level: 'ok', detail: `${identity}; ${NO_DEVELOPER_NAME} (${DEVELOPER_NAME_REMEDIES})` };
302
+ return { name: DEVELOPER_IDENTITY_CHECK, level: 'ok', detail: `${identity} (${name})` };
112
303
  }
113
304
  /**
114
305
  * Whether the backend answers at all, and where OTLP would go.
@@ -120,33 +311,96 @@ async function developerIdentityCheck(env, context, options) {
120
311
  * @returns The checks.
121
312
  */
122
313
  async function connectivityChecks(context) {
314
+ if (context.disabled)
315
+ return [];
123
316
  const checks = [];
124
- const url = eventsUrl(context.config);
125
- if (url)
126
- checks.push(await probeBackend(url));
127
- const otlp = otlpBaseUrl(context.config);
317
+ // The rooted URL, probed with the rooted token: a 2xx here is what lifts a
318
+ // standing block, and the only credential whose proof may lift a block is the
319
+ // one the block was raised against.
320
+ const url = eventsUrl(context.identityConfig);
321
+ checks.push(url ? await probeBackend(url, context) : { name: BACKEND_CONNECTIVITY_CHECK, level: 'warn', detail: noBackendDetail(context) });
322
+ const otlp = otlpBaseUrl(context.identityConfig);
128
323
  if (otlp)
129
324
  checks.push({ name: 'OTLP base URL', level: 'ok', detail: otlp });
130
325
  return checks;
131
326
  }
132
327
  /**
133
- * Post an empty batch and report what came back.
328
+ * Why there is nothing to probe.
329
+ *
330
+ * A root that names a destination of its own does not inherit the machine's
331
+ * routes, so a root that named only its OTLP base has no events route at all —
332
+ * a deliberate stop, but one that read as an unconfigured machine while the
333
+ * line above printed this root's endpoint. `agentwatch setup` is the wrong
334
+ * remedy for it too: re-running under the root writes the machine's endpoint
335
+ * into the entry, which stops it naming a destination of its own and quietly
336
+ * makes it a second seat on the machine's backend.
337
+ *
338
+ * @param context - Resolved CLI context.
339
+ * @returns The detail line.
340
+ */
341
+ function noBackendDetail(context) {
342
+ if (context.identityRoot === undefined)
343
+ return 'no backend configured yet — run `agentwatch setup`';
344
+ if (context.identityConfig.endpoint === null)
345
+ return `root ${context.identityRoot} has a refused endpoint and no events route — fix the refused endpoint, see the configuration check`;
346
+ if (context.identityConfig.eventsUrl === null)
347
+ return `root ${context.identityRoot} has no usable eventsUrl — check the configuration warnings or set an events route on this root`;
348
+ return `root ${context.identityRoot} names a backend of its own and no events route to it — set "eventsUrl" or "endpoint" on that root, or remove its other URL to inherit the machine's`;
349
+ }
350
+ /**
351
+ * Post an empty batch as the configured install, and say what came back.
352
+ *
353
+ * Authenticated on purpose: an anonymous probe answers a question nobody asked.
354
+ * It made a healthy install whose backend requires auth *warn* on 401, and made
355
+ * the single most common misconfiguration — a wrong, expired or revoked token —
356
+ * indistinguishable from success. Sending the same headers a real delivery
357
+ * sends is what makes the verdict a statement about *this* install.
358
+ *
359
+ * It runs whatever the local state says, block or no block: the diagnostic is
360
+ * the operator asking the backend a direct question, and must never be answered
361
+ * from a cache. A 2xx is therefore also the proof that lifts a standing block.
134
362
  *
135
363
  * @param url - The events URL.
364
+ * @param context - Resolved CLI context, for the credential and the block.
136
365
  * @returns The check.
137
366
  */
138
- async function probeBackend(url) {
367
+ async function probeBackend(url, context) {
368
+ const name = BACKEND_CONNECTIVITY_CHECK;
369
+ // Nothing to prove, and an install that has not signed in sends nothing at all.
370
+ if (awaitingSignIn(context.identityConfig))
371
+ return { name, level: 'warn', detail: `${url} not probed: not signed in yet` };
372
+ const bearer = await resolveContextBearer(context, BACKEND_PROBE_TIMEOUT_MS);
373
+ // Probing with no bearer would earn a 401 that says nothing about the
374
+ // credential this machine actually holds; the credential check names why.
375
+ if (hasCredential(context.identityConfig) && !bearer) {
376
+ return { name, level: 'fail', detail: `${url} not probed: no access token could be obtained for this machine's device credential — see the credential check` };
377
+ }
139
378
  try {
140
379
  const response = await fetch(url, {
141
380
  method: 'POST',
142
- headers: { 'content-type': 'application/json' },
381
+ headers: { [CONTENT_TYPE_HEADER]: JSON_CONTENT_TYPE, ...edgeHeaders(bearer, context.identityConfig.installationId) },
143
382
  body: JSON.stringify({ events: [] }),
383
+ redirect: 'error',
144
384
  signal: AbortSignal.timeout(BACKEND_PROBE_TIMEOUT_MS)
145
385
  });
146
- return { name: 'backend connectivity', level: response.ok ? 'ok' : 'warn', detail: `${url} -> HTTP ${response.status}` };
386
+ discardResponseBody(response);
387
+ if (response.ok) {
388
+ await buildAuthBlock(context).clear();
389
+ return { name, level: 'ok', detail: `${url} -> HTTP ${response.status}` };
390
+ }
391
+ // The gateway authenticates before it validates the body, and answers an
392
+ // empty batch 422: the credential passed, only the probe's payload did not.
393
+ if (response.status === EMPTY_BATCH_REFUSED_STATUS) {
394
+ await buildAuthBlock(context).clear();
395
+ return { name, level: 'ok', detail: `${url} -> HTTP ${response.status}: credential accepted (the empty probe batch is refused by design)` };
396
+ }
397
+ if (AUTH_REJECTED_STATUSES.has(response.status)) {
398
+ return { name, level: 'fail', detail: `${url} -> HTTP ${response.status}: credential rejected — the configured token is wrong, expired or revoked` };
399
+ }
400
+ return { name, level: 'warn', detail: `${url} -> HTTP ${response.status}` };
147
401
  }
148
402
  catch (error) {
149
- return { name: 'backend connectivity', level: 'fail', detail: `${url} unreachable (${error.name})` };
403
+ return { name, level: 'fail', detail: `${url} unreachable (${error.name})` };
150
404
  }
151
405
  }
152
406
  /**
@@ -169,6 +423,7 @@ async function agentChecks(env, context) {
169
423
  const checks = [];
170
424
  for (const provider of providers) {
171
425
  const detection = await provider.detect(env);
426
+ checks.push(...(await installedHookChecks(detection.hookConfigPath, env)).map((check) => ({ ...check, name: `${provider.displayName} ${check.name}` })));
172
427
  if (!detection.detected) {
173
428
  checks.push({ name: provider.displayName, level: 'warn', detail: 'not detected' });
174
429
  continue;
@@ -180,7 +435,7 @@ async function agentChecks(env, context) {
180
435
  level: detection.hooksInstalled ? 'ok' : 'warn',
181
436
  detail: detection.hooksInstalled ? detection.hookConfigPath : 'not installed — run `agentwatch setup`'
182
437
  });
183
- if (provider.nativeTelemetry)
438
+ if (provider.nativeTelemetry && !context.disabled)
184
439
  checks.push(await otelCheck(provider, env, context));
185
440
  }
186
441
  return checks;
@@ -258,14 +513,36 @@ async function otelCheck(provider, env, context) {
258
513
  installState: context.installState
259
514
  };
260
515
  const status = await provider.nativeTelemetry.inspect(setupContext);
516
+ const withheld = provider.nativeTelemetry.withheldSignals?.(context.config) ?? [];
517
+ // Setup leaves it out until the sign-in, which configures it.
518
+ if (!status.configured && awaitingSignIn(context.config))
519
+ return { name: `${provider.displayName} native OpenTelemetry`, level: 'warn', detail: 'configured when you sign in with `agentwatch setup`' };
261
520
  return {
262
521
  name: `${provider.displayName} native OpenTelemetry`,
263
522
  level: status.configured ? 'ok' : 'fail',
264
523
  detail: status.configured
265
- ? (status.detail ?? 'configured (llm.call ledger enabled)')
524
+ ? (status.detail ?? configuredDetail(context.config.otel, withheld))
266
525
  : (status.conflict ?? status.detail ?? 'not configured — llm.call records would be lost')
267
526
  };
268
527
  }
528
+ /**
529
+ * What "configured" actually means for this agent right now.
530
+ *
531
+ * Gemini under partial consent is configured *and* exporting metrics only, so
532
+ * the flat "llm.call ledger enabled" line claimed a ledger that consent had
533
+ * already withheld. Name the signals instead of the intent.
534
+ *
535
+ * @param requested - The signals the machine asked for.
536
+ * @param withheld - The ones consent holds back.
537
+ * @returns The detail line.
538
+ */
539
+ function configuredDetail(requested, withheld) {
540
+ if (withheld.length === 0)
541
+ return 'configured (llm.call ledger enabled)';
542
+ const live = enabledSignalNames(requested).filter((name) => !withheld.includes(name));
543
+ const exporting = live.length > 0 ? live.join(', ') : 'nothing';
544
+ return `configured for ${exporting}; ${withheld.join(', ')} withheld by content consent${withheld.includes('logs') ? ' — no llm.call ledger from this agent' : ''}`;
545
+ }
269
546
  /**
270
547
  * Whether the offline queue is healthy.
271
548
  *
@@ -273,15 +550,21 @@ async function otelCheck(provider, env, context) {
273
550
  * @returns The check.
274
551
  */
275
552
  async function queueChecks(context) {
276
- const queue = buildQueue(context);
277
- const pending = await queue.pendingCount();
278
- const oldest = await queue.oldestPendingAgeMs();
553
+ const queue = await buildQueue(context);
554
+ const [pending, oldest, unattributed] = await Promise.all([queue.pendingCount(), queue.oldestPendingAgeMs(), unattributedCount(context.paths.queueDir)]);
279
555
  const stale = pending > 0 && oldest !== undefined && oldest > STALE_QUEUE_AGE_MS;
280
556
  return [
281
557
  {
282
558
  name: 'delivery queue',
283
559
  level: stale ? 'warn' : 'ok',
284
560
  detail: `${pending} pending${oldest !== undefined ? `, oldest ${Math.round(oldest / 60000)} min` : ''}`
561
+ },
562
+ {
563
+ name: 'unattributed queue',
564
+ level: unattributed > 0 ? 'warn' : 'ok',
565
+ detail: unattributed > 0
566
+ ? `${unattributed} event(s) predating per-tenant queues in ${unattributedQueue(context.paths.queueDir)} — move them into a tenant's partition to deliver`
567
+ : 'none'
285
568
  }
286
569
  ];
287
570
  }
@@ -312,7 +595,7 @@ async function repositoryChecks(env, context) {
312
595
  catch {
313
596
  // Repo overrides are best-effort; their absence is not a finding.
314
597
  }
315
- const enabled = CONTENT_CAPTURE_FLAGS.filter((flag) => capture[flag]);
598
+ const enabled = CONTENT_CAPTURE_KEYS.filter((flag) => capture[flag]);
316
599
  checks.push({
317
600
  name: 'privacy',
318
601
  level: 'ok',
@@ -333,7 +616,12 @@ async function writableCheck(name, dir) {
333
616
  try {
334
617
  await fs.mkdir(dir, { recursive: true });
335
618
  const probe = path.join(dir, `.probe-${process.pid}`);
336
- await fs.writeFile(probe, 'ok');
619
+ // `rm` then an exclusive create: `rm` unlinks a symlink rather than
620
+ // following it, and `wx` refuses to write through one that appears in
621
+ // between. The data root can be a shared directory — `AGENTWATCH_DATA_DIR`
622
+ // decides — and this is the one write the diagnostic makes.
623
+ await fs.rm(probe, { force: true });
624
+ await fs.writeFile(probe, 'ok', { flag: 'wx', mode: SECRET_FILE_MODE });
337
625
  await fs.rm(probe, { force: true });
338
626
  return { name, level: 'ok', detail: dir };
339
627
  }
@@ -0,0 +1,23 @@
1
+ import type { Env } from '../core/types/core.types.js';
2
+ import type { Check } from './types/cli.types.js';
3
+ /**
4
+ * Inspect commands only from a provider's user hook file, never repository config.
5
+ *
6
+ * The whole file is walked rather than a `hooks` key: Antigravity nests its
7
+ * handlers under its own group name. Only commands `isAgentWatchHookCommand`
8
+ * claims are collected, so a wider walk cannot pick up a foreign command.
9
+ *
10
+ * @param file - User hook configuration path.
11
+ * @param env - Launch environment to validate.
12
+ * @returns A finding for every distinct managed command.
13
+ */
14
+ export declare function installedHookChecks(file: string, env: Env): Promise<Check[]>;
15
+ /**
16
+ * Validate a recognized hook without invoking a shell or an unknown installation.
17
+ * @param command - Command from a user-scoped hook file.
18
+ * @param env - Coding agent launch environment.
19
+ * @param currentCli - Trusted running CLI, injectable for isolated tests.
20
+ * @param timeoutMs - Maximum version probe duration.
21
+ * @returns A diagnostic without command output or credential values.
22
+ */
23
+ export declare function checkHookCommand(command: string, env: Env, currentCli?: string, timeoutMs?: number): Promise<Check>;
@@ -0,0 +1,114 @@
1
+ import { execFile } from 'node:child_process';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { asRecord } from '../core/object.js';
6
+ import { findExecutable } from '../core/which.js';
7
+ import { isAgentWatchHookCommand, tokenizeHookCommand } from '../providers/provider.js';
8
+ import { readJsonFile } from '../storage/json-file.js';
9
+ const CLI_PATH = fileURLToPath(new URL('../cli.js', import.meta.url));
10
+ const VERSION_TIMEOUT_MS = 1500;
11
+ const VERSION_MANAGER_PATH = /(?:\.nvm|\.fnm|fnm_multishells|\.asdf|\.volta)[/\\]/;
12
+ const NODE_NAME = /^node(?:[\d.]*|js)?(?:\.exe)?$/;
13
+ const VERSION_OUTPUT = /^\d+\.\d+\.\d+(?:[-+][\w.-]+)?\s*$/;
14
+ const REMEDY = 'Install Node.js 20+ on the coding agent launch PATH, reinstall @agent-watch-ai/edge, then run agentwatch setup from that installation and restart the agent. GUI applications may have a different PATH.';
15
+ /**
16
+ * Inspect commands only from a provider's user hook file, never repository config.
17
+ *
18
+ * The whole file is walked rather than a `hooks` key: Antigravity nests its
19
+ * handlers under its own group name. Only commands `isAgentWatchHookCommand`
20
+ * claims are collected, so a wider walk cannot pick up a foreign command.
21
+ *
22
+ * @param file - User hook configuration path.
23
+ * @param env - Launch environment to validate.
24
+ * @returns A finding for every distinct managed command.
25
+ */
26
+ export async function installedHookChecks(file, env) {
27
+ const read = await readJsonFile(file);
28
+ if (read.state !== 'ok')
29
+ return [];
30
+ const commands = new Set(collectCommands(read.value));
31
+ return Promise.all([...commands].map((command) => checkHookCommand(command, env)));
32
+ }
33
+ /**
34
+ * Validate a recognized hook without invoking a shell or an unknown installation.
35
+ * @param command - Command from a user-scoped hook file.
36
+ * @param env - Coding agent launch environment.
37
+ * @param currentCli - Trusted running CLI, injectable for isolated tests.
38
+ * @param timeoutMs - Maximum version probe duration.
39
+ * @returns A diagnostic without command output or credential values.
40
+ */
41
+ export async function checkHookCommand(command, env, currentCli = CLI_PATH, timeoutMs = VERSION_TIMEOUT_MS) {
42
+ const name = 'installed hook command';
43
+ const fail = (detail) => ({ name, level: 'fail', detail: `${detail}. ${REMEDY}` });
44
+ if (!isAgentWatchHookCommand(command))
45
+ return fail('Unrecognized hook command; inspect user hook configuration manually');
46
+ const tokens = tokenizeHookCommand(command);
47
+ const prefix = tokens.slice(0, tokens.indexOf('hook'));
48
+ const executable = resolveExecutable(prefix[0], env);
49
+ const script = prefix.length === 2 ? prefix[1] : executable;
50
+ if (!executable || !(await executableFile(executable)))
51
+ return fail('Missing executable or stale nvm/fnm/asdf path');
52
+ if (!script || !path.isAbsolute(script))
53
+ return fail('Hook script no longer resolves to an absolute installation');
54
+ const actual = await fs.realpath(script).catch(() => undefined);
55
+ const expected = await fs.realpath(currentCli).catch(() => undefined);
56
+ if (!actual)
57
+ return fail('Missing CLI script or stale absolute path');
58
+ // Not a failure on its own: pnpm, yarn, volta and Windows install a wrapper
59
+ // script whose realpath is never dist/cli.js, so a healthy install lands
60
+ // here too. A hook pointing at something unresolvable already failed above.
61
+ if (!expected || actual !== expected) {
62
+ return { name, level: 'warn', detail: `Hook resolves to a different AgentWatch installation than this one; version probe skipped. ${REMEDY}` };
63
+ }
64
+ const runtime = prefix.length === 2 ? executable : findExecutable(env, 'node');
65
+ if (!runtime || !(await executableFile(runtime)))
66
+ return fail('Missing Node.js runtime on the agent PATH');
67
+ if (prefix.length === 2 && !NODE_NAME.test(path.basename(runtime)))
68
+ return fail('Unsupported runtime; version probe skipped');
69
+ // Only our verified CLI runs; the original shell command is never executed.
70
+ const ok = await new Promise((resolve) => {
71
+ execFile(runtime, [actual, '--version'], {
72
+ timeout: timeoutMs,
73
+ killSignal: 'SIGKILL',
74
+ maxBuffer: 4096,
75
+ cwd: env.home,
76
+ env: { PATH: env.vars['PATH'] ?? '', HOME: env.home }
77
+ }, (error, stdout) => resolve(!error && VERSION_OUTPUT.test(stdout)));
78
+ });
79
+ if (!ok)
80
+ return fail('Hook --version failed or timed out');
81
+ const versionManaged = VERSION_MANAGER_PATH.test(executable);
82
+ return {
83
+ name,
84
+ level: versionManaged ? 'warn' : 'ok',
85
+ detail: versionManaged
86
+ ? `Resolved, but tied to a version-manager path that may become stale. ${REMEDY}`
87
+ : 'CLI and Node.js resolve; bounded --version passed. Repeat doctor with the GUI agent launch PATH if it differs.'
88
+ };
89
+ }
90
+ function collectCommands(value) {
91
+ if (Array.isArray(value))
92
+ return value.flatMap(collectCommands);
93
+ const record = asRecord(value);
94
+ if (!record)
95
+ return [];
96
+ const command = record['command'];
97
+ if (typeof command === 'string')
98
+ return isAgentWatchHookCommand(command) ? [command] : [];
99
+ return Object.values(record).flatMap(collectCommands);
100
+ }
101
+ function resolveExecutable(value, env) {
102
+ if (path.isAbsolute(value))
103
+ return value;
104
+ return findExecutable(env, value);
105
+ }
106
+ async function executableFile(file) {
107
+ try {
108
+ await fs.access(file, fs.constants.X_OK);
109
+ return (await fs.stat(file)).isFile();
110
+ }
111
+ catch {
112
+ return false;
113
+ }
114
+ }