@bonesofspring/ai-rules 0.2.74 → 0.2.76

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 (301) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +2 -2
  3. package/bin/lib/engine-scripts.js +4 -0
  4. package/docs/TEAM-DB.md +10 -0
  5. package/docs/TOKEN-ECONOMY.md +18 -5
  6. package/package.json +2 -2
  7. package/presets/_shared/ai-local/scripts/check-write-scope.mjs +56 -26
  8. package/presets/_shared/ai-local/scripts/lock.mjs +103 -30
  9. package/presets/_shared/ai-local/scripts/rule-improver.mjs +4 -0
  10. package/presets/_shared/ai-local/scripts/run-compact.mjs +132 -0
  11. package/presets/_shared/ai-local/scripts/signals.mjs +3 -1
  12. package/presets/_shared/ai-local/scripts/team-db-api.mjs +7 -2
  13. package/presets/_shared/ai-local/scripts/team-db-project.mjs +276 -1
  14. package/presets/_shared/ai-local/scripts/team-db-scheduler.mjs +32 -2
  15. package/presets/_shared/ai-local/scripts/team-db-schema.mjs +99 -0
  16. package/presets/_shared/ai-local/scripts/team-db-task-runner.mjs +3 -1
  17. package/presets/_shared/core/agent-team/agent-task-metrics.md +29 -0
  18. package/presets/_shared/core/agent-team/agent-team-orchestrator.md +1 -1
  19. package/presets/_shared/core/meta/preset-pr-checklist.md +2 -2
  20. package/presets/_shared/core/quality/context-and-iteration.md +1 -1
  21. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +4 -1
  22. package/presets/_shared/hooks/compact-shell-output.mjs +68 -0
  23. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +4 -1
  24. package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  25. package/presets/claude/android-kotlin/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  26. package/presets/claude/android-kotlin/team/README.md +1 -1
  27. package/presets/claude/go/hooks/chain-team-phases.sh +4 -1
  28. package/presets/claude/go/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  29. package/presets/claude/go/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  30. package/presets/claude/go/team/README.md +1 -1
  31. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +4 -1
  32. package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  33. package/presets/claude/ios-swift/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  34. package/presets/claude/ios-swift/team/README.md +1 -1
  35. package/presets/claude/java/hooks/chain-team-phases.sh +4 -1
  36. package/presets/claude/java/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  37. package/presets/claude/java/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  38. package/presets/claude/java/team/README.md +1 -1
  39. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +4 -1
  40. package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  41. package/presets/claude/mcp-ts/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  42. package/presets/claude/mcp-ts/team/README.md +1 -1
  43. package/presets/claude/mol/hooks/chain-team-phases.sh +4 -1
  44. package/presets/claude/mol/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  45. package/presets/claude/mol/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  46. package/presets/claude/mol/team/README.md +1 -1
  47. package/presets/claude/next/agents/build-verifier.md +1 -1
  48. package/presets/claude/next/agents/code-reviewer.md +2 -0
  49. package/presets/claude/next/hooks/chain-team-phases.sh +4 -1
  50. package/presets/claude/next/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  51. package/presets/claude/next/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  52. package/presets/claude/next/team/README.md +1 -1
  53. package/presets/claude/nuxt/hooks/chain-team-phases.sh +4 -1
  54. package/presets/claude/nuxt/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  55. package/presets/claude/nuxt/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  56. package/presets/claude/nuxt/team/README.md +1 -1
  57. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +4 -1
  58. package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  59. package/presets/claude/php-hexagonal/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  60. package/presets/claude/php-hexagonal/team/README.md +1 -1
  61. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +4 -1
  62. package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  63. package/presets/claude/php-laravel/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  64. package/presets/claude/php-laravel/team/README.md +1 -1
  65. package/presets/claude/svelte/hooks/chain-team-phases.sh +4 -1
  66. package/presets/claude/svelte/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  67. package/presets/claude/svelte/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  68. package/presets/claude/svelte/team/README.md +1 -1
  69. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +4 -1
  70. package/presets/cursor/android-kotlin/hooks/compact-shell-output.mjs +68 -0
  71. package/presets/cursor/android-kotlin/hooks.json +7 -0
  72. package/presets/cursor/android-kotlin/rules/preset-pr-checklist.mdc +2 -2
  73. package/presets/cursor/android-kotlin/team/README.md +1 -1
  74. package/presets/cursor/go/hooks/chain-team-phases.sh +4 -1
  75. package/presets/cursor/go/hooks/compact-shell-output.mjs +68 -0
  76. package/presets/cursor/go/hooks.json +7 -0
  77. package/presets/cursor/go/rules/preset-pr-checklist.mdc +2 -2
  78. package/presets/cursor/go/team/README.md +1 -1
  79. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +4 -1
  80. package/presets/cursor/ios-swift/hooks/compact-shell-output.mjs +68 -0
  81. package/presets/cursor/ios-swift/hooks.json +7 -0
  82. package/presets/cursor/ios-swift/rules/preset-pr-checklist.mdc +2 -2
  83. package/presets/cursor/ios-swift/team/README.md +1 -1
  84. package/presets/cursor/java/hooks/chain-team-phases.sh +4 -1
  85. package/presets/cursor/java/hooks/compact-shell-output.mjs +68 -0
  86. package/presets/cursor/java/hooks.json +7 -0
  87. package/presets/cursor/java/rules/preset-pr-checklist.mdc +2 -2
  88. package/presets/cursor/java/team/README.md +1 -1
  89. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +4 -1
  90. package/presets/cursor/mcp-ts/hooks/compact-shell-output.mjs +68 -0
  91. package/presets/cursor/mcp-ts/hooks.json +7 -0
  92. package/presets/cursor/mcp-ts/rules/preset-pr-checklist.mdc +2 -2
  93. package/presets/cursor/mcp-ts/team/README.md +1 -1
  94. package/presets/cursor/mol/hooks/chain-team-phases.sh +4 -1
  95. package/presets/cursor/mol/hooks/compact-shell-output.mjs +68 -0
  96. package/presets/cursor/mol/hooks.json +7 -0
  97. package/presets/cursor/mol/rules/preset-pr-checklist.mdc +2 -2
  98. package/presets/cursor/mol/team/README.md +1 -1
  99. package/presets/cursor/next/agents/build-verifier.md +1 -1
  100. package/presets/cursor/next/agents/code-reviewer.md +2 -0
  101. package/presets/cursor/next/hooks/chain-team-phases.sh +4 -1
  102. package/presets/cursor/next/hooks/compact-shell-output.mjs +68 -0
  103. package/presets/cursor/next/hooks.json +7 -0
  104. package/presets/cursor/next/rules/preset-pr-checklist.mdc +2 -2
  105. package/presets/cursor/next/team/README.md +1 -1
  106. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +4 -1
  107. package/presets/cursor/nuxt/hooks/compact-shell-output.mjs +68 -0
  108. package/presets/cursor/nuxt/hooks.json +7 -0
  109. package/presets/cursor/nuxt/rules/preset-pr-checklist.mdc +2 -2
  110. package/presets/cursor/nuxt/team/README.md +1 -1
  111. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +4 -1
  112. package/presets/cursor/php-hexagonal/hooks/compact-shell-output.mjs +68 -0
  113. package/presets/cursor/php-hexagonal/hooks.json +7 -0
  114. package/presets/cursor/php-hexagonal/rules/preset-pr-checklist.mdc +2 -2
  115. package/presets/cursor/php-hexagonal/team/README.md +1 -1
  116. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +4 -1
  117. package/presets/cursor/php-laravel/hooks/compact-shell-output.mjs +68 -0
  118. package/presets/cursor/php-laravel/hooks.json +7 -0
  119. package/presets/cursor/php-laravel/rules/preset-pr-checklist.mdc +2 -2
  120. package/presets/cursor/php-laravel/team/README.md +1 -1
  121. package/presets/cursor/svelte/hooks/chain-team-phases.sh +4 -1
  122. package/presets/cursor/svelte/hooks/compact-shell-output.mjs +68 -0
  123. package/presets/cursor/svelte/hooks.json +7 -0
  124. package/presets/cursor/svelte/rules/preset-pr-checklist.mdc +2 -2
  125. package/presets/cursor/svelte/team/README.md +1 -1
  126. package/presets/mavis/android-kotlin/adapter-map.json +9 -1
  127. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +4 -1
  128. package/presets/mavis/android-kotlin/rules/agent-team-orchestrator.md +1 -1
  129. package/presets/mavis/android-kotlin/rules/preset-pr-checklist.md +2 -2
  130. package/presets/mavis/android-kotlin/team/README.md +1 -1
  131. package/presets/mavis/go/adapter-map.json +9 -1
  132. package/presets/mavis/go/hooks/chain-team-phases.sh +4 -1
  133. package/presets/mavis/go/rules/agent-team-orchestrator.md +1 -1
  134. package/presets/mavis/go/rules/preset-pr-checklist.md +2 -2
  135. package/presets/mavis/go/team/README.md +1 -1
  136. package/presets/mavis/ios-swift/adapter-map.json +9 -1
  137. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +4 -1
  138. package/presets/mavis/ios-swift/rules/agent-team-orchestrator.md +1 -1
  139. package/presets/mavis/ios-swift/rules/preset-pr-checklist.md +2 -2
  140. package/presets/mavis/ios-swift/team/README.md +1 -1
  141. package/presets/mavis/java/adapter-map.json +9 -1
  142. package/presets/mavis/java/hooks/chain-team-phases.sh +4 -1
  143. package/presets/mavis/java/rules/agent-team-orchestrator.md +1 -1
  144. package/presets/mavis/java/rules/preset-pr-checklist.md +2 -2
  145. package/presets/mavis/java/team/README.md +1 -1
  146. package/presets/mavis/mcp-ts/adapter-map.json +9 -1
  147. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +4 -1
  148. package/presets/mavis/mcp-ts/rules/agent-team-orchestrator.md +1 -1
  149. package/presets/mavis/mcp-ts/rules/preset-pr-checklist.md +2 -2
  150. package/presets/mavis/mcp-ts/team/README.md +1 -1
  151. package/presets/mavis/mol/adapter-map.json +9 -1
  152. package/presets/mavis/mol/hooks/chain-team-phases.sh +4 -1
  153. package/presets/mavis/mol/rules/agent-team-orchestrator.md +1 -1
  154. package/presets/mavis/mol/rules/preset-pr-checklist.md +2 -2
  155. package/presets/mavis/mol/team/README.md +1 -1
  156. package/presets/mavis/next/adapter-map.json +9 -1
  157. package/presets/mavis/next/agents/build-verifier.md +1 -1
  158. package/presets/mavis/next/agents/code-reviewer.md +2 -0
  159. package/presets/mavis/next/hooks/chain-team-phases.sh +4 -1
  160. package/presets/mavis/next/rules/agent-team-orchestrator.md +1 -1
  161. package/presets/mavis/next/rules/preset-pr-checklist.md +2 -2
  162. package/presets/mavis/next/team/README.md +1 -1
  163. package/presets/mavis/nuxt/adapter-map.json +9 -1
  164. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +4 -1
  165. package/presets/mavis/nuxt/rules/agent-team-orchestrator.md +1 -1
  166. package/presets/mavis/nuxt/rules/preset-pr-checklist.md +2 -2
  167. package/presets/mavis/nuxt/team/README.md +1 -1
  168. package/presets/mavis/php-hexagonal/adapter-map.json +9 -1
  169. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +4 -1
  170. package/presets/mavis/php-hexagonal/rules/agent-team-orchestrator.md +1 -1
  171. package/presets/mavis/php-hexagonal/rules/preset-pr-checklist.md +2 -2
  172. package/presets/mavis/php-hexagonal/team/README.md +1 -1
  173. package/presets/mavis/php-laravel/adapter-map.json +9 -1
  174. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +4 -1
  175. package/presets/mavis/php-laravel/rules/agent-team-orchestrator.md +1 -1
  176. package/presets/mavis/php-laravel/rules/preset-pr-checklist.md +2 -2
  177. package/presets/mavis/php-laravel/team/README.md +1 -1
  178. package/presets/mavis/svelte/adapter-map.json +9 -1
  179. package/presets/mavis/svelte/hooks/chain-team-phases.sh +4 -1
  180. package/presets/mavis/svelte/rules/agent-team-orchestrator.md +1 -1
  181. package/presets/mavis/svelte/rules/preset-pr-checklist.md +2 -2
  182. package/presets/mavis/svelte/team/README.md +1 -1
  183. package/presets/opencode/android-kotlin/adapter-map.json +9 -1
  184. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +4 -1
  185. package/presets/opencode/android-kotlin/rules/agent-team-orchestrator.md +1 -1
  186. package/presets/opencode/android-kotlin/rules/preset-pr-checklist.md +2 -2
  187. package/presets/opencode/android-kotlin/team/README.md +1 -1
  188. package/presets/opencode/go/adapter-map.json +9 -1
  189. package/presets/opencode/go/hooks/chain-team-phases.sh +4 -1
  190. package/presets/opencode/go/rules/agent-team-orchestrator.md +1 -1
  191. package/presets/opencode/go/rules/preset-pr-checklist.md +2 -2
  192. package/presets/opencode/go/team/README.md +1 -1
  193. package/presets/opencode/ios-swift/adapter-map.json +9 -1
  194. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +4 -1
  195. package/presets/opencode/ios-swift/rules/agent-team-orchestrator.md +1 -1
  196. package/presets/opencode/ios-swift/rules/preset-pr-checklist.md +2 -2
  197. package/presets/opencode/ios-swift/team/README.md +1 -1
  198. package/presets/opencode/java/adapter-map.json +9 -1
  199. package/presets/opencode/java/hooks/chain-team-phases.sh +4 -1
  200. package/presets/opencode/java/rules/agent-team-orchestrator.md +1 -1
  201. package/presets/opencode/java/rules/preset-pr-checklist.md +2 -2
  202. package/presets/opencode/java/team/README.md +1 -1
  203. package/presets/opencode/mcp-ts/adapter-map.json +9 -1
  204. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +4 -1
  205. package/presets/opencode/mcp-ts/rules/agent-team-orchestrator.md +1 -1
  206. package/presets/opencode/mcp-ts/rules/preset-pr-checklist.md +2 -2
  207. package/presets/opencode/mcp-ts/team/README.md +1 -1
  208. package/presets/opencode/mol/adapter-map.json +9 -1
  209. package/presets/opencode/mol/hooks/chain-team-phases.sh +4 -1
  210. package/presets/opencode/mol/rules/agent-team-orchestrator.md +1 -1
  211. package/presets/opencode/mol/rules/preset-pr-checklist.md +2 -2
  212. package/presets/opencode/mol/team/README.md +1 -1
  213. package/presets/opencode/next/adapter-map.json +9 -1
  214. package/presets/opencode/next/agents/build-verifier.md +1 -1
  215. package/presets/opencode/next/agents/code-reviewer.md +2 -0
  216. package/presets/opencode/next/hooks/chain-team-phases.sh +4 -1
  217. package/presets/opencode/next/rules/agent-team-orchestrator.md +1 -1
  218. package/presets/opencode/next/rules/preset-pr-checklist.md +2 -2
  219. package/presets/opencode/next/team/README.md +1 -1
  220. package/presets/opencode/nuxt/adapter-map.json +9 -1
  221. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +4 -1
  222. package/presets/opencode/nuxt/rules/agent-team-orchestrator.md +1 -1
  223. package/presets/opencode/nuxt/rules/preset-pr-checklist.md +2 -2
  224. package/presets/opencode/nuxt/team/README.md +1 -1
  225. package/presets/opencode/php-hexagonal/adapter-map.json +9 -1
  226. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +4 -1
  227. package/presets/opencode/php-hexagonal/rules/agent-team-orchestrator.md +1 -1
  228. package/presets/opencode/php-hexagonal/rules/preset-pr-checklist.md +2 -2
  229. package/presets/opencode/php-hexagonal/team/README.md +1 -1
  230. package/presets/opencode/php-laravel/adapter-map.json +9 -1
  231. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +4 -1
  232. package/presets/opencode/php-laravel/rules/agent-team-orchestrator.md +1 -1
  233. package/presets/opencode/php-laravel/rules/preset-pr-checklist.md +2 -2
  234. package/presets/opencode/php-laravel/team/README.md +1 -1
  235. package/presets/opencode/plugins/output-guard/README.md +3 -2
  236. package/presets/opencode/plugins/output-guard/rewrite.ts +10 -1
  237. package/presets/opencode/svelte/adapter-map.json +9 -1
  238. package/presets/opencode/svelte/hooks/chain-team-phases.sh +4 -1
  239. package/presets/opencode/svelte/rules/agent-team-orchestrator.md +1 -1
  240. package/presets/opencode/svelte/rules/preset-pr-checklist.md +2 -2
  241. package/presets/opencode/svelte/team/README.md +1 -1
  242. package/presets/zcode/android-kotlin/adapter-map.json +9 -1
  243. package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +4 -1
  244. package/presets/zcode/android-kotlin/rules/agent-team-orchestrator.md +1 -1
  245. package/presets/zcode/android-kotlin/rules/preset-pr-checklist.md +2 -2
  246. package/presets/zcode/android-kotlin/team/README.md +1 -1
  247. package/presets/zcode/go/adapter-map.json +9 -1
  248. package/presets/zcode/go/hooks/chain-team-phases.sh +4 -1
  249. package/presets/zcode/go/rules/agent-team-orchestrator.md +1 -1
  250. package/presets/zcode/go/rules/preset-pr-checklist.md +2 -2
  251. package/presets/zcode/go/team/README.md +1 -1
  252. package/presets/zcode/ios-swift/adapter-map.json +9 -1
  253. package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +4 -1
  254. package/presets/zcode/ios-swift/rules/agent-team-orchestrator.md +1 -1
  255. package/presets/zcode/ios-swift/rules/preset-pr-checklist.md +2 -2
  256. package/presets/zcode/ios-swift/team/README.md +1 -1
  257. package/presets/zcode/java/adapter-map.json +9 -1
  258. package/presets/zcode/java/hooks/chain-team-phases.sh +4 -1
  259. package/presets/zcode/java/rules/agent-team-orchestrator.md +1 -1
  260. package/presets/zcode/java/rules/preset-pr-checklist.md +2 -2
  261. package/presets/zcode/java/team/README.md +1 -1
  262. package/presets/zcode/mcp-ts/adapter-map.json +9 -1
  263. package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +4 -1
  264. package/presets/zcode/mcp-ts/rules/agent-team-orchestrator.md +1 -1
  265. package/presets/zcode/mcp-ts/rules/preset-pr-checklist.md +2 -2
  266. package/presets/zcode/mcp-ts/team/README.md +1 -1
  267. package/presets/zcode/mol/adapter-map.json +9 -1
  268. package/presets/zcode/mol/hooks/chain-team-phases.sh +4 -1
  269. package/presets/zcode/mol/rules/agent-team-orchestrator.md +1 -1
  270. package/presets/zcode/mol/rules/preset-pr-checklist.md +2 -2
  271. package/presets/zcode/mol/team/README.md +1 -1
  272. package/presets/zcode/next/adapter-map.json +9 -1
  273. package/presets/zcode/next/agents/build-verifier.md +1 -1
  274. package/presets/zcode/next/agents/code-reviewer.md +2 -0
  275. package/presets/zcode/next/hooks/chain-team-phases.sh +4 -1
  276. package/presets/zcode/next/rules/agent-team-orchestrator.md +1 -1
  277. package/presets/zcode/next/rules/preset-pr-checklist.md +2 -2
  278. package/presets/zcode/next/team/README.md +1 -1
  279. package/presets/zcode/nuxt/adapter-map.json +9 -1
  280. package/presets/zcode/nuxt/hooks/chain-team-phases.sh +4 -1
  281. package/presets/zcode/nuxt/rules/agent-team-orchestrator.md +1 -1
  282. package/presets/zcode/nuxt/rules/preset-pr-checklist.md +2 -2
  283. package/presets/zcode/nuxt/team/README.md +1 -1
  284. package/presets/zcode/php-hexagonal/adapter-map.json +9 -1
  285. package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +4 -1
  286. package/presets/zcode/php-hexagonal/rules/agent-team-orchestrator.md +1 -1
  287. package/presets/zcode/php-hexagonal/rules/preset-pr-checklist.md +2 -2
  288. package/presets/zcode/php-hexagonal/team/README.md +1 -1
  289. package/presets/zcode/php-laravel/adapter-map.json +9 -1
  290. package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +4 -1
  291. package/presets/zcode/php-laravel/rules/agent-team-orchestrator.md +1 -1
  292. package/presets/zcode/php-laravel/rules/preset-pr-checklist.md +2 -2
  293. package/presets/zcode/php-laravel/team/README.md +1 -1
  294. package/presets/zcode/svelte/adapter-map.json +9 -1
  295. package/presets/zcode/svelte/hooks/chain-team-phases.sh +4 -1
  296. package/presets/zcode/svelte/rules/agent-team-orchestrator.md +1 -1
  297. package/presets/zcode/svelte/rules/preset-pr-checklist.md +2 -2
  298. package/presets/zcode/svelte/team/README.md +1 -1
  299. package/scripts/close-agent-task-human-gate.mjs +3 -3
  300. package/scripts/report-context-cost.mjs +10 -3
  301. package/scripts/aggregate-agent-task-metrics.mjs +0 -480
