@desplega.ai/agent-swarm 2.7.9 → 2.7.10

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 (212) hide show
  1. package/dist/{acp-adapter-dn4gdsgr.js → acp-adapter-srfhs1s9.js} +5 -5
  2. package/dist/{actions-g563mbn2.js → actions-b8aqhrsg.js} +19 -18
  3. package/dist/{amp-adapter-q61w05eb.js → amp-adapter-4c165vgn.js} +1 -1
  4. package/dist/app-m9khefrh.js +20 -0
  5. package/dist/{assistant-p477rjwj.js → assistant-rh4v3ntz.js} +21 -20
  6. package/dist/{boot-args-schema-h4qj462e.js → boot-args-schema-hwkc8bzv.js} +1 -1
  7. package/dist/{boot-reembed-n1ehfbsw.js → boot-reembed-5y6yw9sj.js} +1 -1
  8. package/dist/{boot-reembed-qw4mc0pt.js → boot-reembed-fdyk55h4.js} +1 -1
  9. package/dist/{boot-scrub-sweep-9w9jp4sm.js → boot-scrub-sweep-r5r8kqsn.js} +3 -3
  10. package/dist/{boot-seeds-qdaf3sdy.js → boot-seeds-8f9zt5cm.js} +5 -5
  11. package/dist/{claude-adapter-348p5hx9.js → claude-adapter-s5df247c.js} +5 -5
  12. package/dist/{claude-managed-setup-7787fxtp.js → claude-managed-setup-9gsmwzyx.js} +1 -1
  13. package/dist/{claude-sdk-session-hbszbt8a.js → claude-sdk-session-dq1j4nz9.js} +5 -5
  14. package/dist/{cli-btf6fw39.js → cli-0m7rtm11.js} +1 -1
  15. package/dist/{cli-cseh6f8w.js → cli-16phend6.js} +1 -1
  16. package/dist/{cli-ms5m5r1y.js → cli-18qt3few.js} +1 -1
  17. package/dist/{cli-sgs5k6yd.js → cli-2tsfpc70.js} +1 -1
  18. package/dist/{cli-rwymrnaz.js → cli-36wdfzgn.js} +8 -8
  19. package/dist/{cli-qzt90yze.js → cli-38yww4e9.js} +8 -8
  20. package/dist/{cli-2a8py3sx.js → cli-3xddv0rk.js} +4 -4
  21. package/dist/{cli-p0m0p34z.js → cli-4vwxp550.js} +2 -2
  22. package/dist/{cli-bc779n4v.js → cli-55bkx8hh.js} +1 -1
  23. package/dist/{cli-21159vea.js → cli-5wfz00be.js} +2 -2
  24. package/dist/{cli-9aezs55w.js → cli-5xcb8gxq.js} +4 -4
  25. package/dist/{cli-12xyjhws.js → cli-6m6b4bep.js} +2 -2
  26. package/dist/{cli-fayav105.js → cli-7wz05bx3.js} +292 -83
  27. package/dist/{cli-y8nbefpb.js → cli-8ewkreqd.js} +9 -5
  28. package/dist/{cli-0whpms1z.js → cli-an1knn2k.js} +4 -4
  29. package/dist/{cli-qmd3mse0.js → cli-bxz823sz.js} +1 -1
  30. package/dist/{cli-a0657jmf.js → cli-bzvs88tv.js} +1 -1
  31. package/dist/{cli-agyaeef4.js → cli-cr14kftt.js} +2 -2
  32. package/dist/{cli-715t1gx6.js → cli-eb2azq8n.js} +3 -3
  33. package/dist/{cli-530hkwdy.js → cli-ed6yqpf1.js} +2 -2
  34. package/dist/{cli-k70e3x9e.js → cli-eqk5p56g.js} +3 -3
  35. package/dist/{cli-4t0fmf3z.js → cli-g1px1g2e.js} +1 -1
  36. package/dist/{cli-09kmfkmq.js → cli-h49ejvmc.js} +1 -1
  37. package/dist/{cli-cvs2r2vq.js → cli-hfkwwy1h.js} +39 -5
  38. package/dist/{cli-neyag5p6.js → cli-j7d73g1y.js} +371 -116
  39. package/dist/{cli-p17970qv.js → cli-jg24scat.js} +2 -2
  40. package/dist/{cli-varqt4d1.js → cli-kx4c8j05.js} +16 -13
  41. package/dist/{cli-jfx48xrj.js → cli-mp9aa8g5.js} +1 -1
  42. package/dist/{cli-605nn699.js → cli-mr97t7cc.js} +644 -225
  43. package/dist/{cli-v3cf1ts9.js → cli-n07eecjs.js} +3 -3
  44. package/dist/{cli-y5rbvxhc.js → cli-n515ex5z.js} +14 -14
  45. package/dist/{cli-3tqcamp6.js → cli-n9abj89w.js} +13 -12
  46. package/dist/{cli-ypff1qwp.js → cli-n9ftpys4.js} +7 -7
  47. package/dist/{cli-xk879m3k.js → cli-nj3x45rw.js} +27 -27
  48. package/dist/{cli-9r5gtwjr.js → cli-pyrxt9gw.js} +196 -1
  49. package/dist/{cli-mnrkgg60.js → cli-q581b386.js} +2 -2
  50. package/dist/{cli-hwprv9e4.js → cli-rjyghzg4.js} +2 -2
  51. package/dist/{cli-650zv9q9.js → cli-rt0ag4x1.js} +3 -3
  52. package/dist/{cli-vxh6acp7.js → cli-td33w98c.js} +2 -2
  53. package/dist/{cli-tqq0hspb.js → cli-tmft5dz2.js} +1 -1
  54. package/dist/{cli-q26b9wre.js → cli-tph5wt3y.js} +4 -4
  55. package/dist/{cli-qkdmz8c8.js → cli-ttbqe3q4.js} +1 -1
  56. package/dist/{cli-zgv8gxgs.js → cli-v2fwbnsk.js} +6 -6
  57. package/dist/{cli-b932gexn.js → cli-w3bk0dgv.js} +1 -1
  58. package/dist/{cli-serm8zrx.js → cli-x9exydey.js} +1 -1
  59. package/dist/{cli-hae9j8sv.js → cli-xbtq4d6s.js} +3 -3
  60. package/dist/{cli-587857ys.js → cli-xd5ebp64.js} +3 -3
  61. package/dist/{cli-ejkvvqbe.js → cli-xncjscpm.js} +10 -10
  62. package/dist/{cli-gce09r66.js → cli-xvymtmv4.js} +2 -2
  63. package/dist/{cli-btc9cb4c.js → cli-yz7v0sh4.js} +2 -2
  64. package/dist/{cli-sya22y84.js → cli-z9cs5m0w.js} +3 -3
  65. package/dist/{cli-2ccpqyyf.js → cli-zjphdj1a.js} +71 -10
  66. package/dist/cli.js +15 -15
  67. package/dist/{codex-adapter-ysq6bzha.js → codex-adapter-yr60sme6.js} +3 -3
  68. package/dist/{codex-session-runner-qakzfx93.js → codex-session-runner-pch8x584.js} +3 -3
  69. package/dist/{commands-rs7hkv9r.js → commands-phjfbkv0.js} +3 -3
  70. package/dist/{controller-r5x9bg6e.js → controller-jkx994pz.js} +2 -2
  71. package/dist/{controllers-connect-498hrxvk.js → controllers-connect-c4448kwa.js} +20 -19
  72. package/dist/{cursor-adapter-d46qszer.js → cursor-adapter-ndebqnm8.js} +1 -1
  73. package/dist/{db-pm96nhdb.js → db-ef32tbfc.js} +4 -2
  74. package/dist/{db-s13dqhr6.js → db-ez6egt6v.js} +3 -3
  75. package/dist/{dispatcher-j3h81t7m.js → dispatcher-g3tt9hs9.js} +18 -17
  76. package/dist/{dsh-adapter-rw0d5rc4.js → dsh-adapter-tcyn3099.js} +1 -1
  77. package/dist/{easter-egg-3d-qtgfxgze.js → easter-egg-3d-e36hk5td.js} +1 -1
  78. package/dist/{embedding-space-xh8p4q4x.js → embedding-space-4kyh5qqj.js} +6 -6
  79. package/dist/{embeddings-wp745m91.js → embeddings-6a8v4a6t.js} +1 -1
  80. package/dist/{execute-2fzb9z74.js → execute-3cbg0twf.js} +1 -1
  81. package/dist/{external-channel-ys21h3sy.js → external-channel-se646snz.js} +2 -2
  82. package/dist/{fx-adapter-vz0b9z3g.js → fx-adapter-yw795hqq.js} +6 -6
  83. package/dist/{google-generative-ai-ytpgncx9.js → google-generative-ai-h7s3e9kk.js} +1 -1
  84. package/dist/{google-vertex-tqhze5j7.js → google-vertex-fhxaafzw.js} +1 -1
  85. package/dist/{grok-adapter-spea7zkj.js → grok-adapter-ttmcss2j.js} +6 -6
  86. package/dist/handlers-17wha3ze.js +33 -0
  87. package/dist/{heartbeat-8phn1kdq.js → heartbeat-gwewgdms.js} +21 -20
  88. package/dist/{hook-amcj4s10.js → hook-g3nhexsy.js} +5 -5
  89. package/dist/{hook-bc6n49qn.js → hook-hq93y5ej.js} +4 -4
  90. package/dist/{http-7374brv5.js → http-5a9p4h6y.js} +210 -69
  91. package/dist/{index-pxn30mse.js → index-0eny15vj.js} +8 -8
  92. package/dist/{index-5a9jtqde.js → index-0rvk3vd4.js} +46 -46
  93. package/dist/{index-fvzke5kx.js → index-1qw6f2dc.js} +10 -10
  94. package/dist/{index-p4hjwbvw.js → index-3c5pxbge.js} +1 -1
  95. package/dist/{index-q5cmtbz5.js → index-6haqt3v5.js} +12296 -11042
  96. package/dist/index-8arwq8mw.js +34 -0
  97. package/dist/{index-h7f61sy9.js → index-e5pfbsys.js} +3 -3
  98. package/dist/{index-c9y31ytf.js → index-hgn3c961.js} +12 -11
  99. package/dist/{index-hsad2t3r.js → index-m5gx1xd6.js} +38 -38
  100. package/dist/{index-5fx3b3kw.js → index-rvccek1w.js} +9 -9
  101. package/dist/{index-w4m9z29z.js → index-s72rqgsx.js} +1 -1
  102. package/dist/index-tpw054az.js +38 -0
  103. package/dist/{index-514d9pf6.js → index-w7em4ktq.js} +8 -8
  104. package/dist/index-waq75j2j.js +31 -0
  105. package/dist/{keepalive-wy29kbrg.js → keepalive-1j4n4dmk.js} +3 -3
  106. package/dist/lead-re73kdgc.js +72 -0
  107. package/dist/{maintenance-h2ds9w6c.js → maintenance-dmghacy5.js} +1 -1
  108. package/dist/{oauth-refresh-sweep-q7mtbyp3.js → oauth-refresh-sweep-yy06c03c.js} +2 -2
  109. package/dist/{onboard-vw8r2fdw.js → onboard-52f9t5dm.js} +3 -3
  110. package/dist/{opencode-adapter-mtb0953j.js → opencode-adapter-krnh9jkn.js} +4 -4
  111. package/dist/{otel-impl-j42czw3r.js → otel-impl-xjqz6wjj.js} +1 -1
  112. package/dist/{pi-mono-adapter-zk8pg9jr.js → pi-mono-adapter-dbxyp0qv.js} +6 -6
  113. package/dist/{pricing-refresh-x7nhv23d.js → pricing-refresh-ctdr74pd.js} +3 -3
  114. package/dist/{rbac-roles-bzvee6cf.js → rbac-roles-ehv8s10n.js} +3 -3
  115. package/dist/{rbac-roles-9044425x.js → rbac-roles-q0gr8eyj.js} +2 -2
  116. package/dist/{render-v2-t7bn4skz.js → render-v2-5b6chvcq.js} +9 -4
  117. package/dist/{resume-x94gemep.js → resume-5a5d2845.js} +6 -6
  118. package/dist/{runtime-breq6fmv.js → runtime-khxszyfp.js} +1 -1
  119. package/dist/{session-access-q7dmqjvt.js → session-access-gj0bjhqg.js} +4 -4
  120. package/dist/{session-source-backfill-440ysamr.js → session-source-backfill-2sy0krfk.js} +2 -2
  121. package/dist/{setup-07n4727s.js → setup-7ssfakk1.js} +1 -1
  122. package/dist/{virtual-modules-z5h6mcyf.js → virtual-modules-pjj0knwf.js} +3 -3
  123. package/dist/{work-objects-pnq5y534.js → work-objects-bf3syvhq.js} +22 -21
  124. package/dist/{worker-follow-up-7z1gfkr8.js → worker-follow-up-38xevga6.js} +18 -17
  125. package/dist/worker-r8mz7a65.js +72 -0
  126. package/openapi.json +1 -1
  127. package/package.json +3 -3
  128. package/src/apps/catalog.generated.json +55 -0
  129. package/src/apps/page-validator.ts +19 -0
  130. package/src/assets/key.ts +77 -4
  131. package/src/be/db/session-labels.ts +57 -0
  132. package/src/be/db/session-tree.ts +51 -7
  133. package/src/be/db/slack-trees.ts +146 -0
  134. package/src/be/db/tasks/read.ts +102 -7
  135. package/src/be/db-client.ts +8 -2
  136. package/src/be/db.ts +95 -84
  137. package/src/be/event-loop-lag.ts +146 -0
  138. package/src/be/mcp-overflow-sweep.ts +2 -1
  139. package/src/be/memory/providers/sqlite-store.ts +39 -8
  140. package/src/be/migrations/278_slack_render_v2_reconcile.sql +108 -0
  141. package/src/be/swarm-config-guard.ts +2 -0
  142. package/src/commands/context-preamble.ts +258 -0
  143. package/src/commands/onboard/agent-fs-version.ts +1 -1
  144. package/src/extensions/catalog.generated.json +3 -3
  145. package/src/heartbeat/heartbeat.ts +5 -4
  146. package/src/http/core.ts +9 -3
  147. package/src/http/index.ts +10 -6
  148. package/src/http/memory.ts +9 -4
  149. package/src/http/sessions.ts +16 -3
  150. package/src/http/utils.ts +18 -0
  151. package/src/http/webhooks.ts +48 -0
  152. package/src/integrations/chat-sdk/commands.ts +167 -31
  153. package/src/integrations/chat-sdk/inbound.ts +10 -8
  154. package/src/integrations/chat-sdk/message-text.ts +117 -0
  155. package/src/providers/amp-adapter.ts +1 -1
  156. package/src/providers/cursor-adapter.ts +1 -1
  157. package/src/providers/dsh-adapter.ts +1 -1
  158. package/src/scheduler/scheduler.ts +4 -1
  159. package/src/scripts-runtime/executors/quickjs-runner.ts +2 -0
  160. package/src/scripts-runtime/executors/quickjs-structured-clone.ts +180 -0
  161. package/src/scripts-runtime/quickjs-compat.ts +0 -1
  162. package/src/slack/app.ts +332 -10
  163. package/src/slack/handlers.ts +9 -2
  164. package/src/slack/index.ts +7 -1
  165. package/src/slack/lifecycle-lock.ts +29 -0
  166. package/src/slack/render-v2.ts +424 -212
  167. package/src/slack/socket-fence.ts +64 -0
  168. package/src/slack/watcher.ts +42 -8
  169. package/src/tests/apps-schema-form.test.ts +151 -0
  170. package/src/tests/chat-sdk-commands.test.ts +359 -2
  171. package/src/tests/chat-sdk-inbound.test.ts +20 -0
  172. package/src/tests/chat-sdk-slack.test.ts +189 -1
  173. package/src/tests/db-client-busy-retry.test.ts +69 -18
  174. package/src/tests/db-client.test.ts +26 -1
  175. package/src/tests/db-task-read-contract.test.ts +2 -0
  176. package/src/tests/db-task-write-contract.test.ts +1 -0
  177. package/src/tests/dsh-adapter.test.ts +1 -1
  178. package/src/tests/event-loop-lag.test.ts +184 -0
  179. package/src/tests/extensions-example-comms-adherence-gate.test.ts +115 -0
  180. package/src/tests/github-webhook-early-ack.test.ts +144 -0
  181. package/src/tests/http-api-integration.test.ts +2 -0
  182. package/src/tests/http-log-scrubbing.test.ts +68 -2
  183. package/src/tests/kv-storage.test.ts +92 -1
  184. package/src/tests/memory-key-paths.test.ts +57 -0
  185. package/src/tests/memory-retrieval-purge.test.ts +19 -0
  186. package/src/tests/quickjs-compat.test.ts +1 -1
  187. package/src/tests/runner-context-preamble.test.ts +552 -0
  188. package/src/tests/script-connections.test.ts +3 -0
  189. package/src/tests/script-executor-conformance.test.ts +188 -0
  190. package/src/tests/sessions-tree.test.ts +133 -2
  191. package/src/tests/slack-app-icon.test.ts +4 -0
  192. package/src/tests/slack-dm-implicit-mention.test.ts +236 -0
  193. package/src/tests/slack-file-tools-attachments.test.ts +1 -0
  194. package/src/tests/slack-read-boundaries.test.ts +4 -3
  195. package/src/tests/slack-render-v2-query-plans.test.ts +262 -3
  196. package/src/tests/slack-render-v2-reconcile.test.ts +201 -0
  197. package/src/tests/slack-socket-watchdog.test.ts +748 -0
  198. package/src/tests/vcs-identity-inheritance.test.ts +85 -0
  199. package/src/tools/utils.ts +16 -7
  200. package/templates/extensions/comms-adherence-gate/README.md +25 -0
  201. package/templates/extensions/comms-adherence-gate/hooks.ts +100 -11
  202. package/templates/extensions/comms-adherence-gate/manifest.json +1 -1
  203. package/templates/skills/apps/SKILL.md +7 -0
  204. package/templates/skills/apps/content.md +7 -0
  205. package/dist/app-a66ssc4k.js +0 -17
  206. package/dist/handlers-crckt5dq.js +0 -32
  207. package/dist/index-4x08sjtk.js +0 -30
  208. package/dist/index-8ybffts4.js +0 -37
  209. package/dist/index-nfy4kkg5.js +0 -33
  210. package/dist/lead-zdqxsvjn.js +0 -71
  211. package/dist/worker-y62rvvq3.js +0 -71
  212. package/dist/{cli-gxy8y1dt.js → cli-8bpgbr8k.js} +3 -3
