@alexkroman1/aai-cli 0.17.0 → 0.18.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 (438) hide show
  1. package/dist/{_agent-BopNO5Bq.mjs → _agent-BN21AHsJ.mjs} +4 -4
  2. package/dist/_api-client-Uljj0CQi.mjs +312 -0
  3. package/dist/_api-client.d.ts +69 -1
  4. package/dist/{_bundler-DCuNHjDF.mjs → _bundler-DvZDEu2p.mjs} +67 -7
  5. package/dist/_bundler.d.ts +15 -0
  6. package/dist/_cli-common.d.ts +42 -0
  7. package/dist/{client-bundler-DE-AGdm7.mjs → _client-plugins-kR43nZnb.mjs} +30 -132
  8. package/dist/_client-plugins.d.ts +16 -0
  9. package/dist/{_config-mq1I5Cva.mjs → _config-Dlh8PRRp.mjs} +2 -20
  10. package/dist/_config.d.ts +0 -8
  11. package/dist/{_dev-server-D6VSQbYW.mjs → _dev-server-C_zidzWj.mjs} +15 -10
  12. package/dist/_dev-session-ticket.d.ts +3 -0
  13. package/dist/_dev-tunnel.d.ts +20 -2
  14. package/dist/_dotenv-file.d.ts +6 -0
  15. package/dist/_init.d.ts +2 -11
  16. package/dist/_output.d.ts +47 -20
  17. package/dist/_safe-write.d.ts +38 -0
  18. package/dist/{_server-common-CVXIeWrY.mjs → _server-common-C6j67AcZ.mjs} +37 -2
  19. package/dist/_server-common.d.ts +16 -0
  20. package/dist/{_slug-api-BnmTHtjd.mjs → _slug-api-B9cptz7Q.mjs} +3 -2
  21. package/dist/_start-affinity.d.ts +70 -0
  22. package/dist/_start-log.d.ts +39 -0
  23. package/dist/_start-router.d.ts +85 -0
  24. package/dist/_start-run.d.ts +101 -0
  25. package/dist/_start-worker.d.ts +61 -0
  26. package/dist/_start-workers-BNdOnTal.mjs +529 -0
  27. package/dist/_start-workers.d.ts +262 -0
  28. package/dist/_studio-zympBLlD.mjs +140 -0
  29. package/dist/_studio.d.ts +14 -0
  30. package/dist/_target-bundle.d.ts +4 -0
  31. package/dist/{_templates-BVMVsQh0.mjs → _templates-ChZuhW66.mjs} +110 -8
  32. package/dist/_templates.d.ts +20 -1
  33. package/dist/{_typecheck-gate-CcX2gLJZ.mjs → _typecheck-gate-BNF5cboL.mjs} +2 -2
  34. package/dist/_ui-C0RufoYZ.mjs +147 -0
  35. package/dist/_ui.d.ts +14 -3
  36. package/dist/_utils-ChU85MEg.mjs +486 -0
  37. package/dist/_utils.d.ts +28 -0
  38. package/dist/_vendor-openers.d.ts +87 -0
  39. package/dist/{_vitest-runner-CKI8_K1b.mjs → _vitest-runner-tzyto9IU.mjs} +7 -3
  40. package/dist/_vitest-runner.d.ts +8 -1
  41. package/dist/{build-BnXLgfk-.mjs → build-BHgd-QYb.mjs} +13 -10
  42. package/dist/build.d.ts +21 -0
  43. package/dist/cli-workflow.d.ts +7 -0
  44. package/dist/cli.d.ts +16 -0
  45. package/dist/cli.mjs +243 -70
  46. package/dist/client-bundler-CImhqcp2.mjs +133 -0
  47. package/dist/client-bundler.mjs +1 -1
  48. package/dist/{console-tVBjfKyR.mjs → console-DwycgRkC.mjs} +4 -5
  49. package/dist/delete-ZcA3J_3o.mjs +75 -0
  50. package/dist/delete.d.ts +10 -1
  51. package/dist/{deploy-eWDoiwvn.mjs → deploy-CkfkiZE3.mjs} +9 -9
  52. package/dist/{dev-CT_QHHZL.mjs → dev-BX9g6qcf.mjs} +81 -18
  53. package/dist/{eval-Dl8o91yC.mjs → eval-CUKvfxRq.mjs} +4 -4
  54. package/dist/{init-CidslZZz.mjs → init-B9Uw76-_.mjs} +62 -32
  55. package/dist/{login-oJdBWu2B.mjs → login-Ct73CqU1.mjs} +30 -6
  56. package/dist/login.d.ts +2 -0
  57. package/dist/{logs-CkmFdSbr.mjs → logs-BBsUy96d.mjs} +59 -14
  58. package/dist/logs.d.ts +4 -1
  59. package/dist/project-config.mjs +1 -1
  60. package/dist/scaffold/CLAUDE.md +72 -55
  61. package/dist/scaffold/agent-guide/AGENT-API.md +44 -34
  62. package/dist/scaffold/agent-guide/HOSTING.md +11 -0
  63. package/dist/scaffold/agent-guide/TESTING-EVALS.md +105 -36
  64. package/dist/scaffold/agent-guide/TOOLS.md +189 -33
  65. package/dist/scaffold/agent-guide/UI.md +111 -39
  66. package/dist/scaffold/agent-guide/WORKFLOWS.md +234 -160
  67. package/dist/scaffold/package.json +4 -4
  68. package/dist/{secret-DPdPEet2.mjs → secret-CKjHRrVX.mjs} +112 -35
  69. package/dist/start.d.ts +14 -14
  70. package/dist/start.mjs +840 -40
  71. package/dist/{studio-COjK25Rl.mjs → studio-U6DvBNAx.mjs} +123 -35
  72. package/dist/studio.d.ts +1 -0
  73. package/dist/templates/applicant-screening-agent/agent.eval.test.ts +23 -52
  74. package/dist/templates/applicant-screening-agent/agent.test.ts +821 -826
  75. package/dist/templates/applicant-screening-agent/agent.ts +1 -6
  76. package/dist/templates/applicant-screening-agent/client.tsx +1 -19
  77. package/dist/templates/applicant-screening-agent/shared.ts +8 -18
  78. package/dist/templates/applicant-screening-agent/tools/candidate_details.ts +24 -27
  79. package/dist/templates/applicant-screening-agent/tools/proceed_to_emails.ts +75 -82
  80. package/dist/templates/applicant-screening-agent/tools/read_email.ts +24 -24
  81. package/dist/templates/applicant-screening-agent/tools/rescore_with_feedback.ts +92 -99
  82. package/dist/templates/applicant-screening-agent/tools/screen_candidates.ts +72 -83
  83. package/dist/templates/applicant-screening-agent/tools/screening_status.ts +21 -29
  84. package/dist/templates/call-audit-workflow/agent.eval.test.ts +14 -19
  85. package/dist/templates/call-audit-workflow/agent.test.ts +275 -169
  86. package/dist/templates/call-audit-workflow/agent.ts +12 -30
  87. package/dist/templates/call-audit-workflow/client.tsx +9 -27
  88. package/dist/templates/call-audit-workflow/guards.test.ts +24 -71
  89. package/dist/templates/call-audit-workflow/workflows/audit.ts +24 -52
  90. package/dist/templates/call-audit-workflow/workflows/ingest.ts +32 -59
  91. package/dist/templates/call-audit-workflow/workflows/media.ts +4 -44
  92. package/dist/templates/call-audit-workflow/workflows/summarize.ts +72 -107
  93. package/dist/templates/code-interpreter-agent/agent.eval.test.ts +3 -2
  94. package/dist/templates/code-interpreter-agent/agent.test.ts +4 -17
  95. package/dist/templates/code-interpreter-agent/agent.ts +1 -1
  96. package/dist/templates/coding-agent/agent.test.ts +17 -12
  97. package/dist/templates/coding-agent/agent.ts +1 -1
  98. package/dist/templates/custom-pipeline-agent/agent.test.ts +6 -14
  99. package/dist/templates/custom-pipeline-agent/agent.ts +1 -1
  100. package/dist/templates/custom-pipeline-agent/modes.test.ts +0 -1
  101. package/dist/templates/document-redline-workflow/agent.test.ts +88 -221
  102. package/dist/templates/document-redline-workflow/agent.ts +22 -32
  103. package/dist/templates/document-redline-workflow/client.tsx +46 -88
  104. package/dist/templates/document-redline-workflow/workflows/prompts.ts +0 -3
  105. package/dist/templates/document-redline-workflow/workflows/redline.ts +33 -50
  106. package/dist/templates/emergency-dispatch-agent/agent.eval.test.ts +22 -71
  107. package/dist/templates/emergency-dispatch-agent/agent.test.ts +466 -495
  108. package/dist/templates/emergency-dispatch-agent/agent.ts +27 -43
  109. package/dist/templates/emergency-dispatch-agent/client.tsx +85 -119
  110. package/dist/templates/emergency-dispatch-agent/shared.ts +51 -88
  111. package/dist/templates/emergency-dispatch-agent/tools/incident_add_note.ts +11 -17
  112. package/dist/templates/emergency-dispatch-agent/tools/incident_create.ts +21 -30
  113. package/dist/templates/emergency-dispatch-agent/tools/incident_escalate.ts +60 -63
  114. package/dist/templates/emergency-dispatch-agent/tools/incident_get.ts +6 -15
  115. package/dist/templates/emergency-dispatch-agent/tools/incident_triage.ts +40 -53
  116. package/dist/templates/emergency-dispatch-agent/tools/incident_update_status.ts +41 -47
  117. package/dist/templates/emergency-dispatch-agent/tools/ops_dashboard.ts +2 -2
  118. package/dist/templates/emergency-dispatch-agent/tools/ops_protocols.ts +1 -1
  119. package/dist/templates/emergency-dispatch-agent/tools/ops_run_scenario.ts +13 -10
  120. package/dist/templates/emergency-dispatch-agent/tools/resources_dispatch.ts +42 -51
  121. package/dist/templates/emergency-dispatch-agent/tools/resources_update_status.ts +40 -41
  122. package/dist/templates/entertainment-picks-agent/agent.eval.test.ts +14 -42
  123. package/dist/templates/entertainment-picks-agent/agent.test.ts +174 -221
  124. package/dist/templates/entertainment-picks-agent/agent.ts +1 -6
  125. package/dist/templates/entertainment-picks-agent/client.tsx +1 -12
  126. package/dist/templates/entertainment-picks-agent/shared.ts +12 -6
  127. package/dist/templates/entertainment-picks-agent/tools/recommend.ts +2 -2
  128. package/dist/templates/entertainment-picks-agent/tools/revisit.ts +1 -0
  129. package/dist/templates/executive-inbox-agent/agent.eval.test.ts +15 -22
  130. package/dist/templates/executive-inbox-agent/agent.test.ts +515 -527
  131. package/dist/templates/executive-inbox-agent/agent.ts +4 -8
  132. package/dist/templates/executive-inbox-agent/calendar.test.ts +23 -22
  133. package/dist/templates/executive-inbox-agent/client.tsx +1 -23
  134. package/dist/templates/executive-inbox-agent/review.ts +125 -113
  135. package/dist/templates/executive-inbox-agent/shared.ts +3 -0
  136. package/dist/templates/executive-inbox-agent/tools/ask_question.ts +6 -6
  137. package/dist/templates/executive-inbox-agent/tools/draft_reply.ts +16 -18
  138. package/dist/templates/executive-inbox-agent/tools/inbox_status.ts +1 -0
  139. package/dist/templates/executive-inbox-agent/tools/meeting_assistant.ts +20 -20
  140. package/dist/templates/executive-inbox-agent/tools/new_email.ts +17 -21
  141. package/dist/templates/executive-inbox-agent/tools/open_email.ts +72 -74
  142. package/dist/templates/executive-inbox-agent/tools/review_memory.ts +1 -0
  143. package/dist/templates/executive-inbox-agent/tools/send_calendar_invite.ts +19 -20
  144. package/dist/templates/executive-inbox-agent/tools/triage_inbox.ts +53 -50
  145. package/dist/templates/front-desk-agent/agent.eval.test.ts +22 -14
  146. package/dist/templates/front-desk-agent/agent.test.ts +139 -123
  147. package/dist/templates/front-desk-agent/agent.ts +4 -7
  148. package/dist/templates/front-desk-agent/shared.ts +88 -74
  149. package/dist/templates/front-door-agent/agent.eval.test.ts +61 -0
  150. package/dist/templates/front-door-agent/agent.test.ts +393 -0
  151. package/dist/templates/front-door-agent/agent.ts +35 -0
  152. package/dist/templates/front-door-agent/client.tsx +250 -0
  153. package/dist/templates/front-door-agent/routes.ts +91 -0
  154. package/dist/templates/front-door-agent/shared.ts +35 -0
  155. package/dist/templates/front-door-agent/system-prompt.md +12 -0
  156. package/dist/templates/front-door-agent/tools/leave_message.ts +39 -0
  157. package/dist/templates/front-door-agent/tools/link_phone.ts +49 -0
  158. package/dist/templates/front-door-agent/workflows/announce.ts +38 -0
  159. package/dist/templates/front-door-agent/workflows/digest.ts +53 -0
  160. package/dist/templates/front-door-agent/workflows/pair.ts +28 -0
  161. package/dist/templates/home-assistant-agent/agent.eval.test.ts +5 -9
  162. package/dist/templates/home-assistant-agent/agent.test.ts +513 -399
  163. package/dist/templates/home-assistant-agent/agent.ts +8 -5
  164. package/dist/templates/home-assistant-agent/client.tsx +48 -9
  165. package/dist/templates/home-assistant-agent/tools/cancel_reminders.ts +1 -0
  166. package/dist/templates/home-assistant-agent/tools/remind_me.ts +2 -1
  167. package/dist/templates/hotel-reception-agent/agent.eval.test.ts +27 -52
  168. package/dist/templates/hotel-reception-agent/agent.test.ts +980 -964
  169. package/dist/templates/hotel-reception-agent/agent.ts +8 -21
  170. package/dist/templates/hotel-reception-agent/booking.ts +2 -2
  171. package/dist/templates/hotel-reception-agent/client.tsx +5 -20
  172. package/dist/templates/hotel-reception-agent/concierge.ts +2 -0
  173. package/dist/templates/hotel-reception-agent/desk-seams.test.ts +285 -275
  174. package/dist/templates/hotel-reception-agent/desk.ts +45 -12
  175. package/dist/templates/hotel-reception-agent/hotel.ts +6 -6
  176. package/dist/templates/hotel-reception-agent/restaurant.ts +3 -4
  177. package/dist/templates/hotel-reception-agent/session.ts +14 -30
  178. package/dist/templates/hotel-reception-agent/shared.ts +33 -46
  179. package/dist/templates/hotel-reception-agent/tools/abandon_booking.ts +14 -15
  180. package/dist/templates/hotel-reception-agent/tools/add_to_waitlist.ts +1 -0
  181. package/dist/templates/hotel-reception-agent/tools/book_airport_car.ts +1 -0
  182. package/dist/templates/hotel-reception-agent/tools/cancel_restaurant_reservation.ts +2 -2
  183. package/dist/templates/hotel-reception-agent/tools/cancel_room_booking.ts +13 -10
  184. package/dist/templates/hotel-reception-agent/tools/choose_room.ts +1 -1
  185. package/dist/templates/hotel-reception-agent/tools/confirm_booking.ts +6 -7
  186. package/dist/templates/hotel-reception-agent/tools/dispatch_emergency.ts +1 -0
  187. package/dist/templates/hotel-reception-agent/tools/dispute_charge.ts +5 -4
  188. package/dist/templates/hotel-reception-agent/tools/flag_late_arrival.ts +6 -5
  189. package/dist/templates/hotel-reception-agent/tools/lookup_booking.ts +3 -4
  190. package/dist/templates/hotel-reception-agent/tools/lookup_invoice.ts +4 -4
  191. package/dist/templates/hotel-reception-agent/tools/modify_restaurant_reservation.ts +1 -0
  192. package/dist/templates/hotel-reception-agent/tools/record_card.ts +1 -1
  193. package/dist/templates/hotel-reception-agent/tools/record_followup.ts +1 -0
  194. package/dist/templates/hotel-reception-agent/tools/record_group_inquiry.ts +1 -0
  195. package/dist/templates/hotel-reception-agent/tools/record_guest_details.ts +1 -1
  196. package/dist/templates/hotel-reception-agent/tools/reinstate_booking.ts +1 -0
  197. package/dist/templates/hotel-reception-agent/tools/request_flight_reconfirmation.ts +1 -0
  198. package/dist/templates/hotel-reception-agent/tools/resend_confirmation.ts +4 -4
  199. package/dist/templates/hotel-reception-agent/tools/reserve_table.ts +1 -0
  200. package/dist/templates/hotel-reception-agent/tools/resolve_room_conflict.ts +4 -3
  201. package/dist/templates/hotel-reception-agent/tools/schedule_wakeup_call.ts +1 -0
  202. package/dist/templates/hotel-reception-agent/tools/set_do_not_disturb.ts +1 -0
  203. package/dist/templates/hotel-reception-agent/tools/set_extras.ts +1 -1
  204. package/dist/templates/hotel-reception-agent/tools/set_stay.ts +1 -1
  205. package/dist/templates/hotel-reception-agent/tools/start_booking_modification.ts +30 -32
  206. package/dist/templates/hotel-reception-agent/tools/start_room_booking.ts +22 -25
  207. package/dist/templates/hotel-reception-agent/tools/take_guest_message.ts +1 -0
  208. package/dist/templates/hotel-reception-agent/tools/update_card.ts +5 -4
  209. package/dist/templates/hotel-reception-agent/tools/verify_booking.ts +23 -13
  210. package/dist/templates/kitchen-coach-agent/agent.eval.test.ts +38 -0
  211. package/dist/templates/kitchen-coach-agent/agent.test.ts +204 -0
  212. package/dist/templates/kitchen-coach-agent/agent.ts +22 -0
  213. package/dist/templates/kitchen-coach-agent/client.tsx +232 -0
  214. package/dist/templates/kitchen-coach-agent/history.ts +37 -0
  215. package/dist/templates/kitchen-coach-agent/shared.ts +131 -0
  216. package/dist/templates/kitchen-coach-agent/system-prompt.md +17 -0
  217. package/dist/templates/kitchen-coach-agent/tools/get_kitchen.ts +17 -0
  218. package/dist/templates/kitchen-coach-agent/tools/scale_amount.ts +31 -0
  219. package/dist/templates/kitchen-coach-agent/tools/start_timer.ts +24 -0
  220. package/dist/templates/link-digest-workflow/agent.eval.test.ts +16 -40
  221. package/dist/templates/link-digest-workflow/agent.test.ts +84 -164
  222. package/dist/templates/link-digest-workflow/agent.ts +27 -42
  223. package/dist/templates/link-digest-workflow/api-client.ts +3 -2
  224. package/dist/templates/link-digest-workflow/client.tsx +5 -5
  225. package/dist/templates/link-digest-workflow/workflows/digest.ts +53 -95
  226. package/dist/templates/medication-safety-agent/agent.eval.test.ts +10 -30
  227. package/dist/templates/medication-safety-agent/agent.test.ts +16 -46
  228. package/dist/templates/medication-safety-agent/agent.ts +1 -4
  229. package/dist/templates/medication-safety-agent/tools/check_drug_interaction.ts +13 -10
  230. package/dist/templates/meeting-recap-agent/agent.eval.test.ts +238 -396
  231. package/dist/templates/meeting-recap-agent/agent.test.ts +414 -1070
  232. package/dist/templates/meeting-recap-agent/agent.ts +26 -67
  233. package/dist/templates/meeting-recap-agent/system-prompt.md +1 -0
  234. package/dist/templates/meeting-recap-agent/tools/keep_transcript.ts +10 -12
  235. package/dist/templates/meeting-recap-agent/tools/request_recap.ts +9 -20
  236. package/dist/templates/meeting-recap-agent/workflows/recap.ts +224 -547
  237. package/dist/templates/outbound-call-agent/agent.eval.test.ts +10 -12
  238. package/dist/templates/outbound-call-agent/agent.test.ts +419 -453
  239. package/dist/templates/outbound-call-agent/agent.ts +57 -62
  240. package/dist/templates/outbound-call-agent/api.ts +53 -68
  241. package/dist/templates/outbound-call-agent/client.tsx +105 -176
  242. package/dist/templates/outbound-call-agent/shared.ts +10 -39
  243. package/dist/templates/outbound-call-agent/system-prompt.md +3 -4
  244. package/dist/templates/outbound-call-agent/tools/end_call.ts +15 -12
  245. package/dist/templates/outbound-call-agent/tools/press_keys.ts +8 -13
  246. package/dist/templates/outbound-call-agent/workflows/call.ts +89 -62
  247. package/dist/templates/pizza-ordering-agent/agent.eval.test.ts +18 -54
  248. package/dist/templates/pizza-ordering-agent/agent.test.ts +205 -244
  249. package/dist/templates/pizza-ordering-agent/agent.ts +5 -12
  250. package/dist/templates/pizza-ordering-agent/client.tsx +3 -14
  251. package/dist/templates/pizza-ordering-agent/shared.ts +31 -36
  252. package/dist/templates/pizza-ordering-agent/tools/add_pizza.ts +1 -0
  253. package/dist/templates/pizza-ordering-agent/tools/place_order.ts +5 -2
  254. package/dist/templates/pizza-ordering-agent/tools/remove_pizza.ts +1 -0
  255. package/dist/templates/pizza-ordering-agent/tools/update_pizza.ts +2 -3
  256. package/dist/templates/pizza-ordering-agent/tools/view_order.ts +7 -3
  257. package/dist/templates/podcast-digest-workflow/agent.test.ts +53 -102
  258. package/dist/templates/podcast-digest-workflow/agent.ts +11 -17
  259. package/dist/templates/podcast-digest-workflow/client.tsx +29 -51
  260. package/dist/templates/podcast-digest-workflow/workflows/digest.ts +24 -26
  261. package/dist/templates/push-to-talk-agent/agent.eval.test.ts +13 -14
  262. package/dist/templates/push-to-talk-agent/agent.test.ts +30 -23
  263. package/dist/templates/push-to-talk-agent/agent.ts +1 -5
  264. package/dist/templates/push-to-talk-agent/client.tsx +1 -11
  265. package/dist/templates/push-to-talk-agent/shared.ts +12 -6
  266. package/dist/templates/push-to-talk-agent/tools/list_notes.ts +1 -0
  267. package/dist/templates/push-to-talk-agent/tools/save_note.ts +1 -0
  268. package/dist/templates/quickstart-agent/agent.eval.test.ts +0 -10
  269. package/dist/templates/quickstart-agent/agent.test.ts +18 -30
  270. package/dist/templates/quickstart-agent/agent.ts +3 -4
  271. package/dist/templates/research-handoff-agent/agent.eval.test.ts +161 -290
  272. package/dist/templates/research-handoff-agent/agent.test.ts +131 -457
  273. package/dist/templates/research-handoff-agent/agent.ts +26 -86
  274. package/dist/templates/research-handoff-agent/system-prompt.md +1 -0
  275. package/dist/templates/research-handoff-agent/tools/file_it_now.ts +8 -21
  276. package/dist/templates/research-handoff-agent/tools/request_research.ts +7 -16
  277. package/dist/templates/research-handoff-agent/workflows/research.ts +88 -40
  278. package/dist/templates/research-planner-agent/agent.eval.test.ts +15 -40
  279. package/dist/templates/research-planner-agent/agent.test.ts +415 -464
  280. package/dist/templates/research-planner-agent/agent.ts +3 -8
  281. package/dist/templates/research-planner-agent/client.tsx +1 -14
  282. package/dist/templates/research-planner-agent/procedure.ts +9 -3
  283. package/dist/templates/research-planner-agent/shared.ts +30 -33
  284. package/dist/templates/research-planner-agent/tools/plan_status.ts +7 -15
  285. package/dist/templates/research-planner-agent/tools/revise_plan.ts +29 -36
  286. package/dist/templates/research-planner-agent/tools/start_plan.ts +25 -39
  287. package/dist/templates/research-planner-agent/tools/work_next_step.ts +25 -42
  288. package/dist/templates/retail-orders-agent/agent.eval.test.ts +14 -34
  289. package/dist/templates/retail-orders-agent/agent.test.ts +1079 -1073
  290. package/dist/templates/retail-orders-agent/agent.ts +25 -78
  291. package/dist/templates/retail-orders-agent/client.tsx +120 -168
  292. package/dist/templates/retail-orders-agent/pending.test.ts +7 -14
  293. package/dist/templates/retail-orders-agent/registry.test.ts +93 -192
  294. package/dist/templates/retail-orders-agent/shared.test.ts +1 -1
  295. package/dist/templates/retail-orders-agent/shared.ts +10 -20
  296. package/dist/templates/retail-orders-agent/store.test.ts +46 -128
  297. package/dist/templates/retail-orders-agent/store.ts +42 -175
  298. package/dist/templates/retail-orders-agent/tools/cancel_change.ts +3 -6
  299. package/dist/templates/retail-orders-agent/tools/cancel_pending_order.ts +3 -4
  300. package/dist/templates/retail-orders-agent/tools/confirm_change.ts +4 -6
  301. package/dist/templates/retail-orders-agent/tools/exchange_delivered_order_items.ts +3 -4
  302. package/dist/templates/retail-orders-agent/tools/find_user_id_by_email.ts +3 -4
  303. package/dist/templates/retail-orders-agent/tools/find_user_id_by_name_zip.ts +3 -4
  304. package/dist/templates/retail-orders-agent/tools/get_item_details.ts +3 -4
  305. package/dist/templates/retail-orders-agent/tools/get_order_details.ts +3 -4
  306. package/dist/templates/retail-orders-agent/tools/get_product_details.ts +3 -4
  307. package/dist/templates/retail-orders-agent/tools/get_user_details.ts +3 -4
  308. package/dist/templates/retail-orders-agent/tools/list_all_product_types.ts +3 -8
  309. package/dist/templates/retail-orders-agent/tools/modify_pending_order_address.ts +3 -4
  310. package/dist/templates/retail-orders-agent/tools/modify_pending_order_items.ts +3 -4
  311. package/dist/templates/retail-orders-agent/tools/modify_pending_order_payment.ts +3 -4
  312. package/dist/templates/retail-orders-agent/tools/modify_user_address.ts +3 -4
  313. package/dist/templates/retail-orders-agent/tools/return_delivered_order_items.ts +3 -4
  314. package/dist/templates/retail-orders-agent/tools/transfer_to_human_agents.ts +3 -4
  315. package/dist/templates/roadside-assistance-agent/agent.eval.test.ts +22 -25
  316. package/dist/templates/roadside-assistance-agent/agent.test.ts +453 -490
  317. package/dist/templates/roadside-assistance-agent/agent.ts +28 -60
  318. package/dist/templates/roadside-assistance-agent/call.ts +16 -22
  319. package/dist/templates/roadside-assistance-agent/shared.ts +24 -54
  320. package/dist/templates/roadside-assistance-agent/tools/acknowledge_disclosure.ts +29 -37
  321. package/dist/templates/roadside-assistance-agent/tools/dispatch_truck.ts +44 -70
  322. package/dist/templates/roadside-assistance-agent/tools/job_status.ts +16 -24
  323. package/dist/templates/roadside-assistance-agent/tools/lookup_coverage.ts +39 -51
  324. package/dist/templates/roadside-assistance-agent/tools/report_location.ts +34 -33
  325. package/dist/templates/roadside-assistance-agent/tools/service_disclosure.ts +18 -39
  326. package/dist/templates/roadside-assistance-agent/yard.test.ts +22 -19
  327. package/dist/templates/roadside-assistance-agent/yard.ts +3 -3
  328. package/dist/templates/spoken-summary-workflow/agent.eval.test.ts +38 -40
  329. package/dist/templates/spoken-summary-workflow/agent.test.ts +129 -279
  330. package/dist/templates/spoken-summary-workflow/agent.ts +15 -40
  331. package/dist/templates/spoken-summary-workflow/client.tsx +13 -25
  332. package/dist/templates/spoken-summary-workflow/workflows/summarize.ts +52 -92
  333. package/dist/templates/tabletop-rpg-agent/agent.eval.test.ts +31 -74
  334. package/dist/templates/tabletop-rpg-agent/agent.test.ts +756 -774
  335. package/dist/templates/tabletop-rpg-agent/agent.ts +9 -46
  336. package/dist/templates/tabletop-rpg-agent/client.tsx +13 -21
  337. package/dist/templates/tabletop-rpg-agent/shared.ts +40 -99
  338. package/dist/templates/tabletop-rpg-agent/tools/action_roll.ts +67 -83
  339. package/dist/templates/tabletop-rpg-agent/tools/burn_momentum.ts +65 -88
  340. package/dist/templates/tabletop-rpg-agent/tools/check_state.ts +8 -27
  341. package/dist/templates/tabletop-rpg-agent/tools/setup_character.ts +18 -36
  342. package/dist/templates/tabletop-rpg-agent/tools/update_state.ts +101 -111
  343. package/dist/templates/technical-support-agent/agent.eval.test.ts +31 -72
  344. package/dist/templates/technical-support-agent/agent.test.ts +231 -260
  345. package/dist/templates/technical-support-agent/agent.ts +4 -10
  346. package/dist/templates/technical-support-agent/client.tsx +4 -18
  347. package/dist/templates/technical-support-agent/shared.ts +15 -25
  348. package/dist/templates/technical-support-agent/tools/answer_question.ts +46 -56
  349. package/dist/templates/technical-support-agent/tools/list_topics.ts +1 -0
  350. package/dist/templates/technical-support-agent/tools/log_ticket.ts +8 -5
  351. package/dist/templates/text-adventure-agent/agent.eval.test.ts +37 -126
  352. package/dist/templates/text-adventure-agent/agent.test.ts +197 -368
  353. package/dist/templates/text-adventure-agent/agent.ts +15 -65
  354. package/dist/templates/text-adventure-agent/client.tsx +38 -98
  355. package/dist/templates/text-adventure-agent/shared.ts +31 -143
  356. package/dist/templates/text-adventure-agent/tools/game_state_drop.ts +6 -12
  357. package/dist/templates/text-adventure-agent/tools/game_state_get.ts +4 -11
  358. package/dist/templates/text-adventure-agent/tools/game_state_move.ts +0 -2
  359. package/dist/templates/text-adventure-agent/tools/game_state_restart.ts +1 -3
  360. package/dist/templates/text-adventure-agent/tools/game_state_score.ts +5 -7
  361. package/dist/templates/topic-briefing-agent/agent.eval.test.ts +12 -50
  362. package/dist/templates/topic-briefing-agent/agent.test.ts +478 -476
  363. package/dist/templates/topic-briefing-agent/agent.ts +3 -3
  364. package/dist/templates/topic-briefing-agent/shared.ts +11 -16
  365. package/dist/templates/topic-briefing-agent/slack.ts +12 -4
  366. package/dist/templates/topic-briefing-agent/tools/briefing_so_far.ts +10 -17
  367. package/dist/templates/topic-briefing-agent/tools/research_topic.ts +21 -24
  368. package/dist/templates/topic-briefing-agent/tools/send_briefing.ts +13 -14
  369. package/dist/templates/topic-briefing-agent/tools/verify_claim.ts +16 -13
  370. package/dist/templates/transcription-workflow/agent.test.ts +114 -259
  371. package/dist/templates/transcription-workflow/agent.ts +6 -9
  372. package/dist/templates/transcription-workflow/client.tsx +100 -258
  373. package/dist/templates/transcription-workflow/recover.test.ts +6 -136
  374. package/dist/templates/transcription-workflow/recover.ts +14 -97
  375. package/dist/templates/transcription-workflow/run-panel.tsx +71 -8
  376. package/dist/templates/transcription-workflow/workflows/batch.ts +28 -159
  377. package/dist/templates/transcription-workflow/workflows/normalize.ts +50 -86
  378. package/dist/templates/transcription-workflow/workflows/stream.ts +2 -2
  379. package/dist/templates/transcription-workflow/workflows/transcribe.ts +16 -23
  380. package/dist/templates/travel-concierge-agent/agent.eval.test.ts +7 -25
  381. package/dist/templates/travel-concierge-agent/agent.test.ts +505 -517
  382. package/dist/templates/travel-concierge-agent/agent.ts +22 -46
  383. package/dist/templates/travel-concierge-agent/client.tsx +1 -22
  384. package/dist/templates/travel-concierge-agent/routing.ts +29 -31
  385. package/dist/templates/travel-concierge-agent/shared.ts +63 -152
  386. package/dist/templates/travel-concierge-agent/tools/book_car_rental.ts +8 -9
  387. package/dist/templates/travel-concierge-agent/tools/book_excursion.ts +8 -8
  388. package/dist/templates/travel-concierge-agent/tools/book_hotel.ts +9 -6
  389. package/dist/templates/travel-concierge-agent/tools/cancel_ticket.ts +10 -10
  390. package/dist/templates/travel-concierge-agent/tools/search_car_rentals.ts +3 -2
  391. package/dist/templates/travel-concierge-agent/tools/search_excursions.ts +3 -2
  392. package/dist/templates/travel-concierge-agent/tools/search_flights.ts +4 -3
  393. package/dist/templates/travel-concierge-agent/tools/search_hotels.ts +3 -2
  394. package/dist/templates/travel-concierge-agent/tools/update_ticket.ts +13 -8
  395. package/dist/templates/web-research-agent/agent.test.ts +19 -30
  396. package/dist/templates/web-research-agent/agent.ts +3 -4
  397. package/dist/templates/word-game-agent/agent.eval.test.ts +47 -67
  398. package/dist/templates/word-game-agent/agent.test.ts +369 -382
  399. package/dist/templates/word-game-agent/agent.ts +2 -5
  400. package/dist/templates/word-game-agent/client.tsx +1 -8
  401. package/dist/templates/word-game-agent/game.ts +15 -27
  402. package/dist/templates/word-game-agent/shared.ts +36 -20
  403. package/dist/templates/word-game-agent/tools/final_score.ts +14 -13
  404. package/dist/templates/word-game-agent/tools/relay_description.ts +90 -66
  405. package/dist/templates/word-game-agent/tools/repeat_word.ts +11 -10
  406. package/dist/templates/word-game-agent/tools/skip_word.ts +17 -21
  407. package/dist/templates/word-game-agent/tools/start_game.ts +26 -30
  408. package/dist/{test-XufelYGW.mjs → test-CW5cw5fy.mjs} +3 -4
  409. package/dist/typecheck.mjs +1 -1
  410. package/dist/worker-bundler-D8uCzpYP.mjs +335 -0
  411. package/dist/worker-bundler.d.ts +39 -0
  412. package/dist/worker-bundler.mjs +2 -155
  413. package/dist/{workflow-CDUlTD5B.mjs → workflow-5gOZMB2M.mjs} +66 -19
  414. package/package.json +4 -4
  415. package/dist/_output-DBP9Op_d.mjs +0 -120
  416. package/dist/_studio-B5m4jBTD.mjs +0 -256
  417. package/dist/_ui-Coe0zwmm.mjs +0 -102
  418. package/dist/_utils-BVLdBvdT.mjs +0 -186
  419. package/dist/delete-DwXCHzTl.mjs +0 -55
  420. package/dist/templates/document-redline-workflow/form.ts +0 -73
  421. package/dist/templates/emergency-dispatch-agent/events.ts +0 -48
  422. package/dist/templates/hotel-reception-agent/events.ts +0 -80
  423. package/dist/templates/meeting-recap-agent/shared.ts +0 -44
  424. package/dist/templates/meeting-recap-agent/tools/cancel_recap.ts +0 -25
  425. package/dist/templates/meeting-recap-agent/tools/recap_progress.ts +0 -24
  426. package/dist/templates/meeting-recap-agent/tools/recap_status.ts +0 -45
  427. package/dist/templates/meeting-recap-agent/workflows/tokens.ts +0 -47
  428. package/dist/templates/outbound-call-agent/call-params.ts +0 -109
  429. package/dist/templates/outbound-call-agent/live-calls.ts +0 -80
  430. package/dist/templates/outbound-call-agent/workflows/tokens.ts +0 -16
  431. package/dist/templates/research-handoff-agent/shared.ts +0 -41
  432. package/dist/templates/research-handoff-agent/tools/research_progress.ts +0 -23
  433. package/dist/templates/research-handoff-agent/tools/research_status.ts +0 -73
  434. package/dist/templates/research-handoff-agent/workflows/review.ts +0 -43
  435. package/dist/templates/roadside-assistance-agent/events.ts +0 -92
  436. package/dist/templates/spoken-summary-workflow/workflows/transcribe.ts +0 -137
  437. package/dist/templates/transcription-workflow/total-latency.tsx +0 -170
  438. package/dist/templates/travel-concierge-agent/call-events.ts +0 -80