@@ -0,0 +1,132 @@
1
+ #!/usr/bin/env node
2
+ // Run a command, store its combined output, and print a short view.
3
+ // Exit with the child status so a passing store cannot hide a failing test.
4
+
5
+ import { spawnSync } from 'node:child_process';
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { resolveTeamRoot } from './dump-output.mjs';
11
+
12
+ const PASS_THROUGH_BYTES = 4096;
13
+ const HEAD_LINES = 40;
14
+ const HEAD_BYTES = 8 * 1024;
15
+ const CAPTURE_BYTES = 2 * 1024 * 1024;
16
+ const FAIL_LINE = /\b(FAIL|ERROR|Error|AssertionError)\b|✗|×/u;
17
+
18
+ const here = path.dirname(fileURLToPath(import.meta.url));
19
+ const dumpScript = path.join(here, 'dump-output.mjs');
20
+
21
+ const usageFail = (message) => {
22
+ const error = new Error(message);
23
+ error.exitCode = 2;
24
+ throw error;
25
+ };
26
+
27
+ const parseArgs = (argv) => {
28
+ const split = argv.indexOf('--');
29
+ if (split === -1) usageFail('missing -- before the command');
30
+ const child = argv.slice(split + 1);
31
+ if (child.length === 0) usageFail('missing command after --');
32
+ let task = '';
33
+ let root = '';
34
+ for (let index = 0; index < split; index += 1) {
35
+ const token = argv[index];
36
+ if (token !== '--task' && token !== '--root') usageFail(`unknown flag ${token}`);
37
+ const value = argv[index + 1];
38
+ if (value === undefined || value.startsWith('--')) usageFail(`flag ${token} needs a value`);
39
+ if (token === '--task') task = value;
40
+ else root = value;
41
+ index += 1;
42
+ }
43
+ if (task === '') usageFail('missing --task');
44
+ return { task, root, child };
45
+ };
46
+
47
+ const footerOf = (dumpStdout) =>
48
+ dumpStdout
49
+ .split('\n')
50
+ .filter((line) => line.startsWith('bytes: ') || line.startsWith('path: ') || line.startsWith('grep -n '))
51
+ .join('\n');
52
+
53
+ const failureLines = (text) => {
54
+ const lines = text.split('\n');
55
+ if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
56
+ const picked = [];
57
+ let used = 0;
58
+ for (let index = 0; index < lines.length && picked.length < HEAD_LINES; index += 1) {
59
+ if (!FAIL_LINE.test(lines[index])) continue;
60
+ const block = [lines[index]];
61
+ if (lines[index + 1]) block.push(lines[index + 1]);
62
+ for (const line of block) {
63
+ if (picked.length >= HEAD_LINES) break;
64
+ const size = Buffer.byteLength(line) + 1;
65
+ if (used + size > HEAD_BYTES) return picked;
66
+ picked.push(line);
67
+ used += size;
68
+ }
69
+ }
70
+ return picked;
71
+ };
72
+
73
+ const viewFor = ({ dumpStdout, storedText, storedBytes }) => {
74
+ if (storedBytes <= PASS_THROUGH_BYTES) return dumpStdout;
75
+ const picked = failureLines(storedText);
76
+ if (picked.length === 0) return dumpStdout;
77
+ const footer = footerOf(dumpStdout);
78
+ return `head:\n${picked.join('\n')}\n${footer}\n`;
79
+ };
80
+
81
+ const run = ({ task, root, child }) => {
82
+ const teamRoot = root ? path.resolve(root) : resolveTeamRoot(process.cwd());
83
+ if (!teamRoot) usageFail('no .ai.local/team found above the current directory; pass --root <team-dir>');
84
+ const captured = spawnSync(child[0], child.slice(1), {
85
+ cwd: process.cwd(),
86
+ maxBuffer: CAPTURE_BYTES,
87
+ });
88
+ const status = captured.status ?? 128;
89
+ const body = Buffer.concat([captured.stdout ?? Buffer.alloc(0), captured.stderr ?? Buffer.alloc(0)]);
90
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'run-compact-'));
91
+ const input = path.join(dir, 'output.bin');
92
+ try {
93
+ fs.writeFileSync(input, body);
94
+ const stored = spawnSync(
95
+ process.execPath,
96
+ [dumpScript, '--input', input, '--task', task, '--label', 'compact', '--root', teamRoot],
97
+ { encoding: 'utf8' },
98
+ );
99
+ if (stored.status !== 0) {
100
+ process.stderr.write(stored.stderr || stored.stdout || '');
101
+ return status;
102
+ }
103
+ const storedBytesMatch = stored.stdout.match(/^bytes: (\d+)/m);
104
+ const storedBytes = storedBytesMatch ? Number(storedBytesMatch[1]) : body.length;
105
+ const storedText = body.subarray(0, CAPTURE_BYTES).toString('utf8');
106
+ const view = viewFor({ dumpStdout: stored.stdout, storedText, storedBytes });
107
+ const shownBytes = Buffer.byteLength(view);
108
+ process.stdout.write(view);
109
+ process.stdout.write(`stored_bytes: ${storedBytes} shown_bytes: ${shownBytes}\n`);
110
+ return status;
111
+ } finally {
112
+ fs.rmSync(dir, { recursive: true, force: true });
113
+ }
114
+ };
115
+
116
+ const invokedDirectly = (() => {
117
+ if (!process.argv[1]) return false;
118
+ try {
119
+ return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url));
120
+ } catch {
121
+ return false;
122
+ }
123
+ })();
124
+
125
+ if (invokedDirectly) {
126
+ try {
127
+ process.exitCode = run(parseArgs(process.argv.slice(2)));
128
+ } catch (error) {
129
+ process.stderr.write(`run-compact: ${error.message}\n`);
130
+ process.exitCode = typeof error.exitCode === 'number' ? error.exitCode : 1;
131
+ }
132
+ }
@@ -21,7 +21,9 @@ import { acquireLock, releaseLock } from './lock.mjs';
21
21
  const SIGNALS_FILE = 'signals.jsonl';