@@ -5,16 +5,16 @@
5
5
  "$schema": "../manifest.schema.json",
6
6
  "name": "comms-adherence-gate",
7
7
  "description": "Judges every Slack-facing store-progress completion and agent Slack post against the comms preferences of the requester, or of the person it @-mentions, their latest request and a plain-language rubric with Jev (TypeSafe or OpenRouter), and in enforce blocks a failing call once per task",
8
- "version": "1.7.0",
8
+ "version": "1.8.0",
9
9
  "runtime": "api",
10
10
  "assets": {
11
11
  "hooks": "hooks.ts"
12
12
  }
13
13
  },
14
14
  "files": {
15
- "hooks.ts": "import { type ApiCtx, block, type SwarmExtension } from \"swarm-extension\";\nimport { z } from \"zod\";\n\n/**\n * comms-adherence-gate\n *\n * When an agent calls `store-progress` with status \"completed\" on a task that\n * reaches a human in Slack, or posts to Slack itself (`slack-reply`,\n * `slack-post`, `slack-start-thread`, `slack-update`), judge the text with Jev:\n * against the requesting user's stored comms preferences\n * (users.metadata.$.comms) and what that user actually asked for in their\n * latest message, and against a plain-language rubric that applies to every\n * message whatever preferences exist. An explicit request (\"tell me a long\n * joke\", \"explain in detail\") outranks the stored default, so a requested long\n * answer is not a verbosity failure.\n *\n * Threads with several people: a message that @-mentions someone is judged\n * against the first mentioned person with stored preferences, skipping a\n * requester without preferences; otherwise against the requester. `plain` applies to everyone.\n *\n * Transport (config.provider): Jev is served by TypeSafe directly and by\n * OpenRouter's Decisions endpoint. Both take the same {model, state, questions}\n * body and return the same `answers` shape. `auto` uses TYPESAFE_API_KEY when\n * set, else OPENROUTER_API_KEY.\n *\n * modes (config.mode for the preference dimensions, config.plainMode for `plain`):\n * off -> never evaluate\n * shadow -> evaluate + record, never block (default)\n * enforce -> record, and block the call up to maxBlocksPerTask times per task\n * with actionable feedback. The budget is shared by both modes and\n * by every gated tool.\n *\n * Fails OPEN on every error: a judge outage must never wall the swarm.\n * Every verdict lands in KV namespace `ext:comms-gate`.\n */\n\nexport const config = z.object({\n mode: z.enum([\"off\", \"shadow\", \"enforce\"]).default(\"shadow\"),\n /** A preference dimension scoring below this fails. */\n threshold: z.number().min(0).max(1).default(0.5),\n /** The `plain` dimension, judged on every message. Independent of `mode`. */\n plainMode: z.enum([\"off\", \"shadow\", \"enforce\"]).default(\"shadow\"),\n /**\n * `plain` scoring below this fails. Jev scores dense status text low and\n * plain text high with little in between, so this sits far below `threshold`.\n */\n plainThreshold: z.number().min(0).max(1).default(0.25),\n timeoutMs: z.number().int().positive().default(4000),\n maxBlocksPerTask: z.number().int().min(0).default(1),\n provider: z.enum([\"auto\", \"typesafe\", \"openrouter\"]).default(\"auto\"),\n /** Jev model on the TypeSafe transport. */\n model: z.string().default(\"jev-latest\"),\n /** Jev model on the OpenRouter transport. */\n openrouterModel: z.string().default(\"typesafe/jev-1.13\"),\n /** Explicit TypeSafe key; otherwise TYPESAFE_API_KEY from the API process env. */\n apiKey: z.string().optional(),\n});\n\ntype Cfg = z.infer<typeof config>;\ntype Swarm = ApiCtx[\"swarm\"];\n\nconst NS = \"ext:comms-gate\";\nconst TYPESAFE_ENDPOINT = \"https://api.typesafe.ai/v1/systemone\";\nconst OPENROUTER_ENDPOINT = \"https://openrouter.ai/api/alpha/decisions\";\nconst UUID_RE = /^[0-9a-fA-F-]{36}$/;\n/** MCP tools that post agent-authored text to Slack, all with a `message` arg. */\nexport const SLACK_TOOLS = new Set([\n \"slack-reply\",\n \"slack-post\",\n \"slack-start-thread\",\n \"slack-update\",\n]);\n// The dispatcher cancels a handler after 5 s; leave room for the DB read and KV writes.\nconst MAX_TIMEOUT_MS = 4000;\n\nexport const cfgOf = (raw: unknown): Cfg => {\n const parsed = config.safeParse(raw ?? {});\n return parsed.success ? parsed.data : config.parse({});\n};\n\n// kv keys accept [a-zA-Z0-9._:/%-]\nconst safeKey = (raw: string | undefined | null): string =>\n (raw && raw.length > 0 ? raw : \"unknown\").replace(/[^a-zA-Z0-9._-]/g, \"_\").slice(0, 120);\n\n/** SDK envelopes: {success, data:{...}} or the bare payload. */\ntype Envelope = {\n data?: { rows?: unknown[]; value?: unknown };\n rows?: unknown[];\n value?: unknown;\n} | null;\n\nconst cell = (row: unknown, i: number, key: string): unknown =>\n Array.isArray(row) ? row[i] : (row as Record<string, unknown>)?.[key];\n\n/**\n * The newest human message sits at the END of a Slack task: the\n * `<thread_context>` blob comes first and can run to thousands of chars, so a\n * leading slice of `agent_tasks.task` shows the judge everything except the\n * actual request. Take the tail, then the part after the last `</thread_context>`.\n */\nconst CTX_END = \"</thread_context>\";\nexport const latestAsk = (tail: string): string => {\n const end = tail.lastIndexOf(CTX_END);\n let out = (end >= 0 ? tail.slice(end + CTX_END.length) : tail)\n .replace(/\\[Thread follow-up[^\\]]*\\]/g, \"\")\n .trim();\n // Some tasks end with the context block; fall back to the last messages in it.\n if (out.length < 8) out = (end >= 0 ? tail.slice(0, end) : tail).trim().slice(-800);\n return out.slice(0, 900);\n};\n\n// Preferences are the DEFAULT. A direct request outranks them.\nconst JUDGING_RULES = [\n \"The requester's explicit instruction in latest_request OUTRANKS requester_preferences. Preferences describe the DEFAULT; they never override a direct request.\",\n \"If latest_request asks for something long, detailed, creative, a story, a joke, a full explanation or a document, then length and structure serving that request are CORRECT and must NOT be penalized.\",\n \"Judge whether agent_message serves what latest_request actually asked for, written in the requester's manner. Do not judge it against the default preference when the request overrides it.\",\n];\n\ntype Prefs = { verbosity?: unknown; tone?: unknown; language?: unknown } & Record<string, unknown>;\n\n/**\n * The `plain` rubric, from the `comms` skill (Simpler and Precise modes). Jev\n * separates dense from plain text reliably only with contrasting examples; a\n * prose-only rubric scored a plain rewrite as low as the dense original.\n */\nexport const PLAIN_RULES = [\n \"Examples of NOT plain: 'p50 Δ +120ms vs baseline (n=37)', 'error rate 2.1% → 0.4% (cohort B, ±0.3 at 95%)', 'cost $-42/day', 'first-call hit ratio 0.61', 'drift unmeasured; 2 flaky'.\",\n \"Examples of plain: 'Pages load 120 ms slower than last week, across 37 runs', 'Errors dropped from 2 in 100 requests to 4 in 1,000', 'We spend $42 a day less', 'PR #123 keeps the migration reversible', 'Lead saves about $75 a week'.\",\n \"Code identifiers, task ids, PR numbers, links, file paths and version numbers are fine as they are.\",\n];\n\nexport const PLAIN_QUESTION = {\n type: \"noul\",\n instructions:\n \"Is agent_message written like the plain examples in plain_language_rules rather than like the NOT plain ones? Ignore length and tone.\",\n criteria: {\n true: \"Written like the plain examples: everyday words and numbers with units and direction.\",\n false:\n \"Written like the NOT plain examples: statistics shorthand, abbreviations, signed or cryptic numbers.\",\n },\n};\n\n/** Structured output (an outputSchema answer) is for machines; `plain` skips it. */\nexport const looksLikeJson = (text: string): boolean => {\n if (!/^[[{]/.test(text)) return false;\n try {\n JSON.parse(text);\n return true;\n } catch {\n return false;\n }\n};\n\n/** One `noul` question per stated preference the gate knows how to judge. */\nexport const buildQuestions = (prefs: Prefs): Record<string, unknown> => {\n const questions: Record<string, unknown> = {};\n if (prefs.verbosity) {\n questions.verbosity = {\n type: \"noul\",\n instructions:\n \"Does agent_message respect the requester's verbosity preference, AS OVERRIDDEN by any explicit instruction in latest_request? Apply judging_rules.\",\n criteria: {\n true: \"Length and structure fit what latest_request asked for (or the stated preference when the request does not override it), and it leads with the result.\",\n false:\n \"Too long for what was asked, or it opens with preamble, recaps the request, narrates the process, or ends with an offer to elaborate. Length explicitly requested in latest_request is NOT a failure.\",\n },\n };\n }\n if (prefs.tone) {\n questions.tone = {\n type: \"noul\",\n instructions:\n \"Does agent_message match the requester's stated tone preference, as overridden by any explicit instruction in latest_request? Apply judging_rules.\",\n criteria: {\n true: \"The tone matches what the requester asked for.\",\n false:\n \"The tone conflicts with it (for example hedging, flattery or filler when the requester asked for direct and plain). A voice appropriate to an explicitly requested creative or narrative form is NOT a failure.\",\n },\n };\n }\n if (prefs.language) {\n questions.language = {\n type: \"noul\",\n instructions: \"Is agent_message written in the requester's stated language?\",\n criteria: {\n true: \"Written in the stated language.\",\n false: \"Written in a different language.\",\n },\n };\n }\n return questions;\n};\n\nconst secretCache = new Map<string, { value: string; at: number }>();\nconst KEY_TTL_MS = 5 * 60 * 1000;\nconst usable = (v: string): boolean => Boolean(v) && !v.startsWith(\"[REDACTED\");\nconst envOf = (name: string): string => String(process.env[name] ?? \"\");\n\n/**\n * Resolve a secret: explicit value, then the API process env. The API process loads\n * global swarm_config rows into process.env at boot and on config reload.\n * ctx.swarm.config_get cannot serve it: the SDK scrubs secrets to \"[REDACTED:<name>]\".\n */\nconst secret = (name: string, explicit?: string): string => {\n const cached = secretCache.get(name);\n if (cached && Date.now() - cached.at < KEY_TTL_MS) return cached.value;\n const value = [String(explicit ?? \"\"), envOf(name)].find(usable) ?? \"\";\n if (usable(value)) secretCache.set(name, { value, at: Date.now() });\n return value;\n};\n\n/** Test hook: forget cached secrets. */\nexport const resetKeyCache = (): void => {\n secretCache.clear();\n};\n\nexport type JevTransport = {\n provider: \"typesafe\" | \"openrouter\";\n endpoint: string;\n key: string;\n model: string;\n};\n\n/**\n * Pick the Jev transport. `auto` prefers TypeSafe and falls back to OpenRouter.\n * Throws when the chosen provider has no usable key; the handler fails open.\n */\nexport const resolveTransport = (cfg: Cfg): JevTransport => {\n const typesafe = (): JevTransport | null => {\n const key = secret(\"TYPESAFE_API_KEY\", cfg.apiKey);\n return usable(key)\n ? { provider: \"typesafe\", endpoint: TYPESAFE_ENDPOINT, key, model: cfg.model }\n : null;\n };\n const openrouter = (): JevTransport | null => {\n const key = secret(\"OPENROUTER_API_KEY\");\n return usable(key)\n ? { provider: \"openrouter\", endpoint: OPENROUTER_ENDPOINT, key, model: cfg.openrouterModel }\n : null;\n };\n const transport =\n cfg.provider === \"typesafe\"\n ? typesafe()\n : cfg.provider === \"openrouter\"\n ? openrouter()\n : (typesafe() ?? openrouter());\n if (transport) return transport;\n throw new Error(\n cfg.provider === \"typesafe\"\n ? \"no TYPESAFE_API_KEY\"\n : cfg.provider === \"openrouter\"\n ? \"no OPENROUTER_API_KEY\"\n : \"no TYPESAFE_API_KEY or OPENROUTER_API_KEY\",\n );\n};\n\n/** One Jev call; returns the `noul` score per question. Throws on any failure. */\nexport const askJev = async (\n state: Record<string, unknown>,\n questions: Record<string, unknown>,\n transport: JevTransport,\n cfg: Cfg,\n outer?: AbortSignal,\n): Promise<{ scores: Record<string, number>; latencyMs: number }> => {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), Math.min(cfg.timeoutMs, MAX_TIMEOUT_MS));\n const onOuterAbort = () => controller.abort();\n outer?.addEventListener(\"abort\", onOuterAbort);\n const t0 = Date.now();\n try {\n const res = await fetch(transport.endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", Authorization: `Bearer ${transport.key}` },\n body: JSON.stringify({ state, model: transport.model, questions }),\n signal: controller.signal,\n });\n if (!res.ok) throw new Error(`${transport.provider} ${res.status}`);\n const body = (await res.json()) as { answers?: Record<string, { noul?: unknown }> } | null;\n const answers = body?.answers;\n if (!answers || typeof answers !== \"object\") throw new Error(\"no answers in response\");\n const scores: Record<string, number> = {};\n for (const [id, a] of Object.entries(answers)) {\n if (typeof a?.noul === \"number\") scores[id] = a.noul;\n }\n if (Object.keys(scores).length === 0) throw new Error(\"no scores in response\");\n return { scores, latencyMs: Date.now() - t0 };\n } finally {\n clearTimeout(timer);\n outer?.removeEventListener(\"abort\", onOuterAbort);\n }\n};\n\nconst SELFTEST = \"comms-gate-selftest\";\nconst SELFTEST_PREFS = {\n tone: \"direct, plain, no hedging\",\n language: \"English\",\n verbosity:\n \"very terse - answer in the first sentence, ~400 chars max. No preamble, no recap, no closing offer.\",\n};\nconst SELFTEST_BAD =\n \"Great question! Let me walk you through what I did here. First I looked at the task, then I reviewed the relevant files, and after careful consideration I decided to go with option B. I hope this helps - let me know if you would like me to elaborate further on any of the above!\";\nconst SELFTEST_GOOD =\n \"Went with option B: it is the only one that keeps the migration reversible. PR #123.\";\n// A real dense monitor post a requester had to ask to have rewritten, and that rewrite.\nconst SELFTEST_PLAIN_BAD =\n \"Prompt cache monitor, day 7 verdict for v2.0.0: partial. Lead first-call read median 12.4k (baseline v1.173.0, n 410) → 19.1k tokens (n 2234; expected 25.0k-40.0k). First-call saving about $75/week on Lead vs v1.173.0 (expected $129; sampling noise ±$24 at 95%, one baseline version, day-to-day drift not measured); session $ change $-167/week; fleet first-call saving $-7/week.\";\nconst SELFTEST_PLAIN_GOOD =\n \"Cheaper, but half what we hoped: Lead saves about $75 a week, not $129. Whole Lead tasks still cost $167 a week more, probably from other releases and heavier work, not this change.\";\n\nconst below = (bad: unknown, good: unknown, threshold: number): boolean =>\n typeof bad === \"number\" && typeof good === \"number\" && bad < threshold && good >= threshold;\n\n/**\n * Run the judge on known-bad (positive control, must score below threshold) and\n * known-good (negative control, must score at or above it) messages and record\n * them under `selftest:last`: one pair for verbosity, one for `plain`. Proves key,\n * egress and KV from inside the API runtime without touching real traffic.\n */\nconst selfTest = async (swarm: Swarm, cfg: Cfg, signal?: AbortSignal): Promise<void> => {\n const started = Date.now();\n try {\n const transport = resolveTransport(cfg);\n const judge = (message: string, dim: \"verbosity\" | \"plain\") =>\n askJev(\n dim === \"plain\"\n ? { plain_language_rules: PLAIN_RULES, agent_message: message }\n : { requester_preferences: SELFTEST_PREFS, agent_message: message },\n { [dim]: dim === \"plain\" ? PLAIN_QUESTION : buildQuestions(SELFTEST_PREFS).verbosity },\n transport,\n cfg,\n signal,\n ).then((r) => r.scores[dim] ?? null);\n const [bad, good, plainBad, plainGood] = await Promise.all([\n judge(SELFTEST_BAD, \"verbosity\"),\n judge(SELFTEST_GOOD, \"verbosity\"),\n judge(SELFTEST_PLAIN_BAD, \"plain\"),\n judge(SELFTEST_PLAIN_GOOD, \"plain\"),\n ]);\n await swarm.kv_set({\n namespace: NS,\n key: \"selftest:last\",\n value: {\n at: new Date().toISOString(),\n provider: transport.provider,\n threshold: cfg.threshold,\n positiveControlBadScore: bad,\n negativeControlGoodScore: good,\n controlsOk: below(bad, good, cfg.threshold),\n plainThreshold: cfg.plainThreshold,\n plainPositiveControlBadScore: plainBad,\n plainNegativeControlGoodScore: plainGood,\n plainControlsOk: below(plainBad, plainGood, cfg.plainThreshold),\n latencyMs: Date.now() - started,\n },\n });\n } catch (err) {\n await swarm\n .kv_set({\n namespace: NS,\n key: \"selftest:last\",\n value: {\n at: new Date().toISOString(),\n error: String(err).slice(0, 400),\n latencyMs: Date.now() - started,\n },\n })\n .catch(() => {});\n }\n};\n\nconst TASK_SQL = `SELECT t.source, t.slackThreadTs, t.agentId, t.requestedByUserId,\n json_extract(u.metadata, '$.comms') AS comms, u.name,\n substr(t.task, 1, 400) AS askHead,\n substr(t.task, -1400) AS askTail,\n t.creatorAgentId\nFROM agent_tasks t\nLEFT JOIN users u ON u.id = t.requestedByUserId\nWHERE t.id = ?`;\n\nconst LEAD_SQL = \"SELECT isLead FROM agents WHERE id = ?\";\n\n/** Slack user mentions in agent text: `<@U123>` or `<@U123|name>`. */\nconst MENTION_RE = /<@([UW][A-Z0-9]+)(?:\\|[^>]*)?>/g;\nconst MAX_MENTIONS = 5;\n\n/** Mentioned Slack user ids in order of first appearance, capped. */\nexport const mentionedSlackIds = (text: string): string[] => {\n const ids: string[] = [];\n for (const m of text.matchAll(MENTION_RE)) {\n if (!ids.includes(m[1]!)) ids.push(m[1]!);\n if (ids.length >= MAX_MENTIONS) break;\n }\n return ids;\n};\n\nconst addresseeSql = (n: number) => `SELECT x.externalId, u.id, u.name,\n json_extract(u.metadata, '$.comms') AS comms\nFROM user_external_ids x\nJOIN users u ON u.id = x.userId\nWHERE x.kind = 'slack' AND x.externalId IN (${Array(n).fill(\"?\").join(\", \")})`;\n\nconst parsePrefs = (raw: unknown): Prefs | null => {\n if (!raw) return null;\n const parsed = typeof raw === \"string\" ? JSON.parse(raw) : raw;\n return parsed && typeof parsed === \"object\" && Object.keys(parsed).length > 0\n ? (parsed as Prefs)\n : null;\n};\n\ntype Audience = { id: string; name: string; prefs: Prefs; via: \"mention\" | \"requester\" };\n\n/**\n * Whose preferences a message is judged against. In a thread with several\n * people, the message is for whoever it @-mentions: the first mentioned person\n * with stored preferences wins, including the requester only if they have prefs.\n * Without such a mention, the task requester (the\n * person whose message created this task). One SQL read, only when the text\n * mentions someone; no judge call.\n */\nconst resolveAudience = async (\n swarm: Swarm,\n text: string,\n requester: Audience,\n): Promise<Audience> => {\n const ids = mentionedSlackIds(text);\n if (ids.length === 0) return requester;\n const q = (await swarm.db_query({ sql: addresseeSql(ids.length), params: ids })) as Envelope;\n const rows = q?.data?.rows ?? q?.rows ?? [];\n for (const slackId of ids) {\n const row = rows.find((r) => String(cell(r, 0, \"externalId\")) === slackId);\n if (!row) continue;\n const userId = String(cell(row, 1, \"id\") ?? \"\");\n // A requester with stored preferences keeps their own task context.\n if (userId && userId === requester.id) {\n if (Object.keys(requester.prefs).length > 0) return requester;\n continue;\n }\n const prefs = parsePrefs(cell(row, 3, \"comms\"));\n if (!prefs) continue;\n return { id: userId, name: String(cell(row, 2, \"name\") ?? userId), prefs, via: \"mention\" };\n }\n return requester;\n};\n\n/**\n * Mirrors the `task.progress.write` rule store-progress enforces\n * (src/rbac/legacy-policy.ts): the caller owns the task, the task is\n * unassigned, or the caller is a lead. Lead status comes from the caller's\n * agents row, never from tool args. Extension callers return before this.\n */\nconst mayWriteProgress = async (\n swarm: Swarm,\n callerId: string | undefined,\n taskAgentId: string,\n): Promise<boolean> => {\n if (!callerId) return false;\n if (!taskAgentId || taskAgentId === callerId) return true;\n const q = (await swarm.db_query({ sql: LEAD_SQL, params: [callerId] })) as Envelope;\n const row = (q?.data?.rows ?? q?.rows ?? [])[0];\n return Number(cell(row, 0, \"isLead\") ?? 0) === 1;\n};\n\n/** The text a gated call would put in front of a human, and the task it belongs to. */\nconst gatedText = (\n tool: string,\n args: Record<string, unknown>,\n sourceTaskId: string | undefined,\n): { text: string; taskId: string } | null => {\n if (tool === \"store-progress\") {\n if (args.status !== \"completed\") return null;\n return {\n text: typeof args.output === \"string\" ? args.output.trim() : \"\",\n taskId: String(args.taskId ?? sourceTaskId ?? \"\"),\n };\n }\n if (SLACK_TOOLS.has(tool)) {\n // slack-reply names its task; the other tools post from the caller's task context.\n const named = tool === \"slack-reply\" ? args.taskId : undefined;\n return {\n text: typeof args.message === \"string\" ? args.message.trim() : \"\",\n taskId: String(named ?? sourceTaskId ?? \"\"),\n };\n }\n return null;\n};\n\nconst extension: SwarmExtension = (api) => {\n api.on(\"pre.tool.call\", async (event, ctx) => {\n if (event.tool !== \"store-progress\" && !SLACK_TOOLS.has(event.tool)) return;\n const origin = event.requestInfo?.callOrigin;\n if (origin === \"extension\") return;\n\n const cfg = cfgOf(ctx.config);\n if (cfg.mode === \"off\" && cfg.plainMode === \"off\") return;\n\n const args = (event.args ?? {}) as Record<string, unknown>;\n\n // Self-test hatch: a progress call whose text starts with the sentinel runs\n // the controls and records them under `selftest:last`.\n if (\n event.tool === \"store-progress\" &&\n args.status !== \"completed\" &&\n typeof args.progress === \"string\" &&\n args.progress.startsWith(SELFTEST)\n ) {\n await selfTest(ctx.swarm, cfg, ctx.signal);\n return;\n }\n\n const gated = gatedText(event.tool, args, event.requestInfo?.sourceTaskId);\n if (!gated?.text) return;\n const { text, taskId } = gated;\n if (!UUID_RE.test(taskId)) return;\n\n try {\n const q = (await ctx.swarm.db_query({ sql: TASK_SQL, params: [taskId] })) as Envelope;\n const row = (q?.data?.rows ?? q?.rows ?? [])[0];\n if (!row) return;\n\n const source = String(cell(row, 0, \"source\") ?? \"\");\n const slackThreadTs = cell(row, 1, \"slackThreadTs\");\n const agentId = String(cell(row, 2, \"agentId\") ?? \"\");\n const requesterId = String(cell(row, 3, \"requestedByUserId\") ?? \"\");\n const commsRaw = cell(row, 4, \"comms\");\n const requesterName = String(cell(row, 5, \"name\") ?? (requesterId || \"the requester\"));\n const threadOpening = String(cell(row, 6, \"askHead\") ?? \"\");\n const ask = latestAsk(String(cell(row, 7, \"askTail\") ?? \"\"));\n\n // Judge only a call the tool itself will accept, so no agent can ship another\n // task's thread and preferences to the external judge. store-progress follows\n // its write rule; the Slack tools follow slack-reply's: the caller is the\n // task's assignee or its creator.\n const callerId = event.requestInfo?.agentId;\n const creatorAgentId = String(cell(row, 8, \"creatorAgentId\") ?? \"\");\n const allowed =\n event.tool === \"store-progress\"\n ? await mayWriteProgress(ctx.swarm, callerId, agentId)\n : Boolean(callerId) && (callerId === agentId || callerId === creatorAgentId);\n if (!allowed) return;\n\n // A completion reaches a human only on a Slack task; a Slack tool always does.\n if (event.tool === \"store-progress\" && source !== \"slack\" && !slackThreadTs) return;\n\n const requester: Audience = {\n id: requesterId,\n name: requesterName,\n prefs: parsePrefs(commsRaw) ?? {},\n via: \"requester\",\n };\n // `plain` alone judges no one's preferences, so it skips the lookup.\n const audience =\n cfg.mode === \"off\" ? requester : await resolveAudience(ctx.swarm, text, requester);\n const { prefs, name: audienceName } = audience;\n\n const questions: Record<string, unknown> = cfg.mode === \"off\" ? {} : buildQuestions(prefs);\n // Only a store-progress outputSchema answer is machine JSON; a Slack post is\n // always read by a human, JSON or not.\n if (cfg.plainMode !== \"off\" && (event.tool !== \"store-progress\" || !looksLikeJson(text)))\n questions.plain = PLAIN_QUESTION;\n if (Object.keys(questions).length === 0) return;\n\n const transport = resolveTransport(cfg);\n const { scores, latencyMs } = await askJev(\n {\n role: \"You audit an AI agent's message to the human who requested the work.\",\n requester: audienceName,\n requester_preferences: prefs,\n latest_request: ask,\n thread_opening: threadOpening,\n judging_rules: JUDGING_RULES,\n plain_language_rules: PLAIN_RULES,\n agent_message: text,\n },\n questions,\n transport,\n cfg,\n ctx.signal,\n );\n\n const limitOf = (dim: string) => (dim === \"plain\" ? cfg.plainThreshold : cfg.threshold);\n const failed = Object.entries(scores)\n .filter(([k, v]) => v < limitOf(k))\n .map(([k]) => k);\n // Script SDK calls never reach pre.tool.call today; if one does, record it only.\n const blocking =\n origin === \"script-sdk\"\n ? []\n : failed.filter((d) => (d === \"plain\" ? cfg.plainMode : cfg.mode) === \"enforce\");\n\n const verdict = {\n at: new Date().toISOString(),\n tool: event.tool,\n taskId,\n agentId,\n source,\n requester: requesterName,\n requesterId,\n judgedFor: audience.via,\n audienceId: audience.id,\n audience: audienceName,\n provider: transport.provider,\n scores,\n failed,\n threshold: cfg.threshold,\n plainThreshold: cfg.plainThreshold,\n mode: cfg.mode,\n plainMode: cfg.plainMode,\n latencyMs,\n preferences: prefs,\n askPreview: ask.slice(0, 400),\n outputPreview: text.slice(0, 700),\n };\n\n await ctx.swarm.kv_incr({ namespace: NS, key: \"total\" });\n await ctx.swarm.kv_set({ namespace: NS, key: \"last\", value: verdict });\n\n if (failed.length === 0) {\n await ctx.swarm.kv_incr({ namespace: NS, key: \"pass\" });\n return;\n }\n\n await ctx.swarm.kv_incr({ namespace: NS, key: \"fail\" });\n for (const dim of failed) {\n await ctx.swarm.kv_incr({ namespace: NS, key: `dim:${safeKey(dim)}` });\n }\n\n const blocksKey = `blocks:${safeKey(taskId)}`;\n // kv_get answers {success, data:{value}}, and {success:false} when absent.\n const prior = (await ctx.swarm.kv_get({ namespace: NS, key: blocksKey })) as Envelope;\n const priorBlocks = Number(prior?.data?.value ?? prior?.value ?? 0) || 0;\n const willBlock = blocking.length > 0 && priorBlocks < cfg.maxBlocksPerTask;\n\n await ctx.swarm.kv_set({\n namespace: NS,\n key: `fail:${Date.now()}:${safeKey(taskId)}`,\n value: { ...verdict, action: willBlock ? \"blocked\" : \"recorded\" },\n });\n\n if (!willBlock) {\n await ctx.swarm.kv_incr({\n namespace: NS,\n key: blocking.length > 0 ? \"escaped\" : \"shadowed\",\n });\n return;\n }\n\n await ctx.swarm.kv_incr({ namespace: NS, key: \"blocked\" });\n await ctx.swarm.kv_incr({ namespace: NS, key: blocksKey });\n\n const lines = [\n blocking.includes(\"plain\")\n ? `Comms gate: this message is not in plain words for ${audienceName}.`\n : `Comms gate: this output does not match ${audienceName}'s stated preferences.`,\n ];\n for (const d of blocking) {\n const score = `${d} (${scores[d]!.toFixed(2)} vs ${limitOf(d)})`;\n lines.push(\n d === \"plain\"\n ? `${score}: a reader outside the swarm cannot follow it on first read.`\n : `${score}: requested ${String(prefs[d] ?? \"\").slice(0, 220)}`,\n );\n }\n lines.push(\n blocking.includes(\"plain\")\n ? `Rewrite the message with the \\`comms\\` skill (Simpler mode): common words, one idea per sentence, every number with a unit and a direction word, shorthand explained or replaced. Keep every number, name, link and hedge verbatim, then call ${event.tool} again.`\n : `Rewrite the message to match and call ${event.tool} again. Do not change the facts, only how they are said.`,\n );\n return block(lines.join(\"\\n\"));\n } catch (err) {\n // Fail open, always.\n try {\n await ctx.swarm.kv_incr({ namespace: NS, key: \"error\" });\n await ctx.swarm.kv_set({\n namespace: NS,\n key: \"error:last\",\n value: {\n at: new Date().toISOString(),\n tool: event.tool,\n taskId,\n error: String(err).slice(0, 400),\n },\n });\n } catch {\n /* ignore */\n }\n ctx.log.warn(\"comms-adherence-gate: failing open\", { error: String(err) });\n return;\n }\n });\n};\n\nexport default extension;\n"
15
+ "hooks.ts": "import { type ApiCtx, block, type SwarmExtension } from \"swarm-extension\";\nimport { z } from \"zod\";\n\n/**\n * comms-adherence-gate\n *\n * When an agent calls `store-progress` with status \"completed\" on a task that\n * reaches a human in Slack, or posts to Slack itself (`slack-reply`,\n * `slack-post`, `slack-start-thread`, `slack-update`), judge the text with Jev:\n * against the requesting user's stored comms preferences\n * (users.metadata.$.comms) and what that user actually asked for in their\n * latest message, and against a plain-language rubric that applies to every\n * message whatever preferences exist. An explicit request (\"tell me a long\n * joke\", \"explain in detail\") outranks the stored default, so a requested long\n * answer is not a verbosity failure.\n *\n * Threads with several people: a message that @-mentions someone is judged\n * against the first mentioned person with stored preferences, skipping a\n * requester without preferences; otherwise against the requester. `plain` applies to everyone.\n *\n * Transport (config.provider): Jev is served by TypeSafe directly and by\n * OpenRouter's Decisions endpoint. Both take the same {model, state, questions}\n * body and return the same `answers` shape. `auto` uses TYPESAFE_API_KEY when\n * set, else OPENROUTER_API_KEY.\n *\n * modes (config.mode for the preference dimensions, config.plainMode for `plain`):\n * off -> never evaluate\n * shadow -> evaluate + record, never block (default)\n * enforce -> record, and block the call up to maxBlocksPerTask times per task\n * with actionable feedback. The budget is shared by both modes and\n * by every gated tool.\n *\n * Fails OPEN on every error: a judge outage must never wall the swarm.\n * Every verdict lands in KV namespace `ext:comms-gate`.\n */\n\nexport const config = z.object({\n mode: z.enum([\"off\", \"shadow\", \"enforce\"]).default(\"shadow\"),\n /** A preference dimension scoring below this fails. */\n threshold: z.number().min(0).max(1).default(0.5),\n /** The `plain` dimension, judged on every message. Independent of `mode`. */\n plainMode: z.enum([\"off\", \"shadow\", \"enforce\"]).default(\"shadow\"),\n /**\n * `plain` scoring below this fails. Jev scores dense status text low and\n * plain text high with little in between, so this sits far below `threshold`.\n */\n plainThreshold: z.number().min(0).max(1).default(0.25),\n timeoutMs: z.number().int().positive().default(4000),\n maxBlocksPerTask: z.number().int().min(0).default(1),\n provider: z.enum([\"auto\", \"typesafe\", \"openrouter\"]).default(\"auto\"),\n /** Jev model on the TypeSafe transport. */\n model: z.string().default(\"jev-latest\"),\n /** Jev model on the OpenRouter transport. */\n openrouterModel: z.string().default(\"typesafe/jev-1.13\"),\n /** Explicit TypeSafe key; otherwise TYPESAFE_API_KEY from the API process env. */\n apiKey: z.string().optional(),\n /**\n * Fixed text the operator's own templates mandate, judged by the self-test and\n * expected to pass. Kept loose here and parsed per entry by `fixturesOf`, so one\n * bad entry cannot fail the whole config and drop `mode` back to its default.\n */\n fixtures: z.unknown().optional(),\n});\n\ntype Cfg = z.infer<typeof config>;\ntype Swarm = ApiCtx[\"swarm\"];\n\nconst NS = \"ext:comms-gate\";\nconst TYPESAFE_ENDPOINT = \"https://api.typesafe.ai/v1/systemone\";\nconst OPENROUTER_ENDPOINT = \"https://openrouter.ai/api/alpha/decisions\";\nconst UUID_RE = /^[0-9a-fA-F-]{36}$/;\n/** MCP tools that post agent-authored text to Slack, all with a `message` arg. */\nexport const SLACK_TOOLS = new Set([\n \"slack-reply\",\n \"slack-post\",\n \"slack-start-thread\",\n \"slack-update\",\n]);\n// The dispatcher cancels a handler after 5 s; leave room for the DB read and KV writes.\nconst MAX_TIMEOUT_MS = 4000;\n\nexport const cfgOf = (raw: unknown): Cfg => {\n const parsed = config.safeParse(raw ?? {});\n return parsed.success ? parsed.data : config.parse({});\n};\n\n// kv keys accept [a-zA-Z0-9._:/%-]\nconst safeKey = (raw: string | undefined | null): string =>\n (raw && raw.length > 0 ? raw : \"unknown\").replace(/[^a-zA-Z0-9._-]/g, \"_\").slice(0, 120);\n\n/** SDK envelopes: {success, data:{...}} or the bare payload. */\ntype Envelope = {\n data?: { rows?: unknown[]; value?: unknown };\n rows?: unknown[];\n value?: unknown;\n} | null;\n\nconst cell = (row: unknown, i: number, key: string): unknown =>\n Array.isArray(row) ? row[i] : (row as Record<string, unknown>)?.[key];\n\n/**\n * The newest human message sits at the END of a Slack task: the\n * `<thread_context>` blob comes first and can run to thousands of chars, so a\n * leading slice of `agent_tasks.task` shows the judge everything except the\n * actual request. Take the tail, then the part after the last `</thread_context>`.\n */\nconst CTX_END = \"</thread_context>\";\nexport const latestAsk = (tail: string): string => {\n const end = tail.lastIndexOf(CTX_END);\n let out = (end >= 0 ? tail.slice(end + CTX_END.length) : tail)\n .replace(/\\[Thread follow-up[^\\]]*\\]/g, \"\")\n .trim();\n // Some tasks end with the context block; fall back to the last messages in it.\n if (out.length < 8) out = (end >= 0 ? tail.slice(0, end) : tail).trim().slice(-800);\n return out.slice(0, 900);\n};\n\n// Preferences are the DEFAULT. A direct request outranks them.\nconst JUDGING_RULES = [\n \"The requester's explicit instruction in latest_request OUTRANKS requester_preferences. Preferences describe the DEFAULT; they never override a direct request.\",\n \"If latest_request asks for something long, detailed, creative, a story, a joke, a full explanation or a document, then length and structure serving that request are CORRECT and must NOT be penalized.\",\n \"Judge whether agent_message serves what latest_request actually asked for, written in the requester's manner. Do not judge it against the default preference when the request overrides it.\",\n];\n\ntype Prefs = { verbosity?: unknown; tone?: unknown; language?: unknown } & Record<string, unknown>;\n\n/**\n * The `plain` rubric, from the `comms` skill (Simpler and Precise modes). Jev\n * separates dense from plain text reliably only with contrasting examples; a\n * prose-only rubric scored a plain rewrite as low as the dense original.\n */\nexport const PLAIN_RULES = [\n \"Examples of NOT plain: 'p50 Δ +120ms vs baseline (n=37)', 'error rate 2.1% → 0.4% (cohort B, ±0.3 at 95%)', 'cost $-42/day', 'first-call hit ratio 0.61', 'drift unmeasured; 2 flaky'.\",\n \"Examples of plain: 'Pages load 120 ms slower than last week, across 37 runs', 'Errors dropped from 2 in 100 requests to 4 in 1,000', 'We spend $42 a day less', 'PR #123 keeps the migration reversible', 'Lead saves about $75 a week'.\",\n \"Code identifiers, task ids, PR numbers, links, file paths and version numbers are fine as they are.\",\n];\n\nexport const PLAIN_QUESTION = {\n type: \"noul\",\n instructions:\n \"Is agent_message written like the plain examples in plain_language_rules rather than like the NOT plain ones? Ignore length and tone.\",\n criteria: {\n true: \"Written like the plain examples: everyday words and numbers with units and direction.\",\n false:\n \"Written like the NOT plain examples: statistics shorthand, abbreviations, signed or cryptic numbers.\",\n },\n};\n\n/** Structured output (an outputSchema answer) is for machines; `plain` skips it. */\nexport const looksLikeJson = (text: string): boolean => {\n if (!/^[[{]/.test(text)) return false;\n try {\n JSON.parse(text);\n return true;\n } catch {\n return false;\n }\n};\n\n/** One `noul` question per stated preference the gate knows how to judge. */\nexport const buildQuestions = (prefs: Prefs): Record<string, unknown> => {\n const questions: Record<string, unknown> = {};\n if (prefs.verbosity) {\n questions.verbosity = {\n type: \"noul\",\n instructions:\n \"Does agent_message respect the requester's verbosity preference, AS OVERRIDDEN by any explicit instruction in latest_request? Apply judging_rules.\",\n criteria: {\n true: \"Length and structure fit what latest_request asked for (or the stated preference when the request does not override it), and it leads with the result.\",\n false:\n \"Too long for what was asked, or it opens with preamble, recaps the request, narrates the process, or ends with an offer to elaborate. Length explicitly requested in latest_request is NOT a failure.\",\n },\n };\n }\n if (prefs.tone) {\n questions.tone = {\n type: \"noul\",\n instructions:\n \"Does agent_message match the requester's stated tone preference, as overridden by any explicit instruction in latest_request? Apply judging_rules.\",\n criteria: {\n true: \"The tone matches what the requester asked for.\",\n false:\n \"The tone conflicts with it (for example hedging, flattery or filler when the requester asked for direct and plain). A voice appropriate to an explicitly requested creative or narrative form is NOT a failure.\",\n },\n };\n }\n if (prefs.language) {\n questions.language = {\n type: \"noul\",\n instructions: \"Is agent_message written in the requester's stated language?\",\n criteria: {\n true: \"Written in the stated language.\",\n false: \"Written in a different language.\",\n },\n };\n }\n return questions;\n};\n\nconst secretCache = new Map<string, { value: string; at: number }>();\nconst KEY_TTL_MS = 5 * 60 * 1000;\nconst usable = (v: string): boolean => Boolean(v) && !v.startsWith(\"[REDACTED\");\nconst envOf = (name: string): string => String(process.env[name] ?? \"\");\n\n/**\n * Resolve a secret: explicit value, then the API process env. The API process loads\n * global swarm_config rows into process.env at boot and on config reload.\n * ctx.swarm.config_get cannot serve it: the SDK scrubs secrets to \"[REDACTED:<name>]\".\n */\nconst secret = (name: string, explicit?: string): string => {\n const cached = secretCache.get(name);\n if (cached && Date.now() - cached.at < KEY_TTL_MS) return cached.value;\n const value = [String(explicit ?? \"\"), envOf(name)].find(usable) ?? \"\";\n if (usable(value)) secretCache.set(name, { value, at: Date.now() });\n return value;\n};\n\n/** Test hook: forget cached secrets. */\nexport const resetKeyCache = (): void => {\n secretCache.clear();\n};\n\nexport type JevTransport = {\n provider: \"typesafe\" | \"openrouter\";\n endpoint: string;\n key: string;\n model: string;\n};\n\n/**\n * Pick the Jev transport. `auto` prefers TypeSafe and falls back to OpenRouter.\n * Throws when the chosen provider has no usable key; the handler fails open.\n */\nexport const resolveTransport = (cfg: Cfg): JevTransport => {\n const typesafe = (): JevTransport | null => {\n const key = secret(\"TYPESAFE_API_KEY\", cfg.apiKey);\n return usable(key)\n ? { provider: \"typesafe\", endpoint: TYPESAFE_ENDPOINT, key, model: cfg.model }\n : null;\n };\n const openrouter = (): JevTransport | null => {\n const key = secret(\"OPENROUTER_API_KEY\");\n return usable(key)\n ? { provider: \"openrouter\", endpoint: OPENROUTER_ENDPOINT, key, model: cfg.openrouterModel }\n : null;\n };\n const transport =\n cfg.provider === \"typesafe\"\n ? typesafe()\n : cfg.provider === \"openrouter\"\n ? openrouter()\n : (typesafe() ?? openrouter());\n if (transport) return transport;\n throw new Error(\n cfg.provider === \"typesafe\"\n ? \"no TYPESAFE_API_KEY\"\n : cfg.provider === \"openrouter\"\n ? \"no OPENROUTER_API_KEY\"\n : \"no TYPESAFE_API_KEY or OPENROUTER_API_KEY\",\n );\n};\n\n/**\n * The judge input for one message. The live gate and the self-test fixtures build it\n * here, so a fixture is judged exactly like real traffic.\n */\nexport const gateState = (s: {\n requester: string;\n prefs: Prefs;\n ask: string;\n threadOpening: string;\n text: string;\n}): Record<string, unknown> => ({\n role: \"You audit an AI agent's message to the human who requested the work.\",\n requester: s.requester,\n requester_preferences: s.prefs,\n latest_request: s.ask,\n thread_opening: s.threadOpening,\n judging_rules: JUDGING_RULES,\n plain_language_rules: PLAIN_RULES,\n agent_message: s.text,\n});\n\n/** One Jev call; returns the `noul` score per question. Throws on any failure. */\nexport const askJev = async (\n state: Record<string, unknown>,\n questions: Record<string, unknown>,\n transport: JevTransport,\n cfg: Cfg,\n outer?: AbortSignal,\n): Promise<{ scores: Record<string, number>; latencyMs: number }> => {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), Math.min(cfg.timeoutMs, MAX_TIMEOUT_MS));\n const onOuterAbort = () => controller.abort();\n outer?.addEventListener(\"abort\", onOuterAbort);\n const t0 = Date.now();\n try {\n const res = await fetch(transport.endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", Authorization: `Bearer ${transport.key}` },\n body: JSON.stringify({ state, model: transport.model, questions }),\n signal: controller.signal,\n });\n if (!res.ok) throw new Error(`${transport.provider} ${res.status}`);\n const body = (await res.json()) as { answers?: Record<string, { noul?: unknown }> } | null;\n const answers = body?.answers;\n if (!answers || typeof answers !== \"object\") throw new Error(\"no answers in response\");\n const scores: Record<string, number> = {};\n for (const [id, a] of Object.entries(answers)) {\n if (typeof a?.noul === \"number\") scores[id] = a.noul;\n }\n if (Object.keys(scores).length === 0) throw new Error(\"no scores in response\");\n return { scores, latencyMs: Date.now() - t0 };\n } finally {\n clearTimeout(timer);\n outer?.removeEventListener(\"abort\", onOuterAbort);\n }\n};\n\nconst SELFTEST = \"comms-gate-selftest\";\nconst SELFTEST_PREFS = {\n tone: \"direct, plain, no hedging\",\n language: \"English\",\n verbosity:\n \"very terse - answer in the first sentence, ~400 chars max. No preamble, no recap, no closing offer.\",\n};\nconst SELFTEST_BAD =\n \"Great question! Let me walk you through what I did here. First I looked at the task, then I reviewed the relevant files, and after careful consideration I decided to go with option B. I hope this helps - let me know if you would like me to elaborate further on any of the above!\";\nconst SELFTEST_GOOD =\n \"Went with option B: it is the only one that keeps the migration reversible. PR #123.\";\n// A real dense monitor post a requester had to ask to have rewritten, and that rewrite.\nconst SELFTEST_PLAIN_BAD =\n \"Prompt cache monitor, day 7 verdict for v2.0.0: partial. Lead first-call read median 12.4k (baseline v1.173.0, n 410) → 19.1k tokens (n 2234; expected 25.0k-40.0k). First-call saving about $75/week on Lead vs v1.173.0 (expected $129; sampling noise ±$24 at 95%, one baseline version, day-to-day drift not measured); session $ change $-167/week; fleet first-call saving $-7/week.\";\nconst SELFTEST_PLAIN_GOOD =\n \"Cheaper, but half what we hoped: Lead saves about $75 a week, not $129. Whole Lead tasks still cost $167 a week more, probably from other releases and heavier work, not this change.\";\n\nconst below = (bad: unknown, good: unknown, threshold: number): boolean =>\n typeof bad === \"number\" && typeof good === \"number\" && bad < threshold && good >= threshold;\n\n/** Fixtures judged per self-test run: one Jev call each, inside the 5 s handler budget. */\nexport const MAX_FIXTURES = 8;\nconst fixture = z.object({\n name: z.string().min(1).max(80),\n /** The fixed text as it will be posted, placeholders filled with sample values. */\n text: z.string().min(1).max(4000),\n /** Audience preferences; omit to judge `plain` only. */\n prefs: z\n .object({\n verbosity: z.string().optional(),\n tone: z.string().optional(),\n language: z.string().optional(),\n })\n .optional(),\n /** The request the text answers, as `latest_request`. */\n request: z.string().max(900).optional(),\n});\nexport type Fixture = z.infer<typeof fixture>;\n\n/** Valid fixture entries, in order, capped at MAX_FIXTURES; invalid entries are skipped. */\nexport const fixturesOf = (raw: unknown): Fixture[] =>\n (Array.isArray(raw) ? raw : [])\n .map((f) => fixture.safeParse(f))\n .filter((r) => r.success)\n .map((r) => r.data)\n .slice(0, MAX_FIXTURES);\n\n/**\n * Judge each fixture with the live gate's questions and state. A fixture is fixed\n * text the operator expects to pass, so any dimension below its threshold fails it.\n */\nconst judgeFixtures = async (\n fixtures: Fixture[],\n transport: JevTransport,\n cfg: Cfg,\n signal?: AbortSignal,\n) =>\n Promise.all(\n fixtures.map(async (f) => {\n const prefs: Prefs = f.prefs ?? {};\n const questions = { ...buildQuestions(prefs), plain: PLAIN_QUESTION };\n try {\n const { scores } = await askJev(\n gateState({\n requester: \"the requester\",\n prefs,\n ask: f.request ?? \"\",\n threadOpening: \"\",\n text: f.text,\n }),\n questions,\n transport,\n cfg,\n signal,\n );\n const failed = Object.keys(questions).filter((dim) => {\n const s = scores[dim];\n return typeof s !== \"number\" || s < (dim === \"plain\" ? cfg.plainThreshold : cfg.threshold);\n });\n return { name: f.name, scores, failed, pass: failed.length === 0 };\n } catch (err) {\n return { name: f.name, error: String(err).slice(0, 200), pass: false };\n }\n }),\n );\n\n/**\n * Run the judge on known-bad (positive control, must score below threshold) and\n * known-good (negative control, must score at or above it) messages and record\n * them under `selftest:last`: one pair for verbosity, one for `plain`. Proves key,\n * egress and KV from inside the API runtime without touching real traffic.\n */\nconst selfTest = async (swarm: Swarm, cfg: Cfg, signal?: AbortSignal): Promise<void> => {\n const started = Date.now();\n try {\n const transport = resolveTransport(cfg);\n const judge = (message: string, dim: \"verbosity\" | \"plain\") =>\n askJev(\n dim === \"plain\"\n ? { plain_language_rules: PLAIN_RULES, agent_message: message }\n : { requester_preferences: SELFTEST_PREFS, agent_message: message },\n { [dim]: dim === \"plain\" ? PLAIN_QUESTION : buildQuestions(SELFTEST_PREFS).verbosity },\n transport,\n cfg,\n signal,\n ).then((r) => r.scores[dim] ?? null);\n const fixtures = fixturesOf(cfg.fixtures);\n const [bad, good, plainBad, plainGood, fixtureResults] = await Promise.all([\n judge(SELFTEST_BAD, \"verbosity\"),\n judge(SELFTEST_GOOD, \"verbosity\"),\n judge(SELFTEST_PLAIN_BAD, \"plain\"),\n judge(SELFTEST_PLAIN_GOOD, \"plain\"),\n judgeFixtures(fixtures, transport, cfg, signal),\n ]);\n await swarm.kv_set({\n namespace: NS,\n key: \"selftest:last\",\n value: {\n at: new Date().toISOString(),\n provider: transport.provider,\n threshold: cfg.threshold,\n positiveControlBadScore: bad,\n negativeControlGoodScore: good,\n controlsOk: below(bad, good, cfg.threshold),\n plainThreshold: cfg.plainThreshold,\n plainPositiveControlBadScore: plainBad,\n plainNegativeControlGoodScore: plainGood,\n plainControlsOk: below(plainBad, plainGood, cfg.plainThreshold),\n fixtures: fixtureResults,\n // null when none are configured: zero fixtures is not a pass.\n fixturesOk: fixtureResults.length === 0 ? null : fixtureResults.every((f) => f.pass),\n latencyMs: Date.now() - started,\n },\n });\n } catch (err) {\n await swarm\n .kv_set({\n namespace: NS,\n key: \"selftest:last\",\n value: {\n at: new Date().toISOString(),\n error: String(err).slice(0, 400),\n latencyMs: Date.now() - started,\n },\n })\n .catch(() => {});\n }\n};\n\nconst TASK_SQL = `SELECT t.source, t.slackThreadTs, t.agentId, t.requestedByUserId,\n json_extract(u.metadata, '$.comms') AS comms, u.name,\n substr(t.task, 1, 400) AS askHead,\n substr(t.task, -1400) AS askTail,\n t.creatorAgentId\nFROM agent_tasks t\nLEFT JOIN users u ON u.id = t.requestedByUserId\nWHERE t.id = ?`;\n\nconst LEAD_SQL = \"SELECT isLead FROM agents WHERE id = ?\";\n\n/** Slack user mentions in agent text: `<@U123>` or `<@U123|name>`. */\nconst MENTION_RE = /<@([UW][A-Z0-9]+)(?:\\|[^>]*)?>/g;\nconst MAX_MENTIONS = 5;\n\n/** Mentioned Slack user ids in order of first appearance, capped. */\nexport const mentionedSlackIds = (text: string): string[] => {\n const ids: string[] = [];\n for (const m of text.matchAll(MENTION_RE)) {\n if (!ids.includes(m[1]!)) ids.push(m[1]!);\n if (ids.length >= MAX_MENTIONS) break;\n }\n return ids;\n};\n\nconst addresseeSql = (n: number) => `SELECT x.externalId, u.id, u.name,\n json_extract(u.metadata, '$.comms') AS comms\nFROM user_external_ids x\nJOIN users u ON u.id = x.userId\nWHERE x.kind = 'slack' AND x.externalId IN (${Array(n).fill(\"?\").join(\", \")})`;\n\nconst parsePrefs = (raw: unknown): Prefs | null => {\n if (!raw) return null;\n const parsed = typeof raw === \"string\" ? JSON.parse(raw) : raw;\n return parsed && typeof parsed === \"object\" && Object.keys(parsed).length > 0\n ? (parsed as Prefs)\n : null;\n};\n\ntype Audience = { id: string; name: string; prefs: Prefs; via: \"mention\" | \"requester\" };\n\n/**\n * Whose preferences a message is judged against. In a thread with several\n * people, the message is for whoever it @-mentions: the first mentioned person\n * with stored preferences wins, including the requester only if they have prefs.\n * Without such a mention, the task requester (the\n * person whose message created this task). One SQL read, only when the text\n * mentions someone; no judge call.\n */\nconst resolveAudience = async (\n swarm: Swarm,\n text: string,\n requester: Audience,\n): Promise<Audience> => {\n const ids = mentionedSlackIds(text);\n if (ids.length === 0) return requester;\n const q = (await swarm.db_query({ sql: addresseeSql(ids.length), params: ids })) as Envelope;\n const rows = q?.data?.rows ?? q?.rows ?? [];\n for (const slackId of ids) {\n const row = rows.find((r) => String(cell(r, 0, \"externalId\")) === slackId);\n if (!row) continue;\n const userId = String(cell(row, 1, \"id\") ?? \"\");\n // A requester with stored preferences keeps their own task context.\n if (userId && userId === requester.id) {\n if (Object.keys(requester.prefs).length > 0) return requester;\n continue;\n }\n const prefs = parsePrefs(cell(row, 3, \"comms\"));\n if (!prefs) continue;\n return { id: userId, name: String(cell(row, 2, \"name\") ?? userId), prefs, via: \"mention\" };\n }\n return requester;\n};\n\n/**\n * Mirrors the `task.progress.write` rule store-progress enforces\n * (src/rbac/legacy-policy.ts): the caller owns the task, the task is\n * unassigned, or the caller is a lead. Lead status comes from the caller's\n * agents row, never from tool args. Extension callers return before this.\n */\nconst mayWriteProgress = async (\n swarm: Swarm,\n callerId: string | undefined,\n taskAgentId: string,\n): Promise<boolean> => {\n if (!callerId) return false;\n if (!taskAgentId || taskAgentId === callerId) return true;\n const q = (await swarm.db_query({ sql: LEAD_SQL, params: [callerId] })) as Envelope;\n const row = (q?.data?.rows ?? q?.rows ?? [])[0];\n return Number(cell(row, 0, \"isLead\") ?? 0) === 1;\n};\n\n/** The text a gated call would put in front of a human, and the task it belongs to. */\nconst gatedText = (\n tool: string,\n args: Record<string, unknown>,\n sourceTaskId: string | undefined,\n): { text: string; taskId: string } | null => {\n if (tool === \"store-progress\") {\n if (args.status !== \"completed\") return null;\n return {\n text: typeof args.output === \"string\" ? args.output.trim() : \"\",\n taskId: String(args.taskId ?? sourceTaskId ?? \"\"),\n };\n }\n if (SLACK_TOOLS.has(tool)) {\n // slack-reply names its task; the other tools post from the caller's task context.\n const named = tool === \"slack-reply\" ? args.taskId : undefined;\n return {\n text: typeof args.message === \"string\" ? args.message.trim() : \"\",\n taskId: String(named ?? sourceTaskId ?? \"\"),\n };\n }\n return null;\n};\n\nconst extension: SwarmExtension = (api) => {\n api.on(\"pre.tool.call\", async (event, ctx) => {\n if (event.tool !== \"store-progress\" && !SLACK_TOOLS.has(event.tool)) return;\n const origin = event.requestInfo?.callOrigin;\n if (origin === \"extension\") return;\n\n const cfg = cfgOf(ctx.config);\n if (cfg.mode === \"off\" && cfg.plainMode === \"off\") return;\n\n const args = (event.args ?? {}) as Record<string, unknown>;\n\n // Self-test hatch: a progress call whose text starts with the sentinel runs\n // the controls and records them under `selftest:last`.\n if (\n event.tool === \"store-progress\" &&\n args.status !== \"completed\" &&\n typeof args.progress === \"string\" &&\n args.progress.startsWith(SELFTEST)\n ) {\n await selfTest(ctx.swarm, cfg, ctx.signal);\n return;\n }\n\n const gated = gatedText(event.tool, args, event.requestInfo?.sourceTaskId);\n if (!gated?.text) return;\n const { text, taskId } = gated;\n if (!UUID_RE.test(taskId)) return;\n\n try {\n const q = (await ctx.swarm.db_query({ sql: TASK_SQL, params: [taskId] })) as Envelope;\n const row = (q?.data?.rows ?? q?.rows ?? [])[0];\n if (!row) return;\n\n const source = String(cell(row, 0, \"source\") ?? \"\");\n const slackThreadTs = cell(row, 1, \"slackThreadTs\");\n const agentId = String(cell(row, 2, \"agentId\") ?? \"\");\n const requesterId = String(cell(row, 3, \"requestedByUserId\") ?? \"\");\n const commsRaw = cell(row, 4, \"comms\");\n const requesterName = String(cell(row, 5, \"name\") ?? (requesterId || \"the requester\"));\n const threadOpening = String(cell(row, 6, \"askHead\") ?? \"\");\n const ask = latestAsk(String(cell(row, 7, \"askTail\") ?? \"\"));\n\n // Judge only a call the tool itself will accept, so no agent can ship another\n // task's thread and preferences to the external judge. store-progress follows\n // its write rule; the Slack tools follow slack-reply's: the caller is the\n // task's assignee or its creator.\n const callerId = event.requestInfo?.agentId;\n const creatorAgentId = String(cell(row, 8, \"creatorAgentId\") ?? \"\");\n const allowed =\n event.tool === \"store-progress\"\n ? await mayWriteProgress(ctx.swarm, callerId, agentId)\n : Boolean(callerId) && (callerId === agentId || callerId === creatorAgentId);\n if (!allowed) return;\n\n // A completion reaches a human only on a Slack task; a Slack tool always does.\n if (event.tool === \"store-progress\" && source !== \"slack\" && !slackThreadTs) return;\n\n const requester: Audience = {\n id: requesterId,\n name: requesterName,\n prefs: parsePrefs(commsRaw) ?? {},\n via: \"requester\",\n };\n // `plain` alone judges no one's preferences, so it skips the lookup.\n const audience =\n cfg.mode === \"off\" ? requester : await resolveAudience(ctx.swarm, text, requester);\n const { prefs, name: audienceName } = audience;\n\n const questions: Record<string, unknown> = cfg.mode === \"off\" ? {} : buildQuestions(prefs);\n // Only a store-progress outputSchema answer is machine JSON; a Slack post is\n // always read by a human, JSON or not.\n if (cfg.plainMode !== \"off\" && (event.tool !== \"store-progress\" || !looksLikeJson(text)))\n questions.plain = PLAIN_QUESTION;\n if (Object.keys(questions).length === 0) return;\n\n const transport = resolveTransport(cfg);\n const { scores, latencyMs } = await askJev(\n gateState({ requester: audienceName, prefs, ask, threadOpening, text }),\n questions,\n transport,\n cfg,\n ctx.signal,\n );\n\n const limitOf = (dim: string) => (dim === \"plain\" ? cfg.plainThreshold : cfg.threshold);\n const failed = Object.entries(scores)\n .filter(([k, v]) => v < limitOf(k))\n .map(([k]) => k);\n // Script SDK calls never reach pre.tool.call today; if one does, record it only.\n const blocking =\n origin === \"script-sdk\"\n ? []\n : failed.filter((d) => (d === \"plain\" ? cfg.plainMode : cfg.mode) === \"enforce\");\n\n const verdict = {\n at: new Date().toISOString(),\n tool: event.tool,\n taskId,\n agentId,\n source,\n requester: requesterName,\n requesterId,\n judgedFor: audience.via,\n audienceId: audience.id,\n audience: audienceName,\n provider: transport.provider,\n scores,\n failed,\n threshold: cfg.threshold,\n plainThreshold: cfg.plainThreshold,\n mode: cfg.mode,\n plainMode: cfg.plainMode,\n latencyMs,\n preferences: prefs,\n askPreview: ask.slice(0, 400),\n outputPreview: text.slice(0, 700),\n };\n\n await ctx.swarm.kv_incr({ namespace: NS, key: \"total\" });\n await ctx.swarm.kv_set({ namespace: NS, key: \"last\", value: verdict });\n\n if (failed.length === 0) {\n await ctx.swarm.kv_incr({ namespace: NS, key: \"pass\" });\n return;\n }\n\n await ctx.swarm.kv_incr({ namespace: NS, key: \"fail\" });\n for (const dim of failed) {\n await ctx.swarm.kv_incr({ namespace: NS, key: `dim:${safeKey(dim)}` });\n }\n\n const blocksKey = `blocks:${safeKey(taskId)}`;\n // kv_get answers {success, data:{value}}, and {success:false} when absent.\n const prior = (await ctx.swarm.kv_get({ namespace: NS, key: blocksKey })) as Envelope;\n const priorBlocks = Number(prior?.data?.value ?? prior?.value ?? 0) || 0;\n const willBlock = blocking.length > 0 && priorBlocks < cfg.maxBlocksPerTask;\n\n await ctx.swarm.kv_set({\n namespace: NS,\n key: `fail:${Date.now()}:${safeKey(taskId)}`,\n value: { ...verdict, action: willBlock ? \"blocked\" : \"recorded\" },\n });\n\n if (!willBlock) {\n await ctx.swarm.kv_incr({\n namespace: NS,\n key: blocking.length > 0 ? \"escaped\" : \"shadowed\",\n });\n return;\n }\n\n await ctx.swarm.kv_incr({ namespace: NS, key: \"blocked\" });\n await ctx.swarm.kv_incr({ namespace: NS, key: blocksKey });\n\n const lines = [\n blocking.includes(\"plain\")\n ? `Comms gate: this message is not in plain words for ${audienceName}.`\n : `Comms gate: this output does not match ${audienceName}'s stated preferences.`,\n ];\n for (const d of blocking) {\n const score = `${d} (${scores[d]!.toFixed(2)} vs ${limitOf(d)})`;\n lines.push(\n d === \"plain\"\n ? `${score}: a reader outside the swarm cannot follow it on first read.`\n : `${score}: requested ${String(prefs[d] ?? \"\").slice(0, 220)}`,\n );\n }\n lines.push(\n blocking.includes(\"plain\")\n ? `Rewrite the message with the \\`comms\\` skill (Simpler mode): common words, one idea per sentence, every number with a unit and a direction word, shorthand explained or replaced. Keep every number, name, link and hedge verbatim, then call ${event.tool} again.`\n : `Rewrite the message to match and call ${event.tool} again. Do not change the facts, only how they are said.`,\n );\n return block(lines.join(\"\\n\"));\n } catch (err) {\n // Fail open, always.\n try {\n await ctx.swarm.kv_incr({ namespace: NS, key: \"error\" });\n await ctx.swarm.kv_set({\n namespace: NS,\n key: \"error:last\",\n value: {\n at: new Date().toISOString(),\n tool: event.tool,\n taskId,\n error: String(err).slice(0, 400),\n },\n });\n } catch {\n /* ignore */\n }\n ctx.log.warn(\"comms-adherence-gate: failing open\", { error: String(err) });\n return;\n }\n });\n};\n\nexport default extension;\n"
16
16
  },