@@ -1,22 +1,28 @@
1
1
  /** The def a DEPLOYED agent runs: authored, plus what `tools/` declares. */
2
2
  import agentDef from "virtual:aai/agent";
3
- import type { GenerateFn, GenerateOptions, GuardrailVerdict, ToolContext } from "@alexkroman1/aai";
4
- import { isToolFailure } from "@alexkroman1/aai";
3
+ import type {
4
+ DialogToolResult,
5
+ GenerateFn,
6
+ GenerateOptions,
7
+ GuardrailVerdict,
8
+ ToolContext,
9
+ ToolFailure,
10
+ } from "@alexkroman1/aai";
11
+ import { instructionOf, isToolFailure } from "@alexkroman1/aai";
5
12
  import {
6
13
  createToolContext,
7
- expectDialogOk,
8
14
  expectDialogRefused,
15
+ expectSlotContract,
9
16
  expectToolOk,
10
17
  parseSchemaInput,
11
18
  runGuardrail,
12
- runTool,
13
19
  type SentEvent,
14
20
  type StubDelegateCall,
15
21
  type StubGenerateCall,
16
22
  schemaInputIssues,
17
23
  type TestToolContext,
18
- toolRunner,
19
24
  } from "@alexkroman1/aai-runtime/testing";
25
+ import { describeAgent } from "@alexkroman1/aai-runtime/testing/vitest";
20
26
  import { describe, expect, test } from "vitest";
