@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
@@ -3,16 +3,28 @@ 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 { 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 { buildAuthBlock, buildCliContext, buildHookCommand, buildQueue, resolveContextBearer } from './context.js';
25
+ import { installedHookChecks } from './hook-check.js';
26
+ 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';
27
+ import { bold, customEndpointOverride, dim, levelSymbol, println } from './ui.js';
16
28
  /**
17
29
  * `agentwatch doctor` — every reason telemetry might not be arriving, in one
18
30
  * pass.
@@ -26,11 +38,28 @@ import { bold, dim, levelSymbol, println } from './ui.js';
26
38
  * @returns 1 when any check failed, else 0.
27
39
  */
28
40
  export async function runDoctor(env, options = {}) {
29
- const context = await buildCliContext(env);
41
+ const loaded = await buildCliContext(env);
42
+ // Before the per-agent checks, so they inspect what is left. Even while
43
+ // disabled: the off switch stops hooks, not an exporter carrying a bearer.
44
+ // Not on a missing or invalid config, whose fallback trusts no custom origin.
45
+ const swept = loaded.configState === 'ok'
46
+ ? await removeRefusedExporters({ env, paths: loaded.paths, config: loaded.config, hookCommand: '', installState: loaded.installState }, providers)
47
+ : { installState: loaded.installState, refused: [] };
48
+ if (swept.installState !== loaded.installState)
49
+ await saveInstallState(loaded.paths, swept.installState);
50
+ const context = { ...loaded, installState: swept.installState };
51
+ const gated = await withheldNativeSignals(env, context.config);
30
52
  const checks = [
53
+ { name: 'AgentWatch operation', level: context.disabled ? 'warn' : 'ok', detail: context.disabled ? 'DISABLED; restart running agents to stop native exporters' : 'enabled' },
54
+ { 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' },
55
+ retiredCaptureCheck(await storedRetiredCapture(context.paths)),
56
+ nativePrivacyCheck(gated),
31
57
  nodeVersionCheck(),
32
58
  configurationCheck(context),
33
- ...endpointChecks(context),
59
+ ...(await endpointChecks(context)),
60
+ ...endpointAllowlistChecks(context.config),
61
+ ...swept.refused.map((refused) => ({ name: `${refused.agent} native exporter allowlist`, level: refused.removed ? 'warn' : 'fail', detail: refused.message })),
62
+ enforcementCheck(context),
34
63
  await developerIdentityCheck(env, context, options),
35
64
  ...(await connectivityChecks(context)),
36
65
  await gitCheck(),
@@ -53,6 +82,67 @@ export async function runDoctor(env, options = {}) {
53
82
  println();
54
83
  return exitCode(checks);
55
84
  }
85
+ /**
86
+ * Detected providers holding back signals, and which signals each one loses.
87
+ *
88
+ * Asks every configurator its own rule rather than keying on `otel.logs` and
89
+ * one global predicate: Codex drops logs *and* traces together on the two tool
90
+ * flags, Gemini never gets traces (they can carry prompts) even when its logs
91
+ * are allowed, and a provider with per-field switches — Claude — answers
92
+ * nothing. Keying on `otel.logs` alone reported "compatible" for both of the
93
+ * cases above while the exporters were in fact being withheld.
94
+ *
95
+ * @param env - User environment, for detection.
96
+ * @param config - Effective global configuration.
97
+ * @returns One `Name (signals)` entry per affected provider that is installed.
98
+ */
99
+ async function withheldNativeSignals(env, config) {
100
+ const gated = await Promise.all(providers.map(async (provider) => {
101
+ const withheld = provider.nativeTelemetry?.withheldSignals?.(config) ?? [];
102
+ if (withheld.length === 0 || !(await provider.detect(env)).detected)
103
+ return undefined;
104
+ return `${provider.displayName} (${withheld.join(', ')})`;
105
+ }));
106
+ return gated.filter((entry) => entry !== undefined);
107
+ }
108
+ /**
109
+ * Explain why a detected provider's native signals cannot run in metadata-only mode.
110
+ *
111
+ * Named providers only: warning about Codex and Gemini on a Claude-only machine
112
+ * is a permanent warning nobody can act on, which is how a report stops being read.
113
+ *
114
+ * @param gated - Affected providers and the signals they lose.
115
+ * @returns A visible limitation or the explicit consent state.
116
+ */
117
+ function nativePrivacyCheck(gated) {
118
+ return {
119
+ name: 'native telemetry privacy',
120
+ level: gated.length > 0 ? 'warn' : 'ok',
121
+ detail: gated.length > 0
122
+ ? `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`
123
+ : 'requested native signals are compatible with current global content consent'
124
+ };
125
+ }
126
+ /**
127
+ * Name retired prompt/response flags still written in the global config.
128
+ *
129
+ * They collect nothing whatever their value — the schema strips them, and
130
+ * prompt text is `promptText` now — but a file that still says `prompts: true`
131
+ * reads as opted in to anyone auditing the machine. The next `agentwatch setup`
132
+ * removes them.
133
+ *
134
+ * @param retired - Retired keys present on disk.
135
+ * @returns The check.
136
+ */
137
+ function retiredCaptureCheck(retired) {
138
+ return {
139
+ name: 'retired capture flags',
140
+ level: retired.length > 0 ? 'warn' : 'ok',
141
+ detail: retired.length > 0
142
+ ? `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`
143
+ : 'none'
144
+ };
145
+ }
56
146
  /**
57
147
  * Whether the runtime is new enough.
58
148
  *
@@ -73,24 +163,110 @@ function nodeVersionCheck() {
73
163
  * @returns The check.
74
164
  */
75
165
  function configurationCheck(context) {
166
+ // The state first, because `loadConfig` attaches warnings to an *invalid*
167
+ // result too: a file with both a refused URL and a genuinely fatal error —
168
+ // a `schemaVersion` from a downgrade, a `maxAttempts` a templating tool sent
169
+ // as a string — would otherwise report only the URL, and never the fact that
170
+ // the runtime is on `fallbackConfig()` with no token, no installation id and
171
+ // the backlog orphaned. The developer fixes the URL, re-runs, and reads the
172
+ // same line. `status.ts` orders these the same way.
173
+ if (context.configState === 'invalid') {
174
+ return { name: 'configuration', level: 'fail', detail: [context.configError, ...context.configWarnings].join('; ') };
175
+ }
176
+ // Then a refused field: the file parsed, so every other check reads healthy
177
+ // while one destination receives nothing.
178
+ if (context.configWarnings.length > 0)
179
+ return { name: 'configuration', level: 'fail', detail: `${context.paths.configFile}: ${context.configWarnings.join('; ')}` };
76
180
  if (context.configState === 'ok')
77
181
  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 };
182
+ return { name: 'configuration', level: 'warn', detail: 'not found — run `agentwatch setup`' };
81
183
  }
82
184
  /**
83
185
  * Whether a backend and a token are configured. Never reveals the token.
84
186
  *
187
+ * The *rooted* identity, and it says so when a root produced it: a diagnostic
188
+ * that names the machine-global endpoint while the hooks in this directory send
189
+ * somewhere else on another token is a diagnostic of an install nobody is
190
+ * running.
191
+ *
85
192
  * @param context - Resolved CLI context.
86
193
  * @returns The checks.
87
194
  */
88
- function endpointChecks(context) {
195
+ async function endpointChecks(context) {
196
+ const config = context.identityConfig;
197
+ const via = context.identityRoot === undefined ? '' : ` (root ${context.identityRoot})`;
198
+ const credential = await describeCredential(context.paths, config, context.credentialScope);
89
199
  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' }
200
+ { name: 'backend endpoint', level: config.endpoint ? 'ok' : 'warn', detail: endpointDetail(config.endpoint, via) },
201
+ { name: 'credential', level: credential.level, detail: `${credential.detail}${via}` }
92
202
  ];
93
203
  }
204
+ /**
205
+ * The origins this machine trusts outside the Agent Watch hosts, when it has any.
206
+ *
207
+ * `warn`, not `fail`: the override is a deliberate, supported setup for a
208
+ * self-hosted backend, and a fleet script must not treat it as broken. Never
209
+ * silent while it exists (SPEC R9). A URL the allowlist refused is the
210
+ * configuration check's failure, with its remedy.
211
+ *
212
+ * @param config - The machine config.
213
+ * @returns The check, or none.
214
+ */
215
+ function endpointAllowlistChecks(config) {
216
+ if (config.customEndpoints.length === 0)
217
+ return [];
218
+ return [{ name: 'endpoint allowlist', level: 'warn', detail: customEndpointOverride(config.customEndpoints) }];
219
+ }
220
+ // A refused root must never expose its bearer to machine enforcement, but the
221
+ // resulting lack of budget checks must be an explicit failure in diagnostics.
222
+ function enforcementCheck(context) {
223
+ const name = 'budget enforcement';
224
+ const config = context.identityConfig;
225
+ const via = context.identityRoot === undefined ? '' : ` under root ${context.identityRoot}`;
226
+ if (context.disabled || !config.enforcement.enabled)
227
+ return { name, level: 'warn', detail: 'disabled; budget caps are not enforced' };
228
+ if (!hasCredential(config))
229
+ return { name, level: 'warn', detail: 'no credential configured; budget caps are not enforced' };
230
+ const url = enforcementUrl(config);
231
+ if (!url)
232
+ return { name, level: 'fail', detail: `budget caps are not enforced${via}: no usable decision URL; fix the endpoint reported by the configuration check` };
233
+ const root = context.identityRoot === undefined ? undefined : selectRoot(context.config.roots, context.identityRoot)?.override;
234
+ const host = new URL(url).host;
235
+ // Compare destinations, not which fields happened to be present. An own
236
+ // base states policy intent; otherwise explicit telemetry routes identify
237
+ // the root's hosts, falling back to the shared machine base for token-only roots.
238
+ const routes = root?.endpoint ? [root.endpoint] : [root?.eventsUrl, root?.otlpUrl].filter((value) => Boolean(value));
239
+ const expected = routes.length > 0 ? routes : [context.config.endpoint];
240
+ // `none match`, not `any differs`: a root with a split ingest - events to the backend, OTLP
241
+ // to its own collector - declares two hosts, and the decision host can only be one of them.
242
+ // Asking whether any route differs calls that layout foreign while the decision host is the
243
+ // root's own events host, and then advises setting `endpoint`, which would collapse the split.
244
+ // The credential is somewhere it was never pointed at only when nothing the root declared matches.
245
+ const foreignPolicy = !expected.some((value) => value && new URL(value).host === host);
246
+ if (root && foreignPolicy) {
247
+ 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` };
248
+ }
249
+ return { name, level: 'ok', detail: `decision route at ${host}${via}; request failures allow turns` };
250
+ }
251
+ /**
252
+ * How the endpoint reads in the report when there is no URL to print.
253
+ *
254
+ * Three states, not two: `undefined` is "nothing was ever configured", `null`
255
+ * is "a URL was written here and the edge refuses to talk to it". Printing the
256
+ * latter through the same branch as a real URL interpolated the literal string
257
+ * `null` into a report an install script parses.
258
+ *
259
+ * @param endpoint - The rooted identity's endpoint, as parsed.
260
+ * @param via - Suffix naming the root, empty for the machine identity.
261
+ * @returns The detail line.
262
+ */
263
+ function endpointDetail(endpoint, via) {
264
+ if (endpoint === undefined)
265
+ return 'not configured';
266
+ if (endpoint === null)
267
+ return `refused — see the configuration check${via}`;
268
+ return `${endpoint}${via}`;
269
+ }
94
270
  /**
95
271
  * Whether anything on this machine can name the developer.
96
272
  *
@@ -105,10 +281,20 @@ function endpointChecks(context) {
105
281
  * @returns The check.
106
282
  */
107
283
  async function developerIdentityCheck(env, context, options) {
108
- const identity = await developerIdentity(context.config.developerEmail, env.cwd, { home: env.home, run: options.gitRun });
284
+ // Together, not in turn: each can cost its own git timeout, and doctor has no
285
+ // reason to pay both in sequence.
286
+ const [identity, name] = await Promise.all([
287
+ developerIdentity(context.identityConfig.developerEmail, env.cwd, { home: env.home, run: options.gitRun }),
288
+ developerDisplayName(context.identityConfig.developerName, env.cwd, { home: env.home, run: options.gitRun })
289
+ ]);
109
290
  if (!identity)
110
291
  return { name: DEVELOPER_IDENTITY_CHECK, level: 'fail', detail: `${NO_DEVELOPER_IDENTITY}; ${DEVELOPER_IDENTITY_REMEDIES}` };
111
- return { name: DEVELOPER_IDENTITY_CHECK, level: 'ok', detail: identity };
292
+ // The name is reported beside the identity, never instead of it: the address
293
+ // is what a turn is keyed on, and a reader has to be able to see the value
294
+ // policy will match.
295
+ if (!name)
296
+ return { name: DEVELOPER_IDENTITY_CHECK, level: 'ok', detail: `${identity}; ${NO_DEVELOPER_NAME} (${DEVELOPER_NAME_REMEDIES})` };
297
+ return { name: DEVELOPER_IDENTITY_CHECK, level: 'ok', detail: `${identity} (${name})` };
112
298
  }
113
299
  /**
114
300
  * Whether the backend answers at all, and where OTLP would go.
@@ -120,33 +306,93 @@ async function developerIdentityCheck(env, context, options) {
120
306
  * @returns The checks.
121
307
  */
122
308
  async function connectivityChecks(context) {
309
+ if (context.disabled)
310
+ return [];
123
311
  const checks = [];
124
- const url = eventsUrl(context.config);
125
- if (url)
126
- checks.push(await probeBackend(url));
127
- const otlp = otlpBaseUrl(context.config);
312
+ // The rooted URL, probed with the rooted token: a 2xx here is what lifts a
313
+ // standing block, and the only credential whose proof may lift a block is the
314
+ // one the block was raised against.
315
+ const url = eventsUrl(context.identityConfig);
316
+ checks.push(url ? await probeBackend(url, context) : { name: BACKEND_CONNECTIVITY_CHECK, level: 'warn', detail: noBackendDetail(context) });
317
+ const otlp = otlpBaseUrl(context.identityConfig);
128
318
  if (otlp)
129
319
  checks.push({ name: 'OTLP base URL', level: 'ok', detail: otlp });
130
320
  return checks;
131
321
  }
132
322
  /**
133
- * Post an empty batch and report what came back.
323
+ * Why there is nothing to probe.
324
+ *
325
+ * A root that names a destination of its own does not inherit the machine's
326
+ * routes, so a root that named only its OTLP base has no events route at all —
327
+ * a deliberate stop, but one that read as an unconfigured machine while the
328
+ * line above printed this root's endpoint. `agentwatch setup` is the wrong
329
+ * remedy for it too: re-running under the root writes the machine's endpoint
330
+ * into the entry, which stops it naming a destination of its own and quietly
331
+ * makes it a second seat on the machine's backend.
332
+ *
333
+ * @param context - Resolved CLI context.
334
+ * @returns The detail line.
335
+ */
336
+ function noBackendDetail(context) {
337
+ if (context.identityRoot === undefined)
338
+ return 'no backend configured yet — run `agentwatch setup`';
339
+ if (context.identityConfig.endpoint === null)
340
+ return `root ${context.identityRoot} has a refused endpoint and no events route — fix the refused endpoint, see the configuration check`;
341
+ if (context.identityConfig.eventsUrl === null)
342
+ return `root ${context.identityRoot} has no usable eventsUrl — check the configuration warnings or set an events route on this root`;
343
+ 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`;
344
+ }
345
+ /**
346
+ * Post an empty batch as the configured install, and say what came back.
347
+ *
348
+ * Authenticated on purpose: an anonymous probe answers a question nobody asked.
349
+ * It made a healthy install whose backend requires auth *warn* on 401, and made
350
+ * the single most common misconfiguration — a wrong, expired or revoked token —
351
+ * indistinguishable from success. Sending the same headers a real delivery
352
+ * sends is what makes the verdict a statement about *this* install.
353
+ *
354
+ * It runs whatever the local state says, block or no block: the diagnostic is
355
+ * the operator asking the backend a direct question, and must never be answered
356
+ * from a cache. A 2xx is therefore also the proof that lifts a standing block.
134
357
  *
135
358
  * @param url - The events URL.
359
+ * @param context - Resolved CLI context, for the credential and the block.
136
360
  * @returns The check.
137
361
  */
138
- async function probeBackend(url) {
362
+ async function probeBackend(url, context) {
363
+ const name = BACKEND_CONNECTIVITY_CHECK;
364
+ const bearer = await resolveContextBearer(context, BACKEND_PROBE_TIMEOUT_MS);
365
+ // Probing with no bearer would earn a 401 that says nothing about the
366
+ // credential this machine actually holds; the credential check names why.
367
+ if (hasCredential(context.identityConfig) && !bearer) {
368
+ return { name, level: 'fail', detail: `${url} not probed: no access token could be obtained for this machine's device credential — see the credential check` };
369
+ }
139
370
  try {
140
371
  const response = await fetch(url, {
141
372
  method: 'POST',
142
- headers: { 'content-type': 'application/json' },
373
+ headers: { [CONTENT_TYPE_HEADER]: JSON_CONTENT_TYPE, ...edgeHeaders(bearer, context.identityConfig.installationId) },
143
374
  body: JSON.stringify({ events: [] }),
375
+ redirect: 'error',
144
376
  signal: AbortSignal.timeout(BACKEND_PROBE_TIMEOUT_MS)
145
377
  });
146
- return { name: 'backend connectivity', level: response.ok ? 'ok' : 'warn', detail: `${url} -> HTTP ${response.status}` };
378
+ discardResponseBody(response);
379
+ if (response.ok) {
380
+ await buildAuthBlock(context).clear();
381
+ return { name, level: 'ok', detail: `${url} -> HTTP ${response.status}` };
382
+ }
383
+ // The gateway authenticates before it validates the body, and answers an
384
+ // empty batch 422: the credential passed, only the probe's payload did not.
385
+ if (response.status === EMPTY_BATCH_REFUSED_STATUS) {
386
+ await buildAuthBlock(context).clear();
387
+ return { name, level: 'ok', detail: `${url} -> HTTP ${response.status}: credential accepted (the empty probe batch is refused by design)` };
388
+ }
389
+ if (AUTH_REJECTED_STATUSES.has(response.status)) {
390
+ return { name, level: 'fail', detail: `${url} -> HTTP ${response.status}: credential rejected — the configured token is wrong, expired or revoked` };
391
+ }
392
+ return { name, level: 'warn', detail: `${url} -> HTTP ${response.status}` };
147
393
  }
148
394
  catch (error) {
149
- return { name: 'backend connectivity', level: 'fail', detail: `${url} unreachable (${error.name})` };
395
+ return { name, level: 'fail', detail: `${url} unreachable (${error.name})` };
150
396
  }
151
397
  }
152
398
  /**
@@ -169,6 +415,7 @@ async function agentChecks(env, context) {
169
415
  const checks = [];
170
416
  for (const provider of providers) {
171
417
  const detection = await provider.detect(env);
418
+ checks.push(...(await installedHookChecks(detection.hookConfigPath, env)).map((check) => ({ ...check, name: `${provider.displayName} ${check.name}` })));
172
419
  if (!detection.detected) {
173
420
  checks.push({ name: provider.displayName, level: 'warn', detail: 'not detected' });
174
421
  continue;
@@ -180,7 +427,7 @@ async function agentChecks(env, context) {
180
427
  level: detection.hooksInstalled ? 'ok' : 'warn',
181
428
  detail: detection.hooksInstalled ? detection.hookConfigPath : 'not installed — run `agentwatch setup`'
182
429
  });
183
- if (provider.nativeTelemetry)
430
+ if (provider.nativeTelemetry && !context.disabled)
184
431
  checks.push(await otelCheck(provider, env, context));
185
432
  }
186
433
  return checks;
@@ -258,14 +505,33 @@ async function otelCheck(provider, env, context) {
258
505
  installState: context.installState
259
506
  };
260
507
  const status = await provider.nativeTelemetry.inspect(setupContext);
508
+ const withheld = provider.nativeTelemetry.withheldSignals?.(context.config) ?? [];
261
509
  return {
262
510
  name: `${provider.displayName} native OpenTelemetry`,
263
511
  level: status.configured ? 'ok' : 'fail',
264
512
  detail: status.configured
265
- ? (status.detail ?? 'configured (llm.call ledger enabled)')
513
+ ? (status.detail ?? configuredDetail(context.config.otel, withheld))
266
514
  : (status.conflict ?? status.detail ?? 'not configured — llm.call records would be lost')
267
515
  };
268
516
  }
517
+ /**
518
+ * What "configured" actually means for this agent right now.
519
+ *
520
+ * Gemini under partial consent is configured *and* exporting metrics only, so
521
+ * the flat "llm.call ledger enabled" line claimed a ledger that consent had
522
+ * already withheld. Name the signals instead of the intent.
523
+ *
524
+ * @param requested - The signals the machine asked for.
525
+ * @param withheld - The ones consent holds back.
526
+ * @returns The detail line.
527
+ */
528
+ function configuredDetail(requested, withheld) {
529
+ if (withheld.length === 0)
530
+ return 'configured (llm.call ledger enabled)';
531
+ const live = enabledSignalNames(requested).filter((name) => !withheld.includes(name));
532
+ const exporting = live.length > 0 ? live.join(', ') : 'nothing';
533
+ return `configured for ${exporting}; ${withheld.join(', ')} withheld by content consent${withheld.includes('logs') ? ' — no llm.call ledger from this agent' : ''}`;
534
+ }
269
535
  /**
270
536
  * Whether the offline queue is healthy.
271
537
  *
@@ -273,15 +539,21 @@ async function otelCheck(provider, env, context) {
273
539
  * @returns The check.
274
540
  */
275
541
  async function queueChecks(context) {
276
- const queue = buildQueue(context);
277
- const pending = await queue.pendingCount();
278
- const oldest = await queue.oldestPendingAgeMs();
542
+ const queue = await buildQueue(context);
543
+ const [pending, oldest, unattributed] = await Promise.all([queue.pendingCount(), queue.oldestPendingAgeMs(), unattributedCount(context.paths.queueDir)]);
279
544
  const stale = pending > 0 && oldest !== undefined && oldest > STALE_QUEUE_AGE_MS;
280
545
  return [
281
546
  {
282
547
  name: 'delivery queue',
283
548
  level: stale ? 'warn' : 'ok',
284
549
  detail: `${pending} pending${oldest !== undefined ? `, oldest ${Math.round(oldest / 60000)} min` : ''}`
550
+ },
551
+ {
552
+ name: 'unattributed queue',
553
+ level: unattributed > 0 ? 'warn' : 'ok',
554
+ detail: unattributed > 0
555
+ ? `${unattributed} event(s) predating per-tenant queues in ${unattributedQueue(context.paths.queueDir)} — move them into a tenant's partition to deliver`
556
+ : 'none'
285
557
  }
286
558
  ];
287
559
  }
@@ -312,7 +584,7 @@ async function repositoryChecks(env, context) {
312
584
  catch {
313
585
  // Repo overrides are best-effort; their absence is not a finding.
314
586
  }
315
- const enabled = CONTENT_CAPTURE_FLAGS.filter((flag) => capture[flag]);
587
+ const enabled = CONTENT_CAPTURE_KEYS.filter((flag) => capture[flag]);
316
588
  checks.push({
317
589
  name: 'privacy',
318
590
  level: 'ok',
@@ -333,7 +605,12 @@ async function writableCheck(name, dir) {
333
605
  try {
334
606
  await fs.mkdir(dir, { recursive: true });
335
607
  const probe = path.join(dir, `.probe-${process.pid}`);
336
- await fs.writeFile(probe, 'ok');
608
+ // `rm` then an exclusive create: `rm` unlinks a symlink rather than
609
+ // following it, and `wx` refuses to write through one that appears in
610
+ // between. The data root can be a shared directory — `AGENTWATCH_DATA_DIR`
611
+ // decides — and this is the one write the diagnostic makes.
612
+ await fs.rm(probe, { force: true });
613
+ await fs.writeFile(probe, 'ok', { flag: 'wx', mode: SECRET_FILE_MODE });
337
614
  await fs.rm(probe, { force: true });
338
615
  return { name, level: 'ok', detail: dir };
339
616
  }
@@ -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
+ }