17
- "readme": "# comms-adherence-gate\n\nAgents finish Slack tasks with a final message a human reads, and post to Slack threads directly. This extension judges that text with Jev, [TypeSafe](https://typesafe.ai)'s decision model: against the requester's stated comms preferences and their latest request, and against a plain-language rubric that applies to every message. In `enforce` it blocks a failing call once and tells the agent what to fix. A `plain` failure points the agent at the `comms` skill.\n\nInstall config:\n\n```json\n{ \"mode\": \"shadow\", \"plainMode\": \"shadow\" }\n```\n\nStart in `shadow`, read the verdicts in KV for a few days, then switch to `enforce`. `mode` and `plainMode` move independently.\n\n## Modes\n\n| `mode` | Effect |\n|---|---|\n| `off` | Never evaluates. |\n| `shadow` (default) | Asks Jev and records the verdict. Never blocks. |\n| `enforce` | Asks Jev, records the verdict, and blocks the call when a dimension fails, at most `maxBlocksPerTask` times per task. The agent gets the failed dimensions, their scores and the stated preference, and calls again. |\n\n`mode` governs the preference dimensions (`verbosity`, `tone`, `language`). `plainMode` governs `plain`. A dimension blocks only when its own mode is `enforce`. Both share one block budget per task, across every gated tool.\n\n## What it gates\n\nHook: `pre.tool.call` on:\n\n- `store-progress` with `status: \"completed\"` and a non-empty `output`, on a task that came from Slack (`source = \"slack\"` or a `slackThreadTs`). Other completions pass without a Jev call.\n- `slack-reply`, `slack-post`, `slack-start-thread` and `slack-update`, judged on `message`. The task is `slack-reply`'s `taskId`, else the caller's task context. A post with no task context passes.\n\nOnly a call the tool itself accepts is judged, so no other task's text reaches Jev. For `store-progress` the caller must own the task, the task must be unassigned, or the caller must be a lead. For the Slack tools the caller must be the task's assignee or its creator, the rule `slack-reply` enforces. Calls made by extensions are skipped. Script SDK calls never reach `pre.tool.call` (the tool registrar dispatches it only for MCP calls); if one ever does, the gate records it and never blocks.\n\nA requester with no stated preferences in `users.metadata.comms` still gets the `plain` question. Set preferences with the `manage-user` tool.\n\nIn a thread with several people, the requester is the person whose message created the task. A message that @-mentions someone (`<@U123>`) is judged against the first mentioned person with stored preferences, resolved through their Slack identity in `user_external_ids`; otherwise against the requester. The lookup is one SQL read, only when the text mentions someone and `mode` is not `off`. The verdict records who was judged in `judgedFor` (`mention` or `requester`) and `audience`.\n\n## Decision\n\nThe gate reads the task row and asks one `noul` question per stated preference it knows: `verbosity`, `tone`, `language`. Any other key in `comms` is context only.\n\nJev sees the preferences, the requester's latest message (the text after the last `</thread_context>`, from the last 1,400 characters of the task), the first 400 characters of the task, and the output. Its judging rules say an explicit request outranks the stored default. A requested long answer, story or document is not a verbosity failure.\n\nIt also asks `plain` on every message unless `plainMode` is `off` or the text is a JSON document (structured output for an `outputSchema`). The rubric comes from the `comms` skill: everyday words, one idea per sentence, every number with a unit and a direction word, and no unexplained shorthand (n, median, p90, cohort, baseline, delta, `±X at 95%`). Code identifiers, task ids, PR numbers, links and versions are fine. Jev gets contrasting plain and dense examples in `plain_language_rules`; a prose-only rubric scored plain rewrites as low as the dense originals.\n\nAll questions go in one Jev request. A preference dimension fails below `threshold`; `plain` fails below `plainThreshold`. Any failed dimension fails the message.\n\n### Calibration of `plain`\n\nJev scores dense status text near 0 and plain text near 0.8 to 0.9, with a wide middle of compact but readable engineering notes. Measured on 400 Slack-facing completions over 7 days, at `threshold` 0.75 for preferences:\n\n| `plainThreshold` | Newly blocked (of messages that pass today) |\n|---|---|\n| 0.75 | 81% to 83% |\n| 0.3 | 9% to 13% |\n| 0.25 (default) | 5% to 7% |\n\nAt 0.25 the dense prompt-cache-monitor post scores about 0.15 and its plain rewrite about 0.81.\n\n## Jev transport\n\nJev is reachable two ways. Both take the same request and return the same answer.\n\n| `provider` | Endpoint | Key | Model |\n|---|---|---|---|\n| `typesafe` | `POST https://api.typesafe.ai/v1/systemone` | `TYPESAFE_API_KEY` (or `apiKey`) | `model`, default `jev-latest` |\n| `openrouter` | `POST https://openrouter.ai/api/alpha/decisions` | `OPENROUTER_API_KEY` | `openrouterModel`, default `typesafe/jev-1.13` |\n| `auto` (default) | TypeSafe when its key is set, else OpenRouter | | |\n\nEach verdict row records the `provider` that answered.\n\n## Fail open\n\nEvery error lets the completion through: a missing key, an HTTP error, a network error, a timeout, a malformed answer, or a failed DB read. The handler never throws, so an outage cannot auto-disable the extension. Each failure bumps the `error` counter and overwrites `error:last`.\n\n## Self-test\n\nCall `store-progress` with a non-completed status and `progress` starting with `comms-gate-selftest`. The gate judges a known-bad and a known-good message against a terse preference, and a dense and a plain message on `plain`, then writes `selftest:last`: every score, both thresholds, the provider, `controlsOk` (verbosity: bad below `threshold`, good at or above it) and `plainControlsOk` (the same against `plainThreshold`). Real traffic is untouched.\n\n## Config\n\n| Key | Default | Notes |\n|---|---|---|\n| `mode` | `shadow` | `off`, `shadow`, or `enforce` |\n| `threshold` | `0.5` | A preference dimension scoring below this fails |\n| `plainMode` | `shadow` | `off`, `shadow`, or `enforce` for the `plain` dimension |\n| `plainThreshold` | `0.25` | `plain` scoring below this fails. See [Calibration](#calibration-of-plain) |\n| `timeoutMs` | `4000` | Jev call timeout, capped at 4000 (the dispatcher cancels a handler at 5 s) |\n| `maxBlocksPerTask` | `1` | Blocks per task in `enforce`; after that the gate records and lets it through |\n| `provider` | `auto` | `auto`, `typesafe`, or `openrouter`. See [Jev transport](#jev-transport) |\n| `model` | `jev-latest` | Jev model on TypeSafe |\n| `openrouterModel` | `typesafe/jev-1.13` | Jev model on OpenRouter |\n| `apiKey` | unset | Explicit TypeSafe key. Prefer the `TYPESAFE_API_KEY` secret below |\n\n## Required secrets\n\nRead from the API process environment at call time. Set them as global `swarm_config` secrets: the API process loads global rows into `process.env` at boot and on config reload.\n\n- `TYPESAFE_API_KEY` or `OPENROUTER_API_KEY`: one is required for any evaluation. Under `auto`, TypeSafe wins when both are set. Without either, every completion fails open.\n\nNo key is written to config, KV, logs, or a block reason.\n\n## KV namespace `ext:comms-gate`\n\n- `last`: the latest verdict, with `tool`, `scores`, `failed`, `mode`, `plainMode`, `provider`, `latencyMs`, the preferences, a 400-character `askPreview` and a 700-character `outputPreview`.\n- `fail:<epochMs>:<taskId>`: one row per failed verdict, with `action` (`blocked` or `recorded`).\n- `blocks:<taskId>`: blocks issued for that task.\n- `error:last`, `selftest:last`.\n- Counters: `total`, `pass`, `fail`, `blocked`, `escaped` (a blocking dimension failed, block budget spent), `shadowed` (only non-blocking dimensions failed), `error`, and `dim:<dimension>`.\n\n## Known limits\n\n- Only the last 1,400 characters of the task are searched for the latest request. A very long final message is cut to its last 900 characters.\n- The block budget is per task, so a retried call after a block goes through once the budget is spent, even if it still fails.\n- Each gated Slack post waits for one Jev call (about 0.2 s measured, capped by `timeoutMs`).\n"
17
+ "readme": "# comms-adherence-gate\n\nAgents finish Slack tasks with a final message a human reads, and post to Slack threads directly. This extension judges that text with Jev, [TypeSafe](https://typesafe.ai)'s decision model: against the requester's stated comms preferences and their latest request, and against a plain-language rubric that applies to every message. In `enforce` it blocks a failing call once and tells the agent what to fix. A `plain` failure points the agent at the `comms` skill.\n\nInstall config:\n\n```json\n{ \"mode\": \"shadow\", \"plainMode\": \"shadow\" }\n```\n\nStart in `shadow`, read the verdicts in KV for a few days, then switch to `enforce`. `mode` and `plainMode` move independently.\n\n## Modes\n\n| `mode` | Effect |\n|---|---|\n| `off` | Never evaluates. |\n| `shadow` (default) | Asks Jev and records the verdict. Never blocks. |\n| `enforce` | Asks Jev, records the verdict, and blocks the call when a dimension fails, at most `maxBlocksPerTask` times per task. The agent gets the failed dimensions, their scores and the stated preference, and calls again. |\n\n`mode` governs the preference dimensions (`verbosity`, `tone`, `language`). `plainMode` governs `plain`. A dimension blocks only when its own mode is `enforce`. Both share one block budget per task, across every gated tool.\n\n## What it gates\n\nHook: `pre.tool.call` on:\n\n- `store-progress` with `status: \"completed\"` and a non-empty `output`, on a task that came from Slack (`source = \"slack\"` or a `slackThreadTs`). Other completions pass without a Jev call.\n- `slack-reply`, `slack-post`, `slack-start-thread` and `slack-update`, judged on `message`. The task is `slack-reply`'s `taskId`, else the caller's task context. A post with no task context passes.\n\nOnly a call the tool itself accepts is judged, so no other task's text reaches Jev. For `store-progress` the caller must own the task, the task must be unassigned, or the caller must be a lead. For the Slack tools the caller must be the task's assignee or its creator, the rule `slack-reply` enforces. Calls made by extensions are skipped. Script SDK calls never reach `pre.tool.call` (the tool registrar dispatches it only for MCP calls); if one ever does, the gate records it and never blocks.\n\nA requester with no stated preferences in `users.metadata.comms` still gets the `plain` question. Set preferences with the `manage-user` tool.\n\nIn a thread with several people, the requester is the person whose message created the task. A message that @-mentions someone (`<@U123>`) is judged against the first mentioned person with stored preferences, resolved through their Slack identity in `user_external_ids`; otherwise against the requester. The lookup is one SQL read, only when the text mentions someone and `mode` is not `off`. The verdict records who was judged in `judgedFor` (`mention` or `requester`) and `audience`.\n\n## Decision\n\nThe gate reads the task row and asks one `noul` question per stated preference it knows: `verbosity`, `tone`, `language`. Any other key in `comms` is context only.\n\nJev sees the preferences, the requester's latest message (the text after the last `</thread_context>`, from the last 1,400 characters of the task), the first 400 characters of the task, and the output. Its judging rules say an explicit request outranks the stored default. A requested long answer, story or document is not a verbosity failure.\n\nIt also asks `plain` on every message unless `plainMode` is `off` or the text is a JSON document (structured output for an `outputSchema`). The rubric comes from the `comms` skill: everyday words, one idea per sentence, every number with a unit and a direction word, and no unexplained shorthand (n, median, p90, cohort, baseline, delta, `±X at 95%`). Code identifiers, task ids, PR numbers, links and versions are fine. Jev gets contrasting plain and dense examples in `plain_language_rules`; a prose-only rubric scored plain rewrites as low as the dense originals.\n\nAll questions go in one Jev request. A preference dimension fails below `threshold`; `plain` fails below `plainThreshold`. Any failed dimension fails the message.\n\n### Calibration of `plain`\n\nJev scores dense status text near 0 and plain text near 0.8 to 0.9, with a wide middle of compact but readable engineering notes. Measured on 400 Slack-facing completions over 7 days, at `threshold` 0.75 for preferences:\n\n| `plainThreshold` | Newly blocked (of messages that pass today) |\n|---|---|\n| 0.75 | 81% to 83% |\n| 0.3 | 9% to 13% |\n| 0.25 (default) | 5% to 7% |\n\nAt 0.25 the dense prompt-cache-monitor post scores about 0.15 and its plain rewrite about 0.81.\n\n## Jev transport\n\nJev is reachable two ways. Both take the same request and return the same answer.\n\n| `provider` | Endpoint | Key | Model |\n|---|---|---|---|\n| `typesafe` | `POST https://api.typesafe.ai/v1/systemone` | `TYPESAFE_API_KEY` (or `apiKey`) | `model`, default `jev-latest` |\n| `openrouter` | `POST https://openrouter.ai/api/alpha/decisions` | `OPENROUTER_API_KEY` | `openrouterModel`, default `typesafe/jev-1.13` |\n| `auto` (default) | TypeSafe when its key is set, else OpenRouter | | |\n\nEach verdict row records the `provider` that answered.\n\n## Fail open\n\nEvery error lets the completion through: a missing key, an HTTP error, a network error, a timeout, a malformed answer, or a failed DB read. The handler never throws, so an outage cannot auto-disable the extension. Each failure bumps the `error` counter and overwrites `error:last`.\n\n## Self-test\n\nCall `store-progress` with a non-completed status and `progress` starting with `comms-gate-selftest`. The gate judges a known-bad and a known-good message against a terse preference, and a dense and a plain message on `plain`, then writes `selftest:last`: every score, both thresholds, the provider, `controlsOk` (verbosity: bad below `threshold`, good at or above it) and `plainControlsOk` (the same against `plainThreshold`). Real traffic is untouched.\n\n### Fixtures\n\nFixed text that your own templates tell an agent to post (a daily report's all-clear line, a standard reply) should pass the gate. List it under `fixtures` and the self-test judges each entry with the same state and questions as real traffic, then records `fixtures` (per entry: `name`, `scores`, `failed`, `pass`) and `fixturesOk` in `selftest:last`. A failing fixture means the template line or the gate needs a fix before a quiet day forces an ad-hoc rewrite.\n\n```json\n{\n \"fixtures\": [\n { \"name\": \"daily-report-all-clear\", \"text\": \"📊 11-03: all clear, nothing for you. 56 of 73 workflows are turned on.\" },\n {\n \"name\": \"short-reply\",\n \"text\": \"Went with option B: it keeps the migration reversible. PR #123.\",\n \"prefs\": { \"verbosity\": \"very terse, ~400 chars max\" },\n \"request\": \"which option did you pick?\"\n }\n ]\n}\n```\n\nFill placeholders with realistic sample values. `prefs` adds the preference dimensions it names; without it only `plain` is judged. At most 8 entries run; an invalid entry is skipped, never fatal to the rest of the config.\n\n`fixturesOk` is `true` only when at least one entry ran and every entry passed. It is `null` when no valid entry ran: `fixtures` unset, an explicit `fixtures: []`, or every entry invalid. `null` means nothing was checked, so never read it as a pass. A skipped entry is missing from `fixtures` in `selftest:last`, so compare that list with your config.\n\nUnit tests mock Jev, so they cannot show that a line passes. Only the self-test, which calls the live judge, can.\n\n## Config\n\n| Key | Default | Notes |\n|---|---|---|\n| `mode` | `shadow` | `off`, `shadow`, or `enforce` |\n| `threshold` | `0.5` | A preference dimension scoring below this fails |\n| `plainMode` | `shadow` | `off`, `shadow`, or `enforce` for the `plain` dimension |\n| `plainThreshold` | `0.25` | `plain` scoring below this fails. See [Calibration](#calibration-of-plain) |\n| `timeoutMs` | `4000` | Jev call timeout, capped at 4000 (the dispatcher cancels a handler at 5 s) |\n| `maxBlocksPerTask` | `1` | Blocks per task in `enforce`; after that the gate records and lets it through |\n| `provider` | `auto` | `auto`, `typesafe`, or `openrouter`. See [Jev transport](#jev-transport) |\n| `model` | `jev-latest` | Jev model on TypeSafe |\n| `openrouterModel` | `typesafe/jev-1.13` | Jev model on OpenRouter |\n| `apiKey` | unset | Explicit TypeSafe key. Prefer the `TYPESAFE_API_KEY` secret below |\n| `fixtures` | unset | Fixed template text the self-test expects to pass. See [Fixtures](#fixtures) |\n\n## Required secrets\n\nRead from the API process environment at call time. Set them as global `swarm_config` secrets: the API process loads global rows into `process.env` at boot and on config reload.\n\n- `TYPESAFE_API_KEY` or `OPENROUTER_API_KEY`: one is required for any evaluation. Under `auto`, TypeSafe wins when both are set. Without either, every completion fails open.\n\nNo key is written to config, KV, logs, or a block reason.\n\n## KV namespace `ext:comms-gate`\n\n- `last`: the latest verdict, with `tool`, `scores`, `failed`, `mode`, `plainMode`, `provider`, `latencyMs`, the preferences, a 400-character `askPreview` and a 700-character `outputPreview`.\n- `fail:<epochMs>:<taskId>`: one row per failed verdict, with `action` (`blocked` or `recorded`).\n- `blocks:<taskId>`: blocks issued for that task.\n- `error:last`, `selftest:last`.\n- Counters: `total`, `pass`, `fail`, `blocked`, `escaped` (a blocking dimension failed, block budget spent), `shadowed` (only non-blocking dimensions failed), `error`, and `dim:<dimension>`.\n\n## Known limits\n\n- Only the last 1,400 characters of the task are searched for the latest request. A very long final message is cut to its last 900 characters.\n- The block budget is per task, so a retried call after a block goes through once the budget is spent, even if it still fails.\n- Each gated Slack post waits for one Jev call (about 0.2 s measured, capped by `timeoutMs`).\n"
18
18
  },
