@app-vitals/agent-admin 0.0.1 → 0.1.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 (325) hide show
  1. package/Dockerfile +43 -0
  2. package/README.md +72 -2
  3. package/e2e/agents-page.e2e.ts +338 -0
  4. package/e2e/chat-degraded.e2e.ts +153 -0
  5. package/e2e/chat-page.e2e.ts +169 -0
  6. package/e2e/chat-progress.e2e.ts +206 -0
  7. package/e2e/chat-thread-page.e2e.ts +444 -0
  8. package/e2e/login-page.e2e.ts +148 -0
  9. package/e2e/test-server.ts +427 -0
  10. package/openapi.json +6098 -0
  11. package/openapi.platform.json +5553 -0
  12. package/package.json +62 -4
  13. package/playwright.config.ts +25 -0
  14. package/prisma/client/browser.ts +134 -0
  15. package/prisma/client/client.ts +158 -0
  16. package/prisma/client/commonInputTypes.ts +578 -0
  17. package/prisma/client/enums.ts +15 -0
  18. package/prisma/client/internal/class.ts +424 -0
  19. package/prisma/client/internal/prismaNamespace.ts +2898 -0
  20. package/prisma/client/internal/prismaNamespaceBrowser.ts +476 -0
  21. package/prisma/client/models/Account.ts +1774 -0
  22. package/prisma/client/models/AccountInvite.ts +1386 -0
  23. package/prisma/client/models/AccountMember.ts +1351 -0
  24. package/prisma/client/models/Agent.ts +4554 -0
  25. package/prisma/client/models/AgentAsk.ts +1373 -0
  26. package/prisma/client/models/AgentChatTokenUsageDailyByModel.ts +1638 -0
  27. package/prisma/client/models/AgentCronJob.ts +2416 -0
  28. package/prisma/client/models/AgentCronRun.ts +2858 -0
  29. package/prisma/client/models/AgentCronRunModelBreakdown.ts +1532 -0
  30. package/prisma/client/models/AgentCronRunSkillUsage.ts +1642 -0
  31. package/prisma/client/models/AgentEnv.ts +1421 -0
  32. package/prisma/client/models/AgentGitHubInstallationsSnapshot.ts +1289 -0
  33. package/prisma/client/models/AgentMember.ts +1316 -0
  34. package/prisma/client/models/AgentPhaseMethodology.ts +1355 -0
  35. package/prisma/client/models/AgentPlugin.ts +1421 -0
  36. package/prisma/client/models/AgentToken.ts +1380 -0
  37. package/prisma/client/models/AgentTool.ts +1351 -0
  38. package/prisma/client/models/AgentWorkQueueSnapshot.ts +1297 -0
  39. package/prisma/client/models/ChatThreadWatch.ts +1183 -0
  40. package/prisma/client/models/PushSubscription.ts +1233 -0
  41. package/prisma/client/models/SessionAlertState.ts +1187 -0
  42. package/prisma/client/models/SessionFollow.ts +1187 -0
  43. package/prisma/client/models/UserNotificationPrefs.ts +1221 -0
  44. package/prisma/client/models.ts +34 -0
  45. package/prisma/migrations/20260608000000_init/migration.sql +112 -0
  46. package/prisma/migrations/20260616000000_agent_members/migration.sql +18 -0
  47. package/prisma/migrations/20260624000000_add_agent_self_hosted/migration.sql +2 -0
  48. package/prisma/migrations/20260624120000_add_agent_repos/migration.sql +3 -0
  49. package/prisma/migrations/20260625000000_add_agent_cron_run/migration.sql +26 -0
  50. package/prisma/migrations/20260626000000_add_cron_run_token_fields/migration.sql +10 -0
  51. package/prisma/migrations/20260627000000_add_agent_chat_token_usage_daily/migration.sql +18 -0
  52. package/prisma/migrations/20260627010000_add_agent_chat_token_usage_fk/migration.sql +2 -0
  53. package/prisma/migrations/20260701000000_add_chat_threads_messages/migration.sql +37 -0
  54. package/prisma/migrations/20260701010000_drop_chat_threads_messages/migration.sql +17 -0
  55. package/prisma/migrations/20260701020000_add_cron_run_model_breakdown/migration.sql +23 -0
  56. package/prisma/migrations/20260701020000_chat_token_by_model/migration.sql +25 -0
  57. package/prisma/migrations/20260701030000_add_secret_flag_to_agent_env/migration.sql +2 -0
  58. package/prisma/migrations/20260701030000_drop_cron_run_legacy_columns/migration.sql +5 -0
  59. package/prisma/migrations/20260706000000_consolidate_cron_run_token_accounting/migration.sql +54 -0
  60. package/prisma/migrations/20260709000000_add_phase_to_agent_cron_run/migration.sql +8 -0
  61. package/prisma/migrations/20260717000000_add_item_tracking_to_agent_cron_run/migration.sql +10 -0
  62. package/prisma/migrations/20260717010000_add_agent_work_queue_snapshot/migration.sql +20 -0
  63. package/prisma/migrations/20260718000000_add_cron_phase_columns/migration.sql +25 -0
  64. package/prisma/migrations/20260718100000_drop_agent_cron_run_phase_column/migration.sql +8 -0
  65. package/prisma/migrations/20260724000000_add_agent_type_name/migration.sql +3 -0
  66. package/prisma/migrations/20260725232433_add_agent_author_allowlist/migration.sql +2 -0
  67. package/prisma/migrations/20260727120000_add_not_null_to_agent_author_allowlist/migration.sql +3 -0
  68. package/prisma/migrations/20260731000000_add_session_id_to_agent_cron_run/migration.sql +2 -0
  69. package/prisma/migrations/20260821000000_add_agent_restrict_slack_to_members/migration.sql +3 -0
  70. package/prisma/migrations/20260901000000_add_push_subscription_and_chat_thread_watch/migration.sql +40 -0
  71. package/prisma/migrations/20260903000000_add_agent_patch_author_allowlist/migration.sql +2 -0
  72. package/prisma/migrations/20260903120000_add_agent_review_author_allowlist/migration.sql +18 -0
  73. package/prisma/migrations/20260903150000_drop_agent_author_allowlist/migration.sql +14 -0
  74. package/prisma/migrations/20260905000000_add_started_at_index_to_agent_cron_run/migration.sql +11 -0
  75. package/prisma/migrations/20260906000000_add_session_follow_notification_prefs_alert_state/migration.sql +47 -0
  76. package/prisma/migrations/20260911000000_backfill_auto_follow_since/migration.sql +16 -0
  77. package/prisma/migrations/20260923115814_add_last_heartbeat_at_to_agent_cron_run/migration.sql +2 -0
  78. package/prisma/migrations/20260924120000_add_trial_expiry_fields_to_agent/migration.sql +6 -0
  79. package/prisma/migrations/20260929000000_add_agent_phase_methodology/migration.sql +21 -0
  80. package/prisma/migrations/20260929120000_add_agent_policy_fields/migration.sql +15 -0
  81. package/prisma/migrations/20261005000000_add_agent_github_installations_snapshot/migration.sql +21 -0
  82. package/prisma/migrations/20261008000000_add_cron_run_telemetry/migration.sql +50 -0
  83. package/prisma/migrations/20261008010000_add_account_models/migration.sql +48 -0
  84. package/prisma/migrations/20261008020000_add_cron_lockdown_disabled_at/migration.sql +3 -0
  85. package/prisma/migrations/20261009000000_chat_token_usage_bigint/migration.sql +7 -0
  86. package/prisma/migrations/20261010000000_add_cron_run_command_variant/migration.sql +2 -0
  87. package/prisma/migrations/20261019000000_add_agent_anthropic_identity/migration.sql +9 -0
  88. package/prisma/migrations/20261025000000_add_agent_ask/migration.sql +23 -0
  89. package/prisma/migrations/migration_lock.toml +3 -0
  90. package/prisma/schema/coding.prisma +85 -0
  91. package/prisma/schema/schema.prisma +506 -0
  92. package/prisma.config.ts +34 -0
  93. package/pwa-assets/icons/apple-touch-icon.png +0 -0
  94. package/pwa-assets/icons/favicon-32.png +0 -0
  95. package/pwa-assets/icons/icon-192.png +0 -0
  96. package/pwa-assets/icons/icon-512.png +0 -0
  97. package/pwa-assets/icons/icon-maskable-192.png +0 -0
  98. package/pwa-assets/icons/icon-maskable-512.png +0 -0
  99. package/src/account-agent-create.ts +42 -0
  100. package/src/account-agent-create.unit.test.ts +28 -0
  101. package/src/account-created-notifier.ts +71 -0
  102. package/src/account-created-notifier.unit.test.ts +70 -0
  103. package/src/account-email.ts +9 -0
  104. package/src/account-email.unit.test.ts +21 -0
  105. package/src/account-invites.ts +70 -0
  106. package/src/account-lifecycle.integration.test.ts +329 -0
  107. package/src/account-lifecycle.ts +206 -0
  108. package/src/account-lifecycle.unit.test.ts +108 -0
  109. package/src/account-members.ts +128 -0
  110. package/src/account-onboarding.integration.test.ts +101 -0
  111. package/src/account-onboarding.ts +95 -0
  112. package/src/account-trial-expiry-sweeper.ts +85 -0
  113. package/src/account-trial-warning-sweeper.integration.test.ts +228 -0
  114. package/src/account-trial-warning-sweeper.ts +216 -0
  115. package/src/accounts-api.integration.test.ts +196 -0
  116. package/src/accounts-api.smoke.test.ts +292 -0
  117. package/src/accounts-api.ts +289 -0
  118. package/src/accounts-api.unit.test.ts +93 -0
  119. package/src/accounts.integration.test.ts +178 -0
  120. package/src/accounts.ts +208 -0
  121. package/src/admin-boot-config.ts +574 -0
  122. package/src/admin-boot-config.unit.test.ts +28 -0
  123. package/src/admin-boot.boot-order.unit.test.ts +91 -0
  124. package/src/admin-boot.ts +690 -0
  125. package/src/admin-dev-login.smoke.test.ts +317 -0
  126. package/src/admin-extension.ts +432 -0
  127. package/src/admin-extension.unit.test.ts +532 -0
  128. package/src/admin-local-agent.smoke.test.ts +1643 -0
  129. package/src/admin-spec.smoke.test.ts +96 -0
  130. package/src/admin-spec.ts +186 -0
  131. package/src/admin-ui-account-nav.ts +20 -0
  132. package/src/admin-ui-account-pages.ts +131 -0
  133. package/src/admin-ui-account-pages.unit.test.ts +112 -0
  134. package/src/admin-ui-account.smoke.test.ts +286 -0
  135. package/src/admin-ui-account.ts +185 -0
  136. package/src/admin-ui-accounts-pages.ts +202 -0
  137. package/src/admin-ui-accounts-pages.unit.test.ts +138 -0
  138. package/src/admin-ui-accounts.smoke.test.ts +434 -0
  139. package/src/admin-ui-accounts.ts +266 -0
  140. package/src/admin-ui-layout.ts +60 -0
  141. package/src/admin-ui-layout.unit.test.ts +140 -0
  142. package/src/admin-ui-pages.ts +3489 -0
  143. package/src/admin-ui-pages.unit.test.ts +4355 -0
  144. package/src/admin-ui-push-test.smoke.test.ts +125 -0
  145. package/src/admin-ui-push-test.ts +102 -0
  146. package/src/admin-ui-styles.ts +656 -0
  147. package/src/admin-ui-styles.unit.test.ts +103 -0
  148. package/src/admin-ui.fixtures.ts +457 -0
  149. package/src/admin-ui.smoke.test.ts +7227 -0
  150. package/src/admin-ui.ts +3824 -0
  151. package/src/agent-account-assignment.ts +49 -0
  152. package/src/agent-account-assignment.unit.test.ts +99 -0
  153. package/src/agent-anthropic-identity.integration.test.ts +99 -0
  154. package/src/agent-anthropic-identity.ts +78 -0
  155. package/src/agent-anthropic-identity.unit.test.ts +77 -0
  156. package/src/agent-ask-config.ts +59 -0
  157. package/src/agent-ask-config.unit.test.ts +70 -0
  158. package/src/agent-ask.integration.test.ts +175 -0
  159. package/src/agent-ask.smoke.test.ts +457 -0
  160. package/src/agent-ask.ts +378 -0
  161. package/src/agent-chat-tokens.integration.test.ts +420 -0
  162. package/src/agent-chat-tokens.smoke.test.ts +551 -0
  163. package/src/agent-chat-tokens.ts +259 -0
  164. package/src/agent-cron-jobs.integration.test.ts +582 -0
  165. package/src/agent-cron-jobs.ts +615 -0
  166. package/src/agent-cron-jobs.unit.test.ts +420 -0
  167. package/src/agent-cron-run-stats.integration.test.ts +1551 -0
  168. package/src/agent-cron-run-stats.smoke.test.ts +953 -0
  169. package/src/agent-cron-run-stats.ts +752 -0
  170. package/src/agent-cron-runs.integration.test.ts +1491 -0
  171. package/src/agent-cron-runs.ts +489 -0
  172. package/src/agent-deletion-checklist.ts +128 -0
  173. package/src/agent-deletion-checklist.unit.test.ts +201 -0
  174. package/src/agent-deletion-per-agent.integration.test.ts +323 -0
  175. package/src/agent-deletion.integration.test.ts +323 -0
  176. package/src/agent-deletion.ts +329 -0
  177. package/src/agent-deletion.unit.test.ts +412 -0
  178. package/src/agent-envs.integration.test.ts +323 -0
  179. package/src/agent-envs.ts +244 -0
  180. package/src/agent-github-installations.integration.test.ts +115 -0
  181. package/src/agent-github-installations.ts +52 -0
  182. package/src/agent-manifest.ts +685 -0
  183. package/src/agent-manifest.unit.test.ts +870 -0
  184. package/src/agent-members.ts +69 -0
  185. package/src/agent-members.unit.test.ts +250 -0
  186. package/src/agent-patch-author-allowlist.integration.test.ts +218 -0
  187. package/src/agent-plugins.integration.test.ts +157 -0
  188. package/src/agent-plugins.ts +95 -0
  189. package/src/agent-plugins.unit.test.ts +43 -0
  190. package/src/agent-provisioner-per-agent.integration.test.ts +949 -0
  191. package/src/agent-provisioner.integration.test.ts +1245 -0
  192. package/src/agent-provisioner.ts +1650 -0
  193. package/src/agent-provisioner.unit.test.ts +1852 -0
  194. package/src/agent-tokens.integration.test.ts +150 -0
  195. package/src/agent-tokens.ts +112 -0
  196. package/src/agent-tools.integration.test.ts +129 -0
  197. package/src/agent-tools.ts +111 -0
  198. package/src/agents-api.integration.test.ts +705 -0
  199. package/src/agents-api.sentry.smoke.test.ts +478 -0
  200. package/src/agents-api.smoke.test.ts +5986 -0
  201. package/src/agents-api.ts +2826 -0
  202. package/src/agents.integration.test.ts +512 -0
  203. package/src/agents.ts +1097 -0
  204. package/src/agents.unit.test.ts +1736 -0
  205. package/src/anthropic-credential-guard.ts +44 -0
  206. package/src/anthropic-credential-guard.unit.test.ts +88 -0
  207. package/src/anthropic-federated-token-provider.integration.test.ts +248 -0
  208. package/src/anthropic-federated-token-provider.ts +249 -0
  209. package/src/anthropic-identity-client.fixtures.ts +237 -0
  210. package/src/anthropic-identity-client.integration.test.ts +342 -0
  211. package/src/anthropic-identity-client.ts +473 -0
  212. package/src/anthropic-identity-fixture-spec.integration.test.ts +169 -0
  213. package/src/anthropic-identity-name.integration.test.ts +83 -0
  214. package/src/anthropic-identity-name.ts +163 -0
  215. package/src/anthropic-identity-name.unit.test.ts +345 -0
  216. package/src/anthropic-openapi-contract.fixtures.ts +192 -0
  217. package/src/api-auth.ts +383 -0
  218. package/src/api-auth.unit.test.ts +837 -0
  219. package/src/api.smoke.test.ts +1225 -0
  220. package/src/api.ts +376 -0
  221. package/src/attachment-validation.ts +124 -0
  222. package/src/attachment-validation.unit.test.ts +218 -0
  223. package/src/caller-scope.ts +131 -0
  224. package/src/caller-scope.unit.test.ts +116 -0
  225. package/src/chat-credential-config.ts +22 -0
  226. package/src/chat-credentials-logging.unit.test.ts +92 -0
  227. package/src/chat-markers.ts +114 -0
  228. package/src/chat-markers.unit.test.ts +116 -0
  229. package/src/chat-service-provisioning-client.integration.test.ts +412 -0
  230. package/src/chat-service-provisioning-client.ts +221 -0
  231. package/src/chat.smoke.test.ts +1875 -0
  232. package/src/clock.ts +47 -0
  233. package/src/coding-task-store-provisioning-client.integration.test.ts +372 -0
  234. package/src/coding-task-store-provisioning-client.ts +156 -0
  235. package/src/crypto.ts +83 -0
  236. package/src/dev-auth-guard.ts +29 -0
  237. package/src/dev-auth-guard.unit.test.ts +51 -0
  238. package/src/errors.ts +77 -0
  239. package/src/errors.unit.test.ts +52 -0
  240. package/src/fixtures/anthropic-identity-recorded-fixtures.json +850 -0
  241. package/src/fixtures/anthropic-openapi/SDK_VERSION +1 -0
  242. package/src/fixtures/anthropic-openapi/mock-spec.json.gz +0 -0
  243. package/src/fixtures/chat-service-provisioning-cassette.json +156 -0
  244. package/src/fixtures/github-app-manifest-cassette.json +44 -0
  245. package/src/fixtures/google-auth-cassette.json +36 -0
  246. package/src/fixtures/http-chat-client-cassette.json +226 -0
  247. package/src/fixtures/k8s-cassette.json +470 -0
  248. package/src/fixtures/okta-auth-cassette.json +36 -0
  249. package/src/fixtures/slack-provision-cassette.json +12 -0
  250. package/src/fixtures/slack-provisioning-http-cassette.json +98 -0
  251. package/src/fixtures/task-store-provisioning-cassette.json +85 -0
  252. package/src/github-app-provisioning-client.integration.test.ts +149 -0
  253. package/src/github-app-provisioning-client.ts +161 -0
  254. package/src/github-app-provisioning-client.unit.test.ts +114 -0
  255. package/src/github-provisioning-service.ts +569 -0
  256. package/src/github-provisioning-service.unit.test.ts +123 -0
  257. package/src/google-auth-client.integration.test.ts +195 -0
  258. package/src/google-auth-client.ts +121 -0
  259. package/src/http-chat-client.integration.test.ts +554 -0
  260. package/src/http-chat-client.ts +533 -0
  261. package/src/http-chat-client.unit.test.ts +119 -0
  262. package/src/import-boundary.unit.test.ts +240 -0
  263. package/src/kubernetes-client.integration.test.ts +697 -0
  264. package/src/kubernetes-client.ts +1027 -0
  265. package/src/kubernetes-client.unit.test.ts +726 -0
  266. package/src/main.smoke.test.ts +91 -0
  267. package/src/main.ts +21 -0
  268. package/src/main.unit.test.ts +801 -0
  269. package/src/okta-auth-client.integration.test.ts +263 -0
  270. package/src/okta-auth-client.ts +152 -0
  271. package/src/openapi-schemas.ts +1310 -0
  272. package/src/openapi-schemas.unit.test.ts +348 -0
  273. package/src/per-agent-identity.fixtures.ts +305 -0
  274. package/src/platform-doc-route.ts +40 -0
  275. package/src/prisma-client.integration.test.ts +57 -0
  276. package/src/prisma-client.ts +187 -0
  277. package/src/prisma-client.unit.test.ts +178 -0
  278. package/src/prisma-tx.ts +23 -0
  279. package/src/push-content.ts +177 -0
  280. package/src/push-content.unit.test.ts +213 -0
  281. package/src/push-crypto.ts +135 -0
  282. package/src/push-crypto.unit.test.ts +66 -0
  283. package/src/push-sender.ts +169 -0
  284. package/src/push-sender.unit.test.ts +107 -0
  285. package/src/push-service.ts +332 -0
  286. package/src/push-service.unit.test.ts +679 -0
  287. package/src/push-toggle.ts +135 -0
  288. package/src/push-toggle.unit.test.ts +78 -0
  289. package/src/pwa-https-gating.smoke.test.ts +229 -0
  290. package/src/pwa-icons.unit.test.ts +41 -0
  291. package/src/pwa-routes.smoke.test.ts +276 -0
  292. package/src/pwa.ts +380 -0
  293. package/src/pwa.unit.test.ts +321 -0
  294. package/src/schema.unit.test.ts +122 -0
  295. package/src/self-serve-config.ts +52 -0
  296. package/src/self-serve-config.unit.test.ts +79 -0
  297. package/src/server.smoke.test.ts +273 -0
  298. package/src/server.ts +50 -0
  299. package/src/service-integration.ts +67 -0
  300. package/src/service-integration.unit.test.ts +129 -0
  301. package/src/slack-provisioning-client.integration.test.ts +308 -0
  302. package/src/slack-provisioning-client.ts +411 -0
  303. package/src/slack-provisioning-client.unit.test.ts +80 -0
  304. package/src/slack-provisioning-service.integration.test.ts +637 -0
  305. package/src/slack-provisioning-service.ts +451 -0
  306. package/src/slack-provisioning.integration.test.ts +395 -0
  307. package/src/specialty-manifest-loader.fixture.integration.test.ts +63 -0
  308. package/src/specialty-manifest-loader.ts +255 -0
  309. package/src/specialty-manifest-loader.unit.test.ts +301 -0
  310. package/src/specialty-registry.schema.unit.test.ts +35 -0
  311. package/src/specialty-registry.ts +236 -0
  312. package/src/specialty-registry.unit.test.ts +272 -0
  313. package/src/startup-policy-reconcile.ts +77 -0
  314. package/src/startup-policy-reconcile.unit.test.ts +251 -0
  315. package/src/theme-tokens.json +12 -0
  316. package/src/token-crypto.ts +60 -0
  317. package/src/token-crypto.unit.test.ts +182 -0
  318. package/src/trial-expiry-sweeper.integration.test.ts +318 -0
  319. package/src/trial-expiry-sweeper.ts +132 -0
  320. package/src/trial-expiry-sweeper.unit.test.ts +391 -0
  321. package/src/trial-expiry-warning-sweeper.integration.test.ts +468 -0
  322. package/src/trial-expiry-warning-sweeper.ts +447 -0
  323. package/src/trial-expiry-warning-sweeper.unit.test.ts +148 -0
  324. package/src/voice-contract.unit.test.ts +102 -0
  325. package/tsconfig.json +9 -0