21
27
  import {
22
28
  COORDINATOR_NAME,
@@ -51,937 +57,926 @@ import {
51
57
  stageLabel,
52
58
  } from "./shared.ts";
53
59
  import candidateDetails from "./tools/candidate_details.ts";
60
+ import proceedToEmails from "./tools/proceed_to_emails.ts";
54
61
  import readEmail from "./tools/read_email.ts";
62
+ import rescoreWithFeedback from "./tools/rescore_with_feedback.ts";
55
63
  import screenCandidates from "./tools/screen_candidates.ts";
56
64
  import screeningStatus from "./tools/screening_status.ts";
57
65
 
58
- // ─── A scripted desk ─────────────────────────────────────────────────────────
59
- //
60
- // TWO fakes, because the desk reaches a model two ways — and that split is the
61
- // port showing through in the spec. The evaluator is a `ctx.generate` with a
62
- // schema, so `stubGenerate` drives it, routed by its system prompt; the
63
- // coordinator is a subagent, so `stubDelegate` drives it, routed by name.
64
- // Nothing here runs a model: what is worth asserting is what the desk ASKS for
65
- // and what it does with what comes back.
66
-
67
- const run = toolRunner(agentDef);
68
-
69
- /** What the evaluator says about each applicant, keyed by id — so the stub
70
- * really "reads" the brief it was handed rather than answering by position. */
71
- const SCORES: Readonly<Record<string, number>> = {
72
- c01: 87,
73
- c07: 84,
74
- c04: 71,
75
- c11: 69,
76
- c05: 66,
77
- c09: 63,
78
- c02: 52,
79
- c08: 47,
80
- c12: 41,
81
- c10: 38,
82
- c03: 34,
83
- c06: 22,
84
- };
85
-
86
- /** The same table after "weight TypeScript more": Aisha and Mei climb into the
87
- * top three, Tom drops out, Priya stays. */
88
- const TYPESCRIPT_SCORES: Readonly<Record<string, number>> = {
89
- ...SCORES,
90
- c05: 86,
91
- c11: 85,
92
- c04: 60,
93
- };
94
-
95
- /** The candidate a brief is about, read back out of the prompt. */
96
- function candidateIdIn(prompt: string): string {
97
- const id = prompt.match(/Candidate ID: (c\d\d)/)?.[1];
98
- if (!id) throw new Error("the evaluator's brief names no candidate");
99
- return id;
66
+ /** A gated tool's envelope, position kept, or a throw quoting the refusal. */
67
+ function landed<R>(answer: DialogToolResult<R> | ToolFailure): DialogToolResult<R> {
68
+ if (isToolFailure(answer)) throw new Error(`tool refused: ${answer.error}`);
69
+ return answer;
100
70
  }
101
71
 
102
- /** A coordinator's email, as the guardrail requires it. */
103
- function emailFor(call: StubDelegateCall): string {
104
- const name = call.task.match(/^Name: (.+)$/m)?.[1] ?? "there";
105
- const proceed = call.task.includes("PROCEEDING WITH CANDIDATE: True");
106
- const subject = proceed ? "Next steps on your application" : "Your application";
107
- const body = proceed
108
- ? `Hi ${name},\n\nWe'd like to talk. Could you share your availability for a Zoom call this week?`
109
- : `Hi ${name},\n\nThank you for applying. We've decided to move forward with other candidates.`;
110
- return `Subject: ${subject}\n\n${body}\n\nBest,\n${COORDINATOR_NAME}`;
111
- }
112
-
113
- interface Script {
114
- /** The score table the evaluator answers from. */
115
- scores?: Readonly<Record<string, number>>;
116
- /** Candidate ids whose evaluation FAILS. */
117
- failScoring?: readonly string[];
118
- /** Candidate names whose email FAILS. */
119
- failEmail?: readonly string[];
120
- /** The coordinator's reply, when the default is not the case at hand. */
121
- email?: (call: StubDelegateCall) => string | { text: string; complaint?: string };
122
- }
123
-
124
- /**
125
- * The two fakes over one MUTABLE script: a test that screens and then re-scores
126
- * changes `script.scores` between the two calls, and the routes read the script
127
- * at call time — the slot is keyed by the context, so swapping the context to
128
- * swap the model would also swap the state.
129
- */
130
- function scriptedDesk(script: Script = {}) {
131
- const ctx = createToolContext({
132
- generate: {
133
- routes: {
134
- [EVALUATOR_SYSTEM]: (call: StubGenerateCall) => {
135
- const id = candidateIdIn(call.prompt);
136
- if (script.failScoring?.includes(id)) throw new Error(`gateway said no for ${id}`);
137
- const table = script.scores ?? SCORES;
138
- return { object: { score: table[id] ?? 50, reason: `Scripted reasoning for ${id}.` } };
72
+ describeAgent(agentDef, (run) => {
73
+ // ─── A scripted desk ─────────────────────────────────────────────────────────
74
+ //
75
+ // TWO fakes, because the desk reaches a model two ways — and that split is the
76
+ // port showing through in the spec. The evaluator is a `ctx.generate` with a
77
+ // schema, so `stubGenerate` drives it, routed by its system prompt; the
78
+ // coordinator is a subagent, so `stubDelegate` drives it, routed by name.
79
+ // Nothing here runs a model: what is worth asserting is what the desk ASKS for
80
+ // and what it does with what comes back.
81
+
82
+ /** What the evaluator says about each applicant, keyed by id — so the stub
83
+ * really "reads" the brief it was handed rather than answering by position. */
84
+ const SCORES: Readonly<Record<string, number>> = {
85
+ c01: 87,
86
+ c07: 84,
87
+ c04: 71,
88
+ c11: 69,
89
+ c05: 66,
90
+ c09: 63,
91
+ c02: 52,
92
+ c08: 47,
93
+ c12: 41,
94
+ c10: 38,
95
+ c03: 34,
96
+ c06: 22,
97
+ };
98
+
99
+ /** The same table after "weight TypeScript more": Aisha and Mei climb into the
100
+ * top three, Tom drops out, Priya stays. */
101
+ const TYPESCRIPT_SCORES: Readonly<Record<string, number>> = {
102
+ ...SCORES,
103
+ c05: 86,
104
+ c11: 85,
105
+ c04: 60,
106
+ };
107
+
108
+ /** The candidate a brief is about, read back out of the prompt. */
109
+ function candidateIdIn(prompt: string): string {
110
+ const id = prompt.match(/Candidate ID: (c\d\d)/)?.[1];
111
+ if (!id) throw new Error("the evaluator's brief names no candidate");
112
+ return id;
113
+ }
114
+
115
+ /** A coordinator's email, as the guardrail requires it. */
116
+ function emailFor(call: StubDelegateCall): string {
117
+ const name = call.task.match(/^Name: (.+)$/m)?.[1] ?? "there";
118
+ const proceed = call.task.includes("PROCEEDING WITH CANDIDATE: True");
119
+ const subject = proceed ? "Next steps on your application" : "Your application";
120
+ const body = proceed
121
+ ? `Hi ${name},\n\nWe'd like to talk. Could you share your availability for a Zoom call this week?`
122
+ : `Hi ${name},\n\nThank you for applying. We've decided to move forward with other candidates.`;
123
+ return `Subject: ${subject}\n\n${body}\n\nBest,\n${COORDINATOR_NAME}`;
124
+ }
125
+
126
+ interface Script {
127
+ /** The score table the evaluator answers from. */
128
+ scores?: Readonly<Record<string, number>>;
129
+ /** Candidate ids whose evaluation FAILS. */
130
+ failScoring?: readonly string[];
131
+ /** Candidate names whose email FAILS. */
132
+ failEmail?: readonly string[];
133
+ /** The coordinator's reply, when the default is not the case at hand. */
134
+ email?: (call: StubDelegateCall) => string | { text: string; complaint?: string };
135
+ }
136
+
137
+ /**
138
+ * The two fakes over one MUTABLE script: a test that screens and then re-scores
139
+ * changes `script.scores` between the two calls, and the routes read the script
140
+ * at call time — the slot is keyed by the context, so swapping the context to
141
+ * swap the model would also swap the state.
142
+ */
143
+ function scriptedDesk(script: Script = {}) {
144
+ const ctx = createToolContext({
145
+ generate: {
146
+ routes: {
147
+ [EVALUATOR_SYSTEM]: (call: StubGenerateCall) => {
148
+ const id = candidateIdIn(call.prompt);
149
+ if (script.failScoring?.includes(id)) throw new Error(`gateway said no for ${id}`);
150
+ const table = script.scores ?? SCORES;
151
+ return { object: { score: table[id] ?? 50, reason: `Scripted reasoning for ${id}.` } };
152
+ },
139
153
  },
140
154
  },
141
- },
142
- delegate: {
143
- routes: {
144
- "hr-coordinator": (call) => {
145
- const name = call.task.match(/^Name: (.+)$/m)?.[1] ?? "";
146
- if (script.failEmail?.includes(name)) throw new Error(`coordinator timed out on ${name}`);
147
- const reply = script.email ? script.email(call) : emailFor(call);
148
- return typeof reply === "string" ? { text: reply } : reply;
155
+ delegate: {
156
+ routes: {
157
+ "hr-coordinator": (call) => {
158
+ const name = call.task.match(/^Name: (.+)$/m)?.[1] ?? "";
159
+ if (script.failEmail?.includes(name))
160
+ throw new Error(`coordinator timed out on ${name}`);
161
+ const reply = script.email ? script.email(call) : emailFor(call);
162
+ return typeof reply === "string" ? { text: reply } : reply;
163
+ },
149
164
  },
150
165
  },
151
- },
166
+ });
167
+ return { ctx, model: ctx.model, desk: ctx.desk, script };
168
+ }
169
+
170
+ const at = (ctx: ToolContext) => hiringFlow.position(ctx).state;
171
+ const stateOf = (ctx: ToolContext) => hiringSlot.get(ctx);
172
+ const nameAt = (ctx: ToolContext, rank: number) =>
173
+ ranked(stateOf(ctx)).find((one) => one.rank === rank)?.name;
174
+
175
+ /** A screening that has run, so a test about the review stage starts there. */
176
+ async function screened(script: Script = {}) {
177
+ const desk = scriptedDesk(script);
178
+ await run(screenCandidates, {}, desk.ctx);
179
+ desk.model.calls.length = 0;
180
+ return desk;
181
+ }
182
+
183
+ // ─── The flow ────────────────────────────────────────────────────────────────
184
+
185
+ describe("the flow", () => {
186
+ test("starts with nothing screened", () => {
187
+ const { ctx } = scriptedDesk();
188
+ expect(at(ctx)).toBe("idle");
189
+ expect(stageLabel(hiringFlow.position(ctx))).toBe("nothing screened yet");
190
+ });
191
+
192
+ test("refuses feedback and emails before anything is scored, spending no model", async () => {
193
+ const { ctx, model, desk } = scriptedDesk();
194
+ for (const [tool, args] of [
195
+ [rescoreWithFeedback, { feedback: "more TypeScript" }],
196
+ [proceedToEmails, {}],
197
+ ] as const) {
198
+ // Their router is only reachable after `score_leads`; here that is the
199
+ // gate, and its refusal names the position and quotes the state's own
200
+ // instruction so the model can recover on its turn.
201
+ const refused = expectDialogRefused(await run(tool, args, ctx), "idle");
202
+ expect(refused.error).toMatch(/screen_candidates/);
203
+ }
204
+ expect(model.calls).toEqual([]);
205
+ expect(desk.calls).toEqual([]);
206
+ expect(at(ctx)).toBe("idle");
207
+ });
152
208
  });
153
- return { ctx, model: ctx.model, desk: ctx.desk, script };
154
- }
155
209
 
156
- const at = (ctx: ToolContext) => hiringFlow.position(ctx).state;
157
- const stateOf = (ctx: ToolContext) => hiringSlot.get(ctx);
158
- const nameAt = (ctx: ToolContext, rank: number) =>
159
- ranked(stateOf(ctx)).find((one) => one.rank === rank)?.name;
160
-
161
- /** A screening that has run, so a test about the review stage starts there. */
162
- async function screened(script: Script = {}) {
163
- const desk = scriptedDesk(script);
164
- await run("screen_candidates", {}, desk.ctx);
165
- desk.model.calls.length = 0;
166
- return desk;
167
- }
210
+ // ─── Crew A: screen_candidates ───────────────────────────────────────────────
168
211
 
169
- // ─── The flow ────────────────────────────────────────────────────────────────
212
+ describe("screen_candidates (their load_leads + score_leads)", () => {
213
+ test("scores every applicant once, through the evaluator, and lands in reviewing", async () => {
214
+ const { ctx, model } = scriptedDesk();
170
215
 
171
- describe("the flow", () => {
172
- test("starts with nothing screened", () => {
173
- const { ctx } = scriptedDesk();
174
- expect(at(ctx)).toBe("idle");
175
- expect(stageLabel(hiringFlow.position(ctx))).toBe("nothing screened yet");
176
- });
216
+ const result = expectToolOk(await run(screenCandidates, {}, ctx));
177
217
 
178
- test("refuses feedback and emails before anything is scored, spending no model", async () => {
179
- const { ctx, model, desk } = scriptedDesk();
180
- for (const [name, args] of [
181
- ["rescore_with_feedback", { feedback: "more TypeScript" }],
182
- ["proceed_to_emails", {}],
183
- ] as const) {
184
- // Their router is only reachable after `score_leads`; here that is the
185
- // gate, and its refusal names the position and quotes the state's own
186
- // instruction so the model can recover on its turn.
187
- const refused = expectDialogRefused(await run(name, args, ctx), "idle");
188
- expect(refused.error).toMatch(/screen_candidates/);
189
- }
190
- expect(model.calls).toEqual([]);
191
- expect(desk.calls).toEqual([]);
192
- expect(at(ctx)).toBe("idle");
193
- });
194
- });
218
+ expect(model.calls).toHaveLength(LEADS.length);
219
+ expect(new Set(model.calls.map((call) => call.system))).toEqual(new Set([EVALUATOR_SYSTEM]));
220
+ // Every brief names a different applicant — one evaluation each, none twice.
221
+ expect(new Set(model.calls.map((call) => candidateIdIn(call.prompt))).size).toBe(
222
+ LEADS.length,
223
+ );
224
+ expect(result.screened).toBe(LEADS.length);
225
+ expect(at(ctx)).toBe("reviewing");
226
+ });
195
227
 
196
- // ─── Crew A: screen_candidates ───────────────────────────────────────────────
228
+ test("reads back the top three, best first, with the evaluator's reasoning", async () => {
229
+ const { ctx } = scriptedDesk();
230
+ const result = expectToolOk(await run(screenCandidates, {}, ctx));
231
+
232
+ expect(result.top.map((one) => one.name)).toEqual([
233
+ "Priya Raman",
234
+ "Sofia Lindqvist",
235
+ "Tom Whitfield",
236
+ ]);
237
+ expect(result.top.map((one) => one.rank)).toEqual([1, 2, 3]);
238
+ expect(result.top.map((one) => one.score)).toEqual([87, 84, 71]);
239
+ for (const one of result.top) expect(one.reason).toMatch(/Scripted reasoning/);
240
+ expect(result.message).toContain("1. Priya Raman (87)");
241
+ expect(result.unscored).toBeUndefined();
242
+ });
197
243
 
198
- describe("screen_candidates (their load_leads + score_leads)", () => {
199
- test("scores every applicant once, through the evaluator, and lands in reviewing", async () => {
200
- const { ctx, model } = scriptedDesk();
244
+ test("screens against the shipped role unless the caller named another", async () => {
245
+ const { ctx, model } = scriptedDesk();
246
+ const result = expectToolOk(await run(screenCandidates, {}, ctx));
247
+ expect(result.job).toBe(DEFAULT_JOB.title);
248
+ expect(stateOf(ctx).job).toEqual(DEFAULT_JOB);
249
+ for (const call of model.calls) {
250
+ expect(call.prompt).toContain(`Title: ${DEFAULT_JOB.title}`);
251
+ // The first round carries no feedback section: there is nothing yet.
252
+ expect(call.prompt).not.toContain("hiring manager has reviewed");
253
+ }
254
+ });
201
255
 
202
- const result = expectToolOk(await runTool(screenCandidates, {}, ctx));
256
+ test("carries a role the caller described into every brief", async () => {
257
+ const { ctx, model } = scriptedDesk();
258
+ await run(
259
+ screenCandidates,
260
+ {
261
+ jobTitle: "Design Systems Engineer",
262
+ jobDescription: "Storybook, tokens, accessibility.",
263
+ },
264
+ ctx,
265
+ );
266
+ for (const call of model.calls) {
267
+ expect(call.prompt).toContain("Title: Design Systems Engineer");
268
+ expect(call.prompt).toContain("Storybook, tokens, accessibility.");
269
+ }
270
+ // A title alone keeps the default's description under the caller's title.
271
+ const { ctx: ctx2, model: model2 } = scriptedDesk();
272
+ await run(screenCandidates, { jobTitle: "Frontend Engineer" }, ctx2);
273
+ expect(model2.calls[0]?.prompt).toContain("Title: Frontend Engineer");
274
+ expect(model2.calls[0]?.prompt).toContain("twelve-month contract");
275
+ });
203
276
 
204
- expect(model.calls).toHaveLength(LEADS.length);
205
- expect(new Set(model.calls.map((call) => call.system))).toEqual(new Set([EVALUATOR_SYSTEM]));
206
- // Every brief names a different applicant — one evaluation each, none twice.
207
- expect(new Set(model.calls.map((call) => candidateIdIn(call.prompt))).size).toBe(LEADS.length);
208
- expect(result.screened).toBe(LEADS.length);
209
- expect(result.state).toBe("reviewing");
210
- expect(at(ctx)).toBe("reviewing");
211
- });
277
+ test("runs the evaluations through a window, not all at once and not one by one", async () => {
278
+ const { model } = scriptedDesk();
279
+ let inFlight = 0;
280
+ let peak = 0;
281
+ // The fake answers on a microtask, so `inFlight` only ever exceeds 1 if the
282
+ // fan-out really issued several briefs before awaiting any — and it never
283
+ // exceeds the window if the window is real.
284
+ const generate = ((options: GenerateOptions) => {
285
+ inFlight += 1;
286
+ peak = Math.max(peak, inFlight);
287
+ return model.generate(options).finally(() => {
288
+ inFlight -= 1;
289
+ });
290
+ }) as GenerateFn;
291
+ const ctx = createToolContext({ generate });
292
+
293
+ await run(screenCandidates, {}, ctx);
294
+
295
+ expect(LEADS.length).toBeGreaterThan(SCORING_CONCURRENCY);
296
+ expect(peak).toBe(SCORING_CONCURRENCY);
297
+ });
212
298
 
213
- test("reads back the top three, best first, with the evaluator's reasoning", async () => {
214
- const { ctx } = scriptedDesk();
215
- const result = expectToolOk(await runTool(screenCandidates, {}, ctx));
216
-
217
- expect(result.top.map((one) => one.name)).toEqual([
218
- "Priya Raman",
219
- "Sofia Lindqvist",
220
- "Tom Whitfield",
221
- ]);
222
- expect(result.top.map((one) => one.rank)).toEqual([1, 2, 3]);
223
- expect(result.top.map((one) => one.score)).toEqual([87, 84, 71]);
224
- for (const one of result.top) expect(one.reason).toMatch(/Scripted reasoning/);
225
- expect(result.message).toContain("1. Priya Raman (87)");
226
- expect(result.unscored).toBeUndefined();
227
- });
299
+ test("a second screening in the same step waits: two fan-outs, never interleaved", async () => {
300
+ const { model } = scriptedDesk();
301
+ let inFlight = 0;
302
+ let peak = 0;
303
+ const generate = ((options: GenerateOptions) => {
304
+ inFlight += 1;
305
+ peak = Math.max(peak, inFlight);
306
+ return model.generate(options).finally(() => {
307
+ inFlight -= 1;
308
+ });
309
+ }) as GenerateFn;
310
+ const ctx = createToolContext({ generate });
311
+
312
+ await Promise.all([
313
+ run(screenCandidates, {}, ctx),
314
+ run(screenCandidates, { jobTitle: "Another role" }, ctx),
315
+ ]);
316
+
317
+ // Both screenings really ran, and the window never held two fan-outs at
318
+ // once — which is what the screening lock buys. Without it the second reads
319
+ // and writes the table across the first's awaits, and the ranking the
320
+ // caller was just read is not the one the desk now holds.
321
+ expect(model.calls).toHaveLength(LEADS.length * 2);
322
+ expect(peak).toBe(SCORING_CONCURRENCY);
323
+ const state = stateOf(ctx);
324
+ expect(Object.keys(state.scores)).toHaveLength(LEADS.length);
325
+ expect(state.unscored).toEqual([]);
326
+ expect(at(ctx)).toBe("reviewing");
327
+ });
228
328
 
229
- test("screens against the shipped role unless the caller named another", async () => {
230
- const { ctx, model } = scriptedDesk();
231
- const result = expectToolOk(await runTool(screenCandidates, {}, ctx));
232
- expect(result.job).toBe(DEFAULT_JOB.title);
233
- expect(stateOf(ctx).job).toEqual(DEFAULT_JOB);
234
- for (const call of model.calls) {
235
- expect(call.prompt).toContain(`Title: ${DEFAULT_JOB.title}`);
236
- // The first round carries no feedback section: there is nothing yet.
237
- expect(call.prompt).not.toContain("hiring manager has reviewed");
238
- }
239
- });
329
+ test("one applicant the evaluator could not score does not sink the screening", async () => {
330
+ const { ctx } = scriptedDesk({ failScoring: ["c07"] });
331
+
332
+ const result = expectToolOk(await run(screenCandidates, {}, ctx));
333
+
334
+ expect(result.screened).toBe(LEADS.length - 1);
335
+ expect(result.unscored).toBe("Sofia Lindqvist");
336
+ expect(result.message).toMatch(/could not be scored/);
337
+ // Not ranked at zero — absent, and named. A zero would read as a verdict.
338
+ expect(result.top.map((one) => one.name)).toEqual([
339
+ "Priya Raman",
340
+ "Tom Whitfield",
341
+ "Mei Tanaka",
342
+ ]);
343
+ expect(stateOf(ctx).unscored).toEqual(["c07"]);
344
+ expect(hiringView(stateOf(ctx)).unscored).toEqual(["Sofia Lindqvist"]);
345
+ });
240
346
 
241
- test("carries a role the caller described into every brief", async () => {
242
- const { ctx, model } = scriptedDesk();
243
- await run(
244
- "screen_candidates",
245
- { jobTitle: "Design Systems Engineer", jobDescription: "Storybook, tokens, accessibility." },
246
- ctx,
247
- );
248
- for (const call of model.calls) {
249
- expect(call.prompt).toContain("Title: Design Systems Engineer");
250
- expect(call.prompt).toContain("Storybook, tokens, accessibility.");
251
- }
252
- // A title alone keeps the default's description under the caller's title.
253
- const { ctx: ctx2, model: model2 } = scriptedDesk();
254
- await run("screen_candidates", { jobTitle: "Frontend Engineer" }, ctx2);
255
- expect(model2.calls[0]?.prompt).toContain("Title: Frontend Engineer");
256
- expect(model2.calls[0]?.prompt).toContain("twelve-month contract");
257
- });
347
+ test("fails as a tool when nobody could be scored, and the flow does not move", async () => {
348
+ const { ctx } = scriptedDesk({ failScoring: LEADS.map((one) => one.id) });
258
349
 
259
- test("runs the evaluations through a window, not all at once and not one by one", async () => {
260
- const { model } = scriptedDesk();
261
- let inFlight = 0;
262
- let peak = 0;
263
- // The fake answers on a microtask, so `inFlight` only ever exceeds 1 if the
264
- // fan-out really issued several briefs before awaiting any — and it never
265
- // exceeds the window if the window is real.
266
- const generate = ((options: GenerateOptions) => {
267
- inFlight += 1;
268
- peak = Math.max(peak, inFlight);
269
- return model.generate(options).finally(() => {
270
- inFlight -= 1;
271
- });
272
- }) as GenerateFn;
273
- const ctx = createToolContext({ generate });
350
+ const result = await run(screenCandidates, {}, ctx);
274
351
 
275
- await run("screen_candidates", {}, ctx);
352
+ expect(result).toEqual({ error: expect.stringContaining("gateway said no") });
353
+ expect(at(ctx)).toBe("idle");
354
+ expect(stateOf(ctx)).toEqual(emptyHiring());
355
+ });
276
356
 
277
- expect(LEADS.length).toBeGreaterThan(SCORING_CONCURRENCY);
278
- expect(peak).toBe(SCORING_CONCURRENCY);
357
+ test("a second screening starts over: feedback, rounds, shortlist and drafts are cleared", async () => {
358
+ const { ctx } = await screened();
359
+ await run(rescoreWithFeedback, { feedback: "more TypeScript" }, ctx);
360
+ await run(proceedToEmails, {}, ctx);
361
+ expect(at(ctx)).toBe("emailed");
362
+ expect(stateOf(ctx).drafts).not.toEqual([]);
363
+
364
+ await run(screenCandidates, { jobTitle: "Another role" }, ctx);
365
+
366
+ const state = stateOf(ctx);
367
+ expect(state.feedback).toEqual([]);
368
+ expect(state.rounds).toBe(0);
369
+ expect(state.shortlist).toEqual([]);
370
+ expect(state.drafts).toEqual([]);
371
+ expect(state.job?.title).toBe("Another role");
372
+ expect(at(ctx)).toBe("reviewing");
373
+ });
279
374
  });
280
375
 
281
- test("a second screening in the same step waits: two fan-outs, never interleaved", async () => {
282
- const { model } = scriptedDesk();
283
- let inFlight = 0;
284
- let peak = 0;
285
- const generate = ((options: GenerateOptions) => {
286
- inFlight += 1;
287
- peak = Math.max(peak, inFlight);
288
- return model.generate(options).finally(() => {
289
- inFlight -= 1;
290
- });
291
- }) as GenerateFn;
292
- const ctx = createToolContext({ generate });
293
-
294
- await Promise.all([
295
- run("screen_candidates", {}, ctx),
296
- run("screen_candidates", { jobTitle: "Another role" }, ctx),
297
- ]);
298
-
299
- // Both screenings really ran, and the window never held two fan-outs at
300
- // once — which is what the screening lock buys. Without it the second reads
301
- // and writes the table across the first's awaits, and the ranking the
302
- // caller was just read is not the one the desk now holds.
303
- expect(model.calls).toHaveLength(LEADS.length * 2);
304
- expect(peak).toBe(SCORING_CONCURRENCY);
305
- const state = stateOf(ctx);
306
- expect(Object.keys(state.scores)).toHaveLength(LEADS.length);
307
- expect(state.unscored).toEqual([]);
308
- expect(at(ctx)).toBe("reviewing");
309
- });
376
+ // ─── The router's option 2: rescore_with_feedback ────────────────────────────
310
377
 
311
- test("one applicant the evaluator could not score does not sink the screening", async () => {
312
- const { ctx } = scriptedDesk({ failScoring: ["c07"] });
313
-
314
- const result = expectToolOk(await runTool(screenCandidates, {}, ctx));
315
-
316
- expect(result.screened).toBe(LEADS.length - 1);
317
- expect(result.unscored).toBe("Sofia Lindqvist");
318
- expect(result.message).toMatch(/could not be scored/);
319
- // Not ranked at zero — absent, and named. A zero would read as a verdict.
320
- expect(result.top.map((one) => one.name)).toEqual([
321
- "Priya Raman",
322
- "Tom Whitfield",
323
- "Mei Tanaka",
324
- ]);
325
- expect(stateOf(ctx).unscored).toEqual(["c07"]);
326
- expect(hiringView(stateOf(ctx)).unscored).toEqual(["Sofia Lindqvist"]);
327
- });
378
+ describe("rescore_with_feedback (their option 2)", () => {
379
+ test("re-scores everyone with the feedback in every brief, and reports who moved", async () => {
380
+ const { ctx, model, script } = await screened();
381
+ // The evaluator reads the feedback, so the table changes with it.
382
+ script.scores = TYPESCRIPT_SCORES;
328
383
 
329
- test("fails as a tool when nobody could be scored, and the flow does not move", async () => {
330
- const { ctx } = scriptedDesk({ failScoring: LEADS.map((one) => one.id) });
384
+ const moved = landed(
385
+ await run(rescoreWithFeedback, { feedback: "Weight TypeScript much more heavily" }, ctx),
386
+ );
331
387
 
332
- const result = await run("screen_candidates", {}, ctx);
388
+ expect(model.calls).toHaveLength(LEADS.length);
389
+ for (const call of model.calls) {
390
+ expect(call.prompt).toContain("hiring manager has reviewed");
391
+ expect(call.prompt).toContain("- Weight TypeScript much more heavily");
392
+ }
393
+ expect(moved.state).toBe("reviewing");
394
+ expect(moved.result.round).toBe(1);
395
+ expect(moved.result.roundsLeft).toBe(MAX_FEEDBACK_ROUNDS - 1);
396
+ expect(moved.result.top.map((one) => one.name)).toEqual([
397
+ "Priya Raman",
398
+ "Aisha Bello",
399
+ "Mei Tanaka",
400
+ ]);
401
+ expect(moved.result.promoted).toEqual(["Aisha Bello", "Mei Tanaka"]);
402
+ expect(moved.result.dropped).toEqual(["Sofia Lindqvist", "Tom Whitfield"]);
403
+ expect(moved.result.message).toMatch(/moved in \(Aisha Bello, Mei Tanaka\)/);
404
+ expect(stateOf(ctx).rounds).toBe(1);
405
+ });
333
406
 
334
- expect(result).toEqual({ error: expect.stringContaining("gateway said no") });
335
- expect(at(ctx)).toBe("idle");
336
- expect(stateOf(ctx)).toEqual(emptyHiring());
337
- });
407
+ test("feedback ACCUMULATES across rounds, in order", async () => {
408
+ const { ctx, model } = await screened();
409
+
410
+ await run(rescoreWithFeedback, { feedback: "more TypeScript" }, ctx);
411
+ await run(rescoreWithFeedback, { feedback: "less weight on years of experience" }, ctx);
412
+
413
+ expect(stateOf(ctx).feedback).toEqual([
414
+ "more TypeScript",
415
+ "less weight on years of experience",
416
+ ]);
417
+ const last = model.calls.at(-1)?.prompt ?? "";
418
+ // Theirs overwrote; a caller who said both meant both, and in that order.
419
+ expect(last.indexOf("- more TypeScript")).toBeGreaterThan(-1);
420
+ expect(last.indexOf("- more TypeScript")).toBeLessThan(
421
+ last.indexOf("- less weight on years of experience"),
422
+ );
423
+ expect(stateOf(ctx).rounds).toBe(2);
424
+ });
338
425
 
339
- test("a second screening starts over: feedback, rounds, shortlist and drafts are cleared", async () => {
340
- const { ctx } = await screened();
341
- await run("rescore_with_feedback", { feedback: "more TypeScript" }, ctx);
342
- await run("proceed_to_emails", {}, ctx);
343
- expect(at(ctx)).toBe("emailed");
344
- expect(stateOf(ctx).drafts).not.toEqual([]);
345
-
346
- await run("screen_candidates", { jobTitle: "Another role" }, ctx);
347
-
348
- const state = stateOf(ctx);
349
- expect(state.feedback).toEqual([]);
350
- expect(state.rounds).toBe(0);
351
- expect(state.shortlist).toEqual([]);
352
- expect(state.drafts).toEqual([]);
353
- expect(state.job?.title).toBe("Another role");
354
- expect(at(ctx)).toBe("reviewing");
355
- });
356
- });
426
+ test("two re-scores in the same step count TWO rounds, and neither loses its feedback", async () => {
427
+ const { ctx, model } = await screened();
428
+
429
+ await Promise.all([
430
+ run(rescoreWithFeedback, { feedback: "more TypeScript" }, ctx),
431
+ run(rescoreWithFeedback, { feedback: "less weight on years of experience" }, ctx),
432
+ ]);
433
+
434
+ // Read-modify-write across a fan-out: without the lock both read
435
+ // `rounds: 0`, both write `rounds: 1`, and one round of twelve model calls
436
+ // the caller was charged for is uncounted — which also unbounds the bound.
437
+ const state = stateOf(ctx);
438
+ expect(state.rounds).toBe(2);
439
+ expect(state.feedback).toHaveLength(2);
440
+ expect(state.feedback).toEqual(
441
+ expect.arrayContaining(["more TypeScript", "less weight on years of experience"]),
442
+ );
443
+ expect(model.calls).toHaveLength(LEADS.length * 2);
444
+ // The second round's briefs carry BOTH pieces of feedback, which is only
445
+ // true if it read the trail the first round had already written.
446
+ const last = model.calls.at(-1)?.prompt ?? "";
447
+ expect(last).toContain("- more TypeScript");
448
+ expect(last).toContain("- less weight on years of experience");
449
+ });
357
450
 
358
- // ─── The router's option 2: rescore_with_feedback ────────────────────────────
451
+ test("says so when the same three people are still on top", async () => {
452
+ const { ctx } = await screened();
453
+ const same = landed(await run(rescoreWithFeedback, { feedback: "nothing really" }, ctx));
454
+ expect(same.result.promoted).toEqual([]);
455
+ expect(same.result.message).toMatch(/same people/);
456
+ });
359
457
 
360
- interface RescoreResult {
361
- round: number;
362
- roundsLeft: number;
363
- feedbackApplied: string[];
364
- top: { name: string; score: number }[];
365
- promoted: string[];
366
- dropped: string[];
367
- message: string;
368
- }
458
+ test("refuses blank feedback without spending the evaluator", async () => {
459
+ const { ctx, model } = await screened();
460
+ const refused = await run(rescoreWithFeedback, { feedback: " " }, ctx);
461
+ expect(refused).toEqual({ error: expect.stringContaining("what the caller wants changed") });
462
+ expect(model.calls).toEqual([]);
463
+ expect(stateOf(ctx).rounds).toBe(0);
464
+ });
369
465
 
370
- describe("rescore_with_feedback (their option 2)", () => {
371
- test("re-scores everyone with the feedback in every brief, and reports who moved", async () => {
372
- const { ctx, model, script } = await screened();
373
- // The evaluator reads the feedback, so the table changes with it.
374
- script.scores = TYPESCRIPT_SCORES;
375
-
376
- const moved = expectDialogOk<RescoreResult>(
377
- await run("rescore_with_feedback", { feedback: "Weight TypeScript much more heavily" }, ctx),
378
- );
379
-
380
- expect(model.calls).toHaveLength(LEADS.length);
381
- for (const call of model.calls) {
382
- expect(call.prompt).toContain("hiring manager has reviewed");
383
- expect(call.prompt).toContain("- Weight TypeScript much more heavily");
384
- }
385
- expect(moved.state).toBe("reviewing");
386
- expect(moved.result.round).toBe(1);
387
- expect(moved.result.roundsLeft).toBe(MAX_FEEDBACK_ROUNDS - 1);
388
- expect(moved.result.top.map((one) => one.name)).toEqual([
389
- "Priya Raman",
390
- "Aisha Bello",
391
- "Mei Tanaka",
392
- ]);
393
- expect(moved.result.promoted).toEqual(["Aisha Bello", "Mei Tanaka"]);
394
- expect(moved.result.dropped).toEqual(["Sofia Lindqvist", "Tom Whitfield"]);
395
- expect(moved.result.message).toMatch(/moved in \(Aisha Bello, Mei Tanaka\)/);
396
- expect(stateOf(ctx).rounds).toBe(1);
397
- });
466
+ test("is BOUNDED: past MAX_FEEDBACK_ROUNDS it refuses, naming the two ways out", async () => {
467
+ const { ctx, model } = await screened();
468
+ for (let round = 1; round <= MAX_FEEDBACK_ROUNDS; round++) {
469
+ const again = landed(await run(rescoreWithFeedback, { feedback: `round ${round}` }, ctx));
470
+ expect(again.result.roundsLeft).toBe(MAX_FEEDBACK_ROUNDS - round);
471
+ }
472
+ // The last accepted round says it was the last.
473
+ model.calls.length = 0;
474
+
475
+ const refused = await run(rescoreWithFeedback, { feedback: "one more" }, ctx);
476
+
477
+ expect(isToolFailure(refused)).toBe(true);
478
+ if (isToolFailure(refused)) {
479
+ expect(refused.error).toMatch(/limit is 3/);
480
+ expect(refused.error).toMatch(/proceed to emails/);
481
+ expect(refused.error).toMatch(/stop/);
482
+ }
483
+ // No model spent, no round counted, and the position did not move on a failure.
484
+ expect(model.calls).toEqual([]);
485
+ expect(stateOf(ctx).rounds).toBe(MAX_FEEDBACK_ROUNDS);
486
+ expect(stateOf(ctx).feedback).toHaveLength(MAX_FEEDBACK_ROUNDS);
487
+ expect(at(ctx)).toBe("reviewing");
488
+ });
398
489
 
399
- test("feedback ACCUMULATES across rounds, in order", async () => {
400
- const { ctx, model } = await screened();
401
-
402
- await run("rescore_with_feedback", { feedback: "more TypeScript" }, ctx);
403
- await run("rescore_with_feedback", { feedback: "less weight on years of experience" }, ctx);
404
-
405
- expect(stateOf(ctx).feedback).toEqual([
406
- "more TypeScript",
407
- "less weight on years of experience",
408
- ]);
409
- const last = model.calls.at(-1)?.prompt ?? "";
410
- // Theirs overwrote; a caller who said both meant both, and in that order.
411
- expect(last.indexOf("- more TypeScript")).toBeGreaterThan(-1);
412
- expect(last.indexOf("- more TypeScript")).toBeLessThan(
413
- last.indexOf("- less weight on years of experience"),
414
- );
415
- expect(stateOf(ctx).rounds).toBe(2);
416
- });
490
+ test("tells the desk the last round was the last", async () => {
491
+ const { ctx } = await screened();
492
+ let last: { message: string } | undefined;
493
+ for (let round = 1; round <= MAX_FEEDBACK_ROUNDS; round++) {
494
+ last = landed(await run(rescoreWithFeedback, { feedback: `round ${round}` }, ctx)).result;
495
+ }
496
+ expect(last?.message).toMatch(/last round of feedback/);
497
+ });
417
498
 
418
- test("two re-scores in the same step count TWO rounds, and neither loses its feedback", async () => {
419
- const { ctx, model } = await screened();
420
-
421
- await Promise.all([
422
- run("rescore_with_feedback", { feedback: "more TypeScript" }, ctx),
423
- run("rescore_with_feedback", { feedback: "less weight on years of experience" }, ctx),
424
- ]);
425
-
426
- // Read-modify-write across a fan-out: without the lock both read
427
- // `rounds: 0`, both write `rounds: 1`, and one round of twelve model calls
428
- // the caller was charged for is uncounted — which also unbounds the bound.
429
- const state = stateOf(ctx);
430
- expect(state.rounds).toBe(2);
431
- expect(state.feedback).toHaveLength(2);
432
- expect(state.feedback).toEqual(
433
- expect.arrayContaining(["more TypeScript", "less weight on years of experience"]),
434
- );
435
- expect(model.calls).toHaveLength(LEADS.length * 2);
436
- // The second round's briefs carry BOTH pieces of feedback, which is only
437
- // true if it read the trail the first round had already written.
438
- const last = model.calls.at(-1)?.prompt ?? "";
439
- expect(last).toContain("- more TypeScript");
440
- expect(last).toContain("- less weight on years of experience");
441
- });
499
+ test("keeps the previous ranking when nobody could be re-scored", async () => {
500
+ const { ctx, script } = await screened();
501
+ const before = stateOf(ctx);
502
+ script.failScoring = LEADS.map((one) => one.id);
442
503
 
443
- test("says so when the same three people are still on top", async () => {
444
- const { ctx } = await screened();
445
- const same = expectDialogOk<RescoreResult>(
446
- await run("rescore_with_feedback", { feedback: "nothing really" }, ctx),
447
- );
448
- expect(same.result.promoted).toEqual([]);
449
- expect(same.result.message).toMatch(/same people/);
450
- });
504
+ const result = await run(rescoreWithFeedback, { feedback: "more TypeScript" }, ctx);
451
505
 
452
- test("refuses blank feedback without spending the evaluator", async () => {
453
- const { ctx, model } = await screened();
454
- const refused = await run("rescore_with_feedback", { feedback: " " }, ctx);
455
- expect(refused).toEqual({ error: expect.stringContaining("what the caller wants changed") });
456
- expect(model.calls).toEqual([]);
457
- expect(stateOf(ctx).rounds).toBe(0);
506
+ expect(result).toEqual({ error: expect.stringContaining("ranking is unchanged") });
507
+ expect(stateOf(ctx).scores).toEqual(before.scores);
508
+ expect(stateOf(ctx).rounds).toBe(0);
509
+ expect(stateOf(ctx).feedback).toEqual([]);
510
+ expect(at(ctx)).toBe("reviewing");
511
+ });
458
512
  });
459
513
 
460
- test("is BOUNDED: past MAX_FEEDBACK_ROUNDS it refuses, naming the two ways out", async () => {
461
- const { ctx, model } = await screened();
462
- for (let round = 1; round <= MAX_FEEDBACK_ROUNDS; round++) {
463
- const again = expectDialogOk<RescoreResult>(
464
- await run("rescore_with_feedback", { feedback: `round ${round}` }, ctx),
465
- );
466
- expect(again.result.roundsLeft).toBe(MAX_FEEDBACK_ROUNDS - round);
467
- }
468
- // The last accepted round says it was the last.
469
- model.calls.length = 0;
470
-
471
- const refused = await run("rescore_with_feedback", { feedback: "one more" }, ctx);
472
-
473
- expect(isToolFailure(refused)).toBe(true);
474
- if (isToolFailure(refused)) {
475
- expect(refused.error).toMatch(/limit is 3/);
476
- expect(refused.error).toMatch(/proceed to emails/);
477
- expect(refused.error).toMatch(/stop/);
478
- }
479
- // No model spent, no round counted, and the position did not move on a failure.
480
- expect(model.calls).toEqual([]);
481
- expect(stateOf(ctx).rounds).toBe(MAX_FEEDBACK_ROUNDS);
482
- expect(stateOf(ctx).feedback).toHaveLength(MAX_FEEDBACK_ROUNDS);
483
- expect(at(ctx)).toBe("reviewing");
484
- });
514
+ // ─── The router's option 3: proceed_to_emails ────────────────────────────────
485
515
 
486
- test("tells the desk the last round was the last", async () => {
487
- const { ctx } = await screened();
488
- let last: RescoreResult | undefined;
489
- for (let round = 1; round <= MAX_FEEDBACK_ROUNDS; round++) {
490
- last = expectDialogOk<RescoreResult>(
491
- await run("rescore_with_feedback", { feedback: `round ${round}` }, ctx),
492
- ).result;
493
- }
494
- expect(last?.message).toMatch(/last round of feedback/);
495
- });
516
+ describe("proceed_to_emails (their option 3 → write_and_save_emails)", () => {
517
+ test("writes EVERY applicant an email through the coordinator, inviting the top three", async () => {
518
+ const { ctx, desk } = await screened();
496
519
 
497
- test("keeps the previous ranking when nobody could be re-scored", async () => {
498
- const { ctx, script } = await screened();
499
- const before = stateOf(ctx);
500
- script.failScoring = LEADS.map((one) => one.id);
520
+ const done = landed(await run(proceedToEmails, {}, ctx));
501
521
 
502
- const result = await run("rescore_with_feedback", { feedback: "more TypeScript" }, ctx);
522
+ expect(desk.calls).toHaveLength(LEADS.length);
523
+ expect(new Set(desk.calls.map((call) => call.subagent.name))).toEqual(
524
+ new Set(["hr-coordinator"]),
525
+ );
526
+ // Their `proceed_with_candidate`: True for the shortlist, False for everyone else.
527
+ const proceeding = desk.calls
528
+ .filter((call) => call.task.includes("PROCEEDING WITH CANDIDATE: True"))
529
+ .map((call) => call.task.match(/^Name: (.+)$/m)?.[1]);
530
+ // In ROSTER order — the fan-out walks the roster, not the ranking.
531
+ expect(proceeding).toEqual(["Priya Raman", "Tom Whitfield", "Sofia Lindqvist"]);
532
+ expect(done.state).toBe("emailed");
533
+ expect(done.done).toBe(false);
534
+ expect(done.result.invited).toEqual([
535
+ "1. Priya Raman (87)",
536
+ "2. Sofia Lindqvist (84)",
537
+ "3. Tom Whitfield (71)",
538
+ ]);
539
+ expect(done.result.declined).toBe(LEADS.length - SHORTLIST_SIZE);
540
+ expect(done.result.drafted).toBe(LEADS.length);
541
+ expect(done.result.needsLook).toEqual([]);
542
+ expect(stateOf(ctx).shortlist).toEqual(["c01", "c07", "c04"]);
543
+ });
503
544
 
504
- expect(result).toEqual({ error: expect.stringContaining("ranking is unchanged") });
505
- expect(stateOf(ctx).scores).toEqual(before.scores);
506
- expect(stateOf(ctx).rounds).toBe(0);
507
- expect(stateOf(ctx).feedback).toEqual([]);
508
- expect(at(ctx)).toBe("reviewing");
509
- });
510
- });
545
+ test("keeps each draft's subject apart from its body, and the role in the brief", async () => {
546
+ const { ctx, desk } = await screened();
547
+ await run(proceedToEmails, {}, ctx);
548
+ const priya = stateOf(ctx).drafts.find((draft) => draft.candidateId === "c01");
549
+ expect(priya).toMatchObject({
550
+ proceed: true,
551
+ subject: "Next steps on your application",
552
+ accepted: true,
553
+ });
554
+ expect(priya?.body).toMatch(/^Hi Priya Raman,/);
555
+ expect(priya?.body).not.toMatch(/Subject:/);
556
+ // Theirs never told the coordinator which job; every brief here names it.
557
+ for (const call of desk.calls)
558
+ expect(call.task).toContain(`ROLE APPLIED FOR: ${DEFAULT_JOB.title}`);
559
+ });
511
560
 
512
- // ─── The router's option 3: proceed_to_emails ────────────────────────────────
561
+ test("a spoken shortlist replaces the top three, by name or by position", async () => {
562
+ const { ctx, desk } = await screened();
513
563
 
514
- interface ProceedResult {
515
- invited: string[];
516
- declined: number;
517
- drafted: number;
518
- failed: string[];
519
- needsLook: string[];
520
- message: string;
521
- }
564
+ const done = landed(
565
+ await run(proceedToEmails, { shortlist: ["Priya", "the fifth one", "Mehta"] }, ctx),
566
+ );
522
567
 
523
- describe("proceed_to_emails (their option 3 → write_and_save_emails)", () => {
524
- test("writes EVERY applicant an email through the coordinator, inviting the top three", async () => {
525
- const { ctx, desk } = await screened();
526
-
527
- const done = expectDialogOk<ProceedResult>(await run("proceed_to_emails", {}, ctx));
528
-
529
- expect(desk.calls).toHaveLength(LEADS.length);
530
- expect(new Set(desk.calls.map((call) => call.subagent.name))).toEqual(
531
- new Set(["hr-coordinator"]),
532
- );
533
- // Their `proceed_with_candidate`: True for the shortlist, False for everyone else.
534
- const proceeding = desk.calls
535
- .filter((call) => call.task.includes("PROCEEDING WITH CANDIDATE: True"))
536
- .map((call) => call.task.match(/^Name: (.+)$/m)?.[1]);
537
- // In ROSTER order — the fan-out walks the roster, not the ranking.
538
- expect(proceeding).toEqual(["Priya Raman", "Tom Whitfield", "Sofia Lindqvist"]);
539
- expect(done.state).toBe("emailed");
540
- expect(done.done).toBe(false);
541
- expect(done.result.invited).toEqual([
542
- "1. Priya Raman (87)",
543
- "2. Sofia Lindqvist (84)",
544
- "3. Tom Whitfield (71)",
545
- ]);
546
- expect(done.result.declined).toBe(LEADS.length - SHORTLIST_SIZE);
547
- expect(done.result.drafted).toBe(LEADS.length);
548
- expect(done.result.needsLook).toEqual([]);
549
- expect(stateOf(ctx).shortlist).toEqual(["c01", "c07", "c04"]);
550
- });
568
+ expect(done.result.invited).toEqual([
569
+ "1. Priya Raman (87)",
570
+ "5. Aisha Bello (66)",
571
+ "8. Rahul Mehta (47)",
572
+ ]);
573
+ const proceeding = desk.calls.filter((call) =>
574
+ call.task.includes("PROCEEDING WITH CANDIDATE: True"),
575
+ );
576
+ expect(proceeding).toHaveLength(3);
577
+ expect(stateOf(ctx).shortlist).toEqual(["c01", "c05", "c08"]);
578
+ });
551
579
 
552
- test("keeps each draft's subject apart from its body, and the role in the brief", async () => {
553
- const { ctx, desk } = await screened();
554
- await run("proceed_to_emails", {}, ctx);
555
- const priya = stateOf(ctx).drafts.find((draft) => draft.candidateId === "c01");
556
- expect(priya).toMatchObject({
557
- proceed: true,
558
- subject: "Next steps on your application",
559
- accepted: true,
560
- });
561
- expect(priya?.body).toMatch(/^Hi Priya Raman,/);
562
- expect(priya?.body).not.toMatch(/Subject:/);
563
- // Theirs never told the coordinator which job; every brief here names it.
564
- for (const call of desk.calls)
565
- expect(call.task).toContain(`ROLE APPLIED FOR: ${DEFAULT_JOB.title}`);
566
- });
580
+ test("names the same person twice as one invitation", async () => {
581
+ const { ctx } = await screened();
582
+ const done = landed(await run(proceedToEmails, { shortlist: ["Priya", "Raman"] }, ctx));
583
+ expect(done.result.invited).toEqual(["1. Priya Raman (87)"]);
584
+ });
567
585
 
568
- test("a spoken shortlist replaces the top three, by name or by position", async () => {
569
- const { ctx, desk } = await screened();
570
-
571
- const done = expectDialogOk<ProceedResult>(
572
- await run("proceed_to_emails", { shortlist: ["Priya", "the fifth one", "Mehta"] }, ctx),
573
- );
574
-
575
- expect(done.result.invited).toEqual([
576
- "1. Priya Raman (87)",
577
- "5. Aisha Bello (66)",
578
- "8. Rahul Mehta (47)",
579
- ]);
580
- const proceeding = desk.calls.filter((call) =>
581
- call.task.includes("PROCEEDING WITH CANDIDATE: True"),
582
- );
583
- expect(proceeding).toHaveLength(3);
584
- expect(stateOf(ctx).shortlist).toEqual(["c01", "c05", "c08"]);
585
- });
586
+ test("never guesses: a name that matches nobody is refused, listing the ranking, before any email", async () => {
587
+ const { ctx, desk } = await screened();
586
588
 
587
- test("names the same person twice as one invitation", async () => {
588
- const { ctx } = await screened();
589
- const done = expectDialogOk<ProceedResult>(
590
- await run("proceed_to_emails", { shortlist: ["Priya", "Raman"] }, ctx),
591
- );
592
- expect(done.result.invited).toEqual(["1. Priya Raman (87)"]);
593
- });
589
+ const refused = await run(proceedToEmails, { shortlist: ["Priya", "Zelda"] }, ctx);
594
590
 
595
- test("never guesses: a name that matches nobody is refused, listing the ranking, before any email", async () => {
596
- const { ctx, desk } = await screened();
591
+ expect(isToolFailure(refused)).toBe(true);
592
+ if (isToolFailure(refused)) expect(refused.error).toContain("Priya Raman (87)");
593
+ expect(desk.calls).toEqual([]);
594
+ expect(at(ctx)).toBe("reviewing");
595
+ expect(stateOf(ctx).drafts).toEqual([]);
596
+ });
597
597
 
598
- const refused = await run("proceed_to_emails", { shortlist: ["Priya", "Zelda"] }, ctx);
598
+ test("a draft the guardrail never accepted comes back flagged, not hidden", async () => {
599
+ const { ctx } = await screened({
600
+ email: (call) =>
601
+ call.task.includes("Name: Tom Whitfield")
602
+ ? { text: "Hi Tom, let's talk soon.", complaint: "no subject line" }
603
+ : emailFor(call),
604
+ });
599
605
 
600
- expect(isToolFailure(refused)).toBe(true);
601
- if (isToolFailure(refused)) expect(refused.error).toContain("Priya Raman (87)");
602
- expect(desk.calls).toEqual([]);
603
- expect(at(ctx)).toBe("reviewing");
604
- expect(stateOf(ctx).drafts).toEqual([]);
605
- });
606
+ const done = landed(await run(proceedToEmails, {}, ctx));
606
607
 
607
- test("a draft the guardrail never accepted comes back flagged, not hidden", async () => {
608
- const { ctx } = await screened({
609
- email: (call) =>
610
- call.task.includes("Name: Tom Whitfield")
611
- ? { text: "Hi Tom, let's talk soon.", complaint: "no subject line" }
612
- : emailFor(call),
608
+ expect(done.result.needsLook).toEqual(["Tom Whitfield"]);
609
+ expect(done.result.message).toMatch(/need a look/);
610
+ const tom = stateOf(ctx).drafts.find((draft) => draft.candidateId === "c04");
611
+ expect(tom).toMatchObject({ accepted: false, subject: "(no subject)" });
612
+ expect(
613
+ hiringView(stateOf(ctx)).drafts.find((d) => d.name === "Tom Whitfield")?.accepted,
614
+ ).toBe(false);
613
615
  });
614
616
 
615
- const done = expectDialogOk<ProceedResult>(await run("proceed_to_emails", {}, ctx));
616
-
617
- expect(done.result.needsLook).toEqual(["Tom Whitfield"]);
618
- expect(done.result.message).toMatch(/need a look/);
619
- const tom = stateOf(ctx).drafts.find((draft) => draft.candidateId === "c04");
620
- expect(tom).toMatchObject({ accepted: false, subject: "(no subject)" });
621
- expect(hiringView(stateOf(ctx)).drafts.find((d) => d.name === "Tom Whitfield")?.accepted).toBe(
622
- false,
623
- );
624
- });
625
-
626
- test("one email the coordinator could not write does not sink the rest", async () => {
627
- const { ctx } = await screened({ failEmail: ["Elena Vasquez"] });
617
+ test("one email the coordinator could not write does not sink the rest", async () => {
618
+ const { ctx } = await screened({ failEmail: ["Elena Vasquez"] });
628
619
 
629
- const done = expectDialogOk<ProceedResult>(await run("proceed_to_emails", {}, ctx));
620
+ const done = landed(await run(proceedToEmails, {}, ctx));
630
621
 
631
- expect(done.result.drafted).toBe(LEADS.length - 1);
632
- expect(done.result.failed).toEqual(["Elena Vasquez"]);
633
- expect(done.result.message).toMatch(/No email could be written for Elena Vasquez/);
634
- expect(done.state).toBe("emailed");
635
- });
622
+ expect(done.result.drafted).toBe(LEADS.length - 1);
623
+ expect(done.result.failed).toEqual(["Elena Vasquez"]);
624
+ expect(done.result.message).toMatch(/No email could be written for Elena Vasquez/);
625
+ expect(done.state).toBe("emailed");
626
+ });
636
627
 
637
- test("fails as a tool when no email could be written, and the flow does not move", async () => {
638
- const { ctx } = await screened({ failEmail: LEADS.map((one) => one.name) });
628
+ test("fails as a tool when no email could be written, and the flow does not move", async () => {
629
+ const { ctx } = await screened({ failEmail: LEADS.map((one) => one.name) });
639
630
 
640
- const result = await run("proceed_to_emails", {}, ctx);
631
+ const result = await run(proceedToEmails, {}, ctx);
641
632
 
642
- expect(result).toEqual({ error: expect.stringContaining("coordinator timed out") });
643
- expect(at(ctx)).toBe("reviewing");
644
- expect(stateOf(ctx).drafts).toEqual([]);
645
- });
633
+ expect(result).toEqual({ error: expect.stringContaining("coordinator timed out") });
634
+ expect(at(ctx)).toBe("reviewing");
635
+ expect(stateOf(ctx).drafts).toEqual([]);
636
+ });
646
637
 
647
- test("refuses a second round of emails for one ranking", async () => {
648
- const { ctx, desk } = await screened();
649
- await run("proceed_to_emails", {}, ctx);
650
- desk.calls.length = 0;
651
-
652
- // `emailed` accepts no PROCEEDED, so the gate — not the body — is what
653
- // refuses. Asserted through the SDK's own unwrap, which fails HERE if the
654
- // call succeeded instead of skipping every assertion after it.
655
- const refused = expectDialogRefused(await run("proceed_to_emails", {}, ctx), "emailed");
656
- expect(refused.error).toMatch(/read_email/);
657
- expect(desk.calls).toEqual([]);
638
+ test("refuses a second round of emails for one ranking", async () => {
639
+ const { ctx, desk } = await screened();
640
+ await run(proceedToEmails, {}, ctx);
641
+ desk.calls.length = 0;
642
+
643
+ // `emailed` accepts no PROCEEDED, so the gate — not the body — is what
644
+ // refuses. Asserted through the SDK's own unwrap, which fails HERE if the
645
+ // call succeeded instead of skipping every assertion after it.
646
+ const refused = expectDialogRefused(await run(proceedToEmails, {}, ctx), "emailed");
647
+ expect(refused.error).toMatch(/read_email/);
648
+ expect(desk.calls).toEqual([]);
649
+ });
658
650
  });
659
- });
660
651
 
661
- // ─── The wait ────────────────────────────────────────────────────────────────
652
+ // ─── The wait ────────────────────────────────────────────────────────────────
662
653
 
663
- /** What a tool sent the browser, filtered to the ticker's own event. */
664
- const progressIn = (ctx: TestToolContext): SentEvent[] =>
665
- ctx.sent.filter((sent) => sent.event === SCREENING_PROGRESS);
654
+ /** What a tool sent the browser, filtered to the ticker's own event. */
655
+ const progressIn = (ctx: TestToolContext): SentEvent[] =>
656
+ ctx.sent.filter((sent) => sent.event === SCREENING_PROGRESS);
666
657
 
667
- /** The ticks a fan-out over the roster should have produced, in order. */
668
- const everyTick = (phase: "scoring" | "writing") =>
669
- LEADS.map((_, index) => ({ phase, done: index + 1, total: LEADS.length }));
658
+ /** The ticks a fan-out over the roster should have produced, in order. */
659
+ const everyTick = (phase: "scoring" | "writing") =>
660
+ LEADS.map((_, index) => ({ phase, done: index + 1, total: LEADS.length }));
670
661
 
671
- describe("the progress ticker", () => {
672
- test("ticks once per applicant while the evaluator runs, ending on the total", async () => {
673
- const { ctx } = scriptedDesk();
662
+ describe("the progress ticker", () => {
663
+ test("ticks once per applicant while the evaluator runs, ending on the total", async () => {
664
+ const { ctx } = scriptedDesk();
674
665
 
675
- await run("screen_candidates", {}, ctx);
666
+ await run(screenCandidates, {}, ctx);
676
667
 
677
- // A MOMENT rather than state: the slot is still written once, at the end,
678
- // so nothing ever reads half a screening — see `shared.ts`.
679
- expect(progressIn(ctx).map((tick) => tick.data)).toEqual(everyTick("scoring"));
680
- expect(stateOf(ctx).candidates).toHaveLength(LEADS.length);
681
- });
668
+ // A MOMENT rather than state: the slot is still written once, at the end,
669
+ // so nothing ever reads half a screening — see `shared.ts`.
670
+ expect(progressIn(ctx).map((tick) => tick.data)).toEqual(everyTick("scoring"));
671
+ expect(stateOf(ctx).candidates).toHaveLength(LEADS.length);
672
+ });
682
673
 
683
- test("an applicant the evaluator refused ticks too, so the count reaches the total", async () => {
684
- const { ctx } = scriptedDesk({ failScoring: ["c07"] });
674
+ test("an applicant the evaluator refused ticks too, so the count reaches the total", async () => {
675
+ const { ctx } = scriptedDesk({ failScoring: ["c07"] });
685
676
 
686
- await run("screen_candidates", {}, ctx);
677
+ await run(screenCandidates, {}, ctx);
687
678
 
688
- // A ticker that stopped at eleven of twelve reads as a hang, and the wait
689
- // for that applicant really is over.
690
- expect(progressIn(ctx)).toHaveLength(LEADS.length);
691
- });
679
+ // A ticker that stopped at eleven of twelve reads as a hang, and the wait
680
+ // for that applicant really is over.
681
+ expect(progressIn(ctx)).toHaveLength(LEADS.length);
682
+ });
692
683
 
693
- test("the coordinator's fan-out ticks under its own phase", async () => {
694
- const { ctx } = await screened();
695
- ctx.sent.length = 0;
684
+ test("the coordinator's fan-out ticks under its own phase", async () => {
685
+ const { ctx } = await screened();
686
+ ctx.sent.length = 0;
696
687
 
697
- await run("proceed_to_emails", {}, ctx);
688
+ await run(proceedToEmails, {}, ctx);
698
689
 
699
- expect(progressIn(ctx).map((tick) => tick.data)).toEqual(everyTick("writing"));
690
+ expect(progressIn(ctx).map((tick) => tick.data)).toEqual(everyTick("writing"));
691
+ });
700
692
  });
701
- });
702
693
 
703
- // ─── The reads ───────────────────────────────────────────────────────────────
694
+ // ─── The reads ───────────────────────────────────────────────────────────────
704
695
 
705
- describe("candidate_details", () => {
706
- test("has nothing to say before a screening", async () => {
707
- const { ctx } = scriptedDesk();
708
- expect(await run("candidate_details", { candidate: "Priya" }, ctx)).toEqual({
709
- error: expect.stringContaining("screen_candidates"),
696
+ describe("candidate_details", () => {
697
+ test("has nothing to say before a screening", async () => {
698
+ const { ctx } = scriptedDesk();
699
+ expect(await run(candidateDetails, { candidate: "Priya" }, ctx)).toEqual({
700
+ error: expect.stringContaining("screen_candidates"),
701
+ });
710
702
  });
711
- });
712
703
 
713
- test("resolves 'the second one' against the RANKING the caller was read", async () => {
714
- const { ctx } = await screened();
715
- const second = expectToolOk(
716
- await runTool(candidateDetails, { candidate: "the second one" }, ctx),
717
- );
718
- expect(second.rank).toBe(2);
719
- expect(second.name).toBe(nameAt(ctx, 2));
720
- expect(second.score).toBe(84);
721
- expect(second.bio).toMatch(/Stockholm/);
722
- expect(second.emailDrafted).toBeNull();
723
- });
704
+ test("resolves 'the second one' against the RANKING the caller was read", async () => {
705
+ const { ctx } = await screened();
706
+ const second = expectToolOk(
707
+ await run(candidateDetails, { candidate: "the second one" }, ctx),
708
+ );
709
+ expect(second.rank).toBe(2);
710
+ expect(second.name).toBe(nameAt(ctx, 2));
711
+ expect(second.score).toBe(84);
712
+ expect(second.bio).toMatch(/Stockholm/);
713
+ expect(second.emailDrafted).toBeNull();
714
+ });
724
715
 
725
- test("resolves a surname, and reports the draft once one exists", async () => {
726
- const { ctx } = await screened();
727
- await run("proceed_to_emails", {}, ctx);
728
- const rahul = await runTool(candidateDetails, { candidate: "Mehta" }, ctx);
729
- expect(rahul).toMatchObject({
730
- name: "Rahul Mehta",
731
- shortlisted: false,
732
- emailDrafted: "decline",
733
- });
734
- const priya = await runTool(candidateDetails, { candidate: "Priya" }, ctx);
735
- expect(priya).toMatchObject({ shortlisted: true, emailDrafted: "invitation" });
736
- });
716
+ test("resolves a surname, and reports the draft once one exists", async () => {
717
+ const { ctx } = await screened();
718
+ await run(proceedToEmails, {}, ctx);
719
+ const rahul = await run(candidateDetails, { candidate: "Mehta" }, ctx);
720
+ expect(rahul).toMatchObject({
721
+ name: "Rahul Mehta",
722
+ shortlisted: false,
723
+ emailDrafted: "decline",
724
+ });
725
+ const priya = await run(candidateDetails, { candidate: "Priya" }, ctx);
726
+ expect(priya).toMatchObject({ shortlisted: true, emailDrafted: "invitation" });
727
+ });
737
728
 
738
- test("lists the ranking rather than guessing at a name nobody has", async () => {
739
- const { ctx } = await screened();
740
- const refused = await run("candidate_details", { candidate: "Zelda" }, ctx);
741
- expect(isToolFailure(refused)).toBe(true);
742
- if (isToolFailure(refused)) expect(refused.error).toContain("12. Daniel Kowalski (22)");
729
+ test("lists the ranking rather than guessing at a name nobody has", async () => {
730
+ const { ctx } = await screened();
731
+ const refused = await run(candidateDetails, { candidate: "Zelda" }, ctx);
732
+ expect(isToolFailure(refused)).toBe(true);
733
+ if (isToolFailure(refused)) expect(refused.error).toContain("12. Daniel Kowalski (22)");
734
+ });
743
735
  });
744
- });
745
736
 
746
- describe("read_email", () => {
747
- test("says the emails are not written yet, naming the tool that writes them", async () => {
748
- const { ctx } = await screened();
749
- expect(await run("read_email", { candidate: "Priya" }, ctx)).toEqual({
750
- error: expect.stringContaining("proceed_to_emails"),
737
+ describe("read_email", () => {
738
+ test("says the emails are not written yet, naming the tool that writes them", async () => {
739
+ const { ctx } = await screened();
740
+ expect(await run(readEmail, { candidate: "Priya" }, ctx)).toEqual({
741
+ error: expect.stringContaining("proceed_to_emails"),
742
+ });
751
743
  });
752
- });
753
744
 
754
- test("reads back a draft's subject and body, saying which kind it is", async () => {
755
- const { ctx } = await screened();
756
- await run("proceed_to_emails", {}, ctx);
757
- const invite = expectToolOk(await runTool(readEmail, { candidate: "the first one" }, ctx));
758
- expect(invite).toMatchObject({
759
- to: "Priya Raman",
760
- kind: "invitation",
761
- subject: "Next steps on your application",
762
- });
763
- expect(invite.body).toMatch(/availability/);
764
- expect(invite.message).toMatch(/subject line/);
765
- const decline = expectToolOk(await runTool(readEmail, { candidate: "Kowalski" }, ctx));
766
- expect(decline.kind).toBe("decline");
767
- });
745
+ test("reads back a draft's subject and body, saying which kind it is", async () => {
746
+ const { ctx } = await screened();
747
+ await run(proceedToEmails, {}, ctx);
748
+ const invite = expectToolOk(await run(readEmail, { candidate: "the first one" }, ctx));
749
+ expect(invite).toMatchObject({
750
+ to: "Priya Raman",
751
+ kind: "invitation",
752
+ subject: "Next steps on your application",
753
+ });
754
+ expect(invite.body).toMatch(/availability/);
755
+ // Said to the MODEL, per outcome, and stripped from what a page reads.
756
+ expect(instructionOf(invite)).toMatch(/subject line/);
757
+ const decline = expectToolOk(await run(readEmail, { candidate: "Kowalski" }, ctx));
758
+ expect(decline.kind).toBe("decline");
759
+ });
768
760
 
769
- test("warns before reading a draft the guardrail never accepted", async () => {
770
- const { ctx } = await screened({
771
- email: (call) =>
772
- call.task.includes("Name: Priya Raman")
773
- ? { text: "Priya — let's talk.", complaint: "unsigned" }
774
- : emailFor(call),
775
- });
776
- await run("proceed_to_emails", {}, ctx);
777
- const flagged = expectToolOk(await runTool(readEmail, { candidate: "Priya" }, ctx));
778
- expect(flagged.accepted).toBe(false);
779
- expect(flagged.message).toMatch(/did not pass/);
780
- });
761
+ test("warns before reading a draft the guardrail never accepted", async () => {
762
+ const { ctx } = await screened({
763
+ email: (call) =>
764
+ call.task.includes("Name: Priya Raman")
765
+ ? { text: "Priya — let's talk.", complaint: "unsigned" }
766
+ : emailFor(call),
767
+ });
768
+ await run(proceedToEmails, {}, ctx);
769
+ const flagged = expectToolOk(await run(readEmail, { candidate: "Priya" }, ctx));
770
+ expect(flagged.accepted).toBe(false);
771
+ expect(instructionOf(flagged)).toMatch(/did not pass/);
772
+ });
781
773
 
782
- test("says so when the coordinator's run for that person failed", async () => {
783
- const { ctx } = await screened({ failEmail: ["Rahul Mehta"] });
784
- await run("proceed_to_emails", {}, ctx);
785
- expect(await run("read_email", { candidate: "Mehta" }, ctx)).toEqual({
786
- error: expect.stringContaining("No email was written for Rahul Mehta"),
774
+ test("says so when the coordinator's run for that person failed", async () => {
775
+ const { ctx } = await screened({ failEmail: ["Rahul Mehta"] });
776
+ await run(proceedToEmails, {}, ctx);
777
+ expect(await run(readEmail, { candidate: "Mehta" }, ctx)).toEqual({
778
+ error: expect.stringContaining("No email was written for Rahul Mehta"),
779
+ });
787
780
  });
788
781
  });
789
- });
790
782
 
791
- describe("screening_status", () => {
792
- test("reads the stage off the flow, not off the data", async () => {
793
- const { ctx, model } = scriptedDesk();
794
- const idle = await runTool(screeningStatus, ctx);
795
- expect(idle).toMatchObject({
796
- stage: "nothing screened yet",
797
- state: "idle",
798
- screened: 0,
799
- top: [],
800
- });
801
- expect(idle.message).toMatch(/offer to screen/);
802
- expect(model.calls).toEqual([]);
803
- });
783
+ describe("screening_status", () => {
784
+ test("reads the stage off the flow, not off the data", async () => {
785
+ const { ctx, model } = scriptedDesk();
786
+ const answer = await run(screeningStatus, ctx);
787
+ const idle = landed(answer);
788
+ expect(idle.state).toBe("idle");
789
+ expect(idle.result).toMatchObject({ stage: "nothing screened yet", screened: 0, top: [] });
790
+ // What the model is told to do with it rides the envelope as its instruction.
791
+ expect(instructionOf(answer)).toMatch(/offer to screen/);
792
+ expect(model.calls).toEqual([]);
793
+ });
804
794
 
805
- test("sums the screening up once it has run", async () => {
806
- const { ctx } = await screened({ failScoring: ["c06"] });
807
- await run("rescore_with_feedback", { feedback: "more TypeScript" }, ctx);
808
- await run("proceed_to_emails", {}, ctx);
809
- const status = await runTool(screeningStatus, ctx);
810
- expect(status).toMatchObject({
811
- stage: "emails drafted",
812
- job: DEFAULT_JOB.title,
813
- screened: LEADS.length - 1,
814
- unscored: 1,
815
- feedbackRounds: `1 of ${MAX_FEEDBACK_ROUNDS}`,
816
- feedback: ["more TypeScript"],
817
- drafts: LEADS.length,
795
+ test("sums the screening up once it has run", async () => {
796
+ const { ctx } = await screened({ failScoring: ["c06"] });
797
+ await run(rescoreWithFeedback, { feedback: "more TypeScript" }, ctx);
798
+ await run(proceedToEmails, {}, ctx);
799
+ const status = landed(await run(screeningStatus, ctx));
800
+ expect(status.result).toMatchObject({
801
+ stage: "emails drafted",
802
+ job: DEFAULT_JOB.title,
803
+ screened: LEADS.length - 1,
804
+ unscored: 1,
805
+ feedbackRounds: `1 of ${MAX_FEEDBACK_ROUNDS}`,
806
+ feedback: ["more TypeScript"],
807
+ drafts: LEADS.length,
808
+ });
818
809
  });
819
810
  });
820
- });
821
811
 
822
- // ─── The crews ───────────────────────────────────────────────────────────────
823
-
824
- /** The coordinator's guardrail, called the way the runtime calls it. */
825
- const check = (text: string) => runGuardrail(emailWriter, text);
826
-
827
- /** What a verdict COMPLAINED about, or `null` when it accepted.
828
- * `GuardrailVerdict` is `true | string`, and narrowing it here is what stops
829
- * an ACCEPTING verdict being matched against a complaint by accident — a
830
- * stringified `true` matches no pattern in this file and would read as a pass. */
831
- const complaint = (verdict: GuardrailVerdict): string | null => (verdict === true ? null : verdict);
832
-
833
- describe("the crews", () => {
834
- test("render a CrewAI agent through CrewAI's own role_playing template", () => {
835
- expect(crewAgentPrompt(HR_EVALUATION_AGENT)).toBe(
836
- `You are ${HR_EVALUATION_AGENT.role}. ${HR_EVALUATION_AGENT.backstory}\n` +
837
- `Your personal goal is: ${HR_EVALUATION_AGENT.goal}`,
838
- );
839
- expect(EVALUATOR_SYSTEM).toMatch(/^You are Senior HR Evaluation Expert\./);
840
- expect(emailWriter.systemPrompt).toBe(crewAgentPrompt(EMAIL_FOLLOWUP_AGENT));
841
- expect(crewExpectedOutput("X")).toMatch(/expected criteria for your final answer: X/);
842
- });
812
+ // ─── The crews ───────────────────────────────────────────────────────────────
843
813
 
844
- test("the evaluator's brief keeps their anti-round-number rule and asks for two sentences", () => {
845
- const brief = evaluationTask(LEADS[0] as (typeof LEADS)[number], DEFAULT_JOB, []);
846
- expect(brief).toContain("Don't use numbers like 100, 75, or 50");
847
- expect(brief).toContain("two sentences");
848
- expect(brief).toContain("Candidate ID: c01");
849
- expect(brief).toContain("expected criteria for your final answer");
850
- });
814
+ /** The coordinator's guardrail, called the way the runtime calls it. */
815
+ const check = (text: string) => runGuardrail(emailWriter, text);
851
816
 
852
- test("the coordinator's brief carries their proceed flag as they spelled it", () => {
853
- const candidate = LEADS[0] as (typeof LEADS)[number];
854
- expect(emailTask(candidate, DEFAULT_JOB, true)).toContain("PROCEEDING WITH CANDIDATE: True");
855
- expect(emailTask(candidate, DEFAULT_JOB, false)).toContain("PROCEEDING WITH CANDIDATE: False");
856
- });
817
+ /** What a verdict COMPLAINED about, or `null` when it accepted.
818
+ * `GuardrailVerdict` is `true | string`, and narrowing it here is what stops
819
+ * an ACCEPTING verdict being matched against a complaint by accident — a
820
+ * stringified `true` matches no pattern in this file and would read as a pass. */
821
+ const complaint = (verdict: GuardrailVerdict): string | null =>
822
+ verdict === true ? null : verdict;
857
823
 
858
- test("the coordinator declares what a good email is, a guardrail, and its retry budget", () => {
859
- expect(emailWriter.expectedOutput).toMatch(/Subject:/);
860
- expect(emailWriter.expectedOutput).toContain(COORDINATOR_NAME);
861
- expect(emailWriter.guardrail).toBe(emailGuardrail);
862
- // No tools, one step: a writing pass, which is exactly what their agent is.
863
- expect(emailWriter.tools).toBeUndefined();
864
- expect(emailWriter.maxSteps).toBe(1);
865
- // Their `guardrail` retries three times; this is one, written out at the
866
- // declaration. Pinned to the NUMBER as well as to the constant, so an SDK
867
- // default that moved is a decision this template makes again rather than
868
- // one it inherits.
869
- expect(emailWriter.maxRevisions).toBe(EMAIL_GUARDRAIL_REVISIONS);
870
- expect(EMAIL_GUARDRAIL_REVISIONS).toBe(1);
871
- });
824
+ describe("the crews", () => {
825
+ test("render a CrewAI agent through CrewAI's own role_playing template", () => {
826
+ expect(crewAgentPrompt(HR_EVALUATION_AGENT)).toBe(
827
+ `You are ${HR_EVALUATION_AGENT.role}. ${HR_EVALUATION_AGENT.backstory}\n` +
828
+ `Your personal goal is: ${HR_EVALUATION_AGENT.goal}`,
829
+ );
830
+ expect(EVALUATOR_SYSTEM).toMatch(/^You are Senior HR Evaluation Expert\./);
831
+ expect(emailWriter.systemPrompt).toBe(crewAgentPrompt(EMAIL_FOLLOWUP_AGENT));
832
+ expect(crewExpectedOutput("X")).toMatch(/expected criteria for your final answer: X/);
833
+ });
872
834
 
873
- test("the guardrail accepts a subject line and a signature, and names what is missing", () => {
874
- expect(check("Subject: Hello\n\nHi,\n\nBest,\nSarah")).toBe(true);
875
- expect(check(" Subject: Hello\nHi — Sarah")).toBe(true);
876
- expect(complaint(check("Hi,\n\nBest,\nSarah"))).toMatch(/Subject:/);
877
- expect(complaint(check("Subject: Hello\n\nHi,\n\nBest,\nThe team"))).toMatch(
878
- /Sign the email as Sarah/,
879
- );
880
- });
835
+ test("the evaluator's brief keeps their anti-round-number rule and asks for two sentences", () => {
836
+ const brief = evaluationTask(LEADS[0] as (typeof LEADS)[number], DEFAULT_JOB, []);
837
+ expect(brief).toContain("Don't use numbers like 100, 75, or 50");
838
+ expect(brief).toContain("two sentences");
839
+ expect(brief).toContain("Candidate ID: c01");
840
+ expect(brief).toContain("expected criteria for your final answer");
841
+ });
881
842
 
882
- test("the evaluator's schema IS their output_pydantic: a whole 1–100 score, a capped reason", async () => {
883
- const verdict = await parseSchemaInput<CandidateScore>(
884
- candidateScoreSchema,
885
- { score: 87, reason: "Ships React daily and has taken an LLM feature end to end." },
886
- "the evaluator's verdict",
887
- );
888
- expect(verdict).toEqual({
889
- score: 87,
890
- reason: "Ships React daily and has taken an LLM feature end to end.",
891
- });
892
- // The three a model really does return, each of which the desk could not
893
- // read back: a zero, a half point, and the "detailed reasoning" theirs
894
- // asked for where two spoken sentences were wanted.
895
- expect(await schemaInputIssues(candidateScoreSchema, { score: 0, reason: "r" })).toBeDefined();
896
- expect(
897
- await schemaInputIssues(candidateScoreSchema, { score: 87.5, reason: "r" }),
898
- ).toBeDefined();
899
- expect(
900
- await schemaInputIssues(candidateScoreSchema, { score: 87, reason: "x".repeat(501) }),
901
- ).toBeDefined();
902
- });
843
+ test("the coordinator's brief carries their proceed flag as they spelled it", () => {
844
+ const candidate = LEADS[0] as (typeof LEADS)[number];
845
+ expect(emailTask(candidate, DEFAULT_JOB, true)).toContain("PROCEEDING WITH CANDIDATE: True");
846
+ expect(emailTask(candidate, DEFAULT_JOB, false)).toContain(
847
+ "PROCEEDING WITH CANDIDATE: False",
848
+ );
849
+ });
903
850
 
904
- test("parseEmail splits the subject from the body, and copes with a draft that has none", () => {
905
- expect(parseEmail("Subject: Next steps\n\nHi Priya,\n\nSarah")).toEqual({
906
- subject: "Next steps",
907
- body: "Hi Priya,\n\nSarah",
851
+ test("the coordinator declares what a good email is, a guardrail, and its retry budget", () => {
852
+ expect(emailWriter.expectedOutput).toMatch(/Subject:/);
853
+ expect(emailWriter.expectedOutput).toContain(COORDINATOR_NAME);
854
+ expect(emailWriter.guardrail).toBe(emailGuardrail);
855
+ // No tools, one step: a writing pass, which is exactly what their agent is.
856
+ expect(emailWriter.tools).toBeUndefined();
857
+ expect(emailWriter.maxSteps).toBe(1);
858
+ // Their `guardrail` retries three times; this is one, written out at the
859
+ // declaration. Pinned to the NUMBER as well as to the constant, so an SDK
860
+ // default that moved is a decision this template makes again rather than
861
+ // one it inherits.
862
+ expect(emailWriter.maxRevisions).toBe(EMAIL_GUARDRAIL_REVISIONS);
863
+ expect(EMAIL_GUARDRAIL_REVISIONS).toBe(1);
908
864
  });
909
- expect(parseEmail("Hi Priya — talk soon.")).toEqual({
910
- subject: "(no subject)",
911
- body: "Hi Priya — talk soon.",
865
+
866
+ test("the guardrail accepts a subject line and a signature, and names what is missing", () => {
867
+ expect(check("Subject: Hello\n\nHi,\n\nBest,\nSarah")).toBe(true);
868
+ expect(check(" Subject: Hello\nHi — Sarah")).toBe(true);
869
+ expect(complaint(check("Hi,\n\nBest,\nSarah"))).toMatch(/Subject:/);
870
+ expect(complaint(check("Subject: Hello\n\nHi,\n\nBest,\nThe team"))).toMatch(
871
+ /Sign the email as Sarah/,
872
+ );
912
873
  });
913
- });
914
- });
915
874
 
916
- // ─── The state ───────────────────────────────────────────────────────────────
917
-
918
- describe("the ranking", () => {
919
- test("joins scores onto the roster, best first, and leaves the unscored out", () => {
920
- const state = emptyHiring();
921
- state.candidates = [...LEADS];
922
- state.scores = { c03: { score: 40, reason: "r" }, c01: { score: 90, reason: "r" } };
923
- const rows = ranked(state);
924
- expect(rows.map((row) => [row.rank, row.id, row.score])).toEqual([
925
- [1, "c01", 90],
926
- [2, "c03", 40],
927
- ]);
928
- });
875
+ test("the evaluator's schema IS their output_pydantic: a whole 1–100 score, a capped reason", async () => {
876
+ const verdict = await parseSchemaInput<CandidateScore>(
877
+ candidateScoreSchema,
878
+ { score: 87, reason: "Ships React daily and has taken an LLM feature end to end." },
879
+ "the evaluator's verdict",
880
+ );
881
+ expect(verdict).toEqual({
882
+ score: 87,
883
+ reason: "Ships React daily and has taken an LLM feature end to end.",
884
+ });
885
+ // The three a model really does return, each of which the desk could not
886
+ // read back: a zero, a half point, and the "detailed reasoning" theirs
887
+ // asked for where two spoken sentences were wanted.
888
+ expect(
889
+ await schemaInputIssues(candidateScoreSchema, { score: 0, reason: "r" }),
890
+ ).toBeDefined();
891
+ expect(
892
+ await schemaInputIssues(candidateScoreSchema, { score: 87.5, reason: "r" }),
893
+ ).toBeDefined();
894
+ expect(
895
+ await schemaInputIssues(candidateScoreSchema, { score: 87, reason: "x".repeat(501) }),
896
+ ).toBeDefined();
897
+ });
929
898
 
930
- test("breaks a tie by roster order, so a ranking is stable across reads", () => {
931
- const state = emptyHiring();
932
- state.candidates = [...LEADS];
933
- state.scores = { c05: { score: 70, reason: "r" }, c02: { score: 70, reason: "r" } };
934
- expect(ranked(state).map((row) => row.id)).toEqual(["c02", "c05"]);
935
- expect(ranked(state).map((row) => row.id)).toEqual(["c02", "c05"]);
899
+ test("parseEmail splits the subject from the body, and copes with a draft that has none", () => {
900
+ expect(parseEmail("Subject: Next steps\n\nHi Priya,\n\nSarah")).toEqual({
901
+ subject: "Next steps",
902
+ body: "Hi Priya,\n\nSarah",
903
+ });
904
+ expect(parseEmail("Hi Priya — talk soon.")).toEqual({
905
+ subject: "(no subject)",
906
+ body: "Hi Priya — talk soon.",
907
+ });
908
+ });
936
909
  });
937
910
 
938
- test("resolves a first name, a surname or a position, and lists the options otherwise", () => {
939
- const state = emptyHiring();
940
- state.candidates = [...LEADS];
941
- state.scores = Object.fromEntries(
942
- Object.entries(SCORES).map(([id, score]) => [id, { score, reason: "r" }]),
943
- );
944
- expect(resolveCandidate(state, "priya")).toMatchObject({ id: "c01" });
945
- expect(resolveCandidate(state, "O'Connor")).toMatchObject({ id: "c10" });
946
- expect(resolveCandidate(state, "the third one")).toMatchObject({ id: "c04" });
947
- const nobody = resolveCandidate(state, "Zelda");
948
- expect(isToolFailure(nobody)).toBe(true);
949
- if (isToolFailure(nobody)) expect(nobody.error).toContain("1. Priya Raman (87)");
950
- // An empty ranking is answered, not thrown at.
951
- expect(isToolFailure(resolveCandidate(emptyHiring(), "Priya"))).toBe(true);
952
- });
911
+ // ─── The state ───────────────────────────────────────────────────────────────
953
912
 
954
- test("holds MAX_FEEDBACK_ENTRIES entries of feedback, dropping the oldest", () => {
955
- // The bound is the SLOT's (`caps`), so it holds whatever pushed — a plain
956
- // `push` here is the same write `rescore_with_feedback` makes.
957
- const ctx = createToolContext();
958
- hiringSlot.update(ctx, (state) => {
959
- for (let index = 0; index < MAX_FEEDBACK_ENTRIES + 2; index++)
960
- state.feedback.push(`f${index}`);
961
- });
962
- const { feedback } = stateOf(ctx);
963
- expect(feedback).toHaveLength(MAX_FEEDBACK_ENTRIES);
964
- expect(feedback[0]).toBe("f2");
965
- // The cap is the round cap restated: no round can be dropped while it counts.
966
- expect(MAX_FEEDBACK_ENTRIES).toBeGreaterThan(MAX_FEEDBACK_ROUNDS);
967
- });
913
+ describe("the ranking", () => {
914
+ test("joins scores onto the roster, best first, and leaves the unscored out", () => {
915
+ const state = emptyHiring();
916
+ state.candidates = [...LEADS];
917
+ state.scores = { c03: { score: 40, reason: "r" }, c01: { score: 90, reason: "r" } };
918
+ const rows = ranked(state);
919
+ expect(rows.map((row) => [row.rank, row.id, row.score])).toEqual([
920
+ [1, "c01", 90],
921
+ [2, "c03", 40],
922
+ ]);
923
+ });
968
924
 
969
- test("the projection carries names and scores, never an email address", async () => {
970
- const { ctx } = await screened();
971
- await run("proceed_to_emails", {}, ctx);
972
- const view = hiringView(stateOf(ctx));
973
- expect(view.jobTitle).toBe(DEFAULT_JOB.title);
974
- expect(view.leaderboard).toHaveLength(LEADS.length);
975
- expect(view.leaderboard[0]).toMatchObject({ rank: 1, name: "Priya Raman", shortlisted: true });
976
- expect(view.leaderboard.filter((row) => row.shortlisted)).toHaveLength(SHORTLIST_SIZE);
977
- expect(view.drafts).toHaveLength(LEADS.length);
978
- expect(view.drafts[0]).toMatchObject({ name: "Priya Raman", proceed: true, accepted: true });
979
- expect(JSON.stringify(view)).not.toContain("@example.com");
980
- });
925
+ test("breaks a tie by roster order, so a ranking is stable across reads", () => {
926
+ const state = emptyHiring();
927
+ state.candidates = [...LEADS];
928
+ state.scores = { c05: { score: 70, reason: "r" }, c02: { score: 70, reason: "r" } };
929
+ expect(ranked(state).map((row) => row.id)).toEqual(["c02", "c05"]);
930
+ expect(ranked(state).map((row) => row.id)).toEqual(["c02", "c05"]);
931
+ });
932
+
933
+ test("resolves a first name, a surname or a position, and lists the options otherwise", () => {
934
+ const state = emptyHiring();
935
+ state.candidates = [...LEADS];
936
+ state.scores = Object.fromEntries(
937
+ Object.entries(SCORES).map(([id, score]) => [id, { score, reason: "r" }]),
938
+ );
939
+ expect(resolveCandidate(state, "priya")).toMatchObject({ id: "c01" });
940
+ expect(resolveCandidate(state, "O'Connor")).toMatchObject({ id: "c10" });
941
+ expect(resolveCandidate(state, "the third one")).toMatchObject({ id: "c04" });
942
+ const nobody = resolveCandidate(state, "Zelda");
943
+ expect(isToolFailure(nobody)).toBe(true);
944
+ if (isToolFailure(nobody)) expect(nobody.error).toContain("1. Priya Raman (87)");
945
+ // An empty ranking is answered, not thrown at.
946
+ expect(isToolFailure(resolveCandidate(emptyHiring(), "Priya"))).toBe(true);
947
+ });
948
+
949
+ test("the slot keeps its contract, and the feedback cap is the round cap restated", () => {
950
+ expectSlotContract(hiringSlot, {
951
+ write: (state) => {
952
+ state.rounds = 1;
953
+ },
954
+ });
955
+ // No round can be dropped while it counts.
956
+ expect(MAX_FEEDBACK_ENTRIES).toBeGreaterThan(MAX_FEEDBACK_ROUNDS);
957
+ });
981
958
 
982
- test("stageLabel reads every state", () => {
983
- expect(stageLabel({ state: "idle", done: false })).toBe("nothing screened yet");
984
- expect(stageLabel({ state: "reviewing", done: false })).toBe("shortlist under review");
985
- expect(stageLabel({ state: "emailed", done: false })).toBe("emails drafted");
959
+ test("the projection carries names and scores, never an email address", async () => {
960
+ const { ctx } = await screened();
961
+ await run(proceedToEmails, {}, ctx);
962
+ const view = hiringView(stateOf(ctx));
963
+ expect(view.jobTitle).toBe(DEFAULT_JOB.title);
964
+ expect(view.leaderboard).toHaveLength(LEADS.length);
965
+ expect(view.leaderboard[0]).toMatchObject({
966
+ rank: 1,
967
+ name: "Priya Raman",
968
+ shortlisted: true,
969
+ });
970
+ expect(view.leaderboard.filter((row) => row.shortlisted)).toHaveLength(SHORTLIST_SIZE);
971
+ expect(view.drafts).toHaveLength(LEADS.length);
972
+ expect(view.drafts[0]).toMatchObject({ name: "Priya Raman", proceed: true, accepted: true });
973
+ expect(JSON.stringify(view)).not.toContain("@example.com");
974
+ });
975
+
976
+ test("stageLabel reads every state", () => {
977
+ expect(stageLabel({ state: "idle", done: false })).toBe("nothing screened yet");
978
+ expect(stageLabel({ state: "reviewing", done: false })).toBe("shortlist under review");
979
+ expect(stageLabel({ state: "emailed", done: false })).toBe("emails drafted");
980
+ });
986
981
  });
987
982
  });