19
19
  "deploy-awareness": {
20
20
  "manifestFile": "manifest.json",
@@ -51,6 +51,7 @@ import {
51
51
  upsertKv,
52
52
  } from "../be/db";
53
53
  import { repointTrackerSyncBySwarmId } from "../be/db-queries/tracker";
54
+ import { withLoopPath } from "../be/event-loop-lag";
54
55
  import { poolTaskRunsOnHarness } from "../be/model-validation";
55
56
  import {
56
57
  countActiveRuntimeInstancesForAgent,
@@ -2031,8 +2032,8 @@ export function startHeartbeat(intervalMs = defaultIntervalMs()): void {
2031
2032
  // `finally` but has no `catch`, so a throw anywhere inside it escapes as an
2032
2033
  // unhandled rejection unless it is caught here.
2033
2034
  setTimeout(() => {
2034
- runRebootSweep()
2035
- .then(() => runHeartbeatSweep())
2035
+ withLoopPath("heartbeat.boot-sweep", () => runRebootSweep())
2036
+ .then(() => withLoopPath("heartbeat.sweep", () => runHeartbeatSweep()))
2036
2037
  .catch((err) =>
2037
2038
  console.error(
2038
2039
  "[Heartbeat] boot sweep failed:",
@@ -2042,7 +2043,7 @@ export function startHeartbeat(intervalMs = defaultIntervalMs()): void {
2042
2043
  }, 5000);
2043
2044
 
2044
2045
  heartbeatInterval = setInterval(() => {
2045
- runHeartbeatSweep().catch((err) =>
2046
+ withLoopPath("heartbeat.sweep", () => runHeartbeatSweep()).catch((err) =>
2046
2047
  console.error(
2047
2048
  "[Heartbeat] sweep failed:",
2048
2049
  scrubSecrets(err instanceof Error ? err.message : String(err)),
@@ -2163,7 +2164,7 @@ export function startHeartbeatChecklist(intervalMs = heartbeatChecklistIntervalM
2163
2164
 
2164
2165
  // Recurring checklist starts from the second interval onward
2165
2166
  checklistInterval = setInterval(() => {
2166
- checkHeartbeatChecklist().catch((err) =>
2167
+ withLoopPath("heartbeat.checklist", () => checkHeartbeatChecklist()).catch((err) =>
2167
2168
  console.error(
2168
2169
  "[Heartbeat] checklist check failed:",
2169
2170
  scrubSecrets(err instanceof Error ? err.message : String(err)),
package/src/http/core.ts CHANGED
@@ -41,7 +41,8 @@ import { restartChatSdkIfConfigChanged } from "../integrations/chat-sdk/runtime"
41
41
  import { initJira, resetJira } from "../jira";
42
42
  import { initLinear, resetLinear } from "../linear";
43
43
  import { can, decideAdmission, isRbacEnabled } from "../rbac";
44
- import { startSlackApp, stopSlackApp } from "../slack";
44
+ import { startSlackApp, stopSlackAppUnderLifecycleLock } from "../slack";
45
+ import { runSlackLifecycleExclusive } from "../slack/lifecycle-lock";
45
46
  import type { AgentStatus } from "../types";
46
47
  import { isMultiRuntimeEnabled } from "../utils/multi-runtime";
47
48
  import {
@@ -180,7 +181,11 @@ export async function reloadGlobalConfigsAndIntegrations(): Promise<ReloadConfig
180
181
  // request's frame they capture that request's auth slot for their whole
181
182
  // lifetime, and their later DB writes get attributed to whichever user
182
183
  // happened to save config.
183
- return runWithoutRequestAuth(() => reloadGlobalConfigsAndIntegrationsInner());
184
+ // The shared Slack lifecycle lock keeps the socket watchdog from restarting
185
+ // the Slack app while a reload tears it down and rebuilds it.
186
+ return runWithoutRequestAuth(() =>
187
+ runSlackLifecycleExclusive(() => reloadGlobalConfigsAndIntegrationsInner()),
188
+ );
184
189
  }
185
190
 
186
191
  async function reloadGlobalConfigsAndIntegrationsInner(): Promise<ReloadConfigResult> {
@@ -201,7 +206,8 @@ async function reloadGlobalConfigsAndIntegrationsInner(): Promise<ReloadConfigRe
201
206
 
202
207
  // Retire the old transport before any other integration can fail during
203
208
  // reload. HTTP/invalid selection must never leave the previous socket live.
204
- await stopSlackApp();
209
+ // The reload already holds the Slack lifecycle lock (see the caller).
210
+ await stopSlackAppUnderLifecycleLock();
205
211
 
206
212
  // File-storage provider selection reads process.env once and memoizes; the
207
213
  // env we just (re)hydrated may flip it (local-fs → agent-fs after late
package/src/http/index.ts CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  } from "../be/db";
18
18
  import { startTaskSearchBackfill, stopTaskSearchBackfill } from "../be/db/tasks/search-index";
19
19
  import { startDbRetention, stopDbRetention } from "../be/db-retention";
20
+ import { startEventLoopLagProbe, stopEventLoopLagProbe, withLoopPath } from "../be/event-loop-lag";
20
21
  import { startHumanFreeDrain, stopHumanFreeDrain } from "../be/human-free-drain";
21
22
  import { startMcpOverflowSweep, stopMcpOverflowSweep } from "../be/mcp-overflow-sweep";
22
23
  import {
@@ -151,6 +152,7 @@ import { handleUsers } from "./users";
151
152
  import {
152
153
  getPathSegments,
153
154
  httpServerSemconvAttributes,
155
+ loopPathForRequest,
154
156
  parseQueryParams,
155
157
  redactShareTokenInPath,
156
158
  safeRequestUrlForLog,
@@ -225,7 +227,8 @@ function startApiGcInterval() {
225
227
  }
226
228
 
227
229
  const interval = setInterval(() => {
228
- void sweepRooms().catch((error) =>
230
+ // The rooms sweep is the DB work of this tick; name it for the stall line.
231
+ void withLoopPath("http.gc-interval", () => sweepRooms()).catch((error) =>
229
232
  console.error("[rooms] Sweep failed:", scrubSecrets(String(error))),
230
233
  );
231
234
  const closedOwnerTransports = closeIdleMcpTransports(transports, transportActivity, {
@@ -455,11 +458,10 @@ const httpServer = createHttpServer(async (req, res) => {
455
458
  }
456
459
  };
457
460
 
458
- if (span) {
459
- await withSpanContext(span, handleRequest);
460
- } else {
461
- await handleRequest();
462
- }
461
+ // Name the entry point for the event-loop stall line.
462
+ await withLoopPath(loopPathForRequest(req.method, pathSegments), () =>
463
+ span ? withSpanContext(span, handleRequest) : handleRequest(),
464
+ );
463
465
  });
464
466
  });
465
467
 
@@ -565,6 +567,7 @@ async function shutdown() {
565
567
  clearInterval(globalState.__apiGcInterval);
566
568
  delete globalState.__apiGcInterval;
567
569
  }
570
+ stopEventLoopLagProbe();
568
571
 
569
572
  // Close all active transports (SSE connections, etc.)
570
573
  for (const [id, transport] of Object.entries(transports)) {
@@ -624,6 +627,7 @@ if (!globalState.__runId) {
624
627
  }
625
628
 
626
629
  startApiGcInterval();
630
+ startEventLoopLagProbe();
627
631
 
628
632
  // Load global swarm configs before the server starts listening so decrypt/key
629
633
  // failures fail closed instead of leaving the runtime half-initialized.
@@ -1,6 +1,7 @@
1
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
2
  import { z } from "zod";
3
3
  import { getAgentById, getDbClient, getTaskById } from "../be/db";
4
+ import { withLoopPath } from "../be/event-loop-lag";
4
5
  import { getEmbeddingProvider, getMemoryStore } from "../be/memory";
5
6
  import { canReadMemory } from "../be/memory/access";
6
7
  import { CANDIDATE_SET_MULTIPLIER } from "../be/memory/constants";
@@ -1568,8 +1569,12 @@ const MEMORY_GC_INTERVAL_MS = 60 * 60 * 1000; // 1 hour
1568
1569
  let memoryGcTimer: ReturnType<typeof setInterval> | null = null;
1569
1570
 
1570
1571
  const SEARCH_RETRIEVAL_TTL_DAYS = 90;
1571
- /** Rows per purge statement. The purge yields the event loop between batches. */
1572
- const SEARCH_RETRIEVAL_PURGE_BATCH = 2000;
1572
+ /**
1573
+ * Rows per purge statement. The purge yields the event loop between batches.
1574
+ * A 2,000-row batch blocked the loop for 1.1 s in production; 500 keeps one
1575
+ * batch near the 250 ms target.
1576
+ */
1577
+ const SEARCH_RETRIEVAL_PURGE_BATCH = 500;
1573
1578
 
1574
1579
  export async function purgeStaleSearchRetrievals(
1575
1580
  batchSize = SEARCH_RETRIEVAL_PURGE_BATCH,
@@ -1629,12 +1634,12 @@ export async function startMemoryGc(
1629
1634
  // Clear any backlog soon after startup, but off the boot path.
1630
1635
  memoryGcInitialTimer = setTimeout(() => {
1631
1636
  memoryGcInitialTimer = null;
1632
- void runMemoryGcTick("Initial");
1637
+ void withLoopPath("memory-gc.tick", () => runMemoryGcTick("Initial"));
1633
1638
  }, initialDelayMs);
1634
1639
  if (typeof memoryGcInitialTimer?.unref === "function") memoryGcInitialTimer.unref();
1635
1640
 
1636
1641
  memoryGcTimer = setInterval(() => {
1637
- void runMemoryGcTick("Periodic");
1642
+ void withLoopPath("memory-gc.tick", () => runMemoryGcTick("Periodic"));
1638
1643
  }, intervalMs);
1639
1644
  if (typeof memoryGcTimer?.unref === "function") memoryGcTimer.unref();
1640
1645
  }
@@ -3,8 +3,10 @@ import { z } from "zod";
3
3
  import {
4
4
  ASSET_KEY_MAX_LENGTH,
5
5
  defaultAssetKey,
6
+ isResourceGroupPrefix,
6
7
  normalizeAssetKey,
7
8
  parseAssetKey,
9
+ RESOURCE_GROUPS_READ_ONLY,
8
10
  } from "../assets/key";
9
11
  import { SOURCE_GROUPS_READ_ONLY, sourceMoveError, sourceOfKey } from "../assets/source-key";
10
12
  import { AssetKeyAuthorizationError, authorizeAssetKeyWrite } from "../be/asset-key-auth";
@@ -22,7 +24,7 @@ import {
22
24
  getTasksDispatchedFrom,
23
25
  listRecentSessions,
24
26
  } from "../be/db";
25
- import { getSessionLabels } from "../be/db/session-labels";
27
+ import { getResourceSessionLabels, getSessionLabels } from "../be/db/session-labels";
26
28
  import {
27
29
  listPrefixRoots,
28
30
  listSharedPrefixRoots,
@@ -1098,8 +1100,12 @@ export async function handleSessions(
1098
1100
  showSource: parsed.query.showSource,
1099
1101
  });
1100
1102
  // Labels cover hidden sources too: a pane or tab of a hidden source still names its group.
1101
- const { sourceGroups, slackChannels, threadLabels, ...counts } = tree;
1102
- const labels = { ...threadLabels, ...(await getSessionLabels(sourceGroups)) };
1103
+ const { sourceGroups, slackChannels, threadLabels, resourceGroups, ...counts } = tree;
1104
+ const [sourceLabels, resourceLabels] = await Promise.all([
1105
+ getSessionLabels(sourceGroups),
1106
+ getResourceSessionLabels(resourceGroups),
1107
+ ]);
1108
+ const labels = { ...threadLabels, ...sourceLabels, ...resourceLabels };
1103
1109
  warmSlackChannelLabels(
1104
1110
  slackChannels.map((id) => `shared/slack/${id}/`).filter((key) => labels[key] === undefined),
1105
1111
  );
@@ -1166,6 +1172,13 @@ export async function handleSessions(
1166
1172
  jsonError(res, SOURCE_GROUPS_READ_ONLY, 400);
1167
1173
  return true;
1168
1174
  }
1175
+ if (
1176
+ isResourceGroupPrefix(from) ||
1177
+ (parsed.body.to && isResourceGroupPrefix(normalizeAssetKey(parsed.body.to)))
1178
+ ) {
1179
+ jsonError(res, RESOURCE_GROUPS_READ_ONLY, 400);
1180
+ return true;
1181
+ }
1169
1182
  if (parseAssetKey(from).relativeSegments.length === 0) {
1170
1183
  jsonError(res, "Cannot move a namespace root", 400);
1171
1184
  return true;
package/src/http/utils.ts CHANGED
@@ -274,6 +274,24 @@ export function redactShareTokenInPath(pathname: string): string {
274
274
  return pathname;
275
275
  }
276
276
 
277
+ /**
278
+ * Event-loop path label for an HTTP request: method plus the first three path
279
+ * segments. Segments past the third are ids, so they are left out to bound
280
+ * the label cardinality. Invite codes and share tokens are credentials, so
281
+ * the label is redacted before it can reach a log line.
282
+ */
283
+ export function loopPathForRequest(
284
+ method: string | undefined,
285
+ segments: readonly string[],
286
+ ): string {
287
+ const redacted = redactShareTokenInPath(`/${segments.join("/")}`)
288
+ .split("/")
289
+ .filter(Boolean)
290
+ .slice(0, 3)
291
+ .join("/");
292
+ return scrubSecrets(`http ${method} ${redacted}`);
293
+ }
294
+
277
295
  export function safeRequestUrlForLog(rawUrl: string | undefined): string {
278
296
  if (!rawUrl) return "";
279
297
 
@@ -142,6 +142,45 @@ async function runBlockableHandler(
142
142
  }
143
143
  }
144
144
 
145
+ /**
146
+ * GitHub events with a real handler (or a signature-checked control event).
147
+ * Every other event is a no-op today, so it is acknowledged before its body is
148
+ * read: the request span then excludes the payload upload, which dominated
149
+ * latency for large CI payloads (check_run, workflow_run, ...).
150
+ */
151
+ const GITHUB_VERIFIED_EVENTS = new Set([
152
+ "ping",
153
+ "pull_request",
154
+ "issues",
155
+ "issue_comment",
156
+ "pull_request_review_comment",
157
+ "pull_request_review",
158
+ ]);
159
+
160
+ const GITHUB_IGNORED_SUMMARY_MS = 60_000;
161
+ const githubIgnoredCounts = new Map<string, number>();
162
+ let githubIgnoredTimer: ReturnType<typeof setInterval> | null = null;
163
+
164
+ function flushGithubIgnoredCounts(): void {
165
+ if (githubIgnoredCounts.size === 0) return;
166
+ const parts = [...githubIgnoredCounts.entries()].map(([name, n]) => `${name}=${n}`);
167
+ githubIgnoredCounts.clear();
168
+ console.log(
169
+ `[GitHub] ignored events last ${GITHUB_IGNORED_SUMMARY_MS / 1000}s: ${parts.join(" ")}`,
170
+ );
171
+ }
172
+
173
+ function countGithubIgnoredEvent(eventType: string): void {
174
+ // Bound the key space: the header is unauthenticated input.
175
+ const key =
176
+ githubIgnoredCounts.has(eventType) || githubIgnoredCounts.size < 50 ? eventType : "other";
177
+ githubIgnoredCounts.set(key, (githubIgnoredCounts.get(key) ?? 0) + 1);
178
+ if (!githubIgnoredTimer) {
179
+ githubIgnoredTimer = setInterval(flushGithubIgnoredCounts, GITHUB_IGNORED_SUMMARY_MS);
180
+ githubIgnoredTimer.unref();
181
+ }
182
+ }
183
+
145
184
  const githubWebhook = route({
146
185
  method: "post",
147
186
  path: "/api/github/webhook",
@@ -398,6 +437,15 @@ export async function handleWebhooks(
398
437
  const eventType = req.headers["x-github-event"] as string | undefined;
399
438
  const signature = req.headers["x-hub-signature-256"] as string | undefined;
400
439
 
440
+ // Early ack: events nothing handles (check_run, workflow_run, push, ...) change
441
+ // no state, so skip the body read, HMAC and parse, and drain the body in the background.
442
+ if (typeof eventType === "string" && eventType && !GITHUB_VERIFIED_EVENTS.has(eventType)) {
443
+ countGithubIgnoredEvent(eventType);
444
+ githubWebhook.respond(res, 200, { created: false });
445
+ req.resume();
446
+ return true;
447
+ }
448
+
401
449
  const chunks: Buffer[] = [];
402
450
  for await (const chunk of req) {
403
451
  chunks.push(chunk);