@@ -0,0 +1,953 @@
1
+ /**
2
+ * admin/src/agent-cron-run-stats.smoke.test.ts
3
+ * Smoke tests for GET /agents/all/cron-runs/stats.
4
+ *
5
+ * Uses app.request() — no real server, no real DB.
6
+ * AgentCronRunStatsService is injected as an in-memory mock.
7
+ */
8
+
9
+ import { beforeAll, describe, expect, it } from "bun:test";
10
+ import { sign } from "hono/jwt";
11
+ import type {
12
+ AgentCronRunStatsService,
13
+ CronRunOutcomes,
14
+ } from "./agent-cron-run-stats.ts";
15
+ import type { AdminDeps } from "./agents-api.ts";
16
+ import { createAdminApp, parseAdminApiKeys } from "./agents-api.ts";
17
+
18
+ const SESSION_SECRET = "test-admin-session-secret-32-bytes!";
19
+ const AGENT_ID = "agent-test-123";
20
+ const ADMIN_API_KEY = "admin-stats-key-for-tests";
21
+ const VALID_BEARER_TOKEN = "valid-bearer-token-value";
22
+
23
+ async function makeSessionCookie(secret = SESSION_SECRET): Promise<string> {
24
+ return sign(
25
+ {
26
+ isAdmin: true,
27
+ userId: "user-123",
28
+ email: "admin@example.com",
29
+ name: "Admin User",
30
+ iat: Math.floor(Date.now() / 1000),
31
+ exp: Math.floor(Date.now() / 1000) + 3600,
32
+ },
33
+ secret,
34
+ "HS256",
35
+ );
36
+ }
37
+
38
+ // Minimal mock stats response matching CronRunTokenStats shape
39
+ const MOCK_STATS = {
40
+ totals: {
41
+ input: 600,
42
+ output: 300,
43
+ cacheRead: 60,
44
+ cacheCreation: 30,
45
+ total: 990,
46
+ costUsd: 0.006,
47
+ },
48
+ byAgent: [
49
+ {
50
+ key: "agent-1",
51
+ input: 400,
52
+ output: 200,
53
+ cacheRead: 40,
54
+ cacheCreation: 20,
55
+ total: 660,
56
+ costUsd: 0.004,
57
+ },
58
+ {
59
+ key: "agent-2",
60
+ input: 200,
61
+ output: 100,
62
+ cacheRead: 20,
63
+ cacheCreation: 10,
64
+ total: 330,
65
+ costUsd: 0.002,
66
+ },
67
+ ],
68
+ byCron: [
69
+ {
70
+ key1: "agent-1",
71
+ key2: "cron-alpha",
72
+ input: 400,
73
+ output: 200,
74
+ cacheRead: 40,
75
+ cacheCreation: 20,
76
+ total: 660,
77
+ costUsd: 0.004,
78
+ },
79
+ {
80
+ key1: "agent-2",
81
+ key2: "cron-beta",
82
+ input: 200,
83
+ output: 100,
84
+ cacheRead: 20,
85
+ cacheCreation: 10,
86
+ total: 330,
87
+ costUsd: 0.002,
88
+ },
89
+ ],
90
+ byModel: [
91
+ {
92
+ key1: "agent-1",
93
+ key2: "claude-sonnet-4-5",
94
+ input: 400,
95
+ output: 200,
96
+ cacheRead: 40,
97
+ cacheCreation: 20,
98
+ total: 660,
99
+ costUsd: 0.004,
100
+ },
101
+ {
102
+ key1: "agent-2",
103
+ key2: "claude-opus-4-5",
104
+ input: 200,
105
+ output: 100,
106
+ cacheRead: 20,
107
+ cacheCreation: 10,
108
+ total: 330,
109
+ costUsd: 0.002,
110
+ },
111
+ ],
112
+ daily: [
113
+ {
114
+ period: "2026-01-10",
115
+ input: 100,
116
+ output: 50,
117
+ cacheRead: 10,
118
+ cacheCreation: 5,
119
+ total: 165,
120
+ costUsd: 0.001,
121
+ },
122
+ {
123
+ period: "2026-01-11",
124
+ input: 200,
125
+ output: 100,
126
+ cacheRead: 20,
127
+ cacheCreation: 10,
128
+ total: 330,
129
+ costUsd: 0.002,
130
+ },
131
+ {
132
+ period: "2026-01-12",
133
+ input: 300,
134
+ output: 150,
135
+ cacheRead: 30,
136
+ cacheCreation: 15,
137
+ total: 495,
138
+ costUsd: 0.003,
139
+ },
140
+ ],
141
+ byCronModel: [],
142
+ byPhase: [
143
+ {
144
+ key: "dev-task",
145
+ input: 400,
146
+ output: 200,
147
+ cacheRead: 40,
148
+ cacheCreation: 20,
149
+ total: 660,
150
+ costUsd: 0.004,
151
+ },
152
+ {
153
+ key: "review",
154
+ input: 200,
155
+ output: 100,
156
+ cacheRead: 20,
157
+ cacheCreation: 10,
158
+ total: 330,
159
+ costUsd: 0.002,
160
+ },
161
+ ],
162
+ bySkill: [
163
+ {
164
+ kind: "skill",
165
+ name: "shipwright:dev-task",
166
+ runs: 2,
167
+ invocations: 3,
168
+ turns: 10,
169
+ input: 100,
170
+ output: 50,
171
+ cacheRead: 10,
172
+ cacheCreation: 5,
173
+ avgInvokeContextDelta: 1200,
174
+ },
175
+ ],
176
+ baselines: [
177
+ {
178
+ contextFingerprint: "fp-1",
179
+ baselineModel: "claude-sonnet-5-5",
180
+ phase: "dev-task",
181
+ runs: 3,
182
+ avgContextTokens: 24000,
183
+ minContextTokens: 23000,
184
+ maxContextTokens: 25000,
185
+ avgTurns: 30,
186
+ avgToolCalls: null,
187
+ firstSeen: "2026-01-10T09:00:00.000Z",
188
+ lastSeen: "2026-01-12T09:00:00.000Z",
189
+ },
190
+ ],
191
+ };
192
+
193
+ const MOCK_OUTCOMES: CronRunOutcomes = {
194
+ series: [
195
+ {
196
+ phase: "dev-task",
197
+ contextFingerprint: "abc123def456",
198
+ runs: 5,
199
+ completed: 3,
200
+ failed: 1,
201
+ skipped: 1,
202
+ skipReasons: { "no-ready-task": 1 },
203
+ avgDurationMs: 120000,
204
+ p50DurationMs: 90000,
205
+ avgTurns: 40,
206
+ avgToolCalls: 55,
207
+ avgContextTokens: 21000,
208
+ },
209
+ {
210
+ phase: null,
211
+ contextFingerprint: null,
212
+ runs: 1,
213
+ completed: 0,
214
+ failed: 0,
215
+ skipped: 1,
216
+ skipReasons: { unknown: 1 },
217
+ avgDurationMs: null,
218
+ p50DurationMs: null,
219
+ avgTurns: null,
220
+ avgToolCalls: null,
221
+ avgContextTokens: null,
222
+ },
223
+ ],
224
+ };
225
+
226
+ function makeMockStatsService(): Pick<
227
+ AgentCronRunStatsService,
228
+ "query" | "outcomes"
229
+ > {
230
+ return {
231
+ query: async (_from?: string, _to?: string, _agentId?: string) =>
232
+ MOCK_STATS,
233
+ outcomes: async () => MOCK_OUTCOMES,
234
+ };
235
+ }
236
+
237
+ function makeMockDeps(): AdminDeps {
238
+ return {
239
+ agentService: {
240
+ create: async () => {
241
+ throw new Error("not implemented");
242
+ },
243
+ delete: async () => {},
244
+ list: async () => [],
245
+ getSummary: async () => null,
246
+ getDetail: async () => null,
247
+ exists: async () => false,
248
+ updateSelfHosted: async () => {
249
+ throw new Error("not implemented");
250
+ },
251
+ updateFields: async () => {
252
+ throw new Error("not implemented");
253
+ },
254
+ runTransaction: async (fn) => fn(undefined as never),
255
+ },
256
+ agentEnvService: {
257
+ upsert: async () => {},
258
+ patch: async () => {},
259
+ getByAgentId: async () => ({ env: {}, secretKeys: [] }),
260
+ deleteKey: async () => {},
261
+ },
262
+ agentCronJobService: {
263
+ list: async () => [],
264
+ listWithRunSummary: async () => [],
265
+ create: async () => ({
266
+ id: "cron-id",
267
+ agentId: AGENT_ID,
268
+ schedule: "0 9 * * *",
269
+ prompt: "test",
270
+ channel: null,
271
+ user: null,
272
+ silent: false,
273
+ enabled: true,
274
+ preCheck: null,
275
+ name: null,
276
+ system: false,
277
+ parentCronId: null,
278
+ lockdownDisabledAt: null,
279
+ createdAt: new Date("2024-01-01"),
280
+ updatedAt: new Date("2024-01-01"),
281
+ }),
282
+ update: async () => ({
283
+ id: "cron-id",
284
+ agentId: AGENT_ID,
285
+ schedule: "0 9 * * *",
286
+ prompt: "test",
287
+ channel: null,
288
+ user: null,
289
+ silent: false,
290
+ enabled: true,
291
+ preCheck: null,
292
+ name: null,
293
+ system: false,
294
+ parentCronId: null,
295
+ lockdownDisabledAt: null,
296
+ createdAt: new Date("2024-01-01"),
297
+ updatedAt: new Date("2024-01-01"),
298
+ }),
299
+ delete: async () => {},
300
+ get: async () => ({
301
+ id: "cron-id",
302
+ agentId: AGENT_ID,
303
+ schedule: "0 9 * * *",
304
+ prompt: "test",
305
+ channel: null,
306
+ user: null,
307
+ silent: false,
308
+ enabled: true,
309
+ preCheck: null,
310
+ name: null,
311
+ system: false,
312
+ parentCronId: null,
313
+ lockdownDisabledAt: null,
314
+ createdAt: new Date("2024-01-01"),
315
+ updatedAt: new Date("2024-01-01"),
316
+ }),
317
+ setEnabled: async (_agentId, _cronId, enabled) => ({
318
+ id: "cron-id",
319
+ agentId: AGENT_ID,
320
+ schedule: "0 9 * * *",
321
+ prompt: "test",
322
+ channel: null,
323
+ user: null,
324
+ silent: false,
325
+ enabled,
326
+ preCheck: null,
327
+ name: null,
328
+ system: false,
329
+ parentCronId: null,
330
+ lockdownDisabledAt: null,
331
+ createdAt: new Date("2024-01-01"),
332
+ updatedAt: new Date("2024-01-01"),
333
+ }),
334
+ updatePreCheck: async (_agentId, _cronId, preCheck) => ({
335
+ id: "cron-id",
336
+ agentId: AGENT_ID,
337
+ schedule: "0 9 * * *",
338
+ prompt: "test",
339
+ channel: null,
340
+ user: null,
341
+ silent: false,
342
+ enabled: true,
343
+ preCheck,
344
+ name: null,
345
+ system: false,
346
+ parentCronId: null,
347
+ lockdownDisabledAt: null,
348
+ createdAt: new Date("2024-01-01"),
349
+ updatedAt: new Date("2024-01-01"),
350
+ }),
351
+ reconcileSystemCrons: async () => ({
352
+ created: 0,
353
+ updated: 0,
354
+ deleted: 0,
355
+ }),
356
+ },
357
+ agentToolService: {
358
+ list: async () => [],
359
+ add: async () => ({
360
+ id: "tool-id",
361
+ agentId: AGENT_ID,
362
+ pattern: "Read",
363
+ enabled: true,
364
+ createdAt: new Date(),
365
+ }),
366
+ toggle: async () => ({
367
+ id: "tool-id",
368
+ agentId: AGENT_ID,
369
+ pattern: "Read",
370
+ enabled: false,
371
+ createdAt: new Date(),
372
+ }),
373
+ remove: async () => {},
374
+ },
375
+ agentTokenService: {
376
+ create: async () => ({
377
+ token: {
378
+ id: "token-id",
379
+ agentId: AGENT_ID,
380
+ token: "sha256hash",
381
+ label: null,
382
+ createdAt: new Date(),
383
+ revokedAt: null,
384
+ },
385
+ rawToken:
386
+ "raw-hex-token-64chars-placeholder-pad-pad-pad-pad-pad-pad-pad",
387
+ }),
388
+ listForAgent: async () => [],
389
+ revoke: async () => ({
390
+ id: "token-id",
391
+ agentId: AGENT_ID,
392
+ token: "sha256hash",
393
+ label: null,
394
+ createdAt: new Date(),
395
+ revokedAt: new Date(),
396
+ }),
397
+ validate: async () => null,
398
+ },
399
+ agentPluginService: {
400
+ list: async () => [],
401
+ add: async () => ({
402
+ id: "plugin-id",
403
+ agentId: AGENT_ID,
404
+ name: "test",
405
+ version: "1.0.0",
406
+ enabled: true,
407
+ createdAt: new Date(),
408
+ updatedAt: new Date(),
409
+ }),
410
+ remove: async () => {},
411
+ removeByName: async () => {},
412
+ },
413
+ agentMemberService: {
414
+ exists: async () => false,
415
+ listByEmail: async () => [],
416
+ add: async (agentId: string, email: string) => ({
417
+ id: "member-1",
418
+ agentId,
419
+ email,
420
+ createdAt: new Date(),
421
+ }),
422
+ listByAgentId: async () => [],
423
+ },
424
+ specialtyRegistry: {
425
+ getManifest: () => {
426
+ throw new Error("not implemented");
427
+ },
428
+ tryGetManifest: () => undefined,
429
+ listTypes: () => [],
430
+ },
431
+ agentChatTokenService: {
432
+ upsertDailyByModel: async (
433
+ agentId: string,
434
+ date: string,
435
+ model: string,
436
+ ) => ({
437
+ id: "daily-id",
438
+ agentId,
439
+ date,
440
+ model,
441
+ inputTokens: 0,
442
+ outputTokens: 0,
443
+ cacheReadTokens: 0,
444
+ cacheCreationTokens: 0,
445
+ costUsd: 0,
446
+ createdAt: new Date(),
447
+ updatedAt: new Date(),
448
+ }),
449
+ queryStats: async () => ({
450
+ totals: {
451
+ input: 0,
452
+ output: 0,
453
+ cacheRead: 0,
454
+ cacheCreation: 0,
455
+ total: 0,
456
+ },
457
+ byAgent: [],
458
+ byModel: [],
459
+ daily: [],
460
+ }),
461
+ },
462
+ agentGitHubInstallationsService: {
463
+ push: async () => {
464
+ throw new Error("not implemented");
465
+ },
466
+ get: async () => null,
467
+ },
468
+ agentCronRunService: {
469
+ create: async () => ({
470
+ id: "run-id",
471
+ cronId: "cron-id",
472
+ agentId: AGENT_ID,
473
+ startedAt: new Date(),
474
+ completedAt: null,
475
+ skipped: false,
476
+ skipReason: null,
477
+ outcome: null,
478
+ error: null,
479
+ phase: null,
480
+ itemType: null,
481
+ itemId: null,
482
+ commandVariant: null,
483
+ sessionId: null,
484
+ lastHeartbeatAt: null,
485
+ baselineModel: null,
486
+ baselineContextTokens: null,
487
+ baselineInputTokens: null,
488
+ baselineCacheCreationTokens: null,
489
+ baselineCacheReadTokens: null,
490
+ turns: null,
491
+ toolCalls: null,
492
+ contextFingerprint: null,
493
+ pluginVersion: null,
494
+ claudeCodeVersion: null,
495
+ phaseId: null,
496
+ inputTokens: null,
497
+ outputTokens: null,
498
+ cacheReadTokens: null,
499
+ cacheCreationTokens: null,
500
+ costUsd: null,
501
+ model: null,
502
+ createdAt: new Date(),
503
+ }),
504
+ list: async () => ({ items: [], total: 0, limit: 20, offset: 0 }),
505
+ patch: async () => ({
506
+ id: "run-id",
507
+ cronId: "cron-id",
508
+ agentId: AGENT_ID,
509
+ startedAt: new Date(),
510
+ completedAt: null,
511
+ skipped: false,
512
+ skipReason: null,
513
+ outcome: null,
514
+ error: null,
515
+ phase: null,
516
+ itemType: null,
517
+ itemId: null,
518
+ commandVariant: null,
519
+ sessionId: null,
520
+ lastHeartbeatAt: null,
521
+ baselineModel: null,
522
+ baselineContextTokens: null,
523
+ baselineInputTokens: null,
524
+ baselineCacheCreationTokens: null,
525
+ baselineCacheReadTokens: null,
526
+ turns: null,
527
+ toolCalls: null,
528
+ contextFingerprint: null,
529
+ pluginVersion: null,
530
+ claudeCodeVersion: null,
531
+ phaseId: null,
532
+ inputTokens: null,
533
+ outputTokens: null,
534
+ cacheReadTokens: null,
535
+ cacheCreationTokens: null,
536
+ costUsd: null,
537
+ model: null,
538
+ createdAt: new Date(),
539
+ modelBreakdown: [],
540
+ }),
541
+ },
542
+ agentCronRunStatsService: makeMockStatsService(),
543
+ prisma: {
544
+ agent: {
545
+ create: async (args: {
546
+ data: { name: string; slackId: string | null; selfHosted?: boolean };
547
+ }) => ({
548
+ id: "agent-new-id",
549
+ name: args.data.name,
550
+ slackId: args.data.slackId,
551
+ selfHosted: args.data.selfHosted ?? false,
552
+ createdAt: new Date("2024-01-01"),
553
+ updatedAt: new Date("2024-01-01"),
554
+ }),
555
+ findUnique: async (args: { where: { id: string } }) =>
556
+ args.where.id === AGENT_ID
557
+ ? {
558
+ id: AGENT_ID,
559
+ name: "Test Agent",
560
+ slackId: null,
561
+ selfHosted: false,
562
+ createdAt: new Date(),
563
+ updatedAt: new Date(),
564
+ }
565
+ : null,
566
+ findMany: async () => [],
567
+ delete: async (args: { where: { id: string } }) => ({
568
+ id: args.where.id,
569
+ name: "Test Agent",
570
+ slackId: null,
571
+ selfHosted: false,
572
+ createdAt: new Date(),
573
+ updatedAt: new Date(),
574
+ }),
575
+ update: async (args: { where: { id: string }; data: unknown }) => ({
576
+ id: args.where.id,
577
+ name: "Test Agent",
578
+ slackId: null,
579
+ selfHosted: false,
580
+ repos: [],
581
+ createdAt: new Date(),
582
+ updatedAt: new Date(),
583
+ }),
584
+ },
585
+ } as unknown as AdminDeps["prisma"],
586
+ provisioner: {
587
+ canProvision: false,
588
+ provision: async (agentId) => ({
589
+ resourceName: agentId,
590
+ secretName: `${agentId}-token`,
591
+ deploymentName: agentId,
592
+ }),
593
+ deprovision: async () => {},
594
+ reconcile: async () => ({
595
+ recreated: [],
596
+ migrated: [],
597
+ noOwner: [],
598
+ dryRun: false,
599
+ updated: [],
600
+ orphans: [],
601
+ failed: [],
602
+ }),
603
+ },
604
+ serviceIntegrations: [
605
+ {
606
+ name: "task-store",
607
+ listTokensForAgent: async () => [],
608
+ revokeToken: async () => {},
609
+ },
610
+ ],
611
+ chatService: {
612
+ listTokensForAgent: async () => [],
613
+ revokeToken: async () => {},
614
+ deleteThreadsForAgent: async () => ({ deleted: 0 }),
615
+ },
616
+ slack: {
617
+ deleteApp: async () => {},
618
+ },
619
+ decrypt: (value: string) => value,
620
+ sessionSecret: SESSION_SECRET,
621
+ };
622
+ }
623
+
624
+ // ─── Stats route smoke tests ─────────────────────────────────────────────────
625
+
626
+ describe("admin API — GET /agents/all/cron-runs/stats", () => {
627
+ let cookie: string;
628
+
629
+ beforeAll(async () => {
630
+ cookie = await makeSessionCookie();
631
+ });
632
+
633
+ it("returns 200 with correct CronRunTokenStats shape (session auth)", async () => {
634
+ const app = createAdminApp(makeMockDeps());
635
+ const res = await app.request("/agents/all/cron-runs/stats", {
636
+ headers: { Cookie: `admin_session=${cookie}` },
637
+ });
638
+ expect(res.status).toBe(200);
639
+ const body = await res.json();
640
+
641
+ // Check all dimensions are present, including byPhase
642
+ expect(body.totals).toBeDefined();
643
+ expect(body.byAgent).toBeDefined();
644
+ expect(body.byCron).toBeDefined();
645
+ expect(body.byModel).toBeDefined();
646
+ expect(body.daily).toBeDefined();
647
+ expect(body.byPhase).toBeDefined();
648
+
649
+ // Verify totals shape
650
+ expect(typeof body.totals.input).toBe("number");
651
+ expect(typeof body.totals.output).toBe("number");
652
+ expect(typeof body.totals.cacheRead).toBe("number");
653
+ expect(typeof body.totals.cacheCreation).toBe("number");
654
+ expect(typeof body.totals.total).toBe("number");
655
+
656
+ // Verify arrays
657
+ expect(Array.isArray(body.byAgent)).toBe(true);
658
+ expect(Array.isArray(body.byCron)).toBe(true);
659
+ expect(Array.isArray(body.byModel)).toBe(true);
660
+ expect(Array.isArray(body.daily)).toBe(true);
661
+
662
+ // Verify keyed shapes
663
+ if (body.byAgent.length > 0) {
664
+ expect(body.byAgent[0].key).toBeDefined();
665
+ expect(typeof body.byAgent[0].input).toBe("number");
666
+ }
667
+ if (body.byCron.length > 0) {
668
+ expect(body.byCron[0].key1).toBeDefined();
669
+ expect(body.byCron[0].key2).toBeDefined();
670
+ }
671
+ if (body.byModel.length > 0) {
672
+ expect(body.byModel[0].key1).toBeDefined();
673
+ expect(body.byModel[0].key2).toBeDefined();
674
+ }
675
+ if (body.daily.length > 0) {
676
+ expect(body.daily[0].period).toBeDefined();
677
+ expect(typeof body.daily[0].input).toBe("number");
678
+ }
679
+ expect(Array.isArray(body.byPhase)).toBe(true);
680
+ if (body.byPhase.length > 0) {
681
+ expect(body.byPhase[0].key).toBeDefined();
682
+ expect(typeof body.byPhase[0].input).toBe("number");
683
+ }
684
+ });
685
+
686
+ it("returns correct mock data values", async () => {
687
+ const app = createAdminApp(makeMockDeps());
688
+ const res = await app.request("/agents/all/cron-runs/stats", {
689
+ headers: { Cookie: `admin_session=${cookie}` },
690
+ });
691
+ expect(res.status).toBe(200);
692
+ const body = await res.json();
693
+
694
+ expect(body.totals.input).toBe(600);
695
+ expect(body.totals.total).toBe(990);
696
+ expect(body.byAgent).toHaveLength(2);
697
+ expect(body.byCron).toHaveLength(2);
698
+ expect(body.byModel).toHaveLength(2);
699
+ expect(body.daily).toHaveLength(3);
700
+ expect(body.byPhase).toHaveLength(2);
701
+ expect(body.byPhase[0].key).toBe("dev-task");
702
+ });
703
+
704
+ it("returns bySkill and baselines with the documented shape", async () => {
705
+ const app = createAdminApp(makeMockDeps());
706
+ const res = await app.request("/agents/all/cron-runs/stats", {
707
+ headers: { Cookie: `admin_session=${cookie}` },
708
+ });
709
+ expect(res.status).toBe(200);
710
+ const body = await res.json();
711
+
712
+ expect(body.bySkill).toHaveLength(1);
713
+ expect(body.bySkill[0].kind).toBe("skill");
714
+ expect(body.bySkill[0].name).toBe("shipwright:dev-task");
715
+ expect(body.bySkill[0].invocations).toBe(3);
716
+ expect(body.bySkill[0].avgInvokeContextDelta).toBe(1200);
717
+
718
+ expect(body.baselines).toHaveLength(1);
719
+ expect(body.baselines[0].contextFingerprint).toBe("fp-1");
720
+ expect(body.baselines[0].baselineModel).toBe("claude-sonnet-5-5");
721
+ expect(body.baselines[0].phase).toBe("dev-task");
722
+ expect(body.baselines[0].avgContextTokens).toBe(24000);
723
+ expect(body.baselines[0].avgToolCalls).toBeNull();
724
+ expect(typeof body.baselines[0].firstSeen).toBe("string");
725
+ });
726
+
727
+ it("accepts from/to query params without error", async () => {
728
+ const app = createAdminApp(makeMockDeps());
729
+ const res = await app.request(
730
+ "/agents/all/cron-runs/stats?from=2026-01-01T00:00:00Z&to=2026-01-31T00:00:00Z",
731
+ { headers: { Cookie: `admin_session=${cookie}` } },
732
+ );
733
+ expect(res.status).toBe(200);
734
+ });
735
+
736
+ it("returns 200 with admin bearer token", async () => {
737
+ const deps: AdminDeps = {
738
+ ...makeMockDeps(),
739
+ adminApiKeys: parseAdminApiKeys(`admin:${ADMIN_API_KEY}:*`),
740
+ };
741
+ const app = createAdminApp(deps);
742
+ const res = await app.request("/agents/all/cron-runs/stats", {
743
+ headers: { Authorization: `Bearer ${ADMIN_API_KEY}` },
744
+ });
745
+ expect(res.status).toBe(200);
746
+ });
747
+
748
+ it("unauthenticated request returns 401", async () => {
749
+ const app = createAdminApp(makeMockDeps());
750
+ const res = await app.request("/agents/all/cron-runs/stats");
751
+ expect(res.status).toBe(401);
752
+ });
753
+
754
+ it("agent-scoped bearer token returns 403", async () => {
755
+ const deps: AdminDeps = {
756
+ ...makeMockDeps(),
757
+ agentTokenService: {
758
+ ...makeMockDeps().agentTokenService,
759
+ // Returns a per-agent token (not admin)
760
+ validate: async () => ({ agentId: AGENT_ID }),
761
+ },
762
+ };
763
+ const app = createAdminApp(deps);
764
+ const res = await app.request("/agents/all/cron-runs/stats", {
765
+ headers: { Authorization: `Bearer ${VALID_BEARER_TOKEN}` },
766
+ });
767
+ expect(res.status).toBe(403);
768
+ });
769
+ });
770
+
771
+ describe("admin API — GET /agents/:id/cron-runs/stats", () => {
772
+ function depsWithAgentToken(calls: Array<string | undefined>): AdminDeps {
773
+ const base = makeMockDeps();
774
+ return {
775
+ ...base,
776
+ agentCronRunStatsService: {
777
+ ...base.agentCronRunStatsService,
778
+ query: async (_from?: string, _to?: string, agentId?: string) => {
779
+ calls.push(agentId);
780
+ return MOCK_STATS;
781
+ },
782
+ },
783
+ agentTokenService: {
784
+ ...base.agentTokenService,
785
+ validate: async () => ({ agentId: AGENT_ID }),
786
+ },
787
+ };
788
+ }
789
+
790
+ it("agent's own bearer token gets 200 and the query is scoped to that agent", async () => {
791
+ const calls: Array<string | undefined> = [];
792
+ const app = createAdminApp(depsWithAgentToken(calls));
793
+ const res = await app.request(`/agents/${AGENT_ID}/cron-runs/stats`, {
794
+ headers: { Authorization: `Bearer ${VALID_BEARER_TOKEN}` },
795
+ });
796
+ expect(res.status).toBe(200);
797
+ expect(calls).toEqual([AGENT_ID]);
798
+ });
799
+
800
+ it("another agent's bearer token returns 403 without querying", async () => {
801
+ const calls: Array<string | undefined> = [];
802
+ const app = createAdminApp(depsWithAgentToken(calls));
803
+ const res = await app.request("/agents/other-agent/cron-runs/stats", {
804
+ headers: { Authorization: `Bearer ${VALID_BEARER_TOKEN}` },
805
+ });
806
+ expect(res.status).toBe(403);
807
+ expect(calls).toEqual([]);
808
+ });
809
+
810
+ it("unauthenticated request returns 401", async () => {
811
+ const app = createAdminApp(makeMockDeps());
812
+ const res = await app.request(`/agents/${AGENT_ID}/cron-runs/stats`);
813
+ expect(res.status).toBe(401);
814
+ });
815
+
816
+ it("does not swallow the static /agents/all/cron-runs/stats admin route", async () => {
817
+ const calls: Array<string | undefined> = [];
818
+ const app = createAdminApp(depsWithAgentToken(calls));
819
+ const res = await app.request("/agents/all/cron-runs/stats", {
820
+ headers: { Authorization: `Bearer ${VALID_BEARER_TOKEN}` },
821
+ });
822
+ expect(res.status).toBe(403);
823
+ expect(calls).toEqual([]);
824
+ });
825
+ });
826
+
827
+ describe("admin API — GET /agents/:id/cron-runs/outcomes", () => {
828
+ function depsWithAgentToken(calls: Array<string | undefined>): AdminDeps {
829
+ const base = makeMockDeps();
830
+ return {
831
+ ...base,
832
+ agentCronRunStatsService: {
833
+ ...base.agentCronRunStatsService,
834
+ outcomes: async (_from?: string, _to?: string, agentId?: string) => {
835
+ calls.push(agentId);
836
+ return MOCK_OUTCOMES;
837
+ },
838
+ },
839
+ agentTokenService: {
840
+ ...base.agentTokenService,
841
+ validate: async () => ({ agentId: AGENT_ID }),
842
+ },
843
+ };
844
+ }
845
+
846
+ it("agent's own bearer token gets 200 and outcomes are scoped to that agent", async () => {
847
+ const calls: Array<string | undefined> = [];
848
+ const app = createAdminApp(depsWithAgentToken(calls));
849
+ const res = await app.request(`/agents/${AGENT_ID}/cron-runs/outcomes`, {
850
+ headers: { Authorization: `Bearer ${VALID_BEARER_TOKEN}` },
851
+ });
852
+ expect(res.status).toBe(200);
853
+ expect(calls).toEqual([AGENT_ID]);
854
+ });
855
+
856
+ it("another agent's bearer token returns 403 without querying", async () => {
857
+ const calls: Array<string | undefined> = [];
858
+ const app = createAdminApp(depsWithAgentToken(calls));
859
+ const res = await app.request("/agents/other-agent/cron-runs/outcomes", {
860
+ headers: { Authorization: `Bearer ${VALID_BEARER_TOKEN}` },
861
+ });
862
+ expect(res.status).toBe(403);
863
+ expect(calls).toEqual([]);
864
+ });
865
+
866
+ it("unauthenticated request returns 401", async () => {
867
+ const app = createAdminApp(makeMockDeps());
868
+ const res = await app.request(`/agents/${AGENT_ID}/cron-runs/outcomes`);
869
+ expect(res.status).toBe(401);
870
+ });
871
+
872
+ it("does not swallow the static /agents/all/cron-runs/outcomes admin route", async () => {
873
+ const calls: Array<string | undefined> = [];
874
+ const app = createAdminApp(depsWithAgentToken(calls));
875
+ const res = await app.request("/agents/all/cron-runs/outcomes", {
876
+ headers: { Authorization: `Bearer ${VALID_BEARER_TOKEN}` },
877
+ });
878
+ expect(res.status).toBe(403);
879
+ expect(calls).toEqual([]);
880
+ });
881
+ });
882
+
883
+ describe("admin API — GET /agents/all/cron-runs/outcomes", () => {
884
+ let cookie: string;
885
+
886
+ beforeAll(async () => {
887
+ cookie = await makeSessionCookie();
888
+ });
889
+
890
+ it("returns 200 with the per-(phase, contextFingerprint) series shape", async () => {
891
+ const app = createAdminApp(makeMockDeps());
892
+ const res = await app.request("/agents/all/cron-runs/outcomes", {
893
+ headers: { Cookie: `admin_session=${cookie}` },
894
+ });
895
+ expect(res.status).toBe(200);
896
+ const body = await res.json();
897
+ expect(body.series).toHaveLength(2);
898
+ expect(body.series[0]).toEqual(MOCK_OUTCOMES.series[0]);
899
+ expect(body.series[1].phase).toBeNull();
900
+ expect(body.series[1].avgDurationMs).toBeNull();
901
+ });
902
+
903
+ it("passes from/to through to the service", async () => {
904
+ const calls: Array<[string | undefined, string | undefined]> = [];
905
+ const deps = makeMockDeps();
906
+ deps.agentCronRunStatsService = {
907
+ ...makeMockStatsService(),
908
+ outcomes: async (from?: string, to?: string) => {
909
+ calls.push([from, to]);
910
+ return MOCK_OUTCOMES;
911
+ },
912
+ };
913
+ const app = createAdminApp(deps);
914
+ const res = await app.request(
915
+ "/agents/all/cron-runs/outcomes?from=2026-01-01T00:00:00Z&to=2026-01-31T00:00:00Z",
916
+ { headers: { Cookie: `admin_session=${cookie}` } },
917
+ );
918
+ expect(res.status).toBe(200);
919
+ expect(calls).toEqual([["2026-01-01T00:00:00Z", "2026-01-31T00:00:00Z"]]);
920
+ });
921
+
922
+ it("returns 200 with admin bearer token", async () => {
923
+ const app = createAdminApp({
924
+ ...makeMockDeps(),
925
+ adminApiKeys: parseAdminApiKeys(`admin:${ADMIN_API_KEY}:*`),
926
+ });
927
+ const res = await app.request("/agents/all/cron-runs/outcomes", {
928
+ headers: { Authorization: `Bearer ${ADMIN_API_KEY}` },
929
+ });
930
+ expect(res.status).toBe(200);
931
+ });
932
+
933
+ it("unauthenticated request returns 401", async () => {
934
+ const app = createAdminApp(makeMockDeps());
935
+ const res = await app.request("/agents/all/cron-runs/outcomes");
936
+ expect(res.status).toBe(401);
937
+ });
938
+
939
+ it("agent-scoped bearer token returns 403", async () => {
940
+ const deps: AdminDeps = {
941
+ ...makeMockDeps(),
942
+ agentTokenService: {
943
+ ...makeMockDeps().agentTokenService,
944
+ validate: async () => ({ agentId: AGENT_ID }),
945
+ },
946
+ };
947
+ const app = createAdminApp(deps);
948
+ const res = await app.request("/agents/all/cron-runs/outcomes", {
949
+ headers: { Authorization: `Bearer ${VALID_BEARER_TOKEN}` },
950
+ });
951
+ expect(res.status).toBe(403);
952
+ });
953
+ });