22
22
  export const DEFAULT_SIGNALS_PATH = path.join(process.cwd(), '.ai.local', SIGNALS_FILE);
23
23
 
24
- const KINDS = ['correction', 'retry', 'waste', 'reversal', 'dead-end'];
24
+ // `exemplar` is a repeated clean path, not a wrong turn. The rule improver
25
+ // skips it; the efficacy oracle's wrong-turn list does not include it.
26
+ const KINDS = ['correction', 'retry', 'waste', 'reversal', 'dead-end', 'exemplar'];
25
27
  const SEVERITIES = ['high', 'med', 'low'];
26
28
  const SOURCES = ['self-review', 'gate', 'technical-retro', 'user'];
27
29
  const STATUSES = ['proposed', 'staged', 'applied', 'rolled_back', 'rejected'];
@@ -28,6 +28,7 @@ import {
28
28
  isKillSwitchSet,
29
29
  listAppliedMigrations,
30
30
  openTeamDb,
31
+ readNewerSchemaModule,
31
32
  readSchemaMeta,
32
33
  readSearchMode,
33
34
  readUserVersion,
@@ -3343,11 +3344,15 @@ const handle = async (req, res, settings) => {
3343
3344
  if (params.slug !== undefined) params.slug = parseSlug(params.slug);
3344
3345
 
3345
3346
  // The handler opens the connection lazily and the caller closes it, so a
3346
- // static route never touches the database.
3347
+ // static route never touches the database. A schema file newer than the
3348
+ // module this process loaded is opened with that file, not the cached one.
3349
+ const freshSchema = await readNewerSchemaModule();
3347
3350
  let opened = null;
3348
3351
  const handleOnce = () => {
3349
3352
  if (!opened) {
3350
- opened = settings.services.openDb?.(settings) ?? openTeamDb({ teamRoot: settings.teamRoot, dbPath: settings.dbPath, readOnly: true });
3353
+ opened = freshSchema
3354
+ ? freshSchema.openTeamDb({ teamRoot: settings.teamRoot, dbPath: settings.dbPath, readOnly: true })
3355
+ : (settings.services.openDb?.(settings) ?? openTeamDb({ teamRoot: settings.teamRoot, dbPath: settings.dbPath, readOnly: true }));
3351
3356
  }
3352
3357
  return opened;
3353
3358
  };
@@ -750,7 +750,12 @@ const normalizeEvent = (event, index, slug) => {
750
750
  attemptId: typeof event.attemptId === 'string' ? event.attemptId : null,
751
751
  stepIndex: integerOrNull(event.stepIndex),
752
752
  stepLabel: typeof event.stepLabel === 'string' ? event.stepLabel : null,
753
- agent: typeof event.agent === 'string' ? event.agent : null,
753
+ agent:
754
+ typeof event.agent === 'string' && event.agent !== ''
755
+ ? event.agent
756
+ : typeof event.nextAgent === 'string' && event.nextAgent !== ''
757
+ ? event.nextAgent
758
+ : null,
754
759
  role: typeof event.role === 'string' ? event.role : null,
755
760
  attemptNo: integerOrNull(event.attempt),
756
761
  outcome: typeof event.outcome === 'string' ? event.outcome : null,
@@ -2370,6 +2375,47 @@ const projectSessionLeases = (db, teamRoot) => {
2370
2375
  return projected;
2371
2376
  };
2372
2377
 
2378
+ const INSTANT_LEASE_MS = 1000;
2379
+ const LEASE_ATTEMPT_SPAN_MS = 7 * 24 * 60 * 60 * 1000;
2380
+
2381
+ /**
2382
+ * An instant lease (the file still has no grown `firstSeenAt`) covers the
2383
+ * attempt span of its slug, at most a week either side of that instant. A
2384
+ * lease that already has a window is left alone. The next-lease clip runs
2385
+ * after this, so a later slug of the same session still owns the overlap.
2386
+ */
2387
+ const expandInstantLeases = (db, bySession) => {
2388
+ let attempts;
2389
+ try {
2390
+ attempts = db
2391
+ .prepare('SELECT task_slug, started_at, finished_at FROM attempts WHERE started_at IS NOT NULL')
2392
+ .all();
2393
+ } catch {
2394
+ return;
2395
+ }
2396
+ const bySlug = new Map();
2397
+ for (const row of attempts) {
2398
+ const list = bySlug.get(row.task_slug) ?? [];
2399
+ list.push(row);
2400
+ bySlug.set(row.task_slug, list);
2401
+ }
2402
+ for (const sessions of bySession.values()) {
2403
+ for (const window of sessions) {
2404
+ if (window.last - window.first > INSTANT_LEASE_MS) continue;
2405
+ for (const row of bySlug.get(window.slug) ?? []) {
2406
+ const start = Date.parse(row.started_at);
2407
+ const end = row.finished_at ? Date.parse(row.finished_at) : start;
2408
+ if (!Number.isFinite(start) || !Number.isFinite(end)) continue;
2409
+ if (start > window.last + LEASE_ATTEMPT_SPAN_MS) continue;
2410
+ if (end < window.first - LEASE_ATTEMPT_SPAN_MS) continue;
2411
+ if (start < window.first) window.first = start;
2412
+ if (end > window.last) window.last = end;
2413
+ }
2414
+ window.end = window.last + LEASE_TTL_MS;
2415
+ }
2416
+ }
2417
+ };
2418
+
2373
2419
  /**
2374
2420
  * The attribution context: the lease windows of every session, the same
2375
2421
  * windows indexed by task, and the mtime of every task directory.
@@ -2393,6 +2439,7 @@ const leaseWindows = (db) => {
2393
2439
  tasks.push(window);
2394
2440
  byTask.set(row.task_slug, tasks);
2395
2441
  }
2442
+ expandInstantLeases(db, bySession);
2396
2443
  for (const sessions of bySession.values()) {
2397
2444
  sessions.sort((left, right) => left.first - right.first || (left.slug < right.slug ? -1 : left.slug > right.slug ? 1 : 0));
2398
2445
  for (let index = 0; index < sessions.length - 1; index += 1) {
@@ -2604,6 +2651,227 @@ const ingestLedgerFile = ({ db, file, kind, keyOf, ingestedAt, deadlineAt, conte
2604
2651
  return { rows, invalid, refused, ingested: true };
2605
2652
  };
2606
2653
 
2654
+ const RUNG_RANK = { unmapped: 0, 'dir-mtime': 1, window: 2, lease: 3 };
2655
+ const BOUND_RUNGS = new Set(['lease', 'window']);
2656
+ const EPISODE_CAP = 40;
2657
+
2658
+ /**
2659
+ * The attempt whose window contains the call. A matching agent outranks a
2660
+ * shorter window; otherwise the narrowest window wins, then the later start.
2661
+ * Returns null when the call has no task or no attempt covers it.
2662
+ */
2663
+ export function matchAttemptId(call, attempts) {
2664
+ const at = Date.parse(call.observedAt ?? '');
2665
+ if (!Number.isFinite(at) || !call.taskSlug) return null;
2666
+ let best = null;
2667
+ for (const attempt of attempts) {
2668
+ if (attempt.taskSlug !== call.taskSlug || !attempt.attemptId) continue;
2669
+ const start = Date.parse(attempt.startedAt ?? '');
2670
+ if (!Number.isFinite(start) || start > at) continue;
2671
+ const finished = attempt.finishedAt ? Date.parse(attempt.finishedAt) : Number.POSITIVE_INFINITY;
2672
+ if (!Number.isFinite(finished) || at > finished) continue;
2673
+ const agentMatch = Boolean(call.agent && attempt.agent && call.agent === attempt.agent);
2674
+ const span = finished === Number.POSITIVE_INFINITY ? Number.POSITIVE_INFINITY : finished - start;
2675
+ const rank = { agentMatch, span, start, attemptId: attempt.attemptId, agent: attempt.agent ?? null };
2676
+ if (
2677
+ best === null
2678
+ || rank.agentMatch > best.agentMatch
2679
+ || (rank.agentMatch === best.agentMatch && rank.span < best.span)
2680
+ || (rank.agentMatch === best.agentMatch && rank.span === best.span && rank.start > best.start)
2681
+ ) {
2682
+ best = rank;
2683
+ }
2684
+ }
2685
+ return best;
2686
+ }
2687
+
2688
+ const reattributeRows = (db, teamRoot) => {
2689
+ const context = { ...leaseWindows(db), dirs: taskDirectoryWindows(teamRoot) };
2690
+ const updateCall = db.prepare('UPDATE tool_calls SET task_slug = ?, attribution = ? WHERE call_key = ?');
2691
+ const updateTurn = db.prepare('UPDATE usage_turns SET task_slug = ?, attribution = ? WHERE turn_key = ?');
2692
+ let upgraded = 0;
2693
+ for (const row of db.prepare('SELECT call_key, session_id, observed_at, attribution FROM tool_calls').all()) {
2694
+ const next = resolveAttribution(context, row.session_id, row.observed_at);
2695
+ if ((RUNG_RANK[next.attribution] ?? 0) <= (RUNG_RANK[row.attribution] ?? 0)) continue;
2696
+ updateCall.run(next.taskSlug, next.attribution, row.call_key);
2697
+ upgraded += 1;
2698
+ }
2699
+ for (const row of db.prepare('SELECT turn_key, session_id, observed_at, attribution FROM usage_turns').all()) {
2700
+ const next = resolveAttribution(context, row.session_id, row.observed_at);
2701
+ if ((RUNG_RANK[next.attribution] ?? 0) <= (RUNG_RANK[row.attribution] ?? 0)) continue;
2702
+ updateTurn.run(next.taskSlug, next.attribution, row.turn_key);
2703
+ upgraded += 1;
2704
+ }
2705
+ return upgraded;
2706
+ };
2707
+
2708
+ const bindAttemptIds = (db) => {
2709
+ const attempts = db
2710
+ .prepare(
2711
+ `SELECT attempt_id AS attemptId, task_slug AS taskSlug, agent, started_at AS startedAt, finished_at AS finishedAt
2712
+ FROM attempts WHERE started_at IS NOT NULL`,
2713
+ )
2714
+ .all();
2715
+ const update = db.prepare('UPDATE tool_calls SET attempt_id = ?, agent = COALESCE(agent, ?) WHERE call_key = ?');
2716
+ const clear = db.prepare('UPDATE tool_calls SET attempt_id = NULL WHERE call_key = ?');
2717
+ let bound = 0;
2718
+ for (const call of db.prepare('SELECT call_key, task_slug, observed_at, agent, attribution FROM tool_calls').all()) {
2719
+ if (!BOUND_RUNGS.has(call.attribution)) {
2720
+ clear.run(call.call_key);
2721
+ continue;
2722
+ }
2723
+ const match = matchAttemptId(
2724
+ { taskSlug: call.task_slug, observedAt: call.observed_at, agent: call.agent },
2725
+ attempts,
2726
+ );
2727
+ if (!match) {
2728
+ clear.run(call.call_key);
2729
+ continue;
2730
+ }
2731
+ update.run(match.attemptId, match.agent, call.call_key);
2732
+ bound += 1;
2733
+ }
2734
+ return bound;
2735
+ };
2736
+
2737
+ const rebuildEpisodes = (db) => {
2738
+ db.exec('DELETE FROM attempt_episodes');
2739
+ const insert = db.prepare(
2740
+ `INSERT INTO attempt_episodes (attempt_id, ordinal, intent, target_key, error_class, observed_at)
2741
+ VALUES (?, ?, ?, ?, ?, ?)`,
2742
+ );
2743
+ const counts = new Map();
2744
+ let episodes = 0;
2745
+ for (const call of db
2746
+ .prepare(
2747
+ `SELECT attempt_id, intent, target_key, error_class, observed_at
2748
+ FROM tool_calls WHERE attempt_id IS NOT NULL
2749
+ ORDER BY attempt_id, observed_at, call_key`,
2750
+ )
2751
+ .all()) {
2752
+ const ordinal = counts.get(call.attempt_id) ?? 0;
2753
+ if (ordinal >= EPISODE_CAP) continue;
2754
+ counts.set(call.attempt_id, ordinal + 1);
2755
+ insert.run(call.attempt_id, ordinal, call.intent, call.target_key, call.error_class, call.observed_at);
2756
+ episodes += 1;
2757
+ }
2758
+ return episodes;
2759
+ };
2760
+
2761
+ const fillGaps = (db) => {
2762
+ const update = db.prepare('UPDATE tool_calls SET gap_ms = ? WHERE call_key = ? AND gap_ms IS NULL');
2763
+ let filled = 0;
2764
+ let previous = null;
2765
+ for (const row of db
2766
+ .prepare('SELECT call_key, session_id, observed_at, gap_ms FROM tool_calls ORDER BY session_id, observed_at, call_key')
2767
+ .all()) {
2768
+ if (previous && previous.session_id === row.session_id && row.gap_ms === null) {
2769
+ const gap = Date.parse(row.observed_at) - Date.parse(previous.observed_at);
2770
+ if (Number.isFinite(gap) && gap >= 0 && gap <= LEASE_TTL_MS) {
2771
+ update.run(gap, row.call_key);
2772
+ filled += 1;
2773
+ }
2774
+ }
2775
+ previous = row;
2776
+ }
2777
+ return filled;
2778
+ };
2779
+
2780
+ const foldSessionUsage = (db) => {
2781
+ const attempts = db
2782
+ .prepare(
2783
+ `SELECT attempt_id, task_slug, started_at, finished_at, usage_source FROM attempts
2784
+ WHERE (usage_source IS NULL OR usage_source = 'session') AND started_at IS NOT NULL`,
2785
+ )
2786
+ .all();
2787
+ const byTask = new Map();
2788
+ for (const turn of db
2789
+ .prepare(
2790
+ `SELECT task_slug, observed_at, input_tokens, output_tokens, reasoning_tokens,
2791
+ cache_read_tokens, cache_write_tokens, cost_usd, provider_id, model_id
2792
+ FROM usage_turns WHERE attribution IN ('lease', 'window') AND task_slug IS NOT NULL`,
2793
+ )
2794
+ .all()) {
2795
+ const list = byTask.get(turn.task_slug) ?? [];
2796
+ list.push(turn);
2797
+ byTask.set(turn.task_slug, list);
2798
+ }
2799
+ const update = db.prepare(
2800
+ `UPDATE attempts SET
2801
+ input_tokens = ?, output_tokens = ?, reasoning_tokens = ?,
2802
+ cache_read_tokens = ?, cache_write_tokens = ?, cost_usd = ?,
2803
+ usage_origin = 'measured', usage_source = 'session', usage_turn_count = ?,
2804
+ model_provider = ?, model_id = ?
2805
+ WHERE attempt_id = ? AND (usage_source IS NULL OR usage_source = 'session')`,
2806
+ );
2807
+ const clear = db.prepare(
2808
+ `UPDATE attempts SET
2809
+ input_tokens = NULL, output_tokens = NULL, reasoning_tokens = NULL,
2810
+ cache_read_tokens = NULL, cache_write_tokens = NULL, cost_usd = NULL,
2811
+ usage_origin = NULL, usage_source = NULL, usage_turn_count = NULL,
2812
+ model_provider = NULL, model_id = NULL
2813
+ WHERE attempt_id = ? AND usage_source = 'session'`,
2814
+ );
2815
+ let usage = 0;
2816
+ for (const attempt of attempts) {
2817
+ const start = Date.parse(attempt.started_at);
2818
+ const end = attempt.finished_at ? Date.parse(attempt.finished_at) : Number.POSITIVE_INFINITY;
2819
+ const matched = (byTask.get(attempt.task_slug) ?? []).filter((turn) => {
2820
+ const at = Date.parse(turn.observed_at);
2821
+ return Number.isFinite(at) && at >= start && at <= end;
2822
+ });
2823
+ if (matched.length === 0) {
2824
+ if (attempt.usage_source === 'session') clear.run(attempt.attempt_id);
2825
+ continue;
2826
+ }
2827
+ const sum = (key) => matched.reduce((total, turn) => total + Number(turn[key] ?? 0), 0);
2828
+ let model = matched[0];
2829
+ for (const turn of matched) {
2830
+ if (Number(turn.input_tokens) > Number(model.input_tokens)) model = turn;
2831
+ }
2832
+ update.run(
2833
+ sum('input_tokens'),
2834
+ sum('output_tokens'),
2835
+ sum('reasoning_tokens'),
2836
+ sum('cache_read_tokens'),
2837
+ sum('cache_write_tokens'),
2838
+ sum('cost_usd'),
2839
+ matched.length,
2840
+ model.provider_id,
2841
+ model.model_id,
2842
+ attempt.attempt_id,
2843
+ );
2844
+ usage += 1;
2845
+ }
2846
+ return usage;
2847
+ };
2848
+
2849
+ /**
2850
+ * Join already-projected calls to attempts. Stronger attribution replaces a
2851
+ * weaker one; host and CLI usage are never overwritten. Safe to re-run.
2852
+ */
2853
+ export function bindBehaviorResearch(db, teamRoot) {
2854
+ const columns = db.prepare('PRAGMA table_info(tool_calls)').all().map((row) => row.name);
2855
+ if (!columns.includes('attempt_id')) return { upgraded: 0, bound: 0, episodes: 0, gaps: 0, usage: 0 };
2856
+ db.exec('BEGIN IMMEDIATE');
2857
+ try {
2858
+ const upgraded = teamRoot ? reattributeRows(db, teamRoot) : 0;
2859
+ const bound = bindAttemptIds(db);
2860
+ const episodes = rebuildEpisodes(db);
2861
+ const gaps = fillGaps(db);
2862
+ const usage = foldSessionUsage(db);
2863
+ db.exec('COMMIT');
2864
+ return { upgraded, bound, episodes, gaps, usage };
2865
+ } catch (error) {
2866
+ try {
2867
+ db.exec('ROLLBACK');
2868
+ } catch {
2869
+ /* the original error is the finding */
2870
+ }
2871
+ throw error;
2872
+ }
2873
+ }
2874
+
2607
2875
  /**
2608
2876
  * Ingest the OpenCode ledgers into `tool_calls` / `usage_turns` and the
2609
2877
  * session leases into `session_tasks`. Full sync only; a per-file watermark
@@ -2884,6 +3152,13 @@ export function syncProjection(options = {}) {
2884
3152
  logProjectionFailure('E_TELEMETRY_FAILED', error.message, options.env);
2885
3153
  }
2886
3154
  }
3155
+ if (!slug) {
3156
+ try {
3157
+ bindBehaviorResearch(db, handle.teamRoot);
3158
+ } catch (error) {
3159
+ logProjectionFailure('E_TELEMETRY_FAILED', error.message, options.env);
3160
+ }
3161
+ }
2887
3162
  if (maintain) {
2888
3163
  result.retained += maintainDatabase(db, startedAt).retained;
2889
3164
  retainRuns(db);
@@ -32,6 +32,7 @@ import {
32
32
  isKillSwitchSet,
33
33
  isSqliteAvailable,
34
34
  openTeamDb,
35
+ readNewerSchemaModule,
35
36
  teamDbFail,
36
37
  } from './team-db-schema.mjs';
37
38
 
@@ -2223,8 +2224,9 @@ export async function runScheduler(options = {}) {
2223
2224
  }
2224
2225
  fs.mkdirSync(schedulerPaths(teamRoot).runs, { recursive: true, mode: 0o700 });
2225
2226
 
2226
- const handle = openTeamDb({ teamRoot });
2227
- const { db } = handle;
2227
+ let handle = openTeamDb({ teamRoot });
2228
+ let db = handle.db;
2229
+ let loadedSchemaMtime = 0;
2228
2230
  let draining = false;
2229
2231
  const inFlight = new Set();
2230
2232
 
@@ -2258,7 +2260,35 @@ export async function runScheduler(options = {}) {
2258
2260
  process.once('SIGINT', shutdown);
2259
2261
  process.once('SIGTERM', shutdown);
2260
2262
 
2263
+ const reloadSchema = async () => {
2264
+ if (inFlight.size > 0) return;
2265
+ let fresh = null;
2266
+ try {
2267
+ fresh = await readNewerSchemaModule();
2268
+ } catch (error) {
2269
+ err(`schedule: schema reload failed: ${error.message}\n`);
2270
+ return;
2271
+ }
2272
+ if (!fresh || fresh.mtimeMs === loadedSchemaMtime) return;
2273
+ try {
2274
+ const next = fresh.openTeamDb({ teamRoot });
2275
+ try {
2276
+ handle.db.close();
2277
+ } catch {
2278
+ /* the replacement connection is the one the next tick uses */
2279
+ }
2280
+ handle = next;
2281
+ db = next.db;
2282
+ loadedSchemaMtime = fresh.mtimeMs;
2283
+ if (!options.quiet) out(`schedule: reloaded schema v${fresh.SCHEMA_VERSION}\n`);
2284
+ } catch (error) {
2285
+ loadedSchemaMtime = fresh.mtimeMs;
2286
+ err(`schedule: schema reload failed: ${error.message}\n`);
2287
+ }
2288
+ };
2289
+
2261
2290
  const tick = async () => {
2291
+ await reloadSchema();
2262
2292
  const now = Date.now();
2263
2293
  const nowIso = new Date(now).toISOString();
2264
2294
  let file;
@@ -18,6 +18,7 @@ import crypto from 'node:crypto';
18
18
  import fs from 'node:fs';
19
19
  import { createRequire } from 'node:module';
20
20
  import path from 'node:path';
21
+ import { fileURLToPath, pathToFileURL } from 'node:url';
21
22
 
22
23
  /** Node floor for the unflagged `node:sqlite` module. */
23
24
  export const MIN_NODE = '22.13.0';
@@ -791,6 +792,59 @@ SELECT task_slug, signal, value FROM (
791
792
  ) WHERE value > 0;
792
793
  `;
793
794
 
795
+ /**
796
+ * Migration 7: the research join. `attempt_id` on a call, one capped episode
797
+ * per attempt, and a closed task-quality label. Every new column is nullable
798
+ * and the episode table starts empty, so a version-6 file migrates in place.
799
+ */
800
+ export const BEHAVIOR_RESEARCH_SQL = SQL`-- The call belongs to the attempt whose window contains it. Nullable:
801
+ -- a dir-mtime or unmapped row stays unbound.
802
+ ALTER TABLE tool_calls ADD COLUMN attempt_id TEXT;
803
+
804
+ CREATE INDEX idx_tool_calls_attempt ON tool_calls(attempt_id, observed_at);
805
+
806
+ -- Ordered (intent, target hash, error class) for one attempt. No command
807
+ -- text and no path. Rebuilt by the projector; ordinal is the only order.
808
+ CREATE TABLE attempt_episodes (
809
+ attempt_id TEXT NOT NULL,
810
+ ordinal INTEGER NOT NULL,
811
+ intent TEXT,
812
+ target_key TEXT,
813
+ error_class TEXT,
814
+ observed_at TEXT NOT NULL,
815
+ PRIMARY KEY (attempt_id, ordinal)
816
+ ) STRICT;
817
+
818
+ -- One closed label per task. Step outcome stays on attempts; this is the
819
+ -- research cohort key. A task still in progress stays NULL.
820
+ CREATE VIEW task_quality AS
821
+ SELECT
822
+ t.slug AS task_slug,
823
+ CASE
824
+ WHEN NOT EXISTS (
825
+ SELECT 1 FROM events e WHERE e.task_slug = t.slug AND e.type = 'task_completed'
826
+ ) AND EXISTS (
827
+ SELECT 1 FROM attempts a
828
+ WHERE a.task_slug = t.slug AND a.outcome IN ('blocked', 'validation_failed')
829
+ ) THEN 'failed'
830
+ WHEN EXISTS (
831
+ SELECT 1 FROM attempts a WHERE a.task_slug = t.slug AND a.outcome = 'changes_requested'
832
+ ) THEN 'rework'
833
+ WHEN EXISTS (
834
+ SELECT 1 FROM events e WHERE e.task_slug = t.slug AND e.type = 'task_completed'
835
+ ) AND EXISTS (
836
+ SELECT 1 FROM events e WHERE e.task_slug = t.slug AND e.type = 'verification_recorded'
837
+ ) AND NOT EXISTS (
838
+ SELECT 1 FROM events e WHERE e.task_slug = t.slug AND e.type = 'verification_stale'
839
+ ) THEN 'met'
840
+ WHEN EXISTS (
841
+ SELECT 1 FROM events e WHERE e.task_slug = t.slug AND e.type = 'task_completed'
842
+ ) THEN 'unverified'
843
+ ELSE NULL
844
+ END AS quality
845
+ FROM tasks t;
846
+ `;
847
+
794
848
  const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
795
849
  /**
796
850
  * Ordered, immutable migrations. The literal checksum is verified before any
@@ -833,6 +887,12 @@ export const MIGRATIONS = [
833
887
  sql: ACTION_TELEMETRY_SQL,
834
888
  checksum: 'f250814d462f1d6085ff56a1cc233179002dd5b5d97c200ed28104e4e42fbbfe',
835
889
  },
890
+ {
891
+ version: 7,
892
+ name: '0007-behavior-research',
893
+ sql: BEHAVIOR_RESEARCH_SQL,
894
+ checksum: '5a64fd028118ef7b3831006a13e5ca9ac6bd17ee5ce3dfa5441d7946cf4694e0',
895
+ },
836
896
  ];
837
897
 
838
898
  /** Highest migration version shipped by this module. */
@@ -1247,6 +1307,45 @@ export function moveDatabaseAside(dbPath, reason) {
1247
1307
  return suffix;
1248
1308
  }
1249
1309
 
1310
+ const schemaModuleUrl = new URL(import.meta.url);
1311
+ schemaModuleUrl.search = '';
1312
+ schemaModuleUrl.hash = '';
1313
+ const schemaModulePath = fileURLToPath(schemaModuleUrl);
1314
+ const schemaModuleMtimeMs = fs.statSync(schemaModulePath).mtimeMs;
1315
+ let newerSchemaLoad = null;
1316
+
1317
+ /**
1318
+ * The schema module a long-lived process loaded at startup.
1319
+ *
1320
+ * `serve` and `schedule` keep this module in memory. A later edit that raises
1321
+ * `SCHEMA_VERSION`, applied by another process, makes every cached open fail
1322
+ * with `E_SCHEMA_NEWER`. Re-importing the file picks up that version. A
1323
+ * database newer than the file on disk still fails closed: the result is
1324
+ * `null` when the file is unchanged or its version is not higher.
1325
+ *
1326
+ * @returns {Promise<{ mtimeMs: number, SCHEMA_VERSION: number, openTeamDb: typeof openTeamDb } | null>}
1327
+ */
1328
+ export async function readNewerSchemaModule() {
1329
+ let mtimeMs;
1330
+ try {
1331
+ mtimeMs = fs.statSync(schemaModulePath).mtimeMs;
1332
+ } catch {
1333
+ return null;
1334
+ }
1335
+ if (!(mtimeMs > schemaModuleMtimeMs)) return null;
1336
+ if (!newerSchemaLoad || newerSchemaLoad.mtimeMs !== mtimeMs) {
1337
+ const stamp = mtimeMs;
1338
+ newerSchemaLoad = {
1339
+ mtimeMs: stamp,
1340
+ promise: import(`${pathToFileURL(schemaModulePath).href}?mtime=${stamp}`).then((fresh) => {
1341
+ if (!(fresh.SCHEMA_VERSION > SCHEMA_VERSION)) return null;
1342
+ return { mtimeMs: stamp, SCHEMA_VERSION: fresh.SCHEMA_VERSION, openTeamDb: fresh.openTeamDb };
1343
+ }),
1344
+ };
1345
+ }
1346
+ return newerSchemaLoad.promise;
1347
+ }
1348
+
1250
1349
  /**
1251
1350
  * Open, migrate, verify and return a connection handle.
1252
1351
  *
@@ -158,7 +158,9 @@ const repoRootOf = (teamRoot) => path.resolve(teamRoot, '..', '..');
158
158
 
159
159
  const resolveConfigCwd = (teamRoot, config) => {
160
160
  const root = repoRootOf(teamRoot);
161
- const resolved = path.isAbsolute(config.cwd) ? config.cwd : path.resolve(root, config.cwd);
161
+ // A relative cwd belongs to the file that declares it, so it resolves
162
+ // against the team root and the seeded "../.." is the repository root.
163
+ const resolved = path.isAbsolute(config.cwd) ? config.cwd : path.resolve(teamRoot, config.cwd);
162
164
  const relative = path.relative(root, resolved);
163
165
  if (relative.startsWith('..') || path.isAbsolute(relative)) {
164
166
  reject('E_VALIDATION', 'runner.json: cwd must stay inside the repository root');